PageRenderTime 189ms CodeModel.GetById 93ms app.highlight 64ms RepoModel.GetById 1ms app.codeStats 2ms

/wp-includes/functions.php

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

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