xx - PHP Online

Form of PHP Sandbox

Enter Your PHP code here for testing/debugging in the Online PHP Sandbox. As in the usual PHP files, you can also add HTML, but do not forget to add the tag <?php in the places where the PHP script should be executed.



Your result can be seen below.

Result of php executing





Full code of xx.php

  1. <?php
  2.  
  3. if (!defined('ABSPATH')) {
  4.         exit;
  5. }
  6.  
  7. if (!function_exists('getimagesizefromstring')) {
  8.         function getimagesizefromstring($string_data) {
  9.                 $uri = 'data://application/octet-stream;base64,' . base64_encode($string_data);
  10.                 return getimagesize($uri);
  11.         }
  12. }
  13.  
  14. class OL_Scrapes {
  15.         public static $task_id = 0;
  16.         public static $tld;
  17.        
  18.         public static function activate_plugin() {
  19.                 self::write_log('Scrapes activated');
  20.                 self::write_log(self::system_info());
  21.         }
  22.        
  23.         public static function deactivate_plugin() {
  24.                 self::write_log('Scrapes deactivated');
  25.                 self::clear_all_schedules();
  26.         }
  27.        
  28.         public static function uninstall_plugin() {
  29.                 self::clear_all_schedules();
  30.                 self::clear_all_tasks();
  31.                 self::clear_all_values();
  32.         }
  33.        
  34.         public function requirements_check() {
  35.                 load_plugin_textdomain('ol-scrapes', false, dirname(plugin_basename(__FILE__)) . '/../languages');
  36.                 $min_wp = '3.5';
  37.                 $min_php = '5.2.4';
  38.                 $exts = array('dom', 'mbstring', 'iconv', 'json', 'simplexml');
  39.                
  40.                 $errors = array();
  41.                
  42.                 if (version_compare(get_bloginfo('version'), $min_wp, '<')) {
  43.                         $errors[] = __("Your WordPress version is below 3.5. Please update.", "ol-scrapes");
  44.                 }
  45.                
  46.                 if (version_compare(PHP_VERSION, $min_php, '<')) {
  47.                         $errors[] = __("PHP version is below 5.2.4. Please update.", "ol-scrapes");
  48.                 }
  49.                
  50.                 foreach ($exts as $ext) {
  51.                         if (!extension_loaded($ext)) {
  52.                                 $errors[] = sprintf(__("PHP extension %s is not loaded. Please contact your server administrator or visit http://php.net/manual/en/%s.installation.php for installation.", "ol-scrapes"), $ext, $ext);
  53.                         }
  54.                 }
  55.                
  56.                 $folder = plugin_dir_path(__FILE__) . "../logs";
  57.                
  58.                 if (!is_dir($folder) && mkdir($folder, 0755) === false) {
  59.                         $errors[] = sprintf(__("%s folder is not writable. Please update permissions for this folder to chmod 755.", "ol-scrapes"), $folder);
  60.                 }
  61.                
  62.                 if (fopen($folder . DIRECTORY_SEPARATOR . "logs.txt", "a") === false) {
  63.                         $errors[] = sprintf(__("%s folder is not writable therefore logs.txt file could not be created. Please update permissions for this folder to chmod 755.", "ol-scrapes"), $folder);
  64.                 }
  65.                
  66.                 return $errors;
  67.         }
  68.        
  69.         public function add_admin_js_css() {
  70.                 add_action('admin_enqueue_scripts', array($this, "init_admin_js_css"));
  71.         }
  72.        
  73.         public function init_admin_js_css($hook_suffix) {
  74.                 wp_enqueue_style("ol_menu_css", plugins_url("assets/css/menu.css", dirname(__FILE__)), null, OL_VERSION);
  75.                
  76.                 if (is_object(get_current_screen()) && get_current_screen()->post_type == "scrape") {
  77.                         if (in_array($hook_suffix, array('post.php', 'post-new.php'))) {
  78.                                 wp_enqueue_script("ol_fix_jquery", plugins_url("assets/js/fix_jquery.js", dirname(__FILE__)), null, OL_VERSION);
  79.                                 wp_enqueue_script("ol_jquery", plugins_url("libraries/jquery-2.2.4/jquery-2.2.4.min.js", dirname(__FILE__)), null, OL_VERSION);
  80.                                 wp_enqueue_script("ol_jquery_ui", plugins_url("libraries/jquery-ui-1.12.1.custom/jquery-ui.min.js", dirname(__FILE__)), null, OL_VERSION);
  81.                                 wp_enqueue_script("ol_bootstrap", plugins_url("libraries/bootstrap-3.3.7-dist/js/bootstrap.min.js", dirname(__FILE__)), null, OL_VERSION);
  82.                                 wp_enqueue_script("ol_angular", plugins_url("libraries/angular-1.5.8/angular.min.js", dirname(__FILE__)), null, OL_VERSION);
  83.                                 wp_register_script("ol_main_js", plugins_url("assets/js/main.js", dirname(__FILE__)), null, OL_VERSION);
  84.                                 $translation_array = array(
  85.                                         'plugin_path' => plugins_url(),
  86.                                         'media_library_title' => __('Featured image', 'ol-scrapes'),
  87.                                         'name' => __('Name', 'ol-scrapes'),
  88.                                         'eg_name' => __('e.g. name', 'ol-scrapes'),
  89.                                         'eg_value' => __('e.g. value', 'ol-scrapes'),
  90.                                         'eg_1' => __('e.g. 1', 'ol-scrapes'),
  91.                                         'value' => __('Value', 'ol-scrapes'),
  92.                                         'increment' => __('Increment', 'ol-scrapes'),
  93.                                         'xpath_placeholder' => __("e.g. //div[@id='octolooks']", 'ol-scrapes'),
  94.                                         'enter_valid' => __("Please enter a valid value.", 'ol-scrapes'),
  95.                                         'attribute' => __("Attribute", "ol-scrapes"),
  96.                                         'eg_href' => __("e.g. href", "ol-scrapes"),
  97.                                         'eg_scrape_value' => __("e.g. [scrape_value]", "ol-scrapes"),
  98.                                         'template' => __("Template", "ol-scrapes"),
  99.                                         'btn_value' => __("value", "ol-scrapes"),
  100.                                         'btn_calculate' => __("calculate", "ol-scrapes"),
  101.                                         'btn_date' => __("date", "ol-scrapes"),
  102.                                         'btn_custom_field' => __("custom field", "ol-scrapes"),
  103.                                         'btn_source_url' => __("source url", "ol-scrapes"),
  104.                                         'btn_product_url' => __("product url", "ol-scrapes"),
  105.                                         'btn_cart_url' => __("cart url", "ol-scrapes"),
  106.                                         'add_new_replace' => __("Add new find and replace rule", "ol-scrapes"),
  107.                                         'enable_template' => __("Enable template", "ol-scrapes"),
  108.                                         'enable_find_replace' => __("Enable find and replace rules", "ol-scrapes"),
  109.                                         'find' => __("Find", "ol-scrapes"),
  110.                                         'replace' => __("Replace", "ol-scrapes"),
  111.                                         'eg_find' => __("e.g. find", "ol-scrapes"),
  112.                                         'eg_replace' => __("e.g. replace", "ol-scrapes"),
  113.                                         'select_taxonomy' => __("Please select a taxonomy", "ol-scrapes"),
  114.                                         'source_url_not_valid' => __("Source URL is not valid.", "ol-scrapes"),
  115.                                         'post_item_not_valid' => __("Post item is not valid.", "ol-scrapes"),
  116.                                         'item_not_link' => __("Selected item is not a link", "ol-scrapes"),
  117.                                         'item_not_image' => __("Selected item is not an image", "ol-scrapes"),
  118.                                         'allow_html_tags' => __("Allow HTML tags", "ol-scrapes"),
  119.                                         'Operator' => __("Operator", "ol-scrapes"),
  120.                                         'Contains' => __("Contains", "ol-scrapes"),
  121.                                         'Does_not_contain' => __("Does not contain", "ol-scrapes"),
  122.                                         'Exists' => __("Exists", "ol-scrapes"),
  123.                                         'Not_exists' => __("Not exists", "ol-scrapes"),
  124.                                         'Equal_to' => __("Equal_to", "ol-scrapes"),
  125.                                         'Not_equal_to' => __("Not_equal_to", "ol-scrapes"),
  126.                                         'Greater_than' => __("Greater_than", "ol-scrapes"),
  127.                                         'Less_than' => __("Less than", "ol-scrapes"),
  128.                                         'Field' => __("Field", "ol-scrapes"),
  129.                                         'Title' => __("Title", "ol-scrapes"),
  130.                                         'Content' => __("Content", "ol-scrapes"),
  131.                                         'Excerpt' => __("Excerpt", "ol-scrapes"),
  132.                                         'Featured_image' => __("Featured image", "ol-scrapes"),
  133.                                         'Date' => __("Date", "ol-scrapes"),
  134.                                         'enable_dont_update' => __("Do Not update", "ol-scrapes"),
  135.                                         'Taxonomy' => __("Taxonomy", "ol-scrapes"),
  136.                                         'Please_select_a_taxonomy' => __("Please select a taxonomy", "ol-scrapes"),
  137.                                         'separator' => __("Separator", "ol-scrapes"),
  138.                                         'eg_comma' => __("e.g. ,", "ol-scrapes"),
  139.                                         'btn_affiliate' => __("affiliate", "ol-scrapes"),
  140.                                 );
  141.                                 wp_localize_script('ol_main_js', 'translate', $translation_array);
  142.                                 wp_enqueue_script('ol_main_js');
  143.                                 wp_enqueue_style("ol_main_css", plugins_url("assets/css/main.css", dirname(__FILE__)), null, OL_VERSION);                          
  144.                                 if (is_rtl()) {
  145.                                         wp_enqueue_style("ol_rtl_css", plugins_url("assets/css/rtl.css", dirname(__FILE__)), null, OL_VERSION);
  146.                                 }                              
  147.                                 wp_enqueue_media();
  148.                         }
  149.                         if (in_array($hook_suffix, array('edit.php'))) {
  150.                                 wp_enqueue_script("ol_view_js", plugins_url("assets/js/view.js", dirname(__FILE__)), null, OL_VERSION);
  151.                                 wp_enqueue_style("ol_view_css", plugins_url("assets/css/view.css", dirname(__FILE__)), null, OL_VERSION);
  152.                         }
  153.                 }
  154.                 if (in_array($hook_suffix, array("scrape_page_scrapes-support"))) {
  155.                         wp_enqueue_script("ol_fix_jquery", plugins_url("assets/js/fix_jquery.js", dirname(__FILE__)), null, OL_VERSION);
  156.                         wp_enqueue_script("ol_jquery", plugins_url("libraries/jquery-2.2.4/jquery-2.2.4.min.js", dirname(__FILE__)), null, OL_VERSION);
  157.                         wp_enqueue_script("ol_jquery_ui", plugins_url("libraries/jquery-ui-1.12.1.custom/jquery-ui.min.js", dirname(__FILE__)), null, OL_VERSION);
  158.                         wp_enqueue_script("ol_bootstrap", plugins_url("libraries/bootstrap-3.3.7-dist/js/bootstrap.min.js", dirname(__FILE__)), null, OL_VERSION);
  159.                         wp_enqueue_script("ol_angular", plugins_url("libraries/angular-1.5.8/angular.min.js", dirname(__FILE__)), null, OL_VERSION);
  160.                         wp_enqueue_script("ol_settings_js", plugins_url("assets/js/settings.js", dirname(__FILE__)), null, OL_VERSION);
  161.                         wp_enqueue_style("ol_settings_css", plugins_url("assets/css/settings.css", dirname(__FILE__)), null, OL_VERSION);
  162.                         wp_enqueue_style("ol_support_css", plugins_url("assets/css/support.css", dirname(__FILE__)), null, OL_VERSION);
  163.                         wp_enqueue_script("ol_lity_js", plugins_url("assets/js/lity.min.js", dirname(__FILE__)), null, OL_VERSION);
  164.                         wp_enqueue_style("ol_lity_css", plugins_url("assets/css/lity.min.css", dirname(__FILE__)), null, OL_VERSION);
  165.                         if(is_rtl()) {
  166.                                 wp_enqueue_style("ol_support_rtl", plugins_url("assets/css/support-rtl.css", dirname(__FILE__)), null, OL_VERSION);
  167.                         }
  168.                 }
  169.         }
  170.  
  171.         public function init_admin_fonts() {
  172.                 $path = dirname(plugin_basename(__FILE__)) . '/../libraries/ionicons-2.0.1/fonts/';
  173.                 foreach (glob(WP_PLUGIN_DIR . '/' . $path . '.*.ttc') as $font) {
  174.                         wp_enqueue_font($font);
  175.                 }
  176.         }
  177.        
  178.         public function add_post_type() {
  179.                 add_action('init', array($this, 'register_post_type'));
  180.         }
  181.        
  182.         public function register_post_type() {
  183.                 register_post_type("scrape", array(
  184.                         'labels' => array(
  185.                                 'name' => __('Scrapes', 'ol-scrapes'), 'add_new' => __('Add New', 'ol-scrapes'), 'all_items' => __('All Scrapes', 'ol-scrapes')
  186.                         ), 'public' => false, 'publicly_queriable' => false, 'show_ui' => true, 'menu_position' => 25, 'menu_icon' => '', 'supports' => array('custom-fields'), 'register_meta_box_cb' => array($this, 'register_scrape_meta_boxes'), 'has_archive' => true, 'rewrite' => false, 'capability_type' => 'post'
  187.                 ));
  188.         }
  189.        
  190.         public function add_settings_submenu() {
  191.                 add_action('admin_menu', array($this, 'add_settings_view'));
  192.         }
  193.        
  194.         public function add_settings_view() {
  195.                 add_submenu_page('edit.php?post_type=scrape', __('Scrapes Support', 'ol-scrapes'), __('Support', 'ol-scrapes'), 'manage_options', "scrapes-support", array($this, "scrapes_support_page"));
  196.         }
  197.        
  198.         public function scrapes_support_page() {
  199.                 require plugin_dir_path(__FILE__) . "../views/support-page.php";
  200.         }
  201.  
  202.         public function scrapes_settings_page() {
  203.                 require_once plugin_dir_path(__FILE__) . "../views/scrape-settings.php";
  204.         }
  205.        
  206.         public function save_post_handler() {
  207.                 add_action('save_post', array($this, "save_scrape_task"), 10, 2);
  208.         }
  209.        
  210.         public function save_scrape_task($post_id, $post_object) {
  211.                 if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
  212.                         $this->write_log("doing autosave scrape returns");
  213.                         return;
  214.                 }
  215.                
  216.                 if ($post_object->post_type == 'scrape' && !defined("WP_IMPORTING")) {
  217.                         $post_data = $_POST;
  218.                         $this->write_log("post data for scrape task");
  219.                         $this->write_log($post_data);
  220.                         if (!empty($post_data)) {
  221.                                
  222.                                 $vals = get_post_meta($post_id);
  223.                                 foreach ($vals as $key => $val) {
  224.                                         delete_post_meta($post_id, $key);
  225.                                 }                              
  226.                                
  227.                                 foreach ($post_data as $key => $value) {
  228.                                         if ($key == "scrape_custom_fields" || $key == "scrape_categoryxpath_tax") {
  229.                                                 if ($key == "scrape_custom_fields") {
  230.                                                         foreach ($value as $timestamp => $arr) {
  231.                                                                 if (!isset($arr['template_status'])) {
  232.                                                                         $value[$timestamp]['template_status'] = '';
  233.                                                                 }
  234.                                                                 if (!isset($arr['regex_status'])) {
  235.                                                                         $value[$timestamp]['regex_status'] = '';
  236.                                                                 }
  237.                                                                 if (!isset($arr['allowhtml'])) {
  238.                                                                         $value[$timestamp]['allowhtml'] = '';
  239.                                                                 }
  240.                                                                 if (!isset($arr['dont_update'])) {
  241.                                                                         $value[$timestamp]['dont_update'] = '';
  242.                                                                 }                                                      
  243.                                                         }
  244.                                                         update_post_meta($post_id, $key, $value);
  245.                                                 }
  246.                                                 foreach ($post_data as $key => $value) {
  247.                                                         if ($key == "scrape_categoryxpath_tax") {
  248.                                                                 foreach ($value as $taxtimestmp => $tax) {
  249.                                                                         if (!isset($tax['regex_status'])) {
  250.                                                                                 $value[$taxtimestmp]['regex_status'] = '';
  251.                                                                         }
  252.                                                                         if (!isset($tax['template_status'])) {
  253.                                                                                 $value[$taxtimestmp]['template_status'] = '';
  254.                                                                         }                                                                      
  255.                                                                 }
  256.                                                                 update_post_meta($post_id, $key, $value);
  257.                                                         }
  258.                                                 }
  259.                                         } else {
  260.                                                 if (strpos($key, "scrape_") !== false) {
  261.                                                         update_post_meta($post_id, $key, $value);
  262.                                                 }
  263.                                         }
  264.                                 }
  265.                                
  266.                                 $checkboxes = array(
  267.                                         'scrape_unique_title', 'scrape_unique_content', 'scrape_unique_url', 'scrape_allowhtml', 'scrape_category', 'scrape_post_unlimited', 'scrape_run_unlimited', 'scrape_download_images', 'scrape_comment', 'scrape_template_status', 'scrape_finish_repeat_enabled', 'scrape_title_template_status', 'scrape_title_regex_status', 'scrape_content_template_status', 'scrape_content_regex_status', 'scrape_excerpt_regex_status', 'scrape_excerpt_template_status', 'scrape_tags_regex_status', 'scrape_date_regex_status', 'scrape_translate_enable', 'scrape_spin_enable', 'scrape_exact_match', 'scrape_dont_update', 'scrape_change_status', 'scrape_watermark_images', 'scrape_data_src_images', 'scrape_product_variable', 'scrape_delete_all_links'
  268.                                 );
  269.                                
  270.                                 foreach ($checkboxes as $cb) {
  271.                                         if (!isset($post_data[$cb])) {
  272.                                                 update_post_meta($post_id, $cb, '');
  273.                                         }
  274.                                 }
  275.  
  276.  
  277.  
  278.                                 update_post_meta($post_id, 'scrape_workstatus', 'waiting');
  279.                                 update_post_meta($post_id, 'scrape_run_count', 0);
  280.                                 update_post_meta($post_id, 'scrape_start_time', '');
  281.                                 update_post_meta($post_id, 'scrape_end_time', '');
  282.                                 update_post_meta($post_id, 'scrape_last_scrape', '');
  283.                                 update_post_meta($post_id, 'scrape_task_id', $post_id);
  284.  
  285.                 if(DEMO) {
  286.                     update_post_meta($post_id, 'scrape_waitpage', 5);
  287.                     update_post_meta($post_id, 'scrape_post_limit', 100);
  288.                     delete_post_meta($post_id, 'scrape_post_unlimited');
  289.                 }
  290.                                
  291.                                 if (!isset($post_data['scrape_recurrence'])) {
  292.                                         update_post_meta($post_id, 'scrape_recurrence', 'scrape_1 Month');
  293.                                 }
  294.                                
  295.                                 if (!isset($post_data['scrape_stillworking'])) {
  296.                                         update_post_meta($post_id, 'scrape_stillworking', 'wait');
  297.                                 }
  298.                                
  299.                                 if ($post_object->post_status != "trash") {
  300.                                         $this->write_log("before handle");
  301.                                         $this->handle_cron_job($post_id);
  302.                                        
  303.                                         if ($post_data['scrape_cron_type'] == S_WORD) {
  304.                                                 $this->write_log("before " . S_WORD . " cron");
  305.                                                 $this->create_system_cron($post_id);
  306.                                         }
  307.                                 }
  308.                                 $this->clear_cron_tab();
  309.                                 $errors = get_transient("scrape_msg");
  310.                                 if (empty($errors) && isset($post_data['user_ID'])) {
  311.                                         $this->write_log("before edit screen redirect");
  312.                                         wp_redirect(add_query_arg('post_type', 'scrape', admin_url('/edit.php')));
  313.                                         exit;
  314.                                 }
  315.                         } else {
  316.                                 update_post_meta($post_id, 'scrape_workstatus', 'waiting');
  317.                         }
  318.                 } else {
  319.                         if ($post_object->post_type == 'scrape' && defined("WP_IMPORTING")) {
  320.                                 $this->write_log("post importing id : " . $post_id);
  321.                                 $this->write_log($post_object);
  322.                                
  323.                                 delete_post_meta($post_id, 'scrape_workstatus');
  324.                                 delete_post_meta($post_id, 'scrape_run_count');
  325.                                 delete_post_meta($post_id, 'scrape_start_time');
  326.                                 delete_post_meta($post_id, 'scrape_end_time');
  327.                                 delete_post_meta($post_id, 'scrape_task_id');
  328.                                 update_post_meta($post_id, 'scrape_workstatus', 'waiting');
  329.                                 update_post_meta($post_id, 'scrape_run_count', 0);
  330.                                 update_post_meta($post_id, 'scrape_start_time', '');
  331.                                 update_post_meta($post_id, 'scrape_end_time', '');
  332.                                 update_post_meta($post_id, 'scrape_task_id', $post_id);
  333.                         }
  334.                 }
  335.         }
  336.        
  337.         public function remove_pings() {
  338.                 add_action('publish_post', array($this, 'remove_publish_pings'), 99999, 1);
  339.                 add_action('save_post', array($this, 'remove_publish_pings'), 99999, 1);
  340.                 add_action('updated_post_meta', array($this, 'remove_publish_pings_after_meta'), 9999, 2);
  341.                 add_action('added_post_meta', array($this, 'remove_publish_pings_after_meta'), 9999, 2);
  342.                 if(DEMO) {
  343.                         add_action('publish_scrape', 'add_tried_link');
  344.                         function add_tried_link() {
  345.                                 global $wpdb;
  346.                                 $user = wp_get_current_user();
  347.                                 $wpdb->insert("tried_links",array("user_email" => $user->user_email, "site_url" => $_POST['scrape_url'], "create_date" => date("Y-m-d H:i:s")));
  348.                         }
  349.                 }
  350.         }
  351.        
  352.         public function remove_publish_pings($post_id) {
  353.                 $is_automatic_post = get_post_meta($post_id, '_scrape_task_id', true);
  354.                 if (!empty($is_automatic_post)) {
  355.                         delete_post_meta($post_id, '_pingme');
  356.                         delete_post_meta($post_id, '_encloseme');
  357.                 }
  358.         }
  359.        
  360.         public function remove_publish_pings_after_meta($meta_id, $object_id) {
  361.                 $is_automatic_post = get_post_meta($object_id, '_scrape_task_id', true);
  362.                 if (!empty($is_automatic_post)) {
  363.                         delete_post_meta($object_id, '_pingme');
  364.                         delete_post_meta($object_id, '_encloseme');
  365.                 }
  366.         }
  367.        
  368.        
  369.         public function register_scrape_meta_boxes() {
  370.                 if (Scrapes_Plugin_SDK::is_activated() !== true) {
  371.                         wp_redirect(add_query_arg(array("page" => "scrapes-settings", "post_type" => "scrape"), admin_url("edit.php")));
  372.                         exit;
  373.                 }
  374.                 add_action("edit_form_after_title", array($this, "show_scrape_options_html"));       
  375.         }
  376.        
  377.         public function show_scrape_options_html() {
  378.                 global $post, $wpdb;
  379.                 $post_object = $post;
  380.                
  381.                 $post_types = array_merge(array('post'), get_post_types(array('_builtin' => false)));
  382.                
  383.                 $post_types_metas = $wpdb->get_results("SELECT 
  384.                                                                                                         p.post_type, pm.meta_key, pm.meta_value
  385.                                                                                                 FROM
  386.                                                                                                         $wpdb->posts p
  387.                                                                                                         LEFT JOIN
  388.                                                                                                         $wpdb->postmeta pm ON p.id = pm.post_id
  389.                                                                                                 WHERE
  390.                                                                                                         p.post_type IN('" . implode("','", $post_types) . "') 
  391.                                                                                                         AND pm.meta_key IS NOT NULL 
  392.                                                                                                         AND pm.meta_key NOT LIKE '_oembed%'
  393.                                                                                                         AND pm.meta_key NOT LIKE '_nxs_snap%'
  394.                                                                                                         AND p.post_status = 'publish'
  395.                                                                                                 GROUP BY p.post_type , pm.meta_key
  396.                                                                                                 ORDER BY p.post_type, pm.meta_key");
  397.                
  398.                 $auto_complete = array();
  399.                 foreach ($post_types_metas as $row) {
  400.                         $auto_complete[$row->post_type][] = $row->meta_key;
  401.                 }
  402.                 $google_languages = array(
  403.                         __('Afrikaans') => 'af', __('Albanian','ol-scrapes') => 'sq', __('Amharic','ol-scrapes') => 'am', __('Arabic','ol-scrapes') => 'ar', __('Armenian','ol-scrapes') => 'hy', __('Azeerbaijani','ol-scrapes') => 'az', __('Basque','ol-scrapes') => 'eu', __('Belarusian','ol-scrapes') => 'be', __('Bengali','ol-scrapes') => 'bn', __('Bosnian','ol-scrapes') => 'bs', __('Bulgarian','ol-scrapes') => 'bg', __('Catalan','ol-scrapes') => 'ca', __('Cebuano','ol-scrapes') => 'ceb', __('Chichewa','ol-scrapes') => 'ny', __('Chinese (Simplified)','ol-scrapes') => 'zh-CN', __('Chinese (Traditional)','ol-scrapes') => 'zh-TW', __('Corsican','ol-scrapes') => 'co', __('Croatian','ol-scrapes') => 'hr', __('Czech','ol-scrapes') => 'cs', __('Danish','ol-scrapes') => 'da', __('Dutch','ol-scrapes') => 'nl', __('English','ol-scrapes') => 'en', __('Esperanto','ol-scrapes') => 'eo', __('Estonian','ol-scrapes') => 'et', __('Filipino','ol-scrapes') => 'tl', __('Finnish','ol-scrapes') => 'fi', __('French','ol-scrapes') => 'fr', __('Frisian','ol-scrapes') => 'fy', __('Galician','ol-scrapes') => 'gl', __('Georgian','ol-scrapes') => 'ka', __('German','ol-scrapes') => 'de', __('Greek','ol-scrapes') => 'el', __('Gujarati','ol-scrapes') => 'gu', __('Haitian Creole','ol-scrapes') => 'ht', __('Hausa','ol-scrapes') => 'ha', __('Hawaiian','ol-scrapes') => 'haw', __('Hebrew','ol-scrapes') => 'iw', __('Hindi','ol-scrapes') => 'hi', __('Hmong','ol-scrapes') => 'hmn', __('Hungarian','ol-scrapes') => 'hu', __('Icelandic','ol-scrapes') => 'is', __('Igbo','ol-scrapes') => 'ig', __('Indonesian','ol-scrapes') => 'id', __('Irish','ol-scrapes') => 'ga', __('Italian','ol-scrapes') => 'it', __('Japanese','ol-scrapes') => 'ja', __('Javanese','ol-scrapes') => 'jw', __('Kannada','ol-scrapes') => 'kn', __('Kazakh','ol-scrapes') => 'kk', __('Khmer','ol-scrapes') => 'km', __('Korean','ol-scrapes') => 'ko', __('Kurdish','ol-scrapes') => 'ku', __('Kyrgyz','ol-scrapes') => 'ky', __('Lao','ol-scrapes') => 'lo', __('Latin','ol-scrapes') => 'la', __('Latvian','ol-scrapes') => 'lv', __('Lithuanian','ol-scrapes') => 'lt', __('Luxembourgish','ol-scrapes') => 'lb', __('Macedonian','ol-scrapes') => 'mk', __('Malagasy','ol-scrapes') => 'mg', __('Malay','ol-scrapes') => 'ms', __('Malayalam','ol-scrapes') => 'ml', __('Maltese','ol-scrapes') => 'mt', __('Maori','ol-scrapes') => 'mi', __('Marathi','ol-scrapes') => 'mr', __('Mongolian','ol-scrapes') => 'mn', __('Burmese','ol-scrapes') => 'my', __('Nepali','ol-scrapes') => 'ne', __('Norwegian','ol-scrapes') => 'no', __('Pashto','ol-scrapes') => 'ps', __('Persian','ol-scrapes') => 'fa', __('Polish','ol-scrapes') => 'pl', __('Portuguese','ol-scrapes') => 'pt', __('Punjabi','ol-scrapes') => 'ma', __('Romanian','ol-scrapes') => 'ro', __('Russian','ol-scrapes') => 'ru', __('Samoan','ol-scrapes') => 'sm', __('Scots Gaelic','ol-scrapes') => 'gd', __('Serbian','ol-scrapes') => 'sr', __('Sesotho','ol-scrapes') => 'st', __('Shona','ol-scrapes') => 'sn', __('Sindhi','ol-scrapes') => 'sd', __('Sinhala','ol-scrapes') => 'si', __('Slovak','ol-scrapes') => 'sk', __('Slovenian','ol-scrapes') => 'sl', __('Somali','ol-scrapes') => 'so', __('Somali','ol-scrapes') => 'so', __('Spanish','ol-scrapes') => 'es', __('Sundanese','ol-scrapes') => 'su', __('Swahili','ol-scrapes') => 'sw', __('Swedish','ol-scrapes') => 'sv', __('Tajik','ol-scrapes') => 'tg', __('Tamil','ol-scrapes') => 'ta', __('Telugu','ol-scrapes') => 'te', __('Thai','ol-scrapes') => 'th', __('Turkish','ol-scrapes') => 'tr', __('Ukrainian','ol-scrapes') => 'uk', __('Urdu','ol-scrapes') => 'ur', __('Uzbek','ol-scrapes') => 'uz', __('Vietnamese','ol-scrapes') => 'vi', __('Welsh','ol-scrapes') => 'cy', __('Xhosa','ol-scrapes') => 'xh', __('Yiddish','ol-scrapes') => 'yi', __('Yoruba','ol-scrapes') => 'yo', __('Zulu','ol-scrapes') => 'zu'
  404.                 );
  405.                 require plugin_dir_path(__FILE__) . "../views/scrape-meta-box.php";
  406.         }
  407.        
  408.         public function trash_post_handler() {
  409.                 add_action("wp_trash_post", array($this, "trash_scrape_task"));
  410.         }
  411.        
  412.         public function trash_scrape_task($post_id) {
  413.                 $post = get_post($post_id);
  414.                 if ($post->post_type == "scrape") {
  415.                        
  416.                         $timestamp = wp_next_scheduled("scrape_event", array($post_id));
  417.                        
  418.                         wp_clear_scheduled_hook("scrape_event", array($post_id));
  419.                         wp_unschedule_event($timestamp, "scrape_event", array($post_id));
  420.                        
  421.                         update_post_meta($post_id, "scrape_workstatus", "waiting");
  422.                         $this->clear_cron_tab();
  423.                         $this->write_log($post_id . " trash button clicked.");
  424.                 }
  425.         }
  426.        
  427.         public function clear_cron_tab() {
  428.                 if ($this->check_exec_works()) {
  429.                         $all_tasks = get_posts(array(
  430.                                 'numberposts' => -1, 'post_type' => 'scrape', 'post_status' => 'publish'
  431.                         ));
  432.                        
  433.                         $all_wp_cron = true;
  434.                        
  435.                         foreach ($all_tasks as $task) {
  436.                                 $cron_type = get_post_meta($task->ID, 'scrape_cron_type', true);
  437.                                 if ($cron_type == S_WORD) {
  438.                                         $all_wp_cron = false;
  439.                                 }
  440.                         }
  441.                        
  442.                         if ($all_wp_cron) {
  443.                                 $e_word = E_WORD;
  444.                                 $e_word(C_WORD . ' -l', $output, $return);
  445.                                 $command_string = '* * * * * wget -q -O - ' . site_url() . ' >/dev/null 2>&1';
  446.                                 if (!$return) {
  447.                                         foreach ($output as $key => $line) {
  448.                                                 if (strpos($line, $command_string) !== false) {
  449.                                                         unset($output[$key]);
  450.                                                 }
  451.                                         }
  452.                                         $output = implode(PHP_EOL, $output);
  453.                                         $cron_file = OL_PLUGIN_PATH . DIRECTORY_SEPARATOR . 'logs' . DIRECTORY_SEPARATOR . "scrape_cron_file.txt";
  454.                                         file_put_contents($cron_file, $output);
  455.                                         $e_word(C_WORD . " " . $cron_file);
  456.                                 }
  457.                         }
  458.                 }
  459.         }
  460.        
  461.        
  462.         public function add_ajax_handler() {
  463.                 add_action("wp_ajax_" . "get_url", array($this, "ajax_url_load"));
  464.                 add_action("wp_ajax_" . "get_post_cats", array($this, "ajax_post_cats"));
  465.                 add_action("wp_ajax_" . "get_post_tax", array($this, "ajax_post_tax"));
  466.                 add_action("wp_ajax_" . "get_tasks", array($this, "ajax_tasks"));
  467.         }
  468.        
  469.         public function ajax_tasks() {
  470.                 $all_tasks = get_posts(array(
  471.                         'numberposts' => -1, 'post_type' => 'scrape', 'post_status' => 'publish'
  472.                 ));
  473.                
  474.                 $array = array();
  475.                 foreach ($all_tasks as $task) {
  476.                         $post_ID = $task->ID;
  477.                        
  478.                         clean_post_cache($post_ID);
  479.                         $post_status = get_post_status($post_ID);
  480.                         $scrape_status = get_post_meta($post_ID, 'scrape_workstatus', true);
  481.                         $run_limit = get_post_meta($post_ID, 'scrape_run_limit', true);
  482.                         $run_count = get_post_meta($post_ID, 'scrape_run_count', true);
  483.                         $run_unlimited = get_post_meta($post_ID, 'scrape_run_unlimited', true);
  484.                         $status = '';
  485.                         $css_class = '';
  486.                        
  487.                         if ($post_status == 'trash') {
  488.                                 $status = __("Deactivated", "ol-scrapes");
  489.                                 $css_class = "deactivated";
  490.                         } else {
  491.                                 if ($run_count == 0 && $scrape_status == 'waiting') {
  492.                                         $status = __("Preparing", "ol-scrapes");
  493.                                         $css_class = "preparing";
  494.                                 } else {
  495.                                         if ((!empty($run_unlimited) || $run_count < $run_limit) && $scrape_status == 'waiting') {
  496.                                                 $status = __("Waiting next run", "ol-scrapes");
  497.                                                 $css_class = "wait_next";
  498.                                         } else {
  499.                                                 if (((!empty($run_limit) && $run_count < $run_limit) || (!empty($run_unlimited))) && $scrape_status == 'running') {
  500.                                                         $status = __("Running", "ol-scrapes");
  501.                                                         $css_class = "running";
  502.                                                 } else {
  503.                                                         if (empty($run_unlimited) && $run_count == $run_limit && $scrape_status == 'waiting') {
  504.                                                                 $status = __("Complete", "ol-scrapes");
  505.                                                                 $css_class = "complete";
  506.                                                         }
  507.                                                 }
  508.                                         }
  509.                                 }
  510.                         }
  511.                        
  512.                         $last_run = get_post_meta($post_ID, 'scrape_start_time', true) != "" ? get_post_meta($post_ID, 'scrape_start_time', true) : __("None", "ol-scrapes");
  513.                         $last_complete = get_post_meta($post_ID, 'scrape_end_time', true) != "" ? get_post_meta($post_ID, 'scrape_end_time', true) : __("None", "ol-scrapes");
  514.                         $last_scrape = get_post_meta($post_ID, 'scrape_last_scrape', true) != "" ? get_post_meta($post_ID, 'scrape_last_scrape', true) : __("None", "ol-scrapes");
  515.                         $run_count_progress = $run_count;
  516.                         if ($run_unlimited == "") {
  517.                                 $run_count_progress .= " / " . $run_limit;
  518.                         }
  519.                         $offset = get_option('gmt_offset') * 3600;
  520.                         $date = date("Y-m-d H:i:s", wp_next_scheduled("scrape_event", array($post_ID)) + $offset);
  521.                         if (strpos($date, "1970-01-01") !== false) {
  522.                                 $date = __("No Schedule", "ol-scrapes");
  523.                         }
  524.                         $array[] = array(
  525.                                 $task->ID, $css_class, $status, $last_run, $last_complete, $date, $run_count_progress, $last_scrape
  526.                         );
  527.                 }
  528.                
  529.                 echo json_encode($array);
  530.                 wp_die();
  531.         }
  532.        
  533.         public function ajax_post_cats() {
  534.                 if (isset($_POST['post_type'])) {
  535.                         $post_type = $_POST['post_type'];
  536.                         $object_taxonomies = get_object_taxonomies($post_type);
  537.                         if (!empty($object_taxonomies)) {
  538.                                 $cats = get_categories(array(
  539.                                         'hide_empty' => 0, 'taxonomy' => array_diff($object_taxonomies, array('post_tag')), 'type' => $post_type
  540.                                 ));
  541.                         } else {
  542.                                 $cats = array();
  543.                         }
  544.                         $scrape_category = get_post_meta($_POST['post_id'], 'scrape_category', true);
  545.                         foreach ($cats as $c) {
  546.                                 echo '<div class="checkbox"><label><input type="checkbox" name="scrape_category[]" value="' . $c->cat_ID . '"' . (!empty($scrape_category) && in_array($c->cat_ID, $scrape_category) ? " checked" : "") . '> ' . $c->name . '<small> (' . get_taxonomy($c->taxonomy)->labels->name . ')</small></label></div>';
  547.                         }
  548.                         wp_die();
  549.                 }
  550.         }
  551.        
  552.         public function ajax_post_tax() {
  553.                 if (isset($_POST['post_type'])) {
  554.                         $post_type = $_POST['post_type'];
  555.                         $object_taxonomies = get_object_taxonomies($post_type, "objects");
  556.                         unset($object_taxonomies['post_tag']);
  557.                         $scrape_categoryxpath_tax = get_post_meta($_POST['post_id'], 'scrape_categoryxpath_tax', true);
  558.                         foreach ($object_taxonomies as $tax) {
  559.                                 echo "<option value='$tax->name'" . ($tax->name == $scrape_categoryxpath_tax " selected" : "") . " >" . $tax->labels->name . "</option>";
  560.                         }
  561.                         wp_die();
  562.                 }
  563.         }
  564.        
  565.         public function ajax_url_load() {
  566.                 if (isset($_GET['address'])) {
  567.                        
  568.                         update_site_option('scrape_user_agent', $_SERVER['HTTP_USER_AGENT']);
  569.                         $args = $this->return_html_args();
  570.                        
  571.                        
  572.                         if (isset($_GET['scrape_feed'])) {
  573.                                 $response = wp_remote_get($_GET['address'], $args);
  574.                                 $body = wp_remote_retrieve_body($response);
  575.                                 $charset = $this->detect_feed_encoding_and_replace(wp_remote_retrieve_header($response, "Content-Type"), $body, true);
  576.                                 $body = iconv($charset, "UTF-8//IGNORE", $body);
  577.                                 if (function_exists("tidy_repair_string")) {
  578.                                         $body = tidy_repair_string($body, array(
  579.                                                 'output-xml' => true, 'input-xml' => true
  580.                                         ), 'utf8');
  581.                                 }
  582.                                 if ($body === false) {
  583.                                         wp_die("utf 8 convert error");
  584.                                 }
  585.                                 $xml = simplexml_load_string($body);
  586.                                 if ($xml === false) {
  587.                                         $this->write_log(libxml_get_errors(), true);
  588.                                         libxml_clear_errors();
  589.                                 }
  590.                                 $feed_type = $xml->getName();
  591.                                 $this->write_log("feed type is : " . $feed_type);
  592.                                 if ($feed_type == 'rss') {
  593.                                         $items = $xml->channel->item;
  594.                                         $_GET['address'] = strval($items[0]->link);
  595.                                 } else {
  596.                                         if ($feed_type == 'feed') {
  597.                                                 $items = $xml->entry;
  598.                                                 $alternate_found = false;
  599.                                                 foreach ($items[0]->link as $link) {
  600.                                                         if ($link->attributes()->rel == "alternate") {
  601.                                                                 $_GET['address'] = strval($link->attributes()->href);
  602.                                                                 $alternate_found = true;
  603.                                                         }
  604.                                                 }
  605.                                                 if (!$alternate_found) {
  606.                                                         $_GET['address'] = strval($items[0]->link->attributes()->href);
  607.                                                 }
  608.                                         } else {
  609.                                                 if ($feed_type == 'RDF') {
  610.                                                         $items = $xml->item;
  611.                                                         $_GET['address'] = strval($items[0]->link);
  612.                                                 }
  613.                                         }
  614.                                 }
  615.                                 $_GET['address'] = trim($_GET['address']);
  616.                                 $this->write_log("first item in rss: " . $_GET['address']);
  617.                         }
  618.                        
  619.                         $request = wp_remote_get($_GET['address'], $args);
  620.                         if (is_wp_error($request)) {
  621.                                 wp_die($request->get_error_message());
  622.                         }
  623.                         $body = wp_remote_retrieve_body($request);
  624.                         $body = trim($body);
  625.                         if (substr($body, 0, 3) == pack("CCC", 0xef, 0xbb, 0xbf)) {
  626.                                 $body = substr($body, 3);
  627.                         }
  628.                         $dom = new DOMDocument();
  629.                         $dom->preserveWhiteSpace = false;
  630.                        
  631.                         $charset = $this->detect_html_encoding_and_replace(wp_remote_retrieve_header($request, "Content-Type"), $body, true);
  632.                         $body = iconv($charset, "UTF-8//IGNORE", $body);
  633.                        
  634.                         if ($body === false) {
  635.                                 wp_die("utf-8 convert error");
  636.                         }
  637.                        
  638.                         $body = preg_replace(array(
  639.                                 "'<\s*script[^>]*[^/]>(.*?)<\s*/\s*script\s*>'isu", "'<\s*script\s*>(.*?)<\s*/\s*script\s*>'isu", "'<\s*noscript[^>]*[^/]>(.*?)<\s*/\s*noscript\s*>'isu", "'<\s*noscript\s*>(.*?)<\s*/\s*noscript\s*>'isu"
  640.                         ), array(
  641.                                 "", "", "", ""
  642.                         ), $body);
  643.                        
  644.                         $body = mb_convert_encoding($body, 'HTML-ENTITIES', 'UTF-8');
  645.                         @$dom->loadHTML('<?xml encoding="utf-8" ?>' . $body);
  646.                         $url = parse_url($_GET['address']);
  647.                         $url = $url['scheme'] . "://" . $url['host'];
  648.                         $base = $dom->getElementsByTagName('base')->item(0);
  649.                         $html_base_url = null;
  650.                         if (!is_null($base)) {
  651.                                 $html_base_url = $this->create_absolute_url($base->getAttribute('href'), $url, null);
  652.                         }
  653.                        
  654.                        
  655.                         $imgs = $dom->getElementsByTagName('img');
  656.                         if ($imgs->length) {
  657.                                 foreach ($imgs as $item) {
  658.                                         if ($item->getAttribute('src') != '') {
  659.                                                 $item->setAttribute('src', $this->create_absolute_url(trim($item->getAttribute('src')), $_GET['address'], $html_base_url));
  660.                                         }
  661.                                 }
  662.                         }
  663.                        
  664.                         $as = $dom->getElementsByTagName('a');
  665.                         if ($as->length) {
  666.                                 foreach ($as as $item) {
  667.                                         if ($item->getAttribute('href') != '') {
  668.                                                 $item->setAttribute('href', $this->create_absolute_url(trim($item->getAttribute('href')), $_GET['address'], $html_base_url));
  669.                                         }
  670.                                 }
  671.                         }
  672.                        
  673.                         $links = $dom->getElementsByTagName('link');
  674.                         if ($links->length) {
  675.                                 foreach ($links as $item) {
  676.                                         if ($item->getAttribute('href') != '') {
  677.                                                 $item->setAttribute('href', $this->create_absolute_url(trim($item->getAttribute('href')), $_GET['address'], $html_base_url));
  678.                                         }
  679.                                 }
  680.                         }
  681.                        
  682.                         $all_elements = $dom->getElementsByTagName('*');
  683.                         foreach ($all_elements as $item) {
  684.                                 if ($item->hasAttributes()) {
  685.                                         foreach ($item->attributes as $name => $attr_node) {
  686.                                                 if (preg_match("/^on\w+$/", $name)) {
  687.                                                         $item->removeAttribute($name);
  688.                                                 }
  689.                                         }
  690.                                 }
  691.                         }
  692.                        
  693.                         $html = $dom->saveHTML();
  694.                         echo $html;
  695.                         wp_die();
  696.                 }
  697.         }
  698.        
  699.         public function create_cron_schedules() {
  700.                 add_filter('cron_schedules', array($this, 'add_custom_schedules'), 999, 1);
  701.                 add_action('scrape_event', array($this, 'execute_post_task'));
  702.         }
  703.        
  704.         public function add_custom_schedules($schedules) {
  705.                 $schedules['scrape_' . "5 Minutes"] = array(
  706.                         'interval' => 5 * 60, 'display' => __("Every 5 minutes", "ol-scrapes")
  707.                 );
  708.                 $schedules['scrape_' . "10 Minutes"] = array(
  709.                         'interval' => 10 * 60, 'display' => __("Every 10 minutes", "ol-scrapes")
  710.                 );
  711.                 $schedules['scrape_' . "15 Minutes"] = array(
  712.                         'interval' => 15 * 60, 'display' => __("Every 15 minutes", "ol-scrapes")
  713.                 );
  714.                 $schedules['scrape_' . "30 Minutes"] = array(
  715.                         'interval' => 30 * 60, 'display' => __("Every 30 minutes", "ol-scrapes")
  716.                 );
  717.                 $schedules['scrape_' . "45 Minutes"] = array(
  718.                         'interval' => 45 * 60, 'display' => __("Every 45 minutes", "ol-scrapes")
  719.                 );
  720.                 $schedules['scrape_' . "1 Hour"] = array(
  721.                         'interval' => 60 * 60, 'display' => __("Every hour", "ol-scrapes")
  722.                 );
  723.                 $schedules['scrape_' . "2 Hours"] = array(
  724.                         'interval' => 2 * 60 * 60, 'display' => __("Every 2 hours", "ol-scrapes")
  725.                 );
  726.                 $schedules['scrape_' . "4 Hours"] = array(
  727.                         'interval' => 4 * 60 * 60, 'display' => __("Every 4 hours", "ol-scrapes")
  728.                 );
  729.                 $schedules['scrape_' . "6 Hours"] = array(
  730.                         'interval' => 6 * 60 * 60, 'display' => __("Every 6 hours", "ol-scrapes")
  731.                 );
  732.                 $schedules['scrape_' . "8 Hours"] = array(
  733.                         'interval' => 8 * 60 * 60, 'display' => __("Every 8 hours", "ol-scrapes")
  734.                 );
  735.                 $schedules['scrape_' . "12 Hours"] = array(
  736.                         'interval' => 12 * 60 * 60, 'display' => __("Every 12 hours", "ol-scrapes")
  737.                 );
  738.                 $schedules['scrape_' . "1 Day"] = array(
  739.                         'interval' => 24 * 60 * 60, 'display' => __("Every day", "ol-scrapes")
  740.                 );
  741.                 $schedules['scrape_' . "2 Days"] = array(
  742.                         'interval' => 2 * 24 * 60 * 60, 'display' => __("Every 2 days", "ol-scrapes")
  743.                 );
  744.                 $schedules['scrape_' . "3 Days"] = array(
  745.                         'interval' => 3 * 24 * 60 * 60, 'display' => __("Every 3 days", "ol-scrapes")
  746.                 );
  747.                 $schedules['scrape_' . "1 Week"] = array(
  748.                         'interval' => 7 * 24 * 60 * 60, 'display' => __("Every week", "ol-scrapes")
  749.                 );
  750.                 $schedules['scrape_' . "2 Weeks"] = array(
  751.                         'interval' => 2 * 7 * 24 * 60 * 60, 'display' => __("Every 2 weeks", "ol-scrapes")
  752.                 );
  753.                 $schedules['scrape_' . "1 Month"] = array(
  754.                         'interval' => 30 * 24 * 60 * 60, 'display' => __("Every month", "ol-scrapes")
  755.                 );
  756.                
  757.                 return $schedules;
  758.         }
  759.        
  760.         public static function handle_cron_job($post_id) {
  761.                 $cron_recurrence = get_post_meta($post_id, 'scrape_recurrence', true);
  762.                 $timestamp = wp_next_scheduled('scrape_event', array($post_id));
  763.                 if ($timestamp) {
  764.                         //wp_unschedule_event($timestamp, 'scrape_event', array($post_id));
  765.                         wp_clear_scheduled_hook('scrape_event', array($post_id));
  766.                 }
  767.  
  768.         $first_run = get_post_meta($post_id, 'scrape_first_run_time', true);
  769.         $first_run = explode('hour_', $first_run);
  770.  
  771.                 $schedule_res = wp_schedule_event(time() + ($first_run[1] * 3600) + 10, $cron_recurrence, "scrape_event", array($post_id));
  772.                 if ($schedule_res === false) {
  773.                         self::write_log("$post_id task can not be added to wordpress schedule. Please save post again later.", true);
  774.                 }
  775.         }
  776.        
  777.         public function process_task_queue() {
  778.                 $this->write_log('process task queue called');
  779.                
  780.                
  781.                 if (function_exists('set_time_limit')) {
  782.                         $success = @set_time_limit(0);
  783.                         if (!$success) {
  784.                                 if (function_exists('ini_set')) {
  785.                                         $success = @ini_set('max_execution_time', 0);
  786.                                         if (!$success) {
  787.                                                 $this->write_log("Preventing timeout can not be succeeded", true);
  788.                                         }
  789.                                 } else {
  790.                                         $this->write_log('ini_set does not exist.', true);
  791.                                 }
  792.                         }
  793.                 } else {
  794.                         $this->write_log('set_time_limit does not exist.', true);
  795.                 }
  796.                
  797.                 session_write_close();
  798.                
  799.                 if (isset($_REQUEST['post_id']) && get_post_meta($_REQUEST['post_id'], 'scrape_nonce', true) === $_REQUEST['nonce']) {
  800.                         $this->write_log("process_task_queue starts");
  801.                         $this->write_log("max_execution_time: " . ini_get('max_execution_time'));
  802.                        
  803.                         $post_id = $_REQUEST['post_id'];
  804.                         self::$task_id = $post_id;
  805.  
  806. //                      if(get_transient('lock_' . $post_id)) {
  807. //                          $this->write_log('another lock is set', true);
  808. //                          wp_die();
  809. //            }
  810. //
  811. //            set_transient('lock_' . $post_id, true);
  812.                        
  813.                         $_POST = $_REQUEST['variables'];
  814.                         clean_post_cache($post_id);
  815.                         $process_queue = get_post_meta($post_id, 'scrape_queue', true);
  816.                        
  817.                         $meta_vals = $process_queue['meta_vals'];
  818.                         $first_item = array_shift($process_queue['items']);
  819.                        
  820.                         if ($this->check_terminate($process_queue['start_time'], $process_queue['modify_time'], $post_id)) {
  821.                                
  822.                                 if (empty($meta_vals['scrape_run_unlimited'][0]) && get_post_meta($post_id, 'scrape_run_count', true) >= get_post_meta($post_id, 'scrape_run_limit', true)) {
  823.                                         $timestamp = wp_next_scheduled("scrape_event", array($post_id));
  824.                                         wp_unschedule_event($timestamp, "scrape_event", array($post_id));
  825.                                         wp_clear_scheduled_hook("scrape_event", array($post_id));
  826.                                 }
  827.                                
  828.                                 $this->write_log("$post_id id task ended");
  829.                                 return;
  830.                         }
  831.                        
  832.                         $this->write_log("repeat count:" . $process_queue['repeat_count']);
  833.                         $this->single_scrape($first_item['url'], $process_queue['meta_vals'], $process_queue['repeat_count'], $first_item['rss_item']);
  834.                         $process_queue['number_of_posts'] += 1;
  835.                         $this->write_log("number of posts: " . $process_queue['number_of_posts']);
  836.                        
  837.                         $end_of_posts = false;
  838.                         $post_limit_reached = false;
  839.                         $repeat_limit_reached = false;
  840.                        
  841.                         if (count($process_queue['items']) == 0 && !empty($process_queue['next_page'])) {
  842.                                 $args = $this->return_html_args($meta_vals);
  843.                                 $response = wp_remote_get($process_queue['next_page'], $args);
  844.                                 update_post_meta($post_id, 'scrape_last_url', $process_queue['next_page']);
  845.                                
  846.                                 if (!isset($response->errors)) {
  847.                                        
  848.                                         $process_queue['page_no'] += 1;
  849.                                        
  850.                                         $body = wp_remote_retrieve_body($response);
  851.                                         $body = trim($body);
  852.                                        
  853.                                         if (substr($body, 0, 3) == pack("CCC", 0xef, 0xbb, 0xbf)) {
  854.                                                 $body = substr($body, 3);
  855.                                         }
  856.                                        
  857.                                         $charset = $this->detect_html_encoding_and_replace(wp_remote_retrieve_header($response, "Content-Type"), $body);
  858.                                         $body_iconv = iconv($charset, "UTF-8//IGNORE", $body);
  859.                                        
  860.                                         $body_preg = '<?xml encoding="utf-8" ?>' . preg_replace(array(
  861.                                                         "/<!--.*?-->/isu", '/(<table([^>]+)?>([^<>]+)?)(?!<tbody([^>]+)?>)/isu', '/(<(?!(\/tbody))([^>]+)?>)(<\/table([^>]+)?>)/isu', "'<\s*script[^>]*[^/]>(.*?)<\s*/\s*script\s*>'isu", "'<\s*script\s*>(.*?)<\s*/\s*script\s*>'isu", "'<\s*noscript[^>]*[^/]>(.*?)<\s*/\s*noscript\s*>'isu", "'<\s*noscript\s*>(.*?)<\s*/\s*noscript\s*>'isu",
  862.                                                
  863.                                                 ), array(
  864.                                                         "", '$1<tbody>', '$1</tbody>$4', "", "", "", ""
  865.                                                 ), $body_iconv);
  866.                                        
  867.                                         $doc = new DOMDocument;
  868.                                         $doc->preserveWhiteSpace = false;
  869.                                         $body_preg = mb_convert_encoding($body_preg, 'HTML-ENTITIES', 'UTF-8');
  870.                                         @$doc->loadHTML($body_preg);
  871.                                        
  872.                                         $url = parse_url($first_item['url']);
  873.                                         $url = $url['scheme'] . "://" . $url['host'];
  874.                                         $base = $doc->getElementsByTagName('base')->item(0);
  875.                                         $html_base_url = null;
  876.                                         if (!is_null($base)) {
  877.                                                 $html_base_url = $this->create_absolute_url($base->getAttribute('href'), $url, null);
  878.                                         }
  879.                                        
  880.                                         $xpath = new DOMXPath($doc);
  881.                                        
  882.                                         $next_buttons = (!empty($meta_vals['scrape_nextpage'][0]) ? $xpath->query($meta_vals['scrape_nextpage'][0]) : new DOMNodeList);
  883.                                        
  884.                                         $next_button = false;
  885.                                         $is_facebook_page = false;
  886.                                        
  887.                                         if (parse_url($meta_vals['scrape_url'][0], PHP_URL_HOST) == 'mbasic.facebook.com') {
  888.                                                 $is_facebook_page = true;
  889.                                         }
  890.                                        
  891.                                         $ref_a_element = $xpath->query($meta_vals['scrape_listitem'][0])->item(0);
  892.                                         if (is_null($ref_a_element)) {
  893.                                                 $this->write_log("Reference a element not found URL:" . $meta_vals['scrape_url'][0] . " XPath: " . $meta_vals['scrape_listitem'][0]);
  894.                         update_post_meta($post_id, 'scrape_workstatus', 'waiting');
  895.                         update_post_meta($post_id, "scrape_end_time", current_time('mysql'));
  896.                         delete_post_meta($post_id, 'scrape_last_url');
  897.  
  898.                         if (empty($meta_vals['scrape_run_unlimited'][0]) && get_post_meta($post_id, 'scrape_run_count', true) >= get_post_meta($post_id, 'scrape_run_limit', true)) {
  899.                             $timestamp = wp_next_scheduled("scrape_event", array($post_id));
  900.                             wp_unschedule_event($timestamp, "scrape_event", array($post_id));
  901.                             wp_clear_scheduled_hook("scrape_event", array($post_id));
  902.                             $this->write_log("run count reached, deleting task from schedules.");
  903.                         }
  904.                         $this->write_log("$post_id task ended");
  905.                                                 return;
  906.                                         }
  907.                                         $ref_node_path = $ref_a_element->getNodePath();
  908.                                         $ref_node_no_digits = preg_replace("/\[\d+\]/", "", $ref_node_path);
  909.                                         $ref_a_children = array();
  910.                                         foreach ($ref_a_element->childNodes as $node) {
  911.                                                 $ref_a_children[] = $node->nodeName;
  912.                                         }
  913.                                        
  914.                                         $this->write_log("scraping page #" . $process_queue['page_no']);
  915.                                        
  916.                                         $all_links = $xpath->query("//a");
  917.                                         if ($is_facebook_page) {
  918.                                                 $all_links = $xpath->query("//a[text()='" . trim($ref_a_element->textContent) . "']");
  919.                                         } else {
  920.                                                 if (!empty($meta_vals['scrape_exact_match'][0])) {
  921.                                                         $all_links = $xpath->query($meta_vals['scrape_listitem'][0]);
  922.                                                 }
  923.                                         }
  924.                                        
  925.                                         $single_links = array();
  926.                                         if (empty($meta_vals['scrape_exact_match'][0])) {
  927.                                                 $this->write_log("serial fuzzy match links");
  928.                                                 foreach ($all_links as $a_elem) {
  929.                                                        
  930.                                                         $parent_path = $a_elem->getNodePath();
  931.                                                         $parent_path_no_digits = preg_replace("/\[\d+\]/", "", $parent_path);
  932.                                                         if ($parent_path_no_digits == $ref_node_no_digits) {
  933.                                                                 $children_node_names = array();
  934.                                                                 foreach ($a_elem->childNodes as $node) {
  935.                                                                         $children_node_names[] = $node->nodeName;
  936.                                                                 }
  937.                                                                 if ($ref_a_children === $children_node_names) {
  938.                                                                         $single_links[] = $a_elem->getAttribute('href');
  939.                                                                 }
  940.                                                         }
  941.                                                 }
  942.                                         } else {
  943.                                                 $this->write_log("serial exact match links");
  944.                                                 foreach ($all_links as $a_elem) {
  945.                                                         $single_links[] = $a_elem->getAttribute('href');
  946.                                                 }
  947.                                         }
  948.                                        
  949.                                         $single_links = array_unique($single_links);
  950.                                         $this->write_log("number of links:" . count($single_links));
  951.                                         foreach ($single_links as $k => $single_link) {
  952.                                                 $process_queue['items'][] = array(
  953.                                                         'url' => $this->create_absolute_url($single_link, $meta_vals['scrape_url'][0], $html_base_url), 'rss_item' => null
  954.                                                 );
  955.                                         }
  956.                                         if($meta_vals['scrape_nextpage_type'][0] == 'source') {
  957.                         $this->write_log('checking candidate next buttons');
  958.                         foreach ($next_buttons as $btn) {
  959.                             $next_button_text = preg_replace("/\s+/", " ", $btn->textContent);
  960.                             $next_button_text = str_replace(chr(0xC2) . chr(0xA0), " ", $next_button_text);
  961.  
  962.                             if ($next_button_text == $meta_vals['scrape_nextpage_innerhtml'][0]) {
  963.                                 $this->write_log("next page found");
  964.                                 $next_button = $btn;
  965.                             }
  966.                         }
  967.  
  968.                         $next_link = null;
  969.                         if ($next_button) {
  970.                             $next_link = $this->create_absolute_url($next_button->getAttribute('href'), $meta_vals['scrape_url'][0], $html_base_url);
  971.                         }
  972.                     } else {
  973.                         $query = parse_url($meta_vals['scrape_url'][0], PHP_URL_QUERY);
  974.                         $names = unserialize($meta_vals['scrape_next_page_url_parameters_names'][0]);
  975.                         $values = unserialize($meta_vals['scrape_next_page_url_parameters_values'][0]);
  976.                         $increments = unserialize($meta_vals['scrape_next_page_url_parameters_increments'][0]);
  977.  
  978.                         $build_query = array();
  979.  
  980.                         for($i = 0; $i < count($names); $i++) {
  981.                             $build_query[$names[$i]] = $values[$i] + ($increments[$i] * ($process_queue['page_no']));
  982.                         }
  983.                         if ($query) {
  984.                             $next_link = $meta_vals['scrape_url'][0] . "&" . http_build_query($build_query);
  985.                         } else {
  986.                             $next_link = $meta_vals['scrape_url'][0] . "?" . http_build_query($build_query);
  987.                         }
  988.                     }
  989.                                        
  990.                                        
  991.                                         $this->write_log("next link is: " . $next_link);
  992.                                         $process_queue['next_page'] = $next_link;
  993.                                 } else {
  994.                                         return;
  995.                                 }
  996.                         }
  997.                        
  998.                         if (count($process_queue['items']) == 0 && empty($process_queue['next_page'])) {
  999.                                 $end_of_posts = true;
  1000.                                 $this->write_log("end of posts.");
  1001.                         }
  1002.                         if (empty($meta_vals['scrape_post_unlimited'][0]) && !empty($meta_vals['scrape_post_limit'][0]) && $process_queue['number_of_posts'] == $meta_vals['scrape_post_limit'][0]) {
  1003.                                 $post_limit_reached = true;
  1004.                                 $this->write_log("post limit reached.");
  1005.                         }
  1006.                         $this->write_log("repeat count: " . $process_queue['repeat_count']);
  1007.                         if (!empty($meta_vals['scrape_finish_repeat']) && $process_queue['repeat_count'] == $meta_vals['scrape_finish_repeat'][0]) {
  1008.                                 $repeat_limit_reached = true;
  1009.                                 $this->write_log("enable loop repeat limit reached.");
  1010.                         }
  1011.                        
  1012.                         if ($end_of_posts || $post_limit_reached || $repeat_limit_reached) {
  1013.                                 update_post_meta($post_id, 'scrape_workstatus', 'waiting');
  1014.                                 update_post_meta($post_id, "scrape_end_time", current_time('mysql'));
  1015.                                 delete_post_meta($post_id, 'scrape_last_url');
  1016.                                
  1017.                                 if (empty($meta_vals['scrape_run_unlimited'][0]) && get_post_meta($post_id, 'scrape_run_count', true) >= get_post_meta($post_id, 'scrape_run_limit', true)) {
  1018.                                         $timestamp = wp_next_scheduled("scrape_event", array($post_id));
  1019.                                         wp_unschedule_event($timestamp, "scrape_event", array($post_id));
  1020.                                         wp_clear_scheduled_hook("scrape_event", array($post_id));
  1021.                                         $this->write_log("run count reached, deleting task from schedules.");
  1022.                                 }
  1023.                                 $this->write_log("$post_id task ended");
  1024.                                 return;
  1025.                         }
  1026.                        
  1027.                         update_post_meta($post_id, 'scrape_queue', wp_slash($process_queue));
  1028.                        
  1029.                         sleep($meta_vals['scrape_waitpage'][0]);
  1030.                         $nonce = wp_create_nonce('process_task_queue');
  1031.                         update_post_meta($post_id, 'scrape_nonce', $nonce);
  1032. //                      delete_transient('lock_' . $post_id);
  1033.                         wp_remote_get(add_query_arg(array(
  1034.                                 'action' => 'process_task_queue', 'nonce' => $nonce, 'post_id' => $post_id, 'variables' => $_POST
  1035.                         ), admin_url('admin-ajax.php')), array(
  1036.                                 'timeout' => 3, 'blocking' => false, 'sslverify' => false,
  1037.                         ));
  1038.                         $this->write_log("non blocking admin ajax called exiting");
  1039.                 } else {
  1040.                         $this->write_log('nonce failed, not trusted request');
  1041.                 }
  1042.                 wp_die();
  1043.         }
  1044.        
  1045.         public function queue() {
  1046.                 add_action('wp_ajax_nopriv_' . 'process_task_queue', array($this, 'process_task_queue'));
  1047.         }
  1048.        
  1049.         public function execute_post_task($post_id) {
  1050.                 global $meta_vals;
  1051.                
  1052.                 if (Scrapes_Plugin_SDK::is_activated() === true) {
  1053.                         ${"GLOBALS"}["dksfkn"] = "post_id";
  1054.                         ${"GLOBALS"}["unlvnrgtpgv"] = "task_id";
  1055.                         self::${${"GLOBALS"}["unlvnrgtpgv"]} = ${${"GLOBALS"}["dksfkn"]};
  1056.                 }
  1057.                 $meta_vals = get_post_meta($post_id);
  1058.                        
  1059.                 $this->write_log("$post_id id task starting...");
  1060.                 clean_post_cache($post_id);
  1061.                 //clean_post_meta($post_id);
  1062.        
  1063.                 if (empty($meta_vals['scrape_run_unlimited'][0]) && !empty($meta_vals['scrape_run_count']) && !empty($meta_vals['scrape_run_limit']) && $meta_vals['scrape_run_count'][0] >= $meta_vals['scrape_run_limit'][0]) {
  1064.                         $this->write_log("run count limit reached. task returns");
  1065.                         return;
  1066.                 }
  1067.                 if (!empty($meta_vals['scrape_workstatus']) && $meta_vals['scrape_workstatus'][0] == 'running' && $meta_vals['scrape_stillworking'][0] == 'wait') {
  1068.                         $this->write_log($post_id . " wait until finish is selected. returning");
  1069.                         return;
  1070.                 }
  1071.                
  1072.                 $start_time = current_time('mysql');
  1073.                 $modify_time = get_post_modified_time('U', null, $post_id);
  1074.                 update_post_meta($post_id, "scrape_start_time", $start_time);
  1075.                 update_post_meta($post_id, "scrape_end_time", '');
  1076.                 update_post_meta($post_id, 'scrape_workstatus', 'running');
  1077.                 $queue_items = array(
  1078.                         'items' => array(), 'meta_vals' => $meta_vals, 'repeat_count' => 0, 'number_of_posts' => 0, 'page_no' => 1, 'start_time' => $start_time, 'modify_time' => $modify_time, 'next_page' => null
  1079.                 );
  1080.                
  1081.                 if ($meta_vals['scrape_type'][0] == 'single') {
  1082.                         $queue_items['items'][] = array(
  1083.                                 'url' => $meta_vals['scrape_url'][0], 'rss_item' => null
  1084.                         );
  1085.                         update_post_meta($post_id, 'scrape_queue', wp_slash($queue_items));
  1086.                 } else {
  1087.                         if ($meta_vals['scrape_type'][0] == 'feed') {
  1088.                                 $this->write_log("rss xml download");
  1089.                                 $args = $this->return_html_args($meta_vals);
  1090.                                 $url = $meta_vals['scrape_url'][0];
  1091.                                 $response = wp_remote_get($url, $args);
  1092.                                 if (!isset($response->errors)) {
  1093.                                         $body = wp_remote_retrieve_body($response);
  1094.                                         $charset = $this->detect_feed_encoding_and_replace(wp_remote_retrieve_header($response, "Content-Type"), $body);
  1095.                                         $body = iconv($charset, "UTF-8//IGNORE", $body);
  1096.                                         if ($body === false) {
  1097.                                                 $this->write_log("UTF8 Convert error from charset:" . $charset);
  1098.                                         }
  1099.                                        
  1100.                                         if (function_exists('tidy_repair_string')) {
  1101.                                                 $body = tidy_repair_string($body, array(
  1102.                                                         'output-xml' => true, 'input-xml' => true
  1103.                                                 ), 'utf8');
  1104.                                         }
  1105.                                        
  1106.                                         $xml = simplexml_load_string($body);
  1107.                                        
  1108.                                         if ($xml === false) {
  1109.                                                 $this->write_log(libxml_get_errors(), true);
  1110.                                                 libxml_clear_errors();
  1111.                                         }
  1112.                                        
  1113.                                         $namespaces = $xml->getNamespaces(true);
  1114.                                        
  1115.                                         $feed_type = $xml->getName();
  1116.                                        
  1117.                                         $feed_image = '';
  1118.                                         if ($feed_type == 'rss') {
  1119.                                                 $items = $xml->channel->item;
  1120.                                                 if (isset($xml->channel->image)) {
  1121.                                                         $feed_image = $xml->channel->image->url;
  1122.                                                 }
  1123.                                         } else {
  1124.                                                 if ($feed_type == 'feed') {
  1125.                                                         $items = $xml->entry;
  1126.                                                         $feed_image = (!empty($xml->logo) ? $xml->logo : $xml->icon);
  1127.                                                 } else {
  1128.                                                         if ($feed_type == 'RDF') {
  1129.                                                                 $items = $xml->item;
  1130.                                                                 $feed_image = $xml->channel->image->attributes($namespaces['rdf'])->resource;
  1131.                                                         }
  1132.                                                 }
  1133.                                         }
  1134.  
  1135.                                         foreach ($items as $item) {
  1136.                                                
  1137.                                                 $post_date = '';
  1138.                                                 if ($feed_type == 'rss') {
  1139.                                                         $post_date = $item->pubDate;
  1140.                                                 } else {
  1141.                                                         if ($feed_type == 'feed') {
  1142.                                                                 $post_date = $item->published;
  1143.                                                         } else {
  1144.                                                                 if ($feed_type == 'RDF') {
  1145.                                                                         $post_date = $item->children($namespaces['dc'])->date;
  1146.                                                                 }
  1147.                                                         }
  1148.                                                 }
  1149.                                                
  1150.                                                 $post_date = date('Y-m-d H:i:s', strtotime($post_date));
  1151.                                                
  1152.                                                 if ($feed_type != 'feed') {
  1153.                                                         $post_content = html_entity_decode($item->description, ENT_COMPAT, "UTF-8");
  1154.                                                         $original_html_content = $post_content;
  1155.                                                 } else {
  1156.                                                         $post_content = html_entity_decode($item->content, ENT_COMPAT, "UTF-8");
  1157.                                                         $original_html_content = $post_content;
  1158.                                                 }
  1159.                                                
  1160.                                                 if ($meta_vals['scrape_allowhtml'][0] != 'on') {
  1161.                                                         $post_content = wp_strip_all_tags($post_content);
  1162.                                                 }
  1163.                                                
  1164.                                                 $post_content = trim($post_content);
  1165.                                                
  1166.                                                 if (isset($namespaces['media'])) {
  1167.                                                         $media = $item->children($namespaces['media']);
  1168.                                                 } else {
  1169.                                                         $media = $item->children();
  1170.                                                 }
  1171.                                                
  1172.                                                 if (isset($media->content) && $feed_type != 'feed') {
  1173.                                                         $this->write_log("image from media:content");
  1174.                                                         $url = (string)$media->content->attributes()->url;
  1175.                                                         $featured_image_url = $url;
  1176.                                                 } else {
  1177.                                                         if (isset($media->thumbnail)) {
  1178.                                                                 $this->write_log("image from media:thumbnail");
  1179.                                                                 $url = (string)$media->thumbnail->attributes()->url;
  1180.                                                                 $featured_image_url = $url;
  1181.                                                         } else {
  1182.                                                                 if (isset($item->enclosure)) {
  1183.                                                                         $this->write_log("image from enclosure");
  1184.                                                                         $url = (string)$item->enclosure['url'];
  1185.                                                                         $featured_image_url = $url;
  1186.                                                                 } else {
  1187.                                                                         if (isset($item->description) || (isset($item->content) && $feed_type == 'feed')) {
  1188.                                                                                 $item_content = (isset($item->description) ? $item->description : $item->content);
  1189.                                                                                 $this->write_log("image from description");
  1190.                                                                                 $doc = new DOMDocument();
  1191.                                                                                 $doc->preserveWhiteSpace = false;
  1192.                                                                                 @$doc->loadHTML('<?xml encoding="utf-8" ?>' . html_entity_decode($item_content));
  1193.                                                                                
  1194.                                                                                 $imgs = $doc->getElementsByTagName('img');
  1195.                                                                                
  1196.                                                                                 if ($imgs->length) {
  1197.                                                                                         $featured_image_url = $imgs->item(0)->attributes->getNamedItem('src')->nodeValue;
  1198.                                                                                 }
  1199.                                                                         } else {
  1200.                                                                                 if (!empty($feed_image)) {
  1201.                                                                                         $this->write_log("image from channel");
  1202.                                                                                         $featured_image_url = $feed_image;
  1203.                                                                                 }
  1204.                                                                         }
  1205.                                                                 }
  1206.                                                         }
  1207.                                                 }
  1208.                                                
  1209.                                                 $rss_item = array(
  1210.                                                         'post_date' => strval($post_date), 'post_content' => strval($post_content), 'post_original_content' => $original_html_content, 'featured_image' => $this->create_absolute_url(strval($featured_image_url), $url, null), 'post_title' => strval($item->title)
  1211.                                                 );
  1212.                                                 if ($feed_type == 'feed') {
  1213.                                                         $alternate_found = false;
  1214.                                                         foreach ($item->link as $link) {
  1215.                                                                 $this->write_log($link->attributes()->rel);
  1216.                                                                 if ($link->attributes()->rel == 'alternate') {
  1217.                                                                         $single_url = strval($link->attributes()->href);
  1218.                                                                         $this->write_log('found alternate attribute link: ' . $single_url);
  1219.                                                                         $alternate_found = true;
  1220.                                                                 }
  1221.                                                         }
  1222.                                                         if (!$alternate_found) {
  1223.                                                                 $single_url = strval($item->link->attributes()->href);
  1224.                                                         }
  1225.                                                 } else {
  1226.                                                         $single_url = strval($item->link);
  1227.                                                 }
  1228.                                                
  1229.                                                 $this->write_log('foreach items');
  1230.                                                 $this->write_log($single_url);
  1231.                                                 $this->write_log($rss_item);
  1232.                                                
  1233.                                                 $queue_items['items'][] = array(
  1234.                                                         'url' => $single_url, 'rss_item' => $rss_item
  1235.                                                 );
  1236.                                         }
  1237.                                        
  1238.                                         update_post_meta($post_id, 'scrape_queue', wp_slash($queue_items));
  1239.                                 } else {
  1240.                                         $this->write_log($post_id . " http error:" . $response->get_error_message());
  1241.                                         if ($meta_vals['scrape_onerror'][0] == 'stop') {
  1242.                                                 $this->write_log($post_id . " on error chosen stop. returning code " . $response->get_error_message(), true);
  1243.                                                 return;
  1244.                                         }
  1245.                                 }
  1246.                         } else {
  1247.                                 if ($meta_vals['scrape_type'][0] == 'list') {
  1248.                                         $args = $this->return_html_args($meta_vals);
  1249.                                         if (!empty($meta_vals['scrape_last_url']) && $meta_vals['scrape_run_type'][0] == 'continue') {
  1250.                                                 $this->write_log("continues from last stopped url" . $meta_vals['scrape_last_url'][0]);
  1251.                                                 $meta_vals['scrape_url'][0] = $meta_vals['scrape_last_url'][0];
  1252.                                         }
  1253.                                        
  1254.                                         $this->write_log("Serial scrape starts at URL:" . $meta_vals['scrape_url'][0]);
  1255.                                        
  1256.                                         $response = wp_remote_get($meta_vals['scrape_url'][0], $args);
  1257.                                         update_post_meta($post_id, 'scrape_last_url', $meta_vals['scrape_url'][0]);
  1258.                                        
  1259.                                         if (!isset($response->errors)) {
  1260.                                                 $body = wp_remote_retrieve_body($response);
  1261.                                                 $body = trim($body);
  1262.                                                
  1263.                                                 if (substr($body, 0, 3) == pack("CCC", 0xef, 0xbb, 0xbf)) {
  1264.                                                         $body = substr($body, 3);
  1265.                                                 }
  1266.                                                
  1267.                                                 $charset = $this->detect_html_encoding_and_replace(wp_remote_retrieve_header($response, "Content-Type"), $body);
  1268.                                                 $body_iconv = iconv($charset, "UTF-8//IGNORE", $body);
  1269.                                                
  1270.                                                 $body_preg = '<?xml encoding="utf-8" ?>' . preg_replace(array(
  1271.                                                                 "/<!--.*?-->/isu", '/(<table([^>]+)?>([^<>]+)?)(?!<tbody([^>]+)?>)/isu', '/(<(?!(\/tbody))([^>]+)?>)(<\/table([^>]+)?>)/isu', "'<\s*script[^>]*[^/]>(.*?)<\s*/\s*script\s*>'isu", "'<\s*script\s*>(.*?)<\s*/\s*script\s*>'isu", "'<\s*noscript[^>]*[^/]>(.*?)<\s*/\s*noscript\s*>'isu", "'<\s*noscript\s*>(.*?)<\s*/\s*noscript\s*>'isu",
  1272.                                                        
  1273.                                                         ), array(
  1274.                                                                 "", '$1<tbody>', '$1</tbody>$4', "", "", "", ""
  1275.                                                         ), $body_iconv);
  1276.                                                
  1277.                                                 $doc = new DOMDocument;
  1278.                                                 $doc->preserveWhiteSpace = false;
  1279.                                                 $body_preg = mb_convert_encoding($body_preg, 'HTML-ENTITIES', 'UTF-8');
  1280.                                                 @$doc->loadHTML($body_preg);
  1281.                                                
  1282.                                                 $url = parse_url($meta_vals['scrape_url'][0]);
  1283.                                                 $url = $url['scheme'] . "://" . $url['host'];
  1284.                                                 $base = $doc->getElementsByTagName('base')->item(0);
  1285.                                                 $html_base_url = null;
  1286.                                                 if (!is_null($base)) {
  1287.                                                         $html_base_url = $this->create_absolute_url($base->getAttribute('href'), $url, null);
  1288.                                                 }
  1289.                                                
  1290.                                                 $xpath = new DOMXPath($doc);
  1291.                                                
  1292.                                                 $next_buttons = (!empty($meta_vals['scrape_nextpage'][0]) ? $xpath->query($meta_vals['scrape_nextpage'][0]) : new DOMNodeList);
  1293.                                                
  1294.                                                 $next_button = false;
  1295.                                                 $is_facebook_page = false;
  1296.                                                
  1297.                                                 if (parse_url($meta_vals['scrape_url'][0], PHP_URL_HOST) == 'mbasic.facebook.com') {
  1298.                                                         $is_facebook_page = true;
  1299.                                                 }
  1300.                                                
  1301.                                                 $ref_a_element = $xpath->query($meta_vals['scrape_listitem'][0])->item(0);
  1302.                                                 if (is_null($ref_a_element)) {
  1303.                                                         $this->write_log("Reference a element not found URL:" . $meta_vals['scrape_url'][0] . " XPath: " . $meta_vals['scrape_listitem'][0]);
  1304.                             update_post_meta($post_id, 'scrape_workstatus', 'waiting');
  1305.                             update_post_meta($post_id, "scrape_end_time", current_time('mysql'));
  1306.                             delete_post_meta($post_id, 'scrape_last_url');
  1307.  
  1308.                             if (empty($meta_vals['scrape_run_unlimited'][0]) && get_post_meta($post_id, 'scrape_run_count', true) >= get_post_meta($post_id, 'scrape_run_limit', true)) {
  1309.                                 $timestamp = wp_next_scheduled("scrape_event", array($post_id));
  1310.                                 wp_unschedule_event($timestamp, "scrape_event", array($post_id));
  1311.                                 wp_clear_scheduled_hook("scrape_event", array($post_id));
  1312.                                 $this->write_log("run count reached, deleting task from schedules.");
  1313.                             }
  1314.                             $this->write_log("$post_id task ended");
  1315.                             return;
  1316.                                                 }
  1317.                                                 $ref_node_path = $ref_a_element->getNodePath();
  1318.                                                 $ref_node_no_digits = preg_replace("/\[\d+\]/", "", $ref_node_path);
  1319.                                                 $ref_a_children = array();
  1320.                                                 foreach ($ref_a_element->childNodes as $node) {
  1321.                                                         $ref_a_children[] = $node->nodeName;
  1322.                                                 }
  1323.                                                
  1324.                                                 $this->write_log("scraping page #" . $queue_items['page_no']);
  1325.                                                
  1326.                                                 $all_links = $xpath->query("//a");
  1327.                                                 if ($is_facebook_page) {
  1328.                                                         $all_links = $xpath->query("//a[text()='" . trim($ref_a_element->textContent) . "']");
  1329.                                                 } else {
  1330.                                                         if (!empty($meta_vals['scrape_exact_match'][0])) {
  1331.                                                                 $all_links = $xpath->query($meta_vals['scrape_listitem'][0]);
  1332.                                                         }
  1333.                                                 }
  1334.                                                
  1335.                                                 $single_links = array();
  1336.                                                 if (empty($meta_vals['scrape_exact_match'][0])) {
  1337.                                                         $this->write_log("serial fuzzy match links");
  1338.                                                         foreach ($all_links as $a_elem) {
  1339.                                                                
  1340.                                                                 $parent_path = $a_elem->getNodePath();
  1341.                                                                 $parent_path_no_digits = preg_replace("/\[\d+\]/", "", $parent_path);
  1342.                                                                 if ($parent_path_no_digits == $ref_node_no_digits) {
  1343.                                                                         $children_node_names = array();
  1344.                                                                         foreach ($a_elem->childNodes as $node) {
  1345.                                                                                 $children_node_names[] = $node->nodeName;
  1346.                                                                         }
  1347.                                                                         if ($ref_a_children === $children_node_names) {
  1348.                                                                                 $single_links[] = $a_elem->getAttribute('href');
  1349.                                                                         }
  1350.                                                                 }
  1351.                                                         }
  1352.                                                 } else {
  1353.                                                         $this->write_log("serial exact match links");
  1354.                                                         foreach ($all_links as $a_elem) {
  1355.                                                                 $single_links[] = $a_elem->getAttribute('href');
  1356.                                                         }
  1357.                                                 }
  1358.                                                
  1359.                                                 $single_links = array_unique($single_links);
  1360.                                                 $this->write_log("number of links:" . count($single_links));
  1361.                                                 foreach ($single_links as $k => $single_link) {
  1362.                                                         $queue_items['items'][] = array(
  1363.                                                                 'url' => $this->create_absolute_url($single_link, $meta_vals['scrape_url'][0], $html_base_url), 'rss_item' => null
  1364.                                                         );
  1365.                                                 }
  1366.  
  1367.                                                 if($meta_vals['scrape_nextpage_type'][0] == 'source') {
  1368.  
  1369.  
  1370.                             $this->write_log('checking candidate next buttons');
  1371.                             foreach ($next_buttons as $btn) {
  1372.                                 $next_button_text = preg_replace("/\s+/", " ", $btn->textContent);
  1373.                                 $next_button_text = str_replace(chr(0xC2) . chr(0xA0), " ", $next_button_text);
  1374.  
  1375.                                 if ($next_button_text == $meta_vals['scrape_nextpage_innerhtml'][0]) {
  1376.                                     $this->write_log("next page found");
  1377.                                     $next_button = $btn;
  1378.                                 } else {
  1379.                                     $this->write_log($next_button_text . ' ' . $meta_vals['scrape_nextpage_innerhtml'][0] . ' does not match');
  1380.                                 }
  1381.                             }
  1382.                             $next_link = null;
  1383.                             if ($next_button) {
  1384.                                 $next_link = $this->create_absolute_url($next_button->getAttribute('href'), $meta_vals['scrape_url'][0], $html_base_url);
  1385.                             }
  1386.                         } else {
  1387.                             $query = parse_url($meta_vals['scrape_url'][0], PHP_URL_QUERY);
  1388.                             $names = unserialize($meta_vals['scrape_next_page_url_parameters_names'][0]);
  1389.                             $values = unserialize($meta_vals['scrape_next_page_url_parameters_values'][0]);
  1390.                             $increments = unserialize($meta_vals['scrape_next_page_url_parameters_increments'][0]);
  1391.  
  1392.                             $build_query = array();
  1393.  
  1394.                             for($i = 0; $i < count($names); $i++) {
  1395.                                 $build_query[$names[$i]] = $values[$i] + ($increments[$i] * (1));
  1396.                             }
  1397.                             if ($query) {
  1398.                                 $next_link = $meta_vals['scrape_url'][0] . "&" . http_build_query($build_query);
  1399.                             } else {
  1400.                                 $next_link = $meta_vals['scrape_url'][0] . "?" . http_build_query($build_query);
  1401.                             }
  1402.                         }
  1403.                                                
  1404.                                                
  1405.                                                 $this->write_log("next link is: " . $next_link);
  1406.                                                 $queue_items['next_page'] = $next_link;
  1407.                                                 update_post_meta($post_id, 'scrape_queue', wp_slash($queue_items));
  1408.                                         } else {
  1409.                                                 $this->write_log($post_id . " http error in url " . $meta_vals['scrape_url'][0] . " : " . $response->get_error_message(), true);
  1410.                                                 if ($meta_vals['scrape_onerror'][0] == 'stop') {
  1411.                                                         $this->write_log($post_id . " on error chosen stop. returning code ", true);
  1412.                                                         return;
  1413.                                                 }
  1414.                                         }
  1415.                                 }
  1416.                         }
  1417.                 }
  1418.                
  1419.                 $nonce = wp_create_nonce('process_task_queue');
  1420.                 update_post_meta($post_id, 'scrape_nonce', $nonce);
  1421.                
  1422.                 update_post_meta($post_id, "scrape_run_count", $meta_vals['scrape_run_count'][0] + 1);
  1423.                
  1424.                 $this->write_log("$post_id id task queued...");
  1425.                
  1426.                 wp_remote_get(add_query_arg(array('action' => 'process_task_queue', 'nonce' => $nonce, 'post_id' => $post_id, 'variables' => $_POST), admin_url('admin-ajax.php')), array(
  1427.                         'timeout' => 3, 'blocking' => false, 'sslverify' => false
  1428.                 ));
  1429.                
  1430.         }
  1431.        
  1432.         public function single_scrape($url, $meta_vals, &$repeat_count = 0, $rss_item = null) {
  1433.                 global $wpdb, $new_id, $post_arr, $doc;
  1434.                
  1435.                 update_post_meta($meta_vals['scrape_task_id'][0], 'scrape_last_scrape', current_time('mysql'));
  1436.                
  1437.                 $args = $this->return_html_args($meta_vals);
  1438.                
  1439.                 $is_facebook_page = false;
  1440.                 $is_amazon = false;
  1441.                
  1442.                 if (parse_url($url, PHP_URL_HOST) == 'mbasic.facebook.com') {
  1443.                         $is_facebook_page = true;
  1444.                 }
  1445.                
  1446.                 if (preg_match("/(\/|\.)amazon\./", $meta_vals['scrape_url'][0])) {
  1447.                         $is_amazon = true;
  1448.                 }
  1449.                 $response = wp_remote_get($url, $args);
  1450.  
  1451.                 $scrape_count = get_site_option('ol_scrapes_scrape_count', ['current' => 0, 'total' => 0]);
  1452.                 $scrape_count['total']++;
  1453.                 update_site_option('ol_scrapes_scrape_count', $scrape_count);
  1454.                
  1455.                 if (!isset($response->errors)) {
  1456.                         $this->write_log("Single scraping started: " . $url);
  1457.                         $body = $response['body'];
  1458.                         $body = trim($body);
  1459.                        
  1460.                         if (substr($body, 0, 3) == pack("CCC", 0xef, 0xbb, 0xbf)) {
  1461.                                 $body = substr($body, 3);
  1462.                         }
  1463.                        
  1464.                         $charset = $this->detect_html_encoding_and_replace(wp_remote_retrieve_header($response, "Content-Type"), $body);                   
  1465.                         $body_iconv = iconv($charset, "UTF-8//IGNORE", $body);
  1466.                         unset($body);
  1467.                         $body_preg = preg_replace(array(
  1468.                                 "/<!--.*?-->/isu", '/(<table([^>]+)?>([^<>]+)?)(?!<tbody([^>]+)?>)/isu', '/(<(?!(\/tbody))([^>]+)?>)(<\/table([^>]+)?>)/isu', "'<\s*script[^>]*[^/]>(.*?)<\s*/\s*script\s*>'isu", "'<\s*script\s*>(.*?)<\s*/\s*script\s*>'isu", "'<\s*noscript[^>]*[^/]>(.*?)<\s*/\s*noscript\s*>'isu", "'<\s*noscript\s*>(.*?)<\s*/\s*noscript\s*>'isu",
  1469.                        
  1470.                         ), array(
  1471.                                 "", '$1<tbody>', '$1</tbody>$4', "", "", "", ""
  1472.                         ), $body_iconv);
  1473.                         unset($body_iconv);
  1474.                         $doc = new DOMDocument;
  1475.                         //DOMObject('body');
  1476.                                
  1477.                         $doc->preserveWhiteSpace = false;
  1478.                         $body_preg = mb_convert_encoding($body_preg, 'HTML-ENTITIES', 'UTF-8');
  1479.                         @$doc->loadHTML('<?xml encoding="utf-8" ?>' . $body_preg);
  1480.  
  1481.                         ${"GLOBALS"}["dhpebyms"] = "xpath";
  1482.                         if (Scrapes_Plugin_SDK::is_activated() === true) {
  1483.                                 $gnzcwtbppmph = "doc";
  1484.                                 ${${"GLOBALS"}["dhpebyms"]} = new DOMXPath(${$gnzcwtbppmph});
  1485.                         }
  1486.                        
  1487.                         $parsed_url = parse_url($meta_vals['scrape_url'][0]);
  1488.                         $parsed_url = $parsed_url['scheme'] . "://" . $parsed_url['host'];
  1489.                         $base = $doc->getElementsByTagName('base')->item(0);
  1490.                         $html_base_url = null;
  1491.                         if (!is_null($base)) {
  1492.                                 $html_base_url = $this->create_absolute_url($base->getAttribute('href'), $parsed_url, null);
  1493.                         }
  1494.                        
  1495.                         $ID = 0;
  1496.                        
  1497.                         $post_type = $meta_vals['scrape_post_type'][0];
  1498.                         $enable_translate = !empty($meta_vals['scrape_translate_enable'][0]);
  1499.                         if ($enable_translate) {
  1500.                                 $source_language = $meta_vals['scrape_translate_source'][0];
  1501.                                 $target_language = $meta_vals['scrape_translate_target'][0];
  1502.                         }
  1503.  
  1504.                         $enable_spin = !empty($meta_vals['scrape_spin_enable'][0]);
  1505.             if ($enable_spin) {
  1506.                 $spin_email = $meta_vals['scrape_spin_email'][0];
  1507.                 $spin_password = $meta_vals['scrape_spin_password'][0];
  1508.             }
  1509.                        
  1510.                         $post_date_type = $meta_vals['scrape_date_type'][0];
  1511.                         if ($post_date_type == 'xpath') {
  1512.                                 $post_date = $meta_vals['scrape_date'][0];
  1513.                                 $node = $xpath->query($post_date);
  1514.                                 if ($node->length) {
  1515.                                        
  1516.                                         $node = $node->item(0);
  1517.                                         $post_date = $node->nodeValue;
  1518.                                         if (!empty($meta_vals['scrape_date_regex_status'][0])) {
  1519.                                                 $regex_finds = unserialize($meta_vals['scrape_date_regex_finds'][0]);
  1520.                                                 $regex_replaces = unserialize($meta_vals['scrape_date_regex_replaces'][0]);
  1521.                                                 $combined = array_combine($regex_finds, $regex_replaces);
  1522.                                                 foreach ($combined as $regex => $replace) {
  1523.                                                         $post_date = preg_replace("/" . str_replace("/", "\/", $regex) . "/isu", $replace, $post_date);
  1524.                                                 }
  1525.                                                 $this->write_log("date after regex:" . $post_date);
  1526.                                         }
  1527.                                         if ($is_facebook_page) {
  1528.                                                 $this->write_log("facebook date original " . $post_date);
  1529.                                                 if (preg_match_all("/just now/i", $post_date, $matches)) {
  1530.                                                         $post_date = current_time('mysql');
  1531.                                                 } else {
  1532.                                                         if (preg_match_all("/(\d{1,2}) min(ute)?(s)?/i", $post_date, $matches)) {
  1533.                                                                 $post_date = date("Y-m-d H:i:s", strtotime($matches[1][0] . " minutes ago", current_time('timestamp')));
  1534.                                                         } else {
  1535.                                                                 if (preg_match_all("/(\d{1,2}) h(ou)?r(s)?/i", $post_date, $matches)) {
  1536.                                                                         $post_date = date("Y-m-d H:i:s", strtotime($matches[1][0] . " hours ago", current_time('timestamp')));
  1537.                                                                 } else {
  1538.                                                                         $post_date = str_replace("Yesterday", date("F j, Y", strtotime("-1 day", current_time('timestamp'))), $post_date);
  1539.                                                                         if (!preg_match("/\d{4}/i", $post_date)) {
  1540.                                                                                 $at_position = strpos($post_date, "at");
  1541.                                                                                 if ($at_position !== false) {
  1542.                                                                                         if (in_array(substr($post_date, 0, $at_position - 1), array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"))) {
  1543.                                                                                                 $post_date = date("F j, Y", strtotime("last " . substr($post_date, 0, $at_position - 1), current_time('timestamp'))) . " " . substr($post_date, $at_position + 2);
  1544.                                                                                         } else {
  1545.                                                                                                 $post_date = substr($post_date, 0, $at_position) . " " . date("Y") . " " . substr($post_date, $at_position + 2);
  1546.                                                                                         }
  1547.                                                                                        
  1548.                                                                                 } else {
  1549.                                                                                         $post_date .= " " . date("Y");
  1550.                                                                                 }
  1551.                                                                                
  1552.                                                                         }
  1553.                                                                 }
  1554.                                                         }
  1555.                                                 }
  1556.                                                 $this->write_log("after facebook $post_date");
  1557.                                         }
  1558.                                         if(function_exists('convert_to_english')) {
  1559.                                                 $option_ts = (get_option('ts_page_settings_is_active',true));
  1560.                                                 if($option_ts['ts_active_jalali_date'] != 'off') {
  1561.                                                         $post_date = convert_to_english($post_date);
  1562.                                                 }
  1563.                                         }                                      
  1564.                                         $tmp_post_date = $post_date;
  1565.                                         $post_date = date_parse($post_date);
  1566.                                         if (!is_integer($post_date['year']) || !is_integer(($post_date['month'])) || !is_integer($post_date['day'])) {
  1567.                                                 $this->write_log("date can not be parsed correctly. trying translations");
  1568.                                                 $post_date = $tmp_post_date;
  1569.                                                 $post_date = $this->translate_months($post_date);
  1570.                                                 $this->write_log("date value: " . $post_date);
  1571.                                                 $post_date = date_parse($post_date);
  1572.                                                 if (!is_integer($post_date['year']) || !is_integer(($post_date['month'])) || !is_integer($post_date['day'])) {
  1573.                                                         $this->write_log("translation is not accepted valid");
  1574.                                                         $post_date = '';
  1575.                                                 } else {
  1576.                                                         $this->write_log("translation is accepted valid");
  1577.                                                         if(class_exists('TS_Options')) {
  1578.                                                                 if(function_exists('wp_date')) {
  1579.                                                                         $post_time = array('hour' => $post_date['hour'], 'min' => $post_date['minute'], 'sec' => $post_date['second']);
  1580.                                                                         $post_date = date("Y-m-d H:i:s", mktime($post_date['hour'], $post_date['minute'], $post_date['second'], $post_date['month'], $post_date['day'], $post_date['year']));
  1581.                                                                         $save_post_date_jalali = $post_date;
  1582.                                                                         $post_date = za_jalali_to_geo($post_date, $post_time['hour'], $post_time['min'], $post_time['sec']);
  1583.                                                                 }
  1584.                                                         } else {
  1585.                                                                 $post_date = date("Y-m-d H:i:s", mktime($post_date['hour'], $post_date['minute'], $post_date['second'], $post_date['month'], $post_date['day'], $post_date['year']));
  1586.                                                         }
  1587.                                                 }
  1588.                                         } else {
  1589.                                                 $this->write_log("date parsed correctly");
  1590.                                                 $post_date = date("Y-m-d H:i:s", mktime($post_date['hour'], $post_date['minute'], $post_date['second'], $post_date['month'], $post_date['day'], $post_date['year']));
  1591.                                         }
  1592.                                 } else {
  1593.                                         $post_date = '';
  1594.                                         $this->write_log("URL: " . $url . " XPath: " . $meta_vals['scrape_date'][0] . " returned empty for post date", true);
  1595.                                 }
  1596.                         } else {
  1597.                                 if ($post_date_type == 'runtime') {
  1598.                                         $post_date = current_time('mysql');
  1599.                                         if(class_exists('TS_Options')) {
  1600.                                                 if(function_exists('wp_date')) {
  1601.                                                         $save_post_date_jalali = za_geo_to_jalali($post_date);
  1602.                                                 }
  1603.                                         }                                      
  1604.                                 } else {
  1605.                                         if ($post_date_type == 'custom') {
  1606.                                                 $post_date = $meta_vals['scrape_date_custom'][0];
  1607.                                                 if(class_exists('TS_Options')) {
  1608.                                                         if(function_exists('wp_date')) {
  1609.                                                                 $save_post_date_jalali = $post_date;
  1610.                                                                 $post_time = explode(' ', $post_date);
  1611.                                                                 $post_time = explode(':', $post_time[1]);
  1612.                                                                 $post_date = za_jalali_to_geo($post_date, $post_time[0], $post_time[1], $post_time[2]);
  1613.                                                         }
  1614.                                                 }                                              
  1615.                                         } else {
  1616.                                                 if ($post_date_type == 'feed') {
  1617.                                                         $post_date = $rss_item['post_date'];
  1618.                                                 } else {
  1619.                                                         $post_date = '';
  1620.                                                 }
  1621.                                         }
  1622.                                 }
  1623.                         }
  1624.                        
  1625.                         $post_meta_names = array();
  1626.                         $post_meta_values = array();
  1627.                         $post_meta_attributes = array();
  1628.                         $post_meta_templates = array();
  1629.                         $post_meta_regex_finds = array();
  1630.                         $post_meta_regex_replaces = array();
  1631.                         $post_meta_regex_statuses = array();
  1632.                         $post_meta_template_statuses = array();
  1633.                         $post_meta_allowhtmls = array();
  1634.                         $post_meta_dont_updates = array();
  1635.                        
  1636.                         if (!empty($meta_vals['scrape_custom_fields'])) {
  1637.                                 $scrape_custom_fields = unserialize($meta_vals['scrape_custom_fields'][0]);
  1638.                                 foreach ($scrape_custom_fields as $timestamp => $arr) {
  1639.                                         $post_meta_names[] = $arr["name"];
  1640.                                         $post_meta_values[] = $arr["value"];
  1641.                                         $post_meta_attributes[] = $arr["attribute"];
  1642.                                         $post_meta_templates[] = $arr["template"];
  1643.                                         $post_meta_regex_finds[] = isset($arr["regex_finds"]) ? $arr["regex_finds"] : array();
  1644.                                         $post_meta_regex_replaces[] = isset($arr["regex_replaces"]) ? $arr["regex_replaces"] : array();
  1645.                                         $post_meta_regex_statuses[] = $arr['regex_status'];
  1646.                                         $post_meta_template_statuses[] = $arr['template_status'];
  1647.                                         $post_meta_allowhtmls[] = $arr['allowhtml'];
  1648.                                         $post_meta_dont_updates[] = $arr['dont_update'];
  1649.                                 }
  1650.                         }
  1651.                        
  1652.                         $post_meta_name_values = array();
  1653.                         if (!empty($post_meta_names) && !empty($post_meta_values)) {
  1654.                                 $post_meta_name_values = array_combine($post_meta_names, $post_meta_values);
  1655.                         }
  1656.                        
  1657.                         $meta_input = array();
  1658.                        
  1659.                         $woo_active = false;
  1660.                         $woo_price_metas = array('_price', '_sale_price', '_regular_price');
  1661.                         $woo_decimal_metas = array('_height', '_length', '_width', '_weight');
  1662.                         $woo_integer_metas = array('_download_expiry', '_download_limit', '_stock', 'total_sales', '_download_expiry', '_download_limit');
  1663.                         include_once(ABSPATH . 'wp-admin/includes/plugin.php');
  1664.                         if (is_plugin_active('woocommerce/woocommerce.php')) {
  1665.                                 $woo_active = true;
  1666.                         }
  1667.                        
  1668.                         $post_meta_index = 0;
  1669.                         foreach ($post_meta_name_values as $key => $value) {
  1670.                                 if (stripos($value, "//") === 0) {
  1671.                                         $node = $xpath->query($value);
  1672.                                         if ($node->length) {
  1673.                                                 $node = $node->item(0);
  1674.                                                 if(class_exists('TS_Options')) {
  1675.                                                         $option_ts = (get_option('ts_page_settings_is_active',true));
  1676.                                                         $ts_tab_custom_field = array_key_exists("ts_active_custom_field", $option_ts) ? $option_ts['ts_active_custom_field'] : '';
  1677.                                                 }
  1678.                                                 if (!empty($post_meta_allowhtmls[$post_meta_index]) || $key == '_ts_meta_size' ||  $key == '_ts_meta_color' || $key == '_ts_meta_custom' || $key == $ts_tab_custom_field) {
  1679.                                                         $value = $node->ownerDocument->saveXML($node);
  1680.                                                         $value = $this->convert_html_links($value, $url, $html_base_url);
  1681.                                                 } else {
  1682.                                                         if (!empty($post_meta_attributes[$post_meta_index])) {
  1683.                                                                 $value = $node->getAttribute($post_meta_attributes[$post_meta_index]);
  1684.                                                         } else {
  1685.                                                                 $value = $node->nodeValue;
  1686.                                                         }
  1687.                                                 }
  1688.                                                 if(function_exists('convert_to_english')){
  1689.                                                         if(!empty('_price') || !empty('_sale_price') || !empty('_regular_price') || !empty('_stock')) {
  1690.                                                                 if($option_ts['ts_active_persian_price'] != 'off'){
  1691.                                                                         $value = convert_to_english($value);
  1692.                                                                 }
  1693.                                                         }
  1694.                                                 }                                              
  1695.                                                
  1696.                                                 $this->write_log("post meta $key : " . (string)$value);
  1697.                         if ($enable_spin) {
  1698.                             $value = $this->spin_content_with_thebestspinner($spin_email, $spin_password, $value);
  1699.                         }
  1700.                                                 if ($enable_translate) {
  1701.                                                         if (class_exists('TS_Translate')) {
  1702.                                                                 $value = TS_Translate::translate($source_language, $target_language, $value);
  1703.                                                                 $value = $this->ordered_html_tag($value);
  1704.                                                         }
  1705.                                                 }
  1706.                                                
  1707.                                                 if (!empty($post_meta_regex_statuses[$post_meta_index])) {
  1708.                                                        
  1709.                                                         $regex_combined = array_combine($post_meta_regex_finds[$post_meta_index], $post_meta_regex_replaces[$post_meta_index]);
  1710.                                                         foreach ($regex_combined as $find => $replace) {
  1711.                                                                 $this->write_log("custom field value before regex $value");
  1712.                                                                 $value = preg_replace("/" . str_replace("/", "\/", $find) . "/isu", $replace, $value);
  1713.                                                                 $this->write_log("custom field value after regex $value");
  1714.                                                         }
  1715.                                                 }
  1716.                                         } else {
  1717.                                                 $this->write_log("post meta $key : found empty.", true);
  1718.                                                 $this->write_log("URL: " . $url . " XPath: " . $value . " returned empty for post meta $key", true);
  1719.                                                 $value = '';
  1720.                                         }
  1721.                                 }
  1722.                                
  1723.                                 if ($woo_active && $post_type == 'product') {
  1724.                                         if (in_array($key, $woo_price_metas)) {
  1725.                                                 $value = $this->convert_str_to_woo_decimal($value);
  1726.                                         }
  1727.                                         if (in_array($key, $woo_decimal_metas)) {
  1728.                                                 $value = floatval($value);
  1729.                                         }
  1730.                                         if (in_array($key, $woo_integer_metas)) {
  1731.                                                 $value = intval($value);
  1732.                                         }
  1733.                                 }
  1734.                                
  1735.                                 if (!empty($post_meta_template_statuses[$post_meta_index])) {
  1736.                                         $template_value = $post_meta_templates[$post_meta_index];
  1737.                                         $affiliate = $this->scrape_url_shorten($url);
  1738.                                         $affiliate = base64_encode($affiliate);
  1739.                                         $value = str_replace("[scrape_value]", $value, $template_value);
  1740.                                         if(class_exists('TS_Options')) {
  1741.                                                 if(function_exists('wp_date')) {                                      
  1742.                                                         $value = str_replace("[scrape_date]", $save_post_date_jalali, $value);
  1743.                                                 }
  1744.                                         } else {
  1745.                                                 $value = str_replace("[scrape_date]", $post_date, $value);
  1746.                                         }
  1747.                                         $value = str_replace("[scrape_url]", $url, $value);
  1748.                                         $value = str_replace("[affiliate]", $affiliate, $value);
  1749.                                        
  1750.                                         preg_match_all('/\[scrape_meta name="([^"]*)"\]/', $value, $matches);
  1751.                                        
  1752.                                         $full_matches = $matches[0];
  1753.                                         $name_matches = $matches[1];
  1754.                                         if (!empty($full_matches)) {
  1755.                                                 $combined = array_combine($name_matches, $full_matches);
  1756.                                                
  1757.                                                 foreach ($combined as $meta_name => $template_string) {
  1758.                                                         $val = $meta_input[$meta_name];
  1759.                                                         $value = str_replace($template_string, $val, $value);
  1760.                                                 }
  1761.                                         }
  1762.                                        
  1763.                                         if (preg_match('/calc\((.*)\)/isu', $value, $matches)) {
  1764.                                                 $full_text = $matches[0];
  1765.                                                 $text = $matches[1];
  1766.                                                 $calculated = $this->template_calculator($text);
  1767.                                                 $value = str_replace($full_text, $calculated, $value);
  1768.                                         }
  1769.                                        
  1770.                                         if (preg_match('/\/([a-zA-Z0-9]{10})(?:[\/?]|$)/', $url, $matches)) {
  1771.                                                 $value = str_replace("[scrape_asin]", $matches[1], $value);
  1772.                                         }
  1773.                                        
  1774.                                 }
  1775.                                
  1776.                                 $meta_input[$key] = $value;
  1777.                                 $post_meta_index++;
  1778.                                
  1779.                                 $this->write_log("final meta for " . $key . " is " . $value);
  1780.                         }
  1781.                        
  1782.                         if ($woo_active && $post_type == 'product') {
  1783.                                 if (empty($meta_input['_price'])) {
  1784.                                         if (!empty($meta_input['_sale_price']) || !empty($meta_input['_regular_price'])) {
  1785.                                                 $meta_input['_price'] = !empty($meta_input['_sale_price']) ? $meta_input['_sale_price'] : $meta_input['_regular_price'];
  1786.                                         }
  1787.                                 }
  1788.                                 if (empty($meta_input['_visibility'])) {
  1789.                                         $meta_input['_visibility'] = 'visible';
  1790.                                 }
  1791.                                 if (empty($meta_input['_manage_stock'])) {
  1792.                                         $meta_input['_manage_stock'] = 'no';
  1793.                                         $meta_input['_stock_status'] = 'instock';
  1794.                                 }
  1795.                                 if (empty($meta_input['total_sales'])) {
  1796.                                         $meta_input['total_sales'] = 0;
  1797.                                 }
  1798.                 if(empty($meta_input['_stock']) && empty($meta_input['_regular_price']) && empty($meta_input['_price'])) {
  1799.                     $meta_input['_manage_stock'] = 'no';
  1800.                     $meta_input['_stock_status'] = 'outofstock';
  1801.                 }                              
  1802.                                 if(!empty($meta_input['_product_attributes']) && !empty($meta_input['_ts_meta_size']) && empty($meta_input['_ts_meta_color'])) {
  1803.                                         $meta_attributes = $meta_input['_product_attributes'];
  1804.                                         $meta_box = $meta_input['_ts_meta_size'];
  1805.                                         $meta_box = preg_match_all('/(?<=>)
  1806. *([^<]+)/', $meta_box, $matches);
  1807.                                         $meta_box = array_filter(array_map('trim', $matches[1]));
  1808.                                         $meta_box = array_unique($meta_box);
  1809.                                         $product_attributes = array($meta_attributes => $meta_box);
  1810.                                 }
  1811.                                 if(!empty($meta_input['_product_attributes']) && empty($meta_input['_ts_meta_size']) && !empty($meta_input['_ts_meta_color'])) {
  1812.                                         $meta_attributes = $meta_input['_product_attributes'];
  1813.                                         $meta_box = $meta_input['_ts_meta_color'];
  1814.                                         $meta_box = preg_match_all('/(?<=>)
  1815. *([^<]+)/', $meta_box, $matches);
  1816.                                         $meta_box = array_filter(array_map('trim', $matches[1]));
  1817.                                         $meta_box = array_unique($meta_box);
  1818.                                         $meta_box = array_values($meta_box);
  1819.                                         $product_attributes = array($meta_attributes => $meta_box);
  1820.                                 }
  1821.                                 //$product_attributes = array_values($product_attributes);
  1822.                                 if(is_array($meta_box) && !empty($meta_box)) {
  1823.                                         if(!empty($meta_input['_ts_meta_size'])) {
  1824.                                                 $meta_input['_ts_meta_size'] = __('The value received was successfully recorded!', 'ol-scrapes');
  1825.                                         }
  1826.                                         if(!empty($meta_input['_ts_meta_color'])) {
  1827.                                                 $meta_input['_ts_meta_color'] = __('The value received was successfully recorded!', 'ol-scrapes');
  1828.                                         }
  1829.                                 } elseif(!empty($meta_input['_ts_meta_size']) && empty($meta_input['_product_attributes'])) {
  1830.                                         $meta_input['_ts_meta_size'] = __('The value received failed!', 'ol-scrapes');
  1831.                                 } elseif(!empty($meta_input['_ts_meta_color']) && empty($meta_input['_product_attributes'])) {
  1832.                                         $meta_input['_ts_meta_color'] = __('The value received failed!', 'ol-scrapes');
  1833.  
  1834.                                 } elseif(!empty($meta_input['_product_attributes']) && !empty($meta_input['_ts_meta_size']) && !empty($meta_input['_ts_meta_color'])) {
  1835.                                         $meta_input['_ts_meta_size'] = __('At present, both color and size are not received at the same time!', 'ol-scrapes');
  1836.                                         $meta_input['_ts_meta_color'] = __('At present, both color and size are not received at the same time!', 'ol-scrapes');
  1837.                                 } else {
  1838.                                         if(!empty($meta_input['_ts_meta_size'])) {
  1839.                                                 $meta_input['_ts_meta_size'] = __('The value received failed!', 'ol-scrapes');
  1840.                                         }
  1841.                                         if(!empty($meta_input['_ts_meta_color'])) {
  1842.                                                 $meta_input['_ts_meta_color'] = __('The value received failed!', 'ol-scrapes');
  1843.                                         }
  1844.                                 }                              
  1845.                         }
  1846.                        
  1847.                         $post_title = $this->trimmed_templated_value('scrape_title', $meta_vals, $xpath, $post_date, $save_post_date_jalali, $url, $meta_input, $rss_item);
  1848.                         $this->write_log($post_title);
  1849.                        
  1850.                         $post_content_type = $meta_vals['scrape_content_type'][0];
  1851.                        
  1852.                         if ($post_content_type == 'auto') {
  1853.                                 $post_content = $this->convert_readable_html($body_preg);
  1854.                                 $original_html_content = $post_content;
  1855.                                 if ($enable_spin) {
  1856.                                     $post_content = $this->spin_content_with_thebestspinner($spin_email, $spin_password, $post_content);
  1857.                 }
  1858.                                 if ($enable_translate) {
  1859.                                         if (class_exists('TS_Translate')) {
  1860.                                             $post_content = TS_Translate::translate($source_language, $target_language, $post_content);
  1861.                                                 $post_content = $this->ordered_html_tag($post_content);
  1862.                                     }
  1863.                                 }                              
  1864.                                 $post_content = $this->convert_html_links($post_content, $url, $html_base_url);
  1865.                                
  1866.                                 if($enable_translate) {
  1867.                                         $post_content = $this->replace_img_org_to_translate($post_content, $original_html_content);
  1868.                                 }                              
  1869.                                 if (!empty($meta_vals['scrape_data_src_images'][0])) {
  1870.                                         $post_content = $this->fix_image_link_content($post_content, $original_html_content);
  1871.                                 }
  1872.                                 if(!empty($meta_vals['scrape_delete_all_links'][0])) {
  1873.                                         $post_content = preg_replace("/<\/?a(|\s+[^>]+)>/", '', $post_content);
  1874.                                 }
  1875.                                
  1876.                                 if (!empty($meta_vals['scrape_content_regex_finds'])) {
  1877.                                         $regex_finds = unserialize($meta_vals['scrape_content_regex_finds'][0]);
  1878.                                         $regex_replaces = unserialize($meta_vals['scrape_content_regex_replaces'][0]);
  1879.                                         $combined = array_combine($regex_finds, $regex_replaces);
  1880.                                         foreach ($combined as $regex => $replace) {
  1881.                                                
  1882.                                                 $this->write_log("content regex $regex");
  1883.                                                 $this->write_log("content replace $replace");
  1884.                                                
  1885.                                                 $this->write_log("regex before content");
  1886.                                                 $this->write_log($post_content);
  1887.                                                 $post_content = preg_replace("/" . str_replace("/", "\/", $regex) . "/isu", $replace, $post_content);
  1888.                                                 $this->write_log("regex after content");
  1889.                                                 $this->write_log($post_content);
  1890.                                         }
  1891.                                 }
  1892.                                                                
  1893.                                 if (empty($meta_vals['scrape_allowhtml'][0])) {
  1894.                                         $post_content = wp_strip_all_tags($post_content);
  1895.                                 }
  1896.                         } else {
  1897.                                 if ($post_content_type == 'xpath') {
  1898.                                         $node = $xpath->query($meta_vals['scrape_content'][0]);
  1899.                                         if ($node->length) {
  1900.                                                 $node = $node->item(0);
  1901.                                                 $post_content = $node->ownerDocument->saveXML($node);
  1902.                                                 $original_html_content = $post_content;
  1903.                                                 if ($enable_spin) {
  1904.                                                     $post_content = $this->spin_content_with_thebestspinner($spin_email, $spin_password, $post_content);
  1905.                         }
  1906.                                                 if ($enable_translate) {
  1907.                                                         if (class_exists('TS_Translate')) {
  1908.                                                             $post_content = TS_Translate::translate($source_language, $target_language, $post_content);
  1909.                                                                 $post_content = $this->ordered_html_tag($post_content);
  1910.                                                         }
  1911.                                                 }
  1912.                                                 $post_content = $this->convert_html_links($post_content, $url, $html_base_url);
  1913.                                                
  1914.                                                 if($enable_translate) {
  1915.                                                         $post_content = $this->replace_img_org_to_translate($post_content, $original_html_content);
  1916.                                                 }                              
  1917.                                                 if (!empty($meta_vals['scrape_data_src_images'][0])) {
  1918.                                                         $post_content = $this->fix_image_link_content($post_content, $original_html_content);
  1919.                                                 }
  1920.                                                 if(!empty($meta_vals['scrape_delete_all_links'][0])) {
  1921.                                                         $post_content = preg_replace("/<\/?a(|\s+[^>]+)>/", '', $post_content);
  1922.                                                 }                                              
  1923.                                                
  1924.                                                 if (!empty($meta_vals['scrape_content_regex_finds'])) {
  1925.                                                         $regex_finds = unserialize($meta_vals['scrape_content_regex_finds'][0]);
  1926.                                                         $regex_replaces = unserialize($meta_vals['scrape_content_regex_replaces'][0]);
  1927.                                                         $combined = array_combine($regex_finds, $regex_replaces);
  1928.                                                         foreach ($combined as $regex => $replace) {
  1929.                                                                 $this->write_log("content regex $regex");
  1930.                                                                 $this->write_log("content replace $replace");
  1931.                                                                
  1932.                                                                 $this->write_log("regex before content");
  1933.                                                                 $this->write_log($post_content);
  1934.                                                                 $post_content = preg_replace("/" . str_replace("/", "\/", $regex) . "/isu", $replace, $post_content);
  1935.                                                                 $this->write_log("regex after content");
  1936.                                                                 $this->write_log($post_content);
  1937.                                                         }
  1938.                                                 }
  1939.                                                
  1940.                                                 if (empty($meta_vals['scrape_allowhtml'][0])) {
  1941.                                                         $post_content = wp_strip_all_tags($post_content);
  1942.                                                 }
  1943.                                         } else {
  1944.                                                 $this->write_log("URL: " . $url . " XPath: " . $meta_vals['scrape_content'][0] . " returned empty for post content", true);
  1945.                                                 $post_content = '';
  1946.                                                 $original_html_content = '';
  1947.                                         }
  1948.                                 } else {
  1949.                                         if ($post_content_type == 'feed') {
  1950.                                                 $post_content = $rss_item['post_content'];
  1951.                                                 if ($enable_spin) {
  1952.                                                     $post_content = $this->spin_content_with_thebestspinner($spin_email, $spin_password, $post_content);
  1953.                         }
  1954.                                                 if ($enable_translate) {
  1955.                                                         if (class_exists('TS_Translate')) {
  1956.                                                                 $post_content = TS_Translate::translate($source_language, $target_language, $post_content);
  1957.                                                                 $post_content = $this->ordered_html_tag($post_content);
  1958.                                                         }
  1959.                                                 }
  1960.                                                 $original_html_content = $rss_item['post_original_content'];
  1961.                                                
  1962.                                                 $post_content = $this->convert_html_links($post_content, $url, $html_base_url);
  1963.                                                 if (!empty($meta_vals['scrape_content_regex_finds'])) {
  1964.                                                         $regex_finds = unserialize($meta_vals['scrape_content_regex_finds'][0]);
  1965.                                                         $regex_replaces = unserialize($meta_vals['scrape_content_regex_replaces'][0]);
  1966.                                                         $combined = array_combine($regex_finds, $regex_replaces);
  1967.                                                         foreach ($combined as $regex => $replace) {
  1968.                                                                 $this->write_log("content regex $regex");
  1969.                                                                 $this->write_log("content replace $replace");
  1970.                                                                
  1971.                                                                 $this->write_log("regex before content");
  1972.                                                                 $this->write_log($post_content);
  1973.                                                                 $post_content = preg_replace("/" . str_replace("/", "\/", $regex) . "/isu", $replace, $post_content);
  1974.                                                                 $this->write_log("regex after content");
  1975.                                                                 $this->write_log($post_content);
  1976.                                                         }
  1977.                                                 }
  1978.                                                 if (empty($meta_vals['scrape_allowhtml'][0])) {
  1979.                                                         $post_content = wp_strip_all_tags($post_content);
  1980.                                                 }
  1981.                                                
  1982.                                         }
  1983.                                 }
  1984.                         }
  1985.                        
  1986.                         unset($body_preg);
  1987.                        
  1988.                         $post_content = trim($post_content);
  1989.                         $post_content = html_entity_decode($post_content, ENT_COMPAT, "UTF-8");
  1990.                         $post_excerpt = $this->trimmed_templated_value("scrape_excerpt", $meta_vals, $xpath, $post_date, $save_post_date_jalali, $url, $meta_input);
  1991.                         $post_author = $meta_vals['scrape_author'][0];
  1992.                         $post_status = $meta_vals['scrape_status'][0];
  1993.                         $post_category = $meta_vals['scrape_category'][0];
  1994.                         $post_category = unserialize($post_category);
  1995.                        
  1996.                         if (empty($post_category)) {
  1997.                                 $post_category = array();
  1998.                         }
  1999.                        
  2000.                         $post_tax_name = array();
  2001.                         $post_tax_value = array();
  2002.                         $post_tax_separator = array();
  2003.                         $post_tax_templates = array();
  2004.                         $post_tax_regex_finds = array();
  2005.                         $post_tax_regex_replaces = array();
  2006.                         $post_tax_regex_statuses = array();
  2007.                         $post_tax_template_statuses = array();
  2008.                        
  2009.                         if (!empty($meta_vals['scrape_categoryxpath_tax'])) {
  2010.                                 $scrape_categoryxpath_tax = unserialize($meta_vals['scrape_categoryxpath_tax'][0]);
  2011.                                 foreach ($scrape_categoryxpath_tax as $timestamp => $tax) {
  2012.                                         $post_tax_name[] = $tax["name"];
  2013.                                         $post_tax_value[] = $tax["value"];
  2014.                                         $post_tax_separator[] = $tax['separator'];
  2015.                                         $post_tax_templates[] = $tax["template"];
  2016.                                         $post_tax_regex_finds[] = isset($tax["regex_finds"]) ? $tax["regex_finds"] : array();
  2017.                                         $post_tax_regex_replaces[] = isset($tax["regex_replaces"]) ? $tax["regex_replaces"] : array();
  2018.                                         $post_tax_regex_statuses[] = $tax['regex_status'];
  2019.                                         $post_tax_template_statuses[] = $tax['template_status'];
  2020.                                 }                                      
  2021.                         }
  2022.                        
  2023.                         $post_tax_name_values = array();
  2024.                         if (!empty($post_tax_name) && !empty($post_tax_value)) {
  2025.                                 $post_tax_name_values = array_combine($post_tax_name, $post_tax_value);
  2026.                         }              
  2027.                        
  2028.                         if (!empty($meta_vals['scrape_categoryxpath_tax'])) {
  2029.                                 $post_meta_index = 0;
  2030.                                 foreach($post_tax_name_values as $tax_name => $tax_value) {
  2031.                                         $node = $xpath->query($tax_value);
  2032.                                         if ($node->length) {
  2033.                                                 if ($node->length > 1) {
  2034.                                                         $post_cat = array();
  2035.                                                         foreach ($node as $item) {
  2036.                                                                 $orig = trim($item->nodeValue);
  2037.                                                                 if ($enable_spin) {
  2038.                                                                         $orig =  $this->spin_content_with_thebestspinner($spin_email, $spin_password, $orig);
  2039.                                                                 }
  2040.                                                                 if ($enable_translate) {
  2041.                                                                         if (class_exists('TS_Translate')) {
  2042.                                                                                 $orig = TS_Translate::translate($source_language, $target_language, $orig);
  2043.                                                                         }
  2044.                                                                 }
  2045.                                                                 if (!empty($post_tax_regex_statuses[$post_meta_index])) {
  2046.                                                                         $combined = array_combine($post_tax_regex_finds[$post_meta_index], $post_tax_regex_replaces[$post_meta_index]);
  2047.                                                                         foreach ($combined as $regex => $replace) {
  2048.                                                                                 $this->write_log('category before regex: ' . $orig);
  2049.                                                                                 $orig = preg_replace("/" . str_replace("/", "\/", $regex) . "/isu", $replace, $orig);
  2050.                                                                                 $this->write_log('category after regex: ' . $orig);
  2051.                                                                         }
  2052.                                                                 }
  2053.                                                                 $post_cat[] = $orig;
  2054.                                                         }
  2055.                                                 } else {
  2056.                                                         $post_cat = $node->item(0)->nodeValue;
  2057.                                                         if ($enable_spin) {
  2058.                                                                 $post_cat = $this->spin_content_with_thebestspinner($spin_email, $spin_password, $post_cat);
  2059.                                                         }
  2060.                                                         if ($enable_translate) {
  2061.                                                                 if (class_exists('TS_Translate')) {
  2062.                                                                         $post_cat = TS_Translate::translate($source_language, $target_language, $post_cat);
  2063.                                                                 }
  2064.                                                         }
  2065.                                                         if (!empty($post_tax_regex_statuses[$post_meta_index])) {
  2066.                                                                 $combined = array_combine($post_tax_regex_finds[$post_meta_index], $post_tax_regex_replaces[$post_meta_index]);
  2067.                                                                 foreach ($combined as $regex => $replace) {
  2068.                                                                         $this->write_log('category before regex: ' . $post_cat);
  2069.                                                                         $post_cat = preg_replace("/" . str_replace("/", "\/", $regex) . "/isu", $replace, $post_cat);
  2070.                                                                         $this->write_log('category after regex: ' . $post_cat);
  2071.                                                                 }                                                              
  2072.                                                         }
  2073.                                                 }
  2074.                                                 if (!empty($post_tax_template_statuses[$post_meta_index])) {
  2075.                                                         $template_value = $post_tax_templates[$post_meta_index];
  2076.                                                         $post_cat = str_replace("[scrape_value]", $post_cat, $template_value);             
  2077.                                                 }                                              
  2078.                                                 $this->write_log("category : ");
  2079.                                                 $this->write_log($post_cat);
  2080.                                                
  2081.                                                 $cat_separator = $post_tax_separator[$post_meta_index];
  2082.                                                
  2083.                                                 if (!is_array($post_cat) || count($post_cat) == 0) {
  2084.                                                         if ($cat_separator != "") {
  2085.                                                                 $post_cat = str_replace(" ", ' ', $post_cat);
  2086.                                                                 $post_cats = explode($cat_separator, $post_cat);
  2087.                                                                 $post_cats = array_map("trim", $post_cats);
  2088.                                                         } else {
  2089.                                                                 $post_cats = array($post_cat);
  2090.                                                         }
  2091.                                                 } else {
  2092.                                                         $post_cats = $post_cat;
  2093.                                                 }
  2094.                                                
  2095.                                                 foreach ($post_cats as $post_cat) {
  2096.                                                         $arg_tax = $tax_name;
  2097.                                                         $cats = get_term_by('name', $post_cat, $arg_tax);
  2098.                                                        
  2099.                                                         if (empty($cats)) {
  2100.                                                                 $term_id = wp_insert_term($post_cat, $tax_name);
  2101.                                                                 if (!is_wp_error($term_id)) {
  2102.                                                                         $post_category[] = $term_id['term_id'];
  2103.                                                                         $this->write_log($post_cat . " added to categories");
  2104.                                                                 } else {
  2105.                                                                         $this->write_log("$post_cat can not be added as " . $tax_name . ": " . $term_id->get_error_message());
  2106.                                                                 }
  2107.                                                                
  2108.                                                         } else {
  2109.                                                                 $post_category[] = $cats->term_id;
  2110.                                                         }
  2111.                                                 }
  2112.                                         }
  2113.                                         $post_meta_index++;
  2114.                                 }
  2115.                         }
  2116.                        
  2117.                         $post_comment = (!empty($meta_vals['scrape_comment'][0]) ? "open" : "closed");
  2118.                        
  2119.                         if ($is_facebook_page) {
  2120.                                 $url = str_replace(array("mbasic", "story.php"), array("www", "permalink.php"), $url);
  2121.                         }
  2122.                        
  2123.                         if (!empty($meta_vals['scrape_unique_title'][0]) || !empty($meta_vals['scrape_unique_content'][0]) || !empty($meta_vals['scrape_unique_url'][0])) {
  2124.                                 $repeat_condition = false;
  2125.                                 $unique_check_sql = '';
  2126.                                 $post_id = null;
  2127.                                 $chk_title = $meta_vals['scrape_unique_title'][0];
  2128.                                 $chk_content = $meta_vals['scrape_unique_content'][0];
  2129.                                 $chk_url = $meta_vals['scrape_unique_url'][0];
  2130.                                
  2131.                                 if (empty($chk_title) && empty($chk_content) && !empty($chk_url)) {
  2132.                                         $repeat_condition = !empty($url);
  2133.                                         $unique_check_sql = $wpdb->prepare("SELECT ID " . "FROM $wpdb->posts p LEFT JOIN $wpdb->postmeta pm ON pm.post_id = p.ID " . "WHERE pm.meta_value = %s AND pm.meta_key = '_scrape_original_url' " . "      AND p.post_type = %s " . " AND p.post_status <> 'trash'", $url, $post_type);
  2134.                                         $this->write_log("Repeat check only url");
  2135.                                 }
  2136.                                 if (empty($chk_title) && !empty($chk_content) && empty($chk_url)) {
  2137.                                         $repeat_condition = !empty($original_html_content);
  2138.                                         $unique_check_sql = $wpdb->prepare("SELECT ID " . "FROM $wpdb->posts p LEFT JOIN $wpdb->postmeta pm ON pm.post_id = p.ID " . "WHERE pm.meta_value = %s AND pm.meta_key = '_scrape_original_html_content' " . "     AND p.post_type = %s " . " AND p.post_status <> 'trash'", $original_html_content, $post_type);
  2139.                                         $this->write_log("Repeat check only content");
  2140.                                 }
  2141.                                 if (empty($chk_title) && !empty($chk_content) && !empty($chk_url)) {
  2142.                                         $repeat_condition = !empty($original_html_content) && !empty($url);
  2143.                                         $unique_check_sql = $wpdb->prepare("SELECT ID " . "FROM $wpdb->posts p LEFT JOIN $wpdb->postmeta pm1 ON pm.post_id = p.ID " . " LEFT JOIN $wpdb->postmeta pm2 ON pm2.post_id = p.ID " . "WHERE pm1.meta_value = %s AND pm1.meta_key = '_scrape_original_html_content' " . " AND pm2.meta_value = %s AND pm2.meta_key = '_scrape_original_url' " . "  AND p.post_type = %s " . " AND p.post_status <> 'trash'", $original_html_content, $url, $post_type);
  2144.                                         $this->write_log("Repeat check content and url");
  2145.                                 }
  2146.                                 if (!empty($chk_title) && empty($chk_content) && empty($chk_url)) {
  2147.                                         $repeat_condition = !empty($post_title);
  2148.                                         $unique_check_sql = $wpdb->prepare("SELECT ID " . "FROM $wpdb->posts p " . "WHERE p.post_title = %s " . "      AND p.post_type = %s " . " AND p.post_status <> 'trash'", $post_title, $post_type);
  2149.                                         $this->write_log("Repeat check only title:" . $post_title);
  2150.                                 }
  2151.                                 if (!empty($chk_title) && empty($chk_content) && !empty($chk_url)) {
  2152.                                         $repeat_condition = !empty($post_title) && !empty($url);
  2153.                                         $unique_check_sql = $wpdb->prepare("SELECT ID " . "FROM $wpdb->posts p LEFT JOIN $wpdb->postmeta pm ON pm.post_id = p.ID " . "WHERE p.post_title = %s " . " AND pm.meta_value = %s AND pm.meta_key = '_scrape_original_url'" . " AND p.post_type = %s " . "   AND p.post_status <> 'trash'", $post_title, $url, $post_type);
  2154.                                         $this->write_log("Repeat check title and url");
  2155.                                 }
  2156.                                 if (!empty($chk_title) && !empty($chk_content) && empty($chk_url)) {
  2157.                                         $repeat_condition = !empty($post_title) && !empty($original_html_content);
  2158.                                         $unique_check_sql = $wpdb->prepare("SELECT ID " . "FROM $wpdb->posts p LEFT JOIN $wpdb->postmeta pm ON pm.post_id = p.ID " . "WHERE p.post_title = %s " . " AND pm.meta_value = %s AND pm.meta_key = '_scrape_original_html_content'" . " AND p.post_type = %s " . "  AND p.post_status <> 'trash'", $post_title, $original_html_content, $post_type);
  2159.                                         $this->write_log("Repeat check title and content");
  2160.                                 }
  2161.                                 if (!empty($chk_title) && !empty($chk_content) && !empty($chk_url)) {
  2162.                                         $repeat_condition = !empty($post_title) && !empty($original_html_content) && !empty($url);
  2163.                                         $unique_check_sql = $wpdb->prepare("SELECT ID " . "FROM $wpdb->posts p LEFT JOIN $wpdb->postmeta pm1 ON pm1.post_id = p.ID " . " LEFT JOIN $wpdb->postmeta pm2 ON pm2.post_id = p.ID " . "WHERE p.post_title = %s " . " AND pm1.meta_value = %s AND pm1.meta_key = '_scrape_original_html_content'" . " AND pm2.meta_value = %s AND pm2.meta_key = '_scrape_original_url'" . "  AND p.post_type = %s " . " AND p.post_status <> 'trash'", $post_title, $original_html_content, $url, $post_type);
  2164.                                         $this->write_log("Repeat check title content and url");
  2165.                                 }
  2166.                                
  2167.                                 $post_id = $wpdb->get_var($unique_check_sql);
  2168.                                
  2169.                                 if (!empty($post_id)) {
  2170.                                         $ID = $post_id;
  2171.                                        
  2172.                                         if ($repeat_condition) {
  2173.                                                 $repeat_count++;
  2174.                                         }
  2175.                                        
  2176.                                         if ($meta_vals['scrape_on_unique'][0] == "skip") {
  2177.                                                 return;
  2178.                                         }
  2179.                                         $meta_vals_of_post = get_post_meta($ID);
  2180.                                         foreach ($meta_vals_of_post as $key => $value) {
  2181.                                                 delete_post_meta($ID, $key);
  2182.                                         }
  2183.                                 }
  2184.                         }
  2185.                        
  2186.                         if ($meta_vals['scrape_tags_type'][0] == 'xpath' && !empty($meta_vals['scrape_tags'][0])) {
  2187.                                 $node = $xpath->query($meta_vals['scrape_tags'][0]);
  2188.                                 $this->write_log("tag length: " . $node->length);
  2189.                                 if ($node->length) {
  2190.                                         if ($node->length > 1) {
  2191.                                                 $post_tags = array();
  2192.                                                 foreach ($node as $item) {
  2193.                                                         $orig = trim($item->nodeValue);
  2194.                             if ($enable_spin) {
  2195.                                 $orig = $this->spin_content_with_thebestspinner($spin_email, $spin_password, $orig);
  2196.                             }
  2197.                                                         if ($enable_translate) {
  2198.                                                                 if (class_exists('TS_Translate')) {
  2199.                                                                     $orig = TS_Translate::translate($source_language, $target_language, $orig);
  2200.                                                                 }
  2201.                                                         }
  2202.                                                         if (!empty($meta_vals['scrape_tags_regex_status'][0])) {
  2203.                                                                 $regex_finds = unserialize($meta_vals['scrape_tags_regex_finds'][0]);
  2204.                                                                 $regex_replaces = unserialize($meta_vals['scrape_tags_regex_replaces'][0]);
  2205.                                                                 $combined = array_combine($regex_finds, $regex_replaces);
  2206.                                                                 foreach ($combined as $regex => $replace) {
  2207.                                                                         $orig = preg_replace("/" . str_replace("/", "\/", $regex) . "/isu", $replace, $orig);
  2208.                                                                 }
  2209.                                                         }
  2210.                                                         $post_tags[] = $orig;
  2211.                                                 }
  2212.                                         } else {
  2213.                                                 $post_tags = $node->item(0)->nodeValue;
  2214.                         if ($enable_spin) {
  2215.                             $post_tags = $this->spin_content_with_thebestspinner($spin_email, $spin_password, $post_tags);
  2216.                         }
  2217.                                                 if ($enable_translate) {
  2218.                                                         if (class_exists('TS_Translate')) {
  2219.                                                             $post_tags = TS_Translate::translate($source_language, $target_language, $post_tags);
  2220.                                                         }
  2221.                                                 }
  2222.                                                 if (!empty($meta_vals['scrape_tags_regex_status'][0])) {
  2223.                                                         $regex_finds = unserialize($meta_vals['scrape_tags_regex_finds'][0]);
  2224.                                                         $regex_replaces = unserialize($meta_vals['scrape_tags_regex_replaces'][0]);
  2225.                                                         $combined = array_combine($regex_finds, $regex_replaces);
  2226.                                                         foreach ($combined as $regex => $replace) {
  2227.                                                                 $post_tags = preg_replace("/" . str_replace("/", "\/", $regex) . "/isu", $replace, $post_tags);
  2228.                                                         }
  2229.                                                 }
  2230.                                         }
  2231.                                         $this->write_log("tags : ");
  2232.                                         $this->write_log($post_tags);
  2233.                                 } else {
  2234.                                         $this->write_log("URL: " . $url . " XPath: " . $meta_vals['scrape_tags'][0] . " returned empty for post tags", true);
  2235.                                         $post_tags = array();
  2236.                                 }
  2237.                         } else {
  2238.                                 if (!empty($meta_vals['scrape_tags_custom'][0])) {
  2239.                                         $post_tags = $meta_vals['scrape_tags_custom'][0];
  2240.                                 } else {
  2241.                                         $post_tags = array();
  2242.                                 }
  2243.                         }
  2244.                        
  2245.                         if (!is_array($post_tags) || count($post_tags) == 0) {
  2246.                                 $tag_separator = "";
  2247.                                 if (isset($meta_vals['scrape_tags_separator'])) {
  2248.                                         $tag_separator = $meta_vals['scrape_tags_separator'][0];
  2249.                                         if ($tag_separator != "" && !empty($post_tags)) {
  2250.                                                 $post_tags = str_replace(" ", ' ', $post_tags);
  2251.                                                 $post_tags = explode($tag_separator, $post_tags);
  2252.                                                 $post_tags = array_map("trim", $post_tags);
  2253.                                         }
  2254.                                 }
  2255.                         }
  2256.                        
  2257.                         $i_key = 0;
  2258.                         $i_dont_update = '';
  2259.                         $i_allowhtml = '';
  2260.                         foreach($post_meta_name_values as $meta_key => $name_vals) {
  2261.                                 if(!empty($post_meta_dont_updates[$i_key]) && !empty($meta_vals_of_post[$meta_key])) {
  2262.                                         $meta_input[$meta_key] = $meta_vals_of_post[$meta_key][0];
  2263.                                 }
  2264.                                 if($meta_key == '_product_image_gallery' && !empty($post_meta_dont_updates[$i_key])) {
  2265.                                         $i_dont_update = $i_key;
  2266.                                 }
  2267.                                 if($meta_key == '_product_image_gallery' && !empty($post_meta_allowhtmls[$i_key])) {
  2268.                                         $i_allowhtml = $i_key;
  2269.                                 }
  2270.                                 $i_key++;
  2271.                         }
  2272.                        
  2273.                         if(!empty($meta_vals['scrape_dont_update'][0])) {
  2274.                                 $available_post = get_post( $ID );
  2275.                                 if(!empty($available_post)) {
  2276.                                         $post_content = $available_post->post_content;
  2277.                                 }                              
  2278.                         }
  2279.                        
  2280.                         if(!empty($meta_vals['scrape_change_status'][0])) {
  2281.                                 if(get_post_status( $ID ) == 'publish') {
  2282.                                         $post_status = 'publish';
  2283.                                 }
  2284.                         }
  2285.                        
  2286.                         $post_arr = array(
  2287.                                 'ID' => $ID,
  2288.                 'post_author' => $post_author,
  2289.                 'post_date' => date("Y-m-d H:i:s", strtotime($post_date)),
  2290.                 'post_content' => trim($post_content),
  2291.                 'post_title' => trim($post_title),
  2292.                 'post_status' => $post_status,
  2293.                 'comment_status' => $post_comment,
  2294.                 'meta_input' => $meta_input,
  2295.                 'post_type' => $post_type,
  2296.                 'tags_input' => $post_tags,
  2297.                 'filter' => false,
  2298.                 'ping_status' => 'closed',
  2299.                 'post_excerpt' => $post_excerpt
  2300.                         );
  2301.  
  2302.             $featured_image_type = $meta_vals['scrape_featured_type'][0];
  2303.             if ($featured_image_type == 'xpath' && !empty($meta_vals['scrape_featured'][0])) {
  2304.                 $node = $xpath->query($meta_vals['scrape_featured'][0]);
  2305.                 if ($node->length) {
  2306.                     $post_featured_img = trim($node->item(0)->nodeValue);
  2307.                     if ($is_amazon) {
  2308.                         $data_old_hires = trim($node->item(0)->parentNode->getAttribute('data-old-hires'));
  2309.                         if (!empty($data_old_hires)) {
  2310.                             $post_featured_img = preg_replace("/\._.*_/", "", $data_old_hires);
  2311.                         } else {
  2312.                             $data_a_dynamic_image = trim($node->item(0)->parentNode->getAttribute('data-a-dynamic-image'));
  2313.                             if (!empty($data_a_dynamic_image)) {
  2314.                                 $post_featured_img = array_keys(json_decode($data_a_dynamic_image, true));
  2315.                                 $post_featured_img = end($post_featured_img);
  2316.                             }
  2317.                         }
  2318.                     }
  2319.                     $post_featured_img = $this->create_absolute_url($post_featured_img, $url, $html_base_url);
  2320.                     $post_featured_image_url = $post_featured_img;
  2321.                 } else {
  2322.                     $post_featured_image_url = null;
  2323.                 }
  2324.             } else {
  2325.                 if ($featured_image_type == 'feed') {
  2326.                     $post_featured_image_url = $rss_item['featured_image'];
  2327.                 } else {
  2328.                     if ($featured_image_type == 'gallery') {
  2329.                         $post_featured_image_url = wp_get_attachment_url($meta_vals['scrape_featured_gallery'][0]);
  2330.                     }
  2331.                 }
  2332.             }
  2333.  
  2334.             $scrape_featured_regex_status = $meta_vals['scrape_featured_regex_status'][0];
  2335.             if (!empty($scrape_featured_regex_status)) {
  2336.                 $scrape_featured_regex_finds = unserialize($meta_vals['scrape_featured_regex_finds'][0]);
  2337.                 $scrape_featured_regex_replaces = unserialize($meta_vals['scrape_featured_regex_replaces'][0]);
  2338.  
  2339.                 if (!empty($scrape_featured_regex_finds)) {
  2340.                     $regex_combined = array_combine(
  2341.                         $scrape_featured_regex_finds,
  2342.                         $scrape_featured_regex_replaces
  2343.                     );
  2344.  
  2345.                     foreach ($combined as $regex => $replace) {
  2346.                         $post_date = preg_replace("/" . str_replace("/", "\/", $regex) . "/isu", $replace, $post_date);
  2347.                     }
  2348.                     $this->write_log("date after regex:" . $post_date);
  2349.  
  2350.                     foreach ($regex_combined as $regex => $replace) {
  2351.                         $post_featured_image_url = preg_replace("/" . str_replace("/", "\/", $regex) . "/isu", $replace, $post_featured_image_url);
  2352.                         $this->write_log("featured image url after regex:" . $post_featured_image_url);
  2353.                     }
  2354.                 }
  2355.             }
  2356.  
  2357.             $scrape_featured_template_status = $meta_vals['scrape_featured_template_status'][0];
  2358.             if (!empty($scrape_featured_template_status)) {
  2359.                 $template_value = $meta_vals['scrape_featured_template'][0];
  2360.                 $post_featured_image_url = str_replace("[scrape_value]", $post_featured_image_url, $template_value);
  2361.                                 if(class_exists('TS_Options')) {
  2362.                                         if(function_exists('wp_date')) {                
  2363.                                                 $post_featured_image_url = str_replace("[scrape_date]", $save_post_date_jalali, $post_featured_image_url);
  2364.                                         }
  2365.                                 } else {
  2366.                                         $post_featured_image_url = str_replace("[scrape_date]", $post_date, $post_featured_image_url);
  2367.                                 }
  2368.                 $post_featured_image_url = str_replace("[scrape_url]", $url, $post_featured_image_url);
  2369.  
  2370.                 preg_match_all('/\[scrape_meta name="([^"]*)"\]/', $post_featured_image_url, $matches);
  2371.  
  2372.                 $full_matches = $matches[0];
  2373.                 $name_matches = $matches[1];
  2374.                 if (!empty($full_matches)) {
  2375.                     $combined = array_combine($name_matches, $full_matches);
  2376.  
  2377.                     foreach ($combined as $meta_name => $template_string) {
  2378.                         $val = $meta_input[$meta_name];
  2379.                         $post_featured_image_url = str_replace($template_string, $val, $post_featured_image_url);
  2380.                     }
  2381.                 }
  2382.             }
  2383.  
  2384.  
  2385.             $scrape_filters_fields = $meta_vals['scrape_filters_fields'][0];
  2386.  
  2387.             if ($scrape_filters_fields != '') {
  2388.  
  2389.                 $scrape_filters_fields = unserialize($meta_vals['scrape_filters_fields'][0]);
  2390.                 $scrape_filters_operators = unserialize($meta_vals['scrape_filters_operators'][0]);
  2391.                 $scrape_filters_values = unserialize($meta_vals['scrape_filters_values'][0]);
  2392.  
  2393.                 for ($i = 0; $i < count($scrape_filters_fields); $i++) {
  2394.  
  2395.                     $field = $scrape_filters_fields[$i];
  2396.                     $operator = $scrape_filters_operators[$i];
  2397.                     $value = $scrape_filters_values[$i];
  2398.  
  2399.  
  2400.                     if ($field == 'title') {
  2401.                         $actual_value = $post_arr['post_title'];
  2402.                     } else if ($field == 'content') {
  2403.                         $actual_value = $post_arr['post_content'];
  2404.                     } else if ($field == 'excerpt') {
  2405.                         $actual_value = $post_arr['post_excerpt'];
  2406.                     } else if ($field == 'featured_image') {
  2407.                         $actual_value = $post_featured_image_url;
  2408.                     } else if ($field == 'date') {
  2409.                         $actual_value = $save_post_date_jalali;
  2410.                     } else if (strpos($field, 'custom_field_') === 0) {
  2411.                         $exploded = explode('_', $field);
  2412.                         $exploded = end($exploded);
  2413.                         $actual_value = $post_arr['meta_input'][$scrape_custom_fields[$exploded]['name']];
  2414.                     }
  2415.  
  2416.                     if ($operator == 'not_exists') {
  2417.                         if (is_null($actual_value)) {
  2418.                             $this->write_log('post filter applied: ' . var_export($actual_value, true) . ' operator : ' . $operator . ' ' . $value, 'warning');
  2419.                             return;
  2420.                         }
  2421.                     }
  2422.  
  2423.                     if ($operator == 'exists') {
  2424.                         if (!is_null($actual_value)) {
  2425.                             $this->write_log('post filter applied: ' . $actual_value . ' operator : ' . $operator . ' ' . $value, 'warning');
  2426.                             return;
  2427.                         }
  2428.                     }
  2429.                     if ($operator == 'does_not_contain') {
  2430.                         if (is_string($actual_value)) {
  2431.                             if (stripos($actual_value, $value) === false) {
  2432.                                 $this->write_log('post filter applied: ' . $actual_value . ' operator : ' . $operator . ' ' . $value, 'warning');
  2433.                                 return;
  2434.                             }
  2435.                         } else if (is_array($actual_value)) {
  2436.                             if (!in_array($value, $actual_value)) {
  2437.                                 $this->write_log('post filter applied: ' . var_export($actual_value, true) . ' operator : ' . $operator . ' ' . $value, 'warning');
  2438.                                 return;
  2439.                             }
  2440.                         }
  2441.                     }
  2442.  
  2443.                     if ($operator == 'not_equal_to') {
  2444.                         if ($actual_value != $value) {
  2445.                             $this->write_log('post filter applied: ' . $actual_value . ' operator : ' . $operator . ' ' . $value, 'warning');
  2446.                             return;
  2447.                         }
  2448.                     }
  2449.  
  2450.                     if ($operator == 'contains') {
  2451.                         if (is_string($actual_value)) {
  2452.                             if (stripos($actual_value, $value) !== false) {
  2453.                                 $this->write_log('post filter applied: ' . $actual_value . ' operator : ' . $operator . ' ' . $value, 'warning');
  2454.                                 return;
  2455.                             }
  2456.                         } else if (is_array($actual_value)) {
  2457.                             if (in_array($value, $actual_value)) {
  2458.                                 $this->write_log('post filter applied: ' . var_export($actual_value, true) . ' operator : ' . $operator . ' ' . $value, 'warning');
  2459.                                 return;
  2460.                             }
  2461.                         }
  2462.                     }
  2463.  
  2464.                     if ($operator == 'equal_to') {
  2465.                         if ($actual_value == $value) {
  2466.                             $this->write_log('post filter applied: ' . $actual_value . ' operator : ' . $operator . ' ' . $value, 'warning');
  2467.                             return;
  2468.                         }
  2469.                     }
  2470.  
  2471.                     if ($operator == 'less_than') {
  2472.                         if ($actual_value < $value) {
  2473.                             $this->write_log('post filter applied: ' . $actual_value . ' operator : ' . $operator . ' ' . $value, 'warning');
  2474.                             return;
  2475.                         }
  2476.                     }
  2477.  
  2478.                     if ($operator == 'greater_than') {
  2479.                         if ($actual_value > $value) {
  2480.                             $this->write_log('post filter applied: ' . $actual_value . ' operator : ' . $operator . ' ' . $value, 'warning');
  2481.                             return;
  2482.                         }
  2483.                     }
  2484.                 }
  2485.             }
  2486.                        
  2487.                         $post_category = array_map('intval', $post_category);
  2488.                         /*update_post_category(array(
  2489.                                 'ID' => $ID, 'post_category' => $post_category
  2490.                         ));*/
  2491.                         if ($post_type == 'post') {
  2492.                                 $post_arr['post_category'] = $post_category;
  2493.                         }
  2494.                         kses_remove_filters();
  2495.                         $new_id = wp_insert_post($post_arr, true);
  2496.                         kses_init_filters();
  2497.                        
  2498.                         if (is_wp_error($new_id)) {
  2499.                                 $this->write_log("error occurred in wordpress post entry: " . $new_id->get_error_message() . " " . $new_id->get_error_code(), true);
  2500.                                 return;
  2501.                         }                      
  2502.                         update_post_meta($new_id, '_scrape_task_id', $meta_vals['scrape_task_id'][0]);
  2503.                        
  2504.                         update_post_meta($new_id, '_scrape_original_url', $url);
  2505.                         update_post_meta($new_id, '_scrape_original_html_content', $original_html_content);
  2506.                        
  2507.                         $cmd = $ID ? "updated" : "inserted";
  2508.                         $this->write_log("post $cmd with id: " . $new_id);
  2509.                        
  2510.                         $product_type = $meta_vals['scrape_product_type'][0];
  2511.                         $key_type = count($post_category);
  2512.                         if(empty($key_type)) {
  2513.                                 $key_type = 0;
  2514.                         }
  2515.                        
  2516.                         if(!empty($meta_vals['scrape_product_variable'][0]) && !empty($product_type) && $product_type == 4) {
  2517.                                
  2518.                                 if(empty($meta_box) && $woo_active && $post_type == 'product') {                                
  2519.                                         $product_type = 2;                                                                                                                                   
  2520.                                 }                                                                                                      
  2521.                         }
  2522.                         $post_category[$key_type] = $product_type;
  2523.                         $post_category = array_map('intval', $post_category);                       
  2524.                        
  2525.                         $tax_term_array = array();
  2526.                         foreach ($post_category as $cat_id) {
  2527.                                 $term = get_term($cat_id);
  2528.                                 $term_tax = $term->taxonomy;
  2529.                                 $tax_term_array[$term_tax][] = $cat_id;
  2530.                         }
  2531.                         foreach ($tax_term_array as $tax => $terms) {
  2532.                                 wp_set_object_terms($new_id, $terms, $tax);
  2533.                         }
  2534.                        
  2535.  
  2536.                         if ($featured_image_type == 'xpath' && !empty($meta_vals['scrape_featured'][0])) {
  2537.                             if(!is_null($post_featured_image_url)) {
  2538.                                         $this->generate_featured_image($post_featured_image_url, $new_id);
  2539.                                 } else {
  2540.                                         $this->write_log("URL: " . $url . " XPath: " . $meta_vals['scrape_featured'][0] . " returned empty for thumbnail image", true);
  2541.                                 }
  2542.                         } else {
  2543.                                 if ($featured_image_type == 'feed') {
  2544.                                         $this->generate_featured_image($rss_item['featured_image'], $new_id);
  2545.                                 } else {
  2546.                                         if ($featured_image_type == 'gallery') {
  2547.                                                 set_post_thumbnail($new_id, $meta_vals['scrape_featured_gallery'][0]);
  2548.                                         }
  2549.                                 }
  2550.                         }
  2551.                        
  2552.                         if (array_key_exists('_product_image_gallery', $meta_input) && $post_type == 'product' && $woo_active) {
  2553.                                 if(empty($post_meta_dont_updates[$i_dont_update]) && empty($post_meta_allowhtmls[$i_allowhtml])) {
  2554.                                         $this->write_log('image gallery process starts for WooCommerce');
  2555.                                         $woo_img_xpath = $post_meta_values[array_search('_product_image_gallery', $post_meta_names)];
  2556.                                         $woo_img_xpath = $woo_img_xpath . "//img | " . $woo_img_xpath . "//a | " . $woo_img_xpath . "//div |" . $woo_img_xpath . "//li";
  2557.                                         $nodes = $xpath->query($woo_img_xpath);
  2558.                                         $this->write_log("Gallery images length is " . $nodes->length);
  2559.                                        
  2560.                                         $max_width = 0;
  2561.                                         $max_height = 0;
  2562.                                         $gallery_images = array();
  2563.                                         $product_gallery_ids = array();
  2564.                                         foreach ($nodes as $img) {
  2565.                                                 $post_meta_index = array_search('_product_image_gallery', $post_meta_names);
  2566.                                                 $attr = $post_meta_attributes[$post_meta_index];
  2567.                                                 if (empty($attr)) {
  2568.                                                         if ($img->nodeName == "img") {
  2569.                                                                 $attr = 'src';
  2570.                                                         } else {
  2571.                                                                 $attr = 'href';
  2572.                                                         }
  2573.                                                 }
  2574.                                                 $img_url = trim($img->getAttribute($attr));
  2575.                                                 if (!empty($post_meta_regex_statuses[$post_meta_index])) {
  2576.                                                         $regex_combined = array_combine($post_meta_regex_finds[$post_meta_index], $post_meta_regex_replaces[$post_meta_index]);
  2577.                                                         foreach ($regex_combined as $find => $replace) {
  2578.                                                                 $this->write_log("custom field value before regex $img_url");
  2579.                                                                 $img_url = preg_replace("/" . str_replace("/", "\/", $find) . "/isu", $replace, $img_url);
  2580.                                                                 $this->write_log("custom field value after regex $img_url");
  2581.                                                         }
  2582.                                                 }
  2583.                                                 $img_abs_url = $this->create_absolute_url($img_url, $url, $html_base_url);
  2584.                                                 $this->write_log($img_abs_url);
  2585.                                                 $is_base64 = false;
  2586.                                                 if (substr($img_abs_url, 0, 11) == 'data:image/') {
  2587.                                                         $array_result = getimagesizefromstring(base64_decode(substr($img_abs_url, strpos($img_abs_url, 'base64') + 7)));
  2588.                                                         $is_base64 = true;
  2589.                                                 } else {
  2590.                                                        
  2591.                                                         $args = $this->return_html_args($meta_vals);
  2592.                                                        
  2593.                                                         $image_req = wp_remote_get($img_abs_url, $args);
  2594.                                                         if (is_wp_error($image_req)) {
  2595.                                                                 $this->write_log("http error in " . $img_abs_url . " " . $image_req->get_error_message(), true);
  2596.                                                                 $array_result = false;
  2597.                                                         } else {
  2598.                                                                 $array_result = getimagesizefromstring($image_req['body']);
  2599.                                                         }
  2600.                                                        
  2601.                                                 }
  2602.                                                 if ($array_result !== false) {
  2603.                                                         $width = $array_result[0];
  2604.                                                         $height = $array_result[1];
  2605.                                                         if ($width > $max_width) {
  2606.                                                                 $max_width = $width;
  2607.                                                         }
  2608.                                                         if ($height > $max_height) {
  2609.                                                                 $max_height = $height;
  2610.                                                         }
  2611.                                                        
  2612.                                                         $gallery_images[] = array(
  2613.                                                                 'width' => $width, 'height' => $height, 'url' => $img_abs_url, 'is_base64' => $is_base64
  2614.                                                         );
  2615.                                                 } else {
  2616.                                                         $this->write_log("Image size data could not be retrieved", true);
  2617.                                                 }
  2618.                                         }
  2619.                                        
  2620.                                         $this->write_log("Max width found: " . $max_width . " Max height found: " . $max_height);
  2621.                                         foreach ($gallery_images as $gi) {
  2622.                                                 if ($gi['is_base64']) {
  2623.                                                         continue;
  2624.                                                 }
  2625.                                                 $old_url = $gi['url'];
  2626.                                                 $width = $gi['width'];
  2627.                                                 $height = $gi['height'];
  2628.                                                
  2629.                                                 $offset = 0;
  2630.                                                 $width_pos = array();
  2631.                                                
  2632.                                                 while (strpos($old_url, strval($width), $offset) !== false) {
  2633.                                                         $width_pos[] = strpos($old_url, strval($width), $offset);
  2634.                                                         $offset = strpos($old_url, strval($width), $offset) + 1;
  2635.                                                 }
  2636.                                                
  2637.                                                 $offset = 0;
  2638.                                                 $height_pos = array();
  2639.                                                
  2640.                                                 while (strpos($old_url, strval($height), $offset) !== false) {
  2641.                                                         $height_pos[] = strpos($old_url, strval($height), $offset);
  2642.                                                         $offset = strpos($old_url, strval($height), $offset) + 1;
  2643.                                                 }
  2644.                                                
  2645.                                                 $min_distance = PHP_INT_MAX;
  2646.                                                 $width_replace_pos = 0;
  2647.                                                 $height_replace_pos = 0;
  2648.                                                 foreach ($width_pos as $wr) {
  2649.                                                         foreach ($height_pos as $hr) {
  2650.                                                                 $distance = abs($wr - $hr);
  2651.                                                                 if ($distance < $min_distance && $distance != 0) {
  2652.                                                                         $min_distance = $distance;
  2653.                                                                         $width_replace_pos = $wr;
  2654.                                                                         $height_replace_pos = $hr;
  2655.                                                                 }
  2656.                                                         }
  2657.                                                 }
  2658.                                                 $min_pos = min($width_replace_pos, $height_replace_pos);
  2659.                                                 $max_pos = max($width_replace_pos, $height_replace_pos);
  2660.                                                
  2661.                                                 $new_url = "";
  2662.                                                
  2663.                                                 if ($min_pos != $max_pos) {
  2664.                                                         $this->write_log("Different pos found not square");
  2665.                                                         $new_url = substr($old_url, 0, $min_pos) . strval($max_width) . substr($old_url, $min_pos + strlen($width), $max_pos - ($min_pos + strlen($width))) . strval($max_height) . substr($old_url, $max_pos + strlen($height));
  2666.                                                 } else {
  2667.                                                         if ($min_distance == PHP_INT_MAX && strpos($old_url, strval($width)) !== false) {
  2668.                                                                 $this->write_log("Same pos found square image");
  2669.                                                                 $new_url = substr($old_url, 0, strpos($old_url, strval($width))) . strval(max($max_width, $max_height)) . substr($old_url, strpos($old_url, strval($width)) + strlen($width));
  2670.                                                         }
  2671.                                                 }
  2672.                                                
  2673.                                                 $this->write_log("Old gallery image url: " . $old_url);
  2674.                                                 $this->write_log("New gallery image url: " . $new_url);
  2675.                                                 if ($is_amazon) {
  2676.                                                         $new_url = preg_replace("/\._.*_/", "", $old_url);
  2677.                                                 }
  2678.                                                
  2679.                                                 $pgi_id = $this->generate_featured_image($new_url, $new_id, false);
  2680.                                                 if (!empty($pgi_id)) {
  2681.                                                         $product_gallery_ids[] = $pgi_id;
  2682.                                                 } else {
  2683.                                                         $pgi_id = $this->generate_featured_image($old_url, $new_id, false);
  2684.                                                         if (!empty($pgi_id)) {
  2685.                                                                 $product_gallery_ids[] = $pgi_id;
  2686.                                                         }
  2687.                                                 }
  2688.                                         }
  2689.                                 }
  2690.                                 if(!empty($post_meta_allowhtmls[$i_allowhtml]) && empty($post_meta_dont_updates[$i_dont_update])) {
  2691.                                         $gallery_images = $meta_input['_product_image_gallery'];
  2692.                                         $gallery_images = preg_match_all('/data-high-res-src="([^"]*)"/', $gallery_images, $matches);
  2693.                                         $gallery_images = array_unique($matches[1]);
  2694.                                         foreach($gallery_images as $old_url) {
  2695.                                                 $pgi_id = $this->generate_featured_image($old_url, $new_id, false);
  2696.                                                 if (!empty($pgi_id)) {
  2697.                                                         $product_gallery_ids[] = $pgi_id;
  2698.                                                 }                                              
  2699.                                         }
  2700.                                 } elseif(!empty($post_meta_allowhtmls[$i_allowhtml]) && !empty($post_meta_dont_updates[$i_dont_update]) && empty($meta_vals_of_post['_product_image_gallery'][0])) {
  2701.                                         $gallery_images = $meta_input['_product_image_gallery'];
  2702.                                         $gallery_images = preg_match_all('/data-high-res-src="([^"]*)"/', $gallery_images, $matches);
  2703.                                         $gallery_images = array_unique($matches[1]);
  2704.                                         foreach($gallery_images as $old_url) {
  2705.                                                 $pgi_id = $this->generate_featured_image($old_url, $new_id, false);
  2706.                                                 if (!empty($pgi_id)) {
  2707.                                                         $product_gallery_ids[] = $pgi_id;
  2708.                                                 }                                              
  2709.                                         }                                      
  2710.                                 } elseif(!empty($post_meta_dont_updates[$i_dont_update]) && !empty($meta_vals_of_post['_product_image_gallery'][0])) {
  2711.                                         $attachment_ids = $meta_vals_of_post['_product_image_gallery'][0];
  2712.                                         $product_gallery_ids = explode(',', $attachment_ids);                                       
  2713.                                 }
  2714.                                 update_post_meta($new_id, '_product_image_gallery', implode(",", array_unique($product_gallery_ids)));
  2715.                         }
  2716.  
  2717.                         if (array_key_exists('_product_attributes', $meta_input) && $post_type == 'product' && $woo_active) {
  2718.                                 if(class_exists('TS_Options')) {
  2719.                                         TS_Options::ts_create_product_variation( $product_attributes, $new_id, $meta_input, $meta_box, $gallery_images );
  2720.                                 }                                      
  2721.                         }                      
  2722.                        
  2723.                         if (!empty($meta_vals['scrape_download_images'][0])) {
  2724.                                 if (!empty($meta_vals['scrape_allowhtml'][0])) {
  2725.                                         $new_html = $this->download_images_from_html_string($post_arr['post_content'], $new_id);
  2726.                                         kses_remove_filters();
  2727.                                         $new_id = wp_update_post(array(
  2728.                                                 'ID' => $new_id, 'post_content' => $new_html
  2729.                                         ));
  2730.                                         kses_init_filters();
  2731.                                 } else {
  2732.                                         $temp_str = $this->convert_html_links($original_html_content, $url, $html_base_url);
  2733.                                         $this->download_images_from_html_string($temp_str, $new_id);
  2734.                                 }
  2735.                         }
  2736.                        
  2737.                         if (!empty($meta_vals['scrape_template_status'][0])) {
  2738.                                 $post = get_post($new_id);
  2739.                                 if(class_exists('TS_Options')) {
  2740.                                         if(function_exists('wp_date')) {
  2741.                                                 $post->post_date = $save_post_date_jalali;
  2742.                                         }
  2743.                                 }                                      
  2744.                                 $post_metas = get_post_meta($new_id);
  2745.                                 if (class_exists('TS_Aparat')) {
  2746.                                         $url = preg_match('/https?:\/\/(?:www)\.aparat\.com\/v\/([a-zA-Z0-9]+)/', $url, $matches);
  2747.                                         $id = $matches[1];
  2748.                                         $aparat = TS_Aparat::ts_video_embed_link($id);
  2749.                                 }                              
  2750.                                 $template = $meta_vals['scrape_template'][0];
  2751.                                 $template = str_replace(array(
  2752.                                         "[scrape_title]", "[scrape_content]", "[scrape_date]", "[scrape_url]", "[scrape_aparat]", "[scrape_gallery]", "[scrape_categories]", "[scrape_tags]", "[scrape_thumbnail]"
  2753.                                 ), array(
  2754.                                         $post->post_title, $post->post_content, $post->post_date, $post_metas['_scrape_original_url'][0], $aparat, "[gallery]", implode(", ", wp_get_post_terms($new_id, array_diff(get_post_taxonomies($new_id), array('post_tag', 'post_format')), array('fields' => 'names'))), implode(", ", wp_get_post_tags($new_id, array('fields' => 'names'))), get_the_post_thumbnail($new_id)
  2755.                                 ), $template);
  2756.                                
  2757.                                 preg_match_all('/\[scrape_meta name="([^"]*)"\]/', $template, $matches);
  2758.                                
  2759.                                 $full_matches = $matches[0];
  2760.                                 $name_matches = $matches[1];
  2761.                                 if (!empty($full_matches)) {
  2762.                                         $combined = array_combine($name_matches, $full_matches);
  2763.                                        
  2764.                                         foreach ($combined as $meta_name => $template_string) {
  2765.                                                 $val = get_post_meta($new_id, $meta_name, true);
  2766.                                                 $template = str_replace($template_string, $val, $template);
  2767.                                         }
  2768.                                 }
  2769.                                
  2770.                                 kses_remove_filters();
  2771.                                 wp_update_post(array(
  2772.                                         'ID' => $new_id, 'post_content' => $template
  2773.                                 ));
  2774.                                 kses_init_filters();
  2775.                         }
  2776.                        
  2777.                         unset($doc);
  2778.                         unset($xpath);
  2779.                         unset($response);
  2780.                 } else {
  2781.                         $this->write_log($url . " http error in single scrape. error message " . $response->get_error_message(), true);
  2782.                 }
  2783.         }
  2784.        
  2785.         public static function clear_all_schedules() {
  2786.                 $all_tasks = get_posts(array(
  2787.                         'numberposts' => -1, 'post_type' => 'scrape', 'post_status' => 'any'
  2788.                 ));
  2789.                
  2790.                 foreach ($all_tasks as $task) {
  2791.                         $post_id = $task->ID;
  2792.                         $timestamp = wp_next_scheduled("scrape_event", array($post_id));
  2793.                         wp_unschedule_event($timestamp, "scrape_event", array($post_id));
  2794.                         wp_clear_scheduled_hook("scrape_event", array($post_id));
  2795.                        
  2796.                         wp_update_post(array(
  2797.                                 'ID' => $post_id, 'post_date_gmt' => date("Y-m-d H:i:s")
  2798.                         ));
  2799.                 }
  2800.                
  2801.                 if (self::check_exec_works()) {
  2802.                         $e_word = E_WORD;
  2803.                         $c_word = C_WORD;
  2804.                         $e_word($c_word . ' -l', $output, $return);
  2805.                         $command_string = '* * * * * wget -q -O - ' . site_url() . ' >/dev/null 2>&1' . PHP_EOL;
  2806.                         if (!$return) {
  2807.                                 foreach ($output as $key => $line) {
  2808.                                         if ($line == $command_string) {
  2809.                                                 unset($output[$key]);
  2810.                                         }
  2811.                                 }
  2812.                         }
  2813.                         $output = implode(PHP_EOL, $output);
  2814.                         $cron_file = OL_PLUGIN_PATH . DIRECTORY_SEPARATOR . 'logs' . DIRECTORY_SEPARATOR . "scrape_cron_file.txt";
  2815.                         file_put_contents($cron_file, $output);
  2816.                         $e_word($c_word . " " . $cron_file);
  2817.                 }
  2818.         }
  2819.        
  2820.         public static function create_system_cron($post_id) {
  2821.             if(DEMO) {
  2822.                 return;
  2823.         }
  2824.                 if (!self::check_exec_works()) {
  2825.                         set_transient("scrape_msg", array(__("Your " . S_WORD . " does not allow php " . E_WORD . " function. Your cron type is saved as WordPress cron type.", "ol-scrapes")));
  2826.                         self::write_log("cron error: " . E_WORD . " is disabled in " . S_WORD . ".", true);
  2827.                         update_post_meta($post_id, 'scrape_cron_type', 'wordpress');
  2828.                         return;
  2829.                 }
  2830.                
  2831.                 $cron_file = OL_PLUGIN_PATH . DIRECTORY_SEPARATOR . 'logs' . DIRECTORY_SEPARATOR . "scrape_cron_file.txt";
  2832.                 touch($cron_file);
  2833.                 chmod($cron_file, 0755);
  2834.                 $command_string = '* * * * * wget -q -O - ' . site_url() . ' >/dev/null 2>&1';
  2835.                 $e_word = E_WORD;
  2836.                 $c_word = C_WORD;
  2837.                 $e_word($c_word . ' -l', $output, $return);
  2838.                 $output = implode(PHP_EOL, $output);
  2839.                 self::write_log($c_word . " -l result ");
  2840.                 self::write_log($output);
  2841.                 if (!$return) {
  2842.                         if (strpos($output, $command_string) === false) {
  2843.                                 $command_string = $output . PHP_EOL . $command_string . PHP_EOL;
  2844.                                
  2845.                                 file_put_contents($cron_file, $command_string);
  2846.                                
  2847.                                 $command = $c_word . ' ' . $cron_file;
  2848.                                 $output = $return = null;
  2849.                                 $e_word($command, $output, $return);
  2850.                                
  2851.                                 self::write_log($output);
  2852.                                 if ($return) {
  2853.                                         set_transient("scrape_msg", array(__(S_WORD . " error occurred during " . C_WORD . " installation. Your cron type is saved as WordPress cron type.", "ol-scrapes")));
  2854.                                         update_post_meta($post_id, 'scrape_cron_type', 'wordpress');
  2855.                                 }
  2856.                         }
  2857.                 } else {
  2858.                         set_transient("scrape_msg", array(__(S_WORD . " error occurred while getting your cron jobs. Your cron type is saved as WordPress cron type.", "ol-scrapes")));
  2859.                         update_post_meta($post_id, 'scrape_cron_type', 'wordpress');
  2860.                 }
  2861.         }
  2862.        
  2863.         public static function clear_all_tasks() {
  2864.                 $all_tasks = get_posts(array(
  2865.                         'numberposts' => -1, 'post_type' => 'scrape', 'post_status' => 'any'
  2866.                 ));
  2867.                
  2868.                 foreach ($all_tasks as $task) {
  2869.                         $meta_vals = get_post_meta($task->ID);
  2870.                         foreach ($meta_vals as $key => $value) {
  2871.                                 delete_post_meta($task->ID, $key);
  2872.                         }
  2873.                         wp_delete_post($task->ID, true);
  2874.                 }
  2875.         }
  2876.        
  2877.         public static function clear_all_values() {
  2878.                 delete_site_option("ol_scrapes_valid");
  2879.                 delete_site_option("ol_scrapes_domain");
  2880.                 delete_site_option("ol_scrapes_pc");
  2881.                
  2882.                 delete_site_option("scrape_plugin_activation_error");
  2883.                 delete_site_option("scrape_user_agent");
  2884.                
  2885.                 delete_transient("scrape_msg");
  2886.                 delete_transient("scrape_msg_req");
  2887.                 delete_transient("scrape_msg_set");
  2888.                 delete_transient("scrape_msg_set_success");
  2889.         }
  2890.        
  2891.         public function check_warnings() {
  2892.                 $message = "";
  2893.                 if (defined("DISABLE_WP_CRON") && DISABLE_WP_CRON) {
  2894.                         $message .= __("DISABLE_WP_CRON is probably set true in wp-config.php.<br/>Please delete or set it to false, or make sure that you ping wp-cron.php automatically.", "ol-scrapes");
  2895.                 }
  2896.                 if (!empty($message)) {
  2897.                         set_transient("scrape_msg", array($message));
  2898.                 }
  2899.         }
  2900.        
  2901.         public function detect_html_encoding_and_replace($header, &$body, $ajax = false) {
  2902.                 global $charset_header, $charset_php, $charset_meta;
  2903.  
  2904.                 //if ($ajax) {
  2905.                 //      wp_ajax_url($ajax);
  2906.                 //}
  2907.                
  2908.                 $charset_regex = preg_match("/<meta(?!\s*(?:name|value)\s*=)(?:[^>]*?content\s*=[\s\"']*)?([^>]*?)[\s\"';]*charset\s*=[\s\"']*([^\s\"'\/>]*)[\s\"']*\/?>/i", $body, $matches);
  2909.                 if (empty($header)) {
  2910.                         $charset_header = false;
  2911.                 } else {
  2912.                         $charset_header = explode(";", $header);
  2913.                         if (count($charset_header) == 2) {
  2914.                                 $charset_header = $charset_header[1];
  2915.                                 $charset_header = explode("=", $charset_header);
  2916.                                 $charset_header = strtolower(trim(trim($charset_header[1]), "\"''"));
  2917.                                 if ($charset_header == "utf8") {
  2918.                                         $charset_header = "utf-8";
  2919.                                 }
  2920.                         } else {
  2921.                                 $charset_header = false;
  2922.                         }
  2923.                 }
  2924.                 if ($charset_regex) {
  2925.                         $charset_meta = strtolower($matches[2]);
  2926.                         if ($charset_meta == "utf8") {
  2927.                                 $charset_meta = "utf-8";
  2928.                         }
  2929.                         if ($charset_meta != "utf-8") {
  2930.                                 $body = str_replace($matches[0], "<meta charset='utf-8'>", $body);
  2931.                         }
  2932.                 } else {
  2933.                         $charset_meta = false;
  2934.                 }
  2935.                
  2936.                 $charset_php = strtolower(mb_detect_encoding($body, mb_list_encodings(), false));
  2937.  
  2938.                 if ($charset_header && $charset_meta) {
  2939.                         return $charset_header;
  2940.  
  2941.                 }
  2942.  
  2943.                 if (!$charset_header && !$charset_meta) {
  2944.  
  2945.                         return $charset_php;
  2946.                 } else {
  2947.                         return !empty($charset_meta) ? $charset_meta : $charset_header;
  2948.                 }
  2949.         }
  2950.        
  2951.         public function detect_feed_encoding_and_replace($header, &$body, $ajax = false) {
  2952.                 global $charset_header, $charset_php, $charset_xml;
  2953.  
  2954.                 //if ($ajax) {
  2955.                 //      wp_ajax_url($ajax);
  2956.                 //}
  2957.                
  2958.                 $encoding_regex = preg_match("/encoding\s*=\s*[\"']([^\"']*)\s*[\"']/isu", $body, $matches);
  2959.                 if (empty($header)) {
  2960.                         $charset_header = false;
  2961.                 } else {
  2962.                         $charset_header = explode(";", $header);
  2963.                         if (count($charset_header) == 2) {
  2964.                                 $charset_header = $charset_header[1];
  2965.                                 $charset_header = explode("=", $charset_header);
  2966.                                 $charset_header = strtolower(trim(trim($charset_header[1]), "\"''"));
  2967.                         } else {
  2968.                                 $charset_header = false;
  2969.                         }
  2970.                 }
  2971.                 if ($encoding_regex) {
  2972.                         $charset_xml = strtolower($matches[1]);
  2973.                         if ($charset_xml != "utf-8") {
  2974.                                 $body = str_replace($matches[1], 'utf-8', $body);
  2975.                         }
  2976.                 } else {
  2977.                         $charset_xml = false;
  2978.                 }
  2979.                
  2980.                 $charset_php = strtolower(mb_detect_encoding($body, mb_list_encodings(), false));
  2981.  
  2982.         if ($charset_header && $charset_xml) {
  2983.             return $charset_header;
  2984.         }
  2985.  
  2986.         if (!$charset_header && !$charset_xml) {
  2987.             return $charset_php;
  2988.         } else {
  2989.             return !empty($charset_xml) ? $charset_xml : $charset_header;
  2990.         }
  2991.         }
  2992.        
  2993.         public function add_attachment_from_url($attachment_url, $post_id) {
  2994.                 $this->write_log($attachment_url . " attachment controls");
  2995.                 $meta_vals = get_post_meta(self::$task_id);
  2996.                 $upload_dir = wp_upload_dir();
  2997.                
  2998.                 $parsed = parse_url($attachment_url);
  2999.                 $filename = basename($parsed['path']);
  3000.                
  3001.                 global $wpdb;
  3002.                 $query = "SELECT ID FROM {$wpdb->posts} WHERE post_title LIKE '" . $filename . "%' and post_type ='attachment' and post_parent = $post_id";
  3003.                 $attachment_id = $wpdb->get_var($query);
  3004.                
  3005.                 $this->write_log("found attachment id for $post_id : " . $attachment_id);
  3006.                
  3007.                 if (empty($attachment_id)) {
  3008.                         if (wp_mkdir_p($upload_dir['path'])) {
  3009.                                 $file = $upload_dir['path'] . '/' . $filename;
  3010.                         } else {
  3011.                                 $file = $upload_dir['basedir'] . '/' . $filename;
  3012.                         }
  3013.                        
  3014.                         $args = $this->return_html_args($meta_vals);
  3015.                        
  3016.                         $file_data = wp_remote_get($attachment_url, $args);
  3017.                         if (is_wp_error($file_data)) {
  3018.                                 $this->write_log("http error in " . $attachment_url . " " . $file_data->get_error_message(), true);
  3019.                                 return;
  3020.                         }
  3021.                        
  3022.                        
  3023.                         $mimetype = wp_check_filetype($filename);
  3024.                         if ($mimetype === false) {
  3025.                                 $this->write_log("mime type of image can not be found");
  3026.                                 return;
  3027.                         }
  3028.                        
  3029.                         $mimetype = $mimetype['type'];
  3030.                         $extension = $mimetype['ext'];
  3031.                        
  3032.                         file_put_contents($filename, $file_data['body']);
  3033.                        
  3034.                         $attachment = array(
  3035.                                 'post_mime_type' => $mimetype, 'post_title' => $filename . ".$extension", 'post_content' => '', 'post_status' => 'inherit'
  3036.                         );
  3037.                        
  3038.                         $attach_id = wp_insert_attachment($attachment, $file, $post_id);
  3039.                        
  3040.                         $this->write_log("attachment id : " . $attach_id . " mime type: " . $mimetype . " added to media library.");
  3041.                        
  3042.                         require_once(ABSPATH . 'wp-admin/includes/image.php');
  3043.                         $attach_data = wp_generate_attachment_metadata($attach_id, $file);
  3044.                         wp_update_attachment_metadata($attach_id, $attach_data);
  3045.                         return $attach_id;
  3046.                 }
  3047.                 return $attachment_id;
  3048.         }
  3049.        
  3050.         public function generate_featured_image($image_url, $post_id, $featured = true) {
  3051.                 $this->write_log($image_url . " thumbnail controls");
  3052.                 $meta_vals = get_post_meta(self::$task_id);
  3053.         $parent_post_title = get_the_title($post_id);
  3054.                 $upload_dir = wp_upload_dir();
  3055.                
  3056.                 global $wpdb;
  3057.                 $query = "SELECT ID FROM {$wpdb->posts} WHERE post_content LIKE '" . md5($image_url) . "%' and post_type ='attachment' and post_parent = $post_id";
  3058.                 $image_id = $wpdb->get_var($query);
  3059.                
  3060.                 $this->write_log("found image id for $post_id : " . $image_id);
  3061.                
  3062.                 if (empty($image_id)) {
  3063.  
  3064.             $filename = sanitize_file_name(sanitize_title($parent_post_title) . '_' . uniqid());
  3065.  
  3066.                         if (wp_mkdir_p($upload_dir['path'])) {
  3067.                                 $file = $upload_dir['path'] . '/' . $filename;
  3068.                         } else {
  3069.                                 $file = $upload_dir['basedir'] . '/' . $filename;
  3070.                         }
  3071.                        
  3072.                         if (substr($image_url, 0, 11) == 'data:image/') {
  3073.                                 $image_data = array(
  3074.                                         'body' => base64_decode(substr($image_url, strpos($image_url, 'base64') + 7))
  3075.                                 );
  3076.                         } else {
  3077.                                 $args = $this->return_html_args($meta_vals);
  3078.                                
  3079.                                 $image_data = wp_remote_get($image_url, $args);
  3080.                                 if (is_wp_error($image_data)) {
  3081.                                         $this->write_log("http error in " . $image_url . " " . $image_data->get_error_message(), true);
  3082.                                         return;
  3083.                                 }
  3084.                         }
  3085.                        
  3086.                         $mimetype = getimagesizefromstring($image_data['body']);
  3087.                         if ($mimetype === false) {
  3088.                                 $this->write_log("mime type of image can not be found");
  3089.                                 $this->write_log(substr($image_data['body'], 0, 150));
  3090.                                 return;
  3091.                         }
  3092.                        
  3093.                         $mimetype = $mimetype["mime"];
  3094.                         $extension = substr($mimetype, strpos($mimetype, "/") + 1);
  3095.                         $file .= ".$extension";
  3096.                        
  3097.                         file_put_contents($file, $image_data['body']);
  3098.                        
  3099.                         $attachment = array(
  3100.                                 'post_mime_type' => $mimetype,
  3101.                 'post_title' => $parent_post_title . '_' . uniqid() . '.' . $extension,
  3102.                 'post_content' => md5($image_url),
  3103.                 'post_status' => 'inherit'
  3104.                         );
  3105.                        
  3106.                         if (!empty($meta_vals['scrape_watermark_images'][0])) {
  3107.                                 if( class_exists('Image_Watermark')) {
  3108.                                         $image_watermark = new Image_Watermark();
  3109.                                         $image_watermark->do_watermark( $post_id, $file, $mimetype, $upload_dir, $attachment );
  3110.                                 }
  3111.                         }                              
  3112.                        
  3113.                         $attach_id = wp_insert_attachment($attachment, $file, $post_id);
  3114.                        
  3115.                         $this->write_log("attachment id : " . $attach_id . " mime type: " . $mimetype . " added to media library.");
  3116.                        
  3117.                         require_once(ABSPATH . 'wp-admin/includes/image.php');
  3118.                         $attach_data = wp_generate_attachment_metadata($attach_id, $file);
  3119.                         wp_update_attachment_metadata($attach_id, $attach_data);
  3120.                         if ($featured) {
  3121.                                 set_post_thumbnail($post_id, $attach_id);
  3122.                         }
  3123.                        
  3124.                         unset($attach_data);
  3125.                         unset($image_data);
  3126.                         unset($mimetype);
  3127.                         return $attach_id;
  3128.                 } else {
  3129.                         if ($featured) {
  3130.                                 $this->write_log("image already exists set thumbnail for post " . $post_id . " to " . $image_id);
  3131.                                 set_post_thumbnail($post_id, $image_id);
  3132.                         }
  3133.                 }
  3134.                 return $image_id;
  3135.         }
  3136.        
  3137.         public function create_absolute_url($rel, $base, $html_base) {
  3138.                 $rel = trim($rel);
  3139.                 $base = strtolower(trim($base));
  3140.                 if (substr($rel, 0, 11) == 'data:image/') {
  3141.                         return $rel;
  3142.                 }
  3143.                
  3144.                 if (!empty($html_base)) {
  3145.                         $base = $html_base;
  3146.                 }
  3147.                 return str_replace(" ", "%20", WP_Http::make_absolute_url($rel, $base));
  3148.         }
  3149.        
  3150.         public static function write_log($message, $is_error = false) {
  3151.                 $folder = plugin_dir_path(__FILE__) . "../logs";
  3152.                 $handle = fopen($folder . DIRECTORY_SEPARATOR . "logs.txt", "a");
  3153.                 if (!is_string($message)) {
  3154.                         $message = print_r($message, true);
  3155.                 }
  3156.                 if ($is_error) {
  3157.                         $message = PHP_EOL . " === Scrapes Warning === " . PHP_EOL . $message . PHP_EOL . " === Scrapes Warning === ";
  3158.                 }
  3159.                 fwrite($handle, current_time('mysql') . " TASK ID: " . self::$task_id . " - PID: " . getmypid() . " - RAM: " . (round(memory_get_usage() / (1024 * 1024), 2)) . "MB - " . get_current_blog_id() . " " . $message . PHP_EOL);
  3160.                 if ((filesize($folder . DIRECTORY_SEPARATOR . "logs.txt") / 1024 / 1024) >= 10) {
  3161.                         fclose($handle);
  3162.                         unlink($folder . DIRECTORY_SEPARATOR . "logs.txt");
  3163.                         $handle = fopen($folder . DIRECTORY_SEPARATOR . "logs.txt", "a");
  3164.                         fwrite($handle, current_time('mysql') . " - " . getmypid() . " - " . self::system_info() . PHP_EOL);
  3165.                 }
  3166.                 fclose($handle);
  3167.         }
  3168.        
  3169.         public static function system_info() {
  3170.                 global $wpdb;
  3171.                
  3172.                 if (!function_exists('get_plugins')) {
  3173.                         require_once ABSPATH . 'wp-admin/includes/plugin.php';
  3174.                 }
  3175.                
  3176.                 $system_info = "";
  3177.                 $system_info .= "Website Name: " . get_bloginfo() . PHP_EOL;
  3178.                 $system_info .= "Wordpress URL: " . site_url() . PHP_EOL;
  3179.                 $system_info .= "Site URL: " . home_url() . PHP_EOL;
  3180.                 $system_info .= "Wordpress Version: " . get_bloginfo('version') . PHP_EOL;
  3181.                 $system_info .= "Multisite: " . (is_multisite() ? "yes" : "no") . PHP_EOL;
  3182.                 $system_info .= "Theme: " . wp_get_theme() . PHP_EOL;
  3183.                 $system_info .= "PHP Version: " . phpversion() . PHP_EOL;
  3184.                 $system_info .= "PHP Extensions: " . json_encode(get_loaded_extensions()) . PHP_EOL;
  3185.                 $system_info .= "MySQL Version: " . $wpdb->db_version() . PHP_EOL;
  3186.                 $system_info .= "Server Info: " . $_SERVER['SERVER_SOFTWARE'] . PHP_EOL;
  3187.                 $system_info .= "WP Memory Limit: " . WP_MEMORY_LIMIT . PHP_EOL;
  3188.                 $system_info .= "WP Admin Memory Limit: " . WP_MAX_MEMORY_LIMIT . PHP_EOL;
  3189.                 $system_info .= "PHP Memory Limit: " . ini_get('memory_limit') . PHP_EOL;
  3190.                 $system_info .= "Wordpress Plugins: " . json_encode(get_plugins()) . PHP_EOL;
  3191.                 $system_info .= "Wordpress Active Plugins: " . json_encode(get_option('active_plugins')) . PHP_EOL;
  3192.                 return $system_info;
  3193.         }
  3194.        
  3195.         public static function disable_plugin() {
  3196.                 if (current_user_can('activate_plugins') && is_plugin_active(plugin_basename(OL_PLUGIN_PATH . 'ol_scrapes.php'))) {
  3197.                         deactivate_plugins(plugin_basename(OL_PLUGIN_PATH . 'ol_scrapes.php'));
  3198.                         if (isset($_GET['activate'])) {
  3199.                                 unset($_GET['activate']);
  3200.                         }
  3201.                 }
  3202.         }
  3203.        
  3204.         public static function show_notice() {
  3205.                 load_plugin_textdomain('ol-scrapes', false, dirname(plugin_basename(__FILE__)) . '/../languages');
  3206.                 $msgs = get_transient("scrape_msg");
  3207.                 if (!empty($msgs)) :
  3208.                         foreach ($msgs as $msg) :
  3209.                                 ?>
  3210.                 <div class="notice notice-error">
  3211.                     <p><strong>Scrapes: </strong><?php echo $msg; ?> <a
  3212.                                 href="<?php echo add_query_arg('post_type', 'scrape', admin_url('edit.php')); ?>"><?php _e("View All Scrapes", "ol-scrapes"); ?></a>.
  3213.                     </p>
  3214.                 </div>
  3215.                                 <?php
  3216.                         endforeach;
  3217.                 endif;
  3218.                
  3219.                 $msgs = get_transient("scrape_msg_req");
  3220.                 if (!empty($msgs)) :
  3221.                         foreach ($msgs as $msg) :
  3222.                                 ?>
  3223.                 <div class="notice notice-error">
  3224.                     <p><strong>Scrapes: </strong><?php echo $msg; ?></p>
  3225.                 </div>
  3226.                                 <?php
  3227.                         endforeach;
  3228.                 endif;
  3229.                
  3230.                 $msgs = get_transient("scrape_msg_set");
  3231.                 if (!empty($msgs)) :
  3232.                         foreach ($msgs as $msg) :
  3233.                                 ?>
  3234.                 <div class="notice notice-error">
  3235.                     <p><strong>Scrapes: </strong><?php echo $msg; ?></p>
  3236.                 </div>
  3237.                                 <?php
  3238.                         endforeach;
  3239.                 endif;
  3240.                
  3241.                 $msgs = get_transient("scrape_msg_set_success");
  3242.                 if (!empty($msgs)) :
  3243.                         foreach ($msgs as $msg) :
  3244.                                 ?>
  3245.                 <div class="notice notice-success">
  3246.                     <p><strong>Scrapes: </strong><?php echo $msg; ?></p>
  3247.                 </div>
  3248.                                 <?php
  3249.                         endforeach;
  3250.                 endif;
  3251.                
  3252.                 delete_transient("scrape_msg");
  3253.                 delete_transient("scrape_msg_req");
  3254.                 delete_transient("scrape_msg_set");
  3255.                 delete_transient("scrape_msg_set_success");
  3256.         }
  3257.        
  3258.         public function custom_column() {
  3259.                 add_filter('manage_' . 'scrape' . '_posts_columns', array($this, 'add_status_column'));
  3260.                 add_action('manage_' . 'scrape' . '_posts_custom_column', array($this, 'show_status_column'), 10, 2);
  3261.                 add_filter('post_row_actions', array($this, 'remove_row_actions'), 10, 2);
  3262.                 add_filter('manage_' . 'edit-scrape' . '_sortable_columns', array($this, 'add_sortable_column'));
  3263.         }
  3264.        
  3265.         public function add_sortable_column() {
  3266.                 return array(
  3267.                         'name' => 'title'
  3268.                 );
  3269.         }
  3270.        
  3271.         public function custom_start_stop_action() {
  3272.                 add_action('load-edit.php', array($this, 'scrape_custom_actions'));
  3273.         }
  3274.        
  3275.         public function scrape_custom_actions() {
  3276.                 $nonce = isset($_REQUEST['_wpnonce']) ? $_REQUEST['_wpnonce'] : null;
  3277.                 $action = isset($_REQUEST['scrape_action']) ? $_REQUEST['scrape_action'] : null;
  3278.                 $post_id = isset($_REQUEST['scrape_id']) ? intval($_REQUEST['scrape_id']) : null;
  3279.                 if (wp_verify_nonce($nonce, 'scrape_custom_action') && isset($post_id)) {
  3280.                        
  3281.                         if ($action == 'stop_scrape') {
  3282.                                 $my_post = array();
  3283.                                 $my_post['ID'] = $post_id;
  3284.                                 $my_post['post_date_gmt'] = date("Y-m-d H:i:s");
  3285.                                 wp_update_post($my_post);
  3286.                                 $this->write_log($post_id . " stop button clicked."); 
  3287.                         } else {
  3288.                                 if ($action == 'start_scrape') {
  3289.                                         update_post_meta($post_id, 'scrape_workstatus', 'waiting');
  3290.                                         update_post_meta($post_id, 'scrape_run_count', 0);
  3291.                                         update_post_meta($post_id, 'scrape_start_time', '');
  3292.                                         update_post_meta($post_id, 'scrape_end_time', '');
  3293.                                         update_post_meta($post_id, 'scrape_last_scrape', '');
  3294.                                         update_post_meta($post_id, 'scrape_task_id', $post_id);
  3295.                                         $this->handle_cron_job($_REQUEST['scrape_id']);
  3296.                                         $this->write_log($post_id . " start button clicked."); 
  3297.                                 } else {
  3298.                                         if ($action == 'duplicate_scrape') {
  3299.                                                 $post = get_post($post_id, ARRAY_A);
  3300.                                                 $post['ID'] = 0;
  3301.                                                 $insert_id = wp_insert_post($post);
  3302.                                                 $post_meta = get_post_meta($post_id);
  3303.                                                 foreach ($post_meta as $name => $value) {
  3304.                                                         update_post_meta($insert_id, $name, get_post_meta($post_id, $name, true));
  3305.                                                 }
  3306.                                                 update_post_meta($insert_id, 'scrape_workstatus', 'waiting');
  3307.                                                 update_post_meta($insert_id, 'scrape_run_count', 0);
  3308.                                                 update_post_meta($insert_id, 'scrape_start_time', '');
  3309.                                                 update_post_meta($insert_id, 'scrape_end_time', '');
  3310.                                                 update_post_meta($insert_id, 'scrape_last_scrape', '');
  3311.                                                 update_post_meta($insert_id, 'scrape_task_id', $insert_id);
  3312.                                                 $this->write_log($post_id . " duplicate button clicked."); 
  3313.                                         }
  3314.                                 }
  3315.                         }
  3316.                         wp_redirect(add_query_arg('post_type', 'scrape', admin_url('/edit.php')));
  3317.                         exit;
  3318.                 }
  3319.         }
  3320.        
  3321.         public function remove_row_actions($actions, $post) {
  3322.                 if ($post->post_type == 'scrape') {
  3323.                         unset($actions);
  3324.                         return array(
  3325.                                 '' => ''
  3326.                         );
  3327.                 }
  3328.                 return $actions;
  3329.         }
  3330.        
  3331.         public function add_status_column($columns) {
  3332.                 unset($columns['title']);
  3333.                 unset($columns['date']);
  3334.                 $columns['name'] = __('Name', "ol-scrapes");
  3335.                 $columns['status'] = __('Status', "ol-scrapes");
  3336.                 $columns['schedules'] = __('Schedules', "ol-scrapes");
  3337.                 $columns['actions'] = __('Actions', "ol-scrapes");
  3338.                 return $columns;
  3339.         }
  3340.        
  3341.         public function show_status_column($column_name, $post_ID) {
  3342.                 clean_post_cache($post_ID);
  3343.                 $post_status = get_post_status($post_ID);
  3344.                 $post_title = get_post_field('post_title', $post_ID);
  3345.                 $scrape_status = get_post_meta($post_ID, 'scrape_workstatus', true);
  3346.                 $run_limit = get_post_meta($post_ID, 'scrape_run_limit', true);
  3347.                 $run_count = get_post_meta($post_ID, 'scrape_run_count', true);
  3348.                 $run_unlimited = get_post_meta($post_ID, 'scrape_run_unlimited', true);
  3349.                 $css_class = '';
  3350.                
  3351.                 if ($post_status == 'trash') {
  3352.                         $status = __("Deactivated", "ol-scrapes");
  3353.                         $css_class = "deactivated";
  3354.                 } else {
  3355.                         if ($run_count == 0 && $scrape_status == 'waiting') {
  3356.                                 $status = __("Preparing", "ol-scrapes");
  3357.                                 $css_class = "preparing";
  3358.                         } else {
  3359.                                 if ((!empty($run_unlimited) || $run_count < $run_limit) && $scrape_status == 'waiting') {
  3360.                                         $status = __("Waiting next run", "ol-scrapes");
  3361.                                         $css_class = "wait_next";
  3362.                                 } else {
  3363.                                         if (((!empty($run_limit) && $run_count < $run_limit) || (!empty($run_unlimited))) && $scrape_status == 'running') {
  3364.                                                 $status = __("Running", "ol-scrapes");
  3365.                                                 $css_class = "running";
  3366.                                         } else {
  3367.                                                 if (empty($run_unlimited) && $run_count == $run_limit && $scrape_status == 'waiting') {
  3368.                                                         $status = __("Complete", "ol-scrapes");
  3369.                                                         $css_class = "complete";
  3370.                                                 }
  3371.                                         }
  3372.                                 }
  3373.                         }
  3374.                 }
  3375.                
  3376.                 if ($column_name == 'status') {
  3377.                         echo "<span class='ol_status ol_status_$css_class'>" . $status . "</span>";
  3378.                 }
  3379.                
  3380.                 if ($column_name == 'name') {
  3381.                         echo "<p><strong><a href='" . get_edit_post_link($post_ID) . "'>" . $post_title . "</a></strong></p>" . "<p><span class='id'>ID: " . $post_ID . "</span></p>";
  3382.                 }
  3383.                
  3384.                 if ($column_name == 'schedules') {
  3385.                         $last_run = get_post_meta($post_ID, 'scrape_start_time', true) != "" ? get_post_meta($post_ID, 'scrape_start_time', true) : __("None", "ol-scrapes");
  3386.                         $last_complete = get_post_meta($post_ID, 'scrape_end_time', true) != "" ? get_post_meta($post_ID, 'scrape_end_time', true) : __("None", "ol-scrapes");
  3387.                         $last_scrape = get_post_meta($post_ID, 'scrape_last_scrape', true) != "" ? get_post_meta($post_ID, 'scrape_last_scrape', true) : __("None", "ol-scrapes");
  3388.                         $run_count_progress = $run_count;
  3389.                         if ($run_unlimited == "") {
  3390.                                 $run_count_progress .= " / " . $run_limit;
  3391.                         }
  3392.                        
  3393.                         $offset = get_option('gmt_offset') * 3600;
  3394.                         $date = date("Y-m-d H:i:s", wp_next_scheduled("scrape_event", array($post_ID)) + $offset);
  3395.                         if (strpos($date, "1970-01-01") !== false) {
  3396.                                 $date = __("No Schedule", "ol-scrapes");
  3397.                         }
  3398.                         echo "<p><label>" . __("Last Run:", "ol-scrapes") . "</label> <span>" . $last_run . "</span></p>" . "<p><label>" . __("Last Complete:", "ol-scrapes") . "</label> <span>" . $last_complete . "</span></p>" . "<p><label>" . __("Last Scrape:", "ol-scrapes") . "</label> <span>" . $last_scrape . "</span></p>" . "<p><label>" . __("Next Run:", "ol-scrapes") . "</label> <span>" . $date . "</span></p>" . "<p><label>" . __("Total Run:", "ol-scrapes") . "</label> <span>" . $run_count_progress . "</span></p>";
  3399.                 }
  3400.                 if ($column_name == "actions") {
  3401.                         $nonce = wp_create_nonce('scrape_custom_action');
  3402.                         $untrash = wp_create_nonce('untrash-post_' . $post_ID);
  3403.                         echo ($post_status != 'trash' ? "<a href='" . get_edit_post_link($post_ID) . "' class='button edit'><i class='icon ion-android-create'></i>" . __("Edit", "ol-scrapes") . "</a>" : "") . ($post_status != 'trash' ? "<a href='" . admin_url("edit.php?post_type=scrape&scrape_id=$post_ID&_wpnonce=$nonce&scrape_action=start_scrape") . "' class='button run ol_status_" . $css_class . "'><i class='icon ion-play'></i>" . __("Run", "ol-scrapes") . "</a>" : "") . ($post_status != 'trash' ? "<a href='" . admin_url("edit.php?post_type=scrape&scrape_id=$post_ID&_wpnonce=$nonce&scrape_action=stop_scrape") . "' class='button stop ol_status_" . $css_class . "'><i class='icon ion-pause'></i>" . __("Pause", "ol-scrapes") . "</a>" : "") . ($post_status != 'trash' ? "<br><a href='" . admin_url("edit.php?post_type=scrape&scrape_id=$post_ID&_wpnonce=$nonce&scrape_action=duplicate_scrape") . "' class='button duplicate'><i class='icon ion-android-add-circle'></i>" . __("Copy", "ol-scrapes") . "</a>" : "") . ($post_status != 'trash' ? "<a href='" . get_delete_post_link($post_ID) . "' class='button trash'><i class='icon ion-trash-b'></i>" . __("Trash", "ol-scrapes") . "</a>" : "<a href='" . admin_url('post.php?post=' . $post_ID . '&action=untrash&_wpnonce=' . $untrash) . "' class='button restore'><i class='icon ion-forward'></i>" . __("Restore", "ol-scrapes") . "</a>");
  3404.                 }
  3405.         }
  3406.        
  3407.         public function convert_readable_html($html_string) {
  3408.                 require_once "class-readability.php";
  3409.                
  3410.                 $readability = new Readability($html_string);
  3411.                 $readability->debug = false;
  3412.                 $readability->convertLinksToFootnotes = false;
  3413.                 $result = $readability->init();
  3414.                 if ($result) {
  3415.                         $content = $readability->getContent()->innerHTML;
  3416.                         return $content;
  3417.                 } else {
  3418.                         return '';
  3419.                 }
  3420.         }
  3421.        
  3422.         public function remove_publish() {
  3423.                 add_action('admin_menu', array($this, 'remove_other_metaboxes'));
  3424.                 add_filter('get_user_option_screen_layout_' . 'scrape', array($this, 'screen_layout_post'));
  3425.         }
  3426.        
  3427.         public function remove_other_metaboxes() {
  3428.                 remove_meta_box('submitdiv', 'scrape', 'side');
  3429.                 remove_meta_box('slugdiv', 'scrape', 'normal');
  3430.                 remove_meta_box('postcustom', 'scrape', 'normal');
  3431.         }
  3432.        
  3433.         public function screen_layout_post() {
  3434.                 add_filter('screen_options_show_screen', '__return_false');
  3435.                 return 1;
  3436.         }
  3437.        
  3438.         public function replace_img_org_to_translate($html_string, $org_html_string) {
  3439.                
  3440.                 preg_match_all('/<\/?img(|\s+[^>]+)>/', $html_string, $old_images);
  3441.                 preg_match_all('/<\/?img(|\s+[^>]+)>/', $org_html_string, $new_images);
  3442.                
  3443.                 $post_content = str_ireplace(array_values($old_images[0]), array_values($new_images[0]), $html_string);
  3444.                
  3445.                 return $post_content;
  3446.         }
  3447.        
  3448.         public function get_orginal_image_link_from_content($orgi_html) {
  3449.                 $doc = new DOMDocument();
  3450.                 $doc->preserveWhiteSpace = false;
  3451.                 @$doc->loadHTML('<?xml encoding="utf-8" ?>' . $orgi_html);
  3452.                 $org_image = $doc->getElementsByTagName('img');
  3453.                 if ($org_image->length) {
  3454.                         foreach ($org_image as $itemnew) {
  3455.                                 if ($itemnew->getAttribute('data-lazy-src') != '') {
  3456.                                         $get_image[] = $itemnew->getAttribute('data-lazy-src');
  3457.                                 } elseif ($itemnew->getAttribute('data-src') != '') {
  3458.                                         $get_image[] = $itemnew->getAttribute('data-src');
  3459.                                 } elseif ($itemnew->getAttribute('src') != '') {
  3460.                                         $get_image[] = $itemnew->getAttribute('src');
  3461.                                 }
  3462.                         }
  3463.                 }
  3464.  
  3465.                 return $get_image;
  3466.         }
  3467.        
  3468.         public function fix_image_link_content($html_string, $original_html_string) {
  3469.                 if (empty($html_string)) {
  3470.                         return "";
  3471.                 }
  3472.                 $new_image = $this->get_orginal_image_link_from_content($original_html_string);
  3473.                 $doc = new DOMDocument();
  3474.                 $doc->preserveWhiteSpace = false;
  3475.                 @$doc->loadHTML('<?xml encoding="utf-8" ?>' . $html_string);
  3476.                 $imgs = $doc->getElementsByTagName('img');
  3477.                 if ($imgs->length) {
  3478.                         $i = 0;
  3479.                         foreach ($imgs as $itemold) {
  3480.                                 if ($itemold->getAttribute('src') != '') {
  3481.                                         $old_image[] = $itemold->getAttribute('src');
  3482.                                         $itemold->setAttribute('src', $new_image[$i]);
  3483.                                 }
  3484.                                 $i++;
  3485.                         }
  3486.                 }              
  3487.                
  3488.                 return $this->save_html_clean($doc);
  3489.         }
  3490.        
  3491.         public function convert_html_links($html_string, $base_url, $html_base_url) {
  3492.                 if (empty($html_string)) {
  3493.                         return "";
  3494.                 }
  3495.                 $doc = new DOMDocument();
  3496.                 $doc->preserveWhiteSpace = false;
  3497.                 @$doc->loadHTML('<?xml encoding="utf-8" ?>' . $html_string);
  3498.                 $imgs = $doc->getElementsByTagName('img');
  3499.                 if ($imgs->length) {
  3500.                         foreach ($imgs as $item) {
  3501.                                 if ($item->getAttribute('src') != '') {
  3502.                                         $item->setAttribute('src', $this->create_absolute_url($item->getAttribute('src'), $base_url, $html_base_url));
  3503.                                 }
  3504.                         }
  3505.                 }              
  3506.                
  3507.                 $a = $doc->getElementsByTagName('a');
  3508.                 if ($a->length) {
  3509.                         foreach ($a as $item) {
  3510.                                 if ($item->getAttribute('href') != '') {
  3511.                                         $item->setAttribute('href', $this->create_absolute_url($item->getAttribute('href'), $base_url, $html_base_url));
  3512.                                 }
  3513.                         }
  3514.                 }
  3515.                
  3516.                 return $this->save_html_clean($doc);
  3517.         }
  3518.        
  3519.         public function convert_str_to_woo_decimal($money) {
  3520.                 $decimal_separator = stripslashes(get_option('woocommerce_price_decimal_sep'));
  3521.                 $thousand_separator = stripslashes(get_option('woocommerce_price_thousand_sep'));
  3522.                
  3523.                 $money = preg_replace("/[^\d\.,]/", '', $money);
  3524.                 $money = str_replace($thousand_separator, '', $money);
  3525.                 $money = str_replace($decimal_separator, '.', $money);
  3526.                 return $money;
  3527.         }
  3528.  
  3529.     public function spin_content_with_thebestspinner($email, $password, $content) {
  3530.  
  3531.         $output = wp_remote_post('http://thebestspinner.com/api.php', array(
  3532.                 'method' => 'POST',
  3533.                 'timeout' => 60,
  3534.                 'redirection' => 5,
  3535.                 'httpversion' => '1.0',
  3536.                 'blocking' => true,
  3537.                 'headers' => array(),
  3538.                 'body' => array(
  3539.                     'action' => 'authenticate',
  3540.                     'format' => 'php',
  3541.                     'username' => $email,
  3542.                     'password' => $password,
  3543.                     'rewrite' => 1
  3544.                 ),
  3545.                 'cookies' => array()
  3546.             )
  3547.         );
  3548.  
  3549.         $output = unserialize($output);
  3550.  
  3551.         $this->write_log('best spinner result ' . $output);
  3552.         if ($output['success'] == true) {
  3553.             $content = wp_remote_post('http://thebestspinner.com/api.php', array(
  3554.                     'method' => 'POST',
  3555.                     'timeout' => 60,
  3556.                     'redirection' => 5,
  3557.                     'httpversion' => '1.0',
  3558.                     'blocking' => true,
  3559.                     'headers' => array(),
  3560.                     'body' => array(
  3561.                         'session' => $output['session'],
  3562.                         'format' => 'php',
  3563.                         'text' => $content,
  3564.                         'action' => 'rewriteText'
  3565.                     ),
  3566.                     'cookies' => array()
  3567.                 )
  3568.             );
  3569.         }
  3570.         return $content;
  3571.     }
  3572.        
  3573.         public function download_images_from_html_string($html_string, $post_id) {
  3574.                 if (empty($html_string)) {
  3575.                         return "";
  3576.                 }
  3577.                 $doc = new DOMDocument();
  3578.                 $doc->preserveWhiteSpace = false;
  3579.                 @$doc->loadHTML('<?xml encoding="utf-8" ?>' . $html_string);
  3580.                 $imgs = $doc->getElementsByTagName('img');
  3581.                 if ($imgs->length) {
  3582.                         foreach ($imgs as $item) {
  3583.                                
  3584.                                 $image_url = $item->getAttribute('src');
  3585.                                 global $wpdb;
  3586.                                 $query = "SELECT ID FROM {$wpdb->posts} WHERE post_title LIKE '" . md5($image_url) . "%' and post_type ='attachment' and post_parent = $post_id";
  3587.                                 $count = $wpdb->get_var($query);
  3588.                                
  3589.                                 $this->write_log("download image id for post $post_id is " . $count);
  3590.                                
  3591.                                 if (empty($count)) {
  3592.                                         $attach_id = $this->generate_featured_image($image_url, $post_id, false);
  3593.                                         $item->setAttribute('src', wp_get_attachment_url($attach_id));
  3594.                                 } else {
  3595.                                         $item->setAttribute('src', wp_get_attachment_url($count));
  3596.                                 }
  3597.                                 $item->removeAttribute('srcset');
  3598.                                 $item->removeAttribute('sizes');
  3599.                                 unset($image_url);
  3600.                         }
  3601.                 }
  3602.                
  3603.                 return $this->save_html_clean($doc);
  3604.         }
  3605.        
  3606.         public function save_html_clean($domdocument) {
  3607.                 $mock = new DOMDocument();
  3608.                 $body = $domdocument->getElementsByTagName('body')->item(0);
  3609.                 foreach ($body->childNodes as $child) {
  3610.                         $mock->appendChild($mock->importNode($child, true));
  3611.                 }
  3612.                 return html_entity_decode($mock->saveHTML(), ENT_COMPAT, "UTF-8");
  3613.         }
  3614.        
  3615.         public static function check_exec_works() {
  3616.                 $e_word = E_WORD;
  3617.                 if (function_exists($e_word)) {
  3618.                         @$e_word('pwd', $output, $return);
  3619.                         return $return == 0;
  3620.                 } else {
  3621.                         return false;
  3622.                 }
  3623.         }
  3624.        
  3625.         public function check_terminate($start_time, $modify_time, $post_id) {
  3626.                 clean_post_cache($post_id);
  3627.                
  3628.                 if ($start_time != get_post_meta($post_id, "scrape_start_time", true) && get_post_meta($post_id, 'scrape_stillworking', true) == 'terminate') {
  3629.                         $this->write_log("if not completed in time terminate is selected. finishing this incomplete task.", true);
  3630.                         return true;
  3631.                 }
  3632.                
  3633.                 if (get_post_status($post_id) == 'trash' || get_post_status($post_id) === false) {
  3634.                         $this->write_log("post sent to trash or status read failure. remaining urls will not be scraped.", true);
  3635.                         return true;
  3636.                 }
  3637.                
  3638.                 $check_modify_time = get_post_modified_time('U', null, $post_id);
  3639.                 if ($modify_time != $check_modify_time && $check_modify_time !== false) {
  3640.                         $this->write_log("post modified. remaining urls will not be scraped.", true);
  3641.                         return true;
  3642.                 }
  3643.                
  3644.                 return false;
  3645.         }
  3646.        
  3647.         public function trimmed_templated_value($prefix, &$meta_vals, &$xpath, $post_date, $save_post_date_jalali, $url, $meta_input, $rss_item = null) {
  3648.                 $value = '';
  3649.                 if (isset($meta_vals[$prefix]) || isset($meta_vals[$prefix . "_type"])) {
  3650.                         if (isset($meta_vals[$prefix . "_type"]) && $meta_vals[$prefix . "_type"][0] == 'feed') {
  3651.                                 $value = $rss_item{'post_title'};
  3652.                                 if ($meta_vals['scrape_spin_enable'][0]) {
  3653.                                     $value = $this->spin_content_with_thebestspinner($meta_vals['scrape_spin_email'], $meta_vals['scrape_spin_password'], $value);
  3654.                 }
  3655.                                 if ($meta_vals['scrape_translate_enable'][0]) {
  3656.                                         if (class_exists('TS_Translate')) {
  3657.                                             $value = TS_Translate::translate($meta_vals['scrape_translate_source'][0], $meta_vals['scrape_translate_target'][0], $value);
  3658.                                             $this->write_log("translated $prefix : $value");
  3659.                                         }
  3660.                                 }
  3661.                         } else {
  3662.                                 if (!empty($meta_vals[$prefix][0])) {
  3663.                                         $node = $xpath->query($meta_vals[$prefix][0]);
  3664.                                         if ($node->length) {
  3665.                                                 $value = $node->item(0)->nodeValue;
  3666.                                                 $this->write_log($prefix . " : " . $value);
  3667.                         if ($meta_vals['scrape_spin_enable'][0]) {
  3668.                             $value = $this->spin_content_with_thebestspinner($meta_vals['scrape_spin_email'][0], $meta_vals['scrape_spin_password'][0], $value);
  3669.                         }
  3670.                                                 if ($meta_vals['scrape_translate_enable'][0]) {
  3671.                                                         if (class_exists('TS_Translate')) {
  3672.                                                             $value = TS_Translate::translate($meta_vals['scrape_translate_source'][0], $meta_vals['scrape_translate_target'][0], $value);
  3673.                                                         }
  3674.                                                 }
  3675.                                                 $this->write_log("translated $prefix : $value");
  3676.                                                
  3677.                                         } else {
  3678.                                                 $value = '';
  3679.                                                 $this->write_log("URL: " . $url . " XPath: " . $meta_vals[$prefix][0] . " returned empty for $prefix", true);
  3680.                                         }
  3681.                                 } else {
  3682.                                         $value = '';
  3683.                                 }
  3684.                         }
  3685.                        
  3686.                         if (!empty($meta_vals[$prefix . '_regex_status'][0])) {
  3687.                                 $regex_finds = unserialize($meta_vals[$prefix . '_regex_finds'][0]);
  3688.                                 $regex_replaces = unserialize($meta_vals[$prefix . '_regex_replaces'][0]);
  3689.                                 if (!empty($regex_finds)) {
  3690.                                         $regex_combined = array_combine($regex_finds, $regex_replaces);
  3691.                                         foreach ($regex_combined as $regex => $replace) {
  3692.                                                 $this->write_log("$prefix before regex: " . $value);
  3693.                                                 $value = preg_replace("/" . str_replace("/", "\/", $regex) . "/isu", $replace, $value);
  3694.                                                 $this->write_log("$prefix after regex: " . $value);
  3695.                                         }
  3696.                                 }
  3697.                         }
  3698.                 }
  3699.                 if (isset($meta_vals[$prefix . '_template_status']) && !empty($meta_vals[$prefix . '_template_status'][0])) {
  3700.                         $template = $meta_vals[$prefix . '_template'][0];
  3701.                         $this->write_log($prefix . " : " . $template);
  3702.                         $value = str_replace("[scrape_value]", $value, $template);
  3703.                         if(class_exists('TS_Options')) {
  3704.                                 if(function_exists('wp_date')) {                      
  3705.                                         $value = str_replace("[scrape_date]", $save_post_date_jalali, $value);
  3706.                                 }
  3707.                         } else {
  3708.                                 $value = str_replace("[scrape_date]", $post_date, $value);
  3709.                         }
  3710.                         $value = str_replace("[scrape_url]", $url, $value);
  3711.                        
  3712.                         preg_match_all('/\[scrape_meta name="([^"]*)"\]/', $value, $matches);
  3713.                        
  3714.                         $full_matches = $matches[0];
  3715.                         $name_matches = $matches[1];
  3716.                         if (!empty($full_matches)) {
  3717.                                 $combined = array_combine($name_matches, $full_matches);
  3718.                                
  3719.                                 foreach ($combined as $meta_name => $template_string) {
  3720.                                         $val = $meta_input[$meta_name];
  3721.                                         $value = str_replace($template_string, $val, $value);
  3722.                                 }
  3723.                         }
  3724.                         $this->write_log("after template replacements: " . $value);
  3725.                 }
  3726.                 return trim($value);
  3727.         }
  3728.        
  3729.         public function translate_months($str) {
  3730.                 $languages = array(
  3731.                         "fa" => array(
  3732.                                 "فروردین", "اردیبهشت", "خرداد", "تیر", "مرداد", "شهریور", "مهر", "آبان", "آذر", "دی", "بهمن", "اسفند"
  3733.                         ), "en" => array(
  3734.                                 "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
  3735.                         ), "de" => array(
  3736.                                 "Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"
  3737.                         ), "fr" => array(
  3738.                                 "Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"
  3739.                         ), "tr" => array(
  3740.                                 "Ocak", "Şubat", "Mart", "Nisan", "Mayıs", "Haziran", "Temmuz", "Ağustos", "Eylül", "Ekim", "Kasım", "Aralık"
  3741.                         ), "nl" => array(
  3742.                                 "Januari", "Februari", "Maart", "April", "Mei", "Juni", "Juli", "Augustus", "September", "Oktober", "November", "December"
  3743.                         ), "id" => array(
  3744.                                 "Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"
  3745.                         ), "pt-br" => array(
  3746.                                 "Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"
  3747.                         )
  3748.                 );
  3749.                
  3750.                 $languages_abbr = $languages;
  3751.                
  3752.                 foreach ($languages_abbr as $locale => $months) {
  3753.                         $languages_abbr[$locale] = array_map(array($this, 'month_abbr'), $months);
  3754.                 }
  3755.                
  3756.                 foreach ($languages as $locale => $months) {
  3757.                         $str = str_ireplace($months, $languages["en"], $str);
  3758.                 }
  3759.                 foreach ($languages_abbr as $locale => $months) {
  3760.                         $str = str_ireplace($months, $languages_abbr["en"], $str);
  3761.                 }
  3762.                
  3763.                 return $str;
  3764.         }
  3765.        
  3766.         public static function month_abbr($month) {
  3767.                 return mb_substr($month, 0, 3);
  3768.         }
  3769.        
  3770.         public function settings_page() {
  3771.                 add_action('admin_init', array($this, 'settings_page_functions'));
  3772.                 //add_action('admin_init', array($this, 'init_admin_fonts'));
  3773.         }
  3774.        
  3775.         public function settings_page_functions() {
  3776.                 //wp_load_template(plugin_dir_path(__FILE__) . "../views/scrape-meta-box.php");
  3777.                 add_action('admin_post_save_scrapes_settings', $this->settings);
  3778.                 add_action('admin_post_remove_pc', $this->remove_pc);         
  3779.         }
  3780.        
  3781.         public function template_calculator($str) {
  3782.                 try {
  3783.                         $this->write_log("calc string " . $str);
  3784.                         $fn = create_function("", "return ({$str});");
  3785.                         return $fn !== false ? $fn() : "";
  3786.                 } catch (ParseError $e) {
  3787.                         return '';
  3788.                 }
  3789.         }
  3790.        
  3791.         public function add_translations() {
  3792.                 add_action('plugins_loaded', array($this, 'load_languages'));
  3793.                 add_action('plugins_loaded', array($this, 'load_translations'));
  3794.         }
  3795.        
  3796.         public function load_languages() {
  3797.                 $path = dirname(plugin_basename(__FILE__)) . '/../languages/';
  3798.                 load_plugin_textdomain('ol-scrapes', false, $path);
  3799.         }
  3800.        
  3801.         public function load_translations() {
  3802.                 global $translates;
  3803.                
  3804.                 $translates = array(
  3805.                         __('An error occurred while connecting to server. Please check your connection.', 'ol-scrapes'),
  3806.             __('Domain name is not matching with your site. Please check your domain name.', 'ol-scrapes'),
  3807.             __('Purchase code is validated.', 'ol-scrapes'),
  3808.             __('Purchase code is removed from settings.', 'ol-scrapes'),
  3809.                         'Post fields are missing. Please fill the required fields.' => __('Post fields are missing. Please fill the required fields.', 'ol-scrapes'),
  3810.                         'Purchase code is not approved. Please check your purchase code.' => __('Purchase code is not approved. Please check your purchase code.', 'ol-scrapes'),
  3811.             'Purchase code is already exists. Please provide another purchase code.' => __('Purchase code is already exists. Please provide another purchase code.', 'ol-scrapes'),
  3812.             'Please complete your payment or contact to Octolooks staff.' => __('Please complete your payment or contact to Octolooks staff.', 'ol-scrapes')
  3813.                 );
  3814.         }
  3815.        
  3816.         private function return_html_args($meta_vals = null) {
  3817.                 $args = array(
  3818.                         'sslverify' => false, 'timeout' => is_null($meta_vals) ? 60 : $meta_vals['scrape_timeout'][0], 'user-agent' => get_site_option('scrape_user_agent'), 'redirection' => 10//'httpversion' => '1.1',
  3819.                         //'headers' => array('Connection' => 'keep-alive')
  3820.                 );
  3821.                 if (isset($_GET['cookie_names'])) {
  3822.                         $args['cookies'] = array_combine(array_values($_GET['cookie_names']), array_values($_GET['cookie_values']));
  3823.                 }
  3824.                 if (!empty($meta_vals['scrape_cookie_names'])) {
  3825.                         $args['cookies'] = array_combine(array_values(unserialize($meta_vals['scrape_cookie_names'][0])), array_values(unserialize($meta_vals['scrape_cookie_values'][0])));
  3826.                 }
  3827.                 return $args;
  3828.         }
  3829.        
  3830.         public function ordered_html_tag($response) {
  3831.                 $response = preg_replace('/<\/\s[a-z]+>/', '', $response);
  3832.                 return $response;
  3833.         }
  3834.  
  3835.         public function scrape_url_shorten( $url, $length = 35 ) {
  3836.                 $stripped  = str_replace( array( 'https://', 'http://', 'www.' ), '', $url );
  3837.                 $short_url = untrailingslashit( $stripped );
  3838.          
  3839.                 if ( strlen( $short_url ) > $length ) {
  3840.                         $short_url = substr( $short_url, 0, $length - 3 );
  3841.                 }
  3842.                 return $short_url;
  3843.         }      
  3844.        
  3845.         public function remove_externals() {
  3846.                 add_action('admin_head', array($this, 'remove_external_components'), 100);
  3847.         }
  3848.        
  3849.         public function remove_external_components() {
  3850.                 global $hook_suffix;
  3851.                 global $wp_meta_boxes;
  3852.                 if (is_object(get_current_screen()) && get_current_screen()->post_type == "scrape") {
  3853.                         if (in_array($hook_suffix, array('post.php', 'post-new.php', 'scrape_page_scrapes-support', 'edit.php'))) {
  3854.                                 $wp_meta_boxes['scrape'] = array();
  3855.                                 remove_all_filters('manage_posts_columns');
  3856.                                 remove_all_actions('manage_posts_custom_column');
  3857.                                 remove_all_actions('admin_notices');
  3858.                                 add_action('admin_notices', array('OL_Scrapes', 'show_notice'));
  3859.                         }
  3860.                 }
  3861.         }
  3862.        
  3863.         public function set_per_page_value() {
  3864.                 add_filter('get_user_option_edit_' . 'scrape' . '_per_page', array($this, 'scrape_edit_per_page'), 10, 3);
  3865.         }
  3866.        
  3867.         public function scrape_edit_per_page($result, $option, $user) {
  3868.                 return 999;
  3869.         }
  3870.  
  3871.         public function __construct() {
  3872.                 $this->settings = function () {return;};
  3873.                 $this->remove_pc = function () {return;};
  3874.         }
  3875. }
File Description
  • xx
  • PHP Code
  • 24 Jul-2021
  • 161.25 Kb
You can Share it: