PageRenderTime 62ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/functions.php

https://github.com/younggive/WordPress
PHP | 3761 lines | 2064 code | 368 blank | 1329 comment | 407 complexity | 5ca830cba5588d940873b189a2fa4e8c MD5 | raw file
Possible License(s): GPL-2.0, AGPL-1.0, LGPL-2.1

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

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