PageRenderTime 73ms CodeModel.GetById 31ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-includes/functions.php

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

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