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

/wp-includes/functions.php

https://bitbucket.org/Thane2376/death-edge.ru
PHP | 4630 lines | 2184 code | 463 blank | 1983 comment | 503 complexity | 9a8a16908cb2332ada3f33272452590d MD5 | raw file
Possible License(s): LGPL-2.1, GPL-2.0, LGPL-3.0, AGPL-1.0

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

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

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