/** * Import processing step (status console) */ public function process($save_history = true) { $wp_uploads = wp_upload_dir(); $import = $this->data['update_previous']; $history_log = new PMXI_History_Record(); $input = new PMXI_Input(); if (!empty(PMXI_Plugin::$session->history_id)) { $history_log->getById(PMXI_Plugin::$session->history_id); } $log_storage = (int) PMXI_Plugin::getInstance()->getOption('log_storage'); if (!PMXI_Plugin::is_ajax()) { $import->set((empty(PMXI_Plugin::$session->source) ? array() : PMXI_Plugin::$session->source) + array('xpath' => PMXI_Plugin::$session->xpath, 'options' => PMXI_Plugin::$session->options, 'count' => PMXI_Plugin::$session->count, 'friendly_name' => PMXI_Plugin::$session->options['friendly_name'], 'feed_type' => PMXI_Plugin::$session->feed_type, 'parent_import_id' => $this->data['update_previous']->isEmpty() ? PMXI_Plugin::$session->parent_import_id : $this->data['update_previous']->parent_import_id, 'queue_chunk_number' => 0, 'triggered' => 0, 'processing' => 0, 'executing' => 1, 'iteration' => !empty($import->iteration) ? $import->iteration : 0))->save(); if (PMXI_Plugin::$session->action != 'continue') { // store import info in database $import->set(array('imported' => 0, 'created' => 0, 'updated' => 0, 'skipped' => 0, 'deleted' => 0))->update(); } // add history log $custom_type = get_post_type_object($import->options['custom_type']); // unlink previous logs $by = array(); $by[] = array(array('import_id' => $import->id, 'type NOT LIKE' => 'trigger'), 'AND'); $historyLogs = new PMXI_History_List(); $historyLogs->setColumns('id', 'import_id', 'type', 'date')->getBy($by, 'id ASC'); if ($historyLogs->count() and $historyLogs->count() >= $log_storage) { $logsToRemove = $historyLogs->count() - $log_storage; foreach ($historyLogs as $i => $file) { $historyRecord = new PMXI_History_Record(); $historyRecord->getBy('id', $file['id']); if (!$historyRecord->isEmpty()) { $historyRecord->delete(); } // unlink history file only if ($i == $logsToRemove) { break; } } } $history_log->set(array('import_id' => $import->id, 'date' => date('Y-m-d H:i:s'), 'type' => PMXI_Plugin::$session->action != 'continue' ? 'manual' : 'continue', 'summary' => sprintf(__("%d %ss created %d updated %d deleted %d skipped", "pmxi_plugin"), $import->created, $custom_type->labels->singular_name, $import->updated, $import->deleted, $import->skipped)))->save(); PMXI_Plugin::$session->set('history_id', $history_log->id); foreach (get_taxonomies() as $tax) { delete_transient("pmxi_{$tax}_terms"); } do_action('pmxi_before_xml_import', $import->id); PMXI_Plugin::$session->set('update_previous', $import->id); if (empty($import->options['encoding'])) { $currentOptions = $import->options; $currentOptions['encoding'] = 'UTF-8'; $import->set(array('options' => $currentOptions))->update(); } // unlink previous files $history = new PMXI_File_List(); $history->setColumns('id', 'name', 'registered_on', 'path')->getBy(array('import_id' => $import->id), 'id DESC'); if ($history->count()) { foreach ($history as $file) { $history_file_path = wp_all_import_get_absolute_path($file['path']); if (@file_exists($history_file_path) and $history_file_path != PMXI_Plugin::$session->filePath) { if (in_array($import->type, array('upload'))) { wp_all_import_remove_source($history_file_path, false); } else { wp_all_import_remove_source($history_file_path); } } $history_file = new PMXI_File_Record(); $history_file->getBy('id', $file['id']); if (!$history_file->isEmpty()) { $history_file->delete(); } } } if ($save_history) { $history_file = new PMXI_File_Record(); $history_file->set(array('name' => $import->name, 'import_id' => $import->id, 'path' => wp_all_import_get_relative_path(PMXI_Plugin::$session->filePath), 'registered_on' => date('Y-m-d H:i:s')))->save(); } /* Split file up into 1000 record chunks. This option will decrease the amount of slowdown experienced at the end of large imports. The slowdown is partially caused by the need for WP All Import to read deeper and deeper into the file on each successive iteration. Splitting the file into pieces means that, for example, instead of having to read 19000 records into a 20000 record file when importing the last 1000 records, WP All Import will just split it into 20 chunks, and then read the last chunk from the beginning. */ if ("ajax" == $import->options['import_processing'] and $import->count > PMXI_Plugin::getInstance()->getOption('large_feed_limit') and $import->options['chuncking']) { $chunk_files = array(); if (!empty(PMXI_Plugin::$session->local_paths)) { $records_count = 0; $chunk_records_count = 0; $feed = "<?xml version=\"1.0\" encoding=\"" . $import->options['encoding'] . "\"?>" . "\n" . "<pmxi_records>"; foreach (PMXI_Plugin::$session->local_paths as $key => $path) { $file = new PMXI_Chunk($path, array('element' => $import->root_element, 'encoding' => $import->options['encoding'])); // loop through the file until all lines are read while ($xml = $file->read()) { if (!empty($xml)) { PMXI_Import_Record::preprocessXml($xml); $chunk = "<?xml version=\"1.0\" encoding=\"" . $import->options['encoding'] . "\"?>" . "\n" . $xml; $dom = new DOMDocument('1.0', $import->options['encoding']); $old = libxml_use_internal_errors(true); $dom->loadXML($chunk); // FIX: libxml xpath doesn't handle default namespace properly, so remove it upon XML load libxml_use_internal_errors($old); $xpath = new DOMXPath($dom); if ($elements = @$xpath->query($import->xpath) and $elements->length) { $records_count += $elements->length; $chunk_records_count += $elements->length; $feed .= $xml; } } if ($chunk_records_count == PMXI_Plugin::getInstance()->getOption('large_feed_limit') or $records_count == $import->count) { $feed .= "</pmxi_records>"; $chunk_file_path = wp_all_import_secure_file($wp_uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::TEMP_DIRECTORY) . DIRECTORY_SEPARATOR . "pmxi_chunk_" . count($chunk_files) . "_" . basename($path); file_put_contents($chunk_file_path, $feed); $chunk_files[] = $chunk_file_path; $chunk_records_count = 0; $feed = "<?xml version=\"1.0\" encoding=\"" . $import->options['encoding'] . "\"?>" . "\n" . "<pmxi_records>"; } } } PMXI_Plugin::$session->set('local_paths', $chunk_files); } } PMXI_Plugin::$session->save_data(); if ($log_storage) { $log_file = wp_all_import_secure_file($wp_uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::LOGS_DIRECTORY, $history_log->id) . DIRECTORY_SEPARATOR . $history_log->id . '.html'; if (PMXI_Plugin::$session->action != 'continue') { if (file_exists($log_file)) { wp_all_import_remove_source($log_file, false); } //@file_put_contents($log_file, sprintf(__('<p>Source path `%s`</p>', 'wp_all_import_plugin'), $import->path)); } } $this->data['ajax_processing'] = "ajax" == $import->options['import_processing'] ? true : false; $this->render(); wp_ob_end_flush_all(); flush(); @set_time_limit(0); $import_id = $input->get('id', 0); if ("ajax" == $import->options['import_processing'] and !$import_id) { PMXI_Plugin::$session->convertData($import->id); //die(); } } elseif (empty($import->id)) { $import = new PMXI_Import_Record(); $import_id = $input->get('id', PMXI_Plugin::$session->update_previous); $import->getById($import_id); } $ajax_processing = "ajax" == $import->options['import_processing'] ? true : false; if (PMXI_Plugin::is_ajax() and $ajax_processing and !check_ajax_referer('wp_all_import_secure', 'security', false)) { exit(__('Security check', 'wp_all_import_plugin')); } if ($ajax_processing) { $logger = create_function('$m', 'echo "<div class=\\"progress-msg\\">$m</div>\\n"; flush();'); } else { $logger = create_function('$m', 'echo "<div class=\\"progress-msg\\">$m</div>\\n"; if ( "" != strip_tags(wp_all_import_strip_tags_content($m))) { PMXI_Plugin::$session->log .= "<p>".strip_tags(wp_all_import_strip_tags_content($m))."</p>"; flush(); }'); } PMXI_Plugin::$session->set('start_time', empty(PMXI_Plugin::$session->start_time) ? time() : PMXI_Plugin::$session->start_time); wp_cache_flush(); if (PMXI_Plugin::is_ajax() or !$ajax_processing) { $iteration_start_time = time(); if ($log_storage) { $log_file = wp_all_import_secure_file($wp_uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::LOGS_DIRECTORY, $history_log->id) . DIRECTORY_SEPARATOR . $history_log->id . '.html'; } if ($ajax_processing) { // HTTP headers for no cache etc header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); } $loop = 0; $pointer = 0; $records = array(); if ($import->options['is_import_specified']) { foreach (preg_split('% *, *%', $import->options['import_specified'], -1, PREG_SPLIT_NO_EMPTY) as $chank) { if (preg_match('%^(\\d+)-(\\d+)$%', $chank, $mtch)) { $records = array_merge($records, range(intval($mtch[1]), intval($mtch[2]))); } else { $records = array_merge($records, array(intval($chank))); } } } $records_to_import = empty($records) ? $import->count : $records[count($records) - 1]; $failures = $input->get('failures', 0); // auto decrease records per iteration option if ($failures) { $options = $import->options; $options['records_per_request'] = ceil($options['records_per_request'] / 2) ? ceil($options['records_per_request'] / 2) : 1; $import->set(array('options' => $options))->update(); } $records_per_request = (!$ajax_processing and $import->options['records_per_request'] < 50) ? 50 : $import->options['records_per_request']; if (!empty(PMXI_Plugin::$session->local_paths)) { $feed = "<?xml version=\"1.0\" encoding=\"" . $import->options['encoding'] . "\"?>" . "\n" . "<pmxi_records>"; foreach (PMXI_Plugin::$session->local_paths as $key => $path) { $import_done = $import->imported + $import->skipped == $records_to_import ? true : false; if ($import_done) { if (strpos($path, "pmxi_chunk_") !== false and @file_exists($path)) { wp_all_import_remove_source($path, false); } PMXI_Plugin::$session->set('local_paths', array()); PMXI_Plugin::$session->save_data(); break; } $file = new PMXI_Chunk($path, array('element' => $import->root_element, 'encoding' => $import->options['encoding'], 'pointer' => PMXI_Plugin::$session->pointer, 'filter' => true)); // loop through the file until all lines are read while ($xml = $file->read() and empty($import->canceled)) { if (!empty($xml)) { if (!$import->options['chuncking']) { PMXI_Import_Record::preprocessXml($xml); } $chunk = "<?xml version=\"1.0\" encoding=\"" . $import->options['encoding'] . "\"?>" . "\n" . $xml; $dom = new DOMDocument('1.0', $import->options['encoding']); $old = libxml_use_internal_errors(true); $dom->loadXML($chunk); // FIX: libxml xpath doesn't handle default namespace properly, so remove it upon XML load libxml_use_internal_errors($old); $xpath = new DOMXPath($dom); $pointer++; if ($this->data['elements'] = $elements = @$xpath->query($import->xpath) and $elements->length) { /* Merge nested XML/CSV files */ /*$nested_files = json_decode($import->options['nested_files'], true); if ( ! empty($nested_files) and is_array($nested_files)){ $merger = new PMXI_Nested($dom, $nested_files, $xml, $import->xpath, $elements); $merger->merge(); $xml = $merger->get_xml(); unset($merger); } */ // continue action if ($import->imported + $import->skipped >= PMXI_Plugin::$session->chunk_number + $elements->length - 1) { PMXI_Plugin::$session->set('chunk_number', PMXI_Plugin::$session->chunk_number + $elements->length); PMXI_Plugin::$session->save_data(); continue; } if (!$loop and $ajax_processing) { ob_start(); } $feed .= $xml; $loop += $elements->length; $processed_records = $import->imported + $import->skipped; if ($loop == $records_per_request or $processed_records + $loop == $records_to_import or $processed_records == $records_to_import) { $feed .= "</pmxi_records>"; $import->process($feed, $logger, PMXI_Plugin::$session->chunk_number, false, '/pmxi_records', $loop); unset($dom, $xpath); if (!$ajax_processing) { $feed = "<?xml version=\"1.0\" encoding=\"" . $import->options['encoding'] . "\"?>" . "\n" . "<pmxi_records>"; $loop = 0; } else { if (!$history_log->isEmpty()) { $custom_type = get_post_type_object($import->options['custom_type']); $history_log->set(array('time_run' => time() - strtotime($history_log->date), 'summary' => sprintf(__("%d %ss created %d updated %d deleted %d skipped", "pmxi_plugin"), $import->created, $custom_type->labels->singular_name, $import->updated, $import->deleted, $import->skipped)))->update(); } unset($file); PMXI_Plugin::$session->set('pointer', PMXI_Plugin::$session->pointer + $pointer); PMXI_Plugin::$session->save_data(); $log_data = ob_get_clean(); if ($log_storage) { $log = @fopen($log_file, 'a+'); @fwrite($log, $log_data); @fclose($log); } $iteration_execution_time = time() - $iteration_start_time; wp_send_json(array('imported' => $import->imported, 'created' => $import->created, 'updated' => $import->updated, 'percentage' => ceil($processed_records / $import->count * 100), 'warnings' => PMXI_Plugin::$session->warnings, 'errors' => PMXI_Plugin::$session->errors, 'log' => $log_data, 'done' => false, 'records_per_request' => $import->options['records_per_request'])); } } } } } // Move to the next file, set pointer to first element if ($ajax_processing) { if (strpos($path, "pmxi_chunk_") !== false and @file_exists($path)) { @unlink($path); } PMXI_Plugin::$session->set('pointer', 1); $pointer = 0; $lp = PMXI_Plugin::$session->local_paths; array_shift($lp); PMXI_Plugin::$session->set('local_paths', $lp); PMXI_Plugin::$session->save_data(); } else { break; } } } } if (PMXI_Plugin::is_ajax() and empty(PMXI_Plugin::$session->local_paths) or !$ajax_processing or !empty($import->canceled)) { if ("ajax" != $import->options['import_processing'] and $log_storage) { $log_file = wp_all_import_secure_file($wp_uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::LOGS_DIRECTORY, $history_log->id) . DIRECTORY_SEPARATOR . $history_log->id . '.html'; if (PMXI_Plugin::$session->action != 'continue') { @file_put_contents($log_file, PMXI_Plugin::$session->log); } else { $log = @fopen($log_file, 'a+'); @fwrite($log, PMXI_Plugin::$session->log); @fclose($log); } } wp_cache_flush(); foreach (get_taxonomies() as $tax) { delete_option("{$tax}_children"); _get_term_hierarchy($tax); } $import->set(array('registered_on' => date('Y-m-d H:i:s'), 'executing' => 0))->update(); // add history log $custom_type = get_post_type_object($import->options['custom_type']); $history_log->set(array('time_run' => time() - strtotime($history_log->date), 'summary' => sprintf(__("%d %ss created %d updated %d deleted %d skipped", "pmxi_plugin"), $import->created, $custom_type->labels->singular_name, $import->updated, $import->deleted, $import->skipped)))->update(); // clear import session PMXI_Plugin::$session->clean_session($import->id); // clear session data (prevent from reimporting the same data on page refresh) // [indicate in header process is complete] $msg = !empty($import->canceled) ? addcslashes(__('Canceled', 'wp_all_import_plugin'), "\n\r") : addcslashes(__('Complete', 'wp_all_import_plugin'), "\n\r"); if ($ajax_processing) { ob_start(); } do_action('pmxi_after_xml_import', $import->id); $import->options['is_import_specified'] and $logger and call_user_func($logger, 'Done'); echo <<<COMPLETE <script type="text/javascript"> //<![CDATA[ (function(\$){\t \t\$('#status').html('{$msg}');\t \twindow.onbeforeunload = false; })(jQuery); //]]> </script> COMPLETE; // [/indicate in header process is complete] if ($ajax_processing) { wp_send_json(array('imported' => $import->imported, 'created' => $import->created, 'updated' => $import->updated, 'percentage' => 100, 'warnings' => PMXI_Plugin::$session->warnings, 'errors' => PMXI_Plugin::$session->errors, 'log' => ob_get_clean(), 'done' => true, 'records_per_request' => $import->options['records_per_request'])); } } }
/** * Displays the given administration message. * * @since 2.1.0 * * @param string|WP_Error $message */ function show_message($message) { if (is_wp_error($message)) { if ($message->get_error_data() && is_string($message->get_error_data())) { $message = $message->get_error_message() . ': ' . $message->get_error_data(); } else { $message = $message->get_error_message(); } } echo "<p>{$message}</p>\n"; wp_ob_end_flush_all(); flush(); }
function gmedia_import_handler() { global $wpdb, $gmCore, $gmDB; ini_set('max_execution_time', 600); // HTTP headers for no cache etc send_nosniff_header(); //send_origin_headers(); nocache_headers(); check_admin_referer('GmediaImport'); if (!current_user_can('gmedia_import')) { wp_die(__('You do not have permission to upload files.')); } // 10 minutes execution time @set_time_limit(10 * 60); // fake upload time usleep(10); $import = $gmCore->_post('import'); $terms = $gmCore->_post('terms', array()); if (ob_get_level() == 0) { ob_start(); } echo str_pad(' ', 4096) . PHP_EOL; wp_ob_end_flush_all(); flush(); ?> <html> <style type="text/css"> * { margin:0; padding:0; } pre { display:block; } p { padding:10px 0; font-size:14px; } .ok { color:darkgreen; } .ko { color:darkred; } </style> <body> <?php if ('import-folder' == $import || isset($_POST['import-folder'])) { $path = $gmCore->_post('path'); echo '<h4 style="margin: 0 0 10px">' . __('Import Server Folder') . " `{$path}`:</h4>" . PHP_EOL; if ($path) { $path = trim(urldecode($path), '/'); if (!empty($path)) { $fullpath = ABSPATH . trailingslashit($path); $files = glob($fullpath . '?*.?*', GLOB_NOSORT); if (!empty($files)) { $allowed_ext = get_allowed_mime_types(); $allowed_ext = array_keys($allowed_ext); $allowed_ext = implode('|', $allowed_ext); $allowed_ext = explode('|', $allowed_ext); if (GMEDIA_UPLOAD_FOLDER == basename(dirname(dirname($path))) || GMEDIA_UPLOAD_FOLDER == basename(dirname($path))) { global $wpdb; $gmedias = $wpdb->get_col("SELECT gmuid FROM {$wpdb->prefix}gmedia"); foreach ($files as $i => $filepath) { $gmuid = basename($filepath); if (in_array($gmuid, $gmedias)) { $fileinfo = $gmCore->fileinfo($gmuid, false); if (!('image' == $fileinfo['dirname'] && !is_file($fileinfo['filepath']))) { unset($files[$i]); } } } $move = false; $exists = false; } else { $move = $gmCore->_post('delete_source'); $exists = $gmCore->_post('skip_exists', 0); } foreach ($files as $i => $filepath) { $ext = pathinfo($filepath, PATHINFO_EXTENSION); if (!in_array(strtolower($ext), $allowed_ext)) { unset($files[$i]); } } $gmCore->gmedia_import_files($files, $terms, $move, $exists); } else { echo sprintf(__('Folder `%s` is empty', 'grand-media'), $path) . PHP_EOL; } } else { echo __('No folder chosen', 'grand-media') . PHP_EOL; } } } elseif ('import-flagallery' == $import || isset($_POST['import-flagallery'])) { echo '<h4 style="margin: 0 0 10px">' . __('Import from Flagallery plugin') . ":</h4>" . PHP_EOL; $gallery = $gmCore->_post('gallery'); if (!empty($gallery)) { $album = !isset($terms['gmedia_album']) || empty($terms['gmedia_album']) ? false : true; foreach ($gallery as $gid) { $flag_gallery = $wpdb->get_row($wpdb->prepare("SELECT gid, path, title, galdesc FROM {$wpdb->prefix}flag_gallery WHERE gid = %d", $gid), ARRAY_A); if (empty($flag_gallery)) { continue; } if (!$album) { $terms['gmedia_album'] = $flag_gallery['title']; if ($gmCore->is_digit($terms['gmedia_album'])) { $terms['gmedia_album'] = 'a' . $terms['gmedia_album']; } if (!$gmDB->term_exists($terms['gmedia_album'], 'gmedia_album')) { $term_id = $gmDB->insert_term($terms['gmedia_album'], 'gmedia_album', array('description' => htmlspecialchars_decode(stripslashes($flag_gallery['galdesc'])))); } } $path = ABSPATH . trailingslashit($flag_gallery['path']); echo '<h5 style="margin: 10px 0 5px">' . sprintf(__('Import `%s` gallery', 'grand-media'), $flag_gallery['title']) . ":</h5>" . PHP_EOL; $flag_pictures = $wpdb->get_results($wpdb->prepare("SELECT CONCAT('%s', filename) AS file, description, alttext AS title, link FROM {$wpdb->prefix}flag_pictures WHERE galleryid = %d", $path, $flag_gallery['gid']), ARRAY_A); if (empty($flag_pictures)) { echo '<pre>' . __('gallery contains 0 images', 'grand-media') . '</pre>'; continue; } $exists = $gmCore->_post('skip_exists', 0); //echo '<pre>'.print_r($flag_pictures, true).'</pre>'; $gmCore->gmedia_import_files($flag_pictures, $terms, false, $exists); } } else { echo __('No gallery chosen', 'grand-media') . PHP_EOL; } } elseif ('import-nextgen' == $import || isset($_POST['import-nextgen'])) { echo '<h4 style="margin: 0 0 10px">' . __('Import from NextGen plugin') . ":</h4>" . PHP_EOL; $gallery = $gmCore->_post('gallery'); if (!empty($gallery)) { $album = !isset($terms['gmedia_album']) || empty($terms['gmedia_album']) ? false : true; foreach ($gallery as $gid) { $ngg_gallery = $wpdb->get_row($wpdb->prepare("SELECT gid, path, title, galdesc FROM {$wpdb->prefix}ngg_gallery WHERE gid = %d", $gid), ARRAY_A); if (empty($ngg_gallery)) { continue; } if (!$album) { $terms['gmedia_album'] = $ngg_gallery['title']; if ($gmCore->is_digit($terms['gmedia_album'])) { $terms['gmedia_album'] = 'a' . $ngg_gallery['title']; } if (!$gmDB->term_exists($terms['gmedia_album'], 'gmedia_album')) { $term_id = $gmDB->insert_term($terms['gmedia_album'], 'gmedia_album', array('description' => htmlspecialchars_decode(stripslashes($ngg_gallery['galdesc'])))); } } $path = ABSPATH . trailingslashit($ngg_gallery['path']); echo '<h5 style="margin: 10px 0 5px">' . sprintf(__('Import `%s` gallery', 'grand-media'), $ngg_gallery['title']) . ":</h5>" . PHP_EOL; $ngg_pictures = $wpdb->get_results($wpdb->prepare("SELECT CONCAT('%s', filename) AS file, description, alttext AS title FROM {$wpdb->prefix}ngg_pictures WHERE galleryid = %d", $path, $ngg_gallery['gid']), ARRAY_A); if (empty($ngg_pictures)) { echo '<pre>' . __('gallery contains 0 images', 'grand-media') . '</pre>'; continue; } $exists = $gmCore->_post('skip_exists', 0); $gmCore->gmedia_import_files($ngg_pictures, $terms, false, $exists); } } else { echo __('No gallery chosen', 'grand-media') . PHP_EOL; } } elseif ('import-wpmedia' == $import || isset($_POST['import-wpmedia'])) { echo '<h4 style="margin: 0 0 10px">' . __('Import from WP Media Library') . ":</h4>" . PHP_EOL; $wpMediaLib = $gmDB->get_wp_media_lib(array('filter' => 'selected', 'selected' => $gmCore->_post('selected'))); if (!empty($wpMediaLib)) { $wp_media = array(); foreach ($wpMediaLib as $item) { $wp_media[] = array('file' => get_attached_file($item->ID), 'title' => $item->post_title, 'description' => $item->post_content); } $exists = $gmCore->_post('skip_exists', 0); //echo '<pre>' . print_r($wp_media, true) . '</pre>'; $gmCore->gmedia_import_files($wp_media, $terms, false, $exists); } else { echo __('No items chosen', 'grand-media') . PHP_EOL; } } ?> </body> </html> <?php wp_ob_end_flush_all(); die; }
function handle_imports() { if (!empty($_POST['files']) && !empty($_POST['cwd'])) { $files = array_map('stripslashes', $_POST['files']); $cwd = trailingslashit(stripslashes($_POST['cwd'])); $post_id = isset($_REQUEST['post_id']) ? intval($_REQUEST['post_id']) : 0; $import_date = isset($_REQUEST['import-date']) ? $_REQUEST['import-date'] : 'file'; $import_to_gallery = isset($_POST['gallery']) && 'on' == $_POST['gallery']; if (!$import_to_gallery && !isset($_REQUEST['cwd'])) { $import_to_gallery = true; } // cwd should always be set, if it's not, and neither is gallery, this must be the first page load. if (!$import_to_gallery) { $post_id = 0; } flush(); wp_ob_end_flush_all(); foreach ((array) $files as $file) { $filename = $cwd . $file; $id = $this->handle_import_file($filename, $post_id, $import_date); if (is_wp_error($id)) { echo '<div class="updated error"><p>' . sprintf(__('<em>%s</em> was <strong>not</strong> imported due to an error: %s', 'add-from-server'), esc_html($file), $id->get_error_message()) . '</p></div>'; } else { //increment the gallery count if ($import_to_gallery) { echo "<script type='text/javascript'>jQuery('#attachments-count').text(1 * jQuery('#attachments-count').text() + 1);</script>"; } echo '<div class="updated"><p>' . sprintf(__('<em>%s</em> has been added to Media library', 'add-from-server'), esc_html($file)) . '</p></div>'; } flush(); wp_ob_end_flush_all(); } } }
/** * Flush * Use some aggressive flushing to make the "Building ..." dialog appear as soon as possible * on step 4. This is based on ticket #18525 * @link http://core.trac.wordpress.org/ticket/18525 */ public function flush() { if ('cli' === php_sapi_name()) { return; } wp_ob_end_flush_all(); $buffer_string = '<!--' . str_repeat(chr(' '), 16384) . '-->'; // 16 KB if (headers_sent()) { echo $buffer_string; flush(); } }
/** * Import processing step (status console) */ public function process($save_history = true) { $wp_uploads = wp_upload_dir(); $import = $this->data['update_previous']; $logger = create_function('$m', 'echo "<div class=\\"progress-msg\\">$m</div>\\n"; if ( "" != strip_tags(pmxi_strip_tags_content($m)) and !empty(PMXI_Plugin::$session[\'pmxi_import\'][\'log\'])) { PMXI_Plugin::$session[\'pmxi_import\'][\'log\'] .= "<p>".strip_tags(pmxi_strip_tags_content($m))."</p>"; flush(); }'); if (!PMXI_Plugin::is_ajax()) { $import->set((empty(PMXI_Plugin::$session->data['pmxi_import']['source']) ? array() : PMXI_Plugin::$session->data['pmxi_import']['source']) + array('xpath' => PMXI_Plugin::$session->data['pmxi_import']['xpath'], 'template' => PMXI_Plugin::$session->data['pmxi_import']['template'], 'options' => PMXI_Plugin::$session->data['pmxi_import']['options'], 'count' => PMXI_Plugin::$session->data['pmxi_import']['count'], 'friendly_name' => PMXI_Plugin::$session->data['pmxi_import']['options']['friendly_name'], 'feed_type' => PMXI_Plugin::$session->data['pmxi_import']['feed_type'], 'parent_import_id' => $this->data['update_previous']->isEmpty() ? PMXI_Plugin::$session->data['pmxi_import']['parent_import_id'] : $this->data['update_previous']->parent_import_id, 'queue_chunk_number' => 0, 'triggered' => 0, 'processing' => 0, 'iteration' => !empty($import->iteration) ? $import->iteration : 0))->save(); if (PMXI_Plugin::$session->data['pmxi_import']['action'] != 'continue') { // store import info in database $import->set(array('imported' => 0, 'created' => 0, 'updated' => 0, 'skipped' => 0))->update(); } foreach (get_taxonomies() as $tax) { delete_transient("pmxi_{$tax}_terms"); } do_action('pmxi_before_xml_import', $import->id); PMXI_Plugin::$session['pmxi_import']['update_previous'] = $import->id; // unlick previous files $history = new PMXI_File_List(); $history->setColumns('id', 'name', 'registered_on', 'path')->getBy(array('import_id' => $import->id), 'id DESC'); if ($history->count()) { foreach ($history as $file) { if (@file_exists($file['path']) and $file['path'] != PMXI_Plugin::$session->data['pmxi_import']['filePath']) { @unlink($file['path']); } $history_file = new PMXI_File_Record(); $history_file->getBy('id', $file['id']); if (!$history_file->isEmpty()) { $history_file->delete(); } } } if ($save_history) { $history_file = new PMXI_File_Record(); $history_file->set(array('name' => $import->name, 'import_id' => $import->id, 'path' => PMXI_Plugin::$session->data['pmxi_import']['filePath'], 'contents' => $this->get_xml(), 'registered_on' => date('Y-m-d H:i:s')))->save(); } /* Split file up into 1000 record chunks. This option will decrease the amount of slowdown experienced at the end of large imports. The slowdown is partially caused by the need for WP All Import to read deeper and deeper into the file on each successive iteration. Splitting the file into pieces means that, for example, instead of having to read 19000 records into a 20000 record file when importing the last 1000 records, WP All Import will just split it into 20 chunks, and then read the last chunk from the beginning. */ if ("ajax" == $import->options['import_processing'] and $import->count > PMXI_Plugin::getInstance()->getOption('large_feed_limit') and $import->options['chuncking']) { $chunk_files = array(); if (!empty(PMXI_Plugin::$session->data['pmxi_import']['local_paths'])) { $records_count = 0; $chunk_records_count = 0; $feed = "<?xml version=\"1.0\" encoding=\"" . $import->options['encoding'] . "\"?>" . "\n" . "<pmxi_records>"; foreach (PMXI_Plugin::$session->data['pmxi_import']['local_paths'] as $key => $path) { $file = new PMXI_Chunk($path, array('element' => $import->root_element, 'encoding' => $import->options['encoding'])); // loop through the file until all lines are read while ($xml = $file->read()) { if (!empty($xml)) { PMXI_Import_Record::preprocessXml($xml); $chunk = "<?xml version=\"1.0\" encoding=\"" . $import->options['encoding'] . "\"?>" . "\n" . $xml; $dom = new DOMDocument('1.0', $import->options['encoding']); $old = libxml_use_internal_errors(true); $dom->loadXML($chunk); // FIX: libxml xpath doesn't handle default namespace properly, so remove it upon XML load libxml_use_internal_errors($old); $xpath = new DOMXPath($dom); if ($elements = @$xpath->query($import->xpath) and $elements->length) { $records_count += $elements->length; $chunk_records_count += $elements->length; $feed .= $xml; } } if ($chunk_records_count == PMXI_Plugin::getInstance()->getOption('large_feed_limit') or $records_count == $import->count) { $feed .= "</pmxi_records>"; $chunk_file_path = $wp_uploads['path'] . "/pmxi_chunk_" . count($chunk_files) . "_" . basename($path); file_put_contents($chunk_file_path, $feed); $chunk_files[] = $chunk_file_path; $chunk_records_count = 0; $feed = "<?xml version=\"1.0\" encoding=\"" . $import->options['encoding'] . "\"?>" . "\n" . "<pmxi_records>"; } } } PMXI_Plugin::$session['pmxi_import']['local_paths'] = $chunk_files; } } pmxi_session_commit(); $this->render(); wp_ob_end_flush_all(); flush(); @set_time_limit(0); if ("ajax" == $import->options['import_processing']) { die; } } elseif (empty($import->id)) { $import = new PMXI_Import_Record(); $import->getById(PMXI_Plugin::$session->data['pmxi_import']['update_previous']); } $ajax_processing = "ajax" == $import->options['import_processing'] ? true : false; PMXI_Plugin::$session['pmxi_import']['start_time'] = empty(PMXI_Plugin::$session->data['pmxi_import']['start_time']) ? time() : PMXI_Plugin::$session->data['pmxi_import']['start_time']; wp_cache_flush(); if (PMXI_Plugin::is_ajax() or !$ajax_processing) { if ("ajax" == $import->options['import_processing']) { // HTTP headers for no cache etc header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); } $loop = 0; $pointer = 0; $records = array(); if ($import->options['is_import_specified']) { foreach (preg_split('% *, *%', $import->options['import_specified'], -1, PREG_SPLIT_NO_EMPTY) as $chank) { if (preg_match('%^(\\d+)-(\\d+)$%', $chank, $mtch)) { $records = array_merge($records, range(intval($mtch[1]), intval($mtch[2]))); } else { $records = array_merge($records, array(intval($chank))); } } } $records_to_import = empty($records) ? $import->count : $records[count($records) - 1]; $records_per_request = (!$ajax_processing and $import->options['records_per_request'] < 50) ? 50 : $import->options['records_per_request']; if (!empty(PMXI_Plugin::$session->data['pmxi_import']['local_paths'])) { $feed = "<?xml version=\"1.0\" encoding=\"" . $import->options['encoding'] . "\"?>" . "\n" . "<pmxi_records>"; foreach (PMXI_Plugin::$session->data['pmxi_import']['local_paths'] as $key => $path) { $import_done = $import->imported + $import->skipped + PMXI_Plugin::$session->data['pmxi_import']['errors'] == $records_to_import ? true : false; if ($import_done) { if (strpos($path, "pmxi_chunk_") !== false and @file_exists($path)) { @unlink($path); } PMXI_Plugin::$session['pmxi_import']['local_paths'] = array(); pmxi_session_commit(); break; } $file = new PMXI_Chunk($path, array('element' => $import->root_element, 'encoding' => $import->options['encoding'], 'pointer' => PMXI_Plugin::$session->data['pmxi_import']['pointer'])); // loop through the file until all lines are read while ($xml = $file->read()) { if (!empty($xml)) { PMXI_Import_Record::preprocessXml($xml); $chunk = "<?xml version=\"1.0\" encoding=\"" . $import->options['encoding'] . "\"?>" . "\n" . $xml; $dom = new DOMDocument('1.0', $import->options['encoding']); $old = libxml_use_internal_errors(true); $dom->loadXML($chunk); // FIX: libxml xpath doesn't handle default namespace properly, so remove it upon XML load libxml_use_internal_errors($old); $xpath = new DOMXPath($dom); $pointer++; if ($this->data['elements'] = $elements = @$xpath->query($import->xpath) and $elements->length) { // continue action if ($import->imported + $import->skipped >= PMXI_Plugin::$session->data['pmxi_import']['chunk_number'] + $elements->length - 1) { PMXI_Plugin::$session['pmxi_import']['chunk_number'] = PMXI_Plugin::$session->data['pmxi_import']['chunk_number'] + $elements->length; pmxi_session_commit(); continue; } if (!$loop and $ajax_processing) { ob_start(); } $feed .= $xml; $loop += $elements->length; $processed_records = $import->imported + $import->skipped + PMXI_Plugin::$session->data['pmxi_import']['errors']; if ($loop == $records_per_request or $processed_records + $loop == $records_to_import or $processed_records == $records_to_import) { $feed .= "</pmxi_records>"; $import->process($feed, $logger, PMXI_Plugin::$session->data['pmxi_import']['chunk_number'], false, '/pmxi_records'); unset($dom, $xpath); if (!$ajax_processing) { $feed = "<?xml version=\"1.0\" encoding=\"" . $import->options['encoding'] . "\"?>" . "\n" . "<pmxi_records>"; $loop = 0; } else { unset($file); PMXI_Plugin::$session['pmxi_import']['pointer'] = PMXI_Plugin::$session->data['pmxi_import']['pointer'] + $pointer; pmxi_session_commit(); wp_send_json(array('created' => $import->created, 'updated' => $import->updated, 'percentage' => ceil($processed_records / $import->count * 100), 'warnings' => PMXI_Plugin::$session->data['pmxi_import']['warnings'], 'errors' => PMXI_Plugin::$session->data['pmxi_import']['errors'], 'log' => ob_get_clean(), 'done' => false)); } } } } } // Move to the next file, set pointer to first element if ($ajax_processing) { if (strpos($path, "pmxi_chunk_") !== false and @file_exists($path)) { @unlink($path); } PMXI_Plugin::$session['pmxi_import']['pointer'] = 1; $pointer = 0; array_shift(PMXI_Plugin::$session->data['pmxi_import']['local_paths']); PMXI_Plugin::$session['pmxi_import']['local_paths'] = PMXI_Plugin::$session->data['pmxi_import']['local_paths']; pmxi_session_commit(); } else { break; } } } } if (PMXI_Plugin::is_ajax() and empty(PMXI_Plugin::$session->data['pmxi_import']['local_paths']) or !$ajax_processing) { // Save import process log $log_file = $wp_uploads['basedir'] . '/wpallimport_logs/' . $import->id . '.html'; if (file_exists($log_file)) { unlink($log_file); } @file_put_contents($log_file, PMXI_Plugin::$session->data['pmxi_import']['log']); if (!empty(PMXI_Plugin::$session->data['pmxi_import'])) { do_action('pmxi_after_xml_import', $import->id); } wp_cache_flush(); foreach (get_taxonomies() as $tax) { delete_option("{$tax}_children"); _get_term_hierarchy($tax); } $import->set('registered_on', date('Y-m-d H:i:s'))->update(); // clear import session pmxi_session_unset(); // clear session data (prevent from reimporting the same data on page refresh) // [indicate in header process is complete] $msg = addcslashes(__('Complete', 'pmxi_plugin'), "\n\r"); if ($ajax_processing) { ob_start(); } $import->options['is_import_specified'] and $logger and call_user_func($logger, 'Done'); echo <<<COMPLETE <script type="text/javascript"> //<![CDATA[ (function(\$){\t \t\$('#status').html('{$msg}'); \t\$('#import_finished').show(); \twindow.onbeforeunload = false; })(jQuery); //]]> </script> COMPLETE; // [/indicate in header process is complete] if ($ajax_processing) { wp_send_json(array('created' => $import->created, 'updated' => $import->updated, 'percentage' => 100, 'warnings' => PMXI_Plugin::$session->data['pmxi_import']['warnings'], 'errors' => PMXI_Plugin::$session->data['pmxi_import']['errors'], 'log' => ob_get_clean(), 'done' => true)); } } }
/** * Constructor * * This loads most of what's needed to run the plugin and sets actions and filters. * * @global float $timestart Seconds from when script started */ function __construct() { global $timestart; $this->version = '2.2'; $this->time = intval($timestart); $this->plugin_dir = dirname(plugin_basename(__FILE__)); $this->text_domain = 'backup'; // Enable internationalization load_plugin_textdomain($this->text_domain, false, $this->plugin_dir . '/languages'); $this->scope = array('https://www.googleapis.com/auth/drive.file', 'https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo.email', 'https://docs.google.com/feeds/', 'https://docs.googleusercontent.com/', 'https://spreadsheets.google.com/feeds/'); $this->http_transports = array('curl', 'streams', 'fsockopen'); $this->schedules = array('weekly' => array('interval' => 604800, 'display' => __('Weekly', $this->text_domain)), 'monthly' => array('interval' => 2592000, 'display' => __('Monthly', $this->text_domain))); $this->redirect_uri = admin_url('options-general.php?page=backup&action=auth'); // Get options if they exist, else set defaults if (!($this->options = get_option('backup_options'))) { $this->options = array('plugin_version' => $this->version, 'backup_token' => '', 'refresh_token' => '', 'backup_title' => get_bloginfo('name'), 'local_folder' => '', 'drive_folder' => '', 'backup_frequency' => 'never', 'source_list' => array('database', 'content', 'uploads', 'plugins'), 'exclude_list' => array('.svn', '.git', '.DS_Store'), 'include_list' => array(), 'backup_list' => array(), 'client_id' => '', 'client_secret' => '', 'local_number' => 1, 'drive_number' => 10, 'quota_total' => '', 'quota_used' => '', 'chunk_size' => 1, 'time_limit' => 600, 'backup_attempts' => 3, 'request_timeout' => 60, 'enabled_transports' => $this->http_transports, 'ssl_verify' => true, 'email_notify' => false, 'user_info' => array()); } else { if (!isset($this->options['plugin_version']) || version_compare($this->version, $this->options['plugin_version'], '>')) { add_action('init', array(&$this, 'upgrade'), 1); } } // Allow some options to be overwritten from the config file. if (defined('BACKUP_REFRESH_TOKEN')) { $this->options['refresh_token'] = BACKUP_REFRESH_TOKEN; } if (defined('BACKUP_DRIVE_FOLDER')) { $this->options['drive_folder'] = BACKUP_DRIVE_FOLDER; } if (defined('BACKUP_CLIENT_ID')) { $this->options['client_id'] = BACKUP_CLIENT_ID; } if (defined('BACKUP_CLIENT_SECRET')) { $this->options['client_secret'] = BACKUP_CLIENT_SECRET; } if (defined('BACKUP_LOCAL_FOLDER')) { $this->options['local_folder'] = BACKUP_LOCAL_FOLDER; } $this->local_folder = absolute_path($this->options['local_folder'], ABSPATH); if (defined('BACKUP_LOCAL_FOLDER')) { $this->create_dir($this->local_folder); } $this->dump_file = $this->local_folder . '/dump.sql'; $upload_dir = wp_upload_dir(); $this->sources = array('database' => array('title' => __('Database', $this->text_domain), 'path' => $this->dump_file), 'content' => array('title' => __('Content', $this->text_domain), 'path' => WP_CONTENT_DIR), 'uploads' => array('title' => __('Uploads', $this->text_domain), 'path' => $upload_dir['basedir']), 'plugins' => array('title' => __('Plugins', $this->text_domain), 'path' => WP_PLUGIN_DIR), 'wordpress' => array('title' => __('WordPress', $this->text_domain), 'path' => ABSPATH)); $this->exclude[] = $this->local_folder; register_activation_hook(__FILE__, array(&$this, 'activate')); // Add custom cron intervals add_filter('cron_schedules', array(&$this, 'cron_add_intervals')); // Link to the settings page from the plugins page add_filter('plugin_action_links', array(&$this, 'action_links'), 10, 2); // Disable unwanted HTTP transports. if (isset($this->options['enabled_transports'])) { foreach ($this->http_transports as $t) { if (!in_array($t, $this->options['enabled_transports'])) { add_filter('use_' . $t . '_transport', '__return_false'); } } } // Add 'Backup' to the Settings admin menu; save default metabox layout in the database. add_action('admin_menu', array(&$this, 'backup_menu')); // Handle Google OAuth2. if ($this->is_auth()) { add_action('init', array(&$this, 'auth')); } // Display persistent error notifications if we have any. if (isset($this->options['messages']['error'])) { add_action('admin_notices', array(&$this, 'error_notice'), 3); } // Print admin notices. add_action('admin_notices', array(&$this, 'print_notices'), 2); // Do backup on schedule. add_action('backup_schedule', array(&$this, 'do_backup')); // Retry to backup after a failed attempt. add_action('backup_retry', array(&$this, 'retry_backup')); // Do stuff just before the end of script execution. add_action('shutdown', array(&$this, 'shutdown')); // Prepare GOAuth object. $this->goauth = new GOAuth(array('client_id' => $this->options['client_id'], 'client_secret' => $this->options['client_secret'], 'redirect_uri' => $this->redirect_uri, 'refresh_token' => $this->options['refresh_token'], 'request_timeout' => $this->options['request_timeout'], 'ssl_verify' => $this->options['ssl_verify'])); // If we're doing backup work set the environment accordingly. if ($this->doing_backup()) { if (get_transient('backup_lock')) { exit; } // Exit if another backup process is running. set_transient('backup_lock', $this->time, 60 * 60 * 24); add_action('shutdown', array(&$this, 'unlock')); // Enable manual backup URI. add_action('template_redirect', array(&$this, 'manual_backup')); @ini_set('safe_mode', 0); // Try to disable safe mode. set_time_limit($this->options['time_limit']); // Set the time limit. // We might need a lot of memory for backing up. @ini_set('memory_limit', apply_filters('admin_memory_limit', WP_MAX_MEMORY_LIMIT)); ignore_user_abort(true); // Allow the script to run after the user closes the window. // All this is needed in order that every echo gets sent to the browser. @ini_set('zlib.output_compression', 0); @ini_set('implicit_flush', 1); wp_ob_end_flush_all(); ob_implicit_flush(); } }
/** * @param $files * @param $terms * @param $move * @param int|string $exists */ function gmedia_import_files($files, $terms, $move, $exists = 0) { global $gmCore, $gmGallery, $gmDB; if (ob_get_level() == 0) { ob_start(); } $eol = '</pre>' . PHP_EOL; $_terms = $terms; $gmedia_album = isset($_terms['gmedia_album']) ? $_terms['gmedia_album'] : false; if ($gmedia_album && $gmCore->is_digit($gmedia_album)) { $album = $gmDB->get_term($gmedia_album, 'gmedia_album'); if (empty($album) || is_wp_error($album)) { $status = 'public'; } else { $status = $album->status; $album_name = $album->name; } } else { $status = 'public'; } $c = count($files); $i = 0; foreach ($files as $file) { if (is_array($file)) { if (isset($file['file'])) { extract($file); } else { _e('Something went wrong...', 'gmLang'); die; } } wp_ob_end_flush_all(); flush(); $i++; $prefix = "\n<pre>{$i}/{$c} - "; $prefix_ko = "\n<pre class='ko'>{$i}/{$c} - "; if (!is_file($file)) { echo $prefix_ko . sprintf(__('File not exists: %s', 'gmLang'), $file) . $eol; continue; } if ('skip' === $exists) { $file_suffix = false; } else { $file_suffix = $exists; } $fileinfo = $gmCore->fileinfo($file, $file_suffix); if ('skip' === $exists && file_exists($fileinfo['filepath'])) { echo $prefix . $fileinfo['basename'] . ': ' . __('file already exists', 'gmLang') . $eol; continue; } // try to make grand-media dir if not exists if (!wp_mkdir_p($fileinfo['dirpath'])) { echo $prefix_ko . sprintf(__('Unable to create directory `%s`. Is its parent directory writable by the server?', 'gmLang'), $fileinfo['dirpath']) . $eol; continue; } // Check if grand-media dir is writable if (!is_writable($fileinfo['dirpath'])) { @chmod($fileinfo['dirpath'], 0755); if (!is_writable($fileinfo['dirpath'])) { echo $prefix_ko . sprintf(__('Directory `%s` or its subfolders are not writable by the server.', 'gmLang'), dirname($fileinfo['dirpath'])) . $eol; continue; } } if (!copy($file, $fileinfo['filepath'])) { echo $prefix_ko . sprintf(__("Can't copy file from `%s` to `%s`", 'gmLang'), $file, $fileinfo['filepath']) . $eol; continue; } $gmCore->file_chmod($fileinfo['filepath']); $size = false; $is_webimage = false; if ('image' == $fileinfo['dirname']) { /** WordPress Image Administration API */ require_once ABSPATH . 'wp-admin/includes/image.php'; $size = @getimagesize($fileinfo['filepath']); if ($size && file_is_displayable_image($fileinfo['filepath'])) { if (function_exists('memory_get_usage')) { $extensions = array('1' => 'GIF', '2' => 'JPG', '3' => 'PNG', '6' => 'BMP'); switch ($extensions[$size[2]]) { case 'GIF': $CHANNEL = 1; break; case 'JPG': $CHANNEL = $size['channels']; break; case 'PNG': $CHANNEL = 3; break; case 'BMP': default: $CHANNEL = 6; break; } $MB = 1048576; // number of bytes in 1M $K64 = 65536; // number of bytes in 64K $TWEAKFACTOR = 1.8; // Or whatever works for you $memoryNeeded = round(($size[0] * $size[1] * $size['bits'] * $CHANNEL / 8 + $K64) * $TWEAKFACTOR); $memoryNeeded = memory_get_usage() + $memoryNeeded; $current_limit = @ini_get('memory_limit'); $current_limit_int = intval($current_limit); if (false !== strpos($current_limit, 'M')) { $current_limit_int *= $MB; } if (false !== strpos($current_limit, 'G')) { $current_limit_int *= 1024; } if (-1 != $current_limit && $memoryNeeded > $current_limit_int) { $newLimit = $current_limit_int / $MB + ceil(($memoryNeeded - $current_limit_int) / $MB); @ini_set('memory_limit', $newLimit . 'M'); } } if (!wp_mkdir_p($fileinfo['dirpath_thumb'])) { echo $prefix_ko . sprintf(__('Unable to create directory `%s`. Is its parent directory writable by the server?', 'gmLang'), $fileinfo['dirpath_thumb']) . $eol; continue; } if (!is_writable($fileinfo['dirpath_thumb'])) { @chmod($fileinfo['dirpath_thumb'], 0755); if (!is_writable($fileinfo['dirpath_thumb'])) { @unlink($fileinfo['filepath']); echo $prefix_ko . sprintf(__('Directory `%s` is not writable by the server.', 'gmLang'), $fileinfo['dirpath_thumb']) . $eol; continue; } } if (!wp_mkdir_p($fileinfo['dirpath_original'])) { echo $prefix_ko . sprintf(__('Unable to create directory `%s`. Is its parent directory writable by the server?', 'gmLang'), $fileinfo['dirpath_original']) . $eol; continue; } if (!is_writable($fileinfo['dirpath_original'])) { @chmod($fileinfo['dirpath_original'], 0755); if (!is_writable($fileinfo['dirpath_original'])) { @unlink($fileinfo['filepath']); echo $prefix_ko . sprintf(__('Directory `%s` is not writable by the server.', 'gmLang'), $fileinfo['dirpath_original']) . $eol; continue; } } // Optimized image $webimg = $gmGallery->options['image']; $thumbimg = $gmGallery->options['thumb']; $webimg['resize'] = $webimg['width'] < $size[0] || $webimg['height'] < $size[1] ? true : false; $thumbimg['resize'] = $thumbimg['width'] < $size[0] || $thumbimg['height'] < $size[1] ? true : false; if ($webimg['resize']) { rename($fileinfo['filepath'], $fileinfo['filepath_original']); } else { copy($fileinfo['filepath'], $fileinfo['filepath_original']); } if ($webimg['resize'] || $thumbimg['resize']) { $editor = wp_get_image_editor($fileinfo['filepath_original']); if (is_wp_error($editor)) { @unlink($fileinfo['filepath_original']); echo $prefix_ko . $fileinfo['basename'] . " (wp_get_image_editor): " . $editor->get_error_message() . $eol; continue; } if ($webimg['resize']) { $editor->set_quality($webimg['quality']); $resized = $editor->resize($webimg['width'], $webimg['height'], $webimg['crop']); if (is_wp_error($resized)) { @unlink($fileinfo['filepath_original']); echo $prefix_ko . $fileinfo['basename'] . " (" . $resized->get_error_code() . " | editor->resize->webimage({$webimg['width']}, {$webimg['height']}, {$webimg['crop']})): " . $resized->get_error_message() . $eol; continue; } $saved = $editor->save($fileinfo['filepath']); if (is_wp_error($saved)) { @unlink($fileinfo['filepath_original']); echo $prefix_ko . $fileinfo['basename'] . " (" . $saved->get_error_code() . " | editor->save->webimage): " . $saved->get_error_message() . $eol; continue; } } // Thumbnail $editor->set_quality($thumbimg['quality']); $resized = $editor->resize($thumbimg['width'], $thumbimg['height'], $thumbimg['crop']); if (is_wp_error($resized)) { @unlink($fileinfo['filepath']); @unlink($fileinfo['filepath_original']); echo $prefix_ko . $fileinfo['basename'] . " (" . $resized->get_error_code() . " | editor->resize->thumb({$thumbimg['width']}, {$thumbimg['height']}, {$thumbimg['crop']})): " . $resized->get_error_message() . $eol; continue; } $saved = $editor->save($fileinfo['filepath_thumb']); if (is_wp_error($saved)) { @unlink($fileinfo['filepath']); @unlink($fileinfo['filepath_original']); echo $prefix_ko . $fileinfo['basename'] . " (" . $saved->get_error_code() . " | editor->save->thumb): " . $saved->get_error_message() . $eol; continue; } } else { copy($fileinfo['filepath'], $fileinfo['filepath_thumb']); } $is_webimage = true; } else { @unlink($fileinfo['filepath']); echo $prefix_ko . $fileinfo['basename'] . ": " . __("Could not read image size. Invalid image was deleted.", 'gmLang') . $eol; continue; } } // Write media data to DB // TODO Option to set title empty string or from metadata or from filename or both // use image exif/iptc data for title and caption defaults if possible if ($size && !isset($title) && !isset($description)) { $image_meta = @$gmCore->wp_read_image_metadata($fileinfo['filepath_original']); if (trim($image_meta['title']) && !is_numeric(sanitize_title($image_meta['title']))) { $title = $image_meta['title']; } if (trim($image_meta['caption'])) { $description = $image_meta['caption']; } } if (!isset($title) || empty($title)) { $title = $fileinfo['title']; } if (!isset($description)) { $description = ''; } if (!isset($link)) { $link = ''; } if (!$is_webimage) { unset($_terms['gmedia_category']); } // Construct the media_data array $media_data = array('mime_type' => $fileinfo['mime_type'], 'gmuid' => $fileinfo['basename'], 'title' => $title, 'link' => $link, 'description' => $description, 'status' => $status, 'terms' => $_terms); if (!current_user_can('gmedia_delete_others_media')) { $media_data['author'] = get_current_user_id(); } unset($title, $description); // Save the data $id = $gmDB->insert_gmedia($media_data); $gmDB->update_metadata($meta_type = 'gmedia', $id, $meta_key = '_metadata', $gmDB->generate_gmedia_metadata($id, $fileinfo)); echo $prefix . $fileinfo['basename'] . ': <span class="ok">' . sprintf(__('success (ID #%s)', 'gmLang'), $id) . '</span>' . $eol; if ($move) { @unlink($file); } } echo '<p><b>' . __('Category') . ':</b> ' . (isset($terms['gmedia_category']) && !empty($terms['gmedia_category']) ? esc_html($gmGallery->options['taxonomies']['gmedia_category'][$terms['gmedia_category']]) : '-') . PHP_EOL; echo '<br /><b>' . __('Album') . ':</b> ' . (isset($terms['gmedia_album']) && !empty($terms['gmedia_album']) ? isset($album_name) ? $album_name : esc_html($terms['gmedia_album']) : '-') . PHP_EOL; echo '<br /><b>' . __('Tags') . ':</b> ' . (isset($terms['gmedia_tag']) && !empty($terms['gmedia_tag']) ? esc_html(str_replace(',', ', ', $terms['gmedia_tag'])) : '-') . '</p>' . PHP_EOL; wp_ob_end_flush_all(); flush(); }
function handle_imports() { if (!empty($_POST['files']) && !empty($_POST['cwd'])) { $files = wp_unslash($_POST['files']); $cwd = trailingslashit(wp_unslash($_POST['cwd'])); $post_id = isset($_REQUEST['post_id']) ? intval($_REQUEST['post_id']) : 0; $import_date = isset($_REQUEST['import-date']) ? $_REQUEST['import-date'] : 'current'; $import_to_gallery = isset($_POST['gallery']) && 'on' == $_POST['gallery']; if (!$import_to_gallery && !isset($_REQUEST['cwd'])) { $import_to_gallery = true; // cwd should always be set, if it's not, and neither is gallery, this must be the first page load. } if (!$import_to_gallery) { $post_id = 0; } flush(); wp_ob_end_flush_all(); foreach ((array) $files as $file) { $filename = $cwd . $file; $id = $this->handle_import_file($filename, $post_id, $import_date); if (is_wp_error($id)) { echo '<div class="updated error"><p>' . sprintf(__('<em>%s</em> was <strong>not</strong> imported due to an error: %s', 'add-from-server'), esc_html($file), $id->get_error_message()) . '</p></div>'; } else { echo '<div class="updated"><p>' . sprintf(__('<em>%s</em> has been added to Media library', 'add-from-server'), esc_html($file)) . '</p></div>'; } flush(); wp_ob_end_flush_all(); } } }
/** * {@internal Missing Short Description}} * * @since 2.1.0 * * @param unknown_type $message */ function show_message($message) { if ( is_wp_error($message) ){ if ( $message->get_error_data() ) $message = $message->get_error_message() . ': ' . $message->get_error_data(); else $message = $message->get_error_message(); } echo "<p>$message</p>\n"; wp_ob_end_flush_all(); flush(); }
function hippo_flush_buffer() { wp_ob_end_flush_all(); @ob_flush(); flush(); }
/** * Run an import, and send an event-stream response. * * Streams logs and success messages to the browser to allow live status * and updates. */ public function stream_import() { // Turn off PHP output compression @ini_set('output_buffering', 'off'); @ini_set('zlib.output_compression', false); if ($GLOBALS['is_nginx']) { // Setting this header instructs Nginx to disable fastcgi_buffering // and disable gzip for this request. header('X-Accel-Buffering: no'); header('Content-Encoding: none'); } // Start the event stream. header('Content-Type: text/event-stream'); $this->id = wp_unslash((int) $_REQUEST['id']); $settings = get_post_meta($this->id, '_wxr_import_settings', true); if (empty($settings)) { // Tell the browser to stop reconnecting. status_header(204); exit; } // 2KB padding for IE echo ':' . str_repeat(' ', 2048) . "\n\n"; // Time to run the import! set_time_limit(0); // Ensure we're not buffered. wp_ob_end_flush_all(); flush(); $mapping = $settings['mapping']; $this->fetch_attachments = (bool) $settings['fetch_attachments']; $importer = $this->get_importer(); if (!empty($mapping['mapping'])) { $importer->set_user_mapping($mapping['mapping']); } if (!empty($mapping['slug_overrides'])) { $importer->set_user_slug_overrides($mapping['slug_overrides']); } // Are we allowed to create users? if (!$this->allow_create_users()) { add_filter('wxr_importer.pre_process.user', '__return_null'); } // Keep track of our progress add_action('wxr_importer.processed.post', array($this, 'imported_post'), 10, 2); add_action('wxr_importer.process_failed.post', array($this, 'imported_post'), 10, 2); add_action('wxr_importer.processed.comment', array($this, 'imported_comment')); add_action('wxr_importer.processed.term', array($this, 'imported_term')); add_action('wxr_importer.process_failed.term', array($this, 'imported_term')); add_action('wxr_importer.processed.user', array($this, 'imported_user')); add_action('wxr_importer.process_failed.user', array($this, 'imported_user')); // Clean up some memory unset($settings); // Flush once more. flush(); $file = get_attached_file($this->id); $err = $importer->import($file); // Remove the settings to stop future reconnects. delete_post_meta($this->id, '_wxr_import_settings'); // Let the browser know we're done. $complete = array('action' => 'complete', 'error' => false); if (is_wp_error($err)) { $complete['error'] = $err->get_error_message(); } $this->emit_sse_message($complete); exit; }
/** * @param $files */ function gmedia_images_update($files) { global $wpdb, $gmCore, $gmGallery; if (ob_get_level() == 0) { ob_start(); } $eol = '</pre>' . PHP_EOL; $c = count($files); $i = 0; foreach ($files as $file) { /** * @var $file * @var $id */ if (is_array($file)) { if (isset($file['file'])) { extract($file); } else { _e('Something went wrong...', 'gmLang'); die; } } wp_ob_end_flush_all(); $i++; $prefix = "\n<pre style='display:block;'>{$i}/{$c} - "; $prefix_ko = "\n<pre style='display:block;color:darkred;'>{$i}/{$c} - "; if (!is_file($file)) { $fileinfo = $gmCore->fileinfo($file, false); if (is_file($fileinfo['filepath_original'])) { @rename($fileinfo['filepath_original'], $fileinfo['filepath']); } else { echo $prefix_ko . sprintf(__('File not exists: %s', 'gmLang'), $file) . $eol; continue; } } $file_File = $file; $fileinfo = $gmCore->fileinfo($file, false); if ($file_File != $fileinfo['filepath']) { @rename($file_File, $fileinfo['filepath']); $wpdb->update($wpdb->prefix . 'gmedia', array('gmuid' => $fileinfo['basename']), array('gmuid' => basename($file_File))); } if ('image' == $fileinfo['dirname']) { $size = @getimagesize($fileinfo['filepath']); if (!file_exists($fileinfo['filepath_thumb']) && file_is_displayable_image($fileinfo['filepath'])) { if (function_exists('memory_get_usage')) { $extensions = array('1' => 'GIF', '2' => 'JPG', '3' => 'PNG', '6' => 'BMP'); switch ($extensions[$size[2]]) { case 'GIF': $CHANNEL = 1; break; case 'JPG': $CHANNEL = $size['channels']; break; case 'PNG': $CHANNEL = 3; break; case 'BMP': default: $CHANNEL = 6; break; } $MB = 1048576; // number of bytes in 1M $K64 = 65536; // number of bytes in 64K $TWEAKFACTOR = 1.8; // Or whatever works for you $memoryNeeded = round(($size[0] * $size[1] * $size['bits'] * $CHANNEL / 8 + $K64) * $TWEAKFACTOR); $memoryNeeded = memory_get_usage() + $memoryNeeded; $current_limit = @ini_get('memory_limit'); $current_limit_int = intval($current_limit); if (false !== strpos($current_limit, 'M')) { $current_limit_int *= $MB; } if (false !== strpos($current_limit, 'G')) { $current_limit_int *= 1024; } if (-1 != $current_limit && $memoryNeeded > $current_limit_int) { $newLimit = $current_limit_int / $MB + ceil(($memoryNeeded - $current_limit_int) / $MB); @ini_set('memory_limit', $newLimit . 'M'); } } if (!wp_mkdir_p($fileinfo['dirpath_thumb'])) { echo $prefix_ko . sprintf(__('Unable to create directory `%s`. Is its parent directory writable by the server?', 'gmLang'), $fileinfo['dirpath_thumb']) . $eol; continue; } if (!is_writable($fileinfo['dirpath_thumb'])) { @chmod($fileinfo['dirpath_thumb'], 0755); if (!is_writable($fileinfo['dirpath_thumb'])) { echo $prefix_ko . sprintf(__('Directory `%s` is not writable by the server.', 'gmLang'), $fileinfo['dirpath_thumb']) . $eol; continue; } } if (!wp_mkdir_p($fileinfo['dirpath_original'])) { echo $prefix_ko . sprintf(__('Unable to create directory `%s`. Is its parent directory writable by the server?', 'gmLang'), $fileinfo['dirpath_original']) . $eol; continue; } if (!is_writable($fileinfo['dirpath_original'])) { @chmod($fileinfo['dirpath_original'], 0755); if (!is_writable($fileinfo['dirpath_original'])) { echo $prefix_ko . sprintf(__('Directory `%s` is not writable by the server.', 'gmLang'), $fileinfo['dirpath_original']) . $eol; continue; } } // Optimized image $webimg = $gmGallery->options['image']; $thumbimg = $gmGallery->options['thumb']; $webimg['resize'] = $webimg['width'] < $size[0] || $webimg['height'] < $size[1] ? true : false; $thumbimg['resize'] = $thumbimg['width'] < $size[0] || $thumbimg['height'] < $size[1] ? true : false; if ($webimg['resize']) { rename($fileinfo['filepath'], $fileinfo['filepath_original']); } else { copy($fileinfo['filepath'], $fileinfo['filepath_original']); } if ($webimg['resize'] || $thumbimg['resize']) { $editor = wp_get_image_editor($fileinfo['filepath_original']); if (is_wp_error($editor)) { echo $prefix_ko . $fileinfo['basename'] . " (wp_get_image_editor): " . $editor->get_error_message(); continue; } if ($webimg['resize']) { $editor->set_quality($webimg['quality']); $resized = $editor->resize($webimg['width'], $webimg['height'], $webimg['crop']); if (is_wp_error($resized)) { echo $prefix_ko . $fileinfo['basename'] . " (" . $resized->get_error_code() . " | editor->resize->webimage({$webimg['width']}, {$webimg['height']}, {$webimg['crop']})): " . $resized->get_error_message() . $eol; continue; } $saved = $editor->save($fileinfo['filepath']); if (is_wp_error($saved)) { echo $prefix_ko . $fileinfo['basename'] . " (" . $saved->get_error_code() . " | editor->save->webimage): " . $saved->get_error_message() . $eol; continue; } } // Thumbnail $editor->set_quality($thumbimg['quality']); $resized = $editor->resize($thumbimg['width'], $thumbimg['height'], $thumbimg['crop']); if (is_wp_error($resized)) { echo $prefix_ko . $fileinfo['basename'] . " (" . $resized->get_error_code() . " | editor->resize->thumb({$thumbimg['width']}, {$thumbimg['height']}, {$thumbimg['crop']})): " . $resized->get_error_message() . $eol; continue; } $saved = $editor->save($fileinfo['filepath_thumb']); if (is_wp_error($saved)) { echo $prefix_ko . $fileinfo['basename'] . " (" . $saved->get_error_code() . " | editor->save->thumb): " . $saved->get_error_message() . $eol; continue; } } else { copy($fileinfo['filepath'], $fileinfo['filepath_thumb']); } } else { //echo $prefix_ko . $fileinfo['basename']. ": " . __("Could not read image size.", 'gmLang') . $eol; echo $prefix . $fileinfo['basename'] . ": " . __("Ignored", 'gmLang') . $eol; continue; } } else { echo $prefix_ko . $fileinfo['basename'] . ": " . __("Invalid image.", 'gmLang') . $eol; continue; } global $gmDB; // Save the data $gmDB->update_metadata($meta_type = 'gmedia', $id, $meta_key = '_metadata', $gmDB->generate_gmedia_metadata($id, $fileinfo)); echo $prefix . $fileinfo['basename'] . ': <span style="color:darkgreen;">' . sprintf(__('success (ID #%s)', 'gmLang'), $id) . '</span>' . $eol; } echo '<p>' . __('Image update process complete...', 'gmLang') . '</p>'; wp_ob_end_flush_all(); }
/** * Flush footer output buffer and iterate $this->i to make sure the * installation strings reference the correct plugin. * * @since 2.2.0 */ public function after_flush_output() { wp_ob_end_flush_all(); flush(); $this->i++; }
/** * Flush output to browser * * @return void */ private function flush_output() { wp_ob_end_flush_all(); flush(); }
/** * @access public */ public function flush_output() { wp_ob_end_flush_all(); flush(); }
/** * @param $files * @param $_terms * @param $move * @param int|string $exists */ function gmedia_import_files($files, $_terms, $move, $exists = 0) { global $wpdb, $gmGallery, $gmDB; if (ob_get_level() == 0) { ob_start(); } $eol = '</pre>' . PHP_EOL; $gmedia_album = isset($_terms['gmedia_album']) ? $_terms['gmedia_album'] : false; if ($gmedia_album && $this->is_digit($gmedia_album)) { $album = $gmDB->get_term($gmedia_album); if (empty($album) || is_wp_error($album)) { $_status = 'publish'; } else { $_status = $album->status; $album_name = $album->name; } } else { $_status = 'publish'; } if (isset($_terms['gmedia_album']) && !empty($_terms['gmedia_album'])) { if (is_array($_terms['gmedia_album'])) { $_terms['gmedia_album'] = trim(reset($_terms['gmedia_album'])); } } else { $_terms['gmedia_album'] = ''; } if (isset($_terms['gmedia_category']) && !empty($_terms['gmedia_category'])) { if (!is_array($_terms['gmedia_category'])) { $_terms['gmedia_category'] = array_filter(array_map('trim', explode(',', $_terms['gmedia_category']))); } } else { $_terms['gmedia_category'] = array(); } if (isset($_terms['gmedia_tag']) && !empty($_terms['gmedia_tag'])) { if (!is_array($_terms['gmedia_tag'])) { $_terms['gmedia_tag'] = array_filter(array_map('trim', explode(',', $_terms['gmedia_tag']))); } } else { $_terms['gmedia_tag'] = array(); } $c = count($files); $i = 0; foreach ($files as $file) { $title = ''; $description = ''; $link = ''; $status = $_status; $terms = $_terms; if (is_array($file)) { if (isset($file['file'])) { extract($file); } else { _e('Something went wrong...', 'grand-media'); die; } } wp_ob_end_flush_all(); flush(); $i++; $prefix = "\n<pre>{$i}/{$c} - "; $prefix_ko = "\n<pre class='ko'>{$i}/{$c} - "; if (!is_file($file)) { echo $prefix_ko . sprintf(__('File not exists: %s', 'grand-media'), $file) . $eol; continue; } if ('skip' === $exists) { $file_suffix = false; } else { $file_suffix = $exists; } $fileinfo = $this->fileinfo($file, $file_suffix); if ('skip' === $exists && is_file($fileinfo['filepath'])) { echo $prefix . $fileinfo['basename_original'] . ': ' . __('file with the same name already exists', 'grand-media') . $eol; continue; } // try to make grand-media dir if not exists if (!wp_mkdir_p($fileinfo['dirpath'])) { echo $prefix_ko . sprintf(__('Unable to create directory `%s`. Is its parent directory writable by the server?', 'grand-media'), $fileinfo['dirpath']) . $eol; continue; } // Check if grand-media dir is writable if (!is_writable($fileinfo['dirpath'])) { @chmod($fileinfo['dirpath'], 0755); if (!is_writable($fileinfo['dirpath'])) { echo $prefix_ko . sprintf(__('Directory `%s` or its subfolders are not writable by the server.', 'grand-media'), dirname($fileinfo['dirpath'])) . $eol; continue; } } if ($file != $fileinfo['filepath'] && !copy($file, $fileinfo['filepath'])) { echo $prefix_ko . sprintf(__("Can't copy file from `%s` to `%s`", 'grand-media'), $file, $fileinfo['filepath']) . $eol; continue; } $this->file_chmod($fileinfo['filepath']); $hash_file = hash_file('md5', $fileinfo['filepath']); $duplicate_id = $wpdb->get_var($wpdb->prepare("SELECT gmedia_id FROM {$wpdb->prefix}gmedia_meta WHERE meta_key = '_hash' AND meta_value = %s LIMIT 1;", $hash_file)); if ($duplicate_id) { @unlink($fileinfo['filepath']); echo $prefix_ko . $fileinfo['basename_original'] . ": " . sprintf(__("Seems like it is duplicate of file with ID #%d", 'grand-media'), $duplicate_id) . $eol; continue; } $size = false; $is_webimage = false; if ('image' == $fileinfo['dirname']) { /** WordPress Image Administration API */ require_once ABSPATH . 'wp-admin/includes/image.php'; $size = @getimagesize($fileinfo['filepath']); if ($size && file_is_displayable_image($fileinfo['filepath'])) { $extensions = array('1' => 'GIF', '2' => 'JPG', '3' => 'PNG', '6' => 'BMP'); if (function_exists('memory_get_usage')) { switch ($extensions[$size[2]]) { case 'GIF': $CHANNEL = 1; break; case 'JPG': $CHANNEL = $size['channels']; break; case 'PNG': $CHANNEL = 3; break; case 'BMP': default: $CHANNEL = 6; break; } $MB = 1048576; // number of bytes in 1M $K64 = 65536; // number of bytes in 64K $TWEAKFACTOR = 1.8; // Or whatever works for you $memoryNeeded = round(($size[0] * $size[1] * $size['bits'] * $CHANNEL / 8 + $K64) * $TWEAKFACTOR); $memoryNeeded = memory_get_usage() + $memoryNeeded; $current_limit = @ini_get('memory_limit'); $current_limit_int = intval($current_limit); if (false !== strpos($current_limit, 'M')) { $current_limit_int *= $MB; } if (false !== strpos($current_limit, 'G')) { $current_limit_int *= 1024; } if (-1 != $current_limit && $memoryNeeded > $current_limit_int) { $newLimit = $current_limit_int / $MB + ceil(($memoryNeeded - $current_limit_int) / $MB); if ($newLimit < 256) { $newLimit = 256; } @ini_set('memory_limit', $newLimit . 'M'); } } if (!wp_mkdir_p($fileinfo['dirpath_thumb'])) { echo $prefix_ko . sprintf(__('Unable to create directory `%s`. Is its parent directory writable by the server?', 'grand-media'), $fileinfo['dirpath_thumb']) . $eol; continue; } if (!is_writable($fileinfo['dirpath_thumb'])) { @chmod($fileinfo['dirpath_thumb'], 0755); if (!is_writable($fileinfo['dirpath_thumb'])) { @unlink($fileinfo['filepath']); echo $prefix_ko . sprintf(__('Directory `%s` is not writable by the server.', 'grand-media'), $fileinfo['dirpath_thumb']) . $eol; continue; } } if (!wp_mkdir_p($fileinfo['dirpath_original'])) { echo $prefix_ko . sprintf(__('Unable to create directory `%s`. Is its parent directory writable by the server?', 'grand-media'), $fileinfo['dirpath_original']) . $eol; continue; } if (!is_writable($fileinfo['dirpath_original'])) { @chmod($fileinfo['dirpath_original'], 0755); if (!is_writable($fileinfo['dirpath_original'])) { @unlink($fileinfo['filepath']); echo $prefix_ko . sprintf(__('Directory `%s` is not writable by the server.', 'grand-media'), $fileinfo['dirpath_original']) . $eol; continue; } } // Optimized image $webimg = $gmGallery->options['image']; $thumbimg = $gmGallery->options['thumb']; $webimg['resize'] = $webimg['width'] < $size[0] || $webimg['height'] < $size[1] ? true : false; if ($webimg['resize']) { rename($fileinfo['filepath'], $fileinfo['filepath_original']); } else { copy($fileinfo['filepath'], $fileinfo['filepath_original']); } $size_ratio = $size[0] / $size[1]; $angle = 0; $image_meta = @$this->wp_read_image_metadata($fileinfo['filepath_original']); if (!empty($image_meta['orientation'])) { switch ($image_meta['orientation']) { case 3: $angle = 180; break; case 6: $angle = 270; $size_ratio = $size[1] / $size[0]; break; case 8: $angle = 90; $size_ratio = $size[1] / $size[0]; break; } } $thumbimg['resize'] = 1 >= $size_ratio && $thumbimg['width'] > $size[0] || 1 <= $size_ratio && $thumbimg['height'] > $size[1] ? false : true; if ($webimg['resize'] || $thumbimg['resize'] || $angle) { $editor = wp_get_image_editor($fileinfo['filepath_original']); if (is_wp_error($editor)) { @unlink($fileinfo['filepath']); @unlink($fileinfo['filepath_original']); echo $prefix_ko . $fileinfo['basename'] . " (wp_get_image_editor): " . $editor->get_error_message() . $eol; continue; } if ($angle) { $editor->rotate($angle); } if ($webimg['resize'] || $angle) { $editor->set_quality($webimg['quality']); if ($webimg['resize']) { $resized = $editor->resize($webimg['width'], $webimg['height'], $webimg['crop']); if (is_wp_error($resized)) { @unlink($fileinfo['filepath']); @unlink($fileinfo['filepath_original']); echo $prefix_ko . $fileinfo['basename'] . " (" . $resized->get_error_code() . " | editor->resize->webimage({$webimg['width']}, {$webimg['height']}, {$webimg['crop']})): " . $resized->get_error_message() . $eol; continue; } } $saved = $editor->save($fileinfo['filepath']); if (is_wp_error($saved)) { @unlink($fileinfo['filepath']); @unlink($fileinfo['filepath_original']); echo $prefix_ko . $fileinfo['basename'] . " (" . $saved->get_error_code() . " | editor->save->webimage): " . $saved->get_error_message() . $eol; continue; } if ('JPG' == $extensions[$size[2]] && !(extension_loaded('imagick') || class_exists("Imagick"))) { $this->copy_exif($fileinfo['filepath_original'], $fileinfo['filepath']); } } // Thumbnail $editor->set_quality($thumbimg['quality']); if ($thumbimg['resize']) { $ed_size = $editor->get_size(); $ed_ratio = $ed_size['width'] / $ed_size['height']; if (1 > $ed_ratio) { $resized = $editor->resize($thumbimg['width'], 0, $thumbimg['crop']); } else { $resized = $editor->resize(0, $thumbimg['height'], $thumbimg['crop']); } if (is_wp_error($resized)) { @unlink($fileinfo['filepath']); @unlink($fileinfo['filepath_original']); echo $prefix_ko . $fileinfo['basename'] . " (" . $resized->get_error_code() . " | editor->resize->thumb({$thumbimg['width']}, {$thumbimg['height']}, {$thumbimg['crop']})): " . $resized->get_error_message() . $eol; continue; } } $saved = $editor->save($fileinfo['filepath_thumb']); if (is_wp_error($saved)) { @unlink($fileinfo['filepath']); @unlink($fileinfo['filepath_original']); echo $prefix_ko . $fileinfo['basename'] . " (" . $saved->get_error_code() . " | editor->save->thumb): " . $saved->get_error_message() . $eol; continue; } } else { copy($fileinfo['filepath'], $fileinfo['filepath_thumb']); } $is_webimage = true; } else { @unlink($fileinfo['filepath']); echo $prefix_ko . $fileinfo['basename'] . ": " . __("Could not read image size. Invalid image was deleted.", 'grand-media') . $eol; continue; } } // Write media data to DB if ($size) { if (!empty($image_meta)) { if (empty($title) && !empty($image_meta['title']) && trim($image_meta['title']) && !is_numeric(sanitize_title($image_meta['title']))) { $title = $image_meta['title']; } if (empty($description) && !empty($image_meta['caption']) && trim($image_meta['caption'])) { $description = $image_meta['caption']; } if (!empty($image_meta['keywords'])) { $terms['gmedia_tag'] = array_unique(array_merge((array) $_terms['gmedia_tag'], $image_meta['keywords'])); } } } else { $file_meta = $this->get_file_metadata($fileinfo['filepath_original'], $fileinfo); if (!empty($file_meta)) { if (empty($title) && !empty($file_meta['title']) && trim($file_meta['title']) && !is_numeric(sanitize_title($file_meta['title']))) { $title = $file_meta['title']; } if (empty($description) && !empty($file_meta['comment']) && trim($file_meta['comment'])) { $description = $file_meta['comment']; } if (empty($terms['gmedia_album']) && !empty($file_meta['album'])) { $terms['gmedia_album'] = array($file_meta['album']); } } } if (empty($title)) { $title = $fileinfo['title']; } // Construct the media_data array $media_data = array('mime_type' => $fileinfo['mime_type'], 'gmuid' => $fileinfo['basename'], 'title' => $title, 'link' => $link, 'description' => $description, 'status' => $status, 'terms' => $terms); if (!current_user_can('gmedia_delete_others_media')) { $media_data['author'] = get_current_user_id(); } // Save the data $id = $gmDB->insert_gmedia($media_data); $media_metadata = $gmDB->generate_gmedia_metadata($id, $fileinfo); if ($size && !empty($image_meta)) { if (empty($media_metadata['image_meta'])) { $media_metadata['image_meta'] = $image_meta; } if (!empty($image_meta['created_timestamp'])) { $gmDB->update_metadata($meta_type = 'gmedia', $id, $meta_key = '_created_timestamp', $image_meta['created_timestamp']); } if (!empty($image_meta['GPS'])) { $gmDB->update_metadata($meta_type = 'gmedia', $id, $meta_key = '_gps', $image_meta['GPS']); } } $gmDB->update_metadata($meta_type = 'gmedia', $id, $meta_key = '_metadata', $media_metadata); $gmDB->update_metadata($meta_type = 'gmedia', $id, $meta_key = '_hash', $hash_file); $file_size = filesize($fileinfo['filepath_original']); $gmDB->update_metadata($meta_type = 'gmedia', $id, $meta_key = '_size', $file_size); echo $prefix . $fileinfo['basename'] . ': <span class="ok">' . sprintf(__('success (ID #%s)', 'grand-media'), $id) . '</span>' . $eol; if ((int) $gmGallery->options['delete_originals']) { @unlink($fileinfo['filepath_original']); } if ($move) { @unlink($file); } } echo '<p><b>' . __('Category') . ':</b> ' . (!empty($_terms['gmedia_category']) ? esc_html(implode(', ', $_terms['gmedia_category'])) : '-') . PHP_EOL; echo '<br /><b>' . __('Album') . ':</b> ' . (!empty($_terms['gmedia_album']) ? isset($album_name) ? $album_name : esc_html($_terms['gmedia_album']) : '-') . PHP_EOL; echo '<br /><b>' . __('Tags') . ':</b> ' . (!empty($_terms['gmedia_tag']) ? esc_html(implode(', ', $_terms['gmedia_tag'])) : '-') . '</p>' . PHP_EOL; wp_ob_end_flush_all(); flush(); }