Esempio n. 1
1
 /**
  * Delete an import
  */
 public function delete()
 {
     if (!get_current_user_id() or !current_user_can('manage_options')) {
         // This nonce is not valid.
         die('Security check');
     } else {
         $id = $this->input->get('id');
         $this->data['item'] = $item = new PMXI_History_Record();
         if (!$id or $item->getById($id)->isEmpty()) {
             wp_redirect($this->baseUrl);
             die;
         }
         $item->delete();
         wp_redirect(add_query_arg('pmxi_nt', urlencode(__('History deleted', 'wp_all_import_plugin')), $this->baseUrl));
         die;
     }
 }
function pmxi_wp_loaded()
{
    @ini_set("max_input_time", PMXI_Plugin::getInstance()->getOption('max_input_time'));
    @ini_set("max_execution_time", PMXI_Plugin::getInstance()->getOption('max_execution_time'));
    $table = PMXI_Plugin::getInstance()->getTablePrefix() . 'imports';
    global $wpdb;
    $imports = $wpdb->get_results("SELECT `id`, `name`, `path` FROM {$table} WHERE `path` IS NULL", ARRAY_A);
    if (!empty($imports)) {
        $importRecord = new PMXI_Import_Record();
        $importRecord->clear();
        foreach ($imports as $imp) {
            $importRecord->getById($imp['id']);
            if (!$importRecord->isEmpty()) {
                $importRecord->delete(true);
            }
            $importRecord->clear();
        }
    }
    /* Check if cron is manualy, then execute import */
    $cron_job_key = PMXI_Plugin::getInstance()->getOption('cron_job_key');
    if (!empty($cron_job_key) and !empty($_GET['import_id']) and !empty($_GET['import_key']) and $_GET['import_key'] == $cron_job_key and !empty($_GET['action']) and in_array($_GET['action'], array('processing', 'trigger', 'pipe'))) {
        $logger = create_function('$m', 'echo "<p>$m</p>\\n";');
        $import = new PMXI_Import_Record();
        $ids = explode(',', $_GET['import_id']);
        if (!empty($ids) and is_array($ids)) {
            foreach ($ids as $id) {
                if (empty($id)) {
                    continue;
                }
                $import->getById($id);
                if (!$import->isEmpty()) {
                    if (!in_array($import->type, array('url', 'ftp', 'file'))) {
                        $logger and call_user_func($logger, sprintf(__('Scheduling update is not working with "upload" import type. Import #%s.', 'wp_all_import_plugin'), $id));
                    }
                    switch ($_GET['action']) {
                        case 'trigger':
                            if ((int) $import->executing) {
                                $logger and call_user_func($logger, sprintf(__('Import #%s is currently in manually process. Request skipped.', 'wp_all_import_plugin'), $id));
                            } elseif (!$import->processing and !$import->triggered) {
                                $import->set(array('triggered' => 1, 'imported' => 0, 'created' => 0, 'updated' => 0, 'skipped' => 0, 'deleted' => 0, 'queue_chunk_number' => 0, 'last_activity' => date('Y-m-d H:i:s')))->update();
                                $history_log = new PMXI_History_Record();
                                $history_log->set(array('import_id' => $import->id, 'date' => date('Y-m-d H:i:s'), 'type' => 'trigger', 'summary' => __("triggered by cron", "wp_all_import_plugin")))->save();
                                $logger and call_user_func($logger, sprintf(__('#%s Cron job triggered.', 'wp_all_import_plugin'), $id));
                            } elseif ($import->processing and !$import->triggered) {
                                $logger and call_user_func($logger, sprintf(__('Import #%s currently in process. Request skipped.', 'wp_all_import_plugin'), $id));
                            } elseif (!$import->processing and $import->triggered) {
                                $logger and call_user_func($logger, sprintf(__('Import #%s already triggered. Request skipped.', 'wp_all_import_plugin'), $id));
                            }
                            break;
                        case 'processing':
                            if ($import->processing == 1 and time() - strtotime($import->registered_on) > (PMXI_Plugin::getInstance()->getOption('cron_processing_time_limit') ? PMXI_Plugin::getInstance()->getOption('cron_processing_time_limit') : 120)) {
                                // it means processor crashed, so it will reset processing to false, and terminate. Then next run it will work normally.
                                $import->set(array('processing' => 0))->update();
                            }
                            // start execution imports that is in the cron process
                            if (!(int) $import->triggered) {
                                $logger and call_user_func($logger, sprintf(__('Import #%s is not triggered. Request skipped.', 'wp_all_import_plugin'), $id));
                            } elseif ((int) $import->executing) {
                                $logger and call_user_func($logger, sprintf(__('Import #%s is currently in manually process. Request skipped.', 'wp_all_import_plugin'), $id));
                            } elseif ((int) $import->triggered and !(int) $import->processing) {
                                $log_storage = (int) PMXI_Plugin::getInstance()->getOption('log_storage');
                                // unlink previous logs
                                $by = array();
                                $by[] = array(array('import_id' => $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 = new PMXI_History_Record();
                                $history_log->set(array('import_id' => $import->id, 'date' => date('Y-m-d H:i:s'), 'type' => 'processing', 'summary' => __("cron processing", "wp_all_import_plugin")))->save();
                                if ($log_storage) {
                                    $wp_uploads = wp_upload_dir();
                                    $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 (@file_exists($log_file)) {
                                        wp_all_import_remove_source($log_file, false);
                                    }
                                }
                                ob_start();
                                $import->set(array('canceled' => 0, 'failed' => 0))->execute($logger, true, $history_log->id);
                                $log_data = ob_get_clean();
                                if ($log_storage) {
                                    $log = @fopen($log_file, 'a+');
                                    @fwrite($log, $log_data);
                                    @fclose($log);
                                }
                                if (!(int) $import->queue_chunk_number) {
                                    $logger and call_user_func($logger, sprintf(__('Import #%s complete', 'wp_all_import_plugin'), $import->id));
                                } else {
                                    $logger and call_user_func($logger, sprintf(__('Records Count %s', 'wp_all_import_plugin'), (int) $import->count));
                                    $logger and call_user_func($logger, sprintf(__('Records Processed %s', 'wp_all_import_plugin'), (int) $import->queue_chunk_number));
                                }
                            } else {
                                $logger and call_user_func($logger, sprintf(__('Import #%s already processing. Request skipped.', 'wp_all_import_plugin'), $id));
                            }
                            break;
                        case 'pipe':
                            $import->execute($logger);
                            break;
                    }
                }
            }
        }
    }
}
Esempio n. 3
0
    /**
     * 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']));
            }
        }
    }
Esempio n. 4
0
 public function cleanup()
 {
     $removedFiles = 0;
     $wp_uploads = wp_upload_dir();
     $dir = $wp_uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::TEMP_DIRECTORY;
     $cacheDir = PMXI_Plugin::ROOT_DIR . '/libraries/cache';
     $files = array_diff(@scandir($dir), array('.', '..'));
     $cacheFiles = @array_diff(@scandir($cacheDir), array('.', '..'));
     $msg = __('Files not found', 'wp_all_import_plugin');
     if (count($files) or count($cacheFiles)) {
         wp_all_import_clear_directory($dir);
         wp_all_import_clear_directory($cacheDir);
         $msg = __('Clean Up has been successfully completed.', 'wp_all_import_plugin');
     }
     // clean logs files
     $table = PMXI_Plugin::getInstance()->getTablePrefix() . 'history';
     global $wpdb;
     $histories = $wpdb->get_results("SELECT * FROM {$table}", ARRAY_A);
     if (!empty($histories)) {
         $importRecord = new PMXI_Import_Record();
         $importRecord->clear();
         foreach ($histories as $history) {
             $importRecord->getById($history['import_id']);
             if ($importRecord->isEmpty()) {
                 $historyRecord = new PMXI_History_Record();
                 $historyRecord->getById($history['id']);
                 if (!$historyRecord->isEmpty()) {
                     $historyRecord->delete();
                 }
             }
             $importRecord->clear();
         }
     }
     // clean uploads folder
     $table = PMXI_Plugin::getInstance()->getTablePrefix() . 'files';
     $files = $wpdb->get_results("SELECT * FROM {$table}", ARRAY_A);
     $required_dirs = array();
     if (!empty($files)) {
         $importRecord = new PMXI_Import_Record();
         $importRecord->clear();
         foreach ($files as $file) {
             $importRecord->getById($file['import_id']);
             if ($importRecord->isEmpty()) {
                 $fileRecord = new PMXI_File_Record();
                 $fileRecord->getById($file['id']);
                 if (!$fileRecord->isEmpty()) {
                     $fileRecord->delete();
                 }
             } else {
                 $path_parts = pathinfo(wp_all_import_get_absolute_path($file['path']));
                 if (!empty($path_parts['dirname'])) {
                     $path_all_parts = explode('/', $path_parts['dirname']);
                     $dirname = array_pop($path_all_parts);
                     if (wp_all_import_isValidMd5($dirname)) {
                         $required_dirs[] = $path_parts['dirname'];
                     }
                 }
             }
             $importRecord->clear();
         }
     }
     $uploads_dir = $wp_uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::UPLOADS_DIRECTORY;
     if (($dir = @opendir($uploads_dir . DIRECTORY_SEPARATOR)) !== false or ($dir = @opendir($uploads_dir)) !== false) {
         while (($file = @readdir($dir)) !== false) {
             $filePath = $uploads_dir . DIRECTORY_SEPARATOR . $file;
             if (is_dir($filePath) and !in_array($filePath, $required_dirs) and !in_array($file, array('.', '..'))) {
                 wp_all_import_rmdir($filePath);
             }
         }
     }
     wp_redirect(add_query_arg('pmxi_nt', urlencode($msg), $this->baseUrl));
     die;
 }
Esempio n. 5
0
 /**
  * Import all files matched by path
  * @param callback[optional] $logger Method where progress messages are submmitted
  * @return PMXI_Import_Record
  * @chainable
  */
 public function execute($logger = NULL, $cron = true, $history_log_id = false)
 {
     $uploads = wp_upload_dir();
     if ($this->path) {
         $files = array($this->path);
         foreach ($files as $ind => $path) {
             $filePath = '';
             if ($this->queue_chunk_number == 0 and $this->processing == 0) {
                 $this->set(array('processing' => 1))->update();
                 // lock cron requests
                 if ($this->type == 'ftp') {
                     $this->set(array('processing' => 0))->update();
                     return array('status' => 500, 'message' => sprintf(__('This import appears to be using FTP. Unfortunately WP All Import no longer supports the FTP protocol. Please contact <a href="mailto:support@wpallimport.com">%s</a> if you have any questions.', 'wp_all_import_plugin'), '*****@*****.**'));
                     //$logger and call_user_func($logger, sprintf(__('This import appears to be using FTP. Unfortunately WP All Import no longer supports the FTP protocol. Please contact <a href="mailto:support@wpallimport.com">%s</a> if you have any questions.', 'wp_all_import_plugin'), '*****@*****.**'));
                     die;
                 } elseif ($this->type == 'url') {
                     $filesXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<data><node></node></data>";
                     $filePaths = XmlImportParser::factory($filesXML, '/data/node', $this->path, $file)->parse();
                     $tmp_files[] = $file;
                     foreach ($tmp_files as $tmp_file) {
                         // remove all temporary files created
                         @unlink($tmp_file);
                     }
                     $file_to_import = $this->path;
                     if (!empty($filePaths) and is_array($filePaths)) {
                         $file_to_import = array_shift($filePaths);
                     }
                     $uploader = new PMXI_Upload(trim($file_to_import), $this->errors);
                     $upload_result = $uploader->url($this->feed_type, $this->path);
                     if ($upload_result instanceof WP_Error) {
                         $this->errors = $upload_result;
                     } else {
                         $filePath = $upload_result['filePath'];
                     }
                 } elseif ($this->type == 'file') {
                     $uploader = new PMXI_Upload(trim(basename($this->path)), $this->errors);
                     $upload_result = $uploader->file();
                     if ($upload_result instanceof WP_Error) {
                         $this->errors = $upload_result;
                     } else {
                         $filePath = $upload_result['filePath'];
                     }
                 } elseif (!in_array($this->type, array('ftp'))) {
                     // retrieve already uploaded file
                     $uploader = new PMXI_Upload(trim($this->path), $this->errors, rtrim(str_replace(basename($this->path), '', $this->path), '/'));
                     $upload_result = $uploader->upload();
                     if ($upload_result instanceof WP_Error) {
                         $this->errors = $upload_result;
                     } else {
                         $filePath = $upload_result['filePath'];
                     }
                 }
                 if (!$this->errors->get_error_codes() and "" != $filePath) {
                     $this->set(array('queue_chunk_number' => 1))->update();
                 } elseif ($this->errors->get_error_codes()) {
                     $msgs = $this->errors->get_error_messages();
                     if (!is_array($msgs)) {
                         $msgs = array($msgs);
                     }
                     // foreach ($msgs as $msg){
                     // 	$logger and call_user_func($logger, sprintf(__('ERROR: %s', 'wp_all_import_plugin'), $msg));
                     // }
                     $this->set(array('processing' => 0))->update();
                     return array('status' => 500, 'message' => $msgs);
                     die;
                 }
                 $this->set(array('processing' => 0))->update();
                 // unlock cron requests
             }
             // if empty file path, than it's mean feed in cron process. Take feed path from history.
             if (empty($filePath)) {
                 $history = new PMXI_File_List();
                 $history->setColumns('id', 'name', 'registered_on', 'path')->getBy(array('import_id' => $this->id), 'id DESC');
                 if ($history->count()) {
                     $history_file = new PMXI_File_Record();
                     $history_file->getBy('id', $history[0]['id']);
                     $filePath = wp_all_import_get_absolute_path($history_file->path);
                 }
             }
             // if feed path found
             if (!empty($filePath) and @file_exists($filePath)) {
                 if ($this->queue_chunk_number === 1 and $this->processing == 0) {
                     // import first cron request
                     $this->set(array('processing' => 1))->update();
                     // lock cron requests
                     if (empty($this->options['encoding'])) {
                         $currentOptions = $this->options;
                         $currentOptions['encoding'] = 'UTF-8';
                         $this->set(array('options' => $currentOptions))->update();
                     }
                     set_time_limit(0);
                     $file = new PMXI_Chunk($filePath, array('element' => $this->root_element, 'encoding' => $this->options['encoding']));
                     // chunks counting
                     $chunks = 0;
                     $history_xml = '';
                     while ($xml = $file->read()) {
                         if (!empty($xml)) {
                             PMXI_Import_Record::preprocessXml($xml);
                             $xml = "<?xml version=\"1.0\" encoding=\"" . $this->options['encoding'] . "\"?>" . "\n" . $xml;
                             $dom = new DOMDocument('1.0', !empty($this->options['encoding']) ? $this->options['encoding'] : 'UTF-8');
                             $old = libxml_use_internal_errors(true);
                             $dom->loadXML($xml);
                             libxml_use_internal_errors($old);
                             $xpath = new DOMXPath($dom);
                             if ($elements = @$xpath->query($this->xpath) and $elements->length) {
                                 $chunks += $elements->length;
                                 if ("" == $history_xml) {
                                     $history_xml = $xml;
                                 }
                             }
                             unset($dom, $xpath, $elements);
                         }
                     }
                     unset($file);
                     if (!$chunks) {
                         //$logger and call_user_func($logger, sprintf(__('#%s No matching elements found for Root element and XPath expression specified', 'wp_all_import_plugin'), $this->id));
                         $this->set(array('queue_chunk_number' => 0, 'processing' => 0, 'imported' => 0, 'created' => 0, 'updated' => 0, 'skipped' => 0, 'deleted' => 0, 'triggered' => 0))->update();
                         return array('status' => 500, 'message' => sprintf(__('#%s No matching elements found for Root element and XPath expression specified', 'wp_all_import_plugin'), $this->id));
                         die;
                     }
                     // unlick previous files
                     $history = new PMXI_File_List();
                     $history->setColumns('id', 'name', 'registered_on', 'path')->getBy(array('import_id' => $this->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 != $filePath) {
                                 if (in_array($this->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($history_file_path != $filePath);
                             }
                         }
                     }
                     // update history
                     $history_file = new PMXI_File_Record();
                     $history_file->set(array('name' => $this->name, 'import_id' => $this->id, 'path' => wp_all_import_get_relative_path($filePath), 'registered_on' => date('Y-m-d H:i:s')))->insert();
                     do_action('pmxi_before_xml_import', $this->id);
                     $this->set(array('count' => $chunks, 'processing' => 0))->update();
                     // set pointer to the first chunk, updates feed elements count and unlock cron process
                 }
                 // compose data to look like result of wizard steps
                 if ($this->queue_chunk_number and $this->processing == 0) {
                     $this->set(array('processing' => 1))->update();
                     // lock cron requests
                     @set_time_limit(0);
                     $file = new PMXI_Chunk($filePath, array('element' => $this->root_element, 'encoding' => $this->options['encoding'], 'pointer' => $this->queue_chunk_number));
                     $feed = "<?xml version=\"1.0\" encoding=\"" . $this->options['encoding'] . "\"?>" . "\n" . "<pmxi_records>";
                     $loop = 0;
                     $xml = '';
                     $processing_time_limit = PMXI_Plugin::getInstance()->getOption('cron_processing_time_limit') ? PMXI_Plugin::getInstance()->getOption('cron_processing_time_limit') : 120;
                     $start_rocessing_time = time();
                     $chunk_number = $this->queue_chunk_number;
                     $functions = $uploads['basedir'] . DIRECTORY_SEPARATOR . WP_ALL_IMPORT_UPLOADS_BASE_DIRECTORY . DIRECTORY_SEPARATOR . 'functions.php';
                     if (@file_exists($functions)) {
                         require_once $functions;
                     }
                     while ($xml = $file->read() and $this->processing == 1 and time() - $start_rocessing_time <= $processing_time_limit) {
                         if (!empty($xml)) {
                             $chunk_number++;
                             PMXI_Import_Record::preprocessXml($xml);
                             $xml_chunk = "<?xml version=\"1.0\" encoding=\"" . $this->options['encoding'] . "\"?>" . "\n" . $xml;
                             $dom = new DOMDocument('1.0', !empty($this->options['encoding']) ? $this->options['encoding'] : 'UTF-8');
                             $old = libxml_use_internal_errors(true);
                             $dom->loadXML($xml_chunk);
                             libxml_use_internal_errors($old);
                             $xpath = new DOMXPath($dom);
                             if ($elements = @$xpath->query($this->xpath) and $elements->length) {
                                 $feed .= $xml;
                                 $loop += $elements->length;
                             }
                             unset($dom, $xpath, $elements);
                         }
                         if ($loop == $this->options['records_per_request'] or $this->count == $this->imported + $this->skipped or $this->count == $loop + $this->imported + $this->skipped) {
                             // skipping scheduled imports if any for the next hit
                             $feed .= "</pmxi_records>";
                             $this->process($feed, $logger, $chunk_number, $cron, '/pmxi_records', $loop);
                             // set last update
                             $this->set(array('registered_on' => date('Y-m-d H:i:s'), 'queue_chunk_number' => $chunk_number))->update();
                             $loop = 0;
                             $feed = "<?xml version=\"1.0\" encoding=\"" . $this->options['encoding'] . "\"?>" . "\n" . "<pmxi_records>";
                         }
                     }
                     unset($file);
                     // delect, if cron process if finished
                     if ((int) $this->count <= (int) $this->imported + (int) $this->skipped) {
                         // Delete posts that are no longer present in your file
                         if (!empty($this->options['is_delete_missing']) and $this->options['duplicate_matching'] == 'auto') {
                             $postList = new PMXI_Post_List();
                             $missing_ids = array();
                             $missingPosts = $postList->getBy(array('import_id' => $this->id, 'iteration !=' => $this->iteration));
                             if (!$missingPosts->isEmpty()) {
                                 foreach ($missingPosts as $missingPost) {
                                     $missing_ids[] = $missingPost['post_id'];
                                 }
                             }
                             // Delete posts from database
                             if (!empty($missing_ids) && is_array($missing_ids)) {
                                 $missing_ids_arr = array_chunk($missing_ids, 100);
                                 foreach ($missing_ids_arr as $key => $ids) {
                                     if (!empty($ids)) {
                                         foreach ($ids as $k => $id) {
                                             $to_delete = true;
                                             // Instead of deletion, set Custom Field
                                             if ($this->options['is_update_missing_cf']) {
                                                 update_post_meta($id, $this->options['update_missing_cf_name'], $this->options['update_missing_cf_value']);
                                                 $to_delete = false;
                                             }
                                             // Instead of deletion, change post status to Draft
                                             $final_post_type = get_post_type($pid);
                                             if ($this->options['set_missing_to_draft'] and $final_post_type != 'product_variation') {
                                                 $this->wpdb->update($this->wpdb->posts, array('post_status' => 'draft'), array('ID' => $id));
                                                 $to_delete = false;
                                             }
                                             // Delete posts that are no longer present in your file
                                             if ($to_delete) {
                                                 // Remove attachments
                                                 empty($this->options['is_keep_attachments']) and wp_delete_attachments($id, true, 'files');
                                                 // Remove images
                                                 empty($this->options['is_keep_imgs']) and wp_delete_attachments($id, true, 'images');
                                                 // Clear post's relationships
                                                 if ($this->options['custom_type'] != "import_users") {
                                                     wp_delete_object_term_relationships($id, get_object_taxonomies('' != $this->options['custom_type'] ? $this->options['custom_type'] : 'post'));
                                                 }
                                             } else {
                                                 unset($ids[$k]);
                                             }
                                         }
                                         if (!empty($ids)) {
                                             do_action('pmxi_delete_post', $ids);
                                             if ($this->options['custom_type'] == "import_users") {
                                                 $sql = "delete a,b\n\t\t\t\t\t\t\t\t\t\t\t\t\tFROM " . $this->wpdb->users . " a\n\t\t\t\t\t\t\t\t\t\t\t\t\tLEFT JOIN " . $this->wpdb->usermeta . " b ON ( a.ID = b.user_id )\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE a.ID IN (" . implode(',', $ids) . ");";
                                             } else {
                                                 $sql = "delete a,b,c\n\t\t\t\t\t\t\t\t\t\t\t\t\tFROM " . $this->wpdb->posts . " a\n\t\t\t\t\t\t\t\t\t\t\t\t\tLEFT JOIN " . $this->wpdb->term_relationships . " b ON ( a.ID = b.object_id )\n\t\t\t\t\t\t\t\t\t\t\t\t\tLEFT JOIN " . $this->wpdb->postmeta . " c ON ( a.ID = c.post_id )\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE a.ID IN (" . implode(',', $ids) . ");";
                                             }
                                             $this->wpdb->query($sql);
                                             // Delete record form pmxi_posts
                                             $sql = "DELETE FROM " . PMXI_Plugin::getInstance()->getTablePrefix() . "posts WHERE post_id IN (" . implode(',', $ids) . ") AND import_id = %d";
                                             $this->wpdb->query($this->wpdb->prepare($sql, $this->id));
                                             $this->set(array('deleted' => $this->deleted + count($ids)))->update();
                                         }
                                     }
                                 }
                             }
                         }
                         // Set out of stock status for missing records [Woocommerce add-on option]
                         if (empty($this->options['is_delete_missing']) and $this->options['custom_type'] == "product" and class_exists('PMWI_Plugin') and !empty($this->options['missing_records_stock_status'])) {
                             $postList = new PMXI_Post_List();
                             $missingPosts = $postList->getBy(array('import_id' => $this->id, 'iteration !=' => $this->iteration));
                             if (!$missingPosts->isEmpty()) {
                                 foreach ($missingPosts as $missingPost) {
                                     update_post_meta($missingPost['post_id'], '_stock_status', 'outofstock');
                                     update_post_meta($missingPost['post_id'], '_stock', 0);
                                     $postRecord = new PMXI_Post_Record();
                                     $postRecord->getBy('id', $missingPost['id']);
                                     if (!$postRecord->isEmpty()) {
                                         $postRecord->set(array('iteration' => $this->iteration))->update();
                                     }
                                     unset($postRecord);
                                 }
                             }
                         }
                         $this->set(array('processing' => 0, 'triggered' => 0, 'queue_chunk_number' => 0, 'registered_on' => date('Y-m-d H:i:s'), 'iteration' => ++$this->iteration))->update();
                         wp_cache_flush();
                         foreach (get_taxonomies() as $tax) {
                             delete_option("{$tax}_children");
                             _get_term_hierarchy($tax);
                         }
                         if ($history_log_id) {
                             $history_log = new PMXI_History_Record();
                             $history_log->getById($history_log_id);
                             if (!$history_log->isEmpty()) {
                                 $custom_type = get_post_type_object($this->options['custom_type']);
                                 $history_log->set(array('time_run' => time() - strtotime($history_log->date), 'summary' => sprintf(__("import finished & cron un-triggered<br>%s %s created %s updated %s deleted %s skipped", "pmxi_plugin"), $this->created, $custom_type->labels->name, $this->updated, $this->deleted, $this->skipped)))->save();
                             }
                         }
                         do_action('pmxi_after_xml_import', $this->id);
                         return array('status' => 200, 'message' => sprintf(__('Import #%s complete', 'wp_all_import_plugin'), $this->id));
                         //$logger and call_user_func($logger, sprintf(__('Import #%s complete', 'wp_all_import_plugin'), $this->id));
                     } else {
                         $this->set(array('processing' => 0))->update();
                         if ($history_log_id) {
                             $history_log = new PMXI_History_Record();
                             $history_log->getById($history_log_id);
                             if (!$history_log->isEmpty()) {
                                 $custom_type = get_post_type_object($this->options['custom_type']);
                                 $history_log->set(array('time_run' => time() - strtotime($history_log->date), 'summary' => sprintf(__("%d %s created %d updated %d deleted %d skipped", "pmxi_plugin"), $this->created, $custom_type->labels->name, $this->updated, $this->deleted, $this->skipped)))->save();
                             }
                         }
                         return array('status' => 200, 'message' => sprintf(__('Records Processed %s. Records Count %s.', 'wp_all_import_plugin'), (int) $this->queue_chunk_number, (int) $this->count));
                         // $logger and call_user_func($logger, sprintf(__('Records Count %s', 'wp_all_import_plugin'), (int) $this->count));
                         // $logger and call_user_func($logger, sprintf(__('Records Processed %s', 'wp_all_import_plugin'), (int) $this->imported + (int) $this->skipped));
                     }
                 }
             } else {
                 $this->set(array('processing' => 0, 'triggered' => 0, 'queue_chunk_number' => 0, 'imported' => 0, 'created' => 0, 'updated' => 0, 'skipped' => 0, 'deleted' => 0))->update();
                 return array('status' => 500, 'message' => sprintf(__('#%s source file not found', 'wp_all_import_plugin'), $this->id));
                 //$logger and call_user_func($logger, sprintf(__('#%s source file not found', 'wp_all_import_plugin'), $this->id));
                 die;
             }
         }
     }
     return $this;
 }
Esempio n. 6
-1
 /**
  * Delete an import
  */
 public function delete()
 {
     $id = $this->input->get('id');
     $this->data['item'] = $item = new PMXI_History_Record();
     if (!$id or $item->getById($id)->isEmpty()) {
         wp_redirect($this->baseUrl);
         die;
     }
     $item->delete();
     wp_redirect(add_query_arg('pmxi_nt', urlencode(__('History deleted', 'pmxi_plugin')), $this->baseUrl));
     die;
 }