PageRenderTime 352ms CodeModel.GetById 101ms app.highlight 122ms RepoModel.GetById 79ms app.codeStats 2ms

/wp-includes/functions.php

https://github.com/davodey/WordPress
PHP | 4457 lines | 2144 code | 466 blank | 1847 comment | 501 complexity | 6428cb004221fe4ca3c9252a6f3acdcc MD5 | raw file

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

   1<?php
   2/**
   3 * Main WordPress API
   4 *
   5 * @package WordPress
   6 */
   7
   8require( ABSPATH . WPINC . '/option.php' );
   9
  10/**
  11 * Converts given date string into a different format.
  12 *
  13 * $format should be either a PHP date format string, e.g. 'U' for a Unix
  14 * timestamp, or 'G' for a Unix timestamp assuming that $date is GMT.
  15 *
  16 * If $translate is true then the given date and format string will
  17 * be passed to date_i18n() for translation.
  18 *
  19 * @since 0.71
  20 *
  21 * @param string $format Format of the date to return.
  22 * @param string $date Date string to convert.
  23 * @param bool $translate Whether the return date should be translated. Default is true.
  24 * @return string|int Formatted date string, or Unix timestamp.
  25 */
  26function mysql2date( $format, $date, $translate = true ) {
  27	if ( empty( $date ) )
  28		return false;
  29
  30	if ( 'G' == $format )
  31		return strtotime( $date . ' +0000' );
  32
  33	$i = strtotime( $date );
  34
  35	if ( 'U' == $format )
  36		return $i;
  37
  38	if ( $translate )
  39		return date_i18n( $format, $i );
  40	else
  41		return date( $format, $i );
  42}
  43
  44/**
  45 * Retrieve the current time based on specified type.
  46 *
  47 * The 'mysql' type will return the time in the format for MySQL DATETIME field.
  48 * The 'timestamp' type will return the current timestamp.
  49 * Other strings will be interpreted as PHP date formats (e.g. 'Y-m-d').
  50 *
  51 * If $gmt is set to either '1' or 'true', then both types will use GMT time.
  52 * if $gmt is false, the output is adjusted with the GMT offset in the WordPress option.
  53 *
  54 * @since 1.0.0
  55 *
  56 * @param string $type 'mysql', 'timestamp', or PHP date format string (e.g. 'Y-m-d').
  57 * @param int|bool $gmt Optional. Whether to use GMT timezone. Default is false.
  58 * @return int|string Integer if $type is 'timestamp', string otherwise.
  59 */
  60function current_time( $type, $gmt = 0 ) {
  61	switch ( $type ) {
  62		case 'mysql':
  63			return ( $gmt ) ? gmdate( 'Y-m-d H:i:s' ) : gmdate( 'Y-m-d H:i:s', ( time() + ( get_option( 'gmt_offset' ) * HOUR_IN_SECONDS ) ) );
  64		case 'timestamp':
  65			return ( $gmt ) ? time() : time() + ( get_option( 'gmt_offset' ) * HOUR_IN_SECONDS );
  66		default:
  67			return ( $gmt ) ? date( $type ) : date( $type, time() + ( get_option( 'gmt_offset' ) * HOUR_IN_SECONDS ) );
  68	}
  69}
  70
  71/**
  72 * Retrieve the date in localized format, based on timestamp.
  73 *
  74 * If the locale specifies the locale month and weekday, then the locale will
  75 * take over the format for the date. If it isn't, then the date format string
  76 * will be used instead.
  77 *
  78 * @since 0.71
  79 *
  80 * @param string $dateformatstring Format to display the date.
  81 * @param int $unixtimestamp Optional. Unix timestamp.
  82 * @param bool $gmt Optional, default is false. Whether to convert to GMT for time.
  83 * @return string The date, translated if locale specifies it.
  84 */
  85function date_i18n( $dateformatstring, $unixtimestamp = false, $gmt = false ) {
  86	global $wp_locale;
  87	$i = $unixtimestamp;
  88
  89	if ( false === $i ) {
  90		if ( ! $gmt )
  91			$i = current_time( 'timestamp' );
  92		else
  93			$i = time();
  94		// we should not let date() interfere with our
  95		// specially computed timestamp
  96		$gmt = true;
  97	}
  98
  99	// store original value for language with untypical grammars
 100	// see http://core.trac.wordpress.org/ticket/9396
 101	$req_format = $dateformatstring;
 102
 103	$datefunc = $gmt? 'gmdate' : 'date';
 104
 105	if ( ( !empty( $wp_locale->month ) ) && ( !empty( $wp_locale->weekday ) ) ) {
 106		$datemonth = $wp_locale->get_month( $datefunc( 'm', $i ) );
 107		$datemonth_abbrev = $wp_locale->get_month_abbrev( $datemonth );
 108		$dateweekday = $wp_locale->get_weekday( $datefunc( 'w', $i ) );
 109		$dateweekday_abbrev = $wp_locale->get_weekday_abbrev( $dateweekday );
 110		$datemeridiem = $wp_locale->get_meridiem( $datefunc( 'a', $i ) );
 111		$datemeridiem_capital = $wp_locale->get_meridiem( $datefunc( 'A', $i ) );
 112		$dateformatstring = ' '.$dateformatstring;
 113		$dateformatstring = preg_replace( "/([^\\\])D/", "\\1" . backslashit( $dateweekday_abbrev ), $dateformatstring );
 114		$dateformatstring = preg_replace( "/([^\\\])F/", "\\1" . backslashit( $datemonth ), $dateformatstring );
 115		$dateformatstring = preg_replace( "/([^\\\])l/", "\\1" . backslashit( $dateweekday ), $dateformatstring );
 116		$dateformatstring = preg_replace( "/([^\\\])M/", "\\1" . backslashit( $datemonth_abbrev ), $dateformatstring );
 117		$dateformatstring = preg_replace( "/([^\\\])a/", "\\1" . backslashit( $datemeridiem ), $dateformatstring );
 118		$dateformatstring = preg_replace( "/([^\\\])A/", "\\1" . backslashit( $datemeridiem_capital ), $dateformatstring );
 119
 120		$dateformatstring = substr( $dateformatstring, 1, strlen( $dateformatstring ) -1 );
 121	}
 122	$timezone_formats = array( 'P', 'I', 'O', 'T', 'Z', 'e' );
 123	$timezone_formats_re = implode( '|', $timezone_formats );
 124	if ( preg_match( "/$timezone_formats_re/", $dateformatstring ) ) {
 125		$timezone_string = get_option( 'timezone_string' );
 126		if ( $timezone_string ) {
 127			$timezone_object = timezone_open( $timezone_string );
 128			$date_object = date_create( null, $timezone_object );
 129			foreach( $timezone_formats as $timezone_format ) {
 130				if ( false !== strpos( $dateformatstring, $timezone_format ) ) {
 131					$formatted = date_format( $date_object, $timezone_format );
 132					$dateformatstring = ' '.$dateformatstring;
 133					$dateformatstring = preg_replace( "/([^\\\])$timezone_format/", "\\1" . backslashit( $formatted ), $dateformatstring );
 134					$dateformatstring = substr( $dateformatstring, 1, strlen( $dateformatstring ) -1 );
 135				}
 136			}
 137		}
 138	}
 139	$j = @$datefunc( $dateformatstring, $i );
 140
 141	/**
 142	 * Filter the date formatted based on the locale.
 143	 *
 144	 * @since 2.8.0
 145	 *
 146	 * @param string $j          Formatted date string.
 147	 * @param string $req_format Format to display the date.
 148	 * @param int    $i          Unix timestamp.
 149	 * @param bool   $gmt        Whether to convert to GMT for time. Default false.
 150	 */
 151	$j = apply_filters( 'date_i18n', $j, $req_format, $i, $gmt );
 152	return $j;
 153}
 154
 155/**
 156 * Convert integer number to format based on the locale.
 157 *
 158 * @since 2.3.0
 159 *
 160 * @param int $number The number to convert based on locale.
 161 * @param int $decimals Precision of the number of decimal places.
 162 * @return string Converted number in string format.
 163 */
 164function number_format_i18n( $number, $decimals = 0 ) {
 165	global $wp_locale;
 166	$formatted = number_format( $number, absint( $decimals ), $wp_locale->number_format['decimal_point'], $wp_locale->number_format['thousands_sep'] );
 167
 168	/**
 169	 * Filter the number formatted based on the locale.
 170	 *
 171	 * @since  2.8.0
 172	 *
 173	 * @param string $formatted Converted number in string format.
 174	 */
 175	return apply_filters( 'number_format_i18n', $formatted );
 176}
 177
 178/**
 179 * Convert number of bytes largest unit bytes will fit into.
 180 *
 181 * It is easier to read 1kB than 1024 bytes and 1MB than 1048576 bytes. Converts
 182 * number of bytes to human readable number by taking the number of that unit
 183 * that the bytes will go into it. Supports TB value.
 184 *
 185 * Please note that integers in PHP are limited to 32 bits, unless they are on
 186 * 64 bit architecture, then they have 64 bit size. If you need to place the
 187 * larger size then what PHP integer type will hold, then use a string. It will
 188 * be converted to a double, which should always have 64 bit length.
 189 *
 190 * Technically the correct unit names for powers of 1024 are KiB, MiB etc.
 191 * @link http://en.wikipedia.org/wiki/Byte
 192 *
 193 * @since 2.3.0
 194 *
 195 * @param int|string $bytes Number of bytes. Note max integer size for integers.
 196 * @param int $decimals Precision of number of decimal places. Deprecated.
 197 * @return bool|string False on failure. Number string on success.
 198 */
 199function size_format( $bytes, $decimals = 0 ) {
 200	$quant = array(
 201		// ========================= Origin ====
 202		'TB' => 1099511627776,  // pow( 1024, 4)
 203		'GB' => 1073741824,     // pow( 1024, 3)
 204		'MB' => 1048576,        // pow( 1024, 2)
 205		'kB' => 1024,           // pow( 1024, 1)
 206		'B ' => 1,              // pow( 1024, 0)
 207	);
 208	foreach ( $quant as $unit => $mag )
 209		if ( doubleval($bytes) >= $mag )
 210			return number_format_i18n( $bytes / $mag, $decimals ) . ' ' . $unit;
 211
 212	return false;
 213}
 214
 215/**
 216 * Get the week start and end from the datetime or date string from mysql.
 217 *
 218 * @since 0.71
 219 *
 220 * @param string $mysqlstring Date or datetime field type from mysql.
 221 * @param int $start_of_week Optional. Start of the week as an integer.
 222 * @return array Keys are 'start' and 'end'.
 223 */
 224function get_weekstartend( $mysqlstring, $start_of_week = '' ) {
 225	$my = substr( $mysqlstring, 0, 4 ); // Mysql string Year
 226	$mm = substr( $mysqlstring, 8, 2 ); // Mysql string Month
 227	$md = substr( $mysqlstring, 5, 2 ); // Mysql string day
 228	$day = mktime( 0, 0, 0, $md, $mm, $my ); // The timestamp for mysqlstring day.
 229	$weekday = date( 'w', $day ); // The day of the week from the timestamp
 230	if ( !is_numeric($start_of_week) )
 231		$start_of_week = get_option( 'start_of_week' );
 232
 233	if ( $weekday < $start_of_week )
 234		$weekday += 7;
 235
 236	$start = $day - DAY_IN_SECONDS * ( $weekday - $start_of_week ); // The most recent week start day on or before $day
 237	$end = $start + 7 * DAY_IN_SECONDS - 1; // $start + 7 days - 1 second
 238	return compact( 'start', 'end' );
 239}
 240
 241/**
 242 * Unserialize value only if it was serialized.
 243 *
 244 * @since 2.0.0
 245 *
 246 * @param string $original Maybe unserialized original, if is needed.
 247 * @return mixed Unserialized data can be any type.
 248 */
 249function maybe_unserialize( $original ) {
 250	if ( is_serialized( $original ) ) // don't attempt to unserialize data that wasn't serialized going in
 251		return @unserialize( $original );
 252	return $original;
 253}
 254
 255/**
 256 * Check value to find if it was serialized.
 257 *
 258 * If $data is not an string, then returned value will always be false.
 259 * Serialized data is always a string.
 260 *
 261 * @since 2.0.5
 262 *
 263 * @param mixed $data Value to check to see if was serialized.
 264 * @param bool $strict Optional. Whether to be strict about the end of the string. Defaults true.
 265 * @return bool False if not serialized and true if it was.
 266 */
 267function is_serialized( $data, $strict = true ) {
 268	// if it isn't a string, it isn't serialized
 269	if ( ! is_string( $data ) ) {
 270		return false;
 271	}
 272	$data = trim( $data );
 273 	if ( 'N;' == $data ) {
 274		return true;
 275	}
 276	if ( strlen( $data ) < 4 ) {
 277		return false;
 278	}
 279	if ( ':' !== $data[1] ) {
 280		return false;
 281	}
 282	if ( $strict ) {
 283		$lastc = substr( $data, -1 );
 284		if ( ';' !== $lastc && '}' !== $lastc ) {
 285			return false;
 286		}
 287	} else {
 288		$semicolon = strpos( $data, ';' );
 289		$brace     = strpos( $data, '}' );
 290		// Either ; or } must exist.
 291		if ( false === $semicolon && false === $brace )
 292			return false;
 293		// But neither must be in the first X characters.
 294		if ( false !== $semicolon && $semicolon < 3 )
 295			return false;
 296		if ( false !== $brace && $brace < 4 )
 297			return false;
 298	}
 299	$token = $data[0];
 300	switch ( $token ) {
 301		case 's' :
 302			if ( $strict ) {
 303				if ( '"' !== substr( $data, -2, 1 ) ) {
 304					return false;
 305				}
 306			} elseif ( false === strpos( $data, '"' ) ) {
 307				return false;
 308			}
 309			// or else fall through
 310		case 'a' :
 311		case 'O' :
 312			return (bool) preg_match( "/^{$token}:[0-9]+:/s", $data );
 313		case 'b' :
 314		case 'i' :
 315		case 'd' :
 316			$end = $strict ? '$' : '';
 317			return (bool) preg_match( "/^{$token}:[0-9.E-]+;$end/", $data );
 318	}
 319	return false;
 320}
 321
 322/**
 323 * Check whether serialized data is of string type.
 324 *
 325 * @since 2.0.5
 326 *
 327 * @param mixed $data Serialized data
 328 * @return bool False if not a serialized string, true if it is.
 329 */
 330function is_serialized_string( $data ) {
 331	// if it isn't a string, it isn't a serialized string
 332	if ( ! is_string( $data ) ) {
 333		return false;
 334	}
 335	$data = trim( $data );
 336	if ( strlen( $data ) < 4 ) {
 337		return false;
 338	} elseif ( ':' !== $data[1] ) {
 339		return false;
 340	} elseif ( ';' !== substr( $data, -1 ) ) {
 341		return false;
 342	} elseif ( $data[0] !== 's' ) {
 343		return false;
 344	} elseif ( '"' !== substr( $data, -2, 1 ) ) {
 345		return false;
 346	} else {
 347		return true;
 348	}
 349}
 350
 351/**
 352 * Serialize data, if needed.
 353 *
 354 * @since 2.0.5
 355 *
 356 * @param mixed $data Data that might be serialized.
 357 * @return mixed A scalar data
 358 */
 359function maybe_serialize( $data ) {
 360	if ( is_array( $data ) || is_object( $data ) )
 361		return serialize( $data );
 362
 363	// Double serialization is required for backward compatibility.
 364	// See http://core.trac.wordpress.org/ticket/12930
 365	if ( is_serialized( $data, false ) )
 366		return serialize( $data );
 367
 368	return $data;
 369}
 370
 371/**
 372 * Retrieve post title from XMLRPC XML.
 373 *
 374 * If the title element is not part of the XML, then the default post title from
 375 * the $post_default_title will be used instead.
 376 *
 377 * @since 0.71
 378 *
 379 * @global string $post_default_title Default XMLRPC post title.
 380 *
 381 * @param string $content XMLRPC XML Request content
 382 * @return string Post title
 383 */
 384function xmlrpc_getposttitle( $content ) {
 385	global $post_default_title;
 386	if ( preg_match( '/<title>(.+?)<\/title>/is', $content, $matchtitle ) ) {
 387		$post_title = $matchtitle[1];
 388	} else {
 389		$post_title = $post_default_title;
 390	}
 391	return $post_title;
 392}
 393
 394/**
 395 * Retrieve the post category or categories from XMLRPC XML.
 396 *
 397 * If the category element is not found, then the default post category will be
 398 * used. The return type then would be what $post_default_category. If the
 399 * category is found, then it will always be an array.
 400 *
 401 * @since 0.71
 402 *
 403 * @global string $post_default_category Default XMLRPC post category.
 404 *
 405 * @param string $content XMLRPC XML Request content
 406 * @return string|array List of categories or category name.
 407 */
 408function xmlrpc_getpostcategory( $content ) {
 409	global $post_default_category;
 410	if ( preg_match( '/<category>(.+?)<\/category>/is', $content, $matchcat ) ) {
 411		$post_category = trim( $matchcat[1], ',' );
 412		$post_category = explode( ',', $post_category );
 413	} else {
 414		$post_category = $post_default_category;
 415	}
 416	return $post_category;
 417}
 418
 419/**
 420 * XMLRPC XML content without title and category elements.
 421 *
 422 * @since 0.71
 423 *
 424 * @param string $content XMLRPC XML Request content
 425 * @return string XMLRPC XML Request content without title and category elements.
 426 */
 427function xmlrpc_removepostdata( $content ) {
 428	$content = preg_replace( '/<title>(.+?)<\/title>/si', '', $content );
 429	$content = preg_replace( '/<category>(.+?)<\/category>/si', '', $content );
 430	$content = trim( $content );
 431	return $content;
 432}
 433
 434/**
 435 * Use RegEx to extract URLs from arbitrary content
 436 *
 437 * @since 3.7.0
 438 *
 439 * @param string $content
 440 * @return array URLs found in passed string
 441 */
 442function wp_extract_urls( $content ) {
 443	preg_match_all(
 444		"#((?:[\w-]+://?|[\w\d]+[.])[^\s()<>]+[.](?:\([\w\d]+\)|(?:[^`!()\[\]{};:'\".,<>?«»“”‘’\s]|(?:[:]\d+)?/?)+))#",
 445		$content,
 446		$post_links
 447	);
 448
 449	$post_links = array_unique( array_map( 'html_entity_decode', $post_links[0] ) );
 450
 451	return array_values( $post_links );
 452}
 453
 454/**
 455 * Check content for video and audio links to add as enclosures.
 456 *
 457 * Will not add enclosures that have already been added and will
 458 * remove enclosures that are no longer in the post. This is called as
 459 * pingbacks and trackbacks.
 460 *
 461 * @since 1.5.0
 462 *
 463 * @uses $wpdb
 464 *
 465 * @param string $content Post Content
 466 * @param int $post_ID Post ID
 467 */
 468function do_enclose( $content, $post_ID ) {
 469	global $wpdb;
 470
 471	//TODO: Tidy this ghetto code up and make the debug code optional
 472	include_once( ABSPATH . WPINC . '/class-IXR.php' );
 473
 474	$post_links = array();
 475
 476	$pung = get_enclosed( $post_ID );
 477
 478	$post_links_temp = wp_extract_urls( $content );
 479
 480	foreach ( $pung as $link_test ) {
 481		if ( ! in_array( $link_test, $post_links_temp ) ) { // link no longer in post
 482			$mids = $wpdb->get_col( $wpdb->prepare("SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = 'enclosure' AND meta_value LIKE (%s)", $post_ID, like_escape( $link_test ) . '%') );
 483			foreach ( $mids as $mid )
 484				delete_metadata_by_mid( 'post', $mid );
 485		}
 486	}
 487
 488	foreach ( (array) $post_links_temp as $link_test ) {
 489		if ( !in_array( $link_test, $pung ) ) { // If we haven't pung it already
 490			$test = @parse_url( $link_test );
 491			if ( false === $test )
 492				continue;
 493			if ( isset( $test['query'] ) )
 494				$post_links[] = $link_test;
 495			elseif ( isset($test['path']) && ( $test['path'] != '/' ) &&  ($test['path'] != '' ) )
 496				$post_links[] = $link_test;
 497		}
 498	}
 499
 500	foreach ( (array) $post_links as $url ) {
 501		if ( $url != '' && !$wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = 'enclosure' AND meta_value LIKE (%s)", $post_ID, like_escape( $url ) . '%' ) ) ) {
 502
 503			if ( $headers = wp_get_http_headers( $url) ) {
 504				$len = isset( $headers['content-length'] ) ? (int) $headers['content-length'] : 0;
 505				$type = isset( $headers['content-type'] ) ? $headers['content-type'] : '';
 506				$allowed_types = array( 'video', 'audio' );
 507
 508				// Check to see if we can figure out the mime type from
 509				// the extension
 510				$url_parts = @parse_url( $url );
 511				if ( false !== $url_parts ) {
 512					$extension = pathinfo( $url_parts['path'], PATHINFO_EXTENSION );
 513					if ( !empty( $extension ) ) {
 514						foreach ( wp_get_mime_types() as $exts => $mime ) {
 515							if ( preg_match( '!^(' . $exts . ')$!i', $extension ) ) {
 516								$type = $mime;
 517								break;
 518							}
 519						}
 520					}
 521				}
 522
 523				if ( in_array( substr( $type, 0, strpos( $type, "/" ) ), $allowed_types ) ) {
 524					add_post_meta( $post_ID, 'enclosure', "$url\n$len\n$mime\n" );
 525				}
 526			}
 527		}
 528	}
 529}
 530
 531/**
 532 * Perform a HTTP HEAD or GET request.
 533 *
 534 * If $file_path is a writable filename, this will do a GET request and write
 535 * the file to that path.
 536 *
 537 * @since 2.5.0
 538 *
 539 * @param string $url URL to fetch.
 540 * @param string|bool $file_path Optional. File path to write request to.
 541 * @param int $red (private) The number of Redirects followed, Upon 5 being hit, returns false.
 542 * @return bool|string False on failure and string of headers if HEAD request.
 543 */
 544function wp_get_http( $url, $file_path = false, $red = 1 ) {
 545	@set_time_limit( 60 );
 546
 547	if ( $red > 5 )
 548		return false;
 549
 550	$options = array();
 551	$options['redirection'] = 5;
 552
 553	if ( false == $file_path )
 554		$options['method'] = 'HEAD';
 555	else
 556		$options['method'] = 'GET';
 557
 558	$response = wp_safe_remote_request( $url, $options );
 559
 560	if ( is_wp_error( $response ) )
 561		return false;
 562
 563	$headers = wp_remote_retrieve_headers( $response );
 564	$headers['response'] = wp_remote_retrieve_response_code( $response );
 565
 566	// WP_HTTP no longer follows redirects for HEAD requests.
 567	if ( 'HEAD' == $options['method'] && in_array($headers['response'], array(301, 302)) && isset( $headers['location'] ) ) {
 568		return wp_get_http( $headers['location'], $file_path, ++$red );
 569	}
 570
 571	if ( false == $file_path )
 572		return $headers;
 573
 574	// GET request - write it to the supplied filename
 575	$out_fp = fopen($file_path, 'w');
 576	if ( !$out_fp )
 577		return $headers;
 578
 579	fwrite( $out_fp,  wp_remote_retrieve_body( $response ) );
 580	fclose($out_fp);
 581	clearstatcache();
 582
 583	return $headers;
 584}
 585
 586/**
 587 * Retrieve HTTP Headers from URL.
 588 *
 589 * @since 1.5.1
 590 *
 591 * @param string $url
 592 * @param bool $deprecated Not Used.
 593 * @return bool|string False on failure, headers on success.
 594 */
 595function wp_get_http_headers( $url, $deprecated = false ) {
 596	if ( !empty( $deprecated ) )
 597		_deprecated_argument( __FUNCTION__, '2.7' );
 598
 599	$response = wp_safe_remote_head( $url );
 600
 601	if ( is_wp_error( $response ) )
 602		return false;
 603
 604	return wp_remote_retrieve_headers( $response );
 605}
 606
 607/**
 608 * Whether the publish date of the current post in the loop is different from the
 609 * publish date of the previous post in the loop.
 610 *
 611 * @since 0.71
 612 * @global string $currentday The day of the current post in the loop.
 613 * @global string $previousday The day of the previous post in the loop.
 614 *
 615 * @return int 1 when new day, 0 if not a new day.
 616 */
 617function is_new_day() {
 618	global $currentday, $previousday;
 619	if ( $currentday != $previousday )
 620		return 1;
 621	else
 622		return 0;
 623}
 624
 625/**
 626 * Build URL query based on an associative and, or indexed array.
 627 *
 628 * This is a convenient function for easily building url queries. It sets the
 629 * separator to '&' and uses _http_build_query() function.
 630 *
 631 * @see _http_build_query() Used to build the query
 632 * @link http://us2.php.net/manual/en/function.http-build-query.php more on what
 633 *		http_build_query() does.
 634 *
 635 * @since 2.3.0
 636 *
 637 * @param array $data URL-encode key/value pairs.
 638 * @return string URL encoded string
 639 */
 640function build_query( $data ) {
 641	return _http_build_query( $data, null, '&', '', false );
 642}
 643
 644// from php.net (modified by Mark Jaquith to behave like the native PHP5 function)
 645function _http_build_query($data, $prefix=null, $sep=null, $key='', $urlencode=true) {
 646	$ret = array();
 647
 648	foreach ( (array) $data as $k => $v ) {
 649		if ( $urlencode)
 650			$k = urlencode($k);
 651		if ( is_int($k) && $prefix != null )
 652			$k = $prefix.$k;
 653		if ( !empty($key) )
 654			$k = $key . '%5B' . $k . '%5D';
 655		if ( $v === null )
 656			continue;
 657		elseif ( $v === FALSE )
 658			$v = '0';
 659
 660		if ( is_array($v) || is_object($v) )
 661			array_push($ret,_http_build_query($v, '', $sep, $k, $urlencode));
 662		elseif ( $urlencode )
 663			array_push($ret, $k.'='.urlencode($v));
 664		else
 665			array_push($ret, $k.'='.$v);
 666	}
 667
 668	if ( null === $sep )
 669		$sep = ini_get('arg_separator.output');
 670
 671	return implode($sep, $ret);
 672}
 673
 674/**
 675 * Retrieve a modified URL query string.
 676 *
 677 * You can rebuild the URL and append a new query variable to the URL query by
 678 * using this function. You can also retrieve the full URL with query data.
 679 *
 680 * Adding a single key & value or an associative array. Setting a key value to
 681 * an empty string removes the key. Omitting oldquery_or_uri uses the $_SERVER
 682 * value. Additional values provided are expected to be encoded appropriately
 683 * with urlencode() or rawurlencode().
 684 *
 685 * @since 1.5.0
 686 *
 687 * @param mixed $param1 Either newkey or an associative_array
 688 * @param mixed $param2 Either newvalue or oldquery or uri
 689 * @param mixed $param3 Optional. Old query or uri
 690 * @return string New URL query string.
 691 */
 692function add_query_arg() {
 693	$args = func_get_args();
 694	if ( is_array( $args[0] ) ) {
 695		if ( count( $args ) < 2 || false === $args[1] )
 696			$uri = $_SERVER['REQUEST_URI'];
 697		else
 698			$uri = $args[1];
 699	} else {
 700		if ( count( $args ) < 3 || false === $args[2] )
 701			$uri = $_SERVER['REQUEST_URI'];
 702		else
 703			$uri = $args[2];
 704	}
 705
 706	if ( $frag = strstr( $uri, '#' ) )
 707		$uri = substr( $uri, 0, -strlen( $frag ) );
 708	else
 709		$frag = '';
 710
 711	if ( 0 === stripos( $uri, 'http://' ) ) {
 712		$protocol = 'http://';
 713		$uri = substr( $uri, 7 );
 714	} elseif ( 0 === stripos( $uri, 'https://' ) ) {
 715		$protocol = 'https://';
 716		$uri = substr( $uri, 8 );
 717	} else {
 718		$protocol = '';
 719	}
 720
 721	if ( strpos( $uri, '?' ) !== false ) {
 722		list( $base, $query ) = explode( '?', $uri, 2 );
 723		$base .= '?';
 724	} elseif ( $protocol || strpos( $uri, '=' ) === false ) {
 725		$base = $uri . '?';
 726		$query = '';
 727	} else {
 728		$base = '';
 729		$query = $uri;
 730	}
 731
 732	wp_parse_str( $query, $qs );
 733	$qs = urlencode_deep( $qs ); // this re-URL-encodes things that were already in the query string
 734	if ( is_array( $args[0] ) ) {
 735		$kayvees = $args[0];
 736		$qs = array_merge( $qs, $kayvees );
 737	} else {
 738		$qs[ $args[0] ] = $args[1];
 739	}
 740
 741	foreach ( $qs as $k => $v ) {
 742		if ( $v === false )
 743			unset( $qs[$k] );
 744	}
 745
 746	$ret = build_query( $qs );
 747	$ret = trim( $ret, '?' );
 748	$ret = preg_replace( '#=(&|$)#', '$1', $ret );
 749	$ret = $protocol . $base . $ret . $frag;
 750	$ret = rtrim( $ret, '?' );
 751	return $ret;
 752}
 753
 754/**
 755 * Removes an item or list from the query string.
 756 *
 757 * @since 1.5.0
 758 *
 759 * @param string|array $key Query key or keys to remove.
 760 * @param bool $query When false uses the $_SERVER value.
 761 * @return string New URL query string.
 762 */
 763function remove_query_arg( $key, $query=false ) {
 764	if ( is_array( $key ) ) { // removing multiple keys
 765		foreach ( $key as $k )
 766			$query = add_query_arg( $k, false, $query );
 767		return $query;
 768	}
 769	return add_query_arg( $key, false, $query );
 770}
 771
 772/**
 773 * Walks the array while sanitizing the contents.
 774 *
 775 * @since 0.71
 776 *
 777 * @param array $array Array to walk while sanitizing contents.
 778 * @return array Sanitized $array.
 779 */
 780function add_magic_quotes( $array ) {
 781	foreach ( (array) $array as $k => $v ) {
 782		if ( is_array( $v ) ) {
 783			$array[$k] = add_magic_quotes( $v );
 784		} else {
 785			$array[$k] = addslashes( $v );
 786		}
 787	}
 788	return $array;
 789}
 790
 791/**
 792 * HTTP request for URI to retrieve content.
 793 *
 794 * @since 1.5.1
 795 * @uses wp_remote_get()
 796 *
 797 * @param string $uri URI/URL of web page to retrieve.
 798 * @return bool|string HTTP content. False on failure.
 799 */
 800function wp_remote_fopen( $uri ) {
 801	$parsed_url = @parse_url( $uri );
 802
 803	if ( !$parsed_url || !is_array( $parsed_url ) )
 804		return false;
 805
 806	$options = array();
 807	$options['timeout'] = 10;
 808
 809	$response = wp_safe_remote_get( $uri, $options );
 810
 811	if ( is_wp_error( $response ) )
 812		return false;
 813
 814	return wp_remote_retrieve_body( $response );
 815}
 816
 817/**
 818 * Set up the WordPress query.
 819 *
 820 * @since 2.0.0
 821 *
 822 * @param string $query_vars Default WP_Query arguments.
 823 */
 824function wp( $query_vars = '' ) {
 825	global $wp, $wp_query, $wp_the_query;
 826	$wp->main( $query_vars );
 827
 828	if ( !isset($wp_the_query) )
 829		$wp_the_query = $wp_query;
 830}
 831
 832/**
 833 * Retrieve the description for the HTTP status.
 834 *
 835 * @since 2.3.0
 836 *
 837 * @param int $code HTTP status code.
 838 * @return string Empty string if not found, or description if found.
 839 */
 840function get_status_header_desc( $code ) {
 841	global $wp_header_to_desc;
 842
 843	$code = absint( $code );
 844
 845	if ( !isset( $wp_header_to_desc ) ) {
 846		$wp_header_to_desc = array(
 847			100 => 'Continue',
 848			101 => 'Switching Protocols',
 849			102 => 'Processing',
 850
 851			200 => 'OK',
 852			201 => 'Created',
 853			202 => 'Accepted',
 854			203 => 'Non-Authoritative Information',
 855			204 => 'No Content',
 856			205 => 'Reset Content',
 857			206 => 'Partial Content',
 858			207 => 'Multi-Status',
 859			226 => 'IM Used',
 860
 861			300 => 'Multiple Choices',
 862			301 => 'Moved Permanently',
 863			302 => 'Found',
 864			303 => 'See Other',
 865			304 => 'Not Modified',
 866			305 => 'Use Proxy',
 867			306 => 'Reserved',
 868			307 => 'Temporary Redirect',
 869
 870			400 => 'Bad Request',
 871			401 => 'Unauthorized',
 872			402 => 'Payment Required',
 873			403 => 'Forbidden',
 874			404 => 'Not Found',
 875			405 => 'Method Not Allowed',
 876			406 => 'Not Acceptable',
 877			407 => 'Proxy Authentication Required',
 878			408 => 'Request Timeout',
 879			409 => 'Conflict',
 880			410 => 'Gone',
 881			411 => 'Length Required',
 882			412 => 'Precondition Failed',
 883			413 => 'Request Entity Too Large',
 884			414 => 'Request-URI Too Long',
 885			415 => 'Unsupported Media Type',
 886			416 => 'Requested Range Not Satisfiable',
 887			417 => 'Expectation Failed',
 888			418 => 'I\'m a teapot',
 889			422 => 'Unprocessable Entity',
 890			423 => 'Locked',
 891			424 => 'Failed Dependency',
 892			426 => 'Upgrade Required',
 893			428 => 'Precondition Required',
 894			429 => 'Too Many Requests',
 895			431 => 'Request Header Fields Too Large',
 896
 897			500 => 'Internal Server Error',
 898			501 => 'Not Implemented',
 899			502 => 'Bad Gateway',
 900			503 => 'Service Unavailable',
 901			504 => 'Gateway Timeout',
 902			505 => 'HTTP Version Not Supported',
 903			506 => 'Variant Also Negotiates',
 904			507 => 'Insufficient Storage',
 905			510 => 'Not Extended',
 906			511 => 'Network Authentication Required',
 907		);
 908	}
 909
 910	if ( isset( $wp_header_to_desc[$code] ) )
 911		return $wp_header_to_desc[$code];
 912	else
 913		return '';
 914}
 915
 916/**
 917 * Set HTTP status header.
 918 *
 919 * @since 2.0.0
 920 * @see get_status_header_desc()
 921 *
 922 * @param int $code HTTP status code.
 923 */
 924function status_header( $code ) {
 925	$description = get_status_header_desc( $code );
 926
 927	if ( empty( $description ) )
 928		return;
 929
 930	$protocol = $_SERVER['SERVER_PROTOCOL'];
 931	if ( 'HTTP/1.1' != $protocol && 'HTTP/1.0' != $protocol )
 932		$protocol = 'HTTP/1.0';
 933	$status_header = "$protocol $code $description";
 934	if ( function_exists( 'apply_filters' ) )
 935
 936		/**
 937		 * Filter an HTTP status header.
 938		 *
 939		 * @since 2.2.0
 940		 *
 941		 * @param string $status_header HTTP status header.
 942		 * @param int    $code          HTTP status code.
 943		 * @param string $description   Description for the status code.
 944		 * @param string $protocol      Server protocol.
 945		 */
 946		$status_header = apply_filters( 'status_header', $status_header, $code, $description, $protocol );
 947
 948	@header( $status_header, true, $code );
 949}
 950
 951/**
 952 * Gets the header information to prevent caching.
 953 *
 954 * The several different headers cover the different ways cache prevention is handled
 955 * by different browsers
 956 *
 957 * @since 2.8.0
 958 *
 959 * @return array The associative array of header names and field values.
 960 */
 961function wp_get_nocache_headers() {
 962	$headers = array(
 963		'Expires' => 'Wed, 11 Jan 1984 05:00:00 GMT',
 964		'Cache-Control' => 'no-cache, must-revalidate, max-age=0',
 965		'Pragma' => 'no-cache',
 966	);
 967
 968	if ( function_exists('apply_filters') ) {
 969		/**
 970		 * Filter the cache-controlling headers.
 971		 *
 972		 * @since 2.8.0
 973		 *
 974		 * @param array $headers {
 975		 *     Header names and field values.
 976		 *
 977		 *     @type string $Expires       Expires header.
 978		 *     @type string $Cache-Control Cache-Control header.
 979		 *     @type string $Pragma        Pragma header.
 980		 * }
 981		 */
 982		$headers = (array) apply_filters( 'nocache_headers', $headers );
 983	}
 984	$headers['Last-Modified'] = false;
 985	return $headers;
 986}
 987
 988/**
 989 * Sets the headers to prevent caching for the different browsers.
 990 *
 991 * Different browsers support different nocache headers, so several headers must
 992 * be sent so that all of them get the point that no caching should occur.
 993 *
 994 * @since 2.0.0
 995 * @see wp_get_nocache_headers()
 996 */
 997function nocache_headers() {
 998	$headers = wp_get_nocache_headers();
 999
1000	unset( $headers['Last-Modified'] );
1001
1002	// In PHP 5.3+, make sure we are not sending a Last-Modified header.
1003	if ( function_exists( 'header_remove' ) ) {
1004		@header_remove( 'Last-Modified' );
1005	} else {
1006		// In PHP 5.2, send an empty Last-Modified header, but only as a
1007		// last resort to override a header already sent. #WP23021
1008		foreach ( headers_list() as $header ) {
1009			if ( 0 === stripos( $header, 'Last-Modified' ) ) {
1010				$headers['Last-Modified'] = '';
1011				break;
1012			}
1013		}
1014	}
1015
1016	foreach( $headers as $name => $field_value )
1017		@header("{$name}: {$field_value}");
1018}
1019
1020/**
1021 * Set the headers for caching for 10 days with JavaScript content type.
1022 *
1023 * @since 2.1.0
1024 */
1025function cache_javascript_headers() {
1026	$expiresOffset = 10 * DAY_IN_SECONDS;
1027	header( "Content-Type: text/javascript; charset=" . get_bloginfo( 'charset' ) );
1028	header( "Vary: Accept-Encoding" ); // Handle proxies
1029	header( "Expires: " . gmdate( "D, d M Y H:i:s", time() + $expiresOffset ) . " GMT" );
1030}
1031
1032/**
1033 * Retrieve the number of database queries during the WordPress execution.
1034 *
1035 * @since 2.0.0
1036 *
1037 * @return int Number of database queries
1038 */
1039function get_num_queries() {
1040	global $wpdb;
1041	return $wpdb->num_queries;
1042}
1043
1044/**
1045 * Whether input is yes or no. Must be 'y' to be true.
1046 *
1047 * @since 1.0.0
1048 *
1049 * @param string $yn Character string containing either 'y' or 'n'
1050 * @return bool True if yes, false on anything else
1051 */
1052function bool_from_yn( $yn ) {
1053	return ( strtolower( $yn ) == 'y' );
1054}
1055
1056/**
1057 * Loads the feed template from the use of an action hook.
1058 *
1059 * If the feed action does not have a hook, then the function will die with a
1060 * message telling the visitor that the feed is not valid.
1061 *
1062 * It is better to only have one hook for each feed.
1063 *
1064 * @since 2.1.0
1065 *
1066 * @uses $wp_query Used to tell if the use a comment feed.
1067 */
1068function do_feed() {
1069	global $wp_query;
1070
1071	$feed = get_query_var( 'feed' );
1072
1073	// Remove the pad, if present.
1074	$feed = preg_replace( '/^_+/', '', $feed );
1075
1076	if ( $feed == '' || $feed == 'feed' )
1077		$feed = get_default_feed();
1078
1079	$hook = 'do_feed_' . $feed;
1080	if ( ! has_action( $hook ) )
1081		wp_die( __( 'ERROR: This is not a valid feed template.' ), '', array( 'response' => 404 ) );
1082
1083	/**
1084	 * Fires once the given feed is loaded.
1085	 *
1086	 * The dynamic hook name, $hook, refers to the feed name.
1087	 *
1088	 * @since 2.1.0
1089	 *
1090	 * @param bool $is_comment_feed Whether the feed is a comment feed.
1091	 */
1092	do_action( $hook, $wp_query->is_comment_feed );
1093}
1094
1095/**
1096 * Load the RDF RSS 0.91 Feed template.
1097 *
1098 * @since 2.1.0
1099 */
1100function do_feed_rdf() {
1101	load_template( ABSPATH . WPINC . '/feed-rdf.php' );
1102}
1103
1104/**
1105 * Load the RSS 1.0 Feed Template.
1106 *
1107 * @since 2.1.0
1108 */
1109function do_feed_rss() {
1110	load_template( ABSPATH . WPINC . '/feed-rss.php' );
1111}
1112
1113/**
1114 * Load either the RSS2 comment feed or the RSS2 posts feed.
1115 *
1116 * @since 2.1.0
1117 *
1118 * @param bool $for_comments True for the comment feed, false for normal feed.
1119 */
1120function do_feed_rss2( $for_comments ) {
1121	if ( $for_comments )
1122		load_template( ABSPATH . WPINC . '/feed-rss2-comments.php' );
1123	else
1124		load_template( ABSPATH . WPINC . '/feed-rss2.php' );
1125}
1126
1127/**
1128 * Load either Atom comment feed or Atom posts feed.
1129 *
1130 * @since 2.1.0
1131 *
1132 * @param bool $for_comments True for the comment feed, false for normal feed.
1133 */
1134function do_feed_atom( $for_comments ) {
1135	if ($for_comments)
1136		load_template( ABSPATH . WPINC . '/feed-atom-comments.php');
1137	else
1138		load_template( ABSPATH . WPINC . '/feed-atom.php' );
1139}
1140
1141/**
1142 * Display the robots.txt file content.
1143 *
1144 * The echo content should be with usage of the permalinks or for creating the
1145 * robots.txt file.
1146 *
1147 * @since 2.1.0
1148 */
1149function do_robots() {
1150	header( 'Content-Type: text/plain; charset=utf-8' );
1151
1152	/**
1153	 * Fires when displaying the robots.txt file.
1154	 *
1155	 * @since 2.1.0
1156	 */
1157	do_action( 'do_robotstxt' );
1158
1159	$output = "User-agent: *\n";
1160	$public = get_option( 'blog_public' );
1161	if ( '0' == $public ) {
1162		$output .= "Disallow: /\n";
1163	} else {
1164		$site_url = parse_url( site_url() );
1165		$path = ( !empty( $site_url['path'] ) ) ? $site_url['path'] : '';
1166		$output .= "Disallow: $path/wp-admin/\n";
1167		$output .= "Disallow: $path/wp-includes/\n";
1168	}
1169
1170	/**
1171	 * Filter the robots.txt output.
1172	 *
1173	 * @since 3.0.0
1174	 *
1175	 * @param string $output Robots.txt output.
1176	 * @param bool   $public Whether the site is considered "public".
1177	 */
1178	echo apply_filters( 'robots_txt', $output, $public );
1179}
1180
1181/**
1182 * Test whether blog is already installed.
1183 *
1184 * The cache will be checked first. If you have a cache plugin, which saves the
1185 * cache values, then this will work. If you use the default WordPress cache,
1186 * and the database goes away, then you might have problems.
1187 *
1188 * Checks for the option siteurl for whether WordPress is installed.
1189 *
1190 * @since 2.1.0
1191 * @uses $wpdb
1192 *
1193 * @return bool Whether blog is already installed.
1194 */
1195function is_blog_installed() {
1196	global $wpdb;
1197
1198	// Check cache first. If options table goes away and we have true cached, oh well.
1199	if ( wp_cache_get( 'is_blog_installed' ) )
1200		return true;
1201
1202	$suppress = $wpdb->suppress_errors();
1203	if ( ! defined( 'WP_INSTALLING' ) ) {
1204		$alloptions = wp_load_alloptions();
1205	}
1206	// If siteurl is not set to autoload, check it specifically
1207	if ( !isset( $alloptions['siteurl'] ) )
1208		$installed = $wpdb->get_var( "SELECT option_value FROM $wpdb->options WHERE option_name = 'siteurl'" );
1209	else
1210		$installed = $alloptions['siteurl'];
1211	$wpdb->suppress_errors( $suppress );
1212
1213	$installed = !empty( $installed );
1214	wp_cache_set( 'is_blog_installed', $installed );
1215
1216	if ( $installed )
1217		return true;
1218
1219	// If visiting repair.php, return true and let it take over.
1220	if ( defined( 'WP_REPAIRING' ) )
1221		return true;
1222
1223	$suppress = $wpdb->suppress_errors();
1224
1225	// Loop over the WP tables. If none exist, then scratch install is allowed.
1226	// If one or more exist, suggest table repair since we got here because the options
1227	// table could not be accessed.
1228	$wp_tables = $wpdb->tables();
1229	foreach ( $wp_tables as $table ) {
1230		// The existence of custom user tables shouldn't suggest an insane state or prevent a clean install.
1231		if ( defined( 'CUSTOM_USER_TABLE' ) && CUSTOM_USER_TABLE == $table )
1232			continue;
1233		if ( defined( 'CUSTOM_USER_META_TABLE' ) && CUSTOM_USER_META_TABLE == $table )
1234			continue;
1235
1236		if ( ! $wpdb->get_results( "DESCRIBE $table;" ) )
1237			continue;
1238
1239		// One or more tables exist. We are insane.
1240
1241		wp_load_translations_early();
1242
1243		// Die with a DB error.
1244		$wpdb->error = sprintf( __( 'One or more database tables are unavailable. The database may need to be <a href="%s">repaired</a>.' ), 'maint/repair.php?referrer=is_blog_installed' );
1245		dead_db();
1246	}
1247
1248	$wpdb->suppress_errors( $suppress );
1249
1250	wp_cache_set( 'is_blog_installed', false );
1251
1252	return false;
1253}
1254
1255/**
1256 * Retrieve URL with nonce added to URL query.
1257 *
1258 * @since 2.0.4
1259 *
1260 * @param string $actionurl URL to add nonce action.
1261 * @param string $action Optional. Nonce action name.
1262 * @param string $name Optional. Nonce name.
1263 * @return string Escaped URL with nonce action added.
1264 */
1265function wp_nonce_url( $actionurl, $action = -1, $name = '_wpnonce' ) {
1266	$actionurl = str_replace( '&amp;', '&', $actionurl );
1267	return esc_html( add_query_arg( $name, wp_create_nonce( $action ), $actionurl ) );
1268}
1269
1270/**
1271 * Retrieve or display nonce hidden field for forms.
1272 *
1273 * The nonce field is used to validate that the contents of the form came from
1274 * the location on the current site and not somewhere else. The nonce does not
1275 * offer absolute protection, but should protect against most cases. It is very
1276 * important to use nonce field in forms.
1277 *
1278 * The $action and $name are optional, but if you want to have better security,
1279 * it is strongly suggested to set those two parameters. It is easier to just
1280 * call the function without any parameters, because validation of the nonce
1281 * doesn't require any parameters, but since crackers know what the default is
1282 * it won't be difficult for them to find a way around your nonce and cause
1283 * damage.
1284 *
1285 * The input name will be whatever $name value you gave. The input value will be
1286 * the nonce creation value.
1287 *
1288 * @since 2.0.4
1289 *
1290 * @param string $action Optional. Action name.
1291 * @param string $name Optional. Nonce name.
1292 * @param bool $referer Optional, default true. Whether to set the referer field for validation.
1293 * @param bool $echo Optional, default true. Whether to display or return hidden form field.
1294 * @return string Nonce field.
1295 */
1296function wp_nonce_field( $action = -1, $name = "_wpnonce", $referer = true , $echo = true ) {
1297	$name = esc_attr( $name );
1298	$nonce_field = '<input type="hidden" id="' . $name . '" name="' . $name . '" value="' . wp_create_nonce( $action ) . '" />';
1299
1300	if ( $referer )
1301		$nonce_field .= wp_referer_field( false );
1302
1303	if ( $echo )
1304		echo $nonce_field;
1305
1306	return $nonce_field;
1307}
1308
1309/**
1310 * Retrieve or display referer hidden field for forms.
1311 *
1312 * The referer link is the current Request URI from the server super global. The
1313 * input name is '_wp_http_referer', in case you wanted to check manually.
1314 *
1315 * @since 2.0.4
1316 *
1317 * @param bool $echo Whether to echo or return the referer field.
1318 * @return string Referer field.
1319 */
1320function wp_referer_field( $echo = true ) {
1321	$referer_field = '<input type="hidden" name="_wp_http_referer" value="'. esc_attr( wp_unslash( $_SERVER['REQUEST_URI'] ) ) . '" />';
1322
1323	if ( $echo )
1324		echo $referer_field;
1325	return $referer_field;
1326}
1327
1328/**
1329 * Retrieve or display original referer hidden field for forms.
1330 *
1331 * The input name is '_wp_original_http_referer' and will be either the same
1332 * value of {@link wp_referer_field()}, if that was posted already or it will
1333 * be the current page, if it doesn't exist.
1334 *
1335 * @since 2.0.4
1336 *
1337 * @param bool $echo Whether to echo the original http referer
1338 * @param string $jump_back_to Optional, default is 'current'. Can be 'previous' or page you want to jump back to.
1339 * @return string Original referer field.
1340 */
1341function wp_original_referer_field( $echo = true, $jump_back_to = 'current' ) {
1342	if ( ! $ref = wp_get_original_referer() ) {
1343		$ref = 'previous' == $jump_back_to ? wp_get_referer() : wp_unslash( $_SERVER['REQUEST_URI'] );
1344	}
1345	$orig_referer_field = '<input type="hidden" name="_wp_original_http_referer" value="' . esc_attr( $ref ) . '" />';
1346	if ( $echo )
1347		echo $orig_referer_field;
1348	return $orig_referer_field;
1349}
1350
1351/**
1352 * Retrieve referer from '_wp_http_referer' or HTTP referer. If it's the same
1353 * as the current request URL, will return false.
1354 *
1355 * @since 2.0.4
1356 *
1357 * @return string|bool False on failure. Referer URL on success.
1358 */
1359function wp_get_referer() {
1360	if ( ! function_exists( 'wp_validate_redirect' ) )
1361		return false;
1362	$ref = false;
1363	if ( ! empty( $_REQUEST['_wp_http_referer'] ) )
1364		$ref = wp_unslash( $_REQUEST['_wp_http_referer'] );
1365	else if ( ! empty( $_SERVER['HTTP_REFERER'] ) )
1366		$ref = wp_unslash( $_SERVER['HTTP_REFERER'] );
1367
1368	if ( $ref && $ref !== wp_unslash( $_SERVER['REQUEST_URI'] ) )
1369		return wp_validate_redirect( $ref, false );
1370	return false;
1371}
1372
1373/**
1374 * Retrieve original referer that was posted, if it exists.
1375 *
1376 * @since 2.0.4
1377 *
1378 * @return string|bool False if no original referer or original referer if set.
1379 */
1380function wp_get_original_referer() {
1381	if ( ! empty( $_REQUEST['_wp_original_http_referer'] ) && function_exists( 'wp_validate_redirect' ) )
1382		return wp_validate_redirect( wp_unslash( $_REQUEST['_wp_original_http_referer'] ), false );
1383	return false;
1384}
1385
1386/**
1387 * Recursive directory creation based on full path.
1388 *
1389 * Will attempt to set permissions on folders.
1390 *
1391 * @since 2.0.1
1392 *
1393 * @param string $target Full path to attempt to create.
1394 * @return bool Whether the path was created. True if path already exists.
1395 */
1396function wp_mkdir_p( $target ) {
1397	$wrapper = null;
1398
1399	// strip the protocol
1400	if( wp_is_stream( $target ) ) {
1401		list( $wrapper, $target ) = explode( '://', $target, 2 );
1402	}
1403
1404	// from php.net/mkdir user contributed notes
1405	$target = str_replace( '//', '/', $target );
1406
1407	// put the wrapper back on the target
1408	if( $wrapper !== null ) {
1409		$target = $wrapper . '://' . $target;
1410	}
1411
1412	// safe mode fails with a trailing slash under certain PHP versions.
1413	$target = rtrim($target, '/'); // Use rtrim() instead of untrailingslashit to avoid formatting.php dependency.
1414	if ( empty($target) )
1415		$target = '/';
1416
1417	if ( file_exists( $target ) )
1418		return @is_dir( $target );
1419
1420	// We need to find the permissions of the parent folder that exists and inherit that.
1421	$target_parent = dirname( $target );
1422	while ( '.' != $target_parent && ! is_dir( $target_parent ) ) {
1423		$target_parent = dirname( $target_parent );
1424	}
1425
1426	// Get the permission bits.
1427	if ( $stat = @stat( $target_parent ) ) {
1428		$dir_perms = $stat['mode'] & 0007777;
1429	} else {
1430		$dir_perms = 0777;
1431	}
1432
1433	if ( @mkdir( $target, $dir_perms, true ) ) {
1434
1435		// If a umask is set that modifies $dir_perms, we'll have to re-set the $dir_perms correctly with chmod()
1436		if ( $dir_perms != ( $dir_perms & ~umask() ) ) {
1437			$folder_parts = explode( '/', substr( $target, strlen( $target_parent ) + 1 ) );
1438			for ( $i = 1; $i <= count( $folder_parts ); $i++ ) {
1439				@chmod( $target_parent . '/' . implode( '/', array_slice( $folder_parts, 0, $i ) ), $dir_perms );
1440			}
1441		}
1442
1443		return true;
1444	}
1445
1446	return false;
1447}
1448
1449/**
1450 * Test if a give filesystem path is absolute ('/foo/bar', 'c:\windows').
1451 *
1452 * @since 2.5.0
1453 *
1454 * @param string $path File path
1455 * @return bool True if path is absolute, false is not absolute.
1456 */
1457function path_is_absolute( $path ) {
1458	// this is definitive if true but fails if $path does not exist or contains a symbolic link
1459	if ( realpath($path) == $path )
1460		return true;
1461
1462	if ( strlen($path) == 0 || $path[0] == '.' )
1463		return false;
1464
1465	// windows allows absolute paths like this
1466	if ( preg_match('#^[a-zA-Z]:\\\\#', $path) )
1467		return true;
1468
1469	// a path starting with / or \ is absolute; anything else is relative
1470	return ( $path[0] == '/' || $path[0] == '\\' );
1471}
1472
1473/**
1474 * Join two filesystem paths together (e.g. 'give me $path relative to $base').
1475 *
1476 * If the $path is absolute, then it the full path is returned.
1477 *
1478 * @since 2.5.0
1479 *
1480 * @param string $base
1481 * @param string $path
1482 * @return string The path with the base or absolute path.
1483 */
1484function path_join( $base, $path ) {
1485	if ( path_is_absolute($path) )
1486		return $path;
1487
1488	return rtrim($base, '/') . '/' . ltrim($path, '/');
1489}
1490
1491/**
1492 * Normalize a filesystem path.
1493 *
1494 * Replaces backslashes with forward slashes for Windows systems,
1495 * and ensures no duplicate slashes exist.
1496 *
1497 * @since 3.9.0
1498 *
1499 * @param string $path Path to normalize.
1500 * @return string Normalized path.
1501 */
1502function wp_normalize_path( $path ) {
1503	$path = str_replace( '\\', '/', $path );
1504	$path = preg_replace( '|/+|','/', $path );
1505	return $path;
1506}
1507
1508/**
1509 * Determines a writable directory for temporary files.
1510 * Function's preference is the return value of <code>sys_get_temp_dir()</code>,
1511 * followed by your PHP temporary upload directory, followed by WP_CONTENT_DIR,
1512 * before finally defaulting to /tmp/
1513 *
1514 * In the event that this function does not find a writable location,
1515 * It may be overridden by the <code>WP_TEMP_DIR</code> constant in
1516 * your <code>wp-config.php</code> file.
1517 *
1518 * @since 2.5.0
1519 *
1520 * @return string Writable temporary directory
1521 */
1522function get_temp_dir() {
1523	static $temp;
1524	if ( defined('WP_TEMP_DIR') )
1525		return trailingslashit(WP_TEMP_DIR);
1526
1527	if ( $temp )
1528		return trailingslashit( $temp );
1529
1530	if ( function_exists('sys_get_temp_dir') ) {
1531		$temp = sys_get_temp_dir();
1532		if ( @is_dir( $temp ) && wp_is_writable( $temp ) )
1533			return trailingslashit( $temp );
1534	}
1535
1536	$temp = ini_get('upload_tmp_dir');
1537	if ( @is_dir( $temp ) && wp_is_writable( $temp ) )
1538		return trailingslashit( $temp );
1539
1540	$temp = WP_CONTENT_DIR . '/';
1541	if ( is_dir( $temp ) && wp_is_writable( $temp ) )
1542		return $temp;
1543
1544	$temp = '/tmp/';
1545	return $temp;
1546}
1547
1548/**
1549 * Determine if a directory is writable.
1550 *
1551 * This function is used to work around certain ACL issues
1552 * in PHP primarily affecting Windows Servers.
1553 *
1554 * @see win_is_writable()
1555 *
1556 * @since 3.6.0
1557 *
1558 * @param string $path
1559 * @return bool
1560 */
1561function wp_is_writable( $path ) {
1562	if ( 'WIN' === strtoupper( substr( PHP_OS, 0, 3 ) ) )
1563		return win_is_writable( $path );
1564	else
1565		return @is_writable( $path );
1566}
1567
1568/**
1569 * Workaround for Windows bug in is_writable() function
1570 *
1571 * PHP has issues with Windows ACL's for determine if a
1572 * directory is writable or not, this works around them by
1573 * checking the ability to open files rather than relying
1574 * upon PHP to interprate the OS ACL.
1575 *
1576 * @link http://bugs.php.net/bug.php?id=27609
1577 * @link http://bugs.php.net/bug.php?id=30931
1578 *
1579 * @since 2.8.0
1580 *
1581 * @param string $path
1582 * @return bool
1583 */
1584function win_is_writable( $path ) {
1585
1586	if ( $path[strlen( $path ) - 1] == '/' ) // if it looks like a directory, check a random file within the directory
1587		return win_is_writable( $path . uniqid( mt_rand() ) . '.tmp');
1588	else if ( is_dir( $path ) ) // If it's a directory (and not a file) check a random file within the directory
1589		return win_is_writable( $path . '/' . uniqid( mt_rand() ) . '.tmp' );
1590
1591	// check tmp file for read/write capabilities
1592	$should_delete_tmp_file = !file_exists( $path );
1593	$f = @fopen( $path, 'a' );
1594	if ( $f === false )
1595		return false;
1596	fclose( $f );
1597	if ( $should_delete_tmp_file )
1598		unlink( $path );
1599	return true;
1600}
1601
1602/**
1603 * Get an array containing the current upload directory's path and url.
1604 *
1605 * Checks the 'upload_path' option, which should be from the web root folder,
1606 * and if it isn't empty it will be used. If it is empty, then the path will be
1607 * 'WP_CONTENT_DIR/uploads'. If the 'UPLOADS' constant is defined, then it will
1608 * override the 'upload_path' option and 'WP_CONTENT_DIR/uploads' path.
1609 *
1610 * The upload URL path is set either by the 'upload_url_path' option or by using
1611 * the 'WP_CONTENT_URL' constant and appending '/uploads' to the path.
1612 *
1613 * If the 'uploads_use_yearmonth_folders' is set to true (checkbox if checked in
1614 * the administration settings panel), then the time will be used. The format
1615 * will be year first and then month.
1616 *
1617 * If the path couldn't be created, then an error will be returned with the key
1618 * 'error' containing the error message. The error suggests that the parent
1619 * directory is not writable by the server.
1620 *
1621 * On success, the returned array will have many indices:
1622 * 'path' - base directory and sub directory or full path to upload directory.
1623 * 'url' - base url and sub directory or absolute URL to upload directory.
1624 * 'subdir' - sub directory if uploads use year/month folders option is on.
1625 * 'basedir' - path without subdir.
1626 * 'baseurl' - URL path without subdir.
1627 * 'error' - set to false.
1628 *
1629 * @since 2.0.0
1630 *
1631 * @param string $time Optional. Time formatted in 'yyyy/mm'.
1632 * @return array See above for description.
1633 */
1634function wp_upload_dir( $time = null ) {
1635	$siteurl = get_option( 'siteurl' );
1636	$upload_path = trim( get_option( 'upload_path' ) );
1637
1638	if ( empty( $upload_path ) || 'wp-content/uploads' == $upload_path ) {
1639		$dir = WP_CONTENT_DIR . '/uploads';
1640	} elseif ( 0 !== strpos( $upload_path, ABSPATH ) ) {
1641		// $dir is absolute, $upload_path is (maybe) relative to ABSPATH
1642		$dir = path_join( ABSPATH, $upload_path );
1643	} else {
1644		$dir = $upload_path;
1645	}
1646
1647	if ( !$url = get_option( 'upload_url_path' ) ) {
1648		if ( empty($upload_path) || ( 'wp-content/uploads' == $upload_path ) || ( $upload_path == $dir ) )
1649			$url = WP_CONTENT_URL . '/uploads';
1650		else
1651			$url = trailingslashit( $siteurl ) . $upload_path;
1652	}
1653
1654	// Obey the value of UPLOADS. This happens as long as ms-files rewriting is disabled.
1655	// We also sometimes obey UPLOADS when rewriting is enabled -- see the next block.
1656	if ( defined( 'UPLOADS' ) && ! ( is_multisite() && get_site_option( 'ms_files_rewriting' ) ) ) {
1657		$dir = ABSPATH . UPLOADS;
1658		$url = trailingslashit( $siteurl ) . UPLOADS;
1659	}
1660
1661	// If multisite (and if not the main site in a post-MU network)
1662	if ( is_multisite() && ! ( is_main_network() && is_main_site() && defined( 'MULTISITE' ) ) ) {
1663
1664		if ( ! get_site_option( 'ms_files_rewriting' ) ) {
1665			// If ms-files rewriting is disabled (networks created post-3.5), it is fairly straightforward:
1666			// Append sites/%d if we're not on the main site (for post-MU networks). (The extra directory
1667			// prevents a four-digit ID from conflicting with a year-based directory for the main site.
1668			// But if a MU-era network has disabled ms-files rewriting manually, they don't need the extra
1669			// directory, as they never had wp-content/uploads for the main site.)
1670
1671			if ( defined( 'MULTISITE' ) )
1672				$ms_dir = '/sites/' . get_current_blog_id();
1673			else
1674				$ms_dir = '/' . get_current_blog_id();
1675
1676			$dir .= $ms_dir;
1677			$url .= $ms_dir;
1678
1679		} elseif ( defined( 'UPLOADS' ) && ! ms_is_switched() ) {
1680			// Handle the old-form ms-files.php rewriting if the net…

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