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

/wp-includes/functions.php

https://bitbucket.org/chimbien/mekongtest
PHP | 4072 lines | 2355 code | 378 blank | 1339 comment | 438 complexity | 3c85295a2a401a21903a6d6f9847f2e4 MD5 | raw file
Possible License(s): LGPL-2.1, GPL-2.0, AGPL-1.0

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

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