PageRenderTime 59ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/web/wordpress/wp-includes/functions.php

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

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