Unable to save image paths to database yii - php

I am using the xupload extension, which is based on the blueimp jquery fileuploader, and while I can successfully upload to the folder, I am unable to add the paths and other details to the database. Below is the upload action and the model, in that order. Please help. Thanks.
public function actionUpload( ) {
//Here we define the paths where the files will be stored temporarily
$path = Yii::app() -> getBasePath() . "/../images/";
$publicPath = Yii::app()->getBaseUrl( )."/images/";
//This is for IE which doens't handle 'Content-type: application/json' correctly
header( 'Vary: Accept' );
if( isset( $_SERVER['HTTP_ACCEPT'] )
&& (strpos( $_SERVER['HTTP_ACCEPT'], 'application/json' ) !== false) ) {
header( 'Content-type: application/json' );
} else {
header( 'Content-type: text/plain' );
}
//Here we check if we are deleting and uploaded file
if( isset( $_GET["_method"] ) ) {
if( $_GET["_method"] == "delete" ) {
if( $_GET["file"][0] !== '.' ) {
$file = $path.$_GET["file"];
if( is_file( $file ) ) {
unlink( $file );
}
}
echo json_encode( true );
}
} else {
$model = new Photo;
$model->file = CUploadedFile::getInstance( $model, 'file' );
//We check that the file was successfully uploaded
if( $model->file !== null ) {
//Grab some data
$model->mime_type = $model->file->getType( );
//$model->size = $model->file->getSize( );
$model->name = $model->file->getName( );
//(optional) Generate a random name for our file
$filename = md5( Yii::app( )->user->id.microtime( ).$model->name);
$filename .= ".".$model->file->getExtensionName( );
if( $model->validate( ) ) {
//Move our file to our temporary dir
$model->file->saveAs( $path.$filename );
chmod( $path.$filename, 0777 );
//$model -> path = "/images/uploads/".$filename;
//here you can also generate the image versions you need
//using something like PHPThumb
//Now we need to save this path to the user's session
if( Yii::app( )->user->hasState( 'images' ) ) {
$userImages = Yii::app( )->user->getState( 'images' );
} else {
$userImages = array();
}
$userImages[] = array(
"path" => $path.$filename,
//the same file or a thumb version that you generated
"thumb" => $path.$filename,
"filename" => $filename,
'size' => $model->size,
'mime' => $model->mime_type,
'name' => $model->name,
);
Yii::app( )->user->setState( 'images', $userImages );
//Now we need to tell our widget that the upload was succesfull
//We do so, using the json structure defined in
// https://github.com/blueimp/jQuery-File-Upload/wiki/Setup
echo json_encode( array( array(
"name" => $model->name,
"type" => $model->mime_type,
"size" => $model->size,
"url" => $publicPath.$filename,
"thumbnail_url" => $publicPath."thumbs/$filename",
"delete_url" => $this->createUrl( "upload", array(
"_method" => "delete",
"file" => $filename
) ),
"delete_type" => "POST"
) ) );
} else {
//If the upload failed for some reason we log some data and let the widget know
echo json_encode( array(
array( "error" => $model->getErrors( 'file' ),
) ) );
Yii::log( "XUploadAction: ".CVarDumper::dumpAsString( $model->getErrors( ) ),
CLogger::LEVEL_ERROR, "xupload.actions.XUploadAction"
);
}
} else {
throw new CHttpException( 500, "Could not upload file" );
}
}
}
and the model;
<?php
class Photo extends CFormModel
{
public $file;
public $mime_type;
public $size;
public $name;
public $filename;
public function tableName()
{
return 'photo';
}
public static function model($className=__CLASS__)
{
return parent::model($className);
}
public function rules()
{
return array(
array('file', 'file', 'types'=>'jpg,gif,html'),
);
}
/**
* Declares attribute labels.
*/
public function attributeLabels()
{
return array(
'file'=>'Upload files',
);
}
public function getReadableFileSize($retstring = null) {
// adapted from code at http://aidanlister.com/repos/v/function.size_readable.php
$sizes = array('bytes', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
if ($retstring === null) { $retstring = '%01.2f %s'; }
$lastsizestring = end($sizes);
foreach ($sizes as $sizestring) {
if ($this->size < 1024) { break; }
if ($sizestring != $lastsizestring) { $this->size /= 1024; }
}
if ($sizestring == $sizes[0]) { $retstring = '%01d %s'; } // Bytes aren't normally fractional
return sprintf($retstring, $this->size, $sizestring);
}
/**
* A stub to allow overrides of thumbnails returned
* #since 0.5
* #author acorncom
* #return string thumbnail name (if blank, thumbnail won't display)
*/
public function getThumbnailUrl($publicPath) {
return $publicPath.$this->filename;
}
public function afterSave()
{
$this->addPhotos();
parent::afterSave();
}
public function addPhotos()
{
if(Yii::app()->user->hasState('images')){
$userImages = Yii::app()->user->getState('images');
$path = Yii::app()->getBasePath."/../images/uploads/";
if(!is_dir($path)){
mkdir($path);
chmod($path, 0777);
}
foreach($userImages as $image){
if(is_file($image['path'])){
if(rename($image['path'], $path.$image['filename'])){
chmod($path.$image['filename'], 0777);
$photo = new Photo;
//$photo -> size = $image['size'];
//$photo -> mime = $image['mime'];
$photo ->name = $image['name'];
$photo -> path = "/images/uploads/".$image['filename'];
if(!$photo->save()){
Yii::log(("Can't Save: \n").CVarDumper::dumpAsString($photo->getErrors()),CLogger::LEVEL_ERROR);
throw new Exception( "Could not save Image");
}
}
}
else{
Yii::log($image['path']."is not a file", CLogger::LEVEL_WARNING);
}
}
Yii::app()->user->setState('images', null);
}
}
}

So turns out if I use Active Record, or the Query Builder, it doesn't work. So I have used SQL and it works. Here is the code:
public function actionPost( ) {
//Here we define the paths where the files will be stored temporarily
$path = Yii::app() -> getBasePath() . "/../images/";
$publicPath = Yii::app()->getBaseUrl( )."/images/";
//This is for IE which doens't handle 'Content-type: application/json' correctly
header( 'Vary: Accept' );
if( isset( $_SERVER['HTTP_ACCEPT'] )
&& (strpos( $_SERVER['HTTP_ACCEPT'], 'application/json' ) !== false) ) {
header( 'Content-type: application/json' );
} else {
header( 'Content-type: text/plain' );
}
//Here we check if we are deleting and uploaded file
if( isset( $_GET["_method"] ) ) {
if( $_GET["_method"] == "delete" ) {
if( $_GET["file"][0] !== '.' ) {
$query = "DELETE FROM `fuck`.`photo` WHERE `photo`.`path` = $file";
$file = $path.$_GET["file"];
if( is_file( $file ) ) {
unlink( $file );
Yii::app()->db->createCommand($query)->execute();
}
}
echo json_encode( true );
}
} else {
$model = new Photo;
$model->file = CUploadedFile::getInstance( $model, 'file' );
//We check that the file was successfully uploaded
if( $model->file !== null ) {
//Grab some data
$model->mime_type = $model->file->getType( );
$model->size = $model->file->getSize( );
$model->name = $model->file->getName( );
//(optional) Generate a random name for our file
$filename = md5( Yii::app( )->user->id.microtime( ).$model->name);
$filename .= ".".$model->file->getExtensionName( );
if( $model->validate( ) ) {
//Move our file to our temporary dir
$model->file->saveAs( $path.$filename );
chmod( $path.$filename, 0777 );
$drive = "/images/".$filename;
/* $db->createCommand()->insert('photo', array(
//'id'=>$newID,
'name'=>$model->name,
'path'=>$drive,
)); */
$sql = "INSERT INTO `gallery`.`photo` (
`name` ,
`path`
)
VALUES (
'$model->name', '$drive'
);
";
Yii::app()->db->createCommand($sql)->execute();
echo json_encode( array( array(
"name" => $model->name,
"type" => $model->mime_type,
"size" => $model->size,
"url" => $publicPath.$filename,
"thumbnail_url" => $publicPath."thumbs/$filename",
"delete_url" => $this->createUrl( "upload", array(
"_method" => "delete",
"file" => $filename
) ),
"delete_type" => "POST"
) ) );
} else {
//If the upload failed for some reason we log some data and let the widget know
echo json_encode( array(
array( "error" => $model->getErrors( 'file' ),
) ) );
Yii::log( "XUploadAction: ".CVarDumper::dumpAsString( $model->getErrors( ) ),
CLogger::LEVEL_ERROR, "xupload.actions.XUploadAction"
);
}
} else {
throw new CHttpException( 500, "Could not upload file" );
}
}
}

Related

Using gform_after_submission with gform_notification

I am trying to use gform_after_submission to grab a field value(url of a file) then pass the value to a notification so it can be sent as an attachment. This is what I have so far:
add_action("gform_after_submission", "after_submission", 10, 2);
function after_submission($entry, $form){
$pdf = $entry["3"];
return $pdf;
}
add_filter( 'gform_notification_3', 'add_notification_attachments', 10, 3 );
function add_notification_attachments( $notification, $form, $entry ) {
if ( $notification['name'] == 'Admin Notification' ) {
$path = 'path/to/file.pdf';
$notification['attachments'] = array( $path );
}
return $notification;
}
Untested but you shouldn't need the first action, only the notification filter.
add_filter( 'gform_notification_3', 'add_notification_attachments', 10, 3 );
function add_notification_attachments( $notification, $form, $entry ) {
if ( $notification['name'] == 'Admin Notification' ) {
$path = $entry['3'];
$notification['attachments'] = array( $path );
}
return $notification;
}
Thanks Dave, couldn't see your updated code but here's what I managed to do once you told me about converting the URL to a path & it now works perfectly:
function get_file_path_from_url( $file_url ){
return realpath($_SERVER['DOCUMENT_ROOT'] . parse_url( $file_url, PHP_URL_PATH ));
}
add_filter( 'gform_notification_3', 'add_notification_attachments', 10, 3 );
function add_notification_attachments( $notification, $form, $entry ) {
if ( $notification['name'] == 'Admin Notification' ) {
$path = $entry['3'];
$path = get_file_path_from_url($path);
$notification['attachments'] = array( $path );
}
return $notification;
}

WordPress wp-insert-post function creating arbitrary no-title pages

I am using the wp-insert post function to dynamically generate pages from a website I am working on. However, I have been getting these no title posts that increase every time I refresh the page along with the actual pages that are generated from my code.
I have tried solving this by adding a hook into my page creation process, however this does not seem to do anything. I was wondering how I can only create the pages I need without these no title posts appearing.
My code:
if( !class_exists("PageCreator")) {
class PageCreator
{
public function __construct()
{
add_action('init', array($this, 'AddThisPage'));
}
public function AddThisPage()
{
$dirName = "/zotpull/resources/temp/";
$filename = dirname(__DIR__, 2) . $dirName . "useData.txt";
$theFile = fopen($filename, "r");
$msg = fread($theFile, filesize($filename));
fclose($theFile);
$links = explode("\n", $msg);
foreach( array_slice($links, 0, count($links) -1) as $item ) {
$item = str_replace("/","-",$item);
$str2 = substr($item, 5);
$page = array(
'page_template' => 'datePage.php', //Sets the template for the page.
'post_title' => $str2, //The title of your post.
'post_status' => 'publish',
'post_type' => 'page'
);
if ( ! function_exists( 'post_exists' ) ) {
require_once( ABSPATH . 'wp-admin/includes/post.php' );
}
$page_exists = post_exists($page['post_title']);
if ($page_exists == 0) {
$insert = wp_insert_post($page);
}
}
}
}
}
Try to use wp_update_post after wp_insert_post. check the below code.
if( !class_exists("PageCreator")) {
class PageCreator{
public function __construct()
{
add_action('init', array($this, 'AddThisPage'));
}
public function AddThisPage()
{
$dirName = "/zotpull/resources/temp/";
$filename = dirname(__DIR__, 2) . $dirName . "useData.txt";
$theFile = fopen($filename, "r");
$msg = fread($theFile, filesize($filename));
fclose($theFile);
$links = explode("\n", $msg);
foreach( array_slice($links, 0, count($links) -1) as $item ) {
$item = str_replace("/","-",$item);
$str2 = substr($item, 5);
$page = array(
'page_template' => 'datePage.php', //Sets the template for the page.
'post_title' => $str2, //The title of your post.
'post_status' => 'publish',
'post_type' => 'page'
);
if ( ! function_exists( 'post_exists' ) ) {
require_once( ABSPATH . 'wp-admin/includes/post.php' );
}
$page_exists = post_exists($page['post_title']);
if ($page_exists == 0) {
$insert = wp_insert_post($page);
$my_post = array(
'ID' => $insert,
'post_title' => $str2
);
wp_update_post( $my_post );
}
}
}
}
}

PHP zip file downloads locally but not in production

I am working on some files to download in a zip. Works fine locally but not in any environment (staging or production). Using WP VIP also, not sure if that helps. I'm a little new to VIP. Really racked by brains here and can't seem to figure out the issue.
I've read the resources on PHP zip creation. I do get the "Unable to add zip file.', 500 );" error producing.
Code below:
$context = [];
$post = theme()->twig()->create_post();
$tab_index = filter_input( INPUT_GET, 'tab-index', FILTER_SANITIZE_NUMBER_INT );
$content_calendar = $post->get_field('content_calendar');
if ( ! isset( $content_calendar[ $tab_index ] ) ) {
\wp_send_json_error( 'Invalid tab-index.', 400 );
exit;
}
$tab = $content_calendar[ $tab_index ];
// Create zip name;
$name = 'content-calendar-' . $tab_index;
$group_index = filter_input( INPUT_GET, 'group-index', FILTER_SANITIZE_NUMBER_INT );
if ( null !== $group_index ) {
if ( ! isset( $tab['groups'][ $group_index ] ) ) {
\wp_send_json_error( 'Invalid group-index.', 400 );
exit;
}
$groups = [ $tab['groups'][ $group_index ] ];
// Append group to name
$name .= '-' . $group_index;
} else {
$groups = $tab['groups'];
}
// Extract paths from resources with assets
$paths = [];
foreach ( $groups as $group ) {
foreach ( $group['resources'] as $resource ) {
if ( $resource['social_resource'] ) {
$asset_id = get_field( 'asset', $resource['social_resource'] );
if ( $asset_id ) {
$paths[] = get_attached_file( $asset_id, true );
}
}
}
}
// Remove invalid or duplicate URLs
$paths = array_unique( array_filter( $paths ) );
if ( empty( $paths ) ) {
\wp_send_json_error( 'No files to download.', 400 );
exit;
}
// Generate file names
$zipfile = wp_upload_dir()['basedir'] . '/' . $name . '.zip';
$zipname = $name . '-' . date('Y-m-d') . '.zip';
// Generate file
$zip = new ZipArchive;
if ( true !== $zip->open( $zipfile, ZipArchive::CREATE | ZipArchive::OVERWRITE ) ) {
\wp_send_json_error( 'Unable to create zip file.', 500 );
exit;
}
foreach ( $paths as $path ) {
if ( true !== $zip->addFile( $path, basename( $path ) ) ) {
$zip->close();
\wp_send_json_error( 'Unable to add file to zip.', 500 );
exit;
}
}
$zip->close();
// Send headers and stream file
header( 'Content-Type: application/zip' );
header( 'Content-disposition: attachment; filename=' . $zipname );
header( 'Content-Length: ' . filesize( $zipfile ) );
readfile( $zipfile );
exit;
Any help is appreciated.

$_POST variable staying the same

I'm having trouble with this code and using different emails to view images in a directory (processed/$email) and the email changes per user's respective form entry, yet only shows the images from the most recent folder created regardless of the email given.
<form action="<?php echo $_SERVER["PHP_SELF"];?>" method="POST">
E-mail:
<input type="text" name="email" id="email2"><br>
<br>
<input type="submit" value="Retrieve" name="submit"><br><br>
</form>
and here's the PHP:
<?php
function scanDirectoryImages($directory, array $exts = array('jpeg', 'jpg', 'gif', 'png'))
{
if (substr($directory, -1) == '/') {
$directory = substr($directory, 0, -1);
}
$html = '';
if (
is_readable($directory)
&& (file_exists($directory) || is_dir($directory))
) {
$directoryList = opendir($directory);
while($file = readdir($directoryList)) {
if ($file != '.' && $file != '..') {
$path = $directory . '/' . $file;
if (is_readable($path)) {
if (is_dir($path)) {
return scanDirectoryImages($path, $exts);
}
if (
is_file($path)
&& in_array(end(explode('.', end(explode('/', $path)))), $exts)
) {
$html .= '<a href="' . $path . '"><img src="' . $path
. '" style="max-height:250px;max-width:250px" /> </a>';
}
}
}
}
closedir($directoryList);
}
return $html;
}
echo scanDirectoryImages(processed.$_POST['email2']);
?>
I've tried unsetting variables, etc. It doesn't work. When I go back to the form from any page, it's still only showing the most recently uploaded folder of images. The only thing that will make it show new images is if there is a new directory. I feel like I must be approaching this fundamentally wrong somehow and I'm new to PHP so some help would be hugely appreciated.
The original function has a recursive nature to it but doesn't utilise the existing suite of recursiveIterator classes - hopefully the below will be of use in that respect. When I tried your original function all I got it to return was a folder name and not a list of files / images.
function scanImageDirectory( $directory, $root, $exts=array('jpg','jpeg','png','gif'), $exclusions=array('bmp') ){
$html=array();
$dirItr = new RecursiveDirectoryIterator( $directory );
$filterItr = new DirFileFilter( $dirItr, $exclusions, $directory, 'all' );
$recItr = new RecursiveIteratorIterator( $filterItr, RecursiveIteratorIterator::SELF_FIRST );
foreach( $recItr as $filepath => $info ){
if( $info->isFile() && in_array( strtolower( pathinfo( $info, PATHINFO_EXTENSION ) ), $exts ) ) {
$filename=str_replace( array( realpath( $root ), chr(92) ), array( '', chr(47) ), realpath( $info ) );
$html[]="<a href='{$filename}' target='_blank'><img src='{$filename}' alt='{$info->getFilename()}' /></a>";
}
}
return implode( PHP_EOL,$html );
}
$dir=ROOT.'/images/css/icons/browsers';
$root='c:/wwwroot';
echo scanImageDirectory( $dir, $root );
Or, as example for your situation
$dir="processed/{$_POST['email']}";
$root=$_SERVER['DOCUMENT_ROOT'];
echo scanImageDirectory( $dir, $root );
I realise that the class DirFileFilter is one I wrote and not a native PHP class - this can only be described as an id-10-T error.. Apologies - here is that class.
class DirFileFilter extends RecursiveFilterIterator{
protected $exclude;
protected $root;
protected $mode;
public function __construct( $iterator, array $exclude, $root, $mode='all' ){
parent::__construct( $iterator );
$this->exclude = $exclude;
$this->root = $root;
$this->mode = $mode;
}
public function accept(){
$folpath=rtrim( str_replace( $this->root, '', $this->getPathname() ), '\\' );
$ext=strtolower( pathinfo( $this->getFilename(), PATHINFO_EXTENSION ) );
switch( $this->mode ){
case 'all':
return !( in_array( $this->getFilename(), $this->exclude ) or in_array( $folpath, $this->exclude ) or in_array( $ext, $this->exclude ) );
case 'files':
return ( $this->isFile() && ( !in_array( $this->getFilename(), $this->exclude ) or !in_array( $ext, $this->exclude ) ) );
break;
case 'dirs':
case 'folders':
return ( $this->isDir() && !( in_array( $this->getFilename(), $this->exclude ) ) && !in_array( $folpath, $this->exclude ) );
break;
default:
echo 'config error: ' . $this->mode .' is not recognised';
break;
}
return false;
}
public function getChildren(){
return new self( $this->getInnerIterator()->getChildren(), $this->exclude, $this->root, $this->mode );
}
}

Recieving PHP Warning copy(): Filename cannot be empty

I am receiving this warning in one of the Wordpress plugins.
copy(): Filename cannot be empty in /wp-content/plugins/nix-gravatar-cache/nf-gravatar-cache.php on line 181
Please help me correct this, if somebody can. I am not very good with PHP. Thanks
Here is the code.
<?php
class NFGC_Gravatar_Cache {
protected $upload_url;
protected $upload_path;
protected $plugin_dir_path;
public $plugin_name = 'NIX Gravatar Cache';
function __construct(){
if ( get_option( 'upload_url_path' ) ) {
$this->upload_url = get_option( 'upload_url_path' );
$this->upload_path = get_option( 'upload_path' );
}
else {
$up_dir = wp_upload_dir();
$this->upload_url = $up_dir['baseurl'];
$this->upload_path = $up_dir['basedir'];
}
$this->plugin_dir_path = plugin_dir_path( __FILE__ );
require_once $this->plugin_dir_path . '/messages.class.php';
NFGC_Messages::init();
$active = get_option( 'nf_c_a_options' );
if ( $active[0]['active'] == 1 ) {
add_filter( 'get_avatar', array( $this,'get_cached_avatar' ), -1000000000, 5 );
}
add_action( 'admin_menu', array( $this,'add_admin_menu' ) );
register_activation_hook( __FILE__, array( $this, 'activate' ) );
$this->init();
register_deactivation_hook( __FILE__, 'deactivate' );
register_uninstall_hook( __FILE__ , 'uninstall' );
if ( !is_writable( $this->upload_path.'/gravatar/' ) && is_dir( $this->upload_path.'/gravatar/' ) ) {
NFGC_Messages::add_message( 'error', 'Please set write permissions for "'. $this->upload_path .'/gravatar/"' );
}else{
if ( #!mkdir( $this->upload_path.'/gravatar/', 0777 ) && ! is_dir( $this->upload_path.'/gravatar/' ) ) {
NFGC_Messages::add_message( 'error', 'Could not create directory "gravatar". Please set write permissions for "'. $this->upload_path .'/gravatar/"' );
}
}
if ( isset ( $_POST['nf_clear_cache'] ) )
$this->clear_cache();
}
public function get_template_path() {
return $this->plugin_dir_path .'template';
}
// Activate plugin and update default option
public function activate() {
$dir = $this->upload_path.'/gravatar/';
// delete_option('nf_c_a_options');
if ( get_option( 'nf_c_a_options' ) == false ) {
$default_options = array('active' => 1,
'ttl_day' => 10,
'ttl_hour' => 0,
'ttl_min' => 0
);
update_option( 'nf_c_a_options', array( $default_options ) );
}
}
// Deactivate plugin and clear cache
public function deactivate() {
$this->clear_cache();
}
// Notice in plugin options page
public function admin_help_notice() {
global $current_screen;
if ( $current_screen->base == 'settings_page_'. basename( __FILE__,'.php' ) ) {
return true;
}
}
// convert ttl option to second
private function cache_to_second(){
$cache_time = get_option( 'nf_c_a_options' );
$cache_time = array_reverse( $cache_time[0] );
$action = array();
foreach ( $cache_time as $key => $value ) {
if ( $key == 'active' )
continue;
switch ( $key ) {
case 'ttl_min':
$cache_second = $value != 0 ? $value*60 : '';
break;
case 'ttl_hour':
$cache_second = $value != 0 ? ( $value*60*60 ) + $cache_second : $cache_second;
break;
case 'ttl_day':
$cache_second = $value != 0 ? ( $value*60*60*24 ) + $cache_second : $cache_second;
break;
}
}
if ( ! $cache_second ) {
$cache_second = 864000;// TTL of cache in seconds (10 days)
}
return $cache_second;
}
// The main functional
public function get_cached_avatar( $source, $id_or_email, $size, $default, $alt ) {
if ( !is_writable( $this->upload_path.'/gravatar/' ) || is_admin() ) {
return $source;
}
$time = $this->cache_to_second();
preg_match('/d=([^&]*)/', $source, $d_tmp);
$g_url_default_sorce = isset($d_tmp[1]) ? $d_tmp[1] : false;
preg_match('/forcedefault=([^&]*)/', $source, $d_tmp);
$g_forcedefault = isset($d_tmp[1]) ? $d_tmp[1] : false;
preg_match('/avatar\/([a-z0-9]+)\?s=(\d+)/', $source, $tmp);
$garvatar_id = $tmp[1];
$file_name = md5($garvatar_id.$g_url_default_sorce);
$g_path = $this->upload_path.'/gravatar/'.$file_name.'-s'.$size.'.jpg';
//* $g_path_default = $this->upload_path.'/gravatar/default'.'-s'.$size.'.jpg';
$g_url = $this->upload_url.'/gravatar/'.$file_name.'-s'.$size.'.jpg';
//* $g_url_default = $this->upload_url.'/gravatar/'.'default'.'-s'.$size.'.jpg';
// Check cache
static $nf_avatars_cache = null;
if ($nf_avatars_cache === null) $nf_avatars_cache = get_option('nf_avatars_cache');
if (! is_array($nf_avatars_cache)) $nf_avatars_cache = array();
if (isset($nf_avatars_cache[$garvatar_id][$size])) {
$g_url = $nf_avatars_cache[$garvatar_id][$size]['url'];
$g_path = $nf_avatars_cache[$garvatar_id][$size]['path'];
}
if (! is_file($g_path) || (time()-filemtime($g_path)) > $time) {
$curl_url = 'https://www.gravatar.com/avatar/'.$garvatar_id.'?s='.$size.'&r=G&d='.$g_url_default_sorce;
$ch = curl_init($curl_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$response = curl_exec($ch);
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $header_size);
// Checking for redirect
$header_array = array();
preg_match('/^Location\: (.*)$/m', $header, $header_array);
$redirect_url = isset($header_array[1]) ? $header_array[1] : false;
if ($redirect_url) {
$g_url = $g_url_default;
$g_path = $g_path_default;
if (! is_file($g_path) || (time()-filemtime($g_path)) > $time) {
copy($redirect_url, $g_path);
}
}
else {
// Check mime type
$mime_str = curl_getinfo( $ch, CURLINFO_CONTENT_TYPE );
$mime_array = array();
preg_match( '#/([a-z]*)#i', $mime_str, $mime_array );
if (isset($mime_array[1])) {
// Write cache to file
$fp = fopen( $g_path, "wb" );
$body = substr( $response, $header_size );
fwrite( $fp, $body );
fclose( $fp );
}
}
curl_close($ch);
$nf_avatars_cache[$garvatar_id][$size]['url'] = $g_url;
$nf_avatars_cache[$garvatar_id][$size]['path'] = $g_path;
update_option( 'nf_avatars_cache', $nf_avatars_cache );
}
return '<img alt = "'.$alt.'" src=\''.$g_url.'\' class="avatar avatar-'.$size.'" width="'.$size.'" height="'.$size.'" />';
}
// Create plugin option settings menu
public function add_admin_menu() {
// settings menu page
add_options_page( 'Cached Avatar ', $this->plugin_name, 'manage_options', basename( __FILE__ ), array( $this,'view_options_page' ) );
}
// Create page option
public function view_options_page() {
// update options
if ( isset( $_POST['nf_c_a_submit'] ) ) {
$update_val_options = $_POST['nf_c_a_options'];
foreach ( $update_val_options as $option => $value ) {
$update_val_options[$option] = abs( intval( $value ) );
}
if( $update_val_options['ttl_min'] == 0 && $update_val_options['ttl_hour'] == 0 && $update_val_options['ttl_day'] == 0 ) {
$update_val_options['ttl_day'] = 10;
}
update_option( 'nf_c_a_options', array( $update_val_options ) );
}
$options = get_option( 'nf_c_a_options' );
include( $this->get_template_path() .'/main-options-page.php');
}
private function clear_cache() {
$dir = $this->upload_path.'/gravatar/';
$no_permision_to_delete = false;
// Open directory
if ( is_dir( $dir ) ) {
if ( $opendir = opendir( $dir ) ) {
$count = 0;
while ( ( $file = readdir( $opendir ) ) !== false ) {
if ( filetype( $dir . $file ) == 'file' ) {
if ( #unlink( $dir . $file ) ) {
$count++;
}else {
$no_permision_to_delete = true;
}
}
}
if ( $no_permision_to_delete ) {
NFGC_Messages::add_message( 'error','Unable to clear the cache' );
}else{
update_option('nf_avatars_cache', array() );
NFGC_Messages::add_message( 'info','The cache is cleared!' );
NFGC_Messages::add_message( 'info','Removed '.$count.' files' );
}
closedir( $opendir );
}
}
}
// return count and size
public function get_cache_info() {
$dir = $this->upload_path.'/gravatar/';
$skip = array('.','..');
$unit = array('b', 'kb', 'mb', 'gb', 'tb', 'pb');
if ( is_dir( $dir ) ) {
$file_list = scandir( $dir );
// delete . and ..
foreach ( $skip as $value ) {
unset( $file_list[ array_search( $value, $file_list ) ] );
}
// sum files size
foreach ( $file_list as $file ) {
$size = filesize( $dir . $file );
$all_size = $all_size + $size;
}
}
$readable_form = #round( $all_size / pow( 1024, ( $i = floor( log( $all_size, 1024) ) ) ), 2 ) . ' ' . $unit[$i];
return array( 'amount' => count( $file_list ) , 'used_space' => $readable_form );
}
private function init() {
return false;
wp_enqueue_script( 'nfgc-main-script', plugins_url( '/js/main.js', __FILE__ ), array('jquery') );
wp_enqueue_style( 'nfgc-main-style', plugins_url( '/css/style.css', __FILE__ ) );
}
}// Class
global $nfgc;
$nfgc = new NFGC_Gravatar_Cache();
add_action('wp_enqueue_scripts', function() {
wp_enqueue_script( 'nfgc-main-script', plugins_url( '/js/main.js', __FILE__ ), array('jquery') );
wp_enqueue_style( 'nfgc-main-style', plugins_url( '/css/style.css', __FILE__ ) );
});
`
Try this..
Use file_exists
Returns TRUE if the file or directory specified by filename exists; FALSE otherwise.
if (file_exists($redirect_url)) {
$g_url = $g_url_default;
$g_path = $g_path_default;
if (! is_file($g_path) || (time()-filemtime($g_path)) > $time) {
copy($redirect_url, $g_path);
}
}
http://php.net/manual/en/function.file-exists.php

Categories