function A_insert_post_format($post_ID, $ablog, $item) { if (!empty($ablog['postformat'])) { set_post_format($post_ID, $ablog['postformat']); } else { set_post_format($post_ID, 'standard'); } }
public static function wpSetUpBeforeClass(WP_UnitTest_Factory $factory) { self::$page_on_front = $factory->post->create_and_get(array('post_type' => 'page', 'post_name' => 'page-on-front')); self::$page_for_posts = $factory->post->create_and_get(array('post_type' => 'page', 'post_name' => 'page-for-posts')); self::$page = $factory->post->create_and_get(array('post_type' => 'page', 'post_name' => 'page-name')); add_post_meta(self::$page->ID, '_wp_page_template', 'templates/page.php'); self::$post = $factory->post->create_and_get(array('post_type' => 'post', 'post_name' => 'post-name', 'post_date' => '1984-02-25 12:34:56')); set_post_format(self::$post, 'quote'); }
/** * Press It form handler. * * @package WordPress * @subpackage Press_This * @since 2.6.0 * * @return int Post ID */ function press_it() { $post = get_default_post_to_edit(); $post = get_object_vars($post); $post_ID = $post['ID'] = (int) $_POST['post_id']; if ( !current_user_can('edit_post', $post_ID) ) wp_die(__('You are not allowed to edit this post.')); $post['post_category'] = isset($_POST['post_category']) ? $_POST['post_category'] : ''; $post['tax_input'] = isset($_POST['tax_input']) ? $_POST['tax_input'] : ''; $post['post_title'] = isset($_POST['title']) ? $_POST['title'] : ''; $content = isset($_POST['content']) ? $_POST['content'] : ''; $upload = false; if ( !empty($_POST['photo_src']) && current_user_can('upload_files') ) { foreach( (array) $_POST['photo_src'] as $key => $image) { // see if files exist in content - we don't want to upload non-used selected files. if ( strpos($_POST['content'], htmlspecialchars($image)) !== false ) { $desc = isset($_POST['photo_description'][$key]) ? $_POST['photo_description'][$key] : ''; $upload = media_sideload_image($image, $post_ID, $desc); // Replace the POSTED content <img> with correct uploaded ones. Regex contains fix for Magic Quotes if ( !is_wp_error($upload) ) $content = preg_replace('/<img ([^>]*)src=\\\?(\"|\')'.preg_quote(htmlspecialchars($image), '/').'\\\?(\2)([^>\/]*)\/*>/is', $upload, $content); } } } // set the post_content and status $post['post_content'] = $content; if ( isset( $_POST['publish'] ) && current_user_can( 'publish_posts' ) ) $post['post_status'] = 'publish'; elseif ( isset( $_POST['review'] ) ) $post['post_status'] = 'pending'; else $post['post_status'] = 'draft'; // error handling for media_sideload if ( is_wp_error($upload) ) { wp_delete_post($post_ID); wp_die($upload); } else { // Post formats if ( isset( $_POST['post_format'] ) ) { if ( current_theme_supports( 'post-formats', $_POST['post_format'] ) ) set_post_format( $post_ID, $_POST['post_format'] ); elseif ( '0' == $_POST['post_format'] ) set_post_format( $post_ID, false ); } $post_ID = wp_update_post($post); } return $post_ID; }
/** * AJAX handler for saving the post as draft or published. * * @since 4.2.0 * @access public */ public function save_post() { if (empty($_POST['post_ID']) || !($post_id = (int) $_POST['post_ID'])) { wp_send_json_error(array('errorMessage' => __('Missing post ID.'))); } if (empty($_POST['_wpnonce']) || !wp_verify_nonce($_POST['_wpnonce'], 'update-post_' . $post_id) || !current_user_can('edit_post', $post_id)) { wp_send_json_error(array('errorMessage' => __('Invalid post.'))); } $post = array('ID' => $post_id, 'post_title' => !empty($_POST['post_title']) ? sanitize_text_field(trim($_POST['post_title'])) : '', 'post_content' => !empty($_POST['post_content']) ? trim($_POST['post_content']) : '', 'post_type' => 'post', 'post_status' => 'draft', 'post_format' => !empty($_POST['post_format']) ? sanitize_text_field($_POST['post_format']) : '', 'tax_input' => !empty($_POST['tax_input']) ? $_POST['tax_input'] : array(), 'post_category' => !empty($_POST['post_category']) ? $_POST['post_category'] : array()); if (!empty($_POST['post_status']) && 'publish' === $_POST['post_status']) { if (current_user_can('publish_posts')) { $post['post_status'] = 'publish'; } else { $post['post_status'] = 'pending'; } } $post['post_content'] = $this->side_load_images($post_id, $post['post_content']); $updated = wp_update_post($post, true); if (is_wp_error($updated)) { wp_send_json_error(array('errorMessage' => $updated->get_error_message())); } else { if (isset($post['post_format'])) { if (current_theme_supports('post-formats', $post['post_format'])) { set_post_format($post_id, $post['post_format']); } elseif ($post['post_format']) { set_post_format($post_id, false); } } $forceRedirect = false; if ('publish' === get_post_status($post_id)) { $redirect = get_post_permalink($post_id); } elseif (isset($_POST['pt-force-redirect']) && $_POST['pt-force-redirect'] === 'true') { $forceRedirect = true; $redirect = get_edit_post_link($post_id, 'js'); } else { $redirect = false; } /** * Filter the URL to redirect to when Press This saves. * * @since 4.2.0 * * @param string $url Redirect URL. If `$status` is 'publish', this will be the post permalink. * Otherwise, the default is false resulting in no redirect. * @param int $post_id Post ID. * @param string $status Post status. */ $redirect = apply_filters('press_this_save_redirect', $redirect, $post_id, $post['post_status']); if ($redirect) { wp_send_json_success(array('redirect' => $redirect, 'force' => $forceRedirect)); } else { wp_send_json_success(array('postSaved' => true)); } } }
/** * Press It form handler. * * @package WordPress * @subpackage Press_This * @since 2.6.0 * * @return int Post ID */ function press_it() { // define some basic variables $quick = array(); $quick['post_status'] = 'draft'; // set as draft first $quick['post_category'] = isset($_POST['post_category']) ? $_POST['post_category'] : null; $quick['tax_input'] = isset($_POST['tax_input']) ? $_POST['tax_input'] : null; $quick['post_title'] = trim($_POST['title']) != '' ? $_POST['title'] : ' '; $quick['post_content'] = isset($_POST['post_content']) ? $_POST['post_content'] : ''; // insert the post with nothing in it, to get an ID $post_ID = wp_insert_post($quick, true); if (is_wp_error($post_ID)) { wp_die($post_ID); } $content = isset($_POST['content']) ? $_POST['content'] : ''; $upload = false; if (!empty($_POST['photo_src']) && current_user_can('upload_files')) { foreach ((array) $_POST['photo_src'] as $key => $image) { // see if files exist in content - we don't want to upload non-used selected files. if (strpos($_POST['content'], htmlspecialchars($image)) !== false) { $desc = isset($_POST['photo_description'][$key]) ? $_POST['photo_description'][$key] : ''; $upload = media_sideload_image($image, $post_ID, $desc); // Replace the POSTED content <img> with correct uploaded ones. Regex contains fix for Magic Quotes if (!is_wp_error($upload)) { $content = preg_replace('/<img ([^>]*)src=\\\\?(\\"|\')' . preg_quote(htmlspecialchars($image), '/') . '\\\\?(\\2)([^>\\/]*)\\/*>/is', $upload, $content); } } } } // set the post_content and status $quick['post_status'] = isset($_POST['publish']) ? 'publish' : 'draft'; $quick['post_content'] = $content; // error handling for media_sideload if (is_wp_error($upload)) { wp_delete_post($post_ID); wp_die($upload); } else { // Post formats if (current_theme_supports('post-formats') && isset($_POST['post_format'])) { $post_formats = get_theme_support('post-formats'); if (is_array($post_formats)) { $post_formats = $post_formats[0]; if (in_array($_POST['post_format'], $post_formats)) { set_post_format($post_ID, $_POST['post_format']); } elseif ('0' == $_POST['post_format']) { set_post_format($post_ID, false); } } } $quick['ID'] = $post_ID; wp_update_post($quick); } return $post_ID; }
function create_post_type() { $section_labels = array('name' => __('Page Sections'), 'singular_name' => __('Page Section'), 'add_new_item' => __('Add new Page Section')); $section_args = array('labels' => $section_labels, 'public' => true, 'has_archive' => false, 'rewrite' => array('slug' => 'sections'), 'menu_position' => 9, 'menu_icon' => 'dashicons-editor-alignleft', 'supports' => ['title', 'editor']); register_post_type('section', $section_args); $sermon_labels = array('name' => __('Sermons'), 'singular_name' => __('Sermon'), 'add_new_item' => __('Upload New Sermon')); $sermon_args = array('labels' => $sermon_labels, 'public' => true, 'has_archive' => true, 'rewrite' => array('slug' => 'sermons'), 'menu_position' => 5, 'menu_icon' => 'dashicons-megaphone', 'supports' => ['title', 'editor', 'thumbnail']); register_post_type('sermon', $sermon_args); set_post_format('sermon', 'audio'); $event_labels = array('name' => __('Events'), 'singular_name' => __('Event'), 'add_new_item' => __('Add New Event')); $event_args = array('labels' => $event_labels, 'public' => true, 'has_archive' => true, 'rewrite' => array('slug' => 'events'), 'menu_position' => 5, 'menu_icon' => 'dashicons-location-alt', 'supports' => ['title', 'editor', 'thumbnail']); register_post_type('event', $event_args); }
public function save($item) { global $post; $post = array(); $metas = array(); global $ph_migrate_field_handlers; $field_handlers = array(); $class = get_class($this); while (FALSE != $class) { if (isset($ph_migrate_field_handlers[$class])) { $field_handlers = array_merge($field_handlers, $ph_migrate_field_handlers[$class]); } $class = get_parent_class($class); } $postprocess = array(); foreach ($item as $property => $value) { $handled = false; foreach ($field_handlers as $key => $callback) { if (0 === strpos($property, $key)) { $handled = true; if (!isset($postprocess[$key])) { $postprocess[$key] = array('callback' => $callback, 'fields' => array()); } $postprocess[$key]['fields'][$property] = $value; } } if (!$handled) { $post[$property] = $value; } } if (isset($post['ID'])) { wp_update_post($post); if (isset($post['post_format'])) { set_post_format($post['ID'], $post['post_format']); } $id = $post['ID']; ph_migrate_statistics_increment("Posts (Type:" . $post['post_type'] . ") updated", 1); } else { $id = wp_insert_post($post); $post['ID'] = $id; if (isset($post['post_format'])) { set_post_format($post['ID'], $post['post_format']); } ph_migrate_statistics_increment("Posts (Type:" . $post['post_type'] . ") created", 1); } foreach ($postprocess as $key => $dataset) { $callback = $dataset['callback']; $callback($post, $dataset['fields']); } return $id; }
public function data_template_requests() { $post = self::factory()->post->create_and_get(array('post_type' => 'post', 'post_name' => 'post-name')); set_post_format($post, 'quote'); $page = self::factory()->post->create_and_get(array('post_type' => 'page', 'post_name' => 'page-name')); add_post_meta($page->ID, '_wp_page_template', 'templates/page.php'); $data = array(); // Single post embed $data[] = array(get_post_embed_url($post), array('embed-post-quote.php', 'embed-post.php', 'embed.php', 'single-post-post-name.php', 'single-post.php', 'single.php', 'singular.php')); // Search $data[] = array(add_query_arg('s', 'foo', home_url()), array('search.php')); // Single page $data[] = array(get_permalink($page), array('templates/page.php', 'page-page-name.php', "page-{$page->ID}.php", 'page.php', 'singular.php')); // Single post $data[] = array(get_permalink($post), array('single-post-post-name.php', 'single-post.php', 'single.php', 'singular.php')); return $data; }
function test_has_format() { $post_id = $this->factory->post->create(); $this->assertFalse(has_post_format('standard', $post_id)); $this->assertFalse(has_post_format('', $post_id)); $result = set_post_format($post_id, 'aside'); $this->assertNotInstanceOf('WP_Error', $result); $this->assertInternalType('array', $result); $this->assertEquals(1, count($result)); $this->assertTrue(has_post_format('aside', $post_id)); $result = set_post_format($post_id, 'standard'); $this->assertNotInstanceOf('WP_Error', $result); $this->assertInternalType('array', $result); $this->assertEquals(0, count($result)); // Standard is a special case. It shows as false when set. $this->assertFalse(has_post_format('standard', $post_id)); // Dummy format type $this->assertFalse(has_post_format('dummy', $post_id)); // Dummy post id $this->assertFalse(has_post_format('aside', 12345)); }
function apply($postid, $postdetails) { if ($this->PostFormat != 'standard') { set_post_format($postid, $this->PostFormat); } }
function save_post_actions($pidd, $post) { global $wpdb; wp_defer_term_counting(true); list($post_type, $post_status) = $wpdb->get_row("SELECT post_type, post_status FROM {$wpdb->posts} WHERE ID = " . $pidd, ARRAY_N); // exceptions if (!$this->is_translated_post_type($post_type) || isset($post) && $post->post_status == "auto-draft" || isset($_POST['autosave']) || isset($_POST['skip_sitepress_actions']) || isset($_POST['post_ID']) && $_POST['post_ID'] != $pidd || isset($_POST['post_type']) && $_POST['post_type'] == 'revision' || $post_type == 'revision' || get_post_meta($pidd, '_wp_trash_meta_status', true) || isset($_GET['action']) && $_GET['action'] == 'untrash') { wp_defer_term_counting(false); return; } $default_language = $this->get_default_language(); if (!isset($post) && $pidd) { $post = get_post($pidd); } // exception for auto-drafts - setting the right language // allow post arguments to be passed via wp_insert_post directly and not be expected on $_POST exclusively $post_vars = (array) $_POST; foreach ((array) $post as $k => $v) { $post_vars[$k] = $v; } if (!isset($post_vars['post_type'])) { $post_vars['post_type'] = $post_type; } $element_type = 'post_' . $post_type; $language_code = false; if (isset($post_vars['action']) && $post_vars['action'] == 'post-quickpress-publish') { $post_id = $pidd; $language_code = $default_language; } elseif (isset($_GET['bulk_edit'])) { $post_id = $pidd; } else { $post_id = isset($post_vars['post_ID']) ? $post_vars['post_ID'] : $pidd; //latter case for XML-RPC publishing if (isset($post_vars['icl_post_language'])) { $language_code = $post_vars['icl_post_language']; } elseif (isset($_GET['lang'])) { $language_code = $_GET['lang']; } elseif ($_ldet = $this->get_element_language_details($post_id, $element_type)) { $language_code = $_ldet->language_code; } elseif (isset($this->this_lang)) { $language_code = $this->this_lang; } else { $language_code = $default_language; //latter case for XML-RPC publishing } } if (isset($post_vars['action']) && $post_vars['action'] == 'inline-save' || isset($_GET['bulk_edit']) || isset($_GET['doing_wp_cron']) || isset($_GET['action']) && $_GET['action'] == 'untrash') { $res = $this->get_element_language_details($post_id, 'post_' . $post->post_type); if (!isset($res) || !$res) { return; } $language_code = $res->language_code; $trid = $res->trid; } else { if (isset($post_vars['icl_trid'])) { $trid = @intval($post_vars['icl_trid']); } elseif (isset($_GET['trid'])) { $trid = @intval($_GET['trid']); } else { $trid = $this->get_element_trid($post_id, 'post_' . $post->post_type); } // see if we have a "translation of" setting. if (isset($post_vars['icl_translation_of'])) { if (is_numeric($post_vars['icl_translation_of'])) { $translation_of_data_prepared = $wpdb->prepare("SELECT trid, language_code FROM {$wpdb->prefix}icl_translations WHERE element_id=%d AND element_type=%s", $post_vars['icl_translation_of'], 'post_' . $post->post_type); list($trid, $source_language) = $wpdb->get_row($translation_of_data_prepared, 'ARRAY_N'); } else { if (empty($post_vars['icl_trid'])) { $trid = null; } } } } if (isset($_POST['action']) && $_POST['action'] == 'inline-save') { $trid = $this->get_element_trid($post_id, 'post_' . $post_type); } else { if (isset($post_vars['icl_translation_of']) && $post_vars['icl_translation_of'] == 'none') { $trid = null; } } if (!$trid) { $trid_from_referrer = $this->get_trid_from_referer(); if ($trid_from_referrer) { $trid = $trid_from_referrer; } } if (!$this->is_active_language($language_code)) { $language_code = $default_language; } // set trid if front-end translation creating $trid = apply_filters('wpml_save_post_trid_value', $trid, $post_status); // set post language if front-end translation creating $language_code = apply_filters('wpml_save_post_lang', $language_code); // after getting the right trid set the source language from it by referring to the root translation // of this trid, in case no proper source language is set already if (!isset($source_language) || !$source_language || $source_language == $language_code) { //if we are in the editor we can get the source language from the http-referer of the ajax request $source_language = self::get_source_language_from_referer(); if (!$source_language) { //if getting the source language from the referer fails too, we get that of the first element of the trid $source_language = self::get_source_language_by_trid($trid); } } /* Before setting the language of the post to be saved, check if a translation in this language already exists * This check is necessary, so that synchronization actions like thrashing or un-trashing of posts, do not lead to * database corruption, due to erroneously changing a posts language into a state, * where it collides with an existing translation. While the UI prevents this sort of action for the most part, * this is not necessarily the case for other plugins like TM. * The logic here first of all checks if an existing translation id is present in the desired language_code. * If so but this translation is actually not the currently to be saved post, * then this post will be saved to its current language. If the translation already exists, * the existing translation id will be used. In all other cases a new entry in icl_translations will be created. */ $existing_translations = $this->get_element_translations($trid, $element_type); if ($existing_translations && isset($existing_translations[$language_code])) { $current_language_details = $this->get_element_language_details($post_id, $element_type); $existing_translation = $existing_translations[$language_code]; if ($current_language_details && isset($current_language_details->language_code) && $existing_translation && isset($existing_translation->element_id) && isset($current_language_details->element_id) && $existing_translation->element_id != $current_language_details->element_id) { $translation_id = $existing_translations[$current_language_details->language_code]->translation_id; $language_code = $current_language_details->language_code; } else { $translation_id = $existing_translations[$existing_translation->language_code]->translation_id; } } else { $translation_id = $this->set_element_language_details($post_id, $element_type, $trid, $language_code, $source_language); } //get trid of $translation_id $translated_id_trid = $wpdb->get_var($wpdb->prepare("SELECT trid FROM {$wpdb->prefix}icl_translations WHERE translation_id=%d", array($translation_id))); //get all translations $translated_element_id = $wpdb->get_col($wpdb->prepare("SELECT element_id FROM {$wpdb->prefix}icl_translations WHERE trid=%d", $translated_id_trid)); if (!in_array($post_type, array('post', 'page')) && !$this->is_translated_post_type($post_type)) { wp_defer_term_counting(false); return; } // synchronize the page order for translations if ($trid && $this->settings['sync_page_ordering'] && $translated_element_id && is_array($translated_element_id)) { $menu_order = esc_sql($post_vars['menu_order']); // Only use non-null element ids for the menu ordering. $non_null_eids = array_filter($translated_element_id); $wpdb->query("UPDATE {$wpdb->posts} SET menu_order={$menu_order} WHERE ID IN (" . join(',', $non_null_eids) . ")"); } // synchronize the page parent for translations if ($trid && $this->settings['sync_page_parent']) { $original_id = $this->get_original_element_id($post_id, 'post_' . $post_vars['post_type']); if ($original_id == $post_id) { $translations = $this->get_element_translations($trid, 'post_' . $post_vars['post_type']); foreach ($translations as $target_lang => $target_details) { if ($target_lang != $language_code) { if ($target_details->element_id) { $this->fix_translated_parent($post_id, $target_details->element_id, $target_lang); } } } } } // synchronize the page template if (isset($post_vars['page_template']) && $trid && $post_vars['post_type'] == 'page' && $this->settings['sync_page_template']) { if ($translated_element_id && is_array($translated_element_id)) { foreach ($translated_element_id as $tp) { if ($tp != $post_id) { update_post_meta($tp, '_wp_page_template', $post_vars['page_template']); } } } } // synchronize comment and ping status if ($trid && ($this->settings['sync_ping_status'] || $this->settings['sync_comment_status'])) { $arr = array(); if ($this->settings['sync_comment_status']) { $arr['comment_status'] = $post_vars['comment_status']; } if ($this->settings['sync_ping_status']) { $arr['ping_status'] = $post_vars['ping_status']; } if (!empty($arr) && $translated_element_id && is_array($translated_element_id)) { foreach ($translated_element_id as $tp) { if ($tp != $post_id) { $wpdb->update($wpdb->posts, $arr, array('ID' => $tp)); } } } } // copy custom fields from original $translations = $this->get_element_translations($trid, 'post_' . $post_vars['post_type']); if (!empty($translations)) { $original_post_id = false; foreach ($translations as $t) { if ($t->original) { $original_post_id = $t->element_id; break; } } // this runs only for translated documents if ($post_id != $original_post_id) { $this->copy_custom_fields($original_post_id, $post_id); } else { foreach ($translations as $t) { if ($original_post_id != $t->element_id) { $this->copy_custom_fields($original_post_id, $t->element_id); } } } } //sync posts stickiness if (isset($post_vars['post_type']) && $post_vars['post_type'] == 'post' && isset($post_vars['action']) && $post_vars['action'] != 'post-quickpress-publish' && $this->settings['sync_sticky_flag']) { //not for quick press remove_filter('option_sticky_posts', array($this, 'option_sticky_posts')); // remove filter used to get language relevant stickies. get them all $sticky_posts = get_option('sticky_posts'); add_filter('option_sticky_posts', array($this, 'option_sticky_posts')); // add filter back // get ids of the translations if ($trid) { $translations = $wpdb->get_col($wpdb->prepare("SELECT element_id FROM {$wpdb->prefix}icl_translations WHERE trid=%d", $trid)); } else { $translations = array(); } if (isset($post_vars['sticky']) && $post_vars['sticky'] == 'sticky') { $sticky_posts = array_unique(array_merge($sticky_posts, $translations)); } else { //makes sure translations are not set to sticky if this posts switched from sticky to not-sticky $sticky_posts = array_diff($sticky_posts, $translations); } update_option('sticky_posts', $sticky_posts); } //sync private flag if ($this->settings['sync_private_flag']) { if ($post_status == 'private' && (empty($post_vars['original_post_status']) || $post_vars['original_post_status'] != 'private')) { if ($translated_element_id && is_array($translated_element_id)) { foreach ($translated_element_id as $tp) { if ($tp != $post_id) { $wpdb->update($wpdb->posts, array('post_status' => 'private'), array('ID' => $tp)); } } } } elseif ($post_status != 'private' && isset($post_vars['original_post_status']) && $post_vars['original_post_status'] == 'private') { if ($translated_element_id && is_array($translated_element_id)) { foreach ($translated_element_id as $tp) { if ($tp != $post_id) { $wpdb->update($wpdb->posts, array('post_status' => $post_status), array('ID' => $tp)); } } } } } //sync post format if ($this->settings['sync_post_format'] && function_exists('set_post_format')) { $format = get_post_format($post_id); if ($translated_element_id && is_array($translated_element_id)) { foreach ($translated_element_id as $tp) { if ($tp != $post_id) { set_post_format($tp, $format); } } } } // sync post dates if (!empty($this->settings['sync_post_date'])) { if ($language_code == $default_language) { if ($translated_element_id && is_array($translated_element_id)) { $post_date = $wpdb->get_var($wpdb->prepare("SELECT post_date FROM {$wpdb->posts} WHERE ID=%d", $post_id)); foreach ($translated_element_id as $tp) { if ($tp != $post_id) { $wpdb->update($wpdb->posts, array('post_date' => $post_date, 'post_date_gmt' => get_gmt_from_date($post_date)), array('ID' => $tp)); } } } } else { if (!is_null($trid)) { $source_lang = isset($_GET['source_lang']) ? $_GET['source_lang'] : $default_language; $original_id = $wpdb->get_var($wpdb->prepare("SELECT element_id FROM {$wpdb->prefix}icl_translations WHERE trid=%d AND language_code=%s", $trid, $source_lang)); if (!$original_id) { global $post; if (isset($post->ID)) { $original_id = $post->ID; } } if (isset($original_id)) { $post_date = $wpdb->get_var($wpdb->prepare("SELECT post_date FROM {$wpdb->posts} WHERE ID=%d", $original_id)); $wpdb->update($wpdb->posts, array('post_date' => $post_date, 'post_date_gmt' => get_gmt_from_date($post_date)), array('ID' => $post_id)); } } } } if (isset($post_vars['icl_tn_note'])) { update_post_meta($post_id, '_icl_translator_note', $post_vars['icl_tn_note']); } //fix guid if ($this->settings['language_negotiation_type'] == 2 && $this->get_current_language() != $default_language) { $guid = $this->convert_url(get_post_field('guid', $post_id)); $wpdb->update($wpdb->posts, array('guid' => $guid), array('id' => $post_id)); } require_once ICL_PLUGIN_PATH . '/inc/cache.php'; icl_cache_clear($post_vars['post_type'] . 's_per_language', true); wp_defer_term_counting(false); }
/** * Default post information to use when populating the "Write Post" form. * * @since 2.0.0 * * @param string $post_type Optional. A post type string. Default 'post'. * @param bool $create_in_db Optional. Whether to insert the post into database. Default false. * @return WP_Post Post object containing all the default post data as attributes */ function get_default_post_to_edit($post_type = 'post', $create_in_db = false) { $post_title = ''; if (!empty($_REQUEST['post_title'])) { $post_title = esc_html(wp_unslash($_REQUEST['post_title'])); } $post_content = ''; if (!empty($_REQUEST['content'])) { $post_content = esc_html(wp_unslash($_REQUEST['content'])); } $post_excerpt = ''; if (!empty($_REQUEST['excerpt'])) { $post_excerpt = esc_html(wp_unslash($_REQUEST['excerpt'])); } if ($create_in_db) { $post_id = wp_insert_post(array('post_title' => __('Auto Draft'), 'post_type' => $post_type, 'post_status' => 'auto-draft')); $post = get_post($post_id); if (current_theme_supports('post-formats') && post_type_supports($post->post_type, 'post-formats') && get_option('default_post_format')) { set_post_format($post, get_option('default_post_format')); } } else { $post = new stdClass(); $post->ID = 0; $post->post_author = ''; $post->post_date = ''; $post->post_date_gmt = ''; $post->post_password = ''; $post->post_name = ''; $post->post_type = $post_type; $post->post_status = 'draft'; $post->to_ping = ''; $post->pinged = ''; $post->comment_status = get_default_comment_status($post_type); $post->ping_status = get_default_comment_status($post_type, 'pingback'); $post->post_pingback = get_option('default_pingback_flag'); $post->post_category = get_option('default_category'); $post->page_template = 'default'; $post->post_parent = 0; $post->menu_order = 0; $post = new WP_Post($post); } /** * Filters the default post content initially used in the "Write Post" form. * * @since 1.5.0 * * @param string $post_content Default post content. * @param WP_Post $post Post object. */ $post->post_content = apply_filters('default_content', $post_content, $post); /** * Filters the default post title initially used in the "Write Post" form. * * @since 1.5.0 * * @param string $post_title Default post title. * @param WP_Post $post Post object. */ $post->post_title = apply_filters('default_title', $post_title, $post); /** * Filters the default post excerpt initially used in the "Write Post" form. * * @since 1.5.0 * * @param string $post_excerpt Default post excerpt. * @param WP_Post $post Post object. */ $post->post_excerpt = apply_filters('default_excerpt', $post_excerpt, $post); return $post; }
/** * 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; }
function woo_tumblog_publish($type, $data) { global $current_user; //Gets the current user's info get_currentuserinfo(); $content_method = get_option('woo_tumblog_content_method'); //Set custom fields $tumblog_custom_fields = array('video-embed' => 'video-embed', 'quote-copy' => 'quote-copy', 'quote-author' => 'quote-author', 'quote-url' => 'quote-url', 'link-url' => 'link-url', 'image-url' => 'image', 'audio-url' => 'audio'); //get term ids $tumblog_items = array('articles' => get_option('woo_articles_term_id'), 'images' => get_option('woo_images_term_id'), 'audio' => get_option('woo_audio_term_id'), 'video' => get_option('woo_video_term_id'), 'quotes' => get_option('woo_quotes_term_id'), 'links' => get_option('woo_links_term_id')); //Set date formatting $php_formatting = "Y-m-d H:i:s"; //default post settings $tumbl_note = array(); $tumbl_note['post_status'] = 'publish'; $browser = $_SERVER['HTTP_USER_AGENT'] . "\n\n"; $safari_check = substr_count(strtolower($browser), strtolower('safari')); if ($safari_check > 0) { $data['tumblog-content'] = str_ireplace(array('<div>', '</div>'), array('', '<br>'), $data['tumblog-content']); $data['tumblog-content'] = str_ireplace(array('<br><br><br>'), array('<br><br>'), $data['tumblog-content']); $data['tumblog-content'] = str_ireplace(array(' '), array(' '), $data['tumblog-content']); } //Handle Tumblog Types switch ($type) { case 'note': //Create post object $tumbl_note['post_title'] = $data['note-title']; $tumbl_note['post_content'] = $data['tumblog-content']; // DEPRECATED // if (get_option( 'tumblog_woo_tumblog_upgraded') == 'true') { if ($data['tumblog-status'] != '') { $tumbl_note['post_status'] = $data['tumblog-status']; } //Hours and Mins $original_hours = (int) $data['original-tumblog-hours']; $original_mins = (int) $data['original-tumblog-mins']; $original_date = strtotime($data['original-tumblog-date']); $posted_date = strtotime($data['tumblog-date']); $note_hours = (int) $data['tumblog-hours']; if ($note_hours == 0) { $note_hours = 12; } elseif ($note_hours >= 24) { $note_hours = 0; } $note_mins = (int) $data['tumblog-mins']; if ($note_mins == 0) { $note_mins = 0; } elseif ($note_mins >= 60) { $note_mins = 0; } //Convert to Y-m-d H:i:s //if everything is unchanged if ($note_hours == $original_hours && $note_mins == $original_mins && $posted_date == $original_date) { $time_now_hours = date_i18n("H"); $time_now_mins = date_i18n("i"); $date_raw = date("Y") . '-' . date("m") . '-' . date("d") . ' ' . $time_now_hours . ':' . $time_now_mins . ':00'; } else { $date_raw = date("Y", strtotime($data['tumblog-date'])) . '-' . date("m", strtotime($data['tumblog-date'])) . '-' . date("d", strtotime($data['tumblog-date'])) . ' ' . $note_hours . ':' . $note_mins . ':00'; } $date_formatted = date($php_formatting, strtotime($date_raw)); $tumbl_note['post_date'] = $date_formatted; // DEPRECATED // } $tumbl_note['post_author'] = $current_user->ID; $tumbl_note['tags_input'] = $data['tumblog-tags']; // DEPRECATED // Get Category from Theme Options /* if (get_option( 'tumblog_woo_tumblog_upgraded') != 'true') { $category_id = get_cat_ID( get_option( 'woo_articles_category') ); $categories = array($category_id); } else { $categories = array(); } */ $categories = array(); $post_cat_array = $data['post_category']; if (empty($post_cat_array)) { //Do nothing } else { $N = count($post_cat_array); for ($i = 0; $i < $N; $i++) { array_push($categories, $post_cat_array[$i]); } } $tumbl_note['post_category'] = $categories; //Insert the note into the database $post_id = wp_insert_post($tumbl_note); // DEPRECATED // if (get_option( 'tumblog_woo_tumblog_upgraded') == 'true') { if ($content_method == 'post_format') { set_post_format($post_id, 'aside'); } else { //update posts taxonomies $taxonomy_data = $data['tax_input']; if (!empty($taxonomy_data)) { foreach ($taxonomy_data as $taxonomy => $tags) { $taxonomy_obj = get_taxonomy($taxonomy); if (is_array($tags)) { // array = hierarchical, string = non-hierarchical. $tags = array_filter($tags); } if (current_user_can($taxonomy_obj->cap->assign_terms)) { array_push($tags, $tumblog_items['articles']); } } } else { $tags[0] = $tumblog_items['articles']; } wp_set_post_terms($post_id, $tags, 'tumblog'); } // DEPRECATED // } break; case 'video': //Create post object $tumbl_note['post_title'] = $data['video-title']; $tumbl_note['post_content'] = $data['tumblog-content']; // DEPRECATED //if (get_option( 'tumblog_woo_tumblog_upgraded') == 'true') { if ($data['tumblog-status'] != '') { $tumbl_note['post_status'] = $data['tumblog-status']; } //Hours and Mins $original_hours = (int) $data['original-tumblog-hours']; $original_mins = (int) $data['original-tumblog-mins']; $original_date = strtotime($data['original-tumblog-date']); $posted_date = strtotime($data['tumblog-date']); $note_hours = (int) $data['tumblog-hours']; if ($note_hours == 0) { $note_hours = 12; } elseif ($note_hours >= 24) { $note_hours = 0; } $note_mins = (int) $data['tumblog-mins']; if ($note_mins == 0) { $note_mins = 0; } elseif ($note_mins >= 60) { $note_mins = 0; } //Convert to Y-m-d H:i:s //if everything is unchanged if ($note_hours == $original_hours && $note_mins == $original_mins && $posted_date == $original_date) { $time_now_hours = date_i18n("H"); $time_now_mins = date_i18n("i"); $date_raw = date("Y") . '-' . date("m") . '-' . date("d") . ' ' . $time_now_hours . ':' . $time_now_mins . ':00'; } else { $date_raw = date("Y", strtotime($data['tumblog-date'])) . '-' . date("m", strtotime($data['tumblog-date'])) . '-' . date("d", strtotime($data['tumblog-date'])) . ' ' . $note_hours . ':' . $note_mins . ':00'; } $date_formatted = date($php_formatting, strtotime($date_raw)); $tumbl_note['post_date'] = $date_formatted; // DEPRECATED // } $tumbl_note['post_author'] = $current_user->ID; $tumbl_note['tags_input'] = $data['tumblog-tags']; // DEPRECATED //Get Category from Theme Options /* if (get_option( 'tumblog_woo_tumblog_upgraded') != 'true') { $category_id = get_cat_ID( get_option( 'woo_videos_category') ); $categories = array($category_id); } else { $categories = array(); } */ $categories = array(); $post_cat_array = $data['post_category']; if (empty($post_cat_array)) { //Do nothing } else { $N = count($post_cat_array); for ($i = 0; $i < $N; $i++) { array_push($categories, $post_cat_array[$i]); } } $tumbl_note['post_category'] = $categories; //Insert the note into the database $post_id = wp_insert_post($tumbl_note); //Add Custom Field Data to the Post add_post_meta($post_id, $tumblog_custom_fields['video-embed'], $data['video-embed'], true); // DEPRECATED // if (get_option( 'tumblog_woo_tumblog_upgraded') == 'true') { if ($content_method == 'post_format') { set_post_format($post_id, 'video'); } else { //update posts taxonomies $taxonomy_data = $data['tax_input']; if (!empty($taxonomy_data)) { foreach ($taxonomy_data as $taxonomy => $tags) { $taxonomy_obj = get_taxonomy($taxonomy); if (is_array($tags)) { // array = hierarchical, string = non-hierarchical. $tags = array_filter($tags); } if (current_user_can($taxonomy_obj->cap->assign_terms)) { array_push($tags, $tumblog_items['video']); } } } else { $tags[0] = $tumblog_items['video']; } wp_set_post_terms($post_id, $tags, 'tumblog'); } // DEPRECATED // } break; case 'image': //Create post object $tumbl_note['post_title'] = $data['image-title']; $tumbl_note['post_content'] = $data['tumblog-content']; // DEPRECATED // if (get_option( 'tumblog_woo_tumblog_upgraded') == 'true') { if ($data['tumblog-status'] != '') { $tumbl_note['post_status'] = $data['tumblog-status']; } //Hours and Mins $original_hours = (int) $data['original-tumblog-hours']; $original_mins = (int) $data['original-tumblog-mins']; $original_date = strtotime($data['original-tumblog-date']); $posted_date = strtotime($data['tumblog-date']); $note_hours = (int) $data['tumblog-hours']; if ($note_hours == 0) { $note_hours = 12; } elseif ($note_hours >= 24) { $note_hours = 0; } $note_mins = (int) $data['tumblog-mins']; if ($note_mins == 0) { $note_mins = 0; } elseif ($note_mins >= 60) { $note_mins = 0; } //Convert to Y-m-d H:i:s //if everything is unchanged if ($note_hours == $original_hours && $note_mins == $original_mins && $posted_date == $original_date) { $time_now_hours = date_i18n("H"); $time_now_mins = date_i18n("i"); $date_raw = date("Y") . '-' . date("m") . '-' . date("d") . ' ' . $time_now_hours . ':' . $time_now_mins . ':00'; } else { $date_raw = date("Y", strtotime($data['tumblog-date'])) . '-' . date("m", strtotime($data['tumblog-date'])) . '-' . date("d", strtotime($data['tumblog-date'])) . ' ' . $note_hours . ':' . $note_mins . ':00'; } $date_formatted = date($php_formatting, strtotime($date_raw)); $tumbl_note['post_date'] = $date_formatted; // DEPRECATED // } $tumbl_note['post_author'] = $current_user->ID; $tumbl_note['tags_input'] = $data['tumblog-tags']; // DEPRECATED //Get Category from Theme Options /* if (get_option( 'tumblog_woo_tumblog_upgraded') != 'true') { $category_id = get_cat_ID( get_option( 'woo_images_category') ); $categories = array($category_id); } else { $categories = array(); } */ $categories = array(); $post_cat_array = $data['post_category']; if (empty($post_cat_array)) { //Do nothing } else { $N = count($post_cat_array); for ($i = 0; $i < $N; $i++) { array_push($categories, $post_cat_array[$i]); } } $tumbl_note['post_category'] = $categories; //Insert the note into the database $post_id = wp_insert_post($tumbl_note); //Add Custom Field Data to the Post if ($data['image-id'] > 0) { $my_post = array(); $my_post['ID'] = $data['image-id']; $my_post['post_parent'] = $post_id; //Update the post into the database wp_update_post($my_post); add_post_meta($post_id, $tumblog_custom_fields['image-url'], $data['image-upload'], true); } else { add_post_meta($post_id, $tumblog_custom_fields['image-url'], $data['image-url'], true); } // DEPRECATED // if (get_option( 'tumblog_woo_tumblog_upgraded') == 'true') { if ($content_method == 'post_format') { set_post_format($post_id, 'image'); } else { //update posts taxonomies $taxonomy_data = $data['tax_input']; if (!empty($taxonomy_data)) { foreach ($taxonomy_data as $taxonomy => $tags) { $taxonomy_obj = get_taxonomy($taxonomy); if (is_array($tags)) { // array = hierarchical, string = non-hierarchical. $tags = array_filter($tags); } if (current_user_can($taxonomy_obj->cap->assign_terms)) { array_push($tags, $tumblog_items['images']); } } } else { $tags[0] = $tumblog_items['images']; } wp_set_post_terms($post_id, $tags, 'tumblog'); } // DEPRECATED // } break; case 'link': //Create post object $tumbl_note['post_title'] = $data['link-title']; $tumbl_note['post_content'] = $data['tumblog-content']; // DEPRECATED // if (get_option( 'tumblog_woo_tumblog_upgraded') == 'true') { if ($data['tumblog-status'] != '') { $tumbl_note['post_status'] = $data['tumblog-status']; } //Hours and Mins $original_hours = (int) $data['original-tumblog-hours']; $original_mins = (int) $data['original-tumblog-mins']; $original_date = strtotime($data['original-tumblog-date']); $posted_date = strtotime($data['tumblog-date']); $note_hours = (int) $data['tumblog-hours']; if ($note_hours == 0) { $note_hours = 12; } elseif ($note_hours >= 24) { $note_hours = 0; } $note_mins = (int) $data['tumblog-mins']; if ($note_mins == 0) { $note_mins = 0; } elseif ($note_mins >= 60) { $note_mins = 0; } //Convert to Y-m-d H:i:s //if everything is unchanged if ($note_hours == $original_hours && $note_mins == $original_mins && $posted_date == $original_date) { $time_now_hours = date_i18n("H"); $time_now_mins = date_i18n("i"); $date_raw = date("Y") . '-' . date("m") . '-' . date("d") . ' ' . $time_now_hours . ':' . $time_now_mins . ':00'; } else { $date_raw = date("Y", strtotime($data['tumblog-date'])) . '-' . date("m", strtotime($data['tumblog-date'])) . '-' . date("d", strtotime($data['tumblog-date'])) . ' ' . $note_hours . ':' . $note_mins . ':00'; } $date_formatted = date($php_formatting, strtotime($date_raw)); $tumbl_note['post_date'] = $date_formatted; // DEPRECATED // } $tumbl_note['post_author'] = $current_user->ID; $tumbl_note['tags_input'] = $data['tumblog-tags']; // DEPRECATED //Get Category from Theme Options /* if (get_option( 'tumblog_woo_tumblog_upgraded') != 'true') { $category_id = get_cat_ID( get_option( 'woo_links_category') ); $categories = array($category_id); } else { $categories = array(); } */ $categories = array(); $post_cat_array = $data['post_category']; if (empty($post_cat_array)) { //Do nothing } else { $N = count($post_cat_array); for ($i = 0; $i < $N; $i++) { array_push($categories, $post_cat_array[$i]); } } $tumbl_note['post_category'] = $categories; //Insert the note into the database $post_id = wp_insert_post($tumbl_note); //Add Custom Field Data to the Post add_post_meta($post_id, $tumblog_custom_fields['link-url'], $data['link-url'], true); // DEPRECATED // if (get_option( 'tumblog_woo_tumblog_upgraded') == 'true') { if ($content_method == 'post_format') { set_post_format($post_id, 'link'); } else { //update posts taxonomies $taxonomy_data = $data['tax_input']; if (!empty($taxonomy_data)) { foreach ($taxonomy_data as $taxonomy => $tags) { $taxonomy_obj = get_taxonomy($taxonomy); if (is_array($tags)) { // array = hierarchical, string = non-hierarchical. $tags = array_filter($tags); } if (current_user_can($taxonomy_obj->cap->assign_terms)) { array_push($tags, $tumblog_items['links']); } } } else { $tags[0] = $tumblog_items['links']; } wp_set_post_terms($post_id, $tags, 'tumblog'); } // DEPRECATED // } break; case 'quote': //Create post object $tumbl_note['post_title'] = $data['quote-title']; $tumbl_note['post_content'] = $data['tumblog-content']; // DEPRECATED // if (get_option( 'tumblog_woo_tumblog_upgraded') == 'true') { if ($data['tumblog-status'] != '') { $tumbl_note['post_status'] = $data['tumblog-status']; } //Hours and Mins $original_hours = (int) $data['original-tumblog-hours']; $original_mins = (int) $data['original-tumblog-mins']; $original_date = strtotime($data['original-tumblog-date']); $posted_date = strtotime($data['tumblog-date']); $note_hours = (int) $data['tumblog-hours']; if ($note_hours == 0) { $note_hours = 12; } elseif ($note_hours >= 24) { $note_hours = 0; } $note_mins = (int) $data['tumblog-mins']; if ($note_mins == 0) { $note_mins = 0; } elseif ($note_mins >= 60) { $note_mins = 0; } //Convert to Y-m-d H:i:s //if everything is unchanged if ($note_hours == $original_hours && $note_mins == $original_mins && $posted_date == $original_date) { $time_now_hours = date_i18n("H"); $time_now_mins = date_i18n("i"); $date_raw = date("Y") . '-' . date("m") . '-' . date("d") . ' ' . $time_now_hours . ':' . $time_now_mins . ':00'; } else { $date_raw = date("Y", strtotime($data['tumblog-date'])) . '-' . date("m", strtotime($data['tumblog-date'])) . '-' . date("d", strtotime($data['tumblog-date'])) . ' ' . $note_hours . ':' . $note_mins . ':00'; } $date_formatted = date($php_formatting, strtotime($date_raw)); $tumbl_note['post_date'] = $date_formatted; // DEPRECATED // } $tumbl_note['post_author'] = $current_user->ID; $tumbl_note['tags_input'] = $data['tumblog-tags']; // DEPRECATED //Get Category from Theme Options /* if (get_option( 'tumblog_woo_tumblog_upgraded') != 'true') { $category_id = get_cat_ID( get_option( 'woo_quotes_category') ); $categories = array($category_id); } else { $categories = array(); } */ $categories = array(); $post_cat_array = $data['post_category']; if (empty($post_cat_array)) { //Do nothing } else { $N = count($post_cat_array); for ($i = 0; $i < $N; $i++) { array_push($categories, $post_cat_array[$i]); } } $tumbl_note['post_category'] = $categories; //Insert the note into the database $post_id = wp_insert_post($tumbl_note); //Add Custom Field Data to the Post add_post_meta($post_id, $tumblog_custom_fields['quote-copy'], $data['quote-copy'], true); add_post_meta($post_id, $tumblog_custom_fields['quote-author'], $data['quote-author'], true); add_post_meta($post_id, $tumblog_custom_fields['quote-url'], $data['quote-url'], true); // DEPRECATED // if (get_option( 'tumblog_woo_tumblog_upgraded') == 'true') { if ($content_method == 'post_format') { set_post_format($post_id, 'quote'); } else { //update posts taxonomies $taxonomy_data = $data['tax_input']; if (!empty($taxonomy_data)) { foreach ($taxonomy_data as $taxonomy => $tags) { $taxonomy_obj = get_taxonomy($taxonomy); if (is_array($tags)) { // array = hierarchical, string = non-hierarchical. $tags = array_filter($tags); } if (current_user_can($taxonomy_obj->cap->assign_terms)) { array_push($tags, $tumblog_items['quotes']); } } } else { $tags[0] = $tumblog_items['quotes']; } wp_set_post_terms($post_id, $tags, 'tumblog'); } // DEPRECATED // } break; case 'audio': //Create post object $tumbl_note['post_title'] = $data['audio-title']; $tumbl_note['post_content'] = $data['tumblog-content']; // DEPRECATED // if (get_option( 'tumblog_woo_tumblog_upgraded') == 'true') { if ($data['tumblog-status'] != '') { $tumbl_note['post_status'] = $data['tumblog-status']; } //Hours and Mins $original_hours = (int) $data['original-tumblog-hours']; $original_mins = (int) $data['original-tumblog-mins']; $original_date = strtotime($data['original-tumblog-date']); $posted_date = strtotime($data['tumblog-date']); $note_hours = (int) $data['tumblog-hours']; if ($note_hours == 0) { $note_hours = 12; } elseif ($note_hours >= 24) { $note_hours = 0; } $note_mins = (int) $data['tumblog-mins']; if ($note_mins == 0) { $note_mins = 0; } elseif ($note_mins >= 60) { $note_mins = 0; } //Convert to Y-m-d H:i:s //if everything is unchanged if ($note_hours == $original_hours && $note_mins == $original_mins && $posted_date == $original_date) { $time_now_hours = date_i18n("H"); $time_now_mins = date_i18n("i"); $date_raw = date("Y") . '-' . date("m") . '-' . date("d") . ' ' . $time_now_hours . ':' . $time_now_mins . ':00'; } else { $date_raw = date("Y", strtotime($data['tumblog-date'])) . '-' . date("m", strtotime($data['tumblog-date'])) . '-' . date("d", strtotime($data['tumblog-date'])) . ' ' . $note_hours . ':' . $note_mins . ':00'; } $date_formatted = date($php_formatting, strtotime($date_raw)); $tumbl_note['post_date'] = $date_formatted; // DEPRECATED // } $tumbl_note['post_author'] = $current_user->ID; $tumbl_note['tags_input'] = $data['tumblog-tags']; // DEPRECATED //Get Category from Theme Options /* if (get_option( 'tumblog_woo_tumblog_upgraded') != 'true') { $category_id = get_cat_ID( get_option( 'woo_audio_category') ); $categories = array($category_id); } else { $categories = array(); } */ $categories = array(); $post_cat_array = $data['post_category']; if (empty($post_cat_array)) { //Do nothing } else { $N = count($post_cat_array); for ($i = 0; $i < $N; $i++) { array_push($categories, $post_cat_array[$i]); } } $tumbl_note['post_category'] = $categories; //Insert the note into the database $post_id = wp_insert_post($tumbl_note); //Add Custom Field Data to the Post if ($data['audio-id'] > 0) { $my_post = array(); $my_post['ID'] = $data['audio-id']; $my_post['post_parent'] = $post_id; //Update the post into the database wp_update_post($my_post); add_post_meta($post_id, $tumblog_custom_fields['audio-url'], $data['audio-upload'], true); } else { add_post_meta($post_id, $tumblog_custom_fields['audio-url'], $data['audio-url'], true); } // DEPRECATED // if (get_option( 'tumblog_woo_tumblog_upgraded') == 'true') { if ($content_method == 'post_format') { set_post_format($post_id, 'audio'); } else { //update posts taxonomies $taxonomy_data = $data['tax_input']; if (!empty($taxonomy_data)) { foreach ($taxonomy_data as $taxonomy => $tags) { $taxonomy_obj = get_taxonomy($taxonomy); if (is_array($tags)) { // array = hierarchical, string = non-hierarchical. $tags = array_filter($tags); } if (current_user_can($taxonomy_obj->cap->assign_terms)) { array_push($tags, $tumblog_items['audio']); } } } else { $tags[0] = $tumblog_items['audio']; } wp_set_post_terms($post_id, $tags, 'tumblog'); } // DEPRECATED // } break; default: break; } }
/** * Helper method for wp_newPost and wp_editPost, containing shared logic. * * @since 3.4.0 * @uses wp_insert_post() * * @param WP_User $user The post author if post_author isn't set in $content_struct. * @param array $content_struct Post data to insert. */ protected function _insert_post($user, $content_struct) { $defaults = array('post_status' => 'draft', 'post_type' => 'post', 'post_author' => 0, 'post_password' => '', 'post_excerpt' => '', 'post_content' => '', 'post_title' => ''); $post_data = wp_parse_args($content_struct, $defaults); $post_type = get_post_type_object($post_data['post_type']); if (!$post_type) { return new IXR_Error(403, __('Invalid post type')); } $update = !empty($post_data['ID']); if ($update) { if (!get_post($post_data['ID'])) { return new IXR_Error(401, __('Invalid post ID.')); } if (!current_user_can($post_type->cap->edit_post, $post_data['ID'])) { return new IXR_Error(401, __('Sorry, you are not allowed to edit this post.')); } if ($post_data['post_type'] != get_post_type($post_data['ID'])) { return new IXR_Error(401, __('The post type may not be changed.')); } } else { if (!current_user_can($post_type->cap->edit_posts)) { return new IXR_Error(401, __('Sorry, you are not allowed to post on this site.')); } } switch ($post_data['post_status']) { case 'draft': case 'pending': break; case 'private': if (!current_user_can($post_type->cap->publish_posts)) { return new IXR_Error(401, __('Sorry, you are not allowed to create private posts in this post type')); } break; case 'publish': case 'future': if (!current_user_can($post_type->cap->publish_posts)) { return new IXR_Error(401, __('Sorry, you are not allowed to publish posts in this post type')); } break; default: $post_data['post_status'] = 'draft'; break; } if (!empty($post_data['post_password']) && !current_user_can($post_type->cap->publish_posts)) { return new IXR_Error(401, __('Sorry, you are not allowed to create password protected posts in this post type')); } $post_data['post_author'] = absint($post_data['post_author']); if (!empty($post_data['post_author']) && $post_data['post_author'] != $user->ID) { if (!current_user_can($post_type->cap->edit_others_posts)) { return new IXR_Error(401, __('You are not allowed to create posts as this user.')); } $author = get_userdata($post_data['post_author']); if (!$author) { return new IXR_Error(404, __('Invalid author ID.')); } } else { $post_data['post_author'] = $user->ID; } if (isset($post_data['comment_status']) && $post_data['comment_status'] != 'open' && $post_data['comment_status'] != 'closed') { unset($post_data['comment_status']); } if (isset($post_data['ping_status']) && $post_data['ping_status'] != 'open' && $post_data['ping_status'] != 'closed') { unset($post_data['ping_status']); } // Do some timestamp voodoo if (!empty($post_data['post_date_gmt'])) { // We know this is supposed to be GMT, so we're going to slap that Z on there by force $dateCreated = rtrim($post_data['post_date_gmt']->getIso(), 'Z') . 'Z'; } elseif (!empty($post_data['post_date'])) { $dateCreated = $post_data['post_date']->getIso(); } if (!empty($dateCreated)) { $post_data['post_date'] = get_date_from_gmt(iso8601_to_datetime($dateCreated)); $post_data['post_date_gmt'] = iso8601_to_datetime($dateCreated, 'GMT'); } if (!isset($post_data['ID'])) { $post_data['ID'] = get_default_post_to_edit($post_data['post_type'], true)->ID; } $post_ID = $post_data['ID']; if ($post_data['post_type'] == 'post') { // Private and password-protected posts cannot be stickied. if ($post_data['post_status'] == 'private' || !empty($post_data['post_password'])) { // Error if the client tried to stick the post, otherwise, silently unstick. if (!empty($post_data['sticky'])) { return new IXR_Error(401, __('Sorry, you cannot stick a private post.')); } if ($update) { unstick_post($post_ID); } } elseif (isset($post_data['sticky'])) { if (!current_user_can($post_type->cap->edit_others_posts)) { return new IXR_Error(401, __('Sorry, you are not allowed to stick this post.')); } if ($post_data['sticky']) { stick_post($post_ID); } else { unstick_post($post_ID); } } } if (isset($post_data['post_thumbnail'])) { // empty value deletes, non-empty value adds/updates if (!$post_data['post_thumbnail']) { delete_post_thumbnail($post_ID); } elseif (!set_post_thumbnail($post_ID, $post_data['post_thumbnail'])) { return new IXR_Error(404, __('Invalid attachment ID.')); } unset($content_struct['post_thumbnail']); } if (isset($post_data['custom_fields'])) { $this->set_custom_fields($post_ID, $post_data['custom_fields']); } if (isset($post_data['terms']) || isset($post_data['terms_names'])) { $post_type_taxonomies = get_object_taxonomies($post_data['post_type'], 'objects'); // accumulate term IDs from terms and terms_names $terms = array(); // first validate the terms specified by ID if (isset($post_data['terms']) && is_array($post_data['terms'])) { $taxonomies = array_keys($post_data['terms']); // validating term ids foreach ($taxonomies as $taxonomy) { if (!array_key_exists($taxonomy, $post_type_taxonomies)) { return new IXR_Error(401, __('Sorry, one of the given taxonomies is not supported by the post type.')); } if (!current_user_can($post_type_taxonomies[$taxonomy]->cap->assign_terms)) { return new IXR_Error(401, __('Sorry, you are not allowed to assign a term to one of the given taxonomies.')); } $term_ids = $post_data['terms'][$taxonomy]; foreach ($term_ids as $term_id) { $term = get_term_by('id', $term_id, $taxonomy); if (!$term) { return new IXR_Error(403, __('Invalid term ID')); } $terms[$taxonomy][] = (int) $term_id; } } } // now validate terms specified by name if (isset($post_data['terms_names']) && is_array($post_data['terms_names'])) { $taxonomies = array_keys($post_data['terms_names']); foreach ($taxonomies as $taxonomy) { if (!array_key_exists($taxonomy, $post_type_taxonomies)) { return new IXR_Error(401, __('Sorry, one of the given taxonomies is not supported by the post type.')); } if (!current_user_can($post_type_taxonomies[$taxonomy]->cap->assign_terms)) { return new IXR_Error(401, __('Sorry, you are not allowed to assign a term to one of the given taxonomies.')); } // for hierarchical taxonomies, we can't assign a term when multiple terms in the hierarchy share the same name $ambiguous_terms = array(); if (is_taxonomy_hierarchical($taxonomy)) { $tax_term_names = get_terms($taxonomy, array('fields' => 'names', 'hide_empty' => false)); // count the number of terms with the same name $tax_term_names_count = array_count_values($tax_term_names); // filter out non-ambiguous term names $ambiguous_tax_term_counts = array_filter($tax_term_names_count, array($this, '_is_greater_than_one')); $ambiguous_terms = array_keys($ambiguous_tax_term_counts); } $term_names = $post_data['terms_names'][$taxonomy]; foreach ($term_names as $term_name) { if (in_array($term_name, $ambiguous_terms)) { return new IXR_Error(401, __('Ambiguous term name used in a hierarchical taxonomy. Please use term ID instead.')); } $term = get_term_by('name', $term_name, $taxonomy); if (!$term) { // term doesn't exist, so check that the user is allowed to create new terms if (!current_user_can($post_type_taxonomies[$taxonomy]->cap->edit_terms)) { return new IXR_Error(401, __('Sorry, you are not allowed to add a term to one of the given taxonomies.')); } // create the new term $term_info = wp_insert_term($term_name, $taxonomy); if (is_wp_error($term_info)) { return new IXR_Error(500, $term_info->get_error_message()); } $terms[$taxonomy][] = (int) $term_info['term_id']; } else { $terms[$taxonomy][] = (int) $term->term_id; } } } } $post_data['tax_input'] = $terms; unset($post_data['terms'], $post_data['terms_names']); } else { // do not allow direct submission of 'tax_input', clients must use 'terms' and/or 'terms_names' unset($post_data['tax_input'], $post_data['post_category'], $post_data['tags_input']); } if (isset($post_data['post_format'])) { $format = set_post_format($post_ID, $post_data['post_format']); if (is_wp_error($format)) { return new IXR_Error(500, $format->get_error_message()); } unset($post_data['post_format']); } // Handle enclosures $enclosure = isset($post_data['enclosure']) ? $post_data['enclosure'] : null; $this->add_enclosure_if_new($post_ID, $enclosure); $this->attach_uploads($post_ID, $post_data['post_content']); $post_data = apply_filters('xmlrpc_wp_insert_post_data', $post_data, $content_struct); $post_ID = wp_insert_post($post_data, true); if (is_wp_error($post_ID)) { return new IXR_Error(500, $post_ID->get_error_message()); } if (!$post_ID) { return new IXR_Error(401, __('Sorry, your entry could not be posted. Something wrong happened.')); } return strval($post_ID); }
private function run_wpml_actions($master_post, $trid, $lang, $id, $post_array) { $master_post_id = $master_post->ID; $this->sitepress->set_element_language_details($id, 'post_' . $master_post->post_type, $trid, $lang); $this->sync_duplicate_password($master_post_id, $id); $this->sync_page_template($master_post_id, $id); $this->duplicate_fix_children($master_post_id, $lang); // make sure post name is copied $this->wpdb->update($this->wpdb->posts, array('post_name' => $master_post->post_name), array('ID' => $id)); update_post_meta($id, '_icl_lang_duplicate_of', $master_post->ID); if ($this->sitepress->get_option('sync_post_taxonomies')) { $this->duplicate_taxonomies($master_post_id, $lang); } $this->duplicate_custom_fields($master_post_id, $lang); // Duplicate post format after the taxonomies because post format is stored // as a taxonomy by WP. if ($this->sitepress->get_setting('sync_post_format')) { $_wp_post_format = get_post_format($master_post_id); set_post_format($id, $_wp_post_format); } if ($this->sitepress->get_setting('sync_comments_on_duplicates')) { $this->duplicate_comments($master_post_id, $id); } $status_helper = wpml_get_post_status_helper(); $status_helper->set_status($id, ICL_TM_DUPLICATE); $status_helper->set_update_status($id, false); do_action('icl_make_duplicate', $master_post_id, $lang, $post_array, $id); clean_post_cache($id); return $id; }
function clone_single_post($id) { $p = get_post($id); if ($p == null) { return false; } $newpost = array('post_name' => $p->post_name, 'post_type' => $p->post_type, 'ping_status' => $p->ping_status, 'post_parent' => $p->post_parent, 'menu_order' => $p->menu_order, 'post_password' => $p->post_password, 'post_excerpt' => $p->post_excerpt, 'comment_status' => $p->comment_status, 'post_title' => $p->post_title . __('- copy'), 'post_content' => $p->post_content, 'post_author' => $p->post_author, 'to_ping' => $p->to_ping, 'pinged' => $p->pinged, 'post_content_filtered' => $p->post_content_filtered, 'post_category' => $p->post_category, 'tags_input' => $p->tags_input, 'tax_input' => $p->tax_input, 'page_template' => $p->page_template); $newid = wp_insert_post($newpost); $format = get_post_format($id); set_post_format($newid, $format); return true; }
/** * Insert tweets as posts * * @param array $tweets Array of tweet objects * @return array Array of stats about the insertion */ function ozh_ta_insert_tweets($tweets) { // Flag as importing : this will cut some queries in the process, regarding (ping|track)backs if (!defined('WP_IMPORTING')) { define('WP_IMPORTING', true); } global $ozh_ta; $inserted = $skipped = $tagged = $num_tags = 0; $user = array(); if (ozh_ta_is_debug()) { $num_sql_batch = new ozh_ta_query_count(); } foreach ((array) $tweets as $tweet) { if (ozh_ta_is_debug()) { $num_sql_post = new ozh_ta_query_count(); } // Current tweet $tid = (string) $tweet->id_str; $text = ozh_ta_linkify_tweet($tweet); $date = date('Y-m-d H:i:s', strtotime($tweet->created_at) + 3600 * get_option('gmt_offset')); $source = $tweet->source; $has_hashtags = count($tweet->entities->hashtags) > 0; $reply_to_name = $tweet->in_reply_to_screen_name; $reply_to_tweet = (string) $tweet->in_reply_to_status_id_str; // Info about Twitter user if (!$user) { $user = array('tweet_counts' => $tweet->user->statuses_count, 'followers' => $tweet->user->followers_count, 'following' => $tweet->user->friends_count, 'listed_count' => $tweet->user->listed_count, 'profile_image_url' => $tweet->user->profile_image_url, 'tweeting_since' => date('Y-m-d H:i:s', strtotime($tweet->user->created_at))); } // Check for duplicate posts before inserting global $wpdb; $sql = "SELECT post_id\n\t\t FROM `{$wpdb->postmeta}`\n\t\t\t\tWHERE `meta_key` = 'ozh_ta_id' AND `meta_value` = '{$tid} ' LIMIT 0,1"; // Yeah, trusting api.twitter.com so we don't sanitize the SQL query, yeeeha if (!$wpdb->get_var($sql)) { // Insert tweet as new post $post = array('post_title' => strip_tags($text), 'post_content' => $text, 'post_date' => $date, 'post_category' => array($ozh_ta['post_category']), 'post_status' => 'publish', 'post_author' => $ozh_ta['post_author'], 'guid' => home_url() . '/?tid=' . $tid); // Post format if ('standard' != $ozh_ta['post_format']) { $post['tax_input'] = array('post_format' => array('post-format-' . $ozh_ta['post_format'])); } // Plugins: hack here $post = apply_filters('ozh_ta_insert_tweets_post', $post); $post_id = wp_insert_post($post); // Apply post format when line 294-296 failed process the request if ('standard' != $ozh_ta['post_format']) { set_post_format($post_id, $ozh_ta['post_format']); } // Insert post meta data add_post_meta($post_id, 'ozh_ta_id', $tid); if ($source) { add_post_meta($post_id, 'ozh_ta_source', $source); } if ($reply_to_name) { add_post_meta($post_id, 'ozh_ta_reply_to_name', $reply_to_name); } if ($reply_to_tweet) { add_post_meta($post_id, 'ozh_ta_reply_to_tweet', $reply_to_tweet); } ozh_ta_debug(" Inserted #{$post_id} (tweet id: {$tid}, tweet: " . ozh_ta_trim_long_string($text, 100) . ')'); if (ozh_ta_is_debug()) { ozh_ta_debug(' Import query cost: ' . $num_sql_post->stop()); } // Tag post if applicable if ($has_hashtags && $ozh_ta['add_hash_as_tags'] == 'yes') { $hashtags = ozh_ta_get_hashtags($tweet); $num_tags += count($hashtags); $hashtags = implode(', ', $hashtags); ozh_ta_debug(" Tagging post {$post_id} with " . $hashtags); $tagged++; if (ozh_ta_is_debug()) { $num_sql_tag = new ozh_ta_query_count(); } wp_set_post_tags($post_id, $hashtags); if (ozh_ta_is_debug()) { ozh_ta_debug(' Tagging query cost: ' . $num_sql_tag->stop()); } } $inserted++; } else { // This tweet has already been imported ?! ozh_ta_debug(" Skipping tweet {$tid}, already imported?!"); $skipped++; } } if (ozh_ta_is_debug()) { ozh_ta_debug('Batch import query cost: ' . $num_sql_batch->stop()); } return array('inserted' => $inserted, 'skipped' => $skipped, 'tagged' => $tagged, 'num_tags' => $num_tags, 'user' => $user); }
public function sync_with_translations($post_id, $post_vars = false) { global $wpdb; $term_count_update = new WPML_Update_Term_Count(); $post = get_post($post_id); $translated_ids = $this->post_translation->get_element_translations($post_id, false, true); $post_format = $this->sync_post_format ? get_post_format($post_id) : null; $ping_status = $this->sync_ping_status ? pings_open($post_id) ? 'open' : 'closed' : null; $comment_status = $this->sync_comment_status ? comments_open($post_id) ? 'open' : 'closed' : null; $post_password = $this->sync_password ? $post->post_password : null; $post_status = $this->sync_private_flag && get_post_status($post_id) === 'private' ? 'private' : null; $menu_order = $this->sync_menu_order && !empty($post->menu_order) ? $post->menu_order : null; $page_template = $this->sync_page_template && get_post_type($post_id) === 'page' ? get_page_template_slug($post_id) : null; $post_date = $this->sync_post_date ? $wpdb->get_var($wpdb->prepare("SELECT post_date FROM {$wpdb->posts} WHERE ID=%d LIMIT 1", $post_id)) : null; if ((bool) $post_vars === true) { $this->sync_sticky_flag($this->post_translation->get_element_trid($post_id), $post_vars); } foreach ($translated_ids as $lang_code => $translated_pid) { $this->sync_custom_fields($post_id, $translated_pid); if ($post_format !== null) { set_post_format($translated_pid, $post_format); } if ($post_date !== null) { $post_date_gmt = get_gmt_from_date($post_date); $data = array('post_date' => $post_date, 'post_date_gmt' => $post_date_gmt); $now = gmdate('Y-m-d H:i:59'); if (mysql2date('U', $post_date_gmt, false) > mysql2date('U', $now, false)) { $post_status = 'future'; } else { $post_status = 'publish'; } $data['post_status'] = $post_status; $wpdb->update($wpdb->posts, $data, array('ID' => $translated_pid)); } if ($post_password !== null) { $wpdb->update($wpdb->posts, array('post_password' => $post_password), array('ID' => $translated_pid)); } if ($post_status !== null && !in_array(get_post_status($translated_pid), array('auto-draft', 'draft', 'inherit', 'trash'))) { $wpdb->update($wpdb->posts, array('post_status' => $post_status), array('ID' => $translated_pid)); $term_count_update->update_for_post($translated_pid); } if ($post_status == null && $this->sync_private_flag && get_post_status($translated_pid) == 'private') { $wpdb->update($wpdb->posts, array('post_status' => get_post_status($post_id)), array('ID' => $translated_pid)); $term_count_update->update_for_post($translated_pid); } if ($ping_status !== null) { $wpdb->update($wpdb->posts, array('ping_status' => $ping_status), array('ID' => $translated_pid)); } if ($comment_status !== null) { $wpdb->update($wpdb->posts, array('comment_status' => $comment_status), array('ID' => $translated_pid)); } if ($page_template !== null) { update_post_meta($translated_pid, '_wp_page_template', $page_template); } $this->sync_with_translations($translated_pid); } if ($this->sync_parent) { $this->maybe_fix_translated_parent(get_post_type($post_id)); } if ($menu_order !== null && (bool) $translated_ids !== false) { $wpdb->query("UPDATE {$wpdb->posts}\n\t\t\t\t SET menu_order={$menu_order}\n\t\t\t\t WHERE ID IN (" . wpml_prepare_in($translated_ids, '%d') . ")"); } }
function draft_post() { check_ajax_referer('wpuf_form_add'); @header('Content-Type: application/json; charset=' . get_option('blog_charset')); $form_id = isset($_POST['form_id']) ? intval($_POST['form_id']) : 0; $form_vars = $this->get_input_fields($form_id); $form_settings = wpuf_get_form_settings($form_id); list($post_vars, $taxonomy_vars, $meta_vars) = $form_vars; // echo json_encode( $_POST ); // print_r( $post_vars ); // print_r( $taxonomy_vars ); // print_r( $meta_vars ); $postarr = array('post_type' => $form_settings['post_type'], 'post_status' => 'draft', 'post_author' => get_current_user_id(), 'post_title' => isset($_POST['post_title']) ? trim($_POST['post_title']) : '', 'post_content' => isset($_POST['post_content']) ? trim($_POST['post_content']) : '', 'post_excerpt' => isset($_POST['post_excerpt']) ? trim($_POST['post_excerpt']) : ''); if (isset($_POST['category'])) { $category = $_POST['category']; $postarr['post_category'] = is_array($category) ? $category : array($category); } if (isset($_POST['tags'])) { $postarr['tags_input'] = explode(',', $_POST['tags']); } // if post_id is passed, we update the post if (isset($_POST['post_id'])) { $is_update = true; $postarr['ID'] = $_POST['post_id']; $postarr['comment_status'] = 'open'; } $post_id = wp_insert_post($postarr); if ($post_id) { self::update_post_meta($meta_vars, $post_id); // set the post form_id for later usage update_post_meta($post_id, self::$config_id, $form_id); // save post formats if have any if (isset($form_settings['post_format']) && $form_settings['post_format'] != '0') { if (post_type_supports($form_settings['post_type'], 'post-formats')) { set_post_format($post_id, $form_settings['post_format']); } } // save any custom taxonomies foreach ($taxonomy_vars as $taxonomy) { if (isset($_POST[$taxonomy['name']])) { if (is_object_in_taxonomy($form_settings['post_type'], $taxonomy['name'])) { $tax = $_POST[$taxonomy['name']]; // if it's not an array, make it one if (!is_array($tax)) { $tax = array($tax); } wp_set_post_terms($post_id, $_POST[$taxonomy['name']], $taxonomy['name']); } } } } wpuf_clear_buffer(); echo json_encode(array('post_id' => $post_id, 'action' => $_POST['action'], 'date' => current_time('mysql'), 'post_author' => get_current_user_id(), 'comment_status' => get_option('default_comment_status'), 'url' => add_query_arg('preview', 'true', get_permalink($post_id)))); exit; }
/** * Default post information to use when populating the "Write Post" form. * * @since 2.0.0 * * @param string $post_type A post type string, defaults to 'post'. * @return WP_Post Post object containing all the default post data as attributes */ function get_default_post_to_edit($post_type = 'post', $create_in_db = false) { global $wpdb; $post_title = ''; if (!empty($_REQUEST['post_title'])) { $post_title = esc_html(wp_unslash($_REQUEST['post_title'])); } $post_content = ''; if (!empty($_REQUEST['content'])) { $post_content = esc_html(wp_unslash($_REQUEST['content'])); } $post_excerpt = ''; if (!empty($_REQUEST['excerpt'])) { $post_excerpt = esc_html(wp_unslash($_REQUEST['excerpt'])); } if ($create_in_db) { $post_id = wp_insert_post(array('post_title' => __('Auto Draft'), 'post_type' => $post_type, 'post_status' => 'auto-draft')); $post = get_post($post_id); if (current_theme_supports('post-formats') && post_type_supports($post->post_type, 'post-formats') && get_option('default_post_format')) { set_post_format($post, get_option('default_post_format')); } } else { $post = new stdClass(); $post->ID = 0; $post->post_author = ''; $post->post_date = ''; $post->post_date_gmt = ''; $post->post_password = ''; $post->post_type = $post_type; $post->post_status = 'draft'; $post->to_ping = ''; $post->pinged = ''; $post->comment_status = get_option('default_comment_status'); $post->ping_status = get_option('default_ping_status'); $post->post_pingback = get_option('default_pingback_flag'); $post->post_category = get_option('default_category'); $post->page_template = 'default'; $post->post_parent = 0; $post->menu_order = 0; $post = new WP_Post($post); } $post->post_content = apply_filters('default_content', $post_content, $post); $post->post_title = apply_filters('default_title', $post_title, $post); $post->post_excerpt = apply_filters('default_excerpt', $post_excerpt, $post); $post->post_name = ''; return $post; }
/** * Save the post as draft or published, via AJAX * * @since 4.2 */ public function save() { if (empty($_POST['pressthis-nonce']) || !wp_verify_nonce($_POST['pressthis-nonce'], 'press-this')) { wp_send_json_error(array('errorMessage' => __('Cheatin’ uh?'))); } if (!isset($_POST['post_ID']) || !($post_id = (int) $_POST['post_ID'])) { wp_send_json_error(array('errorMessage' => __('Missing post ID.'))); } if (!current_user_can('edit_post', $post_id)) { wp_send_json_error(array('errorMessage' => __('Cheatin’ uh?'))); } $post = array('ID' => $post_id, 'post_title' => !empty($_POST['title']) ? sanitize_text_field(trim($_POST['title'])) : '', 'post_content' => !empty($_POST['pressthis']) ? trim($_POST['pressthis']) : '', 'post_type' => 'post', 'post_status' => 'draft', 'post_format' => !empty($_POST['post_format']) ? $_POST['post_format'] : 0, 'tax_input' => !empty($_POST['tax_input']) ? $_POST['tax_input'] : array(), 'post_category' => !empty($_POST['post_category']) ? $_POST['post_category'] : array()); if (!empty($_POST['action']) && 'press_this_publish_post' === $_POST['action']) { if (current_user_can('publish_posts')) { $post['post_status'] = 'publish'; } else { $post['post_status'] = 'pending'; } } $new_content = $this->side_load_images($post_id, $post['post_content']); if (!is_wp_error($new_content)) { $post['post_content'] = $new_content; } $updated = wp_update_post($post, true); if (is_wp_error($updated) || intval($updated) < 1) { wp_send_json_error(array('errorMessage' => __('Error while saving the post. Please try again later.'))); } else { if (isset($post['post_format'])) { if (current_theme_supports('post-formats', $post['post_format'])) { set_post_format($post_id, $post['post_format']); } elseif ($post['post_format']) { set_post_format($post_id, false); } } if ('publish' === get_post_status($post_id)) { /** * press_this_publish_redirect: URL returned to PT on publish sucess, defaults to post permalink. * * @since 4.2 * * @param int $post_id * * @return string URL */ $redirect = apply_filters('press_this_publish_redirect', get_post_permalink($post_id), $post_id); } else { /** * press_this_draft_redirect: URL returned to PT on draft success, defaults to editing the post. * * @since 4.2 * * @param int $post_id * * @return string URL */ $redirect = apply_filters('press_this_draft_redirect', get_edit_post_link($post_id, 'raw'), $post_id); } wp_send_json_success(array('redirect' => $redirect)); } }
/** * Insert a new imported post from facebook * * @param object $fb_post * @param int $group_id * @return int|WP_Error */ function insert_post($fb_post, $group_id) { // bail out if the post already exists if ($post_id = $this->is_post_exists($fb_post->actions[0]->link)) { return $post_id; } $option = get_option('fbgr2wp_settings', array('post_status' => 'publish', 'comment_status' => 'open')); $postarr = array('post_type' => $this->post_type, 'post_status' => $option['post_status'], 'comment_status' => isset($option['comment_status']) ? $option['comment_status'] : 'open', 'ping_status' => isset($option['comment_status']) ? $option['comment_status'] : 'open', 'post_author' => 1, 'post_date' => gmdate('Y-m-d H:i:s', strtotime($fb_post->created_time) + get_option('gmt_offset') * HOUR_IN_SECONDS), 'guid' => $fb_post->actions[0]->link); $meta = array('_fb_author_id' => $fb_post->from->id, '_fb_author_name' => $fb_post->from->name, '_fb_link' => $fb_post->actions[0]->link, '_fb_group_id' => $group_id, '_fb_post_id' => $fb_post->id); switch ($fb_post->type) { case 'status': $postarr['post_title'] = wp_trim_words(strip_tags($fb_post->message), 10, '...'); $postarr['post_content'] = $fb_post->message; break; case 'photo': if (!isset($fb_post->message)) { $postarr['post_title'] = wp_trim_words(strip_tags($fb_post->story), 10, '...'); $postarr['post_content'] = sprintf('<p>%1$s</p> <div class="image-wrap"><img src="%2$s" alt="%1$s" /></div>', $fb_post->story, $fb_post->picture); } else { $postarr['post_title'] = wp_trim_words(strip_tags($fb_post->message), 10, '...'); $postarr['post_content'] = sprintf('<p>%1$s</p> <div class="image-wrap"><img src="%2$s" alt="%1$s" /></div>', $fb_post->message, $fb_post->picture); } break; case 'link': parse_str($fb_post->picture, $parsed_link); $postarr['post_title'] = wp_trim_words(strip_tags($fb_post->message), 10, '...'); $postarr['post_content'] = '<p>' . $fb_post->message . '</p>'; if (!empty($parsed_link['url'])) { $postarr['post_content'] .= sprintf('<a href="%s"><img src="%s"></a>', $fb_post->link, $parsed_link['url']); } else { $postarr['post_content'] .= sprintf('<a href="%s">%s</a>', $fb_post->link, $fb_post->name); } break; default: # code... break; } $post_id = wp_insert_post($postarr); if ($post_id && !is_wp_error($post_id)) { if ($fb_post->type !== 'status') { set_post_format($post_id, $fb_post->type); } foreach ($meta as $key => $value) { update_post_meta($post_id, $key, $value); } } return $post_id; }
function write_post($path, $blog_id, $post_id) { $new = $this->api->ends_with($path, '/new'); $args = $this->query_args(); // unhook publicize, it's hooked again later -- without this, skipping services is impossible if (defined('IS_WPCOM') && IS_WPCOM) { remove_action('save_post', array($GLOBALS['publicize_ui']->publicize, 'async_publicize_post'), 100, 2); add_action('rest_api_inserted_post', array($GLOBALS['publicize_ui']->publicize, 'async_publicize_post')); } if ($new) { $input = $this->input(true); if ('revision' === $input['type']) { if (!isset($input['parent'])) { return new WP_Error('invalid_input', 'Invalid request input', 400); } $input['status'] = 'inherit'; // force inherit for revision type $input['slug'] = $input['parent'] . '-autosave-v1'; } elseif (!isset($input['title']) && !isset($input['content']) && !isset($input['excerpt'])) { return new WP_Error('invalid_input', 'Invalid request input', 400); } // default to post if (empty($input['type'])) { $input['type'] = 'post'; } $post_type = get_post_type_object($input['type']); if (!$this->is_post_type_allowed($input['type'])) { return new WP_Error('unknown_post_type', 'Unknown post type', 404); } if (!empty($input['author'])) { $author_id = $this->parse_and_set_author($input['author'], $input['type']); unset($input['author']); if (is_wp_error($author_id)) { return $author_id; } } if ('publish' === $input['status']) { if (!current_user_can($post_type->cap->publish_posts)) { if (current_user_can($post_type->cap->edit_posts)) { $input['status'] = 'pending'; } else { return new WP_Error('unauthorized', 'User cannot publish posts', 403); } } } else { if (!current_user_can($post_type->cap->edit_posts)) { return new WP_Error('unauthorized', 'User cannot edit posts', 403); } } } else { $input = $this->input(false); if (!is_array($input) || !$input) { return new WP_Error('invalid_input', 'Invalid request input', 400); } $post = get_post($post_id); $_post_type = !empty($input['type']) ? $input['type'] : $post->post_type; $post_type = get_post_type_object($_post_type); if (!$post || is_wp_error($post)) { return new WP_Error('unknown_post', 'Unknown post', 404); } if (!current_user_can('edit_post', $post->ID)) { return new WP_Error('unauthorized', 'User cannot edit post', 403); } if (!empty($input['author'])) { $author_id = $this->parse_and_set_author($input['author'], $_post_type); unset($input['author']); if (is_wp_error($author_id)) { return $author_id; } } if (isset($input['status']) && 'publish' === $input['status'] && 'publish' !== $post->post_status && !current_user_can('publish_post', $post->ID)) { $input['status'] = 'pending'; } $last_status = $post->post_status; $new_status = isset($input['status']) ? $input['status'] : $last_status; // Make sure that drafts get the current date when transitioning to publish if not supplied in the post. $date_in_past = strtotime($post->post_date_gmt) < time(); if ('publish' === $new_status && 'draft' === $last_status && !isset($input['date_gmt']) && $date_in_past) { $input['date_gmt'] = gmdate('Y-m-d H:i:s'); } } // If date is set, $this->input will set date_gmt, date still needs to be adjusted for the blog's offset if (isset($input['date_gmt'])) { $gmt_offset = get_option('gmt_offset'); $time_with_offset = strtotime($input['date_gmt']) + $gmt_offset * HOUR_IN_SECONDS; $input['date'] = date('Y-m-d H:i:s', $time_with_offset); } if (!empty($author_id) && get_current_user_id() != $author_id) { if (!current_user_can($post_type->cap->edit_others_posts)) { return new WP_Error('unauthorized', "User is not allowed to publish others' posts.", 403); } elseif (!user_can($author_id, $post_type->cap->edit_posts)) { return new WP_Error('unauthorized', 'Assigned author cannot publish post.', 403); } } if (!is_post_type_hierarchical($post_type->name) && 'revision' !== $post_type->name) { unset($input['parent']); } $tax_input = array(); foreach (array('categories' => 'category', 'tags' => 'post_tag') as $key => $taxonomy) { if (!isset($input[$key])) { continue; } $tax_input[$taxonomy] = array(); $is_hierarchical = is_taxonomy_hierarchical($taxonomy); if (is_array($input[$key])) { $terms = $input[$key]; } else { $terms = explode(',', $input[$key]); } foreach ($terms as $term) { /** * `curl --data 'category[]=123'` should be interpreted as a category ID, * not a category whose name is '123'. * * Consequence: To add a category/tag whose name is '123', the client must * first look up its ID. */ if (ctype_digit($term)) { $term = (int) $term; } $term_info = term_exists($term, $taxonomy); if (!$term_info) { // A term ID that doesn't already exist. Ignore it: we don't know what name to give it. if (is_int($term)) { continue; } // only add a new tag/cat if the user has access to $tax = get_taxonomy($taxonomy); if (!current_user_can($tax->cap->edit_terms)) { continue; } $term_info = wp_insert_term($term, $taxonomy); } if (!is_wp_error($term_info)) { if ($is_hierarchical) { // Categories must be added by ID $tax_input[$taxonomy][] = (int) $term_info['term_id']; } else { // Tags must be added by name if (is_int($term)) { $term = get_term($term, $taxonomy); $tax_input[$taxonomy][] = $term->name; } else { $tax_input[$taxonomy][] = $term; } } } } } if (isset($input['categories']) && empty($tax_input['category']) && 'revision' !== $post_type->name) { $tax_input['category'][] = get_option('default_category'); } unset($input['tags'], $input['categories']); $insert = array(); if (!empty($input['slug'])) { $insert['post_name'] = $input['slug']; unset($input['slug']); } if (isset($input['comments_open'])) { $insert['comment_status'] = true === $input['comments_open'] ? 'open' : 'closed'; } if (isset($input['pings_open'])) { $insert['ping_status'] = true === $input['pings_open'] ? 'open' : 'closed'; } unset($input['comments_open'], $input['pings_open']); if (isset($input['menu_order'])) { $insert['menu_order'] = $input['menu_order']; unset($input['menu_order']); } $publicize = isset($input['publicize']) ? $input['publicize'] : null; unset($input['publicize']); $publicize_custom_message = isset($input['publicize_message']) ? $input['publicize_message'] : null; unset($input['publicize_message']); if (isset($input['featured_image'])) { $featured_image = trim($input['featured_image']); $delete_featured_image = empty($featured_image); unset($input['featured_image']); } $metadata = isset($input['metadata']) ? $input['metadata'] : null; unset($input['metadata']); $likes = isset($input['likes_enabled']) ? $input['likes_enabled'] : null; unset($input['likes_enabled']); $sharing = isset($input['sharing_enabled']) ? $input['sharing_enabled'] : null; unset($input['sharing_enabled']); $sticky = isset($input['sticky']) ? $input['sticky'] : null; unset($input['sticky']); foreach ($input as $key => $value) { $insert["post_{$key}"] = $value; } if (!empty($author_id)) { $insert['post_author'] = absint($author_id); } if (!empty($tax_input)) { $insert['tax_input'] = $tax_input; } $has_media = isset($input['media']) && $input['media'] ? count($input['media']) : false; $has_media_by_url = isset($input['media_urls']) && $input['media_urls'] ? count($input['media_urls']) : false; if ($new) { if (isset($input['content']) && !has_shortcode($input['content'], 'gallery') && ($has_media || $has_media_by_url)) { switch ($has_media + $has_media_by_url) { case 0: // No images - do nothing. break; case 1: // 1 image - make it big $insert['post_content'] = $input['content'] = "[gallery size=full columns=1]\n\n" . $input['content']; break; default: // Several images - 3 column gallery $insert['post_content'] = $input['content'] = "[gallery]\n\n" . $input['content']; break; } } $post_id = wp_insert_post(add_magic_quotes($insert), true); } else { $insert['ID'] = $post->ID; // wp_update_post ignores date unless edit_date is set // See: http://codex.wordpress.org/Function_Reference/wp_update_post#Scheduling_posts // See: https://core.trac.wordpress.org/browser/tags/3.9.2/src/wp-includes/post.php#L3302 if (isset($input['date_gmt']) || isset($input['date'])) { $insert['edit_date'] = true; } $post_id = wp_update_post((object) $insert); } if (!$post_id || is_wp_error($post_id)) { return $post_id; } // make sure this post actually exists and is not an error of some kind (ie, trying to load media in the posts endpoint) $post_check = $this->get_post_by('ID', $post_id, $args['context']); if (is_wp_error($post_check)) { return $post_check; } if ($has_media) { $this->api->trap_wp_die('upload_error'); foreach ($input['media'] as $media_item) { $_FILES['.api.media.item.'] = $media_item; // check for WP_Error if we ever actually need $media_id $media_id = media_handle_upload('.api.media.item.', $post_id); } $this->api->trap_wp_die(null); unset($_FILES['.api.media.item.']); } if ($has_media_by_url) { foreach ($input['media_urls'] as $url) { $this->handle_media_sideload($url, $post_id); } } // Set like status for the post /** This filter is documented in modules/likes.php */ $sitewide_likes_enabled = (bool) apply_filters('wpl_is_enabled_sitewide', !get_option('disabled_likes')); if ($new) { if ($sitewide_likes_enabled) { if (false === $likes) { update_post_meta($post_id, 'switch_like_status', 1); } else { delete_post_meta($post_id, 'switch_like_status'); } } else { if ($likes) { update_post_meta($post_id, 'switch_like_status', 1); } else { delete_post_meta($post_id, 'switch_like_status'); } } } else { if (isset($likes)) { if ($sitewide_likes_enabled) { if (false === $likes) { update_post_meta($post_id, 'switch_like_status', 1); } else { delete_post_meta($post_id, 'switch_like_status'); } } else { if (true === $likes) { update_post_meta($post_id, 'switch_like_status', 1); } else { delete_post_meta($post_id, 'switch_like_status'); } } } } // Set sharing status of the post if ($new) { $sharing_enabled = isset($sharing) ? (bool) $sharing : true; if (false === $sharing_enabled) { update_post_meta($post_id, 'sharing_disabled', 1); } } else { if (isset($sharing) && true === $sharing) { delete_post_meta($post_id, 'sharing_disabled'); } else { if (isset($sharing) && false == $sharing) { update_post_meta($post_id, 'sharing_disabled', 1); } } } if (isset($sticky)) { if (true === $sticky) { stick_post($post_id); } else { unstick_post($post_id); } } // WPCOM Specific (Jetpack's will get bumped elsewhere // Tracks how many posts are published and sets meta // so we can track some other cool stats (like likes & comments on posts published) if (defined('IS_WPCOM') && IS_WPCOM) { if ($new && 'publish' == $input['status'] || !$new && isset($last_status) && 'publish' != $last_status && isset($new_status) && 'publish' == $new_status) { do_action('jetpack_bump_stats_extras', 'api-insights-posts', $this->api->token_details['client_id']); update_post_meta($post_id, '_rest_api_published', 1); update_post_meta($post_id, '_rest_api_client_id', $this->api->token_details['client_id']); } } // We ask the user/dev to pass Publicize services he/she wants activated for the post, but Publicize expects us // to instead flag the ones we don't want to be skipped. proceed with said logic. // any posts coming from Path (client ID 25952) should also not publicize if ($publicize === false || isset($this->api->token_details['client_id']) && 25952 == $this->api->token_details['client_id']) { // No publicize at all, skip all by ID foreach ($GLOBALS['publicize_ui']->publicize->get_services('all') as $name => $service) { delete_post_meta($post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $name); $service_connections = $GLOBALS['publicize_ui']->publicize->get_connections($name); if (!$service_connections) { continue; } foreach ($service_connections as $service_connection) { update_post_meta($post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id, 1); } } } else { if (is_array($publicize) && count($publicize) > 0) { foreach ($GLOBALS['publicize_ui']->publicize->get_services('all') as $name => $service) { /* * We support both indexed and associative arrays: * * indexed are to pass entire services * * associative are to pass specific connections per service * * We do support mixed arrays: mixed integer and string keys (see 3rd example below). * * EG: array( 'twitter', 'facebook') will only publicize to those, ignoring the other available services * Form data: publicize[]=twitter&publicize[]=facebook * EG: array( 'twitter' => '(int) $pub_conn_id_0, (int) $pub_conn_id_3', 'facebook' => (int) $pub_conn_id_7 ) will publicize to two Twitter accounts, and one Facebook connection, of potentially many. * Form data: publicize[twitter]=$pub_conn_id_0,$pub_conn_id_3&publicize[facebook]=$pub_conn_id_7 * EG: array( 'twitter', 'facebook' => '(int) $pub_conn_id_0, (int) $pub_conn_id_3' ) will publicize to all available Twitter accounts, but only 2 of potentially many Facebook connections * Form data: publicize[]=twitter&publicize[facebook]=$pub_conn_id_0,$pub_conn_id_3 */ // Delete any stale SKIP value for the service by name. We'll add it back by ID. delete_post_meta($post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $name); // Get the user's connections $service_connections = $GLOBALS['publicize_ui']->publicize->get_connections($name); // if the user doesn't have any connections for this service, move on if (!$service_connections) { continue; } if (!in_array($name, $publicize) && !array_key_exists($name, $publicize)) { // Skip the whole service by adding each connection ID foreach ($service_connections as $service_connection) { update_post_meta($post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id, 1); } } else { if (!empty($publicize[$name])) { // Seems we're being asked to only push to [a] specific connection[s]. // Explode the list on commas, which will also support a single passed ID $requested_connections = explode(',', preg_replace('/[\\s]*/', '', $publicize[$name])); // Flag the connections we can't match with the requested list to be skipped. foreach ($service_connections as $service_connection) { if (!in_array($service_connection->meta['connection_data']->id, $requested_connections)) { update_post_meta($post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id, 1); } else { delete_post_meta($post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id); } } } else { // delete all SKIP values; it's okay to publish to all connected IDs for this service foreach ($service_connections as $service_connection) { delete_post_meta($post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id); } } } } } } if (!is_null($publicize_custom_message)) { if (empty($publicize_custom_message)) { delete_post_meta($post_id, $GLOBALS['publicize_ui']->publicize->POST_MESS); } else { update_post_meta($post_id, $GLOBALS['publicize_ui']->publicize->POST_MESS, trim($publicize_custom_message)); } } if (!empty($insert['post_format'])) { if ('default' !== strtolower($insert['post_format'])) { set_post_format($post_id, $insert['post_format']); } else { set_post_format($post_id, get_option('default_post_format')); } } if (isset($featured_image)) { $this->parse_and_set_featured_image($post_id, $delete_featured_image, $featured_image); } if (!empty($metadata)) { foreach ((array) $metadata as $meta) { $meta = (object) $meta; $existing_meta_item = new stdClass(); if (empty($meta->operation)) { $meta->operation = 'update'; } if (!empty($meta->value)) { if ('true' == $meta->value) { $meta->value = true; } if ('false' == $meta->value) { $meta->value = false; } } if (!empty($meta->id)) { $meta->id = absint($meta->id); $existing_meta_item = get_metadata_by_mid('post', $meta->id); } $unslashed_meta_key = wp_unslash($meta->key); // should match what the final key will be $meta->key = wp_slash($meta->key); $unslashed_existing_meta_key = wp_unslash($existing_meta_item->meta_key); $existing_meta_item->meta_key = wp_slash($existing_meta_item->meta_key); // make sure that the meta id passed matches the existing meta key if (!empty($meta->id) && !empty($meta->key)) { $meta_by_id = get_metadata_by_mid('post', $meta->id); if ($meta_by_id->meta_key !== $meta->key) { continue; // skip this meta } } switch ($meta->operation) { case 'delete': if (!empty($meta->id) && !empty($existing_meta_item->meta_key) && current_user_can('delete_post_meta', $post_id, $unslashed_existing_meta_key)) { delete_metadata_by_mid('post', $meta->id); } elseif (!empty($meta->key) && !empty($meta->previous_value) && current_user_can('delete_post_meta', $post_id, $unslashed_meta_key)) { delete_post_meta($post_id, $meta->key, $meta->previous_value); } elseif (!empty($meta->key) && current_user_can('delete_post_meta', $post_id, $unslashed_meta_key)) { delete_post_meta($post_id, $meta->key); } break; case 'add': if (!empty($meta->id) || !empty($meta->previous_value)) { continue; } elseif (!empty($meta->key) && !empty($meta->value) && current_user_can('add_post_meta', $post_id, $unslashed_meta_key) || $this->is_metadata_public($meta->key)) { add_post_meta($post_id, $meta->key, $meta->value); } break; case 'update': if (!isset($meta->value)) { continue; } elseif (!empty($meta->id) && !empty($existing_meta_item->meta_key) && (current_user_can('edit_post_meta', $post_id, $unslashed_existing_meta_key) || $this->is_metadata_public($meta->key))) { update_metadata_by_mid('post', $meta->id, $meta->value); } elseif (!empty($meta->key) && !empty($meta->previous_value) && (current_user_can('edit_post_meta', $post_id, $unslashed_meta_key) || $this->is_metadata_public($meta->key))) { update_post_meta($post_id, $meta->key, $meta->value, $meta->previous_value); } elseif (!empty($meta->key) && (current_user_can('edit_post_meta', $post_id, $unslashed_meta_key) || $this->is_metadata_public($meta->key))) { update_post_meta($post_id, $meta->key, $meta->value); } break; } } } /** * Fires when a post is created via the REST API. * * @since 2.3.0 * * @param int $post_id Post ID. * @param array $insert Data used to build the post. * @param string $new New post URL suffix. */ do_action('rest_api_inserted_post', $post_id, $insert, $new); $return = $this->get_post_by('ID', $post_id, $args['context']); if (!$return || is_wp_error($return)) { return $return; } if (isset($input['type']) && 'revision' === $input['type']) { $return['preview_nonce'] = wp_create_nonce('post_preview_' . $input['parent']); } if (isset($sticky)) { // workaround for sticky test occasionally failing, maybe a race condition with stick_post() above $return['sticky'] = true === $sticky; } /** This action is documented in json-endpoints/class.wpcom-json-api-site-settings-endpoint.php */ do_action('wpcom_json_api_objects', 'posts'); return $return; }
/** * Hook into the add_attachment action, as this should occur after the image has uploaded and after meta data * about the image has been saved. We previously tried using the filter wp_update_attachment_metadata instead, * but that just doesn't seem like the right choice. * * Pulling out extra EXIF areas now, as we weren't really doing anything extra with that, just relying on the * data that WordPress already uses. May be fun to revisit sometime though to allow for more data from Lightroom, etc. * * @param int $post_id The post ID of the attachment that was just added from an image upload. * * @return mixed Only used when breaking from the script */ public function create_post_from_image($post_id) { if (!wp_attachment_is_image($post_id)) { return; } $new_post_category = array(); // If an image is being uploaded through an existing post, it will have been assigned a post parent if ($parent_post_id = get_post($post_id)->post_parent) { /** * It doesn't make sense to create a new post with a featured image from an image * uploaded to an existing post. By default, we'll return having done nothing if * it is detected that this image already has a post parent. The filter allows a * plugin or theme to make a different decision here. */ if (false === apply_filters('afip_post_parent_continue', false, $post_id, $parent_post_id)) { return; } /** * If this image is being added through an existing post, make sure that it inherits * the category setting from its parent. */ if ($parent_post_categories = get_the_category($parent_post_id)) { foreach ($parent_post_categories as $post_cat) { $new_post_category[] = $post_cat->cat_ID; } } } $afip_options = get_option('afip_options'); $current_user = wp_get_current_user(); /* Allow other functions or themes to change the post date before creation. */ $new_post_date = apply_filters('afip_new_post_date', current_time('mysql'), $post_id); /* Allow other functions or themes to change the post title before creation. */ $new_post_title = apply_filters('afip_new_post_title', get_the_title($post_id), $post_id); /* Allow other functions or themes to change the post categories before creation. */ $new_post_category = apply_filters('afip_new_post_category', $new_post_category, $post_id); /* Allow other functions or themes to change the post content before creation. */ $new_post_content = apply_filters('afip_new_post_content', '', $post_id); // Provide a filter to bail before post creation for certain post IDs. if (false === apply_filters('afip_continue_new_post', true, $post_id)) { return; } // Allow others to hook in and perform an action before a post is created. do_action('afip_pre_create_post', $post_id); $new_post_id = wp_insert_post(array('post_title' => $new_post_title, 'post_content' => $new_post_content, 'post_status' => $afip_options['default_post_status'], 'post_author' => $current_user->ID, 'post_date' => $new_post_date, 'post_category' => $new_post_category, 'post_type' => $afip_options['default_post_type'])); if (isset($afip_options['default_post_format']) && 'standard' !== $afip_options['default_post_format']) { set_post_format($new_post_id, $afip_options['default_post_format']); } update_post_meta($new_post_id, '_thumbnail_id', $post_id); // Update the original image (attachment) to reflect new status. wp_update_post(array('ID' => $post_id, 'post_parent' => $new_post_id, 'post_status' => 'inherit')); /** * Allow others to hook in and perform an action as each operation is complete. Passes * $new_post_id from the newly created post and $post_id representing the image. */ do_action('afip_created_post', $new_post_id, $post_id); }
function insert_posts() { global $wpdb; $imported = 0; $skipped = 0; foreach ($this->posts as $post) { extract($post); if ($wpdb->get_var($wpdb->prepare("SELECT meta_id FROM {$wpdb->postmeta} WHERE meta_key = 'flickr_id' AND meta_value = %s", $flickr_id)) || ($post_id = post_exists($post_title, $post_content, $post_date))) { // Looks like a duplicate $skipped++; } else { $post_id = wp_insert_post($post); if (is_wp_error($post_id)) { return $post_id; } if (!$post_id) { continue; } // Mark it as an image set_post_format($post_id, 'image'); // Track which Keyring service was used wp_set_object_terms($post_id, self::LABEL, 'keyring_services'); // Store the flickr id add_post_meta($post_id, 'flickr_id', $flickr_id); add_post_meta($post_id, 'flickr_url', $flickr_url); // Update Category and Tags wp_set_post_categories($post_id, $post_category); if (count($tags)) { wp_set_post_terms($post_id, implode(',', $tags)); } // Store geodata if it's available if (!empty($geo)) { add_post_meta($post_id, 'geo_latitude', $geo['lat']); add_post_meta($post_id, 'geo_longitude', $geo['long']); add_post_meta($post_id, 'geo_public', 1); } add_post_meta($post_id, 'raw_import_data', wp_slash(json_encode($flickr_raw))); $this->sideload_media($flickr_img, $post_id, $post, apply_filters('keyring_flickr_importer_image_embed_size', 'large')); $imported++; do_action('keyring_post_imported', $post_id, static::SLUG, $post); } } $this->posts = array(); // Return, so that the handler can output info (or update DB, or whatever) return array('imported' => $imported, 'skipped' => $skipped); }
public static function create_post($form, &$lead) { GFCommon::log_debug('GFFormsModel::create_post(): Starting.'); $has_post_field = false; foreach ($form['fields'] as $field) { $is_hidden = self::is_field_hidden($form, $field, array(), $lead); if (!$is_hidden && in_array($field->type, array('post_category', 'post_title', 'post_content', 'post_excerpt', 'post_tags', 'post_custom_field', 'post_image'))) { $has_post_field = true; break; } } //if this form does not have any post fields, don't create a post if (!$has_post_field) { GFCommon::log_debug("GFFormsModel::create_post(): Stopping. The form doesn't have any post fields."); return $lead; } //processing post fields GFCommon::log_debug('GFFormsModel::create_post(): Getting post fields.'); $post_data = self::get_post_fields($form, $lead); //allowing users to change post fields before post gets created $post_data = gf_apply_filters('gform_post_data', $form['id'], $post_data, $form, $lead); //adding default title if none of the required post fields are in the form (will make sure wp_insert_post() inserts the post) if (empty($post_data['post_title']) && empty($post_data['post_content']) && empty($post_data['post_excerpt'])) { $post_data['post_title'] = self::get_default_post_title(); } // remove original post status and save it for later $post_status = $post_data['post_status']; // replace original post status with 'draft' so other plugins know this post is not fully populated yet $post_data['post_status'] = 'draft'; // inserting post GFCommon::log_debug('GFFormsModel::create_post(): Inserting post via wp_insert_post().'); $post_id = wp_insert_post($post_data); GFCommon::log_debug("GFFormsModel::create_post(): Result from wp_insert_post(): {$post_id}."); //adding form id and entry id hidden custom fields add_post_meta($post_id, '_gform-form-id', $form['id']); add_post_meta($post_id, '_gform-entry-id', $lead['id']); //creating post images GFCommon::log_debug('GFFormsModel::create_post(): Creating post images.'); $post_images = array(); foreach ($post_data['images'] as $image) { $image_meta = array('post_excerpt' => $image['caption'], 'post_content' => $image['description']); //adding title only if it is not empty. It will default to the file name if it is not in the array if (!empty($image['title'])) { $image_meta['post_title'] = $image['title']; } if (!empty($image['url'])) { GFCommon::log_debug('GFFormsModel::create_post(): Adding image: ' . $image['url']); $media_id = self::media_handle_upload($image['url'], $post_id, $image_meta); if ($media_id) { //save media id for post body/title template variable replacement (below) $post_images[$image['field_id']] = $media_id; $lead[$image['field_id']] .= "|:|{$media_id}"; // set featured image $field = RGFormsModel::get_field($form, $image['field_id']); if ($field->postFeaturedImage) { set_post_thumbnail($post_id, $media_id); } } } } //adding custom fields GFCommon::log_debug('GFFormsModel::create_post(): Adding custom fields.'); foreach ($post_data['post_custom_fields'] as $meta_name => $meta_value) { if (!is_array($meta_value)) { $meta_value = array($meta_value); } $meta_index = 0; foreach ($meta_value as $value) { GFCommon::log_debug('GFFormsModel::create_post(): Getting custom field: ' . $meta_name); $custom_field = self::get_custom_field($form, $meta_name, $meta_index); //replacing template variables if template is enabled if ($custom_field && rgget('customFieldTemplateEnabled', $custom_field)) { //replacing post image variables GFCommon::log_debug('GFFormsModel::create_post(): Replacing post image variables.'); $value = GFCommon::replace_variables_post_image($custom_field['customFieldTemplate'], $post_images, $lead); //replacing all other variables $value = GFCommon::replace_variables($value, $form, $lead, false, false, false); // replace conditional shortcodes $value = do_shortcode($value); } switch (RGFormsModel::get_input_type($custom_field)) { case 'list': $value = maybe_unserialize($value); if (is_array($value)) { foreach ($value as $item) { if (is_array($item)) { $item = implode('|', $item); } if (!rgblank($item)) { add_post_meta($post_id, $meta_name, $item); } } } break; case 'multiselect': case 'checkbox': $value = explode(',', $value); if (is_array($value)) { foreach ($value as $item) { if (!rgblank($item)) { // add post meta and replace HTML symbol in $item with real comma add_post_meta($post_id, $meta_name, str_replace(',', ',', $item)); } } } break; case 'date': $value = GFCommon::date_display($value, rgar($custom_field, 'dateFormat')); if (!rgblank($value)) { add_post_meta($post_id, $meta_name, $value); } break; default: if (!rgblank($value)) { add_post_meta($post_id, $meta_name, $value); } break; } $meta_index++; } } $has_content_field = sizeof(self::get_fields_by_type($form, array('post_content'))) > 0; $has_title_field = sizeof(self::get_fields_by_type($form, array('post_title'))) > 0; $post = false; //if a post field was configured with a content or title template, process template if (rgar($form, 'postContentTemplateEnabled') && $has_content_field || rgar($form, 'postTitleTemplateEnabled') && $has_title_field) { GFCommon::log_debug('GFFormsModel::create_post(): Processing template.'); $post = get_post($post_id); if (rgar($form, 'postContentTemplateEnabled') && $has_content_field) { //replacing post image variables $post_content = GFCommon::replace_variables_post_image($form['postContentTemplate'], $post_images, $lead); //replacing all other variables $post_content = GFCommon::replace_variables($post_content, $form, $lead, false, false, false); //updating post content $post->post_content = $post_content; } if (rgar($form, 'postTitleTemplateEnabled') && $has_title_field) { //replacing post image variables $post_title = GFCommon::replace_variables_post_image($form['postTitleTemplate'], $post_images, $lead); //replacing all other variables $post_title = GFCommon::replace_variables($post_title, $form, $lead, false, false, false); // replace conditional shortcodes $post_title = do_shortcode($post_title); //updating post $post->post_title = $post_title; $post->post_name = $post_title; } } // update post status back to original status (if not draft) if ($post_status != 'draft') { $post = is_object($post) ? $post : get_post($post_id); $post->post_status = $post_status; } // if post has been modified since creation, save updates if (is_object($post)) { GFCommon::log_debug('GFFormsModel::create_post(): Updating post.'); wp_update_post($post); } //adding post format if (current_theme_supports('post-formats') && rgar($form, 'postFormat')) { $formats = get_theme_support('post-formats'); $post_format = rgar($form, 'postFormat'); if (is_array($formats)) { $formats = $formats[0]; if (in_array($post_format, $formats)) { set_post_format($post_id, $post_format); } else { if ('0' == $post_format) { set_post_format($post_id, false); } } } } //update post_id field if a post was created $lead['post_id'] = $post_id; GFCommon::log_debug('GFFormsModel::create_post(): Updating entry with post id.'); self::update_lead_property($lead['id'], 'post_id', $post_id); do_action('gform_after_create_post', $post_id); return $post_id; }
public static function create_post($form, &$lead) { $has_post_field = false; foreach ($form["fields"] as $field) { $is_hidden = self::is_field_hidden($form, $field, array(), $lead); if (!$is_hidden && in_array($field["type"], array("post_category", "post_title", "post_content", "post_excerpt", "post_tags", "post_custom_field", "post_image"))) { $has_post_field = true; break; } } //if this form does not have any post fields, don't create a post if (!$has_post_field) { return $lead; } //processing post fields $post_data = self::get_post_fields($form, $lead); //allowing users to change post fields before post gets created $post_data = apply_filters("gform_post_data_{$form["id"]}", apply_filters("gform_post_data", $post_data, $form, $lead), $form, $lead); //adding default title if none of the required post fields are in the form (will make sure wp_insert_post() inserts the post) if (empty($post_data["post_title"]) && empty($post_data["post_content"]) && empty($post_data["post_excerpt"])) { $post_data["post_title"] = self::get_default_post_title(); } //inserting post if (GFCommon::is_bp_active()) { //disable buddy press action so save_post is not called because the post data is not yet complete at this point remove_action("save_post", "bp_blogs_record_post"); } $post_id = wp_insert_post($post_data); //adding form id and entry id hidden custom fields add_post_meta($post_id, "_gform-form-id", $form["id"]); add_post_meta($post_id, "_gform-entry-id", $lead["id"]); //creating post images $post_images = array(); foreach ($post_data["images"] as $image) { $image_meta = array("post_excerpt" => $image["caption"], "post_content" => $image["description"]); //adding title only if it is not empty. It will default to the file name if it is not in the array if (!empty($image["title"])) { $image_meta["post_title"] = $image["title"]; } if (!empty($image["url"])) { $media_id = self::media_handle_upload($image["url"], $post_id, $image_meta); if ($media_id) { //save media id for post body/title template variable replacement (below) $post_images[$image["field_id"]] = $media_id; $lead[$image["field_id"]] .= "|:|{$media_id}"; // set featured image $field = RGFormsModel::get_field($form, $image["field_id"]); if (rgar($field, 'postFeaturedImage')) { set_post_thumbnail($post_id, $media_id); } } } } //adding custom fields foreach ($post_data["post_custom_fields"] as $meta_name => $meta_value) { if (!is_array($meta_value)) { $meta_value = array($meta_value); } $meta_index = 0; foreach ($meta_value as $value) { $custom_field = self::get_custom_field($form, $meta_name, $meta_index); //replacing template variables if template is enabled if ($custom_field && rgget("customFieldTemplateEnabled", $custom_field)) { //replacing post image variables $value = GFCommon::replace_variables_post_image($custom_field["customFieldTemplate"], $post_images, $lead); //replacing all other variables $value = GFCommon::replace_variables($value, $form, $lead, false, false, false); // replace conditional shortcodes $value = do_shortcode($value); } switch (RGFormsModel::get_input_type($custom_field)) { case "list": $value = maybe_unserialize($value); if (is_array($value)) { foreach ($value as $item) { if (is_array($item)) { $item = implode("|", $item); } if (!rgblank($item)) { add_post_meta($post_id, $meta_name, $item); } } } break; case "multiselect": case "checkbox": $value = explode(",", $value); if (is_array($value)) { foreach ($value as $item) { if (!rgblank($item)) { add_post_meta($post_id, $meta_name, $item); } } } break; case "date": $value = GFCommon::date_display($value, rgar($custom_field, "dateFormat")); if (!rgblank($value)) { add_post_meta($post_id, $meta_name, $value); } break; default: if (!rgblank($value)) { add_post_meta($post_id, $meta_name, $value); } break; } $meta_index++; } } $has_content_field = sizeof(GFCommon::get_fields_by_type($form, array("post_content"))) > 0; $has_title_field = sizeof(GFCommon::get_fields_by_type($form, array("post_title"))) > 0; //if a post field was configured with a content or title template, process template if (rgar($form, "postContentTemplateEnabled") && $has_content_field || rgar($form, "postTitleTemplateEnabled") && $has_title_field) { $post = get_post($post_id); if ($form["postContentTemplateEnabled"] && $has_content_field) { //replacing post image variables $post_content = GFCommon::replace_variables_post_image($form["postContentTemplate"], $post_images, $lead); //replacing all other variables $post_content = GFCommon::replace_variables($post_content, $form, $lead, false, false, false); //updating post content $post->post_content = $post_content; } if ($form["postTitleTemplateEnabled"] && $has_title_field) { //replacing post image variables $post_title = GFCommon::replace_variables_post_image($form["postTitleTemplate"], $post_images, $lead); //replacing all other variables $post_title = GFCommon::replace_variables($post_title, $form, $lead, false, false, false); // replace conditional shortcodes $post_title = do_shortcode($post_title); //updating post $post->post_title = $post_title; $post->post_name = $post_title; } if (GFCommon::is_bp_active()) { //re-enable buddy press action for save_post since the post data is complete at this point add_action('save_post', 'bp_blogs_record_post', 10, 2); } wp_update_post($post); } //adding post format if (current_theme_supports('post-formats') && rgar($form, 'postFormat')) { $formats = get_theme_support('post-formats'); $post_format = rgar($form, 'postFormat'); if (is_array($formats)) { $formats = $formats[0]; if (in_array($post_format, $formats)) { set_post_format($post_id, $post_format); } else { if ('0' == $post_format) { set_post_format($post_id, false); } } } } //update post_id field if a post was created $lead["post_id"] = $post_id; self::update_lead($lead); return $post_id; }
/** * Edit a post. * * @since 1.5.0 * * @param array $args Method parameters. * @return bool|IXR_Error True on success. */ public function mw_editPost($args) { $this->escape($args); $post_ID = (int) $args[0]; $username = $args[1]; $password = $args[2]; $content_struct = $args[3]; $publish = isset($args[4]) ? $args[4] : 0; if (!($user = $this->login($username, $password))) { return $this->error; } /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */ do_action('xmlrpc_call', 'metaWeblog.editPost'); $postdata = get_post($post_ID, ARRAY_A); // If there is no post data for the give post id, stop // now and return an error. Other wise a new post will be // created (which was the old behavior). if (!$postdata || empty($postdata['ID'])) { return new IXR_Error(404, __('Invalid post ID.')); } if (!current_user_can('edit_post', $post_ID)) { return new IXR_Error(401, __('Sorry, you do not have the right to edit this post.')); } // Use wp.editPost to edit post types other than post and page. if (!in_array($postdata['post_type'], array('post', 'page'))) { return new IXR_Error(401, __('Invalid post type')); } // Thwart attempt to change the post type. if (!empty($content_struct['post_type']) && $content_struct['post_type'] != $postdata['post_type']) { return new IXR_Error(401, __('The post type may not be changed.')); } // Check for a valid post format if one was given if (isset($content_struct['wp_post_format'])) { $content_struct['wp_post_format'] = sanitize_key($content_struct['wp_post_format']); if (!array_key_exists($content_struct['wp_post_format'], get_post_format_strings())) { return new IXR_Error(404, __('Invalid post format')); } } $this->escape($postdata); $ID = $postdata['ID']; $post_content = $postdata['post_content']; $post_title = $postdata['post_title']; $post_excerpt = $postdata['post_excerpt']; $post_password = $postdata['post_password']; $post_parent = $postdata['post_parent']; $post_type = $postdata['post_type']; $menu_order = $postdata['menu_order']; // Let WordPress manage slug if none was provided. $post_name = ""; $post_name = $postdata['post_name']; if (isset($content_struct['wp_slug'])) { $post_name = $content_struct['wp_slug']; } // Only use a password if one was given. if (isset($content_struct['wp_password'])) { $post_password = $content_struct['wp_password']; } // Only set a post parent if one was given. if (isset($content_struct['wp_page_parent_id'])) { $post_parent = $content_struct['wp_page_parent_id']; } // Only set the menu_order if it was given. if (isset($content_struct['wp_page_order'])) { $menu_order = $content_struct['wp_page_order']; } $page_template = null; if (!empty($content_struct['wp_page_template']) && 'page' == $post_type) { $page_template = $content_struct['wp_page_template']; } $post_author = $postdata['post_author']; // Only set the post_author if one is set. if (isset($content_struct['wp_author_id']) && $user->ID != $content_struct['wp_author_id']) { switch ($post_type) { case 'post': if (!current_user_can('edit_others_posts')) { return new IXR_Error(401, __('You are not allowed to change the post author as this user.')); } break; case 'page': if (!current_user_can('edit_others_pages')) { return new IXR_Error(401, __('You are not allowed to change the page author as this user.')); } break; default: return new IXR_Error(401, __('Invalid post type')); break; } $post_author = $content_struct['wp_author_id']; } if (isset($content_struct['mt_allow_comments'])) { if (!is_numeric($content_struct['mt_allow_comments'])) { switch ($content_struct['mt_allow_comments']) { case 'closed': $comment_status = 'closed'; break; case 'open': $comment_status = 'open'; break; default: $comment_status = get_option('default_comment_status'); break; } } else { switch ((int) $content_struct['mt_allow_comments']) { case 0: case 2: $comment_status = 'closed'; break; case 1: $comment_status = 'open'; break; default: $comment_status = get_option('default_comment_status'); break; } } } if (isset($content_struct['mt_allow_pings'])) { if (!is_numeric($content_struct['mt_allow_pings'])) { switch ($content_struct['mt_allow_pings']) { case 'closed': $ping_status = 'closed'; break; case 'open': $ping_status = 'open'; break; default: $ping_status = get_option('default_ping_status'); break; } } else { switch ((int) $content_struct["mt_allow_pings"]) { case 0: $ping_status = 'closed'; break; case 1: $ping_status = 'open'; break; default: $ping_status = get_option('default_ping_status'); break; } } } if (isset($content_struct['title'])) { $post_title = $content_struct['title']; } if (isset($content_struct['description'])) { $post_content = $content_struct['description']; } $post_category = array(); if (isset($content_struct['categories'])) { $catnames = $content_struct['categories']; if (is_array($catnames)) { foreach ($catnames as $cat) { $post_category[] = get_cat_ID($cat); } } } if (isset($content_struct['mt_excerpt'])) { $post_excerpt = $content_struct['mt_excerpt']; } $post_more = isset($content_struct['mt_text_more']) ? $content_struct['mt_text_more'] : null; $post_status = $publish ? 'publish' : 'draft'; if (isset($content_struct["{$post_type}_status"])) { switch ($content_struct["{$post_type}_status"]) { case 'draft': case 'pending': case 'private': case 'publish': $post_status = $content_struct["{$post_type}_status"]; break; default: $post_status = $publish ? 'publish' : 'draft'; break; } } $tags_input = isset($content_struct['mt_keywords']) ? $content_struct['mt_keywords'] : null; if ('publish' == $post_status) { if ('page' == $post_type && !current_user_can('publish_pages')) { return new IXR_Error(401, __('Sorry, you do not have the right to publish this page.')); } else { if (!current_user_can('publish_posts')) { return new IXR_Error(401, __('Sorry, you do not have the right to publish this post.')); } } } if ($post_more) { $post_content = $post_content . "<!--more-->" . $post_more; } $to_ping = null; if (isset($content_struct['mt_tb_ping_urls'])) { $to_ping = $content_struct['mt_tb_ping_urls']; if (is_array($to_ping)) { $to_ping = implode(' ', $to_ping); } } // Do some timestamp voodoo if (!empty($content_struct['date_created_gmt'])) { // We know this is supposed to be GMT, so we're going to slap that Z on there by force $dateCreated = rtrim($content_struct['date_created_gmt']->getIso(), 'Z') . 'Z'; } elseif (!empty($content_struct['dateCreated'])) { $dateCreated = $content_struct['dateCreated']->getIso(); } if (!empty($dateCreated)) { $post_date = get_date_from_gmt(iso8601_to_datetime($dateCreated)); $post_date_gmt = iso8601_to_datetime($dateCreated, 'GMT'); } else { $post_date = $postdata['post_date']; $post_date_gmt = $postdata['post_date_gmt']; } // We've got all the data -- post it: $newpost = compact('ID', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt', 'comment_status', 'ping_status', 'post_date', 'post_date_gmt', 'to_ping', 'post_name', 'post_password', 'post_parent', 'menu_order', 'post_author', 'tags_input', 'page_template'); $result = wp_update_post($newpost, true); if (is_wp_error($result)) { return new IXR_Error(500, $result->get_error_message()); } if (!$result) { return new IXR_Error(500, __('Sorry, your entry could not be edited. Something wrong happened.')); } // Only posts can be sticky if ($post_type == 'post' && isset($content_struct['sticky'])) { if ($content_struct['sticky'] == true) { stick_post($post_ID); } elseif ($content_struct['sticky'] == false) { unstick_post($post_ID); } } if (isset($content_struct['custom_fields'])) { $this->set_custom_fields($post_ID, $content_struct['custom_fields']); } if (isset($content_struct['wp_post_thumbnail'])) { // empty value deletes, non-empty value adds/updates if (empty($content_struct['wp_post_thumbnail'])) { delete_post_thumbnail($post_ID); } else { if (set_post_thumbnail($post_ID, $content_struct['wp_post_thumbnail']) === false) { return new IXR_Error(404, __('Invalid attachment ID.')); } } unset($content_struct['wp_post_thumbnail']); } // Handle enclosures $thisEnclosure = isset($content_struct['enclosure']) ? $content_struct['enclosure'] : null; $this->add_enclosure_if_new($post_ID, $thisEnclosure); $this->attach_uploads($ID, $post_content); // Handle post formats if assigned, validation is handled // earlier in this function if (isset($content_struct['wp_post_format'])) { set_post_format($post_ID, $content_struct['wp_post_format']); } /** * Fires after a post has been successfully updated via the XML-RPC MovableType API. * * @since 3.4.0 * * @param int $post_ID ID of the updated post. * @param array $args An array of arguments to update the post. */ do_action('xmlrpc_call_success_mw_editPost', $post_ID, $args); return true; }
function write_post($path, $blog_id, $post_id) { $new = $this->api->ends_with($path, '/new'); $args = $this->query_args(); // unhook publicize, it's hooked again later -- without this, skipping services is impossible if (defined('IS_WPCOM') && IS_WPCOM) { remove_action('save_post', array($GLOBALS['publicize_ui']->publicize, 'async_publicize_post'), 100, 2); add_action('rest_api_inserted_post', array($GLOBALS['publicize_ui']->publicize, 'async_publicize_post')); } if ($new) { $input = $this->input(true); if ('revision' === $input['type']) { if (!isset($input['parent'])) { return new WP_Error('invalid_input', 'Invalid request input', 400); } $input['status'] = 'inherit'; // force inherit for revision type $input['slug'] = $input['parent'] . '-autosave-v1'; } elseif (!isset($input['title']) && !isset($input['content']) && !isset($input['excerpt'])) { return new WP_Error('invalid_input', 'Invalid request input', 400); } // default to post if (empty($input['type'])) { $input['type'] = 'post'; } $post_type = get_post_type_object($input['type']); if (!$this->is_post_type_allowed($input['type'])) { return new WP_Error('unknown_post_type', 'Unknown post type', 404); } if (!empty($input['author'])) { $author_id = parent::parse_and_set_author($input['author'], $input['type']); unset($input['author']); if (is_wp_error($author_id)) { return $author_id; } } if ('publish' === $input['status']) { if (!current_user_can($post_type->cap->publish_posts)) { if (current_user_can($post_type->cap->edit_posts)) { $input['status'] = 'pending'; } else { return new WP_Error('unauthorized', 'User cannot publish posts', 403); } } } else { if (!current_user_can($post_type->cap->edit_posts)) { return new WP_Error('unauthorized', 'User cannot edit posts', 403); } } } else { $input = $this->input(false); if (!is_array($input) || !$input) { return new WP_Error('invalid_input', 'Invalid request input', 400); } $post = get_post($post_id); $_post_type = !empty($input['type']) ? $input['type'] : $post->post_type; $post_type = get_post_type_object($_post_type); if (!$post || is_wp_error($post)) { return new WP_Error('unknown_post', 'Unknown post', 404); } if (!current_user_can('edit_post', $post->ID)) { return new WP_Error('unauthorized', 'User cannot edit post', 403); } if (!empty($input['author'])) { $author_id = parent::parse_and_set_author($input['author'], $_post_type); unset($input['author']); if (is_wp_error($author_id)) { return $author_id; } } if ('publish' === $input['status'] && 'publish' !== $post->post_status && !current_user_can('publish_post', $post->ID)) { $input['status'] = 'pending'; } $last_status = $post->post_status; $new_status = $input['status']; } // Fix for https://iorequests.wordpress.com/2014/08/13/scheduled-posts-made-in-the/ // See: https://a8c.slack.com/archives/io/p1408047082000273 // If date was set, $this->input will set date_gmt, date still needs to be adjusted for the blog's offset if (isset($input['date_gmt'])) { $gmt_offset = get_option('gmt_offset'); $time_with_offset = strtotime($input['date_gmt']) + $gmt_offset * HOUR_IN_SECONDS; $input['date'] = date('Y-m-d H:i:s', $time_with_offset); } if (!empty($author_id) && get_current_user_id() != $author_id) { if (!current_user_can($post_type->cap->edit_others_posts)) { return new WP_Error('unauthorized', "User is not allowed to publish others' posts.", 403); } elseif (!user_can($author_id, $post_type->cap->edit_posts)) { return new WP_Error('unauthorized', 'Assigned author cannot publish post.', 403); } } if (!is_post_type_hierarchical($post_type->name) && 'revision' !== $post_type->name) { unset($input['parent']); } /* add taxonomies by name */ $tax_input = array(); foreach (array('categories' => 'category', 'tags' => 'post_tag') as $key => $taxonomy) { if (!isset($input[$key])) { continue; } $tax_input[$taxonomy] = array(); $is_hierarchical = is_taxonomy_hierarchical($taxonomy); if (is_array($input[$key])) { $terms = $input[$key]; } else { $terms = explode(',', $input[$key]); } foreach ($terms as $term) { /** * We assume these are names, not IDs, even if they are numeric. * Note: A category named "0" will not work right. * https://core.trac.wordpress.org/ticket/9059 */ $term_info = get_term_by('name', $term, $taxonomy, ARRAY_A); if (!$term_info) { // only add a new tag/cat if the user has access to $tax = get_taxonomy($taxonomy); if (!current_user_can($tax->cap->edit_terms)) { continue; } $term_info = wp_insert_term($term, $taxonomy); } if (!is_wp_error($term_info)) { if ($is_hierarchical) { // Categories must be added by ID $tax_input[$taxonomy][] = (int) $term_info['term_id']; } else { // Tags must be added by name $tax_input[$taxonomy][] = $term; } } } } /* add taxonomies by ID */ foreach (array('categories_by_id' => 'category', 'tags_by_id' => 'post_tag') as $key => $taxonomy) { if (!isset($input[$key])) { continue; } // combine with any previous selections if (!is_array($tax_input[$taxonomy])) { $tax_input[$taxonomy] = array(); } $is_hierarchical = is_taxonomy_hierarchical($taxonomy); if (is_array($input[$key])) { $terms = $input[$key]; } else { $terms = explode(',', $input[$key]); } foreach ($terms as $term) { if (!ctype_digit($term)) { // skip anything that doesn't look like an ID continue; } $term = (int) $term; $term_info = get_term_by('id', $term, $taxonomy, ARRAY_A); if ($term_info && !is_wp_error($term_info)) { if ($is_hierarchical) { // Categories must be added by ID $tax_input[$taxonomy][] = $term; } else { // Tags must be added by name $tax_input[$taxonomy][] = $term_info['name']; } } } } if ((isset($input['categories']) || isset($input['categories_by_id'])) && empty($tax_input['category']) && 'revision' !== $post_type->name) { $tax_input['category'][] = get_option('default_category'); } unset($input['tags'], $input['categories'], $input['tags_by_id'], $input['categories_by_id']); $insert = array(); if (!empty($input['slug'])) { $insert['post_name'] = $input['slug']; unset($input['slug']); } if (isset($input['discussion'])) { $discussion = (array) $input['discussion']; foreach (array('comment', 'ping') as $discussion_type) { $discussion_open = sprintf('%ss_open', $discussion_type); $discussion_status = sprintf('%s_status', $discussion_type); if (isset($discussion[$discussion_open])) { $is_open = WPCOM_JSON_API::is_truthy($discussion[$discussion_open]); $discussion[$discussion_status] = $is_open ? 'open' : 'closed'; } if (in_array($discussion[$discussion_status], array('open', 'closed'))) { $insert[$discussion_status] = $discussion[$discussion_status]; } } } unset($input['discussion']); if (isset($input['menu_order'])) { $insert['menu_order'] = $input['menu_order']; unset($input['menu_order']); } if (isset($input['publicize'])) { $publicize = $input['publicize']; unset($input['publicize']); } if (isset($input['publicize_message'])) { $publicize_custom_message = $input['publicize_message']; unset($input['publicize_message']); } if (isset($input['featured_image'])) { $featured_image = trim($input['featured_image']); $delete_featured_image = empty($featured_image); unset($input['featured_image']); } if (isset($input['metadata'])) { $metadata = $input['metadata']; unset($input['metadata']); } if (isset($input['likes_enabled'])) { $likes = $input['likes_enabled']; unset($input['likes_enabled']); } if (isset($input['sharing_enabled'])) { $sharing = $input['sharing_enabled']; unset($input['sharing_enabled']); } if (isset($input['sticky'])) { $sticky = $input['sticky']; unset($input['sticky']); } foreach ($input as $key => $value) { $insert["post_{$key}"] = $value; } if (!empty($author_id)) { $insert['post_author'] = absint($author_id); } if (!empty($tax_input)) { $insert['tax_input'] = $tax_input; } $has_media = !empty($input['media']) ? count($input['media']) : false; $has_media_by_url = !empty($input['media_urls']) ? count($input['media_urls']) : false; if ($new) { if (false === strpos($input['content'], '[gallery') && ($has_media || $has_media_by_url)) { switch ($has_media + $has_media_by_url) { case 0: // No images - do nothing. break; case 1: // 1 image - make it big $insert['post_content'] = $input['content'] = "[gallery size=full columns=1]\n\n" . $input['content']; break; default: // Several images - 3 column gallery $insert['post_content'] = $input['content'] = "[gallery]\n\n" . $input['content']; break; } } $post_id = wp_insert_post(add_magic_quotes($insert), true); } else { $insert['ID'] = $post->ID; // wp_update_post ignores date unless edit_date is set // See: http://codex.wordpress.org/Function_Reference/wp_update_post#Scheduling_posts // See: https://core.trac.wordpress.org/browser/tags/3.9.2/src/wp-includes/post.php#L3302 if (isset($input['date_gmt']) || isset($input['date'])) { $insert['edit_date'] = true; } $post_id = wp_update_post((object) $insert); } if (!$post_id || is_wp_error($post_id)) { return $post_id; } // make sure this post actually exists and is not an error of some kind (ie, trying to load media in the posts endpoint) $post_check = $this->get_post_by('ID', $post_id, $args['context']); if (is_wp_error($post_check)) { return $post_check; } if ($has_media || $has_media_by_url) { $media_files = !empty($input['media']) ? $input['media'] : array(); $media_urls = !empty($input['media_urls']) ? $input['media_urls'] : array(); $media_attrs = !empty($input['media_attrs']) ? $input['media_attrs'] : array(); $force_parent_id = $post_id; $media_results = $this->handle_media_creation_v1_1($media_files, $media_urls, $media_attrs, $force_parent_id); } // set page template for this post.. if (isset($input['page_template']) && 'page' == $post_type->name) { $page_template = $input['page_template']; $page_templates = wp_get_theme()->get_page_templates(get_post($post_id)); if (empty($page_template) || 'default' == $page_template || isset($page_templates[$page_template])) { update_post_meta($post_id, '_wp_page_template', $page_template); } } // Set like status for the post $sitewide_likes_enabled = (bool) apply_filters('wpl_is_enabled_sitewide', !get_option('disabled_likes')); if ($new) { if ($sitewide_likes_enabled) { if (false === $likes) { update_post_meta($post_id, 'switch_like_status', 1); } else { delete_post_meta($post_id, 'switch_like_status'); } } else { if ($likes) { update_post_meta($post_id, 'switch_like_status', 1); } else { delete_post_meta($post_id, 'switch_like_status'); } } } else { if (isset($likes)) { if ($sitewide_likes_enabled) { if (false === $likes) { update_post_meta($post_id, 'switch_like_status', 1); } else { delete_post_meta($post_id, 'switch_like_status'); } } else { if (true === $likes) { update_post_meta($post_id, 'switch_like_status', 1); } else { delete_post_meta($post_id, 'switch_like_status'); } } } } // Set sharing status of the post if ($new) { $sharing_enabled = isset($sharing) ? (bool) $sharing : true; if (false === $sharing_enabled) { update_post_meta($post_id, 'sharing_disabled', 1); } } else { if (isset($sharing) && true === $sharing) { delete_post_meta($post_id, 'sharing_disabled'); } else { if (isset($sharing) && false == $sharing) { update_post_meta($post_id, 'sharing_disabled', 1); } } } if (true === $sticky) { stick_post($post_id); } else { unstick_post($post_id); } // WPCOM Specific (Jetpack's will get bumped elsewhere // Tracks how many posts are published and sets meta so we can track some other cool stats (like likes & comments on posts published) if ($new && 'publish' == $input['status'] || !$new && isset($last_status) && 'publish' != $last_status && isset($new_status) && 'publish' == $new_status) { if (function_exists('bump_stats_extras')) { bump_stats_extras('api-insights-posts', $this->api->token_details['client_id']); update_post_meta($post_id, '_rest_api_published', 1); update_post_meta($post_id, '_rest_api_client_id', $this->api->token_details['client_id']); } } // We ask the user/dev to pass Publicize services he/she wants activated for the post, but Publicize expects us // to instead flag the ones we don't want to be skipped. proceed with said logic. // any posts coming from Path (client ID 25952) should also not publicize if ($publicize === false || isset($this->api->token_details['client_id']) && 25952 == $this->api->token_details['client_id']) { // No publicize at all, skip all by ID foreach ($GLOBALS['publicize_ui']->publicize->get_services('all') as $name => $service) { delete_post_meta($post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $name); $service_connections = $GLOBALS['publicize_ui']->publicize->get_connections($name); if (!$service_connections) { continue; } foreach ($service_connections as $service_connection) { update_post_meta($post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id, 1); } } } else { if (is_array($publicize) && count($publicize) > 0) { foreach ($GLOBALS['publicize_ui']->publicize->get_services('all') as $name => $service) { /* * We support both indexed and associative arrays: * * indexed are to pass entire services * * associative are to pass specific connections per service * * We do support mixed arrays: mixed integer and string keys (see 3rd example below). * * EG: array( 'twitter', 'facebook') will only publicize to those, ignoring the other available services * Form data: publicize[]=twitter&publicize[]=facebook * EG: array( 'twitter' => '(int) $pub_conn_id_0, (int) $pub_conn_id_3', 'facebook' => (int) $pub_conn_id_7 ) will publicize to two Twitter accounts, and one Facebook connection, of potentially many. * Form data: publicize[twitter]=$pub_conn_id_0,$pub_conn_id_3&publicize[facebook]=$pub_conn_id_7 * EG: array( 'twitter', 'facebook' => '(int) $pub_conn_id_0, (int) $pub_conn_id_3' ) will publicize to all available Twitter accounts, but only 2 of potentially many Facebook connections * Form data: publicize[]=twitter&publicize[facebook]=$pub_conn_id_0,$pub_conn_id_3 */ // Delete any stale SKIP value for the service by name. We'll add it back by ID. delete_post_meta($post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $name); // Get the user's connections $service_connections = $GLOBALS['publicize_ui']->publicize->get_connections($name); // if the user doesn't have any connections for this service, move on if (!$service_connections) { continue; } if (!in_array($name, $publicize) && !array_key_exists($name, $publicize)) { // Skip the whole service by adding each connection ID foreach ($service_connections as $service_connection) { update_post_meta($post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id, 1); } } else { if (!empty($publicize[$name])) { // Seems we're being asked to only push to [a] specific connection[s]. // Explode the list on commas, which will also support a single passed ID $requested_connections = explode(',', preg_replace('/[\\s]*/', '', $publicize[$name])); // Flag the connections we can't match with the requested list to be skipped. foreach ($service_connections as $service_connection) { if (!in_array($service_connection->meta['connection_data']->id, $requested_connections)) { update_post_meta($post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id, 1); } else { delete_post_meta($post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id); } } } else { // delete all SKIP values; it's okay to publish to all connected IDs for this service foreach ($service_connections as $service_connection) { delete_post_meta($post_id, $GLOBALS['publicize_ui']->publicize->POST_SKIP . $service_connection->unique_id); } } } } } } if (!empty($publicize_custom_message)) { update_post_meta($post_id, $GLOBALS['publicize_ui']->publicize->POST_MESS, trim($publicize_custom_message)); } set_post_format($post_id, $insert['post_format']); if (isset($featured_image)) { parent::parse_and_set_featured_image($post_id, $delete_featured_image, $featured_image); } if (!empty($metadata)) { foreach ((array) $metadata as $meta) { $meta = (object) $meta; $existing_meta_item = new stdClass(); if (empty($meta->operation)) { $meta->operation = 'update'; } if (!empty($meta->value)) { if ('true' == $meta->value) { $meta->value = true; } if ('false' == $meta->value) { $meta->value = false; } } if (!empty($meta->id)) { $meta->id = absint($meta->id); $existing_meta_item = get_metadata_by_mid('post', $meta->id); } $unslashed_meta_key = wp_unslash($meta->key); // should match what the final key will be $meta->key = wp_slash($meta->key); $unslashed_existing_meta_key = wp_unslash($existing_meta_item->meta_key); $existing_meta_item->meta_key = wp_slash($existing_meta_item->meta_key); // make sure that the meta id passed matches the existing meta key if (!empty($meta->id) && !empty($meta->key)) { $meta_by_id = get_metadata_by_mid('post', $meta->id); if ($meta_by_id->meta_key !== $meta->key) { continue; // skip this meta } } switch ($meta->operation) { case 'delete': if (!empty($meta->id) && !empty($existing_meta_item->meta_key) && current_user_can('delete_post_meta', $post_id, $unslashed_existing_meta_key)) { delete_metadata_by_mid('post', $meta->id); } elseif (!empty($meta->key) && !empty($meta->previous_value) && current_user_can('delete_post_meta', $post_id, $unslashed_meta_key)) { delete_post_meta($post_id, $meta->key, $meta->previous_value); } elseif (!empty($meta->key) && current_user_can('delete_post_meta', $post_id, $unslashed_meta_key)) { delete_post_meta($post_id, $meta->key); } break; case 'add': if (!empty($meta->id) || !empty($meta->previous_value)) { continue; } elseif (!empty($meta->key) && !empty($meta->value) && current_user_can('add_post_meta', $post_id, $unslashed_meta_key) || $this->is_metadata_public($meta->key)) { add_post_meta($post_id, $meta->key, $meta->value); } break; case 'update': if (!isset($meta->value)) { continue; } elseif (!empty($meta->id) && !empty($existing_meta_item->meta_key) && (current_user_can('edit_post_meta', $post_id, $unslashed_existing_meta_key) || $this->is_metadata_public($meta->key))) { update_metadata_by_mid('post', $meta->id, $meta->value); } elseif (!empty($meta->key) && !empty($meta->previous_value) && (current_user_can('edit_post_meta', $post_id, $unslashed_meta_key) || $this->is_metadata_public($meta->key))) { update_post_meta($post_id, $meta->key, $meta->value, $meta->previous_value); } elseif (!empty($meta->key) && (current_user_can('edit_post_meta', $post_id, $unslashed_meta_key) || $this->is_metadata_public($meta->key))) { update_post_meta($post_id, $meta->key, $meta->value); } break; } } } do_action('rest_api_inserted_post', $post_id, $insert, $new); $return = $this->get_post_by('ID', $post_id, $args['context']); if (!$return || is_wp_error($return)) { return $return; } if (isset($input['type']) && 'revision' === $input['type']) { $return['preview_nonce'] = wp_create_nonce('post_preview_' . $input['parent']); } // workaround for sticky test occasionally failing, maybe a race condition with stick_post() above $return['sticky'] = true === $sticky; if (!empty($media_results['errors'])) { $return['media_errors'] = $media_results['errors']; } do_action('wpcom_json_api_objects', 'posts'); return $return; }