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.
So, I'm having a form with two image fields () and I've created a function that uploads the file really nice and neat. All of the files (only images allowed) are shown in Media Library.
But now I need them not to be visible in Media Library.
This is the function I use, and I even had wp_insert_attachment in it and now have it commented, hoping that it will be enough.
The images still show up in Media.
function insertImage ($file){
$wordpress_upload_dir = wp_upload_dir();
$i = 1; // number of tries when the file with the same name is already exists
$upload_dir_custom = $wordpress_upload_dir['basedir']."/custom-folder";
if (!file_exists($upload_dir_custom)) {
mkdir( $upload_dir_custom,0755,true) ;
}
$new_file_path = $upload_dir_custom;
$new_file_mime = mime_content_type( $file['tmp_name'] );
if( empty( $file ) )
die( 'File is not selected.' );
if( $file['error'] )
die( $file['error'] );
if( $file['size'] > wp_max_upload_size() )
die( 'Image is too large!.' );
if( !in_array( $new_file_mime, get_allowed_mime_types() ) )
die( 'WordPress doesn\'t allow this type of uploads.' );
while( file_exists( $new_file_path ) ) {
$i++;
if($i>1){
$new_file_path = $wordpress_upload_dir['basedir'] . '/sponsor-info/' . $i . '_' .$file['name'];
}else{
$new_file_path = $wordpress_upload_dir['basedir'] . '/sponsor-info/'.$file['name'];
}
}
if( move_uploaded_file( $file['tmp_name'], $new_file_path ) ) {
$image_url = $wordpress_upload_dir['url'] . '/sponsor-info/' . basename( $new_file_path);
return $image_url;
}
}
I have created dynamic add / remove file field to insert image in database. But somehow it is not working properly. Following is my code...
$member_image_names = array_map( 'sanitize_file_name', $_FILES['member_image']['name'] );
foreach ( $member_image_names as $member_image_name ) {
if ( empty( $member_image_name ) ) {
global $wpdb;
$project_id = $_SESSION['project_id'];
$project_member_details = $wpdb->get_var( $wpdb->prepare( "SELECT project_members FROM wpxa_orocox_project_members WHERE project_id = %d", $project_id ) );
$project_member_detail = json_decode( $project_member_details, true );
$member_image_newname = $project_member_detail['member_image'];
} else {
$member_image_ext = strtolower( end( explode( '.', $member_image_name ) ) );
$member_image_newname[] = get_current_user_id() . $_SESSION['project_id'] . "_" . time() . "_" . mt_rand() . "." . $member_image_ext;
}
$member_details->member_image = $member_image_newname;
$member_details_encode = wp_json_encode( $member_details );
global $wpdb;
$members_result_update = $wpdb->update( 'wpxa_project_members',
array( 'project_members' => $member_details_encode ),
array( 'project_id' => $_SESSION['project_id'] ),
array( '%s' ),
array( '%d' )
);
if ( ! empty( $members_result_update ) ) {
$member_details_decode = json_decode($member_details_encode, true);
$count_member_decode = count( $member_details_decode['member_image'] );
for ( $i = 0; $i < $count_member_decode; $i++ ) {
$m_image_name = $member_details_decode['member_image'][$i];
$profile_image_folder = "profile-images/";
$profile_image_path = trim( $profile_image_folder . basename( $m_image_name ) );
$profile_image_temp = $_FILES['member_image']['tmp_name'][$i];
$profile_image_ext = strtolower( end( explode( '.', $m_image_name ) ) );
if ( $profile_image_ext == "jpg" || $profile_image_ext == "png" || $profile_image_ext == "jpeg" || $profile_image_ext == "gif" ) {
move_uploaded_file( $profile_image_temp, $profile_image_path );
}
}
}
}
Every thing works well but when I select a new image in first field and submit the value to the database, it removes all other images of other fields from database...
And if I select image for other fields and submit the value to database it then creates new field with that value...
In simple terms, When I want to update any particular file field in the dynamic add / remove file field then that particular field should only be get updated and other fields should remain intact.
Pl Help...
I had this problem and i did it :(Example)
if ( empty( $options['index1_cardimg'] ) ) {$options['index1_cardimg'] = get_myoption_value('index1_cardimg');}
without this check (if (empty){}) all other fields will be reset .
just you need to fill them by last data (if they dont send) .
with a code like this:
if ( empty( $members_result_update ) ) {
// fill Other options with last value
}
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
How would I get this to index pages that have no ending at all? My website is created of pages similar to this http://www.example.com/example/post-id-the-post-title-would-go-here and because it has no ending it does not display within the sitemap.
Update
Config.php
define( 'SITEMAP_DIR', './' );
define( 'SITEMAP_DIR_URL', 'http://www.example.com' );
define( 'RECURSIVE', true );
$filetypes = array( 'php', 'html', 'pdf' );
// The replace array, this works as file => replacement, so 'index.php' => '', would make the index.php be listed as just /
$replace = array( 'index.php' => '' );
$xsl = 'xml.xsl';
$chfreq = 'daily';
$prio = 1;
$ignore = array( 'config.php' );
I am not interested in rewriting the urls because I have already done this from the http://www.exaple.com/index.php?a=track&id=17 when I first started.
Sitemap.php
require './config.php';
// Get the keys so we can check quickly
$replace_files = array_keys( $replace );
// Sent the correct header so browsers display properly, with or without XSL.
header( 'Content-Type: application/xml' );
echo '<?xml version="1.0" encoding="utf-8"?>' . "\n";
$ignore = array_merge( $ignore, array( '.', '..', 'config.php', 'xml-sitemap.php' ) );
if ( isset( $xsl ) && !empty( $xsl ) )
echo '<?xml-stylesheet type="text/xsl" href="' . SITEMAP_DIR_URL . $xsl . '"?>' . "\n";
function parse_dir( $dir, $url ) {
global $ignore, $filetypes, $replace, $chfreq, $prio;
$handle = opendir( $dir );
while ( false !== ( $file = readdir( $handle ) ) ) {
// Check if this file needs to be ignored, if so, skip it.
if ( in_array( utf8_encode( $file ), $ignore ) )
continue;
if ( is_dir( $file ) ) {
if ( defined( 'RECURSIVE' ) && RECURSIVE )
parse_dir( $file, $url . $file . '/' );
}
// Check whether the file has on of the extensions allowed for this XML sitemap
$fileinfo = pathinfo( $dir . $file );
if ( in_array( $fileinfo['extension'], $filetypes ) ) {
// Create a W3C valid date for use in the XML sitemap based on the file modification time
if (filemtime( $dir .'/'. $file )==FALSE) {
$mod = date( 'c', filectime( $dir . $file ) );
} else {
$mod = date( 'c', filemtime( $dir . $file ) );
}
// Replace the file with it's replacement from the settings, if needed.
if ( in_array( $file, $replace ) )
$file = $replace[$file];
// Start creating the output
?>
<url>
<loc><?php echo $url . rawurlencode( $file ); ?></loc>
<lastmod><?php echo $mod; ?></lastmod>
<changefreq><?php echo $chfreq; ?></changefreq>
<priority><?php echo $prio; ?></priority>
</url><?php
}
}
closedir( $handle );
}
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"><?php
parse_dir( SITEMAP_DIR, SITEMAP_DIR_URL );
?>
</urlset>