PageRenderTime 320ms CodeModel.GetById 100ms app.highlight 160ms RepoModel.GetById 41ms app.codeStats 1ms

/wp-admin/includes/post.php

https://github.com/dedavidd/piratenpartij.nl
PHP | 1654 lines | 956 code | 265 blank | 433 comment | 340 complexity | f993ad939b20e221cbe48754da7493ef MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1<?php
   2/**
   3 * WordPress Post Administration API.
   4 *
   5 * @package WordPress
   6 * @subpackage Administration
   7 */
   8
   9/**
  10 * Rename $_POST data from form names to DB post columns.
  11 *
  12 * Manipulates $_POST directly.
  13 *
  14 * @package WordPress
  15 * @since 2.6.0
  16 *
  17 * @param bool $update Are we updating a pre-existing post?
  18 * @param array $post_data Array of post data. Defaults to the contents of $_POST.
  19 * @return object|bool WP_Error on failure, true on success.
  20 */
  21function _wp_translate_postdata( $update = false, $post_data = null ) {
  22
  23	if ( empty($post_data) )
  24		$post_data = &$_POST;
  25
  26	if ( $update )
  27		$post_data['ID'] = (int) $post_data['post_ID'];
  28
  29	$ptype = get_post_type_object( $post_data['post_type'] );
  30
  31	if ( $update && ! current_user_can( 'edit_post', $post_data['ID'] ) ) {
  32		if ( 'page' == $post_data['post_type'] )
  33			return new WP_Error( 'edit_others_pages', __( 'You are not allowed to edit pages as this user.' ) );
  34		else
  35			return new WP_Error( 'edit_others_posts', __( 'You are not allowed to edit posts as this user.' ) );
  36	} elseif ( ! $update && ! current_user_can( $ptype->cap->create_posts ) ) {
  37		if ( 'page' == $post_data['post_type'] )
  38			return new WP_Error( 'edit_others_pages', __( 'You are not allowed to create pages as this user.' ) );
  39		else
  40			return new WP_Error( 'edit_others_posts', __( 'You are not allowed to create posts as this user.' ) );
  41	}
  42
  43	if ( isset( $post_data['content'] ) )
  44		$post_data['post_content'] = $post_data['content'];
  45
  46	if ( isset( $post_data['excerpt'] ) )
  47		$post_data['post_excerpt'] = $post_data['excerpt'];
  48
  49	if ( isset( $post_data['parent_id'] ) )
  50		$post_data['post_parent'] = (int) $post_data['parent_id'];
  51
  52	if ( isset($post_data['trackback_url']) )
  53		$post_data['to_ping'] = $post_data['trackback_url'];
  54
  55	$post_data['user_ID'] = get_current_user_id();
  56
  57	if (!empty ( $post_data['post_author_override'] ) ) {
  58		$post_data['post_author'] = (int) $post_data['post_author_override'];
  59	} else {
  60		if (!empty ( $post_data['post_author'] ) ) {
  61			$post_data['post_author'] = (int) $post_data['post_author'];
  62		} else {
  63			$post_data['post_author'] = (int) $post_data['user_ID'];
  64		}
  65	}
  66
  67	if ( isset( $post_data['user_ID'] ) && ( $post_data['post_author'] != $post_data['user_ID'] )
  68		 && ! current_user_can( $ptype->cap->edit_others_posts ) ) {
  69		if ( $update ) {
  70			if ( 'page' == $post_data['post_type'] )
  71				return new WP_Error( 'edit_others_pages', __( 'You are not allowed to edit pages as this user.' ) );
  72			else
  73				return new WP_Error( 'edit_others_posts', __( 'You are not allowed to edit posts as this user.' ) );
  74		} else {
  75			if ( 'page' == $post_data['post_type'] )
  76				return new WP_Error( 'edit_others_pages', __( 'You are not allowed to create pages as this user.' ) );
  77			else
  78				return new WP_Error( 'edit_others_posts', __( 'You are not allowed to create posts as this user.' ) );
  79		}
  80	}
  81
  82	if ( ! empty( $post_data['post_status'] ) ) {
  83		$post_data['post_status'] = sanitize_key( $post_data['post_status'] );
  84
  85		// No longer an auto-draft
  86		if ( 'auto-draft' === $post_data['post_status'] ) {
  87			$post_data['post_status'] = 'draft';
  88		}
  89
  90		if ( ! get_post_status_object( $post_data['post_status'] ) ) {
  91			unset( $post_data['post_status'] );
  92		}
  93	}
  94
  95	// What to do based on which button they pressed
  96	if ( isset($post_data['saveasdraft']) && '' != $post_data['saveasdraft'] )
  97		$post_data['post_status'] = 'draft';
  98	if ( isset($post_data['saveasprivate']) && '' != $post_data['saveasprivate'] )
  99		$post_data['post_status'] = 'private';
 100	if ( isset($post_data['publish']) && ( '' != $post_data['publish'] ) && ( !isset($post_data['post_status']) || $post_data['post_status'] != 'private' ) )
 101		$post_data['post_status'] = 'publish';
 102	if ( isset($post_data['advanced']) && '' != $post_data['advanced'] )
 103		$post_data['post_status'] = 'draft';
 104	if ( isset($post_data['pending']) && '' != $post_data['pending'] )
 105		$post_data['post_status'] = 'pending';
 106
 107	if ( isset( $post_data['ID'] ) )
 108		$post_id = $post_data['ID'];
 109	else
 110		$post_id = false;
 111	$previous_status = $post_id ? get_post_field( 'post_status', $post_id ) : false;
 112
 113	if ( isset( $post_data['post_status'] ) && 'private' == $post_data['post_status'] && ! current_user_can( $ptype->cap->publish_posts ) ) {
 114		$post_data['post_status'] = $previous_status ? $previous_status : 'pending';
 115	}
 116
 117	$published_statuses = array( 'publish', 'future' );
 118
 119	// Posts 'submitted for approval' present are submitted to $_POST the same as if they were being published.
 120	// Change status from 'publish' to 'pending' if user lacks permissions to publish or to resave published posts.
 121	if ( isset($post_data['post_status']) && (in_array( $post_data['post_status'], $published_statuses ) && !current_user_can( $ptype->cap->publish_posts )) )
 122		if ( ! in_array( $previous_status, $published_statuses ) || !current_user_can( 'edit_post', $post_id ) )
 123			$post_data['post_status'] = 'pending';
 124
 125	if ( ! isset( $post_data['post_status'] ) ) {
 126		$post_data['post_status'] = 'auto-draft' === $previous_status ? 'draft' : $previous_status;
 127	}
 128
 129	if ( isset( $post_data['post_password'] ) && ! current_user_can( $ptype->cap->publish_posts ) ) {
 130		unset( $post_data['post_password'] );
 131	}
 132
 133	if (!isset( $post_data['comment_status'] ))
 134		$post_data['comment_status'] = 'closed';
 135
 136	if (!isset( $post_data['ping_status'] ))
 137		$post_data['ping_status'] = 'closed';
 138
 139	foreach ( array('aa', 'mm', 'jj', 'hh', 'mn') as $timeunit ) {
 140		if ( !empty( $post_data['hidden_' . $timeunit] ) && $post_data['hidden_' . $timeunit] != $post_data[$timeunit] ) {
 141			$post_data['edit_date'] = '1';
 142			break;
 143		}
 144	}
 145
 146	if ( !empty( $post_data['edit_date'] ) ) {
 147		$aa = $post_data['aa'];
 148		$mm = $post_data['mm'];
 149		$jj = $post_data['jj'];
 150		$hh = $post_data['hh'];
 151		$mn = $post_data['mn'];
 152		$ss = $post_data['ss'];
 153		$aa = ($aa <= 0 ) ? date('Y') : $aa;
 154		$mm = ($mm <= 0 ) ? date('n') : $mm;
 155		$jj = ($jj > 31 ) ? 31 : $jj;
 156		$jj = ($jj <= 0 ) ? date('j') : $jj;
 157		$hh = ($hh > 23 ) ? $hh -24 : $hh;
 158		$mn = ($mn > 59 ) ? $mn -60 : $mn;
 159		$ss = ($ss > 59 ) ? $ss -60 : $ss;
 160		$post_data['post_date'] = sprintf( "%04d-%02d-%02d %02d:%02d:%02d", $aa, $mm, $jj, $hh, $mn, $ss );
 161		$valid_date = wp_checkdate( $mm, $jj, $aa, $post_data['post_date'] );
 162		if ( !$valid_date ) {
 163			return new WP_Error( 'invalid_date', __( 'Whoops, the provided date is invalid.' ) );
 164		}
 165		$post_data['post_date_gmt'] = get_gmt_from_date( $post_data['post_date'] );
 166	}
 167
 168	return $post_data;
 169}
 170
 171/**
 172 * Update an existing post with values provided in $_POST.
 173 *
 174 * @since 1.5.0
 175 *
 176 * @param array $post_data Optional.
 177 * @return int Post ID.
 178 */
 179function edit_post( $post_data = null ) {
 180
 181	if ( empty($post_data) )
 182		$post_data = &$_POST;
 183
 184	// Clear out any data in internal vars.
 185	unset( $post_data['filter'] );
 186
 187	$post_ID = (int) $post_data['post_ID'];
 188	$post = get_post( $post_ID );
 189	$post_data['post_type'] = $post->post_type;
 190	$post_data['post_mime_type'] = $post->post_mime_type;
 191
 192	if ( ! empty( $post_data['post_status'] ) ) {
 193		$post_data['post_status'] = sanitize_key( $post_data['post_status'] );
 194
 195		if ( 'inherit' == $post_data['post_status'] ) {
 196			unset( $post_data['post_status'] );
 197		}
 198	}
 199
 200	$ptype = get_post_type_object($post_data['post_type']);
 201	if ( !current_user_can( 'edit_post', $post_ID ) ) {
 202		if ( 'page' == $post_data['post_type'] )
 203			wp_die( __('You are not allowed to edit this page.' ));
 204		else
 205			wp_die( __('You are not allowed to edit this post.' ));
 206	}
 207
 208	if ( post_type_supports( $ptype->name, 'revisions' ) ) {
 209		$revisions = wp_get_post_revisions( $post_ID, array( 'order' => 'ASC', 'posts_per_page' => 1 ) );
 210		$revision = current( $revisions );
 211
 212		// Check if the revisions have been upgraded
 213		if ( $revisions && _wp_get_post_revision_version( $revision ) < 1 )
 214			_wp_upgrade_revisions_of_post( $post, wp_get_post_revisions( $post_ID ) );
 215	}
 216
 217	if ( isset($post_data['visibility']) ) {
 218		switch ( $post_data['visibility'] ) {
 219			case 'public' :
 220				$post_data['post_password'] = '';
 221				break;
 222			case 'password' :
 223				unset( $post_data['sticky'] );
 224				break;
 225			case 'private' :
 226				$post_data['post_status'] = 'private';
 227				$post_data['post_password'] = '';
 228				unset( $post_data['sticky'] );
 229				break;
 230		}
 231	}
 232
 233	$post_data = _wp_translate_postdata( true, $post_data );
 234	if ( is_wp_error($post_data) )
 235		wp_die( $post_data->get_error_message() );
 236
 237	// Post Formats
 238	if ( isset( $post_data['post_format'] ) )
 239		set_post_format( $post_ID, $post_data['post_format'] );
 240
 241	$format_meta_urls = array( 'url', 'link_url', 'quote_source_url' );
 242	foreach ( $format_meta_urls as $format_meta_url ) {
 243		$keyed = '_format_' . $format_meta_url;
 244		if ( isset( $post_data[ $keyed ] ) )
 245			update_post_meta( $post_ID, $keyed, wp_slash( esc_url_raw( wp_unslash( $post_data[ $keyed ] ) ) ) );
 246	}
 247
 248	$format_keys = array( 'quote', 'quote_source_name', 'image', 'gallery', 'audio_embed', 'video_embed' );
 249
 250	foreach ( $format_keys as $key ) {
 251		$keyed = '_format_' . $key;
 252		if ( isset( $post_data[ $keyed ] ) ) {
 253			if ( current_user_can( 'unfiltered_html' ) )
 254				update_post_meta( $post_ID, $keyed, $post_data[ $keyed ] );
 255			else
 256				update_post_meta( $post_ID, $keyed, wp_filter_post_kses( $post_data[ $keyed ] ) );
 257		}
 258	}
 259
 260	if ( 'attachment' === $post_data['post_type'] && preg_match( '#^(audio|video)/#', $post_data['post_mime_type'] ) ) {
 261		$id3data = wp_get_attachment_metadata( $post_ID );
 262		if ( ! is_array( $id3data ) ) {
 263			$id3data = array();
 264		}
 265
 266		foreach ( wp_get_attachment_id3_keys( $post, 'edit' ) as $key => $label ) {
 267			if ( isset( $post_data[ 'id3_' . $key ] ) ) {
 268				$id3data[ $key ] = sanitize_text_field( wp_unslash( $post_data[ 'id3_' . $key ] ) );
 269			}
 270		}
 271		wp_update_attachment_metadata( $post_ID, $id3data );
 272	}
 273
 274	// Meta Stuff
 275	if ( isset($post_data['meta']) && $post_data['meta'] ) {
 276		foreach ( $post_data['meta'] as $key => $value ) {
 277			if ( !$meta = get_post_meta_by_id( $key ) )
 278				continue;
 279			if ( $meta->post_id != $post_ID )
 280				continue;
 281			if ( is_protected_meta( $value['key'], 'post' ) || ! current_user_can( 'edit_post_meta', $post_ID, $value['key'] ) )
 282				continue;
 283			update_meta( $key, $value['key'], $value['value'] );
 284		}
 285	}
 286
 287	if ( isset($post_data['deletemeta']) && $post_data['deletemeta'] ) {
 288		foreach ( $post_data['deletemeta'] as $key => $value ) {
 289			if ( !$meta = get_post_meta_by_id( $key ) )
 290				continue;
 291			if ( $meta->post_id != $post_ID )
 292				continue;
 293			if ( is_protected_meta( $meta->meta_key, 'post' ) || ! current_user_can( 'delete_post_meta', $post_ID, $meta->meta_key ) )
 294				continue;
 295			delete_meta( $key );
 296		}
 297	}
 298
 299	// Attachment stuff
 300	if ( 'attachment' == $post_data['post_type'] ) {
 301		if ( isset( $post_data[ '_wp_attachment_image_alt' ] ) ) {
 302			$image_alt = wp_unslash( $post_data['_wp_attachment_image_alt'] );
 303			if ( $image_alt != get_post_meta( $post_ID, '_wp_attachment_image_alt', true ) ) {
 304				$image_alt = wp_strip_all_tags( $image_alt, true );
 305				// update_meta expects slashed
 306				update_post_meta( $post_ID, '_wp_attachment_image_alt', wp_slash( $image_alt ) );
 307			}
 308		}
 309
 310		$attachment_data = isset( $post_data['attachments'][ $post_ID ] ) ? $post_data['attachments'][ $post_ID ] : array();
 311
 312		/** This filter is documented in wp-admin/includes/media.php */
 313		$post_data = apply_filters( 'attachment_fields_to_save', $post_data, $attachment_data );
 314	}
 315
 316	add_meta( $post_ID );
 317
 318	update_post_meta( $post_ID, '_edit_last', get_current_user_id() );
 319
 320	wp_update_post( $post_data );
 321
 322	// Now that we have an ID we can fix any attachment anchor hrefs
 323	_fix_attachment_links( $post_ID );
 324
 325	wp_set_post_lock( $post_ID );
 326
 327	if ( current_user_can( $ptype->cap->edit_others_posts ) ) {
 328		if ( ! empty( $post_data['sticky'] ) )
 329			stick_post( $post_ID );
 330		else
 331			unstick_post( $post_ID );
 332	}
 333
 334	return $post_ID;
 335}
 336
 337/**
 338 * Process the post data for the bulk editing of posts.
 339 *
 340 * Updates all bulk edited posts/pages, adding (but not removing) tags and
 341 * categories. Skips pages when they would be their own parent or child.
 342 *
 343 * @since 2.7.0
 344 *
 345 * @param array $post_data Optional, the array of post data to process if not provided will use $_POST superglobal.
 346 * @return array
 347 */
 348function bulk_edit_posts( $post_data = null ) {
 349	global $wpdb;
 350
 351	if ( empty($post_data) )
 352		$post_data = &$_POST;
 353
 354	if ( isset($post_data['post_type']) )
 355		$ptype = get_post_type_object($post_data['post_type']);
 356	else
 357		$ptype = get_post_type_object('post');
 358
 359	if ( !current_user_can( $ptype->cap->edit_posts ) ) {
 360		if ( 'page' == $ptype->name )
 361			wp_die( __('You are not allowed to edit pages.'));
 362		else
 363			wp_die( __('You are not allowed to edit posts.'));
 364	}
 365
 366	if ( -1 == $post_data['_status'] ) {
 367		$post_data['post_status'] = null;
 368		unset($post_data['post_status']);
 369	} else {
 370		$post_data['post_status'] = $post_data['_status'];
 371	}
 372	unset($post_data['_status']);
 373
 374	if ( ! empty( $post_data['post_status'] ) ) {
 375		$post_data['post_status'] = sanitize_key( $post_data['post_status'] );
 376
 377		if ( 'inherit' == $post_data['post_status'] ) {
 378			unset( $post_data['post_status'] );
 379		}
 380	}
 381
 382	$post_IDs = array_map( 'intval', (array) $post_data['post'] );
 383
 384	$reset = array(
 385		'post_author', 'post_status', 'post_password',
 386		'post_parent', 'page_template', 'comment_status',
 387		'ping_status', 'keep_private', 'tax_input',
 388		'post_category', 'sticky', 'post_format',
 389	);
 390
 391	foreach ( $reset as $field ) {
 392		if ( isset($post_data[$field]) && ( '' == $post_data[$field] || -1 == $post_data[$field] ) )
 393			unset($post_data[$field]);
 394	}
 395
 396	if ( isset($post_data['post_category']) ) {
 397		if ( is_array($post_data['post_category']) && ! empty($post_data['post_category']) )
 398			$new_cats = array_map( 'absint', $post_data['post_category'] );
 399		else
 400			unset($post_data['post_category']);
 401	}
 402
 403	$tax_input = array();
 404	if ( isset($post_data['tax_input'])) {
 405		foreach ( $post_data['tax_input'] as $tax_name => $terms ) {
 406			if ( empty($terms) )
 407				continue;
 408			if ( is_taxonomy_hierarchical( $tax_name ) ) {
 409				$tax_input[ $tax_name ] = array_map( 'absint', $terms );
 410			} else {
 411				$comma = _x( ',', 'tag delimiter' );
 412				if ( ',' !== $comma )
 413					$terms = str_replace( $comma, ',', $terms );
 414				$tax_input[ $tax_name ] = explode( ',', trim( $terms, " \n\t\r\0\x0B," ) );
 415			}
 416		}
 417	}
 418
 419	if ( isset($post_data['post_parent']) && ($parent = (int) $post_data['post_parent']) ) {
 420		$pages = $wpdb->get_results("SELECT ID, post_parent FROM $wpdb->posts WHERE post_type = 'page'");
 421		$children = array();
 422
 423		for ( $i = 0; $i < 50 && $parent > 0; $i++ ) {
 424			$children[] = $parent;
 425
 426			foreach ( $pages as $page ) {
 427				if ( $page->ID == $parent ) {
 428					$parent = $page->post_parent;
 429					break;
 430				}
 431			}
 432		}
 433	}
 434
 435	$updated = $skipped = $locked = array();
 436	$shared_post_data = $post_data;
 437
 438	foreach ( $post_IDs as $post_ID ) {
 439		// Start with fresh post data with each iteration.
 440		$post_data = $shared_post_data;
 441
 442		$post_type_object = get_post_type_object( get_post_type( $post_ID ) );
 443
 444		if ( !isset( $post_type_object ) || ( isset($children) && in_array($post_ID, $children) ) || !current_user_can( 'edit_post', $post_ID ) ) {
 445			$skipped[] = $post_ID;
 446			continue;
 447		}
 448
 449		if ( wp_check_post_lock( $post_ID ) ) {
 450			$locked[] = $post_ID;
 451			continue;
 452		}
 453
 454		$post = get_post( $post_ID );
 455		$tax_names = get_object_taxonomies( $post );
 456		foreach ( $tax_names as $tax_name ) {
 457			$taxonomy_obj = get_taxonomy($tax_name);
 458			if ( isset( $tax_input[$tax_name]) && current_user_can( $taxonomy_obj->cap->assign_terms ) )
 459				$new_terms = $tax_input[$tax_name];
 460			else
 461				$new_terms = array();
 462
 463			if ( $taxonomy_obj->hierarchical )
 464				$current_terms = (array) wp_get_object_terms( $post_ID, $tax_name, array('fields' => 'ids') );
 465			else
 466				$current_terms = (array) wp_get_object_terms( $post_ID, $tax_name, array('fields' => 'names') );
 467
 468			$post_data['tax_input'][$tax_name] = array_merge( $current_terms, $new_terms );
 469		}
 470
 471		if ( isset($new_cats) && in_array( 'category', $tax_names ) ) {
 472			$cats = (array) wp_get_post_categories($post_ID);
 473			$post_data['post_category'] = array_unique( array_merge($cats, $new_cats) );
 474			unset( $post_data['tax_input']['category'] );
 475		}
 476
 477		$post_data['post_type'] = $post->post_type;
 478		$post_data['post_mime_type'] = $post->post_mime_type;
 479		$post_data['guid'] = $post->guid;
 480
 481		foreach ( array( 'comment_status', 'ping_status', 'post_author' ) as $field ) {
 482			if ( ! isset( $post_data[ $field ] ) ) {
 483				$post_data[ $field ] = $post->$field;
 484			}
 485		}
 486
 487		$post_data['ID'] = $post_ID;
 488		$post_data['post_ID'] = $post_ID;
 489
 490		$post_data = _wp_translate_postdata( true, $post_data );
 491		if ( is_wp_error( $post_data ) ) {
 492			$skipped[] = $post_ID;
 493			continue;
 494		}
 495
 496		$updated[] = wp_update_post( $post_data );
 497
 498		if ( isset( $post_data['sticky'] ) && current_user_can( $ptype->cap->edit_others_posts ) ) {
 499			if ( 'sticky' == $post_data['sticky'] )
 500				stick_post( $post_ID );
 501			else
 502				unstick_post( $post_ID );
 503		}
 504
 505		if ( isset( $post_data['post_format'] ) )
 506			set_post_format( $post_ID, $post_data['post_format'] );
 507	}
 508
 509	return array( 'updated' => $updated, 'skipped' => $skipped, 'locked' => $locked );
 510}
 511
 512/**
 513 * Default post information to use when populating the "Write Post" form.
 514 *
 515 * @since 2.0.0
 516 *
 517 * @param string $post_type A post type string, defaults to 'post'.
 518 * @return WP_Post Post object containing all the default post data as attributes
 519 */
 520function get_default_post_to_edit( $post_type = 'post', $create_in_db = false ) {
 521	$post_title = '';
 522	if ( !empty( $_REQUEST['post_title'] ) )
 523		$post_title = esc_html( wp_unslash( $_REQUEST['post_title'] ));
 524
 525	$post_content = '';
 526	if ( !empty( $_REQUEST['content'] ) )
 527		$post_content = esc_html( wp_unslash( $_REQUEST['content'] ));
 528
 529	$post_excerpt = '';
 530	if ( !empty( $_REQUEST['excerpt'] ) )
 531		$post_excerpt = esc_html( wp_unslash( $_REQUEST['excerpt'] ));
 532
 533	if ( $create_in_db ) {
 534		$post_id = wp_insert_post( array( 'post_title' => __( 'Auto Draft' ), 'post_type' => $post_type, 'post_status' => 'auto-draft' ) );
 535		$post = get_post( $post_id );
 536		if ( current_theme_supports( 'post-formats' ) && post_type_supports( $post->post_type, 'post-formats' ) && get_option( 'default_post_format' ) )
 537			set_post_format( $post, get_option( 'default_post_format' ) );
 538	} else {
 539		$post = new stdClass;
 540		$post->ID = 0;
 541		$post->post_author = '';
 542		$post->post_date = '';
 543		$post->post_date_gmt = '';
 544		$post->post_password = '';
 545		$post->post_type = $post_type;
 546		$post->post_status = 'draft';
 547		$post->to_ping = '';
 548		$post->pinged = '';
 549		$post->comment_status = get_option( 'default_comment_status' );
 550		$post->ping_status = get_option( 'default_ping_status' );
 551		$post->post_pingback = get_option( 'default_pingback_flag' );
 552		$post->post_category = get_option( 'default_category' );
 553		$post->page_template = 'default';
 554		$post->post_parent = 0;
 555		$post->menu_order = 0;
 556		$post = new WP_Post( $post );
 557	}
 558
 559	/**
 560	 * Filter the default post content initially used in the "Write Post" form.
 561	 *
 562	 * @since 1.5.0
 563	 *
 564	 * @param string  $post_content Default post content.
 565	 * @param WP_Post $post         Post object.
 566	 */
 567	$post->post_content = apply_filters( 'default_content', $post_content, $post );
 568
 569	/**
 570	 * Filter the default post title initially used in the "Write Post" form.
 571	 *
 572	 * @since 1.5.0
 573	 *
 574	 * @param string  $post_title Default post title.
 575	 * @param WP_Post $post       Post object.
 576	 */
 577	$post->post_title = apply_filters( 'default_title', $post_title, $post );
 578
 579	/**
 580	 * Filter the default post excerpt initially used in the "Write Post" form.
 581	 *
 582	 * @since 1.5.0
 583	 *
 584	 * @param string  $post_excerpt Default post excerpt.
 585	 * @param WP_Post $post         Post object.
 586	 */
 587	$post->post_excerpt = apply_filters( 'default_excerpt', $post_excerpt, $post );
 588	$post->post_name = '';
 589
 590	return $post;
 591}
 592
 593/**
 594 * Determine if a post exists based on title, content, and date
 595 *
 596 * @since 2.0.0
 597 *
 598 * @param string $title Post title
 599 * @param string $content Optional post content
 600 * @param string $date Optional post date
 601 * @return int Post ID if post exists, 0 otherwise.
 602 */
 603function post_exists($title, $content = '', $date = '') {
 604	global $wpdb;
 605
 606	$post_title = wp_unslash( sanitize_post_field( 'post_title', $title, 0, 'db' ) );
 607	$post_content = wp_unslash( sanitize_post_field( 'post_content', $content, 0, 'db' ) );
 608	$post_date = wp_unslash( sanitize_post_field( 'post_date', $date, 0, 'db' ) );
 609
 610	$query = "SELECT ID FROM $wpdb->posts WHERE 1=1";
 611	$args = array();
 612
 613	if ( !empty ( $date ) ) {
 614		$query .= ' AND post_date = %s';
 615		$args[] = $post_date;
 616	}
 617
 618	if ( !empty ( $title ) ) {
 619		$query .= ' AND post_title = %s';
 620		$args[] = $post_title;
 621	}
 622
 623	if ( !empty ( $content ) ) {
 624		$query .= 'AND post_content = %s';
 625		$args[] = $post_content;
 626	}
 627
 628	if ( !empty ( $args ) )
 629		return (int) $wpdb->get_var( $wpdb->prepare($query, $args) );
 630
 631	return 0;
 632}
 633
 634/**
 635 * Creates a new post from the "Write Post" form using $_POST information.
 636 *
 637 * @since 2.1.0
 638 *
 639 * @return unknown
 640 */
 641function wp_write_post() {
 642	if ( isset($_POST['post_type']) )
 643		$ptype = get_post_type_object($_POST['post_type']);
 644	else
 645		$ptype = get_post_type_object('post');
 646
 647	if ( !current_user_can( $ptype->cap->edit_posts ) ) {
 648		if ( 'page' == $ptype->name )
 649			return new WP_Error( 'edit_pages', __( 'You are not allowed to create pages on this site.' ) );
 650		else
 651			return new WP_Error( 'edit_posts', __( 'You are not allowed to create posts or drafts on this site.' ) );
 652	}
 653
 654	$_POST['post_mime_type'] = '';
 655
 656	// Clear out any data in internal vars.
 657	unset( $_POST['filter'] );
 658
 659	// Edit don't write if we have a post id.
 660	if ( isset( $_POST['post_ID'] ) )
 661		return edit_post();
 662
 663	if ( isset($_POST['visibility']) ) {
 664		switch ( $_POST['visibility'] ) {
 665			case 'public' :
 666				$_POST['post_password'] = '';
 667				break;
 668			case 'password' :
 669				unset( $_POST['sticky'] );
 670				break;
 671			case 'private' :
 672				$_POST['post_status'] = 'private';
 673				$_POST['post_password'] = '';
 674				unset( $_POST['sticky'] );
 675				break;
 676		}
 677	}
 678
 679	$translated = _wp_translate_postdata( false );
 680	if ( is_wp_error($translated) )
 681		return $translated;
 682
 683	// Create the post.
 684	$post_ID = wp_insert_post( $_POST );
 685	if ( is_wp_error( $post_ID ) )
 686		return $post_ID;
 687
 688	if ( empty($post_ID) )
 689		return 0;
 690
 691	add_meta( $post_ID );
 692
 693	add_post_meta( $post_ID, '_edit_last', $GLOBALS['current_user']->ID );
 694
 695	// Now that we have an ID we can fix any attachment anchor hrefs
 696	_fix_attachment_links( $post_ID );
 697
 698	wp_set_post_lock( $post_ID );
 699
 700	return $post_ID;
 701}
 702
 703/**
 704 * Calls wp_write_post() and handles the errors.
 705 *
 706 * @since 2.0.0
 707
 708 * @uses wp_write_post()
 709 * @uses is_wp_error()
 710 * @uses wp_die()
 711 * @return unknown
 712 */
 713function write_post() {
 714	$result = wp_write_post();
 715	if ( is_wp_error( $result ) )
 716		wp_die( $result->get_error_message() );
 717	else
 718		return $result;
 719}
 720
 721//
 722// Post Meta
 723//
 724
 725/**
 726 * {@internal Missing Short Description}}
 727 *
 728 * @since 1.2.0
 729 *
 730 * @param unknown_type $post_ID
 731 * @return unknown
 732 */
 733function add_meta( $post_ID ) {
 734	$post_ID = (int) $post_ID;
 735
 736	$metakeyselect = isset($_POST['metakeyselect']) ? wp_unslash( trim( $_POST['metakeyselect'] ) ) : '';
 737	$metakeyinput = isset($_POST['metakeyinput']) ? wp_unslash( trim( $_POST['metakeyinput'] ) ) : '';
 738	$metavalue = isset($_POST['metavalue']) ? $_POST['metavalue'] : '';
 739	if ( is_string( $metavalue ) )
 740		$metavalue = trim( $metavalue );
 741
 742	if ( ('0' === $metavalue || ! empty ( $metavalue ) ) && ( ( ( '#NONE#' != $metakeyselect ) && !empty ( $metakeyselect) ) || !empty ( $metakeyinput ) ) ) {
 743		// We have a key/value pair. If both the select and the
 744		// input for the key have data, the input takes precedence:
 745
 746 		if ( '#NONE#' != $metakeyselect )
 747			$metakey = $metakeyselect;
 748
 749		if ( $metakeyinput )
 750			$metakey = $metakeyinput; // default
 751
 752		if ( is_protected_meta( $metakey, 'post' ) || ! current_user_can( 'add_post_meta', $post_ID, $metakey ) )
 753			return false;
 754
 755		$metakey = wp_slash( $metakey );
 756
 757		return add_post_meta( $post_ID, $metakey, $metavalue );
 758	}
 759
 760	return false;
 761} // add_meta
 762
 763/**
 764 * {@internal Missing Short Description}}
 765 *
 766 * @since 1.2.0
 767 *
 768 * @param unknown_type $mid
 769 * @return unknown
 770 */
 771function delete_meta( $mid ) {
 772	return delete_metadata_by_mid( 'post' , $mid );
 773}
 774
 775/**
 776 * Get a list of previously defined keys.
 777 *
 778 * @since 1.2.0
 779 *
 780 * @return unknown
 781 */
 782function get_meta_keys() {
 783	global $wpdb;
 784
 785	$keys = $wpdb->get_col( "
 786			SELECT meta_key
 787			FROM $wpdb->postmeta
 788			GROUP BY meta_key
 789			ORDER BY meta_key" );
 790
 791	return $keys;
 792}
 793
 794/**
 795 * {@internal Missing Short Description}}
 796 *
 797 * @since 2.1.0
 798 *
 799 * @param unknown_type $mid
 800 * @return unknown
 801 */
 802function get_post_meta_by_id( $mid ) {
 803	return get_metadata_by_mid( 'post', $mid );
 804}
 805
 806/**
 807 * {@internal Missing Short Description}}
 808 *
 809 * Some postmeta stuff.
 810 *
 811 * @since 1.2.0
 812 *
 813 * @param unknown_type $postid
 814 * @return unknown
 815 */
 816function has_meta( $postid ) {
 817	global $wpdb;
 818
 819	return $wpdb->get_results( $wpdb->prepare("SELECT meta_key, meta_value, meta_id, post_id
 820			FROM $wpdb->postmeta WHERE post_id = %d
 821			ORDER BY meta_key,meta_id", $postid), ARRAY_A );
 822}
 823
 824/**
 825 * {@internal Missing Short Description}}
 826 *
 827 * @since 1.2.0
 828 *
 829 * @param unknown_type $meta_id
 830 * @param unknown_type $meta_key Expect Slashed
 831 * @param unknown_type $meta_value Expect Slashed
 832 * @return unknown
 833 */
 834function update_meta( $meta_id, $meta_key, $meta_value ) {
 835	$meta_key = wp_unslash( $meta_key );
 836	$meta_value = wp_unslash( $meta_value );
 837
 838	return update_metadata_by_mid( 'post', $meta_id, $meta_value, $meta_key );
 839}
 840
 841//
 842// Private
 843//
 844
 845/**
 846 * Replace hrefs of attachment anchors with up-to-date permalinks.
 847 *
 848 * @since 2.3.0
 849 * @access private
 850 *
 851 * @param int|object $post Post ID or post object.
 852 * @return void|int|WP_Error Void if nothing fixed. 0 or WP_Error on update failure. The post ID on update success.
 853 */
 854function _fix_attachment_links( $post ) {
 855	$post = get_post( $post, ARRAY_A );
 856	$content = $post['post_content'];
 857
 858	// Don't run if no pretty permalinks or post is not published, scheduled, or privately published.
 859	if ( ! get_option( 'permalink_structure' ) || ! in_array( $post['post_status'], array( 'publish', 'future', 'private' ) ) )
 860		return;
 861
 862	// Short if there aren't any links or no '?attachment_id=' strings (strpos cannot be zero)
 863	if ( !strpos($content, '?attachment_id=') || !preg_match_all( '/<a ([^>]+)>[\s\S]+?<\/a>/', $content, $link_matches ) )
 864		return;
 865
 866	$site_url = get_bloginfo('url');
 867	$site_url = substr( $site_url, (int) strpos($site_url, '://') ); // remove the http(s)
 868	$replace = '';
 869
 870	foreach ( $link_matches[1] as $key => $value ) {
 871		if ( !strpos($value, '?attachment_id=') || !strpos($value, 'wp-att-')
 872			|| !preg_match( '/href=(["\'])[^"\']*\?attachment_id=(\d+)[^"\']*\\1/', $value, $url_match )
 873			|| !preg_match( '/rel=["\'][^"\']*wp-att-(\d+)/', $value, $rel_match ) )
 874				continue;
 875
 876		$quote = $url_match[1]; // the quote (single or double)
 877		$url_id = (int) $url_match[2];
 878		$rel_id = (int) $rel_match[1];
 879
 880		if ( !$url_id || !$rel_id || $url_id != $rel_id || strpos($url_match[0], $site_url) === false )
 881			continue;
 882
 883		$link = $link_matches[0][$key];
 884		$replace = str_replace( $url_match[0], 'href=' . $quote . get_attachment_link( $url_id ) . $quote, $link );
 885
 886		$content = str_replace( $link, $replace, $content );
 887	}
 888
 889	if ( $replace ) {
 890		$post['post_content'] = $content;
 891		// Escape data pulled from DB.
 892		$post = add_magic_quotes($post);
 893
 894		return wp_update_post($post);
 895	}
 896}
 897
 898/**
 899 * Get all the possible statuses for a post_type
 900 *
 901 * @since 2.5.0
 902 *
 903 * @param string $type The post_type you want the statuses for
 904 * @return array As array of all the statuses for the supplied post type
 905 */
 906function get_available_post_statuses($type = 'post') {
 907	$stati = wp_count_posts($type);
 908
 909	return array_keys(get_object_vars($stati));
 910}
 911
 912/**
 913 * Run the wp query to fetch the posts for listing on the edit posts page
 914 *
 915 * @since 2.5.0
 916 *
 917 * @param array|bool $q Array of query variables to use to build the query or false to use $_GET superglobal.
 918 * @return array
 919 */
 920function wp_edit_posts_query( $q = false ) {
 921	if ( false === $q )
 922		$q = $_GET;
 923	$q['m'] = isset($q['m']) ? (int) $q['m'] : 0;
 924	$q['cat'] = isset($q['cat']) ? (int) $q['cat'] : 0;
 925	$post_stati  = get_post_stati();
 926
 927	if ( isset($q['post_type']) && in_array( $q['post_type'], get_post_types() ) )
 928		$post_type = $q['post_type'];
 929	else
 930		$post_type = 'post';
 931
 932	$avail_post_stati = get_available_post_statuses($post_type);
 933
 934	if ( isset($q['post_status']) && in_array( $q['post_status'], $post_stati ) ) {
 935		$post_status = $q['post_status'];
 936		$perm = 'readable';
 937	}
 938
 939	if ( isset($q['orderby']) )
 940		$orderby = $q['orderby'];
 941	elseif ( isset($q['post_status']) && in_array($q['post_status'], array('pending', 'draft')) )
 942		$orderby = 'modified';
 943
 944	if ( isset($q['order']) )
 945		$order = $q['order'];
 946	elseif ( isset($q['post_status']) && 'pending' == $q['post_status'] )
 947		$order = 'ASC';
 948
 949	$per_page = "edit_{$post_type}_per_page";
 950	$posts_per_page = (int) get_user_option( $per_page );
 951	if ( empty( $posts_per_page ) || $posts_per_page < 1 )
 952		$posts_per_page = 20;
 953
 954	/**
 955	 * Filter the number of items per page to show for a specific 'per_page' type.
 956	 *
 957	 * The dynamic portion of the hook name, $post_type, refers to the post type.
 958	 *
 959	 * Some examples of filter hooks generated here include: 'edit_attachment_per_page',
 960	 * 'edit_post_per_page', 'edit_page_per_page', etc.
 961	 *
 962	 * @since 3.0.0
 963	 *
 964	 * @param int $posts_per_page Number of posts to display per page for the given post
 965	 *                            type. Default 20.
 966	 */
 967	$posts_per_page = apply_filters( "edit_{$post_type}_per_page", $posts_per_page );
 968
 969	/**
 970	 * Filter the number of posts displayed per page when specifically listing "posts".
 971	 *
 972	 * @since 2.8.0
 973	 *
 974	 * @param int    $posts_per_page Number of posts to be displayed. Default 20.
 975	 * @param string $post_type      The post type.
 976	 */
 977	$posts_per_page = apply_filters( 'edit_posts_per_page', $posts_per_page, $post_type );
 978
 979	$query = compact('post_type', 'post_status', 'perm', 'order', 'orderby', 'posts_per_page');
 980
 981	// Hierarchical types require special args.
 982	if ( is_post_type_hierarchical( $post_type ) && !isset($orderby) ) {
 983		$query['orderby'] = 'menu_order title';
 984		$query['order'] = 'asc';
 985		$query['posts_per_page'] = -1;
 986		$query['posts_per_archive_page'] = -1;
 987	}
 988
 989	if ( ! empty( $q['show_sticky'] ) )
 990		$query['post__in'] = (array) get_option( 'sticky_posts' );
 991
 992	wp( $query );
 993
 994	return $avail_post_stati;
 995}
 996
 997/**
 998 * {@internal Missing Short Description}}
 999 *
1000 * @since 2.5.0
1001 *
1002 * @param unknown_type $type
1003 * @return unknown
1004 */
1005function get_available_post_mime_types($type = 'attachment') {
1006	global $wpdb;
1007
1008	$types = $wpdb->get_col($wpdb->prepare("SELECT DISTINCT post_mime_type FROM $wpdb->posts WHERE post_type = %s", $type));
1009	return $types;
1010}
1011
1012/**
1013 * Executes a query for attachments. An array of WP_Query arguments
1014 * can be passed in, which will override the arguments set by this function.
1015 *
1016 * @since 2.5.0
1017 *
1018 * @param array|bool $q Array of query variables to use to build the query or false to use $_GET superglobal.
1019 * @return array
1020 */
1021function wp_edit_attachments_query( $q = false ) {
1022	if ( false === $q )
1023		$q = $_GET;
1024
1025	$q['m']   = isset( $q['m'] ) ? (int) $q['m'] : 0;
1026	$q['cat'] = isset( $q['cat'] ) ? (int) $q['cat'] : 0;
1027	$q['post_type'] = 'attachment';
1028	$post_type = get_post_type_object( 'attachment' );
1029	$states = 'inherit';
1030	if ( current_user_can( $post_type->cap->read_private_posts ) )
1031		$states .= ',private';
1032
1033	$q['post_status'] = isset( $q['status'] ) && 'trash' == $q['status'] ? 'trash' : $states;
1034	$media_per_page = (int) get_user_option( 'upload_per_page' );
1035	if ( empty( $media_per_page ) || $media_per_page < 1 )
1036		$media_per_page = 20;
1037
1038	/**
1039	 * Filter the number of items to list per page when listing media items.
1040	 *
1041	 * @since 2.9.0
1042	 *
1043	 * @param int $media_per_page Number of media to list. Default 20.
1044	 */
1045	$q['posts_per_page'] = apply_filters( 'upload_per_page', $media_per_page );
1046
1047	$post_mime_types = get_post_mime_types();
1048	$avail_post_mime_types = get_available_post_mime_types('attachment');
1049
1050	if ( isset($q['post_mime_type']) && !array_intersect( (array) $q['post_mime_type'], array_keys($post_mime_types) ) )
1051		unset($q['post_mime_type']);
1052
1053	if ( isset($q['detached']) )
1054		$q['post_parent'] = 0;
1055
1056	wp( $q );
1057
1058	return array($post_mime_types, $avail_post_mime_types);
1059}
1060
1061/**
1062 * Returns the list of classes to be used by a metabox
1063 *
1064 * @uses get_user_option()
1065 * @since 2.5.0
1066 *
1067 * @param unknown_type $id
1068 * @param unknown_type $page
1069 * @return unknown
1070 */
1071function postbox_classes( $id, $page ) {
1072	if ( isset( $_GET['edit'] ) && $_GET['edit'] == $id ) {
1073		$classes = array( '' );
1074	} elseif ( $closed = get_user_option('closedpostboxes_'.$page ) ) {
1075		if ( !is_array( $closed ) ) {
1076			$classes = array( '' );
1077		} else {
1078			$classes = in_array( $id, $closed ) ? array( 'closed' ) : array( '' );
1079		}
1080	} else {
1081		$classes = array( '' );
1082	}
1083
1084	/**
1085	 * Filter the postbox classes for a specific screen and screen ID combo.
1086	 *
1087	 * The dynamic portions of the hook name, $page, and $id, refer to
1088	 * the screen, and screen ID, respectively.
1089	 *
1090	 * @since 3.2.0
1091	 *
1092	 * @param array $classes An array of postbox classes.
1093	 */
1094	$classes = apply_filters( "postbox_classes_{$page}_{$id}", $classes );
1095	return implode( ' ', $classes );
1096}
1097
1098/**
1099 * {@internal Missing Short Description}}
1100 *
1101 * @since 2.5.0
1102 *
1103 * @param int|object $id    Post ID or post object.
1104 * @param string $title (optional) Title
1105 * @param string $name (optional) Name
1106 * @return array With two entries of type string
1107 */
1108function get_sample_permalink($id, $title = null, $name = null) {
1109	$post = get_post( $id );
1110	if ( ! $post )
1111		return array( '', '' );
1112
1113	$ptype = get_post_type_object($post->post_type);
1114
1115	$original_status = $post->post_status;
1116	$original_date = $post->post_date;
1117	$original_name = $post->post_name;
1118
1119	// Hack: get_permalink() would return ugly permalink for drafts, so we will fake that our post is published.
1120	if ( in_array( $post->post_status, array( 'draft', 'pending' ) ) ) {
1121		$post->post_status = 'publish';
1122		$post->post_name = sanitize_title($post->post_name ? $post->post_name : $post->post_title, $post->ID);
1123	}
1124
1125	// If the user wants to set a new name -- override the current one
1126	// Note: if empty name is supplied -- use the title instead, see #6072
1127	if ( !is_null($name) )
1128		$post->post_name = sanitize_title($name ? $name : $title, $post->ID);
1129
1130	$post->post_name = wp_unique_post_slug($post->post_name, $post->ID, $post->post_status, $post->post_type, $post->post_parent);
1131
1132	$post->filter = 'sample';
1133
1134	$permalink = get_permalink($post, true);
1135
1136	// Replace custom post_type Token with generic pagename token for ease of use.
1137	$permalink = str_replace("%$post->post_type%", '%pagename%', $permalink);
1138
1139	// Handle page hierarchy
1140	if ( $ptype->hierarchical ) {
1141		$uri = get_page_uri($post);
1142		$uri = untrailingslashit($uri);
1143		$uri = strrev( stristr( strrev( $uri ), '/' ) );
1144		$uri = untrailingslashit($uri);
1145
1146		/** This filter is documented in wp-admin/edit-tag-form.php */
1147		$uri = apply_filters( 'editable_slug', $uri );
1148		if ( !empty($uri) )
1149			$uri .= '/';
1150		$permalink = str_replace('%pagename%', "{$uri}%pagename%", $permalink);
1151	}
1152
1153	/** This filter is documented in wp-admin/edit-tag-form.php */
1154	$permalink = array( $permalink, apply_filters( 'editable_slug', $post->post_name ) );
1155	$post->post_status = $original_status;
1156	$post->post_date = $original_date;
1157	$post->post_name = $original_name;
1158	unset($post->filter);
1159
1160	return $permalink;
1161}
1162
1163/**
1164 * Returns the HTML of the sample permalink slug editor.
1165 *
1166 * @since 2.5.0
1167 *
1168 * @param int|object $id Post ID or post object.
1169 * @param string $new_title Optional. New title.
1170 * @param string $new_slug Optional. New slug.
1171 * @return string The HTML of the sample permalink slug editor.
1172 */
1173function get_sample_permalink_html( $id, $new_title = null, $new_slug = null ) {
1174	$post = get_post( $id );
1175	if ( ! $post )
1176		return '';
1177
1178	list($permalink, $post_name) = get_sample_permalink($post->ID, $new_title, $new_slug);
1179
1180	if ( current_user_can( 'read_post', $post->ID ) ) {
1181		$ptype = get_post_type_object( $post->post_type );
1182		if( 'draft' == $post->post_status ) {
1183			$view_post = __( 'Preview' );
1184		} else {
1185			$view_post = $ptype->labels->view_item;
1186		}
1187	}
1188
1189	if ( 'publish' == get_post_status( $post ) ) {
1190		$title = __('Click to edit this part of the permalink');
1191	} else {
1192		$title = __('Temporary permalink. Click to edit this part.');
1193	}
1194
1195	if ( false === strpos( $permalink, '%postname%' ) && false === strpos( $permalink, '%pagename%' ) ) {
1196		$return = '<strong>' . __('Permalink:') . "</strong>\n" . '<span id="sample-permalink" tabindex="-1">' . $permalink . "</span>\n";
1197		if ( '' == get_option( 'permalink_structure' ) && current_user_can( 'manage_options' ) && !( 'page' == get_option('show_on_front') && $id == get_option('page_on_front') ) ) {
1198			$return .= '<span id="change-permalinks"><a href="options-permalink.php" class="button button-small" target="_blank">' . __('Change Permalinks') . "</a></span>\n";
1199		}
1200	} else {
1201		if ( function_exists( 'mb_strlen' ) && mb_strlen( $post_name ) > 30 ) {
1202			$post_name_abridged = mb_substr( $post_name, 0, 14 ) . '&hellip;' . mb_substr( $post_name, -14 );
1203		} elseif ( strlen( $post_name ) > 30 ) {
1204			$post_name_abridged = substr( $post_name, 0, 14 ) . '&hellip;' . substr( $post_name, -14 );
1205		} else {
1206			$post_name_abridged = $post_name;
1207		}
1208
1209		$post_name_html = '<span id="editable-post-name" title="' . $title . '">' . $post_name_abridged . '</span>';
1210		$display_link = str_replace( array( '%pagename%', '%postname%' ), $post_name_html, $permalink );
1211
1212		$return =  '<strong>' . __( 'Permalink:' ) . "</strong>\n";
1213		$return .= '<span id="sample-permalink" tabindex="-1">' . $display_link . "</span>\n";
1214		$return .= '&lrm;'; // Fix bi-directional text display defect in RTL languages.
1215		$return .= '<span id="edit-slug-buttons"><a href="#post_name" class="edit-slug button button-small hide-if-no-js" onclick="editPermalink(' . $id . '); return false;">' . __( 'Edit' ) . "</a></span>\n";
1216		$return .= '<span id="editable-post-name-full">' . $post_name . "</span>\n";
1217	}
1218
1219	if ( isset( $view_post ) ) {
1220		if( 'draft' == $post->post_status ) {
1221			$preview_link = set_url_scheme( get_permalink( $post->ID ) );
1222			/** This filter is documented in wp-admin/includes/meta-boxes.php */
1223			$preview_link = apply_filters( 'preview_post_link', add_query_arg( 'preview', 'true', $preview_link ), $post );
1224			$return .= "<span id='view-post-btn'><a href='" . esc_url( $preview_link ) . "' class='button button-small' target='wp-preview-{$post->ID}'>$view_post</a></span>\n";
1225		} else {
1226			$return .= "<span id='view-post-btn'><a href='" . get_permalink( $post ) . "' class='button button-small'>$view_post</a></span>\n";
1227		}
1228	}
1229
1230	/**
1231	 * Filter the sample permalink HTML markup.
1232	 *
1233	 * @since 2.9.0
1234	 *
1235	 * @param string      $return    Sample permalink HTML markup.
1236	 * @param int|WP_Post $id        Post object or ID.
1237	 * @param string      $new_title New sample permalink title.
1238	 * @param string      $new_slug  New sample permalink slug.
1239	 */
1240	$return = apply_filters( 'get_sample_permalink_html', $return, $id, $new_title, $new_slug );
1241
1242	return $return;
1243}
1244
1245/**
1246 * Output HTML for the post thumbnail meta-box.
1247 *
1248 * @since 2.9.0
1249 *
1250 * @param int $thumbnail_id ID of the attachment used for thumbnail
1251 * @param mixed $post The post ID or object associated with the thumbnail, defaults to global $post.
1252 * @return string html
1253 */
1254function _wp_post_thumbnail_html( $thumbnail_id = null, $post = null ) {
1255	global $content_width, $_wp_additional_image_sizes;
1256
1257	$post = get_post( $post );
1258
1259	$upload_iframe_src = esc_url( get_upload_iframe_src('image', $post->ID ) );
1260	$set_thumbnail_link = '<p class="hide-if-no-js"><a title="' . esc_attr__( 'Set featured image' ) . '" href="%s" id="set-post-thumbnail" class="thickbox">%s</a></p>';
1261	$content = sprintf( $set_thumbnail_link, $upload_iframe_src, esc_html__( 'Set featured image' ) );
1262
1263	if ( $thumbnail_id && get_post( $thumbnail_id ) ) {
1264		$old_content_width = $content_width;
1265		$content_width = 266;
1266		if ( !isset( $_wp_additional_image_sizes['post-thumbnail'] ) )
1267			$thumbnail_html = wp_get_attachment_image( $thumbnail_id, array( $content_width, $content_width ) );
1268		else
1269			$thumbnail_html = wp_get_attachment_image( $thumbnail_id, 'post-thumbnail' );
1270		if ( !empty( $thumbnail_html ) ) {
1271			$ajax_nonce = wp_create_nonce( 'set_post_thumbnail-' . $post->ID );
1272			$content = sprintf( $set_thumbnail_link, $upload_iframe_src, $thumbnail_html );
1273			$content .= '<p class="hide-if-no-js"><a href="#" id="remove-post-thumbnail" onclick="WPRemoveThumbnail(\'' . $ajax_nonce . '\');return false;">' . esc_html__( 'Remove featured image' ) . '</a></p>';
1274		}
1275		$content_width = $old_content_width;
1276	}
1277
1278	/**
1279	 * Filter the admin post thumbnail HTML markup to return.
1280	 *
1281	 * @since 2.9.0
1282	 *
1283	 * @param string $content Admin post thumbnail HTML markup.
1284	 * @param int    $post_id Post ID.
1285	 */
1286	return apply_filters( 'admin_post_thumbnail_html', $content, $post->ID );
1287}
1288
1289/**
1290 * Check to see if the post is currently being edited by another user.
1291 *
1292 * @since 2.5.0
1293 *
1294 * @param int $post_id ID of the post to check for editing
1295 * @return bool|int False: not locked or locked by current user. Int: user ID of user with lock.
1296 */
1297function wp_check_post_lock( $post_id ) {
1298	if ( !$post = get_post( $post_id ) )
1299		return false;
1300
1301	if ( !$lock = get_post_meta( $post->ID, '_edit_lock', true ) )
1302		return false;
1303
1304	$lock = explode( ':', $lock );
1305	$time = $lock[0];
1306	$user = isset( $lock[1] ) ? $lock[1] : get_post_meta( $post->ID, '_edit_last', true );
1307
1308	/** This filter is documented in wp-admin/includes/ajax-actions.php */
1309	$time_window = apply_filters( 'wp_check_post_lock_window', 150 );
1310
1311	if ( $time && $time > time() - $time_window && $user != get_current_user_id() )
1312		return $user;
1313	return false;
1314}
1315
1316/**
1317 * Mark the post as currently being edited by the current user
1318 *
1319 * @since 2.5.0
1320 *
1321 * @param int $post_id ID of the post to being edited
1322 * @return bool|array Returns false if the post doesn't exist of there is no current user, or
1323 * 	an array of the lock time and the user ID.
1324 */
1325function wp_set_post_lock( $post_id ) {
1326	if ( !$post = get_post( $post_id ) )
1327		return false;
1328	if ( 0 == ($user_id = get_current_user_id()) )
1329		return false;
1330
1331	$now = time();
1332	$lock = "$now:$user_id";
1333
1334	update_post_meta( $post->ID, '_edit_lock', $lock );
1335	return array( $now, $user_id );
1336}
1337
1338/**
1339 * Outputs the HTML for the notice to say that someone else is editing or has taken over editing of this post.
1340 *
1341 * @since 2.8.5
1342 * @return none
1343 */
1344function _admin_notice_post_locked() {
1345	if ( ! $post = get_post() )
1346		return;
1347
1348	$user = null;
1349	if (  $user_id = wp_check_post_lock( $post->ID ) )
1350		$user = get_userdata( $user_id );
1351
1352	if ( $user ) {
1353
1354		/**
1355		 * Filter whether to show the post locked dialog.
1356		 *
1357		 * Returning a falsey value to the filter will short-circuit displaying the dialog.
1358		 *
1359		 * @since 3.6.0
1360		 *
1361		 * @param bool         $display Whether to display the dialog. Default true.
1362		 * @param WP_User|bool $user    WP_User object on success, false otherwise.
1363		 */
1364		if ( ! apply_filters( 'show_post_locked_dialog', true, $post, $user ) )
1365			return;
1366
1367		$locked = true;
1368	} else {
1369		$locked = false;
1370	}
1371
1372	if ( $locked && ( $sendback = wp_get_referer() ) &&
1373		false === strpos( $sendback, 'post.php' ) && false === strpos( $sendback, 'post-new.php' ) ) {
1374
1375		$sendback_text = __('Go back');
1376	} else {
1377		$sendback = admin_url( 'edit.php' );
1378
1379		if ( 'post' != $post->post_type )
1380			$sendback = add_query_arg( 'post_type', $post->post_type, $sendback );
1381
1382		$sendback_text = get_post_type_object( $post->post_type )->labels->all_items;
1383	}
1384
1385	$hidden = $locked ? '' : ' hidden';
1386
1387	?>
1388	<div id="post-lock-dialog" class="notification-dialog-wrap<?php echo $hidden; ?>">
1389	<div class="notification-dialog-background"></div>
1390	<div class="notification-dialog">
1391	<?php
1392
1393	if ( $locked ) {
1394		if ( get_post_type_object( $post->post_type )->public ) {
1395			$preview_link = set_url_scheme( add_query_arg( 'preview', 'true', get_permalink( $post->ID ) ) );
1396
1397			if ( 'publish' == $post->post_status || $user->ID != $post->post_author ) {
1398				// Latest content is in autosave
1399				$nonce = wp_create_nonce( 'post_preview_' . $post->ID );
1400				$preview_link = add_query_arg( array( 'preview_id' => $post->ID, 'preview_nonce' => $nonce ), $preview_link );
1401			}
1402		} else {
1403			$preview_link = '';
1404		}
1405
1406		/** This filter is documented in wp-admin/includes/meta-boxes.php */
1407		$preview_link = apply_filters( 'preview_post_link', $preview_link, $post );
1408
1409		/**
1410		 * Filter whether to allow the post lock to be overridden.
1411		 *
1412		 * Returning a falsey value to the filter will disable the ability
1413		 * to override the post lock.
1414		 *
1415		 * @since 3.6.0
1416		 *
1417		 * @param bool    $override Whether to allow overriding post locks. Default true.
1418		 * @param WP_Post $post     Post object.
1419		 * @param WP_User $user     User object.
1420		 */
1421		$override = apply_filters( 'override_post_lock', true, $post, $user );
1422		$tab_last = $override ? '' : ' wp-tab-last';
1423
1424		?>
1425		<div class="post-locked-message">
1426		<div class="post-locked-avatar"><?php echo get_avatar( $user->ID, 64 ); ?></div>
1427		<p class="currently-editing wp-tab-first" tabindex="0">
1428		<?php
1429			_e( 'This content is currently locked.' );
1430			if ( $override )
1431				printf( ' ' . __( 'If you take over, %s will be blocked from continuing to edit.' ), esc_html( $user->display_name ) );
1432		?>
1433		</p>
1434		<?php
1435		/**
1436		 * Fires inside the post locked dialog before the buttons are displayed.
1437		 *
1438		 * @since 3.6.0
1439		 *
1440		 * @param WP_Post $post Post object.
1441		 */
1442		do_action( 'post_locked_dialog', $post );
1443		?>
1444		<p>
1445		<a class="button" href="<?php echo esc_url( $sendback ); ?>"><?php echo $sendback_text; ?></a>
1446		<?php if ( $preview_link ) { ?>
1447		<a class="button<?php echo $tab_last; ?>" href="<?php echo esc_url( $preview_link ); ?>"><?php _e('Preview'); ?></a>
1448		<?php
1449		}
1450
1451		// Allow plugins to prevent some users overriding the post lock
1452		if ( $override ) {
1453			?>
1454			<a class="button button-primary wp-tab-last" href="<?php echo esc_url( add_query_arg( 'get-post-lock', '1', get_edit_post_link( $post->ID, 'url' ) ) ); ?>"><?php _e('Take over'); ?></a>
1455			<?php
1456		}
1457
1458		?>
1459		</p>
1460		</div>
1461		<?php
1462	} else {
1463		?>
1464		<div class="post-taken-over">
1465			<div class="post-locked-avatar"></div>
1466			<p class="wp-tab-first" tabindex="0">
1467			<span class="currently-editing"></span><br />
1468			<span class="locked-saving hidden"><img src="images/wpspin_light-2x.gif" width="16" height="16" /> <?php _e('Saving revision...'); ?></span>
1469			<span class="locked-saved hidden"><?php _e('Your latest changes were saved as a revision.'); ?></span>
1470			</p>
1471			<?php
1472			/**
1473			 * Fires inside the dialog displayed when a user has lost the post lock.
1474			 *
1475			 * @since 3.6.0
1476			 *
1477			 * @param WP_Post $post Post object.
1478			 */
1479			do_action( 'post_lock_lost_dialog', $post );
1480			?>
1481			<p><a class="button button-primary wp-tab-last" href="<?php echo esc_url( $sendback ); ?>"><?php echo $sendback_text; ?></a></p>
1482		</div>
1483		<?php
1484	}
1485
1486	?>
1487	</div>
1488	</div>
1489	<?php
1490}
1491
1492/**
1493 * Creates autosave data for the specified post from $_POST data.
1494 *
1495 * @package WordPress
1496 * @subpackage Post_Revisions
1497 * @since 2.6.0
1498 *
1499 * @uses _wp_translate_postdata()
1500 * @uses _wp_post_revision_fields()
1501 *
1502 * @param mixed $post_data Associative array containing the post data or int post ID.
1503 * @return mixed The autosave revision ID. WP_Error or 0 on error.
1504 */
1505function wp_create_post_autosave( $post_data ) {
1506	if ( is_numeric( $post_data ) ) {
1507		$post_id = $post_data;
1508		$post_data = &$_POST;
1509	} else {
1510		$post_id = (int) $post_data['post_ID'];
1511	}
1512
1513	$post_data = _wp_translate_postdata( true, $post_data );
1514	if ( is_wp_error( $post_data ) )
1515		return $post_data;
1516
1517	$post_author = get_current_user_id();
1518
1519	// Store one autosave per author. If there is already an autosave, overwrite it.
1520	if ( $old_autosave = wp_get_post_autosave( $post_id, $post_author ) ) {
1521		$new_autosave = _wp_post_revision_fields( $post_data, true );
1522		$new_autosave['ID'] = $old_autosave->ID;
1523		$new_autosave['post_author'] = $post_author;
1524
1525		// If the new autosave has the same content as the post, delete the autosave.
1526		$post = get_post( $post_id );
1527		$autosave_is_different = false;
1528		foreach ( array_intersect( array_keys( $new_autosave ), array_keys( _wp_post_revision_fields() ) ) as $field ) {
1529			if ( normalize_whitespace( $new_autosave[ $field ] ) != normalize_whitespace( $post->$field ) ) {
1530				$autosave_is_different = true;
1531				break;
1532			}
1533		}
1534
1535		if ( ! $autosave_is_different ) {
1536			wp_delete_post_revision( $old_autosave->ID );
1537			return 0;
1538		}
1539
1540		return wp_update_post( $new_autosave );
1541	}
1542
1543	// _wp_put_post_revision() expects unescaped.
1544	$post_data = wp_unslash( $post_data );
1545
1546	// Otherwise create the new autosave as a special post revision
1547	return _wp_put_post_revision( $post_data, true );
1548}
1549
1550/**
1551 * Save draft or manually autosave for showing preview.
1552 *
1553 * @package WordPress
1554 * @since 2.7.0
1555 *
1556 * @uses get_post_status()
1557 * @uses edit_post()
1558 * @uses get_post()
1559 * @uses current_user_can()
1560 * @uses wp_die()
1561 * @uses wp_create_post_autosave()
1562 * @uses add_query_arg()
1563 * @uses wp_create_nonce()
1564 *
1565 * @return str URL to redirect to show the preview
1566 */
1567function post_preview() {
1568
1569	$post_ID = (int) $_POST['post_ID'];
1570	$_POST['ID'] = $post_ID;
1571
1572	if ( ! $post = get_post( $post_ID ) ) {
1573		wp_die( __( 'You are not allowed to edit this post.' ) );
1574	}
1575
1576	if ( ! current_user_can( 'edit_post', $post->ID ) ) {
1577		wp_die( __( 'You are not allowed to edit this post.' ) );
1578	}
1579
1580	$is_autosave = false;
1581
1582	if ( ! wp_check_post_lock( $post->ID ) && get_current_user_id() == $post->post_author && ( 'draft' == $post->post_status || 'auto-draft' == $post->post_status ) ) {
1583		$saved_post_id = edit_post();
1584	} else {
1585		$is_autosave = true;
1586
1587		if ( 'auto-draft' == $_POST['post_status'] )

Large files files are truncated, but you can click here to view the full file