PageRenderTime 49ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/functions.php

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

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