Exemplo n.º 1
0
 /**
  * Validate Date Input
  */
 public function validateDate($data)
 {
     // First validate that it is an actual date
     if (!wp_checkdate(intval($data['mm']), intval($data['jj']), intval($data['aa']), $data['aa'] . '-' . $data['mm'] . '-' . $data['jj'])) {
         return wp_send_json(array('status' => 'error', 'message' => __('Please provide a valid date.', 'nestedpages')));
         die;
     }
     // Validate all the fields are there
     if ($data['aa'] !== "" && $data['mm'] !== "" && $data['jj'] !== "" && $data['hh'] !== "" && $data['mm'] !== "" && $data['ss'] !== "") {
         $date = strtotime($data['aa'] . '-' . $data['mm'] . '-' . $data['jj'] . ' ' . $data['hh'] . ':' . $data['mm'] . ':' . $data['ss']);
         return date('Y-m-d H:i:s', $date);
     } else {
         return wp_send_json(array('status' => 'error', 'message' => __('Please provide a valid date.', 'nestedpages')));
         die;
     }
 }
Exemplo n.º 2
0
 /**
  * Check valid date
  */
 private function checkValidDate($month, $day, $year)
 {
     if (!wp_checkdate(intval($month), intval($day), intval($year), $year . '-' . $month . '-' . $day)) {
         return $this->sendDateError();
     }
 }
 function get_new_expiration_date($post_data = false)
 {
     $new_expiration_date = false;
     if ($post_data === false) {
         $post_data =& $_POST;
     }
     // see if the expiration date has been changed, and thus must be updated
     foreach (array('aa', 'mm', 'jj', 'hh', 'mn') as $timeunit) {
         if (!empty($post_data['cbp-expiration-hidden_' . $timeunit]) && $post_data['cbp-expiration-hidden_' . $timeunit] != $post_data['cbp-expiration-' . $timeunit]) {
             $post_data['edit_expiration_date'] = '1';
             break;
         }
     }
     // if the expiration date has changed, validate it now
     if (!empty($post_data['edit_expiration_date'])) {
         // collect data
         $aa = $post_data['cbp-expiration-aa'];
         $mm = $post_data['cbp-expiration-mm'];
         $jj = $post_data['cbp-expiration-jj'];
         $hh = $post_data['cbp-expiration-hh'];
         $mn = $post_data['cbp-expiration-mn'];
         $ss = $post_data['cbp-expiration-ss'];
         // validate / normalize collected data
         $aa = $aa <= 0 ? date('Y') : $aa;
         $mm = $mm <= 0 ? date('n') : $mm;
         $jj = $jj > 31 ? 31 : $jj;
         $jj = $jj <= 0 ? date('j') : $jj;
         $hh = $hh > 23 ? $hh - 24 : $hh;
         $mn = $mn > 59 ? $mn - 60 : $mn;
         $ss = $ss > 59 ? $ss - 60 : $ss;
         $new_expiration_date = sprintf("%04d-%02d-%02d %02d:%02d:%02d", $aa, $mm, $jj, $hh, $mn, $ss);
         $valid_date = wp_checkdate($mm, $jj, $aa, $new_expiration_date);
         if (!$valid_date) {
             return new WP_Error('invalid_date', __('Whoops, the provided expiration date is invalid.'));
         }
         $post_data['expiration_date_gmt'] = get_gmt_from_date($new_expiration_date);
     }
     // $new_expiration_date is now either false or a valid date
     return $new_expiration_date;
 }
 /**
  * Remove a movie from the queue list.
  * 
  * Simply change the movie's post_status to 'import-draft',
  * update the dates and delete the movie metadata.
  *
  * @since    1.0
  * 
  * @param    string     $post_id Movie Post ID.
  * 
  * @return   int|WP_Error    Post ID if everything worked, WP_Error instance if update of meta delete failed
  */
 public static function dequeue_movie($post_id)
 {
     $post_date = current_time('mysql');
     $post_date = wp_checkdate(substr($post_date, 5, 2), substr($post_date, 8, 2), substr($post_date, 0, 4), $post_date);
     $post_date_gmt = get_gmt_from_date($post_date);
     $_post = array('ID' => $post_id, 'post_date' => $post_date, 'post_date_gmt' => $post_date_gmt, 'post_status' => 'import-draft');
     $update = wp_update_post($_post, $wp_error = true);
     if (is_wp_error($update)) {
         return new WP_Error('error', sprintf(__('An error occured when trying to remove "%s" from the queue: %s', 'wpmovielibrary'), get_the_title($post_id), $update->get_error_message()));
     }
     $update = delete_post_meta($post_id, '_wpmoly_movie_data');
     if (false === $update) {
         return new WP_Error('error', sprintf(__('An error occured when trying to delete "%s" metadata.', 'wpmovielibrary'), get_the_title($post_id)));
     }
     return $post_id;
 }
Exemplo n.º 5
0
/**
 * Insert or update a post.
 *
 * If the $postarr parameter has 'ID' set to a value, then post will be updated.
 *
 * You can set the post date manually, by setting the values for 'post_date'
 * and 'post_date_gmt' keys. You can close the comments or open the comments by
 * setting the value for 'comment_status' key.
 *
 * @global wpdb $wpdb    WordPress database abstraction object.
 *
 * @since 1.0.0
 *
 * @param array $postarr {
 *     An array of elements that make up a post to update or insert.
 *
 *     @type int    'ID'                    The post ID. If equal to something other than 0, the post with that ID will
 *                                          be updated. Default 0.
 *     @type string 'post_status'           The post status. Default 'draft'.
 *     @type string 'post_type'             The post type. Default 'post'.
 *     @type int    'post_author'           The ID of the user who added the post. Default the current user ID.
 *     @type bool   'ping_status'           Whether the post can accept pings. Default value of 'default_ping_status' option.
 *     @type int    'post_parent'           Set this for the post it belongs to, if any. Default 0.
 *     @type int    'menu_order'            The order it is displayed. Default 0.
 *     @type string 'to_ping'               Space or carriage return-separated list of URLs to ping. Default empty string.
 *     @type string 'pinged'                Space or carriage return-separated list of URLs that have been pinged.
 *                                          Default empty string.
 *     @type string 'post_password          The password to access the post. Default empty string.
 *     @type string 'guid'                  Global Unique ID for referencing the post.
 *     @type string 'post_content_filtered' The filtered post content. Default empty string.
 *     @type string 'post_excerpt'          The post excerpt. Default empty string.
 * }
 * @param bool  $wp_error Optional. Allow return of WP_Error on failure.
 * @return int|WP_Error The post ID on success. The value 0 or WP_Error on failure.
 */
function wp_insert_post($postarr, $wp_error = false)
{
    global $wpdb;
    $user_id = get_current_user_id();
    $defaults = array('post_status' => 'draft', 'post_type' => 'post', 'post_author' => $user_id, 'ping_status' => get_option('default_ping_status'), 'post_parent' => 0, 'menu_order' => 0, 'to_ping' => '', 'pinged' => '', 'post_password' => '', 'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0, 'post_content' => '', 'post_title' => '');
    $postarr = wp_parse_args($postarr, $defaults);
    unset($postarr['filter']);
    $postarr = sanitize_post($postarr, 'db');
    // export array as variables
    extract($postarr, EXTR_SKIP);
    // Are we updating or creating?
    $post_ID = 0;
    $update = false;
    if (!empty($ID)) {
        $update = true;
        // Get the post ID and GUID
        $post_ID = $ID;
        $post_before = get_post($post_ID);
        if (is_null($post_before)) {
            if ($wp_error) {
                return new WP_Error('invalid_post', __('Invalid post ID.'));
            }
            return 0;
        }
        $guid = get_post_field('guid', $post_ID);
        $previous_status = get_post_field('post_status', $ID);
    } else {
        $previous_status = 'new';
    }
    $maybe_empty = !$post_content && !$post_title && !$post_excerpt && post_type_supports($post_type, 'editor') && post_type_supports($post_type, 'title') && post_type_supports($post_type, 'excerpt');
    if (apply_filters('wp_insert_post_empty_content', $maybe_empty, $postarr)) {
        if ($wp_error) {
            return new WP_Error('empty_content', __('Content, title, and excerpt are empty.'));
        } else {
            return 0;
        }
    }
    if (empty($post_type)) {
        $post_type = 'post';
    }
    if (empty($post_status)) {
        $post_status = 'draft';
    }
    if (!empty($post_category)) {
        $post_category = array_filter($post_category);
    }
    // Filter out empty terms
    // Make sure we set a valid category.
    if (empty($post_category) || 0 == count($post_category) || !is_array($post_category)) {
        // 'post' requires at least one category.
        if ('post' == $post_type && 'auto-draft' != $post_status) {
            $post_category = array(get_option('default_category'));
        } else {
            $post_category = array();
        }
    }
    if (empty($post_author)) {
        $post_author = $user_id;
    }
    // Don't allow contributors to set the post slug for pending review posts
    if ('pending' == $post_status && !current_user_can('publish_posts')) {
        $post_name = '';
    }
    // Create a valid post name. Drafts and pending posts are allowed to have an empty
    // post name.
    if (empty($post_name)) {
        if (!in_array($post_status, array('draft', 'pending', 'auto-draft'))) {
            $post_name = sanitize_title($post_title);
        } else {
            $post_name = '';
        }
    } else {
        // On updates, we need to check to see if it's using the old, fixed sanitization context.
        $check_name = sanitize_title($post_name, '', 'old-save');
        if ($update && strtolower(urlencode($post_name)) == $check_name && get_post_field('post_name', $ID) == $check_name) {
            $post_name = $check_name;
        } else {
            // new post, or slug has changed.
            $post_name = sanitize_title($post_name);
        }
    }
    // If the post date is empty (due to having been new or a draft) and status is not 'draft' or 'pending', set date to now
    if (empty($post_date) || '0000-00-00 00:00:00' == $post_date) {
        $post_date = current_time('mysql');
    }
    // validate the date
    $mm = substr($post_date, 5, 2);
    $jj = substr($post_date, 8, 2);
    $aa = substr($post_date, 0, 4);
    $valid_date = wp_checkdate($mm, $jj, $aa, $post_date);
    if (!$valid_date) {
        if ($wp_error) {
            return new WP_Error('invalid_date', __('Whoops, the provided date is invalid.'));
        } else {
            return 0;
        }
    }
    if (empty($post_date_gmt) || '0000-00-00 00:00:00' == $post_date_gmt) {
        if (!in_array($post_status, array('draft', 'pending', 'auto-draft'))) {
            $post_date_gmt = get_gmt_from_date($post_date);
        } else {
            $post_date_gmt = '0000-00-00 00:00:00';
        }
    }
    if ($update || '0000-00-00 00:00:00' == $post_date) {
        $post_modified = current_time('mysql');
        $post_modified_gmt = current_time('mysql', 1);
    } else {
        $post_modified = $post_date;
        $post_modified_gmt = $post_date_gmt;
    }
    if ('publish' == $post_status) {
        $now = gmdate('Y-m-d H:i:59');
        if (mysql2date('U', $post_date_gmt, false) > mysql2date('U', $now, false)) {
            $post_status = 'future';
        }
    } elseif ('future' == $post_status) {
        $now = gmdate('Y-m-d H:i:59');
        if (mysql2date('U', $post_date_gmt, false) <= mysql2date('U', $now, false)) {
            $post_status = 'publish';
        }
    }
    if (empty($comment_status)) {
        if ($update) {
            $comment_status = 'closed';
        } else {
            $comment_status = get_option('default_comment_status');
        }
    }
    if (empty($ping_status)) {
        $ping_status = get_option('default_ping_status');
    }
    if (isset($to_ping)) {
        $to_ping = sanitize_trackback_urls($to_ping);
    } else {
        $to_ping = '';
    }
    if (!isset($pinged)) {
        $pinged = '';
    }
    if (isset($post_parent)) {
        $post_parent = (int) $post_parent;
    } else {
        $post_parent = 0;
    }
    // Check the post_parent to see if it will cause a hierarchy loop
    $post_parent = apply_filters('wp_insert_post_parent', $post_parent, $post_ID, compact(array_keys($postarr)), $postarr);
    if (isset($menu_order)) {
        $menu_order = (int) $menu_order;
    } else {
        $menu_order = 0;
    }
    if (!isset($post_password) || 'private' == $post_status) {
        $post_password = '';
    }
    $post_name = wp_unique_post_slug($post_name, $post_ID, $post_status, $post_type, $post_parent);
    // expected_slashed (everything!)
    $data = compact(array('post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_content_filtered', 'post_title', 'post_excerpt', 'post_status', 'post_type', 'comment_status', 'ping_status', 'post_password', 'post_name', 'to_ping', 'pinged', 'post_modified', 'post_modified_gmt', 'post_parent', 'menu_order', 'guid'));
    $data = apply_filters('wp_insert_post_data', $data, $postarr);
    $data = wp_unslash($data);
    $where = array('ID' => $post_ID);
    if ($update) {
        do_action('pre_post_update', $post_ID, $data);
        if (false === $wpdb->update($wpdb->posts, $data, $where)) {
            if ($wp_error) {
                return new WP_Error('db_update_error', __('Could not update post in the database'), $wpdb->last_error);
            } else {
                return 0;
            }
        }
    } else {
        if (isset($post_mime_type)) {
            $data['post_mime_type'] = wp_unslash($post_mime_type);
        }
        // This isn't in the update
        // If there is a suggested ID, use it if not already present
        if (!empty($import_id)) {
            $import_id = (int) $import_id;
            if (!$wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->posts} WHERE ID = %d", $import_id))) {
                $data['ID'] = $import_id;
            }
        }
        if (false === $wpdb->insert($wpdb->posts, $data)) {
            if ($wp_error) {
                return new WP_Error('db_insert_error', __('Could not insert post into the database'), $wpdb->last_error);
            } else {
                return 0;
            }
        }
        $post_ID = (int) $wpdb->insert_id;
        // use the newly generated $post_ID
        $where = array('ID' => $post_ID);
    }
    if (empty($data['post_name']) && !in_array($data['post_status'], array('draft', 'pending', 'auto-draft'))) {
        $data['post_name'] = sanitize_title($data['post_title'], $post_ID);
        $wpdb->update($wpdb->posts, array('post_name' => $data['post_name']), $where);
    }
    if (is_object_in_taxonomy($post_type, 'category')) {
        wp_set_post_categories($post_ID, $post_category);
    }
    if (isset($tags_input) && is_object_in_taxonomy($post_type, 'post_tag')) {
        wp_set_post_tags($post_ID, $tags_input);
    }
    // new-style support for all custom taxonomies
    if (!empty($tax_input)) {
        foreach ($tax_input 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)) {
                wp_set_post_terms($post_ID, $tags, $taxonomy);
            }
        }
    }
    $current_guid = get_post_field('guid', $post_ID);
    // Set GUID
    if (!$update && '' == $current_guid) {
        $wpdb->update($wpdb->posts, array('guid' => get_permalink($post_ID)), $where);
    }
    clean_post_cache($post_ID);
    $post = get_post($post_ID);
    if (!empty($page_template) && 'page' == $data['post_type']) {
        $post->page_template = $page_template;
        $page_templates = wp_get_theme()->get_page_templates();
        if ('default' != $page_template && !isset($page_templates[$page_template])) {
            if ($wp_error) {
                return new WP_Error('invalid_page_template', __('The page template is invalid.'));
            } else {
                return 0;
            }
        }
        update_post_meta($post_ID, '_wp_page_template', $page_template);
    }
    wp_transition_post_status($data['post_status'], $previous_status, $post);
    if ($update) {
        do_action('edit_post', $post_ID, $post);
        $post_after = get_post($post_ID);
        do_action('post_updated', $post_ID, $post_after, $post_before);
    }
    do_action("save_post_{$post->post_type}", $post_ID, $post, $update);
    do_action('save_post', $post_ID, $post, $update);
    do_action('wp_insert_post', $post_ID, $post, $update);
    return $post_ID;
}
Exemplo n.º 6
0
/**
 * Rename $_POST data from form names to DB post columns.
 *
 * Manipulates $_POST directly.
 *
 * @package WordPress
 * @since 2.6.0
 *
 * @param bool $update Are we updating a pre-existing post?
 * @param array $post_data Array of post data. Defaults to the contents of $_POST.
 * @return object|bool WP_Error on failure, true on success.
 */
function _wp_translate_postdata( $update = false, $post_data = null ) {

	if ( empty($post_data) )
		$post_data = &$_POST;

	if ( $update )
		$post_data['ID'] = (int) $post_data['post_ID'];

	$ptype = get_post_type_object( $post_data['post_type'] );

	if ( $update && ! current_user_can( $ptype->cap->edit_post, $post_data['ID'] ) ) {
		if ( 'page' == $post_data['post_type'] )
			return new WP_Error( 'edit_others_pages', __( 'You are not allowed to edit pages as this user.' ) );
		else
			return new WP_Error( 'edit_others_posts', __( 'You are not allowed to edit posts as this user.' ) );
	} elseif ( ! $update && ! current_user_can( $ptype->cap->create_posts ) ) {
		if ( 'page' == $post_data['post_type'] )
			return new WP_Error( 'edit_others_pages', __( 'You are not allowed to create pages as this user.' ) );
		else
			return new WP_Error( 'edit_others_posts', __( 'You are not allowed to create posts as this user.' ) );
	}

	if ( isset( $post_data['content'] ) )
		$post_data['post_content'] = $post_data['content'];

	if ( isset( $post_data['excerpt'] ) )
		$post_data['post_excerpt'] = $post_data['excerpt'];

	if ( isset( $post_data['parent_id'] ) )
		$post_data['post_parent'] = (int) $post_data['parent_id'];

	if ( isset($post_data['trackback_url']) )
		$post_data['to_ping'] = $post_data['trackback_url'];

	if ( !isset($post_data['user_ID']) )
		$post_data['user_ID'] = $GLOBALS['user_ID'];

	if (!empty ( $post_data['post_author_override'] ) ) {
		$post_data['post_author'] = (int) $post_data['post_author_override'];
	} else {
		if (!empty ( $post_data['post_author'] ) ) {
			$post_data['post_author'] = (int) $post_data['post_author'];
		} else {
			$post_data['post_author'] = (int) $post_data['user_ID'];
		}
	}

	if ( ! $update && isset( $post_data['user_ID'] ) && ( $post_data['post_author'] != $post_data['user_ID'] )
		 && ! current_user_can( $ptype->cap->edit_others_posts ) ) {

		if ( 'page' == $post_data['post_type'] )
			return new WP_Error( 'edit_others_pages', __( 'You are not allowed to create pages as this user.' ) );
		else
			return new WP_Error( 'edit_others_posts', __( 'You are not allowed to create posts as this user.' ) );
	}

	// What to do based on which button they pressed
	if ( isset($post_data['saveasdraft']) && '' != $post_data['saveasdraft'] )
		$post_data['post_status'] = 'draft';
	if ( isset($post_data['saveasprivate']) && '' != $post_data['saveasprivate'] )
		$post_data['post_status'] = 'private';
	if ( isset($post_data['publish']) && ( '' != $post_data['publish'] ) && ( !isset($post_data['post_status']) || $post_data['post_status'] != 'private' ) )
		$post_data['post_status'] = 'publish';
	if ( isset($post_data['advanced']) && '' != $post_data['advanced'] )
		$post_data['post_status'] = 'draft';
	if ( isset($post_data['pending']) && '' != $post_data['pending'] )
		$post_data['post_status'] = 'pending';

	if ( isset( $post_data['ID'] ) )
		$post_id = $post_data['ID'];
	else
		$post_id = false;
	$previous_status = $post_id ? get_post_field( 'post_status', $post_id ) : false;

	// Posts 'submitted for approval' present are submitted to $_POST the same as if they were being published.
	// Change status from 'publish' to 'pending' if user lacks permissions to publish or to resave published posts.
	if ( isset($post_data['post_status']) && ('publish' == $post_data['post_status'] && !current_user_can( $ptype->cap->publish_posts )) )
		if ( $previous_status != 'publish' || !current_user_can( 'edit_post', $post_id ) )
			$post_data['post_status'] = 'pending';

	if ( ! isset($post_data['post_status']) )
		$post_data['post_status'] = $previous_status;

	if (!isset( $post_data['comment_status'] ))
		$post_data['comment_status'] = 'closed';

	if (!isset( $post_data['ping_status'] ))
		$post_data['ping_status'] = 'closed';

	foreach ( array('aa', 'mm', 'jj', 'hh', 'mn') as $timeunit ) {
		if ( !empty( $post_data['hidden_' . $timeunit] ) && $post_data['hidden_' . $timeunit] != $post_data[$timeunit] ) {
			$post_data['edit_date'] = '1';
			break;
		}
	}

	if ( !empty( $post_data['edit_date'] ) ) {
		$aa = $post_data['aa'];
		$mm = $post_data['mm'];
		$jj = $post_data['jj'];
		$hh = $post_data['hh'];
		$mn = $post_data['mn'];
		$ss = $post_data['ss'];
		$aa = ($aa <= 0 ) ? date('Y') : $aa;
		$mm = ($mm <= 0 ) ? date('n') : $mm;
		$jj = ($jj > 31 ) ? 31 : $jj;
		$jj = ($jj <= 0 ) ? date('j') : $jj;
		$hh = ($hh > 23 ) ? $hh -24 : $hh;
		$mn = ($mn > 59 ) ? $mn -60 : $mn;
		$ss = ($ss > 59 ) ? $ss -60 : $ss;
		$post_data['post_date'] = sprintf( "%04d-%02d-%02d %02d:%02d:%02d", $aa, $mm, $jj, $hh, $mn, $ss );
		$valid_date = wp_checkdate( $mm, $jj, $aa, $post_data['post_date'] );
		if ( !$valid_date ) {
			return new WP_Error( 'invalid_date', __( 'Whoops, the provided date is invalid.' ) );
		}
		$post_data['post_date_gmt'] = get_gmt_from_date( $post_data['post_date'] );
	}

	return $post_data;
}
Exemplo n.º 7
0
 /**
  * Parse a query string and set query type booleans.
  *
  * @since 1.5.0
  * @since 4.2.0 Introduced the ability to order by specific clauses of a `$meta_query`, by passing the clause's
  *              array key to `$orderby`.
  * @since 4.4.0 Introduced `$post_name__in` and `$title` parameters. `$s` was updated to support excluded
  *              search terms, by prepending a hyphen.
  * @since 4.5.0 Removed the `$comments_popup` parameter.
  *              Introduced the `$comment_status` and `$ping_status` parameters.
  *              Introduced `RAND(x)` syntax for `$orderby`, which allows an integer seed value to random sorts.
  * @since 4.6.0 Added 'post_name__in' support for `$orderby`. Introduced the `$lazy_load_term_meta` argument.
  * @access public
  *
  * @param string|array $query {
  *     Optional. Array or string of Query parameters.
  *
  *     @type int          $attachment_id           Attachment post ID. Used for 'attachment' post_type.
  *     @type int|string   $author                  Author ID, or comma-separated list of IDs.
  *     @type string       $author_name             User 'user_nicename'.
  *     @type array        $author__in              An array of author IDs to query from.
  *     @type array        $author__not_in          An array of author IDs not to query from.
  *     @type bool         $cache_results           Whether to cache post information. Default true.
  *     @type int|string   $cat                     Category ID or comma-separated list of IDs (this or any children).
  *     @type array        $category__and           An array of category IDs (AND in).
  *     @type array        $category__in            An array of category IDs (OR in, no children).
  *     @type array        $category__not_in        An array of category IDs (NOT in).
  *     @type string       $category_name           Use category slug (not name, this or any children).
  *     @type string       $comment_status          Comment status.
  *     @type int          $comments_per_page       The number of comments to return per page.
  *                                                 Default 'comments_per_page' option.
  *     @type array        $date_query              An associative array of WP_Date_Query arguments.
  *                                                 See WP_Date_Query::__construct().
  *     @type int          $day                     Day of the month. Default empty. Accepts numbers 1-31.
  *     @type bool         $exact                   Whether to search by exact keyword. Default false.
  *     @type string|array $fields                  Which fields to return. Single field or all fields (string),
  *                                                 or array of fields. 'id=>parent' uses 'id' and 'post_parent'.
  *                                                 Default all fields. Accepts 'ids', 'id=>parent'.
  *     @type int          $hour                    Hour of the day. Default empty. Accepts numbers 0-23.
  *     @type int|bool     $ignore_sticky_posts     Whether to ignore sticky posts or not. Setting this to false
  *                                                 excludes stickies from 'post__in'. Accepts 1|true, 0|false.
  *                                                 Default 0|false.
  *     @type int          $m                       Combination YearMonth. Accepts any four-digit year and month
  *                                                 numbers 1-12. Default empty.
  *     @type string       $meta_compare            Comparison operator to test the 'meta_value'.
  *     @type string       $meta_key                Custom field key.
  *     @type array        $meta_query              An associative array of WP_Meta_Query arguments. See WP_Meta_Query.
  *     @type string       $meta_value              Custom field value.
  *     @type int          $meta_value_num          Custom field value number.
  *     @type int          $menu_order              The menu order of the posts.
  *     @type int          $monthnum                The two-digit month. Default empty. Accepts numbers 1-12.
  *     @type string       $name                    Post slug.
  *     @type bool         $nopaging                Show all posts (true) or paginate (false). Default false.
  *     @type bool         $no_found_rows           Whether to skip counting the total rows found. Enabling can improve
  *                                                 performance. Default false.
  *     @type int          $offset                  The number of posts to offset before retrieval.
  *     @type string       $order                   Designates ascending or descending order of posts. Default 'DESC'.
  *                                                 Accepts 'ASC', 'DESC'.
  *     @type string|array $orderby                 Sort retrieved posts by parameter. One or more options may be
  *                                                 passed. To use 'meta_value', or 'meta_value_num',
  *                                                 'meta_key=keyname' must be also be defined. To sort by a
  *                                                 specific `$meta_query` clause, use that clause's array key.
  *                                                 Default 'date'. Accepts 'none', 'name', 'author', 'date',
  *                                                 'title', 'modified', 'menu_order', 'parent', 'ID', 'rand',
  *                                                 'RAND(x)' (where 'x' is an integer seed value),
  *                                                 'comment_count', 'meta_value', 'meta_value_num', 'post__in',
  *                                                 'post_name__in', 'post_parent__in', and the array keys
  *                                                 of `$meta_query`.
  *     @type int          $p                       Post ID.
  *     @type int          $page                    Show the number of posts that would show up on page X of a
  *                                                 static front page.
  *     @type int          $paged                   The number of the current page.
  *     @type int          $page_id                 Page ID.
  *     @type string       $pagename                Page slug.
  *     @type string       $perm                    Show posts if user has the appropriate capability.
  *     @type string       $ping_status             Ping status.
  *     @type array        $post__in                An array of post IDs to retrieve, sticky posts will be included
  *     @type string       $post_mime_type          The mime type of the post. Used for 'attachment' post_type.
  *     @type array        $post__not_in            An array of post IDs not to retrieve. Note: a string of comma-
  *                                                 separated IDs will NOT work.
  *     @type int          $post_parent             Page ID to retrieve child pages for. Use 0 to only retrieve
  *                                                 top-level pages.
  *     @type array        $post_parent__in         An array containing parent page IDs to query child pages from.
  *     @type array        $post_parent__not_in     An array containing parent page IDs not to query child pages from.
  *     @type string|array $post_type               A post type slug (string) or array of post type slugs.
  *                                                 Default 'any' if using 'tax_query'.
  *     @type string|array $post_status             A post status (string) or array of post statuses.
  *     @type int          $posts_per_page          The number of posts to query for. Use -1 to request all posts.
  *     @type int          $posts_per_archive_page  The number of posts to query for by archive page. Overrides
  *                                                 'posts_per_page' when is_archive(), or is_search() are true.
  *     @type array        $post_name__in           An array of post slugs that results must match.
  *     @type string       $s                       Search keyword(s). Prepending a term with a hyphen will
  *                                                 exclude posts matching that term. Eg, 'pillow -sofa' will
  *                                                 return posts containing 'pillow' but not 'sofa'.
  *     @type int          $second                  Second of the minute. Default empty. Accepts numbers 0-60.
  *     @type bool         $sentence                Whether to search by phrase. Default false.
  *     @type bool         $suppress_filters        Whether to suppress filters. Default false.
  *     @type string       $tag                     Tag slug. Comma-separated (either), Plus-separated (all).
  *     @type array        $tag__and                An array of tag ids (AND in).
  *     @type array        $tag__in                 An array of tag ids (OR in).
  *     @type array        $tag__not_in             An array of tag ids (NOT in).
  *     @type int          $tag_id                  Tag id or comma-separated list of IDs.
  *     @type array        $tag_slug__and           An array of tag slugs (AND in).
  *     @type array        $tag_slug__in            An array of tag slugs (OR in). unless 'ignore_sticky_posts' is
  *                                                 true. Note: a string of comma-separated IDs will NOT work.
  *     @type array        $tax_query               An associative array of WP_Tax_Query arguments.
  *                                                 See WP_Tax_Query->queries.
  *     @type string       $title                   Post title.
  *     @type bool         $update_post_meta_cache  Whether to update the post meta cache. Default true.
  *     @type bool         $update_post_term_cache  Whether to update the post term cache. Default true.
  *     @type bool         $lazy_load_term_meta     Whether to lazy-load term meta. Setting to false will
  *                                                 disable cache priming for term meta, so that each
  *                                                 get_term_meta() call will hit the database.
  *                                                 Defaults to the value of `$update_post_term_cache`.
  *     @type int          $w                       The week number of the year. Default empty. Accepts numbers 0-53.
  *     @type int          $year                    The four-digit year. Default empty. Accepts any four-digit year.
  * }
  */
 public function parse_query($query = '')
 {
     if (!empty($query)) {
         $this->init();
         $this->query = $this->query_vars = wp_parse_args($query);
     } elseif (!isset($this->query)) {
         $this->query = $this->query_vars;
     }
     $this->query_vars = $this->fill_query_vars($this->query_vars);
     $qv =& $this->query_vars;
     $this->query_vars_changed = true;
     if (!empty($qv['robots'])) {
         $this->is_robots = true;
     }
     if (!is_scalar($qv['p']) || $qv['p'] < 0) {
         $qv['p'] = 0;
         $qv['error'] = '404';
     } else {
         $qv['p'] = intval($qv['p']);
     }
     $qv['page_id'] = absint($qv['page_id']);
     $qv['year'] = absint($qv['year']);
     $qv['monthnum'] = absint($qv['monthnum']);
     $qv['day'] = absint($qv['day']);
     $qv['w'] = absint($qv['w']);
     $qv['m'] = is_scalar($qv['m']) ? preg_replace('|[^0-9]|', '', $qv['m']) : '';
     $qv['paged'] = absint($qv['paged']);
     $qv['cat'] = preg_replace('|[^0-9,-]|', '', $qv['cat']);
     // comma separated list of positive or negative integers
     $qv['author'] = preg_replace('|[^0-9,-]|', '', $qv['author']);
     // comma separated list of positive or negative integers
     $qv['pagename'] = trim($qv['pagename']);
     $qv['name'] = trim($qv['name']);
     $qv['title'] = trim($qv['title']);
     if ('' !== $qv['hour']) {
         $qv['hour'] = absint($qv['hour']);
     }
     if ('' !== $qv['minute']) {
         $qv['minute'] = absint($qv['minute']);
     }
     if ('' !== $qv['second']) {
         $qv['second'] = absint($qv['second']);
     }
     if ('' !== $qv['menu_order']) {
         $qv['menu_order'] = absint($qv['menu_order']);
     }
     // Fairly insane upper bound for search string lengths.
     if (!is_scalar($qv['s']) || !empty($qv['s']) && strlen($qv['s']) > 1600) {
         $qv['s'] = '';
     }
     // Compat. Map subpost to attachment.
     if ('' != $qv['subpost']) {
         $qv['attachment'] = $qv['subpost'];
     }
     if ('' != $qv['subpost_id']) {
         $qv['attachment_id'] = $qv['subpost_id'];
     }
     $qv['attachment_id'] = absint($qv['attachment_id']);
     if ('' != $qv['attachment'] || !empty($qv['attachment_id'])) {
         $this->is_single = true;
         $this->is_attachment = true;
     } elseif ('' != $qv['name']) {
         $this->is_single = true;
     } elseif ($qv['p']) {
         $this->is_single = true;
     } elseif ('' !== $qv['hour'] && '' !== $qv['minute'] && '' !== $qv['second'] && '' != $qv['year'] && '' != $qv['monthnum'] && '' != $qv['day']) {
         // If year, month, day, hour, minute, and second are set, a single
         // post is being queried.
         $this->is_single = true;
     } elseif ('' != $qv['static'] || '' != $qv['pagename'] || !empty($qv['page_id'])) {
         $this->is_page = true;
         $this->is_single = false;
     } else {
         // Look for archive queries. Dates, categories, authors, search, post type archives.
         if (isset($this->query['s'])) {
             $this->is_search = true;
         }
         if ('' !== $qv['second']) {
             $this->is_time = true;
             $this->is_date = true;
         }
         if ('' !== $qv['minute']) {
             $this->is_time = true;
             $this->is_date = true;
         }
         if ('' !== $qv['hour']) {
             $this->is_time = true;
             $this->is_date = true;
         }
         if ($qv['day']) {
             if (!$this->is_date) {
                 $date = sprintf('%04d-%02d-%02d', $qv['year'], $qv['monthnum'], $qv['day']);
                 if ($qv['monthnum'] && $qv['year'] && !wp_checkdate($qv['monthnum'], $qv['day'], $qv['year'], $date)) {
                     $qv['error'] = '404';
                 } else {
                     $this->is_day = true;
                     $this->is_date = true;
                 }
             }
         }
         if ($qv['monthnum']) {
             if (!$this->is_date) {
                 if (12 < $qv['monthnum']) {
                     $qv['error'] = '404';
                 } else {
                     $this->is_month = true;
                     $this->is_date = true;
                 }
             }
         }
         if ($qv['year']) {
             if (!$this->is_date) {
                 $this->is_year = true;
                 $this->is_date = true;
             }
         }
         if ($qv['m']) {
             $this->is_date = true;
             if (strlen($qv['m']) > 9) {
                 $this->is_time = true;
             } elseif (strlen($qv['m']) > 7) {
                 $this->is_day = true;
             } elseif (strlen($qv['m']) > 5) {
                 $this->is_month = true;
             } else {
                 $this->is_year = true;
             }
         }
         if ('' != $qv['w']) {
             $this->is_date = true;
         }
         $this->query_vars_hash = false;
         $this->parse_tax_query($qv);
         foreach ($this->tax_query->queries as $tax_query) {
             if (!is_array($tax_query)) {
                 continue;
             }
             if (isset($tax_query['operator']) && 'NOT IN' != $tax_query['operator']) {
                 switch ($tax_query['taxonomy']) {
                     case 'category':
                         $this->is_category = true;
                         break;
                     case 'post_tag':
                         $this->is_tag = true;
                         break;
                     default:
                         $this->is_tax = true;
                 }
             }
         }
         unset($tax_query);
         if (empty($qv['author']) || $qv['author'] == '0') {
             $this->is_author = false;
         } else {
             $this->is_author = true;
         }
         if ('' != $qv['author_name']) {
             $this->is_author = true;
         }
         if (!empty($qv['post_type']) && !is_array($qv['post_type'])) {
             $post_type_obj = get_post_type_object($qv['post_type']);
             if (!empty($post_type_obj->has_archive)) {
                 $this->is_post_type_archive = true;
             }
         }
         if ($this->is_post_type_archive || $this->is_date || $this->is_author || $this->is_category || $this->is_tag || $this->is_tax) {
             $this->is_archive = true;
         }
     }
     if ('' != $qv['feed']) {
         $this->is_feed = true;
     }
     if ('' != $qv['embed']) {
         $this->is_embed = true;
     }
     if ('' != $qv['tb']) {
         $this->is_trackback = true;
     }
     if ('' != $qv['paged'] && intval($qv['paged']) > 1) {
         $this->is_paged = true;
     }
     // if we're previewing inside the write screen
     if ('' != $qv['preview']) {
         $this->is_preview = true;
     }
     if (is_admin()) {
         $this->is_admin = true;
     }
     if (false !== strpos($qv['feed'], 'comments-')) {
         $qv['feed'] = str_replace('comments-', '', $qv['feed']);
         $qv['withcomments'] = 1;
     }
     $this->is_singular = $this->is_single || $this->is_page || $this->is_attachment;
     if ($this->is_feed && (!empty($qv['withcomments']) || empty($qv['withoutcomments']) && $this->is_singular)) {
         $this->is_comment_feed = true;
     }
     if (!($this->is_singular || $this->is_archive || $this->is_search || $this->is_feed || defined('REST_REQUEST') && REST_REQUEST || $this->is_trackback || $this->is_404 || $this->is_admin || $this->is_robots)) {
         $this->is_home = true;
     }
     // Correct is_* for page_on_front and page_for_posts
     if ($this->is_home && 'page' == get_option('show_on_front') && get_option('page_on_front')) {
         $_query = wp_parse_args($this->query);
         // pagename can be set and empty depending on matched rewrite rules. Ignore an empty pagename.
         if (isset($_query['pagename']) && '' == $_query['pagename']) {
             unset($_query['pagename']);
         }
         unset($_query['embed']);
         if (empty($_query) || !array_diff(array_keys($_query), array('preview', 'page', 'paged', 'cpage'))) {
             $this->is_page = true;
             $this->is_home = false;
             $qv['page_id'] = get_option('page_on_front');
             // Correct <!--nextpage--> for page_on_front
             if (!empty($qv['paged'])) {
                 $qv['page'] = $qv['paged'];
                 unset($qv['paged']);
             }
         }
     }
     if ('' != $qv['pagename']) {
         $this->queried_object = get_page_by_path($qv['pagename']);
         if ($this->queried_object && 'attachment' == $this->queried_object->post_type) {
             if (preg_match("/^[^%]*%(?:postname)%/", get_option('permalink_structure'))) {
                 // See if we also have a post with the same slug
                 $post = get_page_by_path($qv['pagename'], OBJECT, 'post');
                 if ($post) {
                     $this->queried_object = $post;
                     $this->is_page = false;
                     $this->is_single = true;
                 }
             }
         }
         if (!empty($this->queried_object)) {
             $this->queried_object_id = (int) $this->queried_object->ID;
         } else {
             unset($this->queried_object);
         }
         if ('page' == get_option('show_on_front') && isset($this->queried_object_id) && $this->queried_object_id == get_option('page_for_posts')) {
             $this->is_page = false;
             $this->is_home = true;
             $this->is_posts_page = true;
         }
     }
     if ($qv['page_id']) {
         if ('page' == get_option('show_on_front') && $qv['page_id'] == get_option('page_for_posts')) {
             $this->is_page = false;
             $this->is_home = true;
             $this->is_posts_page = true;
         }
     }
     if (!empty($qv['post_type'])) {
         if (is_array($qv['post_type'])) {
             $qv['post_type'] = array_map('sanitize_key', $qv['post_type']);
         } else {
             $qv['post_type'] = sanitize_key($qv['post_type']);
         }
     }
     if (!empty($qv['post_status'])) {
         if (is_array($qv['post_status'])) {
             $qv['post_status'] = array_map('sanitize_key', $qv['post_status']);
         } else {
             $qv['post_status'] = preg_replace('|[^a-z0-9_,-]|', '', $qv['post_status']);
         }
     }
     if ($this->is_posts_page && (!isset($qv['withcomments']) || !$qv['withcomments'])) {
         $this->is_comment_feed = false;
     }
     $this->is_singular = $this->is_single || $this->is_page || $this->is_attachment;
     // Done correcting is_* for page_on_front and page_for_posts
     if ('404' == $qv['error']) {
         $this->set_404();
     }
     $this->is_embed = $this->is_embed && ($this->is_singular || $this->is_404);
     $this->query_vars_hash = md5(serialize($this->query_vars));
     $this->query_vars_changed = false;
     /**
      * Fires after the main query vars have been parsed.
      *
      * @since 1.5.0
      *
      * @param WP_Query &$this The WP_Query instance (passed by reference).
      */
     do_action_ref_array('parse_query', array(&$this));
 }
Exemplo n.º 8
0
 /**
  * Validates the given date_query values and triggers errors if something is not valid.
  *
  * Note that date queries with invalid date ranges are allowed to
  * continue (though of course no items will be found for impossible dates).
  * This method only generates debug notices for these cases.
  *
  * @since  4.1.0
  * @access public
  *
  * @param  array $date_query The date_query array.
  * @return bool  True if all values in the query are valid, false if one or more fail.
  */
 public function validate_date_values($date_query = array())
 {
     if (empty($date_query)) {
         return false;
     }
     $valid = true;
     /*
      * Validate 'before' and 'after' up front, then let the
      * validation routine continue to be sure that all invalid
      * values generate errors too.
      */
     if (array_key_exists('before', $date_query) && is_array($date_query['before'])) {
         $valid = $this->validate_date_values($date_query['before']);
     }
     if (array_key_exists('after', $date_query) && is_array($date_query['after'])) {
         $valid = $this->validate_date_values($date_query['after']);
     }
     // Array containing all min-max checks.
     $min_max_checks = array();
     // Days per year.
     if (array_key_exists('year', $date_query)) {
         /*
          * If a year exists in the date query, we can use it to get the days.
          * If multiple years are provided (as in a BETWEEN), use the first one.
          */
         if (is_array($date_query['year'])) {
             $_year = reset($date_query['year']);
         } else {
             $_year = $date_query['year'];
         }
         $max_days_of_year = date('z', mktime(0, 0, 0, 12, 31, $_year)) + 1;
     } else {
         // otherwise we use the max of 366 (leap-year)
         $max_days_of_year = 366;
     }
     $min_max_checks['dayofyear'] = array('min' => 1, 'max' => $max_days_of_year);
     // Days per week.
     $min_max_checks['dayofweek'] = array('min' => 1, 'max' => 7);
     // Days per week.
     $min_max_checks['dayofweek_iso'] = array('min' => 1, 'max' => 7);
     // Months per year.
     $min_max_checks['month'] = array('min' => 1, 'max' => 12);
     // Weeks per year.
     if (isset($_year)) {
         /*
          * If we have a specific year, use it to calculate number of weeks.
          * Note: the number of weeks in a year is the date in which Dec 28 appears.
          */
         $week_count = date('W', mktime(0, 0, 0, 12, 28, $_year));
     } else {
         // Otherwise set the week-count to a maximum of 53.
         $week_count = 53;
     }
     $min_max_checks['week'] = array('min' => 1, 'max' => $week_count);
     // Days per month.
     $min_max_checks['day'] = array('min' => 1, 'max' => 31);
     // Hours per day.
     $min_max_checks['hour'] = array('min' => 0, 'max' => 23);
     // Minutes per hour.
     $min_max_checks['minute'] = array('min' => 0, 'max' => 59);
     // Seconds per minute.
     $min_max_checks['second'] = array('min' => 0, 'max' => 59);
     // Concatenate and throw a notice for each invalid value.
     foreach ($min_max_checks as $key => $check) {
         if (!array_key_exists($key, $date_query)) {
             continue;
         }
         // Throw a notice for each failing value.
         foreach ((array) $date_query[$key] as $_value) {
             $is_between = $_value >= $check['min'] && $_value <= $check['max'];
             if (!is_numeric($_value) || !$is_between) {
                 $error = sprintf(__('Invalid value %1$s for %2$s. Expected value should be between %3$s and %4$s.'), '<code>' . esc_html($_value) . '</code>', '<code>' . esc_html($key) . '</code>', '<code>' . esc_html($check['min']) . '</code>', '<code>' . esc_html($check['max']) . '</code>');
                 _doing_it_wrong(__CLASS__, $error, '4.1.0');
                 $valid = false;
             }
         }
     }
     // If we already have invalid date messages, don't bother running through checkdate().
     if (!$valid) {
         return $valid;
     }
     $day_month_year_error_msg = '';
     $day_exists = array_key_exists('day', $date_query) && is_numeric($date_query['day']);
     $month_exists = array_key_exists('month', $date_query) && is_numeric($date_query['month']);
     $year_exists = array_key_exists('year', $date_query) && is_numeric($date_query['year']);
     if ($day_exists && $month_exists && $year_exists) {
         // 1. Checking day, month, year combination.
         if (!wp_checkdate($date_query['month'], $date_query['day'], $date_query['year'], sprintf('%s-%s-%s', $date_query['year'], $date_query['month'], $date_query['day']))) {
             /* translators: 1: year, 2: month, 3: day of month */
             $day_month_year_error_msg = sprintf(__('The following values do not describe a valid date: year %1$s, month %2$s, day %3$s.'), '<code>' . esc_html($date_query['year']) . '</code>', '<code>' . esc_html($date_query['month']) . '</code>', '<code>' . esc_html($date_query['day']) . '</code>');
             $valid = false;
         }
     } elseif ($day_exists && $month_exists) {
         /*
          * 2. checking day, month combination
          * We use 2012 because, as a leap year, it's the most permissive.
          */
         if (!wp_checkdate($date_query['month'], $date_query['day'], 2012, sprintf('2012-%s-%s', $date_query['month'], $date_query['day']))) {
             /* translators: 1: month, 2: day of month */
             $day_month_year_error_msg = sprintf(__('The following values do not describe a valid date: month %1$s, day %2$s.'), '<code>' . esc_html($date_query['month']) . '</code>', '<code>' . esc_html($date_query['day']) . '</code>');
             $valid = false;
         }
     }
     if (!empty($day_month_year_error_msg)) {
         _doing_it_wrong(__CLASS__, $day_month_year_error_msg, '4.1.0');
     }
     return $valid;
 }
Exemplo n.º 9
0
function pmxi_insert_post($postarr, $wp_error = false)
{
    global $wpdb;
    $user_id = get_current_user_id();
    $defaults = array('post_status' => 'draft', 'post_type' => 'post', 'post_author' => $user_id, 'ping_status' => get_option('default_ping_status'), 'post_parent' => 0, 'menu_order' => 0, 'to_ping' => '', 'pinged' => '', 'post_password' => '', 'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0, 'post_content' => '', 'post_title' => '');
    $postarr = wp_parse_args($postarr, $defaults);
    $postarr = sanitize_post($postarr, 'db');
    // export array as variables
    extract($postarr, EXTR_SKIP);
    // Are we updating or creating?
    $post_ID = 0;
    $update = false;
    if (!empty($ID)) {
        $update = true;
        // Get the post ID and GUID
        $post_ID = $ID;
        $post_before = get_post($post_ID);
        if (is_null($post_before)) {
            if ($wp_error) {
                return new WP_Error('invalid_post', __('Invalid post ID.'));
            }
            return 0;
        }
        $guid = get_post_field('guid', $post_ID);
        $previous_status = get_post_field('post_status', $ID);
    } else {
        $previous_status = 'new';
    }
    if (empty($post_type)) {
        $post_type = 'post';
    }
    if (empty($post_status)) {
        $post_status = 'draft';
    }
    // Make sure we set a valid category.
    if (empty($post_category) || 0 == count($post_category) || !is_array($post_category)) {
        // 'post' requires at least one category.
        if ('post' == $post_type && 'auto-draft' != $post_status) {
            $post_category = array(get_option('default_category'));
        } else {
            $post_category = array();
        }
    }
    if (empty($post_author)) {
        $post_author = $user_id;
    }
    // Create a valid post name. Drafts and pending posts are allowed to have an empty
    // post name.
    if (empty($post_name)) {
        if (!in_array($post_status, array('draft', 'pending', 'auto-draft'))) {
            $post_name = sanitize_title($post_title);
        } else {
            $post_name = '';
        }
    } else {
        // On updates, we need to check to see if it's using the old, fixed sanitization context.
        $check_name = sanitize_title($post_name, '', 'old-save');
        if ($update && strtolower(urlencode($post_name)) == $check_name && get_post_field('post_name', $ID) == $check_name) {
            $post_name = $check_name;
        } else {
            // new post, or slug has changed.
            $post_name = sanitize_title($post_name);
        }
    }
    // If the post date is empty (due to having been new or a draft) and status is not 'draft' or 'pending', set date to now
    if (empty($post_date) || '0000-00-00 00:00:00' == $post_date) {
        $post_date = current_time('mysql');
    }
    // validate the date
    $mm = substr($post_date, 5, 2);
    $jj = substr($post_date, 8, 2);
    $aa = substr($post_date, 0, 4);
    $valid_date = wp_checkdate($mm, $jj, $aa, $post_date);
    if (!$valid_date) {
        if ($wp_error) {
            return new WP_Error('invalid_date', __('Whoops, the provided date is invalid.'));
        } else {
            return 0;
        }
    }
    if (empty($post_date_gmt) || '0000-00-00 00:00:00' == $post_date_gmt) {
        if (!in_array($post_status, array('draft', 'pending', 'auto-draft'))) {
            $post_date_gmt = get_gmt_from_date($post_date);
        } else {
            $post_date_gmt = '0000-00-00 00:00:00';
        }
    }
    if ($update || '0000-00-00 00:00:00' == $post_date) {
        $post_modified = current_time('mysql');
        $post_modified_gmt = current_time('mysql', 1);
    } else {
        $post_modified = $post_date;
        $post_modified_gmt = $post_date_gmt;
    }
    if ('publish' == $post_status) {
        $now = gmdate('Y-m-d H:i:59');
        if (mysql2date('U', $post_date_gmt, false) > mysql2date('U', $now, false)) {
            $post_status = 'future';
        }
    } elseif ('future' == $post_status) {
        $now = gmdate('Y-m-d H:i:59');
        if (mysql2date('U', $post_date_gmt, false) <= mysql2date('U', $now, false)) {
            $post_status = 'publish';
        }
    }
    if (empty($comment_status)) {
        if ($update) {
            $comment_status = 'closed';
        } else {
            $comment_status = get_option('default_comment_status');
        }
    }
    if (empty($ping_status)) {
        $ping_status = get_option('default_ping_status');
    }
    if (isset($to_ping)) {
        $to_ping = sanitize_trackback_urls($to_ping);
    } else {
        $to_ping = '';
    }
    if (!isset($pinged)) {
        $pinged = '';
    }
    if (isset($post_parent)) {
        $post_parent = (int) $post_parent;
    } else {
        $post_parent = 0;
    }
    // Check the post_parent to see if it will cause a hierarchy loop
    $post_parent = apply_filters('wp_insert_post_parent', $post_parent, $post_ID, compact(array_keys($postarr)), $postarr);
    if (isset($menu_order)) {
        $menu_order = (int) $menu_order;
    } else {
        $menu_order = 0;
    }
    $post_name = wp_unique_post_slug($post_name, $post_ID, $post_status, $post_type, $post_parent);
    // expected_slashed (everything!)
    $data = compact(array('post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_content_filtered', 'post_title', 'post_excerpt', 'post_status', 'post_type', 'comment_status', 'ping_status', 'post_password', 'post_name', 'to_ping', 'pinged', 'post_modified', 'post_modified_gmt', 'post_parent', 'menu_order', 'guid'));
    $data = wp_unslash($data);
    $where = array('ID' => $post_ID);
    if ($update) {
        if (false === $wpdb->update($wpdb->posts, $data, $where)) {
            if ($wp_error) {
                return new WP_Error('db_update_error', __('Could not update post in the database'), $wpdb->last_error);
            } else {
                return 0;
            }
        }
    } else {
        if (isset($post_mime_type)) {
            $data['post_mime_type'] = wp_unslash($post_mime_type);
        }
        // This isn't in the update
        if (false === $wpdb->insert($wpdb->posts, $data)) {
            if ($wp_error) {
                return new WP_Error('db_insert_error', __('Could not insert post into the database'), $wpdb->last_error);
            } else {
                return 0;
            }
        }
        $post_ID = (int) $wpdb->insert_id;
        // use the newly generated $post_ID
        $where = array('ID' => $post_ID);
    }
    if (isset($tags_input) && is_object_in_taxonomy($post_type, 'post_tag')) {
        wp_set_post_tags($post_ID, $tags_input);
    }
    $current_guid = get_post_field('guid', $post_ID);
    // Set GUID
    if (!$update && '' == $current_guid) {
        $wpdb->update($wpdb->posts, array('guid' => get_permalink($post_ID)), $where);
    }
    return $post_ID;
}
Exemplo n.º 10
0
/**
 * Save additional data for adverts custom post type
 * 
 * @uses Adverts_Form 
 * 
 * @param int $ID Post ID
 * @param WP_Post $post
 * @since 0.1
 * @return null
 */
function adverts_save_post($ID = false, $post = false)
{
    global $pagenow;
    if (!in_array($pagenow, array("post.php", "post-new.php"))) {
        return $ID;
    }
    $nonce = 'product_price_box_content_nonce';
    if (!isset($_POST[$nonce]) || !wp_verify_nonce($_POST[$nonce], basename(__FILE__))) {
        //return $ID;
    }
    /* Get the post type object. */
    $post_type = get_post_type_object($post->post_type);
    /* Check if the current user has permission to edit the post. */
    if (!current_user_can($post_type->cap->edit_post, $ID)) {
        return $ID;
    }
    if (!$post->post_type == 'advert') {
        return $ID;
    }
    if (defined("DOING_AJAX") && DOING_AJAX) {
        return $ID;
    }
    /* Save expiration date in DB */
    if (!empty($_POST)) {
        $current_exp_date = get_post_meta($ID, "_expiration_date", true);
        $edit_date = empty($current_exp_date);
    } else {
        $edit_date = false;
    }
    foreach (array('aa', 'mm', 'jj', 'hh', 'mn') as $timeunit) {
        if (!empty($_POST['adverts_hidden_' . $timeunit]) && $_POST['adverts_hidden_' . $timeunit] != $_POST['adverts_' . $timeunit]) {
            $edit_date = 1;
            break;
        }
    }
    if (isset($_POST["never_expires"]) && $_POST["never_expires"] == "1") {
        // Advert does not expire, unset expiration date
        delete_post_meta($ID, "_expiration_date");
    } else {
        if ($edit_date) {
            // Build expiration date, based on submitted $_POST data
            $aa = isset($_POST['adverts_aa']) ? $_POST['adverts_aa'] : null;
            $mm = isset($_POST['adverts_mm']) ? $_POST['adverts_mm'] : null;
            $jj = isset($_POST['adverts_jj']) ? $_POST['adverts_jj'] : null;
            $hh = isset($_POST['adverts_hh']) ? $_POST['adverts_hh'] : null;
            $mn = isset($_POST['adverts_mn']) ? $_POST['adverts_mn'] : null;
            $ss = isset($_POST['adverts_ss']) ? $_POST['adverts_ss'] : null;
            $aa = $aa <= 0 ? date('Y') : $aa;
            $mm = $mm <= 0 ? date('n') : $mm;
            $jj = $jj > 31 ? 31 : $jj;
            $jj = $jj <= 0 ? date('j') : $jj;
            $hh = $hh > 23 ? $hh - 24 : $hh;
            $mn = $mn > 59 ? $mn - 60 : $mn;
            $ss = $ss > 59 ? $ss - 60 : $ss;
            $exp_date = sprintf("%04d-%02d-%02d %02d:%02d:%02d", $aa, $mm, $jj, $hh, $mn, $ss);
            $valid_date = wp_checkdate($mm, $jj, $aa, $exp_date);
            if (!$valid_date) {
                return new WP_Error('invalid_date', __('Whoops, the provided date is invalid.'));
            }
            //$exp_date_gmt = get_gmt_from_date( $exp_date );
            //
            // Save expiration date in DB
            update_post_meta($ID, "_expiration_date", strtotime($exp_date));
        }
    }
    $form = new Adverts_Form();
    $form->load(Adverts::instance()->get("form"));
    $form->bind(stripslashes_deep($_POST));
    foreach ($form->get_fields() as $field) {
        if (isset($field["value"])) {
            $meta_old = get_post_meta($ID, $field["name"]);
            if ($field["value"] == '') {
                delete_post_meta($ID, $field["name"]);
            } else {
                update_post_meta($ID, $field["name"], $field["value"]);
            }
        }
    }
}
Exemplo n.º 11
0
 /**
  * Save slider details. Callback function for action save_post_{post_type}
  * @param int $post_id
  * @param object $post
  * @param bool $update
  */
 public function save_slider($post_id, $post, $update)
 {
     if (!current_user_can('edit_fa_items', $post_id)) {
         wp_die(-1);
     }
     // check for the nonce presence
     if (!isset($_POST['fa-slider-settings-nonce'])) {
         return;
     }
     check_admin_referer('fa-slider-options-save', 'fa-slider-settings-nonce');
     // process expiration date
     $process_date = false;
     foreach (array('exp_mm', 'exp_dd', 'exp_yy', 'exp_hh', 'exp_ii') as $timeunit) {
         if ($_POST[$timeunit] != $_POST['curr_' . $timeunit]) {
             $process_date = true;
             break;
         }
     }
     // if date should be processed
     if ($process_date) {
         $date = $_POST['exp_yy'] . '-' . $_POST['exp_mm'] . '-' . $_POST['exp_dd'];
         if (wp_checkdate($_POST['exp_mm'], $_POST['exp_dd'], $_POST['exp_yy'], $date)) {
             $expiration_date = $date . ' ' . $_POST['exp_hh'] . ':' . $_POST['exp_ii'] . ':' . $_POST['exp_ss'];
             $_POST['slider']['expires'] = $expiration_date;
             // check if currently set up date is less than post date
             if (strtotime($expiration_date) < time() && parent::get_status_expired() != $post->post_status) {
                 $args = array('ID' => $post_id, 'post_status' => parent::get_status_expired());
                 // remove the action to avoid a loop
                 remove_action('save_post_' . parent::get_type_slider(), array($this, 'save_slider'));
                 wp_update_post($args);
             }
         }
     }
     // remove the expiration date if set
     if (isset($_POST['exp_ignore'])) {
         $_POST['slider']['expires'] = '0000-00-00 00:00:00';
     }
     // do not allow no post type specified for posts
     if (!isset($_POST['slides']['post_type'])) {
         $_POST['slides']['post_type'][] = 'post';
     }
     // allow no categories specified (allow all categories if none specified)
     if (!isset($_POST['slides']['tags'])) {
         $_POST['slides']['tags'] = array();
     }
     // allow empty content on mixed posts
     if (!isset($_POST['slides']['posts'])) {
         $_POST['slides']['posts'] = array();
     }
     // allow empty content on images
     if (!isset($_POST['slides']['images'])) {
         $_POST['slides']['images'] = array();
     }
     // set the slider color
     if (isset($_POST['theme']['active'])) {
         $theme = $_POST['theme']['active'];
         // process the layout variation if available
         if (isset($_POST['layout']['class'][$theme])) {
             $_POST['layout']['class'] = $_POST['layout']['class'][$theme];
         } else {
             $_POST['layout']['class'] = '';
         }
         // set the color
         if (isset($_POST['theme_color'][$theme])) {
             $_POST['theme']['color'] = $_POST['theme_color'][$theme];
         } else {
             $_POST['theme']['color'] = '';
         }
     }
     // allow empty on display categories
     if (!isset($_POST['display']['tax'])) {
         $_POST['display']['tax'] = array();
     }
     // allow empty on display posts
     if (!isset($_POST['display']['posts'])) {
         $_POST['display']['posts'] = array();
     }
     // process the publish areas
     $areas = fa_get_options('hooks');
     $set = isset($_POST['slider_area']) ? $_POST['slider_area'] : array();
     foreach ($areas as $area_id => $area) {
         if (in_array($area_id, $set)) {
             if (!in_array($post_id, $area['sliders'])) {
                 $areas[$area_id]['sliders'][] = $post_id;
             }
         } else {
             if (in_array($post_id, $area['sliders'])) {
                 $key = array_search($post_id, $area['sliders']);
                 if (false !== $key) {
                     unset($areas[$area_id]['sliders'][$key]);
                 }
             }
         }
     }
     fa_update_options('hooks', $areas);
     // update the slider options
     fa_update_slider_options($post_id, $_POST);
     /**
      * Action on slider save
      * @param int $post_id - ID of post being saved
      * @param object $post - object of post being saved
      * @param bool $update - is update or new post
      * @param array - values send from form
      */
     do_action('fa-save-slider', $post_id, $post, $update, $_POST);
 }
Exemplo n.º 12
0
 * is not 'draft' or 'pending', set date to now.
 */
if (empty($postarr['post_date']) || '0000-00-00 00:00:00' == $postarr['post_date']) {
    if (empty($postarr['post_date_gmt']) || '0000-00-00 00:00:00' == $postarr['post_date_gmt']) {
        $post_date = current_time('mysql');
    } else {
        $post_date = get_date_from_gmt($postarr['post_date_gmt']);
    }
} else {
    $post_date = $postarr['post_date'];
}
// Validate the date.
$mm = substr($post_date, 5, 2);
$jj = substr($post_date, 8, 2);
$aa = substr($post_date, 0, 4);
$valid_date = wp_checkdate($mm, $jj, $aa, $post_date);
if (!$valid_date) {
    if ($wp_error) {
        $result['status_msg'] .= 'Whoops, the provided date is invalid.';
        echo json_encode($result);
        exit(-1);
    } else {
        $result['status_msg'] .= '时间出错';
        echo json_encode($result);
        exit(-1);
    }
}
if (empty($postarr['post_date_gmt']) || '0000-00-00 00:00:00' == $postarr['post_date_gmt']) {
    if (!in_array($post_status, array('draft', 'pending', 'auto-draft'))) {
        $post_date_gmt = get_gmt_from_date($post_date);
    } else {
 /**
  * Save a temporary movie for submitted title.
  * 
  * This is used to save movies submitted from a list before any
  * alteration is made by user. Posts will be kept as 'import-draft'
  * for 24 hours and then destroyed on the next plugin init.
  *
  * @since    1.0
  * 
  * @param    string    $title Movie title.
  * 
  * @return   int       Newly created post ID if everything worked, 0 if no post created.
  */
 public static function import_movie($movie)
 {
     $post_date = current_time('mysql');
     $post_date = wp_checkdate(substr($post_date, 5, 2), substr($post_date, 8, 2), substr($post_date, 0, 4), $post_date);
     $post_date_gmt = get_gmt_from_date($post_date);
     $post_author = get_current_user_id();
     $post_content = '';
     $post_excerpt = '';
     $post_title = $movie['movietitle'];
     $page = get_page_by_title($post_title, OBJECT, 'movie');
     if (!is_null($page)) {
         $message = sprintf('%s − <span class="edit"><a href="%s">%s</a> |</span> <span class="view"><a href="%s">%s</a></span>', sprintf(__('Movie "%s" already imported.', 'wpmovielibrary'), "<em>" . get_the_title($page->ID) . "</em>"), get_edit_post_link($page->ID), __('Edit', 'wpmovielibrary'), get_permalink($page->ID), __('View', 'wpmovielibrary'));
         return new WP_Error('existing_movie', $message);
     }
     $posts = array('ID' => '', 'comment_status' => 'closed', 'ping_status' => 'closed', 'post_author' => $post_author, 'post_content' => $post_content, 'post_excerpt' => $post_excerpt, 'post_date' => $post_date, 'post_date_gmt' => $post_date_gmt, 'post_name' => sanitize_title($post_title), 'post_status' => 'import-draft', 'post_title' => $post_title, 'post_type' => 'movie');
     $import = wp_insert_post($posts);
     return $import;
 }
 /**
  * prepare the ad post type to be saved
  *
  * @since 1.0.0
  * @param int $post_id id of the post
  * @todo handling this more dynamic based on ad type
  */
 public function save_ad($post_id)
 {
     // only use for ads, no other post type
     if (!isset($_POST['post_type']) || $this->post_type != $_POST['post_type'] || !isset($_POST['advanced_ad']['type'])) {
         return;
     }
     // don’t do this on revisions
     if (wp_is_post_revision($post_id)) {
         return;
     }
     // get ad object
     $ad = new Advanced_Ads_Ad($post_id);
     if (!$ad instanceof Advanced_Ads_Ad) {
         return;
     }
     // filter to allow change of submitted ad settings
     $_POST['advanced_ad'] = apply_filters('advanced-ads-ad-settings-pre-save', $_POST['advanced_ad']);
     $ad->type = $_POST['advanced_ad']['type'];
     if (isset($_POST['advanced_ad']['output'])) {
         $ad->set_option('output', $_POST['advanced_ad']['output']);
     } else {
         $ad->set_option('output', array());
     }
     /**
      * deprecated since introduction of "visitors" in 1.5.4
      */
     if (isset($_POST['advanced_ad']['visitor'])) {
         $ad->set_option('visitor', $_POST['advanced_ad']['visitor']);
     } else {
         $ad->set_option('visitor', array());
     }
     // visitor conditions
     if (isset($_POST['advanced_ad']['visitors'])) {
         $ad->set_option('visitors', $_POST['advanced_ad']['visitors']);
     } else {
         $ad->set_option('visitors', array());
     }
     // save size
     $ad->width = 0;
     if (isset($_POST['advanced_ad']['width'])) {
         $ad->width = absint($_POST['advanced_ad']['width']);
     }
     $ad->height = 0;
     if (isset($_POST['advanced_ad']['height'])) {
         $ad->height = absint($_POST['advanced_ad']['height']);
     }
     if (!empty($_POST['advanced_ad']['description'])) {
         $ad->description = esc_textarea($_POST['advanced_ad']['description']);
     } else {
         $ad->description = '';
     }
     if (!empty($_POST['advanced_ad']['content'])) {
         $ad->content = $_POST['advanced_ad']['content'];
     } else {
         $ad->content = '';
     }
     if (!empty($_POST['advanced_ad']['conditions'])) {
         $ad->conditions = $_POST['advanced_ad']['conditions'];
     } else {
         $ad->conditions = array();
     }
     // prepare expiry date
     if (isset($_POST['advanced_ad']['expiry_date']['enabled'])) {
         $year = absint($_POST['advanced_ad']['expiry_date']['year']);
         $month = absint($_POST['advanced_ad']['expiry_date']['month']);
         $day = absint($_POST['advanced_ad']['expiry_date']['day']);
         $hour = absint($_POST['advanced_ad']['expiry_date']['hour']);
         $minute = absint($_POST['advanced_ad']['expiry_date']['minute']);
         $expiration_date = sprintf("%04d-%02d-%02d %02d:%02d:%02d", $year, $month, $day, $hour, $minute, '00');
         $valid_date = wp_checkdate($month, $day, $year, $expiration_date);
         if (!$valid_date) {
             $ad->expiry_date = 0;
         } else {
             // as PHP 5.2 has not reliable 'u' option need to calculate timestamps this way
             $gmDate = get_gmt_from_date($expiration_date, 'Y-m-d-H-i');
             list($year, $month, $day, $hour, $minute) = explode('-', $gmDate);
             $ad->expiry_date = gmmktime($hour, $minute, 0, $month, $day, $year);
         }
     } else {
         $ad->expiry_date = 0;
     }
     $ad->save();
 }
Exemplo n.º 15
0
 /**
  * Check Gregorian date.
  * 
  * @param  string $time  Date to check
  * @return boolean       True if date is valid
  * @see /wp-includes/post.php
  */
 public function check_date($time)
 {
     /**
      * Validate the date
      * 
      * @see /wp-includes/post.php
      */
     $mm = substr($time, 5, 2);
     $jj = substr($time, 8, 2);
     $aa = substr($time, 0, 4);
     $valid_date = wp_checkdate($mm, $jj, $aa, $time);
     return $valid_date;
 }
Exemplo n.º 16
0
/**
 * Redirects incoming links to the proper URL based on the site url.
 *
 * Search engines consider www.somedomain.com and somedomain.com to be two
 * different URLs when they both go to the same location. This SEO enhancement
 * prevents penalty for duplicate content by redirecting all incoming links to
 * one or the other.
 *
 * Prevents redirection for feeds, trackbacks, searches, comment popup, and
 * admin URLs. Does not redirect on non-pretty-permalink-supporting IIS 7+,
 * page/post previews, WP admin, Trackbacks, robots.txt, searches, or on POST
 * requests.
 *
 * Will also attempt to find the correct link when a user enters a URL that does
 * not exist based on exact WordPress query. Will instead try to parse the URL
 * or query in an attempt to figure the correct page to go to.
 *
 * @since 2.3.0
 *
 * @global WP_Rewrite $wp_rewrite
 * @global bool $is_IIS
 * @global WP_Query $wp_query
 * @global wpdb $wpdb WordPress database abstraction object.
 *
 * @param string $requested_url Optional. The URL that was requested, used to
 *		figure if redirect is needed.
 * @param bool $do_redirect Optional. Redirect to the new URL.
 * @return string|void The string of the URL, if redirect needed.
 */
function redirect_canonical($requested_url = null, $do_redirect = true)
{
    global $wp_rewrite, $is_IIS, $wp_query, $wpdb, $wp;
    if (isset($_SERVER['REQUEST_METHOD']) && !in_array(strtoupper($_SERVER['REQUEST_METHOD']), array('GET', 'HEAD'))) {
        return;
    }
    // If we're not in wp-admin and the post has been published and preview nonce
    // is non-existent or invalid then no need for preview in query
    if (is_preview() && get_query_var('p') && 'publish' == get_post_status(get_query_var('p'))) {
        if (!isset($_GET['preview_id']) || !isset($_GET['preview_nonce']) || !wp_verify_nonce($_GET['preview_nonce'], 'post_preview_' . (int) $_GET['preview_id'])) {
            $wp_query->is_preview = false;
        }
    }
    if (is_trackback() || is_search() || is_comments_popup() || is_admin() || is_preview() || is_robots() || $is_IIS && !iis7_supports_permalinks()) {
        return;
    }
    if (!$requested_url && isset($_SERVER['HTTP_HOST'])) {
        // build the URL in the address bar
        $requested_url = is_ssl() ? 'https://' : 'http://';
        $requested_url .= $_SERVER['HTTP_HOST'];
        $requested_url .= $_SERVER['REQUEST_URI'];
    }
    $original = @parse_url($requested_url);
    if (false === $original) {
        return;
    }
    $redirect = $original;
    $redirect_url = false;
    // Notice fixing
    if (!isset($redirect['path'])) {
        $redirect['path'] = '';
    }
    if (!isset($redirect['query'])) {
        $redirect['query'] = '';
    }
    // If the original URL ended with non-breaking spaces, they were almost
    // certainly inserted by accident. Let's remove them, so the reader doesn't
    // see a 404 error with no obvious cause.
    $redirect['path'] = preg_replace('|(%C2%A0)+$|i', '', $redirect['path']);
    // It's not a preview, so remove it from URL
    if (get_query_var('preview')) {
        $redirect['query'] = remove_query_arg('preview', $redirect['query']);
    }
    if (is_feed() && ($id = get_query_var('p'))) {
        if ($redirect_url = get_post_comments_feed_link($id, get_query_var('feed'))) {
            $redirect['query'] = _remove_qs_args_if_not_in_url($redirect['query'], array('p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type', 'feed'), $redirect_url);
            $redirect['path'] = parse_url($redirect_url, PHP_URL_PATH);
        }
    }
    if (is_singular() && 1 > $wp_query->post_count && ($id = get_query_var('p'))) {
        $vars = $wpdb->get_results($wpdb->prepare("SELECT post_type, post_parent FROM {$wpdb->posts} WHERE ID = %d", $id));
        if (isset($vars[0]) && ($vars = $vars[0])) {
            if ('revision' == $vars->post_type && $vars->post_parent > 0) {
                $id = $vars->post_parent;
            }
            if ($redirect_url = get_permalink($id)) {
                $redirect['query'] = _remove_qs_args_if_not_in_url($redirect['query'], array('p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type'), $redirect_url);
            }
        }
    }
    // These tests give us a WP-generated permalink
    if (is_404()) {
        // Redirect ?page_id, ?p=, ?attachment_id= to their respective url's
        $id = max(get_query_var('p'), get_query_var('page_id'), get_query_var('attachment_id'));
        if ($id && ($redirect_post = get_post($id))) {
            $post_type_obj = get_post_type_object($redirect_post->post_type);
            if ($post_type_obj->public) {
                $redirect_url = get_permalink($redirect_post);
                $redirect['query'] = _remove_qs_args_if_not_in_url($redirect['query'], array('p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type'), $redirect_url);
            }
        }
        if (get_query_var('day') && get_query_var('monthnum') && get_query_var('year')) {
            $year = get_query_var('year');
            $month = get_query_var('monthnum');
            $day = get_query_var('day');
            $date = sprintf('%04d-%02d-%02d', $year, $month, $day);
            if (!wp_checkdate($month, $day, $year, $date)) {
                $redirect_url = get_month_link($year, $month);
                $redirect['query'] = _remove_qs_args_if_not_in_url($redirect['query'], array('year', 'monthnum', 'day'), $redirect_url);
            }
        } elseif (get_query_var('monthnum') && get_query_var('year') && 12 < get_query_var('monthnum')) {
            $redirect_url = get_year_link(get_query_var('year'));
            $redirect['query'] = _remove_qs_args_if_not_in_url($redirect['query'], array('year', 'monthnum'), $redirect_url);
        }
        if (!$redirect_url) {
            if ($redirect_url = redirect_guess_404_permalink()) {
                $redirect['query'] = _remove_qs_args_if_not_in_url($redirect['query'], array('page', 'feed', 'p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type'), $redirect_url);
            }
        }
        if (get_query_var('page') && $wp_query->post && false !== strpos($wp_query->post->post_content, '<!--nextpage-->')) {
            $redirect['path'] = rtrim($redirect['path'], (int) get_query_var('page') . '/');
            $redirect['query'] = remove_query_arg('page', $redirect['query']);
            $redirect_url = get_permalink($wp_query->post->ID);
        }
    } elseif (is_object($wp_rewrite) && $wp_rewrite->using_permalinks()) {
        // rewriting of old ?p=X, ?m=2004, ?m=200401, ?m=20040101
        if (is_attachment() && !array_diff(array_keys($wp->query_vars), array('attachment', 'attachment_id')) && !$redirect_url) {
            if (!empty($_GET['attachment_id'])) {
                $redirect_url = get_attachment_link(get_query_var('attachment_id'));
                if ($redirect_url) {
                    $redirect['query'] = remove_query_arg('attachment_id', $redirect['query']);
                }
            } else {
                $redirect_url = get_attachment_link();
            }
        } elseif (is_single() && !empty($_GET['p']) && !$redirect_url) {
            if ($redirect_url = get_permalink(get_query_var('p'))) {
                $redirect['query'] = remove_query_arg(array('p', 'post_type'), $redirect['query']);
            }
        } elseif (is_single() && !empty($_GET['name']) && !$redirect_url) {
            if ($redirect_url = get_permalink($wp_query->get_queried_object_id())) {
                $redirect['query'] = remove_query_arg('name', $redirect['query']);
            }
        } elseif (is_page() && !empty($_GET['page_id']) && !$redirect_url) {
            if ($redirect_url = get_permalink(get_query_var('page_id'))) {
                $redirect['query'] = remove_query_arg('page_id', $redirect['query']);
            }
        } elseif (is_page() && !is_feed() && isset($wp_query->queried_object) && 'page' == get_option('show_on_front') && $wp_query->queried_object->ID == get_option('page_on_front') && !$redirect_url) {
            $redirect_url = home_url('/');
        } elseif (is_home() && !empty($_GET['page_id']) && 'page' == get_option('show_on_front') && get_query_var('page_id') == get_option('page_for_posts') && !$redirect_url) {
            if ($redirect_url = get_permalink(get_option('page_for_posts'))) {
                $redirect['query'] = remove_query_arg('page_id', $redirect['query']);
            }
        } elseif (!empty($_GET['m']) && (is_year() || is_month() || is_day())) {
            $m = get_query_var('m');
            switch (strlen($m)) {
                case 4:
                    // Yearly
                    $redirect_url = get_year_link($m);
                    break;
                case 6:
                    // Monthly
                    $redirect_url = get_month_link(substr($m, 0, 4), substr($m, 4, 2));
                    break;
                case 8:
                    // Daily
                    $redirect_url = get_day_link(substr($m, 0, 4), substr($m, 4, 2), substr($m, 6, 2));
                    break;
            }
            if ($redirect_url) {
                $redirect['query'] = remove_query_arg('m', $redirect['query']);
            }
            // now moving on to non ?m=X year/month/day links
        } elseif (is_day() && get_query_var('year') && get_query_var('monthnum') && !empty($_GET['day'])) {
            if ($redirect_url = get_day_link(get_query_var('year'), get_query_var('monthnum'), get_query_var('day'))) {
                $redirect['query'] = remove_query_arg(array('year', 'monthnum', 'day'), $redirect['query']);
            }
        } elseif (is_month() && get_query_var('year') && !empty($_GET['monthnum'])) {
            if ($redirect_url = get_month_link(get_query_var('year'), get_query_var('monthnum'))) {
                $redirect['query'] = remove_query_arg(array('year', 'monthnum'), $redirect['query']);
            }
        } elseif (is_year() && !empty($_GET['year'])) {
            if ($redirect_url = get_year_link(get_query_var('year'))) {
                $redirect['query'] = remove_query_arg('year', $redirect['query']);
            }
        } elseif (is_author() && !empty($_GET['author']) && preg_match('|^[0-9]+$|', $_GET['author'])) {
            $author = get_userdata(get_query_var('author'));
            if (false !== $author && $wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->posts} WHERE {$wpdb->posts}.post_author = %d AND {$wpdb->posts}.post_status = 'publish' LIMIT 1", $author->ID))) {
                if ($redirect_url = get_author_posts_url($author->ID, $author->user_nicename)) {
                    $redirect['query'] = remove_query_arg('author', $redirect['query']);
                }
            }
        } elseif (is_category() || is_tag() || is_tax()) {
            // Terms (Tags/categories)
            $term_count = 0;
            foreach ($wp_query->tax_query->queried_terms as $tax_query) {
                $term_count += count($tax_query['terms']);
            }
            $obj = $wp_query->get_queried_object();
            if ($term_count <= 1 && !empty($obj->term_id) && ($tax_url = get_term_link((int) $obj->term_id, $obj->taxonomy)) && !is_wp_error($tax_url)) {
                if (!empty($redirect['query'])) {
                    // Strip taxonomy query vars off the url.
                    $qv_remove = array('term', 'taxonomy');
                    if (is_category()) {
                        $qv_remove[] = 'category_name';
                        $qv_remove[] = 'cat';
                    } elseif (is_tag()) {
                        $qv_remove[] = 'tag';
                        $qv_remove[] = 'tag_id';
                    } else {
                        // Custom taxonomies will have a custom query var, remove those too:
                        $tax_obj = get_taxonomy($obj->taxonomy);
                        if (false !== $tax_obj->query_var) {
                            $qv_remove[] = $tax_obj->query_var;
                        }
                    }
                    $rewrite_vars = array_diff(array_keys($wp_query->query), array_keys($_GET));
                    if (!array_diff($rewrite_vars, array_keys($_GET))) {
                        // Check to see if all the Query vars are coming from the rewrite, none are set via $_GET
                        $redirect['query'] = remove_query_arg($qv_remove, $redirect['query']);
                        //Remove all of the per-tax qv's
                        // Create the destination url for this taxonomy
                        $tax_url = parse_url($tax_url);
                        if (!empty($tax_url['query'])) {
                            // Taxonomy accessible via ?taxonomy=..&term=.. or any custom qv..
                            parse_str($tax_url['query'], $query_vars);
                            $redirect['query'] = add_query_arg($query_vars, $redirect['query']);
                        } else {
                            // Taxonomy is accessible via a "pretty-URL"
                            $redirect['path'] = $tax_url['path'];
                        }
                    } else {
                        // Some query vars are set via $_GET. Unset those from $_GET that exist via the rewrite
                        foreach ($qv_remove as $_qv) {
                            if (isset($rewrite_vars[$_qv])) {
                                $redirect['query'] = remove_query_arg($_qv, $redirect['query']);
                            }
                        }
                    }
                }
            }
        } elseif (is_single() && strpos($wp_rewrite->permalink_structure, '%category%') !== false && ($cat = get_query_var('category_name'))) {
            $category = get_category_by_path($cat);
            $post_terms = wp_get_object_terms($wp_query->get_queried_object_id(), 'category', array('fields' => 'tt_ids'));
            if (!$category || is_wp_error($category) || !is_wp_error($post_terms) && !empty($post_terms) && !in_array($category->term_taxonomy_id, $post_terms)) {
                $redirect_url = get_permalink($wp_query->get_queried_object_id());
            }
        }
        // Post Paging
        if (is_singular() && !is_front_page() && get_query_var('page')) {
            if (!$redirect_url) {
                $redirect_url = get_permalink(get_queried_object_id());
            }
            $redirect_url = trailingslashit($redirect_url) . user_trailingslashit(get_query_var('page'), 'single_paged');
            $redirect['query'] = remove_query_arg('page', $redirect['query']);
        }
        // paging and feeds
        if (get_query_var('paged') || is_feed() || get_query_var('cpage')) {
            while (preg_match("#/{$wp_rewrite->pagination_base}/?[0-9]+?(/+)?\$#", $redirect['path']) || preg_match('#/(comments/?)?(feed|rss|rdf|atom|rss2)(/+)?$#', $redirect['path']) || preg_match("#/{$wp_rewrite->comments_pagination_base}-[0-9]+(/+)?\$#", $redirect['path'])) {
                // Strip off paging and feed
                $redirect['path'] = preg_replace("#/{$wp_rewrite->pagination_base}/?[0-9]+?(/+)?\$#", '/', $redirect['path']);
                // strip off any existing paging
                $redirect['path'] = preg_replace('#/(comments/?)?(feed|rss2?|rdf|atom)(/+|$)#', '/', $redirect['path']);
                // strip off feed endings
                $redirect['path'] = preg_replace("#/{$wp_rewrite->comments_pagination_base}-[0-9]+?(/+)?\$#", '/', $redirect['path']);
                // strip off any existing comment paging
            }
            $addl_path = '';
            if (is_feed() && in_array(get_query_var('feed'), $wp_rewrite->feeds)) {
                $addl_path = !empty($addl_path) ? trailingslashit($addl_path) : '';
                if (!is_singular() && get_query_var('withcomments')) {
                    $addl_path .= 'comments/';
                }
                if ('rss' == get_default_feed() && 'feed' == get_query_var('feed') || 'rss' == get_query_var('feed')) {
                    $addl_path .= user_trailingslashit('feed/' . (get_default_feed() == 'rss2' ? '' : 'rss2'), 'feed');
                } else {
                    $addl_path .= user_trailingslashit('feed/' . (get_default_feed() == get_query_var('feed') || 'feed' == get_query_var('feed') ? '' : get_query_var('feed')), 'feed');
                }
                $redirect['query'] = remove_query_arg('feed', $redirect['query']);
            } elseif (is_feed() && 'old' == get_query_var('feed')) {
                $old_feed_files = array('wp-atom.php' => 'atom', 'wp-commentsrss2.php' => 'comments_rss2', 'wp-feed.php' => get_default_feed(), 'wp-rdf.php' => 'rdf', 'wp-rss.php' => 'rss2', 'wp-rss2.php' => 'rss2');
                if (isset($old_feed_files[basename($redirect['path'])])) {
                    $redirect_url = get_feed_link($old_feed_files[basename($redirect['path'])]);
                    wp_redirect($redirect_url, 301);
                    die;
                }
            }
            if (get_query_var('paged') > 0) {
                $paged = get_query_var('paged');
                $redirect['query'] = remove_query_arg('paged', $redirect['query']);
                if (!is_feed()) {
                    if ($paged > 1 && !is_single()) {
                        $addl_path = (!empty($addl_path) ? trailingslashit($addl_path) : '') . user_trailingslashit("{$wp_rewrite->pagination_base}/{$paged}", 'paged');
                    } elseif (!is_single()) {
                        $addl_path = !empty($addl_path) ? trailingslashit($addl_path) : '';
                    }
                } elseif ($paged > 1) {
                    $redirect['query'] = add_query_arg('paged', $paged, $redirect['query']);
                }
            }
            if (get_option('page_comments') && ('newest' == get_option('default_comments_page') && get_query_var('cpage') > 0 || 'newest' != get_option('default_comments_page') && get_query_var('cpage') > 1)) {
                $addl_path = (!empty($addl_path) ? trailingslashit($addl_path) : '') . user_trailingslashit($wp_rewrite->comments_pagination_base . '-' . get_query_var('cpage'), 'commentpaged');
                $redirect['query'] = remove_query_arg('cpage', $redirect['query']);
            }
            $redirect['path'] = user_trailingslashit(preg_replace('|/' . preg_quote($wp_rewrite->index, '|') . '/?$|', '/', $redirect['path']));
            // strip off trailing /index.php/
            if (!empty($addl_path) && $wp_rewrite->using_index_permalinks() && strpos($redirect['path'], '/' . $wp_rewrite->index . '/') === false) {
                $redirect['path'] = trailingslashit($redirect['path']) . $wp_rewrite->index . '/';
            }
            if (!empty($addl_path)) {
                $redirect['path'] = trailingslashit($redirect['path']) . $addl_path;
            }
            $redirect_url = $redirect['scheme'] . '://' . $redirect['host'] . $redirect['path'];
        }
        if ('wp-register.php' == basename($redirect['path'])) {
            if (is_multisite()) {
                /** This filter is documented in wp-login.php */
                $redirect_url = apply_filters('wp_signup_location', network_site_url('wp-signup.php'));
            } else {
                $redirect_url = wp_registration_url();
            }
            wp_redirect($redirect_url, 301);
            die;
        }
    }
    // tack on any additional query vars
    $redirect['query'] = preg_replace('#^\\??&*?#', '', $redirect['query']);
    if ($redirect_url && !empty($redirect['query'])) {
        parse_str($redirect['query'], $_parsed_query);
        $redirect = @parse_url($redirect_url);
        if (!empty($_parsed_query['name']) && !empty($redirect['query'])) {
            parse_str($redirect['query'], $_parsed_redirect_query);
            if (empty($_parsed_redirect_query['name'])) {
                unset($_parsed_query['name']);
            }
        }
        $_parsed_query = rawurlencode_deep($_parsed_query);
        $redirect_url = add_query_arg($_parsed_query, $redirect_url);
    }
    if ($redirect_url) {
        $redirect = @parse_url($redirect_url);
    }
    // www.example.com vs example.com
    $user_home = @parse_url(home_url());
    if (!empty($user_home['host'])) {
        $redirect['host'] = $user_home['host'];
    }
    if (empty($user_home['path'])) {
        $user_home['path'] = '/';
    }
    // Handle ports
    if (!empty($user_home['port'])) {
        $redirect['port'] = $user_home['port'];
    } else {
        unset($redirect['port']);
    }
    // trailing /index.php
    $redirect['path'] = preg_replace('|/' . preg_quote($wp_rewrite->index, '|') . '/*?$|', '/', $redirect['path']);
    // Remove trailing spaces from the path
    $redirect['path'] = preg_replace('#(%20| )+$#', '', $redirect['path']);
    if (!empty($redirect['query'])) {
        // Remove trailing spaces from certain terminating query string args
        $redirect['query'] = preg_replace('#((p|page_id|cat|tag)=[^&]*?)(%20| )+$#', '$1', $redirect['query']);
        // Clean up empty query strings
        $redirect['query'] = trim(preg_replace('#(^|&)(p|page_id|cat|tag)=?(&|$)#', '&', $redirect['query']), '&');
        // Redirect obsolete feeds
        $redirect['query'] = preg_replace('#(^|&)feed=rss(&|$)#', '$1feed=rss2$2', $redirect['query']);
        // Remove redundant leading ampersands
        $redirect['query'] = preg_replace('#^\\??&*?#', '', $redirect['query']);
    }
    // strip /index.php/ when we're not using PATHINFO permalinks
    if (!$wp_rewrite->using_index_permalinks()) {
        $redirect['path'] = str_replace('/' . $wp_rewrite->index . '/', '/', $redirect['path']);
    }
    // trailing slashes
    if (is_object($wp_rewrite) && $wp_rewrite->using_permalinks() && !is_404() && (!is_front_page() || is_front_page() && get_query_var('paged') > 1)) {
        $user_ts_type = '';
        if (get_query_var('paged') > 0) {
            $user_ts_type = 'paged';
        } else {
            foreach (array('single', 'category', 'page', 'day', 'month', 'year', 'home') as $type) {
                $func = 'is_' . $type;
                if (call_user_func($func)) {
                    $user_ts_type = $type;
                    break;
                }
            }
        }
        $redirect['path'] = user_trailingslashit($redirect['path'], $user_ts_type);
    } elseif (is_front_page()) {
        $redirect['path'] = trailingslashit($redirect['path']);
    }
    // Strip multiple slashes out of the URL
    if (strpos($redirect['path'], '//') > -1) {
        $redirect['path'] = preg_replace('|/+|', '/', $redirect['path']);
    }
    // Always trailing slash the Front Page URL
    if (trailingslashit($redirect['path']) == trailingslashit($user_home['path'])) {
        $redirect['path'] = trailingslashit($redirect['path']);
    }
    // Ignore differences in host capitalization, as this can lead to infinite redirects
    // Only redirect no-www <=> yes-www
    if (strtolower($original['host']) == strtolower($redirect['host']) || strtolower($original['host']) != 'www.' . strtolower($redirect['host']) && 'www.' . strtolower($original['host']) != strtolower($redirect['host'])) {
        $redirect['host'] = $original['host'];
    }
    $compare_original = array($original['host'], $original['path']);
    if (!empty($original['port'])) {
        $compare_original[] = $original['port'];
    }
    if (!empty($original['query'])) {
        $compare_original[] = $original['query'];
    }
    $compare_redirect = array($redirect['host'], $redirect['path']);
    if (!empty($redirect['port'])) {
        $compare_redirect[] = $redirect['port'];
    }
    if (!empty($redirect['query'])) {
        $compare_redirect[] = $redirect['query'];
    }
    if ($compare_original !== $compare_redirect) {
        $redirect_url = $redirect['scheme'] . '://' . $redirect['host'];
        if (!empty($redirect['port'])) {
            $redirect_url .= ':' . $redirect['port'];
        }
        $redirect_url .= $redirect['path'];
        if (!empty($redirect['query'])) {
            $redirect_url .= '?' . $redirect['query'];
        }
    }
    if (!$redirect_url || $redirect_url == $requested_url) {
        return;
    }
    // Hex encoded octets are case-insensitive.
    if (false !== strpos($requested_url, '%')) {
        if (!function_exists('lowercase_octets')) {
            function lowercase_octets($matches)
            {
                return strtolower($matches[0]);
            }
        }
        $requested_url = preg_replace_callback('|%[a-fA-F0-9][a-fA-F0-9]|', 'lowercase_octets', $requested_url);
    }
    /**
     * Filter the canonical redirect URL.
     *
     * Returning false to this filter will cancel the redirect.
     *
     * @since 2.3.0
     *
     * @param string $redirect_url  The redirect URL.
     * @param string $requested_url The requested URL.
     */
    $redirect_url = apply_filters('redirect_canonical', $redirect_url, $requested_url);
    // yes, again -- in case the filter aborted the request
    if (!$redirect_url || $redirect_url == $requested_url) {
        return;
    }
    if ($do_redirect) {
        // protect against chained redirects
        if (!redirect_canonical($redirect_url, false)) {
            wp_redirect($redirect_url, 301);
            exit;
        } else {
            // Debug
            // die("1: $redirect_url<br />2: " . redirect_canonical( $redirect_url, false ) );
            return;
        }
    } else {
        return $redirect_url;
    }
}
Exemplo n.º 17
0
 /**
  * Handle customize_save WP Ajax request to save/update a changeset.
  *
  * @since 3.4.0
  * @since 4.7.0 The semantics of this method have changed to update a changeset, optionally to also change the status and other attributes.
  */
 public function save()
 {
     if (!is_user_logged_in()) {
         wp_send_json_error('unauthenticated');
     }
     if (!$this->is_preview()) {
         wp_send_json_error('not_preview');
     }
     $action = 'save-customize_' . $this->get_stylesheet();
     if (!check_ajax_referer($action, 'nonce', false)) {
         wp_send_json_error('invalid_nonce');
     }
     $changeset_post_id = $this->changeset_post_id();
     if (empty($changeset_post_id)) {
         if (!current_user_can(get_post_type_object('customize_changeset')->cap->create_posts)) {
             wp_send_json_error('cannot_create_changeset_post');
         }
     } else {
         if (!current_user_can(get_post_type_object('customize_changeset')->cap->edit_post, $changeset_post_id)) {
             wp_send_json_error('cannot_edit_changeset_post');
         }
     }
     if (!empty($_POST['customize_changeset_data'])) {
         $input_changeset_data = json_decode(wp_unslash($_POST['customize_changeset_data']), true);
         if (!is_array($input_changeset_data)) {
             wp_send_json_error('invalid_customize_changeset_data');
         }
     } else {
         $input_changeset_data = array();
     }
     // Validate title.
     $changeset_title = null;
     if (isset($_POST['customize_changeset_title'])) {
         $changeset_title = sanitize_text_field(wp_unslash($_POST['customize_changeset_title']));
     }
     // Validate changeset status param.
     $is_publish = null;
     $changeset_status = null;
     if (isset($_POST['customize_changeset_status'])) {
         $changeset_status = wp_unslash($_POST['customize_changeset_status']);
         if (!get_post_status_object($changeset_status) || !in_array($changeset_status, array('draft', 'pending', 'publish', 'future'), true)) {
             wp_send_json_error('bad_customize_changeset_status', 400);
         }
         $is_publish = 'publish' === $changeset_status || 'future' === $changeset_status;
         if ($is_publish && !current_user_can(get_post_type_object('customize_changeset')->cap->publish_posts)) {
             wp_send_json_error('changeset_publish_unauthorized', 403);
         }
     }
     /*
      * Validate changeset date param. Date is assumed to be in local time for
      * the WP if in MySQL format (YYYY-MM-DD HH:MM:SS). Otherwise, the date
      * is parsed with strtotime() so that ISO date format may be supplied
      * or a string like "+10 minutes".
      */
     $changeset_date_gmt = null;
     if (isset($_POST['customize_changeset_date'])) {
         $changeset_date = wp_unslash($_POST['customize_changeset_date']);
         if (preg_match('/^\\d\\d\\d\\d-\\d\\d-\\d\\d \\d\\d:\\d\\d:\\d\\d$/', $changeset_date)) {
             $mm = substr($changeset_date, 5, 2);
             $jj = substr($changeset_date, 8, 2);
             $aa = substr($changeset_date, 0, 4);
             $valid_date = wp_checkdate($mm, $jj, $aa, $changeset_date);
             if (!$valid_date) {
                 wp_send_json_error('bad_customize_changeset_date', 400);
             }
             $changeset_date_gmt = get_gmt_from_date($changeset_date);
         } else {
             $timestamp = strtotime($changeset_date);
             if (!$timestamp) {
                 wp_send_json_error('bad_customize_changeset_date', 400);
             }
             $changeset_date_gmt = gmdate('Y-m-d H:i:s', $timestamp);
         }
     }
     $r = $this->save_changeset_post(array('status' => $changeset_status, 'title' => $changeset_title, 'date_gmt' => $changeset_date_gmt, 'data' => $input_changeset_data));
     if (is_wp_error($r)) {
         $response = array('message' => $r->get_error_message(), 'code' => $r->get_error_code());
         if (is_array($r->get_error_data())) {
             $response = array_merge($response, $r->get_error_data());
         } else {
             $response['data'] = $r->get_error_data();
         }
     } else {
         $response = $r;
         // Note that if the changeset status was publish, then it will get set to trash if revisions are not supported.
         $response['changeset_status'] = get_post_status($this->changeset_post_id());
         if ($is_publish && 'trash' === $response['changeset_status']) {
             $response['changeset_status'] = 'publish';
         }
         if ('publish' === $response['changeset_status']) {
             $response['next_changeset_uuid'] = wp_generate_uuid4();
         }
     }
     if (isset($response['setting_validities'])) {
         $response['setting_validities'] = array_map(array($this, 'prepare_setting_validity_for_js'), $response['setting_validities']);
     }
     /**
      * Filters response data for a successful customize_save Ajax request.
      *
      * This filter does not apply if there was a nonce or authentication failure.
      *
      * @since 4.2.0
      *
      * @param array                $response Additional information passed back to the 'saved'
      *                                       event on `wp.customize`.
      * @param WP_Customize_Manager $this     WP_Customize_Manager instance.
      */
     $response = apply_filters('customize_save_response', $response, $this);
     if (is_wp_error($r)) {
         wp_send_json_error($response);
     } else {
         wp_send_json_success($response);
     }
 }
Exemplo n.º 18
0
/**
 * Rename $_POST data from form names to DB post columns.
 *
 * Manipulates $_POST directly.
 *
 * @package WordPress
 * @since 2.6.0
 *
 * @param bool $update Are we updating a pre-existing post?
 * @param array $post_data Array of post data. Defaults to the contents of $_POST.
 * @return object|bool WP_Error on failure, true on success.
 */
function _wp_translate_postdata($update = false, $post_data = null)
{
    if (empty($post_data)) {
        $post_data =& $_POST;
    }
    if ($update) {
        $post_data['ID'] = (int) $post_data['post_ID'];
    }
    $ptype = get_post_type_object($post_data['post_type']);
    if ($update && !current_user_can('edit_post', $post_data['ID'])) {
        if ('page' == $post_data['post_type']) {
            return new WP_Error('edit_others_pages', __('Sorry, you are not allowed to edit pages as this user.'));
        } else {
            return new WP_Error('edit_others_posts', __('Sorry, you are not allowed to edit posts as this user.'));
        }
    } elseif (!$update && !current_user_can($ptype->cap->create_posts)) {
        if ('page' == $post_data['post_type']) {
            return new WP_Error('edit_others_pages', __('Sorry, you are not allowed to create pages as this user.'));
        } else {
            return new WP_Error('edit_others_posts', __('Sorry, you are not allowed to create posts as this user.'));
        }
    }
    if (isset($post_data['content'])) {
        $post_data['post_content'] = $post_data['content'];
    }
    if (isset($post_data['excerpt'])) {
        $post_data['post_excerpt'] = $post_data['excerpt'];
    }
    if (isset($post_data['parent_id'])) {
        $post_data['post_parent'] = (int) $post_data['parent_id'];
    }
    if (isset($post_data['trackback_url'])) {
        $post_data['to_ping'] = $post_data['trackback_url'];
    }
    $post_data['user_ID'] = get_current_user_id();
    if (!empty($post_data['post_author_override'])) {
        $post_data['post_author'] = (int) $post_data['post_author_override'];
    } else {
        if (!empty($post_data['post_author'])) {
            $post_data['post_author'] = (int) $post_data['post_author'];
        } else {
            $post_data['post_author'] = (int) $post_data['user_ID'];
        }
    }
    if (isset($post_data['user_ID']) && $post_data['post_author'] != $post_data['user_ID'] && !current_user_can($ptype->cap->edit_others_posts)) {
        if ($update) {
            if ('page' == $post_data['post_type']) {
                return new WP_Error('edit_others_pages', __('Sorry, you are not allowed to edit pages as this user.'));
            } else {
                return new WP_Error('edit_others_posts', __('Sorry, you are not allowed to edit posts as this user.'));
            }
        } else {
            if ('page' == $post_data['post_type']) {
                return new WP_Error('edit_others_pages', __('Sorry, you are not allowed to create pages as this user.'));
            } else {
                return new WP_Error('edit_others_posts', __('Sorry, you are not allowed to create posts as this user.'));
            }
        }
    }
    if (!empty($post_data['post_status'])) {
        $post_data['post_status'] = sanitize_key($post_data['post_status']);
        // No longer an auto-draft
        if ('auto-draft' === $post_data['post_status']) {
            $post_data['post_status'] = 'draft';
        }
        if (!get_post_status_object($post_data['post_status'])) {
            unset($post_data['post_status']);
        }
    }
    // What to do based on which button they pressed
    if (isset($post_data['saveasdraft']) && '' != $post_data['saveasdraft']) {
        $post_data['post_status'] = 'draft';
    }
    if (isset($post_data['saveasprivate']) && '' != $post_data['saveasprivate']) {
        $post_data['post_status'] = 'private';
    }
    if (isset($post_data['publish']) && '' != $post_data['publish'] && (!isset($post_data['post_status']) || $post_data['post_status'] != 'private')) {
        $post_data['post_status'] = 'publish';
    }
    if (isset($post_data['advanced']) && '' != $post_data['advanced']) {
        $post_data['post_status'] = 'draft';
    }
    if (isset($post_data['pending']) && '' != $post_data['pending']) {
        $post_data['post_status'] = 'pending';
    }
    if (isset($post_data['ID'])) {
        $post_id = $post_data['ID'];
    } else {
        $post_id = false;
    }
    $previous_status = $post_id ? get_post_field('post_status', $post_id) : false;
    if (isset($post_data['post_status']) && 'private' == $post_data['post_status'] && !current_user_can($ptype->cap->publish_posts)) {
        $post_data['post_status'] = $previous_status ? $previous_status : 'pending';
    }
    $published_statuses = array('publish', 'future');
    // Posts 'submitted for approval' present are submitted to $_POST the same as if they were being published.
    // Change status from 'publish' to 'pending' if user lacks permissions to publish or to resave published posts.
    if (isset($post_data['post_status']) && (in_array($post_data['post_status'], $published_statuses) && !current_user_can($ptype->cap->publish_posts))) {
        if (!in_array($previous_status, $published_statuses) || !current_user_can('edit_post', $post_id)) {
            $post_data['post_status'] = 'pending';
        }
    }
    if (!isset($post_data['post_status'])) {
        $post_data['post_status'] = 'auto-draft' === $previous_status ? 'draft' : $previous_status;
    }
    if (isset($post_data['post_password']) && !current_user_can($ptype->cap->publish_posts)) {
        unset($post_data['post_password']);
    }
    if (!isset($post_data['comment_status'])) {
        $post_data['comment_status'] = 'closed';
    }
    if (!isset($post_data['ping_status'])) {
        $post_data['ping_status'] = 'closed';
    }
    foreach (array('aa', 'mm', 'jj', 'hh', 'mn') as $timeunit) {
        if (!empty($post_data['hidden_' . $timeunit]) && $post_data['hidden_' . $timeunit] != $post_data[$timeunit]) {
            $post_data['edit_date'] = '1';
            break;
        }
    }
    if (!empty($post_data['edit_date'])) {
        $aa = $post_data['aa'];
        $mm = $post_data['mm'];
        $jj = $post_data['jj'];
        $hh = $post_data['hh'];
        $mn = $post_data['mn'];
        $ss = $post_data['ss'];
        $aa = $aa <= 0 ? date('Y') : $aa;
        $mm = $mm <= 0 ? date('n') : $mm;
        $jj = $jj > 31 ? 31 : $jj;
        $jj = $jj <= 0 ? date('j') : $jj;
        $hh = $hh > 23 ? $hh - 24 : $hh;
        $mn = $mn > 59 ? $mn - 60 : $mn;
        $ss = $ss > 59 ? $ss - 60 : $ss;
        $post_data['post_date'] = sprintf("%04d-%02d-%02d %02d:%02d:%02d", $aa, $mm, $jj, $hh, $mn, $ss);
        $valid_date = wp_checkdate($mm, $jj, $aa, $post_data['post_date']);
        if (!$valid_date) {
            return new WP_Error('invalid_date', __('Whoops, the provided date is invalid.'));
        }
        $post_data['post_date_gmt'] = get_gmt_from_date($post_data['post_date']);
    }
    if (isset($post_data['post_category'])) {
        $category_object = get_taxonomy('category');
        if (!current_user_can($category_object->cap->assign_terms)) {
            unset($post_data['post_category']);
        }
    }
    return $post_data;
}
/**
 * Filter the expiration date for a campaign.
 *
 * A hidden/fake input field so the filter is triggered, then
 * add all the other date fields together to create the MySQL date.
 *
 * @since Astoundify Crowdfunding 0.1-alpha
 *
 * @param string $date
 * @return string $end_date Formatted date
 */
function atcf_campaign_save_end_date($new)
{
    global $post;
    if (!isset($_POST['end-aa'])) {
        if ($_POST['campaign_endless'] == 0) {
            delete_post_meta($post->ID, 'campaign_endless');
        }
        return;
    }
    $aa = $_POST['end-aa'];
    $mm = $_POST['end-mm'];
    $jj = $_POST['end-jj'];
    $hh = $_POST['end-hh'];
    $mn = $_POST['end-mn'];
    $ss = $_POST['end-ss'];
    $aa = $aa <= 0 ? date('Y') : $aa;
    $mm = $mm <= 0 ? date('n') : $mm;
    $jj = $jj > 31 ? 31 : $jj;
    $jj = $jj <= 0 ? date('j') : $jj;
    $hh = $hh > 23 ? $hh - 24 : $hh;
    $mn = $mn > 59 ? $mn - 60 : $mn;
    $ss = $ss > 59 ? $ss - 60 : $ss;
    $end_date = sprintf("%04d-%02d-%02d %02d:%02d:%02d", $aa, $mm, $jj, $hh, $mn, $ss);
    $valid_date = wp_checkdate($mm, $jj, $aa, $end_date);
    if (!$valid_date) {
        return new WP_Error('invalid_date', __('Whoops, the provided date is invalid.', 'atcf'));
    }
    if (mysql2date('G', $end_date) > current_time('timestamp')) {
        delete_post_meta($post->ID, '_campaign_expired');
    }
    return $end_date;
}
Exemplo n.º 20
0
/**
 * Insert or update a post.
 *
 * If the $postarr parameter has 'ID' set to a value, then post will be updated.
 *
 * You can set the post date manually, by setting the values for 'post_date'
 * and 'post_date_gmt' keys. You can close the comments or open the comments by
 * setting the value for 'comment_status' key.
 *
 * @since 1.0.0
 * @since 4.2.0 Support was added for encoding emoji in the post title, content, and excerpt.
 * @since 4.4.0 A 'meta_input' array can now be passed to `$postarr` to add post meta data.
 *
 * @see sanitize_post()
 * @global wpdb $wpdb WordPress database abstraction object.
 *
 * @param array $postarr {
 *     An array of elements that make up a post to update or insert.
 *
 *     @type int    $ID                    The post ID. If equal to something other than 0,
 *                                         the post with that ID will be updated. Default 0.
 *     @type int    $post_author           The ID of the user who added the post. Default is
 *                                         the current user ID.
 *     @type string $post_date             The date of the post. Default is the current time.
 *     @type string $post_date_gmt         The date of the post in the GMT timezone. Default is
 *                                         the value of `$post_date`.
 *     @type mixed  $post_content          The post content. Default empty.
 *     @type string $post_content_filtered The filtered post content. Default empty.
 *     @type string $post_title            The post title. Default empty.
 *     @type string $post_excerpt          The post excerpt. Default empty.
 *     @type string $post_status           The post status. Default 'draft'.
 *     @type string $post_type             The post type. Default 'post'.
 *     @type string $comment_status        Whether the post can accept comments. Accepts 'open' or 'closed'.
 *                                         Default is the value of 'default_comment_status' option.
 *     @type string $ping_status           Whether the post can accept pings. Accepts 'open' or 'closed'.
 *                                         Default is the value of 'default_ping_status' option.
 *     @type string $post_password         The password to access the post. Default empty.
 *     @type string $post_name             The post name. Default is the sanitized post title.
 *     @type string $to_ping               Space or carriage return-separated list of URLs to ping.
 *                                         Default empty.
 *     @type string $pinged                Space or carriage return-separated list of URLs that have
 *                                         been pinged. Default empty.
 *     @type string $post_modified         The date when the post was last modified. Default is
 *                                         the current time.
 *     @type string $post_modified_gmt     The date when the post was last modified in the GMT
 *                                         timezone. Default is the current time.
 *     @type int    $post_parent           Set this for the post it belongs to, if any. Default 0.
 *     @type int    $menu_order            The order the post should be displayed in. Default 0.
 *     @type string $post_mime_type        The mime type of the post. Default empty.
 *     @type string $guid                  Global Unique ID for referencing the post. Default empty.
 *     @type array  $tax_input             Array of taxonomy terms keyed by their taxonomy name. Default empty.
 *     @type array  $meta_input            Array of post meta values keyed by their post meta key. Default empty.
 * }
 * @param bool  $wp_error Optional. Whether to allow return of WP_Error on failure. Default false.
 * @return int|WP_Error The post ID on success. The value 0 or WP_Error on failure.
 */
function wp_insert_post($postarr, $wp_error = false)
{
    global $wpdb;
    $user_id = get_current_user_id();
    $defaults = array('post_author' => $user_id, 'post_content' => '', 'post_content_filtered' => '', 'post_title' => '', 'post_excerpt' => '', 'post_status' => 'draft', 'post_type' => 'post', 'comment_status' => '', 'ping_status' => '', 'post_password' => '', 'to_ping' => '', 'pinged' => '', 'post_parent' => 0, 'menu_order' => 0, 'guid' => '', 'import_id' => 0, 'context' => '');
    $postarr = wp_parse_args($postarr, $defaults);
    unset($postarr['filter']);
    $postarr = sanitize_post($postarr, 'db');
    // Are we updating or creating?
    $post_ID = 0;
    $update = false;
    $guid = $postarr['guid'];
    if (!empty($postarr['ID'])) {
        $update = true;
        // Get the post ID and GUID.
        $post_ID = $postarr['ID'];
        $post_before = get_post($post_ID);
        if (is_null($post_before)) {
            if ($wp_error) {
                return new WP_Error('invalid_post', __('Invalid post ID.'));
            }
            return 0;
        }
        $guid = get_post_field('guid', $post_ID);
        $previous_status = get_post_field('post_status', $post_ID);
    } else {
        $previous_status = 'new';
    }
    $post_type = empty($postarr['post_type']) ? 'post' : $postarr['post_type'];
    $post_title = $postarr['post_title'];
    $post_content = $postarr['post_content'];
    $post_excerpt = $postarr['post_excerpt'];
    if (isset($postarr['post_name'])) {
        $post_name = $postarr['post_name'];
    }
    $maybe_empty = 'attachment' !== $post_type && !$post_content && !$post_title && !$post_excerpt && post_type_supports($post_type, 'editor') && post_type_supports($post_type, 'title') && post_type_supports($post_type, 'excerpt');
    /**
     * Filter whether the post should be considered "empty".
     *
     * The post is considered "empty" if both:
     * 1. The post type supports the title, editor, and excerpt fields
     * 2. The title, editor, and excerpt fields are all empty
     *
     * Returning a truthy value to the filter will effectively short-circuit
     * the new post being inserted, returning 0. If $wp_error is true, a WP_Error
     * will be returned instead.
     *
     * @since 3.3.0
     *
     * @param bool  $maybe_empty Whether the post should be considered "empty".
     * @param array $postarr     Array of post data.
     */
    if (apply_filters('wp_insert_post_empty_content', $maybe_empty, $postarr)) {
        if ($wp_error) {
            return new WP_Error('empty_content', __('Content, title, and excerpt are empty.'));
        } else {
            return 0;
        }
    }
    $post_status = empty($postarr['post_status']) ? 'draft' : $postarr['post_status'];
    if ('attachment' === $post_type && !in_array($post_status, array('inherit', 'private', 'trash'))) {
        $post_status = 'inherit';
    }
    if (!empty($postarr['post_category'])) {
        // Filter out empty terms.
        $post_category = array_filter($postarr['post_category']);
    }
    // Make sure we set a valid category.
    if (empty($post_category) || 0 == count($post_category) || !is_array($post_category)) {
        // 'post' requires at least one category.
        if ('post' == $post_type && 'auto-draft' != $post_status) {
            $post_category = array(get_option('default_category'));
        } else {
            $post_category = array();
        }
    }
    // Don't allow contributors to set the post slug for pending review posts.
    if ('pending' == $post_status && !current_user_can('publish_posts')) {
        $post_name = '';
    }
    /*
     * Create a valid post name. Drafts and pending posts are allowed to have
     * an empty post name.
     */
    if (empty($post_name)) {
        if (!in_array($post_status, array('draft', 'pending', 'auto-draft'))) {
            $post_name = sanitize_title($post_title);
        } else {
            $post_name = '';
        }
    } else {
        // On updates, we need to check to see if it's using the old, fixed sanitization context.
        $check_name = sanitize_title($post_name, '', 'old-save');
        if ($update && strtolower(urlencode($post_name)) == $check_name && get_post_field('post_name', $post_ID) == $check_name) {
            $post_name = $check_name;
        } else {
            // new post, or slug has changed.
            $post_name = sanitize_title($post_name);
        }
    }
    /*
     * If the post date is empty (due to having been new or a draft) and status
     * is not 'draft' or 'pending', set date to now.
     */
    if (empty($postarr['post_date']) || '0000-00-00 00:00:00' == $postarr['post_date']) {
        if (empty($postarr['post_date_gmt']) || '0000-00-00 00:00:00' == $postarr['post_date_gmt']) {
            $post_date = current_time('mysql');
        } else {
            $post_date = get_date_from_gmt($postarr['post_date_gmt']);
        }
    } else {
        $post_date = $postarr['post_date'];
    }
    // Validate the date.
    $mm = substr($post_date, 5, 2);
    $jj = substr($post_date, 8, 2);
    $aa = substr($post_date, 0, 4);
    $valid_date = wp_checkdate($mm, $jj, $aa, $post_date);
    if (!$valid_date) {
        if ($wp_error) {
            return new WP_Error('invalid_date', __('Whoops, the provided date is invalid.'));
        } else {
            return 0;
        }
    }
    if (empty($postarr['post_date_gmt']) || '0000-00-00 00:00:00' == $postarr['post_date_gmt']) {
        if (!in_array($post_status, array('draft', 'pending', 'auto-draft'))) {
            $post_date_gmt = get_gmt_from_date($post_date);
        } else {
            $post_date_gmt = '0000-00-00 00:00:00';
        }
    } else {
        $post_date_gmt = $postarr['post_date_gmt'];
    }
    if ($update || '0000-00-00 00:00:00' == $post_date) {
        $post_modified = current_time('mysql');
        $post_modified_gmt = current_time('mysql', 1);
    } else {
        $post_modified = $post_date;
        $post_modified_gmt = $post_date_gmt;
    }
    if ('attachment' !== $post_type) {
        if ('publish' == $post_status) {
            $now = gmdate('Y-m-d H:i:59');
            if (mysql2date('U', $post_date_gmt, false) > mysql2date('U', $now, false)) {
                $post_status = 'future';
            }
        } elseif ('future' == $post_status) {
            $now = gmdate('Y-m-d H:i:59');
            if (mysql2date('U', $post_date_gmt, false) <= mysql2date('U', $now, false)) {
                $post_status = 'publish';
            }
        }
    }
    // Comment status.
    if (empty($postarr['comment_status'])) {
        if ($update) {
            $comment_status = 'closed';
        } else {
            $comment_status = get_default_comment_status($post_type);
        }
    } else {
        $comment_status = $postarr['comment_status'];
    }
    // These variables are needed by compact() later.
    $post_content_filtered = $postarr['post_content_filtered'];
    $post_author = isset($postarr['post_author']) ? $postarr['post_author'] : $user_id;
    $ping_status = empty($postarr['ping_status']) ? get_default_comment_status($post_type, 'pingback') : $postarr['ping_status'];
    $to_ping = isset($postarr['to_ping']) ? sanitize_trackback_urls($postarr['to_ping']) : '';
    $pinged = isset($postarr['pinged']) ? $postarr['pinged'] : '';
    $import_id = isset($postarr['import_id']) ? $postarr['import_id'] : 0;
    /*
     * The 'wp_insert_post_parent' filter expects all variables to be present.
     * Previously, these variables would have already been extracted
     */
    if (isset($postarr['menu_order'])) {
        $menu_order = (int) $postarr['menu_order'];
    } else {
        $menu_order = 0;
    }
    $post_password = isset($postarr['post_password']) ? $postarr['post_password'] : '';
    if ('private' == $post_status) {
        $post_password = '';
    }
    if (isset($postarr['post_parent'])) {
        $post_parent = (int) $postarr['post_parent'];
    } else {
        $post_parent = 0;
    }
    /**
     * Filter the post parent -- used to check for and prevent hierarchy loops.
     *
     * @since 3.1.0
     *
     * @param int   $post_parent Post parent ID.
     * @param int   $post_ID     Post ID.
     * @param array $new_postarr Array of parsed post data.
     * @param array $postarr     Array of sanitized, but otherwise unmodified post data.
     */
    $post_parent = apply_filters('wp_insert_post_parent', $post_parent, $post_ID, compact(array_keys($postarr)), $postarr);
    $post_name = wp_unique_post_slug($post_name, $post_ID, $post_status, $post_type, $post_parent);
    // Don't unslash.
    $post_mime_type = isset($postarr['post_mime_type']) ? $postarr['post_mime_type'] : '';
    // Expected_slashed (everything!).
    $data = compact('post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_content_filtered', 'post_title', 'post_excerpt', 'post_status', 'post_type', 'comment_status', 'ping_status', 'post_password', 'post_name', 'to_ping', 'pinged', 'post_modified', 'post_modified_gmt', 'post_parent', 'menu_order', 'post_mime_type', 'guid');
    $emoji_fields = array('post_title', 'post_content', 'post_excerpt');
    foreach ($emoji_fields as $emoji_field) {
        if (isset($data[$emoji_field])) {
            $charset = $wpdb->get_col_charset($wpdb->posts, $emoji_field);
            if ('utf8' === $charset) {
                $data[$emoji_field] = wp_encode_emoji($data[$emoji_field]);
            }
        }
    }
    if ('attachment' === $post_type) {
        /**
         * Filter attachment post data before it is updated in or added to the database.
         *
         * @since 3.9.0
         *
         * @param array $data    An array of sanitized attachment post data.
         * @param array $postarr An array of unsanitized attachment post data.
         */
        $data = apply_filters('wp_insert_attachment_data', $data, $postarr);
    } else {
        /**
         * Filter slashed post data just before it is inserted into the database.
         *
         * @since 2.7.0
         *
         * @param array $data    An array of slashed post data.
         * @param array $postarr An array of sanitized, but otherwise unmodified post data.
         */
        $data = apply_filters('wp_insert_post_data', $data, $postarr);
    }
    $data = wp_unslash($data);
    $where = array('ID' => $post_ID);
    if ($update) {
        /**
         * Fires immediately before an existing post is updated in the database.
         *
         * @since 2.5.0
         *
         * @param int   $post_ID Post ID.
         * @param array $data    Array of unslashed post data.
         */
        do_action('pre_post_update', $post_ID, $data);
        if (false === $wpdb->update($wpdb->posts, $data, $where)) {
            if ($wp_error) {
                return new WP_Error('db_update_error', __('Could not update post in the database'), $wpdb->last_error);
            } else {
                return 0;
            }
        }
    } else {
        // If there is a suggested ID, use it if not already present.
        if (!empty($import_id)) {
            $import_id = (int) $import_id;
            if (!$wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->posts} WHERE ID = %d", $import_id))) {
                $data['ID'] = $import_id;
            }
        }
        if (false === $wpdb->insert($wpdb->posts, $data)) {
            if ($wp_error) {
                return new WP_Error('db_insert_error', __('Could not insert post into the database'), $wpdb->last_error);
            } else {
                return 0;
            }
        }
        $post_ID = (int) $wpdb->insert_id;
        // Use the newly generated $post_ID.
        $where = array('ID' => $post_ID);
    }
    if (empty($data['post_name']) && !in_array($data['post_status'], array('draft', 'pending', 'auto-draft'))) {
        $data['post_name'] = wp_unique_post_slug(sanitize_title($data['post_title'], $post_ID), $post_ID, $data['post_status'], $post_type, $post_parent);
        $wpdb->update($wpdb->posts, array('post_name' => $data['post_name']), $where);
        clean_post_cache($post_ID);
    }
    if (is_object_in_taxonomy($post_type, 'category')) {
        wp_set_post_categories($post_ID, $post_category);
    }
    if (isset($postarr['tags_input']) && is_object_in_taxonomy($post_type, 'post_tag')) {
        wp_set_post_tags($post_ID, $postarr['tags_input']);
    }
    // New-style support for all custom taxonomies.
    if (!empty($postarr['tax_input'])) {
        foreach ($postarr['tax_input'] as $taxonomy => $tags) {
            $taxonomy_obj = get_taxonomy($taxonomy);
            if (!$taxonomy_obj) {
                /* translators: %s: taxonomy name */
                _doing_it_wrong(__FUNCTION__, sprintf(__('Invalid taxonomy: %s.'), $taxonomy), '4.4.0');
                continue;
            }
            // array = hierarchical, string = non-hierarchical.
            if (is_array($tags)) {
                $tags = array_filter($tags);
            }
            if (current_user_can($taxonomy_obj->cap->assign_terms)) {
                wp_set_post_terms($post_ID, $tags, $taxonomy);
            }
        }
    }
    if (!empty($postarr['meta_input'])) {
        foreach ($postarr['meta_input'] as $field => $value) {
            update_post_meta($post_ID, $field, $value);
        }
    }
    $current_guid = get_post_field('guid', $post_ID);
    // Set GUID.
    if (!$update && '' == $current_guid) {
        $wpdb->update($wpdb->posts, array('guid' => get_permalink($post_ID)), $where);
    }
    if ('attachment' === $postarr['post_type']) {
        if (!empty($postarr['file'])) {
            update_attached_file($post_ID, $postarr['file']);
        }
        if (!empty($postarr['context'])) {
            add_post_meta($post_ID, '_wp_attachment_context', $postarr['context'], true);
        }
    }
    clean_post_cache($post_ID);
    $post = get_post($post_ID);
    if (!empty($postarr['page_template']) && 'page' == $data['post_type']) {
        $post->page_template = $postarr['page_template'];
        $page_templates = wp_get_theme()->get_page_templates($post);
        if ('default' != $postarr['page_template'] && !isset($page_templates[$postarr['page_template']])) {
            if ($wp_error) {
                return new WP_Error('invalid_page_template', __('The page template is invalid.'));
            }
            update_post_meta($post_ID, '_wp_page_template', 'default');
        } else {
            update_post_meta($post_ID, '_wp_page_template', $postarr['page_template']);
        }
    }
    if ('attachment' !== $postarr['post_type']) {
        wp_transition_post_status($data['post_status'], $previous_status, $post);
    } else {
        if ($update) {
            /**
             * Fires once an existing attachment has been updated.
             *
             * @since 2.0.0
             *
             * @param int $post_ID Attachment ID.
             */
            do_action('edit_attachment', $post_ID);
            $post_after = get_post($post_ID);
            /**
             * Fires once an existing attachment has been updated.
             *
             * @since 4.4.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.
             */
            do_action('attachment_updated', $post_ID, $post_after, $post_before);
        } else {
            /**
             * Fires once an attachment has been added.
             *
             * @since 2.0.0
             *
             * @param int $post_ID Attachment ID.
             */
            do_action('add_attachment', $post_ID);
        }
        return $post_ID;
    }
    if ($update) {
        /**
         * Fires once an existing post has been updated.
         *
         * @since 1.2.0
         *
         * @param int     $post_ID Post ID.
         * @param WP_Post $post    Post object.
         */
        do_action('edit_post', $post_ID, $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.
         */
        do_action('post_updated', $post_ID, $post_after, $post_before);
    }
    /**
     * Fires once a post has been saved.
     *
     * The dynamic portion of the hook name, `$post->post_type`, refers to
     * the post type slug.
     *
     * @since 3.7.0
     *
     * @param int     $post_ID Post ID.
     * @param WP_Post $post    Post object.
     * @param bool    $update  Whether this is an existing post being updated or not.
     */
    do_action("save_post_{$post->post_type}", $post_ID, $post, $update);
    /**
     * Fires once a post has been saved.
     *
     * @since 1.5.0
     *
     * @param int     $post_ID Post ID.
     * @param WP_Post $post    Post object.
     * @param bool    $update  Whether this is an existing post being updated or not.
     */
    do_action('save_post', $post_ID, $post, $update);
    /**
     * Fires once a post has been saved.
     *
     * @since 2.0.0
     *
     * @param int     $post_ID Post ID.
     * @param WP_Post $post    Post object.
     * @param bool    $update  Whether this is an existing post being updated or not.
     */
    do_action('wp_insert_post', $post_ID, $post, $update);
    return $post_ID;
}
 /**
  * Save date for expiring posts
  * Called from save_post
  *
  * @param $post_id
  */
 function save_expiration_date($post_id)
 {
     // Check its not an auto save
     if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
         return;
     }
     // make suer we have all of our values
     if (!isset($_POST['expiring_posts_nonce']) || !isset($_POST['exp-aa']) || !isset($_POST['exp-mm']) || !isset($_POST['exp-jj']) || !isset($_POST['exp-hh']) || !isset($_POST['exp-mn']) || !isset($_POST['exp-ss'])) {
         return;
     }
     // Check permissions
     if (!current_user_can('edit_post', $post_id)) {
         return;
     }
     // Finally check the nonce
     check_admin_referer('save_expiration_post_meta', 'expiring_posts_nonce');
     $prev_expiration_date = get_post_meta($post_id, 'exp_expiration_date', true);
     $post_status = get_post_status($post_id);
     // if post was manually set to expired, we want to record the current time with expired_post_transition()
     if ('expired' == $post_status && (!$prev_expiration_date || strtotime($prev_expiration_date) >= time())) {
         return;
     }
     $aa = $_POST['exp-aa'];
     $mm = $_POST['exp-mm'];
     $jj = $_POST['exp-jj'];
     $hh = $_POST['exp-hh'];
     $mn = $_POST['exp-mn'];
     $ss = $_POST['exp-ss'];
     $jj = $jj > 31 ? 31 : $jj;
     $hh = $hh > 23 ? $hh - 24 : $hh;
     $mn = $mn > 59 ? $mn - 60 : $mn;
     $ss = $ss > 59 ? $ss - 60 : $ss;
     $expiration_date = "{$aa}-{$mm}-{$jj} {$hh}:{$mn}:{$ss}";
     $valid_date = wp_checkdate($mm, $jj, $aa, $expiration_date);
     if (!$valid_date) {
         return;
     }
     update_post_meta($post_id, 'exp_expiration_date', sanitize_text_field($expiration_date));
     // Enabling the expiration feature is opt-in, where the checkbox is
     // checked by default
     // If post is already expired, make sure the this is visually represented
     if ('expired' == $post_status) {
         update_post_meta($post_id, 'exp_pending_expiration', true);
         // post is scheduled to expire, enable expiration and set hook. Exception is if the post has
         // just transitioned from expired to publish
     } elseif (!isset($_POST['exp-enable']) && !('expired' === $_POST['hidden_post_status'] && 'publish' === $post_status)) {
         $this->schedule_post_expiration($post_id);
         // post expiration is not enabled. Clear any expiring hooks and disable expiration
     } else {
         $this->unschedule_expired_post($post_id);
     }
 }