public function upsert_post($post, $silent = false)
 {
     global $wpdb;
     // reject the post if it's not a WP_Post
     if (!$post instanceof WP_Post) {
         return;
     }
     $post = $post->to_array();
     // reject posts without an ID
     if (!isset($post['ID'])) {
         return;
     }
     $now = current_time('mysql');
     $now_gmt = get_gmt_from_date($now);
     $defaults = array('ID' => 0, 'post_author' => '0', 'post_content' => '', 'post_content_filtered' => '', 'post_title' => '', 'post_name' => '', 'post_excerpt' => '', 'post_status' => 'draft', 'post_type' => 'post', 'comment_status' => 'closed', 'comment_count' => '0', 'ping_status' => '', 'post_password' => '', 'to_ping' => '', 'pinged' => '', 'post_parent' => 0, 'menu_order' => 0, 'guid' => '', 'post_date' => $now, 'post_date_gmt' => $now_gmt, 'post_modified' => $now, 'post_modified_gmt' => $now_gmt);
     $post = array_intersect_key($post, $defaults);
     $post = sanitize_post($post, 'db');
     unset($post['filter']);
     $exists = $wpdb->get_var($wpdb->prepare("SELECT EXISTS( SELECT 1 FROM {$wpdb->posts} WHERE ID = %d )", $post['ID']));
     if ($exists) {
         $wpdb->update($wpdb->posts, $post, array('ID' => $post['ID']));
     } else {
         $wpdb->insert($wpdb->posts, $post);
     }
     clean_post_cache($post['ID']);
 }
 /**
  * Reset the post_date field on your posts.
  * A sadly necessary step after you change your timezone in WordPress
  * 
  * @synopsis --post_type=<post-type>
  */
 public function __invoke($args, $assoc_args)
 {
     global $wpdb;
     $query_args = array('post_type' => $assoc_args['post_type'], 'posts_per_page' => -1, 'post_status' => 'publish');
     $query = new WP_Query($query_args);
     if (empty($query->posts)) {
         WP_CLI::error("No posts found");
     }
     WP_CLI::line(sprintf("Updating post_date on %d posts.", count($query->posts)));
     foreach ($query->posts as $key => $post) {
         if (empty($post->post_date_gmt) || "0000-00-00 00:00:00" == $post->post_date_gmt) {
             WP_CLI::line(sprintf("Error: Post %d is missing a publish date.", $post->ID));
             continue;
         }
         $original = $post->post_date;
         $new = get_date_from_gmt($post->post_date_gmt);
         if ($new == $original) {
             WP_CLI::line(sprintf("No Change: Post %d has the correct post_date of %s", $post->ID, $original));
             continue;
         }
         $wpdb->update($wpdb->posts, array('post_date' => $new), array('ID' => $post->ID));
         clean_post_cache($post->ID);
         WP_CLI::line(sprintf("Updated: Post %d changed from %s to %s", $post->ID, $original, $new));
         if ($key && $key % 10 == 0) {
             sleep(1);
         }
     }
     WP_CLI::success("Posts were updated with the correct post_date.");
 }
 /**
  * Handle Bulk Action's request
  *
  */
 public function process_bulk_action()
 {
     global $wpdb;
     try {
         switch ($this->current_action()) {
             case 'unassign':
                 if (empty($_REQUEST['post_ids']) || !is_array($_REQUEST['post_ids'])) {
                     throw new \Exception(sprintf(__('Invalid request: no %s IDs provided.', ud_get_wp_property('domain')), \WPP_F::property_label()));
                 }
                 $post_ids = $_REQUEST['post_ids'];
                 foreach ($post_ids as $post_id) {
                     $post_id = (int) $post_id;
                     if (!$post_id) {
                         throw new \Exception(sprintf(__('Invalid request: incorrect %s IDs provided.', ud_get_wp_property('domain')), \WPP_F::property_label()));
                     }
                     $wpdb->query($wpdb->prepare("\n                  UPDATE {$wpdb->posts}\n                  SET post_parent = '0'\n                  WHERE ID = %d\n                ", $post_id));
                     clean_post_cache($post_id);
                 }
                 $label = count($post_ids) > 1 ? __('Children', ud_get_wp_property('domain')) : __('Child', ud_get_wp_property('domain'));
                 $this->message = sprintf(__('Selected %s have been successfully un-assigned from current %s.', ud_get_wp_property('domain')), $label, \WPP_F::property_label());
                 break;
             default:
                 //** Any custom action can be processed using action hook */
                 do_action('wpp::children_list_table::process_bulk_action', $this->current_action());
                 break;
         }
     } catch (\Exception $e) {
         $this->error = $e->getMessage();
     }
 }
Example #4
0
/**
 * Updates the comment count for the post.
 * Recalculates comment count by excluding specified comment types, eg. report, review.
 *
 * @param int $post_id Post ID
 * @param int $new New comment count
 * @param int $old Previous comment count
 *
 * @return void
 */
function _appthemes_update_comment_count($post_id, $new, $old)
{
    global $wpdb;
    if (!current_theme_supports('app-comment-counts')) {
        return;
    }
    $args_sets = get_theme_support('app-comment-counts');
    $options = array('exclude_type' => array());
    if (!is_array($args_sets)) {
        $args_sets = array();
    }
    foreach ($args_sets as $args_set) {
        foreach ($args_set as $key => $arg) {
            if (!isset($options[$key])) {
                $options[$key] = $arg;
            } elseif (is_array($arg)) {
                $options[$key] = array_merge_recursive((array) $options[$key], $arg);
            }
        }
    }
    $exclude_types = apply_filters('appthemes_ctypes_count_exclude', $options['exclude_type']);
    if (empty($exclude_types) || !is_array($exclude_types)) {
        return;
    }
    $post = get_post($post_id);
    $exclude_types = esc_sql($exclude_types);
    $count = (int) $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$wpdb->comments} WHERE comment_post_ID = %d AND comment_approved = '1' AND comment_type NOT IN ( '" . implode("', '", $exclude_types) . "' )", $post_id));
    $wpdb->update($wpdb->posts, array('comment_count' => $count), array('ID' => $post_id));
    clean_post_cache($post);
}
 public function update(array $post_data_array, $direct_db_update = false)
 {
     if ($direct_db_update) {
         $this->wpdb->update($this->wpdb->posts, $post_data_array, array('ID' => $this->post_id));
         clean_post_cache($this->post_id);
     } else {
         $post_data_array['ID'] = $this->post_id;
         wp_update_post($post_data_array);
     }
 }
 private function removeMenuItems($postid)
 {
     global $wpdb;
     $post_ids = $wpdb->get_col($wpdb->prepare("SELECT ID FROM {$wpdb->posts} WHERE post_parent = %d and post_name like %s", $postid, "gwpm_matrimony_%"));
     if (!empty($post_ids)) {
         foreach ($post_ids as $post_id) {
             wp_delete_post($post_id, true);
             clean_post_cache($post_id);
         }
     }
 }
 /**
  * Register a private post type to store cron events
  */
 public function register_post_type()
 {
     register_post_type(self::POST_TYPE, array('label' => 'Cron Events', 'public' => false, 'rewrite' => false, 'export' => false, 'exclude_from_search' => true));
     // Clear caches for any manually-inserted posts, lest stale caches be used
     if (!empty($this->posts_to_clean)) {
         foreach ($this->posts_to_clean as $index => $post_to_clean) {
             clean_post_cache($post_to_clean);
             unset($this->posts_to_clean[$index]);
         }
     }
 }
 function setUp()
 {
     parent::setUp();
     /* Create and setup a loop for testing */
     $post_ids = $this->factory->post->create_many(10);
     foreach ($post_ids as $post_id) {
         clean_post_cache($post_id);
     }
     $query = new WP_Query(array('post_type' => 'post', 'posts_per_page' => 3));
     $GLOBALS['wp_query'] = $query;
 }
Example #9
0
 function transition_post_status($new, $old, $the_post)
 {
     if ('publish' == $old && 'publish' != $new) {
         // A published post was trashed or something else
         $this->delete_post($the_post->ID);
         return;
     }
     clean_post_cache($the_post->ID);
     // Publish a new post
     if ('publish' != $old && $this->post_is_public($the_post->ID) && ('post' == $the_post->post_type || 'page' == $the_post->post_type)) {
         $this->jetpack->sync->post($the_post->ID);
     }
 }
 public function test_publish_missing_post()
 {
     $post = $this->factory->post->create_and_get(['post_author' => 1, 'post_date' => '2017-01-01 00:00:00']);
     $this->assertSame('future', $post->post_status);
     global $wpdb;
     $wpdb->update($wpdb->posts, ['post_date' => '2000-01-01 10:10:10', 'post_date_gmt' => '2000-01-01 10:10:10', 'post_status' => 'future'], ['ID' => $post->ID]);
     clean_post_cache($post->ID);
     $this->class->wp_missing_schedule_posts();
     $updated_post = get_post($post->ID);
     $this->assertSame('publish', $updated_post->post_status);
     $flag = get_post_meta($updated_post->ID, $this->class->get_plugin_slug(), true);
     $date_published = DateTime::createFromFormat('U', $flag);
     $this->assertInstanceOf('DateTime', $date_published);
 }
 public function test_post_flushing_cache()
 {
     $this->factory->post->create_many(10);
     $first_run = $this->query->query([]);
     $this->assertSame($this->obj->all_post_ids, false);
     $post_id = $this->factory->post->create();
     clean_post_cache($post_id);
     $second_run = $this->query->query([]);
     $this->assertSame($this->obj->all_post_ids, false);
     $this->assertNotEquals($first_run, $second_run);
     $third_run = $this->query->query(['p' => $post_id]);
     $this->assertSame($this->obj->all_post_ids, false);
     $this->assertNotEquals($second_run, $third_run);
 }
Example #12
0
 /**
  * Set it Up
  */
 public function setUp()
 {
     parent::setUp();
     $payment_id = Give_Helper_Payment::create_simple_payment();
     $this->_payment_key = give_get_payment_key($payment_id);
     $this->_payment_id = $payment_id;
     $this->_key = $this->_payment_key;
     $this->_transaction_id = 'FIR3SID3';
     give_set_payment_transaction_id($payment_id, $this->_transaction_id);
     give_insert_payment_note($payment_id, sprintf(esc_html__('PayPal Transaction ID: %s', 'give'), $this->_transaction_id));
     // Make sure we're working off a clean object caching in WP Core.
     // Prevents some payment_meta from not being present.
     clean_post_cache($payment_id);
     update_postmeta_cache(array($payment_id));
 }
Example #13
0
 function setUp()
 {
     /* Load the legacy files before anything else - needed for childtheme_overrides* to work */
     include_legacy_xhtml_files();
     /* Load the thematic files */
     parent::setUp();
     /* Create and setup a loop for testing */
     $post_ids = $this->factory->post->create_many(10);
     foreach ($post_ids as $post_id) {
         clean_post_cache($post_id);
     }
     $query = new WP_Query(array('post_type' => 'post', 'posts_per_page' => 5));
     $GLOBALS['wp_query'] = $query;
     thematic_replace_loops();
 }
 /**
  * Check POST date for convert object on an another custom type.
  *
  * @return void
  * @author Amaury Balmer
  */
 function checkConversion()
 {
     if (isset($_POST['custom-type-convert']) && $_POST['custom-type-convert'] == '1') {
         check_admin_referer('convert-post_type');
         foreach ((array) $_POST['objects'] as $object_id => $new_post_type) {
             // Change the post type
             $object = get_post_to_edit($object_id);
             $object->post_type = $new_post_type;
             wp_update_post((array) $object);
             // Clean object cache
             clean_post_cache($object_id);
         }
         return true;
     }
     return false;
 }
Example #15
0
 /**
  * Save post data
  *
  * @param mixed $value
  * @param \WP_Post $post
  */
 protected function save($value, \WP_Post $post = null)
 {
     switch ($this->field) {
         case 'post_meta':
             update_post_meta($post->ID, $this->name, $value);
             break;
         default:
             $post_id = intval($value);
             // TODO: Reconsider updating post row logic
             /** @var \wpdb $wpdb */
             global $wpdb;
             $wpdb->update($wpdb->posts, ['post_parent' => $post_id], ['ID' => $post->ID], ['%d'], ['%d']);
             clean_post_cache($post);
             break;
     }
 }
 /**
  * @ticket 15665
  */
 public function test_get_page_by_path_priority()
 {
     global $wpdb;
     $attachment = self::factory()->post->create_and_get(array('post_title' => 'some-page', 'post_type' => 'attachment'));
     $page = self::factory()->post->create_and_get(array('post_title' => 'some-page', 'post_type' => 'page'));
     $other_att = self::factory()->post->create_and_get(array('post_title' => 'some-other-page', 'post_type' => 'attachment'));
     $wpdb->update($wpdb->posts, array('post_name' => 'some-page'), array('ID' => $page->ID));
     clean_post_cache($page->ID);
     $page = get_post($page->ID);
     $this->assertEquals('some-page', $attachment->post_name);
     $this->assertEquals('some-page', $page->post_name);
     // get_page_by_path() should return a post of the requested type before returning an attachment.
     $this->assertEquals($page, get_page_by_path('some-page'));
     // Make sure get_page_by_path() will still select an attachment when a post of the requested type doesn't exist.
     $this->assertEquals($other_att, get_page_by_path('some-other-page'));
 }
/**
 * Updates the comment count for the post.
 * Recalculates comment count by excluding specified comment types, eg. report, review.
 *
 * @param int $post_id Post ID
 * @param int $new New comment count
 * @param int $old Previous comment count
 *
 * @return void
 */
function _appthemes_update_comment_count($post_id, $new, $old)
{
    global $wpdb;
    if (!current_theme_supports('app-comment-counts')) {
        return;
    }
    list($options) = get_theme_support('app-comment-counts');
    $options = wp_parse_args($options, array('exclude_type' => array()));
    $exclude_types = apply_filters('appthemes_ctypes_count_exclude', $options['exclude_type']);
    if (empty($exclude_types) || !is_array($exclude_types)) {
        return;
    }
    $post = get_post($post_id);
    $exclude_types = esc_sql($exclude_types);
    $count = (int) $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$wpdb->comments} WHERE comment_post_ID = %d AND comment_approved = '1' AND comment_type NOT IN ( '" . implode("', '", $exclude_types) . "' )", $post_id));
    $wpdb->update($wpdb->posts, array('comment_count' => $count), array('ID' => $post_id));
    clean_post_cache($post);
}
Example #18
0
function wooc_apto_order_update_hierarchical($data)
{
    global $wpdb, $blog_id;
    $sort_view_id = $data['sort_view_id'];
    $sort_view_settings = APTO_functions::get_sort_view_settings($sort_view_id);
    $sort_view_data = get_post($sort_view_id);
    $sortID = $sort_view_data->post_parent;
    //return if not woocommerce
    if (APTO_functions::is_woocommerce($sortID) === FALSE) {
        return;
    }
    // Clear product specific transients
    $post_transients_to_clear = array('wc_product_children_ids_', 'wc_product_children_');
    foreach ($post_transients_to_clear as $transient) {
        delete_transient($transient . $data['post_id']);
        $wpdb->query($wpdb->prepare("DELETE FROM `{$wpdb->options}` WHERE `option_name` = %s OR `option_name` = %s", '_transient_' . $transient . $data['post_id'], '_transient_timeout_' . $transient . $data['post_id']));
    }
    clean_post_cache($data['post_id']);
}
 /**
  * Migrate post content from <img> tags to image shortcodes.
  *
  * ## OPTIONS
  *
  * <id>...
  * : One or more IDs of posts to update.
  *
  * [--dry-run]
  * : Only show the content which is to be changed, don't update posts.
  *
  * ## EXAMPLES
  *
  *     ## Migrate all Posts to the Image Shortcake syntax
  *     wp image-shortcake-shortcode migrate `wp post list --post_type=post` --ids`
  *
  *     ## Converts images to shortcodes on one post, preserving a log to rollback in case of errors.
  *     wp image-shortcake migrate 123 > potential-oops.txt
  *
  *
  * @synopsis <id>... [--dry-run]
  */
 public function migrate($args, $assoc_args)
 {
     foreach (array_filter($args) as $post_ID) {
         $post = $this->fetcher->get_check($post_ID);
         $_content = $post->post_content;
         $caption_replacements = Img_Shortcode_Data_Migration::find_caption_shortcodes_for_replacement($_content);
         $_content = str_replace(array_keys($caption_replacements), array_values($caption_replacements), $_content);
         $img_tag_replacements = Img_Shortcode_Data_Migration::find_img_tags_for_replacement($_content);
         $_content = str_replace(array_keys($img_tag_replacements), array_values($img_tag_replacements), $_content);
         $replacements = array_merge((array) $caption_replacements, (array) $img_tag_replacements);
         WP_CLI::log('');
         if (0 === count($replacements)) {
             WP_CLI::log('Nothing to replace on post ' . $post->ID . '. Skipping.');
             WP_CLI::log('');
             continue;
         }
         $header = 'Image shortcode replacements for post ' . $post->ID;
         WP_CLI::log($header);
         WP_CLI::log(str_repeat('=', strlen($header)));
         WP_CLI::log('');
         foreach ($replacements as $del => $ins) {
             \WP_CLI::log(\cli\Colors::colorize('%C-%n') . $del, true);
             \WP_CLI::log(\cli\Colors::colorize('%G+%n') . $ins, true);
         }
         WP_CLI::log('');
         if (isset($assoc_args['dry-run'])) {
             WP_CLI::log('Post not updated: --dry-run specifed.');
             WP_CLI::log('');
             continue;
         }
         global $wpdb;
         // @codingStandardsIgnoreStart
         $updated = $wpdb->update($wpdb->posts, array('post_content' => $_content), array('ID' => $post_ID));
         // @codingStandardsIgnoreEnd
         if (1 === $updated) {
             clean_post_cache($post);
             WP_CLI::success('Updated post ' . $post->ID . '.');
         } else {
             WP_CLI::warning('There was an unexpected error updating post ' . $post->ID . '.');
         }
     }
 }
 /**
  * Control POST data for mass edit tags
  *
  * @param string $type
  */
 function checkFormMassEdit()
 {
     if (!current_user_can('simple_tags')) {
         return false;
     }
     // Get GET data
     if (isset($_GET['post_type'])) {
         $type = stripslashes($_GET['post_type']);
     }
     if (isset($_POST['update_mass'])) {
         // origination and intention
         if (!wp_verify_nonce($_POST['secure_mass'], 'st_mass_terms')) {
             $this->message = __('Security problem. Try again. If this problem persist, contact <a href="mailto:amaury@wordpress-fr.net">plugin author</a>.', 'simpletags');
             $this->status = 'error';
             return false;
         }
         if (isset($_POST['tags'])) {
             $counter = 0;
             foreach ((array) $_POST['tags'] as $object_id => $tag_list) {
                 // Trim data
                 $tag_list = trim(stripslashes($tag_list));
                 // String to array
                 $tags = explode(',', $tag_list);
                 // Remove empty and trim tag
                 $tags = array_filter($tags, '_delete_empty_element');
                 // Add new tag (no append ! replace !)
                 wp_set_object_terms($object_id, $tags, $this->taxonomy);
                 $counter++;
                 // Clean cache
                 if ($this->post_type == 'page') {
                     clean_page_cache($object_id);
                 } else {
                     clean_post_cache($object_id);
                 }
             }
             $this->message = sprintf(__('%1$s %2$s(s) terms updated with success !', 'simpletags'), (int) $counter, strtolower($this->post_type_name));
             return true;
         }
     }
     return false;
 }
 /**
  * Listen POST datas for make bulk posts conversion to new post type
  */
 function listenConversion()
 {
     global $pagenow, $wpdb;
     if ($pagenow != 'edit.php') {
         return false;
     }
     // Default values for CPT
     $typenow = isset($_REQUEST['post_type']) ? $_REQUEST['post_type'] : 'post';
     if (isset($_REQUEST['action']) && substr($_REQUEST['action'], 0, strlen('convert_cpt')) == 'convert_cpt') {
         check_admin_referer('bulk-posts');
         // Source CPT
         $source_cpt = get_post_type_object($typenow);
         if (!current_user_can($source_cpt->cap->edit_posts)) {
             wp_die(__('Cheatin&#8217; uh?'));
         }
         // Destination CPT
         $destination_cpt = get_post_type_object(substr($_REQUEST['action'], strlen('convert_cpt') + 1));
         if (!current_user_can($destination_cpt->cap->edit_posts)) {
             wp_die(__('Cheatin&#8217; uh?'));
         }
         // Loop on posts
         foreach ((array) $_REQUEST['post'] as $post_id) {
             // Change the post type
             $object = get_post_to_edit($post_id);
             $object->post_type = $destination_cpt->name;
             wp_update_post((array) $object);
             // Clean object cache
             clean_post_cache($post_id);
         }
         $location = 'edit.php?post_type=' . $typenow;
         if ($referer = wp_get_referer()) {
             if (false !== strpos($referer, 'edit.php')) {
                 $location = $referer;
             }
         }
         $location = add_query_arg('message', 991, $location);
         wp_redirect($location);
         exit;
     }
 }
Example #22
0
 /**
  * @ticket 22448
  */
 function test_the_posts_filter()
 {
     // Create posts and clear their caches.
     $post_ids = $this->factory->post->create_many(10);
     foreach ($post_ids as $post_id) {
         clean_post_cache($post_id);
     }
     add_filter('the_posts', array($this, 'the_posts_filter'));
     $query = new WP_Query(array('post_type' => 'post', 'posts_per_page' => 5));
     // Sixth post added in filter
     $this->assertEquals(6, count($query->posts));
     $this->assertEquals(6, $query->post_count);
     foreach ($query->posts as $post) {
         // posts are WP_Post objects
         $this->assertTrue(is_a($post, 'WP_Post'));
         // filters are raw
         $this->assertEquals('raw', $post->filter);
         // custom data added in the_posts filter is preserved
         $this->assertEquals(array($post->ID, 'custom data'), $post->custom_data);
     }
     remove_filter('the_posts', array($this, 'the_posts_filter'));
 }
Example #23
0
 public static function CallWooAction($productid, $oldpost = null, $proddata = null)
 {
     if (self::$bwoosave) {
         if (function_exists('wc_get_product')) {
             $product = wc_get_product($productid);
             if (!empty($product) && is_object($product)) {
                 if ($product->product_type === 'variation') {
                     do_action('woocommerce_update_product_variation', $productid);
                 }
                 do_action('woocommerce_product_quick_edit_save', $product);
                 if ($proddata !== null) {
                     do_action('woocommerce_api_edit_product', $productid, $proddata);
                 }
             }
         }
     }
     if (self::$bsavepost) {
         clean_post_cache($productid);
         $post = get_post($productid);
         do_action('edit_post', $productid, $post);
         //			$post_after = get_post($post_ID);
         /**
          * Fires once an existing post has been updated.
          *
          * @since 3.0.0
          *
          * @param int     $post_ID      Post ID.
          * @param WP_Post $post_after   Post object following the update.
          * @param WP_Post $post_before  Post object before the update.
          */
         //			if($oldpost !== null)
         //				do_action( 'post_updated', $productid, $post, $oldpost);
         do_action('save_post', $productid, $post, true);
         do_action("save_post_{$post->post_type}", $productid, $post, true);
         do_action('wp_insert_post', $productid, $post, true);
     }
 }
Example #24
0
/**
 * Hook used to prevent page/post cache and rewrite rules from staying dirty.
 *
 * Does two things. If the post is a page and has a template then it will
 * update/add that template to the meta. For both pages and posts, it will clean
 * the post cache to make sure that the cache updates to the changes done
 * recently. For pages, the rewrite rules of WordPress are flushed to allow for
 * any changes.
 *
 * The $post parameter, only uses 'post_type' property and 'page_template'
 * property.
 *
 * @since 2.3.0
 * @access private
 * @uses $wp_rewrite Flushes Rewrite Rules.
 *
 * @param int $post_id The ID in the database table for the $post
 * @param object $post Object type containing the post information
 */
function _save_post_hook($post_id, $post)
{
    if ($post->post_type == 'page') {
        clean_page_cache($post_id);
        // Avoid flushing rules for every post during import.
        if (!defined('WP_IMPORTING')) {
            global $wp_rewrite;
            $wp_rewrite->flush_rules(false);
        }
    } else {
        clean_post_cache($post_id);
    }
}
 /**
  * @global wpdb    $wpdb
  * @global WP_Post $post
  * @param array $pages
  * @param int $pagenum
  * @param int $per_page
  */
 private function _display_rows_hierarchical($pages, $pagenum = 1, $per_page = 20)
 {
     global $wpdb;
     $level = 0;
     if (!$pages) {
         $pages = get_pages(array('sort_column' => 'menu_order'));
         if (!$pages) {
             return;
         }
     }
     /*
      * Arrange pages into two parts: top level pages and children_pages
      * children_pages is two dimensional array, eg.
      * children_pages[10][] contains all sub-pages whose parent is 10.
      * It only takes O( N ) to arrange this and it takes O( 1 ) for subsequent lookup operations
      * If searching, ignore hierarchy and treat everything as top level
      */
     if (empty($_REQUEST['s'])) {
         $top_level_pages = array();
         $children_pages = array();
         foreach ($pages as $page) {
             // Catch and repair bad pages.
             if ($page->post_parent == $page->ID) {
                 $page->post_parent = 0;
                 $wpdb->update($wpdb->posts, array('post_parent' => 0), array('ID' => $page->ID));
                 clean_post_cache($page);
             }
             if (0 == $page->post_parent) {
                 $top_level_pages[] = $page;
             } else {
                 $children_pages[$page->post_parent][] = $page;
             }
         }
         $pages =& $top_level_pages;
     }
     $count = 0;
     $start = ($pagenum - 1) * $per_page;
     $end = $start + $per_page;
     $to_display = array();
     foreach ($pages as $page) {
         if ($count >= $end) {
             break;
         }
         if ($count >= $start) {
             $to_display[$page->ID] = $level;
         }
         $count++;
         if (isset($children_pages)) {
             $this->_page_rows($children_pages, $count, $page->ID, $level + 1, $pagenum, $per_page, $to_display);
         }
     }
     // If it is the last pagenum and there are orphaned pages, display them with paging as well.
     if (isset($children_pages) && $count < $end) {
         foreach ($children_pages as $orphans) {
             foreach ($orphans as $op) {
                 if ($count >= $end) {
                     break;
                 }
                 if ($count >= $start) {
                     $to_display[$op->ID] = 0;
                 }
                 $count++;
             }
         }
     }
     $ids = array_keys($to_display);
     _prime_post_caches($ids);
     if (!isset($GLOBALS['post'])) {
         $GLOBALS['post'] = reset($ids);
     }
     foreach ($to_display as $page_id => $level) {
         echo "\t";
         $this->single_row($page_id, $level);
     }
 }
Example #26
0
 /**
  * Builds the sitemap and writes it into a xml file.
  *
  * @return array An array with messages such as failed writes etc.
  */
 function BuildSitemap()
 {
     global $wpdb, $posts, $wp_version;
     //Other plugins can detect if the building process is active
     $this->_isActive = true;
     if (true) {
         $fileName = $this->GetXmlPath();
         if ($this->IsFileWritable($fileName)) {
             $this->_fileHandle = fopen($fileName, "w");
         }
     }
     //Write gzipped sitemap file
     if ($this->IsGzipEnabled()) {
         $fileName = $this->GetZipPath();
         if ($this->IsFileWritable($fileName)) {
             $this->_fileZipHandle = gzopen($fileName, "w1");
         }
     }
     if (!$this->_fileHandle && !$this->_fileZipHandle) {
         return;
     }
     //Content of the XML file
     $this->AddElement(new TF_SEO_SitemapGeneratorXmlEntry('<?xml version="1.0" encoding="UTF-8"' . '?' . '>'));
     //All comments as an asso. Array (postID=>commentCount)
     $comments = array();
     //Full number of comments
     $commentCount = 0;
     //Go XML!
     $this->AddElement(new TF_SEO_SitemapGeneratorXmlEntry('<urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'));
     $home = home_url();
     $homePid = 0;
     //Add the home page (WITH a slash!)
     if (true) {
         if ('page' == get_option('show_on_front') && get_option('page_on_front')) {
             $pageOnFront = get_option('page_on_front');
             $p = get_page($pageOnFront);
             if ($p) {
                 $homePid = $p->ID;
                 $this->AddUrl(trailingslashit($home), $this->GetTimestampFromMySql($p->post_modified_gmt && $p->post_modified_gmt != '0000-00-00 00:00:00' ? $p->post_modified_gmt : $p->post_date_gmt), $this->GetOption("cf_home"), $this->GetOption("pr_home"));
             }
         } else {
             $this->AddUrl(trailingslashit($home), $this->GetTimestampFromMySql(get_lastpostmodified('GMT')), $this->GetOption("cf_home"), $this->GetOption("pr_home"));
         }
     }
     //Add the posts
     if (true) {
         $wpCompat = false;
         $excludes = '';
         //Excluded posts and pages (user enetered ID)
         $exclCats = '';
         // Excluded cats
         $sql = "SELECT `ID`, `post_author`, `post_date`, `post_date_gmt`, `post_status`, `post_name`, `post_modified`, `post_modified_gmt`, `post_parent`, `post_type` FROM `" . $wpdb->posts . "` WHERE ";
         $where = '(';
         if (true) {
             $where .= " (post_status = 'publish' AND (post_type in (''";
             foreach (get_post_types() as $customType) {
                 if (!in_array($customType, array('revision', 'nav_menu_item', 'attachment'))) {
                     if (!tfuse_options('seo_xmls_exclude_posttype_' . $customType, false) && 'STOP!' != tfuse_options('seo_xmls_exclude_posttype_' . $customType, 'STOP!')) {
                         $where .= ",'{$customType}'";
                     }
                 }
             }
             $where .= "))) ";
         }
         $where .= ") ";
         $where .= " AND post_password='' ORDER BY post_modified DESC";
         $sql .= $where;
         if ($this->GetOption("b_max_posts") > 0) {
             $sql .= " LIMIT 0," . $this->GetOption("b_max_posts");
         }
         $postCount = intval($wpdb->get_var("SELECT COUNT(*) AS cnt FROM `" . $wpdb->posts . "` WHERE " . $where, 0, 0));
         //Create a new connection because we are using mysql_unbuffered_query and don't want to disturb the WP connection
         //Safe Mode for other plugins which use mysql_query() without a connection handler and will destroy our resultset :(
         $con = $postRes = null;
         if (true) {
             $postRes = mysql_query($sql, $wpdb->dbh);
             if (!$postRes) {
                 trigger_error("MySQL query failed: " . mysql_error(), E_USER_NOTICE);
                 //E_USER_NOTICE will be displayed on our debug mode
                 return;
             }
         }
         if ($postRes) {
             $prioProvider = NULL;
             $z = 1;
             $zz = 1;
             //Default priorities
             $default_prio_posts = $this->GetOption('pr_posts');
             $default_prio_pages = $this->GetOption('pr_pages');
             //Change frequencies
             $cf_pages = $this->GetOption('cf_pages');
             $cf_posts = $this->GetOption('cf_posts');
             $minPrio = $this->GetOption('pr_posts_min');
             //Cycle through all posts and add them
             while ($post = mysql_fetch_object($postRes)) {
                 //Fill the cache with our DB result. Since it's incomplete (no text-content for example), we will clean it later.
                 $cache = array(&$post);
                 update_post_cache($cache);
                 //Set the current working post for other plugins which depend on "the loop"
                 $GLOBALS['post'] =& $post;
                 $permalink = get_permalink($post->ID);
                 if ($permalink != $home && $post->ID != $homePid) {
                     $isPage = false;
                     if ($wpCompat) {
                         $isPage = $post->post_status == 'static';
                     } else {
                         $isPage = $post->post_type == 'page';
                     }
                     //Default Priority if auto calc is disabled
                     $prio = 0;
                     if ($isPage) {
                         //Priority for static pages
                         $prio = $default_prio_pages;
                     } else {
                         //Priority for normal posts
                         $prio = $default_prio_posts;
                     }
                     if (!$isPage && $minPrio > 0 && $prio < $minPrio) {
                         $prio = $minPrio;
                     }
                     //Add it
                     $this->AddUrl($permalink, $this->GetTimestampFromMySql($post->post_modified_gmt && $post->post_modified_gmt != '0000-00-00 00:00:00' ? $post->post_modified_gmt : $post->post_date_gmt), $isPage ? $cf_pages : $cf_posts, $prio);
                     if (false) {
                         $subPage = '';
                         for ($p = 1; $p <= $post->postPages; $p++) {
                             if (get_option('permalink_structure') == '') {
                                 $subPage = $permalink . '&amp;paged=' . ($p + 1);
                             } else {
                                 $subPage = trailingslashit($permalink) . user_trailingslashit($p + 1, 'single_paged');
                             }
                             $this->AddUrl($subPage, $this->GetTimestampFromMySql($post->post_modified_gmt && $post->post_modified_gmt != '0000-00-00 00:00:00' ? $post->post_modified_gmt : $post->post_date_gmt), $isPage ? $cf_pages : $cf_posts, $prio);
                         }
                     }
                 }
                 //Update the status every 100 posts and at the end.
                 //If the script breaks because of memory or time limit,
                 //we have a "last reponded" value which can be compared to the server settings
                 if ($zz == 100 || $z == $postCount) {
                     $zz = 0;
                 } else {
                     $zz++;
                 }
                 $z++;
                 //Clean cache because it's incomplete
                 if (version_compare($wp_version, "2.5", ">=")) {
                     //WP 2.5 makes a mysql query for every clean_post_cache to clear the child cache
                     //so I've copied the function here until a patch arrives...
                     wp_cache_delete($post->ID, 'posts');
                     wp_cache_delete($post->ID, 'post_meta');
                     clean_object_term_cache($post->ID, 'post');
                 } else {
                     clean_post_cache($post->ID);
                 }
             }
             unset($postRes);
             unset($prioProvider);
         }
     }
     //Add custom taxonomy pages
     if (true) {
         $taxList = array();
         foreach (get_taxonomies() as $taxName) {
             if (!in_array($taxName, array('nav_menu', 'link_category', 'post_format'))) {
                 $taxonomy = get_taxonomy($taxName);
                 if (isset($taxonomy->labels->name) && trim($taxonomy->labels->name) != '') {
                     if (!tfuse_options('seo_xmls_exclude_taxonomy_' . $taxName, false) && 'STOP!' != tfuse_options('seo_xmls_exclude_taxonomy_' . $taxName, 'STOP!')) {
                         if ($taxonomy) {
                             $taxList[] = $wpdb->escape($taxonomy->name);
                         }
                     }
                 }
             }
         }
         if (count($taxList) > 0) {
             //We're selecting all term information (t.*) plus some additional fields
             //like the last mod date and the taxonomy name, so WP doesnt need to make
             //additional queries to build the permalink structure.
             //This does NOT work for categories and tags yet, because WP uses get_category_link
             //and get_tag_link internally and that would cause one additional query per term!
             $sql = "\r\r\n\t\t\t\t\tSELECT\r\r\n\t\t\t\t\t\tt.*,\r\r\n\t\t\t\t\t\ttt.taxonomy AS _taxonomy,\r\r\n\t\t\t\t\t\tUNIX_TIMESTAMP(MAX(post_date_gmt)) as _mod_date\r\r\n\t\t\t\t\tFROM\r\r\n\t\t\t\t\t\t{$wpdb->posts} p ,\r\r\n\t\t\t\t\t\t{$wpdb->term_relationships} r,\r\r\n\t\t\t\t\t\t{$wpdb->terms} t,\r\r\n\t\t\t\t\t\t{$wpdb->term_taxonomy} tt\r\r\n\t\t\t\t\tWHERE\r\r\n\t\t\t\t\t\tp.ID = r.object_id\r\r\n\t\t\t\t\t\tAND p.post_status = 'publish'\r\r\n\t\t\t\t\t\tAND p.post_password = ''\r\r\n\t\t\t\t\t\tAND r.term_taxonomy_id = t.term_id\r\r\n\t\t\t\t\t\tAND t.term_id = tt.term_id\r\r\n\t\t\t\t\t\tAND tt.count > 0\r\r\n\t\t\t\t\t\tAND tt.taxonomy IN ('" . implode("','", $taxList) . "')\r\r\n\t\t\t\t\tGROUP BY \r\r\n\t\t\t\t\t\tt.term_id";
             $termInfo = $wpdb->get_results($sql);
             foreach ($termInfo as $term) {
                 if (!in_array($term->_taxonomy, array('nav_menu', 'link_category', 'post_format'))) {
                     $this->AddUrl(get_term_link($term->slug, $term->_taxonomy), $term->_mod_date, $this->GetOption("cf_tags"), $this->GetOption("pr_tags"));
                 }
             }
         }
     }
     //Add the custom pages
     if ($this->_pages && is_array($this->_pages) && count($this->_pages) > 0) {
         //#type $page TF_SEO_SitemapGeneratorPage
         foreach ($this->_pages as $page) {
             $this->AddUrl($page->GetUrl(), $page->getLastMod(), $page->getChangeFreq(), $page->getPriority());
         }
     }
     do_action('tf_seo_buildmap');
     $this->AddElement(new TF_SEO_SitemapGeneratorXmlEntry("</urlset>"));
     $pingUrl = '';
     if (true) {
         if ($this->_fileHandle && fclose($this->_fileHandle)) {
             $this->_fileHandle = null;
             $pingUrl = $this->GetXmlUrl();
         }
     }
     if ($this->IsGzipEnabled()) {
         if ($this->_fileZipHandle && fclose($this->_fileZipHandle)) {
             $this->_fileZipHandle = null;
             $pingUrl = $this->GetZipUrl();
         }
     }
     //Ping Google
     if (!empty($pingUrl)) {
         $sPingUrl = "http://www.google.com/webmasters/sitemaps/ping?sitemap=" . urlencode($pingUrl);
         $pingres = $this->RemoteOpen($sPingUrl);
         if ($pingres == NULL || $pingres === false) {
             trigger_error("Failed to ping Google: " . htmlspecialchars(strip_tags($pingres)), E_USER_NOTICE);
         }
     }
     //Ping Ask.com
     if (!empty($pingUrl)) {
         $sPingUrl = "http://submissions.ask.com/ping?sitemap=" . urlencode($pingUrl);
         $pingres = $this->RemoteOpen($sPingUrl);
         if ($pingres == NULL || $pingres === false || strpos($pingres, "successfully received and added") === false) {
             //Ask.com returns 200 OK even if there was an error, so we need to check the content.
             trigger_error("Failed to ping Ask.com: " . htmlspecialchars(strip_tags($pingres)), E_USER_NOTICE);
         }
     }
     //Ping Bing
     if (!empty($pingUrl)) {
         $sPingUrl = "http://www.bing.com/webmaster/ping.aspx?siteMap=" . urlencode($pingUrl);
         $pingres = $this->RemoteOpen($sPingUrl);
         //Bing returns ip/country-based success messages, so there is no way to check the content. Rely on HTTP 500 only then...
         if ($pingres == NULL || $pingres === false || strpos($pingres, " ") === false) {
             trigger_error("Failed to ping Bing: " . htmlspecialchars(strip_tags($pingres)), E_USER_NOTICE);
         }
     }
     $this->_isActive = false;
     //done...
     return;
 }
Example #27
0
/**
 * Will clean the page in the cache.
 *
 * Clean (read: delete) page from cache that matches $id. Will also clean cache
 * associated with 'all_page_ids' and 'get_pages'.
 *
 * @since 2.0.0
 * @deprecated 3.4.0
 *
 * @uses do_action() Will call the 'clean_page_cache' hook action.
 *
 * @param int $id Page ID to clean
 */
function clean_page_cache($id)
{
    _deprecated_function(__FUNCTION__, '3.4', 'clean_post_cache()');
    clean_post_cache($id);
}
 function get_post_sync_operation($new_status, $old_status, $post, $module_conditions)
 {
     $delete_on_behalf_of = array();
     $submit_on_behalf_of = array();
     $delete_stati = array('delete');
     foreach ($module_conditions as $module => $conditions) {
         if (!in_array($post->post_type, $conditions['post_types'])) {
             continue;
         }
         $deleted_post = in_array($new_status, $delete_stati);
         if ($deleted_post) {
             $delete_on_behalf_of[] = $module;
         } else {
             clean_post_cache($post->ID);
             $new_status = get_post_status($post->ID);
             // Inherited status is resolved here
         }
         $old_status_in_stati = in_array($old_status, $conditions['post_stati']);
         $new_status_in_stati = in_array($new_status, $conditions['post_stati']);
         if ($old_status_in_stati && !$new_status_in_stati) {
             // Jetpack no longer needs the post
             if (!$deleted_post) {
                 $delete_on_behalf_of[] = $module;
             }
             // else, we've already flagged it above
             continue;
         }
         if (!$new_status_in_stati) {
             continue;
         }
         // At this point, we know we want to sync the post, not delete it
         $submit_on_behalf_of[] = $module;
     }
     if (!empty($submit_on_behalf_of)) {
         return array('operation' => 'submit', 'on_behalf_of' => $submit_on_behalf_of);
     }
     if (!empty($delete_on_behalf_of)) {
         return array('operation' => 'delete', 'on_behalf_of' => $delete_on_behalf_of);
     }
     return false;
 }
 /**
  * Automatically tag a post/page from the database terms for the taxonomy specified
  *
  * @param object $object 
  * @param string $taxonomy 
  * @param array $options 
  * @param boolean $counter 
  * @return boolean
  * @author Amaury Balmer
  */
 function autoTermsPost($object, $taxonomy = 'post_tag', $options = array(), $counter = false)
 {
     global $wpdb;
     // Option exists ?
     if ($options == false || empty($options)) {
         return false;
     }
     if (get_the_terms($object->ID, $taxonomy) != false && $options['at_empty'] == 1) {
         return false;
         // Skip post with terms, if term only empty post option is checked
     }
     $terms_to_add = array();
     // Merge title + content + excerpt to compare with terms
     $content = $object->post_content . ' ' . $object->post_title;
     if (isset($object->post_excerpt)) {
         $content .= ' ' . $object->post_excerpt;
     }
     $content = trim(strip_tags($content));
     if (empty($content)) {
         return false;
     }
     // Auto term with specific auto terms list
     if (isset($options['auto_list'])) {
         $terms = (array) maybe_unserialize($options['auto_list']);
         foreach ($terms as $term) {
             if (!is_string($term) && empty($term)) {
                 continue;
             }
             $term = trim($term);
             // Whole word ?
             if ((int) $options['only_full_word'] == 1) {
                 if (preg_match("/\\b" . $term . "\\b/i", $content)) {
                     $terms_to_add[] = $term;
                 }
             } elseif (stristr($content, $term)) {
                 $terms_to_add[] = $term;
             }
         }
         unset($terms, $term);
     }
     // Auto terms with all terms
     if (isset($options['at_all']) && $options['at_all'] == 1) {
         // Get all terms
         $terms = $wpdb->get_col($wpdb->prepare("SELECT DISTINCT name\n\t\t\t\tFROM {$wpdb->terms} AS t\n\t\t\t\tINNER JOIN {$wpdb->term_taxonomy} AS tt ON t.term_id = tt.term_id\n\t\t\t\tWHERE tt.taxonomy = %s", $taxonomy));
         $terms = array_unique($terms);
         foreach ($terms as $term) {
             $term = stripslashes($term);
             if (!is_string($term) && empty($term)) {
                 continue;
             }
             // Whole word ?
             if ((int) $options['only_full_word'] == 1) {
                 $term = ' ' . $term . ' ';
                 // Add space before and after !
             }
             if (stristr($content, $term)) {
                 $terms_to_add[] = $term;
             }
         }
         // Clean memory
         $terms = array();
         unset($terms, $term);
     }
     // Append terms if terms to add
     if (!empty($terms_to_add)) {
         // Remove empty and duplicate elements
         $terms_to_add = array_filter($terms_to_add, '_delete_empty_element');
         $terms_to_add = array_unique($terms_to_add);
         if ($counter == true) {
             // Increment counter
             $counter = (int) get_option('tmp_auto_terms_st') + count($terms_to_add);
             update_option('tmp_auto_terms_st', $counter);
         }
         // Add terms to posts
         wp_set_object_terms($object->ID, $terms_to_add, $taxonomy, true);
         // Clean cache
         if (isset($object->post_type) && ($object->post_type = 'page')) {
             clean_page_cache($object->ID);
         } else {
             clean_post_cache($object->ID);
         }
         return true;
     }
     return false;
 }
Example #30
0
/**
 * Trash or delete an attachment.
 *
 * When an attachment is permanently deleted, the file will also be removed.
 * Deletion removes all post meta fields, taxonomy, comments, etc. associated
 * with the attachment (except the main post).
 *
 * The attachment is moved to the trash instead of permanently deleted unless trash
 * for media is disabled, item is already in the trash, or $force_delete is true.
 *
 * @since 2.0.0
 *
 * @global wpdb $wpdb WordPress database abstraction object.
 *
 * @param int  $post_id      Attachment ID.
 * @param bool $force_delete Optional. Whether to bypass trash and force deletion.
 *                           Default false.
 * @return mixed False on failure. Post data on success.
 */
function wp_delete_attachment($post_id, $force_delete = false)
{
    global $wpdb;
    if (!($post = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->posts} WHERE ID = %d", $post_id)))) {
        return $post;
    }
    if ('attachment' != $post->post_type) {
        return false;
    }
    if (!$force_delete && EMPTY_TRASH_DAYS && MEDIA_TRASH && 'trash' != $post->post_status) {
        return wp_trash_post($post_id);
    }
    delete_post_meta($post_id, '_wp_trash_meta_status');
    delete_post_meta($post_id, '_wp_trash_meta_time');
    $meta = wp_get_attachment_metadata($post_id);
    $backup_sizes = get_post_meta($post->ID, '_wp_attachment_backup_sizes', true);
    $file = get_attached_file($post_id);
    if (is_multisite()) {
        delete_transient('dirsize_cache');
    }
    /**
     * Fires before an attachment is deleted, at the start of wp_delete_attachment().
     *
     * @since 2.0.0
     *
     * @param int $post_id Attachment ID.
     */
    do_action('delete_attachment', $post_id);
    wp_delete_object_term_relationships($post_id, array('category', 'post_tag'));
    wp_delete_object_term_relationships($post_id, get_object_taxonomies($post->post_type));
    // Delete all for any posts.
    delete_metadata('post', null, '_thumbnail_id', $post_id, true);
    wp_defer_comment_counting(true);
    $comment_ids = $wpdb->get_col($wpdb->prepare("SELECT comment_ID FROM {$wpdb->comments} WHERE comment_post_ID = %d", $post_id));
    foreach ($comment_ids as $comment_id) {
        wp_delete_comment($comment_id, true);
    }
    wp_defer_comment_counting(false);
    $post_meta_ids = $wpdb->get_col($wpdb->prepare("SELECT meta_id FROM {$wpdb->postmeta} WHERE post_id = %d ", $post_id));
    foreach ($post_meta_ids as $mid) {
        delete_metadata_by_mid('post', $mid);
    }
    /** This action is documented in wp-includes/post.php */
    do_action('delete_post', $post_id);
    $result = $wpdb->delete($wpdb->posts, array('ID' => $post_id));
    if (!$result) {
        return false;
    }
    /** This action is documented in wp-includes/post.php */
    do_action('deleted_post', $post_id);
    $uploadpath = wp_upload_dir();
    if (!empty($meta['thumb'])) {
        // Don't delete the thumb if another attachment uses it.
        if (!$wpdb->get_row($wpdb->prepare("SELECT meta_id FROM {$wpdb->postmeta} WHERE meta_key = '_wp_attachment_metadata' AND meta_value LIKE %s AND post_id <> %d", '%' . $wpdb->esc_like($meta['thumb']) . '%', $post_id))) {
            $thumbfile = str_replace(basename($file), $meta['thumb'], $file);
            /** This filter is documented in wp-includes/functions.php */
            $thumbfile = apply_filters('wp_delete_file', $thumbfile);
            @unlink(path_join($uploadpath['basedir'], $thumbfile));
        }
    }
    // Remove intermediate and backup images if there are any.
    if (isset($meta['sizes']) && is_array($meta['sizes'])) {
        foreach ($meta['sizes'] as $size => $sizeinfo) {
            $intermediate_file = str_replace(basename($file), $sizeinfo['file'], $file);
            /** This filter is documented in wp-includes/functions.php */
            $intermediate_file = apply_filters('wp_delete_file', $intermediate_file);
            @unlink(path_join($uploadpath['basedir'], $intermediate_file));
        }
    }
    if (is_array($backup_sizes)) {
        foreach ($backup_sizes as $size) {
            $del_file = path_join(dirname($meta['file']), $size['file']);
            /** This filter is documented in wp-includes/functions.php */
            $del_file = apply_filters('wp_delete_file', $del_file);
            @unlink(path_join($uploadpath['basedir'], $del_file));
        }
    }
    wp_delete_file($file);
    clean_post_cache($post);
    return $post;
}