function cfNoKsesOnImport()
{
    //Only if administrator:
    if (current_user_can('manage_options')) {
        kses_remove_filters();
    }
}
 public function allow_unfiltered($value)
 {
     global $post;
     if (isset($post->post_type) && $this->cpt->post_type == $post->post_type && current_user_can('edit_posts')) {
         kses_remove_filters();
     }
     return $value;
 }
Example #3
0
 function unfilter_check($allcaps, $caps, $args)
 {
     global $psts;
     if (is_super_admin()) {
         return;
     }
     if (is_pro_site(false, $psts->get_setting('uh_level', 1)) || $this->ads_unfilter()) {
         $allcaps['unfiltered_html'] = true;
         kses_remove_filters();
     } else {
         unset($allcaps['unfiltered_html']);
     }
     return $allcaps;
 }
Example #4
0
function ajax_comment()
{
    global $wpdb;
    $comment_post_ID = isset($_POST['comment_post_ID']) ? (int) $_POST['comment_post_ID'] : 0;
    $post = get_post($comment_post_ID);
    if (empty($post->comment_status)) {
        do_action('comment_id_not_found', $comment_post_ID);
        ajax_comment_err(__('Invalid comment status.'));
    }
    $status = get_post_status($post);
    $status_obj = get_post_status_object($status);
    if (!comments_open($comment_post_ID)) {
        do_action('comment_closed', $comment_post_ID);
        ajax_comment_err(__('Sorry, comments are closed for this item.'));
    } elseif ('trash' == $status) {
        do_action('comment_on_trash', $comment_post_ID);
        ajax_comment_err(__('Invalid comment status.'));
    } elseif (!$status_obj->public && !$status_obj->private) {
        do_action('comment_on_draft', $comment_post_ID);
        ajax_comment_err(__('Invalid comment status.'));
    } elseif (post_password_required($comment_post_ID)) {
        do_action('comment_on_password_protected', $comment_post_ID);
        ajax_comment_err(__('Password Protected'));
    } else {
        do_action('pre_comment_on_post', $comment_post_ID);
    }
    $comment_author = isset($_POST['author']) ? trim(strip_tags($_POST['author'])) : null;
    $comment_author_email = isset($_POST['email']) ? trim($_POST['email']) : null;
    $comment_author_url = isset($_POST['url']) ? trim($_POST['url']) : null;
    $comment_content = isset($_POST['comment']) ? trim($_POST['comment']) : null;
    $user = wp_get_current_user();
    if ($user->exists()) {
        if (empty($user->display_name)) {
            $user->display_name = $user->user_login;
        }
        $comment_author = $wpdb->escape($user->display_name);
        $comment_author_email = $wpdb->escape($user->user_email);
        $comment_author_url = $wpdb->escape($user->user_url);
        $user_ID = $wpdb->escape($user->ID);
        if (current_user_can('unfiltered_html')) {
            if (wp_create_nonce('unfiltered-html-comment_' . $comment_post_ID) != $_POST['_wp_unfiltered_html_comment']) {
                kses_remove_filters();
                kses_init_filters();
            }
        }
    } else {
        if (get_option('comment_registration') || 'private' == $status) {
            ajax_comment_err('对不起,您必须登录后才能进行评论');
        }
    }
    $comment_type = '';
    if (get_option('require_name_email') && !$user->exists()) {
        if (6 > strlen($comment_author_email) || '' == $comment_author) {
            ajax_comment_err('错误: 请填写如下信息 (姓名, 电子邮件)');
        } elseif (!is_email($comment_author_email)) {
            ajax_comment_err('错误: 请输入正确的邮件地址');
        }
    }
    if ('' == $comment_content) {
        ajax_comment_err('请输入回复内容');
    }
    $dupe = "SELECT comment_ID FROM {$wpdb->comments} WHERE comment_post_ID = '{$comment_post_ID}' AND ( comment_author = '{$comment_author}' ";
    if ($comment_author_email) {
        $dupe .= "OR comment_author_email = '{$comment_author_email}' ";
    }
    $dupe .= ") AND comment_content = '{$comment_content}' LIMIT 1";
    if ($wpdb->get_var($dupe)) {
        ajax_comment_err('重复回复,貌似您已经回复过该信息');
    }
    if ($lasttime = $wpdb->get_var($wpdb->prepare("SELECT comment_date_gmt FROM {$wpdb->comments} WHERE comment_author = %s ORDER BY comment_date DESC LIMIT 1", $comment_author))) {
        $time_lastcomment = mysql2date('U', $lasttime, false);
        $time_newcomment = mysql2date('U', current_time('mysql', 1), false);
        $flood_die = apply_filters('comment_flood_filter', false, $time_lastcomment, $time_newcomment);
        if ($flood_die) {
            ajax_comment_err('您回复速度太快了,请稍后在进行回复');
        }
    }
    $comment_parent = isset($_POST['comment_parent']) ? absint($_POST['comment_parent']) : 0;
    $commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_content', 'comment_type', 'comment_parent', 'user_ID');
    $comment_id = wp_new_comment($commentdata);
    $comment = get_comment($comment_id);
    do_action('set_comment_cookies', $comment, $user);
    $comment_depth = 1;
    $tmp_c = $comment;
    while ($tmp_c->comment_parent != 0) {
        $comment_depth++;
        $tmp_c = get_comment($tmp_c->comment_parent);
    }
    $GLOBALS['comment'] = $comment;
    //your comments here	edit start
    ?>
<li class="comments" <?php 
    comment_class(empty($args['has_children']) ? '' : 'parent');
    ?>
 id="li-comment-<?php 
    comment_ID();
    ?>
">
    <div id="comment-<?php 
    comment_ID();
    ?>
" class="comment-wrap">
        <div class="comment-author pull-left">
        <?php 
    echo get_avatar($comment, 50);
    ?>
        </div>
        <div class="comment-body">
            <h4>
                <?php 
    printf('<cite class="fn">%1$s %2$s</cite>', get_comment_author_link(), $comment->user_id === $post->post_author ? '<small class="label label-primary">博主</small>' : '');
    ?>
                <span class="comment-date">
                    刚刚
                </span>
            </h4>
            <?php 
    if ($comment->comment_approved == '0') {
        ?>
                <p class="comment-awaiting-moderation text-danger"><?php 
        echo "您的评论正在等待审核";
        ?>
</p>
            <?php 
    }
    ?>
            <?php 
    comment_text();
    ?>
        </div>
    </div>
    <?php 
    die;
}
Example #5
0
function ajax_comment_callback()
{
    global $wpdb;
    $comment_post_ID = isset($_POST['comment_post_ID']) ? (int) $_POST['comment_post_ID'] : 0;
    $post = get_post($comment_post_ID);
    $post_author = $post->post_author;
    if (empty($post->comment_status)) {
        do_action('comment_id_not_found', $comment_post_ID);
        ajax_comment_err('Invalid comment status.');
    }
    $status = get_post_status($post);
    $status_obj = get_post_status_object($status);
    if (!comments_open($comment_post_ID)) {
        do_action('comment_closed', $comment_post_ID);
        ajax_comment_err('Sorry, comments are closed for this item.');
    } elseif ('trash' == $status) {
        do_action('comment_on_trash', $comment_post_ID);
        ajax_comment_err('Invalid comment status.');
    } elseif (!$status_obj->public && !$status_obj->private) {
        do_action('comment_on_draft', $comment_post_ID);
        ajax_comment_err('Invalid comment status.');
    } elseif (post_password_required($comment_post_ID)) {
        do_action('comment_on_password_protected', $comment_post_ID);
        ajax_comment_err('Password Protected');
    } else {
        do_action('pre_comment_on_post', $comment_post_ID);
    }
    $comment_author = isset($_POST['author']) ? trim(strip_tags($_POST['author'])) : null;
    $comment_author_email = isset($_POST['email']) ? trim($_POST['email']) : null;
    $comment_author_url = isset($_POST['url']) ? trim($_POST['url']) : null;
    $comment_content = isset($_POST['comment']) ? trim($_POST['comment']) : null;
    $user = wp_get_current_user();
    if ($user->exists()) {
        if (empty($user->display_name)) {
            $user->display_name = $user->user_login;
        }
        $comment_author = esc_sql($user->display_name);
        $comment_author_email = esc_sql($user->user_email);
        $comment_author_url = esc_sql($user->user_url);
        $user_ID = esc_sql($user->ID);
        if (current_user_can('unfiltered_html')) {
            if (wp_create_nonce('unfiltered-html-comment_' . $comment_post_ID) != $_POST['_wp_unfiltered_html_comment']) {
                kses_remove_filters();
                kses_init_filters();
            }
        }
    } else {
        if (get_option('comment_registration') || 'private' == $status) {
            ajax_comment_err('Sorry, you must be logged in to post a comment.');
        }
    }
    $comment_type = '';
    if (get_option('require_name_email') && !$user->exists()) {
        if (6 > strlen($comment_author_email) || '' == $comment_author) {
            ajax_comment_err('Error: please fill the required fields (name, email).');
        } elseif (!is_email($comment_author_email)) {
            ajax_comment_err('Error: please enter a valid email address.');
        }
    }
    if ('' == $comment_content) {
        ajax_comment_err('Error: please type a comment.');
    }
    $dupe = "SELECT comment_ID FROM {$wpdb->comments} WHERE comment_post_ID = '{$comment_post_ID}' AND ( comment_author = '{$comment_author}' ";
    if ($comment_author_email) {
        $dupe .= "OR comment_author_email = '{$comment_author_email}' ";
    }
    $dupe .= ") AND comment_content = '{$comment_content}' LIMIT 1";
    if ($wpdb->get_var($dupe)) {
        ajax_comment_err('Duplicate comment detected; it looks as though you&#8217;ve already said that!');
    }
    if ($lasttime = $wpdb->get_var($wpdb->prepare("SELECT comment_date_gmt FROM {$wpdb->comments} WHERE comment_author = %s ORDER BY comment_date DESC LIMIT 1", $comment_author))) {
        $time_lastcomment = mysql2date('U', $lasttime, false);
        $time_newcomment = mysql2date('U', current_time('mysql', 1), false);
        $flood_die = apply_filters('comment_flood_filter', false, $time_lastcomment, $time_newcomment);
        if ($flood_die) {
            ajax_comment_err('You are posting comments too quickly.  Slow down.');
        }
    }
    $comment_parent = isset($_POST['comment_parent']) ? absint($_POST['comment_parent']) : 0;
    $commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_content', 'comment_type', 'comment_parent', 'user_ID');
    $comment_id = wp_new_comment($commentdata);
    $comment = get_comment($comment_id);
    do_action('set_comment_cookies', $comment, $user);
    $comment_depth = 1;
    $tmp_c = $comment;
    while ($tmp_c->comment_parent != 0) {
        $comment_depth++;
        $tmp_c = get_comment($tmp_c->comment_parent);
    }
    $GLOBALS['comment'] = $comment;
    //这里修改成你的评论结构
    ?>
    <li <?php 
    comment_class();
    ?>
 id="li-comment-<?php 
    comment_ID();
    ?>
" itemtype="http://schema.org/Comment" itemscope itemprop="comment">
		<div class="comment-holder">
			<div class="pull-left">
				<?php 
    if ($comment->comment_parent > 0) {
        echo get_avatar($comment->comment_author_email, 36);
    } else {
        echo get_avatar($comment->comment_author_email, 64);
    }
    ?>
			</div>
			<div id="comment-<?php 
    comment_ID();
    ?>
" class="comment-body">
				<?php 
    if ($comment->comment_parent > 0) {
        ?>
					<div class="comment-meta small">
						<strong><span itemprop="author"><?php 
        echo get_comment_author_link();
        ?>
</span></strong>
						<span><?php 
        printf(__('%1$s %2$s'), get_comment_date(), get_comment_time());
        ?>
</span>
						<span class="country-flag"><?php 
        if (function_exists("get_useragent")) {
            get_useragent($comment->comment_agent);
        }
        ?>
</span>
					</div>
				<?php 
    } else {
        ?>
					<h4 class="media-heading">
						<span itemprop="author"><?php 
        echo get_comment_author_link();
        ?>
</span> 
					</h4>
					<div class="comment-meta small">
						<span><?php 
        printf(__('%1$s %2$s'), get_comment_date(), get_comment_time());
        ?>
</span>
						<span class="country-flag"><?php 
        if (function_exists("get_useragent")) {
            get_useragent($comment->comment_agent);
        }
        ?>
</span>
					</div>
				<?php 
    }
    ?>
				<div class="comment-main" itemprop="description">
					<?php 
    comment_text();
    ?>
					<?php 
    if ($comment->comment_approved == '0') {
        ?>
						<em><?php 
        _e('Your comment is awaiting moderation.');
        ?>
</em>
					<?php 
    }
    ?>
				</div>
			</div>
		</div>
	</li>
    <?php 
    die;
}
function wp_ajax_replyto_comment($action)
{
    global $wp_list_table, $wpdb;
    check_ajax_referer($action, '_ajax_nonce-replyto-comment');
    set_current_screen('edit-comments');
    $comment_post_ID = (int) $_POST['comment_post_ID'];
    if (!current_user_can('edit_post', $comment_post_ID)) {
        wp_die(-1);
    }
    $status = $wpdb->get_var($wpdb->prepare("SELECT post_status FROM {$wpdb->posts} WHERE ID = %d", $comment_post_ID));
    if (empty($status)) {
        wp_die(1);
    } elseif (in_array($status, array('draft', 'pending', 'trash'))) {
        wp_die(__('ERROR: you are replying to a comment on a draft post.'));
    }
    $user = wp_get_current_user();
    if ($user->ID) {
        $user_ID = $user->ID;
        $comment_author = $wpdb->escape($user->display_name);
        $comment_author_email = $wpdb->escape($user->user_email);
        $comment_author_url = $wpdb->escape($user->user_url);
        $comment_content = trim($_POST['content']);
        if (current_user_can('unfiltered_html')) {
            if (wp_create_nonce('unfiltered-html-comment') != $_POST['_wp_unfiltered_html_comment']) {
                kses_remove_filters();
                // start with a clean slate
                kses_init_filters();
                // set up the filters
            }
        }
    } else {
        wp_die(__('Sorry, you must be logged in to reply to a comment.'));
    }
    if ('' == $comment_content) {
        wp_die(__('ERROR: please type a comment.'));
    }
    $comment_parent = absint($_POST['comment_ID']);
    $comment_auto_approved = false;
    $commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_content', 'comment_type', 'comment_parent', 'user_ID');
    $comment_id = wp_new_comment($commentdata);
    $comment = get_comment($comment_id);
    if (!$comment) {
        wp_die(1);
    }
    $position = isset($_POST['position']) && (int) $_POST['position'] ? (int) $_POST['position'] : '-1';
    // automatically approve parent comment
    if (!empty($_POST['approve_parent'])) {
        $parent = get_comment($comment_parent);
        if ($parent && $parent->comment_approved === '0' && $parent->comment_post_ID == $comment_post_ID) {
            if (wp_set_comment_status($parent->comment_ID, 'approve')) {
                $comment_auto_approved = true;
            }
        }
    }
    ob_start();
    if ('dashboard' == $_REQUEST['mode']) {
        require_once ABSPATH . 'wp-admin/includes/dashboard.php';
        _wp_dashboard_recent_comments_row($comment);
    } else {
        if ('single' == $_REQUEST['mode']) {
            $wp_list_table = _get_list_table('WP_Post_Comments_List_Table');
        } else {
            $wp_list_table = _get_list_table('WP_Comments_List_Table');
        }
        $wp_list_table->single_row($comment);
    }
    $comment_list_item = ob_get_contents();
    ob_end_clean();
    $response = array('what' => 'comment', 'id' => $comment->comment_ID, 'data' => $comment_list_item, 'position' => $position);
    if ($comment_auto_approved) {
        $response['supplemental'] = array('parent_approved' => $parent->comment_ID);
    }
    $x = new WP_Ajax_Response();
    $x->add($response);
    $x->send();
}
Example #7
0
function ajax_comment()
{
    global $wpdb;
    //nocache_headers();
    $comment_post_ID = isset($_POST['comment_post_ID']) ? (int) $_POST['comment_post_ID'] : 0;
    $post = get_post($comment_post_ID);
    $post_author = $post->post_author;
    if (empty($post->comment_status)) {
        do_action('comment_id_not_found', $comment_post_ID);
        ajax_comment_err(__('Invalid comment status.', 'Lophita'));
    }
    $status = get_post_status($post);
    $status_obj = get_post_status_object($status);
    if (!comments_open($comment_post_ID)) {
        do_action('comment_closed', $comment_post_ID);
        ajax_comment_err(__('Sorry, comments are closed for this item.', 'Lophita'));
    } elseif ('trash' == $status) {
        do_action('comment_on_trash', $comment_post_ID);
        ajax_comment_err(__('Invalid comment status.', 'Lophita'));
    } elseif (!$status_obj->public && !$status_obj->private) {
        do_action('comment_on_draft', $comment_post_ID);
        ajax_comment_err(__('Invalid comment status.', 'Lophita'));
    } elseif (post_password_required($comment_post_ID)) {
        do_action('comment_on_password_protected', $comment_post_ID);
        ajax_comment_err(__('Password Protected', 'Lophita'));
    } else {
        do_action('pre_comment_on_post', $comment_post_ID);
    }
    $comment_author = isset($_POST['author']) ? trim(strip_tags($_POST['author'])) : null;
    $comment_author_email = isset($_POST['email']) ? trim($_POST['email']) : null;
    $comment_author_url = isset($_POST['url']) ? trim($_POST['url']) : null;
    $comment_content = isset($_POST['comment']) ? trim($_POST['comment']) : null;
    $edit_id = isset($_POST['edit_id']) ? $_POST['edit_id'] : null;
    $user = wp_get_current_user();
    if ($user->exists()) {
        if (empty($user->display_name)) {
            $user->display_name = $user->user_login;
        }
        $comment_author = $wpdb->escape($user->display_name);
        $comment_author_email = $wpdb->escape($user->user_email);
        $comment_author_url = $wpdb->escape($user->user_url);
        $user_ID = $wpdb->escape($user->ID);
        if (current_user_can('unfiltered_html')) {
            if (wp_create_nonce('unfiltered-html-comment_' . $comment_post_ID) != $_POST['_wp_unfiltered_html_comment']) {
                kses_remove_filters();
                kses_init_filters();
            }
        }
    } else {
        if (get_option('comment_registration') || 'private' == $status) {
            ajax_comment_err(__('Sorry, you must be logged in to post a comment.', 'Lophita'));
        }
    }
    $comment_type = '';
    if (get_option('require_name_email') && !$user->exists()) {
        if (6 > strlen($comment_author_email) || '' == $comment_author) {
            ajax_comment_err(__('Error: please fill the required fields (name, email).', 'Lophita'));
        } elseif (!is_email($comment_author_email)) {
            ajax_comment_err(__('Error: please enter a valid email address.', 'Lophita'));
        }
    }
    if ('' == $comment_content) {
        ajax_comment_err(__('Error: please type a comment.', 'Lophita'));
    }
    $dupe = "SELECT comment_ID FROM {$wpdb->comments} WHERE comment_post_ID = '{$comment_post_ID}' AND ( comment_author = '{$comment_author}' ";
    if ($comment_author_email) {
        $dupe .= "OR comment_author_email = '{$comment_author_email}' ";
    }
    $dupe .= ") AND comment_content = '{$comment_content}' LIMIT 1";
    if ($wpdb->get_var($dupe)) {
        ajax_comment_err(__('Duplicate comment detected; it looks as though you&#8217;ve already said that!', 'Lophita'));
    }
    if ($lasttime = $wpdb->get_var($wpdb->prepare("SELECT comment_date_gmt FROM {$wpdb->comments} WHERE comment_author = %s ORDER BY comment_date DESC LIMIT 1", $comment_author))) {
        $time_lastcomment = mysql2date('U', $lasttime, false);
        $time_newcomment = mysql2date('U', current_time('mysql', 1), false);
        $flood_die = apply_filters('comment_flood_filter', false, $time_lastcomment, $time_newcomment);
        if ($flood_die) {
            ajax_comment_err(__('You are posting comments too quickly.  Slow down.', 'Lophita'));
        }
    }
    $comment_parent = isset($_POST['comment_parent']) ? absint($_POST['comment_parent']) : 0;
    $commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_content', 'comment_type', 'comment_parent', 'user_ID');
    if ($edit_id) {
        $comment_id = $commentdata['comment_ID'] = $edit_id;
        if (ihacklog_user_can_edit_comment($commentdata, $comment_id)) {
            wp_update_comment($commentdata);
        } else {
            ajax_comment_err(__('Cheatin&#8217; uh?', 'Lophita'));
        }
    } else {
        $comment_id = wp_new_comment($commentdata);
    }
    $comment = get_comment($comment_id);
    do_action('set_comment_cookies', $comment, $user);
    $comment_depth = 1;
    $tmp_c = $comment;
    while ($tmp_c->comment_parent != 0) {
        $comment_depth++;
        $tmp_c = get_comment($tmp_c->comment_parent);
    }
    $GLOBALS['comment'] = $comment;
    ?>
<li <?php 
    comment_class();
    ?>
 id="li-comment-<?php 
    comment_ID();
    ?>
">
	<article id="comment-<?php 
    comment_ID();
    ?>
" class="comment-container">
		<div class="comment-header">
			<span class="comment-name"><?php 
    printf(__('%s'), get_comment_author_link());
    ?>
</span>
			<time class="comment-date" datetime="<?php 
    comment_time('Y/m/d H:i:s');
    ?>
"><?php 
    echo time_ago();
    ?>
</time>
		</div>
		<?php 
    if ('0' == $comment->comment_approved) {
        ?>
			<p class="comment-awaiting-moderation">您的评论正在排队等待审核,请稍后再来!</p>
		<?php 
    }
    ?>

		<div class="comment-content">
			<?php 
    comment_text();
    ?>
		</div>
	</article>

    <?php 
    die;
}
Example #8
0
/**
 * Sets up most of the Kses filters for input form content.
 *
 * If you remove the kses_init() function from 'init' hook and
 * 'set_current_user' (priority is default), then none of the Kses filter hooks
 * will be added.
 *
 * First removes all of the Kses filters in case the current user does not need
 * to have Kses filter the content. If the user does not have unfiltered_html
 * capability, then Kses filters are added.
 *
 * @since 2.0.0
 */
function kses_init()
{
    kses_remove_filters();
    if (!current_user_can('unfiltered_html')) {
        kses_init_filters();
    }
}
Example #9
0
    function test_the_content_attribute_value_with_colon()
    {
        kses_init_filters();
        // http://bpr3.org/?p=87
        // the title attribute should make it through unfiltered
        $post_content = <<<EOF
<span title="My friends: Alice, Bob and Carol">foo</span>
EOF;
        $expected = <<<EOF
<p><span title="My friends: Alice, Bob and Carol">foo</span></p>
EOF;
        $post_id = self::factory()->post->create(compact('post_content'));
        $this->go_to(get_permalink($post_id));
        $this->assertTrue(is_single());
        $this->assertTrue(have_posts());
        $this->assertNull(the_post());
        $this->assertEquals(strip_ws($expected), strip_ws(get_echo('the_content')));
        kses_remove_filters();
    }
Example #10
0
 /**
  * Set a specific user context for WordPress.
  *
  * @param array $assoc_args
  */
 private static function set_user($assoc_args)
 {
     if (isset($assoc_args['user'])) {
         $fetcher = new \WP_CLI\Fetchers\User();
         $user = $fetcher->get_check($assoc_args['user']);
         wp_set_current_user($user->ID);
     } else {
         kses_remove_filters();
     }
 }
Example #11
0
	$status = $wpdb->get_var( $wpdb->prepare("SELECT post_status FROM $wpdb->posts WHERE ID = %d", $comment_post_ID) );

	if ( empty($status) )
		die('1');
	elseif ( in_array($status, array('draft', 'pending', 'trash') ) )
		die( __('Error: you are replying to a comment on a draft post.') );

	$user = wp_get_current_user();
	if ( $user->ID ) {
		$comment_author       = $wpdb->escape($user->display_name);
		$comment_author_email = $wpdb->escape($user->user_email);
		$comment_author_url   = $wpdb->escape($user->user_url);
		$comment_content      = trim($_POST['content']);
		if ( current_user_can('unfiltered_html') ) {
			if ( wp_create_nonce('unfiltered-html-comment_' . $comment_post_ID) != $_POST['_wp_unfiltered_html_comment'] ) {
				kses_remove_filters(); // start with a clean slate
				kses_init_filters(); // set up the filters
			}
		}
	} else {
		die( __('Sorry, you must be logged in to reply to a comment.') );
	}

	if ( '' == $comment_content )
		die( __('Error: please type a comment.') );

	$comment_parent = absint($_POST['comment_ID']);
	$commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_content', 'comment_type', 'comment_parent', 'user_ID');

	$comment_id = wp_new_comment( $commentdata );
	$comment = get_comment($comment_id);
 function maybe_override_kses()
 {
     if (!empty($_POST) && !empty($_POST['action']) && 'editpost' == $_POST['action']) {
         if (current_user_can('unfiltered_html')) {
             // initial core cap check in kses_init() is unfilterable
             kses_remove_filters();
         }
     }
 }
Example #13
0
/**
 * Sets up most of the Kses filters for input form content.
 *
 * If you remove the kses_init() function from 'init' hook and
 * 'set_current_user' (priority is default), then none of the Kses filter hooks
 * will be added.
 *
 * First removes all of the Kses filters in case the current user does not need
 * to have Kses filter the content. If the user does not have unfiltered html
 * capability, then Kses filters are added.
 *
 * @uses kses_remove_filters() Removes the Kses filters
 * @uses kses_init_filters() Adds the Kses filters back if the user
 *		does not have unfiltered HTML capability.
 * @since 2.0.0
 */
function kses_init()
{
    global $allowedposttags, $allowedtags;
    $allowedposttags = apply_filters('edit_allowedposttags', $allowedposttags);
    $allowedtags = apply_filters('edit_allowedtags', $allowedtags);
    kses_remove_filters();
    kses_init_filters();
}
function ajax_comment_callback()
{
    global $wpdb;
    $comment_post_ID = isset($_POST['comment_post_ID']) ? (int) $_POST['comment_post_ID'] : 0;
    $post = get_post($comment_post_ID);
    $post_author = $post->post_author;
    if (empty($post->comment_status)) {
        do_action('comment_id_not_found', $comment_post_ID);
        ajax_comment_err('异常操作.');
    }
    $status = get_post_status($post);
    $status_obj = get_post_status_object($status);
    if (!comments_open($comment_post_ID)) {
        do_action('comment_closed', $comment_post_ID);
        ajax_comment_err('对不起,评论已经关闭');
    } elseif ('trash' == $status) {
        do_action('comment_on_trash', $comment_post_ID);
        ajax_comment_err('对此条评论的回复功能暂不可用.');
    } elseif (!$status_obj->public && !$status_obj->private) {
        do_action('comment_on_draft', $comment_post_ID);
        ajax_comment_err('对此条评论的回复功能暂不可用..');
    } elseif (post_password_required($comment_post_ID)) {
        do_action('comment_on_password_protected', $comment_post_ID);
        ajax_comment_err('文章受到密码保护');
    } else {
        do_action('pre_comment_on_post', $comment_post_ID);
    }
    $comment_author = isset($_POST['author']) ? trim(strip_tags($_POST['author'])) : null;
    $comment_author_email = isset($_POST['email']) ? trim($_POST['email']) : null;
    $comment_author_url = isset($_POST['url']) ? trim($_POST['url']) : null;
    $comment_content = isset($_POST['comment']) ? trim($_POST['comment']) : null;
    $user = wp_get_current_user();
    if ($user->exists()) {
        if (empty($user->display_name)) {
            $user->display_name = $user->user_login;
        }
        $comment_author = esc_sql($user->display_name);
        $comment_author_email = esc_sql($user->user_email);
        $comment_author_url = esc_sql($user->user_url);
        $user_ID = esc_sql($user->ID);
        if (current_user_can('unfiltered_html')) {
            if (wp_create_nonce('unfiltered-html-comment_' . $comment_post_ID) != $_POST['_wp_unfiltered_html_comment']) {
                kses_remove_filters();
                kses_init_filters();
            }
        }
    } else {
        if (get_option('comment_registration') || 'private' == $status) {
            ajax_comment_err('错误:你必须登陆以添加评论.');
        }
    }
    $comment_type = '';
    if (get_option('require_name_email') && !$user->exists()) {
        if (6 > strlen($comment_author_email) || '' == $comment_author) {
            ajax_comment_err('错误:至少需要填写有效的名字与邮箱地址.');
        } elseif (!is_email($comment_author_email)) {
            ajax_comment_err('错误:邮箱地址无效.');
        }
    }
    if ('' == $comment_content) {
        ajax_comment_err('错误:忘写评论内容了?');
    }
    $dupe = "SELECT comment_ID FROM {$wpdb->comments} WHERE comment_post_ID = '{$comment_post_ID}' AND ( comment_author = '{$comment_author}' ";
    if ($comment_author_email) {
        $dupe .= "OR comment_author_email = '{$comment_author_email}' ";
    }
    $dupe .= ") AND comment_content = '{$comment_content}' LIMIT 1";
    if ($wpdb->get_var($dupe)) {
        ajax_comment_err('错误:检测到重复评论,说明您已经递交过相同内容.');
    }
    if ($lasttime = $wpdb->get_var($wpdb->prepare("SELECT comment_date_gmt FROM {$wpdb->comments} WHERE comment_author = %s ORDER BY comment_date DESC LIMIT 1", $comment_author))) {
        $time_lastcomment = mysql2date('U', $lasttime, false);
        $time_newcomment = mysql2date('U', current_time('mysql', 1), false);
        $flood_die = apply_filters('comment_flood_filter', false, $time_lastcomment, $time_newcomment);
        if ($flood_die) {
            ajax_comment_err('错误:评论递交频率太快.');
        }
    }
    $comment_parent = isset($_POST['comment_parent']) ? absint($_POST['comment_parent']) : 0;
    $commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_content', 'comment_type', 'comment_parent', 'user_ID');
    $comment_id = wp_new_comment($commentdata);
    $comment = get_comment($comment_id);
    do_action('set_comment_cookies', $comment, $user);
    $comment_depth = 1;
    $tmp_c = $comment;
    while ($tmp_c->comment_parent != 0) {
        $comment_depth++;
        $tmp_c = get_comment($tmp_c->comment_parent);
    }
    $GLOBALS['comment'] = $comment;
    //这里修改成你的评论结构
    ?>
    <li <?php 
    comment_class();
    ?>
>
        <article class="comment-body clear">
            <footer class="comment-meta">
                <div class="comment-author vcard">
                    <?php 
    echo get_avatar($comment, $size = '48');
    ?>
                </div>
                <div class="comment-metadata">
                    <b class="fn">
                        <?php 
    echo get_comment_author_link();
    ?>
                    </b>
                    <span class="attime">在 </span><time class="comment-time" datetime="<?php 
    echo get_comment_date('Y-M-d G:i');
    ?>
"><?php 
    echo get_comment_date('Y-M-d G:i');
    ?>
</time><span class="says"> 说:</span>
                </div>
            </footer>
            <div class="comment-content">
                <?php 
    comment_text();
    ?>
            </div>
            <br/>
        </article>
    </li>
    <?php 
    die;
}
 function save_post_translation($translation_id, $translation)
 {
     global $wpdb, $sitepress_settings, $sitepress, $icl_adjust_id_url_filter_off;
     $icl_adjust_id_url_filter_off = true;
     $translation_info = $wpdb->get_row($wpdb->prepare("\n                SELECT * FROM {$wpdb->prefix}icl_translations tr\n                    JOIN {$wpdb->prefix}icl_translation_status ts ON ts.translation_id = tr.translation_id\n                WHERE tr.translation_id=%d", $translation_id));
     $lang_code = $translation_info->language_code;
     $trid = $translation_info->trid;
     $original_post_details = $wpdb->get_row("\n            SELECT p.post_author, p.post_type, p.post_status, p.comment_status, p.ping_status, p.post_parent, p.menu_order, p.post_date, t.language_code\n            FROM {$wpdb->prefix}icl_translations t \n            JOIN {$wpdb->posts} p ON t.element_id = p.ID AND CONCAT('post_',p.post_type) = t.element_type\n            WHERE trid='{$trid}' AND p.ID = '{$translation['original_id']}'\n        ");
     //is the original post a sticky post?
     $sticky_posts = get_option('sticky_posts');
     $is_original_sticky = $original_post_details->post_type == 'post' && in_array($translation['original_id'], $sticky_posts);
     $this->_content_fix_image_paths_in_body($translation);
     $this->_content_fix_relative_link_paths_in_body($translation);
     $this->_content_decode_shortcodes($translation);
     // handle the page parent and set it to the translated parent if we have one.
     if ($original_post_details->post_parent) {
         $post_parent_trid = $wpdb->get_var($wpdb->prepare("\tSELECT trid\n\t\t\t\t\t\tFROM {$wpdb->prefix}icl_translations\n\t\t\t\t\t\tWHERE element_type= %s AND element_id = %d ", 'post_' . $original_post_details->post_type, $original_post_details->post_parent));
         if ($post_parent_trid) {
             $parent_id = $wpdb->get_var($wpdb->prepare("SELECT element_id\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t FROM {$wpdb->prefix}icl_translations\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t WHERE element_type = %s\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  AND trid = %d\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  AND language_code = %s ", 'post_' . $original_post_details->post_type, $post_parent_trid, $lang_code));
         }
     }
     // determine post id based on trid
     $post_id = $translation_info->element_id;
     if ($post_id) {
         // see if the post really exists - make sure it wasn't deleted while the plugin was
         if (!$wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->posts} WHERE ID = %d ", $post_id))) {
             $is_update = false;
             $q = "DELETE FROM {$wpdb->prefix}icl_translations WHERE element_type=%s AND element_id=%d";
             $q_prepared = $wpdb->prepare($q, array('post_' . $original_post_details->post_type, $post_id));
             $wpdb->query($q_prepared);
         } else {
             $is_update = true;
             $postarr['ID'] = $_POST['post_ID'] = $post_id;
         }
     } else {
         $is_update = false;
     }
     $postarr['post_title'] = $translation['title'];
     if ($sitepress_settings['translated_document_page_url'] == 'translate' && isset($translation['URL'])) {
         $postarr['post_name'] = $translation['URL'];
     }
     $postarr['post_content'] = $translation['body'];
     if (isset($translation['excerpt']) && $translation['excerpt'] != "") {
         $postarr['post_excerpt'] = $translation['excerpt'];
     }
     if (isset($translated_taxonomies) && is_array($translated_taxonomies)) {
         foreach ($translated_taxonomies as $taxonomy => $values) {
             $postarr['tax_input'][$taxonomy] = join(',', (array) $values);
         }
     }
     $postarr['post_author'] = $original_post_details->post_author;
     $postarr['post_type'] = $original_post_details->post_type;
     if ($sitepress_settings['sync_comment_status']) {
         $postarr['comment_status'] = $original_post_details->comment_status;
     }
     if ($sitepress_settings['sync_ping_status']) {
         $postarr['ping_status'] = $original_post_details->ping_status;
     }
     if ($sitepress_settings['sync_page_ordering']) {
         $postarr['menu_order'] = $original_post_details->menu_order;
     }
     if ($sitepress_settings['sync_private_flag'] && $original_post_details->post_status == 'private') {
         $postarr['post_status'] = 'private';
     }
     if (!$is_update) {
         $postarr['post_status'] = !$sitepress_settings['translated_document_status'] ? 'draft' : $original_post_details->post_status;
     } else {
         // set post_status to the current post status.
         $postarr['post_status'] = $wpdb->get_var($wpdb->prepare("SELECT post_status\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t FROM {$wpdb->prefix}posts\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t WHERE ID = %d ", $post_id));
     }
     if ($sitepress_settings['sync_post_date']) {
         $postarr['post_date'] = $original_post_details->post_date;
     }
     if (isset($parent_id) && $sitepress_settings['sync_page_parent']) {
         $_POST['post_parent'] = $postarr['post_parent'] = $parent_id;
         $_POST['parent_id'] = $postarr['parent_id'] = $parent_id;
     }
     if ($is_update) {
         $postarr['post_name'] = $wpdb->get_var($wpdb->prepare("SELECT post_name FROM {$wpdb->posts} WHERE ID=%d", $post_id));
     }
     $_POST['trid'] = $trid;
     $_POST['lang'] = $lang_code;
     $_POST['skip_sitepress_actions'] = true;
     global $wp_rewrite;
     if (!isset($wp_rewrite)) {
         $wp_rewrite = new WP_Rewrite();
     }
     kses_remove_filters();
     $postarr = apply_filters('icl_pre_save_pro_translation', $postarr);
     $new_post_id = wp_insert_post($postarr);
     do_action('icl_pro_translation_saved', $new_post_id);
     // set stickiness
     if ($is_original_sticky && $sitepress_settings['sync_sticky_flag']) {
         stick_post($new_post_id);
     } else {
         if ($original_post_details->post_type == 'post' && $is_update) {
             unstick_post($new_post_id);
             //just in case - if this is an update and the original post stckiness has changed since the post was sent to translation
         }
     }
     foreach ((array) $sitepress_settings['translation-management']['custom_fields_translation'] as $cf => $op) {
         if ($op == 1) {
             $sitepress->_sync_custom_field($translation['original_id'], $new_post_id, $cf);
         } elseif ($op == 2 && isset($translation['field-' . $cf])) {
             $field_translation = $translation['field-' . $cf];
             $field_type = $translation['field-' . $cf . '-type'];
             if ($field_type == 'custom_field') {
                 $field_translation = str_replace('&#0A;', "\n", $field_translation);
                 // always decode html entities  eg decode &amp; to &
                 $field_translation = html_entity_decode($field_translation);
                 update_post_meta($new_post_id, $cf, $field_translation);
             }
         }
     }
     // set specific custom fields
     $copied_custom_fields = array('_top_nav_excluded', '_cms_nav_minihome');
     foreach ($copied_custom_fields as $ccf) {
         $val = get_post_meta($translation['original_id'], $ccf, true);
         update_post_meta($new_post_id, $ccf, $val);
     }
     // sync _wp_page_template
     if ($sitepress_settings['sync_page_template']) {
         $_wp_page_template = get_post_meta($translation['original_id'], '_wp_page_template', true);
         update_post_meta($new_post_id, '_wp_page_template', $_wp_page_template);
     }
     // sync post format
     if ($sitepress_settings['sync_post_format']) {
         $_wp_post_format = get_post_format($translation['original_id']);
         set_post_format($new_post_id, $_wp_post_format);
     }
     if (!$new_post_id) {
         return false;
     }
     if (!$is_update) {
         $wpdb->update($wpdb->prefix . 'icl_translations', array('element_id' => $new_post_id), array('translation_id' => $translation_id));
     }
     update_post_meta($new_post_id, '_icl_translation', 1);
     TranslationManagement::set_page_url($new_post_id);
     global $iclTranslationManagement;
     $ts = array('status' => ICL_TM_COMPLETE, 'needs_update' => 0, 'translation_id' => $translation_id);
     $translator_id = $wpdb->get_var($wpdb->prepare("SELECT translator_id FROM {$wpdb->prefix}icl_translation_status WHERE translation_id=%d", $translation_id));
     if (!$translator_id) {
         $lang_status = TranslationProxy_Translator::get_language_pairs();
         foreach ($lang_status as $languages_pair) {
             if ($languages_pair['from'] == $original_post_details->language_code && $languages_pair['to'] == $lang_code && isset($languages_pair['translators'][0]['id'])) {
                 $ts['translator_id'] = $languages_pair['translators'][0]['id'];
                 break;
             }
         }
     }
     // update translation status
     $iclTranslationManagement->update_translation_status($ts);
     // add new translation job
     //$translation_package = $iclTranslationManagement->create_translation_package(get_post($translation['original_id']));
     //$job_id = $iclTranslationManagement->add_translation_job($translation_info->rid, $translation_info->translator_id, $translation_package);
     $job_id = $iclTranslationManagement->get_translation_job_id($trid, $lang_code);
     // save the translation
     $iclTranslationManagement->mark_job_done($job_id);
     $parts = explode('_', $translation['original_id']);
     if ($parts[0] != 'external') {
         $iclTranslationManagement->save_job_fields_from_post($job_id, get_post($new_post_id));
         $this->_content_fix_links_to_translated_content($new_post_id, $lang_code, "post_{$original_post_details->post_type}");
         // Now try to fix links in other translated content that may link to this post.
         $sql = "SELECT\n                        tr.element_id\n                    FROM\n                        {$wpdb->prefix}icl_translations tr\n                    JOIN\n                        {$wpdb->prefix}icl_translation_status ts\n                    ON\n                        tr.translation_id = ts.translation_id\n                    WHERE\n                        ts.links_fixed = 0 AND tr.element_type = %s AND tr.language_code = %s AND tr.element_id IS NOT NULL";
         $sql_prepared = $wpdb->prepare($sql, array('post_' . $original_post_details->post_type, $lang_code));
         $needs_fixing = $wpdb->get_results($sql_prepared);
         foreach ($needs_fixing as $id) {
             if ($id->element_id != $new_post_id) {
                 // fix all except the new_post_id. We have already done this.
                 $this->_content_fix_links_to_translated_content($id->element_id, $lang_code, "post_{$original_post_details->post_type}");
             }
         }
         // if this is a parent page then make sure it's children point to this.
         $this->fix_translated_children($translation['original_id'], $new_post_id, $lang_code);
     }
     WPML_Translation_Job_Terms::save_terms_from_job($job_id, $lang_code);
     do_action('icl_pro_translation_completed', $new_post_id);
     return true;
 }
Example #16
0
function angela_ajax_comment()
{
    if ($_SERVER['REQUEST_METHOD'] == "POST") {
        global $wpdb;
        nocache_headers();
        $comment_post_ID = isset($_POST['comment_post_ID']) ? (int) $_POST['comment_post_ID'] : 0;
        $post = get_post($comment_post_ID);
        if (empty($post->comment_status)) {
            do_action('comment_id_not_found', $comment_post_ID);
            angela_ajax_error(__('Invalid comment status.'));
            // 將 exit 改為錯誤提示
        }
        // get_post_status() will get the parent status for attachments.
        $status = get_post_status($post);
        $status_obj = get_post_status_object($status);
        if (!comments_open($comment_post_ID)) {
            do_action('comment_closed', $comment_post_ID);
            angela_ajax_error(__('评论已关闭!'));
            // 將 wp_die 改為錯誤提示
        } elseif ('trash' == $status) {
            do_action('comment_on_trash', $comment_post_ID);
            angela_ajax_error(__('Invalid comment status.'));
            // 將 exit 改為錯誤提示
        } elseif (!$status_obj->public && !$status_obj->private) {
            do_action('comment_on_draft', $comment_post_ID);
            angela_ajax_error(__('Invalid comment status.'));
            // 將 exit 改為錯誤提示
        } elseif (post_password_required($comment_post_ID)) {
            do_action('comment_on_password_protected', $comment_post_ID);
            angela_ajax_error(__('Password Protected'));
            // 將 exit 改為錯誤提示
        } else {
            do_action('pre_comment_on_post', $comment_post_ID);
        }
        $comment_author = isset($_POST['author']) ? trim(strip_tags($_POST['author'])) : null;
        $comment_author_email = isset($_POST['email']) ? trim($_POST['email']) : null;
        $comment_author_url = isset($_POST['url']) ? trim($_POST['url']) : null;
        $comment_content = isset($_POST['comment']) ? trim($_POST['comment']) : null;
        $user_id = null;
        // If the user is logged in
        $user = wp_get_current_user();
        if ($user->exists()) {
            if (empty($user->display_name)) {
                $user->display_name = $user->user_login;
            }
            $comment_author = $wpdb->escape($user->display_name);
            $comment_author_email = $wpdb->escape($user->user_email);
            $comment_author_url = $wpdb->escape($user->user_url);
            $user_id = $user->ID;
            if (current_user_can('unfiltered_html')) {
                if (wp_create_nonce('unfiltered-html-comment_' . $comment_post_ID) != $_POST['_wp_unfiltered_html_comment']) {
                    kses_remove_filters();
                    // start with a clean slate
                    kses_init_filters();
                    // set up the filters
                }
            }
        } else {
            if (get_option('comment_registration') || 'private' == $status) {
                angela_ajax_error(__('你必须要登陆之后才可以发表评论.'));
            }
            // 將 wp_die 改為錯誤提示
        }
        $comment_type = '';
        if (get_option('require_name_email') && !$user->exists()) {
            if (6 > strlen($comment_author_email) || '' == $comment_author) {
                angela_ajax_error(__('请填写昵称和邮箱.'));
            } elseif (!is_email($comment_author_email)) {
                angela_ajax_error(__('请填写一个有效的邮箱.'));
            }
            // 將 wp_die 改為錯誤提示
        }
        if ('' == $comment_content) {
            angela_ajax_error(__('请输入评论.'));
        }
        // 將 wp_die 改為錯誤提示
        if (!$user_id) {
            // 增加: 檢查重覆評論功能
            $dupe = "SELECT comment_ID FROM {$wpdb->comments} WHERE comment_post_ID = '{$comment_post_ID}' AND ( comment_author = '{$comment_author}' ";
            if ($comment_author_email) {
                $dupe .= "OR comment_author_email = '{$comment_author_email}' ";
            }
            $dupe .= ") AND comment_content = '{$comment_content}' LIMIT 1";
            if ($wpdb->get_var($dupe)) {
                do_action('comment_duplicate_trigger', $comment_post_ID);
                angela_ajax_error(__('您已经发布过一条相同的评论!'));
            }
            // 增加: 檢查評論太快功能
            if ($lasttime = $wpdb->get_var($wpdb->prepare("SELECT comment_date_gmt FROM {$wpdb->comments} WHERE comment_author = %s ORDER BY comment_date DESC LIMIT 1", $comment_author))) {
                $time_lastcomment = mysql2date('U', $lasttime, false);
                $time_newcomment = mysql2date('U', current_time('mysql', 1), false);
                $flood_die = apply_filters('comment_flood_filter', false, $time_lastcomment, $time_newcomment);
                if ($flood_die) {
                    angela_ajax_error(__('请过一会再发表评论.'));
                }
            }
        }
        $comment_parent = isset($_POST['comment_parent']) ? absint($_POST['comment_parent']) : 0;
        $commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_content', 'comment_type', 'comment_parent', 'user_id');
        // 新建評論
        $comment_id = wp_new_comment($commentdata);
        $comment = get_comment($comment_id);
        do_action('set_comment_cookies', $comment, $user);
        $comment_depth = 1;
        //为评论的 class 属性准备的
        $tmp_c = $comment;
        while ($tmp_c->comment_parent != 0) {
            $comment_depth++;
            $tmp_c = get_comment($tmp_c->comment_parent);
        }
        //此处非常必要,无此处下面的评论无法输出 by mufeng
        $GLOBALS['comment'] = $comment;
        ?>
        <li id="comment-<?php 
        comment_ID();
        ?>
" <?php 
        comment_class('commenttips', $comment_id, $comment_post_ID);
        ?>
 >
        <div class="comment-body">
            <div class="comment-avatar">
                <?php 
        echo get_avatar(get_comment_author_email(), '40');
        ?>
            </div>
            <div class="comment-meta">
                <span class="comment-id"><?php 
        comment_author_link();
        ?>
</span>
                <span class="comment-time">评论于<?php 
        echo angela_time_ago(abs(strtotime($comment->comment_date_gmt . "GMT")), true);
        ?>
</span>
            </div>
            <div class="comment-text">
                <?php 
        if ($comment->comment_approved == '0') {
            ?>
                    <?php 
            _e('<p class="comment-warning">Your comment is awaiting moderation.</p>');
            ?>
                <?php 
        }
        ?>
                <?php 
        comment_text();
        //edit_comment_link(' <编辑> ');
        ?>
            </div>
        </div>
        <?php 
        die;
        //以上是評論式樣, 不含 "回覆". 要用你模板的式樣 copy 覆蓋.
    }
}
 public function create_post($post)
 {
     $post = apply_filters('oxy_one_click_post', $post, $this);
     $old_id = $post['ID'];
     unset($post['ID']);
     unset($post['guid']);
     unset($post['post_parent']);
     // make sure wp_insert_post doesnt filter the post content ( adds p tags and shit )
     $post['filter'] = true;
     kses_remove_filters();
     $new_id = wp_insert_post($post);
     kses_init_filters();
     $this->add_to_map($post['post_type'], $old_id, $new_id);
     // handle custom fields
     if (isset($post['custom_fields'])) {
         foreach ($post['custom_fields'] as $key => $value) {
             $add_field = false;
             switch ($key) {
                 case '_thumbnail_id':
                     foreach ($value as $old_media_id) {
                         $new_media_id = $this->lookup_map('attachments', $old_media_id);
                         if ($new_media_id !== false) {
                             add_post_meta($new_id, '_thumbnail_id', $new_media_id);
                         }
                     }
                     break;
                 case '_product_image_gallery':
                     $old_media_ids = explode(',', $value[0]);
                     $new_media_ids = array();
                     foreach ($old_media_ids as $old_media_id) {
                         $new_media_id = $this->lookup_map('attachments', $old_media_id);
                         if ($new_media_id !== false) {
                             $new_media_ids[] = $new_media_id;
                         }
                     }
                     if (count($new_media_id) > 0) {
                         add_post_meta($new_id, '_product_image_gallery', implode(',', $new_media_ids));
                     }
                     break;
                 case THEME_SHORT . '_post_gallery':
                     foreach ($value as $post_gallery) {
                         $post_gallery = $this->replace_gallery_shortcode_ids($post_gallery);
                         add_post_meta($new_id, $key, $post_gallery);
                     }
                     break;
                 case '_edit_last':
                     // ignore
                     break;
                 case THEME_SHORT . '_masonry_image':
                 case THEME_SHORT . '_background_image':
                     // get the new url of the image
                     $new_url = $this->lookup_map('images', $value[0]);
                     add_post_meta($new_id, $key, $new_url);
                     break;
                 default:
                     $add_field = true;
                     break;
             }
             if ($add_field) {
                 foreach ($value as $old_value) {
                     add_post_meta($new_id, $key, $old_value);
                 }
             }
         }
     }
     if (isset($post['taxonomies'])) {
         $taxonomies = get_taxonomies();
         foreach ($taxonomies as $taxonomy) {
             if (isset($post['taxonomies'][$taxonomy])) {
                 foreach ($post['taxonomies'][$taxonomy] as $old_tax) {
                     $term_id = term_exists($old_tax['slug'], $taxonomy);
                     // if tag doesnt exist we must create it
                     if (!$term_id) {
                         $new_tag_args = array('slug' => $old_tax['slug'], 'description' => $old_tax['description']);
                         if ($old_tax['parent'] !== 0) {
                             $new_tag_args['parent'] = $this->lookup_map($taxonomy, $old_tax['term_id']);
                         }
                         $term_id = wp_insert_term($old_tax['name'], $taxonomy, $new_tag_args);
                     }
                     if (!is_wp_error($term_id)) {
                         if (is_array($term_id)) {
                             $term_id = $term_id['term_id'];
                         }
                         // store old / new term id in map
                         $this->add_to_map($taxonomy, $old_tax['term_id'], $term_id);
                         // now save the taxonomy
                         if ($taxonomy === 'post_tag' || $taxonomy === 'product_tag') {
                             wp_set_post_terms($new_id, $old_tax['name'], $taxonomy, true);
                         } else {
                             wp_set_post_terms($new_id, array($term_id), $taxonomy, true);
                         }
                     }
                 }
             }
         }
     }
     // handle post_format
     if (isset($post['format']) && $post['format'] !== false) {
         set_post_format($new_id, $post['format']);
     }
     $this->attach_images($post, $new_id);
     return $new_id;
 }
Example #18
0
/**
 * The new expiration function, to work with single scheduled events.
 *
 * This was designed to hopefully be more flexible for future tweaks/modifications to the architecture.
 *
 * @param array $opts - options to pass into the expiration process, in key/value format
 */
function postExpiratorExpire($id)
{
    $debug = postExpiratorDebug();
    //check for/load debug
    if (empty($id)) {
        if (POSTEXPIRATOR_DEBUG) {
            $debug->save(array('message' => 'No Post ID found - exiting'));
        }
        return false;
    }
    if (is_null(get_post($id))) {
        if (POSTEXPIRATOR_DEBUG) {
            $debug->save(array('message' => $id . ' -> Post does not exist - exiting'));
        }
        return false;
    }
    $postoptions = get_post_meta($id, '_expiration-date-options', true);
    extract($postoptions);
    // Check for default expire only if not passed in
    if (empty($expireType)) {
        $posttype = get_post_type($id);
        if ($posttype == 'page') {
            $expireType = strtolower(get_option('expirationdateExpiredPageStatus', POSTEXPIRATOR_PAGESTATUS));
        } elseif ($posttype == 'post') {
            $expireType = strtolower(get_option('expirationdateExpiredPostStatus', 'Draft'));
        } else {
            $expireType = apply_filters('postexpirator_custom_posttype_expire', $expireType, $posttype);
            //hook to set defaults for custom post types
        }
    }
    // Remove KSES - wp_cron runs as an unauthenticated user, which will by default trigger kses filtering,
    // even if the post was published by a admin user.  It is fairly safe here to remove the filter call since
    // we are only changing the post status/meta information and not touching the content.
    kses_remove_filters();
    // Do Work
    if ($expireType == 'draft') {
        if (wp_update_post(array('ID' => $id, 'post_status' => 'draft')) == 0) {
            if (POSTEXPIRATOR_DEBUG) {
                $debug->save(array('message' => $id . ' -> FAILED ' . $expireType . ' ' . print_r($postoptions, true)));
            }
        } else {
            if (POSTEXPIRATOR_DEBUG) {
                $debug->save(array('message' => $id . ' -> PROCESSED ' . $expireType . ' ' . print_r($postoptions, true)));
            }
        }
    } elseif ($expireType == 'private') {
        if (wp_update_post(array('ID' => $id, 'post_status' => 'private')) == 0) {
            if (POSTEXPIRATOR_DEBUG) {
                $debug->save(array('message' => $id . ' -> FAILED ' . $expireType . ' ' . print_r($postoptions, true)));
            }
        } else {
            if (POSTEXPIRATOR_DEBUG) {
                $debug->save(array('message' => $id . ' -> PROCESSED ' . $expireType . ' ' . print_r($postoptions, true)));
            }
        }
    } elseif ($expireType == 'delete') {
        if (wp_delete_post($id) === false) {
            if (POSTEXPIRATOR_DEBUG) {
                $debug->save(array('message' => $id . ' -> FAILED ' . $expireType . ' ' . print_r($postoptions, true)));
            }
        } else {
            if (POSTEXPIRATOR_DEBUG) {
                $debug->save(array('message' => $id . ' -> PROCESSED ' . $expireType . ' ' . print_r($postoptions, true)));
            }
        }
    } elseif ($expireType == 'category') {
        if (!empty($category)) {
            if (!isset($categoryTaxonomy) || $categoryTaxonomy == 'category') {
                if (wp_update_post(array('ID' => $id, 'post_category' => $category)) == 0) {
                    if (POSTEXPIRATOR_DEBUG) {
                        $debug->save(array('message' => $id . ' -> FAILED ' . $expireType . ' ' . print_r($postoptions, true)));
                    }
                } else {
                    if (POSTEXPIRATOR_DEBUG) {
                        $debug->save(array('message' => $id . ' -> PROCESSED ' . $expireType . ' ' . print_r($postoptions, true)));
                        $debug->save(array('message' => $id . ' -> CATEGORIES REPLACED ' . print_r(_postExpiratorGetCatNames($category), true)));
                        $debug->save(array('message' => $id . ' -> CATEGORIES COMPLETE ' . print_r(_postExpiratorGetCatNames($category), true)));
                    }
                }
            } else {
                $terms = array_map('intval', $category);
                if (is_wp_error(wp_set_object_terms($id, $terms, $categoryTaxonomy, false))) {
                    if (POSTEXPIRATOR_DEBUG) {
                        $debug->save(array('message' => $id . ' -> FAILED ' . $expireType . ' ' . print_r($postoptions, true)));
                    }
                } else {
                    if (POSTEXPIRATOR_DEBUG) {
                        $debug->save(array('message' => $id . ' -> PROCESSED ' . $expireType . ' ' . print_r($postoptions, true)));
                        $debug->save(array('message' => $id . ' -> CATEGORIES REPLACED ' . print_r(_postExpiratorGetCatNames($category), true)));
                        $debug->save(array('message' => $id . ' -> CATEGORIES COMPLETE ' . print_r(_postExpiratorGetCatNames($category), true)));
                    }
                }
            }
        } else {
            if (POSTEXPIRATOR_DEBUG) {
                $debug->save(array('message' => $id . ' -> CATEGORIES MISSING ' . $expireType . ' ' . print_r($postoptions, true)));
            }
        }
    } elseif ($expireType == 'category-add') {
        if (!empty($category)) {
            if (!isset($categoryTaxonomy) || $categoryTaxonomy == 'category') {
                $cats = wp_get_post_categories($id);
                $merged = array_merge($cats, $category);
                if (wp_update_post(array('ID' => $id, 'post_category' => $merged)) == 0) {
                    if (POSTEXPIRATOR_DEBUG) {
                        $debug->save(array('message' => $id . ' -> FAILED ' . $expireType . ' ' . print_r($postoptions, true)));
                    }
                } else {
                    if (POSTEXPIRATOR_DEBUG) {
                        $debug->save(array('message' => $id . ' -> PROCESSED ' . $expireType . ' ' . print_r($postoptions, true)));
                        $debug->save(array('message' => $id . ' -> CATEGORIES ADDED ' . print_r(_postExpiratorGetCatNames($category), true)));
                        $debug->save(array('message' => $id . ' -> CATEGORIES COMPLETE ' . print_r(_postExpiratorGetCatNames($merged), true)));
                    }
                }
            } else {
                $terms = array_map('intval', $category);
                if (is_wp_error(wp_set_object_terms($id, $terms, $categoryTaxonomy, true))) {
                    if (POSTEXPIRATOR_DEBUG) {
                        $debug->save(array('message' => $id . ' -> FAILED ' . $expireType . ' ' . print_r($postoptions, true)));
                    }
                } else {
                    if (POSTEXPIRATOR_DEBUG) {
                        $debug->save(array('message' => $id . ' -> PROCESSED ' . $expireType . ' ' . print_r($postoptions, true)));
                        $debug->save(array('message' => $id . ' -> CATEGORIES ADDED ' . print_r(_postExpiratorGetCatNames($category), true)));
                        $debug->save(array('message' => $id . ' -> CATEGORIES COMPLETE ' . print_r(_postExpiratorGetCatNames($category), true)));
                    }
                }
            }
        } else {
            if (POSTEXPIRATOR_DEBUG) {
                $debug->save(array('message' => $id . ' -> CATEGORIES MISSING ' . $expireType . ' ' . print_r($postoptions, true)));
            }
        }
    } elseif ($expireType == 'category-remove') {
        if (!empty($category)) {
            if (!isset($categoryTaxonomy) || $categoryTaxonomy == 'category') {
                $cats = wp_get_post_categories($id);
                $merged = array();
                foreach ($cats as $cat) {
                    if (!in_array($cat, $category)) {
                        $merged[] = $cat;
                    }
                }
                if (wp_update_post(array('ID' => $id, 'post_category' => $merged)) == 0) {
                    if (POSTEXPIRATOR_DEBUG) {
                        $debug->save(array('message' => $id . ' -> FAILED ' . $expireType . ' ' . print_r($postoptions, true)));
                    }
                } else {
                    if (POSTEXPIRATOR_DEBUG) {
                        $debug->save(array('message' => $id . ' -> PROCESSED ' . $expireType . ' ' . print_r($postoptions, true)));
                        $debug->save(array('message' => $id . ' -> CATEGORIES REMOVED ' . print_r(_postExpiratorGetCatNames($category), true)));
                        $debug->save(array('message' => $id . ' -> CATEGORIES COMPLETE ' . print_r(_postExpiratorGetCatNames($merged), true)));
                    }
                }
            } else {
                $terms = wp_get_object_terms($id, $categoryTaxonomy, array('fields' => 'ids'));
                $merged = array();
                foreach ($terms as $term) {
                    if (!in_array($term, $category)) {
                        $merged[] = $term;
                    }
                }
                $terms = array_map('intval', $merged);
                if (is_wp_error(wp_set_object_terms($id, $terms, $categoryTaxonomy, false))) {
                    if (POSTEXPIRATOR_DEBUG) {
                        $debug->save(array('message' => $id . ' -> FAILED ' . $expireType . ' ' . print_r($postoptions, true)));
                    }
                } else {
                    if (POSTEXPIRATOR_DEBUG) {
                        $debug->save(array('message' => $id . ' -> PROCESSED ' . $expireType . ' ' . print_r($postoptions, true)));
                        $debug->save(array('message' => $id . ' -> CATEGORIES REMOVED ' . print_r(_postExpiratorGetCatNames($category), true)));
                        $debug->save(array('message' => $id . ' -> CATEGORIES COMPLETE ' . print_r(_postExpiratorGetCatNames($category), true)));
                    }
                }
            }
        } else {
            if (POSTEXPIRATOR_DEBUG) {
                $debug->save(array('message' => $id . ' -> CATEGORIES MISSING ' . $expireType . ' ' . print_r($postoptions, true)));
            }
        }
    }
}
Example #19
0
 function tearDown()
 {
     kses_remove_filters();
     parent::tearDown();
 }
Example #20
0
function um_kses_init()
{
    if (current_user_can('unfiltered_html')) {
        kses_remove_filters();
    }
}
Example #21
0
 /**
  * Perform import operation
  * @param string $xml XML string to import
  * @param callback[optional] $logger Method where progress messages are submmitted
  * @return PMXI_Import_Record
  * @chainable
  */
 public function process($xml, $logger = NULL, $chunk = false, $is_cron = false, $xpath_prefix = '', $loop = 0)
 {
     add_filter('user_has_cap', array($this, '_filter_has_cap_unfiltered_html'));
     kses_init();
     // do not perform special filtering for imported content
     kses_remove_filters();
     $cxpath = $xpath_prefix . $this->xpath;
     $this->options += PMXI_Plugin::get_default_import_options();
     // make sure all options are defined
     $avoid_pingbacks = PMXI_Plugin::getInstance()->getOption('pingbacks');
     $cron_sleep = (int) PMXI_Plugin::getInstance()->getOption('cron_sleep');
     if ($avoid_pingbacks and !defined('WP_IMPORTING')) {
         define('WP_IMPORTING', true);
     }
     $postRecord = new PMXI_Post_Record();
     $tmp_files = array();
     // compose records to import
     $records = array();
     $is_import_complete = false;
     try {
         $chunk == 1 and $logger and call_user_func($logger, __('Composing titles...', 'wp_all_import_plugin'));
         if (!empty($this->options['title'])) {
             $titles = XmlImportParser::factory($xml, $cxpath, $this->options['title'], $file)->parse($records);
             $tmp_files[] = $file;
         } else {
             $loop and $titles = array_fill(0, $loop, '');
         }
         $chunk == 1 and $logger and call_user_func($logger, __('Composing excerpts...', 'wp_all_import_plugin'));
         $post_excerpt = array();
         if (!empty($this->options['post_excerpt'])) {
             $post_excerpt = XmlImportParser::factory($xml, $cxpath, $this->options['post_excerpt'], $file)->parse($records);
             $tmp_files[] = $file;
         } else {
             count($titles) and $post_excerpt = array_fill(0, count($titles), '');
         }
         if ("xpath" == $this->options['status']) {
             $chunk == 1 and $logger and call_user_func($logger, __('Composing statuses...', 'wp_all_import_plugin'));
             $post_status = array();
             if (!empty($this->options['status_xpath'])) {
                 $post_status = XmlImportParser::factory($xml, $cxpath, $this->options['status_xpath'], $file)->parse($records);
                 $tmp_files[] = $file;
             } else {
                 count($titles) and $post_status = array_fill(0, count($titles), '');
             }
         }
         if ("xpath" == $this->options['comment_status']) {
             $chunk == 1 and $logger and call_user_func($logger, __('Composing comment statuses...', 'wp_all_import_plugin'));
             $comment_status = array();
             if (!empty($this->options['comment_status_xpath'])) {
                 $comment_status = XmlImportParser::factory($xml, $cxpath, $this->options['comment_status_xpath'], $file)->parse($records);
                 $tmp_files[] = $file;
             } else {
                 count($titles) and $comment_status = array_fill(0, count($titles), 'open');
             }
         }
         if ("xpath" == $this->options['ping_status']) {
             $chunk == 1 and $logger and call_user_func($logger, __('Composing ping statuses...', 'wp_all_import_plugin'));
             $ping_status = array();
             if (!empty($this->options['ping_status_xpath'])) {
                 $ping_status = XmlImportParser::factory($xml, $cxpath, $this->options['ping_status_xpath'], $file)->parse($records);
                 $tmp_files[] = $file;
             } else {
                 count($titles) and $ping_status = array_fill(0, count($titles), 'open');
             }
         }
         if ("xpath" == $this->options['post_format']) {
             $chunk == 1 and $logger and call_user_func($logger, __('Composing post formats...', 'wp_all_import_plugin'));
             $post_format = array();
             if (!empty($this->options['post_format_xpath'])) {
                 $post_format = XmlImportParser::factory($xml, $cxpath, $this->options['post_format_xpath'], $file)->parse($records);
                 $tmp_files[] = $file;
             } else {
                 count($titles) and $post_format = array_fill(0, count($titles), 'open');
             }
         }
         if ("no" == $this->options['is_multiple_page_template']) {
             $chunk == 1 and $logger and call_user_func($logger, __('Composing page templates...', 'wp_all_import_plugin'));
             $page_template = array();
             if (!empty($this->options['single_page_template'])) {
                 $page_template = XmlImportParser::factory($xml, $cxpath, $this->options['single_page_template'], $file)->parse($records);
                 $tmp_files[] = $file;
             } else {
                 count($titles) and $page_template = array_fill(0, count($titles), 'default');
             }
         }
         if ($this->options['is_override_post_type'] and !empty($this->options['post_type_xpath'])) {
             $chunk == 1 and $logger and call_user_func($logger, __('Composing post types...', 'wp_all_import_plugin'));
             $post_type = array();
             $post_type = XmlImportParser::factory($xml, $cxpath, $this->options['post_type_xpath'], $file)->parse($records);
             $tmp_files[] = $file;
         } else {
             if ('post' == $this->options['type'] and '' != $this->options['custom_type']) {
                 $pType = $this->options['custom_type'];
             } else {
                 $pType = $this->options['type'];
             }
             count($titles) and $post_type = array_fill(0, count($titles), $pType);
         }
         if ("no" == $this->options['is_multiple_page_parent']) {
             $chunk == 1 and $logger and call_user_func($logger, __('Composing page parent...', 'wp_all_import_plugin'));
             $page_parent = array();
             if (!empty($this->options['single_page_parent'])) {
                 $page_parent = XmlImportParser::factory($xml, $cxpath, $this->options['single_page_parent'], $file)->parse($records);
                 $tmp_files[] = $file;
                 foreach ($page_parent as $key => $identity) {
                     $page = 0;
                     switch ($this->options['type']) {
                         case 'post':
                             if (!empty($identity)) {
                                 if (ctype_digit($identity)) {
                                     $page = get_post($identity);
                                 } else {
                                     $page = get_page_by_title($identity, OBJECT, $post_type[$key]);
                                     if (empty($page)) {
                                         $args = array('name' => $identity, 'post_type' => $post_type[$key], 'post_status' => 'any', 'numberposts' => 1);
                                         $my_posts = get_posts($args);
                                         if ($my_posts) {
                                             $page = $my_posts[0];
                                         }
                                     }
                                 }
                             }
                             break;
                         case 'page':
                             $page = get_page_by_title($identity) or $page = get_page_by_path($identity) or ctype_digit($identity) and $page = get_post($identity);
                             break;
                         default:
                             # code...
                             break;
                     }
                     $page_parent[$key] = !empty($page) ? $page->ID : 0;
                 }
             } else {
                 count($titles) and $page_parent = array_fill(0, count($titles), 0);
             }
         }
         $chunk == 1 and $logger and call_user_func($logger, __('Composing authors...', 'wp_all_import_plugin'));
         $post_author = array();
         $current_user = wp_get_current_user();
         if (!empty($this->options['author'])) {
             $post_author = XmlImportParser::factory($xml, $cxpath, $this->options['author'], $file)->parse($records);
             $tmp_files[] = $file;
             foreach ($post_author as $key => $author) {
                 $user = get_user_by('login', $author) or $user = get_user_by('slug', $author) or $user = get_user_by('email', $author) or ctype_digit($author) and $user = get_user_by('id', $author);
                 $post_author[$key] = !empty($user) ? $user->ID : $current_user->ID;
             }
         } else {
             count($titles) and $post_author = array_fill(0, count($titles), $current_user->ID);
         }
         $chunk == 1 and $logger and call_user_func($logger, __('Composing slugs...', 'wp_all_import_plugin'));
         $post_slug = array();
         if (!empty($this->options['post_slug'])) {
             $post_slug = XmlImportParser::factory($xml, $cxpath, $this->options['post_slug'], $file)->parse($records);
             $tmp_files[] = $file;
         } else {
             count($titles) and $post_slug = array_fill(0, count($titles), '');
         }
         $chunk == 1 and $logger and call_user_func($logger, __('Composing menu order...', 'wp_all_import_plugin'));
         $menu_order = array();
         if (!empty($this->options['order'])) {
             $menu_order = XmlImportParser::factory($xml, $cxpath, $this->options['order'], $file)->parse($records);
             $tmp_files[] = $file;
         } else {
             count($titles) and $menu_order = array_fill(0, count($titles), '');
         }
         $chunk == 1 and $logger and call_user_func($logger, __('Composing contents...', 'wp_all_import_plugin'));
         if (!empty($this->options['content'])) {
             $contents = XmlImportParser::factory((!empty($this->options['is_keep_linebreaks']) and intval($this->options['is_keep_linebreaks'])) ? $xml : preg_replace('%\\r\\n?|\\n%', ' ', $xml), $cxpath, $this->options['content'], $file)->parse($records);
             $tmp_files[] = $file;
         } else {
             count($titles) and $contents = array_fill(0, count($titles), '');
         }
         $chunk == 1 and $logger and call_user_func($logger, __('Composing dates...', 'wp_all_import_plugin'));
         if ('specific' == $this->options['date_type']) {
             $dates = XmlImportParser::factory($xml, $cxpath, $this->options['date'], $file)->parse($records);
             $tmp_files[] = $file;
             $warned = array();
             // used to prevent the same notice displaying several times
             foreach ($dates as $i => $d) {
                 if ($d == 'now') {
                     $d = current_time('mysql');
                 }
                 // Replace 'now' with the WordPress local time to account for timezone offsets (WordPress references its local time during publishing rather than the server’s time so it should use that)
                 $time = strtotime($d);
                 if (FALSE === $time) {
                     in_array($d, $warned) or $logger and call_user_func($logger, sprintf(__('<b>WARNING</b>: unrecognized date format `%s`, assigning current date', 'wp_all_import_plugin'), $warned[] = $d));
                     $logger and !$is_cron and PMXI_Plugin::$session->warnings++;
                     $time = time();
                 }
                 $dates[$i] = date('Y-m-d H:i:s', $time);
             }
         } else {
             $dates_start = XmlImportParser::factory($xml, $cxpath, $this->options['date_start'], $file)->parse($records);
             $tmp_files[] = $file;
             $dates_end = XmlImportParser::factory($xml, $cxpath, $this->options['date_end'], $file)->parse($records);
             $tmp_files[] = $file;
             $warned = array();
             // used to prevent the same notice displaying several times
             foreach ($dates_start as $i => $d) {
                 $time_start = strtotime($dates_start[$i]);
                 if (FALSE === $time_start) {
                     in_array($dates_start[$i], $warned) or $logger and call_user_func($logger, sprintf(__('<b>WARNING</b>: unrecognized date format `%s`, assigning current date', 'wp_all_import_plugin'), $warned[] = $dates_start[$i]));
                     $logger and !$is_cron and PMXI_Plugin::$session->warnings++;
                     $time_start = time();
                 }
                 $time_end = strtotime($dates_end[$i]);
                 if (FALSE === $time_end) {
                     in_array($dates_end[$i], $warned) or $logger and call_user_func($logger, sprintf(__('<b>WARNING</b>: unrecognized date format `%s`, assigning current date', 'wp_all_import_plugin'), $warned[] = $dates_end[$i]));
                     $logger and !$is_cron and PMXI_Plugin::$session->warnings++;
                     $time_end = time();
                 }
                 $dates[$i] = date('Y-m-d H:i:s', mt_rand($time_start, $time_end));
             }
         }
         // [custom taxonomies]
         require_once ABSPATH . 'wp-admin/includes/taxonomy.php';
         $taxonomies = array();
         $exclude_taxonomies = apply_filters('pmxi_exclude_taxonomies', class_exists('PMWI_Plugin') ? array('post_format', 'product_type', 'product_shipping_class') : array('post_format'));
         $post_taxonomies = array_diff_key(get_taxonomies_by_object_type(array($this->options['custom_type']), 'object'), array_flip($exclude_taxonomies));
         if (!empty($post_taxonomies)) {
             foreach ($post_taxonomies as $ctx) {
                 if ("" == $ctx->labels->name or class_exists('PMWI_Plugin') and strpos($ctx->name, "pa_") === 0 and $this->options['custom_type'] == "product") {
                     continue;
                 }
                 $chunk == 1 and $logger and call_user_func($logger, sprintf(__('Composing terms for `%s` taxonomy...', 'wp_all_import_plugin'), $ctx->labels->name));
                 $tx_name = $ctx->name;
                 $mapping_rules = !empty($this->options['tax_mapping'][$tx_name]) ? json_decode($this->options['tax_mapping'][$tx_name], true) : false;
                 $taxonomies[$tx_name] = array();
                 if (!empty($this->options['tax_logic'][$tx_name]) and !empty($this->options['tax_assing'][$tx_name])) {
                     switch ($this->options['tax_logic'][$tx_name]) {
                         case 'single':
                             if (!empty($this->options['tax_single_xpath'][$tx_name])) {
                                 $txes = XmlImportParser::factory($xml, $cxpath, $this->options['tax_single_xpath'][$tx_name], $file)->parse($records);
                                 $tmp_files[] = $file;
                                 foreach ($txes as $i => $tx) {
                                     $taxonomies[$tx_name][$i][] = wp_all_import_ctx_mapping(array('name' => $tx, 'parent' => false, 'assign' => isset($this->options['term_assing'][$tx_name]) ? $this->options['term_assing'][$tx_name] : true, 'is_mapping' => !empty($this->options['tax_enable_mapping'][$tx_name]), 'hierarchy_level' => 1, 'max_hierarchy_level' => 1), $mapping_rules, $tx_name);
                                 }
                             }
                             break;
                         case 'multiple':
                             if (!empty($this->options['tax_multiple_xpath'][$tx_name])) {
                                 $txes = XmlImportParser::factory($xml, $cxpath, $this->options['tax_multiple_xpath'][$tx_name], $file)->parse($records);
                                 $tmp_files[] = $file;
                                 foreach ($txes as $i => $tx) {
                                     $_tx = $tx;
                                     // apply mapping rules before splitting via separator symbol
                                     if (!empty($this->options['tax_enable_mapping'][$tx_name]) and !empty($this->options['tax_logic_mapping'][$tx_name])) {
                                         if (!empty($mapping_rules)) {
                                             foreach ($mapping_rules as $rule) {
                                                 if (!empty($rule[trim($_tx)])) {
                                                     $_tx = trim($rule[trim($_tx)]);
                                                     break;
                                                 }
                                             }
                                         }
                                     }
                                     $delimeted_taxonomies = explode(!empty($this->options['tax_multiple_delim'][$tx_name]) ? $this->options['tax_multiple_delim'][$tx_name] : ',', $_tx);
                                     if (!empty($delimeted_taxonomies)) {
                                         foreach ($delimeted_taxonomies as $cc) {
                                             $taxonomies[$tx_name][$i][] = wp_all_import_ctx_mapping(array('name' => $cc, 'parent' => false, 'assign' => isset($this->options['multiple_term_assing'][$tx_name]) ? $this->options['multiple_term_assing'][$tx_name] : true, 'is_mapping' => !empty($this->options['tax_enable_mapping'][$tx_name]) and empty($this->options['tax_logic_mapping'][$tx_name]), 'hierarchy_level' => 1, 'max_hierarchy_level' => 1), $mapping_rules, $tx_name);
                                         }
                                     }
                                 }
                             }
                             break;
                         case 'hierarchical':
                             if (!empty($this->options['tax_hierarchical_logic_entire'][$tx_name])) {
                                 if (!empty($this->options['tax_hierarchical_xpath'][$tx_name]) and is_array($this->options['tax_hierarchical_xpath'][$tx_name])) {
                                     count($titles) and $iterator = array_fill(0, count($titles), 0);
                                     $taxonomies_hierarchy_groups = array_fill(0, count($titles), array());
                                     // separate hierarchy groups via symbol
                                     if (!empty($this->options['is_tax_hierarchical_group_delim'][$tx_name]) and !empty($this->options['tax_hierarchical_group_delim'][$tx_name])) {
                                         foreach ($this->options['tax_hierarchical_xpath'][$tx_name] as $k => $tx_xpath) {
                                             if (empty($tx_xpath)) {
                                                 continue;
                                             }
                                             $txes = XmlImportParser::factory($xml, $cxpath, $tx_xpath, $file)->parse($records);
                                             $tmp_files[] = $file;
                                             foreach ($txes as $i => $tx) {
                                                 $_tx = $tx;
                                                 // apply mapping rules before splitting via separator symbol
                                                 if (!empty($this->options['tax_enable_mapping'][$tx_name]) and !empty($this->options['tax_logic_mapping'][$tx_name])) {
                                                     if (!empty($mapping_rules)) {
                                                         foreach ($mapping_rules as $rule) {
                                                             if (!empty($rule[trim($_tx)])) {
                                                                 $_tx = trim($rule[trim($_tx)]);
                                                                 break;
                                                             }
                                                         }
                                                     }
                                                 }
                                                 $delimeted_groups = explode($this->options['tax_hierarchical_group_delim'][$tx_name], $_tx);
                                                 if (!empty($delimeted_groups) and is_array($delimeted_groups)) {
                                                     foreach ($delimeted_groups as $group) {
                                                         if (!empty($group)) {
                                                             array_push($taxonomies_hierarchy_groups[$i], $group);
                                                         }
                                                     }
                                                 }
                                             }
                                         }
                                     } else {
                                         foreach ($this->options['tax_hierarchical_xpath'][$tx_name] as $k => $tx_xpath) {
                                             if (empty($tx_xpath)) {
                                                 continue;
                                             }
                                             $txes = XmlImportParser::factory($xml, $cxpath, $tx_xpath, $file)->parse($records);
                                             $tmp_files[] = $file;
                                             foreach ($txes as $i => $tx) {
                                                 array_push($taxonomies_hierarchy_groups[$i], $tx);
                                             }
                                         }
                                     }
                                     foreach ($taxonomies_hierarchy_groups as $i => $groups) {
                                         if (empty($groups)) {
                                             continue;
                                         }
                                         foreach ($groups as $kk => $tx) {
                                             $_tx = $tx;
                                             // apply mapping rules before splitting via separator symbol
                                             if (!empty($this->options['tax_enable_mapping'][$tx_name]) and !empty($this->options['tax_logic_mapping'][$tx_name])) {
                                                 if (!empty($mapping_rules)) {
                                                     foreach ($mapping_rules as $rule) {
                                                         if (!empty($rule[trim($_tx)])) {
                                                             $_tx = trim($rule[trim($_tx)]);
                                                             break;
                                                         }
                                                     }
                                                 }
                                             }
                                             $delimeted_taxonomies = explode(!empty($this->options['tax_hierarchical_delim'][$tx_name]) ? $this->options['tax_hierarchical_delim'][$tx_name] : ',', $_tx);
                                             if (!empty($delimeted_taxonomies)) {
                                                 foreach ($delimeted_taxonomies as $j => $cc) {
                                                     $is_assign_term = isset($this->options['tax_hierarchical_assing'][$tx_name][$k]) ? $this->options['tax_hierarchical_assing'][$tx_name][$k] : true;
                                                     if (!empty($this->options['tax_hierarchical_last_level_assign'][$tx_name])) {
                                                         $is_assign_term = count($delimeted_taxonomies) == $j + 1 ? 1 : 0;
                                                     }
                                                     $taxonomies[$tx_name][$i][] = wp_all_import_ctx_mapping(array('name' => $cc, 'parent' => (!empty($taxonomies[$tx_name][$i][$iterator[$i] - 1]) and $j) ? $taxonomies[$tx_name][$i][$iterator[$i] - 1] : false, 'assign' => $is_assign_term, 'is_mapping' => !empty($this->options['tax_enable_mapping'][$tx_name]) and empty($this->options['tax_logic_mapping'][$tx_name]), 'hierarchy_level' => $j + 1, 'max_hierarchy_level' => count($delimeted_taxonomies)), $mapping_rules, $tx_name);
                                                     $iterator[$i]++;
                                                 }
                                             }
                                         }
                                     }
                                 }
                             }
                             if (!empty($this->options['tax_hierarchical_logic_manual'][$tx_name])) {
                                 if (!empty($this->options['post_taxonomies'][$tx_name])) {
                                     $taxonomies_hierarchy = json_decode($this->options['post_taxonomies'][$tx_name], true);
                                     foreach ($taxonomies_hierarchy as $k => $taxonomy) {
                                         if ("" == $taxonomy['xpath']) {
                                             continue;
                                         }
                                         $txes_raw = XmlImportParser::factory($xml, $cxpath, $taxonomy['xpath'], $file)->parse($records);
                                         $tmp_files[] = $file;
                                         $warned = array();
                                         foreach ($txes_raw as $i => $cc) {
                                             $_tx = $cc;
                                             // apply mapping rules before splitting via separator symbol
                                             if (!empty($this->options['tax_enable_mapping'][$tx_name]) and !empty($this->options['tax_logic_mapping'][$tx_name])) {
                                                 if (!empty($mapping_rules)) {
                                                     foreach ($mapping_rules as $rule) {
                                                         if (!empty($rule[trim($_tx)])) {
                                                             $_tx = trim($rule[trim($_tx)]);
                                                             break;
                                                         }
                                                     }
                                                 }
                                             }
                                             if (!empty($this->options['tax_manualhierarchy_delim'][$tx_name])) {
                                                 $delimeted_taxonomies = explode($this->options['tax_manualhierarchy_delim'][$tx_name], $_tx);
                                             }
                                             if (empty($delimeted_taxonomies)) {
                                                 continue;
                                             }
                                             if (empty($taxonomies_hierarchy[$k]['txn_names'][$i])) {
                                                 $taxonomies_hierarchy[$k]['txn_names'][$i] = array();
                                             }
                                             if (empty($taxonomies[$tx_name][$i])) {
                                                 $taxonomies[$tx_name][$i] = array();
                                             }
                                             $count_cats = count($taxonomies[$tx_name][$i]);
                                             foreach ($delimeted_taxonomies as $j => $dc) {
                                                 if (!empty($taxonomy['parent_id'])) {
                                                     foreach ($taxonomies_hierarchy as $key => $value) {
                                                         if ($value['item_id'] == $taxonomy['parent_id'] and !empty($value['txn_names'][$i])) {
                                                             foreach ($value['txn_names'][$i] as $parent) {
                                                                 $taxonomies[$tx_name][$i][] = wp_all_import_ctx_mapping(array('name' => trim($dc), 'parent' => $parent, 'assign' => isset($taxonomy['assign']) ? $taxonomy['assign'] : true, 'is_mapping' => !empty($this->options['tax_enable_mapping'][$tx_name]) and empty($this->options['tax_logic_mapping'][$tx_name]), 'hierarchy_level' => 1, 'max_hierarchy_level' => 1), $mapping_rules, $tx_name);
                                                             }
                                                         }
                                                     }
                                                 } else {
                                                     $taxonomies[$tx_name][$i][] = wp_all_import_ctx_mapping(array('name' => trim($dc), 'parent' => false, 'assign' => isset($taxonomy['assign']) ? $taxonomy['assign'] : true, 'is_mapping' => !empty($this->options['tax_enable_mapping'][$tx_name]) and empty($this->options['tax_logic_mapping'][$tx_name]), 'hierarchy_level' => 1, 'max_hierarchy_level' => 1), $mapping_rules, $tx_name);
                                                 }
                                                 if ($count_cats < count($taxonomies[$tx_name][$i])) {
                                                     $taxonomies_hierarchy[$k]['txn_names'][$i][] = $taxonomies[$tx_name][$i][count($taxonomies[$tx_name][$i]) - 1];
                                                 }
                                             }
                                         }
                                     }
                                 }
                             }
                             break;
                         default:
                             break;
                     }
                 }
             }
         }
         // [/custom taxonomies]
         // Composing featured images
         $image_sections = apply_filters('wp_all_import_image_sections', array(array('slug' => '', 'title' => __('Images', 'wp_all_import_plugin'), 'type' => 'images')));
         if (!(($uploads = wp_upload_dir()) && false === $uploads['error'])) {
             $logger and call_user_func($logger, __('<b>WARNING</b>', 'wp_all_import_plugin') . ': ' . $uploads['error']);
             $logger and call_user_func($logger, __('<b>WARNING</b>: No featured images will be created. Uploads folder is not found.', 'wp_all_import_plugin'));
             $logger and !$is_cron and PMXI_Plugin::$session->warnings++;
         } else {
             $images_bundle = array();
             foreach ($image_sections as $section) {
                 $chunk == 1 and $logger and call_user_func($logger, __('Composing URLs for ' . strtolower($section['title']) . '...', 'wp_all_import_plugin'));
                 $featured_images = array();
                 if ("no" == $this->options[$section['slug'] . 'download_images']) {
                     if ($this->options[$section['slug'] . 'featured_image']) {
                         $featured_images = XmlImportParser::factory($xml, $cxpath, $this->options[$section['slug'] . 'featured_image'], $file)->parse($records);
                         $tmp_files[] = $file;
                     } else {
                         count($titles) and $featured_images = array_fill(0, count($titles), '');
                     }
                 } else {
                     if ($this->options[$section['slug'] . 'download_featured_image']) {
                         $featured_images = XmlImportParser::factory($xml, $cxpath, $this->options[$section['slug'] . 'download_featured_image'], $file)->parse($records);
                         $tmp_files[] = $file;
                     } else {
                         count($titles) and $featured_images = array_fill(0, count($titles), '');
                     }
                 }
                 $images_bundle[empty($section['slug']) ? 'pmxi_gallery_image' : $section['slug']] = array('type' => $section['type'], 'files' => $featured_images);
                 // Composing images meta titles
                 $image_meta_titles_bundle = array();
                 if ($this->options[$section['slug'] . 'set_image_meta_title']) {
                     $chunk == 1 and $logger and call_user_func($logger, __('Composing ' . strtolower($section['title']) . ' meta data (titles)...', 'wp_all_import_plugin'));
                     $image_meta_titles = array();
                     if ($this->options[$section['slug'] . 'image_meta_title']) {
                         $image_meta_titles = XmlImportParser::factory($xml, $cxpath, $this->options[$section['slug'] . 'image_meta_title'], $file)->parse($records);
                         $tmp_files[] = $file;
                     } else {
                         count($titles) and $image_meta_titles = array_fill(0, count($titles), '');
                     }
                     $image_meta_titles_bundle[empty($section['slug']) ? 'pmxi_gallery_image' : $section['slug']] = $image_meta_titles;
                 }
                 // Composing images meta captions
                 $image_meta_captions_bundle = array();
                 if ($this->options[$section['slug'] . 'set_image_meta_caption']) {
                     $chunk == 1 and $logger and call_user_func($logger, __('Composing ' . strtolower($section['title']) . ' meta data (captions)...', 'wp_all_import_plugin'));
                     $image_meta_captions = array();
                     if ($this->options[$section['slug'] . 'image_meta_caption']) {
                         $image_meta_captions = XmlImportParser::factory($xml, $cxpath, $this->options[$section['slug'] . 'image_meta_caption'], $file)->parse($records);
                         $tmp_files[] = $file;
                     } else {
                         count($titles) and $image_meta_captions = array_fill(0, count($titles), '');
                     }
                     $image_meta_captions_bundle[empty($section['slug']) ? 'pmxi_gallery_image' : $section['slug']] = $image_meta_captions;
                 }
                 // Composing images meta alt text
                 $image_meta_alts_bundle = array();
                 if ($this->options[$section['slug'] . 'set_image_meta_alt']) {
                     $chunk == 1 and $logger and call_user_func($logger, __('Composing ' . strtolower($section['title']) . ' meta data (alt text)...', 'wp_all_import_plugin'));
                     $image_meta_alts = array();
                     if ($this->options[$section['slug'] . 'image_meta_alt']) {
                         $image_meta_alts = XmlImportParser::factory($xml, $cxpath, $this->options[$section['slug'] . 'image_meta_alt'], $file)->parse($records);
                         $tmp_files[] = $file;
                     } else {
                         count($titles) and $image_meta_alts = array_fill(0, count($titles), '');
                     }
                     $image_meta_alts_bundle[empty($section['slug']) ? 'pmxi_gallery_image' : $section['slug']] = $image_meta_alts;
                 }
                 // Composing images meta description
                 $image_meta_descriptions_bundle = array();
                 if ($this->options[$section['slug'] . 'set_image_meta_description']) {
                     $chunk == 1 and $logger and call_user_func($logger, __('Composing ' . strtolower($section['title']) . ' meta data (description)...', 'wp_all_import_plugin'));
                     $image_meta_descriptions = array();
                     if ($this->options[$section['slug'] . 'image_meta_description']) {
                         $image_meta_descriptions = XmlImportParser::factory($xml, $cxpath, $this->options[$section['slug'] . 'image_meta_description'], $file)->parse($records);
                         $tmp_files[] = $file;
                     } else {
                         count($titles) and $image_meta_descriptions = array_fill(0, count($titles), '');
                     }
                     $image_meta_descriptions_bundle[empty($section['slug']) ? 'pmxi_gallery_image' : $section['slug']] = $image_meta_descriptions;
                 }
                 $auto_rename_images_bundle = array();
                 $auto_extensions_bundle = array();
                 if ("yes" == $this->options[$section['slug'] . 'download_images']) {
                     // Composing images suffix
                     $chunk == 1 and $this->options[$section['slug'] . 'auto_rename_images'] and $logger and call_user_func($logger, __('Composing ' . strtolower($section['title']) . ' suffix...', 'wp_all_import_plugin'));
                     $auto_rename_images = array();
                     if ($this->options[$section['slug'] . 'auto_rename_images'] and !empty($this->options[$section['slug'] . 'auto_rename_images_suffix'])) {
                         $auto_rename_images = XmlImportParser::factory($xml, $cxpath, $this->options[$section['slug'] . 'auto_rename_images_suffix'], $file)->parse($records);
                         $tmp_files[] = $file;
                     } else {
                         count($titles) and $auto_rename_images = array_fill(0, count($titles), '');
                     }
                     $auto_rename_images_bundle[empty($section['slug']) ? 'pmxi_gallery_image' : $section['slug']] = $auto_rename_images;
                     // Composing images extensions
                     $chunk == 1 and $this->options[$section['slug'] . 'auto_set_extension'] and $logger and call_user_func($logger, __('Composing ' . strtolower($section['title']) . ' extensions...', 'wp_all_import_plugin'));
                     $auto_extensions = array();
                     if ($this->options[$section['slug'] . 'auto_set_extension'] and !empty($this->options[$section['slug'] . 'new_extension'])) {
                         $auto_extensions = XmlImportParser::factory($xml, $cxpath, $this->options[$section['slug'] . 'new_extension'], $file)->parse($records);
                         $tmp_files[] = $file;
                     } else {
                         count($titles) and $auto_extensions = array_fill(0, count($titles), '');
                     }
                     $auto_extensions_bundle[empty($section['slug']) ? 'pmxi_gallery_image' : $section['slug']] = $auto_extensions;
                 }
             }
         }
         // Composing attachments
         if (!(($uploads = wp_upload_dir()) && false === $uploads['error'])) {
             $logger and call_user_func($logger, __('<b>WARNING</b>', 'wp_all_import_plugin') . ': ' . $uploads['error']);
             $logger and call_user_func($logger, __('<b>WARNING</b>: No attachments will be created', 'wp_all_import_plugin'));
             $logger and !$is_cron and PMXI_Plugin::$session->warnings++;
         } else {
             $chunk == 1 and $logger and call_user_func($logger, __('Composing URLs for attachments files...', 'wp_all_import_plugin'));
             $attachments = array();
             if ($this->options['attachments']) {
                 // Detect if attachments is separated by comma
                 $atchs = explode(',', $this->options['attachments']);
                 if (!empty($atchs)) {
                     $parse_multiple = true;
                     foreach ($atchs as $atch) {
                         if (!preg_match("/{.*}/", trim($atch))) {
                             $parse_multiple = false;
                         }
                     }
                     if ($parse_multiple) {
                         foreach ($atchs as $atch) {
                             $posts_attachments = XmlImportParser::factory($xml, $cxpath, trim($atch), $file)->parse($records);
                             $tmp_files[] = $file;
                             foreach ($posts_attachments as $i => $val) {
                                 $attachments[$i][] = $val;
                             }
                         }
                     } else {
                         $attachments = XmlImportParser::factory($xml, $cxpath, $this->options['attachments'], $file)->parse($records);
                         $tmp_files[] = $file;
                     }
                 }
             } else {
                 count($titles) and $attachments = array_fill(0, count($titles), '');
             }
         }
         $chunk == 1 and $logger and call_user_func($logger, __('Composing unique keys...', 'wp_all_import_plugin'));
         if (!empty($this->options['unique_key'])) {
             $unique_keys = XmlImportParser::factory($xml, $cxpath, $this->options['unique_key'], $file)->parse($records);
             $tmp_files[] = $file;
         } else {
             count($titles) and $unique_keys = array_fill(0, count($titles), '');
         }
         $chunk == 1 and $logger and call_user_func($logger, __('Processing posts...', 'wp_all_import_plugin'));
         $addons = array();
         $addons_data = array();
         // data parsing for WP All Import add-ons
         $chunk == 1 and $logger and call_user_func($logger, __('Data parsing via add-ons...', 'wp_all_import_plugin'));
         $parsingData = array('import' => $this, 'count' => count($titles), 'xml' => $xml, 'logger' => $logger, 'chunk' => $chunk, 'xpath_prefix' => $xpath_prefix);
         $parse_functions = apply_filters('wp_all_import_addon_parse', array());
         foreach (PMXI_Admin_Addons::get_active_addons() as $class) {
             $model_class = str_replace("_Plugin", "_Import_Record", $class);
             if (class_exists($model_class)) {
                 $addons[$class] = new $model_class();
                 $addons_data[$class] = method_exists($addons[$class], 'parse') ? $addons[$class]->parse($parsingData) : false;
             } else {
                 if (!empty($parse_functions[$class])) {
                     if (is_array($parse_functions[$class]) and is_callable($parse_functions[$class]) or !is_array($parse_functions[$class]) and function_exists($parse_functions[$class])) {
                         $addons_data[$class] = call_user_func($parse_functions[$class], $parsingData);
                     }
                 }
             }
         }
         // save current import state to variables before import
         $created = $this->created;
         $updated = $this->updated;
         $skipped = $this->skipped;
         $specified_records = array();
         if ($this->options['is_import_specified']) {
             $chunk == 1 and $logger and call_user_func($logger, __('Calculate specified records to import...', 'wp_all_import_plugin'));
             foreach (preg_split('% *, *%', $this->options['import_specified'], -1, PREG_SPLIT_NO_EMPTY) as $chank) {
                 if (preg_match('%^(\\d+)-(\\d+)$%', $chank, $mtch)) {
                     $specified_records = array_merge($specified_records, range(intval($mtch[1]), intval($mtch[2])));
                 } else {
                     $specified_records = array_merge($specified_records, array(intval($chank)));
                 }
             }
         }
         $simpleXml = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
         $rootNodes = $simpleXml->xpath($cxpath);
         foreach ($titles as $i => $void) {
             $custom_type_details = get_post_type_object($post_type[$i]);
             if ($is_cron and $cron_sleep) {
                 sleep($cron_sleep);
             }
             $logger and call_user_func($logger, __('---', 'wp_all_import_plugin'));
             $logger and call_user_func($logger, sprintf(__('Record #%s', 'wp_all_import_plugin'), $this->imported + $this->skipped + $i + 1));
             wp_cache_flush();
             $logger and call_user_func($logger, __('<b>ACTION</b>: pmxi_before_post_import ...', 'wp_all_import_plugin'));
             do_action('pmxi_before_post_import', $this->id);
             if (empty($titles[$i])) {
                 if (!empty($addons_data['PMWI_Plugin']) and !empty($addons_data['PMWI_Plugin']['single_product_parent_ID'][$i])) {
                     $titles[$i] = $addons_data['PMWI_Plugin']['single_product_parent_ID'][$i] . ' Product Variation';
                 } else {
                     $logger and call_user_func($logger, __('<b>WARNING</b>: title is empty.', 'wp_all_import_plugin'));
                     $logger and !$is_cron and PMXI_Plugin::$session->warnings++;
                 }
             }
             if ($this->options['custom_type'] == 'import_users') {
                 $articleData = array('user_pass' => $addons_data['PMUI_Plugin']['pmui_pass'][$i], 'user_login' => $addons_data['PMUI_Plugin']['pmui_logins'][$i], 'user_nicename' => $addons_data['PMUI_Plugin']['pmui_nicename'][$i], 'user_url' => $addons_data['PMUI_Plugin']['pmui_url'][$i], 'user_email' => $addons_data['PMUI_Plugin']['pmui_email'][$i], 'display_name' => $addons_data['PMUI_Plugin']['pmui_display_name'][$i], 'user_registered' => $addons_data['PMUI_Plugin']['pmui_registered'][$i], 'first_name' => $addons_data['PMUI_Plugin']['pmui_first_name'][$i], 'last_name' => $addons_data['PMUI_Plugin']['pmui_last_name'][$i], 'description' => $addons_data['PMUI_Plugin']['pmui_description'][$i], 'nickname' => $addons_data['PMUI_Plugin']['pmui_nickname'][$i], 'role' => '' == $addons_data['PMUI_Plugin']['pmui_role'][$i] ? 'subscriber' : strtolower($addons_data['PMUI_Plugin']['pmui_role'][$i]));
                 $logger and call_user_func($logger, sprintf(__('Combine all data for user %s...', 'wp_all_import_plugin'), $articleData['user_login']));
             } else {
                 $articleData = array('post_type' => $post_type[$i], 'post_status' => "xpath" == $this->options['status'] ? $post_status[$i] : $this->options['status'], 'comment_status' => "xpath" == $this->options['comment_status'] ? $comment_status[$i] : $this->options['comment_status'], 'ping_status' => "xpath" == $this->options['ping_status'] ? $ping_status[$i] : $this->options['ping_status'], 'post_title' => !empty($this->options['is_leave_html']) ? html_entity_decode($titles[$i]) : $titles[$i], 'post_excerpt' => apply_filters('pmxi_the_excerpt', !empty($this->options['is_leave_html']) ? html_entity_decode($post_excerpt[$i]) : $post_excerpt[$i], $this->id), 'post_name' => $post_slug[$i], 'post_content' => apply_filters('pmxi_the_content', !empty($this->options['is_leave_html']) ? html_entity_decode($contents[$i]) : $contents[$i], $this->id), 'post_date' => $dates[$i], 'post_date_gmt' => get_gmt_from_date($dates[$i]), 'post_author' => $post_author[$i], 'menu_order' => (int) $menu_order[$i], 'post_parent' => "no" == $this->options['is_multiple_page_parent'] ? (int) $page_parent[$i] : (int) $this->options['parent']);
                 $logger and call_user_func($logger, sprintf(__('Combine all data for post `%s`...', 'wp_all_import_plugin'), $articleData['post_title']));
             }
             // Re-import Records Matching
             $post_to_update = false;
             $post_to_update_id = false;
             // if Auto Matching re-import option selected
             if ("manual" != $this->options['duplicate_matching']) {
                 // find corresponding article among previously imported
                 $logger and call_user_func($logger, sprintf(__('Find corresponding article among previously imported for post `%s`...', 'wp_all_import_plugin'), $articleData['post_title']));
                 $postRecord->clear();
                 $postRecord->getBy(array('unique_key' => $unique_keys[$i], 'import_id' => $this->id));
                 if (!$postRecord->isEmpty()) {
                     $logger and call_user_func($logger, sprintf(__('Duplicate post was founded for post %s with unique key `%s`...', 'wp_all_import_plugin'), $articleData['post_title'], $unique_keys[$i]));
                     if ($this->options['custom_type'] == 'import_users') {
                         $post_to_update = get_user_by('id', $post_to_update_id = $postRecord->post_id);
                     } else {
                         $post_to_update = get_post($post_to_update_id = $postRecord->post_id);
                     }
                 } else {
                     $logger and call_user_func($logger, sprintf(__('Duplicate post wasn\'t founded with unique key `%s`...', 'wp_all_import_plugin'), $unique_keys[$i]));
                 }
                 // if Manual Matching re-import option seleted
             } else {
                 if ('custom field' == $this->options['duplicate_indicator']) {
                     $custom_duplicate_value = XmlImportParser::factory($xml, $cxpath, $this->options['custom_duplicate_value'], $file)->parse($records);
                     $tmp_files[] = $file;
                     $custom_duplicate_name = XmlImportParser::factory($xml, $cxpath, $this->options['custom_duplicate_name'], $file)->parse($records);
                     $tmp_files[] = $file;
                 } else {
                     count($titles) and $custom_duplicate_name = $custom_duplicate_value = array_fill(0, count($titles), '');
                 }
                 $logger and call_user_func($logger, sprintf(__('Find corresponding article among database for post `%s`...', 'wp_all_import_plugin'), $articleData['post_title']));
                 // handle duplicates according to import settings
                 if ($duplicates = pmxi_findDuplicates($articleData, $custom_duplicate_name[$i], $custom_duplicate_value[$i], $this->options['duplicate_indicator'])) {
                     $duplicate_id = array_shift($duplicates);
                     if ($duplicate_id) {
                         $logger and call_user_func($logger, sprintf(__('Duplicate post was founded for post `%s`...', 'wp_all_import_plugin'), $articleData['post_title']));
                         if ($this->options['custom_type'] == 'import_users') {
                             $post_to_update = get_user_by('id', $post_to_update_id = $duplicate_id);
                         } else {
                             $post_to_update = get_post($post_to_update_id = $duplicate_id);
                         }
                     } else {
                         $logger and call_user_func($logger, sprintf(__('Duplicate post wasn\'n founded for post `%s`...', 'wp_all_import_plugin'), $articleData['post_title']));
                     }
                 }
             }
             if (!empty($specified_records)) {
                 if (!in_array($created + $updated + $skipped + 1, $specified_records)) {
                     if (!$postRecord->isEmpty()) {
                         $postRecord->set(array('iteration' => $this->iteration))->update();
                     }
                     $skipped++;
                     $logger and call_user_func($logger, __('<b>SKIPPED</b>: by specified records option', 'wp_all_import_plugin'));
                     $logger and !$is_cron and PMXI_Plugin::$session->warnings++;
                     $logger and !$is_cron and PMXI_Plugin::$session->chunk_number++;
                     $logger and !$is_cron and PMXI_Plugin::$session->save_data();
                     continue;
                 }
             }
             // Duplicate record is founded
             if ($post_to_update) {
                 $continue_import = true;
                 $continue_import = apply_filters('wp_all_import_is_post_to_update', $post_to_update_id, wp_all_import_xml2array($rootNodes[$i]));
                 if (!$continue_import) {
                     if (!$postRecord->isEmpty()) {
                         $postRecord->set(array('iteration' => $this->iteration))->update();
                     }
                     $skipped++;
                     $logger and call_user_func($logger, sprintf(__('<b>SKIPPED</b>: By filter wp_all_import_is_post_to_update `%s`', 'wp_all_import_plugin'), $articleData['post_title']));
                     $logger and !$is_cron and PMXI_Plugin::$session->warnings++;
                     $logger and !$is_cron and PMXI_Plugin::$session->chunk_number++;
                     $logger and !$is_cron and PMXI_Plugin::$session->save_data();
                     continue;
                 }
                 //$logger and call_user_func($logger, sprintf(__('Duplicate record is founded for `%s`', 'wp_all_import_plugin'), $articleData['post_title']));
                 // Do not update already existing records option selected
                 if ("yes" == $this->options['is_keep_former_posts']) {
                     if (!$postRecord->isEmpty()) {
                         $postRecord->set(array('iteration' => $this->iteration))->update();
                     }
                     do_action('pmxi_do_not_update_existing', $post_to_update_id, $this->id, $this->iteration);
                     $skipped++;
                     $logger and call_user_func($logger, sprintf(__('<b>SKIPPED</b>: Previously imported record found for `%s`', 'wp_all_import_plugin'), $articleData['post_title']));
                     $logger and !$is_cron and PMXI_Plugin::$session->warnings++;
                     $logger and !$is_cron and PMXI_Plugin::$session->chunk_number++;
                     $logger and !$is_cron and PMXI_Plugin::$session->save_data();
                     continue;
                 }
                 $articleData['ID'] = $post_to_update_id;
                 // Choose which data to update
                 if ($this->options['update_all_data'] == 'no') {
                     if (!in_array($this->options['custom_type'], array('import_users'))) {
                         // preserve date of already existing article when duplicate is found
                         if (!$this->options['is_update_categories'] and (is_object_in_taxonomy($post_type[$i], 'category') or is_object_in_taxonomy($post_type[$i], 'post_tag')) or $this->options['is_update_categories'] and $this->options['update_categories_logic'] != "full_update") {
                             $logger and call_user_func($logger, sprintf(__('Preserve taxonomies of already existing article for `%s`', 'wp_all_import_plugin'), $articleData['post_title']));
                             $existing_taxonomies = array();
                             foreach (array_keys($taxonomies) as $tx_name) {
                                 $txes_list = get_the_terms($articleData['ID'], $tx_name);
                                 if (is_wp_error($txes_list)) {
                                     $logger and call_user_func($logger, sprintf(__('<b>WARNING</b>: Unable to get current taxonomies for article #%d, updating with those read from XML file', 'wp_all_import_plugin'), $articleData['ID']));
                                     $logger and !$is_cron and PMXI_Plugin::$session->warnings++;
                                 } else {
                                     $txes_new = array();
                                     if (!empty($txes_list)) {
                                         foreach ($txes_list as $t) {
                                             $txes_new[] = $t->term_taxonomy_id;
                                         }
                                     }
                                     $existing_taxonomies[$tx_name][$i] = $txes_new;
                                 }
                             }
                         }
                         if (!$this->options['is_update_dates']) {
                             // preserve date of already existing article when duplicate is found
                             $articleData['post_date'] = $post_to_update->post_date;
                             $articleData['post_date_gmt'] = $post_to_update->post_date_gmt;
                             $logger and call_user_func($logger, sprintf(__('Preserve date of already existing article for `%s`', 'wp_all_import_plugin'), $articleData['post_title']));
                         }
                         if (!$this->options['is_update_status']) {
                             // preserve status and trashed flag
                             $articleData['post_status'] = $post_to_update->post_status;
                             $logger and call_user_func($logger, sprintf(__('Preserve status of already existing article for `%s`', 'wp_all_import_plugin'), $articleData['post_title']));
                         }
                         if (!$this->options['is_update_content']) {
                             $articleData['post_content'] = $post_to_update->post_content;
                             $logger and call_user_func($logger, sprintf(__('Preserve content of already existing article for `%s`', 'wp_all_import_plugin'), $articleData['post_title']));
                         }
                         if (!$this->options['is_update_title']) {
                             $articleData['post_title'] = $post_to_update->post_title;
                             $logger and call_user_func($logger, sprintf(__('Preserve title of already existing article for `%s`', 'wp_all_import_plugin'), $articleData['post_title']));
                         }
                         if (!$this->options['is_update_slug']) {
                             $articleData['post_name'] = $post_to_update->post_name;
                             $logger and call_user_func($logger, sprintf(__('Preserve slug of already existing article for `%s`', 'wp_all_import_plugin'), $articleData['post_title']));
                         }
                         if (!$this->options['is_update_excerpt']) {
                             $articleData['post_excerpt'] = $post_to_update->post_excerpt;
                             $logger and call_user_func($logger, sprintf(__('Preserve excerpt of already existing article for `%s`', 'wp_all_import_plugin'), $articleData['post_title']));
                         }
                         if (!$this->options['is_update_menu_order']) {
                             $articleData['menu_order'] = $post_to_update->menu_order;
                             $logger and call_user_func($logger, sprintf(__('Preserve menu order of already existing article for `%s`', 'wp_all_import_plugin'), $articleData['post_title']));
                         }
                         if (!$this->options['is_update_parent']) {
                             $articleData['post_parent'] = $post_to_update->post_parent;
                             $logger and call_user_func($logger, sprintf(__('Preserve post parent of already existing article for `%s`', 'wp_all_import_plugin'), $articleData['post_title']));
                         }
                         if (!$this->options['is_update_author']) {
                             $articleData['post_author'] = $post_to_update->post_author;
                             $logger and call_user_func($logger, sprintf(__('Preserve post author of already existing article for `%s`', 'wp_all_import_plugin'), $articleData['post_title']));
                         }
                     } else {
                         if (!$this->options['is_update_first_name']) {
                             $articleData['first_name'] = $post_to_update->first_name;
                         }
                         if (!$this->options['is_update_last_name']) {
                             $articleData['last_name'] = $post_to_update->last_name;
                         }
                         if (!$this->options['is_update_role']) {
                             unset($articleData['role']);
                         }
                         if (!$this->options['is_update_nickname']) {
                             $articleData['nickname'] = get_user_meta($post_to_update->ID, 'nickname', true);
                         }
                         if (!$this->options['is_update_description']) {
                             $articleData['description'] = get_user_meta($post_to_update->ID, 'description', true);
                         }
                         if (!$this->options['is_update_login']) {
                             $articleData['user_login'] = $post_to_update->user_login;
                         }
                         if (!$this->options['is_update_password']) {
                             unset($articleData['user_pass']);
                         }
                         if (!$this->options['is_update_nicename']) {
                             $articleData['user_nicename'] = $post_to_update->user_nicename;
                         }
                         if (!$this->options['is_update_email']) {
                             $articleData['user_email'] = $post_to_update->user_email;
                         }
                         if (!$this->options['is_update_registered']) {
                             $articleData['user_registered'] = $post_to_update->user_registered;
                         }
                         if (!$this->options['is_update_display_name']) {
                             $articleData['display_name'] = $post_to_update->display_name;
                         }
                         if (!$this->options['is_update_url']) {
                             $articleData['user_url'] = $post_to_update->user_url;
                         }
                     }
                     $logger and call_user_func($logger, sprintf(__('Applying filter `pmxi_article_data` for `%s`', 'wp_all_import_plugin'), $articleData['post_title']));
                     $articleData = apply_filters('pmxi_article_data', $articleData, $this, $post_to_update);
                 }
                 if (!in_array($this->options['custom_type'], array('import_users'))) {
                     if ($this->options['update_all_data'] == 'yes' or $this->options['update_all_data'] == 'no' and $this->options['is_update_attachments']) {
                         $logger and call_user_func($logger, sprintf(__('Deleting attachments for `%s`', 'wp_all_import_plugin'), $articleData['post_title']));
                         wp_delete_attachments($articleData['ID'], true, 'files');
                     }
                     // handle obsolete attachments (i.e. delete or keep) according to import settings
                     if ($this->options['update_all_data'] == 'yes' or $this->options['update_all_data'] == 'no' and $this->options['is_update_images'] and $this->options['update_images_logic'] == "full_update") {
                         $logger and call_user_func($logger, sprintf(__('Deleting images for `%s`', 'wp_all_import_plugin'), $articleData['post_title']));
                         wp_delete_attachments($articleData['ID'], !$this->options['do_not_remove_images'], 'images');
                     }
                 }
             } elseif (!$postRecord->isEmpty()) {
                 // existing post not found though it's track was found... clear the leftover, plugin will continue to treat record as new
                 $postRecord->clear();
             }
             // no new records are created. it will only update posts it finds matching duplicates for
             if (!$this->options['create_new_records'] and empty($articleData['ID'])) {
                 if (!$postRecord->isEmpty()) {
                     $postRecord->set(array('iteration' => $this->iteration))->update();
                 }
                 $logger and call_user_func($logger, __('<b>SKIPPED</b>: by do not create new posts option.', 'wp_all_import_plugin'));
                 $logger and !$is_cron and PMXI_Plugin::$session->warnings++;
                 $logger and !$is_cron and PMXI_Plugin::$session->chunk_number++;
                 $skipped++;
                 $logger and !$is_cron and PMXI_Plugin::$session->save_data();
                 continue;
             }
             // cloak urls with `WP Wizard Cloak` if corresponding option is set
             if (!empty($this->options['is_cloak']) and class_exists('PMLC_Plugin')) {
                 if (preg_match_all('%<a\\s[^>]*href=(?(?=")"([^"]*)"|(?(?=\')\'([^\']*)\'|([^\\s>]*)))%is', $articleData['post_content'], $matches, PREG_PATTERN_ORDER)) {
                     $hrefs = array_unique(array_merge(array_filter($matches[1]), array_filter($matches[2]), array_filter($matches[3])));
                     foreach ($hrefs as $url) {
                         if (preg_match('%^\\w+://%i', $url)) {
                             // mask only links having protocol
                             // try to find matching cloaked link among already registered ones
                             $list = new PMLC_Link_List();
                             $linkTable = $list->getTable();
                             $rule = new PMLC_Rule_Record();
                             $ruleTable = $rule->getTable();
                             $dest = new PMLC_Destination_Record();
                             $destTable = $dest->getTable();
                             $list->join($ruleTable, "{$ruleTable}.link_id = {$linkTable}.id")->join($destTable, "{$destTable}.rule_id = {$ruleTable}.id")->setColumns("{$linkTable}.*")->getBy(array("{$linkTable}.destination_type =" => 'ONE_SET', "{$linkTable}.is_trashed =" => 0, "{$linkTable}.preset =" => '', "{$linkTable}.expire_on =" => '0000-00-00', "{$ruleTable}.type =" => 'ONE_SET', "{$destTable}.weight =" => 100, "{$destTable}.url LIKE" => $url), NULL, 1, 1)->convertRecords();
                             if ($list->count()) {
                                 // matching link found
                                 $link = $list[0];
                             } else {
                                 // register new cloaked link
                                 global $wpdb;
                                 $slug = max(intval($wpdb->get_var("SELECT MAX(CONVERT(name, SIGNED)) FROM {$linkTable}")), intval($wpdb->get_var("SELECT MAX(CONVERT(slug, SIGNED)) FROM {$linkTable}")), 0);
                                 $i = 0;
                                 do {
                                     is_int(++$slug) and $slug > 0 or $slug = 1;
                                     $is_slug_found = !intval($wpdb->get_var("SELECT COUNT(*) FROM {$linkTable} WHERE name = '{$slug}' OR slug = '{$slug}'"));
                                 } while (!$is_slug_found and $i++ < 100000);
                                 if ($is_slug_found) {
                                     $link = new PMLC_Link_Record(array('name' => strval($slug), 'slug' => strval($slug), 'header_tracking_code' => '', 'footer_tracking_code' => '', 'redirect_type' => '301', 'destination_type' => 'ONE_SET', 'preset' => '', 'forward_url_params' => 1, 'no_global_tracking_code' => 0, 'expire_on' => '0000-00-00', 'created_on' => date('Y-m-d H:i:s'), 'is_trashed' => 0));
                                     $link->insert();
                                     $rule = new PMLC_Rule_Record(array('link_id' => $link->id, 'type' => 'ONE_SET', 'rule' => ''));
                                     $rule->insert();
                                     $dest = new PMLC_Destination_Record(array('rule_id' => $rule->id, 'url' => $url, 'weight' => 100));
                                     $dest->insert();
                                 } else {
                                     $logger and call_user_func($logger, sprintf(__('<b>WARNING</b>: Unable to create cloaked link for %s', 'wp_all_import_plugin'), $url));
                                     $logger and !$is_cron and PMXI_Plugin::$session->warnings++;
                                     $link = NULL;
                                 }
                             }
                             if ($link) {
                                 // cloaked link is found or created for url
                                 $articleData['post_content'] = preg_replace('%' . preg_quote($url, '%') . '(?=([\\s\'"]|$))%i', $link->getUrl(), $articleData['post_content']);
                             }
                         }
                     }
                 }
             }
             // insert article being imported
             if ($this->options['is_fast_mode']) {
                 foreach (array('transition_post_status', 'save_post', 'pre_post_update', 'add_attachment', 'edit_attachment', 'edit_post', 'post_updated', 'wp_insert_post', 'save_post_' . $post_type[$i]) as $act) {
                     remove_all_actions($act);
                 }
             }
             if (!in_array($this->options['custom_type'], array('import_users'))) {
                 if (empty($articleData['ID'])) {
                     $logger and call_user_func($logger, sprintf(__('<b>CREATING</b> `%s` `%s`', 'wp_all_import_plugin'), $articleData['post_title'], $custom_type_details->labels->singular_name));
                 } else {
                     $logger and call_user_func($logger, sprintf(__('<b>UPDATING</b> `%s` `%s`', 'wp_all_import_plugin'), $articleData['post_title'], $custom_type_details->labels->singular_name));
                 }
                 $pid = wp_insert_post($articleData, true);
             } else {
                 $pid = empty($articleData['ID']) ? wp_insert_user($articleData) : wp_update_user($articleData);
                 $articleData['post_title'] = $articleData['user_login'];
             }
             if (is_wp_error($pid)) {
                 $logger and call_user_func($logger, __('<b>ERROR</b>', 'wp_all_import_plugin') . ': ' . $pid->get_error_message());
                 $logger and !$is_cron and PMXI_Plugin::$session->errors++;
                 $skipped++;
             } else {
                 if ("manual" != $this->options['duplicate_matching'] or empty($articleData['ID'])) {
                     // associate post with import
                     $postRecord->isEmpty() and $postRecord->set(array('post_id' => $pid, 'import_id' => $this->id, 'unique_key' => $unique_keys[$i], 'product_key' => ($post_type[$i] == "product" and PMXI_Admin_Addons::get_addon('PMWI_Plugin')) ? $addons_data['PMWI_Plugin']['single_product_ID'][$i] : ''))->insert();
                     $postRecord->set(array('iteration' => $this->iteration))->update();
                     $logger and call_user_func($logger, sprintf(__('Associate post `%s` with current import ...', 'wp_all_import_plugin'), $articleData['post_title']));
                 }
                 // [post format]
                 if (current_theme_supports('post-formats') && post_type_supports($post_type[$i], 'post-formats')) {
                     set_post_format($pid, "xpath" == $this->options['post_format'] ? $post_format[$i] : $this->options['post_format']);
                     $logger and call_user_func($logger, sprintf(__('Associate post `%s` with post format %s ...', 'wp_all_import_plugin'), $articleData['post_title'], "xpath" == $this->options['post_format'] ? $post_format[$i] : $this->options['post_format']));
                 }
                 // [/post format]
                 // [addons import]
                 // prepare data for import
                 $importData = array('pid' => $pid, 'i' => $i, 'import' => $this, 'articleData' => $articleData, 'xml' => $xml, 'is_cron' => $is_cron, 'logger' => $logger, 'xpath_prefix' => $xpath_prefix, 'post_type' => $post_type[$i]);
                 $import_functions = apply_filters('wp_all_import_addon_import', array());
                 // deligate operation to addons
                 foreach (PMXI_Admin_Addons::get_active_addons() as $class) {
                     if (class_exists($class)) {
                         if (method_exists($addons[$class], 'import')) {
                             $addons[$class]->import($importData);
                         }
                     } else {
                         if (!empty($import_functions[$class])) {
                             if (is_array($import_functions[$class]) and is_callable($import_functions[$class]) or !is_array($import_functions[$class]) and function_exists($import_functions[$class])) {
                                 call_user_func($import_functions[$class], $importData, $addons_data[$class]);
                             }
                         }
                     }
                 }
                 // [/addons import]
                 // Page Template
                 if ('page' == $articleData['post_type'] and wp_all_import_is_update_cf('_wp_page_template', $this->options) and (!empty($this->options['page_template']) or "no" == $this->options['is_multiple_page_template'])) {
                     update_post_meta($pid, '_wp_page_template', "no" == $this->options['is_multiple_page_template'] ? $page_template[$i] : $this->options['page_template']);
                 }
                 // [featured image]
                 $is_allow_import_images = apply_filters('wp_all_import_is_allow_import_images', false, $articleData['post_type']);
                 if (!empty($uploads) and false === $uploads['error'] and ($articleData['post_type'] == "product" and class_exists('PMWI_Plugin') or $is_allow_import_images) and (empty($articleData['ID']) or $this->options['update_all_data'] == "yes" or $this->options['update_all_data'] == "no" and $this->options['is_update_images'])) {
                     if (!empty($images_bundle)) {
                         $is_show_add_new_images = apply_filters('wp_all_import_is_show_add_new_images', true, $post_type[$i]);
                         foreach ($images_bundle as $slug => $bundle_data) {
                             $featured_images = $bundle_data['files'];
                             $option_slug = $slug == 'pmxi_gallery_image' ? '' : $slug;
                             if (!empty($featured_images[$i])) {
                                 $targetDir = $uploads['path'];
                                 $targetUrl = $uploads['url'];
                                 $logger and call_user_func($logger, __('<b>IMAGES:</b>', 'wp_all_import_plugin'));
                                 if (!@is_writable($targetDir)) {
                                     $logger and call_user_func($logger, sprintf(__('<b>ERROR</b>: Target directory %s is not writable', 'wp_all_import_plugin'), $targetDir));
                                 } else {
                                     require_once ABSPATH . 'wp-admin/includes/image.php';
                                     $success_images = false;
                                     $gallery_attachment_ids = array();
                                     $imgs = array();
                                     $featured_delim = "yes" == $this->options[$option_slug . 'download_images'] ? $this->options[$option_slug . 'download_featured_delim'] : $this->options[$option_slug . 'featured_delim'];
                                     $line_imgs = explode("\n", $featured_images[$i]);
                                     if (!empty($line_imgs)) {
                                         foreach ($line_imgs as $line_img) {
                                             $imgs = array_merge($imgs, !empty($featured_delim) ? str_getcsv($line_img, $featured_delim) : array($line_img));
                                         }
                                     }
                                     // keep existing and add newest images
                                     if (!empty($articleData['ID']) and $this->options['is_update_images'] and $this->options['update_images_logic'] == "add_new" and $this->options['update_all_data'] == "no" and $is_show_add_new_images) {
                                         $logger and call_user_func($logger, __('- Keep existing and add newest images ...', 'wp_all_import_plugin'));
                                         $attachment_imgs = get_attached_media('image', $pid);
                                         if ($post_type[$i] == "product") {
                                             $gallery_attachment_ids = array_filter(explode(",", get_post_meta($pid, '_product_image_gallery', true)));
                                         }
                                         if ($attachment_imgs) {
                                             foreach ($attachment_imgs as $attachment_img) {
                                                 $post_thumbnail_id = get_post_thumbnail_id($pid);
                                                 if (empty($post_thumbnail_id) and $this->options[$option_slug . 'is_featured']) {
                                                     set_post_thumbnail($pid, $attachment_img->ID);
                                                 } elseif (!in_array($attachment_img->ID, $gallery_attachment_ids) and $post_thumbnail_id != $attachment_img->ID) {
                                                     $gallery_attachment_ids[] = $attachment_img->ID;
                                                 }
                                             }
                                             $success_images = true;
                                         }
                                         if (!empty($gallery_attachment_ids)) {
                                             foreach ($gallery_attachment_ids as $aid) {
                                                 do_action($slug, $pid, $aid, wp_get_attachment_url($aid), 'update_images');
                                             }
                                         }
                                     }
                                     if (!empty($imgs)) {
                                         if ($this->options[$option_slug . 'set_image_meta_title'] and !empty($image_meta_titles_bundle[$slug])) {
                                             $img_titles = array();
                                             $line_img_titles = explode("\n", $image_meta_titles_bundle[$slug][$i]);
                                             if (!empty($line_img_titles)) {
                                                 foreach ($line_img_titles as $line_img_title) {
                                                     $img_titles = array_merge($img_titles, !empty($this->options[$option_slug . 'image_meta_title_delim']) ? str_getcsv($line_img_title, $this->options[$option_slug . 'image_meta_title_delim']) : array($line_img_title));
                                                 }
                                             }
                                         }
                                         if ($this->options[$option_slug . 'set_image_meta_caption'] and !empty($image_meta_captions_bundle[$slug])) {
                                             $img_captions = array();
                                             $line_img_captions = explode("\n", $image_meta_captions_bundle[$slug][$i]);
                                             if (!empty($line_img_captions)) {
                                                 foreach ($line_img_captions as $line_img_caption) {
                                                     $img_captions = array_merge($img_captions, !empty($this->options[$option_slug . 'image_meta_caption_delim']) ? str_getcsv($line_img_caption, $this->options[$option_slug . 'image_meta_caption_delim']) : array($line_img_caption));
                                                 }
                                             }
                                         }
                                         if ($this->options[$option_slug . 'set_image_meta_alt'] and !empty($image_meta_alts_bundle[$slug])) {
                                             $img_alts = array();
                                             $line_img_alts = explode("\n", $image_meta_alts_bundle[$slug][$i]);
                                             if (!empty($line_img_alts)) {
                                                 foreach ($line_img_alts as $line_img_alt) {
                                                     $img_alts = array_merge($img_alts, !empty($this->options[$option_slug . 'image_meta_alt_delim']) ? str_getcsv($line_img_alt, $this->options[$option_slug . 'image_meta_alt_delim']) : array($line_img_alt));
                                                 }
                                             }
                                         }
                                         if ($this->options[$option_slug . 'set_image_meta_description'] and !empty($image_meta_descriptions_bundle[$slug])) {
                                             $img_descriptions = array();
                                             $line_img_descriptions = explode("\n", $image_meta_descriptions_bundle[$slug][$i]);
                                             if (!empty($line_img_descriptions)) {
                                                 foreach ($line_img_descriptions as $line_img_description) {
                                                     $img_descriptions = array_merge($img_descriptions, !empty($this->options[$option_slug . 'image_meta_description_delim']) ? str_getcsv($line_img_description, $this->options[$option_slug . 'image_meta_description_delim']) : array($line_img_description));
                                                 }
                                             }
                                         }
                                         $is_keep_existing_images = (!empty($articleData['ID']) and $this->options['is_update_images'] and $this->options['update_images_logic'] == "add_new" and $this->options['update_all_data'] == "no" and $is_show_add_new_images);
                                         foreach ($imgs as $k => $img_url) {
                                             if (empty($img_url)) {
                                                 continue;
                                             }
                                             $attid = false;
                                             $attch = null;
                                             $url = str_replace(" ", "%20", trim($img_url));
                                             $bn = basename($url);
                                             if ("yes" == $this->options[$option_slug . 'download_images'] and !empty($auto_extensions_bundle[$slug][$i]) and preg_match('%^(jpg|jpeg|png|gif)$%i', $auto_extensions_bundle[$slug][$i])) {
                                                 $img_ext = $auto_extensions_bundle[$slug][$i];
                                             } else {
                                                 $img_ext = pmxi_getExtensionFromStr($url);
                                                 $default_extension = pmxi_getExtension($bn);
                                                 if ($img_ext == "") {
                                                     $img_ext = pmxi_get_remote_image_ext($url);
                                                 }
                                             }
                                             $logger and call_user_func($logger, sprintf(__('- Importing image `%s` for `%s` ...', 'wp_all_import_plugin'), $img_url, $articleData['post_title']));
                                             // generate local file name
                                             $image_name = urldecode(($this->options[$option_slug . 'auto_rename_images'] and !empty($auto_rename_images_bundle[$slug][$i])) ? sanitize_file_name($img_ext ? str_replace("." . $default_extension, "", $auto_rename_images_bundle[$slug][$i]) : $auto_rename_images_bundle[$slug][$i]) : sanitize_file_name($img_ext ? str_replace("." . $default_extension, "", $bn) : $bn)) . ("" != $img_ext ? '.' . $img_ext : '');
                                             // if wizard store image data to custom field
                                             $create_image = false;
                                             $download_image = true;
                                             $wp_filetype = false;
                                             if ($bundle_data['type'] == 'images' and base64_decode($url, true) !== false) {
                                                 $img = @imagecreatefromstring(base64_decode($url));
                                                 if ($img) {
                                                     $logger and call_user_func($logger, __('- Founded base64_encoded image', 'wp_all_import_plugin'));
                                                     $image_filename = md5(time()) . '.jpg';
                                                     $image_filepath = $targetDir . '/' . $image_filename;
                                                     imagejpeg($img, $image_filepath);
                                                     if (!($image_info = @getimagesize($image_filepath)) or !in_array($image_info[2], array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG))) {
                                                         $logger and call_user_func($logger, sprintf(__('- <b>WARNING</b>: File %s is not a valid image and cannot be set as featured one', 'wp_all_import_plugin'), $image_filepath));
                                                         $logger and !$is_cron and PMXI_Plugin::$session->warnings++;
                                                     } else {
                                                         $create_image = true;
                                                     }
                                                 }
                                             } else {
                                                 $image_filename = wp_unique_filename($targetDir, $image_name);
                                                 $image_filepath = $targetDir . '/' . $image_filename;
                                                 // keep existing and add newest images
                                                 if ($is_keep_existing_images) {
                                                     $attch = $this->wpdb->get_row($this->wpdb->prepare("SELECT * FROM " . $this->wpdb->posts . " WHERE (post_title = %s OR post_title = %s OR post_name = %s) AND post_type = %s AND post_parent = %d;", $image_name, preg_replace('/\\.[^.\\s]{3,4}$/', '', $image_name), sanitize_title($image_name), "attachment", $pid));
                                                     if ($attch != null) {
                                                         $post_thumbnail_id = get_post_thumbnail_id($pid);
                                                         if ($post_thumbnail_id == $attch->ID or in_array($attch->ID, $gallery_attachment_ids)) {
                                                             continue;
                                                         }
                                                     } elseif (file_exists($targetDir . '/' . $image_name)) {
                                                         if ($bundle_data['type'] == 'images' and $img_meta = wp_read_image_metadata($targetDir . '/' . $image_name)) {
                                                             if (trim($img_meta['title']) && !is_numeric(sanitize_title($img_meta['title']))) {
                                                                 $img_title = $img_meta['title'];
                                                                 $attch = $this->wpdb->get_row($this->wpdb->prepare("SELECT * FROM " . $this->wpdb->posts . " WHERE post_title = %s AND post_type = %s AND post_parent = %d;", $img_title, "attachment", $pid));
                                                                 if ($attch != null) {
                                                                     $post_thumbnail_id = get_post_thumbnail_id($pid);
                                                                     if ($post_thumbnail_id == $attch->ID or in_array($attch->ID, $gallery_attachment_ids)) {
                                                                         continue;
                                                                     }
                                                                 }
                                                             }
                                                         }
                                                     }
                                                 }
                                                 // search existing attachment
                                                 if ($this->options[$option_slug . 'search_existing_images']) {
                                                     $image_filename = $image_name;
                                                     $attch = $this->wpdb->get_row($this->wpdb->prepare("SELECT * FROM " . $this->wpdb->posts . " WHERE (post_title = %s OR post_title = %s OR post_name = %s) AND post_type = %s;", $image_name, preg_replace('/\\.[^.\\s]{3,4}$/', '', $image_name), sanitize_title($image_name), "attachment"));
                                                     if ($attch != null) {
                                                         $download_image = false;
                                                         $attid = $attch->ID;
                                                     } elseif (@file_exists($targetDir . '/' . $image_name)) {
                                                         if ($bundle_data['type'] == 'images' and $img_meta = wp_read_image_metadata($targetDir . '/' . $image_name)) {
                                                             if (trim($img_meta['title']) && !is_numeric(sanitize_title($img_meta['title']))) {
                                                                 $img_title = $img_meta['title'];
                                                                 $attch = $this->wpdb->get_row($this->wpdb->prepare("SELECT * FROM " . $this->wpdb->posts . " WHERE post_title = %s AND post_type = %s AND post_parent = %d;", $img_title, "attachment", $pid));
                                                                 if ($attch != null) {
                                                                     $download_image = false;
                                                                     $attid = $attch->ID;
                                                                 }
                                                             }
                                                         }
                                                     }
                                                 }
                                                 if ($download_image) {
                                                     // do not download images
                                                     if ("yes" != $this->options[$option_slug . 'download_images']) {
                                                         $image_filename = $image_name;
                                                         $image_filepath = $targetDir . '/' . $image_filename;
                                                         $wpai_uploads = $uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::FILES_DIRECTORY . DIRECTORY_SEPARATOR;
                                                         $wpai_image_path = $wpai_uploads . str_replace('%20', ' ', $url);
                                                         $logger and call_user_func($logger, sprintf(__('- Searching for existing image `%s` in `%s` folder', 'wp_all_import_plugin'), $wpai_image_path, $wpai_uploads));
                                                         if (@file_exists($wpai_image_path) and @copy($wpai_image_path, $image_filepath)) {
                                                             $download_image = false;
                                                             // valdate import attachments
                                                             if ($bundle_data['type'] == 'files') {
                                                                 if (!($wp_filetype = wp_check_filetype(basename($image_filepath), null))) {
                                                                     $logger and call_user_func($logger, sprintf(__('- <b>WARNING</b>: Can\'t detect attachment file type %s', 'wp_all_import_plugin'), trim($image_filepath)));
                                                                     $logger and !$is_cron and PMXI_Plugin::$session->warnings++;
                                                                     @unlink($image_filepath);
                                                                 } else {
                                                                     $create_image = true;
                                                                     $logger and call_user_func($logger, sprintf(__('- File `%s` has been successfully founded', 'wp_all_import_plugin'), $wpai_image_path));
                                                                 }
                                                             } elseif ($bundle_data['type'] == 'images') {
                                                                 if (!($image_info = @getimagesize($image_filepath)) or !in_array($image_info[2], array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG))) {
                                                                     $logger and call_user_func($logger, sprintf(__('- <b>WARNING</b>: File %s is not a valid image and cannot be set as featured one', 'wp_all_import_plugin'), $image_filepath));
                                                                     $logger and !$is_cron and PMXI_Plugin::$session->warnings++;
                                                                     @unlink($image_filepath);
                                                                 } else {
                                                                     $create_image = true;
                                                                     $logger and call_user_func($logger, sprintf(__('- Image `%s` has been successfully founded', 'wp_all_import_plugin'), $wpai_image_path));
                                                                 }
                                                             }
                                                         }
                                                     } else {
                                                         $logger and call_user_func($logger, sprintf(__('- Downloading image from `%s`', 'wp_all_import_plugin'), $url));
                                                         $request = get_file_curl($url, $image_filepath);
                                                         if ((is_wp_error($request) or $request === false) and !@file_put_contents($image_filepath, @file_get_contents($url))) {
                                                             @unlink($image_filepath);
                                                             // delete file since failed upload may result in empty file created
                                                         } else {
                                                             if ($bundle_data['type'] == 'images') {
                                                                 if ($image_info = @getimagesize($image_filepath) and in_array($image_info[2], array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG))) {
                                                                     $create_image = true;
                                                                     $logger and call_user_func($logger, sprintf(__('- Image `%s` has been successfully downloaded', 'wp_all_import_plugin'), $url));
                                                                 }
                                                             } elseif ($bundle_data['type'] == 'files') {
                                                                 if ($wp_filetype = wp_check_filetype(basename($image_filepath), null)) {
                                                                     $create_image = true;
                                                                     $logger and call_user_func($logger, sprintf(__('- File `%s` has been successfully downloaded', 'wp_all_import_plugin'), $url));
                                                                 }
                                                             }
                                                         }
                                                         if (!$create_image) {
                                                             $url = str_replace(" ", "%20", trim(pmxi_convert_encoding($img_url)));
                                                             $request = get_file_curl($url, $image_filepath);
                                                             if ((is_wp_error($request) or $request === false) and !@file_put_contents($image_filepath, @file_get_contents($url))) {
                                                                 $logger and call_user_func($logger, sprintf(__('- <b>WARNING</b>: File %s cannot be saved locally as %s', 'wp_all_import_plugin'), $url, $image_filepath));
                                                                 $logger and !$is_cron and PMXI_Plugin::$session->warnings++;
                                                                 @unlink($image_filepath);
                                                                 // delete file since failed upload may result in empty file created
                                                             } else {
                                                                 if ($bundle_data['type'] == 'images') {
                                                                     if (!($image_info = @getimagesize($image_filepath)) or !in_array($image_info[2], array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG))) {
                                                                         $logger and call_user_func($logger, sprintf(__('- <b>WARNING</b>: File %s is not a valid image and cannot be set as featured one', 'wp_all_import_plugin'), $url));
                                                                         $logger and !$is_cron and PMXI_Plugin::$session->warnings++;
                                                                         @unlink($image_filepath);
                                                                     } else {
                                                                         $create_image = true;
                                                                         $logger and call_user_func($logger, sprintf(__('- Image `%s` has been successfully downloaded', 'wp_all_import_plugin'), $url));
                                                                     }
                                                                 } elseif ($bundle_data['type'] == 'files') {
                                                                     if (!($wp_filetype = wp_check_filetype(basename($image_filepath), null))) {
                                                                         $logger and call_user_func($logger, sprintf(__('- <b>WARNING</b>: Can\'t detect attachment file type %s', 'wp_all_import_plugin'), trim($url)));
                                                                         $logger and !$is_cron and PMXI_Plugin::$session->warnings++;
                                                                         @unlink($image_filepath);
                                                                     } else {
                                                                         $create_image = true;
                                                                         $logger and call_user_func($logger, sprintf(__('- File `%s` has been successfully founded', 'wp_all_import_plugin'), $url));
                                                                     }
                                                                 }
                                                             }
                                                         }
                                                     }
                                                 }
                                             }
                                             if ($create_image) {
                                                 $logger and call_user_func($logger, sprintf(__('- Creating an attachment for image `%s`', 'wp_all_import_plugin'), $targetUrl . '/' . $image_filename));
                                                 $attachment = array('post_mime_type' => $bundle_data['type'] == 'images' ? image_type_to_mime_type($image_info[2]) : $wp_filetype['type'], 'guid' => $targetUrl . '/' . $image_filename, 'post_title' => $image_name, 'post_content' => '', 'post_author' => $post_author[$i]);
                                                 if ($bundle_data['type'] == 'images' and $image_meta = wp_read_image_metadata($image_filepath)) {
                                                     if (trim($image_meta['title']) && !is_numeric(sanitize_title($image_meta['title']))) {
                                                         $attachment['post_title'] = $image_meta['title'];
                                                     }
                                                     if (trim($image_meta['caption'])) {
                                                         $attachment['post_content'] = $image_meta['caption'];
                                                     }
                                                 }
                                                 $attid = wp_insert_attachment($attachment, $image_filepath, $pid);
                                                 if (is_wp_error($attid)) {
                                                     $logger and call_user_func($logger, __('- <b>WARNING</b>', 'wp_all_import_plugin') . ': ' . $attid->get_error_message());
                                                     $logger and !$is_cron and PMXI_Plugin::$session->warnings++;
                                                 } else {
                                                     // you must first include the image.php file
                                                     // for the function wp_generate_attachment_metadata() to work
                                                     require_once ABSPATH . 'wp-admin/includes/image.php';
                                                     wp_update_attachment_metadata($attid, wp_generate_attachment_metadata($attid, $image_filepath));
                                                     $update_attachment_meta = array();
                                                     if ($this->options[$option_slug . 'set_image_meta_title'] and !empty($img_titles[$k])) {
                                                         $update_attachment_meta['post_title'] = $img_titles[$k];
                                                     }
                                                     if ($this->options[$option_slug . 'set_image_meta_caption'] and !empty($img_captions[$k])) {
                                                         $update_attachment_meta['post_excerpt'] = $img_captions[$k];
                                                     }
                                                     if ($this->options[$option_slug . 'set_image_meta_description'] and !empty($img_descriptions[$k])) {
                                                         $update_attachment_meta['post_content'] = $img_descriptions[$k];
                                                     }
                                                     if ($this->options[$option_slug . 'set_image_meta_alt'] and !empty($img_alts[$k])) {
                                                         update_post_meta($attid, '_wp_attachment_image_alt', $img_alts[$k]);
                                                     }
                                                     if (!empty($update_attachment_meta)) {
                                                         $this->wpdb->update($this->wpdb->posts, $update_attachment_meta, array('ID' => $attid));
                                                     }
                                                 }
                                             }
                                             if ($attid) {
                                                 if ($attch != null and empty($attch->post_parent)) {
                                                     wp_update_post(array('ID' => $attch->ID, 'post_parent' => $pid));
                                                 }
                                                 $logger and call_user_func($logger, __('- <b>ACTION</b>: ' . $slug, 'wp_all_import_plugin'));
                                                 do_action($slug, $pid, $attid, $image_filepath, $is_keep_existing_images ? 'add_images' : 'update_images');
                                                 $success_images = true;
                                                 $post_thumbnail_id = get_post_thumbnail_id($pid);
                                                 if ($bundle_data['type'] == 'images' and empty($post_thumbnail_id) and $this->options[$option_slug . 'is_featured']) {
                                                     set_post_thumbnail($pid, $attid);
                                                 } elseif (!in_array($attid, $gallery_attachment_ids) and $post_thumbnail_id != $attid) {
                                                     $gallery_attachment_ids[] = $attid;
                                                 }
                                                 $logger and call_user_func($logger, sprintf(__('- Attachment has been successfully created for image `%s`', 'wp_all_import_plugin'), $targetUrl . '/' . $image_filename));
                                             }
                                         }
                                     }
                                     // Set product gallery images
                                     if ($post_type[$i] == "product") {
                                         update_post_meta($pid, '_product_image_gallery', !empty($gallery_attachment_ids) ? implode(',', $gallery_attachment_ids) : '');
                                     }
                                     // Create entry as Draft if no images are downloaded successfully
                                     if (!$success_images and "yes" == $this->options[$option_slug . 'create_draft']) {
                                         $this->wpdb->update($this->wpdb->posts, array('post_status' => 'draft'), array('ID' => $pid));
                                         $logger and call_user_func($logger, sprintf(__('- Post `%s` saved as Draft, because no images are downloaded successfully', 'wp_all_import_plugin'), $articleData['post_title']));
                                     }
                                 }
                             } else {
                                 // Create entry as Draft if no images are downloaded successfully
                                 if ("yes" == $this->options[$option_slug . 'create_draft']) {
                                     $this->wpdb->update($this->wpdb->posts, array('post_status' => 'draft'), array('ID' => $pid));
                                     $logger and call_user_func($logger, sprintf(__('Post `%s` saved as Draft, because no images are downloaded successfully', 'wp_all_import_plugin'), $articleData['post_title']));
                                 }
                             }
                         }
                     }
                 } else {
                     if (!empty($images_bundle)) {
                         foreach ($images_bundle as $slug => $bundle_data) {
                             if (!empty($bundle_data['images'][$i])) {
                                 $imgs = array();
                                 $featured_delim = "yes" == $this->options[$option_slug . 'download_images'] ? $this->options[$option_slug . 'download_featured_delim'] : $this->options[$option_slug . 'featured_delim'];
                                 $line_imgs = explode("\n", $bundle_data['images'][$i]);
                                 if (!empty($line_imgs)) {
                                     foreach ($line_imgs as $line_img) {
                                         $imgs = array_merge($imgs, !empty($featured_delim) ? str_getcsv($line_img, $featured_delim) : array($line_img));
                                     }
                                 }
                                 foreach ($imgs as $img) {
                                     do_action($slug, $pid, false, $img, false);
                                 }
                             }
                         }
                     }
                 }
                 // [/featured image]
                 // [attachments]
                 if (!empty($uploads) and false === $uploads['error'] and !empty($attachments[$i]) and (empty($articleData['ID']) or $this->options['update_all_data'] == "yes" or $this->options['update_all_data'] == "no" and $this->options['is_update_attachments'])) {
                     $targetDir = $uploads['path'];
                     $targetUrl = $uploads['url'];
                     $logger and call_user_func($logger, __('<b>ATTACHMENTS:</b>', 'wp_all_import_plugin'));
                     if (!@is_writable($targetDir)) {
                         $logger and call_user_func($logger, sprintf(__('- <b>ERROR</b>: Target directory %s is not writable', 'wp_all_import_plugin'), trim($targetDir)));
                     } else {
                         // you must first include the image.php file
                         // for the function wp_generate_attachment_metadata() to work
                         require_once ABSPATH . 'wp-admin/includes/image.php';
                         if (!is_array($attachments[$i])) {
                             $attachments[$i] = array($attachments[$i]);
                         }
                         $logger and call_user_func($logger, sprintf(__('- Importing attachments for `%s` ...', 'wp_all_import_plugin'), $articleData['post_title']));
                         foreach ($attachments[$i] as $attachment) {
                             if ("" == $attachment) {
                                 continue;
                             }
                             $atchs = str_getcsv($attachment, $this->options['atch_delim']);
                             if (!empty($atchs)) {
                                 foreach ($atchs as $atch_url) {
                                     if (empty($atch_url)) {
                                         continue;
                                     }
                                     $download_file = true;
                                     $atch_url = str_replace(" ", "%20", trim($atch_url));
                                     $attachment_filename = urldecode(basename(parse_url(trim($atch_url), PHP_URL_PATH)));
                                     $attachment_filepath = $targetDir . '/' . sanitize_file_name($attachment_filename);
                                     if ($this->options['is_search_existing_attach']) {
                                         // search existing attachment
                                         $attch = $this->wpdb->get_row($this->wpdb->prepare("SELECT * FROM " . $this->wpdb->posts . " WHERE (post_title = %s OR post_title = %s OR post_name = %s OR post_name = %s) AND post_type = %s;", $attachment_filename, preg_replace('/\\.[^.\\s]{3,4}$/', '', $attachment_filename), sanitize_title($attachment_filename), sanitize_title(preg_replace('/\\.[^.\\s]{3,4}$/', '', $attachment_filename)), "attachment"));
                                         if ($attch != null) {
                                             $download_file = false;
                                             $attach_id = $attch->ID;
                                         }
                                     }
                                     if ($download_file) {
                                         $attachment_filename = wp_unique_filename($targetDir, $attachment_filename);
                                         $attachment_filepath = $targetDir . '/' . sanitize_file_name($attachment_filename);
                                         $logger and call_user_func($logger, sprintf(__('- Filename for attachment was generated as %s', 'wp_all_import_plugin'), $attachment_filename));
                                         $request = get_file_curl(trim($atch_url), $attachment_filepath);
                                         if ((is_wp_error($request) or $request === false) and !@file_put_contents($attachment_filepath, @file_get_contents(trim($atch_url)))) {
                                             $logger and call_user_func($logger, sprintf(__('- <b>WARNING</b>: Attachment file %s cannot be saved locally as %s', 'wp_all_import_plugin'), trim($atch_url), $attachment_filepath));
                                             is_wp_error($request) and $logger and call_user_func($logger, sprintf(__('- <b>WP Error</b>: %s', 'wp_all_import_plugin'), $request->get_error_message()));
                                             $logger and !$is_cron and PMXI_Plugin::$session->warnings++;
                                             unlink($attachment_filepath);
                                             // delete file since failed upload may result in empty file created
                                         } elseif (!($wp_filetype = wp_check_filetype(basename($attachment_filename), null))) {
                                             $logger and call_user_func($logger, sprintf(__('- <b>WARNING</b>: Can\'t detect attachment file type %s', 'wp_all_import_plugin'), trim($atch_url)));
                                             $logger and !$is_cron and PMXI_Plugin::$session->warnings++;
                                         } else {
                                             $logger and call_user_func($logger, sprintf(__('- File %s has been successfully downloaded', 'wp_all_import_plugin'), $atch_url));
                                             $attachment_data = array('guid' => $targetUrl . '/' . basename($attachment_filepath), 'post_mime_type' => $wp_filetype['type'], 'post_title' => preg_replace('/\\.[^.]+$/', '', basename($attachment_filepath)), 'post_content' => '', 'post_status' => 'inherit', 'post_author' => $post_author[$i]);
                                             $attach_id = wp_insert_attachment($attachment_data, $attachment_filepath, $pid);
                                             if (is_wp_error($attach_id)) {
                                                 $logger and call_user_func($logger, __('- <b>WARNING</b>', 'wp_all_import_plugin') . ': ' . $pid->get_error_message());
                                                 $logger and !$is_cron and PMXI_Plugin::$session->warnings++;
                                             } else {
                                                 wp_update_attachment_metadata($attach_id, wp_generate_attachment_metadata($attach_id, $attachment_filepath));
                                                 $logger and call_user_func($logger, sprintf(__('- Attachment has been successfully created for post `%s`', 'wp_all_import_plugin'), $articleData['post_title']));
                                                 $logger and call_user_func($logger, __('- <b>ACTION</b>: pmxi_attachment_uploaded', 'wp_all_import_plugin'));
                                                 do_action('pmxi_attachment_uploaded', $pid, $attach_id, $attachment_filepath);
                                             }
                                         }
                                     } else {
                                         $logger and call_user_func($logger, __('- <b>ACTION</b>: pmxi_attachment_uploaded', 'wp_all_import_plugin'));
                                         do_action('pmxi_attachment_uploaded', $pid, $attach_id, $attachment_filepath);
                                     }
                                 }
                             }
                         }
                     }
                 }
                 // [/attachments]
                 // [custom taxonomies]
                 if (!empty($taxonomies)) {
                     $logger and call_user_func($logger, __('<b>TAXONOMIES:</b>', 'wp_all_import_plugin'));
                     foreach ($taxonomies as $tx_name => $txes) {
                         // Skip updating product attributes
                         if (PMXI_Admin_Addons::get_addon('PMWI_Plugin') and strpos($tx_name, "pa_") === 0) {
                             continue;
                         }
                         if (empty($articleData['ID']) or $this->options['update_all_data'] == "yes" or $this->options['update_all_data'] == "no" and $this->options['is_update_categories']) {
                             $logger and call_user_func($logger, sprintf(__('- Importing taxonomy `%s` ...', 'wp_all_import_plugin'), $tx_name));
                             if (!empty($this->options['tax_logic'][$tx_name]) and $this->options['tax_logic'][$tx_name] == 'hierarchical' and !empty($this->options['tax_hierarchical_logic'][$tx_name]) and $this->options['tax_hierarchical_logic'][$tx_name] == 'entire') {
                                 $logger and call_user_func($logger, sprintf(__('- Auto-nest enabled with separator `%s` ...', 'wp_all_import_plugin'), !empty($this->options['tax_hierarchical_delim'][$tx_name]) ? $this->options['tax_hierarchical_delim'][$tx_name] : ','));
                             }
                             if (!empty($articleData['ID'])) {
                                 if ($this->options['update_all_data'] == "no" and $this->options['update_categories_logic'] == "all_except" and !empty($this->options['taxonomies_list']) and is_array($this->options['taxonomies_list']) and in_array($tx_name, $this->options['taxonomies_list'])) {
                                     $logger and call_user_func($logger, sprintf(__('- %s %s `%s` has been skipped attempted to `Leave these taxonomies alone, update all others`...', 'wp_all_import_plugin'), $custom_type_details->labels->singular_name, $tx_name, $single_tax['name']));
                                     continue;
                                 }
                                 if ($this->options['update_all_data'] == "no" and $this->options['update_categories_logic'] == "only" and (!empty($this->options['taxonomies_list']) and is_array($this->options['taxonomies_list']) and !in_array($tx_name, $this->options['taxonomies_list']) or empty($this->options['taxonomies_list']))) {
                                     $logger and call_user_func($logger, sprintf(__('- %s %s `%s` has been skipped attempted to `Update only these taxonomies, leave the rest alone`...', 'wp_all_import_plugin'), $custom_type_details->labels->singular_name, $tx_name, $single_tax['name']));
                                     continue;
                                 }
                             }
                             $assign_taxes = array();
                             if ($this->options['update_categories_logic'] == "add_new" and !empty($existing_taxonomies[$tx_name][$i])) {
                                 $assign_taxes = $existing_taxonomies[$tx_name][$i];
                                 unset($existing_taxonomies[$tx_name][$i]);
                             } elseif (!empty($existing_taxonomies[$tx_name][$i])) {
                                 unset($existing_taxonomies[$tx_name][$i]);
                             }
                             // create term if not exists
                             if (!empty($txes[$i])) {
                                 foreach ($txes[$i] as $key => $single_tax) {
                                     $is_created_term = false;
                                     if (is_array($single_tax) and !empty($single_tax['name'])) {
                                         $parent_id = !empty($single_tax['parent']) ? pmxi_recursion_taxes($single_tax['parent'], $tx_name, $txes[$i], $key) : '';
                                         $term = empty($this->options['tax_is_full_search_' . $this->options['tax_logic'][$tx_name]][$tx_name]) ? term_exists($single_tax['name'], $tx_name, (int) $parent_id) : term_exists($single_tax['name'], $tx_name);
                                         if (empty($term) and !is_wp_error($term)) {
                                             $term = empty($this->options['tax_is_full_search_' . $this->options['tax_logic'][$tx_name]][$tx_name]) ? term_exists(htmlspecialchars($single_tax['name']), $tx_name, (int) $parent_id) : term_exists(htmlspecialchars($single_tax['name']), $tx_name);
                                             if (empty($term) and !is_wp_error($term)) {
                                                 $term_attr = array('parent' => !empty($parent_id) ? $parent_id : 0);
                                                 $term = wp_insert_term($single_tax['name'], $tx_name, $term_attr);
                                                 if (!is_wp_error($term)) {
                                                     $is_created_term = true;
                                                     if (empty($parent_id)) {
                                                         $logger and call_user_func($logger, sprintf(__('- Creating parent %s %s `%s` ...', 'wp_all_import_plugin'), $custom_type_details->labels->singular_name, $tx_name, $single_tax['name']));
                                                     } else {
                                                         $logger and call_user_func($logger, sprintf(__('- Creating child %s %s for %s named `%s` ...', 'wp_all_import_plugin'), $custom_type_details->labels->singular_name, $tx_name, is_array($single_tax['parent']) ? $single_tax['parent']['name'] : $single_tax['parent'], $single_tax['name']));
                                                     }
                                                 }
                                             }
                                         }
                                         if (is_wp_error($term)) {
                                             $logger and call_user_func($logger, sprintf(__('- <b>WARNING</b>: `%s`', 'wp_all_import_plugin'), $term->get_error_message()));
                                             $logger and !$is_cron and PMXI_Plugin::$session->warnings++;
                                         } elseif (!empty($term)) {
                                             $cat_id = $term['term_id'];
                                             if ($cat_id and $single_tax['assign']) {
                                                 $term = get_term_by('id', $cat_id, $tx_name);
                                                 if ($term->parent != '0' and !empty($this->options['tax_is_full_search_' . $this->options['tax_logic'][$tx_name]][$tx_name]) and empty($this->options['tax_assign_to_one_term_' . $this->options['tax_logic'][$tx_name]][$tx_name])) {
                                                     $parent_ids = wp_all_import_get_parent_terms($cat_id, $tx_name);
                                                     if (!empty($parent_ids)) {
                                                         foreach ($parent_ids as $p) {
                                                             if (!in_array($p, $assign_taxes)) {
                                                                 $assign_taxes[] = $p;
                                                             }
                                                         }
                                                     }
                                                 }
                                                 if (!in_array($term->term_taxonomy_id, $assign_taxes)) {
                                                     $assign_taxes[] = $term->term_taxonomy_id;
                                                 }
                                                 if (!$is_created_term) {
                                                     if (empty($parent_id)) {
                                                         $logger and call_user_func($logger, sprintf(__('- Attempted to create parent %s %s `%s`, duplicate detected. Importing %s to existing `%s` %s, ID %d, slug `%s` ...', 'wp_all_import_plugin'), $custom_type_details->labels->singular_name, $tx_name, $single_tax['name'], $custom_type_details->labels->singular_name, $term->name, $tx_name, $term->term_id, $term->slug));
                                                     } else {
                                                         $logger and call_user_func($logger, sprintf(__('- Attempted to create child %s %s `%s`, duplicate detected. Importing %s to existing `%s` %s, ID %d, slug `%s` ...', 'wp_all_import_plugin'), $custom_type_details->labels->singular_name, $tx_name, $single_tax['name'], $custom_type_details->labels->singular_name, $term->name, $tx_name, $term->term_id, $term->slug));
                                                     }
                                                 }
                                             }
                                         }
                                     }
                                 }
                             }
                             // associate taxes with post
                             $this->associate_terms($pid, empty($assign_taxes) ? false : $assign_taxes, $tx_name, $logger, $is_cron);
                         } else {
                             $logger and call_user_func($logger, sprintf(__('- %s %s `%s` has been skipped attempted to `Do not update Taxonomies (incl. Categories and Tags)`...', 'wp_all_import_plugin'), $custom_type_details->labels->singular_name, $tx_name, $single_tax['name']));
                         }
                     }
                     if ($this->options['update_all_data'] == "no" and ($this->options['is_update_categories'] and $this->options['update_categories_logic'] != 'full_update' or !$this->options['is_update_categories'] and (is_object_in_taxonomy($post_type[$i], 'category') or is_object_in_taxonomy($post_type[$i], 'post_tag')))) {
                         if (!empty($existing_taxonomies)) {
                             foreach ($existing_taxonomies as $tx_name => $txes) {
                                 // Skip updating product attributes
                                 if (PMXI_Admin_Addons::get_addon('PMWI_Plugin') and strpos($tx_name, "pa_") === 0) {
                                     continue;
                                 }
                                 if (!empty($txes[$i])) {
                                     $this->associate_terms($pid, $txes[$i], $tx_name, $logger, $is_cron);
                                 }
                             }
                         }
                     }
                 }
                 // [/custom taxonomies]
                 if (empty($articleData['ID'])) {
                     $logger and call_user_func($logger, sprintf(__('<b>CREATED</b> `%s` `%s` (ID: %s)', 'wp_all_import_plugin'), $articleData['post_title'], $custom_type_details->labels->singular_name, $pid));
                 } else {
                     $logger and call_user_func($logger, sprintf(__('<b>UPDATED</b> `%s` `%s` (ID: %s)', 'wp_all_import_plugin'), $articleData['post_title'], $custom_type_details->labels->singular_name, $pid));
                 }
                 // fire important hooks after custom fields are added
                 if (!$this->options['is_fast_mode'] and $this->options['custom_type'] != 'import_users') {
                     $post_object = get_post($pid);
                     $is_update = !empty($articleData['ID']);
                     do_action("save_post_" . $articleData['post_type'], $pid, $post_object, $is_update);
                     do_action('save_post', $pid, $post_object, $is_update);
                     do_action('wp_insert_post', $pid, $post_object, $is_update);
                 }
                 // [addons import]
                 // prepare data for import
                 $importData = array('pid' => $pid, 'import' => $this, 'logger' => $logger);
                 $saved_functions = apply_filters('wp_all_import_addon_saved_post', array());
                 // deligate operation to addons
                 foreach (PMXI_Admin_Addons::get_active_addons() as $class) {
                     if (class_exists($class)) {
                         if (method_exists($addons[$class], 'saved_post')) {
                             $addons[$class]->saved_post($importData);
                         }
                     } else {
                         if (!empty($saved_functions[$class])) {
                             if (is_array($saved_functions[$class]) and is_callable($saved_functions[$class]) or !is_array($saved_functions[$class]) and function_exists($saved_functions[$class])) {
                                 call_user_func($saved_functions[$class], $importData);
                             }
                         }
                     }
                 }
                 // [/addons import]
                 $logger and call_user_func($logger, __('<b>ACTION</b>: pmxi_saved_post', 'wp_all_import_plugin'));
                 do_action('pmxi_saved_post', $pid, $rootNodes[$i]);
                 // hook that was triggered immediately after post saved
                 if (empty($articleData['ID'])) {
                     $created++;
                 } else {
                     $updated++;
                 }
                 if (!$is_cron and "default" == $this->options['import_processing']) {
                     $processed_records = $created + $updated + $skipped;
                     $logger and call_user_func($logger, sprintf(__('<span class="processing_info"><span class="created_count">%s</span><span class="updated_count">%s</span><span class="percents_count">%s</span></span>', 'wp_all_import_plugin'), $created, $updated, ceil($processed_records / $this->count * 100)));
                 }
             }
             $logger and call_user_func($logger, __('<b>ACTION</b>: pmxi_after_post_import', 'wp_all_import_plugin'));
             do_action('pmxi_after_post_import', $this->id);
             $logger and !$is_cron and PMXI_Plugin::$session->chunk_number++;
         }
         wp_cache_flush();
         $this->set(array('imported' => $created + $updated, 'created' => $created, 'updated' => $updated, 'skipped' => $skipped, 'last_activity' => date('Y-m-d H:i:s')))->update();
         if (!$is_cron) {
             PMXI_Plugin::$session->save_data();
             $records_count = $this->created + $this->updated + $this->skipped;
             $is_import_complete = $records_count == $this->count;
             // Delete posts that are no longer present in your file
             if ($is_import_complete and !empty($this->options['is_delete_missing']) and $this->options['duplicate_matching'] == 'auto') {
                 $logger and call_user_func($logger, __('Removing previously imported posts which are no longer actual...', 'wp_all_import_plugin'));
                 $postList = new PMXI_Post_List();
                 $missing_ids = array();
                 $missingPosts = $postList->getBy(array('import_id' => $this->id, 'iteration !=' => $this->iteration));
                 if (!$missingPosts->isEmpty()) {
                     foreach ($missingPosts as $missingPost) {
                         $missing_ids[] = $missingPost['post_id'];
                     }
                 }
                 // Delete posts from database
                 if (!empty($missing_ids) && is_array($missing_ids)) {
                     $logger and call_user_func($logger, __('<b>ACTION</b>: pmxi_delete_post', 'wp_all_import_plugin'));
                     $logger and call_user_func($logger, __('Deleting posts from database', 'wp_all_import_plugin'));
                     $missing_ids_arr = array_chunk($missing_ids, 100);
                     foreach ($missing_ids_arr as $key => $ids) {
                         if (!empty($ids)) {
                             foreach ($ids as $k => $id) {
                                 $to_delete = true;
                                 // Instead of deletion, set Custom Field
                                 if ($this->options['is_update_missing_cf']) {
                                     update_post_meta($id, $this->options['update_missing_cf_name'], $this->options['update_missing_cf_value']);
                                     $to_delete = false;
                                     $logger and call_user_func($logger, sprintf(__('Instead of deletion post with ID `%s`, set Custom Field `%s` to value `%s`', 'wp_all_import_plugin'), $id, $this->options['update_missing_cf_name'], $this->options['update_missing_cf_value']));
                                 }
                                 // Instead of deletion, change post status to Draft
                                 if ($this->options['set_missing_to_draft']) {
                                     $this->wpdb->update($this->wpdb->posts, array('post_status' => 'draft'), array('ID' => $id));
                                     $to_delete = false;
                                     $logger and call_user_func($logger, sprintf(__('Instead of deletion, change post with ID `%s` status to Draft', 'wp_all_import_plugin'), $id));
                                 }
                                 if ($to_delete) {
                                     // Remove attachments
                                     empty($this->options['is_keep_attachments']) and wp_delete_attachments($id, true, 'files');
                                     // Remove images
                                     empty($this->options['is_keep_imgs']) and wp_delete_attachments($id, true, 'images');
                                     // Clear post's relationships
                                     if ($post_type[$i] != "import_users") {
                                         wp_delete_object_term_relationships($id, get_object_taxonomies('' != $this->options['custom_type'] ? $this->options['custom_type'] : 'post'));
                                     }
                                 } else {
                                     unset($ids[$k]);
                                 }
                             }
                             if (!empty($ids)) {
                                 do_action('pmxi_delete_post', $ids);
                                 if ($this->options['custom_type'] == "import_users") {
                                     $sql = "delete a,b\n\t\t\t\t\t\t\t\t\t\tFROM " . $this->wpdb->users . " a\n\t\t\t\t\t\t\t\t\t\tLEFT JOIN " . $this->wpdb->usermeta . " b ON ( a.ID = b.user_id )\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\tWHERE a.ID IN (" . implode(',', $ids) . ");";
                                 } else {
                                     $sql = "delete a,b,c\n\t\t\t\t\t\t\t\t\t\tFROM " . $this->wpdb->posts . " a\n\t\t\t\t\t\t\t\t\t\tLEFT JOIN " . $this->wpdb->term_relationships . " b ON ( a.ID = b.object_id )\n\t\t\t\t\t\t\t\t\t\tLEFT JOIN " . $this->wpdb->postmeta . " c ON ( a.ID = c.post_id )\t\t\t\t\n\t\t\t\t\t\t\t\t\t\tWHERE a.ID IN (" . implode(',', $ids) . ");";
                                 }
                                 $this->wpdb->query($sql);
                                 // Delete record form pmxi_posts
                                 $sql = "DELETE FROM " . PMXI_Plugin::getInstance()->getTablePrefix() . "posts WHERE post_id IN (" . implode(',', $ids) . ") AND import_id = %d";
                                 $this->wpdb->query($this->wpdb->prepare($sql, $this->id));
                                 $this->set(array('deleted' => $this->deleted + count($ids)))->update();
                             }
                         }
                     }
                 }
             }
             // Set out of stock status for missing records [Woocommerce add-on option]
             if ($is_import_complete and empty($this->options['is_delete_missing']) and $post_type[$i] == "product" and class_exists('PMWI_Plugin') and !empty($this->options['missing_records_stock_status'])) {
                 $logger and call_user_func($logger, __('Update stock status previously imported posts which are no longer actual...', 'wp_all_import_plugin'));
                 $postList = new PMXI_Post_List();
                 $missingPosts = $postList->getBy(array('import_id' => $this->id, 'iteration !=' => $this->iteration));
                 if (!$missingPosts->isEmpty()) {
                     foreach ($missingPosts as $missingPost) {
                         update_post_meta($missingPost['post_id'], '_stock_status', 'outofstock');
                         update_post_meta($missingPost['post_id'], '_stock', 0);
                         $missingPostRecord = new PMXI_Post_Record();
                         $missingPostRecord->getBy('id', $missingPost['id']);
                         if (!$missingPostRecord->isEmpty()) {
                             $missingPostRecord->set(array('iteration' => $this->iteration))->update();
                         }
                         unset($missingPostRecord);
                     }
                 }
             }
         }
     } catch (XmlImportException $e) {
         $logger and call_user_func($logger, __('<b>ERROR</b>', 'wp_all_import_plugin') . ': ' . $e->getMessage());
         $logger and !$is_cron and PMXI_Plugin::$session->errors++;
     }
     $logger and $is_import_complete and call_user_func($logger, __('Cleaning temporary data...', 'wp_all_import_plugin'));
     foreach ($tmp_files as $file) {
         // remove all temporary files created
         @unlink($file);
     }
     if (($is_cron or $is_import_complete) and $this->options['is_delete_source']) {
         $logger and call_user_func($logger, __('Deleting source XML file...', 'wp_all_import_plugin'));
         // Delete chunks
         foreach (PMXI_Helper::safe_glob($uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::TEMP_DIRECTORY . DIRECTORY_SEPARATOR . 'pmxi_chunk_*', PMXI_Helper::GLOB_RECURSE | PMXI_Helper::GLOB_PATH) as $filePath) {
             $logger and call_user_func($logger, __('Deleting chunks files...', 'wp_all_import_plugin'));
             @file_exists($filePath) and wp_all_import_remove_source($filePath, false);
         }
         if ($this->type != "ftp") {
             if (!@unlink($this->path)) {
                 $logger and call_user_func($logger, sprintf(__('<b>WARNING</b>: Unable to remove %s', 'wp_all_import_plugin'), $this->path));
             }
         } else {
             $file_path_array = PMXI_Helper::safe_glob($this->path, PMXI_Helper::GLOB_NODIR | PMXI_Helper::GLOB_PATH);
             if (!empty($file_path_array)) {
                 foreach ($file_path_array as $path) {
                     if (!@unlink($path)) {
                         $logger and call_user_func($logger, sprintf(__('<b>WARNING</b>: Unable to remove %s', 'wp_all_import_plugin'), $path));
                     }
                 }
             }
         }
     }
     if (!$is_cron and $is_import_complete) {
         $this->set(array('processing' => 0, 'triggered' => 0, 'queue_chunk_number' => 0, 'registered_on' => date('Y-m-d H:i:s'), 'iteration' => ++$this->iteration))->update();
         $logger and call_user_func($logger, 'Done');
     }
     remove_filter('user_has_cap', array($this, '_filter_has_cap_unfiltered_html'));
     kses_init();
     // return any filtering rules back if they has been disabled for import procedure
     return $this;
 }
 public function remove_kses_filters()
 {
     if (current_user_can('unfiltered_html')) {
         kses_remove_filters();
     }
 }
Example #23
0
/**
 * Handles the submission of a comment, usually posted to wp-comments-post.php via a comment form.
 *
 * This function expects unslashed data, as opposed to functions such as `wp_new_comment()` which
 * expect slashed data.
 *
 * @since 4.4.0
 *
 * @param array $comment_data {
 *     Comment data.
 *
 *     @type string|int $comment_post_ID             The ID of the post that relates to the comment.
 *     @type string     $author                      The name of the comment author.
 *     @type string     $email                       The comment author email address.
 *     @type string     $url                         The comment author URL.
 *     @type string     $comment                     The content of the comment.
 *     @type string|int $comment_parent              The ID of this comment's parent, if any. Default 0.
 *     @type string     $_wp_unfiltered_html_comment The nonce value for allowing unfiltered HTML.
 * }
 * @return WP_Comment|WP_Error A WP_Comment object on success, a WP_Error object on failure.
 */
function wp_handle_comment_submission($comment_data)
{
    $comment_post_ID = $comment_parent = 0;
    $comment_author = $comment_author_email = $comment_author_url = $comment_content = $_wp_unfiltered_html_comment = null;
    if (isset($comment_data['comment_post_ID'])) {
        $comment_post_ID = (int) $comment_data['comment_post_ID'];
    }
    if (isset($comment_data['author']) && is_string($comment_data['author'])) {
        $comment_author = trim(strip_tags($comment_data['author']));
    }
    if (isset($comment_data['email']) && is_string($comment_data['email'])) {
        $comment_author_email = trim($comment_data['email']);
    }
    if (isset($comment_data['url']) && is_string($comment_data['url'])) {
        $comment_author_url = trim($comment_data['url']);
    }
    if (isset($comment_data['comment']) && is_string($comment_data['comment'])) {
        $comment_content = trim($comment_data['comment']);
    }
    if (isset($comment_data['comment_parent'])) {
        $comment_parent = absint($comment_data['comment_parent']);
    }
    if (isset($comment_data['_wp_unfiltered_html_comment']) && is_string($comment_data['_wp_unfiltered_html_comment'])) {
        $_wp_unfiltered_html_comment = trim($comment_data['_wp_unfiltered_html_comment']);
    }
    $post = get_post($comment_post_ID);
    if (empty($post->comment_status)) {
        /**
         * Fires when a comment is attempted on a post that does not exist.
         *
         * @since 1.5.0
         *
         * @param int $comment_post_ID Post ID.
         */
        do_action('comment_id_not_found', $comment_post_ID);
        return new WP_Error('comment_id_not_found');
    }
    // get_post_status() will get the parent status for attachments.
    $status = get_post_status($post);
    $status_obj = get_post_status_object($status);
    if (!comments_open($comment_post_ID)) {
        /**
         * Fires when a comment is attempted on a post that has comments closed.
         *
         * @since 1.5.0
         *
         * @param int $comment_post_ID Post ID.
         */
        do_action('comment_closed', $comment_post_ID);
        return new WP_Error('comment_closed', __('Sorry, comments are closed for this item.'), 403);
    } elseif ('trash' == $status) {
        /**
         * Fires when a comment is attempted on a trashed post.
         *
         * @since 2.9.0
         *
         * @param int $comment_post_ID Post ID.
         */
        do_action('comment_on_trash', $comment_post_ID);
        return new WP_Error('comment_on_trash');
    } elseif (!$status_obj->public && !$status_obj->private) {
        /**
         * Fires when a comment is attempted on a post in draft mode.
         *
         * @since 1.5.1
         *
         * @param int $comment_post_ID Post ID.
         */
        do_action('comment_on_draft', $comment_post_ID);
        return new WP_Error('comment_on_draft');
    } elseif (post_password_required($comment_post_ID)) {
        /**
         * Fires when a comment is attempted on a password-protected post.
         *
         * @since 2.9.0
         *
         * @param int $comment_post_ID Post ID.
         */
        do_action('comment_on_password_protected', $comment_post_ID);
        return new WP_Error('comment_on_password_protected');
    } else {
        /**
         * Fires before a comment is posted.
         *
         * @since 2.8.0
         *
         * @param int $comment_post_ID Post ID.
         */
        do_action('pre_comment_on_post', $comment_post_ID);
    }
    // If the user is logged in
    $user = wp_get_current_user();
    if ($user->exists()) {
        if (empty($user->display_name)) {
            $user->display_name = $user->user_login;
        }
        $comment_author = $user->display_name;
        $comment_author_email = $user->user_email;
        $comment_author_url = $user->user_url;
        if (current_user_can('unfiltered_html')) {
            if (!isset($comment_data['_wp_unfiltered_html_comment']) || !wp_verify_nonce($comment_data['_wp_unfiltered_html_comment'], 'unfiltered-html-comment_' . $comment_post_ID)) {
                kses_remove_filters();
                // start with a clean slate
                kses_init_filters();
                // set up the filters
            }
        }
    } else {
        if (get_option('comment_registration') || 'private' == $status) {
            return new WP_Error('not_logged_in', __('Sorry, you must be logged in to post a comment.'), 403);
        }
    }
    $comment_type = '';
    if (get_option('require_name_email') && !$user->exists()) {
        if (6 > strlen($comment_author_email) || '' == $comment_author) {
            return new WP_Error('require_name_email', __('<strong>ERROR</strong>: please fill the required fields (name, email).'), 200);
        } elseif (!is_email($comment_author_email)) {
            return new WP_Error('require_valid_email', __('<strong>ERROR</strong>: please enter a valid email address.'), 200);
        }
    }
    if ('' == $comment_content) {
        return new WP_Error('require_valid_comment', __('<strong>ERROR</strong>: please type a comment.'), 200);
    }
    $commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_content', 'comment_type', 'comment_parent', 'user_ID');
    $comment_id = wp_new_comment(wp_slash($commentdata));
    if (!$comment_id) {
        return new WP_Error('comment_save_error', __('<strong>ERROR</strong>: The comment could not be saved. Please try again later.'), 500);
    }
    return get_comment($comment_id);
}
	/**
	 * @ticket 22944
	 */
	function test_wp_publish_post_and_avoid_content_filtering() {
		kses_remove_filters();

		$post_id = wp_insert_post( array( 'post_title' => '<script>Test</script>' ) );
		$post = get_post( $post_id );
		$this->assertEquals( '<script>Test</script>', $post->post_title );
		$this->assertEquals( 'draft', $post->post_status );

		kses_init_filters();

		wp_publish_post( $post->ID );
		$post = get_post( $post->ID );
		$this->assertEquals( '<script>Test</script>', $post->post_title );

		kses_remove_filters();
	}
/**
 * Mark bad words
 * @global string $ct_stop_words
 * @param int $comment_id
 * @param int $comment_status Not use
 */
function ct_mark_red($comment_id, $comment_status)
{
    global $ct_stop_words;
    $comment = get_comment($comment_id, 'ARRAY_A');
    $message = $comment['comment_content'];
    foreach (explode(':', $ct_stop_words) as $word) {
        $message = preg_replace("/({$word})/ui", '<font rel="cleantalk" color="#FF1000">' . "\$1" . '</font>', $message);
    }
    $comment['comment_content'] = $message;
    kses_remove_filters();
    wp_update_comment($comment);
}
Example #26
0
/**
 * Ajax handler for replying to a comment.
 *
 * @since 3.1.0
 *
 * @global WP_List_Table $wp_list_table
 *
 * @param string $action Action to perform.
 */
function wp_ajax_replyto_comment($action)
{
    global $wp_list_table;
    if (empty($action)) {
        $action = 'replyto-comment';
    }
    check_ajax_referer($action, '_ajax_nonce-replyto-comment');
    $comment_post_ID = (int) $_POST['comment_post_ID'];
    $post = get_post($comment_post_ID);
    if (!$post) {
        wp_die(-1);
    }
    if (!current_user_can('edit_post', $comment_post_ID)) {
        wp_die(-1);
    }
    if (empty($post->post_status)) {
        wp_die(1);
    } elseif (in_array($post->post_status, array('draft', 'pending', 'trash'))) {
        wp_die(__('ERROR: you are replying to a comment on a draft post.'));
    }
    $user = wp_get_current_user();
    if ($user->exists()) {
        $user_ID = $user->ID;
        $comment_author = wp_slash($user->display_name);
        $comment_author_email = wp_slash($user->user_email);
        $comment_author_url = wp_slash($user->user_url);
        $comment_content = trim($_POST['content']);
        $comment_type = isset($_POST['comment_type']) ? trim($_POST['comment_type']) : '';
        if (current_user_can('unfiltered_html')) {
            if (!isset($_POST['_wp_unfiltered_html_comment'])) {
                $_POST['_wp_unfiltered_html_comment'] = '';
            }
            if (wp_create_nonce('unfiltered-html-comment') != $_POST['_wp_unfiltered_html_comment']) {
                kses_remove_filters();
                // start with a clean slate
                kses_init_filters();
                // set up the filters
            }
        }
    } else {
        wp_die(__('Sorry, you must be logged in to reply to a comment.'));
    }
    if ('' == $comment_content) {
        wp_die(__('ERROR: please type a comment.'));
    }
    $comment_parent = 0;
    if (isset($_POST['comment_ID'])) {
        $comment_parent = absint($_POST['comment_ID']);
    }
    $comment_auto_approved = false;
    $commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_content', 'comment_type', 'comment_parent', 'user_ID');
    // Automatically approve parent comment.
    if (!empty($_POST['approve_parent'])) {
        $parent = get_comment($comment_parent);
        if ($parent && $parent->comment_approved === '0' && $parent->comment_post_ID == $comment_post_ID) {
            if (!current_user_can('edit_comment', $parent->comment_ID)) {
                wp_die(-1);
            }
            if (wp_set_comment_status($parent, 'approve')) {
                $comment_auto_approved = true;
            }
        }
    }
    $comment_id = wp_new_comment($commentdata);
    $comment = get_comment($comment_id);
    if (!$comment) {
        wp_die(1);
    }
    $position = isset($_POST['position']) && (int) $_POST['position'] ? (int) $_POST['position'] : '-1';
    ob_start();
    if (isset($_REQUEST['mode']) && 'dashboard' == $_REQUEST['mode']) {
        require_once ABSPATH . 'wp-admin/includes/dashboard.php';
        _wp_dashboard_recent_comments_row($comment);
    } else {
        if (isset($_REQUEST['mode']) && 'single' == $_REQUEST['mode']) {
            $wp_list_table = _get_list_table('WP_Post_Comments_List_Table', array('screen' => 'edit-comments'));
        } else {
            $wp_list_table = _get_list_table('WP_Comments_List_Table', array('screen' => 'edit-comments'));
        }
        $wp_list_table->single_row($comment);
    }
    $comment_list_item = ob_get_clean();
    $response = array('what' => 'comment', 'id' => $comment->comment_ID, 'data' => $comment_list_item, 'position' => $position);
    $counts = wp_count_comments();
    $response['supplemental'] = array('in_moderation' => $counts->moderated, 'i18n_comments_text' => sprintf(_n('%s Comment', '%s Comments', $counts->approved), number_format_i18n($counts->approved)), 'i18n_moderation_text' => sprintf(_nx('%s in moderation', '%s in moderation', $counts->moderated, 'comments'), number_format_i18n($counts->moderated)));
    if ($comment_auto_approved) {
        $response['supplemental']['parent_approved'] = $parent->comment_ID;
        $response['supplemental']['parent_post_id'] = $parent->comment_post_ID;
    }
    $x = new WP_Ajax_Response();
    $x->add($response);
    $x->send();
}
Example #27
0
$comment_author = isset($_POST['author']) ? trim(strip_tags($_POST['author'])) : null;
$comment_author_email = isset($_POST['email']) ? trim($_POST['email']) : null;
$comment_author_url = isset($_POST['url']) ? trim($_POST['url']) : null;
$comment_content = isset($_POST['comment']) ? trim($_POST['comment']) : null;
// If the user is logged in
$user = wp_get_current_user();
if ($user->exists()) {
    if (empty($user->display_name)) {
        $user->display_name = $user->user_login;
    }
    $comment_author = wp_slash($user->display_name);
    $comment_author_email = wp_slash($user->user_email);
    $comment_author_url = wp_slash($user->user_url);
    if (current_user_can('unfiltered_html')) {
        if (!isset($_POST['_wp_unfiltered_html_comment']) || !wp_verify_nonce($_POST['_wp_unfiltered_html_comment'], 'unfiltered-html-comment_' . $comment_post_ID)) {
            kses_remove_filters();
            // start with a clean slate
            kses_init_filters();
            // set up the filters
        }
    }
} else {
    if (get_option('comment_registration') || 'private' == $status) {
        wp_die(__('Sorry, you must be logged in to post a comment.'), 403);
    }
}
$comment_type = '';
if (get_option('require_name_email') && !$user->exists()) {
    if (6 > strlen($comment_author_email) || '' == $comment_author) {
        wp_die(__('<strong>ERROR</strong>: please fill the required fields (name, email).'), 200);
    } elseif (!is_email($comment_author_email)) {
 /**
  * Save the post for the loaded changeset.
  *
  * @since 4.7.0
  * @access public
  *
  * @param array $args {
  *     Args for changeset post.
  *
  *     @type array  $data            Optional additional changeset data. Values will be merged on top of any existing post values.
  *     @type string $status          Post status. Optional. If supplied, the save will be transactional and a post revision will be allowed.
  *     @type string $title           Post title. Optional.
  *     @type string $date_gmt        Date in GMT. Optional.
  *     @type int    $user_id         ID for user who is saving the changeset. Optional, defaults to the current user ID.
  *     @type bool   $starter_content Whether the data is starter content. If false (default), then $starter_content will be cleared for any $data being saved.
  * }
  *
  * @return array|WP_Error Returns array on success and WP_Error with array data on error.
  */
 function save_changeset_post($args = array())
 {
     $args = array_merge(array('status' => null, 'title' => null, 'data' => array(), 'date_gmt' => null, 'user_id' => get_current_user_id(), 'starter_content' => false), $args);
     $changeset_post_id = $this->changeset_post_id();
     $existing_changeset_data = array();
     if ($changeset_post_id) {
         $existing_status = get_post_status($changeset_post_id);
         if ('publish' === $existing_status || 'trash' === $existing_status) {
             return new WP_Error('changeset_already_published');
         }
         $existing_changeset_data = $this->get_changeset_post_data($changeset_post_id);
     }
     // Fail if attempting to publish but publish hook is missing.
     if ('publish' === $args['status'] && false === has_action('transition_post_status', '_wp_customize_publish_changeset')) {
         return new WP_Error('missing_publish_callback');
     }
     // Validate date.
     $now = gmdate('Y-m-d H:i:59');
     if ($args['date_gmt']) {
         $is_future_dated = mysql2date('U', $args['date_gmt'], false) > mysql2date('U', $now, false);
         if (!$is_future_dated) {
             return new WP_Error('not_future_date');
             // Only future dates are allowed.
         }
         if (!$this->is_theme_active() && ('future' === $args['status'] || $is_future_dated)) {
             return new WP_Error('cannot_schedule_theme_switches');
             // This should be allowed in the future, when theme is a regular setting.
         }
         $will_remain_auto_draft = !$args['status'] && (!$changeset_post_id || 'auto-draft' === get_post_status($changeset_post_id));
         if ($will_remain_auto_draft) {
             return new WP_Error('cannot_supply_date_for_auto_draft_changeset');
         }
     } elseif ($changeset_post_id && 'future' === $args['status']) {
         // Fail if the new status is future but the existing post's date is not in the future.
         $changeset_post = get_post($changeset_post_id);
         if (mysql2date('U', $changeset_post->post_date_gmt, false) <= mysql2date('U', $now, false)) {
             return new WP_Error('not_future_date');
         }
     }
     // The request was made via wp.customize.previewer.save().
     $update_transactionally = (bool) $args['status'];
     $allow_revision = (bool) $args['status'];
     // Amend post values with any supplied data.
     foreach ($args['data'] as $setting_id => $setting_params) {
         if (array_key_exists('value', $setting_params)) {
             $this->set_post_value($setting_id, $setting_params['value']);
             // Add to post values so that they can be validated and sanitized.
         }
     }
     // Note that in addition to post data, this will include any stashed theme mods.
     $post_values = $this->unsanitized_post_values(array('exclude_changeset' => true, 'exclude_post_data' => false));
     $this->add_dynamic_settings(array_keys($post_values));
     // Ensure settings get created even if they lack an input value.
     /*
      * Get list of IDs for settings that have values different from what is currently
      * saved in the changeset. By skipping any values that are already the same, the
      * subset of changed settings can be passed into validate_setting_values to prevent
      * an underprivileged modifying a single setting for which they have the capability
      * from being blocked from saving. This also prevents a user from touching of the
      * previous saved settings and overriding the associated user_id if they made no change.
      */
     $changed_setting_ids = array();
     foreach ($post_values as $setting_id => $setting_value) {
         $setting = $this->get_setting($setting_id);
         if ($setting && 'theme_mod' === $setting->type) {
             $prefixed_setting_id = $this->get_stylesheet() . '::' . $setting->id;
         } else {
             $prefixed_setting_id = $setting_id;
         }
         $is_value_changed = !isset($existing_changeset_data[$prefixed_setting_id]) || !array_key_exists('value', $existing_changeset_data[$prefixed_setting_id]) || $existing_changeset_data[$prefixed_setting_id]['value'] !== $setting_value;
         if ($is_value_changed) {
             $changed_setting_ids[] = $setting_id;
         }
     }
     /**
      * Fires before save validation happens.
      *
      * Plugins can add just-in-time {@see 'customize_validate_{$this->ID}'} filters
      * at this point to catch any settings registered after `customize_register`.
      * The dynamic portion of the hook name, `$this->ID` refers to the setting ID.
      *
      * @since 4.6.0
      *
      * @param WP_Customize_Manager $this WP_Customize_Manager instance.
      */
     do_action('customize_save_validation_before', $this);
     // Validate settings.
     $validated_values = array_merge(array_fill_keys(array_keys($args['data']), null), $post_values);
     $setting_validities = $this->validate_setting_values($validated_values, array('validate_capability' => true, 'validate_existence' => true));
     $invalid_setting_count = count(array_filter($setting_validities, 'is_wp_error'));
     /*
      * Short-circuit if there are invalid settings the update is transactional.
      * A changeset update is transactional when a status is supplied in the request.
      */
     if ($update_transactionally && $invalid_setting_count > 0) {
         $response = array('setting_validities' => $setting_validities, 'message' => sprintf(_n('There is %s invalid setting.', 'There are %s invalid settings.', $invalid_setting_count), number_format_i18n($invalid_setting_count)));
         return new WP_Error('transaction_fail', '', $response);
     }
     // Obtain/merge data for changeset.
     $original_changeset_data = $this->get_changeset_post_data($changeset_post_id);
     $data = $original_changeset_data;
     if (is_wp_error($data)) {
         $data = array();
     }
     // Ensure that all post values are included in the changeset data.
     foreach ($post_values as $setting_id => $post_value) {
         if (!isset($args['data'][$setting_id])) {
             $args['data'][$setting_id] = array();
         }
         if (!isset($args['data'][$setting_id]['value'])) {
             $args['data'][$setting_id]['value'] = $post_value;
         }
     }
     foreach ($args['data'] as $setting_id => $setting_params) {
         $setting = $this->get_setting($setting_id);
         if (!$setting || !$setting->check_capabilities()) {
             continue;
         }
         // Skip updating changeset for invalid setting values.
         if (isset($setting_validities[$setting_id]) && is_wp_error($setting_validities[$setting_id])) {
             continue;
         }
         $changeset_setting_id = $setting_id;
         if ('theme_mod' === $setting->type) {
             $changeset_setting_id = sprintf('%s::%s', $this->get_stylesheet(), $setting_id);
         }
         if (null === $setting_params) {
             // Remove setting from changeset entirely.
             unset($data[$changeset_setting_id]);
         } else {
             if (!isset($data[$changeset_setting_id])) {
                 $data[$changeset_setting_id] = array();
             }
             // Merge any additional setting params that have been supplied with the existing params.
             $merged_setting_params = array_merge($data[$changeset_setting_id], $setting_params);
             // Skip updating setting params if unchanged (ensuring the user_id is not overwritten).
             if ($data[$changeset_setting_id] === $merged_setting_params) {
                 continue;
             }
             $data[$changeset_setting_id] = array_merge($merged_setting_params, array('type' => $setting->type, 'user_id' => $args['user_id']));
             // Clear starter_content flag in data if changeset is not explicitly being updated for starter content.
             if (empty($args['starter_content'])) {
                 unset($data[$changeset_setting_id]['starter_content']);
             }
         }
     }
     $filter_context = array('uuid' => $this->changeset_uuid(), 'title' => $args['title'], 'status' => $args['status'], 'date_gmt' => $args['date_gmt'], 'post_id' => $changeset_post_id, 'previous_data' => is_wp_error($original_changeset_data) ? array() : $original_changeset_data, 'manager' => $this);
     /**
      * Filters the settings' data that will be persisted into the changeset.
      *
      * Plugins may amend additional data (such as additional meta for settings) into the changeset with this filter.
      *
      * @since 4.7.0
      *
      * @param array $data Updated changeset data, mapping setting IDs to arrays containing a $value item and optionally other metadata.
      * @param array $context {
      *     Filter context.
      *
      *     @type string               $uuid          Changeset UUID.
      *     @type string               $title         Requested title for the changeset post.
      *     @type string               $status        Requested status for the changeset post.
      *     @type string               $date_gmt      Requested date for the changeset post in MySQL format and GMT timezone.
      *     @type int|false            $post_id       Post ID for the changeset, or false if it doesn't exist yet.
      *     @type array                $previous_data Previous data contained in the changeset.
      *     @type WP_Customize_Manager $manager       Manager instance.
      * }
      */
     $data = apply_filters('customize_changeset_save_data', $data, $filter_context);
     // Switch theme if publishing changes now.
     if ('publish' === $args['status'] && !$this->is_theme_active()) {
         // Temporarily stop previewing the theme to allow switch_themes() to operate properly.
         $this->stop_previewing_theme();
         switch_theme($this->get_stylesheet());
         update_option('theme_switched_via_customizer', true);
         $this->start_previewing_theme();
     }
     // Gather the data for wp_insert_post()/wp_update_post().
     $json_options = 0;
     if (defined('JSON_UNESCAPED_SLASHES')) {
         $json_options |= JSON_UNESCAPED_SLASHES;
         // Introduced in PHP 5.4. This is only to improve readability as slashes needn't be escaped in storage.
     }
     $json_options |= JSON_PRETTY_PRINT;
     // Also introduced in PHP 5.4, but WP defines constant for back compat. See WP Trac #30139.
     $post_array = array('post_content' => wp_json_encode($data, $json_options));
     if ($args['title']) {
         $post_array['post_title'] = $args['title'];
     }
     if ($changeset_post_id) {
         $post_array['ID'] = $changeset_post_id;
     } else {
         $post_array['post_type'] = 'customize_changeset';
         $post_array['post_name'] = $this->changeset_uuid();
         $post_array['post_status'] = 'auto-draft';
     }
     if ($args['status']) {
         $post_array['post_status'] = $args['status'];
     }
     // Reset post date to now if we are publishing, otherwise pass post_date_gmt and translate for post_date.
     if ('publish' === $args['status']) {
         $post_array['post_date_gmt'] = '0000-00-00 00:00:00';
         $post_array['post_date'] = '0000-00-00 00:00:00';
     } elseif ($args['date_gmt']) {
         $post_array['post_date_gmt'] = $args['date_gmt'];
         $post_array['post_date'] = get_date_from_gmt($args['date_gmt']);
     }
     $this->store_changeset_revision = $allow_revision;
     add_filter('wp_save_post_revision_post_has_changed', array($this, '_filter_revision_post_has_changed'), 5, 3);
     // Update the changeset post. The publish_customize_changeset action will cause the settings in the changeset to be saved via WP_Customize_Setting::save().
     $has_kses = false !== has_filter('content_save_pre', 'wp_filter_post_kses');
     if ($has_kses) {
         kses_remove_filters();
         // Prevent KSES from corrupting JSON in post_content.
     }
     // Note that updating a post with publish status will trigger WP_Customize_Manager::publish_changeset_values().
     if ($changeset_post_id) {
         $post_array['edit_date'] = true;
         // Prevent date clearing.
         $r = wp_update_post(wp_slash($post_array), true);
     } else {
         $r = wp_insert_post(wp_slash($post_array), true);
         if (!is_wp_error($r)) {
             $this->_changeset_post_id = $r;
             // Update cached post ID for the loaded changeset.
         }
     }
     if ($has_kses) {
         kses_init_filters();
     }
     $this->_changeset_data = null;
     // Reset so WP_Customize_Manager::changeset_data() will re-populate with updated contents.
     remove_filter('wp_save_post_revision_post_has_changed', array($this, '_filter_revision_post_has_changed'));
     $response = array('setting_validities' => $setting_validities);
     if (is_wp_error($r)) {
         $response['changeset_post_save_failure'] = $r->get_error_code();
         return new WP_Error('changeset_post_save_failure', '', $response);
     }
     return $response;
 }
 function save_post_translation($translation_id, $translation)
 {
     global $wpdb, $sitepress_settings, $sitepress, $wp_taxonomies, $icl_adjust_id_url_filter_off;
     $icl_adjust_id_url_filter_off = true;
     $taxonomies = array_diff(array_keys((array) $wp_taxonomies), array('post_tag', 'category'));
     $tinfo = $wpdb->get_row($wpdb->prepare("\n                SELECT * FROM {$wpdb->prefix}icl_translations tr\n                    JOIN {$wpdb->prefix}icl_translation_status ts ON ts.translation_id = tr.translation_id\n                WHERE tr.translation_id=%d", $translation_id));
     $lang_code = $tinfo->language_code;
     $trid = $tinfo->trid;
     $original_post_details = $wpdb->get_row("\n            SELECT p.post_author, p.post_type, p.post_status, p.comment_status, p.ping_status, p.post_parent, p.menu_order, p.post_date, t.language_code\n            FROM {$wpdb->prefix}icl_translations t \n            JOIN {$wpdb->posts} p ON t.element_id = p.ID AND CONCAT('post_',p.post_type) = t.element_type\n            WHERE trid='{$trid}' AND p.ID = '{$translation['original_id']}'\n        ");
     //is the original post a sticky post?
     remove_filter('option_sticky_posts', array($sitepress, 'option_sticky_posts'));
     // remove filter used to get language relevant stickies. get them all
     $sticky_posts = get_option('sticky_posts');
     $is_original_sticky = $original_post_details->post_type == 'post' && in_array($translation['original_id'], $sticky_posts);
     $this->_content_fix_image_paths_in_body($translation);
     $this->_content_fix_relative_link_paths_in_body($translation);
     $this->_content_decode_shortcodes($translation);
     // deal with tags
     if (isset($translation['tags'])) {
         $translated_tags = $translation['tags'];
         $translated_tag_ids = explode(',', $translation['tag_ids']);
         foreach ($translated_tags as $k => $v) {
             $tag_trid = $wpdb->get_var("SELECT trid FROM {$wpdb->prefix}icl_translations WHERE element_id='{$translated_tag_ids[$k]}' AND element_type='tax_post_tag'");
             // before adding the new term make sure that another tag with the same name doesn't exist. If it does append @lang
             // same term name exists in a different language?
             $term_different_language = $wpdb->get_var("\n                    SELECT tm.term_id \n                    FROM {$wpdb->term_taxonomy} tx\n                        JOIN {$wpdb->terms} tm ON tx.term_id = tm.term_id \n                        JOIN {$wpdb->prefix}icl_translations tr ON tx.term_taxonomy_id = tr.element_id\n                    WHERE tm.name='" . $wpdb->escape($v) . "' AND tr.element_type LIKE 'tax\\_%' AND tr.language_code <> '{$lang_code}'\n                ");
             if ($term_different_language) {
                 $v .= ' @' . $lang_code;
             }
             //tag exists? (in the current language)
             $etag = get_term_by('name', htmlspecialchars($v), 'post_tag');
             if (!$etag) {
                 $etag = get_term_by('name', htmlspecialchars($v) . ' @' . $lang_code, 'post_tag');
             }
             if (!$etag) {
                 $tmp = wp_insert_term($v, 'post_tag');
                 if (!is_wp_error($tmp) && isset($tmp['term_taxonomy_id'])) {
                     $wpdb->update($wpdb->prefix . 'icl_translations', array('language_code' => $lang_code, 'trid' => $tag_trid, 'source_language_code' => $original_post_details->language_code), array('element_type' => 'tax_post_tag', 'element_id' => $tmp['term_taxonomy_id']));
                 }
             } else {
                 $term_taxonomy_id = $etag->term_taxonomy_id;
                 // check whether we have an orphan translation - the same trid and language but a different element id
                 $__translation_id = $wpdb->get_var("\n                        SELECT translation_id FROM {$wpdb->prefix}icl_translations \n                        WHERE   trid = '{$tag_trid}' \n                            AND language_code = '{$lang_code}' \n                            AND element_id <> '{$term_taxonomy_id}'\n                    ");
                 if ($__translation_id) {
                     $wpdb->query("DELETE FROM {$wpdb->prefix}icl_translations WHERE translation_id={$__translation_id}");
                 }
                 $tag_translation_id = $wpdb->get_var("SELECT translation_id FROM {$wpdb->prefix}icl_translations WHERE element_id={$term_taxonomy_id} AND element_type='tax_post_tag'");
                 if ($tag_translation_id) {
                     $wpdb->update($wpdb->prefix . 'icl_translations', array('language_code' => $lang_code, 'trid' => $tag_trid, 'source_language_code' => $original_post_details->language_code), array('element_type' => 'tax_post_tag', 'translation_id' => $tag_translation_id));
                 } else {
                     $wpdb->insert($wpdb->prefix . 'icl_translations', array('language_code' => $lang_code, 'trid' => $tag_trid, 'element_type' => 'tax_post_tag', 'element_id' => $term_taxonomy_id, 'source_language_code' => $original_post_details->language_code));
                 }
             }
         }
     }
     $original_post_tags = array();
     foreach (wp_get_object_terms($translation['original_id'], 'post_tag') as $t) {
         $original_post_tags[] = $t->term_taxonomy_id;
     }
     if ($original_post_tags) {
         $tag_trids = $wpdb->get_col("SELECT trid FROM {$wpdb->prefix}icl_translations WHERE element_type='tax_post_tag' AND element_id IN (" . join(',', $original_post_tags) . ")");
         if (!empty($tag_trids)) {
             $tag_tr_tts = $wpdb->get_col("SELECT element_id FROM {$wpdb->prefix}icl_translations WHERE element_type='tax_post_tag' AND language_code='{$lang_code}' AND trid IN (" . join(',', $tag_trids) . ")");
         }
         if (!empty($tag_tr_tts)) {
             $translated_tags = $wpdb->get_col("SELECT t.name FROM {$wpdb->terms} t JOIN {$wpdb->term_taxonomy} tx ON tx.term_id = t.term_id WHERE tx.taxonomy='post_tag' AND tx.term_taxonomy_id IN (" . join(',', $tag_tr_tts) . ")");
         }
     }
     // deal with categories
     if (isset($translation['categories'])) {
         $translated_cats = $translation['categories'];
         $translated_cats_ids = explode(',', $translation['category_ids']);
         foreach ($translated_cats as $k => $v) {
             //$v = trim(str_replace('<p>', '', $v));
             $cat_trid = $wpdb->get_var("SELECT trid FROM {$wpdb->prefix}icl_translations WHERE element_id='{$translated_cats_ids[$k]}' AND element_type='tax_category'");
             // before adding the new term make sure that another tag with the same name doesn't exist. If it does append @lang
             // same term name exists in a different language?
             $term_different_language = $wpdb->get_var("\n                    SELECT tm.term_id \n                    FROM {$wpdb->term_taxonomy} tx\n                        JOIN {$wpdb->terms} tm ON tx.term_id = tm.term_id \n                        JOIN {$wpdb->prefix}icl_translations tr ON tx.term_taxonomy_id = tr.element_id\n                    WHERE tm.name='" . $wpdb->escape($v) . "' AND tr.element_type LIKE 'tax\\_%' AND tr.language_code <> '{$lang_code}'\n                ");
             if ($term_different_language) {
                 $v .= ' @' . $lang_code;
             }
             //cat exists?
             $ecat = get_term_by('name', htmlspecialchars($v), 'category');
             if (!$ecat) {
                 $ecat = get_term_by('name', htmlspecialchars($v) . ' @' . $lang_code, 'category');
             }
             if (!$ecat) {
                 // get original category parent id
                 $original_category_parent_id = $wpdb->get_var($wpdb->prepare("SELECT parent FROM {$wpdb->term_taxonomy} WHERE term_taxonomy_id=%d", $translated_cats_ids[$k]));
                 if ($original_category_parent_id) {
                     $_op_tax_id = $wpdb->get_var($wpdb->prepare("SELECT term_taxonomy_id FROM {$wpdb->term_taxonomy} WHERE taxonomy='category' AND term_id=%d", $original_category_parent_id));
                     $_op_trid = $wpdb->get_var($wpdb->prepare("SELECT trid FROM {$wpdb->prefix}icl_translations WHERE element_type='tax_category' AND element_id=%d", $_op_tax_id));
                     // get id of the translated category parent
                     $_tp_tax_id = $wpdb->get_var($wpdb->prepare("SELECT element_id FROM {$wpdb->prefix}icl_translations WHERE language_code='{$lang_code}' AND trid=%d", $_op_trid));
                     if ($_tp_tax_id) {
                         $category_parent_id = $wpdb->get_var($wpdb->prepare("SELECT term_id FROM {$wpdb->term_taxonomy} WHERE taxonomy='category' AND term_taxonomy_id=%d", $_tp_tax_id));
                     } else {
                         $category_parent_id = 0;
                     }
                 } else {
                     $category_parent_id = 0;
                 }
                 $tmp = wp_insert_term($v, 'category', array('parent' => $category_parent_id));
                 if (!is_wp_error($tmp) && isset($tmp['term_taxonomy_id'])) {
                     $wpdb->update($wpdb->prefix . 'icl_translations', array('language_code' => $lang_code, 'trid' => $cat_trid, 'source_language_code' => $original_post_details->language_code), array('element_type' => 'tax_category', 'element_id' => $tmp['term_taxonomy_id']));
                     // if this is a parent category, make sure that nesting is correct for all translations
                     $orig_cat_tax_id = $wpdb->get_var($wpdb->prepare("SELECT element_id FROM {$wpdb->prefix}icl_translations WHERE trid=%d AND source_language_code IS NULL", $cat_trid));
                     $orig_cat_term_id = $wpdb->get_var($wpdb->prepare("SELECT term_id FROM {$wpdb->term_taxonomy} WHERE term_taxonomy_id=%d AND taxonomy='category'", $orig_cat_tax_id));
                     $orig_cat_children = $wpdb->get_col($wpdb->prepare("SELECT term_id FROM {$wpdb->term_taxonomy} WHERE parent=%d", $orig_cat_term_id));
                     if (!empty($orig_cat_children)) {
                         foreach ($orig_cat_children as $ch) {
                             $_tr_child = icl_object_id($ch, 'category', false, $lang_code);
                             if ($_tr_child) {
                                 $wpdb->update($wpdb->term_taxonomy, array('parent' => $tmp['term_id']), array('taxonomy' => 'category', 'term_id' => $_tr_child));
                             }
                         }
                     }
                     delete_option('category_children');
                 }
             } else {
                 $term_taxonomy_id = $ecat->term_taxonomy_id;
                 // check whether we have an orphan translation - the same trid and language but a different element id
                 $__translation_id = $wpdb->get_var("\n                        SELECT translation_id FROM {$wpdb->prefix}icl_translations \n                        WHERE   trid = '{$cat_trid}' \n                            AND language_code = '{$lang_code}' \n                            AND element_id <> '{$term_taxonomy_id}'\n                    ");
                 if ($__translation_id) {
                     $wpdb->query("DELETE FROM {$wpdb->prefix}icl_translations WHERE translation_id={$__translation_id}");
                 }
                 $cat_translation_id = $wpdb->get_var("SELECT translation_id FROM {$wpdb->prefix}icl_translations WHERE element_id={$term_taxonomy_id} AND element_type='tax_category'");
                 if ($cat_translation_id) {
                     $wpdb->update($wpdb->prefix . 'icl_translations', array('language_code' => $lang_code, 'trid' => $cat_trid, 'source_language_code' => $original_post_details->language_code), array('element_type' => 'tax_category', 'translation_id' => $cat_translation_id));
                 } else {
                     $wpdb->insert($wpdb->prefix . 'icl_translations', array('language_code' => $lang_code, 'trid' => $cat_trid, 'element_type' => 'tax_category', 'element_id' => $term_taxonomy_id, 'source_language_code' => $original_post_details->language_code));
                 }
             }
         }
     }
     $original_post_cats = array();
     foreach (wp_get_object_terms($translation['original_id'], 'category') as $t) {
         $original_post_cats[] = $t->term_taxonomy_id;
     }
     if ($original_post_cats) {
         $cat_trids = $wpdb->get_col("SELECT trid FROM {$wpdb->prefix}icl_translations WHERE element_type='tax_category' AND element_id IN (" . join(',', $original_post_cats) . ")");
         if (!empty($cat_trids)) {
             $cat_tr_tts = $wpdb->get_col("SELECT element_id FROM {$wpdb->prefix}icl_translations WHERE element_type='tax_category' AND language_code='{$lang_code}' AND trid IN (" . join(',', $cat_trids) . ")");
         }
         if (!empty($cat_tr_tts)) {
             $translated_cats_ids = $wpdb->get_col("SELECT t.term_id FROM {$wpdb->terms} t JOIN {$wpdb->term_taxonomy} tx ON tx.term_id = t.term_id WHERE tx.taxonomy='category' AND tx.term_taxonomy_id IN (" . join(',', $cat_tr_tts) . ")");
         }
     }
     // deal with custom taxonomies
     if (!empty($sitepress_settings['taxonomies_sync_option'])) {
         foreach ($sitepress_settings['taxonomies_sync_option'] as $taxonomy => $value) {
             if ($value == 1 && isset($translation[$taxonomy])) {
                 $translated_taxs[$taxonomy] = $translation[$taxonomy];
                 $translated_tax_ids[$taxonomy] = explode(',', $translation[$taxonomy . '_ids']);
                 foreach ($translated_taxs[$taxonomy] as $k => $v) {
                     $tax_trid = $wpdb->get_var("\n                                SELECT trid FROM {$wpdb->prefix}icl_translations \n                                WHERE element_id='{$translated_tax_ids[$taxonomy][$k]}' AND element_type='tax_{$taxonomy}'");
                     // before adding the new term make sure that another tag with the same name doesn't exist. If it does append @lang
                     // same term name exists in a different language?
                     $term_different_language = $wpdb->get_var("\n                                SELECT tm.term_id \n                                FROM {$wpdb->term_taxonomy} tx\n                                    JOIN {$wpdb->terms} tm ON tx.term_id = tm.term_id \n                                    JOIN {$wpdb->prefix}icl_translations tr ON tx.term_taxonomy_id = tr.element_id\n                                WHERE tm.name='" . $wpdb->escape($v) . "' AND tr.element_type LIKE 'tax\\_%' AND tr.language_code <> '{$lang_code}'\n                            ");
                     if ($term_different_language) {
                         $v .= ' @' . $lang_code;
                     }
                     //tax exists? (in the current language)
                     $etag = get_term_by('name', htmlspecialchars($v), $taxonomy);
                     if (!$etag) {
                         $etag = get_term_by('name', htmlspecialchars($v) . ' @' . $lang_code, $taxonomy);
                     }
                     if (!$etag) {
                         // get original category parent id
                         $original_t_parent_id = $wpdb->get_var($wpdb->prepare("SELECT parent FROM {$wpdb->term_taxonomy} WHERE term_taxonomy_id=%d", $translated_tax_ids[$taxonomy][$k]));
                         if ($original_t_parent_id) {
                             $_op_tax_id = $wpdb->get_var($wpdb->prepare("SELECT term_taxonomy_id FROM {$wpdb->term_taxonomy} WHERE taxonomy='category' AND term_id=%d", $original_t_parent_id));
                             $_op_trid = $wpdb->get_var($wpdb->prepare("SELECT trid FROM {$wpdb->prefix}icl_translations WHERE element_type='tax_category' AND element_id=%d", $_op_tax_id));
                             // get id of the translated category parent
                             $_tp_tax_id = $wpdb->get_var($wpdb->prepare("SELECT element_id FROM {$wpdb->prefix}icl_translations WHERE language_code='{$lang_code}' AND trid=%d", $_op_trid));
                             if ($_tp_tax_id) {
                                 $t_parent_id = $wpdb->get_var($wpdb->prepare("SELECT term_id FROM {$wpdb->term_taxonomy} WHERE taxonomy='category' AND term_taxonomy_id=%d", $_tp_tax_id));
                             } else {
                                 $t_parent_id = 0;
                             }
                         } else {
                             $t_parent_id = 0;
                         }
                         $tmp = wp_insert_term($v, $taxonomy);
                         if (!is_wp_error($tmp) && isset($tmp['term_taxonomy_id'])) {
                             $wpdb->update($wpdb->prefix . 'icl_translations', array('language_code' => $lang_code, 'trid' => $tax_trid, 'source_language_code' => $original_post_details->language_code), array('element_type' => 'tax_' . $taxonomy, 'element_id' => $tmp['term_taxonomy_id']));
                             // if this is a parent category, make sure that nesting is correct for all translations
                             $orig_tax_id = $wpdb->get_var($wpdb->prepare("SELECT element_id FROM {$wpdb->prefix}icl_translations WHERE trid=%d AND source_language_code IS NULL", $tax_trid));
                             $orig_term_id = $wpdb->get_var($wpdb->prepare("SELECT term_id FROM {$wpdb->term_taxonomy} WHERE term_taxonomy_id=%d AND taxonomy='{$taxonomy}'", $orig_tax_id));
                             $orig_tax_children = $wpdb->get_col($wpdb->prepare("SELECT term_id FROM {$wpdb->term_taxonomy} WHERE parent=%d", $orig_term_id));
                             if (!empty($orig_tax_children)) {
                                 foreach ($orig_tax_children as $ch) {
                                     $_tr_child = icl_object_id($ch, $taxonomy, false, $lang_code);
                                     if ($_tr_child) {
                                         $wpdb->update($wpdb->term_taxonomy, array('parent' => $tmp['term_id']), array('taxonomy' => $taxonomy, 'term_id' => $_tr_child));
                                     }
                                 }
                             }
                             delete_option($taxonomy . '_children');
                         }
                     } else {
                         $term_taxonomy_id = $etag->term_taxonomy_id;
                         // check whether we have an orphan translation - the same trid and language but a different element id
                         $__translation_id = $wpdb->get_var("\n                                SELECT translation_id FROM {$wpdb->prefix}icl_translations \n                                WHERE   trid = '{$tax_trid}' \n                                    AND language_code = '{$lang_code}' \n                                    AND element_id <> '{$term_taxonomy_id}'\n                            ");
                         if ($__translation_id) {
                             $wpdb->query("DELETE FROM {$wpdb->prefix}icl_translations WHERE translation_id={$__translation_id}");
                         }
                         $tax_translation_id = $wpdb->get_var("\n                                SELECT translation_id FROM {$wpdb->prefix}icl_translations \n                                WHERE element_id={$term_taxonomy_id} AND element_type='tax_{$taxonomy}'");
                         if ($tax_translation_id) {
                             $wpdb->update($wpdb->prefix . 'icl_translations', array('language_code' => $lang_code, 'trid' => $tax_trid, 'source_language_code' => $original_post_details->language_code), array('element_type' => 'tax_' . $taxonomy, 'translation_id' => $tax_translation_id));
                         } else {
                             $wpdb->insert($wpdb->prefix . 'icl_translations', array('language_code' => $lang_code, 'trid' => $tax_trid, 'element_type' => 'tax_' . $taxonomy, 'element_id' => $term_taxonomy_id, 'source_language_code' => $original_post_details->language_code));
                         }
                     }
                 }
             }
             $oterms = wp_get_object_terms($translation['original_id'], $taxonomy);
             if (!is_wp_error($oterms)) {
                 foreach ($oterms as $t) {
                     $original_post_taxs[$taxonomy][] = $t->term_taxonomy_id;
                 }
             }
             if (!empty($original_post_taxs[$taxonomy])) {
                 $tax_trids = $wpdb->get_col("SELECT trid FROM {$wpdb->prefix}icl_translations \n                        WHERE element_type='tax_{$taxonomy}' AND element_id IN (" . join(',', $original_post_taxs[$taxonomy]) . ")");
                 if (!empty($tax_trids)) {
                     $tax_tr_tts = $wpdb->get_col("SELECT element_id FROM {$wpdb->prefix}icl_translations \n                        WHERE element_type='tax_{$taxonomy}' AND language_code='{$lang_code}' AND trid IN (" . join(',', $tax_trids) . ")");
                 }
                 if (!empty($tax_tr_tts)) {
                     if ($wp_taxonomies[$taxonomy]->hierarchical) {
                         $translated_tax_ids[$taxonomy] = $wpdb->get_col("SELECT term_id FROM {$wpdb->term_taxonomy} WHERE term_taxonomy_id IN (" . join(',', $tax_tr_tts) . ")");
                     } else {
                         $translated_taxs[$taxonomy] = $wpdb->get_col("SELECT t.name FROM {$wpdb->terms} t \n                                JOIN {$wpdb->term_taxonomy} tx ON tx.term_id = t.term_id \n                                WHERE tx.taxonomy='{$taxonomy}' AND tx.term_taxonomy_id IN (" . join(',', $tax_tr_tts) . ")");
                     }
                 }
             }
         }
     }
     // handle the page parent and set it to the translated parent if we have one.
     if ($original_post_details->post_parent) {
         $post_parent_trid = $wpdb->get_var("SELECT trid FROM {$wpdb->prefix}icl_translations WHERE element_type='post_{$original_post_details->post_type}' AND element_id='{$original_post_details->post_parent}'");
         if ($post_parent_trid) {
             $parent_id = $wpdb->get_var("SELECT element_id FROM {$wpdb->prefix}icl_translations WHERE element_type='post_{$original_post_details->post_type}' AND trid='{$post_parent_trid}' AND language_code='{$lang_code}'");
         }
     }
     // determine post id based on trid
     $post_id = $tinfo->element_id;
     if ($post_id) {
         // see if the post really exists - make sure it wasn't deleted while the plugin was
         if (!$wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE ID={$post_id}")) {
             $is_update = false;
             $wpdb->query("DELETE FROM {$wpdb->prefix}icl_translations WHERE element_type='post_{$original_post_details->post_type}' AND element_id={$post_id}");
         } else {
             $is_update = true;
             $postarr['ID'] = $_POST['post_ID'] = $post_id;
         }
     } else {
         $is_update = false;
     }
     $postarr['post_title'] = $translation['title'];
     $postarr['post_content'] = $translation['body'];
     if (isset($translation['excerpt']) && $translation['excerpt'] != "") {
         $postarr['post_excerpt'] = $translation['excerpt'];
     }
     if (@is_array($translated_tags)) {
         $postarr['tags_input'] = join(',', (array) $translated_tags);
     }
     if (@is_array($translated_taxs)) {
         foreach ($translated_taxs as $taxonomy => $values) {
             $postarr['tax_input'][$taxonomy] = join(',', (array) $values);
         }
     }
     if (@is_array($translated_tax_ids)) {
         $postarr['tax_input'] = $translated_tax_ids;
     }
     if (isset($translated_cats_ids)) {
         $postarr['post_category'] = $translated_cats_ids;
     }
     $postarr['post_author'] = $original_post_details->post_author;
     $postarr['post_type'] = $original_post_details->post_type;
     if ($sitepress_settings['sync_comment_status']) {
         $postarr['comment_status'] = $original_post_details->comment_status;
     }
     if ($sitepress_settings['sync_ping_status']) {
         $postarr['ping_status'] = $original_post_details->ping_status;
     }
     if ($sitepress_settings['sync_page_ordering']) {
         $postarr['menu_order'] = $original_post_details->menu_order;
     }
     if ($sitepress_settings['sync_private_flag'] && $original_post_details->post_status == 'private') {
         $postarr['post_status'] = 'private';
     }
     if (!$is_update) {
         $postarr['post_status'] = !$sitepress_settings['translated_document_status'] ? 'draft' : $original_post_details->post_status;
     } else {
         // set post_status to the current post status.
         $postarr['post_status'] = $wpdb->get_var("SELECT post_status FROM {$wpdb->prefix}posts WHERE ID = " . $post_id);
     }
     if ($sitepress_settings['sync_post_date']) {
         $postarr['post_date'] = $original_post_details->post_date;
     }
     if (isset($parent_id) && $sitepress_settings['sync_page_parent']) {
         $_POST['post_parent'] = $postarr['post_parent'] = $parent_id;
         $_POST['parent_id'] = $postarr['parent_id'] = $parent_id;
     }
     if ($is_update) {
         $postarr['post_name'] = $wpdb->get_var($wpdb->prepare("SELECT post_name FROM {$wpdb->posts} WHERE ID=%d", $post_id));
     }
     $_POST['trid'] = $trid;
     $_POST['lang'] = $lang_code;
     $_POST['skip_sitepress_actions'] = true;
     global $wp_rewrite;
     if (!isset($wp_rewrite)) {
         $wp_rewrite = new WP_Rewrite();
     }
     kses_remove_filters();
     $postarr = apply_filters('icl_pre_save_pro_translation', $postarr);
     $new_post_id = wp_insert_post($postarr);
     do_action('icl_pro_translation_saved', $new_post_id);
     // associate custom taxonomies by hand
     if (!empty($postarr['tax_input'])) {
         foreach ($postarr['tax_input'] as $taxonomy => $tags) {
             wp_set_post_terms($new_post_id, $tags, $taxonomy);
         }
     }
     // set stickiness
     if ($is_original_sticky && $sitepress_settings['sync_sticky_flag']) {
         stick_post($new_post_id);
     } else {
         if ($original_post_details->post_type == 'post' && $is_update) {
             unstick_post($new_post_id);
             //just in case - if this is an update and the original post stckiness has changed since the post was sent to translation
         }
     }
     foreach ((array) $sitepress_settings['translation-management']['custom_fields_translation'] as $cf => $op) {
         if ($op == 1) {
             update_post_meta($new_post_id, $cf, get_post_meta($translation['original_id'], $cf, true));
         } elseif ($op == 2 && isset($translation['field-' . $cf])) {
             $field_translation = $translation['field-' . $cf];
             $field_type = $translation['field-' . $cf . '-type'];
             if ($field_type == 'custom_field') {
                 $field_translation = str_replace('&#0A;', "\n", $field_translation);
                 // always decode html entities  eg decode &amp; to &
                 $field_translation = html_entity_decode($field_translation);
                 update_post_meta($new_post_id, $cf, $field_translation);
             }
         }
     }
     // set specific custom fields
     $copied_custom_fields = array('_top_nav_excluded', '_cms_nav_minihome');
     foreach ($copied_custom_fields as $ccf) {
         $val = get_post_meta($translation['original_id'], $ccf, true);
         update_post_meta($new_post_id, $ccf, $val);
     }
     // sync _wp_page_template
     if ($sitepress_settings['sync_page_template']) {
         $_wp_page_template = get_post_meta($translation['original_id'], '_wp_page_template', true);
         update_post_meta($new_post_id, '_wp_page_template', $_wp_page_template);
     }
     if (!$new_post_id) {
         return false;
     }
     if (!$is_update) {
         $wpdb->update($wpdb->prefix . 'icl_translations', array('element_id' => $new_post_id), array('translation_id' => $translation_id));
     }
     update_post_meta($new_post_id, '_icl_translation', 1);
     global $iclTranslationManagement;
     $ts = array('status' => ICL_TM_COMPLETE, 'needs_update' => 0, 'translation_id' => $translation_id);
     $translator_id = $wpdb->get_var($wpdb->prepare("SELECT translator_id FROM {$wpdb->prefix}icl_translation_status WHERE translation_id=%d", $translation_id));
     if (!$translator_id) {
         foreach ($sitepress_settings['icl_lang_status'] as $lpair) {
             if ($lpair['from'] == $original_post_details->language_code && $lpair['to'] == $lang_code && isset($lpair['translators'][0]['id'])) {
                 $ts['translator_id'] = $lpair['translators'][0]['id'];
                 break;
             }
         }
     }
     // update translation status
     $iclTranslationManagement->update_translation_status($ts);
     // add new translation job
     //$translation_package = $iclTranslationManagement->create_translation_package(get_post($translation['original_id']));
     //$job_id = $iclTranslationManagement->add_translation_job($tinfo->rid, $tinfo->translator_id, $translation_package);
     $job_id = $iclTranslationManagement->get_translation_job_id($trid, $lang_code);
     // save the translation
     $iclTranslationManagement->mark_job_done($job_id);
     $parts = explode('_', $translation['original_id']);
     if ($parts[0] != 'external') {
         $iclTranslationManagement->save_job_fields_from_post($job_id, get_post($new_post_id));
         $this->_content_fix_links_to_translated_content($new_post_id, $lang_code, "post_{$original_post_details->post_type}");
         if (function_exists('icl_st_fix_links_in_strings')) {
             icl_st_fix_links_in_strings($new_post_id);
         }
         // Now try to fix links in other translated content that may link to this post.
         $sql = "SELECT\n                        tr.element_id\n                    FROM\n                        {$wpdb->prefix}icl_translations tr\n                    JOIN\n                        {$wpdb->prefix}icl_translation_status ts\n                    ON\n                        tr.translation_id = ts.translation_id\n                    WHERE\n                        ts.links_fixed = 0 AND tr.element_type = 'post_{$original_post_details->post_type}' AND tr.language_code = '{$lang_code}' AND tr.element_id IS NOT NULL";
         $needs_fixing = $wpdb->get_results($sql);
         foreach ($needs_fixing as $id) {
             if ($id->element_id != $new_post_id) {
                 // fix all except the new_post_id. We have already done this.
                 $this->_content_fix_links_to_translated_content($id->element_id, $lang_code, "post_{$original_post_details->post_type}");
             }
         }
         // if this is a parent page then make sure it's children point to this.
         $this->fix_translated_children($translation['original_id'], $new_post_id, $lang_code);
     }
     return true;
 }
Example #30
0
function Ajax_Comment()
{
    if (isset($_REQUEST['spam_bot'])) {
        if ($_REQUEST['spam_bot'] && $_REQUEST['spam_bot'] !== '') {
            wp_die(__('Your are Bot', 'metrika'));
        }
    }
    $comment_post_ID = isset($_REQUEST['comment_id']) ? (int) $_REQUEST['comment_id'] : 0;
    $post = get_post($comment_post_ID);
    if (empty($post->comment_status)) {
        do_action('comment_id_not_found', $comment_post_ID);
        exit;
    }
    $status = get_post_status($post);
    $status_obj = get_post_status_object($status);
    if (!comments_open($comment_post_ID)) {
        do_action('comment_closed', $comment_post_ID);
        wp_die(__('Sorry, comments are closed for this item.', 'metrika'));
    } elseif ('trash' == $status) {
        do_action('comment_on_trash', $comment_post_ID);
        exit;
    } elseif (!$status_obj->public && !$status_obj->private) {
        do_action('comment_on_draft', $comment_post_ID);
        exit;
    } elseif (post_password_required($comment_post_ID)) {
        do_action('comment_on_password_protected', $comment_post_ID);
        exit;
    } else {
        do_action('pre_comment_on_post', $comment_post_ID);
    }
    $comment_author = isset($_REQUEST['author']) ? trim(strip_tags($_REQUEST['author'])) : null;
    $comment_author_email = isset($_REQUEST['email']) ? trim($_REQUEST['email']) : null;
    $comment_content = isset($_REQUEST['comment']) ? trim($_REQUEST['comment']) : null;
    $user = wp_get_current_user();
    if ($user->exists()) {
        if (empty($user->display_name)) {
            $user->display_name = $user->user_login;
        }
        $comment_author = wp_slash($user->display_name);
        $comment_author_email = wp_slash($user->user_email);
        $comment_author_url = wp_slash($user->user_url);
        if (current_user_can('unfiltered_html')) {
            if (@wp_create_nonce('unfiltered-html-comment_' . $comment_post_ID) != @$_POST['_wp_unfiltered_html_comment']) {
                kses_remove_filters();
                // start with a clean slate
                kses_init_filters();
                // set up the filters
            }
        }
    } else {
        if (get_option('comment_registration') || 'private' == $status) {
            wp_die(__('Sorry, you must be logged in to post a comment.', 'metrika'));
        }
    }
    $comment_type = '';
    if (get_option('require_name_email') && !$user->exists()) {
        if (6 > strlen($comment_author_email) || '' == $comment_author) {
            wp_die(__('Please fill the required fields (Name, E-mail, Comment).', 'metrika'));
        } elseif (!is_email($comment_author_email)) {
            wp_die(__('Please enter a valid email address.', 'metrika'));
        }
    }
    if ('' == $comment_content) {
        wp_die(__('Please type a comment.', 'metrika'));
    }
    $comment_parent = isset($_REQUEST['comment_parrent']) ? absint($_REQUEST['comment_parrent']) : 0;
    $commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_content', 'comment_type', 'comment_parent', 'user_ID');
    $comment_id = wp_new_comment($commentdata);
    $comment = get_comment($comment_id);
    do_action('set_comment_cookies', $comment, $user);
    if ($comment_id) {
        echo __('Your comment awaiting approval', 'metrika');
    } else {
        echo __('Your comment not sending. Please try to later', 'metrika');
    }
    exit;
}