PageRenderTime 72ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-includes/functions.php

https://bitbucket.org/theshipswakecreative/psw
PHP | 4630 lines | 2184 code | 463 blank | 1983 comment | 503 complexity | 3882ad4ef6e553161183d673a0293d2c MD5 | raw file
Possible License(s): LGPL-3.0, Apache-2.0
  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_exists( $path );
  1495. $f = @fopen( $path, 'a' );
  1496. if ( $f === false )
  1497. return false;
  1498. fclose( $f );
  1499. if ( $should_delete_tmp_file )
  1500. unlink( $path );
  1501. return true;
  1502. }
  1503. /**
  1504. * Get an array containing the current upload directory's path and url.
  1505. *
  1506. * Checks the 'upload_path' option, which should be from the web root folder,
  1507. * and if it isn't empty it will be used. If it is empty, then the path will be
  1508. * 'WP_CONTENT_DIR/uploads'. If the 'UPLOADS' constant is defined, then it will
  1509. * override the 'upload_path' option and 'WP_CONTENT_DIR/uploads' path.
  1510. *
  1511. * The upload URL path is set either by the 'upload_url_path' option or by using
  1512. * the 'WP_CONTENT_URL' constant and appending '/uploads' to the path.
  1513. *
  1514. * If the 'uploads_use_yearmonth_folders' is set to true (checkbox if checked in
  1515. * the administration settings panel), then the time will be used. The format
  1516. * will be year first and then month.
  1517. *
  1518. * If the path couldn't be created, then an error will be returned with the key
  1519. * 'error' containing the error message. The error suggests that the parent
  1520. * directory is not writable by the server.
  1521. *
  1522. * On success, the returned array will have many indices:
  1523. * 'path' - base directory and sub directory or full path to upload directory.
  1524. * 'url' - base url and sub directory or absolute URL to upload directory.
  1525. * 'subdir' - sub directory if uploads use year/month folders option is on.
  1526. * 'basedir' - path without subdir.
  1527. * 'baseurl' - URL path without subdir.
  1528. * 'error' - set to false.
  1529. *
  1530. * @since 2.0.0
  1531. *
  1532. * @param string $time Optional. Time formatted in 'yyyy/mm'. Default null.
  1533. * @return array See above for description.
  1534. */
  1535. function wp_upload_dir( $time = null ) {
  1536. $siteurl = get_option( 'siteurl' );
  1537. $upload_path = trim( get_option( 'upload_path' ) );
  1538. if ( empty( $upload_path ) || 'wp-content/uploads' == $upload_path ) {
  1539. $dir = WP_CONTENT_DIR . '/uploads';
  1540. } elseif ( 0 !== strpos( $upload_path, ABSPATH ) ) {
  1541. // $dir is absolute, $upload_path is (maybe) relative to ABSPATH
  1542. $dir = path_join( ABSPATH, $upload_path );
  1543. } else {
  1544. $dir = $upload_path;
  1545. }
  1546. if ( !$url = get_option( 'upload_url_path' ) ) {
  1547. if ( empty($upload_path) || ( 'wp-content/uploads' == $upload_path ) || ( $upload_path == $dir ) )
  1548. $url = WP_CONTENT_URL . '/uploads';
  1549. else
  1550. $url = trailingslashit( $siteurl ) . $upload_path;
  1551. }
  1552. /*
  1553. * Honor the value of UPLOADS. This happens as long as ms-files rewriting is disabled.
  1554. * We also sometimes obey UPLOADS when rewriting is enabled -- see the next block.
  1555. */
  1556. if ( defined( 'UPLOADS' ) && ! ( is_multisite() && get_site_option( 'ms_files_rewriting' ) ) ) {
  1557. $dir = ABSPATH . UPLOADS;
  1558. $url = trailingslashit( $siteurl ) . UPLOADS;
  1559. }
  1560. // If multisite (and if not the main site in a post-MU network)
  1561. if ( is_multisite() && ! ( is_main_network() && is_main_site() && defined( 'MULTISITE' ) ) ) {
  1562. if ( ! get_site_option( 'ms_files_rewriting' ) ) {
  1563. /*
  1564. * If ms-files rewriting is disabled (networks created post-3.5), it is fairly
  1565. * straightforward: Append sites/%d if we're not on the main site (for post-MU
  1566. * networks). (The extra directory prevents a four-digit ID from conflicting with
  1567. * a year-based directory for the main site. But if a MU-era network has disabled
  1568. * ms-files rewriting manually, they don't need the extra directory, as they never
  1569. * had wp-content/uploads for the main site.)
  1570. */
  1571. if ( defined( 'MULTISITE' ) )
  1572. $ms_dir = '/sites/' . get_current_blog_id();
  1573. else
  1574. $ms_dir = '/' . get_current_blog_id();
  1575. $dir .= $ms_dir;
  1576. $url .= $ms_dir;
  1577. } elseif ( defined( 'UPLOADS' ) && ! ms_is_switched() ) {
  1578. /*
  1579. * Handle the old-form ms-files.php rewriting if the network still has that enabled.
  1580. * When ms-files rewriting is enabled, then we only listen to UPLOADS when:
  1581. * 1) We are not on the main site in a post-MU network, as wp-content/uploads is used
  1582. * there, and
  1583. * 2) We are not switched, as ms_upload_constants() hardcodes these constants to reflect
  1584. * the original blog ID.
  1585. *
  1586. * Rather than UPLOADS, we actually use BLOGUPLOADDIR if it is set, as it is absolute.
  1587. * (And it will be set, see ms_upload_constants().) Otherwise, UPLOADS can be used, as
  1588. * as it is relative to ABSPATH. For the final piece: when UPLOADS is used with ms-files
  1589. * rewriting in multisite, the resulting URL is /files. (#WP22702 for background.)
  1590. */
  1591. if ( defined( 'BLOGUPLOADDIR' ) )
  1592. $dir = untrailingslashit( BLOGUPLOADDIR );
  1593. else
  1594. $dir = ABSPATH . UPLOADS;
  1595. $url = trailingslashit( $siteurl ) . 'files';
  1596. }
  1597. }
  1598. $basedir = $dir;
  1599. $baseurl = $url;
  1600. $subdir = '';
  1601. if ( get_option( 'uploads_use_yearmonth_folders' ) ) {
  1602. // Generate the yearly and monthly dirs
  1603. if ( !$time )
  1604. $time = current_time( 'mysql' );
  1605. $y = substr( $time, 0, 4 );
  1606. $m = substr( $time, 5, 2 );
  1607. $subdir = "/$y/$m";
  1608. }
  1609. $dir .= $subdir;
  1610. $url .= $subdir;
  1611. /**
  1612. * Filter the uploads directory data.
  1613. *
  1614. * @since 2.0.0
  1615. *
  1616. * @param array $uploads Array of upload directory data with keys of 'path',
  1617. * 'url', 'subdir, 'basedir', and 'error'.
  1618. */
  1619. $uploads = apply_filters( 'upload_dir',
  1620. array(
  1621. 'path' => $dir,
  1622. 'url' => $url,
  1623. 'subdir' => $subdir,
  1624. 'basedir' => $basedir,
  1625. 'baseurl' => $baseurl,
  1626. 'error' => false,
  1627. ) );
  1628. // Make sure we have an uploads directory.
  1629. if ( ! wp_mkdir_p( $uploads['path'] ) ) {
  1630. if ( 0 === strpos( $uploads['basedir'], ABSPATH ) )
  1631. $error_path = str_replace( ABSPATH, '', $uploads['basedir'] ) . $uploads['subdir'];
  1632. else
  1633. $error_path = basename( $uploads['basedir'] ) . $uploads['subdir'];
  1634. $message = sprintf( __( 'Unable to create directory %s. Is its parent directory writable by the server?' ), $error_path );
  1635. $uploads['error'] = $message;
  1636. }
  1637. return $uploads;
  1638. }
  1639. /**
  1640. * Get a filename that is sanitized and unique for the given directory.
  1641. *
  1642. * If the filename is not unique, then a number will be added to the filename
  1643. * before the extension, and will continue adding numbers until the filename is
  1644. * unique.
  1645. *
  1646. * The callback is passed three parameters, the first one is the directory, the
  1647. * second is the filename, and the third is the extension.
  1648. *
  1649. * @since 2.5.0
  1650. *
  1651. * @param string $dir Directory.
  1652. * @param string $filename File name.
  1653. * @param callback $unique_filename_callback Callback. Default null.
  1654. * @return string New filename, if given wasn't unique.
  1655. */
  1656. function wp_unique_filename( $dir, $filename, $unique_filename_callback = null ) {
  1657. // Sanitize the file name before we begin processing.
  1658. $filename = sanitize_file_name($filename);
  1659. // Separate the filename into a name and extension.
  1660. $info = pathinfo($filename);
  1661. $ext = !empty($info['extension']) ? '.' . $info['extension'] : '';
  1662. $name = basename($filename, $ext);
  1663. // Edge case: if file is named '.ext', treat as an empty name.
  1664. if ( $name === $ext )
  1665. $name = '';
  1666. /*
  1667. * Increment the file number until we have a unique file to save in $dir.
  1668. * Use callback if supplied.
  1669. */
  1670. if ( $unique_filename_callback && is_callable( $unique_filename_callback ) ) {
  1671. $filename = call_user_func( $unique_filename_callback, $dir, $name, $ext );
  1672. } else {
  1673. $number = '';
  1674. // Change '.ext' to lower case.
  1675. if ( $ext && strtolower($ext) != $ext ) {
  1676. $ext2 = strtolower($ext);
  1677. $filename2 = preg_replace( '|' . preg_quote($ext) . '$|', $ext2, $filename );
  1678. // Check for both lower and upper case extension or image sub-sizes may be overwritten.
  1679. while ( file_exists($dir . "/$filename") || file_exists($dir . "/$filename2") ) {
  1680. $new_number = $number + 1;
  1681. $filename = str_replace( "$number$ext", "$new_number$ext", $filename );
  1682. $filename2 = str_replace( "$number$ext2", "$new_number$ext2", $filename2 );
  1683. $number = $new_number;
  1684. }
  1685. return $filename2;
  1686. }
  1687. while ( file_exists( $dir . "/$filename" ) ) {
  1688. if ( '' == "$number$ext" )
  1689. $filename = $filename . ++$number . $ext;
  1690. else
  1691. $filename = str_replace( "$number$ext", ++$number . $ext, $filename );
  1692. }
  1693. }
  1694. return $filename;
  1695. }
  1696. /**
  1697. * Create a file in the upload folder with given content.
  1698. *
  1699. * If there is an error, then the key 'error' will exist with the error message.
  1700. * If success, then the key 'file' will have the unique file path, the 'url' key
  1701. * will have the link to the new file. and the 'error' key will be set to false.
  1702. *
  1703. * This function will not move an uploaded file to the upload folder. It will
  1704. * create a new file with the content in $bits parameter. If you move the upload
  1705. * file, read the content of the uploaded file, and then you can give the
  1706. * filename and content to this function, which will add it to the upload
  1707. * folder.
  1708. *
  1709. * The permissions will be set on the new file automatically by this function.
  1710. *
  1711. * @since 2.0.0
  1712. *
  1713. * @param string $name Filename.
  1714. * @param null $deprecated Never used. Set to null.
  1715. * @param mixed $bits File content
  1716. * @param string $time Optional. Time formatted in 'yyyy/mm'. Default null.
  1717. * @return array
  1718. */
  1719. function wp_upload_bits( $name, $deprecated, $bits, $time = null ) {
  1720. if ( !empty( $deprecated ) )
  1721. _deprecated_argument( __FUNCTION__, '2.0' );
  1722. if ( empty( $name ) )
  1723. return array( 'error' => __( 'Empty filename' ) );
  1724. $wp_filetype = wp_check_filetype( $name );
  1725. if ( ! $wp_filetype['ext'] && ! current_user_can( 'unfiltered_upload' ) )
  1726. return array( 'error' => __( 'Invalid file type' ) );
  1727. $upload = wp_upload_dir( $time );
  1728. if ( $upload['error'] !== false )
  1729. return $upload;
  1730. /**
  1731. * Filter whether to treat the upload bits as an error.
  1732. *
  1733. * Passing a non-array to the filter will effectively short-circuit preparing
  1734. * the upload bits, returning that value instead.
  1735. *
  1736. * @since 3.0.0
  1737. *
  1738. * @param mixed $upload_bits_error An array of upload bits data, or a non-array error to return.
  1739. */
  1740. $upload_bits_error = apply_filters( 'wp_upload_bits', array( 'name' => $name, 'bits' => $bits, 'time' => $time ) );
  1741. if ( !is_array( $upload_bits_error ) ) {
  1742. $upload[ 'error' ] = $upload_bits_error;
  1743. return $upload;
  1744. }
  1745. $filename = wp_unique_filename( $upload['path'], $name );
  1746. $new_file = $upload['path'] . "/$filename";
  1747. if ( ! wp_mkdir_p( dirname( $new_file ) ) ) {
  1748. if ( 0 === strpos( $upload['basedir'], ABSPATH ) )
  1749. $error_path = str_replace( ABSPATH, '', $upload['basedir'] ) . $upload['subdir'];
  1750. else
  1751. $error_path = basename( $upload['basedir'] ) . $upload['subdir'];
  1752. $message = sprintf( __( 'Unable to create directory %s. Is its parent directory writable by the server?' ), $error_path );
  1753. return array( 'error' => $message );
  1754. }
  1755. $ifp = @ fopen( $new_file, 'wb' );
  1756. if ( ! $ifp )
  1757. return array( 'error' => sprintf( __( 'Could not write file %s' ), $new_file ) );
  1758. @fwrite( $ifp, $bits );
  1759. fclose( $ifp );
  1760. clearstatcache();
  1761. // Set correct file permissions
  1762. $stat = @ stat( dirname( $new_file ) );
  1763. $perms = $stat['mode'] & 0007777;
  1764. $perms = $perms & 0000666;
  1765. @ chmod( $new_file, $perms );
  1766. clearstatcache();
  1767. // Compute the URL
  1768. $url = $upload['url'] . "/$filename";
  1769. return array( 'file' => $new_file, 'url' => $url, 'error' => false );
  1770. }
  1771. /**
  1772. * Retrieve the file type based on the extension name.
  1773. *
  1774. * @since 2.5.0
  1775. *
  1776. * @param string $ext The extension to search.
  1777. * @return string|null The file type, example: audio, video, document, spreadsheet, etc.
  1778. * Null if not found.
  1779. */
  1780. function wp_ext2type( $ext ) {
  1781. $ext = strtolower( $ext );
  1782. /**
  1783. * Filter file type based on the extension name.
  1784. *
  1785. * @since 2.5.0
  1786. *
  1787. * @see wp_ext2type()
  1788. *
  1789. * @param array $ext2type Multi-dimensional array with extensions for a default set
  1790. * of file types.
  1791. */
  1792. $ext2type = apply_filters( 'ext2type', array(
  1793. 'image' => array( 'jpg', 'jpeg', 'jpe', 'gif', 'png', 'bmp', 'tif', 'tiff', 'ico' ),
  1794. 'audio' => array( 'aac', 'ac3', 'aif', 'aiff', 'm3a', 'm4a', 'm4b', 'mka', 'mp1', 'mp2', 'mp3', 'ogg', 'oga', 'ram', 'wav', 'wma' ),
  1795. 'video' => array( '3g2', '3gp', '3gpp', 'asf', 'avi', 'divx', 'dv', 'flv', 'm4v', 'mkv', 'mov', 'mp4', 'mpeg', 'mpg', 'mpv', 'ogm', 'ogv', 'qt', 'rm', 'vob', 'wmv' ),
  1796. 'document' => array( 'doc', 'docx', 'docm', 'dotm', 'odt', 'pages', 'pdf', 'xps', 'oxps', 'rtf', 'wp', 'wpd' ),
  1797. 'spreadsheet' => array( 'numbers', 'ods', 'xls', 'xlsx', 'xlsm', 'xlsb' ),
  1798. 'interactive' => array( 'swf', 'key', 'ppt', 'pptx', 'pptm', 'pps', 'ppsx', 'ppsm', 'sldx', 'sldm', 'odp' ),
  1799. 'text' => array( 'asc', 'csv', 'tsv', 'txt' ),
  1800. 'archive' => array( 'bz2', 'cab', 'dmg', 'gz', 'rar', 'sea', 'sit', 'sqx', 'tar', 'tgz', 'zip', '7z' ),
  1801. 'code' => array( 'css', 'htm', 'html', 'php', 'js' ),
  1802. ) );
  1803. foreach ( $ext2type as $type => $exts )
  1804. if ( in_array( $ext, $exts ) )
  1805. return $type;
  1806. return null;
  1807. }
  1808. /**
  1809. * Retrieve the file type from the file name.
  1810. *
  1811. * You can optionally define the mime array, if needed.
  1812. *
  1813. * @since 2.0.4
  1814. *
  1815. * @param string $filename File name or path.
  1816. * @param array $mimes Optional. Key is the file extension with value as the mime type.
  1817. * @return array Values with extension first and mime type.
  1818. */
  1819. function wp_check_filetype( $filename, $mimes = null ) {
  1820. if ( empty($mimes) )
  1821. $mimes = get_allowed_mime_types();
  1822. $type = false;
  1823. $ext = false;
  1824. foreach ( $mimes as $ext_preg => $mime_match ) {
  1825. $ext_preg = '!\.(' . $ext_preg . ')$!i';
  1826. if ( preg_match( $ext_preg, $filename, $ext_matches ) ) {
  1827. $type = $mime_match;
  1828. $ext = $ext_matches[1];
  1829. break;
  1830. }
  1831. }
  1832. return compact( 'ext', 'type' );
  1833. }
  1834. /**
  1835. * Attempt to determine the real file type of a file.
  1836. *
  1837. * If unable to, the file name extension will be used to determine type.
  1838. *
  1839. * If it's determined that the extension does not match the file's real type,
  1840. * then the "proper_filename" value will be set with a proper filename and extension.
  1841. *
  1842. * Currently this function only supports validating images known to getimagesize().
  1843. *
  1844. * @since 3.0.0
  1845. *
  1846. * @param string $file Full path to the file.
  1847. * @param string $filename The name of the file (may differ from $file due to $file being
  1848. * in a tmp directory).
  1849. * @param array $mimes Optional. Key is the file extension with value as the mime type.
  1850. * @return array Values for the extension, MIME, and either a corrected filename or false
  1851. * if original $filename is valid.
  1852. */
  1853. function wp_check_filetype_and_ext( $file, $filename, $mimes = null ) {
  1854. $proper_filename = false;
  1855. // Do basic extension validation and MIME mapping
  1856. $wp_filetype = wp_check_filetype( $filename, $mimes );
  1857. $ext = $wp_filetype['ext'];
  1858. $type = $wp_filetype['type'];
  1859. // We can't do any further validation without a file to work with
  1860. if ( ! file_exists( $file ) ) {
  1861. return compact( 'ext', 'type', 'proper_filename' );
  1862. }
  1863. // We're able to validate images using GD
  1864. if ( $type && 0 === strpos( $type, 'image/' ) && function_exists('getimagesize') ) {
  1865. // Attempt to figure out what type of image it actually is
  1866. $imgstats = @getimagesize( $file );
  1867. // If getimagesize() knows what kind of image it really is and if the real MIME doesn't match the claimed MIME
  1868. if ( !empty($imgstats['mime']) && $imgstats['mime'] != $type ) {
  1869. /**
  1870. * Filter the list mapping image mime types to their respective extensions.
  1871. *
  1872. * @since 3.0.0
  1873. *
  1874. * @param array $mime_to_ext Array of image mime types and their matching extensions.
  1875. */
  1876. $mime_to_ext = apply_filters( 'getimagesize_mimes_to_exts', array(
  1877. 'image/jpeg' => 'jpg',
  1878. 'image/png' => 'png',
  1879. 'image/gif' => 'gif',
  1880. 'image/bmp' => 'bmp',
  1881. 'image/tiff' => 'tif',
  1882. ) );
  1883. // Replace whatever is after the last period in the filename with the correct extension
  1884. if ( ! empty( $mime_to_ext[ $imgstats['mime'] ] ) ) {
  1885. $filename_parts = explode( '.', $filename );
  1886. array_pop( $filename_parts );
  1887. $filename_parts[] = $mime_to_ext[ $imgstats['mime'] ];
  1888. $new_filename = implode( '.', $filename_parts );
  1889. if ( $new_filename != $filename ) {
  1890. $proper_filename = $new_filename; // Mark that it changed
  1891. }
  1892. // Redefine the extension / MIME
  1893. $wp_filetype = wp_check_filetype( $new_filename, $mimes );
  1894. $ext = $wp_filetype['ext'];
  1895. $type = $wp_filetype['type'];
  1896. }
  1897. }
  1898. }
  1899. /**
  1900. * Filter the "real" file type of the given file.
  1901. *
  1902. * @since 3.0.0
  1903. *
  1904. * @param array $wp_check_filetype_and_ext File data array containing 'ext', 'type', and
  1905. * 'proper_filename' keys.
  1906. * @param string $file Full path to the file.
  1907. * @param string $filename The name of the file (may differ from $file due to
  1908. * $file being in a tmp directory).
  1909. * @param array $mimes Key is the file extension with value as the mime type.
  1910. */
  1911. return apply_filters( 'wp_check_filetype_and_ext', compact( 'ext', 'type', 'proper_filename' ), $file, $filename, $mimes );
  1912. }
  1913. /**
  1914. * Retrieve list of mime types and file extensions.
  1915. *
  1916. * @since 3.5.0
  1917. *
  1918. * @return array Array of mime types keyed by the file extension regex corresponding to those types.
  1919. */
  1920. function wp_get_mime_types() {
  1921. /**
  1922. * Filter the list of mime types and file extensions.
  1923. *
  1924. * This filter should be used to add, not remove, mime types. To remove
  1925. * mime types, use the 'upload_mimes' filter.
  1926. *
  1927. * @since 3.5.0
  1928. *
  1929. * @param array $wp_get_mime_types Mime types keyed by the file extension regex
  1930. * corresponding to those types.
  1931. */
  1932. return apply_filters( 'mime_types', array(
  1933. // Image formats.
  1934. 'jpg|jpeg|jpe' => 'image/jpeg',
  1935. 'gif' => 'image/gif',
  1936. 'png' => 'image/png',
  1937. 'bmp' => 'image/bmp',
  1938. 'tif|tiff' => 'image/tiff',
  1939. 'ico' => 'image/x-icon',
  1940. // Video formats.
  1941. 'asf|asx' => 'video/x-ms-asf',
  1942. 'wmv' => 'video/x-ms-wmv',
  1943. 'wmx' => 'video/x-ms-wmx',
  1944. 'wm' => 'video/x-ms-wm',
  1945. 'avi' => 'video/avi',
  1946. 'divx' => 'video/divx',
  1947. 'flv' => 'video/x-flv',
  1948. 'mov|qt' => 'video/quicktime',
  1949. 'mpeg|mpg|mpe' => 'video/mpeg',
  1950. 'mp4|m4v' => 'video/mp4',
  1951. 'ogv' => 'video/ogg',
  1952. 'webm' => 'video/webm',
  1953. 'mkv' => 'video/x-matroska',
  1954. '3gp|3gpp' => 'video/3gpp', // Can also be audio
  1955. '3g2|3gp2' => 'video/3gpp2', // Can also be audio
  1956. // Text formats.
  1957. 'txt|asc|c|cc|h|srt' => 'text/plain',
  1958. 'csv' => 'text/csv',
  1959. 'tsv' => 'text/tab-separated-values',
  1960. 'ics' => 'text/calendar',
  1961. 'rtx' => 'text/richtext',
  1962. 'css' => 'text/css',
  1963. 'htm|html' => 'text/html',
  1964. 'vtt' => 'text/vtt',
  1965. 'dfxp' => 'application/ttaf+xml',
  1966. // Audio formats.
  1967. 'mp3|m4a|m4b' => 'audio/mpeg',
  1968. 'ra|ram' => 'audio/x-realaudio',
  1969. 'wav' => 'audio/wav',
  1970. 'ogg|oga' => 'audio/ogg',
  1971. 'mid|midi' => 'audio/midi',
  1972. 'wma' => 'audio/x-ms-wma',
  1973. 'wax' => 'audio/x-ms-wax',
  1974. 'mka' => 'audio/x-matroska',
  1975. // Misc application formats.
  1976. 'rtf' => 'application/rtf',
  1977. 'js' => 'application/javascript',
  1978. 'pdf' => 'application/pdf',
  1979. 'swf' => 'application/x-shockwave-flash',
  1980. 'class' => 'application/java',
  1981. 'tar' => 'application/x-tar',
  1982. 'zip' => 'application/zip',
  1983. 'gz|gzip' => 'application/x-gzip',
  1984. 'rar' => 'application/rar',
  1985. '7z' => 'application/x-7z-compressed',
  1986. 'exe' => 'application/x-msdownload',
  1987. // MS Office formats.
  1988. 'doc' => 'application/msword',
  1989. 'pot|pps|ppt' => 'application/vnd.ms-powerpoint',
  1990. 'wri' => 'application/vnd.ms-write',
  1991. 'xla|xls|xlt|xlw' => 'application/vnd.ms-excel',
  1992. 'mdb' => 'application/vnd.ms-access',
  1993. 'mpp' => 'application/vnd.ms-project',
  1994. 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  1995. 'docm' => 'application/vnd.ms-word.document.macroEnabled.12',
  1996. 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
  1997. 'dotm' => 'application/vnd.ms-word.template.macroEnabled.12',
  1998. 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  1999. 'xlsm' => 'application/vnd.ms-excel.sheet.macroEnabled.12',
  2000. 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
  2001. 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
  2002. 'xltm' => 'application/vnd.ms-excel.template.macroEnabled.12',
  2003. 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
  2004. 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  2005. 'pptm' => 'application/vnd.ms-powerpoint.presentation.macroEnabled.12',
  2006. 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
  2007. 'ppsm' => 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12',
  2008. 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
  2009. 'potm' => 'application/vnd.ms-powerpoint.template.macroEnabled.12',
  2010. 'ppam' => 'application/vnd.ms-powerpoint.addin.macroEnabled.12',
  2011. 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
  2012. 'sldm' => 'application/vnd.ms-powerpoint.slide.macroEnabled.12',
  2013. 'onetoc|onetoc2|onetmp|onepkg' => 'application/onenote',
  2014. 'oxps' => 'application/oxps',
  2015. 'xps' => 'application/vnd.ms-xpsdocument',
  2016. // OpenOffice formats.
  2017. 'odt' => 'application/vnd.oasis.opendocument.text',
  2018. 'odp' => 'application/vnd.oasis.opendocument.presentation',
  2019. 'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
  2020. 'odg' => 'application/vnd.oasis.opendocument.graphics',
  2021. 'odc' => 'application/vnd.oasis.opendocument.chart',
  2022. 'odb' => 'application/vnd.oasis.opendocument.database',
  2023. 'odf' => 'application/vnd.oasis.opendocument.formula',
  2024. // WordPerfect formats.
  2025. 'wp|wpd' => 'application/wordperfect',
  2026. // iWork formats.
  2027. 'key' => 'application/vnd.apple.keynote',
  2028. 'numbers' => 'application/vnd.apple.numbers',
  2029. 'pages' => 'application/vnd.apple.pages',
  2030. ) );
  2031. }
  2032. /**
  2033. * Retrieve list of allowed mime types and file extensions.
  2034. *
  2035. * @since 2.8.6
  2036. *
  2037. * @uses wp_get_upload_mime_types() to fetch the list of mime types
  2038. *
  2039. * @param int|WP_User $user Optional. User to check. Defaults to current user.
  2040. * @return array Array of mime types keyed by the file extension regex corresponding
  2041. * to those types.
  2042. */
  2043. function get_allowed_mime_types( $user = null ) {
  2044. $t = wp_get_mime_types();
  2045. unset( $t['swf'], $t['exe'] );
  2046. if ( function_exists( 'current_user_can' ) )
  2047. $unfiltered = $user ? user_can( $user, 'unfiltered_html' ) : current_user_can( 'unfiltered_html' );
  2048. if ( empty( $unfiltered ) )
  2049. unset( $t['htm|html'] );
  2050. /**
  2051. * Filter list of allowed mime types and file extensions.
  2052. *
  2053. * @since 2.0.0
  2054. *
  2055. * @param array $t Mime types keyed by the file extension regex corresponding to
  2056. * those types. 'swf' and 'exe' removed from full list. 'htm|html' also
  2057. * removed depending on '$user' capabilities.
  2058. * @param int|WP_User|null $user User ID, User object or null if not provided (indicates current user).
  2059. */
  2060. return apply_filters( 'upload_mimes', $t, $user );
  2061. }
  2062. /**
  2063. * Display "Are You Sure" message to confirm the action being taken.
  2064. *
  2065. * If the action has the nonce explain message, then it will be displayed
  2066. * along with the "Are you sure?" message.
  2067. *
  2068. * @since 2.0.4
  2069. *
  2070. * @param string $action The nonce action.
  2071. */
  2072. function wp_nonce_ays( $action ) {
  2073. $title = __( 'WordPress Failure Notice' );
  2074. if ( 'log-out' == $action ) {
  2075. $html = sprintf( __( 'You are attempting to log out of %s' ), get_bloginfo( 'name' ) ) . '</p><p>';
  2076. $redirect_to = isset( $_REQUEST['redirect_to'] ) ? $_REQUEST['redirect_to'] : '';
  2077. $html .= sprintf( __( "Do you really want to <a href='%s'>log out</a>?"), wp_logout_url( $redirect_to ) );
  2078. } else {
  2079. $html = __( 'Are you sure you want to do this?' );
  2080. if ( wp_get_referer() )
  2081. $html .= "</p><p><a href='" . esc_url( remove_query_arg( 'updated', wp_get_referer() ) ) . "'>" . __( 'Please try again.' ) . "</a>";
  2082. }
  2083. wp_die( $html, $title, array('response' => 403) );
  2084. }
  2085. /**
  2086. * Kill WordPress execution and display HTML message with error message.
  2087. *
  2088. * This function complements the die() PHP function. The difference is that
  2089. * HTML will be displayed to the user. It is recommended to use this function
  2090. * only, when the execution should not continue any further. It is not
  2091. * recommended to call this function very often and try to handle as many errors
  2092. * as possible silently.
  2093. *
  2094. * @since 2.0.4
  2095. *
  2096. * @param string $message Optional. Error message. Default empty.
  2097. * @param string $title Optional. Error title. Default empty.
  2098. * @param string|array $args Optional. Arguments to control behavior. Default empty array.
  2099. */
  2100. function wp_die( $message = '', $title = '', $args = array() ) {
  2101. if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
  2102. /**
  2103. * Filter callback for killing WordPress execution for AJAX requests.
  2104. *
  2105. * @since 3.4.0
  2106. *
  2107. * @param callback $function Callback function name.
  2108. */
  2109. $function = apply_filters( 'wp_die_ajax_handler', '_ajax_wp_die_handler' );
  2110. } elseif ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST ) {
  2111. /**
  2112. * Filter callback for killing WordPress execution for XML-RPC requests.
  2113. *
  2114. * @since 3.4.0
  2115. *
  2116. * @param callback $function Callback function name.
  2117. */
  2118. $function = apply_filters( 'wp_die_xmlrpc_handler', '_xmlrpc_wp_die_handler' );
  2119. } else {
  2120. /**
  2121. * Filter callback for killing WordPress execution for all non-AJAX, non-XML-RPC requests.
  2122. *
  2123. * @since 3.0.0
  2124. *
  2125. * @param callback $function Callback function name.
  2126. */
  2127. $function = apply_filters( 'wp_die_handler', '_default_wp_die_handler' );
  2128. }
  2129. call_user_func( $function, $message, $title, $args );
  2130. }
  2131. /**
  2132. * Kill WordPress execution and display HTML message with error message.
  2133. *
  2134. * This is the default handler for wp_die if you want a custom one for your
  2135. * site then you can overload using the wp_die_handler filter in wp_die
  2136. *
  2137. * @since 3.0.0
  2138. * @access private
  2139. *
  2140. * @param string $message Error message.
  2141. * @param string $title Optional. Error title. Default empty.
  2142. * @param string|array $args Optional. Arguments to control behavior. Default empty array.
  2143. */
  2144. function _default_wp_die_handler( $message, $title = '', $args = array() ) {
  2145. $defaults = array( 'response' => 500 );
  2146. $r = wp_parse_args($args, $defaults);
  2147. $have_gettext = function_exists('__');
  2148. if ( function_exists( 'is_wp_error' ) && is_wp_error( $message ) ) {
  2149. if ( empty( $title ) ) {
  2150. $error_data = $message->get_error_data();
  2151. if ( is_array( $error_data ) && isset( $error_data['title'] ) )
  2152. $title = $error_data['title'];
  2153. }
  2154. $errors = $message->get_error_messages();
  2155. switch ( count( $errors ) ) {
  2156. case 0 :
  2157. $message = '';
  2158. break;
  2159. case 1 :
  2160. $message = "<p>{$errors[0]}</p>";
  2161. break;
  2162. default :
  2163. $message = "<ul>\n\t\t<li>" . join( "</li>\n\t\t<li>", $errors ) . "</li>\n\t</ul>";
  2164. break;
  2165. }
  2166. } elseif ( is_string( $message ) ) {
  2167. $message = "<p>$message</p>";
  2168. }
  2169. if ( isset( $r['back_link'] ) && $r['back_link'] ) {
  2170. $back_text = $have_gettext? __('&laquo; Back') : '&laquo; Back';
  2171. $message .= "\n<p><a href='javascript:history.back()'>$back_text</a></p>";
  2172. }
  2173. if ( ! did_action( 'admin_head' ) ) :
  2174. if ( !headers_sent() ) {
  2175. status_header( $r['response'] );
  2176. nocache_headers();
  2177. header( 'Content-Type: text/html; charset=utf-8' );
  2178. }
  2179. if ( empty($title) )
  2180. $title = $have_gettext ? __('WordPress &rsaquo; Error') : 'WordPress &rsaquo; Error';
  2181. $text_direction = 'ltr';
  2182. if ( isset($r['text_direction']) && 'rtl' == $r['text_direction'] )
  2183. $text_direction = 'rtl';
  2184. elseif ( function_exists( 'is_rtl' ) && is_rtl() )
  2185. $text_direction = 'rtl';
  2186. ?>
  2187. <!DOCTYPE html>
  2188. <!-- Ticket #11289, IE bug fix: always pad the error page with enough characters such that it is greater than 512 bytes, even after gzip compression abcdefghijklmnopqrstuvwxyz1234567890aabbccddeeffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz11223344556677889900abacbcbdcdcededfefegfgfhghgihihjijikjkjlklkmlmlnmnmononpopoqpqprqrqsrsrtstsubcbcdcdedefefgfabcadefbghicjkldmnoepqrfstugvwxhyz1i234j567k890laabmbccnddeoeffpgghqhiirjjksklltmmnunoovppqwqrrxsstytuuzvvw0wxx1yyz2z113223434455666777889890091abc2def3ghi4jkl5mno6pqr7stu8vwx9yz11aab2bcc3dd4ee5ff6gg7hh8ii9j0jk1kl2lmm3nnoo4p5pq6qrr7ss8tt9uuvv0wwx1x2yyzz13aba4cbcb5dcdc6dedfef8egf9gfh0ghg1ihi2hji3jik4jkj5lkl6kml7mln8mnm9ono
  2189. -->
  2190. <html xmlns="http://www.w3.org/1999/xhtml" <?php if ( function_exists( 'language_attributes' ) && function_exists( 'is_rtl' ) ) language_attributes(); else echo "dir='$text_direction'"; ?>>
  2191. <head>
  2192. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  2193. <title><?php echo $title ?></title>
  2194. <style type="text/css">
  2195. html {
  2196. background: #f1f1f1;
  2197. }
  2198. body {
  2199. background: #fff;
  2200. color: #444;
  2201. font-family: "Open Sans", sans-serif;
  2202. margin: 2em auto;
  2203. padding: 1em 2em;
  2204. max-width: 700px;
  2205. -webkit-box-shadow: 0 1px 3px rgba(0,0,0,0.13);
  2206. box-shadow: 0 1px 3px rgba(0,0,0,0.13);
  2207. }
  2208. h1 {
  2209. border-bottom: 1px solid #dadada;
  2210. clear: both;
  2211. color: #666;
  2212. font: 24px "Open Sans", sans-serif;
  2213. margin: 30px 0 0 0;
  2214. padding: 0;
  2215. padding-bottom: 7px;
  2216. }
  2217. #error-page {
  2218. margin-top: 50px;
  2219. }
  2220. #error-page p {
  2221. font-size: 14px;
  2222. line-height: 1.5;
  2223. margin: 25px 0 20px;
  2224. }
  2225. #error-page code {
  2226. font-family: Consolas, Monaco, monospace;
  2227. }
  2228. ul li {
  2229. margin-bottom: 10px;
  2230. font-size: 14px ;
  2231. }
  2232. a {
  2233. color: #21759B;
  2234. text-decoration: none;
  2235. }
  2236. a:hover {
  2237. color: #D54E21;
  2238. }
  2239. .button {
  2240. background: #f7f7f7;
  2241. border: 1px solid #cccccc;
  2242. color: #555;
  2243. display: inline-block;
  2244. text-decoration: none;
  2245. font-size: 13px;
  2246. line-height: 26px;
  2247. height: 28px;
  2248. margin: 0;
  2249. padding: 0 10px 1px;
  2250. cursor: pointer;
  2251. -webkit-border-radius: 3px;
  2252. -webkit-appearance: none;
  2253. border-radius: 3px;
  2254. white-space: nowrap;
  2255. -webkit-box-sizing: border-box;
  2256. -moz-box-sizing: border-box;
  2257. box-sizing: border-box;
  2258. -webkit-box-shadow: inset 0 1px 0 #fff, 0 1px 0 rgba(0,0,0,.08);
  2259. box-shadow: inset 0 1px 0 #fff, 0 1px 0 rgba(0,0,0,.08);
  2260. vertical-align: top;
  2261. }
  2262. .button.button-large {
  2263. height: 29px;
  2264. line-height: 28px;
  2265. padding: 0 12px;
  2266. }
  2267. .button:hover,
  2268. .button:focus {
  2269. background: #fafafa;
  2270. border-color: #999;
  2271. color: #222;
  2272. }
  2273. .button:focus {
  2274. -webkit-box-shadow: 1px 1px 1px rgba(0,0,0,.2);
  2275. box-shadow: 1px 1px 1px rgba(0,0,0,.2);
  2276. }
  2277. .button:active {
  2278. background: #eee;
  2279. border-color: #999;
  2280. color: #333;
  2281. -webkit-box-shadow: inset 0 2px 5px -3px rgba( 0, 0, 0, 0.5 );
  2282. box-shadow: inset 0 2px 5px -3px rgba( 0, 0, 0, 0.5 );
  2283. }
  2284. <?php if ( 'rtl' == $text_direction ) : ?>
  2285. body { font-family: Tahoma, Arial; }
  2286. <?php endif; ?>
  2287. </style>
  2288. </head>
  2289. <body id="error-page">
  2290. <?php endif; // ! did_action( 'admin_head' ) ?>
  2291. <?php echo $message; ?>
  2292. </body>
  2293. </html>
  2294. <?php
  2295. die();
  2296. }
  2297. /**
  2298. * Kill WordPress execution and display XML message with error message.
  2299. *
  2300. * This is the handler for wp_die when processing XMLRPC requests.
  2301. *
  2302. * @since 3.2.0
  2303. * @access private
  2304. *
  2305. * @param string $message Error message.
  2306. * @param string $title Optional. Error title. Default empty.
  2307. * @param string|array $args Optional. Arguments to control behavior. Default empty array.
  2308. */
  2309. function _xmlrpc_wp_die_handler( $message, $title = '', $args = array() ) {
  2310. global $wp_xmlrpc_server;
  2311. $defaults = array( 'response' => 500 );
  2312. $r = wp_parse_args($args, $defaults);
  2313. if ( $wp_xmlrpc_server ) {
  2314. $error = new IXR_Error( $r['response'] , $message);
  2315. $wp_xmlrpc_server->output( $error->getXml() );
  2316. }
  2317. die();
  2318. }
  2319. /**
  2320. * Kill WordPress ajax execution.
  2321. *
  2322. * This is the handler for wp_die when processing Ajax requests.
  2323. *
  2324. * @since 3.4.0
  2325. * @access private
  2326. *
  2327. * @param string $message Optional. Response to print. Default empty.
  2328. */
  2329. function _ajax_wp_die_handler( $message = '' ) {
  2330. if ( is_scalar( $message ) )
  2331. die( (string) $message );
  2332. die( '0' );
  2333. }
  2334. /**
  2335. * Kill WordPress execution.
  2336. *
  2337. * This is the handler for wp_die when processing APP requests.
  2338. *
  2339. * @since 3.4.0
  2340. * @access private
  2341. *
  2342. * @param string $message Optional. Response to print. Default empty.
  2343. */
  2344. function _scalar_wp_die_handler( $message = '' ) {
  2345. if ( is_scalar( $message ) )
  2346. die( (string) $message );
  2347. die();
  2348. }
  2349. /**
  2350. * Send a JSON response back to an Ajax request.
  2351. *
  2352. * @since 3.5.0
  2353. *
  2354. * @param mixed $response Variable (usually an array or object) to encode as JSON,
  2355. * then print and die.
  2356. */
  2357. function wp_send_json( $response ) {
  2358. @header( 'Content-Type: application/json; charset=' . get_option( 'blog_charset' ) );
  2359. echo json_encode( $response );
  2360. if ( defined( 'DOING_AJAX' ) && DOING_AJAX )
  2361. wp_die();
  2362. else
  2363. die;
  2364. }
  2365. /**
  2366. * Send a JSON response back to an Ajax request, indicating success.
  2367. *
  2368. * @since 3.5.0
  2369. *
  2370. * @param mixed $data Data to encode as JSON, then print and die.
  2371. */
  2372. function wp_send_json_success( $data = null ) {
  2373. $response = array( 'success' => true );
  2374. if ( isset( $data ) )
  2375. $response['data'] = $data;
  2376. wp_send_json( $response );
  2377. }
  2378. /**
  2379. * Send a JSON response back to an Ajax request, indicating failure.
  2380. *
  2381. * @since 3.5.0
  2382. *
  2383. * @param mixed $data Data to encode as JSON, then print and die.
  2384. */
  2385. function wp_send_json_error( $data = null ) {
  2386. $response = array( 'success' => false );
  2387. if ( isset( $data ) )
  2388. $response['data'] = $data;
  2389. wp_send_json( $response );
  2390. }
  2391. /**
  2392. * Retrieve the WordPress home page URL.
  2393. *
  2394. * If the constant named 'WP_HOME' exists, then it will be used and returned
  2395. * by the function. This can be used to counter the redirection on your local
  2396. * development environment.
  2397. *
  2398. * @since 2.2.0
  2399. * @access private
  2400. *
  2401. * @see WP_HOME
  2402. *
  2403. * @param string $url URL for the home location.
  2404. * @return string Homepage location.
  2405. */
  2406. function _config_wp_home( $url = '' ) {
  2407. if ( defined( 'WP_HOME' ) )
  2408. return untrailingslashit( WP_HOME );
  2409. return $url;
  2410. }
  2411. /**
  2412. * Retrieve the WordPress site URL.
  2413. *
  2414. * If the constant named 'WP_SITEURL' is defined, then the value in that
  2415. * constant will always be returned. This can be used for debugging a site
  2416. * on your localhost while not having to change the database to your URL.
  2417. *
  2418. * @since 2.2.0
  2419. * @access private
  2420. *
  2421. * @see WP_SITEURL
  2422. *
  2423. * @param string $url URL to set the WordPress site location.
  2424. * @return string The WordPress Site URL.
  2425. */
  2426. function _config_wp_siteurl( $url = '' ) {
  2427. if ( defined( 'WP_SITEURL' ) )
  2428. return untrailingslashit( WP_SITEURL );
  2429. return $url;
  2430. }
  2431. /**
  2432. * Set the localized direction for MCE plugin.
  2433. *
  2434. * Will only set the direction to 'rtl', if the WordPress locale has
  2435. * the text direction set to 'rtl'.
  2436. *
  2437. * Fills in the 'directionality' setting, enables the 'directionality'
  2438. * plugin, and adds the 'ltr' button to 'toolbar1', formerly
  2439. * 'theme_advanced_buttons1' array keys. These keys are then returned
  2440. * in the $input (TinyMCE settings) array.
  2441. *
  2442. * @since 2.1.0
  2443. * @access private
  2444. *
  2445. * @param array $input MCE settings array.
  2446. * @return array Direction set for 'rtl', if needed by locale.
  2447. */
  2448. function _mce_set_direction( $input ) {
  2449. if ( is_rtl() ) {
  2450. $input['directionality'] = 'rtl';
  2451. $input['plugins'] .= ',directionality';
  2452. $input['toolbar1'] .= ',ltr';
  2453. }
  2454. return $input;
  2455. }
  2456. /**
  2457. * Convert smiley code to the icon graphic file equivalent.
  2458. *
  2459. * You can turn off smilies, by going to the write setting screen and unchecking
  2460. * the box, or by setting 'use_smilies' option to false or removing the option.
  2461. *
  2462. * Plugins may override the default smiley list by setting the $wpsmiliestrans
  2463. * to an array, with the key the code the blogger types in and the value the
  2464. * image file.
  2465. *
  2466. * The $wp_smiliessearch global is for the regular expression and is set each
  2467. * time the function is called.
  2468. *
  2469. * The full list of smilies can be found in the function and won't be listed in
  2470. * the description. Probably should create a Codex page for it, so that it is
  2471. * available.
  2472. *
  2473. * @global array $wpsmiliestrans
  2474. * @global array $wp_smiliessearch
  2475. *
  2476. * @since 2.2.0
  2477. */
  2478. function smilies_init() {
  2479. global $wpsmiliestrans, $wp_smiliessearch;
  2480. // don't bother setting up smilies if they are disabled
  2481. if ( !get_option( 'use_smilies' ) )
  2482. return;
  2483. if ( !isset( $wpsmiliestrans ) ) {
  2484. $wpsmiliestrans = array(
  2485. ':mrgreen:' => 'icon_mrgreen.gif',
  2486. ':neutral:' => 'icon_neutral.gif',
  2487. ':twisted:' => 'icon_twisted.gif',
  2488. ':arrow:' => 'icon_arrow.gif',
  2489. ':shock:' => 'icon_eek.gif',
  2490. ':smile:' => 'icon_smile.gif',
  2491. ':???:' => 'icon_confused.gif',
  2492. ':cool:' => 'icon_cool.gif',
  2493. ':evil:' => 'icon_evil.gif',
  2494. ':grin:' => 'icon_biggrin.gif',
  2495. ':idea:' => 'icon_idea.gif',
  2496. ':oops:' => 'icon_redface.gif',
  2497. ':razz:' => 'icon_razz.gif',
  2498. ':roll:' => 'icon_rolleyes.gif',
  2499. ':wink:' => 'icon_wink.gif',
  2500. ':cry:' => 'icon_cry.gif',
  2501. ':eek:' => 'icon_surprised.gif',
  2502. ':lol:' => 'icon_lol.gif',
  2503. ':mad:' => 'icon_mad.gif',
  2504. ':sad:' => 'icon_sad.gif',
  2505. '8-)' => 'icon_cool.gif',
  2506. '8-O' => 'icon_eek.gif',
  2507. ':-(' => 'icon_sad.gif',
  2508. ':-)' => 'icon_smile.gif',
  2509. ':-?' => 'icon_confused.gif',
  2510. ':-D' => 'icon_biggrin.gif',
  2511. ':-P' => 'icon_razz.gif',
  2512. ':-o' => 'icon_surprised.gif',
  2513. ':-x' => 'icon_mad.gif',
  2514. ':-|' => 'icon_neutral.gif',
  2515. ';-)' => 'icon_wink.gif',
  2516. // This one transformation breaks regular text with frequency.
  2517. // '8)' => 'icon_cool.gif',
  2518. '8O' => 'icon_eek.gif',
  2519. ':(' => 'icon_sad.gif',
  2520. ':)' => 'icon_smile.gif',
  2521. ':?' => 'icon_confused.gif',
  2522. ':D' => 'icon_biggrin.gif',
  2523. ':P' => 'icon_razz.gif',
  2524. ':o' => 'icon_surprised.gif',
  2525. ':x' => 'icon_mad.gif',
  2526. ':|' => 'icon_neutral.gif',
  2527. ';)' => 'icon_wink.gif',
  2528. ':!:' => 'icon_exclaim.gif',
  2529. ':?:' => 'icon_question.gif',
  2530. );
  2531. }
  2532. if (count($wpsmiliestrans) == 0) {
  2533. return;
  2534. }
  2535. /*
  2536. * NOTE: we sort the smilies in reverse key order. This is to make sure
  2537. * we match the longest possible smilie (:???: vs :?) as the regular
  2538. * expression used below is first-match
  2539. */
  2540. krsort($wpsmiliestrans);
  2541. $spaces = wp_spaces_regexp();
  2542. // Begin first "subpattern"
  2543. $wp_smiliessearch = '/(?<=' . $spaces . '|^)';
  2544. $subchar = '';
  2545. foreach ( (array) $wpsmiliestrans as $smiley => $img ) {
  2546. $firstchar = substr($smiley, 0, 1);
  2547. $rest = substr($smiley, 1);
  2548. // new subpattern?
  2549. if ($firstchar != $subchar) {
  2550. if ($subchar != '') {
  2551. $wp_smiliessearch .= ')(?=' . $spaces . '|$)'; // End previous "subpattern"
  2552. $wp_smiliessearch .= '|(?<=' . $spaces . '|^)'; // Begin another "subpattern"
  2553. }
  2554. $subchar = $firstchar;
  2555. $wp_smiliessearch .= preg_quote($firstchar, '/') . '(?:';
  2556. } else {
  2557. $wp_smiliessearch .= '|';
  2558. }
  2559. $wp_smiliessearch .= preg_quote($rest, '/');
  2560. }
  2561. $wp_smiliessearch .= ')(?=' . $spaces . '|$)/m';
  2562. }
  2563. /**
  2564. * Merge user defined arguments into defaults array.
  2565. *
  2566. * This function is used throughout WordPress to allow for both string or array
  2567. * to be merged into another array.
  2568. *
  2569. * @since 2.2.0
  2570. *
  2571. * @param string|array $args Value to merge with $defaults
  2572. * @param array $defaults Optional. Array that serves as the defaults. Default empty.
  2573. * @return array Merged user defined values with defaults.
  2574. */
  2575. function wp_parse_args( $args, $defaults = '' ) {
  2576. if ( is_object( $args ) )
  2577. $r = get_object_vars( $args );
  2578. elseif ( is_array( $args ) )
  2579. $r =& $args;
  2580. else
  2581. wp_parse_str( $args, $r );
  2582. if ( is_array( $defaults ) )
  2583. return array_merge( $defaults, $r );
  2584. return $r;
  2585. }
  2586. /**
  2587. * Clean up an array, comma- or space-separated list of IDs.
  2588. *
  2589. * @since 3.0.0
  2590. *
  2591. * @param array|string $list List of ids.
  2592. * @return array Sanitized array of IDs.
  2593. */
  2594. function wp_parse_id_list( $list ) {
  2595. if ( !is_array($list) )
  2596. $list = preg_split('/[\s,]+/', $list);
  2597. return array_unique(array_map('absint', $list));
  2598. }
  2599. /**
  2600. * Extract a slice of an array, given a list of keys.
  2601. *
  2602. * @since 3.1.0
  2603. *
  2604. * @param array $array The original array.
  2605. * @param array $keys The list of keys.
  2606. * @return array The array slice.
  2607. */
  2608. function wp_array_slice_assoc( $array, $keys ) {
  2609. $slice = array();
  2610. foreach ( $keys as $key )
  2611. if ( isset( $array[ $key ] ) )
  2612. $slice[ $key ] = $array[ $key ];
  2613. return $slice;
  2614. }
  2615. /**
  2616. * Filters a list of objects, based on a set of key => value arguments.
  2617. *
  2618. * @since 3.0.0
  2619. *
  2620. * @param array $list An array of objects to filter
  2621. * @param array $args Optional. An array of key => value arguments to match
  2622. * against each object. Default empty array.
  2623. * @param string $operator Optional. The logical operation to perform. 'or' means
  2624. * only one element from the array needs to match; 'and'
  2625. * means all elements must match. Default 'and'.
  2626. * @param bool|string $field A field from the object to place instead of the entire object.
  2627. * Default false.
  2628. * @return array A list of objects or object fields.
  2629. */
  2630. function wp_filter_object_list( $list, $args = array(), $operator = 'and', $field = false ) {
  2631. if ( ! is_array( $list ) )
  2632. return array();
  2633. $list = wp_list_filter( $list, $args, $operator );
  2634. if ( $field )
  2635. $list = wp_list_pluck( $list, $field );
  2636. return $list;
  2637. }
  2638. /**
  2639. * Filters a list of objects, based on a set of key => value arguments.
  2640. *
  2641. * @since 3.1.0
  2642. *
  2643. * @param array $list An array of objects to filter.
  2644. * @param array $args Optional. An array of key => value arguments to match
  2645. * against each object. Default empty array.
  2646. * @param string $operator Optional. The logical operation to perform. 'AND' means
  2647. * all elements from the array must match. 'OR' means only
  2648. * one element needs to match. 'NOT' means no elements may
  2649. * match. Default 'AND'.
  2650. * @return array Array of found values.
  2651. */
  2652. function wp_list_filter( $list, $args = array(), $operator = 'AND' ) {
  2653. if ( ! is_array( $list ) )
  2654. return array();
  2655. if ( empty( $args ) )
  2656. return $list;
  2657. $operator = strtoupper( $operator );
  2658. $count = count( $args );
  2659. $filtered = array();
  2660. foreach ( $list as $key => $obj ) {
  2661. $to_match = (array) $obj;
  2662. $matched = 0;
  2663. foreach ( $args as $m_key => $m_value ) {
  2664. if ( array_key_exists( $m_key, $to_match ) && $m_value == $to_match[ $m_key ] )
  2665. $matched++;
  2666. }
  2667. if ( ( 'AND' == $operator && $matched == $count )
  2668. || ( 'OR' == $operator && $matched > 0 )
  2669. || ( 'NOT' == $operator && 0 == $matched ) ) {
  2670. $filtered[$key] = $obj;
  2671. }
  2672. }
  2673. return $filtered;
  2674. }
  2675. /**
  2676. * Pluck a certain field out of each object in a list.
  2677. *
  2678. * This has the same functionality and prototype of
  2679. * array_column() (PHP 5.5) but also supports objects.
  2680. *
  2681. * @since 3.1.0
  2682. * @since 4.0.0 $index_key parameter added.
  2683. *
  2684. * @param array $list List of objects or arrays
  2685. * @param int|string $field Field from the object to place instead of the entire object
  2686. * @param int|string $index_key Optional. Field from the object to use as keys for the new array.
  2687. * Default null.
  2688. * @return array Array of found values. If $index_key is set, an array of found values with keys
  2689. * corresponding to $index_key.
  2690. */
  2691. function wp_list_pluck( $list, $field, $index_key = null ) {
  2692. if ( ! $index_key ) {
  2693. /*
  2694. * This is simple. Could at some point wrap array_column()
  2695. * if we knew we had an array of arrays.
  2696. */
  2697. foreach ( $list as $key => $value ) {
  2698. if ( is_object( $value ) ) {
  2699. $list[ $key ] = $value->$field;
  2700. } else {
  2701. $list[ $key ] = $value[ $field ];
  2702. }
  2703. }
  2704. return $list;
  2705. }
  2706. /*
  2707. * When index_key is not set for a particular item, push the value
  2708. * to the end of the stack. This is how array_column() behaves.
  2709. */
  2710. $newlist = array();
  2711. foreach ( $list as $value ) {
  2712. if ( is_object( $value ) ) {
  2713. if ( isset( $value->$index_key ) ) {
  2714. $newlist[ $value->$index_key ] = $value->$field;
  2715. } else {
  2716. $newlist[] = $value->$field;
  2717. }
  2718. } else {
  2719. if ( isset( $value[ $index_key ] ) ) {
  2720. $newlist[ $value[ $index_key ] ] = $value[ $field ];
  2721. } else {
  2722. $newlist[] = $value[ $field ];
  2723. }
  2724. }
  2725. }
  2726. return $newlist;
  2727. }
  2728. /**
  2729. * Determines if Widgets library should be loaded.
  2730. *
  2731. * Checks to make sure that the widgets library hasn't already been loaded.
  2732. * If it hasn't, then it will load the widgets library and run an action hook.
  2733. *
  2734. * @since 2.2.0
  2735. */
  2736. function wp_maybe_load_widgets() {
  2737. /**
  2738. * Filter whether to load the Widgets library.
  2739. *
  2740. * Passing a falsey value to the filter will effectively short-circuit
  2741. * the Widgets library from loading.
  2742. *
  2743. * @since 2.8.0
  2744. *
  2745. * @param bool $wp_maybe_load_widgets Whether to load the Widgets library.
  2746. * Default true.
  2747. */
  2748. if ( ! apply_filters( 'load_default_widgets', true ) ) {
  2749. return;
  2750. }
  2751. require_once( ABSPATH . WPINC . '/default-widgets.php' );
  2752. add_action( '_admin_menu', 'wp_widgets_add_menu' );
  2753. }
  2754. /**
  2755. * Append the Widgets menu to the themes main menu.
  2756. *
  2757. * @since 2.2.0
  2758. *
  2759. * @uses $submenu The administration submenu list.
  2760. */
  2761. function wp_widgets_add_menu() {
  2762. global $submenu;
  2763. if ( ! current_theme_supports( 'widgets' ) )
  2764. return;
  2765. $submenu['themes.php'][7] = array( __( 'Widgets' ), 'edit_theme_options', 'widgets.php' );
  2766. ksort( $submenu['themes.php'], SORT_NUMERIC );
  2767. }
  2768. /**
  2769. * Flush all output buffers for PHP 5.2.
  2770. *
  2771. * Make sure all output buffers are flushed before our singletons are destroyed.
  2772. *
  2773. * @since 2.2.0
  2774. */
  2775. function wp_ob_end_flush_all() {
  2776. $levels = ob_get_level();
  2777. for ($i=0; $i<$levels; $i++)
  2778. ob_end_flush();
  2779. }
  2780. /**
  2781. * Load custom DB error or display WordPress DB error.
  2782. *
  2783. * If a file exists in the wp-content directory named db-error.php, then it will
  2784. * be loaded instead of displaying the WordPress DB error. If it is not found,
  2785. * then the WordPress DB error will be displayed instead.
  2786. *
  2787. * The WordPress DB error sets the HTTP status header to 500 to try to prevent
  2788. * search engines from caching the message. Custom DB messages should do the
  2789. * same.
  2790. *
  2791. * This function was backported to WordPress 2.3.2, but originally was added
  2792. * in WordPress 2.5.0.
  2793. *
  2794. * @since 2.3.2
  2795. *
  2796. * @global wpdb $wpdb WordPress database access abstraction object.
  2797. */
  2798. function dead_db() {
  2799. global $wpdb;
  2800. wp_load_translations_early();
  2801. // Load custom DB error template, if present.
  2802. if ( file_exists( WP_CONTENT_DIR . '/db-error.php' ) ) {
  2803. require_once( WP_CONTENT_DIR . '/db-error.php' );
  2804. die();
  2805. }
  2806. // If installing or in the admin, provide the verbose message.
  2807. if ( defined('WP_INSTALLING') || defined('WP_ADMIN') )
  2808. wp_die($wpdb->error);
  2809. // Otherwise, be terse.
  2810. status_header( 500 );
  2811. nocache_headers();
  2812. header( 'Content-Type: text/html; charset=utf-8' );
  2813. ?>
  2814. <!DOCTYPE html>
  2815. <html xmlns="http://www.w3.org/1999/xhtml"<?php if ( is_rtl() ) echo ' dir="rtl"'; ?>>
  2816. <head>
  2817. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  2818. <title><?php _e( 'Database Error' ); ?></title>
  2819. </head>
  2820. <body>
  2821. <h1><?php _e( 'Error establishing a database connection' ); ?></h1>
  2822. </body>
  2823. </html>
  2824. <?php
  2825. die();
  2826. }
  2827. /**
  2828. * Convert a value to non-negative integer.
  2829. *
  2830. * @since 2.5.0
  2831. *
  2832. * @param mixed $maybeint Data you wish to have converted to a non-negative integer.
  2833. * @return int A non-negative integer.
  2834. */
  2835. function absint( $maybeint ) {
  2836. return abs( intval( $maybeint ) );
  2837. }
  2838. /**
  2839. * Mark a function as deprecated and inform when it has been used.
  2840. *
  2841. * There is a hook deprecated_function_run that will be called that can be used
  2842. * to get the backtrace up to what file and function called the deprecated
  2843. * function.
  2844. *
  2845. * The current behavior is to trigger a user error if WP_DEBUG is true.
  2846. *
  2847. * This function is to be used in every function that is deprecated.
  2848. *
  2849. * @since 2.5.0
  2850. * @access private
  2851. *
  2852. * @param string $function The function that was called.
  2853. * @param string $version The version of WordPress that deprecated the function.
  2854. * @param string $replacement Optional. The function that should have been called. Default null.
  2855. */
  2856. function _deprecated_function( $function, $version, $replacement = null ) {
  2857. /**
  2858. * Fires when a deprecated function is called.
  2859. *
  2860. * @since 2.5.0
  2861. *
  2862. * @param string $function The function that was called.
  2863. * @param string $replacement The function that should have been called.
  2864. * @param string $version The version of WordPress that deprecated the function.
  2865. */
  2866. do_action( 'deprecated_function_run', $function, $replacement, $version );
  2867. /**
  2868. * Filter whether to trigger an error for deprecated functions.
  2869. *
  2870. * @since 2.5.0
  2871. *
  2872. * @param bool $trigger Whether to trigger the error for deprecated functions. Default true.
  2873. */
  2874. if ( WP_DEBUG && apply_filters( 'deprecated_function_trigger_error', true ) ) {
  2875. if ( function_exists( '__' ) ) {
  2876. if ( ! is_null( $replacement ) )
  2877. trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.'), $function, $version, $replacement ) );
  2878. else
  2879. trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.'), $function, $version ) );
  2880. } else {
  2881. if ( ! is_null( $replacement ) )
  2882. trigger_error( sprintf( '%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.', $function, $version, $replacement ) );
  2883. else
  2884. trigger_error( sprintf( '%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.', $function, $version ) );
  2885. }
  2886. }
  2887. }
  2888. /**
  2889. * Mark a file as deprecated and inform when it has been used.
  2890. *
  2891. * There is a hook deprecated_file_included that will be called that can be used
  2892. * to get the backtrace up to what file and function included the deprecated
  2893. * file.
  2894. *
  2895. * The current behavior is to trigger a user error if WP_DEBUG is true.
  2896. *
  2897. * This function is to be used in every file that is deprecated.
  2898. *
  2899. * @since 2.5.0
  2900. * @access private
  2901. *
  2902. * @param string $file The file that was included.
  2903. * @param string $version The version of WordPress that deprecated the file.
  2904. * @param string $replacement Optional. The file that should have been included based on ABSPATH.
  2905. * Default null.
  2906. * @param string $message Optional. A message regarding the change. Default empty.
  2907. */
  2908. function _deprecated_file( $file, $version, $replacement = null, $message = '' ) {
  2909. /**
  2910. * Fires when a deprecated file is called.
  2911. *
  2912. * @since 2.5.0
  2913. *
  2914. * @param string $file The file that was called.
  2915. * @param string $replacement The file that should have been included based on ABSPATH.
  2916. * @param string $version The version of WordPress that deprecated the file.
  2917. * @param string $message A message regarding the change.
  2918. */
  2919. do_action( 'deprecated_file_included', $file, $replacement, $version, $message );
  2920. /**
  2921. * Filter whether to trigger an error for deprecated files.
  2922. *
  2923. * @since 2.5.0
  2924. *
  2925. * @param bool $trigger Whether to trigger the error for deprecated files. Default true.
  2926. */
  2927. if ( WP_DEBUG && apply_filters( 'deprecated_file_trigger_error', true ) ) {
  2928. $message = empty( $message ) ? '' : ' ' . $message;
  2929. if ( function_exists( '__' ) ) {
  2930. if ( ! is_null( $replacement ) )
  2931. trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.'), $file, $version, $replacement ) . $message );
  2932. else
  2933. trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.'), $file, $version ) . $message );
  2934. } else {
  2935. if ( ! is_null( $replacement ) )
  2936. trigger_error( sprintf( '%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.', $file, $version, $replacement ) . $message );
  2937. else
  2938. trigger_error( sprintf( '%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.', $file, $version ) . $message );
  2939. }
  2940. }
  2941. }
  2942. /**
  2943. * Mark a function argument as deprecated and inform when it has been used.
  2944. *
  2945. * This function is to be used whenever a deprecated function argument is used.
  2946. * Before this function is called, the argument must be checked for whether it was
  2947. * used by comparing it to its default value or evaluating whether it is empty.
  2948. * For example:
  2949. * <code>
  2950. * if ( ! empty( $deprecated ) ) {
  2951. * _deprecated_argument( __FUNCTION__, '3.0' );
  2952. * }
  2953. * </code>
  2954. *
  2955. * There is a hook deprecated_argument_run that will be called that can be used
  2956. * to get the backtrace up to what file and function used the deprecated
  2957. * argument.
  2958. *
  2959. * The current behavior is to trigger a user error if WP_DEBUG is true.
  2960. *
  2961. * @since 3.0.0
  2962. * @access private
  2963. *
  2964. * @param string $function The function that was called.
  2965. * @param string $version The version of WordPress that deprecated the argument used.
  2966. * @param string $message Optional. A message regarding the change. Default null.
  2967. */
  2968. function _deprecated_argument( $function, $version, $message = null ) {
  2969. /**
  2970. * Fires when a deprecated argument is called.
  2971. *
  2972. * @since 3.0.0
  2973. *
  2974. * @param string $function The function that was called.
  2975. * @param string $message A message regarding the change.
  2976. * @param string $version The version of WordPress that deprecated the argument used.
  2977. */
  2978. do_action( 'deprecated_argument_run', $function, $message, $version );
  2979. /**
  2980. * Filter whether to trigger an error for deprecated arguments.
  2981. *
  2982. * @since 3.0.0
  2983. *
  2984. * @param bool $trigger Whether to trigger the error for deprecated arguments. Default true.
  2985. */
  2986. if ( WP_DEBUG && apply_filters( 'deprecated_argument_trigger_error', true ) ) {
  2987. if ( function_exists( '__' ) ) {
  2988. if ( ! is_null( $message ) )
  2989. trigger_error( sprintf( __('%1$s was called with an argument that is <strong>deprecated</strong> since version %2$s! %3$s'), $function, $version, $message ) );
  2990. else
  2991. trigger_error( sprintf( __('%1$s was called with an argument that is <strong>deprecated</strong> since version %2$s with no alternative available.'), $function, $version ) );
  2992. } else {
  2993. if ( ! is_null( $message ) )
  2994. trigger_error( sprintf( '%1$s was called with an argument that is <strong>deprecated</strong> since version %2$s! %3$s', $function, $version, $message ) );
  2995. else
  2996. trigger_error( sprintf( '%1$s was called with an argument that is <strong>deprecated</strong> since version %2$s with no alternative available.', $function, $version ) );
  2997. }
  2998. }
  2999. }
  3000. /**
  3001. * Mark something as being incorrectly called.
  3002. *
  3003. * There is a hook doing_it_wrong_run that will be called that can be used
  3004. * to get the backtrace up to what file and function called the deprecated
  3005. * function.
  3006. *
  3007. * The current behavior is to trigger a user error if WP_DEBUG is true.
  3008. *
  3009. * @since 3.1.0
  3010. * @access private
  3011. *
  3012. * @param string $function The function that was called.
  3013. * @param string $message A message explaining what has been done incorrectly.
  3014. * @param string $version The version of WordPress where the message was added.
  3015. */
  3016. function _doing_it_wrong( $function, $message, $version ) {
  3017. /**
  3018. * Fires when the given function is being used incorrectly.
  3019. *
  3020. * @since 3.1.0
  3021. *
  3022. * @param string $function The function that was called.
  3023. * @param string $message A message explaining what has been done incorrectly.
  3024. * @param string $version The version of WordPress where the message was added.
  3025. */
  3026. do_action( 'doing_it_wrong_run', $function, $message, $version );
  3027. /**
  3028. * Filter whether to trigger an error for _doing_it_wrong() calls.
  3029. *
  3030. * @since 3.1.0
  3031. *
  3032. * @param bool $trigger Whether to trigger the error for _doing_it_wrong() calls. Default true.
  3033. */
  3034. if ( WP_DEBUG && apply_filters( 'doing_it_wrong_trigger_error', true ) ) {
  3035. if ( function_exists( '__' ) ) {
  3036. $version = is_null( $version ) ? '' : sprintf( __( '(This message was added in version %s.)' ), $version );
  3037. $message .= ' ' . __( 'Please see <a href="http://codex.wordpress.org/Debugging_in_WordPress">Debugging in WordPress</a> for more information.' );
  3038. trigger_error( sprintf( __( '%1$s was called <strong>incorrectly</strong>. %2$s %3$s' ), $function, $message, $version ) );
  3039. } else {
  3040. $version = is_null( $version ) ? '' : sprintf( '(This message was added in version %s.)', $version );
  3041. $message .= ' Please see <a href="http://codex.wordpress.org/Debugging_in_WordPress">Debugging in WordPress</a> for more information.';
  3042. trigger_error( sprintf( '%1$s was called <strong>incorrectly</strong>. %2$s %3$s', $function, $message, $version ) );
  3043. }
  3044. }
  3045. }
  3046. /**
  3047. * Is the server running earlier than 1.5.0 version of lighttpd?
  3048. *
  3049. * @since 2.5.0
  3050. *
  3051. * @return bool Whether the server is running lighttpd < 1.5.0.
  3052. */
  3053. function is_lighttpd_before_150() {
  3054. $server_parts = explode( '/', isset( $_SERVER['SERVER_SOFTWARE'] )? $_SERVER['SERVER_SOFTWARE'] : '' );
  3055. $server_parts[1] = isset( $server_parts[1] )? $server_parts[1] : '';
  3056. return 'lighttpd' == $server_parts[0] && -1 == version_compare( $server_parts[1], '1.5.0' );
  3057. }
  3058. /**
  3059. * Does the specified module exist in the Apache config?
  3060. *
  3061. * @since 2.5.0
  3062. *
  3063. * @param string $mod The module, e.g. mod_rewrite.
  3064. * @param bool $default Optional. The default return value if the module is not found. Default false.
  3065. * @return bool Whether the specified module is loaded.
  3066. */
  3067. function apache_mod_loaded($mod, $default = false) {
  3068. global $is_apache;
  3069. if ( !$is_apache )
  3070. return false;
  3071. if ( function_exists( 'apache_get_modules' ) ) {
  3072. $mods = apache_get_modules();
  3073. if ( in_array($mod, $mods) )
  3074. return true;
  3075. } elseif ( function_exists( 'phpinfo' ) && false === strpos( ini_get( 'disable_functions' ), 'phpinfo' ) ) {
  3076. ob_start();
  3077. phpinfo(8);
  3078. $phpinfo = ob_get_clean();
  3079. if ( false !== strpos($phpinfo, $mod) )
  3080. return true;
  3081. }
  3082. return $default;
  3083. }
  3084. /**
  3085. * Check if IIS 7+ supports pretty permalinks.
  3086. *
  3087. * @since 2.8.0
  3088. *
  3089. * @return bool Whether IIS7 supports permalinks.
  3090. */
  3091. function iis7_supports_permalinks() {
  3092. global $is_iis7;
  3093. $supports_permalinks = false;
  3094. if ( $is_iis7 ) {
  3095. /* First we check if the DOMDocument class exists. If it does not exist, then we cannot
  3096. * easily update the xml configuration file, hence we just bail out and tell user that
  3097. * pretty permalinks cannot be used.
  3098. *
  3099. * Next we check if the URL Rewrite Module 1.1 is loaded and enabled for the web site. When
  3100. * URL Rewrite 1.1 is loaded it always sets a server variable called 'IIS_UrlRewriteModule'.
  3101. * Lastly we make sure that PHP is running via FastCGI. This is important because if it runs
  3102. * via ISAPI then pretty permalinks will not work.
  3103. */
  3104. $supports_permalinks = class_exists('DOMDocument') && isset($_SERVER['IIS_UrlRewriteModule']) && ( php_sapi_name() == 'cgi-fcgi' );
  3105. }
  3106. /**
  3107. * Filter whether IIS 7+ supports pretty permalinks.
  3108. *
  3109. * @since 2.8.0
  3110. *
  3111. * @param bool $supports_permalinks Whether IIS7 supports permalinks. Default false.
  3112. */
  3113. return apply_filters( 'iis7_supports_permalinks', $supports_permalinks );
  3114. }
  3115. /**
  3116. * File validates against allowed set of defined rules.
  3117. *
  3118. * A return value of '1' means that the $file contains either '..' or './'. A
  3119. * return value of '2' means that the $file contains ':' after the first
  3120. * character. A return value of '3' means that the file is not in the allowed
  3121. * files list.
  3122. *
  3123. * @since 1.2.0
  3124. *
  3125. * @param string $file File path.
  3126. * @param array $allowed_files List of allowed files.
  3127. * @return int 0 means nothing is wrong, greater than 0 means something was wrong.
  3128. */
  3129. function validate_file( $file, $allowed_files = '' ) {
  3130. if ( false !== strpos( $file, '..' ) )
  3131. return 1;
  3132. if ( false !== strpos( $file, './' ) )
  3133. return 1;
  3134. if ( ! empty( $allowed_files ) && ! in_array( $file, $allowed_files ) )
  3135. return 3;
  3136. if (':' == substr( $file, 1, 1 ) )
  3137. return 2;
  3138. return 0;
  3139. }
  3140. /**
  3141. * Determine if SSL is used.
  3142. *
  3143. * @since 2.6.0
  3144. *
  3145. * @return bool True if SSL, false if not used.
  3146. */
  3147. function is_ssl() {
  3148. if ( isset($_SERVER['HTTPS']) ) {
  3149. if ( 'on' == strtolower($_SERVER['HTTPS']) )
  3150. return true;
  3151. if ( '1' == $_SERVER['HTTPS'] )
  3152. return true;
  3153. } elseif ( isset($_SERVER['SERVER_PORT']) && ( '443' == $_SERVER['SERVER_PORT'] ) ) {
  3154. return true;
  3155. }
  3156. return false;
  3157. }
  3158. /**
  3159. * Whether SSL login should be forced.
  3160. *
  3161. * @since 2.6.0
  3162. *
  3163. * @see force_ssl_admin()
  3164. *
  3165. * @param string|bool $force Optional Whether to force SSL login. Default null.
  3166. * @return bool True if forced, false if not forced.
  3167. */
  3168. function force_ssl_login( $force = null ) {
  3169. return force_ssl_admin( $force );
  3170. }
  3171. /**
  3172. * Whether to force SSL used for the Administration Screens.
  3173. *
  3174. * @since 2.6.0
  3175. *
  3176. * @param string|bool $force Optional. Whether to force SSL in admin screens. Default null.
  3177. * @return bool True if forced, false if not forced.
  3178. */
  3179. function force_ssl_admin( $force = null ) {
  3180. static $forced = false;
  3181. if ( !is_null( $force ) ) {
  3182. $old_forced = $forced;
  3183. $forced = $force;
  3184. return $old_forced;
  3185. }
  3186. return $forced;
  3187. }
  3188. /**
  3189. * Guess the URL for the site.
  3190. *
  3191. * Will remove wp-admin links to retrieve only return URLs not in the wp-admin
  3192. * directory.
  3193. *
  3194. * @since 2.6.0
  3195. *
  3196. * @return string The guessed URL.
  3197. */
  3198. function wp_guess_url() {
  3199. if ( defined('WP_SITEURL') && '' != WP_SITEURL ) {
  3200. $url = WP_SITEURL;
  3201. } else {
  3202. $abspath_fix = str_replace( '\\', '/', ABSPATH );
  3203. $script_filename_dir = dirname( $_SERVER['SCRIPT_FILENAME'] );
  3204. // The request is for the admin
  3205. if ( strpos( $_SERVER['REQUEST_URI'], 'wp-admin' ) !== false || strpos( $_SERVER['REQUEST_URI'], 'wp-login.php' ) !== false ) {
  3206. $path = preg_replace( '#/(wp-admin/.*|wp-login.php)#i', '', $_SERVER['REQUEST_URI'] );
  3207. // The request is for a file in ABSPATH
  3208. } elseif ( $script_filename_dir . '/' == $abspath_fix ) {
  3209. // Strip off any file/query params in the path
  3210. $path = preg_replace( '#/[^/]*$#i', '', $_SERVER['PHP_SELF'] );
  3211. } else {
  3212. if ( false !== strpos( $_SERVER['SCRIPT_FILENAME'], $abspath_fix ) ) {
  3213. // Request is hitting a file inside ABSPATH
  3214. $directory = str_replace( ABSPATH, '', $script_filename_dir );
  3215. // Strip off the sub directory, and any file/query paramss
  3216. $path = preg_replace( '#/' . preg_quote( $directory, '#' ) . '/[^/]*$#i', '' , $_SERVER['REQUEST_URI'] );
  3217. } elseif ( false !== strpos( $abspath_fix, $script_filename_dir ) ) {
  3218. // Request is hitting a file above ABSPATH
  3219. $subdirectory = substr( $abspath_fix, strpos( $abspath_fix, $script_filename_dir ) + strlen( $script_filename_dir ) );
  3220. // Strip off any file/query params from the path, appending the sub directory to the install
  3221. $path = preg_replace( '#/[^/]*$#i', '' , $_SERVER['REQUEST_URI'] ) . $subdirectory;
  3222. } else {
  3223. $path = $_SERVER['REQUEST_URI'];
  3224. }
  3225. }
  3226. $schema = is_ssl() ? 'https://' : 'http://'; // set_url_scheme() is not defined yet
  3227. $url = $schema . $_SERVER['HTTP_HOST'] . $path;
  3228. }
  3229. return rtrim($url, '/');
  3230. }
  3231. /**
  3232. * Temporarily suspend cache additions.
  3233. *
  3234. * Stops more data being added to the cache, but still allows cache retrieval.
  3235. * This is useful for actions, such as imports, when a lot of data would otherwise
  3236. * be almost uselessly added to the cache.
  3237. *
  3238. * Suspension lasts for a single page load at most. Remember to call this
  3239. * function again if you wish to re-enable cache adds earlier.
  3240. *
  3241. * @since 3.3.0
  3242. *
  3243. * @param bool $suspend Optional. Suspends additions if true, re-enables them if false.
  3244. * @return bool The current suspend setting
  3245. */
  3246. function wp_suspend_cache_addition( $suspend = null ) {
  3247. static $_suspend = false;
  3248. if ( is_bool( $suspend ) )
  3249. $_suspend = $suspend;
  3250. return $_suspend;
  3251. }
  3252. /**
  3253. * Suspend cache invalidation.
  3254. *
  3255. * Turns cache invalidation on and off. Useful during imports where you don't wont to do
  3256. * invalidations every time a post is inserted. Callers must be sure that what they are
  3257. * doing won't lead to an inconsistent cache when invalidation is suspended.
  3258. *
  3259. * @since 2.7.0
  3260. *
  3261. * @param bool $suspend Optional. Whether to suspend or enable cache invalidation. Default true.
  3262. * @return bool The current suspend setting.
  3263. */
  3264. function wp_suspend_cache_invalidation( $suspend = true ) {
  3265. global $_wp_suspend_cache_invalidation;
  3266. $current_suspend = $_wp_suspend_cache_invalidation;
  3267. $_wp_suspend_cache_invalidation = $suspend;
  3268. return $current_suspend;
  3269. }
  3270. /**
  3271. * Determine whether a site is the main site of the current network.
  3272. *
  3273. * @since 3.0.0
  3274. *
  3275. * @param int $site_id Optional. Site ID to test. Defaults to current site.
  3276. * Defaults to current site.
  3277. * @return bool True if $site_id is the main site of the network, or if not
  3278. * running Multisite.
  3279. */
  3280. function is_main_site( $site_id = null ) {
  3281. // This is the current network's information; 'site' is old terminology.
  3282. global $current_site;
  3283. if ( ! is_multisite() )
  3284. return true;
  3285. if ( ! $site_id )
  3286. $site_id = get_current_blog_id();
  3287. return (int) $site_id === (int) $current_site->blog_id;
  3288. }
  3289. /**
  3290. * Determine whether a network is the main network of the Multisite install.
  3291. *
  3292. * @since 3.7.0
  3293. *
  3294. * @param int $network_id Optional. Network ID to test. Defaults to current network.
  3295. * @return bool True if $network_id is the main network, or if not running Multisite.
  3296. */
  3297. function is_main_network( $network_id = null ) {
  3298. global $wpdb;
  3299. if ( ! is_multisite() )
  3300. return true;
  3301. $current_network_id = (int) get_current_site()->id;
  3302. if ( ! $network_id )
  3303. $network_id = $current_network_id;
  3304. $network_id = (int) $network_id;
  3305. if ( defined( 'PRIMARY_NETWORK_ID' ) )
  3306. return $network_id === (int) PRIMARY_NETWORK_ID;
  3307. if ( 1 === $current_network_id )
  3308. return $network_id === $current_network_id;
  3309. $primary_network_id = (int) wp_cache_get( 'primary_network_id', 'site-options' );
  3310. if ( $primary_network_id )
  3311. return $network_id === $primary_network_id;
  3312. $primary_network_id = (int) $wpdb->get_var( "SELECT id FROM $wpdb->site ORDER BY id LIMIT 1" );
  3313. wp_cache_add( 'primary_network_id', $primary_network_id, 'site-options' );
  3314. return $network_id === $primary_network_id;
  3315. }
  3316. /**
  3317. * Determine whether global terms are enabled.
  3318. *
  3319. * @since 3.0.0
  3320. *
  3321. * @return bool True if multisite and global terms enabled.
  3322. */
  3323. function global_terms_enabled() {
  3324. if ( ! is_multisite() )
  3325. return false;
  3326. static $global_terms = null;
  3327. if ( is_null( $global_terms ) ) {
  3328. /**
  3329. * Filter whether global terms are enabled.
  3330. *
  3331. * Passing a non-null value to the filter will effectively short-circuit the function,
  3332. * returning the value of the 'global_terms_enabled' site option instead.
  3333. *
  3334. * @since 3.0.0
  3335. *
  3336. * @param null $anbled Whether global terms are enabled.
  3337. */
  3338. $filter = apply_filters( 'global_terms_enabled', null );
  3339. if ( ! is_null( $filter ) )
  3340. $global_terms = (bool) $filter;
  3341. else
  3342. $global_terms = (bool) get_site_option( 'global_terms_enabled', false );
  3343. }
  3344. return $global_terms;
  3345. }
  3346. /**
  3347. * gmt_offset modification for smart timezone handling.
  3348. *
  3349. * Overrides the gmt_offset option if we have a timezone_string available.
  3350. *
  3351. * @since 2.8.0
  3352. *
  3353. * @return float|bool Timezone GMT offset, false otherwise.
  3354. */
  3355. function wp_timezone_override_offset() {
  3356. if ( !$timezone_string = get_option( 'timezone_string' ) ) {
  3357. return false;
  3358. }
  3359. $timezone_object = timezone_open( $timezone_string );
  3360. $datetime_object = date_create();
  3361. if ( false === $timezone_object || false === $datetime_object ) {
  3362. return false;
  3363. }
  3364. return round( timezone_offset_get( $timezone_object, $datetime_object ) / HOUR_IN_SECONDS, 2 );
  3365. }
  3366. /**
  3367. * Sort-helper for timezones.
  3368. *
  3369. * @since 2.9.0
  3370. * @access private
  3371. *
  3372. * @param array $a
  3373. * @param array $b
  3374. * @return int
  3375. */
  3376. function _wp_timezone_choice_usort_callback( $a, $b ) {
  3377. // Don't use translated versions of Etc
  3378. if ( 'Etc' === $a['continent'] && 'Etc' === $b['continent'] ) {
  3379. // Make the order of these more like the old dropdown
  3380. if ( 'GMT+' === substr( $a['city'], 0, 4 ) && 'GMT+' === substr( $b['city'], 0, 4 ) ) {
  3381. return -1 * ( strnatcasecmp( $a['city'], $b['city'] ) );
  3382. }
  3383. if ( 'UTC' === $a['city'] ) {
  3384. if ( 'GMT+' === substr( $b['city'], 0, 4 ) ) {
  3385. return 1;
  3386. }
  3387. return -1;
  3388. }
  3389. if ( 'UTC' === $b['city'] ) {
  3390. if ( 'GMT+' === substr( $a['city'], 0, 4 ) ) {
  3391. return -1;
  3392. }
  3393. return 1;
  3394. }
  3395. return strnatcasecmp( $a['city'], $b['city'] );
  3396. }
  3397. if ( $a['t_continent'] == $b['t_continent'] ) {
  3398. if ( $a['t_city'] == $b['t_city'] ) {
  3399. return strnatcasecmp( $a['t_subcity'], $b['t_subcity'] );
  3400. }
  3401. return strnatcasecmp( $a['t_city'], $b['t_city'] );
  3402. } else {
  3403. // Force Etc to the bottom of the list
  3404. if ( 'Etc' === $a['continent'] ) {
  3405. return 1;
  3406. }
  3407. if ( 'Etc' === $b['continent'] ) {
  3408. return -1;
  3409. }
  3410. return strnatcasecmp( $a['t_continent'], $b['t_continent'] );
  3411. }
  3412. }
  3413. /**
  3414. * Gives a nicely-formatted list of timezone strings.
  3415. *
  3416. * @since 2.9.0
  3417. *
  3418. * @param string $selected_zone Selected timezone.
  3419. * @return string
  3420. */
  3421. function wp_timezone_choice( $selected_zone ) {
  3422. static $mo_loaded = false;
  3423. $continents = array( 'Africa', 'America', 'Antarctica', 'Arctic', 'Asia', 'Atlantic', 'Australia', 'Europe', 'Indian', 'Pacific');
  3424. // Load translations for continents and cities
  3425. if ( !$mo_loaded ) {
  3426. $locale = get_locale();
  3427. $mofile = WP_LANG_DIR . '/continents-cities-' . $locale . '.mo';
  3428. load_textdomain( 'continents-cities', $mofile );
  3429. $mo_loaded = true;
  3430. }
  3431. $zonen = array();
  3432. foreach ( timezone_identifiers_list() as $zone ) {
  3433. $zone = explode( '/', $zone );
  3434. if ( !in_array( $zone[0], $continents ) ) {
  3435. continue;
  3436. }
  3437. // This determines what gets set and translated - we don't translate Etc/* strings here, they are done later
  3438. $exists = array(
  3439. 0 => ( isset( $zone[0] ) && $zone[0] ),
  3440. 1 => ( isset( $zone[1] ) && $zone[1] ),
  3441. 2 => ( isset( $zone[2] ) && $zone[2] ),
  3442. );
  3443. $exists[3] = ( $exists[0] && 'Etc' !== $zone[0] );
  3444. $exists[4] = ( $exists[1] && $exists[3] );
  3445. $exists[5] = ( $exists[2] && $exists[3] );
  3446. $zonen[] = array(
  3447. 'continent' => ( $exists[0] ? $zone[0] : '' ),
  3448. 'city' => ( $exists[1] ? $zone[1] : '' ),
  3449. 'subcity' => ( $exists[2] ? $zone[2] : '' ),
  3450. 't_continent' => ( $exists[3] ? translate( str_replace( '_', ' ', $zone[0] ), 'continents-cities' ) : '' ),
  3451. 't_city' => ( $exists[4] ? translate( str_replace( '_', ' ', $zone[1] ), 'continents-cities' ) : '' ),
  3452. 't_subcity' => ( $exists[5] ? translate( str_replace( '_', ' ', $zone[2] ), 'continents-cities' ) : '' )
  3453. );
  3454. }
  3455. usort( $zonen, '_wp_timezone_choice_usort_callback' );
  3456. $structure = array();
  3457. if ( empty( $selected_zone ) ) {
  3458. $structure[] = '<option selected="selected" value="">' . __( 'Select a city' ) . '</option>';
  3459. }
  3460. foreach ( $zonen as $key => $zone ) {
  3461. // Build value in an array to join later
  3462. $value = array( $zone['continent'] );
  3463. if ( empty( $zone['city'] ) ) {
  3464. // It's at the continent level (generally won't happen)
  3465. $display = $zone['t_continent'];
  3466. } else {
  3467. // It's inside a continent group
  3468. // Continent optgroup
  3469. if ( !isset( $zonen[$key - 1] ) || $zonen[$key - 1]['continent'] !== $zone['continent'] ) {
  3470. $label = $zone['t_continent'];
  3471. $structure[] = '<optgroup label="'. esc_attr( $label ) .'">';
  3472. }
  3473. // Add the city to the value
  3474. $value[] = $zone['city'];
  3475. $display = $zone['t_city'];
  3476. if ( !empty( $zone['subcity'] ) ) {
  3477. // Add the subcity to the value
  3478. $value[] = $zone['subcity'];
  3479. $display .= ' - ' . $zone['t_subcity'];
  3480. }
  3481. }
  3482. // Build the value
  3483. $value = join( '/', $value );
  3484. $selected = '';
  3485. if ( $value === $selected_zone ) {
  3486. $selected = 'selected="selected" ';
  3487. }
  3488. $structure[] = '<option ' . $selected . 'value="' . esc_attr( $value ) . '">' . esc_html( $display ) . "</option>";
  3489. // Close continent optgroup
  3490. if ( !empty( $zone['city'] ) && ( !isset($zonen[$key + 1]) || (isset( $zonen[$key + 1] ) && $zonen[$key + 1]['continent'] !== $zone['continent']) ) ) {
  3491. $structure[] = '</optgroup>';
  3492. }
  3493. }
  3494. // Do UTC
  3495. $structure[] = '<optgroup label="'. esc_attr__( 'UTC' ) .'">';
  3496. $selected = '';
  3497. if ( 'UTC' === $selected_zone )
  3498. $selected = 'selected="selected" ';
  3499. $structure[] = '<option ' . $selected . 'value="' . esc_attr( 'UTC' ) . '">' . __('UTC') . '</option>';
  3500. $structure[] = '</optgroup>';
  3501. // Do manual UTC offsets
  3502. $structure[] = '<optgroup label="'. esc_attr__( 'Manual Offsets' ) .'">';
  3503. $offset_range = array (-12, -11.5, -11, -10.5, -10, -9.5, -9, -8.5, -8, -7.5, -7, -6.5, -6, -5.5, -5, -4.5, -4, -3.5, -3, -2.5, -2, -1.5, -1, -0.5,
  3504. 0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 5.75, 6, 6.5, 7, 7.5, 8, 8.5, 8.75, 9, 9.5, 10, 10.5, 11, 11.5, 12, 12.75, 13, 13.75, 14);
  3505. foreach ( $offset_range as $offset ) {
  3506. if ( 0 <= $offset )
  3507. $offset_name = '+' . $offset;
  3508. else
  3509. $offset_name = (string) $offset;
  3510. $offset_value = $offset_name;
  3511. $offset_name = str_replace(array('.25','.5','.75'), array(':15',':30',':45'), $offset_name);
  3512. $offset_name = 'UTC' . $offset_name;
  3513. $offset_value = 'UTC' . $offset_value;
  3514. $selected = '';
  3515. if ( $offset_value === $selected_zone )
  3516. $selected = 'selected="selected" ';
  3517. $structure[] = '<option ' . $selected . 'value="' . esc_attr( $offset_value ) . '">' . esc_html( $offset_name ) . "</option>";
  3518. }
  3519. $structure[] = '</optgroup>';
  3520. return join( "\n", $structure );
  3521. }
  3522. /**
  3523. * Strip close comment and close php tags from file headers used by WP.
  3524. *
  3525. * @since 2.8.0
  3526. * @access private
  3527. *
  3528. * @see http://core.trac.wordpress.org/ticket/8497
  3529. *
  3530. * @param string $str Header comment to clean up.
  3531. * @return string
  3532. */
  3533. function _cleanup_header_comment( $str ) {
  3534. return trim(preg_replace("/\s*(?:\*\/|\?>).*/", '', $str));
  3535. }
  3536. /**
  3537. * Permanently delete posts, pages, attachments, and comments which have been
  3538. * in the trash for EMPTY_TRASH_DAYS.
  3539. *
  3540. * @since 2.9.0
  3541. */
  3542. function wp_scheduled_delete() {
  3543. global $wpdb;
  3544. $delete_timestamp = time() - ( DAY_IN_SECONDS * EMPTY_TRASH_DAYS );
  3545. $posts_to_delete = $wpdb->get_results($wpdb->prepare("SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_wp_trash_meta_time' AND meta_value < '%d'", $delete_timestamp), ARRAY_A);
  3546. foreach ( (array) $posts_to_delete as $post ) {
  3547. $post_id = (int) $post['post_id'];
  3548. if ( !$post_id )
  3549. continue;
  3550. $del_post = get_post($post_id);
  3551. if ( !$del_post || 'trash' != $del_post->post_status ) {
  3552. delete_post_meta($post_id, '_wp_trash_meta_status');
  3553. delete_post_meta($post_id, '_wp_trash_meta_time');
  3554. } else {
  3555. wp_delete_post($post_id);
  3556. }
  3557. }
  3558. $comments_to_delete = $wpdb->get_results($wpdb->prepare("SELECT comment_id FROM $wpdb->commentmeta WHERE meta_key = '_wp_trash_meta_time' AND meta_value < '%d'", $delete_timestamp), ARRAY_A);
  3559. foreach ( (array) $comments_to_delete as $comment ) {
  3560. $comment_id = (int) $comment['comment_id'];
  3561. if ( !$comment_id )
  3562. continue;
  3563. $del_comment = get_comment($comment_id);
  3564. if ( !$del_comment || 'trash' != $del_comment->comment_approved ) {
  3565. delete_comment_meta($comment_id, '_wp_trash_meta_time');
  3566. delete_comment_meta($comment_id, '_wp_trash_meta_status');
  3567. } else {
  3568. wp_delete_comment($comment_id);
  3569. }
  3570. }
  3571. }
  3572. /**
  3573. * Retrieve metadata from a file.
  3574. *
  3575. * Searches for metadata in the first 8kiB of a file, such as a plugin or theme.
  3576. * Each piece of metadata must be on its own line. Fields can not span multiple
  3577. * lines, the value will get cut at the end of the first line.
  3578. *
  3579. * If the file data is not within that first 8kiB, then the author should correct
  3580. * their plugin file and move the data headers to the top.
  3581. *
  3582. * @see http://codex.wordpress.org/File_Header
  3583. *
  3584. * @since 2.9.0
  3585. * @param string $file Path to the file.
  3586. * @param array $default_headers List of headers, in the format array('HeaderKey' => 'Header Name').
  3587. * @param string $context Optional. If specified adds filter hook "extra_{$context}_headers".
  3588. * Default empty.
  3589. */
  3590. function get_file_data( $file, $default_headers, $context = '' ) {
  3591. // We don't need to write to the file, so just open for reading.
  3592. $fp = fopen( $file, 'r' );
  3593. // Pull only the first 8kiB of the file in.
  3594. $file_data = fread( $fp, 8192 );
  3595. // PHP will close file handle, but we are good citizens.
  3596. fclose( $fp );
  3597. // Make sure we catch CR-only line endings.
  3598. $file_data = str_replace( "\r", "\n", $file_data );
  3599. /**
  3600. * Filter extra file headers by context.
  3601. *
  3602. * The dynamic portion of the hook name, $context, refers to the context
  3603. * where extra headers might be loaded.
  3604. *
  3605. * @since 2.9.0
  3606. *
  3607. * @param array $extra_context_headers Empty array by default.
  3608. */
  3609. if ( $context && $extra_headers = apply_filters( "extra_{$context}_headers", array() ) ) {
  3610. $extra_headers = array_combine( $extra_headers, $extra_headers ); // keys equal values
  3611. $all_headers = array_merge( $extra_headers, (array) $default_headers );
  3612. } else {
  3613. $all_headers = $default_headers;
  3614. }
  3615. foreach ( $all_headers as $field => $regex ) {
  3616. if ( preg_match( '/^[ \t\/*#@]*' . preg_quote( $regex, '/' ) . ':(.*)$/mi', $file_data, $match ) && $match[1] )
  3617. $all_headers[ $field ] = _cleanup_header_comment( $match[1] );
  3618. else
  3619. $all_headers[ $field ] = '';
  3620. }
  3621. return $all_headers;
  3622. }
  3623. /**
  3624. * Returns true.
  3625. *
  3626. * Useful for returning true to filters easily.
  3627. *
  3628. * @since 3.0.0
  3629. *
  3630. * @see __return_false()
  3631. *
  3632. * @return bool True.
  3633. */
  3634. function __return_true() {
  3635. return true;
  3636. }
  3637. /**
  3638. * Returns false.
  3639. *
  3640. * Useful for returning false to filters easily.
  3641. *
  3642. * @since 3.0.0
  3643. *
  3644. * @see __return_true()
  3645. *
  3646. * @return bool False.
  3647. */
  3648. function __return_false() {
  3649. return false;
  3650. }
  3651. /**
  3652. * Returns 0.
  3653. *
  3654. * Useful for returning 0 to filters easily.
  3655. *
  3656. * @since 3.0.0
  3657. *
  3658. * @return int 0.
  3659. */
  3660. function __return_zero() {
  3661. return 0;
  3662. }
  3663. /**
  3664. * Returns an empty array.
  3665. *
  3666. * Useful for returning an empty array to filters easily.
  3667. *
  3668. * @since 3.0.0
  3669. *
  3670. * @return array Empty array.
  3671. */
  3672. function __return_empty_array() {
  3673. return array();
  3674. }
  3675. /**
  3676. * Returns null.
  3677. *
  3678. * Useful for returning null to filters easily.
  3679. *
  3680. * @since 3.4.0
  3681. *
  3682. * @return null Null value.
  3683. */
  3684. function __return_null() {
  3685. return null;
  3686. }
  3687. /**
  3688. * Returns an empty string.
  3689. *
  3690. * Useful for returning an empty string to filters easily.
  3691. *
  3692. * @since 3.7.0
  3693. *
  3694. * @see __return_null()
  3695. *
  3696. * @return string Empty string.
  3697. */
  3698. function __return_empty_string() {
  3699. return '';
  3700. }
  3701. /**
  3702. * Send a HTTP header to disable content type sniffing in browsers which support it.
  3703. *
  3704. * @since 3.0.0
  3705. *
  3706. * @see http://blogs.msdn.com/ie/archive/2008/07/02/ie8-security-part-v-comprehensive-protection.aspx
  3707. * @see http://src.chromium.org/viewvc/chrome?view=rev&revision=6985
  3708. */
  3709. function send_nosniff_header() {
  3710. @header( 'X-Content-Type-Options: nosniff' );
  3711. }
  3712. /**
  3713. * Return a MySQL expression for selecting the week number based on the start_of_week option.
  3714. *
  3715. * @internal
  3716. * @since 3.0.0
  3717. *
  3718. * @param string $column Database column.
  3719. * @return string SQL clause.
  3720. */
  3721. function _wp_mysql_week( $column ) {
  3722. switch ( $start_of_week = (int) get_option( 'start_of_week' ) ) {
  3723. case 1 :
  3724. return "WEEK( $column, 1 )";
  3725. case 2 :
  3726. case 3 :
  3727. case 4 :
  3728. case 5 :
  3729. case 6 :
  3730. return "WEEK( DATE_SUB( $column, INTERVAL $start_of_week DAY ), 0 )";
  3731. case 0 :
  3732. default :
  3733. return "WEEK( $column, 0 )";
  3734. }
  3735. }
  3736. /**
  3737. * Find hierarchy loops using a callback function that maps object IDs to parent IDs.
  3738. *
  3739. * @since 3.1.0
  3740. * @access private
  3741. *
  3742. * @param callback $callback Function that accepts ( ID, $callback_args ) and outputs parent_ID.
  3743. * @param int $start The ID to start the loop check at.
  3744. * @param int $start_parent The parent_ID of $start to use instead of calling $callback( $start ).
  3745. * Use null to always use $callback
  3746. * @param array $callback_args Optional. Additional arguments to send to $callback.
  3747. * @return array IDs of all members of loop.
  3748. */
  3749. function wp_find_hierarchy_loop( $callback, $start, $start_parent, $callback_args = array() ) {
  3750. $override = is_null( $start_parent ) ? array() : array( $start => $start_parent );
  3751. if ( !$arbitrary_loop_member = wp_find_hierarchy_loop_tortoise_hare( $callback, $start, $override, $callback_args ) )
  3752. return array();
  3753. return wp_find_hierarchy_loop_tortoise_hare( $callback, $arbitrary_loop_member, $override, $callback_args, true );
  3754. }
  3755. /**
  3756. * Use the "The Tortoise and the Hare" algorithm to detect loops.
  3757. *
  3758. * For every step of the algorithm, the hare takes two steps and the tortoise one.
  3759. * If the hare ever laps the tortoise, there must be a loop.
  3760. *
  3761. * @since 3.1.0
  3762. * @access private
  3763. *
  3764. * @param callback $callback Function that accepts ( ID, callback_arg, ... ) and outputs parent_ID.
  3765. * @param int $start The ID to start the loop check at.
  3766. * @param array $override Optional. An array of ( ID => parent_ID, ... ) to use instead of $callback.
  3767. * Default empty array.
  3768. * @param array $callback_args Optional. Additional arguments to send to $callback. Default empty array.
  3769. * @param bool $_return_loop Optional. Return loop members or just detect presence of loop? Only set
  3770. * to true if you already know the given $start is part of a loop (otherwise
  3771. * the returned array might include branches). Default false.
  3772. * @return mixed Scalar ID of some arbitrary member of the loop, or array of IDs of all members of loop if
  3773. * $_return_loop
  3774. */
  3775. function wp_find_hierarchy_loop_tortoise_hare( $callback, $start, $override = array(), $callback_args = array(), $_return_loop = false ) {
  3776. $tortoise = $hare = $evanescent_hare = $start;
  3777. $return = array();
  3778. // Set evanescent_hare to one past hare
  3779. // Increment hare two steps
  3780. while (
  3781. $tortoise
  3782. &&
  3783. ( $evanescent_hare = isset( $override[$hare] ) ? $override[$hare] : call_user_func_array( $callback, array_merge( array( $hare ), $callback_args ) ) )
  3784. &&
  3785. ( $hare = isset( $override[$evanescent_hare] ) ? $override[$evanescent_hare] : call_user_func_array( $callback, array_merge( array( $evanescent_hare ), $callback_args ) ) )
  3786. ) {
  3787. if ( $_return_loop )
  3788. $return[$tortoise] = $return[$evanescent_hare] = $return[$hare] = true;
  3789. // tortoise got lapped - must be a loop
  3790. if ( $tortoise == $evanescent_hare || $tortoise == $hare )
  3791. return $_return_loop ? $return : $tortoise;
  3792. // Increment tortoise by one step
  3793. $tortoise = isset( $override[$tortoise] ) ? $override[$tortoise] : call_user_func_array( $callback, array_merge( array( $tortoise ), $callback_args ) );
  3794. }
  3795. return false;
  3796. }
  3797. /**
  3798. * Send a HTTP header to limit rendering of pages to same origin iframes.
  3799. *
  3800. * @since 3.1.3
  3801. *
  3802. * @see https://developer.mozilla.org/en/the_x-frame-options_response_header
  3803. */
  3804. function send_frame_options_header() {
  3805. @header( 'X-Frame-Options: SAMEORIGIN' );
  3806. }
  3807. /**
  3808. * Retrieve a list of protocols to allow in HTML attributes.
  3809. *
  3810. * @since 3.3.0
  3811. *
  3812. * @see wp_kses()
  3813. * @see esc_url()
  3814. *
  3815. * @return array Array of allowed protocols.
  3816. */
  3817. function wp_allowed_protocols() {
  3818. static $protocols;
  3819. if ( empty( $protocols ) ) {
  3820. $protocols = array( 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet', 'mms', 'rtsp', 'svn', 'tel', 'fax', 'xmpp' );
  3821. /**
  3822. * Filter the list of protocols allowed in HTML attributes.
  3823. *
  3824. * @since 3.0.0
  3825. *
  3826. * @param array $protocols Array of allowed protocols e.g. 'http', 'ftp', 'tel', and more.
  3827. */
  3828. $protocols = apply_filters( 'kses_allowed_protocols', $protocols );
  3829. }
  3830. return $protocols;
  3831. }
  3832. /**
  3833. * Return a comma-separated string of functions that have been called to get
  3834. * to the current point in code.
  3835. *
  3836. * @since 3.4.0
  3837. *
  3838. * @see http://core.trac.wordpress.org/ticket/19589
  3839. *
  3840. * @param string $ignore_class Optional. A class to ignore all function calls within - useful
  3841. * when you want to just give info about the callee. Default null.
  3842. * @param int $skip_frames Optional. A number of stack frames to skip - useful for unwinding
  3843. * back to the source of the issue. Default 0.
  3844. * @param bool $pretty Optional. Whether or not you want a comma separated string or raw
  3845. * array returned. Default true.
  3846. * @return string|array Either a string containing a reversed comma separated trace or an array
  3847. * of individual calls.
  3848. */
  3849. function wp_debug_backtrace_summary( $ignore_class = null, $skip_frames = 0, $pretty = true ) {
  3850. if ( version_compare( PHP_VERSION, '5.2.5', '>=' ) )
  3851. $trace = debug_backtrace( false );
  3852. else
  3853. $trace = debug_backtrace();
  3854. $caller = array();
  3855. $check_class = ! is_null( $ignore_class );
  3856. $skip_frames++; // skip this function
  3857. foreach ( $trace as $call ) {
  3858. if ( $skip_frames > 0 ) {
  3859. $skip_frames--;
  3860. } elseif ( isset( $call['class'] ) ) {
  3861. if ( $check_class && $ignore_class == $call['class'] )
  3862. continue; // Filter out calls
  3863. $caller[] = "{$call['class']}{$call['type']}{$call['function']}";
  3864. } else {
  3865. if ( in_array( $call['function'], array( 'do_action', 'apply_filters' ) ) ) {
  3866. $caller[] = "{$call['function']}('{$call['args'][0]}')";
  3867. } elseif ( in_array( $call['function'], array( 'include', 'include_once', 'require', 'require_once' ) ) ) {
  3868. $caller[] = $call['function'] . "('" . str_replace( array( WP_CONTENT_DIR, ABSPATH ) , '', $call['args'][0] ) . "')";
  3869. } else {
  3870. $caller[] = $call['function'];
  3871. }
  3872. }
  3873. }
  3874. if ( $pretty )
  3875. return join( ', ', array_reverse( $caller ) );
  3876. else
  3877. return $caller;
  3878. }
  3879. /**
  3880. * Retrieve ids that are not already present in the cache.
  3881. *
  3882. * @since 3.4.0
  3883. * @access private
  3884. *
  3885. * @param array $object_ids ID list.
  3886. * @param string $cache_key The cache bucket to check against.
  3887. *
  3888. * @return array List of ids not present in the cache.
  3889. */
  3890. function _get_non_cached_ids( $object_ids, $cache_key ) {
  3891. $clean = array();
  3892. foreach ( $object_ids as $id ) {
  3893. $id = (int) $id;
  3894. if ( !wp_cache_get( $id, $cache_key ) ) {
  3895. $clean[] = $id;
  3896. }
  3897. }
  3898. return $clean;
  3899. }
  3900. /**
  3901. * Test if the current device has the capability to upload files.
  3902. *
  3903. * @since 3.4.0
  3904. * @access private
  3905. *
  3906. * @return bool true|false Whether the device is able to upload files.
  3907. */
  3908. function _device_can_upload() {
  3909. if ( ! wp_is_mobile() )
  3910. return true;
  3911. $ua = $_SERVER['HTTP_USER_AGENT'];
  3912. if ( strpos($ua, 'iPhone') !== false
  3913. || strpos($ua, 'iPad') !== false
  3914. || strpos($ua, 'iPod') !== false ) {
  3915. return preg_match( '#OS ([\d_]+) like Mac OS X#', $ua, $version ) && version_compare( $version[1], '6', '>=' );
  3916. }
  3917. return true;
  3918. }
  3919. /**
  3920. * Test if a given path is a stream URL
  3921. *
  3922. * @param string $path The resource path or URL.
  3923. * @return bool True if the path is a stream URL.
  3924. */
  3925. function wp_is_stream( $path ) {
  3926. $wrappers = stream_get_wrappers();
  3927. $wrappers_re = '(' . join('|', $wrappers) . ')';
  3928. return preg_match( "!^$wrappers_re://!", $path ) === 1;
  3929. }
  3930. /**
  3931. * Test if the supplied date is valid for the Gregorian calendar.
  3932. *
  3933. * @since 3.5.0
  3934. *
  3935. * @see checkdate()
  3936. *
  3937. * @param int $month Month number.
  3938. * @param int $day Day number.
  3939. * @param int $year Year number.
  3940. * @param string $source_date The date to filter.
  3941. * @return bool True if valid date, false if not valid date.
  3942. */
  3943. function wp_checkdate( $month, $day, $year, $source_date ) {
  3944. /**
  3945. * Filter whether the given date is valid for the Gregorian calendar.
  3946. *
  3947. * @since 3.5.0
  3948. *
  3949. * @param bool $checkdate Whether the given date is valid.
  3950. * @param string $source_date Date to check.
  3951. */
  3952. return apply_filters( 'wp_checkdate', checkdate( $month, $day, $year ), $source_date );
  3953. }
  3954. /**
  3955. * Load the auth check for monitoring whether the user is still logged in.
  3956. *
  3957. * Can be disabled with remove_action( 'admin_enqueue_scripts', 'wp_auth_check_load' );
  3958. *
  3959. * This is disabled for certain screens where a login screen could cause an
  3960. * inconvenient interruption. A filter called wp_auth_check_load can be used
  3961. * for fine-grained control.
  3962. *
  3963. * @since 3.6.0
  3964. */
  3965. function wp_auth_check_load() {
  3966. if ( ! is_admin() && ! is_user_logged_in() )
  3967. return;
  3968. if ( defined( 'IFRAME_REQUEST' ) )
  3969. return;
  3970. $screen = get_current_screen();
  3971. $hidden = array( 'update', 'update-network', 'update-core', 'update-core-network', 'upgrade', 'upgrade-network', 'network' );
  3972. $show = ! in_array( $screen->id, $hidden );
  3973. /**
  3974. * Filter whether to load the authentication check.
  3975. *
  3976. * Passing a falsey value to the filter will effectively short-circuit
  3977. * loading the authentication check.
  3978. *
  3979. * @since 3.6.0
  3980. *
  3981. * @param bool $show Whether to load the authentication check.
  3982. * @param WP_Screen $screen The current screen object.
  3983. */
  3984. if ( apply_filters( 'wp_auth_check_load', $show, $screen ) ) {
  3985. wp_enqueue_style( 'wp-auth-check' );
  3986. wp_enqueue_script( 'wp-auth-check' );
  3987. add_action( 'admin_print_footer_scripts', 'wp_auth_check_html', 5 );
  3988. add_action( 'wp_print_footer_scripts', 'wp_auth_check_html', 5 );
  3989. }
  3990. }
  3991. /**
  3992. * Output the HTML that shows the wp-login dialog when the user is no longer logged in.
  3993. *
  3994. * @since 3.6.0
  3995. */
  3996. function wp_auth_check_html() {
  3997. $login_url = wp_login_url();
  3998. $current_domain = ( is_ssl() ? 'https://' : 'http://' ) . $_SERVER['HTTP_HOST'];
  3999. $same_domain = ( strpos( $login_url, $current_domain ) === 0 );
  4000. /**
  4001. * Filter whether the authentication check originated at the same domain.
  4002. *
  4003. * @since 3.6.0
  4004. *
  4005. * @param bool $same_domain Whether the authentication check originated at the same domain.
  4006. */
  4007. $same_domain = apply_filters( 'wp_auth_check_same_domain', $same_domain );
  4008. $wrap_class = $same_domain ? 'hidden' : 'hidden fallback';
  4009. ?>
  4010. <div id="wp-auth-check-wrap" class="<?php echo $wrap_class; ?>">
  4011. <div id="wp-auth-check-bg"></div>
  4012. <div id="wp-auth-check">
  4013. <div class="wp-auth-check-close" tabindex="0" title="<?php esc_attr_e('Close'); ?>"></div>
  4014. <?php
  4015. if ( $same_domain ) {
  4016. ?>
  4017. <div id="wp-auth-check-form" data-src="<?php echo esc_url( add_query_arg( array( 'interim-login' => 1 ), $login_url ) ); ?>"></div>
  4018. <?php
  4019. }
  4020. ?>
  4021. <div class="wp-auth-fallback">
  4022. <p><b class="wp-auth-fallback-expired" tabindex="0"><?php _e('Session expired'); ?></b></p>
  4023. <p><a href="<?php echo esc_url( $login_url ); ?>" target="_blank"><?php _e('Please log in again.'); ?></a>
  4024. <?php _e('The login page will open in a new window. After logging in you can close it and return to this page.'); ?></p>
  4025. </div>
  4026. </div>
  4027. </div>
  4028. <?php
  4029. }
  4030. /**
  4031. * Check whether a user is still logged in, for the heartbeat.
  4032. *
  4033. * Send a result that shows a log-in box if the user is no longer logged in,
  4034. * or if their cookie is within the grace period.
  4035. *
  4036. * @since 3.6.0
  4037. *
  4038. * @param array|object $response The Heartbeat response object or array.
  4039. * @return array|object $response The Heartbeat response object or array with 'wp-auth-check'
  4040. * value set.
  4041. */
  4042. function wp_auth_check( $response ) {
  4043. $response['wp-auth-check'] = is_user_logged_in() && empty( $GLOBALS['login_grace_period'] );
  4044. return $response;
  4045. }
  4046. /**
  4047. * Return RegEx body to liberally match an opening HTML tag.
  4048. *
  4049. * Matches an opening HTML tag that:
  4050. * 1. Is self-closing or
  4051. * 2. Has no body but has a closing tag of the same name or
  4052. * 3. Contains a body and a closing tag of the same name
  4053. *
  4054. * Note: this RegEx does not balance inner tags and does not attempt
  4055. * to produce valid HTML
  4056. *
  4057. * @since 3.6.0
  4058. *
  4059. * @param string $tag An HTML tag name. Example: 'video'.
  4060. * @return string Tag RegEx.
  4061. */
  4062. function get_tag_regex( $tag ) {
  4063. if ( empty( $tag ) )
  4064. return;
  4065. return sprintf( '<%1$s[^<]*(?:>[\s\S]*<\/%1$s>|\s*\/>)', tag_escape( $tag ) );
  4066. }
  4067. /**
  4068. * Retrieve a canonical form of the provided charset appropriate for passing to PHP
  4069. * functions such as htmlspecialchars() and charset html attributes.
  4070. *
  4071. * @since 3.6.0
  4072. * @access private
  4073. *
  4074. * @see http://core.trac.wordpress.org/ticket/23688
  4075. *
  4076. * @param string $charset A charset name.
  4077. * @return string The canonical form of the charset.
  4078. */
  4079. function _canonical_charset( $charset ) {
  4080. if ( 'UTF-8' === $charset || 'utf-8' === $charset || 'utf8' === $charset ||
  4081. 'UTF8' === $charset )
  4082. return 'UTF-8';
  4083. if ( 'ISO-8859-1' === $charset || 'iso-8859-1' === $charset ||
  4084. 'iso8859-1' === $charset || 'ISO8859-1' === $charset )
  4085. return 'ISO-8859-1';
  4086. return $charset;
  4087. }
  4088. /**
  4089. * Set the mbstring internal encoding to a binary safe encoding when func_overload
  4090. * is enabled.
  4091. *
  4092. * When mbstring.func_overload is in use for multi-byte encodings, the results from
  4093. * strlen() and similar functions respect the utf8 characters, causing binary data
  4094. * to return incorrect lengths.
  4095. *
  4096. * This function overrides the mbstring encoding to a binary-safe encoding, and
  4097. * resets it to the users expected encoding afterwards through the
  4098. * `reset_mbstring_encoding` function.
  4099. *
  4100. * It is safe to recursively call this function, however each
  4101. * `mbstring_binary_safe_encoding()` call must be followed up with an equal number
  4102. * of `reset_mbstring_encoding()` calls.
  4103. *
  4104. * @since 3.7.0
  4105. *
  4106. * @see reset_mbstring_encoding()
  4107. *
  4108. * @param bool $reset Optional. Whether to reset the encoding back to a previously-set encoding.
  4109. * Default false.
  4110. */
  4111. function mbstring_binary_safe_encoding( $reset = false ) {
  4112. static $encodings = array();
  4113. static $overloaded = null;
  4114. if ( is_null( $overloaded ) )
  4115. $overloaded = function_exists( 'mb_internal_encoding' ) && ( ini_get( 'mbstring.func_overload' ) & 2 );
  4116. if ( false === $overloaded )
  4117. return;
  4118. if ( ! $reset ) {
  4119. $encoding = mb_internal_encoding();
  4120. array_push( $encodings, $encoding );
  4121. mb_internal_encoding( 'ISO-8859-1' );
  4122. }
  4123. if ( $reset && $encodings ) {
  4124. $encoding = array_pop( $encodings );
  4125. mb_internal_encoding( $encoding );
  4126. }
  4127. }
  4128. /**
  4129. * Reset the mbstring internal encoding to a users previously set encoding.
  4130. *
  4131. * @see mbstring_binary_safe_encoding()
  4132. *
  4133. * @since 3.7.0
  4134. */
  4135. function reset_mbstring_encoding() {
  4136. mbstring_binary_safe_encoding( true );
  4137. }
  4138. /**
  4139. * Alternative to filter_var( $var, FILTER_VALIDATE_BOOLEAN ).
  4140. *
  4141. * @since 4.0.0
  4142. *
  4143. * @param mixed $var Boolean value to validate.
  4144. * @return bool Whether the value is validated.
  4145. */
  4146. function wp_validate_boolean( $var ) {
  4147. if ( is_bool( $var ) ) {
  4148. return $var;
  4149. }
  4150. if ( 'false' === $var ) {
  4151. return false;
  4152. }
  4153. return (bool) $var;
  4154. }