← Back
Editing: fbomatic-facebook-post-generator.php
<?php /** Plugin Name: F-omatic Automatic Post Generator Plugin URI: //1.envato.market/coderevolution Description: This plugin will generate content for you, even in your sleep using Facebook public group feeds. Author: CodeRevolution Version: 3.4.6.2 Author URI: //coderevolution.ro License: Commercial. For personal use only. Not to give away or resell. Text Domain: fbomatic-facebook-post-generator */ /* Copyright 2016 - 2026 CodeRevolution */ defined('ABSPATH') or die(); require_once (dirname(__FILE__) . "/res/other/plugin-dash.php"); function fbomatic_get_version() { $plugin_data = get_file_data( __FILE__ , array('Version' => 'Version'), false); return $plugin_data['Version']; } function fbomatic_load_textdomain() { load_plugin_textdomain( 'fbomatic-facebook-post-generator', false, basename( dirname( __FILE__ ) ) . '/languages' ); } add_action( 'init', 'fbomatic_load_textdomain' ); function fbomatic_fixup_json($json_part){ $json_string = '["' . $json_part . '"]'; $json = json_decode($json_string) ; return $json[0]; } function fbomatic_fix_json_part($json_part){ $json_string = '["' . $json_part . '"]'; $json = json_decode($json_string) ; return $json[0]; } function fbomatic_curl_exec_special(&$ch) { $max_redir = 3; for ($i = 0; $i < $max_redir; $i++) { $exec = curl_exec($ch); $info = curl_getinfo($ch); if (stristr($exec, 'http-equiv="refresh"') && $info['http_code'] == 200 && !stristr($exec, '_fb_noscript')) { preg_match('{<meta.*?http-equiv="refresh".*?>}', $exec, $redirectMatch); if (isset($redirectMatch[0]) && trim($redirectMatch[0]) != '') { preg_match('#\bhttps?://[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/))#', $redirectMatch[0], $urlMatchs); if (isset($urlMatchs[0]) && stristr($urlMatchs[0], 'http')) { $info['http_code'] = 302; $info['redirect_url'] = $urlMatchs[0]; } } } elseif (stristr($exec, 'location.replace')) { preg_match('{location\.replace\((.*?)\)}', $exec, $loc_matches); $possible_redirect = isset($loc_matches[1]) ? $loc_matches[1] : ''; if (stristr($possible_redirect, 'http')) { $possible_redirect = str_replace(array( "'", '"', ), '', $possible_redirect); $info['http_code'] = 302; $info['redirect_url'] = trim($possible_redirect); } } if ($info['http_code'] == 301 || $info['http_code'] == 302) { if (trim($info['redirect_url']) == '') { $info['redirect_url'] = curl_getinfo($ch, CURLINFO_REDIRECT_URL); if (trim($info['redirect_url']) == '') { if (stristr($exec, 'Location:')) { preg_match('{Location:(.*)}', $exec, $loc_matches); $redirect_url = trim($loc_matches[1]); if (trim($redirect_url) != '') { $info['redirect_url'] = $redirect_url; } } } } if (stristr($info['redirect_url'], 'mbasic.facebook')) { $info['redirect_url'] = str_replace('%20', '', $info['redirect_url']); } curl_setopt($ch, CURLOPT_HTTPGET, 1); curl_setopt($ch, CURLOPT_URL, trim($info['redirect_url'])); $exec = curl_exec($ch); } else { break; } } return $exec; } function fbomatic_json_fix($json_part) { $json_string = '["' . $json_part . '"]'; $json = json_decode($json_string) ; if(isset($json[0])) { return $json[0]; } else { return $json_part; } } function fbomatic_assign_var(&$target, $var, $root = false) { static $cnt = 0; $key = key($var); if(is_array($var[$key])) fbomatic_assign_var($target[$key], $var[$key], false); else { if($key==0) { if($cnt == 0 && $root == true) { $target['_fbomaticr_nonce'] = $var[$key]; $cnt++; } elseif($cnt == 1 && $root == true) { $target['_wp_http_referer'] = $var[$key]; $cnt++; } else { $target[] = $var[$key]; } } else { $target[$key] = $var[$key]; } } } $plugin = plugin_basename(__FILE__); if(is_admin()) { if($_SERVER["REQUEST_METHOD"]==="POST" && !empty($_POST["coderevolution_max_input_var_data"])) { $vars = explode("&", $_POST["coderevolution_max_input_var_data"]); $coderevolution_max_input_var_data = array(); foreach($vars as $var) { parse_str($var, $variable); fbomatic_assign_var($_POST, $variable, true); } unset($_POST["coderevolution_max_input_var_data"]); } $plugin_slug = explode('/', $plugin); $plugin_slug = $plugin_slug[0]; if(isset($_POST[$plugin_slug . '_register']) && isset($_POST[$plugin_slug. '_register_code']) && trim($_POST[$plugin_slug . '_register_code']) != '') { update_option('coderevolution_settings_changed', 1); if((strlen(trim($_POST[$plugin_slug . '_register_code'])) != 36 && strlen(trim($_POST[$plugin_slug . '_register_code'])) != 41) || strstr($_POST[$plugin_slug . '_register_code'], '-') == false) { fbomatic_log_to_file('Invalid registration code submitted: ' . $_POST[$plugin_slug . '_register_code']); } else { $ch = curl_init('https://wpinitiate.com/verify-purchase/purchase.php'); if($ch !== false) { $data = array(); $data['code'] = trim($_POST[$plugin_slug . '_register_code']); $data['siteURL'] = get_bloginfo('url'); $data['siteName'] = get_bloginfo('name'); $data['siteEmail'] = get_bloginfo('admin_email'); $fdata = ""; foreach ($data as $key => $val) { $fdata .= "$key=" . urlencode(trim($val)) . "&"; } curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $fdata); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); curl_setopt($ch, CURLOPT_TIMEOUT, 60); $result = curl_exec($ch); if($result === false) { fbomatic_log_to_file('Failed to get verification response: ' . curl_error($ch)); } else { $rj = json_decode($result, true); if(isset($rj['error'])) { update_option('coderevolution_settings_changed', $rj['error']); } elseif(isset($rj['item_name'])) { $rj['code'] = $_POST[$plugin_slug . '_register_code']; if($rj['item_id'] == '19528972' || $rj['item_id'] == '13371337' || $rj['item_id'] == '19651107' || $rj['item_id'] == '19200046') { update_option($plugin_slug . '_registration', $rj); update_option('coderevolution_settings_changed', 2); } else { fbomatic_log_to_file('Invalid response from purchase code verification (are you sure you inputed the right purchase code?): ' . print_r($rj, true)); } } else { fbomatic_log_to_file('Invalid json from purchase code verification: ' . print_r($result, true)); } } curl_close($ch); } else { fbomatic_log_to_file('Failed to init curl when trying to make purchase verification.'); } } } if(isset($_POST[$plugin_slug . '_revoke_license']) && trim($_POST[$plugin_slug . '_revoke_license']) != '') { $ch = curl_init('https://wpinitiate.com/verify-purchase/revoke.php'); if($ch !== false) { $data = array(); $data['siteURL'] = get_bloginfo('url'); $fdata = ""; foreach ($data as $key => $val) { $fdata .= "$key=" . urlencode(trim($val)) . "&"; } curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $fdata); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); curl_setopt($ch, CURLOPT_TIMEOUT, 60); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); $result = curl_exec($ch); if($result === false) { fbomatic_log_to_file('Failed to revoke verification response: ' . curl_error($ch)); update_option($plugin_slug . '_registration', false); } else { update_option($plugin_slug . '_registration', false); } } else { fbomatic_log_to_file('Failed to init curl to revoke verification response.'); } } $uoptions = get_option($plugin_slug . '_registration', array()); if(isset($uoptions['item_id']) && isset($uoptions['item_name']) && isset($uoptions['created_at']) && isset($uoptions['buyer']) && isset($uoptions['licence']) && isset($uoptions['supported_until'])) { require "update-checker/plugin-update-checker.php"; $fwdu3dcarPUC = YahnisElsts\PluginUpdateChecker\v5\PucFactory::buildUpdateChecker("https://wpinitiate.com/auto-update/?action=get_metadata&slug=fbomatic-facebook-post-generator", __FILE__, "fbomatic-facebook-post-generator"); } else { add_action("after_plugin_row_{$plugin}", function( $plugin_file, $plugin_data, $status ) { $plugin_url = 'https://codecanyon.net/item/fbomatic-automatic-post-generator-and-facebook-auto-poster-plugin-for-wordpress/19528972'; echo '<tr class="active"><td> </td><td colspan="2"><p class="cr_auto_update">'; echo sprintf( wp_kses( __( 'The plugin is not registered. Automatic updating is disabled. Please purchase a license for it from <a href="%s" target="_blank">here</a> and register the plugin from the \'Main Settings\' menu using your purchase code. <a href="%s" target="_blank">How I find my purchase code?', 'fbomatic-facebook-post-generator'), array( 'a' => array( 'href' => array(), 'target' => array() ) ) ), esc_url_raw( 'https://1.envato.market/c/1264868/275988/4415?u=' . urlencode($plugin_url)), esc_url_raw('//www.youtube.com/watch?v=NElJ5t_Wd48') ); echo '</a></p> </td></tr>'; }, 10, 3 ); add_action('admin_enqueue_scripts', 'fbomatic_admin_enqueue_all'); add_filter("plugin_action_links_$plugin", 'fbomatic_add_activation_link'); } add_action('admin_menu', 'fbomatic_register_my_custom_menu_page'); add_action('network_admin_menu', 'fbomatic_register_my_custom_menu_page'); add_filter("plugin_action_links_$plugin", 'fbomatic_add_support_link'); add_filter("plugin_action_links_$plugin", 'fbomatic_add_settings_link'); add_filter("plugin_action_links_$plugin", 'fbomatic_add_rating_link'); add_action('add_meta_boxes', 'fbomatic_add_meta_box'); require(dirname(__FILE__) . "/res/fbomatic-main.php"); require(dirname(__FILE__) . "/res/fbomatic-rules-list.php"); require(dirname(__FILE__) . "/res/fbomatic-facebook-list.php"); require(dirname(__FILE__) . "/res/fbomatic-logs.php"); require(dirname(__FILE__) . "/res/fbomatic-offer.php"); } function fbomatic_admin_enqueue_all() { $reg_css_code = '.cr_auto_update{background-color:#fff8e5;margin:5px 20px 15px 20px;border-left:4px solid #fff;padding:12px 12px 12px 12px !important;border-left-color:#ffb900;}'; wp_register_style( 'fbomatic-plugin-reg-style', false ); wp_enqueue_style( 'fbomatic-plugin-reg-style' ); wp_add_inline_style( 'fbomatic-plugin-reg-style', $reg_css_code ); } function fbomatic_add_activation_link($links) { $settings_link = '<a href="admin.php?page=fbomatic_admin_settings">' . esc_html__('Activate Plugin License', 'fbomatic-facebook-post-generator') . '</a>'; array_push($links, $settings_link); return $links; } const FBOMATIC_API_VER = '25.0'; use \Eventviva\ImageResize; function fbomatic_register_my_custom_menu_page() { add_menu_page('F-omatic Post Generator', 'F-omatic Post Generator', 'manage_options', 'fbomatic_admin_settings', 'fbomatic_admin_settings', plugins_url('images/icon.png', __FILE__)); $main = add_submenu_page('fbomatic_admin_settings', esc_html__("Main Settings", 'fbomatic-facebook-post-generator'), esc_html__("Main Settings", 'fbomatic-facebook-post-generator'), 'manage_options', 'fbomatic_admin_settings'); add_action( 'load-' . $main, 'fbomatic_load_all_admin_js' ); add_action( 'load-' . $main, 'fbomatic_load_main_admin_js' ); $fbomatic_Main_Settings = get_option('fbomatic_Main_Settings', false); if (isset($fbomatic_Main_Settings['fbomatic_enabled']) && $fbomatic_Main_Settings['fbomatic_enabled'] == 'on') { $facebook = add_submenu_page('fbomatic_admin_settings', esc_html__('Facebook to Posts', 'fbomatic-facebook-post-generator'), esc_html__('Facebook to Posts', 'fbomatic-facebook-post-generator'), 'manage_options', 'fbomatic_items_panel', 'fbomatic_items_panel'); add_action( 'load-' . $facebook, 'fbomatic_load_admin_js' ); add_action( 'load-' . $facebook, 'fbomatic_load_all_admin_js' ); $post = add_submenu_page('fbomatic_admin_settings', esc_html__('Posts to Facebook', 'fbomatic-facebook-post-generator'), esc_html__('Posts to Facebook', 'fbomatic-facebook-post-generator'), 'manage_options', 'fbomatic_facebook_panel', 'fbomatic_facebook_panel'); add_action( 'load-' . $post, 'fbomatic_load_all_admin_js' ); add_action( 'load-' . $post, 'fbomatic_load_post_admin_js' ); $tips = add_submenu_page('fbomatic_admin_settings', esc_html__('Tips & Tricks', 'fbomatic-facebook-post-generator'), esc_html__('Tips & Tricks', 'fbomatic-facebook-post-generator'), 'manage_options', 'fbomatic_recommendations', 'fbomatic_recommendations'); add_action( 'load-' . $tips, 'fbomatic_load_all_admin_js' ); $logs = add_submenu_page('fbomatic_admin_settings', esc_html__("Activity & Logging", 'fbomatic-facebook-post-generator'), esc_html__("Activity & Logging", 'fbomatic-facebook-post-generator'), 'manage_options', 'fbomatic_logs', 'fbomatic_logs'); add_action( 'load-' . $logs, 'fbomatic_load_all_admin_js' ); } } function fbomatic_load_post_admin_js(){ add_action('admin_enqueue_scripts', 'fbomatic_admin_load_post_files'); } function fbomatic_admin_load_post_files() { wp_register_script('fbomatic-submitter-script', plugins_url('scripts/poster.js', __FILE__), false, '1.0.0'); wp_enqueue_script('fbomatic-submitter-script'); } function fbomatic_load_admin_js(){ add_action('admin_enqueue_scripts', 'fbomatic_enqueue_admin_js'); } function fbomatic_enqueue_admin_js(){ wp_enqueue_script('fbomatic-footer-script', plugins_url('scripts/footer.js', __FILE__), array('jquery'), false, true); $cr_miv = ini_get('max_input_vars'); if($cr_miv === null || $cr_miv === false || !is_numeric($cr_miv)) { $cr_miv = '9999999'; } $footer_conf_settings = array( 'max_input_vars' => $cr_miv, 'plugin_dir_url' => plugin_dir_url(__FILE__), 'ajaxurl' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('fbomatic-run-nonce') ); wp_localize_script('fbomatic-footer-script', 'mycustomsettings', $footer_conf_settings); wp_register_style('fbomatic-rules-style', plugins_url('styles/fbomatic-rules.css', __FILE__), false, '1.0.0'); wp_enqueue_style('fbomatic-rules-style'); } function fbomatic_load_main_admin_js(){ add_action('admin_enqueue_scripts', 'fbomatic_enqueue_main_admin_js'); } function fbomatic_enqueue_main_admin_js(){ $fbomatic_Main_Settings = get_option('fbomatic_Main_Settings', false); wp_enqueue_script('fbomatic-main-script', plugins_url('scripts/main.js', __FILE__), array('jquery')); if(!isset($fbomatic_Main_Settings['best_user'])) { $best_user = ''; } else { $best_user = $fbomatic_Main_Settings['best_user']; } if(!isset($fbomatic_Main_Settings['best_password'])) { $best_password = ''; } else { $best_password = $fbomatic_Main_Settings['best_password']; } $header_main_settings = array( 'best_user' => $best_user, 'best_password' => $best_password ); wp_localize_script('fbomatic-main-script', 'mycustommainsettings', $header_main_settings); } function fbomatic_load_all_admin_js(){ add_action('admin_enqueue_scripts', 'fbomatic_admin_load_files'); } function fbomatic_add_rating_link($links) { $settings_link = '<a href="//codecanyon.net/downloads" target="_blank" title="Rate"> <i class="wdi-rate-stars"><svg xmlns="https://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="#ffb900" stroke="#ffb900" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-star"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon></svg><svg xmlns="https://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="#ffb900" stroke="#ffb900" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-star"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon></svg><svg xmlns="https://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="#ffb900" stroke="#ffb900" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-star"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon></svg><svg xmlns="https://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="#ffb900" stroke="#ffb900" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-star"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon></svg><svg xmlns="https://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="#ffb900" stroke="#ffb900" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-star"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon></svg></i></a>'; array_push($links, $settings_link); return $links; } function fbomatic_add_support_link($links) { $settings_link = '<a href="//coderevolution.ro/knowledge-base/" target="_blank">' . esc_html__('Support', 'fbomatic-facebook-post-generator') . '</a>'; array_push($links, $settings_link); return $links; } function fbomatic_add_settings_link($links) { $settings_link = '<a href="admin.php?page=fbomatic_admin_settings">' . esc_html__('Settings', 'fbomatic-facebook-post-generator') . '</a>'; array_push($links, $settings_link); return $links; } function fbomatic_add_meta_box() { $fbomatic_Main_Settings = get_option('fbomatic_Main_Settings', false); if (isset($fbomatic_Main_Settings['fbomatic_enabled']) && $fbomatic_Main_Settings['fbomatic_enabled'] === 'on') { if (isset($fbomatic_Main_Settings['enable_metabox']) && $fbomatic_Main_Settings['enable_metabox'] == 'on') { foreach ( get_post_types( '', 'names' ) as $post_type ) { add_meta_box('fbomatic_meta_box_function_add', esc_html__('F-omatic Automatic Post Generator Information', 'fbomatic-facebook-post-generator'), 'fbomatic_meta_box_function', $post_type, 'advanced', 'default', array('__back_compat_meta_box' => true)); } } } } add_filter('cron_schedules', 'fbomatic_add_cron_schedule'); function fbomatic_add_cron_schedule($schedules) { $schedules['fbomatic_cron'] = array( 'interval' => 3600, 'display' => esc_html__('F-omatic Cron', 'fbomatic-facebook-post-generator') ); $schedules['minutely'] = array( 'interval' => 60, 'display' => esc_html__('Once A Minute', 'fbomatic-facebook-post-generator') ); $schedules['weekly'] = array( 'interval' => 604800, 'display' => esc_html__('Once Weekly', 'fbomatic-facebook-post-generator') ); $schedules['monthly'] = array( 'interval' => 2592000, 'display' => esc_html__('Once Monthly', 'fbomatic-facebook-post-generator') ); return $schedules; } function fbomatic_auto_clear_log() { global $wp_filesystem; if ( ! is_a( $wp_filesystem, 'WP_Filesystem_Base') ){ include_once(ABSPATH . 'wp-admin/includes/file.php');$creds = request_filesystem_credentials( site_url() ); wp_filesystem($creds); } if ($wp_filesystem->exists(trailingslashit(get_temp_dir()) . 'fbomatic_info.log')) { $wp_filesystem->delete(trailingslashit(get_temp_dir()) . 'fbomatic_info.log'); } } register_deactivation_hook(__FILE__, 'fbomatic_my_deactivation'); function fbomatic_my_deactivation() { wp_clear_scheduled_hook('fbomaticaction'); wp_clear_scheduled_hook('fbomaticactionclear'); $running = array(); update_option('fbomatic_running_list', $running, false); } add_action('fbomaticaction', 'fbomatic_cron'); add_action('fbomaticactionclear', 'fbomatic_auto_clear_log'); function fbomatic_cron_schedule() { $fbomatic_Main_Settings = get_option('fbomatic_Main_Settings', false); if (isset($fbomatic_Main_Settings['fbomatic_enabled']) && $fbomatic_Main_Settings['fbomatic_enabled'] === 'on') { if (!wp_next_scheduled('fbomaticaction')) { $unlocker = get_option('fbomatic_minute_running_unlocked', false); if($unlocker == '1') { $rez = wp_schedule_event(time(), 'minutely', 'fbomaticaction'); } else { $rez = wp_schedule_event(time(), 'hourly', 'fbomaticaction'); } if ($rez === FALSE) { fbomatic_log_to_file('[Scheduler] Failed to schedule fbomaticaction to fbomatic_cron!'); } } if (isset($fbomatic_Main_Settings['enable_logging']) && $fbomatic_Main_Settings['enable_logging'] === 'on' && isset($fbomatic_Main_Settings['auto_clear_logs']) && $fbomatic_Main_Settings['auto_clear_logs'] !== 'No') { if (!wp_next_scheduled('fbomaticactionclear')) { $rez = wp_schedule_event(time(), $fbomatic_Main_Settings['auto_clear_logs'], 'fbomaticactionclear'); if ($rez === FALSE) { fbomatic_log_to_file('[Scheduler] Failed to schedule fbomaticactionclear to ' . $fbomatic_Main_Settings['auto_clear_logs'] . '!'); } add_option('fbomatic_schedule_time', $fbomatic_Main_Settings['auto_clear_logs']); } else { if (!get_option('fbomatic_schedule_time')) { wp_clear_scheduled_hook('fbomaticactionclear'); $rez = wp_schedule_event(time(), $fbomatic_Main_Settings['auto_clear_logs'], 'fbomaticactionclear'); add_option('fbomatic_schedule_time', $fbomatic_Main_Settings['auto_clear_logs']); if ($rez === FALSE) { fbomatic_log_to_file('[Scheduler] Failed to schedule fbomaticactionclear to ' . $fbomatic_Main_Settings['auto_clear_logs'] . '!'); } } else { $the_time = get_option('fbomatic_schedule_time'); if ($the_time != $fbomatic_Main_Settings['auto_clear_logs']) { wp_clear_scheduled_hook('fbomaticactionclear'); delete_option('fbomatic_schedule_time'); $rez = wp_schedule_event(time(), $fbomatic_Main_Settings['auto_clear_logs'], 'fbomaticactionclear'); add_option('fbomatic_schedule_time', $fbomatic_Main_Settings['auto_clear_logs']); if ($rez === FALSE) { fbomatic_log_to_file('[Scheduler] Failed to schedule fbomaticactionclear to ' . $fbomatic_Main_Settings['auto_clear_logs'] . '!'); } } } } } else { if (!wp_next_scheduled('fbomaticactionclear')) { delete_option('fbomatic_schedule_time'); } else { wp_clear_scheduled_hook('fbomaticactionclear'); delete_option('fbomatic_schedule_time'); } } } else { if (wp_next_scheduled('fbomaticaction')) { wp_clear_scheduled_hook('fbomaticaction'); } if (!wp_next_scheduled('fbomaticactionclear')) { delete_option('fbomatic_schedule_time'); } else { wp_clear_scheduled_hook('fbomaticactionclear'); delete_option('fbomatic_schedule_time'); } } } function fbomatic_cron() { $GLOBALS['wp_object_cache']->delete('fbomatic_rules_list', 'options'); if (!get_option('fbomatic_rules_list')) { $rules = array(); } else { $rules = get_option('fbomatic_rules_list'); } $fbomatic_Main_Settings = get_option('fbomatic_Main_Settings', false); if (isset($fbomatic_Main_Settings['run_after']) && $fbomatic_Main_Settings['run_after'] != '' && isset($fbomatic_Main_Settings['run_before']) && $fbomatic_Main_Settings['run_before'] != '') { $exit = true; $mytime = date("H:i"); $min_time = $fbomatic_Main_Settings['run_after']; $max_time = $fbomatic_Main_Settings['run_before']; $date1 = DateTime::createFromFormat('H:i', $mytime); $date2 = DateTime::createFromFormat('H:i', $min_time); $date3 = DateTime::createFromFormat('H:i', $max_time); if ($date1 > $date2 && $date1 < $date3) { $exit = false; } if($exit == true) { return; } } $unlocker = get_option('fbomatic_minute_running_unlocked', false); if (!empty($rules)) { $cont = 0; foreach ($rules as $request => $bundle[]) { $bundle_values = array_values($bundle); $myValues = $bundle_values[$cont]; $array_my_values = array_values($myValues);for($iji=0;$iji<count($array_my_values);++$iji){if(is_string($array_my_values[$iji])){$array_my_values[$iji]=stripslashes($array_my_values[$iji]);}} $schedule = isset($array_my_values[1]) ? $array_my_values[1] : '24'; $active = isset($array_my_values[2]) ? $array_my_values[2] : '0'; $last_run = isset($array_my_values[3]) ? $array_my_values[3] : fbomatic_get_date_now(); if ($active == '1') { $now = fbomatic_get_date_now(); if($unlocker == '1') { $nextrun = fbomatic_add_minute($last_run, $schedule); $fbomatic_hour_diff = (int) fbomatic_minute_diff($now, $nextrun); } else { $nextrun = fbomatic_add_hour($last_run, $schedule); $fbomatic_hour_diff = (int) fbomatic_hour_diff($now, $nextrun); } if ($fbomatic_hour_diff >= 0) { fbomatic_run_rule($cont); } } $cont = $cont + 1; } $running = array(); update_option('fbomatic_running_list', $running); } } function fbomatic_minute_diff($date1, $date2) { $date1 = new DateTime($date1, fbomatic_get_blog_timezone()); $date2 = new DateTime($date2, fbomatic_get_blog_timezone()); $number1 = (int) $date1->format('U'); $number2 = (int) $date2->format('U'); return ($number1 - $number2); } function fbomatic_extractKeyWords($string, $count = 10) { $stopwords = array(); $string = trim(preg_replace('/\s\s+/iu', '\s', strtolower($string))); $string = wp_strip_all_tags($string); $matchWords = array_filter(explode(' ', $string), function($item) use ($stopwords) { return !($item == '' || in_array($item, $stopwords) || strlen($item) <= 2 || (function_exists('ctype_alnum') && ctype_alnum(trim(str_replace(' ', '', $item))) === FALSE) || is_numeric($item)); }); $wordCountArr = array_count_values($matchWords); arsort($wordCountArr); return array_keys(array_slice($wordCountArr, 0, $count)); } function fbomatic_log_to_file($str) { $fbomatic_Main_Settings = get_option('fbomatic_Main_Settings', false); if (isset($fbomatic_Main_Settings['enable_logging']) && $fbomatic_Main_Settings['enable_logging'] == 'on') { $tz = fbomatic_get_blog_timezone(); if($tz !== false) date_default_timezone_set($tz->getName()); $d = date("j-M-Y H:i:s e", time()); error_log("[$d] " . $str . "<br/>\r\n", 3, trailingslashit(get_temp_dir()) . 'fbomatic_info.log'); if($tz !== false) date_default_timezone_set('UTC'); } } function fbomatic_delete_all_posts() { $failed = false; $number = 0; $fbomatic_Main_Settings = get_option('fbomatic_Main_Settings', false); $post_list = array(); $postsPerPage = 50000; $paged = 0; do { $postOffset = $paged * $postsPerPage; $query = array( 'post_status' => array( 'publish', 'draft', 'pending', 'trash', 'private', 'future' ), 'post_type' => array( 'any' ), 'numberposts' => $postsPerPage, 'meta_key' => 'fbomatic_parent_rule', 'fields' => 'ids', 'offset' => $postOffset ); $got_me = get_posts($query); $post_list = array_merge($post_list, $got_me); $paged++; }while(!empty($got_me)); wp_suspend_cache_addition(true); foreach ($post_list as $post) { $index = get_post_meta($post, 'fbomatic_parent_rule', true); if (isset($index) && $index !== '') { $args = array( 'post_parent' => $post ); $post_attachments = get_children($args); if (isset($post_attachments) && !empty($post_attachments)) { foreach ($post_attachments as $attachment) { wp_delete_attachment($attachment->ID, true); } } $res = wp_delete_post($post, true); if ($res === false) { $failed = true; } else { $number++; } } } wp_suspend_cache_addition(false); if ($failed === true) { if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('[PostDelete] Failed to delete all posts!'); } } else { if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('[PostDelete] Successfuly deleted ' . esc_html($number) . ' posts!'); } } } function fbomatic_replaceContentShortcodesAgain($the_content, $item_cat, $item_tags) { $the_content = str_replace('%%item_cat%%', $item_cat, $the_content); $the_content = str_replace('%%item_tags%%', $item_tags, $the_content); $the_content = str_replace('%%auto_tax%%', $item_cat, $the_content); return $the_content; } function fbomatic_shortest_url_handle($href, $api_key) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "https://api.shorte.st/v1/data/url"); curl_setopt($ch, CURLOPT_POSTFIELDS, "urlToShorten=" . trim($href)); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); curl_setopt($ch, CURLOPT_TIMEOUT, 60); $headers = [ 'public-api-token: ' . $api_key, 'Content-Type: application/x-www-form-urlencoded' ]; curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); $serverOutput = json_decode(curl_exec($ch), true); curl_close($ch); if (!isset($serverOutput['shortenedUrl']) || $serverOutput['shortenedUrl'] == '') { return $href; } else { return esc_url_raw($serverOutput['shortenedUrl']); } } function fbomatic_replaceContentShortcodes($the_content, $just_title, $content, $item_url, $item_image, $description, $author, $author_link, $date, $custom_shortcodes_arr, $link, $screenimageURL = '') { $matches = array(); $i = 0; preg_match_all('~%regex\(\s*\"([^"]+?)\s*"\s*[,;]\s*\"([^"]*)\"\s*(?:[,;]\s*\"([^"]*?)\s*\")?(?:[,;]\s*\"([^"]*?)\s*\")?(?:[,;]\s*\"([^"]*?)\s*\")?\)%~si', $the_content, $matches); if (is_array($matches) && count($matches) && is_array($matches[0])) { for($i = 0; $i < count($matches[0]); $i++) { if (isset($matches[0][$i])) $fullmatch = $matches[0][$i]; if (isset($matches[1][$i])) $search_in = fbomatic_replaceContentShortcodes($matches[1][$i], $just_title, $content, $item_url, $item_image, $description, $author, $author_link, $date, $custom_shortcodes_arr, $link, $screenimageURL); if (isset($matches[2][$i])) $matchpattern = $matches[2][$i]; if (isset($matches[3][$i])) $element = $matches[3][$i]; if (isset($matches[4][$i])) $delimeter = $matches[4][$i];if (isset($matches[5][$i])) $counter = $matches[5][$i]; if (isset($matchpattern)) { if (preg_match('<^[\/#%+~[\]{}][\s\S]*[\/#%+~[\]{}]$>', $matchpattern, $z)) { $ret = preg_match_all($matchpattern, $search_in, $submatches, PREG_PATTERN_ORDER); } else { $ret = preg_match_all('~'.$matchpattern.'~si', $search_in, $submatches, PREG_PATTERN_ORDER); } } if (isset($submatches)) { if (is_array($submatches)) { $empty_elements = array_keys($submatches[0], ""); foreach ($empty_elements as $e) { unset($submatches[0][$e]); } $submatches[0] = array_unique($submatches[0]); if (!is_numeric($element)) { $element = 0; }if (!is_numeric($counter)) { $counter = 0; } if(isset($submatches[(int)($element)])) { $matched = $submatches[(int)($element)]; } else { $matched = ''; } $matched = array_unique((array)$matched); if (empty($delimeter) || $delimeter == 'null') { if (isset($matched[$counter])) $matched = $matched[$counter]; } else { $matched = implode($delimeter, $matched); } if (empty($matched)) { $the_content = str_replace($fullmatch, '', $the_content); } else { $the_content = str_replace($fullmatch, $matched, $the_content); } } } } } $spintax = new Fbomatic_Spintax(); $the_content = $spintax->process($the_content); $pcxxx = explode('<!- template ->', $the_content); $the_content = $pcxxx[array_rand($pcxxx)]; $the_content = str_replace('%%random_sentence%%', fbomatic_random_sentence_generator(), $the_content); $the_content = str_replace('%%random_sentence2%%', fbomatic_random_sentence_generator(false), $the_content); $fbomatic_Main_Settings = get_option('fbomatic_Main_Settings', false); if (isset($fbomatic_Main_Settings['custom_html'])) { $the_content = str_replace('%%custom_html%%', $fbomatic_Main_Settings['custom_html'], $the_content); } if (isset($fbomatic_Main_Settings['custom_html2'])) { $the_content = str_replace('%%custom_html2%%', $fbomatic_Main_Settings['custom_html2'], $the_content); } $shortened_url = fbomatic_url_handle($item_url); $the_content = str_replace('%%item_link%%', $link, $the_content); $the_content = str_replace('%%item_title%%', $just_title, $the_content); $the_content = str_replace('%%item_content%%', $content, $the_content); $the_content = str_replace('%%item_url%%', $shortened_url, $the_content); $the_content = str_replace('%%item_embed%%', fbomatic_get_embed($item_url), $the_content); $the_content = str_replace('%%item_date%%', $date, $the_content); $the_content = str_replace('%%item_content_plain_text%%', fbomatic_getPlainContent($content), $the_content); $the_content = str_replace('%%item_read_more_button%%', fbomatic_getReadMoreButton($shortened_url), $the_content); $the_content = str_replace('%%item_show_image%%', fbomatic_getItemImage($item_image), $the_content); $the_content = str_replace('%%item_image_URL%%', $item_image, $the_content); $the_content = str_replace('%%item_description%%', $description, $the_content); $the_content = str_replace('%%author%%', $author, $the_content); $the_content = str_replace('%%author_link%%', $author_link, $the_content); if($screenimageURL != '') { $the_content = str_replace('%%item_screenshot_url%%', esc_url_raw($screenimageURL), $the_content); $the_content = str_replace('%%item_show_screenshot%%', fbomatic_getItemImage(esc_url_raw($screenimageURL), $just_title), $the_content); } else { $snap = 'http://s.wordpress.com/mshots/v1/'; if (isset($fbomatic_Main_Settings['screenshot_height']) && $fbomatic_Main_Settings['screenshot_height'] != '') { $h = esc_attr($fbomatic_Main_Settings['screenshot_height']); } else { $h = '450'; } if (isset($fbomatic_Main_Settings['screenshot_width']) && $fbomatic_Main_Settings['screenshot_width'] != '') { $w = esc_attr($fbomatic_Main_Settings['screenshot_width']); } else { $w = '600'; } $the_content = str_replace('%%item_screenshot_url%%', esc_url_raw($snap . urlencode($item_url) . '?w=' . $w . '&h=' . $h), $the_content); $the_content = str_replace('%%item_show_screenshot%%', fbomatic_getItemImage(esc_url_raw($snap . urlencode($item_url) . '?w=' . $w . '&h=' . $h), $just_title), $the_content); } $like_code = '<div id="fb-root"></div> <div class="fb-like" data-href="" data-layout="button_count" data-action="like" data-size="small" data-show-faces="false" data-share="true"></div>'; $the_content = str_replace('%%facebook_like_button%%', $like_code, $the_content); $tmp = fbomatic_strip_html_tags($content); $rand_num = rand ( 5, 10); $tmp = wp_trim_words($tmp, $rand_num); $the_content = str_replace('%%item_short_content%%', $tmp, $the_content); foreach($custom_shortcodes_arr as $index => $csa) { $the_content = str_replace('%%' . $index . '%%', $csa, $the_content); } $the_content = fbomatic_replaceSynergyShortcodes($the_content); return $the_content; } function fbomatic_get_embed($item_url) { return '<div class="fb-post" data-href="' . $item_url . '" data-width="500" data-show-text="true"><blockquote cite="' . $item_url . '" class="fb-xfbml-parse-ignore">Posted on <a href="https://www.facebook.com/">Facebook</a></blockquote></div>'; } function fbomatic_add_my_custom_js() { $fbomatic_Main_Settings = get_option('fbomatic_Main_Settings', false); if (isset($fbomatic_Main_Settings['fbomatic_enabled']) && $fbomatic_Main_Settings['fbomatic_enabled'] === 'on') { if (!isset($fbomatic_Main_Settings['disable_scripts']) || $fbomatic_Main_Settings['disable_scripts'] !== 'on') { $inline_scr = '(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v'; if (isset($fbomatic_Main_Settings['api_version']) && $fbomatic_Main_Settings['api_version'] != 'default' && $fbomatic_Main_Settings['api_version'] != '') { $inline_scr .= $fbomatic_Main_Settings['api_version']; } else { $inline_scr .= FBOMATIC_API_VER; } $inline_scr .= '"; fjs.parentNode.insertBefore(js, fjs); }(document, "script", "facebook-jssdk"));'; wp_register_script( 'fbomatic-custom-js-footer', ''); wp_enqueue_script( 'fbomatic-custom-js-footer' ); wp_add_inline_script( 'fbomatic-custom-js-footer', $inline_scr ); } } } add_action('wp_enqueue_scripts', 'fbomatic_add_my_custom_js'); add_action('wp_ajax_fbomatic_my_action', 'fbomatic_my_action_callback'); function fbomatic_my_action_callback() { check_ajax_referer('fbomatic-run-nonce', 'nonce'); if ( ! current_user_can('edit_posts') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } $fbomatic_Main_Settings = get_option('fbomatic_Main_Settings', false); $failed = false; $del_id = $_POST['id']; $how = $_POST['how']; if($how == 'duplicate') { $GLOBALS['wp_object_cache']->delete('fbomatic_rules_list', 'options'); if (!get_option('fbomatic_rules_list')) { $rules = array(); } else { $rules = get_option('fbomatic_rules_list'); } if (!empty($rules)) { $found = 0; $cont = 0; foreach ($rules as $request => $bundle[]) { if ($cont == $del_id) { $copy_bundle = $rules[$request]; $rules[] = $copy_bundle; $found = 1; break; } $cont = $cont + 1; } if($found == 0) { fbomatic_log_to_file('fbomatic_rules_list index not found: ' . $del_id); echo 'nochange'; die(); } else { update_option('fbomatic_rules_list', $rules, false); echo 'ok'; die(); } } else { fbomatic_log_to_file('fbomatic_rules_list empty!'); echo 'nochange'; die(); } } $force_delete = true; $number = 0; if ($how == 'trash') { $force_delete = false; } $post_list = array(); $postsPerPage = 50000; $paged = 0; do { $postOffset = $paged * $postsPerPage; $query = array( 'post_status' => array( 'publish', 'draft', 'pending', 'trash', 'private', 'future' ), 'post_type' => array( 'any' ), 'numberposts' => $postsPerPage, 'meta_key' => 'fbomatic_parent_rule', 'fields' => 'ids', 'offset' => $postOffset ); $got_me = get_posts($query); $post_list = array_merge($post_list, $got_me); $paged++; }while(!empty($got_me)); wp_suspend_cache_addition(true); foreach ($post_list as $post) { $index = get_post_meta($post, 'fbomatic_parent_rule', true); if ($index == $del_id) { $args = array( 'post_parent' => $post ); $post_attachments = get_children($args); if (isset($post_attachments) && !empty($post_attachments)) { foreach ($post_attachments as $attachment) { wp_delete_attachment($attachment->ID, true); } } $res = wp_delete_post($post, $force_delete); if ($res === false) { $failed = true; } else { $number++; } } } wp_suspend_cache_addition(false); if ($failed === true) { if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('[PostDelete] Failed to delete all posts for rule id: ' . esc_html($del_id) . '!'); } echo 'failed'; } else { if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('[PostDelete] Successfuly deleted ' . esc_html($number) . ' posts for rule id: ' . esc_html($del_id) . '!'); } if ($number == 0) { echo 'nochange'; } else { echo 'ok'; } } die(); } add_action('wp_ajax_fbomatic_run_my_action', 'fbomatic_run_my_action_callback'); function fbomatic_run_my_action_callback() { check_ajax_referer('fbomatic-run-nonce', 'nonce'); if ( ! current_user_can('edit_posts') ) { wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 ); } $run_id = $_POST['id']; echo fbomatic_run_rule($run_id, 0); die(); } function fbomatic_repairHTML($text) { $text = htmlspecialchars_decode($text); $text = str_replace("< ", "<", $text); $text = str_replace(" >", ">", $text); $text = str_replace("= ", "=", $text); $text = str_replace(" =", "=", $text); $text = str_replace("\/ ", "\/", $text); $text = str_replace("</ iframe>", "</iframe>", $text); $text = str_replace("frameborder ", "frameborder=\"0\" allowfullscreen></iframe>", $text); $doc = new DOMDocument(); $doc->substituteEntities = false; $internalErrors = libxml_use_internal_errors(true); $doc->loadHTML('<?xml encoding="utf-8" ?>' . $text); libxml_use_internal_errors($internalErrors); $text = $doc->saveHTML(); $text = preg_replace('#<!DOCTYPE html PUBLIC "-\/\/W3C\/\/DTD HTML 4\.0 Transitional\/\/EN" "http:\/\/www\.w3\.org\/TR\/REC-html40\/loose\.dtd">(?:[^<]*)<\?xml encoding="utf-8" \?><html><body>(?:<p>)?#i', '', $text); $text = str_replace('</p></body></html>', '', $text); $text = str_replace('</body></html></p>', '', $text); $text = str_replace('</body></html>', '', $text); return $text; } $fbomatic_fatal = false; function fbomatic_clear_flag_at_shutdown($param) { $error = error_get_last(); if ($error !== null && $error['type'] === E_ERROR && $GLOBALS['fbomatic_fatal'] === false) { $GLOBALS['fbomatic_fatal'] = true; $running = array(); update_option('fbomatic_running_list', $running); fbomatic_log_to_file('[FATAL] Exit error: ' . $error['message'] . ', file: ' . $error['file'] . ', line: ' . $error['line'] . ' - rule ID: ' . $param . '!'); fbomatic_clearFromList($param); } else { fbomatic_clearFromList($param); } } function fbomatic_get_web_page($url, $cuser_cookie = '', $xs_cookie = '') { $content = false; $fbomatic_Main_Settings = get_option('fbomatic_Main_Settings', false); if (!isset($fbomatic_Main_Settings['proxy_url']) || $fbomatic_Main_Settings['proxy_url'] == '') { $cookies = array(); if($cuser_cookie != '' && $xs_cookie != '') { $cookies[] = new WP_Http_Cookie( array( 'name' => 'xs', 'value' => $xs_cookie ) ); $cookies[] = new WP_Http_Cookie( array( 'name' => 'c_user', 'value' => $cuser_cookie ) ); $cookies[] = new WP_Http_Cookie( array( 'name' => 'datr', 'value' => 'QGgFYdhWgha-QOwFUUksCDTg' ) ); } $args = array( 'timeout' => 15, 'redirection' => 10, 'user-agent' => fbomatic_get_random_user_agent(), 'blocking' => true, 'headers' => array('sec-fetch-site: none', 'sec-fetch-mode: navigate','sec-fetch-user: ?1','sec-fetch-dest: document' ), 'cookies' => $cookies, 'body' => null, 'compress' => false, 'decompress' => true, 'sslverify' => false, 'stream' => false, 'filename' => null ); $ret_data = wp_remote_get(html_entity_decode($url), $args); $response_code = wp_remote_retrieve_response_code( $ret_data ); $response_message = wp_remote_retrieve_response_message( $ret_data ); if ( 200 != $response_code ) { } else { $content = wp_remote_retrieve_body( $ret_data ); } } if($content === false) { if(function_exists('curl_version') && filter_var($url, FILTER_VALIDATE_URL)) { $user_agent = fbomatic_get_random_user_agent(); $options = array( CURLOPT_CUSTOMREQUEST => "GET", CURLOPT_POST => false, CURLOPT_USERAGENT => $user_agent, CURLOPT_RETURNTRANSFER => true, CURLOPT_HEADER => false, CURLOPT_FOLLOWLOCATION => true, CURLOPT_ENCODING => "", CURLOPT_AUTOREFERER => true, CURLOPT_CONNECTTIMEOUT => 10, CURLOPT_TIMEOUT => 120, CURLOPT_MAXREDIRS => 10, CURLOPT_SSL_VERIFYHOST => 0, CURLOPT_SSL_VERIFYPEER => 0 ); $ch = curl_init($url); if ($ch === FALSE) { return FALSE; } if($cuser_cookie != '' && $xs_cookie != '') { curl_setopt ( $ch,CURLOPT_HTTPHEADER, array('sec-fetch-site: none', 'sec-fetch-mode: navigate','sec-fetch-user: ?1','sec-fetch-dest: document' )); curl_setopt($ch, CURLOPT_COOKIE, 'xs=' . $xs_cookie . ';c_user=' . $cuser_cookie . ';datr=Q-JAYGHTbnwdfy2CkEPlpo0F'); } curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); if (isset($fbomatic_Main_Settings['proxy_url']) && $fbomatic_Main_Settings['proxy_url'] != '') { curl_setopt($ch, CURLOPT_PROXY, $fbomatic_Main_Settings['proxy_url']); if (isset($fbomatic_Main_Settings['proxy_auth']) && $fbomatic_Main_Settings['proxy_auth'] != '') { curl_setopt($ch, CURLOPT_PROXYUSERPWD, $fbomatic_Main_Settings['proxy_auth']); } } curl_setopt_array($ch, $options); $content = curl_exec($ch); if($content == false) { fbomatic_log_to_file('[Warning] Curl error: ' . curl_error($ch)); } curl_close($ch); } else { $allowUrlFopen = preg_match('/1|yes|on|true/i', ini_get('allow_url_fopen')); if ($allowUrlFopen) { global $wp_filesystem; if ( ! is_a( $wp_filesystem, 'WP_Filesystem_Base') ){ include_once(ABSPATH . 'wp-admin/includes/file.php');$creds = request_filesystem_credentials( site_url() ); wp_filesystem($creds); } return $wp_filesystem->get_contents($url); } } } return $content; } function fbomatic_utf8_encode($str) { if(function_exists('mb_convert_encoding') && function_exists('mb_detect_encoding')) { $enc = mb_detect_encoding($str); if ($enc !== FALSE) { $str = mb_convert_encoding($str, 'UTF-8', $enc); } else { $str = mb_convert_encoding($str, 'UTF-8'); } } return $str; } function fbomatic_get_random_user_agent() { $agents = array( "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36" ); $rand = rand( 0, count( $agents ) - 1 ); return trim( $agents[ $rand ] ); } function fbomatic_generate_title($content, $backup, $fbomatic_Main_Settings) { $regexEmoticons = '/[\x{1F600}-\x{1F64F}]/u'; $content = preg_replace($regexEmoticons, '', $content); $regexSymbols = '/[\x{1F300}-\x{1F5FF}]/u'; $content = preg_replace($regexSymbols, '', $content); $regexTransport = '/[\x{1F680}-\x{1F6FF}]/u'; $content = preg_replace($regexTransport, '', $content); $regexMisc = '/[\x{2600}-\x{26FF}]/u'; $content = preg_replace($regexMisc, '', $content); $regexDingbats = '/[\x{2700}-\x{27BF}]/u'; $content = preg_replace($regexDingbats, '', $content); $pattern = "/[a-zA-Z]*[:\/\/]*[A-Za-z0-9\-_]+\.+[A-Za-z0-9\.\/%&=\?\-_]+/i"; $replacement = ""; $content = preg_replace($pattern, $replacement, $content); if (isset($fbomatic_Main_Settings['splitting_char']) && $fbomatic_Main_Settings['splitting_char'] != '') { $xsplit_arr = preg_split('/\r\n|\r|\n/', $fbomatic_Main_Settings['splitting_char']); foreach($xsplit_arr as $xsplit_it) { $xcontent = explode($xsplit_it, $content); $content = $xcontent[0]; } } if (isset($fbomatic_Main_Settings['max_title_words']) && $fbomatic_Main_Settings['max_title_words'] != '') { $cntx = intval($fbomatic_Main_Settings['max_title_words']); } else { $cntx = 14; } $return = trim(trim(trim(wp_trim_words($content, $cntx)), '.'), ','); if ($return == '') { $return = trim(trim(trim(wp_trim_words($backup, $cntx)), '.'), ','); } return $return; } function fbomatic_add_pixel() { $fbomatic_Main_Settings = get_option('fbomatic_Main_Settings', false); if (isset($fbomatic_Main_Settings['fbomatic_enabled']) && $fbomatic_Main_Settings['fbomatic_enabled'] == 'on') { if (isset($fbomatic_Main_Settings['fbomatic_pixel']) && $fbomatic_Main_Settings['fbomatic_pixel'] !== '') { echo $fbomatic_Main_Settings['fbomatic_pixel']; } } } function fbomatic_embed_facebook_video($atts) { if ( is_admin() ) { return; } extract(shortcode_atts(array( 'v' => '', 'width' => '560', 'height' => '' ), $atts)); if (strpos($v, 'http') !== false) { if (strpos($v, 'v=') !== false) { parse_str(parse_url($v, PHP_URL_QUERY), $params); if(isset($params['v'])) { $vid = $params['v']; } else { $vid = ''; } } else { $v = rtrim($v, '/'); $vid = substr($v, strrpos($v, '/') + 1); } $vid = trim($vid); } else { $vid = trim($v); } return '<p><center><div class="fb-video" data-href="https://www.facebook.com/facebook/videos/' . esc_html($vid) . '" data-allowfullscreen="true" data-width="' . esc_attr($width) . '"></div></center></p>'; } add_shortcode('fb-video-fbomatic', 'fbomatic_embed_facebook_video'); add_action('wp_head', 'fbomatic_add_pixel'); function fbomatic_getFacebookId($url, $access_token) { $id = substr(strrchr(trim($url, '/'), '/'), 1); global $wp_filesystem; if ( ! is_a( $wp_filesystem, 'WP_Filesystem_Base') ){ include_once(ABSPATH . 'wp-admin/includes/file.php');$creds = request_filesystem_credentials( site_url() ); wp_filesystem($creds); } $json = $wp_filesystem->get_contents('https://graph.facebook.com/' . $id . '?access_token=' . $access_token); if($json === false) { $json = fbomatic_get_web_page('https://graph.facebook.com/' . $id . '?access_token=' . $access_token); } if ($json == FALSE) { return FALSE; } $json = json_decode($json); if ($json == FALSE || !isset($json->id)) { return FALSE; } return $json->id; } function fbomatic_strip_images($content) { $content = preg_replace("/<img[^>]+\>/i", "", $content); return $content; } function fbomatic_strip_title($content, $title) { $content = str_replace($title, "", $content); return $content; } add_shortcode( 'fbomatic-display-posts', 'fbomatic_display_posts_shortcode' ); function fbomatic_display_posts_shortcode( $atts ) { if ( is_admin() ) { return; } $original_atts = $atts; $atts = shortcode_atts( array( 'author' => '', 'category' => '', 'category_display' => '', 'category_label' => 'Posted in: ', 'content_class' => 'content', 'date_format' => '(n/j/Y)', 'date' => '', 'date_column' => 'post_date', 'date_compare' => '=', 'date_query_before' => '', 'date_query_after' => '', 'date_query_column' => '', 'date_query_compare' => '', 'display_posts_off' => false, 'excerpt_length' => false, 'excerpt_more' => false, 'excerpt_more_link' => false, 'exclude_current' => false, 'id' => false, 'ignore_sticky_posts' => false, 'image_size' => false, 'include_author' => false, 'include_content' => false, 'include_date' => false, 'include_excerpt' => false, 'include_link' => true, 'include_title' => true, 'meta_key' => '', 'meta_value' => '', 'no_posts_message' => '', 'offset' => 0, 'order' => 'DESC', 'orderby' => 'date', 'post_parent' => false, 'post_status' => 'publish', 'post_type' => 'post', 'posts_per_page' => '10', 'tag' => '', 'tax_operator' => 'IN', 'tax_include_children' => true, 'tax_term' => false, 'taxonomy' => false, 'time' => '', 'title' => '', 'title_color' => '#000000', 'excerpt_color' => '#000000', 'link_to_source' => '', 'title_font_size' => '100%', 'excerpt_font_size' => '100%', 'read_more_text' => '', 'wrapper' => 'ul', 'wrapper_class' => 'display-posts-listing', 'wrapper_id' => false, 'ruleid' => '' ), $atts, 'display-posts' ); if( $atts['display_posts_off'] ) return; $author = sanitize_text_field( $atts['author'] ); $ruleid = sanitize_text_field( $atts['ruleid'] ); $category = sanitize_text_field( $atts['category'] ); $category_display = 'true' == $atts['category_display'] ? 'category' : sanitize_text_field( $atts['category_display'] ); $category_label = sanitize_text_field( $atts['category_label'] ); $content_class = array_map( 'sanitize_html_class', ( explode( ' ', $atts['content_class'] ) ) ); $date_format = sanitize_text_field( $atts['date_format'] ); $date = sanitize_text_field( $atts['date'] ); $date_column = sanitize_text_field( $atts['date_column'] ); $date_compare = sanitize_text_field( $atts['date_compare'] ); $date_query_before = sanitize_text_field( $atts['date_query_before'] ); $date_query_after = sanitize_text_field( $atts['date_query_after'] ); $date_query_column = sanitize_text_field( $atts['date_query_column'] ); $date_query_compare = sanitize_text_field( $atts['date_query_compare'] ); $excerpt_length = intval( $atts['excerpt_length'] ); $excerpt_more = sanitize_text_field( $atts['excerpt_more'] ); $excerpt_more_link = filter_var( $atts['excerpt_more_link'], FILTER_VALIDATE_BOOLEAN ); $exclude_current = filter_var( $atts['exclude_current'], FILTER_VALIDATE_BOOLEAN ); $id = $atts['id']; $ignore_sticky_posts = filter_var( $atts['ignore_sticky_posts'], FILTER_VALIDATE_BOOLEAN ); $image_size = sanitize_key( $atts['image_size'] ); $include_title = filter_var( $atts['include_title'], FILTER_VALIDATE_BOOLEAN ); $include_author = filter_var( $atts['include_author'], FILTER_VALIDATE_BOOLEAN ); $include_content = filter_var( $atts['include_content'], FILTER_VALIDATE_BOOLEAN ); $include_date = filter_var( $atts['include_date'], FILTER_VALIDATE_BOOLEAN ); $include_excerpt = filter_var( $atts['include_excerpt'], FILTER_VALIDATE_BOOLEAN ); $include_link = filter_var( $atts['include_link'], FILTER_VALIDATE_BOOLEAN ); $meta_key = sanitize_text_field( $atts['meta_key'] ); $meta_value = sanitize_text_field( $atts['meta_value'] ); $no_posts_message = sanitize_text_field( $atts['no_posts_message'] ); $offset = intval( $atts['offset'] ); $order = sanitize_key( $atts['order'] ); $orderby = sanitize_key( $atts['orderby'] ); $post_parent = $atts['post_parent']; $post_status = $atts['post_status']; $post_type = sanitize_text_field( $atts['post_type'] ); $posts_per_page = intval( $atts['posts_per_page'] ); $tag = sanitize_text_field( $atts['tag'] ); $tax_operator = $atts['tax_operator']; $tax_include_children = filter_var( $atts['tax_include_children'], FILTER_VALIDATE_BOOLEAN ); $tax_term = sanitize_text_field( $atts['tax_term'] ); $taxonomy = sanitize_key( $atts['taxonomy'] ); $time = sanitize_text_field( $atts['time'] ); $shortcode_title = sanitize_text_field( $atts['title'] ); $title_color = sanitize_text_field( $atts['title_color'] ); $excerpt_color = sanitize_text_field( $atts['excerpt_color'] ); $link_to_source = sanitize_text_field( $atts['link_to_source'] ); $excerpt_font_size = sanitize_text_field( $atts['excerpt_font_size'] ); $title_font_size = sanitize_text_field( $atts['title_font_size'] ); $read_more_text = sanitize_text_field( $atts['read_more_text'] ); $wrapper = sanitize_text_field( $atts['wrapper'] ); $wrapper_class = array_map( 'sanitize_html_class', ( explode( ' ', $atts['wrapper_class'] ) ) ); if( !empty( $wrapper_class ) ) $wrapper_class = ' class="' . implode( ' ', $wrapper_class ) . '"'; $wrapper_id = sanitize_html_class( $atts['wrapper_id'] ); if( !empty( $wrapper_id ) ) $wrapper_id = ' id="' . esc_html($wrapper_id) . '"'; $args = array( 'category_name' => $category, 'order' => $order, 'orderby' => $orderby, 'post_type' => explode( ',', $post_type ), 'posts_per_page' => $posts_per_page, 'tag' => $tag, ); if ( ! empty( $date ) || ! empty( $time ) || ! empty( $date_query_after ) || ! empty( $date_query_before ) ) { $initial_date_query = $date_query_top_lvl = array(); $valid_date_columns = array( 'post_date', 'post_date_gmt', 'post_modified', 'post_modified_gmt', 'comment_date', 'comment_date_gmt' ); $valid_compare_ops = array( '=', '!=', '>', '>=', '<', '<=', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ); $dates = fbomatic_sanitize_date_time( $date ); if ( ! empty( $dates ) ) { if ( is_string( $dates ) ) { $timestamp = strtotime( $dates ); $dates = array( 'year' => date( 'Y', $timestamp ), 'month' => date( 'm', $timestamp ), 'day' => date( 'd', $timestamp ), ); } foreach ( $dates as $arg => $segment ) { $initial_date_query[ $arg ] = $segment; } } $times = fbomatic_sanitize_date_time( $time, 'time' ); if ( ! empty( $times ) ) { foreach ( $times as $arg => $segment ) { $initial_date_query[ $arg ] = $segment; } } $before = fbomatic_sanitize_date_time( $date_query_before, 'date', true ); if ( ! empty( $before ) ) { $initial_date_query['before'] = $before; } $after = fbomatic_sanitize_date_time( $date_query_after, 'date', true ); if ( ! empty( $after ) ) { $initial_date_query['after'] = $after; } if ( ! empty( $date_query_column ) && in_array( $date_query_column, $valid_date_columns ) ) { $initial_date_query['column'] = $date_query_column; } if ( ! empty( $date_query_compare ) && in_array( $date_query_compare, $valid_compare_ops ) ) { $initial_date_query['compare'] = $date_query_compare; } if ( ! empty( $date_column ) && in_array( $date_column, $valid_date_columns ) ) { $date_query_top_lvl['column'] = $date_column; } if ( ! empty( $date_compare ) && in_array( $date_compare, $valid_compare_ops ) ) { $date_query_top_lvl['compare'] = $date_compare; } if ( ! empty( $initial_date_query ) ) { $date_query_top_lvl[] = $initial_date_query; } $args['date_query'] = $date_query_top_lvl; } $args['meta_key'] = 'fbomatic_parent_rule'; if($ruleid != '') { $args['meta_value'] = $ruleid; } if( $ignore_sticky_posts ) $args['ignore_sticky_posts'] = true; if( $id ) { $posts_in = array_map( 'intval', explode( ',', $id ) ); $args['post__in'] = $posts_in; } if( is_singular() && $exclude_current ) $args['post__not_in'] = array( get_the_ID() ); if( !empty( $author ) ) { if( 'current' == $author && is_user_logged_in() ) $args['author_name'] = wp_get_current_user()->user_login; elseif( 'current' == $author ) $unrelevar = false; else $args['author_name'] = $author; } if( !empty( $offset ) ) $args['offset'] = $offset; $post_status = explode( ', ', $post_status ); $validated = array(); $available = array( 'publish', 'pending', 'draft', 'auto-draft', 'future', 'private', 'inherit', 'trash', 'any' ); foreach ( $post_status as $unvalidated ) if ( in_array( $unvalidated, $available ) ) $validated[] = $unvalidated; if( !empty( $validated ) ) $args['post_status'] = $validated; if ( !empty( $taxonomy ) && !empty( $tax_term ) ) { if( 'current' == $tax_term ) { global $post; $terms = wp_get_post_terms(get_the_ID(), $taxonomy); $tax_term = array(); foreach ($terms as $term) { $tax_term[] = $term->slug; } }else{ $tax_term = explode( ', ', $tax_term ); } if( !in_array( $tax_operator, array( 'IN', 'NOT IN', 'AND' ) ) ) $tax_operator = 'IN'; $tax_args = array( 'tax_query' => array( array( 'taxonomy' => $taxonomy, 'field' => 'slug', 'terms' => $tax_term, 'operator' => $tax_operator, 'include_children' => $tax_include_children, ) ) ); $count = 2; $more_tax_queries = false; while( isset( $original_atts['taxonomy_' . $count] ) && !empty( $original_atts['taxonomy_' . $count] ) && isset( $original_atts['tax_' . esc_html($count) . '_term'] ) && !empty( $original_atts['tax_' . esc_html($count) . '_term'] ) ): $more_tax_queries = true; $taxonomy = sanitize_key( $original_atts['taxonomy_' . $count] ); $terms = explode( ', ', sanitize_text_field( $original_atts['tax_' . esc_html($count) . '_term'] ) ); $tax_operator = isset( $original_atts['tax_' . esc_html($count) . '_operator'] ) ? $original_atts['tax_' . esc_html($count) . '_operator'] : 'IN'; $tax_operator = in_array( $tax_operator, array( 'IN', 'NOT IN', 'AND' ) ) ? $tax_operator : 'IN'; $tax_include_children = isset( $original_atts['tax_' . esc_html($count) . '_include_children'] ) ? filter_var( $atts['tax_' . esc_html($count) . '_include_children'], FILTER_VALIDATE_BOOLEAN ) : true; $tax_args['tax_query'][] = array( 'taxonomy' => $taxonomy, 'field' => 'slug', 'terms' => $terms, 'operator' => $tax_operator, 'include_children' => $tax_include_children, ); $count++; endwhile; if( $more_tax_queries ): $tax_relation = 'AND'; if( isset( $original_atts['tax_relation'] ) && in_array( $original_atts['tax_relation'], array( 'AND', 'OR' ) ) ) $tax_relation = $original_atts['tax_relation']; $args['tax_query']['relation'] = $tax_relation; endif; $args = array_merge_recursive( $args, $tax_args ); } if( $post_parent !== false ) { if( 'current' == $post_parent ) { global $post; $post_parent = get_the_ID(); } $args['post_parent'] = intval( $post_parent ); } $wrapper_options = array( 'ul', 'ol', 'div' ); if( ! in_array( $wrapper, $wrapper_options ) ) $wrapper = 'ul'; $inner_wrapper = 'div' == $wrapper ? 'div' : 'li'; $listing = new WP_Query( apply_filters( 'display_posts_shortcode_args', $args, $original_atts ) ); if ( ! $listing->have_posts() ) { return apply_filters( 'display_posts_shortcode_no_results', wpautop( $no_posts_message ) ); } $inner = ''; wp_suspend_cache_addition(true); while ( $listing->have_posts() ): $listing->the_post(); global $post; $image = $date = $author = $excerpt = $content = ''; if ( $include_title && $include_link ) { if($link_to_source == 'yes') { $source_url = get_post_meta($post->ID, 'fbomatic_post_url', true); if($source_url != '') { $title = '<a class="fbomatic_display_title" href="' . esc_url_raw($source_url) . '"><span class="cr_display_span" >' . get_the_title() . '</span></a>'; } else { $title = '<a class="fbomatic_display_title" href="' . apply_filters( 'the_permalink', get_permalink() ) . '"><span class="cr_display_span" >' . get_the_title() . '</span></a>'; } } else { $title = '<a class="fbomatic_display_title" href="' . apply_filters( 'the_permalink', get_permalink() ) . '"><span class="cr_display_span" >' . get_the_title() . '</span></a>'; } } elseif( $include_title ) { $title = '<span class="fbomatic_display_title" class="cr_display_span">' . get_the_title() . '</span>'; } else { $title = ''; } if ( $image_size && has_post_thumbnail() && $include_link ) { if($link_to_source == 'yes') { $source_url = get_post_meta($post->ID, 'fbomatic_post_url', true); if($source_url != '') { $image = '<a class="fbomatic_display_image" href="' . esc_url_raw($source_url) . '">' . get_the_post_thumbnail( get_the_ID(), $image_size ) . '</a> <br/>'; } else { $image = '<a class="fbomatic_display_image" href="' . get_permalink() . '">' . get_the_post_thumbnail( get_the_ID(), $image_size ) . '</a> <br/>'; } } else { $image = '<a class="fbomatic_display_image" href="' . get_permalink() . '">' . get_the_post_thumbnail( get_the_ID(), $image_size ) . '</a> <br/>'; } } elseif( $image_size && has_post_thumbnail() ) { $image = '<span class="fbomatic_display_image">' . get_the_post_thumbnail( get_the_ID(), $image_size ) . '</span> <br/>'; } if ( $include_date ) $date = ' <span class="date">' . get_the_date( $date_format ) . '</span>'; if( $include_author ) $author = apply_filters( 'display_posts_shortcode_author', ' <span class="fbomatic_display_author">by ' . get_the_author() . '</span>', $original_atts ); if ( $include_excerpt ) { if( $excerpt_length || $excerpt_more || $excerpt_more_link ) { $length = $excerpt_length ? $excerpt_length : apply_filters( 'excerpt_length', 55 ); $more = $excerpt_more ? $excerpt_more : apply_filters( 'excerpt_more', '' ); $more = $excerpt_more_link ? ' <a href="' . get_permalink() . '">' . esc_html($more) . '</a>' : ' ' . esc_html($more); if( has_excerpt() && apply_filters( 'display_posts_shortcode_full_manual_excerpt', false ) ) { $excerpt = $post->post_excerpt . $more; } elseif( has_excerpt() ) { $excerpt = wp_trim_words( strip_shortcodes( $post->post_excerpt ), $length, $more ); } else { $excerpt = wp_trim_words( strip_shortcodes( $post->post_content ), $length, $more ); } } else { $excerpt = get_the_excerpt(); } $excerpt = ' <br/><br/> <span class="fbomatic_display_excerpt" class="cr_display_excerpt_adv">' . $excerpt . '</span>'; if($read_more_text != '') { if($link_to_source == 'yes') { $source_url = get_post_meta($post->ID, 'fbomatic_post_url', true); if($source_url != '') { $excerpt .= '<br/><a href="' . esc_url_raw($source_url) . '"><span class="fbomatic_display_excerpt" class="cr_display_excerpt_adv">' . esc_html($read_more_text) . '</span></a>'; } else { $excerpt .= '<br/><a href="' . get_permalink() . '"><span class="fbomatic_display_excerpt" class="cr_display_excerpt_adv">' . esc_html($read_more_text) . '</span></a>'; } } else { $excerpt .= '<br/><a href="' . get_permalink() . '"><span class="fbomatic_display_excerpt" class="cr_display_excerpt_adv">' . esc_html($read_more_text) . '</span></a>'; } } } if( $include_content ) { add_filter( 'shortcode_atts_display-posts', 'fbomatic_display_posts_off', 10, 3 ); $content = '<div class="' . implode( ' ', $content_class ) . '">' . apply_filters( 'the_content', get_the_content() ) . '</div>'; remove_filter( 'shortcode_atts_display-posts', 'fbomatic_display_posts_off', 10, 3 ); } $category_display_text = ''; if( $category_display && is_object_in_taxonomy( get_post_type(), $category_display ) ) { $terms = get_the_terms( get_the_ID(), $category_display ); $term_output = array(); foreach( $terms as $term ) $term_output[] = '<a href="' . get_term_link( $term, $category_display ) . '">' . esc_url_raw($term->name) . '</a>'; $category_display_text = ' <span class="category-display"><span class="category-display-label">' . esc_html($category_label) . '</span> ' . implode( ', ', $term_output ) . '</span>'; $category_display_text = apply_filters( 'display_posts_shortcode_category_display', $category_display_text ); } $class = array( 'listing-item' ); $class = array_map( 'sanitize_html_class', apply_filters( 'display_posts_shortcode_post_class', $class, $post, $listing, $original_atts ) ); $output = '<br/><' . esc_html($inner_wrapper) . ' class="' . implode( ' ', $class ) . '">' . $image . $title . $date . $author . $category_display_text . $excerpt . $content . '</' . esc_html($inner_wrapper) . '><br/><br/><hr class="cr_hr_dot"/>'; $inner .= apply_filters( 'display_posts_shortcode_output', $output, $original_atts, $image, $title, $date, $excerpt, $inner_wrapper, $content, $class ); endwhile; wp_reset_postdata(); wp_suspend_cache_addition(false); $open = apply_filters( 'display_posts_shortcode_wrapper_open', '<' . $wrapper . $wrapper_class . $wrapper_id . '>', $original_atts ); $close = apply_filters( 'display_posts_shortcode_wrapper_close', '</' . esc_html($wrapper) . '>', $original_atts ); $return = $open; if( $shortcode_title ) { $title_tag = apply_filters( 'display_posts_shortcode_title_tag', 'h2', $original_atts ); $return .= '<' . esc_html($title_tag) . ' class="display-posts-title">' . esc_html($shortcode_title) . '</' . esc_html($title_tag) . '>' . "\n"; } $return .= $inner . $close; $reg_css_code = '.cr_hr_dot{border-top: dotted 1px;}.cr_display_span{font-size:' . esc_html($title_font_size) . ';color:' . esc_html($title_color) . ' !important;}.cr_display_excerpt_adv{font-size:' . esc_html($excerpt_font_size) . ';color:' . esc_html($excerpt_color) . ' !important;}'; wp_register_style( 'fbomatic-display-style', false ); wp_enqueue_style( 'fbomatic-display-style' ); wp_add_inline_style( 'fbomatic-display-style', $reg_css_code ); return $return; } function fbomatic_sanitize_date_time( $date_time, $type = 'date', $accepts_string = false ) { if ( empty( $date_time ) || ! in_array( $type, array( 'date', 'time' ) ) ) { return array(); } $segments = array(); if ( true === $accepts_string && ( false !== strpos( $date_time, ' ' ) || false === strpos( $date_time, '-' ) ) ) { if ( false !== $timestamp = strtotime( $date_time ) ) { return $date_time; } } $parts = array_map( 'absint', explode( 'date' == $type ? '-' : ':', $date_time ) ); if ( 'date' == $type ) { $year = $month = $day = 1; if ( count( $parts ) >= 3 ) { list( $year, $month, $day ) = $parts; $year = ( $year >= 1 && $year <= 9999 ) ? $year : 1; $month = ( $month >= 1 && $month <= 12 ) ? $month : 1; $day = ( $day >= 1 && $day <= 31 ) ? $day : 1; } $segments = array( 'year' => $year, 'month' => $month, 'day' => $day ); } elseif ( 'time' == $type ) { $hour = $minute = $second = 0; switch( count( $parts ) ) { case 3 : list( $hour, $minute, $second ) = $parts; $hour = ( $hour >= 0 && $hour <= 23 ) ? $hour : 0; $minute = ( $minute >= 0 && $minute <= 60 ) ? $minute : 0; $second = ( $second >= 0 && $second <= 60 ) ? $second : 0; break; case 2 : list( $hour, $minute ) = $parts; $hour = ( $hour >= 0 && $hour <= 23 ) ? $hour : 0; $minute = ( $minute >= 0 && $minute <= 60 ) ? $minute : 0; break; default : break; } $segments = array( 'hour' => $hour, 'minute' => $minute, 'second' => $second ); } return apply_filters( 'display_posts_shortcode_sanitized_segments', $segments, $date_time, $type ); } function fbomatic_display_posts_off( $out, $pairs, $atts ) { $out['display_posts_off'] = apply_filters( 'display_posts_shortcode_inception_override', true ); return $out; } add_shortcode( 'fbomatic-list-posts', 'fbomatic_list_posts' ); function fbomatic_list_posts( $atts ) { if ( is_admin() ) { return; } ob_start(); extract( shortcode_atts( array ( 'type' => 'any', 'order' => 'ASC', 'orderby' => 'title', 'posts' => 50, 'posts_per_page' => 50, 'category' => '', 'ruleid' => '' ), $atts ) ); $options = array( 'post_type' => $type, 'order' => $order, 'orderby' => $orderby, 'posts_per_page' => $posts, 'category_name' => $category, 'meta_key' => 'fbomatic_parent_rule', 'meta_value' => $ruleid ); $query = new WP_Query( $options ); if ( $query->have_posts() ) { ?> <ul class="clothes-listing"> <?php while ( $query->have_posts() ) : $query->the_post(); ?> <li id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <a href="<?php echo esc_url_raw(get_permalink()); ?>"><?php echo esc_html(get_the_title());?></a> </li> <?php endwhile; wp_reset_postdata(); ?> </ul> <?php $myvariable = ob_get_clean(); return $myvariable; } return ''; } function fbomatic_clearFromList($param) { $GLOBALS['wp_object_cache']->delete('fbomatic_running_list', 'options'); $running = get_option('fbomatic_running_list'); if($running !== false) { $key = array_search($param, $running); if ($key !== FALSE) { unset($running[$key]); update_option('fbomatic_running_list', $running); } } } function fbomatic_copy_image_locally($image_url) { global $wp_filesystem; if ( ! is_a( $wp_filesystem, 'WP_Filesystem_Base') ){ include_once(ABSPATH . 'wp-admin/includes/file.php');$creds = request_filesystem_credentials( site_url() ); wp_filesystem($creds); } $upload_dir = wp_upload_dir(); if(substr( $image_url, 0, 10 ) === "data:image") { $data = explode(',', $image_url); if(isset($data[1])) { $image_data = base64_decode($data[1]); if($image_data === FALSE) { return false; } } else { return false; } preg_match('{data:image/(.*?);}', $image_url ,$ex_matches); if(isset($ex_matches[1])) { $image_url = 'image.' . $ex_matches[1]; } else { $image_url = 'image.jpg'; } } else { $image_data = fbomatic_get_web_page(html_entity_decode($image_url)); if ($image_data === FALSE || strpos($image_data, '<Message>Access Denied</Message>') !== FALSE || strpos($image_data, '<title>Just a moment...</title>') !== FALSE || strpos($image_data, '<html') !== FALSE) { return false; } } $filename = basename($image_url); $filename = explode("?", $filename); $filename = $filename[0]; $filename = urlencode($filename); $filename = str_replace('%', '-', $filename); $filename = str_replace('#', '-', $filename); $filename = str_replace('&', '-', $filename); $filename = str_replace('{', '-', $filename); $filename = str_replace('}', '-', $filename); $filename = str_replace('\\', '-', $filename); $filename = str_replace('<', '-', $filename); $filename = str_replace('>', '-', $filename); $filename = str_replace('*', '-', $filename); $filename = str_replace('/', '-', $filename); $filename = str_replace('$', '-', $filename); $filename = str_replace('\'', '-', $filename); $filename = str_replace('"', '-', $filename); $filename = str_replace(':', '-', $filename); $filename = str_replace('@', '-', $filename); $filename = str_replace('+', '-', $filename); $filename = str_replace('|', '-', $filename); $filename = str_replace('=', '-', $filename); $filename = str_replace('`', '-', $filename); $file_parts = pathinfo($filename); switch($file_parts['extension']) { case "": $filename .= 'jpg'; break; case NULL: $filename .= '.jpg'; break; } if (wp_mkdir_p($upload_dir['path'] . '/localimages')) { $file = $upload_dir['path'] . '/localimages/' . $filename; $ret_path = $upload_dir['url'] . '/localimages/' . $filename; } else { $file = $upload_dir['basedir'] . '/' . $filename; $ret_path = $upload_dir['baseurl'] . '/' . $filename; } if($wp_filesystem->exists($file)) { if(empty($file_parts['extension'])) { $file_parts['extension'] = 'jpg'; } $unid = uniqid(); $file .= $unid . '.' . $file_parts['extension']; $ret_path .= $unid . '.' . $file_parts['extension']; } $validate = wp_check_filetype_and_ext($file, $filename); if (empty($validate['type']) || !in_array($validate['ext'], ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'tif', 'tiff', 'avif', 'heic', 'heif', 'ico'])) { return false; } $ret = $wp_filesystem->put_contents($file, $image_data); if ($ret === FALSE) { return false; } $wp_filetype = wp_check_filetype( $file, null ); $attachment = array( 'post_mime_type' => $wp_filetype['type'], 'post_title' => sanitize_file_name( $file ), 'post_content' => '', 'post_status' => 'inherit' ); $screens_attach_id = wp_insert_attachment( $attachment, $file ); require_once( ABSPATH . 'wp-admin/includes/image.php' ); require_once( ABSPATH . 'wp-admin/includes/media.php' ); $attach_data = wp_generate_attachment_metadata( $screens_attach_id, $file ); wp_update_attachment_metadata( $screens_attach_id, $attach_data ); return $ret_path; } function fbomatic_replaceSynergyShortcodes($the_content) { $regex = '#%%([a-z0-9]+?)(?:_title)?_(\d+?)_(\d+?)%%#'; $rezz = preg_match_all($regex, $the_content, $matches); if ($rezz === FALSE) { return $the_content; } if(isset($matches[1][0])) { $two_var_functions = array('pdfomatic'); $three_var_functions = array('bhomatic', 'crawlomatic', 'dmomatic', 'ezinomatic', 'fbomatic', 'flickomatic', 'imguromatic', 'iui', 'instamatic', 'linkedinomatic', 'mediumomatic', 'pinterestomatic', 'echo', 'spinomatic', 'tumblomatic', 'wordpressomatic', 'wpcomomatic', 'youtubomatic', 'mastermind', 'businessomatic'); $four_var_functions = array('aiomatic', 'contentomatic', 'quoramatic', 'newsomatic', 'aliomatic', 'amazomatic', 'blogspotomatic', 'bookomatic', 'careeromatic', 'cbomatic', 'cjomatic', 'craigomatic', 'ebayomatic', 'etsyomatic', 'rakutenomatic', 'learnomatic', 'eventomatic', 'gameomatic', 'gearomatic', 'giphyomatic', 'gplusomatic', 'hackeromatic', 'imageomatic', 'midas', 'movieomatic', 'nasaomatic', 'ocartomatic', 'okomatic', 'playomatic', 'recipeomatic', 'redditomatic', 'soundomatic', 'mp3omatic', 'ticketomatic', 'tmomatic', 'trendomatic', 'tuneomatic', 'twitchomatic', 'twitomatic', 'vimeomatic', 'viralomatic', 'vkomatic', 'walmartomatic', 'bestbuyomatic', 'wikiomatic', 'xlsxomatic', 'yelpomatic', 'yummomatic'); for ($i = 0; $i < count($matches[1]); $i++) { $replace_me = false; if(in_array($matches[1][$i], $four_var_functions)) { $za_function = $matches[1][$i] . '_run_rule'; if(function_exists($za_function)) { $xreflection = new ReflectionFunction($za_function); if($xreflection->getNumberOfParameters() >= 4) { $rule_runner = $za_function($matches[3][$i], $matches[2][$i], 0, 1); if($rule_runner != 'fail' && $rule_runner != 'nochange' && $rule_runner != 'ok' && $rule_runner !== false) { if(is_array($rule_runner)) { $the_content = str_replace('%%' . $matches[1][$i] . '_' . $matches[2][$i] . '_' . $matches[3][$i] . '%%', $rule_runner[0], $the_content); $the_content = str_replace('%%' . $matches[1][$i] . '_title_' . $matches[2][$i] . '_' . $matches[3][$i] . '%%', $rule_runner[1], $the_content); } else { $the_content = str_replace('%%' . $matches[1][$i] . '_' . $matches[2][$i] . '_' . $matches[3][$i] . '%%', $rule_runner, $the_content); $the_content = str_replace('%%' . $matches[1][$i] . '_title_' . $matches[2][$i] . '_' . $matches[3][$i] . '%%', '', $the_content); } $replace_me = true; } } $xreflection = null; unset($xreflection); } } elseif(in_array($matches[1][$i], $three_var_functions)) { $za_function = $matches[1][$i] . '_run_rule'; if(function_exists($za_function)) { $xreflection = new ReflectionFunction($za_function); if($xreflection->getNumberOfParameters() >= 3) { $rule_runner = $za_function($matches[3][$i], 0, 1); if($rule_runner != 'fail' && $rule_runner != 'nochange' && $rule_runner != 'ok' && $rule_runner !== false) { if(is_array($rule_runner)) { $the_content = str_replace('%%' . $matches[1][$i] . '_' . $matches[2][$i] . '_' . $matches[3][$i] . '%%', $rule_runner[0], $the_content); $the_content = str_replace('%%' . $matches[1][$i] . '_title_' . $matches[2][$i] . '_' . $matches[3][$i] . '%%', $rule_runner[1], $the_content); } else { $the_content = str_replace('%%' . $matches[1][$i] . '_' . $matches[2][$i] . '_' . $matches[3][$i] . '%%', $rule_runner, $the_content); $the_content = str_replace('%%' . $matches[1][$i] . '_title_' . $matches[2][$i] . '_' . $matches[3][$i] . '%%', '', $the_content); } $replace_me = true; } } $xreflection = null; unset($xreflection); } } elseif(in_array($matches[1][$i], $two_var_functions)) { $za_function = $matches[1][$i] . '_run_rule'; if(function_exists($za_function)) { $xreflection = new ReflectionFunction($za_function); if($xreflection->getNumberOfParameters() >= 2) { $rule_runner = $za_function($matches[3][$i], 1); if($rule_runner != 'fail' && $rule_runner != 'nochange' && $rule_runner != 'ok' && $rule_runner !== false) { if(is_array($rule_runner)) { $the_content = str_replace('%%' . $matches[1][$i] . '_' . $matches[2][$i] . '_' . $matches[3][$i] . '%%', $rule_runner[0], $the_content); $the_content = str_replace('%%' . $matches[1][$i] . '_title_' . $matches[2][$i] . '_' . $matches[3][$i] . '%%', $rule_runner[1], $the_content); } else { $the_content = str_replace('%%' . $matches[1][$i] . '_' . $matches[2][$i] . '_' . $matches[3][$i] . '%%', $rule_runner, $the_content); $the_content = str_replace('%%' . $matches[1][$i] . '_title_' . $matches[2][$i] . '_' . $matches[3][$i] . '%%', '', $the_content); } $replace_me = true; } } $xreflection = null; unset($xreflection); } } if($replace_me == false) { $the_content = str_replace('%%' . $matches[1][$i] . '_' . $matches[2][$i] . '_' . $matches[3][$i] . '%%', '', $the_content); $the_content = str_replace('%%' . $matches[1][$i] . '_title_' . $matches[2][$i] . '_' . $matches[3][$i] . '%%', '', $the_content); } } } if(function_exists('aiomatic_ai_content_replace')) { $the_content = apply_filters('aiomatic_replace_aicontent_shortcode', $the_content); } else { preg_match_all('#\[[\t\s]*aicontent(?:[\t\s]*model=[\'"]?([^\]"\']+)[\'"]?)?[\t\s]*\](.*?)\[\/[\t\s]*aicontent[\t\s]*\]#i', $the_content, $matches); if(isset($matches[0][0]) && isset($matches[1][0])) { for($i = 0; $i < count($matches[0]); $i++) { $the_content = str_replace($matches[0][$i], '', $the_content); } } } return $the_content; } function fbomatic_assign_featured_image($attach_id, $post_id) { if ($attach_id === 0 || !is_numeric($attach_id)) { return false; } require_once(ABSPATH . 'wp-admin/includes/image.php'); require_once(ABSPATH . 'wp-admin/includes/media.php'); $res2 = set_post_thumbnail($post_id, $attach_id); if ($res2 === FALSE) { return false; } return true; } function fbomatic_run_rule($param, $auto = 1, $ret_content = 0) { $fbomatic_Main_Settings = get_option('fbomatic_Main_Settings', false); if($ret_content == 0) { $f = fopen(get_temp_dir() . 'fbomatic_' . $param, 'w'); if($f !== false) { $flock_disabled = explode(',', ini_get('disable_functions')); if(!in_array('flock', $flock_disabled)) { if (!flock($f, LOCK_EX | LOCK_NB)) { if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('Importing cannot run, already running.'); } return 'nochange'; } } } $GLOBALS['wp_object_cache']->delete('fbomatic_running_list', 'options'); if (!get_option('fbomatic_running_list')) { $running = array(); } else { $running = get_option('fbomatic_running_list'); } if (!empty($running)) { if (in_array($param, $running)) { if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('Only one instance of this rule is allowed. Rule is already running!'); } return 'nochange'; } } $running[] = $param; update_option('fbomatic_running_list', $running, false); register_shutdown_function('fbomatic_clear_flag_at_shutdown', $param); } if (isset($fbomatic_Main_Settings['rule_timeout']) && $fbomatic_Main_Settings['rule_timeout'] != '') { $timeout = intval($fbomatic_Main_Settings['rule_timeout']); } else { $timeout = 3600; } ini_set('safe_mode', 'Off'); ini_set('max_execution_time', $timeout); ini_set('ignore_user_abort', 1); ini_set('user_agent', fbomatic_get_random_user_agent()); if(function_exists('ignore_user_abort')) { ignore_user_abort(true); } if(function_exists('set_time_limit')) { set_time_limit($timeout); } $json = ''; $posts_inserted = 0; if (isset($fbomatic_Main_Settings['fbomatic_enabled']) && $fbomatic_Main_Settings['fbomatic_enabled'] == 'on') { try { if (!isset($fbomatic_Main_Settings['app_id']) || trim($fbomatic_Main_Settings['app_id']) == '') { fbomatic_log_to_file('You need to insert a valid Facebook App ID for this to work!'); if($auto == 1) { fbomatic_clearFromList($param); } return 'fail'; } if (!isset($fbomatic_Main_Settings['app_secret']) || $fbomatic_Main_Settings['app_secret'] == '') { fbomatic_log_to_file('You need to insert a valid Facebook App Secret for this to work!'); if($auto == 1) { fbomatic_clearFromList($param); } return 'fail'; } $item_img = ''; $rule_type = 'group'; $cont = 0; $found = 0; $ids = ''; $schedule = ''; $enable_comments = '1'; $enable_pingback = '1'; $author_link = ''; $max = PHP_INT_MAX; $active = '0'; $last_run = ''; $ruleType = 'week'; $first = false; $others = array(); $post_title = ''; $post_content = ''; $list_item = ''; $default_category = ''; $extra_categories = ''; $posted_items = array(); $posted_ids = array(); $post_status = 'publish'; $post_type = 'post'; $accept_comments = 'closed'; $post_user_name = 1; $skip_no_url = ''; $can_create_cat = 'off'; $item_create_tag = ''; $can_create_tag = '0'; $item_tags = ''; $max = 50; $auto_categories = '0'; $featured_image = '0'; $get_img = ''; $img_found = false; $insert_comments = '0'; $image_url = ''; $strip_images = '0'; $strip_text = '0'; $remove_default = '0'; $keyword_tag = ''; $keyword_cat = ''; $strip_by_regex = ''; $replace_regex = ''; $original_date = '0'; $skip_posts = ''; $no_excerpt = '0'; $rule_description= ''; $video_no_img = '0'; $custom_crawling_expre = ''; $append_comments = '0'; $continue_search = '0'; $custom_fields = ''; $require_words = ''; $banned_words = ''; $custom_tax = ''; $cuser_cookie = ''; $xs_cookie = ''; $default_title = ''; $page_timeout = ''; $attach_screen = ''; $wpml_lang = ''; $access_token = ''; $limit_title_word_count = ''; $post_format = 'post-format-standard'; $parent_category_id = ''; $GLOBALS['wp_object_cache']->delete('fbomatic_rules_list', 'options'); if (!get_option('fbomatic_rules_list')) { $rules = array(); } else { $rules = get_option('fbomatic_rules_list'); } if (!empty($rules)) { foreach ($rules as $request => $bundle[]) { if ($cont == $param) { $bundle_values = array_values($bundle); $myValues = $bundle_values[$cont]; $array_my_values = array_values($myValues);for($iji=0;$iji<count($array_my_values);++$iji){if(is_string($array_my_values[$iji])){$array_my_values[$iji]=stripslashes($array_my_values[$iji]);}} $ids = isset($array_my_values[0]) ? $array_my_values[0] : ''; $schedule = isset($array_my_values[1]) ? $array_my_values[1] : ''; $active = isset($array_my_values[2]) ? $array_my_values[2] : ''; $last_run = isset($array_my_values[3]) ? $array_my_values[3] : ''; $max = isset($array_my_values[4]) ? $array_my_values[4] : ''; $post_status = isset($array_my_values[5]) ? $array_my_values[5] : ''; $post_type = isset($array_my_values[6]) ? $array_my_values[6] : ''; $post_user_name = isset($array_my_values[7]) ? $array_my_values[7] : ''; $item_create_tag = isset($array_my_values[8]) ? $array_my_values[8] : ''; $default_category = isset($array_my_values[9]) ? $array_my_values[9] : ''; $auto_categories = isset($array_my_values[10]) ? $array_my_values[10] : ''; $can_create_tag = isset($array_my_values[11]) ? $array_my_values[11] : ''; $enable_comments = isset($array_my_values[12]) ? $array_my_values[12] : ''; $featured_image = isset($array_my_values[13]) ? $array_my_values[13] : ''; $image_url = isset($array_my_values[14]) ? $array_my_values[14] : ''; $post_title = isset($array_my_values[15]) ? htmlspecialchars_decode($array_my_values[15]) : ''; $post_content = isset($array_my_values[16]) ? htmlspecialchars_decode($array_my_values[16]) : ''; $enable_pingback = isset($array_my_values[17]) ? $array_my_values[17] : ''; $post_format = isset($array_my_values[18]) ? $array_my_values[18] : ''; $rule_type = isset($array_my_values[19]) ? $array_my_values[19] : ''; $insert_comments = isset($array_my_values[20]) ? $array_my_values[20] : ''; $strip_images = isset($array_my_values[21]) ? $array_my_values[21] : ''; $limit_title_word_count = isset($array_my_values[22]) ? $array_my_values[22] : ''; $original_date = isset($array_my_values[23]) ? $array_my_values[23] : ''; $strip_text = isset($array_my_values[24]) ? $array_my_values[24] : ''; $remove_default = isset($array_my_values[25]) ? $array_my_values[25] : ''; $skip_posts = isset($array_my_values[26]) ? $array_my_values[26] : ''; $no_excerpt = isset($array_my_values[27]) ? $array_my_values[27] : ''; $rule_description = isset($array_my_values[28]) ? $array_my_values[28] : ''; $video_no_img = isset($array_my_values[29]) ? $array_my_values[29] : ''; $continue_search = isset($array_my_values[30]) ? $array_my_values[30] : ''; $custom_fields = isset($array_my_values[31]) ? $array_my_values[31] : ''; $custom_tax = isset($array_my_values[32]) ? $array_my_values[32] : ''; $append_comments = isset($array_my_values[33]) ? $array_my_values[33] : ''; $require_words = isset($array_my_values[34]) ? $array_my_values[34] : ''; $banned_words = isset($array_my_values[35]) ? $array_my_values[35] : ''; $parent_category_id= isset($array_my_values[36]) ? $array_my_values[36] : ''; $keyword_tag = isset($array_my_values[37]) ? $array_my_values[37] : ''; $keyword_cat = isset($array_my_values[38]) ? $array_my_values[38] : ''; $strip_by_regex = isset($array_my_values[39]) ? $array_my_values[39] : ''; $replace_regex = isset($array_my_values[40]) ? $array_my_values[40] : ''; $cuser_cookie = isset($array_my_values[41]) ? $array_my_values[41] : ''; $xs_cookie = isset($array_my_values[42]) ? $array_my_values[42] : ''; $page_timeout = isset($array_my_values[43]) ? $array_my_values[43] : ''; $default_title = isset($array_my_values[44]) ? $array_my_values[44] : ''; $custom_crawling_expre = isset($array_my_values[45]) ? $array_my_values[45] : ''; $skip_no_url = isset($array_my_values[46]) ? $array_my_values[46] : ''; $attach_screen = isset($array_my_values[47]) ? $array_my_values[47] : ''; $wpml_lang = isset($array_my_values[48]) ? $array_my_values[48] : ''; $found = 1; break; } $cont = $cont + 1; } } else { fbomatic_log_to_file('No rules found for fbomatic_rules_list!'); if($auto == 1) { fbomatic_clearFromList($param); } return 'fail'; } if($xs_cookie == '' && isset($fbomatic_Main_Settings['xs_cookie']) && $fbomatic_Main_Settings['xs_cookie'] != '') { $xs_cookie = $fbomatic_Main_Settings['xs_cookie']; } if($cuser_cookie == '' && isset($fbomatic_Main_Settings['cuser_cookie']) && $fbomatic_Main_Settings['cuser_cookie'] != '') { $cuser_cookie = $fbomatic_Main_Settings['cuser_cookie']; } if($continue_search == '1') { $GLOBALS['wp_object_cache']->delete('fbomatic_continue_search', 'options'); $skip_posts_temp = get_option('fbomatic_continue_search', array()); } if ($found == 0) { fbomatic_log_to_file($param . ' not found in fbomatic_rules_list!'); if($auto == 1) { fbomatic_clearFromList($param); } return 'fail'; } else { if($ret_content == 0) { $GLOBALS['wp_object_cache']->delete('fbomatic_rules_list', 'options'); $rules = get_option('fbomatic_rules_list'); $rules[$param][3] = fbomatic_get_date_now(); update_option('fbomatic_rules_list', $rules, false); } } if ($enable_comments == '1') { $accept_comments = 'open'; } $ids = fbomatic_replaceSynergyShortcodes($ids); if (!is_numeric($ids)) { $fsname = 'fbomatic_' . $rule_type . '_' . md5($ids); $za_page_id = get_transient($fsname); if(!empty($za_page_id)) { $ids = $za_page_id; } else { if (filter_var($ids, FILTER_VALIDATE_URL) === FALSE) { fbomatic_log_to_file('Facebook Group/Post Url/ID failed failed in parsing: ' . $ids); if($auto == 1) { fbomatic_clearFromList($param); } return 'fail'; } $ch = curl_init(); if ($ch === FALSE) { fbomatic_log_to_file('Failed to init Curl in Facebook learner!'); if ($continue_search == '1') { $skip_posts_temp[$param] = ''; set_transient('fbomatic_continue_search', $skip_posts_temp, 999999999); } return 'fail'; } curl_setopt($ch, CURLOPT_HTTPGET, 1); curl_setopt($ch, CURLOPT_URL, trim($ids)); curl_setopt($ch, CURLOPT_HTTPHEADER, array('sec-fetch-site: none', 'sec-fetch-mode: navigate','sec-fetch-user: ?1','sec-fetch-dest: document' )); curl_setopt($ch, CURLOPT_COOKIE, 'xs=' . $xs_cookie . ';c_user=' . $cuser_cookie . ';datr=QGgFYdhWgha-QOwFUUksCDTg'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_REFERER, 'https://google.com'); curl_setopt($ch, CURLOPT_USERAGENT, fbomatic_get_random_user_agent()); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); curl_setopt($ch, CURLOPT_TIMEOUT, 60); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); if($page_timeout != '' && is_numeric($page_timeout)) { usleep($page_timeout * 1000); } $exec = fbomatic_curl_exec_special($ch); if ($exec === FALSE) { fbomatic_log_to_file('Failed to exec get_web_page to get numeric ID ' . $ids); if($auto == 1) { fbomatic_clearFromList($param); } return 'fail'; } if(strstr($exec, '<title>Redirecting...</title>') !== false) { sleep(1); $exec = fbomatic_get_web_page($ids, $cuser_cookie, $xs_cookie); if(strstr($exec, '<title>Redirecting...</title>') !== false) { fbomatic_log_to_file('Facebook redirected...: ' . $ids . ' -- ' . $exec); if($auto == 1) { fbomatic_clearFromList($param); } return 'fail'; } } if (stristr ( $exec, 'entity_id' ) || stristr ( $exec, '"pageID":' ) || stristr ( $exec, '"userID":"' ) || stristr ( $exec, '"groupID":"' )) { if (stristr ( $exec, '"pageID' )) { preg_match_all ( '{"pageID":"(\d*?)"}', $exec, $matches ); } elseif (stristr ( $exec, '"groupID"' )) { preg_match_all ( '{"groupID":"(\d*?)"}', $exec, $matches ); } elseif (stristr ( $exec, '"userID"' )) { preg_match_all ( '{"userID":"(\d*?)"}', $exec, $matches ); } else { preg_match_all ( '{entity_id":"(\d*?)"}', $exec, $matches ); } $match = $matches[1]; if (isset($match[0])) { $temp_id = $match[0]; if (trim($temp_id) != '') { $ids = $temp_id; } else { fbomatic_log_to_file('Failed to get numeric ID with curl from pageID, pageID is null!'); if($auto == 1) { fbomatic_clearFromList($param); } return 'fail'; } } else { fbomatic_log_to_file('Failed to parse pageID!'); if($auto == 1) { fbomatic_clearFromList($param); } return 'fail'; } } else { if (stristr($exec, 'PageComposerPagelet_') !== FALSE) { preg_match_all('{PageComposerPagelet_(\d*)"}', $exec, $matches); $match = $matches[1]; if (isset($match[0])) { $temp_id = $match[0]; if (trim($temp_id) != '') { $ids = $temp_id; } else { fbomatic_log_to_file('Failed to get numeric ID with curl from PageComposerPagelet, temp_id is null!'); if($auto == 1) { fbomatic_clearFromList($param); } return 'fail'; } } else { fbomatic_log_to_file('Failed to parse PageComposerPagelet!'); if($auto == 1) { fbomatic_clearFromList($param); } return 'fail'; } } else { if (stristr($exec, 'entity_id') !== FALSE) { preg_match_all('{entity_id":"(\d*)"}', $exec, $matches); $match = $matches[1]; if (isset($match[0])) { $temp_id = $match[0]; if (trim($temp_id) != '') { $ids = $temp_id; } else { fbomatic_log_to_file('Failed to get numeric ID with curl from entity_id, temp_id is null!'); if($auto == 1) { fbomatic_clearFromList($param); } return 'fail'; } } else { preg_match_all('|entity_id=(\d*)|', $exec, $matches); $match = $matches[1]; if (isset($match[0])) { $temp_id = $match[0]; if (trim($temp_id) != '') { $ids = $temp_id; } else { fbomatic_log_to_file('Failed to get numeric ID with curl from entity_id, temp_id is null!'); if($auto == 1) { fbomatic_clearFromList($param); } return 'fail'; } } else { fbomatic_log_to_file('Failed to parse entity_id!'); if($auto == 1) { fbomatic_clearFromList($param); } return 'fail'; } } } else { $fnd = false; if (stristr($exec, 'https%3A%2F%2Fwww.facebook.com%2Fgroups%2F') !== FALSE) { preg_match_all('{https%3A%2F%2Fwww\.facebook\.com%2Fgroups%2F(\d*)%2F}i', $exec, $matches); $match = $matches[1]; if (isset($match[0])) { $temp_id = $match[0]; if (trim($temp_id) != '') { $ids = $temp_id; $fnd = true; } else { fbomatic_log_to_file('Failed to get numeric ID with curl from https%3A%2F%2Fwww\.facebook\.com%2Fgroups%2F, temp_id is null!'); } } } if($fnd == false) { if($access_token == '') { fbomatic_log_to_file('Cannot parse ID of page/group! ' . $exec); if($auto == 1) { fbomatic_clearFromList($param); } return 'fail'; } $ids = fbomatic_getFacebookId($ids, $access_token); if ($ids === FALSE) { fbomatic_log_to_file('Failed to get numeric ID, invalid Facebook reply! ' . esc_html($exec)); if($auto == 1) { fbomatic_clearFromList($param); } return 'fail'; } } } } } if (is_numeric($ids)) { set_transient($fsname, $ids, 0); } } } $feed_uri = ''; if($xs_cookie == '' || $cuser_cookie == '') { if (!isset($fbomatic_Main_Settings['access_token']) || $fbomatic_Main_Settings['access_token'] == '') { $turl = "https://graph.facebook.com/oauth/access_token?client_id=" . trim($fbomatic_Main_Settings['app_id']) . "&client_secret=" . $fbomatic_Main_Settings['app_secret'] . "&grant_type=client_credentials"; $exec = fbomatic_get_web_page($turl); if ($exec === FALSE) { fbomatic_log_to_file('Failed to exec fbomatic_get_web_page (access_token).'); if($auto == 1) { fbomatic_clearFromList($param); } return 'fail'; } if (stristr($exec, 'access_token=') !== FALSE) { $expl = explode('=', $exec); $access_token = $expl[1]; } elseif (stristr($exec, '"access_token":"') !== FALSE) { $expl = explode('"access_token":"', $exec); $access_token = $expl[1]; $access_token = substr($access_token, 0, strpos($access_token, '"')); } else { fbomatic_log_to_file('Failed to retrive access token from Facebook. Returned: ' . $exec); if($auto == 1) { fbomatic_clearFromList($param); } return 'fail'; } } else { $access_token = $fbomatic_Main_Settings['access_token']; } } else { $access_token = ''; } if($xs_cookie != '' && $cuser_cookie != '') { require(dirname(__FILE__) . "/res/fbomatic-fbchecker.php"); $items = fbomatic_learn_facebook($cuser_cookie, $xs_cookie, $ids, $insert_comments, $continue_search, $param, $fbomatic_Main_Settings, $max, $page_timeout, FBOMATIC_API_VER, $rule_type, 'posts', $video_no_img); if($items === false || $items === null) { if($continue_search == '1') { $skip_posts_temp[$param] = ''; update_option('fbomatic_continue_search', $skip_posts_temp); } fbomatic_log_to_file('Failed to import results from Facebook.'); if($auto == 1) { fbomatic_clearFromList($param); } return 'fail'; } if (count($items) == 0) { if($continue_search == '1') { $skip_posts_temp[$param] = ''; update_option('fbomatic_continue_search', $skip_posts_temp); } fbomatic_log_to_file('No posts inserted because Facebook did not returned any usable results.'); if($auto == 1) { fbomatic_clearFromList($param); } return 'nochange'; } } else { if($continue_search == '1') { if(isset($skip_posts_temp[$param]) && $skip_posts_temp[$param] !== '') { $feed_uri = $skip_posts_temp[$param]; } } else { $skip_posts_temp[$param] = ''; update_option('fbomatic_continue_search', $skip_posts_temp); } if($feed_uri === '') { $feed_uri = "https://graph.facebook.com/v"; if (isset($fbomatic_Main_Settings['api_version']) && $fbomatic_Main_Settings['api_version'] != 'default' && $fbomatic_Main_Settings['api_version'] != '') { $feed_uri .= $fbomatic_Main_Settings['api_version']; } else { $feed_uri .= FBOMATIC_API_VER; } $feed_uri .= "/" . $ids . "/"; if ($rule_type == 'group') { $feed_uri .= "feed"; } elseif ($rule_type == 'page') { $feed_uri .= "posts"; } else { $feed_uri .= "feed"; } $feed_uri .= "?access_token=" . $access_token; if (isset($fbomatic_Main_Settings['limit_max_posts']) && $fbomatic_Main_Settings['limit_max_posts'] == 'on') { $feed_uri .= "&limit=" . $max; } else { $feed_uri .= "&limit=100"; } $feed_uri .= "&fields=full_picture,picture,id,message,from,story,attachments,created_time"; } $exec = fbomatic_get_web_page($feed_uri); if ($exec === FALSE) { if($continue_search == '1') { $skip_posts_temp[$param] = ''; update_option('fbomatic_continue_search', $skip_posts_temp); } fbomatic_log_to_file('Failed to exec get_web_page to get Facebook search response ' . $feed_uri); if($auto == 1) { fbomatic_clearFromList($param); } return 'fail'; } if (stristr($exec, '"data"') === FALSE) { if($continue_search == '1') { $skip_posts_temp[$param] = ''; update_option('fbomatic_continue_search', $skip_posts_temp); } fbomatic_log_to_file('Unrecognized API response: ' . $exec . ' URI: ' . $feed_uri); if($auto == 1) { fbomatic_clearFromList($param); } return 'fail'; } $json = json_decode($exec); $items = $json->data; if (count($items) == 0) { $feed_uri2 = str_replace('/feed?', '/posts?', $feed_uri); if($feed_uri2 == $feed_uri) { $feed_uri2 = str_replace('/posts?', '/feed?', $feed_uri); } $feed_uri = $feed_uri2; $exec = fbomatic_get_web_page($feed_uri); if ($exec === FALSE) { if($continue_search == '1') { $skip_posts_temp[$param] = ''; update_option('fbomatic_continue_search', $skip_posts_temp); } fbomatic_log_to_file('Failed to exec get_web_page to get Facebook response ' . $feed_uri); if($auto == 1) { fbomatic_clearFromList($param); } return 'fail'; } if (stristr($exec, '"data"') === FALSE) { if($continue_search == '1') { $skip_posts_temp[$param] = ''; update_option('fbomatic_continue_search', $skip_posts_temp); } fbomatic_log_to_file('Unrecognized API response: ' . $exec . ' URI: ' . $feed_uri); if($auto == 1) { fbomatic_clearFromList($param); } return 'fail'; } $json = json_decode($exec); $items = $json->data; if (count($items) == 0) { if($continue_search == '1') { $skip_posts_temp[$param] = ''; update_option('fbomatic_continue_search', $skip_posts_temp); } fbomatic_log_to_file('No posts inserted because App does not have permission to view posts (user_posts permission) or no posts exist.'); if($auto == 1) { fbomatic_clearFromList($param); } return 'nochange'; } } } if (isset($fbomatic_Main_Settings['do_not_check_duplicates']) && $fbomatic_Main_Settings['do_not_check_duplicates'] == 'on') { } else { $post_list = array(); if($ret_content == 0) { $postsPerPage = 50000; $paged = 0; do { $postOffset = $paged * $postsPerPage; $query = array( 'post_status' => array( 'publish', 'draft', 'pending', 'trash', 'private', 'future' ), 'post_type' => array( 'any' ), 'numberposts' => $postsPerPage, 'meta_key' => 'fbomatic_post_url', 'fields' => 'ids', 'offset' => $postOffset ); $got_me = get_posts($query); $post_list = array_merge($post_list, $got_me); $paged++; }while(!empty($got_me)); } wp_suspend_cache_addition(true); foreach ($post_list as $post) { $posted_items[$post] = get_post_meta($post, 'fbomatic_post_url', true); $posted_ids[$post] = get_post_meta($post, 'fb_group_id', true) . get_post_meta($post, 'fbomatic_post_id', true); } wp_suspend_cache_addition(false); } $count = 1; $init_date = time(); $skip_pcount = 0; $skipped_pcount = 0; if($ret_content == 1) { $item_xcounter = count($items); $skip_pcount = rand(0, $item_xcounter-1); } $auto_cat_orig = $auto_categories; foreach ($items as $item) { if($ret_content == 1) { if($skip_pcount > $skipped_pcount) { $skipped_pcount++; continue; } } $get_img = ''; $img_found = false; if ($count > intval($max)) { break; } $item_complex_id = $item->id; $id_parts = explode('_', $item_complex_id); if (!isset($id_parts[1])) { if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('Skipping post "' . esc_html($title) . '", no id parts: ' . pritn_r($id_parts, true)); } continue; } $url = "https://www.facebook.com/" . $id_parts[0] . "/posts/" . $id_parts[1]; if (isset($item->message) && ($cuser_cookie == '' || $xs_cookie == '')) { $item->message = preg_replace('@(https?:\/\/([-\w\.]+[-\w])+(:\d+)?(\/([\w/_\.#-]*(\?\S+)?[^\.\s"\'])?)?)@', '<a href="$1" target="_blank">$0</a>', $item->message); if (!isset($fbomatic_Main_Settings['no_hash_link']) || $fbomatic_Main_Settings['no_hash_link'] != 'on') { $item->message = preg_replace('/#(\w+)/u', ' <a href="https://www.facebook.com/hashtag/$1">#$1</a>', $item->message); } } else { if(!isset($item->message)) { $item->message = ''; } } $backup = ''; if (isset($item->story)) { $backup = $item->story; } else { if (isset($item->name)) { $backup = $item->name; } else { if (isset($item->description)) { $backup = $item->description; } } } if(isset($item->facebook_title) && $item->facebook_title != '') { $title = $item->facebook_title; } else { $title = fbomatic_generate_title($item->message, $backup, $fbomatic_Main_Settings); } if (in_array($url, $posted_items)) { if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('Skipping post "' . esc_html($title) . '", already posted. ID ' . $item_complex_id); } continue; } if (in_array($id_parts[0] . $id_parts[1], $posted_ids)) { if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('Skipping post "' . esc_html($title) . '", already posted (by id).'); } continue; } $content = $item->message; if(isset($item->attachments->data[0]->type) && $item->attachments->data[0]->type != '') { $type = $item->attachments->data[0]->type; } else { if(isset($item->from->attachments->data[0]->type) && $item->from->attachments->data[0]->type != '') { $type = $item->from->attachments->data[0]->type; } else { if(isset($item->from->attachments->data[0]->target->type) && $item->from->attachments->data[0]->target->type != '') { $type = $item->from->attachments->data[0]->target->type; } else { if(isset($item->attachments->data[0]->target->type) && $item->attachments->data[0]->target->type != '') { $type = $item->attachments->data[0]->target->type; } else { if(isset($item->data[0]->target->type) && $item->data[0]->target->type != '') { $type = $item->data[0]->target->type; } else { if(!isset($item->type) || $item->type == '') { $type = 'unknown'; } else { $type = $item->type; } } } } } } $skip_types = $fbomatic_Main_Settings['skip_types']; if (stristr($skip_types, $type)) { if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('Skipping post "' . esc_html($title) . '", because it has post type that should be skipped (global rule): ' . $type); } continue; } if (stristr($skip_posts, $type)) { if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('Skipping post "' . esc_html($title) . '", because it has post type that should be skipped (importing rule): ' . $type); } continue; } if (isset($item->name)) { $description = $item->name; } else { $description = fbomatic_getExcerpt($item->message); } if (isset($item->link)) { $link = $item->link; } else { $link = ''; } if (isset($item->from->name)) { $author = $item->from->name; } else { if (isset($fbomatic_Main_Settings['default_user']) && $fbomatic_Main_Settings['default_user'] != '') { $author = $fbomatic_Main_Settings['default_user']; } else { $author = 'Administrator'; } } if (isset($item->from->id)) { $author_link = "https://facebook.com/" . $item->from->id; } else { $author_link = ''; } if ($type == 'link') { if (trim($get_img != '')) { $content .= '<p>'; if (!isset($fbomatic_Main_Settings['no_img_link']) || $fbomatic_Main_Settings['no_img_link'] != 'on') { if ($link != '') { $content .= '<a href="' . esc_url_raw($link) . '">'; } } $content .= '<br/><img title="' . esc_html($title) . '" src="' . esc_url_raw($get_img) . '" /><br/>'; if (!isset($fbomatic_Main_Settings['no_img_link']) || $fbomatic_Main_Settings['no_img_link'] != 'on') { if ($link != '') { $content .= '</a>'; } } $content .= '</p>'; } $content .= '<p>'; if ($link != '') { if (!isset($fbomatic_Main_Settings['no_link']) || $fbomatic_Main_Settings['no_link'] != 'on') { $content .= '<a href="' . esc_url_raw($link) . '">'; } } if(isset($item->name)) { $content .= $item->name; } if ($link != '') { if (!isset($fbomatic_Main_Settings['no_link']) || $fbomatic_Main_Settings['no_link'] != 'on') { $content .= '</a>'; } } $content .= '</p>'; if (isset($item->description) && trim($item->description) != '' && strstr($content, $item->description) === false) { $content .= $item->description; } } elseif ($type == 'status') { if(isset($item->attachments->data[0])) { $attachment = $item->attachments->data[0]; } else { $attachment = ''; } if (isset($attachment->type) && trim($attachment->type) != '' && isset($attachment->media)) { $attach_img = $attachment->media->image->src; if (!$img_found && substr($attach_img, 0, 10) != "fbstaging:") { $get_img = $attach_img; $img_found = true; } $content .= '<br/>'; if (!isset($fbomatic_Main_Settings['no_img_link']) || $fbomatic_Main_Settings['no_img_link'] != 'on') { if ($link != '') { $content .= '<a href="' . esc_url_raw($link) . '">'; } } if(isset($attachment->title)) { $img_title = $attachment->title; } else { $img_title = 'Facebook image'; } $content .= '<br/><img title="' . esc_html($img_title) . '" src="' . esc_url_raw($attach_img) . '" /><br/>'; if (!isset($fbomatic_Main_Settings['no_img_link']) || $fbomatic_Main_Settings['no_img_link'] != 'on') { if ($link != '') { $content .= '</a>'; } } } if (isset($attachment->description) && $attachment->description != '' && strstr($content, $attachment->description) === false) { $content .= '<br/>'; $content .= $attachment->description; } } elseif ($type == 'photo') { if ($content == '') { if (isset($item->attachments->data[0]->description) && trim($item->attachments->data[0]->description) != '') { $content .= $item->attachments->data[0]->description . '<br>'; } elseif (isset($item->story) && trim($item->story) !== '') { $content .= $item->story . '<br>'; } } if(isset($item->attachments->data[0])) { $attachment_type = $item->attachments->data[0]->type; if ($attachment_type == 'album') { $imgs = $item->attachments->data[0]->subattachments->data; } else { $imgs = $item->attachments->data; } } else { $imgs = array(); } if (count($imgs) > 0) { foreach ($imgs as $image1) { $some_image = $image1->media->image->src; if (!$img_found && substr($some_image, 0, 10) != "fbstaging:") { $get_img = $some_image; $img_found = true; } $content .= '<br/>'; if (!isset($fbomatic_Main_Settings['no_img_link']) || $fbomatic_Main_Settings['no_img_link'] != 'on') { if ($link != '') { $content .= '<a href="' . esc_url_raw($link) . '">'; } } $content .= '<br/><img title="' . esc_html($title) . '" src="' . esc_url_raw($some_image) . '" /><br/>'; if (!isset($fbomatic_Main_Settings['no_img_link']) || $fbomatic_Main_Settings['no_img_link'] != 'on') { if ($link != '') { $content .= '</a>'; } } } } if (isset($item->description) && trim($item->description) != '' && strstr($content, $item->description) === false) { $content .= '<br>' . $item->description; } } elseif ($type == 'video') { if ($link == '') { if(isset($item->attachments->data[0]->media)) { if (!$img_found && substr($item->attachments->data[0]->media->image->src, 0, 10) != "fbstaging:") { if (!isset($fbomatic_Main_Settings['no_video_img']) || $fbomatic_Main_Settings['no_video_img'] != 'on') { $get_img = $item->attachments->data[0]->media->image->src; $img_found = true; } } if($video_no_img != '1') { foreach($item->attachments->data as $fb_data) { $content .= '<br/><img title="' . esc_html($title) . '" src="' . esc_url_raw($fb_data->media->image->src) . '" /><br/>'; } } } else { if(isset($item->attachments->data[0]->subattachments->data[0])) { if (!$img_found && substr($item->attachments->data[0]->subattachments->data[0]->media->image->src, 0, 10) != "fbstaging:") { if (!isset($fbomatic_Main_Settings['no_video_img']) || $fbomatic_Main_Settings['no_video_img'] != 'on') { $get_img = $item->attachments->data[0]->subattachments->data[0]->media->image->src; $img_found = true; } } if($video_no_img != '1') { foreach($item->attachments->data[0]->subattachments->data as $fb_data) { $content .= '<br/><img title="' . esc_html($title) . '" src="' . esc_url_raw($fb_data->media->image->src) . '" /><br/>'; } } } } } else { if (stristr($link, 'youtube.com') || stristr($link, 'youtu.be')) { $content .= '<br><br>[embed]' . esc_url_raw($link) . '[/embed]'; } else { if($link != '') { if($xs_cookie == '' || $cuser_cookie == '') { $content .= '<br><br>[fb-video-fbomatic v="' . esc_url_raw($link) . '"]'; } } } $content = do_shortcode($content); } if (isset($item->description) && strstr($content, $item->description) === false) { $content .= '<br/>'; $content .= $item->description; } } else { if (isset($item->description) && strstr($content, $item->description) === false) { $content .= '<br/>'; $content .= $item->description . ' '; } if(isset($item->attachments->data[0])) { $attachment = $item->attachments->data[0]; if (isset($attachment->type) && trim($attachment->type) != '') { if(isset($attachment->subattachments->data[0])) { if($title == '' && isset($attachment->title)) { $title = $attachment->title; } $xattachment = $attachment->subattachments->data; foreach($xattachment as $attachment) { $attach_img = $attachment->media->image->src; if (!$img_found && substr($attach_img, 0, 10) != "fbstaging:") { $get_img = $attach_img; $img_found = true; } $content .= '<br/>'; if (!isset($fbomatic_Main_Settings['no_img_link']) || $fbomatic_Main_Settings['no_img_link'] != 'on') { $content .= '<a href="' . esc_url_raw($link) . '">'; } if(isset($attachment->title)) { $zattitle = $attachment->title; } else { $zattitle = 'Facebook image'; } $content .= '<br/><img title="' . esc_html($zattitle) . '" src="' . esc_url_raw($attach_img) . '" /><br/>'; if (!isset($fbomatic_Main_Settings['no_img_link']) || $fbomatic_Main_Settings['no_img_link'] != 'on') { $content .= '</a>'; } $content .= '<br/>'; } } elseif(isset($attachment->media->image->src)) { $attach_img = $attachment->media->image->src; if (!$img_found && substr($attach_img, 0, 10) != "fbstaging:") { $get_img = $attach_img; $img_found = true; } $content .= '<br/>'; if (!isset($fbomatic_Main_Settings['no_img_link']) || $fbomatic_Main_Settings['no_img_link'] != 'on') { $content .= '<a href="' . esc_url_raw($link) . '">'; } if(isset($attachment->title)) { $zaat_title = $attachment->title; } else { $zaat_title = 'Facebook image'; } $content .= '<br/><img title="' . esc_html($zaat_title) . '" src="' . esc_url_raw($attach_img) . '" /><br/>'; if (!isset($fbomatic_Main_Settings['no_img_link']) || $fbomatic_Main_Settings['no_img_link'] != 'on') { $content .= '</a>'; } } } if (isset($attachment->description) && $attachment->description != '' && stristr(str_replace(' ', '', strip_tags($content)), str_replace(' ', '', strip_tags($attachment->description))) === false) { $content .= '<br/>' . $attachment->description; } } } if($img_found == false) { if (isset($item->full_picture) && stristr($item->full_picture, 'p12x12') === false && substr($item->full_picture, 0, 10) != "fbstaging:") { $img_found = true; $get_img = $item->full_picture; } else { if (isset($item->picture) && substr($item->picture, 0, 10) != "fbstaging:") { $img_found = true; $get_img = $item->picture; } else { $img_found = false; $get_img = ''; } } } if ($featured_image == '1' && isset($fbomatic_Main_Settings['skip_no_img']) && $fbomatic_Main_Settings['skip_no_img'] == 'on' && $img_found == false) { if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('Skipping post "' . esc_html($title) . '", because it has no detected image file attached'); } continue; } $date = $item->created_time; if (isset($fbomatic_Main_Settings['date_format']) && $fbomatic_Main_Settings['date_format'] != '') { $tmstamp1 = strtotime($date); if($tmstamp1 !== false) { $date1 = date($fbomatic_Main_Settings['date_format'], $tmstamp1); if($date1 !== false) { $date = $date1; } } } if (isset($fbomatic_Main_Settings['skip_old']) && $fbomatic_Main_Settings['skip_old'] == 'on' && isset($fbomatic_Main_Settings['skip_year']) && $fbomatic_Main_Settings['skip_year'] !== '' && isset($fbomatic_Main_Settings['skip_month']) && isset($fbomatic_Main_Settings['skip_day'])) { $old_date = $fbomatic_Main_Settings['skip_day'] . '-' . $fbomatic_Main_Settings['skip_month'] . '-' . $fbomatic_Main_Settings['skip_year']; $time_date = strtotime($date); $time_old_date = strtotime($old_date); if ($time_date !== false && $time_old_date !== false) { if ($time_date < $time_old_date) { if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('Skipping post "' . esc_html($title) . '", because it is older than ' . $old_date . ' - posted on ' . $date); } continue; } } } if (stristr($content, 'safe_image.php')) { preg_match_all('{https://[^:]*?safe_image\.php.*?url=(.*?)"}', $content, $matches); $the_imgs = $matches[0]; $cnt_imgs = $matches[1]; $i = 0; foreach ($the_imgs as $the_img) { $cnt_imgs[$i] = preg_replace('{&.*}', '', $cnt_imgs[$i]); $image_link = urldecode($cnt_imgs[$i]); $content = str_replace($the_img, $image_link . "\"", $content); } $content = str_replace('&w=130', '&w=650', $content); $content = str_replace('&h=130', '&h=650', $content); } if(isset($item->vid_embed) && stristr($content, $item->vid_embed) === false) { $content .= '<br/>' . $item->vid_embed; } if ($type == 'video' && !stristr($content, 'youtube.com') && !stristr($content, 'pages/story/reader/')) { preg_match('{background-image: url\((.*?)\)}', $content, $vid_match); if (isset($vid_match[1]) && trim($vid_match[1]) != '') { $content = str_replace($item->picture, $vid_match[1], $content); } } if (stristr($content, '130x130')) { preg_match_all('{"https://[^"]*?\w130x130/(.*?)\..*?"}', $content, $matches); $tiny_imgs = str_replace('"', '', $matches[0]); $exec = fbomatic_get_web_page(trim(html_entity_decode($url))); if ($exec != FALSE) { if (stristr($exec, '<img class="scaled')) { preg_match_all('{<img class="scaled.*?>}s', $exec, $img_matchs); $html_img = implode(' ', $img_matchs[0]); preg_match_all('{\d{4,8}_(\d*?_\d*?)_}', $html_img, $img_match_ids); $tiny_img_ids = array_unique($img_match_ids[1]); $i = 0; foreach ($tiny_img_ids as $tiny_imd_id) { unset($big_imgs); preg_match('{src="(https://[^"]*?' . $tiny_imd_id . '.*?)"}', $exec, $big_imgs); unset($big_imgs2); preg_match('{src=(https%3A%2F%2F[^&]*?' . $tiny_imd_id . '.*?)&}', $exec, $big_imgs2); if (trim($big_imgs[1]) != '') { if ($i == 0 && (!stristr($content, $tiny_imd_id) || !stristr($content, '130x130')) && ($cuser_cookie == '' || $xs_cookie == '')) { $content = preg_replace('{<img.*?>}', '', $content); } $replace_img = $big_imgs[1]; if (isset($big_imgs2[1]) && trim($big_imgs2[1]) != '') { $replace_img = urldecode($big_imgs2[1]); } if (stristr($content, $tiny_imd_id)) { $content = str_replace($tiny_img_ids[$i], $replace_img, $content); } } $i++; } } } } if($title == '') { if($default_title == '') { $default_titlex = 'Facebook post'; } else { $default_titlex = $default_title; } $title = fbomatic_generate_title($content, $default_titlex, $fbomatic_Main_Settings); } if (stristr($get_img, 'safe_image.php')) { $parts = parse_url($get_img); parse_str($parts['query'], $query); if (isset($query['url']) && $query['url'] != '' && substr($query['url'], 0, 10) != "fbstaging:") { $get_img = $query['url']; } } $my_post = array(); if($original_date == '1') { $my_post['post_date'] = date('Y-m-d H:i:s', strtotime($date)); } else { $postdatex = date("Y-m-d H:i:s", intval($init_date)); $my_post['post_date'] = $postdatex; $init_date = $init_date - 1; } if (isset($item->comments)) { $my_post['crawled_comments'] = $item->comments; } $my_post['insert_comments'] = $insert_comments; $my_post['append_comments'] = $append_comments; $my_post['fb_group_id'] = $id_parts[0]; $my_post['fbomatic_post_id'] = $id_parts[1]; $my_post['fbomatic_enable_pingbacks'] = $enable_pingback; if($get_img == '' && $image_url != '') { $image_url_t = explode(',',$image_url); $get_img = trim($image_url_t[array_rand($image_url_t)]); } preg_match('#src="([^"]*?)"#', $get_img, $imgsxx); if(isset($imgsxx[1])) { $get_img = $imgsxx[1]; } $my_post['fbomatic_post_image'] = $get_img; $my_post['default_category'] = $default_category; $type_set = false; if (isset($fbomatic_Main_Settings['default_types_fb']) && $fbomatic_Main_Settings['default_types_fb'] !== '') { $type_arr = explode(',', $fbomatic_Main_Settings['default_types_fb']); if(count($type_arr) == 6) { if ($type == 'link') { if(post_type_exists(trim($type_arr[0]))) { $my_post['post_type'] = trim($type_arr[0]); $type_set = true; } } elseif ($type == 'status') { if(post_type_exists(trim($type_arr[1]))) { $my_post['post_type'] = trim($type_arr[1]); $type_set = true; } } elseif ($type == 'photo') { if(post_type_exists(trim($type_arr[2]))) { $my_post['post_type'] = trim($type_arr[2]); $type_set = true; } } elseif ($type == 'video') { if(post_type_exists(trim($type_arr[3]))) { $my_post['post_type'] = trim($type_arr[3]); $type_set = true; } } elseif ($type == 'event') { if(post_type_exists(trim($type_arr[4]))) { $my_post['post_type'] = trim($type_arr[4]); $type_set = true; } } elseif ($type == 'offer') { if(post_type_exists(trim($type_arr[5]))) { $my_post['post_type'] = trim($type_arr[5]); $type_set = true; } } } } if($type_set == false) { $my_post['post_type'] = $post_type; } $my_post['comment_status'] = $accept_comments; $my_post['post_status'] = $post_status; if (!isset($fbomatic_Main_Settings['no_utf']) || $fbomatic_Main_Settings['no_utf'] != "on") { $my_post['post_author'] = fbomatic_utf8_encode($post_user_name); } else { $my_post['post_author'] = $post_user_name; } $my_post['fbomatic_post_url'] = $url; $my_post['fbomatic_post_date'] = $date; if (isset($fbomatic_Main_Settings['strip_by_id']) && $fbomatic_Main_Settings['strip_by_id'] != '') { $mock = new DOMDocument; $strip_list = explode(',', $fbomatic_Main_Settings['strip_by_id']); $doc = new DOMDocument(); $internalErrors = libxml_use_internal_errors(true); $doc->loadHTML('<?xml encoding="utf-8" ?>' . $content); libxml_use_internal_errors($internalErrors); foreach ($strip_list as $strip_id) { $element = $doc->getElementById(trim($strip_id)); if (isset($element)) { $element->parentNode->removeChild($element); } } $body = $doc->getElementsByTagName('body')->item(0); if(isset($body->childNodes)) { foreach ($body->childNodes as $child){ $mock->appendChild($mock->importNode($child, true)); } $temp_cont = $mock->saveHTML(); if($temp_cont !== FALSE && $temp_cont != '') { $temp_cont = str_replace('<?xml encoding="utf-8" ?>', '', $temp_cont);$temp_cont = html_entity_decode($temp_cont);$temp_cont = trim($temp_cont);if(substr_compare($temp_cont, '</p>', -strlen('</p>')) === 0){$temp_cont = substr_replace($temp_cont ,"", -4);}if(substr( $temp_cont, 0, 3 ) === "<p>"){$temp_cont = substr($temp_cont, 3);} $content = $temp_cont; } } } if (isset($fbomatic_Main_Settings['strip_by_class']) && $fbomatic_Main_Settings['strip_by_class'] != '') { $mock = new DOMDocument; $strip_list = explode(',', $fbomatic_Main_Settings['strip_by_class']); $doc = new DOMDocument(); $internalErrors = libxml_use_internal_errors(true); $doc->loadHTML('<?xml encoding="utf-8" ?>' . $content); libxml_use_internal_errors($internalErrors); foreach ($strip_list as $strip_class) { if(trim($strip_class) == '') { continue; } $finder = new DomXPath($doc); $classname = trim($strip_class); $nodes = $finder->query("//*[contains(@class, '$classname')]"); if ($nodes === FALSE) { break; } foreach ($nodes as $node) { $node->parentNode->removeChild($node); } } $body = $doc->getElementsByTagName('body')->item(0); if(isset($body->childNodes)) { foreach ($body->childNodes as $child){ $mock->appendChild($mock->importNode($child, true)); } $temp_cont = $mock->saveHTML(); if($temp_cont !== FALSE && $temp_cont != '') { $temp_cont = str_replace('<?xml encoding="utf-8" ?>', '', $temp_cont);$temp_cont = html_entity_decode($temp_cont);$temp_cont = trim($temp_cont);if(substr_compare($temp_cont, '</p>', -strlen('</p>')) === 0){$temp_cont = substr_replace($temp_cont ,"", -4);}if(substr( $temp_cont, 0, 3 ) === "<p>"){$temp_cont = substr($temp_cont, 3);} $content = $temp_cont; } } } $content = preg_replace('{href="/(\w)}', 'href="https://facebook.com/$1', $content); if (isset($fbomatic_Main_Settings['strip_links']) && $fbomatic_Main_Settings['strip_links'] == 'on') { $content = fbomatic_strip_links($content); } if ((isset($fbomatic_Main_Settings['links_hide']) && $fbomatic_Main_Settings['links_hide'] == 'on' && isset($fbomatic_Main_Settings['apiKey']) && $fbomatic_Main_Settings['apiKey'] != '') || (isset($fbomatic_Main_Settings['links_hide_google']) && $fbomatic_Main_Settings['links_hide_google'] == 'on' && isset($fbomatic_Main_Settings['gapiKey']) && $fbomatic_Main_Settings['gapiKey'] != '')) { preg_match_all('@(https?:\/\/([-\w\.]+[-\w])+(:\d+)?(\/([\w/_\.#-]*(\?\S+)?[^\.\s"\'])?)*)@i', $content, $matches); foreach (array_unique($matches[0]) as $match) { if(stristr($match, '//goo.gl') === false && !fbomatic_endsWith($match, ".png") && !fbomatic_endsWith($match, ".jpg") && !fbomatic_endsWith($match, ".jpe") && !fbomatic_endsWith($match, ".gif") && !fbomatic_endsWith($match, ".tif") && !fbomatic_endsWith($match, ".tiff") && !fbomatic_endsWith($match, ".x-icon") && !fbomatic_endsWith($match, ".svg") && !fbomatic_endsWith($match, ".ico") && !fbomatic_endsWith($match, ".icon")) { $content = str_replace($match, fbomatic_url_handle($match), $content); } } } if($skip_no_url == '1') { preg_match_all('@(https?:\/\/([-\w\.]+[-\w])+(:\d+)?(\/([\w/_\.#-]*(\?\S+)?[^\.\s"\'])?)*)@i', $content, $matches); if(count(array_unique($matches[0])) == 0) { if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('Skipping post "' . esc_html($title) . '", because it no link in it\'s content.'); } continue; } } $custom_shortcodes_arr = array(); if(trim($custom_crawling_expre) != '') { $custom_crawling_arr = preg_split('/\r\n|\r|\n/', trim($custom_crawling_expre)); foreach($custom_crawling_arr as $cca) { //shortcode_name => [regex expression] if(trim($cca) != '') { $cshortcode_name = explode('=>', $cca); if(isset($cshortcode_name[1])) { $extended_content = ''; $shortcode_name = trim($cshortcode_name[0]); $shortcode_expre = trim($cshortcode_name[1]); if($shortcode_expre != '') { $matches = array(); $rez = preg_match_all($shortcode_expre, $content, $matches); if ($rez === FALSE) { if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('preg_match_all failed for expr: ' . $shortcode_expre . '!'); } $custom_shortcodes_arr[$shortcode_name] = ''; } else { $regcnt = 0; foreach ($matches as $match) { if($regcnt == 0) { $regcnt++; continue; } if(!isset($match[0])) { continue; } $regcnt++; $extended_content .= $match[0] . ' '; } if($extended_content != '') { $custom_shortcodes_arr[$shortcode_name] = $extended_content; } else { $custom_shortcodes_arr[$shortcode_name] = ''; } } } else { $custom_shortcodes_arr[$shortcode_name] = ''; } } } } } $screenimageURL = ''; $screens_attach_id = ''; if (isset($fbomatic_Main_Settings['phantom_screen']) && $fbomatic_Main_Settings['phantom_screen'] == 'on') { if($attach_screen == '1' || (strstr($post_content, '%%item_show_screenshot%%') !== false || strstr($post_content, '%%item_screenshot_url%%') !== false || strstr($custom_fields, '%%item_show_screenshot%%') !== false || strstr($custom_fields, '%%item_screenshot_url%%') !== false)) { if(function_exists('shell' . '_exec')) { $disabled = explode(',', ini_get('disable_functions')); if(!in_array('shell' . '_exec', $disabled)) { if (isset($fbomatic_Main_Settings['phantom_path']) && $fbomatic_Main_Settings['phantom_path'] != '') { $phantomjs_comm = $fbomatic_Main_Settings['phantom_path'] . ' '; } else { $phantomjs_comm = 'phantomjs '; } if (isset($fbomatic_Main_Settings['screenshot_height']) && $fbomatic_Main_Settings['screenshot_height'] != '') { $h = esc_attr($fbomatic_Main_Settings['screenshot_height']); } else { $h = '0'; } if (isset($fbomatic_Main_Settings['screenshot_width']) && $fbomatic_Main_Settings['screenshot_width'] != '') { $w = esc_attr($fbomatic_Main_Settings['screenshot_width']); } else { $w = '1920'; } $upload_dir = wp_upload_dir(); $dir_name = $upload_dir['basedir'] . '/fbomatic-files'; $dir_url = $upload_dir['baseurl'] . '/fbomatic-files'; global $wp_filesystem; if ( ! is_a( $wp_filesystem, 'WP_Filesystem_Base') ){ include_once(ABSPATH . 'wp-admin/includes/file.php');$creds = request_filesystem_credentials( site_url() ); wp_filesystem($creds); } if (!$wp_filesystem->exists($dir_name)) { wp_mkdir_p($dir_name); } $screen_name = uniqid(); $screenimageName = $dir_name . '/' . $screen_name; $screenimageURL = $dir_url . '/' . $screen_name . '.jpg'; if(isset($fbomatic_Main_Settings['proxy_url']) && $fbomatic_Main_Settings['proxy_url'] != '') { $phantomjs_comm .= '--proxy=' . trim($fbomatic_Main_Settings['proxy_url']) . ' '; if (isset($fbomatic_Main_Settings['proxy_auth']) && $fbomatic_Main_Settings['proxy_auth'] != '') { $phantomjs_comm .= '--proxy-auth=' . trim($fbomatic_Main_Settings['proxy_auth']) . ' '; } } $shefunc = trim(' s ') . trim(' h ') . 'ell' . '_exec'; $cmdResult = $shefunc($phantomjs_comm . '"' . dirname(__FILE__) .'/res/phantomjs/phantom-screenshot.js"' . ' "'. dirname(__FILE__) . '" "' . $url . '" "' . $screenimageName . '" ' . $w . ' ' . $h . ' 2>&1'); if($cmdResult === NULL || $cmdResult == '' || trim($cmdResult) === 'timeout' || stristr($cmdResult, 'sh: phantomjs: command not found') !== false) { $screenimageURL = ''; } else { if($wp_filesystem->exists($screenimageName)) { $wp_filetype = wp_check_filetype( $screen_name . '.jpg', null ); $attachment = array( 'post_mime_type' => $wp_filetype['type'], 'post_title' => sanitize_file_name( $screen_name . '.jpg' ), 'post_content' => '', 'post_status' => 'inherit' ); $screens_attach_id = wp_insert_attachment( $attachment, $screenimageName . '.jpg' ); require_once( ABSPATH . 'wp-admin/includes/image.php' ); require_once( ABSPATH . 'wp-admin/includes/media.php' ); $attach_data = wp_generate_attachment_metadata( $screens_attach_id, $screenimageName . '.jpg' ); wp_update_attachment_metadata( $screens_attach_id, $attach_data ); } else { fbomatic_log_to_file('Screenshot file not found after phantom exec: ' . $cmdResult); } } } else { fbomatic_log_to_file('shell' . '_exec in disabled functions list. Please enable to on your server'); } } else { fbomatic_log_to_file('shell' . '_exec disabled. Please enable to on your server'); } } } elseif (isset($fbomatic_Main_Settings['puppeteer_screen']) && $fbomatic_Main_Settings['puppeteer_screen'] == 'on') { if($attach_screen == '1' || (strstr($post_content, '%%item_show_screenshot%%') !== false || strstr($post_content, '%%item_screenshot_url%%') !== false || strstr($custom_fields, '%%item_show_screenshot%%') !== false || strstr($custom_fields, '%%item_screenshot_url%%') !== false)) { if(function_exists('shell' . '_exec')) { $disabled = explode(',', ini_get('disable_functions')); if(!in_array('shell' . '_exec', $disabled)) { $phantomjs_comm = 'node '; if (isset($fbomatic_Main_Settings['screenshot_height']) && $fbomatic_Main_Settings['screenshot_height'] != '') { $h = esc_attr($fbomatic_Main_Settings['screenshot_height']); } else { $h = '0'; } if (isset($fbomatic_Main_Settings['screenshot_width']) && $fbomatic_Main_Settings['screenshot_width'] != '') { $w = esc_attr($fbomatic_Main_Settings['screenshot_width']); } else { $w = '1920'; } if ($w < 350) { $w = 350; } if ($w > 1920) { $w = 1920; } $upload_dir = wp_upload_dir(); $dir_name = $upload_dir['basedir'] . '/fbomatic-files'; $dir_url = $upload_dir['baseurl'] . '/fbomatic-files'; global $wp_filesystem; if ( ! is_a( $wp_filesystem, 'WP_Filesystem_Base') ){ include_once(ABSPATH . 'wp-admin/includes/file.php');$creds = request_filesystem_credentials( site_url() ); wp_filesystem($creds); } if (!$wp_filesystem->exists($dir_name)) { wp_mkdir_p($dir_name); } $screen_name = uniqid(); $screenimageName = $dir_name . '/' . $screen_name . '.jpg'; $screenimageURL = $dir_url . '/' . $screen_name . '.jpg'; $phantomjs_proxcomm = '"null"'; if (isset($fbomatic_Main_Settings['proxy_url']) && $fbomatic_Main_Settings['proxy_url'] != '') { $prx = explode(',', $fbomatic_Main_Settings['proxy_url']); $randomness = array_rand($prx); $phantomjs_proxcomm = '"' . trim($prx[$randomness]); if (isset($fbomatic_Main_Settings['proxy_auth']) && $fbomatic_Main_Settings['proxy_auth'] != '') { $prx_auth = explode(',', $fbomatic_Main_Settings['proxy_auth']); if(isset($prx_auth[$randomness]) && trim($prx_auth[$randomness]) != '') { $phantomjs_proxcomm .= '~~~' . trim($prx_auth[$randomness]); } } $phantomjs_proxcomm .= '"'; } $custom_user_agent = 'default'; $custom_cookies = 'default'; $user_pass = 'default'; $shefunc = trim(' s ') . trim(' h ') . 'ell' . '_exec'; $cmdResult = $shefunc($phantomjs_comm . '"' . dirname(__FILE__) .'/res/puppeteer/screenshot.js"' . ' "' . $url . '" "' . $screenimageName . '" ' . $w . ' ' . $h . ' ' . $phantomjs_proxcomm . ' "' . $custom_user_agent . '" "' . $custom_cookies . '" "' . $user_pass . '" 2>&1'); if(stristr($cmdResult, 'sh: node: command not found') !== false || stristr($cmdResult, 'throw err;') !== false) { $screenimageURL = ''; fbomatic_log_to_file('Error in puppeteer screenshot: exec: ' . $phantomjs_comm . '"' . dirname(__FILE__) .'/res/puppeteer/screenshot.js"' . ' "' . $url . '" "' . $screenimageName . '" ' . $w . ' ' . $h . ' ' . $phantomjs_proxcomm . ' "' . $custom_user_agent . '" "' . $custom_cookies . '" "' . $user_pass . '" , reterr: ' . $cmdResult); } else { if($wp_filesystem->exists($screenimageName)) { $wp_filetype = wp_check_filetype( $screen_name . '.jpg', null ); $attachment = array( 'post_mime_type' => $wp_filetype['type'], 'post_title' => sanitize_file_name( $screen_name . '.jpg' ), 'post_content' => '', 'post_status' => 'inherit' ); $screens_attach_id = wp_insert_attachment( $attachment, $screenimageName); require_once( ABSPATH . 'wp-admin/includes/image.php' ); require_once( ABSPATH . 'wp-admin/includes/media.php' ); $attach_data = wp_generate_attachment_metadata( $screens_attach_id, $screenimageName); wp_update_attachment_metadata( $screens_attach_id, $attach_data ); } else { fbomatic_log_to_file('Screenshot file not found after puppeteer exec: ' . $cmdResult); } } } } } } $new_post_content = fbomatic_replaceContentShortcodes($post_content, $title, $content, $url, $get_img, $description, $author, $author_link, $date, $custom_shortcodes_arr, $link, $screenimageURL); $new_post_title = fbomatic_replaceContentShortcodes($post_title, $title, $content, $url, $get_img, $description, $author, $author_link, $date, $custom_shortcodes_arr, $link, $screenimageURL); $my_post['description'] = $description; $my_post['author'] = $author; $my_post['author_link'] = $author_link; $arr = fbomatic_spin_and_translate($new_post_title, $new_post_content); $new_post_title = $arr[0]; $new_post_content = $arr[1]; $extra_categories = fbomatic_extractKeyWords($content); $extra_categories = implode(',', $extra_categories); $add_cat = ''; if ($keyword_cat != '') { $required_cat_list = explode(',', $keyword_cat); foreach ($required_cat_list as $rtl) { $reqs = explode('=>', trim($rtl)); if(isset($reqs[1]) && $reqs[1] != '' && $reqs[0] != '') { if (stripos($new_post_content, trim($reqs[0])) !== FALSE || stripos($new_post_title, trim($reqs[0])) !== FALSE) { $add_cat .= trim($reqs[1]) . ','; } } } $add_cat = trim($add_cat, ','); } if($add_cat != '') { if($auto_cat_orig != '1') { $auto_categories = '1'; $extra_categories = $add_cat; } else { $extra_categories .= ',' . $add_cat; } $extra_categories = trim($extra_categories, ','); } else { if($keyword_cat != '') { $extra_categories = ''; } } $my_post['extra_categories'] = $extra_categories; $my_post['screen_attach'] = $screens_attach_id; $item_tags = fbomatic_extractKeyWords($content, 3); $item_tags = implode(',', $item_tags); $my_post['extra_tags'] = $item_tags; if ($can_create_tag == '1') { if (!isset($fbomatic_Main_Settings['no_utf']) || $fbomatic_Main_Settings['no_utf'] != "on") { $post_the_tags = ($item_create_tag != '' ? $item_create_tag . ',' : '') . fbomatic_utf8_encode($item_tags); } else { $post_the_tags = ($item_create_tag != '' ? $item_create_tag . ',' : '') . $item_tags; } } else if ($item_create_tag != '') { if (!isset($fbomatic_Main_Settings['no_utf']) || $fbomatic_Main_Settings['no_utf'] != "on") { $post_the_tags = fbomatic_utf8_encode($item_create_tag); } else { $post_the_tags = $item_create_tag; } } else { $post_the_tags = ''; } $add_tag = ''; if (isset($fbomatic_Main_Settings['keyword_tag']) && $fbomatic_Main_Settings['keyword_tag'] != '') { $required_tag_list = explode(',', $fbomatic_Main_Settings['keyword_tag']); foreach ($required_tag_list as $rtl) { $reqs = explode('=>', trim($rtl)); if(isset($reqs[1]) && $reqs[1] != '' && $reqs[0] != '') { if (stripos($new_post_content, trim($reqs[0])) !== FALSE || stripos($new_post_title, trim($reqs[0])) !== FALSE) { $add_tag .= trim($reqs[1]) . ','; } } } } if ($keyword_tag != '') { $required_tag_list = explode(',', $keyword_tag); foreach ($required_tag_list as $rtl) { $reqs = explode('=>', trim($rtl)); if(isset($reqs[1]) && $reqs[1] != '' && $reqs[0] != '') { if (stripos($new_post_content, trim($reqs[0])) !== FALSE || stripos($new_post_title, trim($reqs[0])) !== FALSE) { $add_tag .= trim($reqs[1]) . ','; } } } } if($add_tag != '') { $post_the_tags .= ',' . $add_tag; $post_the_tags = trim($post_the_tags, ','); } $my_post['tags_input'] = $post_the_tags; $new_post_title = fbomatic_replaceContentShortcodesAgain($new_post_title, $extra_categories, $post_the_tags); $new_post_content = fbomatic_replaceContentShortcodesAgain($new_post_content, $extra_categories, $post_the_tags); if ($img_found == true && isset($fbomatic_Main_Settings['strip_featured_image']) && $fbomatic_Main_Settings['strip_featured_image'] == 'on') { $get_img_tmp = explode('?', $get_img); $get_img_tmp = $get_img_tmp[0]; $ext = pathinfo($get_img_tmp, PATHINFO_EXTENSION); $get_img_tmp = preg_quote($get_img_tmp); $get_img_tmp = str_replace('\.' . $ext, '(?:-?\d+x\d+)\.' . $ext, $get_img_tmp); $new_post_content = preg_replace('#<img(?:[^<>]*?)=[\'"]' . $get_img_tmp . '(?:\?[^<>]*?)?[\'"][^<>]*?\/?>#i', '', $new_post_content); } if ($strip_images == '1') { $new_post_content = fbomatic_strip_images($new_post_content); } else { if (isset($fbomatic_Main_Settings['copy_images']) && $fbomatic_Main_Settings['copy_images'] == 'on') { $new_post_content = preg_replace("~\ssrcset=['\"](?:[^'\"]*)['\"]~i", ' ', $new_post_content); preg_match_all('/(http|https|ftp|ftps)?:\/\/\S+\.(?:jpg|png|gif)(?:\?[^"\'\s]*)/i', $new_post_content, $matches); if(isset($matches[0][0])) { $matches[0] = array_unique($matches[0]); foreach($matches[0] as $match) { $file_path = fbomatic_copy_image_locally($match); if($file_path != false) { $file_path = str_replace('\\', '/', $file_path); $new_post_content = str_replace($match, $file_path, $new_post_content); } } } } } if ($strip_text == '1') { $new_post_content = fbomatic_strip_title($new_post_content, $title); } if ($banned_words != '') { $continue = false; $banned_list = explode(',', $banned_words); foreach ($banned_list as $banned_word) { if (stripos($new_post_content, trim($banned_word)) !== FALSE) { if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('Skipping post "' . esc_html($new_post_title) . '", because it\'s content contains banned word (rule): ' . $banned_word); } $continue = true; break; } if (stripos($new_post_title, trim($banned_word)) !== FALSE) { if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('Skipping post "' . esc_html($new_post_title) . '", because it\'s title contains banned word (rule): ' . $banned_word); } $continue = true; break; } } if ($continue === true) { continue; } } if ($require_words != '') { $continue = true; $required_list = explode(',', $require_words); foreach ($required_list as $required_word) { if($required_word != '') { if (stripos($new_post_content, $required_word) !== FALSE) { $continue = false; break; } if (stripos($new_post_title, $required_word) !== FALSE) { $continue = false; break; } } } if ($continue === true) { if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('Skipping post "' . esc_html($new_post_title) . '", because it doesn\'t contain required words.'); } continue; } } $title_count = -1; if (isset($fbomatic_Main_Settings['min_word_title']) && $fbomatic_Main_Settings['min_word_title'] != '') { $title_count = str_word_count($new_post_title); if ($title_count < intval($fbomatic_Main_Settings['min_word_title'])) { if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('Skipping post "' . esc_html($new_post_title) . '", because title length < ' . $fbomatic_Main_Settings['min_word_title']); } continue; } } if (isset($fbomatic_Main_Settings['max_word_title']) && $fbomatic_Main_Settings['max_word_title'] != '') { if ($title_count == -1) { $title_count = str_word_count($new_post_title); } if ($title_count > intval($fbomatic_Main_Settings['max_word_title'])) { if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('Skipping post "' . esc_html($new_post_title) . '", because title length > ' . $fbomatic_Main_Settings['max_word_title']); } continue; } } $content_count = -1; if (isset($fbomatic_Main_Settings['min_word_content']) && $fbomatic_Main_Settings['min_word_content'] != '') { $content_count = str_word_count(fbomatic_strip_html_tags($new_post_content)); if ($content_count < intval($fbomatic_Main_Settings['min_word_content'])) { if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('Skipping post "' . esc_html($new_post_title) . '", because content length < ' . $fbomatic_Main_Settings['min_word_content']); } continue; } } if (isset($fbomatic_Main_Settings['max_word_content']) && $fbomatic_Main_Settings['max_word_content'] != '') { if ($content_count == -1) { $content_count = str_word_count(fbomatic_strip_html_tags($new_post_content)); } if ($content_count > intval($fbomatic_Main_Settings['max_word_content'])) { if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('Skipping post "' . esc_html($new_post_title) . '", because content length > ' . $fbomatic_Main_Settings['max_word_content']); } continue; } } if (isset($fbomatic_Main_Settings['banned_words']) && $fbomatic_Main_Settings['banned_words'] != '') { $continue = false; $banned_list = explode(',', $fbomatic_Main_Settings['banned_words']); foreach ($banned_list as $banned_word) { if (stripos($new_post_content, trim($banned_word)) !== FALSE) { if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('Skipping post "' . esc_html($new_post_title) . '", because it\'s content contains global banned word: ' . $banned_word); } $continue = true; break; } if (stripos($new_post_title, trim($banned_word)) !== FALSE) { if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('Skipping post "' . esc_html($new_post_title) . '", because it\'s title contains global banned word: ' . $banned_word); } $continue = true; break; } } if ($continue === true) { continue; } } if (isset($fbomatic_Main_Settings['required_words']) && $fbomatic_Main_Settings['required_words'] != '') { $continue = true; $required_list = explode(',', $fbomatic_Main_Settings['required_words']); foreach ($required_list as $required_word) { if($required_word != '') { if (stripos($new_post_content, $required_word) !== FALSE) { $continue = false; break; } if (stripos($new_post_title, $required_word) !== FALSE) { $continue = false; break; } } } if ($continue === true) { if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('Skipping post "' . esc_html($new_post_title) . '", because it doesn\'t contain global required words.'); } continue; } } if (isset($fbomatic_Main_Settings['fix_html']) && $fbomatic_Main_Settings['fix_html'] == "on") { $new_post_content = fbomatic_repairHTML($new_post_content); $new_post_content = str_replace('%20', '', $new_post_content); $new_post_content = str_replace('/V/', '/v/', $new_post_content); $new_post_content = str_replace('?Oh=', '?oh=', $new_post_content); } if ($strip_by_regex !== '') { $xstrip_by_regex = preg_split('/\r\n|\r|\n/', $strip_by_regex); $xreplace_regex = preg_split('/\r\n|\r|\n/', $replace_regex); $xcnt = 0; foreach($xstrip_by_regex as $sbr) { if(isset($xreplace_regex[$xcnt])) { $repreg = $xreplace_regex[$xcnt]; } else { $repreg = ''; } $xcnt++; $temp_cont = preg_replace("~" . $sbr . "~i", $repreg, $new_post_content); if($temp_cont !== NULL) { $new_post_content = $temp_cont; } } } $exc_cont = $content; if ($strip_by_regex !== '') { $xstrip_by_regex = preg_split('/\r\n|\r|\n/', $strip_by_regex); $xreplace_regex = preg_split('/\r\n|\r|\n/', $replace_regex); $xcnt = 0; foreach($xstrip_by_regex as $sbr) { if(isset($xreplace_regex[$xcnt])) { $repreg = $xreplace_regex[$xcnt]; } else { $repreg = ''; } $xcnt++; $temp_cont = preg_replace("~" . $sbr . "~i", $repreg, $exc_cont); if($temp_cont !== NULL) { $exc_cont = $temp_cont; } } } if (!isset($fbomatic_Main_Settings['no_utf']) || $fbomatic_Main_Settings['no_utf'] != "on") { $new_post_content = fbomatic_utf8_encode(html_entity_decode($new_post_content)); } $new_post_content = str_replace('</ iframe>', '</iframe>', $new_post_content); if (!isset($fbomatic_Main_Settings['no_utf']) || $fbomatic_Main_Settings['no_utf'] != "on") { $new_post_title = fbomatic_utf8_encode($new_post_title); } if($limit_title_word_count != '' && is_numeric($limit_title_word_count)) { $new_post_title = wp_trim_words($new_post_title, intval($limit_title_word_count), ''); } if($new_post_title == '') { $new_post_title = $default_title; } else { if (!isset($fbomatic_Main_Settings['no_utf']) || $fbomatic_Main_Settings['no_utf'] != "on") { $new_post_title = str_replace('& hellip;', '...', html_entity_decode($new_post_title)); } else { $new_post_title = str_replace('& hellip;', '...', $new_post_title); } } if (isset($fbomatic_Main_Settings['no_duplicate']) && $fbomatic_Main_Settings['no_duplicate'] == 'on') { $xposts = get_posts( array( 'post_type' => $post_type, 'title' => html_entity_decode($new_post_title), 'post_status' => 'any', 'numberposts' => 1, 'update_post_term_cache' => false, 'update_post_meta_cache' => false, 'orderby' => 'post_date ID', 'order' => 'ASC', ) ); if ( ! empty( $xposts ) ) { $zap = $xposts[0]; } else { $zap = null; } if($zap !== null) { continue; } } if($ret_content == 1) { return array($new_post_content, $new_post_title); } $my_post['post_content'] = $new_post_content; if($no_excerpt != '1') { if (isset($fbomatic_Main_Settings['translate']) && $fbomatic_Main_Settings['translate'] != "disabled" && $fbomatic_Main_Settings['translate'] != "en") { if (!isset($fbomatic_Main_Settings['no_utf']) || $fbomatic_Main_Settings['no_utf'] != "on") { $my_post['post_excerpt'] = fbomatic_utf8_encode(fbomatic_getExcerpt($new_post_content)); } else { $my_post['post_excerpt'] = fbomatic_getExcerpt($new_post_content); } } else { if (!isset($fbomatic_Main_Settings['no_utf']) || $fbomatic_Main_Settings['no_utf'] != "on") { $my_post['post_excerpt'] = fbomatic_utf8_encode(fbomatic_getExcerpt($exc_cont)); } else { $my_post['post_excerpt'] = fbomatic_getExcerpt($exc_cont); } } } else { $my_post['post_excerpt'] = ''; } $my_post['post_title'] = $new_post_title; $my_post['original_title'] = $title; $my_post['original_content'] = $content; $my_post['fbomatic_source_feed'] = $feed_uri; $my_post['fbomatic_timestamp'] = fbomatic_get_date_now(); $my_post['fbomatic_post_format'] = $post_format; if (isset($default_category) && $default_category !== 'fbomatic_no_category_12345678' && $default_category[0] !== 'fbomatic_no_category_12345678') { if(is_array($default_category)) { $cat_list = ''; foreach($default_category as $dc) { $cat_list .= get_cat_name($dc) . ','; } $cat_list = trim($cat_list, ','); $extra_categories_temp = trim( $cat_list . ',' .$extra_categories, ','); } else { $extra_categories_temp = trim(get_cat_name($default_category) . ',' .$extra_categories, ','); } } else { $extra_categories_temp = $extra_categories; } $custom_arr = array(); if($custom_fields != '') { if(stristr($custom_fields, '=>') != false) { $rule_arr = explode(',', trim($custom_fields)); foreach($rule_arr as $rule) { $my_args = explode('=>', trim($rule)); if(isset($my_args[1])) { $custom_field_content = trim($my_args[1]); $custom_field_content = fbomatic_replaceContentShortcodes($custom_field_content, $new_post_title, $new_post_content, $url, $get_img, $description, $author, $author_link, $date, $custom_shortcodes_arr, $link, $screenimageURL); $custom_field_content = fbomatic_replaceContentShortcodesAgain($custom_field_content, $extra_categories, $item_tags); if(stristr($my_args[0], '[') !== false && stristr($my_args[0], ']') !== false) { preg_match_all('#([^\[\]]*?)\[([^\[\]]*?)\]#', $my_args[0], $cfm); if(isset($cfm[2][0])) { if(isset($custom_arr[trim($cfm[1][0])]) && is_array($custom_arr[trim($cfm[1][0])])) { $custom_arr[trim($cfm[1][0])] = array_merge($custom_arr[trim($cfm[1][0])], array(trim($cfm[2][0]) => $custom_field_content)); } else { $custom_arr[trim($cfm[1][0])] = array(trim($cfm[2][0]) => $custom_field_content); } } else { $custom_arr[trim($my_args[0])] = $custom_field_content; } } else { $custom_arr[trim($my_args[0])] = $custom_field_content; } } } } } $custom_arr = array_merge($custom_arr, array('fbomatic_post_cats' => $extra_categories_temp, 'fbomatic_post_tags' => $post_the_tags)); $custom_tax_arr = array(); if($custom_tax != '') { if(stristr($custom_tax, '=>') != false) { $rule_arr = explode(';', trim($custom_tax)); foreach($rule_arr as $rule) { $my_args = explode('=>', trim($rule)); if(isset($my_args[1])) { $custom_tax_content = trim($my_args[1]); $custom_tax_content = fbomatic_replaceContentShortcodes($custom_tax_content, $new_post_title, $new_post_content, $url, $get_img, $description, $author, $author_link, $date, $custom_shortcodes_arr, $link, $screenimageURL); $custom_tax_content = fbomatic_replaceContentShortcodesAgain($custom_tax_content, $extra_categories, $item_tags); if(substr(trim($my_args[0]), 0, 3) === "pa_" && $post_type == 'product' && !empty($custom_tax_content)) { if(isset($custom_arr['_product_attributes'])) { $custom_arr['_product_attributes'] = array_merge($custom_arr['_product_attributes'], array(trim($my_args[0]) =>array( 'name' => trim($my_args[0]), 'value' => $custom_tax_content, 'is_visible' => '1', 'is_taxonomy' => '1' ))); } else { $custom_arr['_product_attributes'] = array(trim($my_args[0]) =>array( 'name' => trim($my_args[0]), 'value' => $custom_tax_content, 'is_visible' => '1', 'is_taxonomy' => '1' )); } } if(isset($custom_tax_arr[trim($my_args[0])])) { $custom_tax_arr[trim($my_args[0])] .= ',' . $custom_tax_content; } else { $custom_tax_arr[trim($my_args[0])] = $custom_tax_content; } } } } } if(count($custom_tax_arr) > 0) { $my_post['taxo_input'] = $custom_tax_arr; } $my_post['meta_input'] = $custom_arr; if ($enable_pingback == '1') { $my_post['ping_status'] = 'open'; } else { $my_post['ping_status'] = 'closed'; } remove_filter('content_save_pre', 'wp_filter_post_kses'); remove_filter('content_filtered_save_pre', 'wp_filter_post_kses');remove_filter('title_save_pre', 'wp_filter_kses'); $post_id = wp_insert_post($my_post, true); add_filter('content_save_pre', 'wp_filter_post_kses'); add_filter('content_filtered_save_pre', 'wp_filter_post_kses');add_filter('title_save_pre', 'wp_filter_kses'); if (!is_wp_error($post_id)) { if($post_id === 0) { fbomatic_log_to_file('An error occurred while inserting post into wp database! Title:' . $my_post['post_title']); continue; } $posts_inserted++; if($wpml_lang != '' && function_exists('pll_set_post_language')) { pll_set_post_language($post_id, $wpml_lang); } if($remove_default == '1' && ($auto_categories == '1' || (isset($default_category) && $default_category !== 'fbomatic_no_category_12345678' && $default_category[0] !== 'fbomatic_no_category_12345678'))) { $default_categories = wp_get_post_categories($post_id); } if(isset($my_post['taxo_input'])) { foreach($my_post['taxo_input'] as $taxn => $taxval) { $taxn = trim($taxn); $taxval = trim($taxval); if(is_taxonomy_hierarchical($taxn)) { $taxval = array_map('trim', explode(',', $taxval)); for($ii = 0; $ii < count($taxval); $ii++) { if(!is_numeric($taxval[$ii])) { $xtermid = get_term_by('name', $taxval[$ii], $taxn); if($xtermid !== false) { $taxval[$ii] = intval($xtermid->term_id); } else { wp_insert_term( $taxval[$ii], $taxn); $xtermid = get_term_by('name', $taxval[$ii], $taxn); if($xtermid !== false) { if($wpml_lang != '' && function_exists('pll_set_term_language')) { pll_set_term_language($xtermid->term_id, $wpml_lang); } elseif($wpml_lang != '' && has_filter('wpml_object_id')) { $wpml_element_type = apply_filters( 'wpml_element_type', $taxn ); $pars['element_id'] = $xtermid->term_id; $pars['element_type'] = $wpml_element_type; $pars['language_code'] = $wpml_lang; $pars['trid'] = FALSE; $pars['source_language_code'] = NULL; do_action('wpml_set_element_language_details', $pars); } $taxval[$ii] = intval($xtermid->term_id); } } } } wp_set_post_terms($post_id, $taxval, $taxn, true); } else { wp_set_post_terms($post_id, trim($taxval), $taxn, true); } } } if (isset($my_post['fbomatic_post_format']) && $my_post['fbomatic_post_format'] != '' && $my_post['fbomatic_post_format'] != 'post-format-standard') { wp_set_post_terms($post_id, $my_post['fbomatic_post_format'], 'post_format', true); } if($my_post['screen_attach'] != '') { $media_post = wp_update_post( array( 'ID' => $my_post['screen_attach'], 'post_parent' => $post_id, ), true ); if( is_wp_error( $media_post ) ) { fbomatic_log_to_file( 'Failed to assign post attachment ' . $my_post['screen_attach'] . ' to post id ' . $post_id . ': ' . print_r( $media_post, 1 ) ); } } $featured_path = ''; $image_failed = false; if ($featured_image == '1') { $get_img = $my_post['fbomatic_post_image']; if ($get_img != '') { if (!fbomatic_generate_featured_image($get_img, $post_id)) { $image_failed = true; if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('fbomatic_generate_featured_image failed for ' . $get_img . '!'); } } else { $featured_path = $get_img; } } else { $image_failed = true; } } if ($image_failed || $featured_image !== '1') { if ($image_url != '') { $image_urlx = explode(',',$image_url); $image_urlx = trim($image_urlx[array_rand($image_urlx)]); $retim = false; if(is_numeric($image_urlx) && intval($image_urlx) > 0) { require_once(ABSPATH . 'wp-admin/includes/image.php'); require_once(ABSPATH . 'wp-admin/includes/media.php'); $res2 = set_post_thumbnail($post_id, $image_urlx); if ($res2 === FALSE) { } else { $retim = true; } } else { { stream_context_set_default( [ 'ssl' => [ 'verify_peer' => false, 'verify_peer_name' => false, ], ]); error_reporting(0); $url_headers = get_headers($image_urlx, 1); error_reporting(E_ALL); if (isset($url_headers['Content-Type'])) { if (is_array($url_headers['Content-Type'])) { $img_type = strtolower($url_headers['Content-Type'][0]); } else { $img_type = strtolower($url_headers['Content-Type']); } if (strstr($img_type, 'image/') !== false) { if (!fbomatic_generate_featured_image($image_urlx, $post_id)) { $image_failed = true; if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('fbomatic_generate_featured_image failed to default value: ' . $image_urlx . '!'); } } else { $featured_path = $image_urlx; } } } } } } } if($featured_image == '1' && $featured_path == '' && isset($fbomatic_Main_Settings['skip_no_img']) && $fbomatic_Main_Settings['skip_no_img'] == 'on') { if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('Skipping post "' . $my_post['post_title'] . '", because it failed to generate a featured image for: ' . $get_img . ' and ' . $image_url); } wp_delete_post($post_id, true); $posts_inserted--; continue; } if ($auto_categories == '1') { if ($my_post['extra_categories'] != '') { $extra_cats = explode(',', $my_post['extra_categories']); foreach($extra_cats as $extra_cat) { if($parent_category_id != '') { $termid = fbomatic_create_terms('category', $parent_category_id, trim($extra_cat)); } else { $termid = fbomatic_create_terms('category', null, trim($extra_cat)); } if($wpml_lang != '' && function_exists('pll_set_term_language')) { foreach($termid as $tx) { pll_set_term_language($tx, $wpml_lang); } } elseif($wpml_lang != '' && has_filter('wpml_object_id')) { $wpml_element_type = apply_filters( 'wpml_element_type', 'category' ); foreach($termid as $tx) { $pars['element_id'] = $tx; $pars['element_type'] = $wpml_element_type; $pars['language_code'] = $wpml_lang; $pars['trid'] = FALSE; $pars['source_language_code'] = NULL; do_action('wpml_set_element_language_details', $pars); } } wp_set_post_terms($post_id, $termid, 'category', true); } } } if (isset($default_category) && $default_category !== 'fbomatic_no_category_12345678' && $default_category[0] !== 'fbomatic_no_category_12345678') { $cats = array(); if(is_array($default_category)) { $cats = $default_category; } else { $cats[] = $default_category; } global $sitepress; if($wpml_lang != '' && has_filter('wpml_current_language') && $sitepress != null) { $current_language = apply_filters( 'wpml_current_language', NULL ); $sitepress->switch_lang($wpml_lang); } wp_set_post_categories($post_id, $cats, true); if($wpml_lang != '' && function_exists('pll_set_term_language')) { foreach($cats as $cc) { pll_set_term_language($cc, $wpml_lang); } } elseif($wpml_lang != '' && has_filter('wpml_current_language') && $sitepress != null) { $sitepress->switch_lang($current_language); } } if($remove_default == '1' && ($auto_categories == '1' || (isset($default_category) && $default_category !== 'fbomatic_no_category_12345678' && $default_category[0] !== 'fbomatic_no_category_12345678'))) { $new_categories = wp_get_post_categories($post_id); if(isset($default_categories) && !($default_categories == $new_categories)) { foreach($default_categories as $dc) { $rem_cat = get_category( $dc ); wp_remove_object_terms( $post_id, $rem_cat->slug, 'category' ); } } } if (isset($fbomatic_Main_Settings['post_source_custom']) && $fbomatic_Main_Settings['post_source_custom'] != '') { $tax_rez = wp_set_object_terms( $post_id, $fbomatic_Main_Settings['post_source_custom'], 'coderevolution_post_source', true); } else { $tax_rez = wp_set_object_terms( $post_id, 'FBomatic_' . $param, 'coderevolution_post_source', true); } if (is_wp_error($tax_rez)) { if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('wp_set_object_terms failed for: ' . $post_id . '!'); } } if (isset($fbomatic_Main_Settings['link_source']) && $fbomatic_Main_Settings['link_source'] == 'on') { $title_link_url = '1'; } else { $title_link_url = '0'; } fbomatic_addPostMeta($post_id, $my_post, $param, $featured_path, $title_link_url); if($wpml_lang != '' && (class_exists('SitePress') || function_exists('wpml_object_id'))) { $wpml_element_type = apply_filters( 'wpml_element_type', $post_type ); $pars['element_id'] = $post_id; $pars['element_type'] = $wpml_element_type; $pars['language_code'] = $wpml_lang; $pars['source_language_code'] = NULL; do_action('wpml_set_element_language_details', $pars); global $wp_filesystem; if ( ! is_a( $wp_filesystem, 'WP_Filesystem_Base') ){ include_once(ABSPATH . 'wp-admin/includes/file.php');$creds = request_filesystem_credentials( site_url() ); wp_filesystem($creds); } if($wp_filesystem->exists(WP_PLUGIN_DIR . '/sitepress-multilingual-cms/inc/wpml-api.php')) { include_once( WP_PLUGIN_DIR . '/sitepress-multilingual-cms/inc/wpml-api.php' ); } $wpml_lang = trim($wpml_lang); if(function_exists('wpml_update_translatable_content')) { wpml_update_translatable_content('post_' . $post_type, $post_id, $wpml_lang); if($my_post['fbomatic_post_url'] != '') { global $sitepress; global $wpdb; $keyid = md5($my_post['fbomatic_post_url']); $keyName = $keyid . '_wpml'; $rezxxxa = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}postmeta WHERE `meta_key` = '$keyName' limit 1", ARRAY_A ); if(count($rezxxxa) != 0) { $metaRow = $rezxxxa[0]; $metaValue = $metaRow['meta_value']; $metaParts = explode('_', $metaValue); $sitepress->set_element_language_details($post_id, 'post_'.$my_post['post_type'] , $metaParts[0], $wpml_lang, $metaParts[1] ); } else { $ptrid = $sitepress->get_element_trid($post_id); add_post_meta($post_id, $keyid.'_wpml', $ptrid.'_'.$wpml_lang ); } } } } if ($my_post['insert_comments'] && $my_post['insert_comments'] != '0' && is_numeric($my_post['insert_comments'])) { if($xs_cookie != '' && $cuser_cookie != '') { if(isset($my_post['crawled_comments'])) { $comms_added = 0; $add_comms = true; $comment_num = intval($my_post['insert_comments']); $comments = $my_post['crawled_comments']; while($add_comms === true) { $date = current_time('mysql'); if ((isset($fbomatic_Main_Settings['spin_text']) && $fbomatic_Main_Settings['spin_text'] !== 'disabled') || (isset($fbomatic_Main_Settings['translate']) && $fbomatic_Main_Settings['translate'] != 'disabled')) { $title_sep = ' 07543210745321 '; $comm_trans = ''; foreach ($comments as $comment) { $comm_trans .= $comment['message'] . $title_sep; } $comm_trans = trim($comm_trans, $title_sep); if($comm_trans != '') { $arr = fbomatic_spin_and_translate($comm_trans, 'hello'); $comm_trans = $arr[0]; $comm_trans = explode(trim($title_sep), $comm_trans); if(count($comm_trans) == count($comments)) { for($i = 0; $i < count($comments); $i++) { $comments[$i]['message'] = $comm_trans[$i]; } } } } if (isset($my_post['append_comments']) && $my_post['append_comments'] == '1') { if(count($comments) > 0) { $content_post = get_post($post_id); $append_cont = '<ul>'; foreach ($comments as $comment) { if ($comment_num > $comms_added) { if(trim($comment['message']) != '') { if(strstr($content_post->post_content, trim($comment['message'])) === false) { $append_cont .= '<li>' . trim($comment['message']); $append_cont .= '</li>'; $comms_added++; } } } else { $add_comms = false; break; } } $append_cont .= '</ul>'; $content_post->post_content .= '<br/>' . $append_cont; $wp_error = ''; remove_filter('content_save_pre', 'wp_filter_post_kses'); remove_filter('content_filtered_save_pre', 'wp_filter_post_kses');remove_filter('title_save_pre', 'wp_filter_kses'); wp_update_post($content_post, $wp_error); add_filter('content_save_pre', 'wp_filter_post_kses'); add_filter('content_filtered_save_pre', 'wp_filter_post_kses');add_filter('title_save_pre', 'wp_filter_kses'); } } else { foreach ($comments as $comment) { if ($comment_num > $comms_added) { $comm = $comment['message']; $author = $comment['author_name']; $authorID = $comment['author_id']; $authorLink = ''; $authorLink = "https://facebook.com/" . $authorID; $date = date('Y-m-d H:i:s', strtotime($comment['time'])); if (trim($comm) != '') { $data = array( 'comment_post_ID' => $post_id, 'comment_author' => $author, 'comment_author_email' => '', 'comment_author_url' => $authorLink, 'comment_content' => $comm, 'comment_type' => '', 'comment_parent' => 0, 'user_id' => 1, 'comment_author_IP' => '127.0.0.1', 'comment_agent' => fbomatic_get_random_user_agent(), 'comment_date' => $date, 'comment_approved' => 1 ); wp_insert_comment($data); $comms_added++; } } else { $add_comms = false; break; } } $add_comms = false; } } } } else { $comms_added = 0; $add_comms = true; $comment_num = intval($my_post['insert_comments']); $url = 'https://graph.facebook.com/v'; if (isset($fbomatic_Main_Settings['api_version']) && $fbomatic_Main_Settings['api_version'] != 'default' && $fbomatic_Main_Settings['api_version'] != '') { $url .= $fbomatic_Main_Settings['api_version']; } else { $url .= FBOMATIC_API_VER; } $url .= '/' . $my_post['fb_group_id'] . '_' . $my_post['fbomatic_post_id'] . '/comments?access_token=' . $access_token . '&filter=toplevel&summary=1&fields=message,id,from,message_tags,created_time,attachment'; $url = $url; while($add_comms === true) { if($comms_added >= 25) { usleep(500000); } $comments = fbomatic_get_web_page($url); if (stristr($comments, 'data')) { $comments_json = json_decode($comments); if(isset($comments_json->paging->next)) { $url = $comments_json->paging->next; } else { $add_comms = false; } $comments = $comments_json->data; $date = current_time('mysql'); if ((isset($fbomatic_Main_Settings['spin_text']) && $fbomatic_Main_Settings['spin_text'] !== 'disabled') || (isset($fbomatic_Main_Settings['translate']) && $fbomatic_Main_Settings['translate'] != 'disabled')) { $title_sep = ' 07543210745321 '; $comm_trans = ''; foreach ($comments as $comment) { $comm_trans .= $comment->message . $title_sep; } $comm_trans = trim($comm_trans, $title_sep); if($comm_trans != '') { $arr = fbomatic_spin_and_translate($comm_trans, 'hello'); $comm_trans = $arr[0]; $comm_trans = explode(trim($title_sep), $comm_trans); if(count($comm_trans) == count($comments)) { for($i = 0; $i < count($comments); $i++) { $comments[$i]->message = $comm_trans[$i]; } } } } if (isset($my_post['append_comments']) && $my_post['append_comments'] == '1') { if(count($comments) > 0) { $content_post = get_post($post_id); $append_cont = '<ul>'; foreach ($comments as $comment) { if ($comment_num > $comms_added) { if(trim($comment->message) != '') { if(strstr($content_post->post_content, trim($comment->message)) === false) { $commentImg = ''; if(isset($comment->attachment->media->image->src)) { $commentImg = $comment->attachment->media->image->src; } $append_cont .= '<li>' . trim($comment->message); if (trim($commentImg) != '') { $append_cont .= '<img src="' . esc_url_raw($commentImg) . '"/><br/>'; } $append_cont .= '</li>'; $comms_added++; } } } else { $add_comms = false; break; } } $append_cont .= '</ul>'; $content_post->post_content .= '<br/>' . $append_cont; $wp_error = ''; remove_filter('content_save_pre', 'wp_filter_post_kses'); remove_filter('content_filtered_save_pre', 'wp_filter_post_kses');remove_filter('title_save_pre', 'wp_filter_kses'); wp_update_post($content_post, $wp_error); add_filter('content_save_pre', 'wp_filter_post_kses'); add_filter('content_filtered_save_pre', 'wp_filter_post_kses');add_filter('title_save_pre', 'wp_filter_kses'); } } else { foreach ($comments as $comment) { if ($comment_num > $comms_added) { $comm = $comment->message; $commentImg = ''; if(isset($comment->attachment->media->image->src)) { $commentImg = $comment->attachment->media->image->src; } if (trim($commentImg) != '') { $comm .= '<img src="' . esc_url_raw($commentImg) . '"/><br/>'; } if(isset($comment->from)) { $author = $comment->from->name; $authorID = $comment->from->id; } else { $author = 'admin'; $authorID = ''; } $authorLink = ''; $authorLink = "https://facebook.com/" . $authorID; $date = date('Y-m-d H:i:s', strtotime($comment->created_time)); if (trim($comm) != '') { $data = array( 'comment_post_ID' => $post_id, 'comment_author' => $author, 'comment_author_email' => '', 'comment_author_url' => $authorLink, 'comment_content' => $comm, 'comment_type' => '', 'comment_parent' => 0, 'user_id' => 1, 'comment_author_IP' => '127.0.0.1', 'comment_agent' => fbomatic_get_random_user_agent(), 'comment_date' => $date, 'comment_approved' => 1 ); wp_insert_comment($data); $comms_added++; } } else { $add_comms = false; break; } } } } } } } } else { fbomatic_log_to_file('Failed to insert post into database! Title:' . $my_post['post_title'] . '! Error: ' . $post_id->get_error_message() . 'Error code: ' . $post_id->get_error_code() . 'Error data: ' . $post_id->get_error_data()); continue; } $count++; } if($count == 1) { if($continue_search == '1') { if(isset($json->paging->next)) { $skip_posts_temp[$param] = $json->paging->next; } else { $skip_posts_temp[$param] = ''; } update_option('fbomatic_continue_search', $skip_posts_temp); } else { $skip_posts_temp[$param] = ''; update_option('fbomatic_continue_search', $skip_posts_temp); } } } catch (Exception $e) { if($continue_search == '1') { $skip_posts_temp[$param] = ''; update_option('fbomatic_continue_search', $skip_posts_temp); } fbomatic_log_to_file('Exception thrown ' . esc_html($e->getMessage()) . '!'); if($auto == 1) { fbomatic_clearFromList($param); } return 'fail'; } if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('Rule ID ' . esc_html($param) . ' (' . $rule_description . ') succesfully run! ' . esc_html($posts_inserted) . ' posts created!'); } if (isset($fbomatic_Main_Settings['send_email']) && $fbomatic_Main_Settings['send_email'] == 'on' && $fbomatic_Main_Settings['email_address'] !== '') { try { $to = $fbomatic_Main_Settings['email_address']; $subject = '[fbomatic] Rule running report - ' . fbomatic_get_date_now(); $message = 'Rule ID ' . esc_html($param) . ' (' . $rule_description . ') succesfully run! ' . esc_html($posts_inserted) . ' posts created!'; $headers[] = 'From: F-omatic Plugin <fbomatic@noreply.net>'; $headers[] = 'Reply-To: noreply@fbomatic.com'; $headers[] = 'X-Mailer: PHP/' . phpversion(); $headers[] = 'Content-Type: text/html'; $headers[] = 'Charset: ' . get_option('blog_charset', 'UTF-8'); wp_mail($to, $subject, $message, $headers); } catch (Exception $e) { if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('Failed to send mail: Exception thrown ' . esc_html($e->getMessage()) . '!'); } } } } if ($posts_inserted == 0) { if($auto == 1) { fbomatic_clearFromList($param); } if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('No new posts found.'); } if($continue_search == '1') { $no_luck = get_option('previous_no_import_fb' . $param, '0'); if($no_luck == '1') { $skip_posts_temp[$param] = ''; update_option('fbomatic_continue_search', $skip_posts_temp); update_option('previous_no_import_fb' . $param, '0'); } else { update_option('previous_no_import_fb' . $param, '1'); } } return 'nochange'; } else { if($continue_search == '1') { update_option('previous_no_import_fb' . $param, '0'); } if($auto == 1) { fbomatic_clearFromList($param); } return 'ok'; } } function fbomatic_strip_links($content) { $content = preg_replace('~<a(?:[^>]*)>~', "", $content); $content = preg_replace('~<\/a>~', "", $content); return $content; } add_filter('the_content', 'fbomatic_add_affiliate_keyword'); add_filter('the_excerpt', 'fbomatic_add_affiliate_keyword'); function fbomatic_add_affiliate_keyword($content) { $rules = get_option('fbomatic_keyword_list'); if(!is_array($rules)) { $rules = array(); } $output = ''; if (!empty($rules)) { foreach ($rules as $request => $value) { if (is_array($value) && isset($value[1]) && $value[1] != '') { $repl = $value[1]; } else { $repl = $request; } if (isset($value[0]) && $value[0] != '') { $content = preg_replace('\'(?!((<.*?)|(<a.*?)))(\b' . preg_quote($request, '\'') . '\b)(?!(([^<>]*?)>)|([^>]*?<\/a>))\'i', '<a href="' . esc_url_raw($value[0]) . '" target="_blank">' . esc_html($repl) . '</a>', $content); } else { $content = preg_replace('\'(?!((<.*?)|(<a.*?)))(\b' . preg_quote($request, '\'') . '\b)(?!(([^<>]*?)>)|([^>]*?<\/a>))\'i', esc_html($repl), $content); } } } return $content; } function fbomatic_testPhantom() { if(!function_exists('shell' . '_exec')) { return 0; } $disabled = explode(',', ini_get('disable_functions')); if(in_array('shell' . '_exec', $disabled)) { return 0; } $fbomatic_Main_Settings = get_option('fbomatic_Main_Settings', false); if (isset($fbomatic_Main_Settings['phantom_path']) && $fbomatic_Main_Settings['phantom_path'] != '') { $phantomjs_comm = $fbomatic_Main_Settings['phantom_path'] . ' '; } else { $phantomjs_comm = 'phantomjs '; } $shefunc = trim(' s ') . trim(' h ') . 'ell' . '_exec'; $cmdResult = $shefunc($phantomjs_comm . '-h 2>&1'); if(stristr($cmdResult, 'Usage') !== false) { return 1; } return 0; } add_action('wp_ajax_fbomatic_post_now', 'fbomatic_submit_post_callback'); function fbomatic_submit_post_callback() { $run_id = $_POST['id']; $wp_post = get_post($run_id); if($wp_post != null) { if($wp_post->post_title == 'Auto Draft' && $wp_post->post_content == '' && $wp_post->post_status == 'auto-draft') { die(); } fbomatic_do_post($wp_post, true); } die(); } add_action('wp_ajax_fbomatic_comments_now', 'fbomatic_submit_comment_callback'); function fbomatic_submit_comment_callback() { $run_id = $_POST['id']; $groupId = $_POST['groupid']; $postId = $_POST['fbpostId']; $commentcontent = $_POST['commentcontent']; $comment_num = $_POST['commentnum']; $wp_post = get_post($run_id); if($comment_num != null && $groupId != null && $postId != null && $wp_post != null) { echo fbomatic_import_comments($wp_post, $groupId, $postId, $comment_num, $commentcontent); } die(); } function fbomatic_import_comments($wp_post, $groupId, $postId, $comment_num, $commentcontent) { $access_token = ''; $fbomatic_Main_Settings = get_option('fbomatic_Main_Settings', false); if (!isset($fbomatic_Main_Settings['app_id']) || trim($fbomatic_Main_Settings['app_id']) == '') { fbomatic_log_to_file('You need to insert a valid Facebook App ID for this to work!'); return 'fail'; } if (!isset($fbomatic_Main_Settings['app_secret']) || trim($fbomatic_Main_Settings['app_secret']) == '') { fbomatic_log_to_file('You need to insert a valid Facebook App Secret for this to work!'); return 'fail'; } if (!isset($fbomatic_Main_Settings['access_token']) || trim($fbomatic_Main_Settings['access_token']) == '') { $url = "https://graph.facebook.com/oauth/access_token?client_id=" . trim($fbomatic_Main_Settings['app_id']) . "&client_secret=" . trim($fbomatic_Main_Settings['app_secret']) . "&grant_type=client_credentials"; $exec = fbomatic_get_web_page($url); if ($exec === FALSE) { fbomatic_log_to_file('Failed to exec fbomatic_get_web_page (in import comments).'); return 'fail'; } if (stristr($exec, 'access_token=') !== FALSE) { $expl = explode('=', $exec); $access_token = $expl[1]; } elseif (stristr($exec, '"access_token":"') !== FALSE) { $expl = explode('"access_token":"', $exec); $access_token = $expl[1]; $access_token = substr($access_token, 0, strpos($access_token, '"')); } else { fbomatic_log_to_file('Failed to retrive access token from Facebook. Returned: ' . $exec); return 'fail'; } } else { $access_token = $fbomatic_Main_Settings['access_token']; } if($access_token == '') { fbomatic_log_to_file('Access token not correct. Please configure plugin correctly from the "Posts to Facebook" settings page (authorize it to post).'); return 'fail'; } $comms_added = 0; $add_comms = true; $url = 'https://graph.facebook.com/v'; if (isset($fbomatic_Main_Settings['api_version']) && $fbomatic_Main_Settings['api_version'] != 'default' && $fbomatic_Main_Settings['api_version'] != '') { $url .= $fbomatic_Main_Settings['api_version']; } else { $url .= FBOMATIC_API_VER; } $url .= '/' . $groupId . '_' . $postId . '/comments?access_token=' . $access_token . '&filter=toplevel&summary=1&fields=message,id,from,message_tags,created_time,attachment'; while($add_comms === true) { if($comms_added >= 25) { usleep(500000); } $comments = fbomatic_get_web_page($url); if (stristr($comments, 'data')) { $comments_json = json_decode($comments); if(isset($comments_json->paging->next)) { $url = $comments_json->paging->next; } else { $add_comms = false; } $comments = $comments_json->data; $date = current_time('mysql'); if ((isset($fbomatic_Main_Settings['spin_text']) && $fbomatic_Main_Settings['spin_text'] !== 'disabled') || (isset($fbomatic_Main_Settings['translate']) && $fbomatic_Main_Settings['translate'] != 'disabled')) { $title_sep = ' 07543210745321 '; $comm_trans = ''; foreach ($comments as $comment) { $comm_trans .= $comment->message . $title_sep; } $comm_trans = trim($comm_trans, $title_sep); if($comm_trans != '') { $arr = fbomatic_spin_and_translate($comm_trans, 'hello'); $comm_trans = $arr[0]; $comm_trans = explode(trim($title_sep), $comm_trans); if(count($comm_trans) == count($comments)) { for($i = 0; $i < count($comments); $i++) { $comments[$i]->message = $comm_trans[$i]; } } } } if(isset($commentcontent) && $commentcontent == 'true') { if(count($comments) > 0) { $content_post = get_post($wp_post->ID); $append_cont = '<ul>'; foreach ($comments as $comment) { if ($comment_num > $comms_added) { if(trim($comment->message) != '') { if(strstr($content_post->post_content, trim($comment->message)) === false) { $commentImg = ''; if(isset($comment->attachment->media->image->src)) { $commentImg = $comment->attachment->media->image->src; } $append_cont .= '<li>' . trim($comment->message); if (trim($commentImg) != '') { $append_cont .= '<img src="' . esc_url_raw($commentImg) . '"/><br/>'; } $append_cont .= '</li>'; $comms_added++; } } } else { $add_comms = false; break; } } $append_cont .= '</ul>'; $content_post->post_content .= '<br/>' . $append_cont; $wp_error = ''; remove_filter('content_save_pre', 'wp_filter_post_kses'); remove_filter('content_filtered_save_pre', 'wp_filter_post_kses');remove_filter('title_save_pre', 'wp_filter_kses'); wp_update_post($content_post, $wp_error); add_filter('content_save_pre', 'wp_filter_post_kses'); add_filter('content_filtered_save_pre', 'wp_filter_post_kses');add_filter('title_save_pre', 'wp_filter_kses'); } } else { foreach ($comments as $comment) { if ($comment_num > $comms_added) { $author = $comment->from->name; $date = date('Y-m-d H:i:s', strtotime($comment->created_time)); if(comment_exists($author, $date)) { continue; } $comm = $comment->message; $commentImg = ''; if(isset($comment->attachment->media->image->src)) { $commentImg = $comment->attachment->media->image->src; } if (trim($commentImg) != '') { $comm .= '<img src="' . esc_url_raw($commentImg) . '"/><br/>'; } $authorID = $comment->from->id; $authorLink = ''; $authorLink = "https://facebook.com/" . $authorID; if (trim($comm) != '') { $data = array( 'comment_post_ID' => $wp_post->ID, 'comment_author' => $author, 'comment_author_email' => '', 'comment_author_url' => $authorLink, 'comment_content' => $comm, 'comment_type' => '', 'comment_parent' => 0, 'user_id' => 1, 'comment_author_IP' => '127.0.0.1', 'comment_agent' => fbomatic_get_random_user_agent(), 'comment_date' => $date, 'comment_approved' => 1 ); wp_insert_comment($data); $comms_added++; } } else { $add_comms = false; break; } } } } } return 'ok'; } use eventomatic_andreskrey\Readability\ReadabilityFbomatic; use eventomatic_andreskrey\Readability\Configuration; function fbomatic_convert_readable_html($html_string) { try { if(!class_exists('\eventomatic_andreskrey\Readability\ReadabilityFbomatic')) { if(!interface_exists('Psr\Log\LoggerInterface')) { require_once (dirname(__FILE__) . '/res/readability/psr/LoggerInterface.php'); require_once (dirname(__FILE__) . '/res/readability/psr/LoggerAwareInterface.php'); require_once (dirname(__FILE__) . '/res/readability/psr/LoggerAwareTrait.php'); require_once (dirname(__FILE__) . '/res/readability/psr/LoggerTrait.php'); require_once (dirname(__FILE__) . '/res/readability/psr/AbstractLogger.php'); require_once (dirname(__FILE__) . '/res/readability/psr/InvalidArgumentException.php'); require_once (dirname(__FILE__) . '/res/readability/psr/LogLevel.php'); require_once (dirname(__FILE__) . '/res/readability/psr/NullLogger.php'); } require_once (dirname(__FILE__) . "/res/readability/Readability.php"); require_once (dirname(__FILE__) . "/res/readability/ParseException.php"); require_once (dirname(__FILE__) . "/res/readability/Configuration.php"); require_once (dirname(__FILE__) . "/res/readability/Nodes/NodeUtility.php"); require_once (dirname(__FILE__) . "/res/readability/Nodes/NodeTrait.php"); require_once (dirname(__FILE__) . "/res/readability/Nodes/DOM/DOMAttr.php"); require_once (dirname(__FILE__) . "/res/readability/Nodes/DOM/DOMCdataSection.php"); require_once (dirname(__FILE__) . "/res/readability/Nodes/DOM/DOMCharacterData.php"); require_once (dirname(__FILE__) . "/res/readability/Nodes/DOM/DOMComment.php"); require_once (dirname(__FILE__) . "/res/readability/Nodes/DOM/DOMDocument.php"); require_once (dirname(__FILE__) . "/res/readability/Nodes/DOM/DOMDocumentFragment.php"); require_once (dirname(__FILE__) . "/res/readability/Nodes/DOM/DOMDocumentType.php"); require_once (dirname(__FILE__) . "/res/readability/Nodes/DOM/DOMElement.php"); require_once (dirname(__FILE__) . "/res/readability/Nodes/DOM/DOMEntity.php"); require_once (dirname(__FILE__) . "/res/readability/Nodes/DOM/DOMEntityReference.php"); require_once (dirname(__FILE__) . "/res/readability/Nodes/DOM/DOMNode.php"); require_once (dirname(__FILE__) . "/res/readability/Nodes/DOM/DOMNotation.php"); require_once (dirname(__FILE__) . "/res/readability/Nodes/DOM/DOMProcessingInstruction.php"); require_once (dirname(__FILE__) . "/res/readability/Nodes/DOM/DOMText.php"); } $readConf = new Configuration(); $readConf->setSummonCthulhu(true); $readability = new ReadabilityFbomatic($readConf); $readability->parse($html_string); $return_me = $readability->getContent(); if($return_me == '' || $return_me == null) { throw new Exception('Content blank'); } $return_me = str_replace('</article>', '', $return_me); $return_me = str_replace('<article>', '', $return_me); return $return_me; } catch (Exception $e) { try { require_once (dirname(__FILE__) . "/res/fbomatic-readability.php"); $readability = new Readability2($html_string); $readability->debug = false; $readability->convertLinksToFootnotes = false; $result = $readability->init(); if ($result) { $content = $readability->getContent()->innerHTML; $content = str_replace('</article>', '', $content); $content = str_replace('<article>', '', $content); return $content; } else { return ''; } } catch(Exception $e2) { fbomatic_log_to_file('Readability failed: ' . sprintf('Error processing text: %s', $e2->getMessage())); return ''; } } } add_action('admin_enqueue_scripts', 'fbomatic_admin_do_post'); function fbomatic_admin_do_post() { wp_enqueue_script('fbomatic-poster-script', plugins_url('scripts/postnow.js', __FILE__), array('jquery'), false, true); } function fbomatic_meta_box_function($post) { wp_register_style('fbomatic-browser-style', plugins_url('styles/fbomatic-browser.css', __FILE__), false, '1.0.0'); wp_enqueue_style('fbomatic-browser-style'); wp_suspend_cache_addition(true); $index = get_post_meta($post->ID, 'fbomatic_parent_rule', true); $title = get_post_meta($post->ID, 'fbomatic_item_title', true); $cats = get_post_meta($post->ID, 'fbomatic_extra_categories', true); $tags = get_post_meta($post->ID, 'fbomatic_extra_tags', true); $img = get_post_meta($post->ID, 'fbomatic_featured_img', true); $post_img = get_post_meta($post->ID, 'fbomatic_post_img', true); $fbomatic_source_feed = get_post_meta($post->ID, 'fbomatic_source_feed', true); $fbomatic_timestamp = get_post_meta($post->ID, 'fbomatic_timestamp', true); $fbomatic_post_date = get_post_meta($post->ID, 'fbomatic_post_date', true); $fbomatic_post_url = get_post_meta($post->ID, 'fbomatic_post_url', true); $fbomatic_post_id = get_post_meta($post->ID, 'fbomatic_post_id', true); $fbomatic_group_id = get_post_meta($post->ID, 'fb_group_id', true); $fbomatic_enable_pingbacks = get_post_meta($post->ID, 'fbomatic_enable_pingbacks', true); $fbomatic_comment_status = get_post_meta($post->ID, 'fbomatic_comment_status', true); $fbomatic_author = get_post_meta($post->ID, 'fbomatic_author', true); $fbomatic_author_link = get_post_meta($post->ID, 'fbomatic_author_link', true); $ech = '<div class="bws_help_box bws_help_box_right dashicons dashicons-editor-help cr_align_middle"><div class="bws_hidden_help_text cr_min_260px">' . esc_html__("Post will be submitted respecting the configurations you made in the \'Posts to Facebook\' plugin menu section.", 'fbomatic-facebook-post-generator') . '</div></div> <span id="fbomatic_span">' . esc_html__("Manually submit post now:", 'fbomatic-facebook-post-generator') . ' </span><br/><br/><form id="fbomatic_form"><input class="button button-primary button-large" type="button" name="fbomatic_submit_post" id="fbomatic_submit_post" value="' . esc_html__('Post To Facebook Now!', 'fbomatic-facebook-post-generator') . '" onclick="fbomatic_post_now(' . $post->ID . ');"/></form><br/><hr/>'; if (isset($index) && $index != '') { if($fbomatic_group_id != '' && $fbomatic_post_id != '') { $ech .= '<div class="bws_help_box bws_help_box_right dashicons dashicons-editor-help cr_align_middle"><div class="bws_hidden_help_text cr_min_260px">' . esc_html__("Comments will be imported from the original Facebook post and added to this post automatically.", 'fbomatic-facebook-post-generator') . '</div></div> <span id="fbomatic_comm_span">Manually import comments now: </span><br/><br/><form id="fbomatic_form">Append comments to post content instead of creating post comments (please refresh the page after importing): <input type="checkbox" id="fbomatic_comment_content"/><br/><input type="number" min="1" step="1" id="fbomatic_comment_num" value="1" class="crf_100"/> <input class="button button-primary button-large" type="button" name="fbomatic_submit_comment" id="fbomatic_submit_comment" value="Import Comments Now!" onclick="fbomatic_comments_now(' . $post->ID . ',' . $fbomatic_group_id . ',' . $fbomatic_post_id .');"/></form><br/><hr/>'; } $ech .= '<table class="crf_table"><tr><td><b>' . esc_html__('Post Parent Rule:', 'fbomatic-facebook-post-generator') . '</b></td><td> ' . esc_html($index) . '</td></tr>'; $ech .= '<tr><td><b>' . esc_html__('Post Original Title:', 'fbomatic-facebook-post-generator') . '</b></td><td> ' . esc_html($title) . '</td></tr>'; if ($fbomatic_author != '') { $ech .= '<tr><td><b>' . esc_html__('Parent Feed Author:', 'fbomatic-facebook-post-generator') . '</b></td><td> ' . esc_html($fbomatic_author) . '</td></tr>'; } if ($fbomatic_author_link != '') { $ech .= '<tr><td><b>' . esc_html__('Parent Feed Author URL:', 'fbomatic-facebook-post-generator') . '</b></td><td> ' . esc_url_raw($fbomatic_author_link) . '</td></tr>'; } if ($fbomatic_timestamp != '') { $ech .= '<tr><td><b>' . esc_html__('Post Creation Date:', 'fbomatic-facebook-post-generator') . '</b></td><td> ' . esc_html($fbomatic_timestamp) . '</td></tr>'; } if ($cats != '') { $ech .= '<tr><td><b>' . esc_html__('Post Categories:', 'fbomatic-facebook-post-generator') . '</b></td><td> ' . esc_html($cats) . '</td></tr>'; } if ($tags != '') { $ech .= '<tr><td><b>' . esc_html__('Post Tags:', 'fbomatic-facebook-post-generator') . '</b></td><td> ' . esc_html($tags) . '</td></tr>'; } if ($img != '') { $ech .= '<tr><td><b>' . esc_html__('Featured Image:', 'fbomatic-facebook-post-generator') . '</b></td><td> ' . esc_url_raw($img) . '</td></tr>'; } if ($post_img != '') { $ech .= '<tr><td><b>' . esc_html__('Post Image:', 'fbomatic-facebook-post-generator') . '</b></td><td> ' . esc_url_raw($post_img) . '</td></tr>'; } if ($fbomatic_source_feed != '') { $ech .= '<tr><td><b>Source Feed:</b></td><td> ' . esc_url_raw($fbomatic_source_feed) . '</td></tr>'; } if ($fbomatic_post_date != '') { $ech .= '<tr><td><b>' . esc_html__('Item Source URL Date:', 'fbomatic-facebook-post-generator') . '</b></td><td> ' . esc_html($fbomatic_post_date) . '</td></tr>'; } if ($fbomatic_post_url != '') { $ech .= '<tr><td><b>' . esc_html__('Item Source URL:', 'fbomatic-facebook-post-generator') . '</b></td><td> ' . esc_url_raw($fbomatic_post_url) . '</td></tr>'; } if ($fbomatic_post_id != '') { $ech .= '<tr><td><b>' . esc_html__('Item Source Post ID:', 'fbomatic-facebook-post-generator') . '</b></td><td> ' . esc_html($fbomatic_post_id) . '</td></tr>'; } if ($fbomatic_enable_pingbacks != '') { $ech .= '<tr><td><b>' . esc_html__('Pingback/Trackback Status:', 'fbomatic-facebook-post-generator') . '</b></td><td> ' . esc_html($fbomatic_enable_pingbacks) . '</td></tr>'; } if ($fbomatic_comment_status != '') { $ech .= '<tr><td><b>' . esc_html__('Comment Status:', 'fbomatic-facebook-post-generator') . '</b></td><td> ' . esc_html($fbomatic_comment_status) . '</td></tr>'; } $ech .= '</table><br/>'; } else { $ech .= esc_html__('This is not an automatically generated post.', 'fbomatic-facebook-post-generator'); } echo $ech; wp_suspend_cache_addition(false); } foreach( [ 'post', 'page', 'post_type' ] as $type ) { add_filter($type . '_link','fbomatic_permalink_changer', 10, 2 ); } add_filter('the_permalink','fbomatic_permalink_changer', 10, 2 ); function fbomatic_permalink_changer($link, $postid = ''){ $le_post_id = ''; if(is_numeric($postid)) { $le_post_id = $postid; } elseif(is_object($postid) && isset($postid->ID)) { $le_post_id = $postid->ID; } else { global $post; if(isset($post->ID)) { $le_post_id = $post->ID; } } if (!empty($le_post_id)) { $url = get_post_meta($le_post_id, 'fbomatic_change_title_link', true); $new_url = get_post_meta($le_post_id, 'fbomatic_post_url', true); if ( trim($url) == '1' && trim($new_url) != '') { return $new_url; } } return $link; } function fbomatic_addPostMeta($post_id, $post, $param, $featured_img, $title_url = 0) { add_post_meta($post_id, 'fbomatic_parent_rule', $param); add_post_meta($post_id, 'fbomatic_enable_pingbacks', $post['fbomatic_enable_pingbacks']); add_post_meta($post_id, 'fbomatic_comment_status', $post['comment_status']); add_post_meta($post_id, 'fbomatic_item_title', wp_slash($post['original_title'])); add_post_meta($post_id, 'fbomatic_extra_categories', wp_slash($post['extra_categories'])); add_post_meta($post_id, 'fbomatic_extra_tags', wp_slash($post['extra_tags'])); add_post_meta($post_id, 'fbomatic_post_img', wp_slash($post['fbomatic_post_image'])); add_post_meta($post_id, 'fbomatic_featured_img', wp_slash($featured_img)); add_post_meta($post_id, 'fbomatic_source_feed', wp_slash($post['fbomatic_source_feed'])); add_post_meta($post_id, 'fbomatic_timestamp', $post['fbomatic_timestamp']); add_post_meta($post_id, 'fbomatic_post_url', wp_slash($post['fbomatic_post_url'])); add_post_meta($post_id, 'fbomatic_post_id', $post['fbomatic_post_id']); add_post_meta($post_id, 'fb_group_id', $post['fb_group_id']); add_post_meta($post_id, 'fbomatic_post_date', $post['fbomatic_post_date']); add_post_meta($post_id, 'fbomatic_author', wp_slash($post['author'])); add_post_meta($post_id, 'fbomatic_author_link', wp_slash($post['author_link'])); if($title_url == '1') { add_post_meta($post_id, 'fbomatic_change_title_link', '1'); } } add_action('wp_head', 'fbomatic_add_og_tags'); function fbomatic_fetch_locale($match = '') { if (empty($match)) $match = get_locale(); $match_len = strlen($match); $valid_locales = (array) fbomatic_fb_locales(); $default = 'en_US'; if ($match_len > 5) { $match = substr($match, 0, 5); $match_len = 5; } if (5 === $match_len) { if (in_array($match, $valid_locales)) return $match; $match = substr($match, 0, 2); $match_len = 2; } if (2 === $match_len) { $locale_keys = (array) fbomatic_language_keys(); if ($key = array_search($match, $locale_keys)) { return $valid_locales[$key]; } } return $default; } function fbomatic_add_og_tags() { $fbomatic_Main_Settings = get_option('fbomatic_Main_Settings', false); if (isset($fbomatic_Main_Settings['page_ids']) && $fbomatic_Main_Settings['page_ids'] != '') { $pageids = explode(',', $fbomatic_Main_Settings['page_ids']); foreach($pageids as $pid) { ?> <meta property="fb:pages" content="<?php echo trim($pid); ?>" /> <?php } } if (isset($fbomatic_Main_Settings['fbomatic_enabled']) && $fbomatic_Main_Settings['fbomatic_enabled'] == 'on') { if (isset($fbomatic_Main_Settings['enable_og']) && $fbomatic_Main_Settings['enable_og'] == 'on') { ?> <meta property="og:title" content="<?php echo the_title(); ?>" /> <meta property="og:site_name" content="<?php bloginfo('name'); ?>" /> <meta property="og:url" content="<?php the_permalink(); ?>" /> <meta property="og:description" content="<?php bloginfo('description'); ?>" /> <meta property="og:locale" content="<?php echo fbomatic_fetch_locale(''); ?>" /> <meta property="og:type" content="website"/> <meta property="og:updated_time" content="<?php the_modified_date(); ?>" /> <?php if (isset($fbomatic_Main_Settings['app_id_og']) && $fbomatic_Main_Settings['app_id_og'] != '') { $app_id_og = $fbomatic_Main_Settings['app_id_og']; ?> <meta property="fb:app_id" content="<?php echo esc_html($app_id_og);?>"/> <?php } if (isset($fbomatic_Main_Settings['default_image_og']) && $fbomatic_Main_Settings['default_image_og'] != '') { $default_img = $fbomatic_Main_Settings['default_image_og']; } else { $default_img = ''; } if (is_single()) { $image = fbomatic_get_open_graph_post_image($default_img); if ($image != '') { ?> <meta property="og:image" content="<?php echo esc_url_raw($image); ?>"/> <?php $fb_width = ''; $fb_height = ''; $fb_type = ''; $fb_attr = ''; try { list( $fb_width, $fb_height, $fb_type, $fb_attr ) = fbomatic_get_open_graph_image_size($image); } catch(Exception $e) { fbomatic_log_to_file('Exception occurred while trying to get featured image size: ' . $e->getMessage()); } if(is_numeric($fb_width)) { ?> <meta property="og:image:width" content="<?php echo intval(esc_attr($fb_width));?>"/> <?php } if(is_numeric($fb_height)) { ?> <meta property="og:image:height" content="<?php echo intval(esc_attr($fb_height));?>"/> <?php } } } else { if($default_img != '') { ?> <meta property="og:image" content="<?php echo esc_url_raw($default_img); ?>"/> <?php $fb_width = ''; $fb_height = ''; $fb_type = ''; $fb_attr = ''; try { list( $fb_width, $fb_height, $fb_type, $fb_attr ) = fbomatic_get_open_graph_image_size($default_img); } catch(Exception $e) { fbomatic_log_to_file('Exception occurred while trying to get featured image size: ' . $e->getMessage()); } if(is_numeric($fb_width)) { ?> <meta property="og:image:width" content="<?php echo intval(esc_attr($fb_width));?>"/> <?php } if(is_numeric($fb_height)) { ?> <meta property="og:image:height" content="<?php echo intval(esc_attr($fb_height));?>"/> <?php } } } } } } function fbomatic_get_open_graph_image_size_curl( $image, $headers ) { $curl = curl_init($image); $fbomatic_Main_Settings = get_option('fbomatic_Main_Settings', false); if ( is_array($headers) ) curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); if (isset($fbomatic_Main_Settings['proxy_url']) && $fbomatic_Main_Settings['proxy_url'] != '') { curl_setopt($curl, CURLOPT_PROXY, $fbomatic_Main_Settings['proxy_url']); if (isset($fbomatic_Main_Settings['proxy_auth']) && $fbomatic_Main_Settings['proxy_auth'] != '') { curl_setopt($curl, CURLOPT_PROXYUSERPWD, $fbomatic_Main_Settings['proxy_auth']); } } curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_REFERER, ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ) ? 'https://' : 'http://' ).$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']); curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10); curl_setopt($curl, CURLOPT_TIMEOUT, 10); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); $data = curl_exec($curl); curl_close($curl); return $data; } function fbomatic_get_open_graph_image_size( $image ) { $transient_key = 'fbomatic_og_image_size_' . md5($image); $transient_val = get_transient($transient_key); if ($transient_val) { return $transient_val; } if(substr( $image, 0, 4 ) != "http") { $image = site_url() . $image; } if(!fbomatic_url_exists($image)) { return false; } error_reporting(0); $img_size = getimagesize($image); error_reporting(E_ALL); if ($img_size) { set_transient($transient_key, $img_size, DAY_IN_SECONDS); return $img_size; } if ( stristr($image, 'http://' ) || stristr($image, 'https://' ) || mb_substr($image, 0, 2)=='//' ) { if ( function_exists('curl_version' ) && function_exists('imagecreatefromstring' ) ) { error_reporting(0); $headers = array( "Range: bytes=0-32768" ); $data = fbomatic_get_open_graph_image_size_curl($image, $headers); if ( $data ) { $done_partial = false; $tried_full = false; try { $im = imagecreatefromstring($data); if ($im) $done_partial = true; } catch(Exception $e) { $tried_full = true; $data = fbomatic_get_open_graph_image_size_curl($image, null); if ( $data ) { $im = imagecreatefromstring($data); } } if ( !$done_partial && !$tried_full ) { $data = fbomatic_get_open_graph_image_size_curl($image, null); if ( $data ) { $im = imagecreatefromstring($data); } } if ( $im ) { if ( $x=imagesx($im) ) { $ext = pathinfo($image, PATHINFO_EXTENSION); switch(strtolower($ext)) { case 'gif': $type=1; break; case 'jpg': case 'jpeg': $type=2; break; case 'png': $type=3; break; default: $type=2; break; } $img_size = array($x, imagesy($im), $type, '' ); } else { $img_size = false; } } else { $img_size = false; } } else { $img_size = false; } error_reporting(E_ALL); } else { if ( intval(ini_get('allow_url_fopen' ))==1 ) { error_reporting(0); $img_size = getimagesize($image); error_reporting(E_ALL); } else { $img_size = false; } } } else { error_reporting(0); $img_size = getimagesize($image); error_reporting(E_ALL); } if ($img_size) { set_transient($transient_key, $img_size, DAY_IN_SECONDS); } return $img_size; } function fbomatic_get_open_graph_post_image($default_image = '') { $post = get_post(); $thumbdone = false; $fb_image = ''; wp_suspend_cache_addition(true); $metas = get_post_custom($post->ID); wp_suspend_cache_addition(false); if(is_array($metas)) { $rez_meta = fbomatic_preg_grep_keys('#.+?_featured_ima?ge?#i', $metas); } else { $rez_meta = array(); } if(count($rez_meta) > 0) { foreach($rez_meta as $rm) { if(isset($rm[0]) && filter_var($rm[0], FILTER_VALIDATE_URL)) { $fb_image = $rm[0]; $thumbdone = true; break; } } } if (!$thumbdone) { $fb_image = get_post_meta($post->ID, 'fbomatic_featured_img', true); if($fb_image != '') { $thumbdone = true; } } if (!$thumbdone) { if (is_attachment()) { if ($temp = wp_get_attachment_image_src(null, 'full')) { $fb_image = trim($temp[0]); if (trim($fb_image) != '') { $thumbdone = true; } } } } if (!$thumbdone) { if (function_exists('get_post_thumbnail_id')) { if ($id_attachment = get_post_thumbnail_id($post->ID)) { $fb_image = wp_get_attachment_url($id_attachment, false); $thumbdone = true; } } } if (!$thumbdone) { $imgreg = '/<img .*src=["\']([^ ^"^\']*)["\']/'; preg_match_all($imgreg, trim($post->post_content), $matches); if ($matches[1]) { $imagetemp = false; foreach ($matches[1] as $image) { $pos = strpos($image, site_url()); if ($pos === false) { if (stristr($image, 'http://') || stristr($image, 'https://') || substr($image, 0, 2) == '//') { if (substr($image, 0, 2) == '//') $image = ((fbomatic_isSecure()) ? 'https:' : 'http:') . $image; $imagetemp = $image; } else { $imagetemp = site_url() . $image; } } else { $imagetemp = $image; } if ($imagetemp) { $fb_image = $imagetemp; $thumbdone = true; break; } } } } if (!$thumbdone) { $images = get_posts(array( 'post_type' => 'attachment', 'numberposts' => 100, 'post_status' => null, 'order' => 'ASC', 'orderby' => 'menu_order', 'post_mime_type' => 'image', 'post_parent' => $post->ID, 'fields' => 'ids' )); if ($images) { foreach ($images as $image) { $imagetemp = wp_get_attachment_url($image, false); $fb_image = $imagetemp; $thumbdone = true; break; } } } if (!$thumbdone) { $fb_image = $default_image; } if($fb_image != '') { if(substr( $fb_image, 0, 4 ) != "http") { $fb_image = site_url() . $fb_image; } } return $fb_image; } function fbomatic_isSecure() { return (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || $_SERVER['SERVER_PORT'] == 443; } function fbomatic_preg_grep_keys( $pattern, $input, $flags = 0 ) { if(!is_array($input)) { return array(); } $keys = preg_grep( $pattern, array_keys( $input ), $flags ); $vals = array(); foreach ( $keys as $key ) { $vals[$key] = $input[$key]; } return $vals; } function fbomatic_replace_attachment_url($att_url, $att_id) { { $post_id = get_the_ID(); wp_suspend_cache_addition(true); $metas = get_post_custom($post_id); wp_suspend_cache_addition(false); $rez_meta = fbomatic_preg_grep_keys('#.+?_featured_img#i', $metas); if(count($rez_meta) > 0) { foreach($rez_meta as $rm) { if(isset($rm[0]) && $rm[0] != '' && filter_var($rm[0], FILTER_VALIDATE_URL)) { return $rm[0]; } } } } return $att_url; } function fbomatic_replace_attachment_image_src($image, $att_id, $size) { { $post_id = get_the_ID(); wp_suspend_cache_addition(true); $metas = get_post_custom($post_id); wp_suspend_cache_addition(false); $rez_meta = fbomatic_preg_grep_keys('#.+?_featured_img#i', $metas); if(count($rez_meta) > 0) { foreach($rez_meta as $rm) { if(isset($rm[0]) && $rm[0] != '' && filter_var($rm[0], FILTER_VALIDATE_URL)) { return array($rm[0], 0, 0, false); } } } } return $image; } function fbomatic_thumbnail_external_replace( $html, $post_id, $thumb_id ) { wp_suspend_cache_addition(true); $metas = get_post_custom($post_id); wp_suspend_cache_addition(false); $rez_meta = fbomatic_preg_grep_keys('#.+?_featured_img#i', $metas); if(count($rez_meta) > 0) { foreach($rez_meta as $rm) { if(isset($rm[0]) && $rm[0] != '' && filter_var($rm[0], FILTER_VALIDATE_URL)) { $alt = get_post_field( 'post_title', $post_id ) . ' ' . esc_html__( 'thumbnail', 'fbomatic-facebook-post-generator' ); $attr = array( 'alt' => $alt ); $attx = get_post($thumb_id); $attr = apply_filters( 'wp_get_attachment_image_attributes', $attr, $attx , 'thumbnail'); $attr = array_map( 'esc_attr', $attr ); $html = sprintf( '<img src="%s"', esc_url_raw($rm[0]) ); foreach ( $attr as $name => $value ) { $html .= " " . esc_html($name) . "=" . '"' . esc_attr($value) . '"'; } $html .= ' />'; return $html; } } } return $html; } function fbomatic_url_is_image( $url ) { $url = str_replace(' ', '%20', $url); if ( ! filter_var( $url, FILTER_VALIDATE_URL ) ) { return FALSE; } $ext = array( 'jpeg', 'jpg', 'gif', 'png', 'jpe', 'tif', 'tiff', 'svg', 'ico' , 'webp', 'dds', 'heic', 'psd', 'pspimage', 'tga', 'thm', 'yuv', 'ai', 'eps', 'php'); $info = (array) pathinfo( parse_url( $url, PHP_URL_PATH ) ); if(!isset( $info['extension'] )) { return true; } return isset( $info['extension'] ) && in_array( strtolower( $info['extension'] ), $ext, TRUE ); } function fbomatic_sanitize_ffile_name( $filename ) { $sanitized_filename = remove_accents( $filename ); $invalid = array( ' ' => '-', '%20' => '-', '_' => '-', ); $sanitized_filename = str_replace( array_keys( $invalid ), array_values( $invalid ), $sanitized_filename ); $sanitized_filename = preg_replace('/[^A-Za-z0-9-\. ]/', '', $sanitized_filename); $sanitized_filename = preg_replace('/\.(?=.*\.)/', '', $sanitized_filename); $sanitized_filename = preg_replace('/-+/', '-', $sanitized_filename); $sanitized_filename = str_replace('-.', '.', $sanitized_filename); $sanitized_filename = strtolower( $sanitized_filename ); if($sanitized_filename == '') { $sanitized_filename = uniqid(); } return $sanitized_filename; } function fbomatic_generate_featured_image($image_url, $post_id) { global $wp_filesystem; if ( ! is_a( $wp_filesystem, 'WP_Filesystem_Base') ){ include_once(ABSPATH . 'wp-admin/includes/file.php');$creds = request_filesystem_credentials( site_url() ); wp_filesystem($creds); } $fbomatic_Main_Settings = get_option('fbomatic_Main_Settings', false); $upload_dir = wp_upload_dir(); if (isset($fbomatic_Main_Settings['no_local_image']) && $fbomatic_Main_Settings['no_local_image'] == 'on') { if(!fbomatic_url_is_image($image_url)) { return false; } $file = $upload_dir['basedir'] . '/default_img_rss_echo.jpg'; if(!$wp_filesystem->exists($file)) { $image_data = fbomatic_get_web_page(html_entity_decode(dirname(__FILE__) . "/images/icon.png")); if ($image_data === FALSE || strpos($image_data, '<Message>Access Denied</Message>') !== FALSE || strpos($image_data, '<title>Just a moment...</title>') !== FALSE || strpos($image_data, '<html') !== FALSE || strpos($image_data, 'ERROR: The requested URL could not be retrieved') !== FALSE) { return false; } $ret = $wp_filesystem->put_contents($file, $image_data); if ($ret === FALSE) { return false; } } $need_attach = false; $checking_id = get_option('fbomatic_attach_id', false); if($checking_id === false) { $need_attach = true; } else { $atturl = wp_get_attachment_url($checking_id); if($atturl === false) { $need_attach = true; } } if($need_attach) { $filename = basename(dirname(__FILE__) . "/images/icon.png"); $wp_filetype = wp_check_filetype($filename, null); if($wp_filetype['type'] == '') { $wp_filetype['type'] = 'image/png'; } $attachment = array( 'post_mime_type' => $wp_filetype['type'], 'post_title' => sanitize_file_name($filename), 'post_content' => '', 'post_status' => 'inherit' ); $attach_id = wp_insert_attachment($attachment, $file, $post_id); if ($attach_id === 0) { return false; } update_option('fbomatic_attach_id', $attach_id); require_once(ABSPATH . 'wp-admin/includes/image.php'); require_once(ABSPATH . 'wp-admin/includes/media.php'); $attach_data = wp_generate_attachment_metadata($attach_id, $file); wp_update_attachment_metadata($attach_id, $attach_data); } else { $attach_id = $checking_id; } $res2 = set_post_thumbnail($post_id, $attach_id); if ($res2 === FALSE) { return false; } return true; } if ( ! is_a( $wp_filesystem, 'WP_Filesystem_Base') ){ include_once(ABSPATH . 'wp-admin/includes/file.php');$creds = request_filesystem_credentials( site_url() ); wp_filesystem($creds); } $image_data = $wp_filesystem->get_contents($image_url); if ($image_data === FALSE || empty($image_data)) { $image_data = fbomatic_get_web_page($image_url); if ($image_data === FALSE || strpos($image_data, '<Message>Access Denied</Message>') !== FALSE || strpos($image_data, '<title>Just a moment...</title>') !== FALSE || strpos($image_data, '<html') !== FALSE || strpos($image_data, 'We cannot complete this request') !== FALSE) { return false; } } $filename = basename($image_url); $temp = explode("?", $filename); $filename = $temp[0]; $filename = str_replace('%', '-', $filename); $filename = str_replace('#', '-', $filename); $filename = str_replace('&', '-', $filename); $filename = str_replace('{', '-', $filename); $filename = str_replace('}', '-', $filename); $filename = str_replace('\\', '-', $filename); $filename = str_replace('<', '-', $filename); $filename = str_replace('>', '-', $filename); $filename = str_replace('*', '-', $filename); $filename = str_replace('/', '-', $filename); $filename = str_replace('$', '-', $filename); $filename = str_replace('\'', '-', $filename); $filename = str_replace('"', '-', $filename); $filename = str_replace(':', '-', $filename); $filename = str_replace('@', '-', $filename); $filename = str_replace('+', '-', $filename); $filename = str_replace('|', '-', $filename); $filename = str_replace('=', '-', $filename); $filename = str_replace('`', '-', $filename); $filename = stripslashes(preg_replace_callback('#(%[a-zA-Z0-9_]*)#', function($matches){ return rand(0, 9); }, preg_quote($filename))); $file_parts = pathinfo($filename); $post_title = get_the_title($post_id); if($post_title != '') { if(isset($file_parts['extension'])) { switch($file_parts['extension']) { case "": $filename = fbomatic_sanitize_ffile_name($post_title) . '.jpg'; break; case NULL: $filename = fbomatic_sanitize_ffile_name($post_title) . '.jpg'; break; default: $filename = fbomatic_sanitize_ffile_name($post_title) . '.' . $file_parts['extension']; break; } } else { $filename = fbomatic_sanitize_ffile_name($post_title) . '.jpg'; } } else { if(isset($file_parts['extension'])) { switch($file_parts['extension']) { case "": if(!fbomatic_endsWith($filename, '.jpg')) $filename .= '.jpg'; break; case NULL: if(!fbomatic_endsWith($filename, '.jpg')) $filename .= '.jpg'; break; default: if(!fbomatic_endsWith($filename, '.' . $file_parts['extension'])) $filename .= '.' . $file_parts['extension']; break; } } else { if(!fbomatic_endsWith($filename, '.jpg')) $filename .= '.jpg'; } } $filename = sanitize_file_name($filename); if (wp_mkdir_p($upload_dir['path'])) $file = $upload_dir['path'] . '/' . $post_id . '-' . $filename; else $file = $upload_dir['basedir'] . '/' . $post_id . '-' . $filename; $validate = wp_check_filetype_and_ext($file, $filename); if (empty($validate['type']) || !in_array($validate['ext'], ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'tif', 'tiff', 'avif', 'heic', 'heif', 'ico'])) { return false; } if ( ! is_a( $wp_filesystem, 'WP_Filesystem_Base') ){ include_once(ABSPATH . 'wp-admin/includes/file.php');$creds = request_filesystem_credentials( site_url() ); wp_filesystem($creds); } $ret = $wp_filesystem->put_contents($file, $image_data); if ($ret === FALSE) { return false; } $wp_filetype = wp_check_filetype($filename, null); if($wp_filetype['type'] == '') { $wp_filetype['type'] = 'image/png'; } $attachment = array( 'post_mime_type' => $wp_filetype['type'], 'post_title' => sanitize_file_name($filename), 'post_content' => '', 'post_status' => 'inherit' ); if ((isset($fbomatic_Main_Settings['resize_height']) && $fbomatic_Main_Settings['resize_height'] !== '') || (isset($fbomatic_Main_Settings['resize_width']) && $fbomatic_Main_Settings['resize_width'] !== '')) { try { if(!class_exists('\Eventviva\ImageResize')){require_once (dirname(__FILE__) . "/res/ImageResize/ImageResize.php");} $imageRes = new ImageResize($file); $imageRes->quality_jpg = 100; if ((isset($fbomatic_Main_Settings['resize_height']) && $fbomatic_Main_Settings['resize_height'] !== '') && (isset($fbomatic_Main_Settings['resize_width']) && $fbomatic_Main_Settings['resize_width'] !== '')) { $imageRes->resizeToBestFit($fbomatic_Main_Settings['resize_width'], $fbomatic_Main_Settings['resize_height'], true); } elseif (isset($fbomatic_Main_Settings['resize_width']) && $fbomatic_Main_Settings['resize_width'] !== '') { $imageRes->resizeToWidth($fbomatic_Main_Settings['resize_width'], true); } elseif (isset($fbomatic_Main_Settings['resize_height']) && $fbomatic_Main_Settings['resize_height'] !== '') { $imageRes->resizeToHeight($fbomatic_Main_Settings['resize_height'], true); } $imageRes->save($file); } catch(Exception $e) { fbomatic_log_to_file('Failed to resize featured image: ' . $image_url . ' to sizes ' . $fbomatic_Main_Settings['resize_width'] . ' - ' . $fbomatic_Main_Settings['resize_height'] . '. Exception thrown ' . esc_html($e->getMessage()) . '!'); } } $attach_id = wp_insert_attachment($attachment, $file, $post_id); if ($attach_id === 0) { return false; } require_once(ABSPATH . 'wp-admin/includes/image.php'); require_once(ABSPATH . 'wp-admin/includes/media.php'); $attach_data = wp_generate_attachment_metadata($attach_id, $file); wp_update_attachment_metadata($attach_id, $attach_data); $res2 = set_post_thumbnail($post_id, $attach_id); if ($res2 === FALSE) { return false; } $post_title = get_the_title($post_id); if($post_title != '') { update_post_meta($attach_id, '_wp_attachment_image_alt', $post_title); } return true; } function fbomatic_endsWith($haystack, $needle) { $length = strlen($needle); if ($length == 0) { return true; } return (substr($haystack, -$length) === $needle); } function fbomatic_hour_diff($date1, $date2) { $date1 = new DateTime($date1, fbomatic_get_blog_timezone()); $date2 = new DateTime($date2, fbomatic_get_blog_timezone()); $number1 = (int) $date1->format('U'); $number2 = (int) $date2->format('U'); return ($number1 - $number2) / 60; } function fbomatic_get_blog_timezone() { $tzstring = get_option( 'timezone_string' ); $offset = get_option( 'gmt_offset' ); if( empty( $tzstring ) && 0 != $offset && floor( $offset ) == $offset ){ $offset_st = $offset > 0 ? "-$offset" : '+'.absint( $offset ); $tzstring = 'Etc/GMT'.$offset_st; } if( empty( $tzstring ) ){ $tzstring = 'UTC'; } $timezone = new DateTimeZone( $tzstring ); return $timezone; } function fbomatic_add_minute($date, $minute) { $date1 = new DateTime($date, fbomatic_get_blog_timezone()); $date1->modify("$minute minutes"); $date1 = (array)$date1; foreach ($date1 as $key => $value) { if ($key == 'date') { return $value; } } return $date; } function fbomatic_add_hour($date, $hour) { $date1 = new DateTime($date, fbomatic_get_blog_timezone()); $date1->modify("$hour hours"); $date1 = (array)$date1; foreach ($date1 as $key => $value) { if ($key == 'date') { return $value; } } return $date; } function fbomatic_get_date_now($param = 'now') { $date = new DateTime($param, fbomatic_get_blog_timezone()); $date = (array)$date; foreach ($date as $key => $value) { if ($key == 'date') { return $value; } } return ''; } function fbomatic_create_terms($taxonomy, $parent, $terms_str) { $terms = explode('/', $terms_str); $categories = array(); $parent_term_id = $parent; foreach ($terms as $term) { $res = term_exists($term, $taxonomy, $parent); if ($res != NULL && $res != 0 && count($res) > 0 && isset($res['term_id'])) { $parent_term_id = $res['term_id']; $categories[] = $parent_term_id; } else { if($parent === null) { $insert_parent = 0; } else { $insert_parent = $parent; } $new_term = wp_insert_term($term, $taxonomy, array( 'parent' => $insert_parent )); if (!is_wp_error( $new_term ) && $new_term != NULL && $new_term != 0 && count($new_term) > 0 && isset($new_term['term_id'])) { $parent_term_id = $new_term['term_id']; $categories[] = $parent_term_id; } } } return $categories; } function fbomatic_getExcerpt($the_content) { $preview = fbomatic_strip_html_tags($the_content); $preview = wp_trim_words($preview, 55, ''); $preview = trim($preview, ','); return $preview; } function fbomatic_getPlainContent($the_content) { $preview = fbomatic_strip_html_tags($the_content); $preview = wp_trim_words($preview, 999999); return $preview; } function fbomatic_getItemImage($img) { if($img == '') { return ''; } $preview = '<img src="' . esc_url_raw($img) . '" alt="image" />'; return $preview; } function fbomatic_getReadMoreButton($url) { $link = ''; if (isset($url)) { $link = '<a href="' . $url . '" class="button purchase" target="_blank">' . esc_html__('Read More', 'fbomatic-facebook-post-generator') . '</a>'; } return $link; } add_action('init', 'fbomatic_create_taxonomy', 0); add_action( 'enqueue_block_editor_assets', 'fbomatic_enqueue_block_editor_assets' ); function fbomatic_enqueue_block_editor_assets() { wp_register_style('fbomatic-browser-style', plugins_url('styles/fbomatic-browser.css', __FILE__), false, '1.0.0'); wp_enqueue_style('fbomatic-browser-style'); $block_js_display = 'scripts/display-posts.js'; wp_enqueue_script( 'fbomatic-display-block-js', plugins_url( $block_js_display, __FILE__ ), array( 'wp-blocks', 'wp-i18n', 'wp-element', ), '1.0.0' ); $block_js_list = 'scripts/list-posts.js'; wp_enqueue_script( 'fbomatic-list-block-js', plugins_url( $block_js_list, __FILE__ ), array( 'wp-blocks', 'wp-i18n', 'wp-element', ), '1.0.0' ); $block_js_list = 'scripts/video-block.js'; wp_enqueue_script( 'fbomatic-video-block-js', plugins_url( $block_js_list, __FILE__ ), array( 'wp-blocks', 'wp-i18n', 'wp-element', ), '1.0.0' ); $block_js_list = 'scripts/sidebar.js'; wp_enqueue_script( 'fbomatic-sidebar-js', plugins_url( $block_js_list, __FILE__ ), array( 'wp-plugins', 'wp-edit-post', 'wp-element', 'wp-data' ), '1.0.0' ); } function fbomatic_create_taxonomy() { $fbomatic_Main_Settings = get_option('fbomatic_Main_Settings', false); if (isset($fbomatic_Main_Settings['fbomatic_enabled']) && $fbomatic_Main_Settings['fbomatic_enabled'] === 'on') { if (isset($fbomatic_Main_Settings['no_local_image']) && $fbomatic_Main_Settings['no_local_image'] == 'on') { add_filter('wp_get_attachment_url', 'fbomatic_replace_attachment_url', 10, 2); add_filter('wp_get_attachment_image_src', 'fbomatic_replace_attachment_image_src', 10, 3); add_filter('post_thumbnail_html', 'fbomatic_thumbnail_external_replace', 10, 6); } } if ( function_exists( 'register_block_type' ) ) { register_block_type( 'fbomatic-facebook-post-generator/fbomatic-display', array( 'render_callback' => 'fbomatic_display_posts_shortcode', ) ); register_block_type( 'fbomatic-facebook-post-generator/fbomatic-list', array( 'render_callback' => 'fbomatic_list_posts', ) ); register_block_type( 'fbomatic-facebook-post-generator/fbomatic-video', array( 'render_callback' => 'fbomatic_embed_facebook_video', ) ); } if(!taxonomy_exists('coderevolution_post_source')) { $labels = array( 'name' => _x('Post Source', 'taxonomy general name', 'fbomatic-facebook-post-generator'), 'singular_name' => _x('Post Source', 'taxonomy singular name', 'fbomatic-facebook-post-generator'), 'search_items' => esc_html__('Search Post Source', 'fbomatic-facebook-post-generator'), 'popular_items' => esc_html__('Popular Post Source', 'fbomatic-facebook-post-generator'), 'all_items' => esc_html__('All Post Sources', 'fbomatic-facebook-post-generator'), 'parent_item' => null, 'parent_item_colon' => null, 'edit_item' => esc_html__('Edit Post Source', 'fbomatic-facebook-post-generator'), 'update_item' => esc_html__('Update Post Source', 'fbomatic-facebook-post-generator'), 'add_new_item' => esc_html__('Add New Post Source', 'fbomatic-facebook-post-generator'), 'new_item_name' => esc_html__('New Post Source Name', 'fbomatic-facebook-post-generator'), 'separate_items_with_commas' => esc_html__('Separate Post Source with commas', 'fbomatic-facebook-post-generator'), 'add_or_remove_items' => esc_html__('Add or remove Post Source', 'fbomatic-facebook-post-generator'), 'choose_from_most_used' => esc_html__('Choose from the most used Post Source', 'fbomatic-facebook-post-generator'), 'not_found' => esc_html__('No Post Sources found.', 'fbomatic-facebook-post-generator'), 'menu_name' => esc_html__('Post Source', 'fbomatic-facebook-post-generator') ); $args = array( 'hierarchical' => false, 'public' => false, 'show_ui' => false, 'show_in_menu' => false, 'description' => 'Post Source', 'labels' => $labels, 'show_admin_column' => true, 'update_count_callback' => '_update_post_term_count', 'rewrite' => false ); $add_post_type = array( 'post', 'page' ); $xargs = array( 'public' => true, '_builtin' => false ); $output = 'names'; $operator = 'and'; $post_types = get_post_types( $xargs, $output, $operator ); if ( $post_types ) { foreach ( $post_types as $post_type ) { $add_post_type[] = $post_type; } } register_taxonomy('coderevolution_post_source', $add_post_type, $args); add_action('pre_get_posts', function($qry) { if (is_admin()) return; if (is_tax('coderevolution_post_source')){ $qry->set_404(); } }); } } function fbomatic_to_facebook_url_handle($href) { $fbomatic_Main_Settings = get_option('fbomatic_Main_Settings', false); if (isset($fbomatic_Main_Settings['links_hide_google2']) && $fbomatic_Main_Settings['links_hide_google2'] == 'on') { $cloak_urls = true; } else { $cloak_urls = false; } if (isset($fbomatic_Main_Settings['gapiKey'])) { $apiKey = trim($fbomatic_Main_Settings['gapiKey']); } else { $apiKey = ''; } if ($cloak_urls == true && $apiKey != '') { $fbomatic_short_group = get_option('fbomatic_short_group', false); $found = false; if($fbomatic_short_group !== false) { $fbomatic_short_group = explode('#', $fbomatic_short_group); if(isset($fbomatic_short_group[1]) && $fbomatic_short_group[0] == $apiKey) { $fbomatic_short_group = $fbomatic_short_group[1]; $found = true; } } if($found == false) { $url = 'https://api-ssl.Bitly.com/v4/groups'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); $headers = [ 'Authorization: Bearer ' . $apiKey, 'Accept: application/json', 'Host: api-ssl.Bitly.com' ]; curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); curl_setopt($ch, CURLOPT_TIMEOUT, 60); $serverOutput = json_decode(curl_exec($ch), true); curl_close($ch); if(isset($serverOutput['groups'][0]['guid'])) { $fbomatic_short_group = $serverOutput['groups'][0]['guid']; update_option('fbomatic_short_group', false); $found = true; } } if($found == false) { return $href; } $url = 'https://api-ssl.Bitly.com/v4/shorten'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); curl_setopt($ch, CURLOPT_TIMEOUT, 60); $headers = [ 'Authorization: Bearer ' . $apiKey, 'Content-Type: application/json', 'Host: api-ssl.Bitly.com' ]; curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); $fdata = ""; $data['long_url'] = trim($href); $data['group_guid'] = $fbomatic_short_group; $fdata = json_encode($data); curl_setopt($ch, CURLOPT_POSTFIELDS, $fdata); $serverOutput = json_decode(curl_exec($ch), true); curl_close($ch); if (!isset($serverOutput['link']) || $serverOutput['link'] == '') { return $href; } else { return esc_url_raw($serverOutput['link']); } } else { return $href; } } function fbomatic_url_handle($href) { $fbomatic_Main_Settings = get_option('fbomatic_Main_Settings', false); if (isset($fbomatic_Main_Settings['links_hide']) && $fbomatic_Main_Settings['links_hide'] == 'on') { $cloak_urls = true; } else { $cloak_urls = false; } if (isset($fbomatic_Main_Settings['apiKey'])) { $apiKey = $fbomatic_Main_Settings['apiKey']; } else { $apiKey = ''; } if ($cloak_urls == true && $apiKey != '') { $longUrl = trim($href); $curlObj = curl_init(); if($curlObj === FALSE) { return $href; } curl_setopt($curlObj, CURLOPT_TIMEOUT_MS, 30000000); curl_setopt($curlObj, CURLOPT_URL, 'https://link.safelinkconverter.com/apishorten.php?user=' . $apiKey . '&type=adsense&url=' . urlencode($href)); curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($curlObj, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($curlObj, CURLOPT_CONNECTTIMEOUT, 10); curl_setopt($curlObj, CURLOPT_TIMEOUT, 10); $response = curl_exec($curlObj); if($response === FALSE) { curl_close($curlObj); return $href; } curl_close($curlObj); return esc_url_raw($response); } if (isset($fbomatic_Main_Settings['links_hide_google']) && $fbomatic_Main_Settings['links_hide_google'] == 'on') { $cloak_urls = true; } else { $cloak_urls = false; } if (isset($fbomatic_Main_Settings['gapiKey'])) { $apiKey = trim($fbomatic_Main_Settings['gapiKey']); } else { $apiKey = ''; } if ($cloak_urls == true && $apiKey != '') { $fbomatic_short_group = get_option('fbomatic_short_group', false); $found = false; if($fbomatic_short_group !== false) { $fbomatic_short_group = explode('#', $fbomatic_short_group); if(isset($fbomatic_short_group[1]) && $fbomatic_short_group[0] == $apiKey) { $fbomatic_short_group = $fbomatic_short_group[1]; $found = true; } } if($found == false) { $url = 'https://api-ssl.Bitly.com/v4/groups'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $headers = [ 'Authorization: Bearer ' . $apiKey, 'Accept: application/json', 'Host: api-ssl.Bitly.com' ]; curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); curl_setopt($ch, CURLOPT_TIMEOUT, 60); $serverOutput = json_decode(curl_exec($ch), true); curl_close($ch); if(isset($serverOutput['groups'][0]['guid'])) { $fbomatic_short_group = $serverOutput['groups'][0]['guid']; update_option('fbomatic_short_group', false); $found = true; } } if($found == false) { return $href; } $url = 'https://api-ssl.Bitly.com/v4/shorten'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $headers = [ 'Authorization: Bearer ' . $apiKey, 'Content-Type: application/json', 'Host: api-ssl.Bitly.com' ]; curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); curl_setopt($ch, CURLOPT_TIMEOUT, 60); $fdata = ""; $data['long_url'] = trim($href); $data['group_guid'] = $fbomatic_short_group; $fdata = json_encode($data); curl_setopt($ch, CURLOPT_POSTFIELDS, $fdata); $serverOutput = json_decode(curl_exec($ch), true); curl_close($ch); if (!isset($serverOutput['link']) || $serverOutput['link'] == '') { return $href; } else { return esc_url_raw($serverOutput['link']); } } else { return $href; } } register_activation_hook(__FILE__, 'fbomatic_activation_callback'); function fbomatic_activation_callback($defaults = FALSE) { if (!get_option('fbomatic_Main_Settings') || $defaults === TRUE) { $fbomatic_Main_Settings = array( 'fbomatic_enabled' => 'on', 'enable_metabox' => 'on', 'app_id' => '', 'app_secret' => '', 'access_token' => '', 'app_id2' => '', 'app_secret2' => '', 'access_token2' => '', 'skip_no_img' => '', 'skip_old' => '', 'skip_year' => '', 'skip_month' => '', 'skip_day' => '', 'translate' => 'disabled', 'translate_source' => 'disabled', 'custom_html2' => '', 'custom_html' => '', 'strip_by_id' => '', 'keyword_tag' => '', 'strip_by_class' => '', 'google_trans_auth' => '', 'sentence_list' => 'This is one %adjective %noun %sentence_ending This is another %adjective %noun %sentence_ending I %love_it %nouns , because they are %adjective %sentence_ending My %family says this plugin is %adjective %sentence_ending These %nouns are %adjective %sentence_ending', 'sentence_list2' => 'Meet this %adjective %noun %sentence_ending This is the %adjective %noun ever %sentence_ending I %love_it %nouns , because they are the %adjective %sentence_ending My %family says this plugin is very %adjective %sentence_ending These %nouns are quite %adjective %sentence_ending', 'variable_list' => 'adjective_very => %adjective;very %adjective; adjective => clever;interesting;smart;huge;astonishing;unbelievable;nice;adorable;beautiful;elegant;fancy;glamorous;magnificent;helpful;awesome noun_with_adjective => %noun;%adjective %noun noun => plugin;WordPress plugin;item;ingredient;component;constituent;module;add-on;plug-in;addon;extension nouns => plugins;WordPress plugins;items;ingredients;components;constituents;modules;add-ons;plug-ins;addons;extensions love_it => love;adore;like;be mad for;be wild about;be nuts about;be crazy about family => %adjective %family_members;%family_members family_members => grandpa;brother;sister;mom;dad;grandma sentence_ending => .;!;!!', 'auto_clear_logs' => 'No', 'enable_logging' => 'on', 'run_after' => '', 'run_before' => '', 'enable_detailed_logging' => '', 'link_source' => '', 'rule_timeout' => '3600', 'date_format' => '', 'default_user' => '', 'strip_links' => '', 'no_hash_link' => '', 'no_img_link' => '', 'max_title_words' => '', 'splitting_char' => '', 'email_address' => '', 'no_link' => '', 'default_types_fb' => '', 'send_email' => '', 'best_password' => '', 'phantom_path' => '', 'phantom_screen' => '', 'puppeteer_screen' => '', 'screenshot_height' => '', 'screenshot_width' => '', 'best_user' => '', 'spin_text' => 'disabled', 'required_words' => '', 'banned_words' => '', 'max_word_content' => '', 'min_word_content' => '', 'max_word_title' => '', 'min_word_title' => '', 'skip_types' => '', 'enable_og' => 'on', 'page_ids' => '', 'fbomatic_pixel' => '', 'resize_width' => '', 'resize_height' => '', 'copy_images' => '', 'no_local_image' => '', 'no_video_img' => '', 'strip_featured_image' => '', 'do_not_check_duplicates' => '', 'app_review_mode' => '', 'api_version' => 'default', 'xs_cookie' => '', 'cuser_cookie' => '', 'disable_scripts' => '', 'limit_max_posts' => 'on', 'no_check' => '', 'apiKey' => '', 'links_hide' => '', 'gapiKey' => '', 'links_hide_google' => '', 'links_hide_google2' => '', 'fix_html' => '', 'no_utf' => '', 'no_duplicate' => '', 'default_image_og' => '', 'app_id_og' => '', 'proxy_auth' => '', 'disable_backend_content' => '', 'proxy_url' => '', 'post_source_custom' => '' ); if ($defaults === FALSE) { add_option('fbomatic_Main_Settings', $fbomatic_Main_Settings); } else { update_option('fbomatic_Main_Settings', $fbomatic_Main_Settings); } } if (!get_option('fbomatic_Facebook_Settings') || $defaults === TRUE) { $fbomatic_Facebook_Settings = array( 'fbomatic_posting' => 'on', 'run_background' => '', 'facebook_format' => '%%post_title%% %%post_link%%', 'create_photo' => '', 'first_url' => '', 'limit_content_word_count' => '', 'only_photo' => '', 'post_posts' => '', 'post_pages' => 'on', 'post_custom' => 'on', 'except_type' => '', 'always_manual' => 'on', 'facebook_pages' => array(), 'facebook_groups' => array(), 'include_blog_name' => 'on', 'include_image' => 'on', 'include_description' => 'on', 'include_title' => 'on', 'include_link' => 'on', 'include_message' => 'on', 'disabled_categories' => array(), 'disable_tags' => '', 'target_country' => '', 'target_region' => '', 'target_city' => '', 'min_age' => 'any', 'group_post_id' => '', 'post_videos' => '', 'only_local' => '', 'only_remote' => '', 'youtube_embedded' => '', 'tiktok_embedded' => '', 'vimeo_embedded' => '', 'dm_embedded' => '', 'fb_embedded' => '', 'tw_embedded' => '', 'only_video' => '', 'delay_post' => '', 'shortcode_percentage' => '', 'shortcode_content' => '', 'max_at_once' => '1', 'max_posts_interval' => '', 'max_posts' => '' ); if ($defaults === FALSE) { add_option('fbomatic_Facebook_Settings', $fbomatic_Facebook_Settings); } else { update_option('fbomatic_Facebook_Settings', $fbomatic_Facebook_Settings); } } } add_action('fbomatic_new_post_cron', 'fbomatic_do_post', 10, 1); add_action('transition_post_status', 'fbomatic_new_post', 10, 3); function fbomatic_new_post($new_status, $old_status, $post) { if ('publish' !== $new_status or 'publish' === $old_status) { return; } else { if($old_status == 'auto-draft' && $new_status == 'publish' && !has_post_thumbnail($post->ID) && ((function_exists('has_blocks') && has_blocks($post)) || ($post->post_content == '' && function_exists('has_blocks') && !class_exists('Classic_Editor')))) { $delay_it_is_gutenberg = true; } else { $delay_it_is_gutenberg = false; } } $fbomatic_Main_Settings = get_option('fbomatic_Main_Settings', false); if (isset($fbomatic_Main_Settings['fbomatic_enabled']) && $fbomatic_Main_Settings['fbomatic_enabled'] == 'on') { $fbomatic_Facebook_Settings = get_option('fbomatic_Facebook_Settings', false); if (isset($fbomatic_Facebook_Settings['fbomatic_posting']) && $fbomatic_Facebook_Settings['fbomatic_posting'] == 'on') { if (isset($fbomatic_Facebook_Settings['delay_post']) && $fbomatic_Facebook_Settings['delay_post'] != '' && is_numeric($fbomatic_Facebook_Settings['delay_post'])) { if(wp_next_scheduled('fbomatic_new_post_cron', array($post)) === false) { if($delay_it_is_gutenberg && $fbomatic_Facebook_Settings['delay_post'] < 2) { $fbomatic_Facebook_Settings['delay_post'] = 2; } wp_schedule_single_event(time() + $fbomatic_Facebook_Settings['delay_post'], 'fbomatic_new_post_cron', array($post)); } } else { if (isset($fbomatic_Facebook_Settings['run_background']) && $fbomatic_Facebook_Settings['run_background'] == 'on') { if($delay_it_is_gutenberg) { if(wp_next_scheduled('fbomatic_new_post_cron', array($post)) === false) { wp_schedule_single_event(time() + 2, 'fbomatic_new_post_cron', array($post)); } } else { $unique_id = uniqid(); update_option('fbomatic_do_post_uniqid', $unique_id); $xcron_url = site_url( '?fbomatic_do_post_cronjob=1&post_id=' . $post->ID . '&fbomatic_do_post_key=' . $unique_id); wp_remote_post( $xcron_url, array( 'timeout' => 1, 'blocking' => false, 'sslverify' => false ) ); } } else { if($delay_it_is_gutenberg) { if(wp_next_scheduled('fbomatic_new_post_cron', array($post)) === false) { wp_schedule_single_event( time() + 2, 'fbomatic_new_post_cron', array($post) ); } } else { fbomatic_do_post($post); } } } } } } add_action('init', 'fbomatic_do_post_callback', 0); function fbomatic_do_post_callback() { $secretp_key = get_option('fbomatic_do_post_uniqid', false); if (isset($_GET['fbomatic_do_post_cronjob']) && $_GET['fbomatic_do_post_cronjob'] == '1' && isset($_GET['post_id']) && is_numeric($_GET['post_id']) && $_GET['fbomatic_do_post_key'] === $secretp_key) { $post = get_post($_GET['post_id']); if($post !== null) { fbomatic_do_post($post); exit(); } } } function fbomatic_tk_getContent($url) { $ch = curl_init(); if($ch === false) { return false; } $options = array( CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_HEADER => false, CURLOPT_FOLLOWLOCATION => true, CURLOPT_USERAGENT => fbomatic_get_random_user_agent(), CURLOPT_ENCODING => "utf-8", CURLOPT_AUTOREFERER => false, CURLOPT_COOKIEJAR => get_temp_dir() . 'cookie.txt', CURLOPT_COOKIEFILE => get_temp_dir() . 'cookie.txt', CURLOPT_REFERER => 'https://www.tiktok.com/', CURLOPT_CONNECTTIMEOUT => 30, CURLOPT_SSL_VERIFYHOST => false, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_TIMEOUT => 30, CURLOPT_MAXREDIRS => 10, ); curl_setopt_array( $ch, $options ); if (defined('CURLOPT_IPRESOLVE') && defined('CURL_IPRESOLVE_V4')) { curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); } $data = curl_exec($ch); if($data === false) { return false; } curl_close($ch); return strval($data); } function fbomatic_tk_downloadVideo($video_url) { global $wp_filesystem; if ( ! is_a( $wp_filesystem, 'WP_Filesystem_Base') ){ include_once(ABSPATH . 'wp-admin/includes/file.php');$creds = request_filesystem_credentials( site_url() ); wp_filesystem($creds); } $upload_dir = wp_upload_dir(); $rand = uniqid(); if (wp_mkdir_p($upload_dir['path'])) { $file = $upload_dir['path'] . '/youtubetempupload' . $rand . '.mp4'; $path = $upload_dir['url'] . '/youtubetempupload' . $rand . '.mp4'; } else { $file = $upload_dir['basedir'] . '/youtubetempupload' . $rand . '.mp4'; $path = $upload_dir['baseurl'] . '/youtubetempupload' . $rand . '.mp4'; } $ch = curl_init(); if($ch === false) { return false; } $headers = array( 'Range: bytes=0-', ); $options = array( CURLOPT_URL => $video_url, CURLOPT_RETURNTRANSFER => true, CURLOPT_HEADER => false, CURLOPT_HTTPHEADER => $headers, CURLOPT_FOLLOWLOCATION => true, CURLINFO_HEADER_OUT => true, CURLOPT_USERAGENT => 'okhttp', CURLOPT_ENCODING => "utf-8", CURLOPT_AUTOREFERER => true, CURLOPT_COOKIEJAR => get_temp_dir() . 'cookie.txt', CURLOPT_COOKIEFILE => get_temp_dir() . 'cookie.txt', CURLOPT_REFERER => 'https://www.tiktok.com/', CURLOPT_CONNECTTIMEOUT => 30, CURLOPT_SSL_VERIFYHOST => false, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_TIMEOUT => 30, CURLOPT_MAXREDIRS => 10, ); curl_setopt_array( $ch, $options ); if (defined('CURLOPT_IPRESOLVE') && defined('CURL_IPRESOLVE_V4')) { curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); } $data = curl_exec($ch); if($data === false) { return false; } curl_close($ch); $d = fopen($file, "w"); if($d === false) { return false; } $e = fwrite($d, $data); if($e === false) { return false; } fclose($d); return array($path, $file); } function fbomatic_do_post($post, $manual = false) { global $wp_filesystem; if ( ! is_a( $wp_filesystem, 'WP_Filesystem_Base') ){ include_once(ABSPATH . 'wp-admin/includes/file.php');$creds = request_filesystem_credentials( site_url() ); wp_filesystem($creds); } $fbomatic_Main_Settings = get_option('fbomatic_Main_Settings', false); if (isset($fbomatic_Main_Settings['app_review_mode']) && $fbomatic_Main_Settings['app_review_mode'] == 'on' && $manual == false) { if (isset($fbomatic_Main_Settings['enable_detailed_logging']) && $fbomatic_Main_Settings['enable_detailed_logging'] == 'on') { fbomatic_log_to_file('Skipping post, because plugin is in app review mode: ' . $post->post_title); } return; } if (isset($fbomatic_Main_Settings['rule_timeout']) && $fbomatic_Main_Settings['rule_timeout'] != '') { $timeout = intval($fbomatic_Main_Settings['rule_timeout']); } else { $timeout = 3600; } ini_set('safe_mode', 'Off'); ini_set('max_execution_time', $timeout); ini_set('ignore_user_abort', 1); ini_set('user_agent', fbomatic_get_random_user_agent()); if(function_exists('ignore_user_abort')) { ignore_user_abort(true); } if(function_exists('set_time_limit')) { set_time_limit($timeout); } if (isset($fbomatic_Main_Settings['fbomatic_enabled']) && $fbomatic_Main_Settings['fbomatic_enabled'] == 'on') { $fbomatic_Facebook_Settings = get_option('fbomatic_Facebook_Settings', false); if ($manual || isset($fbomatic_Facebook_Settings['fbomatic_posting']) && $fbomatic_Facebook_Settings['fbomatic_posting'] == 'on') { if (!isset($fbomatic_Main_Settings['app_id2']) || trim($fbomatic_Main_Settings['app_id2']) == '') { if (!isset($fbomatic_Main_Settings['app_id']) || trim($fbomatic_Main_Settings['app_id']) == '') { if (isset($fbomatic_Main_Settings['enable_detailed_logging']) && $fbomatic_Main_Settings['enable_detailed_logging'] == 'on') { fbomatic_log_to_file('Skipping post, app id not set: ' . $post->post_title); } return; } } if (!isset($fbomatic_Main_Settings['app_secret2']) || trim($fbomatic_Main_Settings['app_secret2']) == '') { if (!isset($fbomatic_Main_Settings['app_secret']) || trim($fbomatic_Main_Settings['app_secret']) == '') { fbomatic_log_to_file('Please insert your App Secret in plugin settings before we can automatically publish on Facebook.'); return; } } if (isset($fbomatic_Facebook_Settings['always_manual']) && $manual == true) { $go_manual = true; } else { $go_manual = false; } $app_secret = ''; $app_id = ''; if (isset($fbomatic_Main_Settings['app_secret2']) && trim($fbomatic_Main_Settings['app_secret2']) != '') { $app_secret = trim($fbomatic_Main_Settings['app_secret2']); } else { if (isset($fbomatic_Main_Settings['app_secret']) && trim($fbomatic_Main_Settings['app_secret']) != '') { $app_secret = trim($fbomatic_Main_Settings['app_secret']); } } if (isset($fbomatic_Main_Settings['app_id2']) && trim($fbomatic_Main_Settings['app_id2']) != '') { $app_id = trim($fbomatic_Main_Settings['app_id2']); } else { if (isset($fbomatic_Main_Settings['app_id']) && trim($fbomatic_Main_Settings['app_id']) != '') { $app_id = trim($fbomatic_Main_Settings['app_id']); } } $authorized = FALSE; if (get_option('fbomatic_auth_id', false) !== FALSE) { if (get_option('fbomatic_auth_secret', false) !== FALSE) { if ($app_id == get_option('fbomatic_auth_id', false) && $app_secret == get_option('fbomatic_auth_secret', false)) { $authorized = TRUE; } } } if ($authorized === FALSE) { if (isset($fbomatic_Main_Settings['enable_detailed_logging']) && $fbomatic_Main_Settings['enable_detailed_logging'] == 'on') { //fbomatic_log_to_file('Skipping post, plugin not authorized to post: ' . $post->post_title); } return; } if (!$go_manual && isset($fbomatic_Facebook_Settings['post_posts'])) { if ($go_manual != true && $fbomatic_Facebook_Settings['post_posts'] == 'on' && 'post' === $post->post_type) { if (isset($fbomatic_Main_Settings['enable_detailed_logging']) && $fbomatic_Main_Settings['enable_detailed_logging'] == 'on') { fbomatic_log_to_file('Skipping post because of post type: ' . $post->post_title); } return; } } if (!$go_manual && isset($fbomatic_Facebook_Settings['post_pages'])) { if ($go_manual != true && $fbomatic_Facebook_Settings['post_pages'] == 'on' && 'page' === $post->post_type) { if (isset($fbomatic_Main_Settings['enable_detailed_logging']) && $fbomatic_Main_Settings['enable_detailed_logging'] == 'on') { fbomatic_log_to_file('Skipping page because of its type: ' . $post->post_title); } return; } } if (!$go_manual && isset($fbomatic_Facebook_Settings['post_custom'])) { if ($go_manual != true && $fbomatic_Facebook_Settings['post_custom'] == 'on' && 'page' !== $post->post_type && 'post' !== $post->post_type) { if (isset($fbomatic_Facebook_Settings['except_type']) && $fbomatic_Facebook_Settings['except_type'] != '') { $excepted_types = explode(',', $fbomatic_Facebook_Settings['except_type']); $excepted_types = array_map('trim', $excepted_types); if(!in_array($post->post_type, $excepted_types)) { return; } } else { return; } } } $meta = get_post_meta($post->ID, "fbomatic_published", true); if ($go_manual != true && $meta == 'pub') { if (isset($fbomatic_Main_Settings['enable_detailed_logging']) && $fbomatic_Main_Settings['enable_detailed_logging'] == 'on') { fbomatic_log_to_file('Skipping post, it was already published before: ' . $post->post_title); } return; } update_post_meta($post->ID, "fbomatic_published", "pub"); if(isset($fbomatic_Facebook_Settings['max_posts']) && $fbomatic_Facebook_Settings['max_posts'] !== '') { $now_time = time(); $post_count = $fbomatic_Facebook_Settings['max_posts']; if(isset($fbomatic_Facebook_Settings['max_posts_interval']) && $fbomatic_Facebook_Settings['max_posts_interval'] !== '') { $post_interval = $fbomatic_Facebook_Settings['max_posts_interval']; } else { $post_interval = '60'; } $GLOBALS['wp_object_cache']->delete('fbomatic_posted_times', 'options'); $posted_times = get_option('fbomatic_posted_times'); if(is_array($posted_times)) { $latest_count = 0; foreach($posted_times as $key => $post_time) { if(intval($post_time) <= $now_time) { $difference = floor(($now_time - intval($post_time))/60); if($difference < intval($post_interval)) { $latest_count++; } else { unset($posted_times[$key]); } } } if($go_manual != true && $latest_count >= intval($post_count)) { if (isset($fbomatic_Main_Settings['enable_detailed_logging']) && $fbomatic_Main_Settings['enable_detailed_logging'] == 'on') { fbomatic_log_to_file('Skipping post, maximum post count reached: ' . $post->post_title); } return; } } else { $posted_times = array(); } } if (!isset($fbomatic_Main_Settings['access_token']) || $fbomatic_Main_Settings['access_token'] == '') { $access_token = get_option('fbomatic_access_token', false); } else { $access_token = $fbomatic_Main_Settings['access_token']; } $store = get_option('fbomatic_page_ids', false); $pageIds = array(); if ($store !== false) { $store = explode(',', $store); $count = count($store); for ($i = 0; $i < $count; $i++) { $exploding = explode('-', $store[$i]); if (!isset($exploding[2])) { continue; } $pageIds[$exploding[0]] = $exploding[1]; } } $store = get_option('fbomatic_group_ids', false); $groupIds = array(); if ($store !== false) { $store = explode(',', $store); $count = count($store); for ($i = 0; $i < $count; $i++) { $exploding = explode('-', $store[$i]); if (!isset($exploding[2])) { continue; } $groupIds[$exploding[0]] = $exploding[1]; } } if (count($groupIds) == 0 && count($pageIds) == 0) { if (isset($fbomatic_Main_Settings['enable_detailed_logging']) && $fbomatic_Main_Settings['enable_detailed_logging'] == 'on') { fbomatic_log_to_file('Skipping post, no groupd id or page id selected in plugin settings: ' . $post->post_title); } return; } $selected_pids = array(); if (isset($fbomatic_Facebook_Settings['facebook_pages']) && is_array($fbomatic_Facebook_Settings['facebook_pages'])) { $facebook_pages = $fbomatic_Facebook_Settings['facebook_pages']; foreach ($pageIds as $pId => $token) { if (in_array($pId, $facebook_pages)) { $selected_pids[$pId] = $token; } } } if (isset($fbomatic_Facebook_Settings['facebook_groups']) && is_array($fbomatic_Facebook_Settings['facebook_groups'])) { $facebook_groups = $fbomatic_Facebook_Settings['facebook_groups']; foreach ($groupIds as $pId => $token) { if (in_array($pId, $facebook_groups)) { $selected_pids[$pId] = $token; } } } if(isset($fbomatic_Facebook_Settings['group_post_id']) && $fbomatic_Facebook_Settings['group_post_id'] != '') { $pIds = explode(',', $fbomatic_Facebook_Settings['group_post_id']); foreach($pIds as $pId) if(is_numeric(trim($pId))) { $selected_pids[trim($pId)] = $access_token; } } if (count($selected_pids) == 0) { if (isset($fbomatic_Main_Settings['enable_detailed_logging']) && $fbomatic_Main_Settings['enable_detailed_logging'] == 'on') { fbomatic_log_to_file('Cannot find group id or page ids where to post: ' . $post->post_title); } return; } $post_excerpt = htmlspecialchars_decode(html_entity_decode($post->post_excerpt)); $post_content = do_shortcode(htmlspecialchars_decode(html_entity_decode($post->post_content))); if($post_excerpt == '') { $post_excerpt = wp_trim_excerpt(strip_tags($post_content)); } //if you don't check both, an error will be given - (#100) A link must be provided if a picture URL is given. if((isset($fbomatic_Facebook_Settings['include_link']) && $fbomatic_Facebook_Settings['include_link'] == 'on') || (isset($fbomatic_Facebook_Settings['include_image']) && $fbomatic_Facebook_Settings['include_image'] == 'on')) { if (isset($fbomatic_Facebook_Settings['first_url']) && $fbomatic_Facebook_Settings['first_url'] == 'on') { $regex = '/https?\:\/\/[^\<" \n]+/i'; preg_match($regex, htmlspecialchars_decode($post_content), $matches); if(isset($matches[0]) && filter_var($matches[0], FILTER_VALIDATE_URL)) { $post_link = fbomatic_to_facebook_url_handle($matches[0]); } else { $post_link = fbomatic_to_facebook_url_handle(get_permalink($post->ID)); } } else { $post_link = fbomatic_to_facebook_url_handle(get_permalink($post->ID)); } } else { $post_link = ''; } if(isset($fbomatic_Facebook_Settings['include_title']) && $fbomatic_Facebook_Settings['include_title'] == 'on') { $post_title = html_entity_decode($post->post_title); if(strlen($post_title) > 255) { $post_title = substr($post_title, 0, 255); } } else { $post_title = ''; } if(isset($fbomatic_Facebook_Settings['include_blog_name']) && $fbomatic_Facebook_Settings['include_blog_name'] == 'on') { $blog_title = html_entity_decode(get_bloginfo('title')); } else { $blog_title = ''; } if(isset($fbomatic_Facebook_Settings['include_description']) && $fbomatic_Facebook_Settings['include_description'] == 'on') { $post_description = $post_excerpt; } else { $post_description = ''; } $author_obj = get_user_by('id', $post->post_author); if(isset($author_obj->user_nicename)) { $user_name = $author_obj->user_nicename; } else { $user_name = ''; } $featured_image = ''; if(isset($fbomatic_Facebook_Settings['include_image']) && $fbomatic_Facebook_Settings['include_image'] == 'on') { wp_suspend_cache_addition(true); $metas = get_post_custom($post->ID); wp_suspend_cache_addition(false); if(is_array($metas)) { $rez_meta = fbomatic_preg_grep_keys('#.+?_featured_ima?ge?#i', $metas); } else { $rez_meta = array(); } if(count($rez_meta) > 0) { foreach($rez_meta as $rm) { if(isset($rm[0]) && filter_var($rm[0], FILTER_VALIDATE_URL)) { $featured_image = $rm[0]; break; } } } if($featured_image == '') { $featured_image = fbomatic_generate_thumbmail($post->ID);; } if($featured_image == '' && $post_content != '') { $dom = new DOMDocument(); $internalErrors = libxml_use_internal_errors(true); $dom->loadHTML($post_content); libxml_use_internal_errors($internalErrors); $tags = $dom->getElementsByTagName('img'); foreach ($tags as $tag) { $temp_get_img = $tag->getAttribute('src'); if ($temp_get_img != '') { $temp_get_img = strtok($temp_get_img, '?'); $featured_image = rtrim($temp_get_img, '/'); } } } } $post_cats = get_post_meta($post->ID, 'fbomatic_post_cats', true); if($post_cats == '') { $post_categories = wp_get_post_categories( $post->ID ); foreach($post_categories as $c){ $cat = get_category( $c ); $post_cats .= $cat->name . ','; } $post_cats = trim($post_cats, ','); } if($post_cats != '') { $post_categories = explode(',', $post_cats); } else { $post_categories = array(); } if(count($post_categories) == 0) { $terms = get_the_terms( $post->ID, 'product_cat' ); if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){ foreach ( $terms as $term ) { $post_categories[] = $term->slug; } $post_cats = implode(',', $post_categories); } } foreach($post_categories as $pc) { if (!$go_manual && isset($fbomatic_Facebook_Settings['disabled_categories']) && !empty($fbomatic_Facebook_Settings['disabled_categories'])) { foreach($fbomatic_Facebook_Settings['disabled_categories'] as $disabled_cat) { if($go_manual != true && trim($pc) == get_cat_name($disabled_cat)) { if (isset($fbomatic_Main_Settings['enable_detailed_logging']) && $fbomatic_Main_Settings['enable_detailed_logging'] == 'on') { fbomatic_log_to_file('Skipping post, has a disabled category: ' . $post->post_title); } return; } } } } $post_tagz = get_post_meta($post->ID, 'fbomatic_post_tags', true); if($post_tagz == '') { $post_tags = wp_get_post_tags( $post->ID ); foreach($post_tags as $t){ $post_tagz .= $t->name . ','; } $post_tagz = trim($post_tagz, ','); } if($post_tagz != '') { $post_tags = explode(',', $post_tagz); } else { $post_tags = array(); } if(count($post_tags) == 0) { $terms = get_the_terms( $post->ID, 'product_tag' ); if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){ foreach ( $terms as $term ) { $post_tags[] = $term->slug; } $post_tagz = implode(',', $post_tags); } } foreach($post_tags as $pt) { if (!$go_manual && isset($fbomatic_Facebook_Settings['disable_tags']) && $fbomatic_Facebook_Settings['disable_tags'] != '') { $disable_tags = explode(",", $fbomatic_Facebook_Settings['disable_tags']); foreach($disable_tags as $disabled_tag) { if($go_manual != true && trim($pt) == trim($disabled_tag)) { if (isset($fbomatic_Main_Settings['enable_detailed_logging']) && $fbomatic_Main_Settings['enable_detailed_logging'] == 'on') { fbomatic_log_to_file('Skipping post, has a disabled tag: ' . $post->post_title); } return; } } } } if(isset($fbomatic_Facebook_Settings['include_message']) && $fbomatic_Facebook_Settings['include_message'] == 'on') { $post_template = $fbomatic_Facebook_Settings['facebook_format']; $post_template = replaceFacebookPostShortcodes($post_template, $post_link, $post_title, $blog_title, $post_excerpt, $post_content, $user_name, $featured_image, $post_cats, $post_tagz, $post->ID); $post_template = fbomatic_strip_html_tags(htmlspecialchars_decode($post_template, ENT_QUOTES)); } else { $post_template = ''; } if(isset($fbomatic_Facebook_Settings['limit_content_word_count']) && $fbomatic_Facebook_Settings['limit_content_word_count'] != '') { $post_template = wp_trim_words($post_template, intval($fbomatic_Facebook_Settings['limit_content_word_count']), ''); } $GLOBALS['wp_object_cache']->delete('fbomatic_post_template', 'options'); $fbomatic_post_template = get_option('fbomatic_post_template', false); $GLOBALS['wp_object_cache']->delete('fbomatic_post_title', 'options'); $fbomatic_post_title = get_option('fbomatic_post_title', false); if((isset($fbomatic_Facebook_Settings['include_message']) && $fbomatic_Facebook_Settings['include_message'] == 'on' && $fbomatic_post_template == $post_template) && ($fbomatic_post_title == $post_title && isset($fbomatic_Facebook_Settings['include_title']) && $fbomatic_Facebook_Settings['include_title'] == 'on')) { } update_option('fbomatic_post_template', $post_template); update_option('fbomatic_post_title', $post_title); $post_added = false; $fbFile = dirname(__FILE__) . "/res/Facebook/autoload.php"; if ($wp_filesystem->exists($fbFile) && $wp_filesystem->is_readable($fbFile)) { try { require_once($fbFile); } catch (Exception $e) { fbomatic_log_to_file('Exception thrown in Facebook/autoload.php: ' . $e->getMessage()); return; } } else { if(!$wp_filesystem->exists($fbFile)) { fbomatic_log_to_file('FbInit file does not exist: ' . $fbFile); } elseif(!$wp_filesystem->is_readable($fbFile)) { fbomatic_log_to_file('FbInit file does not exist: ' . $fbFile); } else { fbomatic_log_to_file('FbInit file is in unknown state... : ' . $fbFile); } return; } if(isset($fbomatic_Facebook_Settings['post_videos']) && $fbomatic_Facebook_Settings['post_videos'] == 'on') { $posted_vids = 0; if(isset($fbomatic_Facebook_Settings['max_at_once']) && $fbomatic_Facebook_Settings['max_at_once'] != '') { $max_vides = intval($fbomatic_Facebook_Settings['max_at_once']); } else { $max_vides = 1; } $pm = get_post_meta($post->ID, "avc_modified", true); if($pm == 'y' || !$manual) { $mypost = get_post($post->ID); if($mypost !== null && isset($mypost->post_content)) { $post->post_content = $mypost->post_content; } } $finals = array(); $att = fbomatic_getUrls($post->post_content); $att = array_unique($att); if(count($att) > 0) { foreach($att as $link) { if(isset($fbomatic_Facebook_Settings['only_local']) && $fbomatic_Facebook_Settings['only_local'] == 'on') { if(fbomatic_IsResourceLocal($link)) { $mime = fbomatic_get_mime($link); if(stristr($mime, "video/mp2t") !== FALSE || stristr($mime, "video/quicktime") !== FALSE || stristr($mime, "video/mpeg4") !== FALSE || stristr($mime, "video/mp4") !== FALSE || stristr($mime, "video/x-msvideo") !== FALSE || stristr($mime, "video/x-ms-wmv") !== FALSE || stristr($mime, "video/mpeg") !== FALSE || stristr($mime, "video/x-flv") !== FALSE || stristr($mime, "video/3gpp") !== FALSE || stristr($mime, "video/webm") !== FALSE){ $finals[] = $link; } } } if(isset($fbomatic_Facebook_Settings['only_remote']) && $fbomatic_Facebook_Settings['only_remote'] == 'on') { if(!array_key_exists('remote' . $link, $finals) && fbomatic_IsResourceRemoteVideo($link)) { $local_path = fbomatic_upload_media_library($link); if($local_path !== false) { if (isset($fbomatic_Main_Settings['enable_detailed_logging']) && $fbomatic_Main_Settings['enable_detailed_logging'] == 'on') { fbomatic_log_to_file('Found Remote Video Link: ' . print_r($local_path[0], true)); } $finals['remote' . $link] = $local_path[0]; $deletes['remote' . $link] = $local_path[1]; } else { if (isset($fbomatic_Main_Settings['enable_detailed_logging']) && $fbomatic_Main_Settings['enable_detailed_logging'] == 'on') { fbomatic_log_to_file('Failed to upload remote video to local library: ' . print_r($link, true)); } } } } } { foreach($att as $lnk) { if($posted_vids >= $max_vides) { break; } if(isset($fbomatic_Facebook_Settings['tiktok_embedded']) && $fbomatic_Facebook_Settings['tiktok_embedded'] == 'on') { $id = ''; { preg_match_all('#(?:https?:\/\/(?:www\.)?tiktok\.com\/@(?:[^/]+)\/video\/(\d+)\/?)#i', $lnk, $embeds); if(isset($embeds[1][0])) { $id = $embeds[1][0]; } else { preg_match_all('#(?:https?:\/\/(?:www\.)?vm\.tiktok\.com\/(\d+)\/?)#i', $lnk, $embeds); if(isset($embeds[1][0])) { $id = $embeds[1][0]; } } } if (trim($id) != '') { $url = 'https://www.tiktok.com/node/share/video/@' . $id . '/' . $id; $resp = fbomatic_tk_getContent($url); if($resp !== false) { $check = explode('"downloadAddr":"', $resp); if (count($check) > 1){ $contentURL = explode("\"",$check[1])[0]; $contentURL = str_replace("\\u0026", "&", $contentURL); if($contentURL != '') { $vid_dl = fbomatic_tk_downloadVideo($contentURL); if($vid_dl !== false) { $finals[] = $vid_dl[0]; $deletes[] = $vid_dl[1]; } else { if (isset($fbomatic_Main_Settings['enable_detailed_logging']) && $fbomatic_Main_Settings['enable_detailed_logging'] == 'on') { fbomatic_log_to_file('Failed to upload TikTok video to local library: ' . print_r($contentURL, true)); } } } } else { if (isset($fbomatic_Main_Settings['enable_detailed_logging']) && $fbomatic_Main_Settings['enable_detailed_logging'] == 'on') { fbomatic_log_to_file('downloadAddr not found in TikTok response: ' . print_r($url, true)); } } } } } if(isset($fbomatic_Facebook_Settings['youtube_embedded']) && $fbomatic_Facebook_Settings['youtube_embedded'] == 'on') { $id = ''; parse_str( parse_url( $lnk, PHP_URL_QUERY ), $my_array_of_vars ); if(stristr($lnk, 'youtu') !== false && isset($my_array_of_vars['v'])) { if(!preg_match('/^[A-Za-z0-9-_]+$/i', $my_array_of_vars['v'])) { continue; } $id = $my_array_of_vars['v']; } else { preg_match_all('#http(?:s)?:\/\/(?:www\.)?youtube\.com\/embed\/([^\/\s"\'?&]*)#i', $lnk, $embeds); if(isset($embeds[1][0])) { $id = $embeds[1][0]; } else { preg_match_all('#http(?:s)?:\/\/(?:www\.)?youtube\.com\/v\/([^\/\s"\'?&]*)#i', $lnk, $embeds); if(isset($embeds[1][0])) { $id = $embeds[1][0]; } else { preg_match_all('#http(?:s)?:\/\/(?:www\.)?youtu\.be\/([^\/\s"\'?&]*)#i', $lnk, $embeds); if(isset($embeds[1][0])) { $id = $embeds[1][0]; } else { preg_match_all('#http(?:s)?:\/\/(?:www\.)?youtube\.com\/oembed\?url=http%3A\/\/(?:www\.)?youtube\.com\/watch\?v%3D([^\/\s"\'?&]*)#i', $lnk, $embeds); if(isset($embeds[1][0])) { $id = $embeds[1][0]; } else { preg_match_all('#http(?:s)?:\/\/(?:www\.)?youtube\.com\/attribution_link\?a=(?:[^&])+&u=%2Fwatch%3Fv%3D([^\/\s"\'?&%]*)#i', $lnk, $embeds); if(isset($embeds[1][0])) { $id = $embeds[1][0]; } else { preg_match_all('#http(?:s)?:\/\/(?:www\.)?youtube\.com\/watch\?v=([^\/\s"\'?&]*)#i', $lnk, $embeds); if(isset($embeds[1][0])) { $id = $embeds[1][0]; } } } } } } } if($id != '') { if(!class_exists('\YouTube\YouTubeDownloader')) { require_once(dirname(__FILE__) . "/res/youtube-dl/php-curl-client-master/src/Client.php"); require_once(dirname(__FILE__) . "/res/youtube-dl/php-curl-client-master/src/BrowserClient.php"); require_once(dirname(__FILE__) . "/res/youtube-dl/php-curl-client-master/src/CurlInfo.php"); require_once(dirname(__FILE__) . "/res/youtube-dl/php-curl-client-master/src/Response.php"); require_once(dirname(__FILE__) . "/res/youtube-dl/php-curl-file-downloader-master/src/ContentTypes.php"); require_once(dirname(__FILE__) . "/res/youtube-dl/php-curl-file-downloader-master/src/HeaderHandler.php"); require_once(dirname(__FILE__) . "/res/youtube-dl/php-curl-file-downloader-master/src/CurlDownloader.php"); require_once(dirname(__FILE__) . "/res/youtube-dl/src/Exception/YouTubeException.php"); require_once(dirname(__FILE__) . "/res/youtube-dl/src/Exception/TooManyRequestsException.php"); require_once(dirname(__FILE__) . "/res/youtube-dl/src/Exception/VideoNotFoundException.php"); require_once(dirname(__FILE__) . "/res/youtube-dl/src/Exception/VideoPlayerNotFoundException.php"); require_once(dirname(__FILE__) . "/res/youtube-dl/src/Models/AbstractModel.php"); require_once(dirname(__FILE__) . "/res/youtube-dl/src/Models/SplitStream.php"); require_once(dirname(__FILE__) . "/res/youtube-dl/src/Models/JsonObject.php"); require_once(dirname(__FILE__) . "/res/youtube-dl/src/Models/YouTubeCaption.php"); require_once(dirname(__FILE__) . "/res/youtube-dl/src/Models/StreamFormat.php"); require_once(dirname(__FILE__) . "/res/youtube-dl/src/Models/VideoDetails.php"); require_once(dirname(__FILE__) . "/res/youtube-dl/src/Models/VideoInfo.php"); require_once(dirname(__FILE__) . "/res/youtube-dl/src/Models/InitialPlayerResponse.php"); require_once(dirname(__FILE__) . "/res/youtube-dl/src/Models/YouTubeConfigData.php"); require_once(dirname(__FILE__) . "/res/youtube-dl/src/Responses/HttpResponse.php"); require_once(dirname(__FILE__) . "/res/youtube-dl/src/Responses/PlayerApiResponse.php"); require_once(dirname(__FILE__) . "/res/youtube-dl/src/Responses/GetVideoInfo.php"); require_once(dirname(__FILE__) . "/res/youtube-dl/src/Responses/VideoPlayerJs.php"); require_once(dirname(__FILE__) . "/res/youtube-dl/src/Responses/WatchVideoPage.php"); require_once(dirname(__FILE__) . "/res/youtube-dl/src/Utils/ITagUtils.php"); require_once(dirname(__FILE__) . "/res/youtube-dl/src/Utils/SerializationUtils.php"); require_once(dirname(__FILE__) . "/res/youtube-dl/src/Utils/Utils.php"); require_once(dirname(__FILE__) . "/res/youtube-dl/src/Browser.php"); require_once(dirname(__FILE__) . "/res/youtube-dl/src/DownloadOptions.php"); require_once(dirname(__FILE__) . "/res/youtube-dl/src/Parser.php"); require_once(dirname(__FILE__) . "/res/youtube-dl/src/Utils.php"); require_once(dirname(__FILE__) . "/res/youtube-dl/src/SignatureDecoder.php"); require_once(dirname(__FILE__) . "/res/youtube-dl/src/SignatureLinkParser.php"); require_once(dirname(__FILE__) . "/res/youtube-dl/src/VideoInfoMapper.php"); require_once(dirname(__FILE__) . "/res/youtube-dl/src/YouTubeDownloader.php"); require_once(dirname(__FILE__) . "/res/youtube-dl/src/YoutubeStreamer.php"); require_once(dirname(__FILE__) . "/res/youtube-dl/src/PlayerResponseParser.php"); } try { $downloader = new YouTube\YouTubeDownloader(); $video = $downloader->getDownloadLinks('https://www.youtube.com/watch?v=' . $id, 'android_vr'); } catch(Exception $e) { fbomatic_log_to_file('Exception thrown while downloading YouTube video: ' . get_class($e) . ' - ' . $e->getMessage()); continue; } $za_vid = ''; if ($video->getAllFormats()) { $vcombined = $video->getCombinedFormats(); if($vcombined != false) { $vcount = count($vcombined); if($vcount > 0) { $za_vid = $vcombined[$vcount-1]->url; } else { $za_vid = $video->getFirstCombinedFormat()->url; } } else { $za_vid = $video->getFirstCombinedFormat()->url; } } if($za_vid != '') { $local_path = fbomatic_upload_media_library($za_vid); if($local_path !== false) { $finals[] = $local_path[0]; $deletes[] = $local_path[1]; $posted_vids++; } } } } if(isset($fbomatic_Facebook_Settings['vimeo_embedded']) && $fbomatic_Facebook_Settings['vimeo_embedded'] == 'on') { preg_match_all('/https?:\/\/(?:www\.|player\.)?vimeo.com\/(?:channels\/(?:\w+\/)?|groups\/([^\/]*)\/videos\/|album\/(\d+)\/video\/|video\/|)(\d+)(?:$|\/|\?)?/', $lnk, $vimeos); if(isset($vimeos[3][0]) && is_numeric($vimeos[3][0])) { $vimeourl = fbomatic_getVimeoMP4($vimeos[3][0]); if($vimeourl !== false && $vimeourl !== '') { $local_path = fbomatic_upload_media_library($vimeourl); if($local_path !== false) { $finals[] = $local_path[0]; $deletes[] = $local_path[1]; $posted_vids++; } } } } if(isset($fbomatic_Facebook_Settings['dm_embedded']) && $fbomatic_Facebook_Settings['dm_embedded'] == 'on') { preg_match_all('#https?:\/\/www.dailymotion.com\/video\/([^\s"\']*)#i', $lnk, $dms); if(isset($dms[1][0])) { $dmurl = fbomatic_getDMMP4($dms[1][0]); if($dmurl !== false && $dmurl !== '') { $local_path = fbomatic_upload_media_library($dmurl); if($local_path !== false) { $finals[] = $local_path[0]; $deletes[] = $local_path[1]; } } } else { preg_match_all('#https?:\/\/www.dailymotion.com\/embed\/video\/([^\s"\']*)#i', $lnk, $dms); if(isset($dms[1][0])) { $dmurl = fbomatic_getDMMP4($dms[1][0]); if($dmurl !== false && $dmurl !== '') { $local_path = fbomatic_upload_media_library($dmurl); if($local_path !== false) { $finals[] = $local_path[0]; $deletes[] = $local_path[1]; } } } } } if(isset($fbomatic_Facebook_Settings['fb_embedded']) && $fbomatic_Facebook_Settings['fb_embedded'] == 'on') { preg_match_all('#https:\/\/www.facebook.com\/(.+?)\/videos\/([^\s\'"]+?)\/#i', $lnk, $dms); if(isset($dms[0][0])) { $dmurl = fbomatic_getFBMP4($dms[0][0]); if($dmurl !== false && $dmurl !== '') { $local_path = fbomatic_upload_media_library($dmurl); if($local_path !== false) { $finals[] = $local_path[0]; $deletes[] = $local_path[1]; } } } else { preg_match_all('#https:\/\/www\.facebook\.com\/plugins\/video\.php\?href=(.+?)&#i', $lnk, $dms); if(isset($dms[1][0])) { $dmurl = fbomatic_getFBMP4(urldecode($dms[1][0])); if($dmurl !== false && $dmurl !== '') { $local_path = fbomatic_upload_media_library($dmurl); if($local_path !== false) { $finals[] = $local_path[0]; $deletes[] = $local_path[1]; } } } else { preg_match_all('#https:\/\/www\.facebook\.com\/(?:video\.php|watch)\/?\?v=(\d*)#i', $lnk, $dms); if(isset($dms[0][0])) { $dmurl = fbomatic_getFBMP4($dms[0][0]); if($dmurl !== false && $dmurl !== '') { $local_path = fbomatic_upload_media_library($dmurl); if($local_path !== false) { $finals[] = $local_path[0]; $deletes[] = $local_path[1]; } } } } } } if(isset($fbomatic_Facebook_Settings['tw_embedded']) && $fbomatic_Facebook_Settings['tw_embedded'] == 'on') { preg_match_all('#https?:\/\/clips\.twitch\.tv\/([^\s\'"]*)#i', $lnk, $dms); if(isset($dms[0][0])) { $dmurl = fbomatic_getTWMP4($dms[0][0]); if($dmurl !== false && $dmurl !== '') { $local_path = fbomatic_upload_media_library($dmurl); if($local_path !== false) { $finals[] = $local_path[0]; $deletes[] = $local_path[1]; } } } else { preg_match_all('#<iframe(?:[^>]*?)src="https:\/\/clips.twitch.tv\/embed\?clip=([^"&\s\']*)"#i', $lnk, $dms); if(isset($dms[1][0])) { $dmurl = fbomatic_getTWMP4('https://clips.twitch.tv/embed?clip=' . $dms[1][0]); if($dmurl !== false && $dmurl !== '') { $local_path = fbomatic_upload_media_library($dmurl); if($local_path !== false) { $finals[] = $local_path[0]; $deletes[] = $local_path[1]; } } } } } } } } } foreach ($selected_pids as $pi => $token) { if ($pi == 0) { continue; } if(!isset($fbomatic_Facebook_Settings['only_video']) || $fbomatic_Facebook_Settings['only_video'] != 'on') { if($go_manual != true && $fbomatic_post_template == $post_template && $fbomatic_post_title == $post_title && isset($fbomatic_Facebook_Settings['include_message']) && $fbomatic_Facebook_Settings['include_message'] == 'on') { if (isset($fbomatic_Main_Settings['enable_detailed_logging']) && $fbomatic_Main_Settings['enable_detailed_logging'] == 'on') { fbomatic_log_to_file('Skipping post, it was already posted before: ' . $post->post_title); } return; } if(isset($fbomatic_Facebook_Settings['create_photo']) && $fbomatic_Facebook_Settings['create_photo'] == 'on' && $featured_image != '') { $attachment = array( 'caption' => $post_template, 'access_token' => $token, 'url' => $featured_image ); if((isset($fbomatic_Facebook_Settings['min_age']) && $fbomatic_Facebook_Settings['min_age'] != '' && $fbomatic_Facebook_Settings['min_age'] != 'any') || (isset($fbomatic_Facebook_Settings['target_country']) && $fbomatic_Facebook_Settings['target_country'] != '') || (isset($fbomatic_Facebook_Settings['target_region']) && $fbomatic_Facebook_Settings['target_region'] != '') || (isset($fbomatic_Facebook_Settings['target_city']) && $fbomatic_Facebook_Settings['target_city'] != '')) { $targeting = array(); if((isset($fbomatic_Facebook_Settings['target_country']) && $fbomatic_Facebook_Settings['target_country'] != '') || (isset($fbomatic_Facebook_Settings['target_region']) && $fbomatic_Facebook_Settings['target_region'] != '') || (isset($fbomatic_Facebook_Settings['target_city']) && $fbomatic_Facebook_Settings['target_city'] != '')) { $geo_locations = array(); if(isset($fbomatic_Facebook_Settings['target_country']) && $fbomatic_Facebook_Settings['target_country'] != '') { $cntry = explode(',', $fbomatic_Facebook_Settings['target_country']); $cntry = array_map('trim', $cntry); $geo_locations['countries'] = $cntry; } if(isset($fbomatic_Facebook_Settings['target_region']) && $fbomatic_Facebook_Settings['target_region'] != '') { $target_region = explode(',', $fbomatic_Facebook_Settings['target_region']); $target_region = array_map('trim', $target_region); $my_regs = array(); foreach($target_region as $tr) { $small_reg = array(); $small_reg['key'] = $tr; $my_regs[] = $small_reg; } $geo_locations['regions'] = $my_regs; } if(isset($fbomatic_Facebook_Settings['target_city']) && $fbomatic_Facebook_Settings['target_city'] != '') { $target_city = explode(',', $fbomatic_Facebook_Settings['target_city']); $target_city = array_map('trim', $target_city); $my_regs_c = array(); foreach($target_city as $tc) { $small_reg = array(); $small_reg['key'] = $tc; $my_regs_c[] = $small_reg; } $geo_locations['cities'] = $my_regs_c; } $targeting['geo_locations'] = $geo_locations; } if(isset($fbomatic_Facebook_Settings['min_age']) && $fbomatic_Facebook_Settings['min_age'] != '' && $fbomatic_Facebook_Settings['min_age'] != 'any') { $targeting['age_min'] = $fbomatic_Facebook_Settings['min_age']; } $attachment['targeting'] = $targeting; } try { $GLOBALS['wp_object_cache']->delete('fbomatic_last_time', 'options'); $last_time = get_option('fbomatic_last_time', false); if($last_time !== false && intval($last_time) + 1 < time()) { $sleep_time = rand (600000, 800000); usleep($sleep_time); } if (isset($fbomatic_Main_Settings['api_version']) && $fbomatic_Main_Settings['api_version'] != 'default' && $fbomatic_Main_Settings['api_version'] != '') { $api_ver = $fbomatic_Main_Settings['api_version']; } else { $api_ver = FBOMATIC_API_VER; } $facebook = new Facebook\Facebook(array( 'app_id' => $app_id, 'app_secret' => $app_secret, 'default_graph_version' => 'v' . $api_ver, 'cookie' => true )); if (isset($fbomatic_Main_Settings['enable_detailed_logging']) && $fbomatic_Main_Settings['enable_detailed_logging'] == 'on') { fbomatic_log_to_file('Submitting new photo to Facebook: ' . $post->post_title); } $result = $facebook->post('/' . $pi . '/photos/', $attachment); update_option('fbomatic_last_time', time()); $post_added = true; } catch (Exception $e) { fbomatic_log_to_file('Exception thrown in Facebook photo auto posting: ' . $e->getMessage()); } } else { if($featured_image == '' && isset($fbomatic_Facebook_Settings['only_photo']) && $fbomatic_Facebook_Settings['only_photo'] == 'on' && isset($fbomatic_Facebook_Settings['create_photo']) && $fbomatic_Facebook_Settings['create_photo'] == 'on') { } else { $attachment = array( 'message' => $post_template, 'access_token' => $token, 'link' => $post_link, 'name' => $post_title, 'caption' => $blog_title, 'description' => $post_description, 'actions' => json_encode(array( 'name' => $post_title, 'link' => $post_link )), 'picture' => $featured_image ); if((isset($fbomatic_Facebook_Settings['min_age']) && $fbomatic_Facebook_Settings['min_age'] != '' && $fbomatic_Facebook_Settings['min_age'] != 'any') || (isset($fbomatic_Facebook_Settings['target_country']) && $fbomatic_Facebook_Settings['target_country'] != '') || (isset($fbomatic_Facebook_Settings['target_region']) && $fbomatic_Facebook_Settings['target_region'] != '') || (isset($fbomatic_Facebook_Settings['target_city']) && $fbomatic_Facebook_Settings['target_city'] != '')) { $targeting = array(); if((isset($fbomatic_Facebook_Settings['target_country']) && $fbomatic_Facebook_Settings['target_country'] != '') || (isset($fbomatic_Facebook_Settings['target_region']) && $fbomatic_Facebook_Settings['target_region'] != '') || (isset($fbomatic_Facebook_Settings['target_city']) && $fbomatic_Facebook_Settings['target_city'] != '')) { $geo_locations = array(); if(isset($fbomatic_Facebook_Settings['target_country']) && $fbomatic_Facebook_Settings['target_country'] != '') { $cntry = explode(',', $fbomatic_Facebook_Settings['target_country']); $cntry = array_map('trim', $cntry); $geo_locations['countries'] = $cntry; } if(isset($fbomatic_Facebook_Settings['target_region']) && $fbomatic_Facebook_Settings['target_region'] != '') { $target_region = explode(',', $fbomatic_Facebook_Settings['target_region']); $target_region = array_map('trim', $target_region); $my_regs = array(); foreach($target_region as $tr) { $small_reg = array(); $small_reg['key'] = $tr; $my_regs[] = $small_reg; } $geo_locations['regions'] = $my_regs; } if(isset($fbomatic_Facebook_Settings['target_city']) && $fbomatic_Facebook_Settings['target_city'] != '') { $target_city = explode(',', $fbomatic_Facebook_Settings['target_city']); $target_city = array_map('trim', $target_city); $my_regs_c = array(); foreach($target_city as $tc) { $small_reg = array(); $small_reg['key'] = $tc; $my_regs_c[] = $small_reg; } $geo_locations['cities'] = $my_regs_c; } $targeting['geo_locations'] = $geo_locations; } if(isset($fbomatic_Facebook_Settings['min_age']) && $fbomatic_Facebook_Settings['min_age'] != '' && $fbomatic_Facebook_Settings['min_age'] != 'any') { $targeting['age_min'] = $fbomatic_Facebook_Settings['min_age']; } $attachment['targeting'] = $targeting; } try { $GLOBALS['wp_object_cache']->delete('fbomatic_last_time', 'options'); $last_time = get_option('fbomatic_last_time', false); if($last_time !== false && intval($last_time) + 1 < time()) { $sleep_time = rand (600000, 800000); usleep($sleep_time); } if (isset($fbomatic_Main_Settings['api_version']) && $fbomatic_Main_Settings['api_version'] != 'default' && $fbomatic_Main_Settings['api_version'] != '') { $api_ver = $fbomatic_Main_Settings['api_version']; } else { $api_ver = FBOMATIC_API_VER; } $facebook = new Facebook\Facebook(array( 'app_id' => $app_id, 'app_secret' => $app_secret, 'default_graph_version' => 'v' . $api_ver, 'cookie' => true )); if (isset($fbomatic_Main_Settings['enable_detailed_logging']) && $fbomatic_Main_Settings['enable_detailed_logging'] == 'on') { fbomatic_log_to_file('Submitting new post to Facebook feed: ' . $post->post_title); } $result = $facebook->post('/' . $pi . '/feed/', $attachment); update_option('fbomatic_last_time', time()); $post_added = true; update_option('fbomatic_post_template', $post_template); update_option('fbomatic_post_title', $post_title); } catch (Exception $e) { update_option('fbomatic_last_time', time()); if(stristr($e->getMessage(), 'Only owners of the URL have the ability to specify the picture, name, thumbnail or description params') !== false) { $attachment2 = array( 'message' => $post_template, 'access_token' => $token, 'link' => $post_link, 'caption' => $blog_title, 'actions' => json_encode(array( 'name' => $post_title, 'link' => $post_link )) ); if((isset($fbomatic_Facebook_Settings['min_age']) && $fbomatic_Facebook_Settings['min_age'] != '' && $fbomatic_Facebook_Settings['min_age'] != 'any') || (isset($fbomatic_Facebook_Settings['target_country']) && $fbomatic_Facebook_Settings['target_country'] != '') || (isset($fbomatic_Facebook_Settings['target_region']) && $fbomatic_Facebook_Settings['target_region'] != '') || (isset($fbomatic_Facebook_Settings['target_city']) && $fbomatic_Facebook_Settings['target_city'] != '')) { $targeting = array(); if((isset($fbomatic_Facebook_Settings['target_country']) && $fbomatic_Facebook_Settings['target_country'] != '') || (isset($fbomatic_Facebook_Settings['target_region']) && $fbomatic_Facebook_Settings['target_region'] != '') || (isset($fbomatic_Facebook_Settings['target_city']) && $fbomatic_Facebook_Settings['target_city'] != '')) { $geo_locations = array(); if(isset($fbomatic_Facebook_Settings['target_country']) && $fbomatic_Facebook_Settings['target_country'] != '') { $cntry = explode(',', $fbomatic_Facebook_Settings['target_country']); $cntry = array_map('trim', $cntry); $geo_locations['countries'] = $cntry; } if(isset($fbomatic_Facebook_Settings['target_region']) && $fbomatic_Facebook_Settings['target_region'] != '') { $target_region = explode(',', $fbomatic_Facebook_Settings['target_region']); $target_region = array_map('trim', $target_region); $my_regs = array(); foreach($target_region as $tr) { $small_reg = array(); $small_reg['key'] = $tr; $my_regs[] = $small_reg; } $geo_locations['regions'] = $my_regs; } if(isset($fbomatic_Facebook_Settings['target_city']) && $fbomatic_Facebook_Settings['target_city'] != '') { $target_city = explode(',', $fbomatic_Facebook_Settings['target_city']); $target_city = array_map('trim', $target_city); $my_regs_c = array(); foreach($target_city as $tc) { $small_reg = array(); $small_reg['key'] = $tc; $my_regs_c[] = $small_reg; } $geo_locations['cities'] = $my_regs_c; } $targeting['geo_locations'] = $geo_locations; } if(isset($fbomatic_Facebook_Settings['min_age']) && $fbomatic_Facebook_Settings['min_age'] != '' && $fbomatic_Facebook_Settings['min_age'] != 'any') { $targeting['age_min'] = $fbomatic_Facebook_Settings['min_age']; } $attachment2['targeting'] = $targeting; } try { $GLOBALS['wp_object_cache']->delete('fbomatic_last_time', 'options'); $last_time = get_option('fbomatic_last_time', false); if($last_time !== false && intval($last_time) + 1 < time()) { $sleep_time = rand (600000, 800000); usleep($sleep_time); } if (isset($fbomatic_Main_Settings['api_version']) && $fbomatic_Main_Settings['api_version'] != 'default' && $fbomatic_Main_Settings['api_version'] != '') { $api_ver = $fbomatic_Main_Settings['api_version']; } else { $api_ver = FBOMATIC_API_VER; } $facebook = new Facebook\Facebook(array( 'app_id' => $app_id, 'app_secret' => $app_secret, 'default_graph_version' => 'v' . $api_ver, 'cookie' => true )); $result = $facebook->post('/' . $pi . '/feed/', $attachment2); update_option('fbomatic_last_time', time()); $post_added = true; update_option('fbomatic_post_template', $post_template); update_option('fbomatic_post_title', $post_title); } catch (Exception $ex) { fbomatic_log_to_file('Exception thrown in Facebook auto posting when trying again: ' . $ex->getMessage()); } } else { fbomatic_log_to_file('Exception thrown in Facebook auto posting: ' . $e->getMessage()); } } } } } $deletes = array(); try { if(isset($fbomatic_Facebook_Settings['post_videos']) && $fbomatic_Facebook_Settings['post_videos'] == 'on') { if(count($att) > 0) { { if(count($finals) != 0) { if(!isset($facebook)) { if (isset($fbomatic_Main_Settings['api_version']) && $fbomatic_Main_Settings['api_version'] != 'default' && $fbomatic_Main_Settings['api_version'] != '') { $api_ver = $fbomatic_Main_Settings['api_version']; } else { $api_ver = FBOMATIC_API_VER; } $facebook = new Facebook\Facebook(array( 'app_id' => $app_id, 'app_secret' => $app_secret, 'default_graph_version' => 'v' . $api_ver, 'cookie' => true )); } foreach($finals as $final_link) { $data = [ 'title' => $post_title, 'description' => $post_template, 'source' => $facebook->videoToUpload($final_link), ]; if((isset($fbomatic_Facebook_Settings['min_age']) && $fbomatic_Facebook_Settings['min_age'] != '' && $fbomatic_Facebook_Settings['min_age'] != 'any') || (isset($fbomatic_Facebook_Settings['target_country']) && $fbomatic_Facebook_Settings['target_country'] != '') || (isset($fbomatic_Facebook_Settings['target_region']) && $fbomatic_Facebook_Settings['target_region'] != '') || (isset($fbomatic_Facebook_Settings['target_city']) && $fbomatic_Facebook_Settings['target_city'] != '')) { $targeting = array(); if((isset($fbomatic_Facebook_Settings['target_country']) && $fbomatic_Facebook_Settings['target_country'] != '') || (isset($fbomatic_Facebook_Settings['target_region']) && $fbomatic_Facebook_Settings['target_region'] != '') || (isset($fbomatic_Facebook_Settings['target_city']) && $fbomatic_Facebook_Settings['target_city'] != '')) { $geo_locations = array(); if(isset($fbomatic_Facebook_Settings['target_country']) && $fbomatic_Facebook_Settings['target_country'] != '') { $cntry = explode(',', $fbomatic_Facebook_Settings['target_country']); $cntry = array_map('trim', $cntry); $geo_locations['countries'] = $cntry; } if(isset($fbomatic_Facebook_Settings['target_region']) && $fbomatic_Facebook_Settings['target_region'] != '') { $target_region = explode(',', $fbomatic_Facebook_Settings['target_region']); $target_region = array_map('trim', $target_region); $my_regs = array(); foreach($target_region as $tr) { $small_reg = array(); $small_reg['key'] = $tr; $my_regs[] = $small_reg; } $geo_locations['regions'] = $my_regs; } if(isset($fbomatic_Facebook_Settings['target_city']) && $fbomatic_Facebook_Settings['target_city'] != '') { $target_city = explode(',', $fbomatic_Facebook_Settings['target_city']); $target_city = array_map('trim', $target_city); $my_regs_c = array(); foreach($target_city as $tc) { $small_reg = array(); $small_reg['key'] = $tc; $my_regs_c[] = $small_reg; } $geo_locations['cities'] = $my_regs_c; } $targeting['geo_locations'] = $geo_locations; } if(isset($fbomatic_Facebook_Settings['min_age']) && $fbomatic_Facebook_Settings['min_age'] != '' && $fbomatic_Facebook_Settings['min_age'] != 'any') { $targeting['age_min'] = $fbomatic_Facebook_Settings['min_age']; } $data['targeting'] = $targeting; } try { $GLOBALS['wp_object_cache']->delete('fbomatic_last_time', 'options'); $last_time = get_option('fbomatic_last_time', false); if($last_time !== false && intval($last_time) + 1 < time()) { $sleep_time = rand (400000, 600000); usleep($sleep_time); } if (isset($fbomatic_Main_Settings['enable_detailed_logging']) && $fbomatic_Main_Settings['enable_detailed_logging'] == 'on') { fbomatic_log_to_file('Submitting new video to Facebook: ' . $post->post_title); } $response = $facebook->post('/' . $pi . '/videos', $data, $token); update_option('fbomatic_last_time', time()); $post_added = true; } catch(Facebook\Exceptions\FacebookResponseException $e) { fbomatic_log_to_file('Failed to post video to Graph returned an error: ' . $e->getMessage()); } catch(Facebook\Exceptions\FacebookSDKException $e) { fbomatic_log_to_file('Failed to post video to Facebook, SDK returned an error: ' . $e->getMessage()); } catch(Exception $e) { fbomatic_log_to_file('Failed to post video to Facebook, SDK returned general error: ' . $e->getMessage()); } } } } } } } catch (Exception $e) { foreach($deletes as $delf) { if ($wp_filesystem->exists($delf)) { $wp_filesystem->delete($delf); } } fbomatic_log_to_file('Exception thrown in Facebook video auto posting: ' . $e->getMessage()); } } foreach($deletes as $delf) { if ($wp_filesystem->exists($delf)) { $wp_filesystem->delete($delf); } } if((isset($fbomatic_Facebook_Settings['post_videos']) && $fbomatic_Facebook_Settings['post_videos'] == 'on') || (isset($fbomatic_Facebook_Settings['only_video']) && $fbomatic_Facebook_Settings['only_video'] == 'on')) { if ($post_added === TRUE) { if(isset($fbomatic_Facebook_Settings['max_posts']) && $fbomatic_Facebook_Settings['max_posts'] !== '') { $posted_times[] = time(); update_option('fbomatic_posted_times', $posted_times); } } } } } } function fbomatic_getDMMP4($vimeo_id) { $result = dmomatic_get_web_page("https://www.dailymotion.com/player/metadata/video/" . $vimeo_id); if($result === false) { global $wp_filesystem; if ( ! is_a( $wp_filesystem, 'WP_Filesystem_Base') ){ include_once(ABSPATH . 'wp-admin/includes/file.php');$creds = request_filesystem_credentials( site_url() ); wp_filesystem($creds); } $result = $wp_filesystem->get_contents($vimeo_id); } if($result === false) { return false; } $data = json_decode($result, true); if($data === false || !isset($data['qualities']['auto'][0]['url'])) { return false; } $xresult = dmomatic_get_web_page($data['qualities']['auto'][0]['url']); if($xresult === false) { return false; } preg_match_all('/#EXT-X-STREAM-INF:(.*)/', $xresult, $streamsRaw); if(!isset($streamsRaw[1])) { return false; } $xresult = $streamsRaw[1]; $streams = array(); foreach ($xresult as $stream) { $quality = dmomatic_getStringBetween($stream, 'NAME="', '"'); $streams[$quality]['url'] = dmomatic_getStringBetween($stream, 'PROGRESSIVE-URI="', '"'); } $retur = ''; ksort($streams, SORT_NUMERIC); if(count($streams) > 0) { $retur = end($streams); $retur = $retur['url']; } return $retur; } function fbomatic_getFBMP4($vimeo_id) { $result = fbomatic_get_web_page($vimeo_id); if($result === false) { global $wp_filesystem; if ( ! is_a( $wp_filesystem, 'WP_Filesystem_Base') ){ include_once(ABSPATH . 'wp-admin/includes/file.php');$creds = request_filesystem_credentials( site_url() ); wp_filesystem($creds); } $result = $wp_filesystem->get_contents($vimeo_id); } if($result === false) { return false; } preg_match_all('#hd_src(?:_no_ratelimit)?:"([^"]+?)"#i', $result, $matches); if(!isset($matches[1][0])) { preg_match_all('#sd_src_no_ratelimit:"(.+?)"#i', $result, $matches); if(!isset($matches[1][0])) { return false; } } return $matches[1][0]; } function fbomatic_getTWMP4($vimeo_id) { $result = fbomatic_get_web_page($vimeo_id); if($result === false) { global $wp_filesystem; if ( ! is_a( $wp_filesystem, 'WP_Filesystem_Base') ){ include_once(ABSPATH . 'wp-admin/includes/file.php');$creds = request_filesystem_credentials( site_url() ); wp_filesystem($creds); } $result = $wp_filesystem->get_contents($vimeo_id); } if($result === false) { return false; } preg_match_all('#{"quality":"720","source":"(.+?)"#i', $result, $matches); if(!isset($matches[1][0])) { return false; } return $matches[1][0]; } function fbomatic_getVimeoMP4($vimeo_id) { require_once(dirname(__FILE__) . "/res/vimeodl.php"); $vd = new VideoControllerDownloaderLoader(); $vimeo_link = $vd->getVimeoDirectUrl('https://vimeo.com/' . $vimeo_id); return trim($vimeo_link); } function fbomatic_IsResourceRemoteVideo($url) { if( empty( $url ) ) { return false; } $extension_found = false; $videoExtensions = array("webm", "mpg", "mpeg", "mpe", "mp4", "m4p", "m4v", "avi", "wmv", "mov"); foreach($videoExtensions as $vid_ext) { if(stristr($url, '.' . $vid_ext) !== false) { $extension_found = true; break; } } if($extension_found == false) { return false; } $urlParsed = parse_url( $url ); $host = $urlParsed['host']; if( empty( $host ) ) { return false; } $host = str_replace('www.', '', $host); $thishost = $_SERVER['HTTP_HOST']; $thishost = str_replace('www.', '', $thishost); if( $host != $thishost ){ return true; } return false; } function fbomatic_upload_media_library($image_url) { global $wp_filesystem; if ( ! is_a( $wp_filesystem, 'WP_Filesystem_Base') ){ include_once(ABSPATH . 'wp-admin/includes/file.php');$creds = request_filesystem_credentials( site_url() ); wp_filesystem($creds); } $upload_dir = wp_upload_dir(); $rand = uniqid(); if (wp_mkdir_p($upload_dir['path'])) { $file = $upload_dir['path'] . '/facebooktempupload' . $rand . '.mp4'; $path = $upload_dir['url'] . '/facebooktempupload' . $rand . '.mp4'; } else { $file = $upload_dir['basedir'] . '/facebooktempupload' . $rand . '.mp4'; $path = $upload_dir['baseurl'] . '/facebooktempupload' . $rand . '.mp4'; } $ret = $wp_filesystem->copy($image_url, $file, true); if($ret === false) { if(!$wp_filesystem->exists($file)) { $errors= error_get_last(); fbomatic_log_to_file('Failed to copy video file ' . $image_url . ' locally to server to ' . $file . ': ' . $errors['type'] . ' - ' . $errors['message']); return false; } else { return array($path, $file); } } else { return array($path, $file); } } function fbomatic_IsResourceLocal($url){ global $wp_filesystem; if ( ! is_a( $wp_filesystem, 'WP_Filesystem_Base') ){ include_once(ABSPATH . 'wp-admin/includes/file.php');$creds = request_filesystem_credentials( site_url() ); wp_filesystem($creds); } if( empty( $url ) ){ return false; } $urlParsed = parse_url( $url ); $host = $urlParsed['host']; if( empty( $host ) ){ $doc_root = $_SERVER['DOCUMENT_ROOT']; $maybefile = $doc_root.$url; $fileexists = $wp_filesystem->exists ( $maybefile ); if( $fileexists ){ return true; } } $host = str_replace('www.','',$host); $thishost = $_SERVER['HTTP_HOST']; $thishost = str_replace('www.','',$thishost); if( $host == $thishost ){ return true; } return false; } function fbomatic_generate_thumbmail( $post_id ) { $post = get_post($post_id); $post_parent_id = $post->post_parent === 0 ? $post->ID : $post->post_parent; if ( has_post_thumbnail($post_parent_id) ) { if ($id_attachment = get_post_thumbnail_id($post_parent_id)) { $the_image = wp_get_attachment_url($id_attachment, false); return $the_image; } } $attachments = array_values(get_children(array( 'post_parent' => $post_parent_id, 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC', 'orderby' => 'menu_order ID') )); if( sizeof($attachments) > 0 ) { $the_image = wp_get_attachment_url($attachments[0]->ID, false); return $the_image; } $media = get_attached_media('image', $post_id); if( sizeof($media) > 0 ) { $the_image = wp_get_attachment_url($media[0]->ID, false); return $the_image; } $image_url = fbomatic_extractThumbnail($post->post_content); return $image_url; } function fbomatic_extractThumbnail($content) { $att = fbomatic_getUrls($content); if(count($att) > 0) { foreach($att as $link) { if(fbomatic_is_image_url($link)) { $mime = fbomatic_get_mime($link); if(stristr($mime, "image/") !== FALSE){ return $link; } } } } else { return ''; } return ''; } function fbomatic_is_image_url($l) { $arr = explode("?", $l); return preg_match("#\.(jpg|jpeg|gif|png)$#i", $arr[0]); } function fbomatic_getUrls($string) { $regex = '/https?\:\/\/[^\"\' \n\s]+/i'; preg_match_all($regex, $string, $matches); return ($matches[0]); } function fbomatic_get_mime ($filename) { $mime_types = array( 'txt' => 'text/plain', 'htm' => 'text/html', 'html' => 'text/html', 'php' => 'text/html', 'css' => 'text/css', 'js' => 'application/javascript', 'json' => 'application/json', 'xml' => 'application/xml', 'swf' => 'application/x-shockwave-flash', 'flv' => 'video/x-flv', 'png' => 'image/png', 'jpe' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'jpg' => 'image/jpeg', 'gif' => 'image/gif', 'bmp' => 'image/bmp', 'ico' => 'image/vnd.microsoft.icon', 'tiff' => 'image/tiff', 'mts' => 'video/mp2t', 'tif' => 'image/tiff', 'svg' => 'image/svg+xml', 'svgz' => 'image/svg+xml', 'zip' => 'application/zip', 'rar' => 'application/x-rar-compressed', 'exe' => 'application/x-msdownload', 'msi' => 'application/x-msdownload', 'cab' => 'application/vnd.ms-cab-compressed', 'mp3' => 'audio/mpeg', 'qt' => 'video/quicktime', 'mov' => 'video/quicktime', 'wmv' => 'video/x-ms-wmv', 'mp4' => 'video/mp4', 'm4p' => 'video/m4p', 'm4v' => 'video/m4v', 'mpg' => 'video/mpg', 'mp2' => 'video/mp2', 'mpe' => 'video/mpe', 'mpv' => 'video/mpv', 'm2v' => 'video/m2v', 'm4v' => 'video/m4v', '3g2' => 'video/3g2', '3gpp' => 'video/3gpp', 'f4v' => 'video/f4v', 'f4p' => 'video/f4p', 'f4a' => 'video/f4a', 'f4b' => 'video/f4b', '3gp' => 'video/3gp', 'avi' => 'video/x-msvideo', 'mpeg' => 'video/mpeg', 'mpegps' => 'video/mpeg', 'webm' => 'video/webm', 'mpeg4' => 'video/mp4', 'mkv' => 'video/mkv', 'pdf' => 'application/pdf', 'psd' => 'image/vnd.adobe.photoshop', 'ai' => 'application/postscript', 'eps' => 'application/postscript', 'ps' => 'application/postscript', 'doc' => 'application/msword', 'rtf' => 'application/rtf', 'xls' => 'application/vnd.ms-excel', 'ppt' => 'application/vnd.ms-powerpoint', 'docx' => 'application/msword', 'xlsx' => 'application/vnd.ms-excel', 'pptx' => 'application/vnd.ms-powerpoint', 'odt' => 'application/vnd.oasis.opendocument.text', 'ods' => 'application/vnd.oasis.opendocument.spreadsheet', ); $ext = array_values(array_slice(explode('.', $filename), -1));$ext = $ext[0]; if(stristr($filename, 'dailymotion.com')) { return 'application/octet-stream'; } if (function_exists('mime_content_type')) { error_reporting(0); $mimetype = mime_content_type($filename); error_reporting(E_ALL); if($mimetype == '') { if (array_key_exists($ext, $mime_types)) { return $mime_types[$ext]; } else { return 'application/octet-stream'; } } return $mimetype; } elseif (function_exists('finfo_open')) { $finfo = finfo_open(FILEINFO_MIME); $mimetype = finfo_file($finfo, $filename); finfo_close($finfo); if($mimetype === false) { if (array_key_exists($ext, $mime_types)) { return $mime_types[$ext]; } else { return 'application/octet-stream'; } } return $mimetype; } elseif (array_key_exists($ext, $mime_types)) { return $mime_types[$ext]; } else { return 'application/octet-stream'; } } function replaceFacebookPostShortcodes($content, $post_link, $post_title, $blog_title, $post_excerpt, $post_content, $user_name, $featured_image, $post_cats, $post_tagz, $post_id) { $matches = array(); $i = 0; preg_match_all('~%regex\(\s*\"([^"]+?)\s*"\s*[,;]\s*\"([^"]*)\"\s*(?:[,;]\s*\"([^"]*?)\s*\")?(?:[,;]\s*\"([^"]*?)\s*\")?(?:[,;]\s*\"([^"]*?)\s*\")?\)%~si', $content, $matches); if (is_array($matches) && count($matches) && is_array($matches[0])) { for($i = 0; $i < count($matches[0]); $i++) { if (isset($matches[0][$i])) $fullmatch = $matches[0][$i]; if (isset($matches[1][$i])) $search_in = replaceFacebookPostShortcodes($matches[1][$i], $post_link, $post_title, $blog_title, $post_excerpt, $post_content, $user_name, $featured_image, $post_cats, $post_tagz, $post_id); if (isset($matches[2][$i])) $matchpattern = $matches[2][$i]; if (isset($matches[3][$i])) $element = $matches[3][$i]; if (isset($matches[4][$i])) $delimeter = $matches[4][$i];if (isset($matches[5][$i])) $counter = $matches[5][$i]; if (isset($matchpattern)) { if (preg_match('<^[\/#%+~[\]{}][\s\S]*[\/#%+~[\]{}]$>', $matchpattern, $z)) { $ret = preg_match_all($matchpattern, $search_in, $submatches, PREG_PATTERN_ORDER); } else { $ret = preg_match_all('~'.$matchpattern.'~si', $search_in, $submatches, PREG_PATTERN_ORDER); } } if (isset($submatches)) { if (is_array($submatches)) { $empty_elements = array_keys($submatches[0], ""); foreach ($empty_elements as $e) { unset($submatches[0][$e]); } $submatches[0] = array_unique($submatches[0]); if (!is_numeric($element)) { $element = 0; }if (!is_numeric($counter)) { $counter = 0; } if(isset($submatches[(int)($element)])) { $matched = $submatches[(int)($element)]; } else { $matched = ''; } $matched = array_unique((array)$matched); if (empty($delimeter) || $delimeter == 'null') { if (isset($matched[$counter])) $matched = $matched[$counter]; } else { $matched = implode($delimeter, $matched); } if (empty($matched)) { $content = str_replace($fullmatch, '', $content); } else { $content = str_replace($fullmatch, $matched, $content); } } } } } $spintax = new Fbomatic_Spintax(); $content = $spintax->process($content); $pcxxx = explode('<!- template ->', $content); $content = $pcxxx[array_rand($pcxxx)]; $content = str_replace('%%random_sentence%%', fbomatic_random_sentence_generator(), $content); $content = str_replace('%%random_sentence2%%', fbomatic_random_sentence_generator(false), $content); $content = str_replace('%%post_link%%', $post_link, $content); $content = str_replace('%%post_title%%', $post_title, $content); $content = str_replace('%%blog_title%%', $blog_title, $content); $content = str_replace('%%post_excerpt%%', $post_excerpt, $content); $content = str_replace('%%post_content%%', $post_content, $content); $content = str_replace('%%author_name%%', $user_name, $content); $content = str_replace('%%featured_image%%', $featured_image, $content); $content = str_replace('%%post_cats%%', $post_cats, $content); $content = str_replace('%%post_tags%%', $post_tagz, $content); $variable_content = ''; $fbomatic_Facebook_Settings = get_option('fbomatic_Facebook_Settings', false); if(isset($fbomatic_Facebook_Settings['shortcode_content']) && $fbomatic_Facebook_Settings['shortcode_content'] != '' && isset($fbomatic_Facebook_Settings['shortcode_percentage']) && $fbomatic_Facebook_Settings['shortcode_percentage'] != '') { $rand = rand(1, 100); if($rand <= intval($fbomatic_Facebook_Settings['shortcode_percentage'])) { $variable_content = $fbomatic_Facebook_Settings['shortcode_content']; } } $content = str_replace('%%variable_content%%', $variable_content, $content); $item_hash = fbomatic_extractKeyWords($post_title, 3); $smart_hash = ''; foreach ($item_hash as $ih) { $smart_hash .= '#' . esc_html($ih) . ' '; } $smart_hash = trim($smart_hash); $content = str_replace('%%smart_hashtags%%', $smart_hash, $content); preg_match_all('#%%!([^!]*?)!%%#', $content, $matched_content); if(isset($matched_content[1][0])) { foreach($matched_content[1] as $mc) { $post_custom_data = get_post_meta($post_id, $mc, true); if($post_custom_data != '') { $content = str_replace('%%!' . $mc . '!%%', $post_custom_data, $content); } else { $content = str_replace('%%!' . $mc . '!%%', '', $content); } } } $content = fbomatic_replaceSynergyShortcodes($content); return $content; } function fbomatic_spin_text($title, $content, $alt = false) { $fbomatic_Main_Settings = get_option('fbomatic_Main_Settings', false); $titleSeparator = '[19459000]'; $text = $title . ' ' . $titleSeparator . ' ' . $content; $text = html_entity_decode($text); preg_match_all("/<[^<>]+>/is", $text, $matches, PREG_PATTERN_ORDER); $htmlfounds = array_filter(array_unique($matches[0])); $htmlfounds[] = '"'; $imgFoundsSeparated = array(); foreach ($htmlfounds as $key => $currentFound) { if (stristr($currentFound, '<img') && stristr($currentFound, 'alt')) { $altSeparator = ''; $colonSeparator = ''; if (stristr($currentFound, 'alt="')) { $altSeparator = 'alt="'; $colonSeparator = '"'; } elseif (stristr($currentFound, 'alt = "')) { $altSeparator = 'alt = "'; $colonSeparator = '"'; } elseif (stristr($currentFound, 'alt ="')) { $altSeparator = 'alt ="'; $colonSeparator = '"'; } elseif (stristr($currentFound, 'alt= "')) { $altSeparator = 'alt= "'; $colonSeparator = '"'; } elseif (stristr($currentFound, 'alt=\'')) { $altSeparator = 'alt=\''; $colonSeparator = '\''; } elseif (stristr($currentFound, 'alt = \'')) { $altSeparator = 'alt = \''; $colonSeparator = '\''; } elseif (stristr($currentFound, 'alt= \'')) { $altSeparator = 'alt= \''; $colonSeparator = '\''; } elseif (stristr($currentFound, 'alt =\'')) { $altSeparator = 'alt =\''; $colonSeparator = '\''; } if (trim($altSeparator) != '') { $currentFoundParts = explode($altSeparator, $currentFound); $preAlt = $currentFoundParts[1]; $preAltParts = explode($colonSeparator, $preAlt); $altText = $preAltParts[0]; if (trim($altText) != '') { unset($preAltParts[0]); $imgFoundsSeparated[] = $currentFoundParts[0] . $altSeparator; $imgFoundsSeparated[] = $colonSeparator . implode('', $preAltParts); $htmlfounds[$key] = ''; } } } } if (count($imgFoundsSeparated) != 0) { $htmlfounds = array_merge($htmlfounds, $imgFoundsSeparated); } preg_match_all("/<\!--.*?-->/is", $text, $matches2, PREG_PATTERN_ORDER); $newhtmlfounds = $matches2[0]; preg_match_all("/\[.*?\]/is", $text, $matches3, PREG_PATTERN_ORDER); $shortcodesfounds = $matches3[0]; $htmlfounds = array_merge($htmlfounds, $newhtmlfounds, $shortcodesfounds); $in = 0; $cleanHtmlFounds = array(); foreach ($htmlfounds as $htmlfound) { if ($htmlfound == '[19459000]') { } elseif (trim($htmlfound) == '') { } else { $cleanHtmlFounds[] = $htmlfound; } } $htmlfounds = $cleanHtmlFounds; $start = 19459001; foreach ($htmlfounds as $htmlfound) { $text = str_replace($htmlfound, '[' . $start . ']', $text); $start++; } try { require_once(dirname(__FILE__) . "/res/fbomatic-text-spinner.php"); $phpTextSpinner = new PhpTextSpinner(); if ($alt === FALSE) { $spinContent = $phpTextSpinner->spinContent($text); } else { $spinContent = $phpTextSpinner->spinContentAlt($text); } $translated = $phpTextSpinner->runTextSpinner($spinContent); } catch (Exception $e) { if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('Exception thrown in spinText ' . $e); } return false; } preg_match_all('{\[.*?\]}', $translated, $brackets); $brackets = $brackets[0]; $brackets = array_unique($brackets); foreach ($brackets as $bracket) { if (stristr($bracket, '19')) { $corrrect_bracket = str_replace(' ', '', $bracket); $corrrect_bracket = str_replace('.', '', $corrrect_bracket); $corrrect_bracket = str_replace(',', '', $corrrect_bracket); $translated = str_replace($bracket, $corrrect_bracket, $translated); } } if (stristr($translated, $titleSeparator)) { $start = 19459001; foreach ($htmlfounds as $htmlfound) { $translated = str_replace('[' . $start . ']', $htmlfound, $translated); $start++; } $contents = explode($titleSeparator, $translated); $title = $contents[0]; $content = $contents[1]; } else { if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('Failed to parse spinned content, separator not found'); } return false; } return array( $title, $content ); } function fbomatic_builtin_spin_text($title, $content) { $fbomatic_Main_Settings = get_option('fbomatic_Main_Settings', false); $titleSeparator = '[19459000]'; $text = $title . ' ' . $titleSeparator . ' ' . $content; try { $file=file(dirname(__FILE__) .'/res/synonyms.dat'); foreach($file as $line){ $synonyms=explode('|',$line); foreach($synonyms as $word){ if(trim($word) != ''){ $word=str_replace('/','\/',$word); if(preg_match('/\b'. $word .'\b/u', $text)) { $rand = array_rand($synonyms, 1); $text = preg_replace('/\b'.$word.'\b/u', trim($synonyms[$rand]), $text); } $uword=ucfirst($word); if(preg_match('/\b'. $uword .'\b/u', $text)) { $rand = array_rand($synonyms, 1); $text = preg_replace('/\b'.$uword.'\b/u', ucfirst(trim($synonyms[$rand])), $text); } } } } $translated = $text; } catch (Exception $e) { if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('Exception thrown in spinText ' . $e); } return false; } if (stristr($translated, $titleSeparator)) { $contents = explode($titleSeparator, $translated); $title = $contents[0]; $content = $contents[1]; } else { if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('Failed to parse spinned content, separator not found'); } return false; } return array( $title, $content ); } function fbomatic_best_spin_text($title, $content) { $fbomatic_Main_Settings = get_option('fbomatic_Main_Settings', false); if (!isset($fbomatic_Main_Settings['best_user']) || $fbomatic_Main_Settings['best_user'] == '' || !isset($fbomatic_Main_Settings['best_password']) || $fbomatic_Main_Settings['best_password'] == '') { fbomatic_log_to_file('Please insert a valid "The Best Spinner" user name and password.'); return FALSE; } $titleSeparator = '[19459000]'; $newhtml = $title . ' ' . $titleSeparator . ' ' . $content; $url = 'https://thebestspinner.com/api.php'; $data = array(); $data['action'] = 'authenticate'; $data['format'] = 'php'; $data['username'] = $fbomatic_Main_Settings['best_user']; $data['password'] = $fbomatic_Main_Settings['best_password']; $ch = curl_init(); if ($ch === FALSE) { if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('Failed to init curl!'); } return FALSE; } if (isset($fbomatic_Main_Settings['proxy_url']) && $fbomatic_Main_Settings['proxy_url'] != '') { curl_setopt($ch, CURLOPT_PROXY, $fbomatic_Main_Settings['proxy_url']); if (isset($fbomatic_Main_Settings['proxy_auth']) && $fbomatic_Main_Settings['proxy_auth'] != '') { curl_setopt($ch, CURLOPT_PROXYUSERPWD, $fbomatic_Main_Settings['proxy_auth']); } } curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); curl_setopt($ch, CURLOPT_TIMEOUT, 60); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, true); $fdata = ""; foreach ($data as $key => $val) { $fdata .= "$key=" . urlencode($val) . "&"; } curl_setopt($ch, CURLOPT_POSTFIELDS, $fdata); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_REFERER, $url); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); $html = curl_exec($ch); curl_close($ch); if ($html === FALSE) { if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('"The Best Spinner" failed to exec curl.'); } return FALSE; } $output = unserialize($html); if ($output['success'] == 'true') { $session = $output['session']; $data = array(); $data['session'] = $session; $data['format'] = 'php'; $data['protectedterms'] = ''; $data['action'] = 'replaceEveryonesFavorites'; $data['maxsyns'] = '100'; $data['quality'] = '1'; $ch = curl_init(); if ($ch === FALSE) { if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('Failed to init curl'); } return FALSE; } $newhtml = html_entity_decode($newhtml); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); curl_setopt($ch, CURLOPT_TIMEOUT, 60); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_REFERER, $url); $spinned = ''; if(str_word_count($newhtml) > 4000) { while($newhtml != '') { $first30k = substr($newhtml, 0, 30000); $first30k = rtrim($first30k, '(*'); $first30k = ltrim($first30k, ')*'); $newhtml = substr($newhtml, 30000); $data['text'] = $first30k; $fdata = ""; foreach ($data as $key => $val) { $fdata .= "$key=" . urlencode($val) . "&"; } curl_setopt($ch, CURLOPT_POSTFIELDS, $fdata); $output = curl_exec($ch); if ($output === FALSE) { if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('"The Best Spinner" failed to exec curl after auth.'); } return FALSE; } $output = unserialize($output); if ($output['success'] == 'true') { $spinned .= ' ' . $output['output']; } else { if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('"The Best Spinner" failed to spin article.'); } return FALSE; } } } else { $data['text'] = $newhtml; $fdata = ""; foreach ($data as $key => $val) { $fdata .= "$key=" . urlencode($val) . "&"; } curl_setopt($ch, CURLOPT_POSTFIELDS, $fdata); $output = curl_exec($ch); if ($output === FALSE) { if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('"The Best Spinner" failed to exec curl after auth.'); } return FALSE; } $output = unserialize($output); if ($output['success'] == 'true') { $spinned = $output['output']; } else { if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('"The Best Spinner" failed to spin article: ' . print_r($output, true)); } return FALSE; } } curl_close($ch); $result = explode($titleSeparator, $spinned); if (count($result) < 2) { if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('"The Best Spinner" failed to spin article - titleseparator not found.' . print_r($output, true)); } return FALSE; } $spintax = new Fbomatic_Spintax(); $result[0] = $spintax->process($result[0]); $result[1] = $spintax->process($result[1]); return $result; } else { if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('"The Best Spinner" authentification failed.'); } return FALSE; } } class Fbomatic_Spintax { public function process($text) { return stripslashes(preg_replace_callback( '/\{(((?>[^\{\}]+)|(?R))*)\}/x', array($this, 'replace'), preg_quote($text) )); } public function replace($text) { $text = $this->process($text[1]); $parts = explode('|', $text); return $parts[array_rand($parts)]; } } function fbomatic_wordai_spin_text($title, $content) { $fbomatic_Main_Settings = get_option('fbomatic_Main_Settings', false); if (!isset($fbomatic_Main_Settings['best_user']) || $fbomatic_Main_Settings['best_user'] == '' || !isset($fbomatic_Main_Settings['best_password']) || $fbomatic_Main_Settings['best_password'] == '') { fbomatic_log_to_file('Please insert a valid "Wordai" user name and password.'); return FALSE; } $wordai_uniqueness = '2'; if (!empty($fbomatic_Main_Settings['wordai_uniqueness']) && in_array($fbomatic_Main_Settings['wordai_uniqueness'], ['1', '2', '3'])) { $wordai_uniqueness = trim($fbomatic_Main_Settings['wordai_uniqueness']); } $titleSeparator = '[19459000]'; $email = $fbomatic_Main_Settings['best_user']; $pass = $fbomatic_Main_Settings['best_password']; $spinned = ''; $newhtml = $title . ' ' . $titleSeparator . ' ' . $content; $wordCount = str_word_count(strip_tags($newhtml)); $sendToWordai = function($htmlChunk) use ($email, $pass, $wordai_uniqueness) { $ch = curl_init('https://wai.wordai.com/api/rewrite'); if ($ch === false) { fbomatic_log_to_file('Failed to init curl in WordAI spinning.'); return FALSE; } curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, "input=" . urlencode($htmlChunk) . "&uniqueness=" . $wordai_uniqueness . "&rewrite_num=1&return_rewrites=true&email=" . $email . "&key=" . $pass); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); curl_setopt($ch, CURLOPT_TIMEOUT, 120); $result = curl_exec($ch); if ($result === FALSE) { fbomatic_log_to_file('"Wordai" failed to exec curl after auth: ' . curl_error($ch)); curl_close($ch); return FALSE; } curl_close($ch); return json_decode($result); }; if ($wordCount > 4950) { $chunks = []; $currentChunk = ''; $words = explode(' ', $newhtml); foreach ($words as $word) { $currentChunk .= $word . ' '; if (str_word_count($currentChunk) >= 4500) { $chunks[] = trim($currentChunk); $currentChunk = ''; } } if (!empty(trim($currentChunk))) { $chunks[] = trim($currentChunk); } foreach ($chunks as $chunk) { sleep(1); $response = $sendToWordai($chunk); if (!isset($response->rewrites)) { fbomatic_log_to_file('"Wordai" unrecognized response on chunk: ' . print_r($response, true)); return FALSE; } $spinned .= ' ' . $response->rewrites[0]; } } else { sleep(1); $response = $sendToWordai($newhtml); if (!isset($response->rewrites)) { fbomatic_log_to_file('"Wordai" unrecognized response: ' . print_r($response, true)); return FALSE; } $spinned = $response->rewrites[0]; } $result = explode($titleSeparator, $spinned, 2); if (count($result) < 2) { $result[1] = $result[0]; $result[0] = $title; } return $result; } function fbomatic_spinrewriter_spin_text($title, $content) { $fbomatic_Main_Settings = get_option('fbomatic_Main_Settings', false); if (!isset($fbomatic_Main_Settings['best_user']) || $fbomatic_Main_Settings['best_user'] == '' || !isset($fbomatic_Main_Settings['best_password']) || $fbomatic_Main_Settings['best_password'] == '') { fbomatic_log_to_file('Please insert a valid "SpinRewriter" user name and password.'); return FALSE; } $titleSeparator = '(19459000)'; $quality = '50'; $html = $title . ' ' . $titleSeparator . ' ' . $content; $html = preg_replace('/\s+/', ' ', $html); $data = array(); $data['email_address'] = $fbomatic_Main_Settings['best_user']; $data['api_key'] = $fbomatic_Main_Settings['best_password']; $data['action'] = "unique_variation"; $data['auto_protected_terms'] = "true"; $data['confidence_level'] = "high"; $data['auto_sentences'] = "true"; $data['auto_paragraphs'] = "false"; $data['auto_new_paragraphs'] = "false"; $data['auto_sentence_trees'] = "false"; $data['use_only_synonyms'] = "true"; $data['reorder_paragraphs'] = "false"; $data['nested_spintax'] = "false"; if(str_word_count($html) >= 2500) { $result = ''; while($html != '' && $html != ' ') { $words = explode(" ", $html); $first30k = join(" ", array_slice($words, 0, 2500)); $html = join(" ", array_slice($words, 2500)); $data['text'] = $first30k; $api_response = fbomatic_spinrewriter_api_post($data); if ($api_response === FALSE) { fbomatic_log_to_file('"SpinRewriter" failed to exec curl after auth.'); return FALSE; } $api_response = json_decode($api_response); if(!isset($api_response->response) || !isset($api_response->status) || $api_response->status != 'OK') { if(isset($api_response->status) && $api_response->status == 'ERROR') { if(isset($api_response->response) && $api_response->response == 'You can only submit entirely new text for analysis once every 7 seconds.') { $api_response = fbomatic_spinrewriter_api_post($data); if ($api_response === FALSE) { fbomatic_log_to_file('"SpinRewriter" failed to exec curl after auth (after resubmit).'); return FALSE; } $api_response = json_decode($api_response); if(!isset($api_response->response) || !isset($api_response->status) || $api_response->status != 'OK') { fbomatic_log_to_file('"SpinRewriter" failed to wait and resubmit spinning: ' . print_r($api_response, true) . ' params: ' . print_r($data, true)); return FALSE; } } else { fbomatic_log_to_file('"SpinRewriter" error response: ' . print_r($api_response, true) . ' params: ' . print_r($data, true)); return FALSE; } } else { fbomatic_log_to_file('"SpinRewriter" error response: ' . print_r($api_response, true) . ' params: ' . print_r($data, true)); return FALSE; } } $spinned = $api_response->response; $result .= ' ' . $spinned; if($html != '' && $html != ' ') { sleep(7); } } } else { $data['text'] = $html; $api_response = fbomatic_spinrewriter_api_post($data); if ($api_response === FALSE) { fbomatic_log_to_file('"SpinRewriter" failed to exec curl after auth.'); return FALSE; } $api_response = json_decode($api_response); if(!isset($api_response->response) || !isset($api_response->status) || $api_response->status != 'OK') { if(isset($api_response->status) && $api_response->status == 'ERROR') { if(isset($api_response->response) && $api_response->response == 'You can only submit entirely new text for analysis once every 7 seconds.') { $api_response = fbomatic_spinrewriter_api_post($data); if ($api_response === FALSE) { fbomatic_log_to_file('"SpinRewriter" failed to exec curl after auth (after resubmit).'); return FALSE; } $api_response = json_decode($api_response); if(!isset($api_response->response) || !isset($api_response->status) || $api_response->status != 'OK') { fbomatic_log_to_file('"SpinRewriter" failed to wait and resubmit spinning: ' . print_r($api_response, true) . ' params: ' . print_r($data, true)); return FALSE; } } else { fbomatic_log_to_file('"SpinRewriter" error response: ' . print_r($api_response, true) . ' params: ' . print_r($data, true)); return FALSE; } } else { fbomatic_log_to_file('"SpinRewriter" error response: ' . print_r($api_response, true) . ' params: ' . print_r($data, true)); return FALSE; } } $result = $api_response->response; } $result = explode($titleSeparator, $result); if (count($result) < 2) { if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('"SpinRewriter" failed to spin article - titleseparator not found: ' . $api_response->response); } return FALSE; } return $result; } function fbomatic_spinrewriter_api_post($data){ $data_raw = ""; $GLOBALS['wp_object_cache']->delete('crspinrewriter_spin_time', 'options'); $spin_time = get_option('crspinrewriter_spin_time', false); if($spin_time !== false && is_numeric($spin_time)) { $c_time = time(); $spassed = $c_time - $spin_time; if($spassed < 10 && $spassed >= 0) { sleep(10 - $spassed); } } update_option('crspinrewriter_spin_time', time()); foreach ($data as $key => $value){ $data_raw = $data_raw . $key . "=" . urlencode($value) . "&"; } $ch = curl_init(); if($ch === false) { return false; } curl_setopt($ch, CURLOPT_URL, "https://www.spinrewriter.com/action/api"); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $data_raw); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); curl_setopt($ch, CURLOPT_TIMEOUT, 60); $response = trim(curl_exec($ch)); curl_close($ch); return $response; } function fbomatic_replaceExcludes($text, &$htmlfounds, &$pre_tags_matches, &$pre_tags_matches_s, &$conseqMatchs) { preg_match_all ( '{<script.*?script>}s', $text, $script_matchs ); $script_matchs = $script_matchs [0]; preg_match_all ( '{<pre.*?/pre>}s', $text, $pre_matchs ); $pre_matchs = $pre_matchs [0]; preg_match_all ( '{<code.*?/code>}s', $text, $code_matchs ); $code_matchs = $code_matchs [0]; preg_match_all ( "/<[^<>]+>/is", $text, $matches, PREG_PATTERN_ORDER ); $htmlfounds = array_filter ( array_unique ( $matches [0] ) ); $htmlfounds = array_merge ( $script_matchs, $pre_matchs, $code_matchs, $htmlfounds ); $htmlfounds [] = '"'; $imgFoundsSeparated = array (); $new_imgFoundsSeparated = array (); $altSeparator = ''; $colonSeparator = ''; foreach ( $htmlfounds as $key => $currentFound ) { if (stristr ( $currentFound, '<img' ) && stristr ( $currentFound, 'alt' ) && ! stristr ( $currentFound, 'alt=""' )) { $altSeparator = ''; $colonSeparator = ''; if (stristr ( $currentFound, 'alt="' )) { $altSeparator = 'alt="'; $colonSeparator = '"'; } elseif (stristr ( $currentFound, 'alt = "' )) { $altSeparator = 'alt = "'; $colonSeparator = '"'; } elseif (stristr ( $currentFound, 'alt ="' )) { $altSeparator = 'alt ="'; $colonSeparator = '"'; } elseif (stristr ( $currentFound, 'alt= "' )) { $altSeparator = 'alt= "'; $colonSeparator = '"'; } elseif (stristr ( $currentFound, 'alt=\'' )) { $altSeparator = 'alt=\''; $colonSeparator = '\''; } elseif (stristr ( $currentFound, 'alt = \'' )) { $altSeparator = 'alt = \''; $colonSeparator = '\''; } elseif (stristr ( $currentFound, 'alt= \'' )) { $altSeparator = 'alt= \''; $colonSeparator = '\''; } elseif (stristr ( $currentFound, 'alt =\'' )) { $altSeparator = 'alt =\''; $colonSeparator = '\''; } if (trim ( $altSeparator ) != '') { $currentFoundParts = explode ( $altSeparator, $currentFound ); $preAlt = $currentFoundParts [1]; $preAltParts = explode ( $colonSeparator, $preAlt ); $altText = $preAltParts [0]; if (trim ( $altText ) != '') { unset ( $preAltParts [0] ); $past_alt_text = implode ( $colonSeparator, $preAltParts ); $imgFoundsSeparated [] = $currentFoundParts [0] . $altSeparator; $imgFoundsSeparated [] = $colonSeparator . $past_alt_text; $htmlfounds [$key] = ''; } } } } $title_separator = str_replace ( 'alt', 'title', $altSeparator ); if($title_separator == '') { $title_separator = 'title'; } if($colonSeparator != '') { foreach ( $imgFoundsSeparated as $img_part ) { if (stristr ( $img_part, ' title' )) { $img_part_parts = explode ( $title_separator, $img_part ); $pre_title_part = $img_part_parts [0] . $title_separator; $post_title_parts = explode ( $colonSeparator, $img_part_parts [1] ); $found_title = $post_title_parts [0]; unset ( $post_title_parts [0] ); $past_title_text = implode ( $colonSeparator, $post_title_parts ); $post_title_part = $colonSeparator . $past_title_text; $new_imgFoundsSeparated [] = $pre_title_part; $new_imgFoundsSeparated [] = $post_title_part; } else { $new_imgFoundsSeparated [] = $img_part; } } } if (count ( $new_imgFoundsSeparated ) != 0) { $htmlfounds = array_merge ( $htmlfounds, $new_imgFoundsSeparated ); } preg_match_all ( "/<\!--.*?-->/is", $text, $matches2, PREG_PATTERN_ORDER ); $newhtmlfounds = $matches2 [0]; preg_match_all ( "/\[.*?\]/is", $text, $matches3, PREG_PATTERN_ORDER ); $shortcodesfounds = $matches3 [0]; $htmlfounds = array_merge ( $htmlfounds, $newhtmlfounds, $shortcodesfounds ); $in = 0; $cleanHtmlFounds = array (); foreach ( $htmlfounds as $htmlfound ) { if ($htmlfound == '[19459000]') { } elseif (trim ( $htmlfound ) == '') { } else { $cleanHtmlFounds [] = $htmlfound; } } $htmlfounds = array_filter ( $cleanHtmlFounds ); $start = 19459001; foreach ( $htmlfounds as $htmlfound ) { $text = str_replace ( $htmlfound, '[' . $start . ']', $text ); $start ++; } $text = str_replace ( '.{', '. {', $text ); preg_match_all ( '!(?:\[1945\d*\][\s]*){2,}!s', $text, $conseqMatchs ); $startConseq = 19659001; foreach ( $conseqMatchs [0] as $conseqMatch ) { $text = preg_replace ( '{' . preg_quote ( trim ( $conseqMatch ) ) . '}', '[' . $startConseq . ']', $text, 1 ); $startConseq ++; } preg_match_all ( '{\[.*?\]}', $text, $pre_tags_matches ); $pre_tags_matches = ($pre_tags_matches [0]); preg_match_all ( '{\s*\[.*?\]\s*}u', $text, $pre_tags_matches_s ); $pre_tags_matches_s = ($pre_tags_matches_s [0]); $text = str_replace ( '[', "\n\n[", $text ); $text = str_replace ( ']', "]\n\n", $text ); return $text; } function fbomatic_restoreExcludes($translated, $htmlfounds, $pre_tags_matches, $pre_tags_matches_s, $conseqMatchs){ $translated = preg_replace ( '{]\s*?1945}', '][1945', $translated ); $translated = preg_replace ( '{ 19459(\d*?)]}', ' [19459$1]', $translated ); $translated = str_replace ( '[ [1945', '[1945', $translated ); $translated = str_replace ( '], ', ']', $translated ); preg_match_all ( '{\[.*?\]}', $translated, $bracket_matchs ); $bracket_matchs = $bracket_matchs [0]; foreach ( $bracket_matchs as $single_bracket ) { if (stristr ( $single_bracket, '1' ) && stristr ( $single_bracket, '9' )) { $single_bracket_clean = str_replace ( array ( ',', ' ' ), '', $single_bracket ); $translated = str_replace ( $single_bracket, $single_bracket_clean, $translated ); } } preg_match_all ( '{\[\d*?\]}', $translated, $post_tags_matches ); $post_tags_matches = ($post_tags_matches [0]); if (count ( $pre_tags_matches ) == count ( $post_tags_matches )) { if ($pre_tags_matches !== $post_tags_matches) { $i = 0; foreach ( $post_tags_matches as $post_tags_match ) { $translated = preg_replace ( '{' . preg_quote ( trim ( $post_tags_match ) ) . '}', '[' . $i . ']', $translated, 1 ); $i ++; } $i = 0; foreach ( $pre_tags_matches as $pre_tags_match ) { $translated = str_replace ( '[' . $i . ']', $pre_tags_match, $translated ); $i ++; } } } $translated = str_replace ( "\n\n[", '[', $translated ); $translated = str_replace ( "]\n\n", ']', $translated ); $i = 0; foreach ( $pre_tags_matches_s as $pre_tags_match ) { $pre_tags_match_h = htmlentities ( $pre_tags_match ); if (stristr ( $pre_tags_match_h, ' ' )) { $pre_tags_match = str_replace ( ' ', ' ', $pre_tags_match_h ); } $translated = preg_replace ( '{' . preg_quote ( trim ( $pre_tags_match ) ) . '}', "[$i]", $translated, 1 ); $i ++; } $translated = preg_replace ( '{\s*\[}u', '[', $translated ); $translated = preg_replace ( '{\]\s*}u', ']', $translated ); $i = 0; foreach ( $pre_tags_matches_s as $pre_tags_match ) { $pre_tags_match_h = htmlentities ( $pre_tags_match ); if (stristr ( $pre_tags_match_h, ' ' )) { $pre_tags_match = str_replace ( ' ', ' ', $pre_tags_match_h ); } $translated = preg_replace ( '{' . preg_quote ( "[$i]" ) . '}', $pre_tags_match, $translated, 1 ); $i ++; } $startConseq = 19659001; foreach ( $conseqMatchs [0] as $conseqMatch ) { $translated = str_replace ( '[' . $startConseq . ']', $conseqMatch, $translated ); $startConseq ++; } preg_match_all ( '!\[.*?\]!', $translated, $brackets ); $brackets = $brackets [0]; $brackets = array_unique ( $brackets ); foreach ( $brackets as $bracket ) { if (stristr ( $bracket, '19' )) { $corrrect_bracket = str_replace ( ' ', '', $bracket ); $corrrect_bracket = str_replace ( '.', '', $corrrect_bracket ); $corrrect_bracket = str_replace ( ',', '', $corrrect_bracket ); $translated = str_replace ( $bracket, $corrrect_bracket, $translated ); } } $start = 19459001; foreach ( $htmlfounds as $htmlfound ) { $translated = str_replace ( '[' . $start . ']', $htmlfound, $translated ); $start ++; } return $translated; } function fbomatic_fix_spinned_content($final_content, $spinner) { if ($spinner == 'wordai') { $final_content = str_replace('-LRB-', '(', $final_content); $final_content1 = preg_replace("/{\*\|.*?}/", '*', $final_content); if($final_content1 !== null) { $final_content = $final_content1; } } elseif ($spinner == 'spinrewriter' || $spinner == 'translate') { $final_content = str_replace('& #', '&#', $final_content); $final_content = preg_replace('#&\s([a-zA-Z]+?);#', '', $final_content); } return $final_content; } function fbomatic_spin_and_translate($post_title, $final_content) { $translation = false; $pre_tags_matches = array(); $pre_tags_matches_s = array(); $conseqMatchs = array(); $fbomatic_Main_Settings = get_option('fbomatic_Main_Settings', false); if (isset($fbomatic_Main_Settings['spin_text']) && $fbomatic_Main_Settings['spin_text'] !== 'disabled') { $htmlfounds = array(); $final_content = fbomatic_replaceExcludes($final_content, $htmlfounds, $pre_tags_matches, $pre_tags_matches_s, $conseqMatchs); if ($fbomatic_Main_Settings['spin_text'] == 'builtin') { $translation = fbomatic_builtin_spin_text($post_title, $final_content); } elseif ($fbomatic_Main_Settings['spin_text'] == 'wikisynonyms') { $translation = fbomatic_spin_text($post_title, $final_content, false); } elseif ($fbomatic_Main_Settings['spin_text'] == 'freethesaurus') { $translation = fbomatic_spin_text($post_title, $final_content, true); } elseif ($fbomatic_Main_Settings['spin_text'] == 'best') { $translation = fbomatic_best_spin_text($post_title, $final_content); } elseif ($fbomatic_Main_Settings['spin_text'] == 'wordai') { $translation = fbomatic_wordai_spin_text($post_title, $final_content); } elseif ($fbomatic_Main_Settings['spin_text'] == 'spinrewriter') { $translation = fbomatic_spinrewriter_spin_text($post_title, $final_content); } if ($translation !== FALSE) { if (is_array($translation) && isset($translation[0]) && isset($translation[1])) { $post_title = $translation[0]; $final_content = $translation[1]; $final_content = fbomatic_fix_spinned_content($final_content, $fbomatic_Main_Settings['spin_text']); $final_content = fbomatic_restoreExcludes($final_content, $htmlfounds, $pre_tags_matches, $pre_tags_matches_s, $conseqMatchs); } else { $final_content = fbomatic_restoreExcludes($final_content, $htmlfounds, $pre_tags_matches, $pre_tags_matches_s, $conseqMatchs); if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('Text Spinning failed - malformed data ' . $fbomatic_Main_Settings['spin_text']); } } } else { $final_content = fbomatic_restoreExcludes($final_content, $htmlfounds, $pre_tags_matches, $pre_tags_matches_s, $conseqMatchs); if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('Text Spinning Failed - returned false ' . $fbomatic_Main_Settings['spin_text']); } } } if (isset($fbomatic_Main_Settings['translate']) && $fbomatic_Main_Settings['translate'] != 'disabled') { if(isset($fbomatic_Main_Settings['translate_source']) && $fbomatic_Main_Settings['translate_source'] != 'disabled') { $translate_source = $fbomatic_Main_Settings['translate_source']; } else { $translate_source = 'en'; } $htmlfounds = array(); $final_content = fbomatic_replaceExcludes($final_content, $htmlfounds, $pre_tags_matches, $pre_tags_matches_s, $conseqMatchs); $translation = fbomatic_translate($post_title, $final_content, $translate_source, $fbomatic_Main_Settings['translate']); if (is_array($translation) && isset($translation[1])) { $translation[1] = preg_replace('#(?<=[\*(])\s+(?=[\*)])#', '', $translation[1]); $translation[1] = preg_replace('#([^(*\s]\s)\*+\)#', '$1', $translation[1]); $translation[1] = preg_replace('#\(\*+([\s][^)*\s])#', '$1', $translation[1]); $translation[1] = fbomatic_restoreExcludes($translation[1], $htmlfounds, $pre_tags_matches, $pre_tags_matches_s, $conseqMatchs); } else { $final_content = fbomatic_restoreExcludes($final_content, $htmlfounds, $pre_tags_matches, $pre_tags_matches_s, $conseqMatchs); } if ($translation !== FALSE) { if (is_array($translation) && isset($translation[0]) && isset($translation[1])) { $post_title = $translation[0]; $final_content = $translation[1]; $final_content = str_replace('</ iframe>', '</iframe>', $final_content); if(stristr($final_content, '<head>') !== false) { $d = new DOMDocument; $mock = new DOMDocument; $internalErrors = libxml_use_internal_errors(true); $d->loadHTML('<?xml encoding="utf-8" ?>' . $final_content); libxml_use_internal_errors($internalErrors); $body = $d->getElementsByTagName('body')->item(0); foreach ($body->childNodes as $child) { $mock->appendChild($mock->importNode($child, true)); } $new_post_content_temp = $mock->saveHTML(); if($new_post_content_temp !== '' && $new_post_content_temp !== false) { $new_post_content_temp = str_replace('<?xml encoding="utf-8" ?>', '', $new_post_content_temp); $final_content = preg_replace("/_addload\(function\(\){([^<]*)/i", "", $new_post_content_temp); } } $final_content = htmlspecialchars_decode($final_content); $final_content = str_replace('</ ', '</', $final_content); $final_content = str_replace(' />', '/>', $final_content); $final_content = str_replace('< br/>', '<br/>', $final_content); $final_content = str_replace('< / ', '</', $final_content); $final_content = str_replace(' / >', '/>', $final_content); $final_content = preg_replace('/[\x00-\x1F\x7F\xA0]/u', '', $final_content); $post_title = preg_replace('{&\s*#\s*(\d+)\s*;}', '&#$1;', $post_title); $post_title = htmlspecialchars_decode($post_title); $post_title = str_replace('</ ', '</', $post_title); $post_title = str_replace(' />', '/>', $post_title); $post_title = preg_replace('/[\x00-\x1F\x7F\xA0]/u', '', $post_title); } else { if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('Translation failed - malformed data!'); } } } else { if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('Translation Failed - returned false!'); } } } return array( $post_title, $final_content ); } function fbomatic_translate($title, $content, $from, $to) { $ch = FALSE; $fbomatic_Main_Settings = get_option('fbomatic_Main_Settings', false); try { if($from == 'disabled') { $from = 'auto'; } if($from != 'en' && $from == $to) { $from = 'en'; } elseif($from == 'en' && $from == $to) { return false; } if (isset($fbomatic_Main_Settings['google_trans_auth']) && trim($fbomatic_Main_Settings['google_trans_auth']) != '') { require_once(dirname(__FILE__) . "/res/translator-api.php"); $ch = curl_init(); if ($ch === FALSE) { if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('Failed to init cURL in translator!'); } return false; } curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); curl_setopt($ch, CURLOPT_TIMEOUT, 10); $GoogleTranslatorAPI = new GoogleTranslatorAPI($ch, $fbomatic_Main_Settings['google_trans_auth']); $translated = ''; $translated_title = ''; if($content != '') { if(strlen($content) > 13000) { while($content != '') { $first30k = substr($content, 0, 13000); $content = substr($content, 13000); $translated_temp = $GoogleTranslatorAPI->translateText($first30k, $from, $to); $translated .= ' ' . $translated_temp; } } else { $translated = $GoogleTranslatorAPI->translateText($content, $from, $to); } } if($title != '') { $translated_title = $GoogleTranslatorAPI->translateText($title, $from, $to); } curl_close($ch); } else { require_once(dirname(__FILE__) . "/res/fbomatic-translator.php"); $ch = curl_init(); if ($ch === FALSE) { if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('Failed to init cURL in translator!'); } return false; } curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); curl_setopt($ch, CURLOPT_USERAGENT, fbomatic_get_random_user_agent()); curl_setopt($ch, CURLOPT_TIMEOUT, 60); if (isset($fbomatic_Main_Settings['proxy_url']) && $fbomatic_Main_Settings['proxy_url'] != '') { $prx = explode(',', $fbomatic_Main_Settings['proxy_url']); $randomness = array_rand($prx); curl_setopt( $ch, CURLOPT_PROXY, trim($prx[$randomness])); if (isset($fbomatic_Main_Settings['proxy_auth']) && $fbomatic_Main_Settings['proxy_auth'] != '') { $prx_auth = explode(',', $fbomatic_Main_Settings['proxy_auth']); if(isset($prx_auth[$randomness]) && trim($prx_auth[$randomness]) != '') { curl_setopt( $ch, CURLOPT_PROXYUSERPWD, trim($prx_auth[$randomness]) ); } } } $GoogleTranslator = new GoogleTranslator($ch); if($content != '') { if(strlen($content) > 13000) { $translated = ''; while($content != '') { $first30k = substr($content, 0, 13000); $content = substr($content, 13000); $translated_temp = $GoogleTranslator->translateText($first30k, $from, $to); if (strpos($translated, '<h2>The page you have attempted to translate is already in ') !== false && strpos($translated, 'Error 400 (Bad Request)!!1') !== false) { throw new Exception('Page content already in ' . $to); } if(substr_compare($translated_temp, '</pre>', -strlen('</pre>')) === 0){$translated_temp = substr_replace($translated_temp ,"", -6);}if(substr( $translated_temp, 0, 5 ) === "<pre>"){$translated_temp = substr($translated_temp, 5);} $translated .= ' ' . $translated_temp; } } else { $translated = $GoogleTranslator->translateText($content, $from, $to); if (strpos($translated, '<h2>The page you have attempted to translate is already in ') !== false) { throw new Exception('Page content already in ' . $to); } if (strpos($translated, 'Error 400 (Bad Request)!!1') !== false) { throw new Exception('Unexpected error while translating page!'); } } } else { $translated = ''; } $translated = htmlspecialchars_decode($translated); $translated = str_replace('. Jpg? Oh = ', '.jpg?oh=', $translated); $translated = str_replace(' & oe = ', '&oe=', $translated); if($title != '') { $translated_title = $GoogleTranslator->translateText($title, $from, $to); if (strpos($translated_title, '<h2>The page you have attempted to translate is already in ') !== false) { throw new Exception('Page title already in ' . $to); } if (strpos($translated_title, 'Error 400 (Bad Request)!!1') !== false) { throw new Exception('Unexpected error while translating page title!'); } } else { $translated_title = ''; } curl_close($ch); } } catch (Exception $e) { curl_close($ch); if (isset($fbomatic_Main_Settings['enable_detailed_logging'])) { fbomatic_log_to_file('Exception thrown in GoogleTranslator ' . $e); } return false; } if(substr_compare($translated_title, '</pre>', -strlen('</pre>')) === 0){$title = substr_replace($translated_title ,"", -6);}else{$title = $translated_title;}if(substr( $title, 0, 5 ) === "<pre>"){$title = substr($title, 5);} if(substr_compare($translated, '</pre>', -strlen('</pre>')) === 0){$text = substr_replace($translated ,"", -6);}else{$text = $translated;}if(substr( $text, 0, 5 ) === "<pre>"){$text = substr($text, 5);} $text = preg_replace('/' . preg_quote('html lang=') . '.*?' . preg_quote('>') . '/', '', $text); $text = preg_replace('/' . preg_quote('!DOCTYPE') . '.*?' . preg_quote('<') . '/', '', $text); $text = preg_replace('#https:\/\/translate\.google\.com\/translate\?hl=en&prev=_t&sl=en&tl=pl&u=([^><"\'\s\n]*)#i', urldecode('$1'), $text); return array( $title, $text ); } function fbomatic_strip_html_tags($str) { $str = html_entity_decode($str); $str1 = preg_replace('/(<|>)\1{2}/is', '', $str); if($str1 !== null) { $str = $str1; } $str1 = preg_replace(array( '@<head[^>]*?>.*?</head>@siu', '@<style[^>]*?>.*?</style>@siu', '@<script[^>]*?.*?</script>@siu', '@<noscript[^>]*?.*?</noscript>@siu' ), "", $str); if($str1 !== null) { $str = $str1; } $str = str_replace('><', '> <', $str); $str = strip_tags($str); return $str; } function fbomatic_DOMinnerHTML(DOMNode $element) { $innerHTML = ""; $children = $element->childNodes; foreach ($children as $child) { $innerHTML .= $element->ownerDocument->saveHTML($child); } return $innerHTML; } function fbomatic_url_exists($url) { stream_context_set_default( [ 'ssl' => [ 'verify_peer' => false, 'verify_peer_name' => false, ], ]); error_reporting(0); $headers = get_headers($url); error_reporting(E_ALL); if (!isset($headers[0]) || strpos($headers[0], '200') === false) return false; return true; } register_activation_hook(__FILE__, 'fbomatic_check_version'); function fbomatic_check_version() { if (!function_exists('curl_init')) { wp_die( 'Please enable the cURL PHP extension. Contact your hosting provider for assistance.', 'Plugin Activation Error', array('back_link' => true) ); } if (!current_user_can('activate_plugins')) { wp_die( 'You are not allowed to activate plugins!', 'Plugin Activation Error', array('back_link' => true) ); } $php_version_required = '5.0'; $wp_version_required = '2.7'; if (version_compare(PHP_VERSION, $php_version_required, '<')) { deactivate_plugins(plugin_basename(__FILE__)); wp_die( sprintf( 'This plugin requires PHP version %1$s or higher. Your current version is %2$s.', $php_version_required, PHP_VERSION ), 'Plugin Activation Error', array('back_link' => true) ); } global $wp_version; if (version_compare($wp_version, $wp_version_required, '<')) { deactivate_plugins(plugin_basename(__FILE__)); wp_die( sprintf( 'This plugin requires WordPress version %1$s or higher. Your current version is %2$s.', $wp_version_required, $wp_version ), 'Plugin Activation Error', array('back_link' => true) ); } } add_action('admin_init', 'fbomatic_register_mysettings'); function fbomatic_register_mysettings() { fbomatic_cron_schedule(); register_setting('fbomatic_option_group', 'fbomatic_Main_Settings'); register_setting('fbomatic_option_group2', 'fbomatic_Facebook_Settings'); if (is_multisite()) { if (!get_option('fbomatic_Main_Settings')) { fbomatic_activation_callback(TRUE); } } } function fbomatic_get_plugin_url() { return plugins_url('', __FILE__); } function fbomatic_get_file_url($url) { return esc_url_raw(fbomatic_get_plugin_url() . '/' . $url); } function fbomatic_admin_load_files() { wp_register_style('fbomatic-browser-style', plugins_url('styles/fbomatic-browser.css', __FILE__), false, '1.0.0'); wp_enqueue_style('fbomatic-browser-style'); wp_register_style('fbomatic-custom-style', plugins_url('styles/coderevolution-style.css', __FILE__), false, '1.0.0'); wp_enqueue_style('fbomatic-custom-style'); wp_enqueue_script('jquery'); wp_enqueue_script('media-upload'); wp_enqueue_script('thickbox'); wp_enqueue_style('thickbox'); } function fbomatic_random_sentence_generator($first = true) { $fbomatic_Main_Settings = get_option('fbomatic_Main_Settings', false); if ($first == false) { $r_sentences = $fbomatic_Main_Settings['sentence_list2']; } else { $r_sentences = $fbomatic_Main_Settings['sentence_list']; } $r_variables = $fbomatic_Main_Settings['variable_list']; $r_sentences = trim($r_sentences); $r_variables = trim($r_variables, ';'); $r_variables = trim($r_variables); $r_sentences = str_replace("\r\n", "\n", $r_sentences); $r_sentences = str_replace("\r", "\n", $r_sentences); $r_sentences = explode("\n", $r_sentences); $r_variables = str_replace("\r\n", "\n", $r_variables); $r_variables = str_replace("\r", "\n", $r_variables); $r_variables = explode("\n", $r_variables); $r_vars = array(); for ($x = 0; $x < count($r_variables); $x++) { $var = explode("=>", trim($r_variables[$x])); if (isset($var[1])) { $key = strtolower(trim($var[0])); $words = explode(";", trim($var[1])); $r_vars[$key] = $words; } } $max_s = count($r_sentences) - 1; $rand_s = rand(0, $max_s); $sentence = $r_sentences[$rand_s]; $sentence = str_replace(' ,', ',', ucfirst(fbomatic_replace_words($sentence, $r_vars))); $sentence = str_replace(' .', '.', $sentence); $sentence = str_replace(' !', '!', $sentence); $sentence = str_replace(' ?', '?', $sentence); $sentence = trim($sentence); return $sentence; } function fbomatic_get_word($key, $r_vars) { if (isset($r_vars[$key])) { $words = $r_vars[$key]; $w_max = count($words) - 1; $w_rand = rand(0, $w_max); return fbomatic_replace_words(trim($words[$w_rand]), $r_vars); } else { return ""; } } function fbomatic_replace_words($sentence, $r_vars) { if (str_replace('%', '', $sentence) == $sentence) return $sentence; $words = explode(" ", $sentence); $new_sentence = array(); for ($w = 0; $w < count($words); $w++) { $word = trim($words[$w]); if ($word != '') { if (preg_match('/^%([^%\n]*)$/', $word, $m)) { $varkey = trim($m[1]); $new_sentence[] = fbomatic_get_word($varkey, $r_vars); } else { $new_sentence[] = $word; } } } return implode(" ", $new_sentence); } function fbomatic_fb_locales() { return array( 'af_ZA', // Afrikaans 'ak_GH', // Akan 'am_ET', // Amharic 'ar_AR', // Arabic 'as_IN', // Assamese 'ay_BO', // Aymara 'az_AZ', // Azerbaijani 'be_BY', // Belarusian 'bg_BG', // Bulgarian 'bn_IN', // Bengali 'br_FR', // Breton 'bs_BA', // Bosnian 'ca_ES', // Catalan 'cb_IQ', // Sorani Kurdish 'ck_US', // Cherokee 'co_FR', // Corsican 'cs_CZ', // Czech 'cx_PH', // Cebuano 'cy_GB', // Welsh 'da_DK', // Danish 'de_DE', // German 'el_GR', // Greek 'en_GB', // English (UK) 'en_IN', // English (India) 'en_PI', // English (Pirate) 'en_UD', // English (Upside Down) 'en_US', // English (US) 'eo_EO', // Esperanto 'es_CL', // Spanish (Chile) 'es_CO', // Spanish (Colombia) 'es_ES', // Spanish (Spain) 'es_LA', // Spanish 'es_MX', // Spanish (Mexico) 'es_VE', // Spanish (Venezuela) 'et_EE', // Estonian 'eu_ES', // Basque 'fa_IR', // Persian 'fb_LT', // Leet Speak 'ff_NG', // Fulah 'fi_FI', // Finnish 'fo_FO', // Faroese 'fr_CA', // French (Canada) 'fr_FR', // French (France) 'fy_NL', // Frisian 'ga_IE', // Irish 'gl_ES', // Galician 'gn_PY', // Guarani 'gu_IN', // Gujarati 'gx_GR', // Classical Greek 'ha_NG', // Hausa 'he_IL', // Hebrew 'hi_IN', // Hindi 'hr_HR', // Croatian 'hu_HU', // Hungarian 'hy_AM', // Armenian 'id_ID', // Indonesian 'ig_NG', // Igbo 'is_IS', // Icelandic 'it_IT', // Italian 'ja_JP', // Japanese 'ja_KS', // Japanese (Kansai) 'jv_ID', // Javanese 'ka_GE', // Georgian 'kk_KZ', // Kazakh 'km_KH', // Khmer 'kn_IN', // Kannada 'ko_KR', // Korean 'ku_TR', // Kurdish (Kurmanji) 'ky_KG', // Kyrgyz 'la_VA', // Latin 'lg_UG', // Ganda 'li_NL', // Limburgish 'ln_CD', // Lingala 'lo_LA', // Lao 'lt_LT', // Lithuanian 'lv_LV', // Latvian 'mg_MG', // Malagasy 'mi_NZ', // Maori 'mk_MK', // Macedonian 'ml_IN', // Malayalam 'mn_MN', // Mongolian 'mr_IN', // Marathi 'ms_MY', // Malay 'mt_MT', // Maltese 'my_MM', // Burmese 'nb_NO', // Norwegian (bokmal) 'nd_ZW', // Ndebele 'ne_NP', // Nepali 'nl_BE', // Dutch (Belgi??) 'nl_NL', // Dutch 'nn_NO', // Norwegian (nynorsk) 'ny_MW', // Chewa 'or_IN', // Oriya 'pa_IN', // Punjabi 'pl_PL', // Polish 'ps_AF', // Pashto 'pt_BR', // Portuguese (Brazil) 'pt_PT', // Portuguese (Portugal) 'qu_PE', // Quechua 'rm_CH', // Romansh 'ro_RO', // Romanian 'ru_RU', // Russian 'rw_RW', // Kinyarwanda 'sa_IN', // Sanskrit 'sc_IT', // Sardinian 'se_NO', // Northern S??mi 'si_LK', // Sinhala 'sk_SK', // Slovak 'sl_SI', // Slovenian 'sn_ZW', // Shona 'so_SO', // Somali 'sq_AL', // Albanian 'sr_RS', // Serbian 'sv_SE', // Swedish 'sy_SY', // Swahili 'sw_KE', // Syriac 'sz_PL', // Silesian 'ta_IN', // Tamil 'te_IN', // Telugu 'tg_TJ', // Tajik 'th_TH', // Thai 'tk_TM', // Turkmen 'tl_PH', // Filipino 'tl_ST', // Klingon 'tr_TR', // Turkish 'tt_RU', // Tatar 'tz_MA', // Tamazight 'uk_UA', // Ukrainian 'ur_PK', // Urdu 'uz_UZ', // Uzbek 'vi_VN', // Vietnamese 'wo_SN', // Wolof 'xh_ZA', // Xhosa 'yi_DE', // Yiddish 'yo_NG', // Yoruba 'zh_CN', // Simplified Chinese (China) 'zh_HK', // Traditional Chinese (Hong Kong) 'zh_TW', // Traditional Chinese (Taiwan) 'zu_ZA', // Zulu 'zz_TR' // Zazaki ); } function fbomatic_language_keys() { return array( 'af', // Afrikaans 'ak', // Akan 'am', // Amharic 'ar', // Arabic 'as', // Assamese 'ay', // Aymara 'az', // Azerbaijani 'be', // Belarusian 'bg', // Bulgarian 'bn', // Bengali 'br', // Breton 'bs', // Bosnian 'ca', // Catalan 'cb', // Sorani Kurdish 'ck', // Cherokee 'co', // Corsican 'cs', // Czech 'cx', // Cebuano 'cy', // Welsh 'da', // Danish 'de', // German 'el', // Greek 'en', // English (UK) 'en', // English (India) 'en', // English (Pirate) 'en', // English (Upside Down) 'en', // English (US) 'eo', // Esperanto 'es', // Spanish (Chile) 'es', // Spanish (Colombia) 'es', // Spanish (Spain) 'es', // Spanish 'es', // Spanish (Mexico) 'es', // Spanish (Venezuela) 'et', // Estonian 'eu', // Basque 'fa', // Persian 'fb', // Leet Speak 'ff', // Fulah 'fi', // Finnish 'fo', // Faroese 'fr', // French (Canada) 'fr', // French (France) 'fy', // Frisian 'ga', // Irish 'gl', // Galician 'gn', // Guarani 'gu', // Gujarati 'gx', // Classical Greek 'ha', // Hausa 'he', // Hebrew 'hi', // Hindi 'hr', // Croatian 'hu', // Hungarian 'hy', // Armenian 'id', // Indonesian 'ig', // Igbo 'is', // Icelandic 'it', // Italian 'ja', // Japanese 'ja', // Japanese (Kansai) 'jv', // Javanese 'ka', // Georgian 'kk', // Kazakh 'km', // Khmer 'kn', // Kannada 'ko', // Korean 'ku', // Kurdish (Kurmanji) 'ky', // Kyrgyz 'la', // Latin 'lg', // Ganda 'li', // Limburgish 'ln', // Lingala 'lo', // Lao 'lt', // Lithuanian 'lv', // Latvian 'mg', // Malagasy 'mi', // Maori 'mk', // Macedonian 'ml', // Malayalam 'mn', // Mongolian 'mr', // Marathi 'ms', // Malay 'mt', // Maltese 'my', // Burmese 'nb', // Norwegian (bokmal) 'nd', // Ndebele 'ne', // Nepali 'nl', // Dutch (Belgi??) 'nl', // Dutch 'nn', // Norwegian (nynorsk) 'ny', // Chewa 'or', // Oriya 'pa', // Punjabi 'pl', // Polish 'ps', // Pashto 'pt', // Portuguese (Brazil) 'pt', // Portuguese (Portugal) 'qu', // Quechua 'rm', // Romansh 'ro', // Romanian 'ru', // Russian 'rw', // Kinyarwanda 'sa', // Sanskrit 'sc', // Sardinian 'se', // Northern S??mi 'si', // Sinhala 'sk', // Slovak 'sl', // Slovenian 'sn', // Shona 'so', // Somali 'sq', // Albanian 'sr', // Serbian 'sv', // Swedish 'sy', // Swahili 'sw', // Syriac 'sz', // Silesian 'ta', // Tamil 'te', // Telugu 'tg', // Tajik 'th', // Thai 'tk', // Turkmen 'tl', // Filipino 'tl', // Klingon 'tr', // Turkish 'tt', // Tatar 'tz', // Tamazight 'uk', // Ukrainian 'ur', // Urdu 'uz', // Uzbek 'vi', // Vietnamese 'wo', // Wolof 'xh', // Xhosa 'yi', // Yiddish 'yo', // Yoruba 'zh', // Simplified Chinese (China) 'zh', // Traditional Chinese (Hong Kong) 'zh', // Traditional Chinese (Taiwan) 'zu', // Zulu 'zz' // Zazaki ); } ?>
Save File
Cancel