PageRenderTime 270ms CodeModel.GetById 80ms app.highlight 98ms RepoModel.GetById 23ms app.codeStats 2ms

/APP/wp-includes/functions.php

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

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