PageRenderTime 67ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/functions.php

https://github.com/davodey/WordPress
PHP | 4457 lines | 2144 code | 466 blank | 1847 comment | 501 complexity | 6428cb004221fe4ca3c9252a6f3acdcc MD5 | raw file
Possible License(s): GPL-2.0, AGPL-1.0, LGPL-2.1
  1. <?php
  2. /**
  3. * Main WordPress API
  4. *
  5. * @package WordPress
  6. */
  7. require( ABSPATH . WPINC . '/option.php' );
  8. /**
  9. * Converts given date string into a different format.
  10. *
  11. * $format should be either a PHP date format string, e.g. 'U' for a Unix
  12. * timestamp, or 'G' for a Unix timestamp assuming that $date is GMT.
  13. *
  14. * If $translate is true then the given date and format string will
  15. * be passed to date_i18n() for translation.
  16. *
  17. * @since 0.71
  18. *
  19. * @param string $format Format of the date to return.
  20. * @param string $date Date string to convert.
  21. * @param bool $translate Whether the return date should be translated. Default is true.
  22. * @return string|int Formatted date string, or Unix timestamp.
  23. */
  24. function mysql2date( $format, $date, $translate = true ) {
  25. if ( empty( $date ) )
  26. return false;
  27. if ( 'G' == $format )
  28. return strtotime( $date . ' +0000' );
  29. $i = strtotime( $date );
  30. if ( 'U' == $format )
  31. return $i;
  32. if ( $translate )
  33. return date_i18n( $format, $i );
  34. else
  35. return date( $format, $i );
  36. }
  37. /**
  38. * Retrieve the current time based on specified type.
  39. *
  40. * The 'mysql' type will return the time in the format for MySQL DATETIME field.
  41. * The 'timestamp' type will return the current timestamp.
  42. * Other strings will be interpreted as PHP date formats (e.g. 'Y-m-d').
  43. *
  44. * If $gmt is set to either '1' or 'true', then both types will use GMT time.
  45. * if $gmt is false, the output is adjusted with the GMT offset in the WordPress option.
  46. *
  47. * @since 1.0.0
  48. *
  49. * @param string $type 'mysql', 'timestamp', or PHP date format string (e.g. 'Y-m-d').
  50. * @param int|bool $gmt Optional. Whether to use GMT timezone. Default is false.
  51. * @return int|string Integer if $type is 'timestamp', string otherwise.
  52. */
  53. function current_time( $type, $gmt = 0 ) {
  54. switch ( $type ) {
  55. case 'mysql':
  56. return ( $gmt ) ? gmdate( 'Y-m-d H:i:s' ) : gmdate( 'Y-m-d H:i:s', ( time() + ( get_option( 'gmt_offset' ) * HOUR_IN_SECONDS ) ) );
  57. case 'timestamp':
  58. return ( $gmt ) ? time() : time() + ( get_option( 'gmt_offset' ) * HOUR_IN_SECONDS );
  59. default:
  60. return ( $gmt ) ? date( $type ) : date( $type, time() + ( get_option( 'gmt_offset' ) * HOUR_IN_SECONDS ) );
  61. }
  62. }
  63. /**
  64. * Retrieve the date in localized format, based on timestamp.
  65. *
  66. * If the locale specifies the locale month and weekday, then the locale will
  67. * take over the format for the date. If it isn't, then the date format string
  68. * will be used instead.
  69. *
  70. * @since 0.71
  71. *
  72. * @param string $dateformatstring Format to display the date.
  73. * @param int $unixtimestamp Optional. Unix timestamp.
  74. * @param bool $gmt Optional, default is false. Whether to convert to GMT for time.
  75. * @return string The date, translated if locale specifies it.
  76. */
  77. function date_i18n( $dateformatstring, $unixtimestamp = false, $gmt = false ) {
  78. global $wp_locale;
  79. $i = $unixtimestamp;
  80. if ( false === $i ) {
  81. if ( ! $gmt )
  82. $i = current_time( 'timestamp' );
  83. else
  84. $i = time();
  85. // we should not let date() interfere with our
  86. // specially computed timestamp
  87. $gmt = true;
  88. }
  89. // store original value for language with untypical grammars
  90. // see http://core.trac.wordpress.org/ticket/9396
  91. $req_format = $dateformatstring;
  92. $datefunc = $gmt? 'gmdate' : 'date';
  93. if ( ( !empty( $wp_locale->month ) ) && ( !empty( $wp_locale->weekday ) ) ) {
  94. $datemonth = $wp_locale->get_month( $datefunc( 'm', $i ) );
  95. $datemonth_abbrev = $wp_locale->get_month_abbrev( $datemonth );
  96. $dateweekday = $wp_locale->get_weekday( $datefunc( 'w', $i ) );
  97. $dateweekday_abbrev = $wp_locale->get_weekday_abbrev( $dateweekday );
  98. $datemeridiem = $wp_locale->get_meridiem( $datefunc( 'a', $i ) );
  99. $datemeridiem_capital = $wp_locale->get_meridiem( $datefunc( 'A', $i ) );
  100. $dateformatstring = ' '.$dateformatstring;
  101. $dateformatstring = preg_replace( "/([^\\\])D/", "\\1" . backslashit( $dateweekday_abbrev ), $dateformatstring );
  102. $dateformatstring = preg_replace( "/([^\\\])F/", "\\1" . backslashit( $datemonth ), $dateformatstring );
  103. $dateformatstring = preg_replace( "/([^\\\])l/", "\\1" . backslashit( $dateweekday ), $dateformatstring );
  104. $dateformatstring = preg_replace( "/([^\\\])M/", "\\1" . backslashit( $datemonth_abbrev ), $dateformatstring );
  105. $dateformatstring = preg_replace( "/([^\\\])a/", "\\1" . backslashit( $datemeridiem ), $dateformatstring );
  106. $dateformatstring = preg_replace( "/([^\\\])A/", "\\1" . backslashit( $datemeridiem_capital ), $dateformatstring );
  107. $dateformatstring = substr( $dateformatstring, 1, strlen( $dateformatstring ) -1 );
  108. }
  109. $timezone_formats = array( 'P', 'I', 'O', 'T', 'Z', 'e' );
  110. $timezone_formats_re = implode( '|', $timezone_formats );
  111. if ( preg_match( "/$timezone_formats_re/", $dateformatstring ) ) {
  112. $timezone_string = get_option( 'timezone_string' );
  113. if ( $timezone_string ) {
  114. $timezone_object = timezone_open( $timezone_string );
  115. $date_object = date_create( null, $timezone_object );
  116. foreach( $timezone_formats as $timezone_format ) {
  117. if ( false !== strpos( $dateformatstring, $timezone_format ) ) {
  118. $formatted = date_format( $date_object, $timezone_format );
  119. $dateformatstring = ' '.$dateformatstring;
  120. $dateformatstring = preg_replace( "/([^\\\])$timezone_format/", "\\1" . backslashit( $formatted ), $dateformatstring );
  121. $dateformatstring = substr( $dateformatstring, 1, strlen( $dateformatstring ) -1 );
  122. }
  123. }
  124. }
  125. }
  126. $j = @$datefunc( $dateformatstring, $i );
  127. /**
  128. * Filter the date formatted based on the locale.
  129. *
  130. * @since 2.8.0
  131. *
  132. * @param string $j Formatted date string.
  133. * @param string $req_format Format to display the date.
  134. * @param int $i Unix timestamp.
  135. * @param bool $gmt Whether to convert to GMT for time. Default false.
  136. */
  137. $j = apply_filters( 'date_i18n', $j, $req_format, $i, $gmt );
  138. return $j;
  139. }
  140. /**
  141. * Convert integer number to format based on the locale.
  142. *
  143. * @since 2.3.0
  144. *
  145. * @param int $number The number to convert based on locale.
  146. * @param int $decimals Precision of the number of decimal places.
  147. * @return string Converted number in string format.
  148. */
  149. function number_format_i18n( $number, $decimals = 0 ) {
  150. global $wp_locale;
  151. $formatted = number_format( $number, absint( $decimals ), $wp_locale->number_format['decimal_point'], $wp_locale->number_format['thousands_sep'] );
  152. /**
  153. * Filter the number formatted based on the locale.
  154. *
  155. * @since 2.8.0
  156. *
  157. * @param string $formatted Converted number in string format.
  158. */
  159. return apply_filters( 'number_format_i18n', $formatted );
  160. }
  161. /**
  162. * Convert number of bytes largest unit bytes will fit into.
  163. *
  164. * It is easier to read 1kB than 1024 bytes and 1MB than 1048576 bytes. Converts
  165. * number of bytes to human readable number by taking the number of that unit
  166. * that the bytes will go into it. Supports TB value.
  167. *
  168. * Please note that integers in PHP are limited to 32 bits, unless they are on
  169. * 64 bit architecture, then they have 64 bit size. If you need to place the
  170. * larger size then what PHP integer type will hold, then use a string. It will
  171. * be converted to a double, which should always have 64 bit length.
  172. *
  173. * Technically the correct unit names for powers of 1024 are KiB, MiB etc.
  174. * @link http://en.wikipedia.org/wiki/Byte
  175. *
  176. * @since 2.3.0
  177. *
  178. * @param int|string $bytes Number of bytes. Note max integer size for integers.
  179. * @param int $decimals Precision of number of decimal places. Deprecated.
  180. * @return bool|string False on failure. Number string on success.
  181. */
  182. function size_format( $bytes, $decimals = 0 ) {
  183. $quant = array(
  184. // ========================= Origin ====
  185. 'TB' => 1099511627776, // pow( 1024, 4)
  186. 'GB' => 1073741824, // pow( 1024, 3)
  187. 'MB' => 1048576, // pow( 1024, 2)
  188. 'kB' => 1024, // pow( 1024, 1)
  189. 'B ' => 1, // pow( 1024, 0)
  190. );
  191. foreach ( $quant as $unit => $mag )
  192. if ( doubleval($bytes) >= $mag )
  193. return number_format_i18n( $bytes / $mag, $decimals ) . ' ' . $unit;
  194. return false;
  195. }
  196. /**
  197. * Get the week start and end from the datetime or date string from mysql.
  198. *
  199. * @since 0.71
  200. *
  201. * @param string $mysqlstring Date or datetime field type from mysql.
  202. * @param int $start_of_week Optional. Start of the week as an integer.
  203. * @return array Keys are 'start' and 'end'.
  204. */
  205. function get_weekstartend( $mysqlstring, $start_of_week = '' ) {
  206. $my = substr( $mysqlstring, 0, 4 ); // Mysql string Year
  207. $mm = substr( $mysqlstring, 8, 2 ); // Mysql string Month
  208. $md = substr( $mysqlstring, 5, 2 ); // Mysql string day
  209. $day = mktime( 0, 0, 0, $md, $mm, $my ); // The timestamp for mysqlstring day.
  210. $weekday = date( 'w', $day ); // The day of the week from the timestamp
  211. if ( !is_numeric($start_of_week) )
  212. $start_of_week = get_option( 'start_of_week' );
  213. if ( $weekday < $start_of_week )
  214. $weekday += 7;
  215. $start = $day - DAY_IN_SECONDS * ( $weekday - $start_of_week ); // The most recent week start day on or before $day
  216. $end = $start + 7 * DAY_IN_SECONDS - 1; // $start + 7 days - 1 second
  217. return compact( 'start', 'end' );
  218. }
  219. /**
  220. * Unserialize value only if it was serialized.
  221. *
  222. * @since 2.0.0
  223. *
  224. * @param string $original Maybe unserialized original, if is needed.
  225. * @return mixed Unserialized data can be any type.
  226. */
  227. function maybe_unserialize( $original ) {
  228. if ( is_serialized( $original ) ) // don't attempt to unserialize data that wasn't serialized going in
  229. return @unserialize( $original );
  230. return $original;
  231. }
  232. /**
  233. * Check value to find if it was serialized.
  234. *
  235. * If $data is not an string, then returned value will always be false.
  236. * Serialized data is always a string.
  237. *
  238. * @since 2.0.5
  239. *
  240. * @param mixed $data Value to check to see if was serialized.
  241. * @param bool $strict Optional. Whether to be strict about the end of the string. Defaults true.
  242. * @return bool False if not serialized and true if it was.
  243. */
  244. function is_serialized( $data, $strict = true ) {
  245. // if it isn't a string, it isn't serialized
  246. if ( ! is_string( $data ) ) {
  247. return false;
  248. }
  249. $data = trim( $data );
  250. if ( 'N;' == $data ) {
  251. return true;
  252. }
  253. if ( strlen( $data ) < 4 ) {
  254. return false;
  255. }
  256. if ( ':' !== $data[1] ) {
  257. return false;
  258. }
  259. if ( $strict ) {
  260. $lastc = substr( $data, -1 );
  261. if ( ';' !== $lastc && '}' !== $lastc ) {
  262. return false;
  263. }
  264. } else {
  265. $semicolon = strpos( $data, ';' );
  266. $brace = strpos( $data, '}' );
  267. // Either ; or } must exist.
  268. if ( false === $semicolon && false === $brace )
  269. return false;
  270. // But neither must be in the first X characters.
  271. if ( false !== $semicolon && $semicolon < 3 )
  272. return false;
  273. if ( false !== $brace && $brace < 4 )
  274. return false;
  275. }
  276. $token = $data[0];
  277. switch ( $token ) {
  278. case 's' :
  279. if ( $strict ) {
  280. if ( '"' !== substr( $data, -2, 1 ) ) {
  281. return false;
  282. }
  283. } elseif ( false === strpos( $data, '"' ) ) {
  284. return false;
  285. }
  286. // or else fall through
  287. case 'a' :
  288. case 'O' :
  289. return (bool) preg_match( "/^{$token}:[0-9]+:/s", $data );
  290. case 'b' :
  291. case 'i' :
  292. case 'd' :
  293. $end = $strict ? '$' : '';
  294. return (bool) preg_match( "/^{$token}:[0-9.E-]+;$end/", $data );
  295. }
  296. return false;
  297. }
  298. /**
  299. * Check whether serialized data is of string type.
  300. *
  301. * @since 2.0.5
  302. *
  303. * @param mixed $data Serialized data
  304. * @return bool False if not a serialized string, true if it is.
  305. */
  306. function is_serialized_string( $data ) {
  307. // if it isn't a string, it isn't a serialized string
  308. if ( ! is_string( $data ) ) {
  309. return false;
  310. }
  311. $data = trim( $data );
  312. if ( strlen( $data ) < 4 ) {
  313. return false;
  314. } elseif ( ':' !== $data[1] ) {
  315. return false;
  316. } elseif ( ';' !== substr( $data, -1 ) ) {
  317. return false;
  318. } elseif ( $data[0] !== 's' ) {
  319. return false;
  320. } elseif ( '"' !== substr( $data, -2, 1 ) ) {
  321. return false;
  322. } else {
  323. return true;
  324. }
  325. }
  326. /**
  327. * Serialize data, if needed.
  328. *
  329. * @since 2.0.5
  330. *
  331. * @param mixed $data Data that might be serialized.
  332. * @return mixed A scalar data
  333. */
  334. function maybe_serialize( $data ) {
  335. if ( is_array( $data ) || is_object( $data ) )
  336. return serialize( $data );
  337. // Double serialization is required for backward compatibility.
  338. // See http://core.trac.wordpress.org/ticket/12930
  339. if ( is_serialized( $data, false ) )
  340. return serialize( $data );
  341. return $data;
  342. }
  343. /**
  344. * Retrieve post title from XMLRPC XML.
  345. *
  346. * If the title element is not part of the XML, then the default post title from
  347. * the $post_default_title will be used instead.
  348. *
  349. * @since 0.71
  350. *
  351. * @global string $post_default_title Default XMLRPC post title.
  352. *
  353. * @param string $content XMLRPC XML Request content
  354. * @return string Post title
  355. */
  356. function xmlrpc_getposttitle( $content ) {
  357. global $post_default_title;
  358. if ( preg_match( '/<title>(.+?)<\/title>/is', $content, $matchtitle ) ) {
  359. $post_title = $matchtitle[1];
  360. } else {
  361. $post_title = $post_default_title;
  362. }
  363. return $post_title;
  364. }
  365. /**
  366. * Retrieve the post category or categories from XMLRPC XML.
  367. *
  368. * If the category element is not found, then the default post category will be
  369. * used. The return type then would be what $post_default_category. If the
  370. * category is found, then it will always be an array.
  371. *
  372. * @since 0.71
  373. *
  374. * @global string $post_default_category Default XMLRPC post category.
  375. *
  376. * @param string $content XMLRPC XML Request content
  377. * @return string|array List of categories or category name.
  378. */
  379. function xmlrpc_getpostcategory( $content ) {
  380. global $post_default_category;
  381. if ( preg_match( '/<category>(.+?)<\/category>/is', $content, $matchcat ) ) {
  382. $post_category = trim( $matchcat[1], ',' );
  383. $post_category = explode( ',', $post_category );
  384. } else {
  385. $post_category = $post_default_category;
  386. }
  387. return $post_category;
  388. }
  389. /**
  390. * XMLRPC XML content without title and category elements.
  391. *
  392. * @since 0.71
  393. *
  394. * @param string $content XMLRPC XML Request content
  395. * @return string XMLRPC XML Request content without title and category elements.
  396. */
  397. function xmlrpc_removepostdata( $content ) {
  398. $content = preg_replace( '/<title>(.+?)<\/title>/si', '', $content );
  399. $content = preg_replace( '/<category>(.+?)<\/category>/si', '', $content );
  400. $content = trim( $content );
  401. return $content;
  402. }
  403. /**
  404. * Use RegEx to extract URLs from arbitrary content
  405. *
  406. * @since 3.7.0
  407. *
  408. * @param string $content
  409. * @return array URLs found in passed string
  410. */
  411. function wp_extract_urls( $content ) {
  412. preg_match_all(
  413. "#((?:[\w-]+://?|[\w\d]+[.])[^\s()<>]+[.](?:\([\w\d]+\)|(?:[^`!()\[\]{};:'\".,<>?«»“”‘’\s]|(?:[:]\d+)?/?)+))#",
  414. $content,
  415. $post_links
  416. );
  417. $post_links = array_unique( array_map( 'html_entity_decode', $post_links[0] ) );
  418. return array_values( $post_links );
  419. }
  420. /**
  421. * Check content for video and audio links to add as enclosures.
  422. *
  423. * Will not add enclosures that have already been added and will
  424. * remove enclosures that are no longer in the post. This is called as
  425. * pingbacks and trackbacks.
  426. *
  427. * @since 1.5.0
  428. *
  429. * @uses $wpdb
  430. *
  431. * @param string $content Post Content
  432. * @param int $post_ID Post ID
  433. */
  434. function do_enclose( $content, $post_ID ) {
  435. global $wpdb;
  436. //TODO: Tidy this ghetto code up and make the debug code optional
  437. include_once( ABSPATH . WPINC . '/class-IXR.php' );
  438. $post_links = array();
  439. $pung = get_enclosed( $post_ID );
  440. $post_links_temp = wp_extract_urls( $content );
  441. foreach ( $pung as $link_test ) {
  442. if ( ! in_array( $link_test, $post_links_temp ) ) { // link no longer in post
  443. $mids = $wpdb->get_col( $wpdb->prepare("SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = 'enclosure' AND meta_value LIKE (%s)", $post_ID, like_escape( $link_test ) . '%') );
  444. foreach ( $mids as $mid )
  445. delete_metadata_by_mid( 'post', $mid );
  446. }
  447. }
  448. foreach ( (array) $post_links_temp as $link_test ) {
  449. if ( !in_array( $link_test, $pung ) ) { // If we haven't pung it already
  450. $test = @parse_url( $link_test );
  451. if ( false === $test )
  452. continue;
  453. if ( isset( $test['query'] ) )
  454. $post_links[] = $link_test;
  455. elseif ( isset($test['path']) && ( $test['path'] != '/' ) && ($test['path'] != '' ) )
  456. $post_links[] = $link_test;
  457. }
  458. }
  459. foreach ( (array) $post_links as $url ) {
  460. if ( $url != '' && !$wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = 'enclosure' AND meta_value LIKE (%s)", $post_ID, like_escape( $url ) . '%' ) ) ) {
  461. if ( $headers = wp_get_http_headers( $url) ) {
  462. $len = isset( $headers['content-length'] ) ? (int) $headers['content-length'] : 0;
  463. $type = isset( $headers['content-type'] ) ? $headers['content-type'] : '';
  464. $allowed_types = array( 'video', 'audio' );
  465. // Check to see if we can figure out the mime type from
  466. // the extension
  467. $url_parts = @parse_url( $url );
  468. if ( false !== $url_parts ) {
  469. $extension = pathinfo( $url_parts['path'], PATHINFO_EXTENSION );
  470. if ( !empty( $extension ) ) {
  471. foreach ( wp_get_mime_types() as $exts => $mime ) {
  472. if ( preg_match( '!^(' . $exts . ')$!i', $extension ) ) {
  473. $type = $mime;
  474. break;
  475. }
  476. }
  477. }
  478. }
  479. if ( in_array( substr( $type, 0, strpos( $type, "/" ) ), $allowed_types ) ) {
  480. add_post_meta( $post_ID, 'enclosure', "$url\n$len\n$mime\n" );
  481. }
  482. }
  483. }
  484. }
  485. }
  486. /**
  487. * Perform a HTTP HEAD or GET request.
  488. *
  489. * If $file_path is a writable filename, this will do a GET request and write
  490. * the file to that path.
  491. *
  492. * @since 2.5.0
  493. *
  494. * @param string $url URL to fetch.
  495. * @param string|bool $file_path Optional. File path to write request to.
  496. * @param int $red (private) The number of Redirects followed, Upon 5 being hit, returns false.
  497. * @return bool|string False on failure and string of headers if HEAD request.
  498. */
  499. function wp_get_http( $url, $file_path = false, $red = 1 ) {
  500. @set_time_limit( 60 );
  501. if ( $red > 5 )
  502. return false;
  503. $options = array();
  504. $options['redirection'] = 5;
  505. if ( false == $file_path )
  506. $options['method'] = 'HEAD';
  507. else
  508. $options['method'] = 'GET';
  509. $response = wp_safe_remote_request( $url, $options );
  510. if ( is_wp_error( $response ) )
  511. return false;
  512. $headers = wp_remote_retrieve_headers( $response );
  513. $headers['response'] = wp_remote_retrieve_response_code( $response );
  514. // WP_HTTP no longer follows redirects for HEAD requests.
  515. if ( 'HEAD' == $options['method'] && in_array($headers['response'], array(301, 302)) && isset( $headers['location'] ) ) {
  516. return wp_get_http( $headers['location'], $file_path, ++$red );
  517. }
  518. if ( false == $file_path )
  519. return $headers;
  520. // GET request - write it to the supplied filename
  521. $out_fp = fopen($file_path, 'w');
  522. if ( !$out_fp )
  523. return $headers;
  524. fwrite( $out_fp, wp_remote_retrieve_body( $response ) );
  525. fclose($out_fp);
  526. clearstatcache();
  527. return $headers;
  528. }
  529. /**
  530. * Retrieve HTTP Headers from URL.
  531. *
  532. * @since 1.5.1
  533. *
  534. * @param string $url
  535. * @param bool $deprecated Not Used.
  536. * @return bool|string False on failure, headers on success.
  537. */
  538. function wp_get_http_headers( $url, $deprecated = false ) {
  539. if ( !empty( $deprecated ) )
  540. _deprecated_argument( __FUNCTION__, '2.7' );
  541. $response = wp_safe_remote_head( $url );
  542. if ( is_wp_error( $response ) )
  543. return false;
  544. return wp_remote_retrieve_headers( $response );
  545. }
  546. /**
  547. * Whether the publish date of the current post in the loop is different from the
  548. * publish date of the previous post in the loop.
  549. *
  550. * @since 0.71
  551. * @global string $currentday The day of the current post in the loop.
  552. * @global string $previousday The day of the previous post in the loop.
  553. *
  554. * @return int 1 when new day, 0 if not a new day.
  555. */
  556. function is_new_day() {
  557. global $currentday, $previousday;
  558. if ( $currentday != $previousday )
  559. return 1;
  560. else
  561. return 0;
  562. }
  563. /**
  564. * Build URL query based on an associative and, or indexed array.
  565. *
  566. * This is a convenient function for easily building url queries. It sets the
  567. * separator to '&' and uses _http_build_query() function.
  568. *
  569. * @see _http_build_query() Used to build the query
  570. * @link http://us2.php.net/manual/en/function.http-build-query.php more on what
  571. * http_build_query() does.
  572. *
  573. * @since 2.3.0
  574. *
  575. * @param array $data URL-encode key/value pairs.
  576. * @return string URL encoded string
  577. */
  578. function build_query( $data ) {
  579. return _http_build_query( $data, null, '&', '', false );
  580. }
  581. // from php.net (modified by Mark Jaquith to behave like the native PHP5 function)
  582. function _http_build_query($data, $prefix=null, $sep=null, $key='', $urlencode=true) {
  583. $ret = array();
  584. foreach ( (array) $data as $k => $v ) {
  585. if ( $urlencode)
  586. $k = urlencode($k);
  587. if ( is_int($k) && $prefix != null )
  588. $k = $prefix.$k;
  589. if ( !empty($key) )
  590. $k = $key . '%5B' . $k . '%5D';
  591. if ( $v === null )
  592. continue;
  593. elseif ( $v === FALSE )
  594. $v = '0';
  595. if ( is_array($v) || is_object($v) )
  596. array_push($ret,_http_build_query($v, '', $sep, $k, $urlencode));
  597. elseif ( $urlencode )
  598. array_push($ret, $k.'='.urlencode($v));
  599. else
  600. array_push($ret, $k.'='.$v);
  601. }
  602. if ( null === $sep )
  603. $sep = ini_get('arg_separator.output');
  604. return implode($sep, $ret);
  605. }
  606. /**
  607. * Retrieve a modified URL query string.
  608. *
  609. * You can rebuild the URL and append a new query variable to the URL query by
  610. * using this function. You can also retrieve the full URL with query data.
  611. *
  612. * Adding a single key & value or an associative array. Setting a key value to
  613. * an empty string removes the key. Omitting oldquery_or_uri uses the $_SERVER
  614. * value. Additional values provided are expected to be encoded appropriately
  615. * with urlencode() or rawurlencode().
  616. *
  617. * @since 1.5.0
  618. *
  619. * @param mixed $param1 Either newkey or an associative_array
  620. * @param mixed $param2 Either newvalue or oldquery or uri
  621. * @param mixed $param3 Optional. Old query or uri
  622. * @return string New URL query string.
  623. */
  624. function add_query_arg() {
  625. $args = func_get_args();
  626. if ( is_array( $args[0] ) ) {
  627. if ( count( $args ) < 2 || false === $args[1] )
  628. $uri = $_SERVER['REQUEST_URI'];
  629. else
  630. $uri = $args[1];
  631. } else {
  632. if ( count( $args ) < 3 || false === $args[2] )
  633. $uri = $_SERVER['REQUEST_URI'];
  634. else
  635. $uri = $args[2];
  636. }
  637. if ( $frag = strstr( $uri, '#' ) )
  638. $uri = substr( $uri, 0, -strlen( $frag ) );
  639. else
  640. $frag = '';
  641. if ( 0 === stripos( $uri, 'http://' ) ) {
  642. $protocol = 'http://';
  643. $uri = substr( $uri, 7 );
  644. } elseif ( 0 === stripos( $uri, 'https://' ) ) {
  645. $protocol = 'https://';
  646. $uri = substr( $uri, 8 );
  647. } else {
  648. $protocol = '';
  649. }
  650. if ( strpos( $uri, '?' ) !== false ) {
  651. list( $base, $query ) = explode( '?', $uri, 2 );
  652. $base .= '?';
  653. } elseif ( $protocol || strpos( $uri, '=' ) === false ) {
  654. $base = $uri . '?';
  655. $query = '';
  656. } else {
  657. $base = '';
  658. $query = $uri;
  659. }
  660. wp_parse_str( $query, $qs );
  661. $qs = urlencode_deep( $qs ); // this re-URL-encodes things that were already in the query string
  662. if ( is_array( $args[0] ) ) {
  663. $kayvees = $args[0];
  664. $qs = array_merge( $qs, $kayvees );
  665. } else {
  666. $qs[ $args[0] ] = $args[1];
  667. }
  668. foreach ( $qs as $k => $v ) {
  669. if ( $v === false )
  670. unset( $qs[$k] );
  671. }
  672. $ret = build_query( $qs );
  673. $ret = trim( $ret, '?' );
  674. $ret = preg_replace( '#=(&|$)#', '$1', $ret );
  675. $ret = $protocol . $base . $ret . $frag;
  676. $ret = rtrim( $ret, '?' );
  677. return $ret;
  678. }
  679. /**
  680. * Removes an item or list from the query string.
  681. *
  682. * @since 1.5.0
  683. *
  684. * @param string|array $key Query key or keys to remove.
  685. * @param bool $query When false uses the $_SERVER value.
  686. * @return string New URL query string.
  687. */
  688. function remove_query_arg( $key, $query=false ) {
  689. if ( is_array( $key ) ) { // removing multiple keys
  690. foreach ( $key as $k )
  691. $query = add_query_arg( $k, false, $query );
  692. return $query;
  693. }
  694. return add_query_arg( $key, false, $query );
  695. }
  696. /**
  697. * Walks the array while sanitizing the contents.
  698. *
  699. * @since 0.71
  700. *
  701. * @param array $array Array to walk while sanitizing contents.
  702. * @return array Sanitized $array.
  703. */
  704. function add_magic_quotes( $array ) {
  705. foreach ( (array) $array as $k => $v ) {
  706. if ( is_array( $v ) ) {
  707. $array[$k] = add_magic_quotes( $v );
  708. } else {
  709. $array[$k] = addslashes( $v );
  710. }
  711. }
  712. return $array;
  713. }
  714. /**
  715. * HTTP request for URI to retrieve content.
  716. *
  717. * @since 1.5.1
  718. * @uses wp_remote_get()
  719. *
  720. * @param string $uri URI/URL of web page to retrieve.
  721. * @return bool|string HTTP content. False on failure.
  722. */
  723. function wp_remote_fopen( $uri ) {
  724. $parsed_url = @parse_url( $uri );
  725. if ( !$parsed_url || !is_array( $parsed_url ) )
  726. return false;
  727. $options = array();
  728. $options['timeout'] = 10;
  729. $response = wp_safe_remote_get( $uri, $options );
  730. if ( is_wp_error( $response ) )
  731. return false;
  732. return wp_remote_retrieve_body( $response );
  733. }
  734. /**
  735. * Set up the WordPress query.
  736. *
  737. * @since 2.0.0
  738. *
  739. * @param string $query_vars Default WP_Query arguments.
  740. */
  741. function wp( $query_vars = '' ) {
  742. global $wp, $wp_query, $wp_the_query;
  743. $wp->main( $query_vars );
  744. if ( !isset($wp_the_query) )
  745. $wp_the_query = $wp_query;
  746. }
  747. /**
  748. * Retrieve the description for the HTTP status.
  749. *
  750. * @since 2.3.0
  751. *
  752. * @param int $code HTTP status code.
  753. * @return string Empty string if not found, or description if found.
  754. */
  755. function get_status_header_desc( $code ) {
  756. global $wp_header_to_desc;
  757. $code = absint( $code );
  758. if ( !isset( $wp_header_to_desc ) ) {
  759. $wp_header_to_desc = array(
  760. 100 => 'Continue',
  761. 101 => 'Switching Protocols',
  762. 102 => 'Processing',
  763. 200 => 'OK',
  764. 201 => 'Created',
  765. 202 => 'Accepted',
  766. 203 => 'Non-Authoritative Information',
  767. 204 => 'No Content',
  768. 205 => 'Reset Content',
  769. 206 => 'Partial Content',
  770. 207 => 'Multi-Status',
  771. 226 => 'IM Used',
  772. 300 => 'Multiple Choices',
  773. 301 => 'Moved Permanently',
  774. 302 => 'Found',
  775. 303 => 'See Other',
  776. 304 => 'Not Modified',
  777. 305 => 'Use Proxy',
  778. 306 => 'Reserved',
  779. 307 => 'Temporary Redirect',
  780. 400 => 'Bad Request',
  781. 401 => 'Unauthorized',
  782. 402 => 'Payment Required',
  783. 403 => 'Forbidden',
  784. 404 => 'Not Found',
  785. 405 => 'Method Not Allowed',
  786. 406 => 'Not Acceptable',
  787. 407 => 'Proxy Authentication Required',
  788. 408 => 'Request Timeout',
  789. 409 => 'Conflict',
  790. 410 => 'Gone',
  791. 411 => 'Length Required',
  792. 412 => 'Precondition Failed',
  793. 413 => 'Request Entity Too Large',
  794. 414 => 'Request-URI Too Long',
  795. 415 => 'Unsupported Media Type',
  796. 416 => 'Requested Range Not Satisfiable',
  797. 417 => 'Expectation Failed',
  798. 418 => 'I\'m a teapot',
  799. 422 => 'Unprocessable Entity',
  800. 423 => 'Locked',
  801. 424 => 'Failed Dependency',
  802. 426 => 'Upgrade Required',
  803. 428 => 'Precondition Required',
  804. 429 => 'Too Many Requests',
  805. 431 => 'Request Header Fields Too Large',
  806. 500 => 'Internal Server Error',
  807. 501 => 'Not Implemented',
  808. 502 => 'Bad Gateway',
  809. 503 => 'Service Unavailable',
  810. 504 => 'Gateway Timeout',
  811. 505 => 'HTTP Version Not Supported',
  812. 506 => 'Variant Also Negotiates',
  813. 507 => 'Insufficient Storage',
  814. 510 => 'Not Extended',
  815. 511 => 'Network Authentication Required',
  816. );
  817. }
  818. if ( isset( $wp_header_to_desc[$code] ) )
  819. return $wp_header_to_desc[$code];
  820. else
  821. return '';
  822. }
  823. /**
  824. * Set HTTP status header.
  825. *
  826. * @since 2.0.0
  827. * @see get_status_header_desc()
  828. *
  829. * @param int $code HTTP status code.
  830. */
  831. function status_header( $code ) {
  832. $description = get_status_header_desc( $code );
  833. if ( empty( $description ) )
  834. return;
  835. $protocol = $_SERVER['SERVER_PROTOCOL'];
  836. if ( 'HTTP/1.1' != $protocol && 'HTTP/1.0' != $protocol )
  837. $protocol = 'HTTP/1.0';
  838. $status_header = "$protocol $code $description";
  839. if ( function_exists( 'apply_filters' ) )
  840. /**
  841. * Filter an HTTP status header.
  842. *
  843. * @since 2.2.0
  844. *
  845. * @param string $status_header HTTP status header.
  846. * @param int $code HTTP status code.
  847. * @param string $description Description for the status code.
  848. * @param string $protocol Server protocol.
  849. */
  850. $status_header = apply_filters( 'status_header', $status_header, $code, $description, $protocol );
  851. @header( $status_header, true, $code );
  852. }
  853. /**
  854. * Gets the header information to prevent caching.
  855. *
  856. * The several different headers cover the different ways cache prevention is handled
  857. * by different browsers
  858. *
  859. * @since 2.8.0
  860. *
  861. * @return array The associative array of header names and field values.
  862. */
  863. function wp_get_nocache_headers() {
  864. $headers = array(
  865. 'Expires' => 'Wed, 11 Jan 1984 05:00:00 GMT',
  866. 'Cache-Control' => 'no-cache, must-revalidate, max-age=0',
  867. 'Pragma' => 'no-cache',
  868. );
  869. if ( function_exists('apply_filters') ) {
  870. /**
  871. * Filter the cache-controlling headers.
  872. *
  873. * @since 2.8.0
  874. *
  875. * @param array $headers {
  876. * Header names and field values.
  877. *
  878. * @type string $Expires Expires header.
  879. * @type string $Cache-Control Cache-Control header.
  880. * @type string $Pragma Pragma header.
  881. * }
  882. */
  883. $headers = (array) apply_filters( 'nocache_headers', $headers );
  884. }
  885. $headers['Last-Modified'] = false;
  886. return $headers;
  887. }
  888. /**
  889. * Sets the headers to prevent caching for the different browsers.
  890. *
  891. * Different browsers support different nocache headers, so several headers must
  892. * be sent so that all of them get the point that no caching should occur.
  893. *
  894. * @since 2.0.0
  895. * @see wp_get_nocache_headers()
  896. */
  897. function nocache_headers() {
  898. $headers = wp_get_nocache_headers();
  899. unset( $headers['Last-Modified'] );
  900. // In PHP 5.3+, make sure we are not sending a Last-Modified header.
  901. if ( function_exists( 'header_remove' ) ) {
  902. @header_remove( 'Last-Modified' );
  903. } else {
  904. // In PHP 5.2, send an empty Last-Modified header, but only as a
  905. // last resort to override a header already sent. #WP23021
  906. foreach ( headers_list() as $header ) {
  907. if ( 0 === stripos( $header, 'Last-Modified' ) ) {
  908. $headers['Last-Modified'] = '';
  909. break;
  910. }
  911. }
  912. }
  913. foreach( $headers as $name => $field_value )
  914. @header("{$name}: {$field_value}");
  915. }
  916. /**
  917. * Set the headers for caching for 10 days with JavaScript content type.
  918. *
  919. * @since 2.1.0
  920. */
  921. function cache_javascript_headers() {
  922. $expiresOffset = 10 * DAY_IN_SECONDS;
  923. header( "Content-Type: text/javascript; charset=" . get_bloginfo( 'charset' ) );
  924. header( "Vary: Accept-Encoding" ); // Handle proxies
  925. header( "Expires: " . gmdate( "D, d M Y H:i:s", time() + $expiresOffset ) . " GMT" );
  926. }
  927. /**
  928. * Retrieve the number of database queries during the WordPress execution.
  929. *
  930. * @since 2.0.0
  931. *
  932. * @return int Number of database queries
  933. */
  934. function get_num_queries() {
  935. global $wpdb;
  936. return $wpdb->num_queries;
  937. }
  938. /**
  939. * Whether input is yes or no. Must be 'y' to be true.
  940. *
  941. * @since 1.0.0
  942. *
  943. * @param string $yn Character string containing either 'y' or 'n'
  944. * @return bool True if yes, false on anything else
  945. */
  946. function bool_from_yn( $yn ) {
  947. return ( strtolower( $yn ) == 'y' );
  948. }
  949. /**
  950. * Loads the feed template from the use of an action hook.
  951. *
  952. * If the feed action does not have a hook, then the function will die with a
  953. * message telling the visitor that the feed is not valid.
  954. *
  955. * It is better to only have one hook for each feed.
  956. *
  957. * @since 2.1.0
  958. *
  959. * @uses $wp_query Used to tell if the use a comment feed.
  960. */
  961. function do_feed() {
  962. global $wp_query;
  963. $feed = get_query_var( 'feed' );
  964. // Remove the pad, if present.
  965. $feed = preg_replace( '/^_+/', '', $feed );
  966. if ( $feed == '' || $feed == 'feed' )
  967. $feed = get_default_feed();
  968. $hook = 'do_feed_' . $feed;
  969. if ( ! has_action( $hook ) )
  970. wp_die( __( 'ERROR: This is not a valid feed template.' ), '', array( 'response' => 404 ) );
  971. /**
  972. * Fires once the given feed is loaded.
  973. *
  974. * The dynamic hook name, $hook, refers to the feed name.
  975. *
  976. * @since 2.1.0
  977. *
  978. * @param bool $is_comment_feed Whether the feed is a comment feed.
  979. */
  980. do_action( $hook, $wp_query->is_comment_feed );
  981. }
  982. /**
  983. * Load the RDF RSS 0.91 Feed template.
  984. *
  985. * @since 2.1.0
  986. */
  987. function do_feed_rdf() {
  988. load_template( ABSPATH . WPINC . '/feed-rdf.php' );
  989. }
  990. /**
  991. * Load the RSS 1.0 Feed Template.
  992. *
  993. * @since 2.1.0
  994. */
  995. function do_feed_rss() {
  996. load_template( ABSPATH . WPINC . '/feed-rss.php' );
  997. }
  998. /**
  999. * Load either the RSS2 comment feed or the RSS2 posts feed.
  1000. *
  1001. * @since 2.1.0
  1002. *
  1003. * @param bool $for_comments True for the comment feed, false for normal feed.
  1004. */
  1005. function do_feed_rss2( $for_comments ) {
  1006. if ( $for_comments )
  1007. load_template( ABSPATH . WPINC . '/feed-rss2-comments.php' );
  1008. else
  1009. load_template( ABSPATH . WPINC . '/feed-rss2.php' );
  1010. }
  1011. /**
  1012. * Load either Atom comment feed or Atom posts feed.
  1013. *
  1014. * @since 2.1.0
  1015. *
  1016. * @param bool $for_comments True for the comment feed, false for normal feed.
  1017. */
  1018. function do_feed_atom( $for_comments ) {
  1019. if ($for_comments)
  1020. load_template( ABSPATH . WPINC . '/feed-atom-comments.php');
  1021. else
  1022. load_template( ABSPATH . WPINC . '/feed-atom.php' );
  1023. }
  1024. /**
  1025. * Display the robots.txt file content.
  1026. *
  1027. * The echo content should be with usage of the permalinks or for creating the
  1028. * robots.txt file.
  1029. *
  1030. * @since 2.1.0
  1031. */
  1032. function do_robots() {
  1033. header( 'Content-Type: text/plain; charset=utf-8' );
  1034. /**
  1035. * Fires when displaying the robots.txt file.
  1036. *
  1037. * @since 2.1.0
  1038. */
  1039. do_action( 'do_robotstxt' );
  1040. $output = "User-agent: *\n";
  1041. $public = get_option( 'blog_public' );
  1042. if ( '0' == $public ) {
  1043. $output .= "Disallow: /\n";
  1044. } else {
  1045. $site_url = parse_url( site_url() );
  1046. $path = ( !empty( $site_url['path'] ) ) ? $site_url['path'] : '';
  1047. $output .= "Disallow: $path/wp-admin/\n";
  1048. $output .= "Disallow: $path/wp-includes/\n";
  1049. }
  1050. /**
  1051. * Filter the robots.txt output.
  1052. *
  1053. * @since 3.0.0
  1054. *
  1055. * @param string $output Robots.txt output.
  1056. * @param bool $public Whether the site is considered "public".
  1057. */
  1058. echo apply_filters( 'robots_txt', $output, $public );
  1059. }
  1060. /**
  1061. * Test whether blog is already installed.
  1062. *
  1063. * The cache will be checked first. If you have a cache plugin, which saves the
  1064. * cache values, then this will work. If you use the default WordPress cache,
  1065. * and the database goes away, then you might have problems.
  1066. *
  1067. * Checks for the option siteurl for whether WordPress is installed.
  1068. *
  1069. * @since 2.1.0
  1070. * @uses $wpdb
  1071. *
  1072. * @return bool Whether blog is already installed.
  1073. */
  1074. function is_blog_installed() {
  1075. global $wpdb;
  1076. // Check cache first. If options table goes away and we have true cached, oh well.
  1077. if ( wp_cache_get( 'is_blog_installed' ) )
  1078. return true;
  1079. $suppress = $wpdb->suppress_errors();
  1080. if ( ! defined( 'WP_INSTALLING' ) ) {
  1081. $alloptions = wp_load_alloptions();
  1082. }
  1083. // If siteurl is not set to autoload, check it specifically
  1084. if ( !isset( $alloptions['siteurl'] ) )
  1085. $installed = $wpdb->get_var( "SELECT option_value FROM $wpdb->options WHERE option_name = 'siteurl'" );
  1086. else
  1087. $installed = $alloptions['siteurl'];
  1088. $wpdb->suppress_errors( $suppress );
  1089. $installed = !empty( $installed );
  1090. wp_cache_set( 'is_blog_installed', $installed );
  1091. if ( $installed )
  1092. return true;
  1093. // If visiting repair.php, return true and let it take over.
  1094. if ( defined( 'WP_REPAIRING' ) )
  1095. return true;
  1096. $suppress = $wpdb->suppress_errors();
  1097. // Loop over the WP tables. If none exist, then scratch install is allowed.
  1098. // If one or more exist, suggest table repair since we got here because the options
  1099. // table could not be accessed.
  1100. $wp_tables = $wpdb->tables();
  1101. foreach ( $wp_tables as $table ) {
  1102. // The existence of custom user tables shouldn't suggest an insane state or prevent a clean install.
  1103. if ( defined( 'CUSTOM_USER_TABLE' ) && CUSTOM_USER_TABLE == $table )
  1104. continue;
  1105. if ( defined( 'CUSTOM_USER_META_TABLE' ) && CUSTOM_USER_META_TABLE == $table )
  1106. continue;
  1107. if ( ! $wpdb->get_results( "DESCRIBE $table;" ) )
  1108. continue;
  1109. // One or more tables exist. We are insane.
  1110. wp_load_translations_early();
  1111. // Die with a DB error.
  1112. $wpdb->error = sprintf( __( 'One or more database tables are unavailable. The database may need to be <a href="%s">repaired</a>.' ), 'maint/repair.php?referrer=is_blog_installed' );
  1113. dead_db();
  1114. }
  1115. $wpdb->suppress_errors( $suppress );
  1116. wp_cache_set( 'is_blog_installed', false );
  1117. return false;
  1118. }
  1119. /**
  1120. * Retrieve URL with nonce added to URL query.
  1121. *
  1122. * @since 2.0.4
  1123. *
  1124. * @param string $actionurl URL to add nonce action.
  1125. * @param string $action Optional. Nonce action name.
  1126. * @param string $name Optional. Nonce name.
  1127. * @return string Escaped URL with nonce action added.
  1128. */
  1129. function wp_nonce_url( $actionurl, $action = -1, $name = '_wpnonce' ) {
  1130. $actionurl = str_replace( '&amp;', '&', $actionurl );
  1131. return esc_html( add_query_arg( $name, wp_create_nonce( $action ), $actionurl ) );
  1132. }
  1133. /**
  1134. * Retrieve or display nonce hidden field for forms.
  1135. *
  1136. * The nonce field is used to validate that the contents of the form came from
  1137. * the location on the current site and not somewhere else. The nonce does not
  1138. * offer absolute protection, but should protect against most cases. It is very
  1139. * important to use nonce field in forms.
  1140. *
  1141. * The $action and $name are optional, but if you want to have better security,
  1142. * it is strongly suggested to set those two parameters. It is easier to just
  1143. * call the function without any parameters, because validation of the nonce
  1144. * doesn't require any parameters, but since crackers know what the default is
  1145. * it won't be difficult for them to find a way around your nonce and cause
  1146. * damage.
  1147. *
  1148. * The input name will be whatever $name value you gave. The input value will be
  1149. * the nonce creation value.
  1150. *
  1151. * @since 2.0.4
  1152. *
  1153. * @param string $action Optional. Action name.
  1154. * @param string $name Optional. Nonce name.
  1155. * @param bool $referer Optional, default true. Whether to set the referer field for validation.
  1156. * @param bool $echo Optional, default true. Whether to display or return hidden form field.
  1157. * @return string Nonce field.
  1158. */
  1159. function wp_nonce_field( $action = -1, $name = "_wpnonce", $referer = true , $echo = true ) {
  1160. $name = esc_attr( $name );
  1161. $nonce_field = '<input type="hidden" id="' . $name . '" name="' . $name . '" value="' . wp_create_nonce( $action ) . '" />';
  1162. if ( $referer )
  1163. $nonce_field .= wp_referer_field( false );
  1164. if ( $echo )
  1165. echo $nonce_field;
  1166. return $nonce_field;
  1167. }
  1168. /**
  1169. * Retrieve or display referer hidden field for forms.
  1170. *
  1171. * The referer link is the current Request URI from the server super global. The
  1172. * input name is '_wp_http_referer', in case you wanted to check manually.
  1173. *
  1174. * @since 2.0.4
  1175. *
  1176. * @param bool $echo Whether to echo or return the referer field.
  1177. * @return string Referer field.
  1178. */
  1179. function wp_referer_field( $echo = true ) {
  1180. $referer_field = '<input type="hidden" name="_wp_http_referer" value="'. esc_attr( wp_unslash( $_SERVER['REQUEST_URI'] ) ) . '" />';
  1181. if ( $echo )
  1182. echo $referer_field;
  1183. return $referer_field;
  1184. }
  1185. /**
  1186. * Retrieve or display original referer hidden field for forms.
  1187. *
  1188. * The input name is '_wp_original_http_referer' and will be either the same
  1189. * value of {@link wp_referer_field()}, if that was posted already or it will
  1190. * be the current page, if it doesn't exist.
  1191. *
  1192. * @since 2.0.4
  1193. *
  1194. * @param bool $echo Whether to echo the original http referer
  1195. * @param string $jump_back_to Optional, default is 'current'. Can be 'previous' or page you want to jump back to.
  1196. * @return string Original referer field.
  1197. */
  1198. function wp_original_referer_field( $echo = true, $jump_back_to = 'current' ) {
  1199. if ( ! $ref = wp_get_original_referer() ) {
  1200. $ref = 'previous' == $jump_back_to ? wp_get_referer() : wp_unslash( $_SERVER['REQUEST_URI'] );
  1201. }
  1202. $orig_referer_field = '<input type="hidden" name="_wp_original_http_referer" value="' . esc_attr( $ref ) . '" />';
  1203. if ( $echo )
  1204. echo $orig_referer_field;
  1205. return $orig_referer_field;
  1206. }
  1207. /**
  1208. * Retrieve referer from '_wp_http_referer' or HTTP referer. If it's the same
  1209. * as the current request URL, will return false.
  1210. *
  1211. * @since 2.0.4
  1212. *
  1213. * @return string|bool False on failure. Referer URL on success.
  1214. */
  1215. function wp_get_referer() {
  1216. if ( ! function_exists( 'wp_validate_redirect' ) )
  1217. return false;
  1218. $ref = false;
  1219. if ( ! empty( $_REQUEST['_wp_http_referer'] ) )
  1220. $ref = wp_unslash( $_REQUEST['_wp_http_referer'] );
  1221. else if ( ! empty( $_SERVER['HTTP_REFERER'] ) )
  1222. $ref = wp_unslash( $_SERVER['HTTP_REFERER'] );
  1223. if ( $ref && $ref !== wp_unslash( $_SERVER['REQUEST_URI'] ) )
  1224. return wp_validate_redirect( $ref, false );
  1225. return false;
  1226. }
  1227. /**
  1228. * Retrieve original referer that was posted, if it exists.
  1229. *
  1230. * @since 2.0.4
  1231. *
  1232. * @return string|bool False if no original referer or original referer if set.
  1233. */
  1234. function wp_get_original_referer() {
  1235. if ( ! empty( $_REQUEST['_wp_original_http_referer'] ) && function_exists( 'wp_validate_redirect' ) )
  1236. return wp_validate_redirect( wp_unslash( $_REQUEST['_wp_original_http_referer'] ), false );
  1237. return false;
  1238. }
  1239. /**
  1240. * Recursive directory creation based on full path.
  1241. *
  1242. * Will attempt to set permissions on folders.
  1243. *
  1244. * @since 2.0.1
  1245. *
  1246. * @param string $target Full path to attempt to create.
  1247. * @return bool Whether the path was created. True if path already exists.
  1248. */
  1249. function wp_mkdir_p( $target ) {
  1250. $wrapper = null;
  1251. // strip the protocol
  1252. if( wp_is_stream( $target ) ) {
  1253. list( $wrapper, $target ) = explode( '://', $target, 2 );
  1254. }
  1255. // from php.net/mkdir user contributed notes
  1256. $target = str_replace( '//', '/', $target );
  1257. // put the wrapper back on the target
  1258. if( $wrapper !== null ) {
  1259. $target = $wrapper . '://' . $target;
  1260. }
  1261. // safe mode fails with a trailing slash under certain PHP versions.
  1262. $target = rtrim($target, '/'); // Use rtrim() instead of untrailingslashit to avoid formatting.php dependency.
  1263. if ( empty($target) )
  1264. $target = '/';
  1265. if ( file_exists( $target ) )
  1266. return @is_dir( $target );
  1267. // We need to find the permissions of the parent folder that exists and inherit that.
  1268. $target_parent = dirname( $target );
  1269. while ( '.' != $target_parent && ! is_dir( $target_parent ) ) {
  1270. $target_parent = dirname( $target_parent );
  1271. }
  1272. // Get the permission bits.
  1273. if ( $stat = @stat( $target_parent ) ) {
  1274. $dir_perms = $stat['mode'] & 0007777;
  1275. } else {
  1276. $dir_perms = 0777;
  1277. }
  1278. if ( @mkdir( $target, $dir_perms, true ) ) {
  1279. // If a umask is set that modifies $dir_perms, we'll have to re-set the $dir_perms correctly with chmod()
  1280. if ( $dir_perms != ( $dir_perms & ~umask() ) ) {
  1281. $folder_parts = explode( '/', substr( $target, strlen( $target_parent ) + 1 ) );
  1282. for ( $i = 1; $i <= count( $folder_parts ); $i++ ) {
  1283. @chmod( $target_parent . '/' . implode( '/', array_slice( $folder_parts, 0, $i ) ), $dir_perms );
  1284. }
  1285. }
  1286. return true;
  1287. }
  1288. return false;
  1289. }
  1290. /**
  1291. * Test if a give filesystem path is absolute ('/foo/bar', 'c:\windows').
  1292. *
  1293. * @since 2.5.0
  1294. *
  1295. * @param string $path File path
  1296. * @return bool True if path is absolute, false is not absolute.
  1297. */
  1298. function path_is_absolute( $path ) {
  1299. // this is definitive if true but fails if $path does not exist or contains a symbolic link
  1300. if ( realpath($path) == $path )
  1301. return true;
  1302. if ( strlen($path) == 0 || $path[0] == '.' )
  1303. return false;
  1304. // windows allows absolute paths like this
  1305. if ( preg_match('#^[a-zA-Z]:\\\\#', $path) )
  1306. return true;
  1307. // a path starting with / or \ is absolute; anything else is relative
  1308. return ( $path[0] == '/' || $path[0] == '\\' );
  1309. }
  1310. /**
  1311. * Join two filesystem paths together (e.g. 'give me $path relative to $base').
  1312. *
  1313. * If the $path is absolute, then it the full path is returned.
  1314. *
  1315. * @since 2.5.0
  1316. *
  1317. * @param string $base
  1318. * @param string $path
  1319. * @return string The path with the base or absolute path.
  1320. */
  1321. function path_join( $base, $path ) {
  1322. if ( path_is_absolute($path) )
  1323. return $path;
  1324. return rtrim($base, '/') . '/' . ltrim($path, '/');
  1325. }
  1326. /**
  1327. * Normalize a filesystem path.
  1328. *
  1329. * Replaces backslashes with forward slashes for Windows systems,
  1330. * and ensures no duplicate slashes exist.
  1331. *
  1332. * @since 3.9.0
  1333. *
  1334. * @param string $path Path to normalize.
  1335. * @return string Normalized path.
  1336. */
  1337. function wp_normalize_path( $path ) {
  1338. $path = str_replace( '\\', '/', $path );
  1339. $path = preg_replace( '|/+|','/', $path );
  1340. return $path;
  1341. }
  1342. /**
  1343. * Determines a writable directory for temporary files.
  1344. * Function's preference is the return value of <code>sys_get_temp_dir()</code>,
  1345. * followed by your PHP temporary upload directory, followed by WP_CONTENT_DIR,
  1346. * before finally defaulting to /tmp/
  1347. *
  1348. * In the event that this function does not find a writable location,
  1349. * It may be overridden by the <code>WP_TEMP_DIR</code> constant in
  1350. * your <code>wp-config.php</code> file.
  1351. *
  1352. * @since 2.5.0
  1353. *
  1354. * @return string Writable temporary directory
  1355. */
  1356. function get_temp_dir() {
  1357. static $temp;
  1358. if ( defined('WP_TEMP_DIR') )
  1359. return trailingslashit(WP_TEMP_DIR);
  1360. if ( $temp )
  1361. return trailingslashit( $temp );
  1362. if ( function_exists('sys_get_temp_dir') ) {
  1363. $temp = sys_get_temp_dir();
  1364. if ( @is_dir( $temp ) && wp_is_writable( $temp ) )
  1365. return trailingslashit( $temp );
  1366. }
  1367. $temp = ini_get('upload_tmp_dir');
  1368. if ( @is_dir( $temp ) && wp_is_writable( $temp ) )
  1369. return trailingslashit( $temp );
  1370. $temp = WP_CONTENT_DIR . '/';
  1371. if ( is_dir( $temp ) && wp_is_writable( $temp ) )
  1372. return $temp;
  1373. $temp = '/tmp/';
  1374. return $temp;
  1375. }
  1376. /**
  1377. * Determine if a directory is writable.
  1378. *
  1379. * This function is used to work around certain ACL issues
  1380. * in PHP primarily affecting Windows Servers.
  1381. *
  1382. * @see win_is_writable()
  1383. *
  1384. * @since 3.6.0
  1385. *
  1386. * @param string $path
  1387. * @return bool
  1388. */
  1389. function wp_is_writable( $path ) {
  1390. if ( 'WIN' === strtoupper( substr( PHP_OS, 0, 3 ) ) )
  1391. return win_is_writable( $path );
  1392. else
  1393. return @is_writable( $path );
  1394. }
  1395. /**
  1396. * Workaround for Windows bug in is_writable() function
  1397. *
  1398. * PHP has issues with Windows ACL's for determine if a
  1399. * directory is writable or not, this works around them by
  1400. * checking the ability to open files rather than relying
  1401. * upon PHP to interprate the OS ACL.
  1402. *
  1403. * @link http://bugs.php.net/bug.php?id=27609
  1404. * @link http://bugs.php.net/bug.php?id=30931
  1405. *
  1406. * @since 2.8.0
  1407. *
  1408. * @param string $path
  1409. * @return bool
  1410. */
  1411. function win_is_writable( $path ) {
  1412. if ( $path[strlen( $path ) - 1] == '/' ) // if it looks like a directory, check a random file within the directory
  1413. return win_is_writable( $path . uniqid( mt_rand() ) . '.tmp');
  1414. else if ( is_dir( $path ) ) // If it's a directory (and not a file) check a random file within the directory
  1415. return win_is_writable( $path . '/' . uniqid( mt_rand() ) . '.tmp' );
  1416. // check tmp file for read/write capabilities
  1417. $should_delete_tmp_file = !file_exists( $path );
  1418. $f = @fopen( $path, 'a' );
  1419. if ( $f === false )
  1420. return false;
  1421. fclose( $f );
  1422. if ( $should_delete_tmp_file )
  1423. unlink( $path );
  1424. return true;
  1425. }
  1426. /**
  1427. * Get an array containing the current upload directory's path and url.
  1428. *
  1429. * Checks the 'upload_path' option, which should be from the web root folder,
  1430. * and if it isn't empty it will be used. If it is empty, then the path will be
  1431. * 'WP_CONTENT_DIR/uploads'. If the 'UPLOADS' constant is defined, then it will
  1432. * override the 'upload_path' option and 'WP_CONTENT_DIR/uploads' path.
  1433. *
  1434. * The upload URL path is set either by the 'upload_url_path' option or by using
  1435. * the 'WP_CONTENT_URL' constant and appending '/uploads' to the path.
  1436. *
  1437. * If the 'uploads_use_yearmonth_folders' is set to true (checkbox if checked in
  1438. * the administration settings panel), then the time will be used. The format
  1439. * will be year first and then month.
  1440. *
  1441. * If the path couldn't be created, then an error will be returned with the key
  1442. * 'error' containing the error message. The error suggests that the parent
  1443. * directory is not writable by the server.
  1444. *
  1445. * On success, the returned array will have many indices:
  1446. * 'path' - base directory and sub directory or full path to upload directory.
  1447. * 'url' - base url and sub directory or absolute URL to upload directory.
  1448. * 'subdir' - sub directory if uploads use year/month folders option is on.
  1449. * 'basedir' - path without subdir.
  1450. * 'baseurl' - URL path without subdir.
  1451. * 'error' - set to false.
  1452. *
  1453. * @since 2.0.0
  1454. *
  1455. * @param string $time Optional. Time formatted in 'yyyy/mm'.
  1456. * @return array See above for description.
  1457. */
  1458. function wp_upload_dir( $time = null ) {
  1459. $siteurl = get_option( 'siteurl' );
  1460. $upload_path = trim( get_option( 'upload_path' ) );
  1461. if ( empty( $upload_path ) || 'wp-content/uploads' == $upload_path ) {
  1462. $dir = WP_CONTENT_DIR . '/uploads';
  1463. } elseif ( 0 !== strpos( $upload_path, ABSPATH ) ) {
  1464. // $dir is absolute, $upload_path is (maybe) relative to ABSPATH
  1465. $dir = path_join( ABSPATH, $upload_path );
  1466. } else {
  1467. $dir = $upload_path;
  1468. }
  1469. if ( !$url = get_option( 'upload_url_path' ) ) {
  1470. if ( empty($upload_path) || ( 'wp-content/uploads' == $upload_path ) || ( $upload_path == $dir ) )
  1471. $url = WP_CONTENT_URL . '/uploads';
  1472. else
  1473. $url = trailingslashit( $siteurl ) . $upload_path;
  1474. }
  1475. // Obey the value of UPLOADS. This happens as long as ms-files rewriting is disabled.
  1476. // We also sometimes obey UPLOADS when rewriting is enabled -- see the next block.
  1477. if ( defined( 'UPLOADS' ) && ! ( is_multisite() && get_site_option( 'ms_files_rewriting' ) ) ) {
  1478. $dir = ABSPATH . UPLOADS;
  1479. $url = trailingslashit( $siteurl ) . UPLOADS;
  1480. }
  1481. // If multisite (and if not the main site in a post-MU network)
  1482. if ( is_multisite() && ! ( is_main_network() && is_main_site() && defined( 'MULTISITE' ) ) ) {
  1483. if ( ! get_site_option( 'ms_files_rewriting' ) ) {
  1484. // If ms-files rewriting is disabled (networks created post-3.5), it is fairly straightforward:
  1485. // Append sites/%d if we're not on the main site (for post-MU networks). (The extra directory
  1486. // prevents a four-digit ID from conflicting with a year-based directory for the main site.
  1487. // But if a MU-era network has disabled ms-files rewriting manually, they don't need the extra
  1488. // directory, as they never had wp-content/uploads for the main site.)
  1489. if ( defined( 'MULTISITE' ) )
  1490. $ms_dir = '/sites/' . get_current_blog_id();
  1491. else
  1492. $ms_dir = '/' . get_current_blog_id();
  1493. $dir .= $ms_dir;
  1494. $url .= $ms_dir;
  1495. } elseif ( defined( 'UPLOADS' ) && ! ms_is_switched() ) {
  1496. // Handle the old-form ms-files.php rewriting if the network still has that enabled.
  1497. // When ms-files rewriting is enabled, then we only listen to UPLOADS when:
  1498. // 1) we are not on the main site in a post-MU network,
  1499. // as wp-content/uploads is used there, and
  1500. // 2) we are not switched, as ms_upload_constants() hardcodes
  1501. // these constants to reflect the original blog ID.
  1502. //
  1503. // Rather than UPLOADS, we actually use BLOGUPLOADDIR if it is set, as it is absolute.
  1504. // (And it will be set, see ms_upload_constants().) Otherwise, UPLOADS can be used, as
  1505. // as it is relative to ABSPATH. For the final piece: when UPLOADS is used with ms-files
  1506. // rewriting in multisite, the resulting URL is /files. (#WP22702 for background.)
  1507. if ( defined( 'BLOGUPLOADDIR' ) )
  1508. $dir = untrailingslashit( BLOGUPLOADDIR );
  1509. else
  1510. $dir = ABSPATH . UPLOADS;
  1511. $url = trailingslashit( $siteurl ) . 'files';
  1512. }
  1513. }
  1514. $basedir = $dir;
  1515. $baseurl = $url;
  1516. $subdir = '';
  1517. if ( get_option( 'uploads_use_yearmonth_folders' ) ) {
  1518. // Generate the yearly and monthly dirs
  1519. if ( !$time )
  1520. $time = current_time( 'mysql' );
  1521. $y = substr( $time, 0, 4 );
  1522. $m = substr( $time, 5, 2 );
  1523. $subdir = "/$y/$m";
  1524. }
  1525. $dir .= $subdir;
  1526. $url .= $subdir;
  1527. /**
  1528. * Filter the uploads directory data.
  1529. *
  1530. * @since 2.0.0
  1531. *
  1532. * @param array $uploads Array of upload directory data with keys of 'path',
  1533. * 'url', 'subdir, 'basedir', and 'error'.
  1534. */
  1535. $uploads = apply_filters( 'upload_dir',
  1536. array(
  1537. 'path' => $dir,
  1538. 'url' => $url,
  1539. 'subdir' => $subdir,
  1540. 'basedir' => $basedir,
  1541. 'baseurl' => $baseurl,
  1542. 'error' => false,
  1543. ) );
  1544. // Make sure we have an uploads dir
  1545. if ( ! wp_mkdir_p( $uploads['path'] ) ) {
  1546. if ( 0 === strpos( $uploads['basedir'], ABSPATH ) )
  1547. $error_path = str_replace( ABSPATH, '', $uploads['basedir'] ) . $uploads['subdir'];
  1548. else
  1549. $error_path = basename( $uploads['basedir'] ) . $uploads['subdir'];
  1550. $message = sprintf( __( 'Unable to create directory %s. Is its parent directory writable by the server?' ), $error_path );
  1551. $uploads['error'] = $message;
  1552. }
  1553. return $uploads;
  1554. }
  1555. /**
  1556. * Get a filename that is sanitized and unique for the given directory.
  1557. *
  1558. * If the filename is not unique, then a number will be added to the filename
  1559. * before the extension, and will continue adding numbers until the filename is
  1560. * unique.
  1561. *
  1562. * The callback is passed three parameters, the first one is the directory, the
  1563. * second is the filename, and the third is the extension.
  1564. *
  1565. * @since 2.5.0
  1566. *
  1567. * @param string $dir
  1568. * @param string $filename
  1569. * @param mixed $unique_filename_callback Callback.
  1570. * @return string New filename, if given wasn't unique.
  1571. */
  1572. function wp_unique_filename( $dir, $filename, $unique_filename_callback = null ) {
  1573. // sanitize the file name before we begin processing
  1574. $filename = sanitize_file_name($filename);
  1575. // separate the filename into a name and extension
  1576. $info = pathinfo($filename);
  1577. $ext = !empty($info['extension']) ? '.' . $info['extension'] : '';
  1578. $name = basename($filename, $ext);
  1579. // edge case: if file is named '.ext', treat as an empty name
  1580. if ( $name === $ext )
  1581. $name = '';
  1582. // Increment the file number until we have a unique file to save in $dir. Use callback if supplied.
  1583. if ( $unique_filename_callback && is_callable( $unique_filename_callback ) ) {
  1584. $filename = call_user_func( $unique_filename_callback, $dir, $name, $ext );
  1585. } else {
  1586. $number = '';
  1587. // change '.ext' to lower case
  1588. if ( $ext && strtolower($ext) != $ext ) {
  1589. $ext2 = strtolower($ext);
  1590. $filename2 = preg_replace( '|' . preg_quote($ext) . '$|', $ext2, $filename );
  1591. // check for both lower and upper case extension or image sub-sizes may be overwritten
  1592. while ( file_exists($dir . "/$filename") || file_exists($dir . "/$filename2") ) {
  1593. $new_number = $number + 1;
  1594. $filename = str_replace( "$number$ext", "$new_number$ext", $filename );
  1595. $filename2 = str_replace( "$number$ext2", "$new_number$ext2", $filename2 );
  1596. $number = $new_number;
  1597. }
  1598. return $filename2;
  1599. }
  1600. while ( file_exists( $dir . "/$filename" ) ) {
  1601. if ( '' == "$number$ext" )
  1602. $filename = $filename . ++$number . $ext;
  1603. else
  1604. $filename = str_replace( "$number$ext", ++$number . $ext, $filename );
  1605. }
  1606. }
  1607. return $filename;
  1608. }
  1609. /**
  1610. * Create a file in the upload folder with given content.
  1611. *
  1612. * If there is an error, then the key 'error' will exist with the error message.
  1613. * If success, then the key 'file' will have the unique file path, the 'url' key
  1614. * will have the link to the new file. and the 'error' key will be set to false.
  1615. *
  1616. * This function will not move an uploaded file to the upload folder. It will
  1617. * create a new file with the content in $bits parameter. If you move the upload
  1618. * file, read the content of the uploaded file, and then you can give the
  1619. * filename and content to this function, which will add it to the upload
  1620. * folder.
  1621. *
  1622. * The permissions will be set on the new file automatically by this function.
  1623. *
  1624. * @since 2.0.0
  1625. *
  1626. * @param string $name
  1627. * @param null $deprecated Never used. Set to null.
  1628. * @param mixed $bits File content
  1629. * @param string $time Optional. Time formatted in 'yyyy/mm'.
  1630. * @return array
  1631. */
  1632. function wp_upload_bits( $name, $deprecated, $bits, $time = null ) {
  1633. if ( !empty( $deprecated ) )
  1634. _deprecated_argument( __FUNCTION__, '2.0' );
  1635. if ( empty( $name ) )
  1636. return array( 'error' => __( 'Empty filename' ) );
  1637. $wp_filetype = wp_check_filetype( $name );
  1638. if ( ! $wp_filetype['ext'] && ! current_user_can( 'unfiltered_upload' ) )
  1639. return array( 'error' => __( 'Invalid file type' ) );
  1640. $upload = wp_upload_dir( $time );
  1641. if ( $upload['error'] !== false )
  1642. return $upload;
  1643. /**
  1644. * Filter whether to treat the upload bits as an error.
  1645. *
  1646. * Passing a non-array to the filter will effectively short-circuit preparing
  1647. * the upload bits, returning that value instead.
  1648. *
  1649. * @since 3.0.0
  1650. *
  1651. * @param mixed $upload_bits_error An array of upload bits data, or a non-array error to return.
  1652. */
  1653. $upload_bits_error = apply_filters( 'wp_upload_bits', array( 'name' => $name, 'bits' => $bits, 'time' => $time ) );
  1654. if ( !is_array( $upload_bits_error ) ) {
  1655. $upload[ 'error' ] = $upload_bits_error;
  1656. return $upload;
  1657. }
  1658. $filename = wp_unique_filename( $upload['path'], $name );
  1659. $new_file = $upload['path'] . "/$filename";
  1660. if ( ! wp_mkdir_p( dirname( $new_file ) ) ) {
  1661. if ( 0 === strpos( $upload['basedir'], ABSPATH ) )
  1662. $error_path = str_replace( ABSPATH, '', $upload['basedir'] ) . $upload['subdir'];
  1663. else
  1664. $error_path = basename( $upload['basedir'] ) . $upload['subdir'];
  1665. $message = sprintf( __( 'Unable to create directory %s. Is its parent directory writable by the server?' ), $error_path );
  1666. return array( 'error' => $message );
  1667. }
  1668. $ifp = @ fopen( $new_file, 'wb' );
  1669. if ( ! $ifp )
  1670. return array( 'error' => sprintf( __( 'Could not write file %s' ), $new_file ) );
  1671. @fwrite( $ifp, $bits );
  1672. fclose( $ifp );
  1673. clearstatcache();
  1674. // Set correct file permissions
  1675. $stat = @ stat( dirname( $new_file ) );
  1676. $perms = $stat['mode'] & 0007777;
  1677. $perms = $perms & 0000666;
  1678. @ chmod( $new_file, $perms );
  1679. clearstatcache();
  1680. // Compute the URL
  1681. $url = $upload['url'] . "/$filename";
  1682. return array( 'file' => $new_file, 'url' => $url, 'error' => false );
  1683. }
  1684. /**
  1685. * Retrieve the file type based on the extension name.
  1686. *
  1687. * @since 2.5.0
  1688. *
  1689. * @param string $ext The extension to search.
  1690. * @return string|null The file type, example: audio, video, document, spreadsheet, etc.
  1691. * Null if not found.
  1692. */
  1693. function wp_ext2type( $ext ) {
  1694. $ext = strtolower( $ext );
  1695. /**
  1696. * Filter file type based on the extension name.
  1697. *
  1698. * @since 2.5.0
  1699. *
  1700. * @see wp_ext2type()
  1701. *
  1702. * @param array $ext2type Multi-dimensional array with extensions for a default set
  1703. * of file types.
  1704. */
  1705. $ext2type = apply_filters( 'ext2type', array(
  1706. 'image' => array( 'jpg', 'jpeg', 'jpe', 'gif', 'png', 'bmp', 'tif', 'tiff', 'ico' ),
  1707. 'audio' => array( 'aac', 'ac3', 'aif', 'aiff', 'm3a', 'm4a', 'm4b', 'mka', 'mp1', 'mp2', 'mp3', 'ogg', 'oga', 'ram', 'wav', 'wma' ),
  1708. 'video' => array( 'asf', 'avi', 'divx', 'dv', 'flv', 'm4v', 'mkv', 'mov', 'mp4', 'mpeg', 'mpg', 'mpv', 'ogm', 'ogv', 'qt', 'rm', 'vob', 'wmv' ),
  1709. 'document' => array( 'doc', 'docx', 'docm', 'dotm', 'odt', 'pages', 'pdf', 'xps', 'oxps', 'rtf', 'wp', 'wpd' ),
  1710. 'spreadsheet' => array( 'numbers', 'ods', 'xls', 'xlsx', 'xlsm', 'xlsb' ),
  1711. 'interactive' => array( 'swf', 'key', 'ppt', 'pptx', 'pptm', 'pps', 'ppsx', 'ppsm', 'sldx', 'sldm', 'odp' ),
  1712. 'text' => array( 'asc', 'csv', 'tsv', 'txt' ),
  1713. 'archive' => array( 'bz2', 'cab', 'dmg', 'gz', 'rar', 'sea', 'sit', 'sqx', 'tar', 'tgz', 'zip', '7z' ),
  1714. 'code' => array( 'css', 'htm', 'html', 'php', 'js' ),
  1715. ) );
  1716. foreach ( $ext2type as $type => $exts )
  1717. if ( in_array( $ext, $exts ) )
  1718. return $type;
  1719. return null;
  1720. }
  1721. /**
  1722. * Retrieve the file type from the file name.
  1723. *
  1724. * You can optionally define the mime array, if needed.
  1725. *
  1726. * @since 2.0.4
  1727. *
  1728. * @param string $filename File name or path.
  1729. * @param array $mimes Optional. Key is the file extension with value as the mime type.
  1730. * @return array Values with extension first and mime type.
  1731. */
  1732. function wp_check_filetype( $filename, $mimes = null ) {
  1733. if ( empty($mimes) )
  1734. $mimes = get_allowed_mime_types();
  1735. $type = false;
  1736. $ext = false;
  1737. foreach ( $mimes as $ext_preg => $mime_match ) {
  1738. $ext_preg = '!\.(' . $ext_preg . ')$!i';
  1739. if ( preg_match( $ext_preg, $filename, $ext_matches ) ) {
  1740. $type = $mime_match;
  1741. $ext = $ext_matches[1];
  1742. break;
  1743. }
  1744. }
  1745. return compact( 'ext', 'type' );
  1746. }
  1747. /**
  1748. * Attempt to determine the real file type of a file.
  1749. * If unable to, the file name extension will be used to determine type.
  1750. *
  1751. * If it's determined that the extension does not match the file's real type,
  1752. * then the "proper_filename" value will be set with a proper filename and extension.
  1753. *
  1754. * Currently this function only supports validating images known to getimagesize().
  1755. *
  1756. * @since 3.0.0
  1757. *
  1758. * @param string $file Full path to the file.
  1759. * @param string $filename The name of the file (may differ from $file due to $file being in a tmp directory)
  1760. * @param array $mimes Optional. Key is the file extension with value as the mime type.
  1761. * @return array Values for the extension, MIME, and either a corrected filename or false if original $filename is valid
  1762. */
  1763. function wp_check_filetype_and_ext( $file, $filename, $mimes = null ) {
  1764. $proper_filename = false;
  1765. // Do basic extension validation and MIME mapping
  1766. $wp_filetype = wp_check_filetype( $filename, $mimes );
  1767. $ext = $wp_filetype['ext'];
  1768. $type = $wp_filetype['type'];
  1769. // We can't do any further validation without a file to work with
  1770. if ( ! file_exists( $file ) ) {
  1771. return compact( 'ext', 'type', 'proper_filename' );
  1772. }
  1773. // We're able to validate images using GD
  1774. if ( $type && 0 === strpos( $type, 'image/' ) && function_exists('getimagesize') ) {
  1775. // Attempt to figure out what type of image it actually is
  1776. $imgstats = @getimagesize( $file );
  1777. // If getimagesize() knows what kind of image it really is and if the real MIME doesn't match the claimed MIME
  1778. if ( !empty($imgstats['mime']) && $imgstats['mime'] != $type ) {
  1779. /**
  1780. * Filter the list mapping image mime types to their respective extensions.
  1781. *
  1782. * @since 3.0.0
  1783. *
  1784. * @param array $mime_to_ext Array of image mime types and their matching extensions.
  1785. */
  1786. $mime_to_ext = apply_filters( 'getimagesize_mimes_to_exts', array(
  1787. 'image/jpeg' => 'jpg',
  1788. 'image/png' => 'png',
  1789. 'image/gif' => 'gif',
  1790. 'image/bmp' => 'bmp',
  1791. 'image/tiff' => 'tif',
  1792. ) );
  1793. // Replace whatever is after the last period in the filename with the correct extension
  1794. if ( ! empty( $mime_to_ext[ $imgstats['mime'] ] ) ) {
  1795. $filename_parts = explode( '.', $filename );
  1796. array_pop( $filename_parts );
  1797. $filename_parts[] = $mime_to_ext[ $imgstats['mime'] ];
  1798. $new_filename = implode( '.', $filename_parts );
  1799. if ( $new_filename != $filename ) {
  1800. $proper_filename = $new_filename; // Mark that it changed
  1801. }
  1802. // Redefine the extension / MIME
  1803. $wp_filetype = wp_check_filetype( $new_filename, $mimes );
  1804. $ext = $wp_filetype['ext'];
  1805. $type = $wp_filetype['type'];
  1806. }
  1807. }
  1808. }
  1809. /**
  1810. * Filter the "real" file type of the given file.
  1811. *
  1812. * @since 3.0.0
  1813. *
  1814. * @param array $wp_check_filetype_and_ext File data array containing 'ext', 'type', and
  1815. * 'proper_filename' keys.
  1816. * @param string $file Full path to the file.
  1817. * @param string $filename The name of the file (may differ from $file due to
  1818. * $file being in a tmp directory).
  1819. * @param array $mimes Key is the file extension with value as the mime type.
  1820. */
  1821. return apply_filters( 'wp_check_filetype_and_ext', compact( 'ext', 'type', 'proper_filename' ), $file, $filename, $mimes );
  1822. }
  1823. /**
  1824. * Retrieve list of mime types and file extensions.
  1825. *
  1826. * @since 3.5.0
  1827. *
  1828. * @return array Array of mime types keyed by the file extension regex corresponding to those types.
  1829. */
  1830. function wp_get_mime_types() {
  1831. /**
  1832. * Filter the list of mime types and file extensions.
  1833. *
  1834. * This filter should be used to add, not remove, mime types. To remove
  1835. * mime types, use the 'upload_mimes' filter.
  1836. *
  1837. * @since 3.5.0
  1838. *
  1839. * @param array $wp_get_mime_types Mime types keyed by the file extension regex
  1840. * corresponding to those types.
  1841. */
  1842. return apply_filters( 'mime_types', array(
  1843. // Image formats
  1844. 'jpg|jpeg|jpe' => 'image/jpeg',
  1845. 'gif' => 'image/gif',
  1846. 'png' => 'image/png',
  1847. 'bmp' => 'image/bmp',
  1848. 'tif|tiff' => 'image/tiff',
  1849. 'ico' => 'image/x-icon',
  1850. // Video formats
  1851. 'asf|asx' => 'video/x-ms-asf',
  1852. 'wmv' => 'video/x-ms-wmv',
  1853. 'wmx' => 'video/x-ms-wmx',
  1854. 'wm' => 'video/x-ms-wm',
  1855. 'avi' => 'video/avi',
  1856. 'divx' => 'video/divx',
  1857. 'flv' => 'video/x-flv',
  1858. 'mov|qt' => 'video/quicktime',
  1859. 'mpeg|mpg|mpe' => 'video/mpeg',
  1860. 'mp4|m4v' => 'video/mp4',
  1861. 'ogv' => 'video/ogg',
  1862. 'webm' => 'video/webm',
  1863. 'mkv' => 'video/x-matroska',
  1864. // Text formats
  1865. 'txt|asc|c|cc|h|srt' => 'text/plain',
  1866. 'csv' => 'text/csv',
  1867. 'tsv' => 'text/tab-separated-values',
  1868. 'ics' => 'text/calendar',
  1869. 'rtx' => 'text/richtext',
  1870. 'css' => 'text/css',
  1871. 'htm|html' => 'text/html',
  1872. 'vtt' => 'text/vtt',
  1873. 'dfxp' => 'application/ttaf+xml',
  1874. // Audio formats
  1875. 'mp3|m4a|m4b' => 'audio/mpeg',
  1876. 'ra|ram' => 'audio/x-realaudio',
  1877. 'wav' => 'audio/wav',
  1878. 'ogg|oga' => 'audio/ogg',
  1879. 'mid|midi' => 'audio/midi',
  1880. 'wma' => 'audio/x-ms-wma',
  1881. 'wax' => 'audio/x-ms-wax',
  1882. 'mka' => 'audio/x-matroska',
  1883. // Misc application formats
  1884. 'rtf' => 'application/rtf',
  1885. 'js' => 'application/javascript',
  1886. 'pdf' => 'application/pdf',
  1887. 'swf' => 'application/x-shockwave-flash',
  1888. 'class' => 'application/java',
  1889. 'tar' => 'application/x-tar',
  1890. 'zip' => 'application/zip',
  1891. 'gz|gzip' => 'application/x-gzip',
  1892. 'rar' => 'application/rar',
  1893. '7z' => 'application/x-7z-compressed',
  1894. 'exe' => 'application/x-msdownload',
  1895. // MS Office formats
  1896. 'doc' => 'application/msword',
  1897. 'pot|pps|ppt' => 'application/vnd.ms-powerpoint',
  1898. 'wri' => 'application/vnd.ms-write',
  1899. 'xla|xls|xlt|xlw' => 'application/vnd.ms-excel',
  1900. 'mdb' => 'application/vnd.ms-access',
  1901. 'mpp' => 'application/vnd.ms-project',
  1902. 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  1903. 'docm' => 'application/vnd.ms-word.document.macroEnabled.12',
  1904. 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
  1905. 'dotm' => 'application/vnd.ms-word.template.macroEnabled.12',
  1906. 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  1907. 'xlsm' => 'application/vnd.ms-excel.sheet.macroEnabled.12',
  1908. 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
  1909. 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
  1910. 'xltm' => 'application/vnd.ms-excel.template.macroEnabled.12',
  1911. 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
  1912. 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  1913. 'pptm' => 'application/vnd.ms-powerpoint.presentation.macroEnabled.12',
  1914. 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
  1915. 'ppsm' => 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12',
  1916. 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
  1917. 'potm' => 'application/vnd.ms-powerpoint.template.macroEnabled.12',
  1918. 'ppam' => 'application/vnd.ms-powerpoint.addin.macroEnabled.12',
  1919. 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
  1920. 'sldm' => 'application/vnd.ms-powerpoint.slide.macroEnabled.12',
  1921. 'onetoc|onetoc2|onetmp|onepkg' => 'application/onenote',
  1922. 'oxps' => 'application/oxps',
  1923. 'xps' => 'application/vnd.ms-xpsdocument',
  1924. // OpenOffice formats
  1925. 'odt' => 'application/vnd.oasis.opendocument.text',
  1926. 'odp' => 'application/vnd.oasis.opendocument.presentation',
  1927. 'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
  1928. 'odg' => 'application/vnd.oasis.opendocument.graphics',
  1929. 'odc' => 'application/vnd.oasis.opendocument.chart',
  1930. 'odb' => 'application/vnd.oasis.opendocument.database',
  1931. 'odf' => 'application/vnd.oasis.opendocument.formula',
  1932. // WordPerfect formats
  1933. 'wp|wpd' => 'application/wordperfect',
  1934. // iWork formats
  1935. 'key' => 'application/vnd.apple.keynote',
  1936. 'numbers' => 'application/vnd.apple.numbers',
  1937. 'pages' => 'application/vnd.apple.pages',
  1938. ) );
  1939. }
  1940. /**
  1941. * Retrieve list of allowed mime types and file extensions.
  1942. *
  1943. * @since 2.8.6
  1944. *
  1945. * @uses wp_get_upload_mime_types() to fetch the list of mime types
  1946. *
  1947. * @param int|WP_User $user Optional. User to check. Defaults to current user.
  1948. * @return array Array of mime types keyed by the file extension regex corresponding to those types.
  1949. */
  1950. function get_allowed_mime_types( $user = null ) {
  1951. $t = wp_get_mime_types();
  1952. unset( $t['swf'], $t['exe'] );
  1953. if ( function_exists( 'current_user_can' ) )
  1954. $unfiltered = $user ? user_can( $user, 'unfiltered_html' ) : current_user_can( 'unfiltered_html' );
  1955. if ( empty( $unfiltered ) )
  1956. unset( $t['htm|html'] );
  1957. /**
  1958. * Filter list of allowed mime types and file extensions.
  1959. *
  1960. * @since 2.0.0
  1961. *
  1962. * @param array $t Mime types keyed by the file extension regex corresponding to
  1963. * those types. 'swf' and 'exe' removed from full list. 'htm|html' also
  1964. * removed depending on '$user' capabilities.
  1965. * @param int|WP_User|null $user User ID, User object or null if not provided (indicates current user).
  1966. */
  1967. return apply_filters( 'upload_mimes', $t, $user );
  1968. }
  1969. /**
  1970. * Display "Are You Sure" message to confirm the action being taken.
  1971. *
  1972. * If the action has the nonce explain message, then it will be displayed along
  1973. * with the "Are you sure?" message.
  1974. *
  1975. * @since 2.0.4
  1976. *
  1977. * @param string $action The nonce action.
  1978. */
  1979. function wp_nonce_ays( $action ) {
  1980. $title = __( 'WordPress Failure Notice' );
  1981. if ( 'log-out' == $action ) {
  1982. $html = sprintf( __( 'You are attempting to log out of %s' ), get_bloginfo( 'name' ) ) . '</p><p>';
  1983. $redirect_to = isset( $_REQUEST['redirect_to'] ) ? $_REQUEST['redirect_to'] : '';
  1984. $html .= sprintf( __( "Do you really want to <a href='%s'>log out</a>?"), wp_logout_url( $redirect_to ) );
  1985. } else {
  1986. $html = __( 'Are you sure you want to do this?' );
  1987. if ( wp_get_referer() )
  1988. $html .= "</p><p><a href='" . esc_url( remove_query_arg( 'updated', wp_get_referer() ) ) . "'>" . __( 'Please try again.' ) . "</a>";
  1989. }
  1990. wp_die( $html, $title, array('response' => 403) );
  1991. }
  1992. /**
  1993. * Kill WordPress execution and display HTML message with error message.
  1994. *
  1995. * This function complements the die() PHP function. The difference is that
  1996. * HTML will be displayed to the user. It is recommended to use this function
  1997. * only, when the execution should not continue any further. It is not
  1998. * recommended to call this function very often and try to handle as many errors
  1999. * as possible silently.
  2000. *
  2001. * @since 2.0.4
  2002. *
  2003. * @param string $message Error message.
  2004. * @param string $title Error title.
  2005. * @param string|array $args Optional arguments to control behavior.
  2006. */
  2007. function wp_die( $message = '', $title = '', $args = array() ) {
  2008. if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
  2009. /**
  2010. * Filter callback for killing WordPress execution for AJAX requests.
  2011. *
  2012. * @since 3.4.0
  2013. *
  2014. * @param callback $function Callback function name.
  2015. */
  2016. $function = apply_filters( 'wp_die_ajax_handler', '_ajax_wp_die_handler' );
  2017. } elseif ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST ) {
  2018. /**
  2019. * Filter callback for killing WordPress execution for XML-RPC requests.
  2020. *
  2021. * @since 3.4.0
  2022. *
  2023. * @param callback $function Callback function name.
  2024. */
  2025. $function = apply_filters( 'wp_die_xmlrpc_handler', '_xmlrpc_wp_die_handler' );
  2026. } else {
  2027. /**
  2028. * Filter callback for killing WordPress execution for all non-AJAX, non-XML-RPC requests.
  2029. *
  2030. * @since 3.0.0
  2031. *
  2032. * @param callback $function Callback function name.
  2033. */
  2034. $function = apply_filters( 'wp_die_handler', '_default_wp_die_handler' );
  2035. }
  2036. call_user_func( $function, $message, $title, $args );
  2037. }
  2038. /**
  2039. * Kill WordPress execution and display HTML message with error message.
  2040. *
  2041. * This is the default handler for wp_die if you want a custom one for your
  2042. * site then you can overload using the wp_die_handler filter in wp_die
  2043. *
  2044. * @since 3.0.0
  2045. * @access private
  2046. *
  2047. * @param string $message Error message.
  2048. * @param string $title Error title.
  2049. * @param string|array $args Optional arguments to control behavior.
  2050. */
  2051. function _default_wp_die_handler( $message, $title = '', $args = array() ) {
  2052. $defaults = array( 'response' => 500 );
  2053. $r = wp_parse_args($args, $defaults);
  2054. $have_gettext = function_exists('__');
  2055. if ( function_exists( 'is_wp_error' ) && is_wp_error( $message ) ) {
  2056. if ( empty( $title ) ) {
  2057. $error_data = $message->get_error_data();
  2058. if ( is_array( $error_data ) && isset( $error_data['title'] ) )
  2059. $title = $error_data['title'];
  2060. }
  2061. $errors = $message->get_error_messages();
  2062. switch ( count( $errors ) ) {
  2063. case 0 :
  2064. $message = '';
  2065. break;
  2066. case 1 :
  2067. $message = "<p>{$errors[0]}</p>";
  2068. break;
  2069. default :
  2070. $message = "<ul>\n\t\t<li>" . join( "</li>\n\t\t<li>", $errors ) . "</li>\n\t</ul>";
  2071. break;
  2072. }
  2073. } elseif ( is_string( $message ) ) {
  2074. $message = "<p>$message</p>";
  2075. }
  2076. if ( isset( $r['back_link'] ) && $r['back_link'] ) {
  2077. $back_text = $have_gettext? __('&laquo; Back') : '&laquo; Back';
  2078. $message .= "\n<p><a href='javascript:history.back()'>$back_text</a></p>";
  2079. }
  2080. if ( ! did_action( 'admin_head' ) ) :
  2081. if ( !headers_sent() ) {
  2082. status_header( $r['response'] );
  2083. nocache_headers();
  2084. header( 'Content-Type: text/html; charset=utf-8' );
  2085. }
  2086. if ( empty($title) )
  2087. $title = $have_gettext ? __('WordPress &rsaquo; Error') : 'WordPress &rsaquo; Error';
  2088. $text_direction = 'ltr';
  2089. if ( isset($r['text_direction']) && 'rtl' == $r['text_direction'] )
  2090. $text_direction = 'rtl';
  2091. elseif ( function_exists( 'is_rtl' ) && is_rtl() )
  2092. $text_direction = 'rtl';
  2093. ?>
  2094. <!DOCTYPE html>
  2095. <!-- 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
  2096. -->
  2097. <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'"; ?>>
  2098. <head>
  2099. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  2100. <title><?php echo $title ?></title>
  2101. <style type="text/css">
  2102. html {
  2103. background: #f1f1f1;
  2104. }
  2105. body {
  2106. background: #fff;
  2107. color: #444;
  2108. font-family: "Open Sans", sans-serif;
  2109. margin: 2em auto;
  2110. padding: 1em 2em;
  2111. max-width: 700px;
  2112. -webkit-box-shadow: 0 1px 3px rgba(0,0,0,0.13);
  2113. box-shadow: 0 1px 3px rgba(0,0,0,0.13);
  2114. }
  2115. h1 {
  2116. border-bottom: 1px solid #dadada;
  2117. clear: both;
  2118. color: #666;
  2119. font: 24px "Open Sans", sans-serif;
  2120. margin: 30px 0 0 0;
  2121. padding: 0;
  2122. padding-bottom: 7px;
  2123. }
  2124. #error-page {
  2125. margin-top: 50px;
  2126. }
  2127. #error-page p {
  2128. font-size: 14px;
  2129. line-height: 1.5;
  2130. margin: 25px 0 20px;
  2131. }
  2132. #error-page code {
  2133. font-family: Consolas, Monaco, monospace;
  2134. }
  2135. ul li {
  2136. margin-bottom: 10px;
  2137. font-size: 14px ;
  2138. }
  2139. a {
  2140. color: #21759B;
  2141. text-decoration: none;
  2142. }
  2143. a:hover {
  2144. color: #D54E21;
  2145. }
  2146. .button {
  2147. background: #f7f7f7;
  2148. border: 1px solid #cccccc;
  2149. color: #555;
  2150. display: inline-block;
  2151. text-decoration: none;
  2152. font-size: 13px;
  2153. line-height: 26px;
  2154. height: 28px;
  2155. margin: 0;
  2156. padding: 0 10px 1px;
  2157. cursor: pointer;
  2158. -webkit-border-radius: 3px;
  2159. -webkit-appearance: none;
  2160. border-radius: 3px;
  2161. white-space: nowrap;
  2162. -webkit-box-sizing: border-box;
  2163. -moz-box-sizing: border-box;
  2164. box-sizing: border-box;
  2165. -webkit-box-shadow: inset 0 1px 0 #fff, 0 1px 0 rgba(0,0,0,.08);
  2166. box-shadow: inset 0 1px 0 #fff, 0 1px 0 rgba(0,0,0,.08);
  2167. vertical-align: top;
  2168. }
  2169. .button.button-large {
  2170. height: 29px;
  2171. line-height: 28px;
  2172. padding: 0 12px;
  2173. }
  2174. .button:hover,
  2175. .button:focus {
  2176. background: #fafafa;
  2177. border-color: #999;
  2178. color: #222;
  2179. }
  2180. .button:focus {
  2181. -webkit-box-shadow: 1px 1px 1px rgba(0,0,0,.2);
  2182. box-shadow: 1px 1px 1px rgba(0,0,0,.2);
  2183. }
  2184. .button:active {
  2185. background: #eee;
  2186. border-color: #999;
  2187. color: #333;
  2188. -webkit-box-shadow: inset 0 2px 5px -3px rgba( 0, 0, 0, 0.5 );
  2189. box-shadow: inset 0 2px 5px -3px rgba( 0, 0, 0, 0.5 );
  2190. }
  2191. <?php if ( 'rtl' == $text_direction ) : ?>
  2192. body { font-family: Tahoma, Arial; }
  2193. <?php endif; ?>
  2194. </style>
  2195. </head>
  2196. <body id="error-page">
  2197. <?php endif; // ! did_action( 'admin_head' ) ?>
  2198. <?php echo $message; ?>
  2199. </body>
  2200. </html>
  2201. <?php
  2202. die();
  2203. }
  2204. /**
  2205. * Kill WordPress execution and display XML message with error message.
  2206. *
  2207. * This is the handler for wp_die when processing XMLRPC requests.
  2208. *
  2209. * @since 3.2.0
  2210. * @access private
  2211. *
  2212. * @param string $message Error message.
  2213. * @param string $title Error title.
  2214. * @param string|array $args Optional arguments to control behavior.
  2215. */
  2216. function _xmlrpc_wp_die_handler( $message, $title = '', $args = array() ) {
  2217. global $wp_xmlrpc_server;
  2218. $defaults = array( 'response' => 500 );
  2219. $r = wp_parse_args($args, $defaults);
  2220. if ( $wp_xmlrpc_server ) {
  2221. $error = new IXR_Error( $r['response'] , $message);
  2222. $wp_xmlrpc_server->output( $error->getXml() );
  2223. }
  2224. die();
  2225. }
  2226. /**
  2227. * Kill WordPress ajax execution.
  2228. *
  2229. * This is the handler for wp_die when processing Ajax requests.
  2230. *
  2231. * @since 3.4.0
  2232. * @access private
  2233. *
  2234. * @param string $message Optional. Response to print.
  2235. */
  2236. function _ajax_wp_die_handler( $message = '' ) {
  2237. if ( is_scalar( $message ) )
  2238. die( (string) $message );
  2239. die( '0' );
  2240. }
  2241. /**
  2242. * Kill WordPress execution.
  2243. *
  2244. * This is the handler for wp_die when processing APP requests.
  2245. *
  2246. * @since 3.4.0
  2247. * @access private
  2248. *
  2249. * @param string $message Optional. Response to print.
  2250. */
  2251. function _scalar_wp_die_handler( $message = '' ) {
  2252. if ( is_scalar( $message ) )
  2253. die( (string) $message );
  2254. die();
  2255. }
  2256. /**
  2257. * Send a JSON response back to an Ajax request.
  2258. *
  2259. * @since 3.5.0
  2260. *
  2261. * @param mixed $response Variable (usually an array or object) to encode as JSON, then print and die.
  2262. */
  2263. function wp_send_json( $response ) {
  2264. @header( 'Content-Type: application/json; charset=' . get_option( 'blog_charset' ) );
  2265. echo json_encode( $response );
  2266. if ( defined( 'DOING_AJAX' ) && DOING_AJAX )
  2267. wp_die();
  2268. else
  2269. die;
  2270. }
  2271. /**
  2272. * Send a JSON response back to an Ajax request, indicating success.
  2273. *
  2274. * @since 3.5.0
  2275. *
  2276. * @param mixed $data Data to encode as JSON, then print and die.
  2277. */
  2278. function wp_send_json_success( $data = null ) {
  2279. $response = array( 'success' => true );
  2280. if ( isset( $data ) )
  2281. $response['data'] = $data;
  2282. wp_send_json( $response );
  2283. }
  2284. /**
  2285. * Send a JSON response back to an Ajax request, indicating failure.
  2286. *
  2287. * @since 3.5.0
  2288. *
  2289. * @param mixed $data Data to encode as JSON, then print and die.
  2290. */
  2291. function wp_send_json_error( $data = null ) {
  2292. $response = array( 'success' => false );
  2293. if ( isset( $data ) )
  2294. $response['data'] = $data;
  2295. wp_send_json( $response );
  2296. }
  2297. /**
  2298. * Retrieve the WordPress home page URL.
  2299. *
  2300. * If the constant named 'WP_HOME' exists, then it will be used and returned by
  2301. * the function. This can be used to counter the redirection on your local
  2302. * development environment.
  2303. *
  2304. * @access private
  2305. * @since 2.2.0
  2306. *
  2307. * @param string $url URL for the home location
  2308. * @return string Homepage location.
  2309. */
  2310. function _config_wp_home( $url = '' ) {
  2311. if ( defined( 'WP_HOME' ) )
  2312. return untrailingslashit( WP_HOME );
  2313. return $url;
  2314. }
  2315. /**
  2316. * Retrieve the WordPress site URL.
  2317. *
  2318. * If the constant named 'WP_SITEURL' is defined, then the value in that
  2319. * constant will always be returned. This can be used for debugging a site on
  2320. * your localhost while not having to change the database to your URL.
  2321. *
  2322. * @access private
  2323. * @since 2.2.0
  2324. *
  2325. * @param string $url URL to set the WordPress site location.
  2326. * @return string The WordPress Site URL
  2327. */
  2328. function _config_wp_siteurl( $url = '' ) {
  2329. if ( defined( 'WP_SITEURL' ) )
  2330. return untrailingslashit( WP_SITEURL );
  2331. return $url;
  2332. }
  2333. /**
  2334. * Set the localized direction for MCE plugin.
  2335. *
  2336. * Will only set the direction to 'rtl', if the WordPress locale has the text
  2337. * direction set to 'rtl'.
  2338. *
  2339. * Fills in the 'directionality' setting, enables the 'directionality' plugin,
  2340. * and adds the 'ltr' button to 'toolbar1', formerly 'theme_advanced_buttons1' array
  2341. * keys. These keys are then returned in the $input (TinyMCE settings) array.
  2342. *
  2343. * @access private
  2344. * @since 2.1.0
  2345. *
  2346. * @param array $input MCE settings array.
  2347. * @return array Direction set for 'rtl', if needed by locale.
  2348. */
  2349. function _mce_set_direction( $input ) {
  2350. if ( is_rtl() ) {
  2351. $input['directionality'] = 'rtl';
  2352. $input['plugins'] .= ',directionality';
  2353. $input['toolbar1'] .= ',ltr';
  2354. }
  2355. return $input;
  2356. }
  2357. /**
  2358. * Convert smiley code to the icon graphic file equivalent.
  2359. *
  2360. * You can turn off smilies, by going to the write setting screen and unchecking
  2361. * the box, or by setting 'use_smilies' option to false or removing the option.
  2362. *
  2363. * Plugins may override the default smiley list by setting the $wpsmiliestrans
  2364. * to an array, with the key the code the blogger types in and the value the
  2365. * image file.
  2366. *
  2367. * The $wp_smiliessearch global is for the regular expression and is set each
  2368. * time the function is called.
  2369. *
  2370. * The full list of smilies can be found in the function and won't be listed in
  2371. * the description. Probably should create a Codex page for it, so that it is
  2372. * available.
  2373. *
  2374. * @global array $wpsmiliestrans
  2375. * @global array $wp_smiliessearch
  2376. * @since 2.2.0
  2377. */
  2378. function smilies_init() {
  2379. global $wpsmiliestrans, $wp_smiliessearch;
  2380. // don't bother setting up smilies if they are disabled
  2381. if ( !get_option( 'use_smilies' ) )
  2382. return;
  2383. if ( !isset( $wpsmiliestrans ) ) {
  2384. $wpsmiliestrans = array(
  2385. ':mrgreen:' => 'icon_mrgreen.gif',
  2386. ':neutral:' => 'icon_neutral.gif',
  2387. ':twisted:' => 'icon_twisted.gif',
  2388. ':arrow:' => 'icon_arrow.gif',
  2389. ':shock:' => 'icon_eek.gif',
  2390. ':smile:' => 'icon_smile.gif',
  2391. ':???:' => 'icon_confused.gif',
  2392. ':cool:' => 'icon_cool.gif',
  2393. ':evil:' => 'icon_evil.gif',
  2394. ':grin:' => 'icon_biggrin.gif',
  2395. ':idea:' => 'icon_idea.gif',
  2396. ':oops:' => 'icon_redface.gif',
  2397. ':razz:' => 'icon_razz.gif',
  2398. ':roll:' => 'icon_rolleyes.gif',
  2399. ':wink:' => 'icon_wink.gif',
  2400. ':cry:' => 'icon_cry.gif',
  2401. ':eek:' => 'icon_surprised.gif',
  2402. ':lol:' => 'icon_lol.gif',
  2403. ':mad:' => 'icon_mad.gif',
  2404. ':sad:' => 'icon_sad.gif',
  2405. '8-)' => 'icon_cool.gif',
  2406. '8-O' => 'icon_eek.gif',
  2407. ':-(' => 'icon_sad.gif',
  2408. ':-)' => 'icon_smile.gif',
  2409. ':-?' => 'icon_confused.gif',
  2410. ':-D' => 'icon_biggrin.gif',
  2411. ':-P' => 'icon_razz.gif',
  2412. ':-o' => 'icon_surprised.gif',
  2413. ':-x' => 'icon_mad.gif',
  2414. ':-|' => 'icon_neutral.gif',
  2415. ';-)' => 'icon_wink.gif',
  2416. // This one transformation breaks regular text with frequency.
  2417. // '8)' => 'icon_cool.gif',
  2418. '8O' => 'icon_eek.gif',
  2419. ':(' => 'icon_sad.gif',
  2420. ':)' => 'icon_smile.gif',
  2421. ':?' => 'icon_confused.gif',
  2422. ':D' => 'icon_biggrin.gif',
  2423. ':P' => 'icon_razz.gif',
  2424. ':o' => 'icon_surprised.gif',
  2425. ':x' => 'icon_mad.gif',
  2426. ':|' => 'icon_neutral.gif',
  2427. ';)' => 'icon_wink.gif',
  2428. ':!:' => 'icon_exclaim.gif',
  2429. ':?:' => 'icon_question.gif',
  2430. );
  2431. }
  2432. if (count($wpsmiliestrans) == 0) {
  2433. return;
  2434. }
  2435. /*
  2436. * NOTE: we sort the smilies in reverse key order. This is to make sure
  2437. * we match the longest possible smilie (:???: vs :?) as the regular
  2438. * expression used below is first-match
  2439. */
  2440. krsort($wpsmiliestrans);
  2441. $wp_smiliessearch = '/((?:\s|^)';
  2442. $subchar = '';
  2443. foreach ( (array) $wpsmiliestrans as $smiley => $img ) {
  2444. $firstchar = substr($smiley, 0, 1);
  2445. $rest = substr($smiley, 1);
  2446. // new subpattern?
  2447. if ($firstchar != $subchar) {
  2448. if ($subchar != '') {
  2449. $wp_smiliessearch .= ')(?=\s|$))|((?:\s|^)'; ;
  2450. }
  2451. $subchar = $firstchar;
  2452. $wp_smiliessearch .= preg_quote($firstchar, '/') . '(?:';
  2453. } else {
  2454. $wp_smiliessearch .= '|';
  2455. }
  2456. $wp_smiliessearch .= preg_quote($rest, '/');
  2457. }
  2458. $wp_smiliessearch .= ')(?=\s|$))/m';
  2459. }
  2460. /**
  2461. * Merge user defined arguments into defaults array.
  2462. *
  2463. * This function is used throughout WordPress to allow for both string or array
  2464. * to be merged into another array.
  2465. *
  2466. * @since 2.2.0
  2467. *
  2468. * @param string|array $args Value to merge with $defaults
  2469. * @param array $defaults Array that serves as the defaults.
  2470. * @return array Merged user defined values with defaults.
  2471. */
  2472. function wp_parse_args( $args, $defaults = '' ) {
  2473. if ( is_object( $args ) )
  2474. $r = get_object_vars( $args );
  2475. elseif ( is_array( $args ) )
  2476. $r =& $args;
  2477. else
  2478. wp_parse_str( $args, $r );
  2479. if ( is_array( $defaults ) )
  2480. return array_merge( $defaults, $r );
  2481. return $r;
  2482. }
  2483. /**
  2484. * Clean up an array, comma- or space-separated list of IDs.
  2485. *
  2486. * @since 3.0.0
  2487. *
  2488. * @param array|string $list
  2489. * @return array Sanitized array of IDs
  2490. */
  2491. function wp_parse_id_list( $list ) {
  2492. if ( !is_array($list) )
  2493. $list = preg_split('/[\s,]+/', $list);
  2494. return array_unique(array_map('absint', $list));
  2495. }
  2496. /**
  2497. * Extract a slice of an array, given a list of keys.
  2498. *
  2499. * @since 3.1.0
  2500. *
  2501. * @param array $array The original array
  2502. * @param array $keys The list of keys
  2503. * @return array The array slice
  2504. */
  2505. function wp_array_slice_assoc( $array, $keys ) {
  2506. $slice = array();
  2507. foreach ( $keys as $key )
  2508. if ( isset( $array[ $key ] ) )
  2509. $slice[ $key ] = $array[ $key ];
  2510. return $slice;
  2511. }
  2512. /**
  2513. * Filters a list of objects, based on a set of key => value arguments.
  2514. *
  2515. * @since 3.0.0
  2516. *
  2517. * @param array $list An array of objects to filter
  2518. * @param array $args An array of key => value arguments to match against each object
  2519. * @param string $operator The logical operation to perform. 'or' means only one element
  2520. * from the array needs to match; 'and' means all elements must match. The default is 'and'.
  2521. * @param bool|string $field A field from the object to place instead of the entire object
  2522. * @return array A list of objects or object fields
  2523. */
  2524. function wp_filter_object_list( $list, $args = array(), $operator = 'and', $field = false ) {
  2525. if ( ! is_array( $list ) )
  2526. return array();
  2527. $list = wp_list_filter( $list, $args, $operator );
  2528. if ( $field )
  2529. $list = wp_list_pluck( $list, $field );
  2530. return $list;
  2531. }
  2532. /**
  2533. * Filters a list of objects, based on a set of key => value arguments.
  2534. *
  2535. * @since 3.1.0
  2536. *
  2537. * @param array $list An array of objects to filter
  2538. * @param array $args An array of key => value arguments to match against each object
  2539. * @param string $operator The logical operation to perform:
  2540. * 'AND' means all elements from the array must match;
  2541. * 'OR' means only one element needs to match;
  2542. * 'NOT' means no elements may match.
  2543. * The default is 'AND'.
  2544. * @return array
  2545. */
  2546. function wp_list_filter( $list, $args = array(), $operator = 'AND' ) {
  2547. if ( ! is_array( $list ) )
  2548. return array();
  2549. if ( empty( $args ) )
  2550. return $list;
  2551. $operator = strtoupper( $operator );
  2552. $count = count( $args );
  2553. $filtered = array();
  2554. foreach ( $list as $key => $obj ) {
  2555. $to_match = (array) $obj;
  2556. $matched = 0;
  2557. foreach ( $args as $m_key => $m_value ) {
  2558. if ( array_key_exists( $m_key, $to_match ) && $m_value == $to_match[ $m_key ] )
  2559. $matched++;
  2560. }
  2561. if ( ( 'AND' == $operator && $matched == $count )
  2562. || ( 'OR' == $operator && $matched > 0 )
  2563. || ( 'NOT' == $operator && 0 == $matched ) ) {
  2564. $filtered[$key] = $obj;
  2565. }
  2566. }
  2567. return $filtered;
  2568. }
  2569. /**
  2570. * Pluck a certain field out of each object in a list.
  2571. *
  2572. * @since 3.1.0
  2573. *
  2574. * @param array $list A list of objects or arrays
  2575. * @param int|string $field A field from the object to place instead of the entire object
  2576. * @return array
  2577. */
  2578. function wp_list_pluck( $list, $field ) {
  2579. foreach ( $list as $key => $value ) {
  2580. if ( is_object( $value ) )
  2581. $list[ $key ] = $value->$field;
  2582. else
  2583. $list[ $key ] = $value[ $field ];
  2584. }
  2585. return $list;
  2586. }
  2587. /**
  2588. * Determines if Widgets library should be loaded.
  2589. *
  2590. * Checks to make sure that the widgets library hasn't already been loaded. If
  2591. * it hasn't, then it will load the widgets library and run an action hook.
  2592. *
  2593. * @since 2.2.0
  2594. * @uses add_action() Calls '_admin_menu' hook with 'wp_widgets_add_menu' value.
  2595. */
  2596. function wp_maybe_load_widgets() {
  2597. /**
  2598. * Filter whether to load the Widgets library.
  2599. *
  2600. * @since 2.8.0
  2601. *
  2602. * @param bool $wp_maybe_load_widgets Whether to load the Widgets library.
  2603. * Default true.
  2604. */
  2605. if ( ! apply_filters( 'load_default_widgets', true ) ) {
  2606. return;
  2607. }
  2608. require_once( ABSPATH . WPINC . '/default-widgets.php' );
  2609. add_action( '_admin_menu', 'wp_widgets_add_menu' );
  2610. }
  2611. /**
  2612. * Append the Widgets menu to the themes main menu.
  2613. *
  2614. * @since 2.2.0
  2615. * @uses $submenu The administration submenu list.
  2616. */
  2617. function wp_widgets_add_menu() {
  2618. global $submenu;
  2619. if ( ! current_theme_supports( 'widgets' ) )
  2620. return;
  2621. $submenu['themes.php'][7] = array( __( 'Widgets' ), 'edit_theme_options', 'widgets.php' );
  2622. ksort( $submenu['themes.php'], SORT_NUMERIC );
  2623. }
  2624. /**
  2625. * Flush all output buffers for PHP 5.2.
  2626. *
  2627. * Make sure all output buffers are flushed before our singletons our destroyed.
  2628. *
  2629. * @since 2.2.0
  2630. */
  2631. function wp_ob_end_flush_all() {
  2632. $levels = ob_get_level();
  2633. for ($i=0; $i<$levels; $i++)
  2634. ob_end_flush();
  2635. }
  2636. /**
  2637. * Load custom DB error or display WordPress DB error.
  2638. *
  2639. * If a file exists in the wp-content directory named db-error.php, then it will
  2640. * be loaded instead of displaying the WordPress DB error. If it is not found,
  2641. * then the WordPress DB error will be displayed instead.
  2642. *
  2643. * The WordPress DB error sets the HTTP status header to 500 to try to prevent
  2644. * search engines from caching the message. Custom DB messages should do the
  2645. * same.
  2646. *
  2647. * This function was backported to WordPress 2.3.2, but originally was added
  2648. * in WordPress 2.5.0.
  2649. *
  2650. * @since 2.3.2
  2651. * @uses $wpdb
  2652. */
  2653. function dead_db() {
  2654. global $wpdb;
  2655. wp_load_translations_early();
  2656. // Load custom DB error template, if present.
  2657. if ( file_exists( WP_CONTENT_DIR . '/db-error.php' ) ) {
  2658. require_once( WP_CONTENT_DIR . '/db-error.php' );
  2659. die();
  2660. }
  2661. // If installing or in the admin, provide the verbose message.
  2662. if ( defined('WP_INSTALLING') || defined('WP_ADMIN') )
  2663. wp_die($wpdb->error);
  2664. // Otherwise, be terse.
  2665. status_header( 500 );
  2666. nocache_headers();
  2667. header( 'Content-Type: text/html; charset=utf-8' );
  2668. ?>
  2669. <!DOCTYPE html>
  2670. <html xmlns="http://www.w3.org/1999/xhtml"<?php if ( is_rtl() ) echo ' dir="rtl"'; ?>>
  2671. <head>
  2672. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  2673. <title><?php _e( 'Database Error' ); ?></title>
  2674. </head>
  2675. <body>
  2676. <h1><?php _e( 'Error establishing a database connection' ); ?></h1>
  2677. </body>
  2678. </html>
  2679. <?php
  2680. die();
  2681. }
  2682. /**
  2683. * Converts value to nonnegative integer.
  2684. *
  2685. * @since 2.5.0
  2686. *
  2687. * @param mixed $maybeint Data you wish to have converted to a nonnegative integer
  2688. * @return int An nonnegative integer
  2689. */
  2690. function absint( $maybeint ) {
  2691. return abs( intval( $maybeint ) );
  2692. }
  2693. /**
  2694. * Determines if the blog can be accessed over SSL.
  2695. *
  2696. * Determines if blog can be accessed over SSL by using cURL to access the site
  2697. * using the https in the siteurl. Requires cURL extension to work correctly.
  2698. *
  2699. * @since 2.5.0
  2700. *
  2701. * @param string $url
  2702. * @return bool Whether SSL access is available
  2703. */
  2704. function url_is_accessable_via_ssl($url)
  2705. {
  2706. if ( in_array( 'curl', get_loaded_extensions() ) ) {
  2707. $ssl = set_url_scheme( $url, 'https' );
  2708. $ch = curl_init();
  2709. curl_setopt($ch, CURLOPT_URL, $ssl);
  2710. curl_setopt($ch, CURLOPT_FAILONERROR, true);
  2711. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  2712. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  2713. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
  2714. curl_exec($ch);
  2715. $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  2716. curl_close ($ch);
  2717. if ($status == 200 || $status == 401) {
  2718. return true;
  2719. }
  2720. }
  2721. return false;
  2722. }
  2723. /**
  2724. * Marks a function as deprecated and informs when it has been used.
  2725. *
  2726. * There is a hook deprecated_function_run that will be called that can be used
  2727. * to get the backtrace up to what file and function called the deprecated
  2728. * function.
  2729. *
  2730. * The current behavior is to trigger a user error if WP_DEBUG is true.
  2731. *
  2732. * This function is to be used in every function that is deprecated.
  2733. *
  2734. * @since 2.5.0
  2735. * @access private
  2736. *
  2737. * @param string $function The function that was called
  2738. * @param string $version The version of WordPress that deprecated the function
  2739. * @param string $replacement Optional. The function that should have been called
  2740. */
  2741. function _deprecated_function( $function, $version, $replacement = null ) {
  2742. /**
  2743. * Fires when a deprecated function is called.
  2744. *
  2745. * @since 2.5.0
  2746. *
  2747. * @param string $function The function that was called.
  2748. * @param string $replacement The function that should have been called.
  2749. * @param string $version The version of WordPress that deprecated the function.
  2750. */
  2751. do_action( 'deprecated_function_run', $function, $replacement, $version );
  2752. /**
  2753. * Filter whether to trigger an error for deprecated functions.
  2754. *
  2755. * @since 2.5.0
  2756. *
  2757. * @param bool $trigger Whether to trigger the error for deprecated functions. Default true.
  2758. */
  2759. if ( WP_DEBUG && apply_filters( 'deprecated_function_trigger_error', true ) ) {
  2760. if ( function_exists( '__' ) ) {
  2761. if ( ! is_null( $replacement ) )
  2762. trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.'), $function, $version, $replacement ) );
  2763. else
  2764. trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.'), $function, $version ) );
  2765. } else {
  2766. if ( ! is_null( $replacement ) )
  2767. trigger_error( sprintf( '%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.', $function, $version, $replacement ) );
  2768. else
  2769. trigger_error( sprintf( '%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.', $function, $version ) );
  2770. }
  2771. }
  2772. }
  2773. /**
  2774. * Marks a file as deprecated and informs when it has been used.
  2775. *
  2776. * There is a hook deprecated_file_included that will be called that can be used
  2777. * to get the backtrace up to what file and function included the deprecated
  2778. * file.
  2779. *
  2780. * The current behavior is to trigger a user error if WP_DEBUG is true.
  2781. *
  2782. * This function is to be used in every file that is deprecated.
  2783. *
  2784. * @since 2.5.0
  2785. * @access private
  2786. *
  2787. * @param string $file The file that was included
  2788. * @param string $version The version of WordPress that deprecated the file
  2789. * @param string $replacement Optional. The file that should have been included based on ABSPATH
  2790. * @param string $message Optional. A message regarding the change
  2791. */
  2792. function _deprecated_file( $file, $version, $replacement = null, $message = '' ) {
  2793. /**
  2794. * Fires when a deprecated file is called.
  2795. *
  2796. * @since 2.5.0
  2797. *
  2798. * @param string $file The file that was called.
  2799. * @param string $replacement The file that should have been included based on ABSPATH.
  2800. * @param string $version The version of WordPress that deprecated the file.
  2801. * @param string $message A message regarding the change.
  2802. */
  2803. do_action( 'deprecated_file_included', $file, $replacement, $version, $message );
  2804. /**
  2805. * Filter whether to trigger an error for deprecated files.
  2806. *
  2807. * @since 2.5.0
  2808. *
  2809. * @param bool $trigger Whether to trigger the error for deprecated files. Default true.
  2810. */
  2811. if ( WP_DEBUG && apply_filters( 'deprecated_file_trigger_error', true ) ) {
  2812. $message = empty( $message ) ? '' : ' ' . $message;
  2813. if ( function_exists( '__' ) ) {
  2814. if ( ! is_null( $replacement ) )
  2815. trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.'), $file, $version, $replacement ) . $message );
  2816. else
  2817. trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.'), $file, $version ) . $message );
  2818. } else {
  2819. if ( ! is_null( $replacement ) )
  2820. trigger_error( sprintf( '%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.', $file, $version, $replacement ) . $message );
  2821. else
  2822. trigger_error( sprintf( '%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.', $file, $version ) . $message );
  2823. }
  2824. }
  2825. }
  2826. /**
  2827. * Marks a function argument as deprecated and informs when it has been used.
  2828. *
  2829. * This function is to be used whenever a deprecated function argument is used.
  2830. * Before this function is called, the argument must be checked for whether it was
  2831. * used by comparing it to its default value or evaluating whether it is empty.
  2832. * For example:
  2833. * <code>
  2834. * if ( !empty($deprecated) )
  2835. * _deprecated_argument( __FUNCTION__, '3.0' );
  2836. * </code>
  2837. *
  2838. * There is a hook deprecated_argument_run that will be called that can be used
  2839. * to get the backtrace up to what file and function used the deprecated
  2840. * argument.
  2841. *
  2842. * The current behavior is to trigger a user error if WP_DEBUG is true.
  2843. *
  2844. * @since 3.0.0
  2845. * @access private
  2846. *
  2847. * @param string $function The function that was called
  2848. * @param string $version The version of WordPress that deprecated the argument used
  2849. * @param string $message Optional. A message regarding the change.
  2850. */
  2851. function _deprecated_argument( $function, $version, $message = null ) {
  2852. /**
  2853. * Fires when a deprecated argument is called.
  2854. *
  2855. * @since 3.0.0
  2856. *
  2857. * @param string $function The function that was called.
  2858. * @param string $message A message regarding the change.
  2859. * @param string $version The version of WordPress that deprecated the argument used.
  2860. */
  2861. do_action( 'deprecated_argument_run', $function, $message, $version );
  2862. /**
  2863. * Filter whether to trigger an error for deprecated arguments.
  2864. *
  2865. * @since 3.0.0
  2866. *
  2867. * @param bool $trigger Whether to trigger the error for deprecated arguments. Default true.
  2868. */
  2869. if ( WP_DEBUG && apply_filters( 'deprecated_argument_trigger_error', true ) ) {
  2870. if ( function_exists( '__' ) ) {
  2871. if ( ! is_null( $message ) )
  2872. trigger_error( sprintf( __('%1$s was called with an argument that is <strong>deprecated</strong> since version %2$s! %3$s'), $function, $version, $message ) );
  2873. else
  2874. 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 ) );
  2875. } else {
  2876. if ( ! is_null( $message ) )
  2877. trigger_error( sprintf( '%1$s was called with an argument that is <strong>deprecated</strong> since version %2$s! %3$s', $function, $version, $message ) );
  2878. else
  2879. 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 ) );
  2880. }
  2881. }
  2882. }
  2883. /**
  2884. * Marks something as being incorrectly called.
  2885. *
  2886. * There is a hook doing_it_wrong_run that will be called that can be used
  2887. * to get the backtrace up to what file and function called the deprecated
  2888. * function.
  2889. *
  2890. * The current behavior is to trigger a user error if WP_DEBUG is true.
  2891. *
  2892. * @since 3.1.0
  2893. * @access private
  2894. *
  2895. * @param string $function The function that was called.
  2896. * @param string $message A message explaining what has been done incorrectly.
  2897. * @param string $version The version of WordPress where the message was added.
  2898. */
  2899. function _doing_it_wrong( $function, $message, $version ) {
  2900. /**
  2901. * Fires when the given function is being used incorrectly.
  2902. *
  2903. * @since 3.1.0
  2904. *
  2905. * @param string $function The function that was called.
  2906. * @param string $message A message explaining what has been done incorrectly.
  2907. * @param string $version The version of WordPress where the message was added.
  2908. */
  2909. do_action( 'doing_it_wrong_run', $function, $message, $version );
  2910. /**
  2911. * Filter whether to trigger an error for _doing_it_wrong() calls.
  2912. *
  2913. * @since 3.1.0
  2914. *
  2915. * @param bool $trigger Whether to trigger the error for _doing_it_wrong() calls. Default true.
  2916. */
  2917. if ( WP_DEBUG && apply_filters( 'doing_it_wrong_trigger_error', true ) ) {
  2918. if ( function_exists( '__' ) ) {
  2919. $version = is_null( $version ) ? '' : sprintf( __( '(This message was added in version %s.)' ), $version );
  2920. $message .= ' ' . __( 'Please see <a href="http://codex.wordpress.org/Debugging_in_WordPress">Debugging in WordPress</a> for more information.' );
  2921. trigger_error( sprintf( __( '%1$s was called <strong>incorrectly</strong>. %2$s %3$s' ), $function, $message, $version ) );
  2922. } else {
  2923. $version = is_null( $version ) ? '' : sprintf( '(This message was added in version %s.)', $version );
  2924. $message .= ' Please see <a href="http://codex.wordpress.org/Debugging_in_WordPress">Debugging in WordPress</a> for more information.';
  2925. trigger_error( sprintf( '%1$s was called <strong>incorrectly</strong>. %2$s %3$s', $function, $message, $version ) );
  2926. }
  2927. }
  2928. }
  2929. /**
  2930. * Is the server running earlier than 1.5.0 version of lighttpd?
  2931. *
  2932. * @since 2.5.0
  2933. *
  2934. * @return bool Whether the server is running lighttpd < 1.5.0
  2935. */
  2936. function is_lighttpd_before_150() {
  2937. $server_parts = explode( '/', isset( $_SERVER['SERVER_SOFTWARE'] )? $_SERVER['SERVER_SOFTWARE'] : '' );
  2938. $server_parts[1] = isset( $server_parts[1] )? $server_parts[1] : '';
  2939. return 'lighttpd' == $server_parts[0] && -1 == version_compare( $server_parts[1], '1.5.0' );
  2940. }
  2941. /**
  2942. * Does the specified module exist in the Apache config?
  2943. *
  2944. * @since 2.5.0
  2945. *
  2946. * @param string $mod e.g. mod_rewrite
  2947. * @param bool $default The default return value if the module is not found
  2948. * @return bool
  2949. */
  2950. function apache_mod_loaded($mod, $default = false) {
  2951. global $is_apache;
  2952. if ( !$is_apache )
  2953. return false;
  2954. if ( function_exists('apache_get_modules') ) {
  2955. $mods = apache_get_modules();
  2956. if ( in_array($mod, $mods) )
  2957. return true;
  2958. } elseif ( function_exists('phpinfo') ) {
  2959. ob_start();
  2960. phpinfo(8);
  2961. $phpinfo = ob_get_clean();
  2962. if ( false !== strpos($phpinfo, $mod) )
  2963. return true;
  2964. }
  2965. return $default;
  2966. }
  2967. /**
  2968. * Check if IIS 7+ supports pretty permalinks.
  2969. *
  2970. * @since 2.8.0
  2971. *
  2972. * @return bool
  2973. */
  2974. function iis7_supports_permalinks() {
  2975. global $is_iis7;
  2976. $supports_permalinks = false;
  2977. if ( $is_iis7 ) {
  2978. /* First we check if the DOMDocument class exists. If it does not exist, then we cannot
  2979. * easily update the xml configuration file, hence we just bail out and tell user that
  2980. * pretty permalinks cannot be used.
  2981. *
  2982. * Next we check if the URL Rewrite Module 1.1 is loaded and enabled for the web site. When
  2983. * URL Rewrite 1.1 is loaded it always sets a server variable called 'IIS_UrlRewriteModule'.
  2984. * Lastly we make sure that PHP is running via FastCGI. This is important because if it runs
  2985. * via ISAPI then pretty permalinks will not work.
  2986. */
  2987. $supports_permalinks = class_exists('DOMDocument') && isset($_SERVER['IIS_UrlRewriteModule']) && ( php_sapi_name() == 'cgi-fcgi' );
  2988. }
  2989. /**
  2990. * Filter whether IIS 7+ supports pretty permalinks.
  2991. *
  2992. * @since 2.8.0
  2993. *
  2994. * @param bool $supports_permalinks Whether IIS7 supports permalinks. Default false.
  2995. */
  2996. return apply_filters( 'iis7_supports_permalinks', $supports_permalinks );
  2997. }
  2998. /**
  2999. * File validates against allowed set of defined rules.
  3000. *
  3001. * A return value of '1' means that the $file contains either '..' or './'. A
  3002. * return value of '2' means that the $file contains ':' after the first
  3003. * character. A return value of '3' means that the file is not in the allowed
  3004. * files list.
  3005. *
  3006. * @since 1.2.0
  3007. *
  3008. * @param string $file File path.
  3009. * @param array $allowed_files List of allowed files.
  3010. * @return int 0 means nothing is wrong, greater than 0 means something was wrong.
  3011. */
  3012. function validate_file( $file, $allowed_files = '' ) {
  3013. if ( false !== strpos( $file, '..' ) )
  3014. return 1;
  3015. if ( false !== strpos( $file, './' ) )
  3016. return 1;
  3017. if ( ! empty( $allowed_files ) && ! in_array( $file, $allowed_files ) )
  3018. return 3;
  3019. if (':' == substr( $file, 1, 1 ) )
  3020. return 2;
  3021. return 0;
  3022. }
  3023. /**
  3024. * Determine if SSL is used.
  3025. *
  3026. * @since 2.6.0
  3027. *
  3028. * @return bool True if SSL, false if not used.
  3029. */
  3030. function is_ssl() {
  3031. if ( isset($_SERVER['HTTPS']) ) {
  3032. if ( 'on' == strtolower($_SERVER['HTTPS']) )
  3033. return true;
  3034. if ( '1' == $_SERVER['HTTPS'] )
  3035. return true;
  3036. } elseif ( isset($_SERVER['SERVER_PORT']) && ( '443' == $_SERVER['SERVER_PORT'] ) ) {
  3037. return true;
  3038. }
  3039. return false;
  3040. }
  3041. /**
  3042. * Whether SSL login should be forced.
  3043. *
  3044. * @since 2.6.0
  3045. *
  3046. * @param string|bool $force Optional.
  3047. * @return bool True if forced, false if not forced.
  3048. */
  3049. function force_ssl_login( $force = null ) {
  3050. return force_ssl_admin( $force );
  3051. }
  3052. /**
  3053. * Whether to force SSL used for the Administration Screens.
  3054. *
  3055. * @since 2.6.0
  3056. *
  3057. * @param string|bool $force
  3058. * @return bool True if forced, false if not forced.
  3059. */
  3060. function force_ssl_admin( $force = null ) {
  3061. static $forced = false;
  3062. if ( !is_null( $force ) ) {
  3063. $old_forced = $forced;
  3064. $forced = $force;
  3065. return $old_forced;
  3066. }
  3067. return $forced;
  3068. }
  3069. /**
  3070. * Guess the URL for the site.
  3071. *
  3072. * Will remove wp-admin links to retrieve only return URLs not in the wp-admin
  3073. * directory.
  3074. *
  3075. * @since 2.6.0
  3076. *
  3077. * @return string
  3078. */
  3079. function wp_guess_url() {
  3080. if ( defined('WP_SITEURL') && '' != WP_SITEURL ) {
  3081. $url = WP_SITEURL;
  3082. } else {
  3083. $abspath_fix = str_replace( '\\', '/', ABSPATH );
  3084. $script_filename_dir = dirname( $_SERVER['SCRIPT_FILENAME'] );
  3085. // The request is for the admin
  3086. if ( strpos( $_SERVER['REQUEST_URI'], 'wp-admin' ) !== false || strpos( $_SERVER['REQUEST_URI'], 'wp-login.php' ) !== false ) {
  3087. $path = preg_replace( '#/(wp-admin/.*|wp-login.php)#i', '', $_SERVER['REQUEST_URI'] );
  3088. // The request is for a file in ABSPATH
  3089. } elseif ( $script_filename_dir . '/' == $abspath_fix ) {
  3090. // Strip off any file/query params in the path
  3091. $path = preg_replace( '#/[^/]*$#i', '', $_SERVER['PHP_SELF'] );
  3092. } else {
  3093. if ( false !== strpos( $_SERVER['SCRIPT_FILENAME'], $abspath_fix ) ) {
  3094. // Request is hitting a file inside ABSPATH
  3095. $directory = str_replace( ABSPATH, '', $script_filename_dir );
  3096. // Strip off the sub directory, and any file/query paramss
  3097. $path = preg_replace( '#/' . preg_quote( $directory, '#' ) . '/[^/]*$#i', '' , $_SERVER['REQUEST_URI'] );
  3098. } elseif ( false !== strpos( $abspath_fix, $script_filename_dir ) ) {
  3099. // Request is hitting a file above ABSPATH
  3100. $subdirectory = substr( $abspath_fix, strpos( $abspath_fix, $script_filename_dir ) + strlen( $script_filename_dir ) );
  3101. // Strip off any file/query params from the path, appending the sub directory to the install
  3102. $path = preg_replace( '#/[^/]*$#i', '' , $_SERVER['REQUEST_URI'] ) . $subdirectory;
  3103. } else {
  3104. $path = $_SERVER['REQUEST_URI'];
  3105. }
  3106. }
  3107. $schema = is_ssl() ? 'https://' : 'http://'; // set_url_scheme() is not defined yet
  3108. $url = $schema . $_SERVER['HTTP_HOST'] . $path;
  3109. }
  3110. return rtrim($url, '/');
  3111. }
  3112. /**
  3113. * Temporarily suspend cache additions.
  3114. *
  3115. * Stops more data being added to the cache, but still allows cache retrieval.
  3116. * This is useful for actions, such as imports, when a lot of data would otherwise
  3117. * be almost uselessly added to the cache.
  3118. *
  3119. * Suspension lasts for a single page load at most. Remember to call this
  3120. * function again if you wish to re-enable cache adds earlier.
  3121. *
  3122. * @since 3.3.0
  3123. *
  3124. * @param bool $suspend Optional. Suspends additions if true, re-enables them if false.
  3125. * @return bool The current suspend setting
  3126. */
  3127. function wp_suspend_cache_addition( $suspend = null ) {
  3128. static $_suspend = false;
  3129. if ( is_bool( $suspend ) )
  3130. $_suspend = $suspend;
  3131. return $_suspend;
  3132. }
  3133. /**
  3134. * Suspend cache invalidation.
  3135. *
  3136. * Turns cache invalidation on and off. Useful during imports where you don't wont to do invalidations
  3137. * every time a post is inserted. Callers must be sure that what they are doing won't lead to an inconsistent
  3138. * cache when invalidation is suspended.
  3139. *
  3140. * @since 2.7.0
  3141. *
  3142. * @param bool $suspend Whether to suspend or enable cache invalidation
  3143. * @return bool The current suspend setting
  3144. */
  3145. function wp_suspend_cache_invalidation($suspend = true) {
  3146. global $_wp_suspend_cache_invalidation;
  3147. $current_suspend = $_wp_suspend_cache_invalidation;
  3148. $_wp_suspend_cache_invalidation = $suspend;
  3149. return $current_suspend;
  3150. }
  3151. /**
  3152. * Whether a site is the main site of the current network.
  3153. *
  3154. * @since 3.0.0
  3155. *
  3156. * @param int $site_id Optional. Site ID to test. Defaults to current site.
  3157. * @return bool True if $site_id is the main site of the network, or if not running multisite.
  3158. */
  3159. function is_main_site( $site_id = null ) {
  3160. // This is the current network's information; 'site' is old terminology.
  3161. global $current_site;
  3162. if ( ! is_multisite() )
  3163. return true;
  3164. if ( ! $site_id )
  3165. $site_id = get_current_blog_id();
  3166. return (int) $site_id === (int) $current_site->blog_id;
  3167. }
  3168. /**
  3169. * Whether a network is the main network of the multisite install.
  3170. *
  3171. * @since 3.7.0
  3172. *
  3173. * @param int $network_id Optional. Network ID to test. Defaults to current network.
  3174. * @return bool True if $network_id is the main network, or if not running multisite.
  3175. */
  3176. function is_main_network( $network_id = null ) {
  3177. global $wpdb;
  3178. if ( ! is_multisite() )
  3179. return true;
  3180. $current_network_id = (int) get_current_site()->id;
  3181. if ( ! $network_id )
  3182. $network_id = $current_network_id;
  3183. $network_id = (int) $network_id;
  3184. if ( defined( 'PRIMARY_NETWORK_ID' ) )
  3185. return $network_id === (int) PRIMARY_NETWORK_ID;
  3186. if ( 1 === $current_network_id )
  3187. return $network_id === $current_network_id;
  3188. $primary_network_id = (int) wp_cache_get( 'primary_network_id', 'site-options' );
  3189. if ( $primary_network_id )
  3190. return $network_id === $primary_network_id;
  3191. $primary_network_id = (int) $wpdb->get_var( "SELECT id FROM $wpdb->site ORDER BY id LIMIT 1" );
  3192. wp_cache_add( 'primary_network_id', $primary_network_id, 'site-options' );
  3193. return $network_id === $primary_network_id;
  3194. }
  3195. /**
  3196. * Whether global terms are enabled.
  3197. *
  3198. *
  3199. * @since 3.0.0
  3200. *
  3201. * @return bool True if multisite and global terms enabled
  3202. */
  3203. function global_terms_enabled() {
  3204. if ( ! is_multisite() )
  3205. return false;
  3206. static $global_terms = null;
  3207. if ( is_null( $global_terms ) ) {
  3208. /**
  3209. * Filter whether global terms are enabled.
  3210. *
  3211. * Passing a non-null value to the filter will effectively short-circuit the function,
  3212. * returning the value of the 'global_terms_enabled' site option instead.
  3213. *
  3214. * @since 3.0.0
  3215. *
  3216. * @param null $anbled Whether global terms are enabled.
  3217. */
  3218. $filter = apply_filters( 'global_terms_enabled', null );
  3219. if ( ! is_null( $filter ) )
  3220. $global_terms = (bool) $filter;
  3221. else
  3222. $global_terms = (bool) get_site_option( 'global_terms_enabled', false );
  3223. }
  3224. return $global_terms;
  3225. }
  3226. /**
  3227. * gmt_offset modification for smart timezone handling.
  3228. *
  3229. * Overrides the gmt_offset option if we have a timezone_string available.
  3230. *
  3231. * @since 2.8.0
  3232. *
  3233. * @return float|bool
  3234. */
  3235. function wp_timezone_override_offset() {
  3236. if ( !$timezone_string = get_option( 'timezone_string' ) ) {
  3237. return false;
  3238. }
  3239. $timezone_object = timezone_open( $timezone_string );
  3240. $datetime_object = date_create();
  3241. if ( false === $timezone_object || false === $datetime_object ) {
  3242. return false;
  3243. }
  3244. return round( timezone_offset_get( $timezone_object, $datetime_object ) / HOUR_IN_SECONDS, 2 );
  3245. }
  3246. /**
  3247. * Sort-helper for timezones.
  3248. *
  3249. * @since 2.9.0
  3250. *
  3251. * @param array $a
  3252. * @param array $b
  3253. * @return int
  3254. */
  3255. function _wp_timezone_choice_usort_callback( $a, $b ) {
  3256. // Don't use translated versions of Etc
  3257. if ( 'Etc' === $a['continent'] && 'Etc' === $b['continent'] ) {
  3258. // Make the order of these more like the old dropdown
  3259. if ( 'GMT+' === substr( $a['city'], 0, 4 ) && 'GMT+' === substr( $b['city'], 0, 4 ) ) {
  3260. return -1 * ( strnatcasecmp( $a['city'], $b['city'] ) );
  3261. }
  3262. if ( 'UTC' === $a['city'] ) {
  3263. if ( 'GMT+' === substr( $b['city'], 0, 4 ) ) {
  3264. return 1;
  3265. }
  3266. return -1;
  3267. }
  3268. if ( 'UTC' === $b['city'] ) {
  3269. if ( 'GMT+' === substr( $a['city'], 0, 4 ) ) {
  3270. return -1;
  3271. }
  3272. return 1;
  3273. }
  3274. return strnatcasecmp( $a['city'], $b['city'] );
  3275. }
  3276. if ( $a['t_continent'] == $b['t_continent'] ) {
  3277. if ( $a['t_city'] == $b['t_city'] ) {
  3278. return strnatcasecmp( $a['t_subcity'], $b['t_subcity'] );
  3279. }
  3280. return strnatcasecmp( $a['t_city'], $b['t_city'] );
  3281. } else {
  3282. // Force Etc to the bottom of the list
  3283. if ( 'Etc' === $a['continent'] ) {
  3284. return 1;
  3285. }
  3286. if ( 'Etc' === $b['continent'] ) {
  3287. return -1;
  3288. }
  3289. return strnatcasecmp( $a['t_continent'], $b['t_continent'] );
  3290. }
  3291. }
  3292. /**
  3293. * Gives a nicely formatted list of timezone strings.
  3294. *
  3295. * @since 2.9.0
  3296. *
  3297. * @param string $selected_zone Selected Zone
  3298. * @return string
  3299. */
  3300. function wp_timezone_choice( $selected_zone ) {
  3301. static $mo_loaded = false;
  3302. $continents = array( 'Africa', 'America', 'Antarctica', 'Arctic', 'Asia', 'Atlantic', 'Australia', 'Europe', 'Indian', 'Pacific');
  3303. // Load translations for continents and cities
  3304. if ( !$mo_loaded ) {
  3305. $locale = get_locale();
  3306. $mofile = WP_LANG_DIR . '/continents-cities-' . $locale . '.mo';
  3307. load_textdomain( 'continents-cities', $mofile );
  3308. $mo_loaded = true;
  3309. }
  3310. $zonen = array();
  3311. foreach ( timezone_identifiers_list() as $zone ) {
  3312. $zone = explode( '/', $zone );
  3313. if ( !in_array( $zone[0], $continents ) ) {
  3314. continue;
  3315. }
  3316. // This determines what gets set and translated - we don't translate Etc/* strings here, they are done later
  3317. $exists = array(
  3318. 0 => ( isset( $zone[0] ) && $zone[0] ),
  3319. 1 => ( isset( $zone[1] ) && $zone[1] ),
  3320. 2 => ( isset( $zone[2] ) && $zone[2] ),
  3321. );
  3322. $exists[3] = ( $exists[0] && 'Etc' !== $zone[0] );
  3323. $exists[4] = ( $exists[1] && $exists[3] );
  3324. $exists[5] = ( $exists[2] && $exists[3] );
  3325. $zonen[] = array(
  3326. 'continent' => ( $exists[0] ? $zone[0] : '' ),
  3327. 'city' => ( $exists[1] ? $zone[1] : '' ),
  3328. 'subcity' => ( $exists[2] ? $zone[2] : '' ),
  3329. 't_continent' => ( $exists[3] ? translate( str_replace( '_', ' ', $zone[0] ), 'continents-cities' ) : '' ),
  3330. 't_city' => ( $exists[4] ? translate( str_replace( '_', ' ', $zone[1] ), 'continents-cities' ) : '' ),
  3331. 't_subcity' => ( $exists[5] ? translate( str_replace( '_', ' ', $zone[2] ), 'continents-cities' ) : '' )
  3332. );
  3333. }
  3334. usort( $zonen, '_wp_timezone_choice_usort_callback' );
  3335. $structure = array();
  3336. if ( empty( $selected_zone ) ) {
  3337. $structure[] = '<option selected="selected" value="">' . __( 'Select a city' ) . '</option>';
  3338. }
  3339. foreach ( $zonen as $key => $zone ) {
  3340. // Build value in an array to join later
  3341. $value = array( $zone['continent'] );
  3342. if ( empty( $zone['city'] ) ) {
  3343. // It's at the continent level (generally won't happen)
  3344. $display = $zone['t_continent'];
  3345. } else {
  3346. // It's inside a continent group
  3347. // Continent optgroup
  3348. if ( !isset( $zonen[$key - 1] ) || $zonen[$key - 1]['continent'] !== $zone['continent'] ) {
  3349. $label = $zone['t_continent'];
  3350. $structure[] = '<optgroup label="'. esc_attr( $label ) .'">';
  3351. }
  3352. // Add the city to the value
  3353. $value[] = $zone['city'];
  3354. $display = $zone['t_city'];
  3355. if ( !empty( $zone['subcity'] ) ) {
  3356. // Add the subcity to the value
  3357. $value[] = $zone['subcity'];
  3358. $display .= ' - ' . $zone['t_subcity'];
  3359. }
  3360. }
  3361. // Build the value
  3362. $value = join( '/', $value );
  3363. $selected = '';
  3364. if ( $value === $selected_zone ) {
  3365. $selected = 'selected="selected" ';
  3366. }
  3367. $structure[] = '<option ' . $selected . 'value="' . esc_attr( $value ) . '">' . esc_html( $display ) . "</option>";
  3368. // Close continent optgroup
  3369. if ( !empty( $zone['city'] ) && ( !isset($zonen[$key + 1]) || (isset( $zonen[$key + 1] ) && $zonen[$key + 1]['continent'] !== $zone['continent']) ) ) {
  3370. $structure[] = '</optgroup>';
  3371. }
  3372. }
  3373. // Do UTC
  3374. $structure[] = '<optgroup label="'. esc_attr__( 'UTC' ) .'">';
  3375. $selected = '';
  3376. if ( 'UTC' === $selected_zone )
  3377. $selected = 'selected="selected" ';
  3378. $structure[] = '<option ' . $selected . 'value="' . esc_attr( 'UTC' ) . '">' . __('UTC') . '</option>';
  3379. $structure[] = '</optgroup>';
  3380. // Do manual UTC offsets
  3381. $structure[] = '<optgroup label="'. esc_attr__( 'Manual Offsets' ) .'">';
  3382. $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,
  3383. 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);
  3384. foreach ( $offset_range as $offset ) {
  3385. if ( 0 <= $offset )
  3386. $offset_name = '+' . $offset;
  3387. else
  3388. $offset_name = (string) $offset;
  3389. $offset_value = $offset_name;
  3390. $offset_name = str_replace(array('.25','.5','.75'), array(':15',':30',':45'), $offset_name);
  3391. $offset_name = 'UTC' . $offset_name;
  3392. $offset_value = 'UTC' . $offset_value;
  3393. $selected = '';
  3394. if ( $offset_value === $selected_zone )
  3395. $selected = 'selected="selected" ';
  3396. $structure[] = '<option ' . $selected . 'value="' . esc_attr( $offset_value ) . '">' . esc_html( $offset_name ) . "</option>";
  3397. }
  3398. $structure[] = '</optgroup>';
  3399. return join( "\n", $structure );
  3400. }
  3401. /**
  3402. * Strip close comment and close php tags from file headers used by WP.
  3403. * See http://core.trac.wordpress.org/ticket/8497
  3404. *
  3405. * @since 2.8.0
  3406. *
  3407. * @param string $str
  3408. * @return string
  3409. */
  3410. function _cleanup_header_comment($str) {
  3411. return trim(preg_replace("/\s*(?:\*\/|\?>).*/", '', $str));
  3412. }
  3413. /**
  3414. * Permanently deletes posts, pages, attachments, and comments which have been in the trash for EMPTY_TRASH_DAYS.
  3415. *
  3416. * @since 2.9.0
  3417. */
  3418. function wp_scheduled_delete() {
  3419. global $wpdb;
  3420. $delete_timestamp = time() - ( DAY_IN_SECONDS * EMPTY_TRASH_DAYS );
  3421. $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);
  3422. foreach ( (array) $posts_to_delete as $post ) {
  3423. $post_id = (int) $post['post_id'];
  3424. if ( !$post_id )
  3425. continue;
  3426. $del_post = get_post($post_id);
  3427. if ( !$del_post || 'trash' != $del_post->post_status ) {
  3428. delete_post_meta($post_id, '_wp_trash_meta_status');
  3429. delete_post_meta($post_id, '_wp_trash_meta_time');
  3430. } else {
  3431. wp_delete_post($post_id);
  3432. }
  3433. }
  3434. $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);
  3435. foreach ( (array) $comments_to_delete as $comment ) {
  3436. $comment_id = (int) $comment['comment_id'];
  3437. if ( !$comment_id )
  3438. continue;
  3439. $del_comment = get_comment($comment_id);
  3440. if ( !$del_comment || 'trash' != $del_comment->comment_approved ) {
  3441. delete_comment_meta($comment_id, '_wp_trash_meta_time');
  3442. delete_comment_meta($comment_id, '_wp_trash_meta_status');
  3443. } else {
  3444. wp_delete_comment($comment_id);
  3445. }
  3446. }
  3447. }
  3448. /**
  3449. * Retrieve metadata from a file.
  3450. *
  3451. * Searches for metadata in the first 8kiB of a file, such as a plugin or theme.
  3452. * Each piece of metadata must be on its own line. Fields can not span multiple
  3453. * lines, the value will get cut at the end of the first line.
  3454. *
  3455. * If the file data is not within that first 8kiB, then the author should correct
  3456. * their plugin file and move the data headers to the top.
  3457. *
  3458. * @see http://codex.wordpress.org/File_Header
  3459. *
  3460. * @since 2.9.0
  3461. * @param string $file Path to the file
  3462. * @param array $default_headers List of headers, in the format array('HeaderKey' => 'Header Name')
  3463. * @param string $context If specified adds filter hook "extra_{$context}_headers"
  3464. */
  3465. function get_file_data( $file, $default_headers, $context = '' ) {
  3466. // We don't need to write to the file, so just open for reading.
  3467. $fp = fopen( $file, 'r' );
  3468. // Pull only the first 8kiB of the file in.
  3469. $file_data = fread( $fp, 8192 );
  3470. // PHP will close file handle, but we are good citizens.
  3471. fclose( $fp );
  3472. // Make sure we catch CR-only line endings.
  3473. $file_data = str_replace( "\r", "\n", $file_data );
  3474. /**
  3475. * Filter extra file headers by context.
  3476. *
  3477. * The dynamic portion of the hook name, $context, refers to the context
  3478. * where extra headers might be loaded.
  3479. *
  3480. * @since 2.9.0
  3481. *
  3482. * @param array $extra_context_headers Empty array by default.
  3483. */
  3484. if ( $context && $extra_headers = apply_filters( "extra_{$context}_headers", array() ) ) {
  3485. $extra_headers = array_combine( $extra_headers, $extra_headers ); // keys equal values
  3486. $all_headers = array_merge( $extra_headers, (array) $default_headers );
  3487. } else {
  3488. $all_headers = $default_headers;
  3489. }
  3490. foreach ( $all_headers as $field => $regex ) {
  3491. if ( preg_match( '/^[ \t\/*#@]*' . preg_quote( $regex, '/' ) . ':(.*)$/mi', $file_data, $match ) && $match[1] )
  3492. $all_headers[ $field ] = _cleanup_header_comment( $match[1] );
  3493. else
  3494. $all_headers[ $field ] = '';
  3495. }
  3496. return $all_headers;
  3497. }
  3498. /**
  3499. * Returns true.
  3500. *
  3501. * Useful for returning true to filters easily.
  3502. *
  3503. * @since 3.0.0
  3504. * @see __return_false()
  3505. * @return bool true
  3506. */
  3507. function __return_true() {
  3508. return true;
  3509. }
  3510. /**
  3511. * Returns false.
  3512. *
  3513. * Useful for returning false to filters easily.
  3514. *
  3515. * @since 3.0.0
  3516. * @see __return_true()
  3517. * @return bool false
  3518. */
  3519. function __return_false() {
  3520. return false;
  3521. }
  3522. /**
  3523. * Returns 0.
  3524. *
  3525. * Useful for returning 0 to filters easily.
  3526. *
  3527. * @since 3.0.0
  3528. * @return int 0
  3529. */
  3530. function __return_zero() {
  3531. return 0;
  3532. }
  3533. /**
  3534. * Returns an empty array.
  3535. *
  3536. * Useful for returning an empty array to filters easily.
  3537. *
  3538. * @since 3.0.0
  3539. * @return array Empty array
  3540. */
  3541. function __return_empty_array() {
  3542. return array();
  3543. }
  3544. /**
  3545. * Returns null.
  3546. *
  3547. * Useful for returning null to filters easily.
  3548. *
  3549. * @since 3.4.0
  3550. * @return null
  3551. */
  3552. function __return_null() {
  3553. return null;
  3554. }
  3555. /**
  3556. * Returns an empty string.
  3557. *
  3558. * Useful for returning an empty string to filters easily.
  3559. *
  3560. * @since 3.7.0
  3561. * @see __return_null()
  3562. * @return string Empty string
  3563. */
  3564. function __return_empty_string() {
  3565. return '';
  3566. }
  3567. /**
  3568. * Send a HTTP header to disable content type sniffing in browsers which support it.
  3569. *
  3570. * @link http://blogs.msdn.com/ie/archive/2008/07/02/ie8-security-part-v-comprehensive-protection.aspx
  3571. * @link http://src.chromium.org/viewvc/chrome?view=rev&revision=6985
  3572. *
  3573. * @since 3.0.0
  3574. * @return none
  3575. */
  3576. function send_nosniff_header() {
  3577. @header( 'X-Content-Type-Options: nosniff' );
  3578. }
  3579. /**
  3580. * Returns a MySQL expression for selecting the week number based on the start_of_week option.
  3581. *
  3582. * @internal
  3583. * @since 3.0.0
  3584. * @param string $column
  3585. * @return string
  3586. */
  3587. function _wp_mysql_week( $column ) {
  3588. switch ( $start_of_week = (int) get_option( 'start_of_week' ) ) {
  3589. case 1 :
  3590. return "WEEK( $column, 1 )";
  3591. case 2 :
  3592. case 3 :
  3593. case 4 :
  3594. case 5 :
  3595. case 6 :
  3596. return "WEEK( DATE_SUB( $column, INTERVAL $start_of_week DAY ), 0 )";
  3597. case 0 :
  3598. default :
  3599. return "WEEK( $column, 0 )";
  3600. }
  3601. }
  3602. /**
  3603. * Finds hierarchy loops using a callback function that maps object IDs to parent IDs.
  3604. *
  3605. * @since 3.1.0
  3606. * @access private
  3607. *
  3608. * @param callback $callback function that accepts ( ID, $callback_args ) and outputs parent_ID
  3609. * @param int $start The ID to start the loop check at
  3610. * @param int $start_parent the parent_ID of $start to use instead of calling $callback( $start ). Use null to always use $callback
  3611. * @param array $callback_args optional additional arguments to send to $callback
  3612. * @return array IDs of all members of loop
  3613. */
  3614. function wp_find_hierarchy_loop( $callback, $start, $start_parent, $callback_args = array() ) {
  3615. $override = is_null( $start_parent ) ? array() : array( $start => $start_parent );
  3616. if ( !$arbitrary_loop_member = wp_find_hierarchy_loop_tortoise_hare( $callback, $start, $override, $callback_args ) )
  3617. return array();
  3618. return wp_find_hierarchy_loop_tortoise_hare( $callback, $arbitrary_loop_member, $override, $callback_args, true );
  3619. }
  3620. /**
  3621. * Uses the "The Tortoise and the Hare" algorithm to detect loops.
  3622. *
  3623. * For every step of the algorithm, the hare takes two steps and the tortoise one.
  3624. * If the hare ever laps the tortoise, there must be a loop.
  3625. *
  3626. * @since 3.1.0
  3627. * @access private
  3628. *
  3629. * @param callback $callback function that accepts ( ID, callback_arg, ... ) and outputs parent_ID
  3630. * @param int $start The ID to start the loop check at
  3631. * @param array $override an array of ( ID => parent_ID, ... ) to use instead of $callback
  3632. * @param array $callback_args optional additional arguments to send to $callback
  3633. * @param bool $_return_loop Return loop members or just detect presence of loop?
  3634. * Only set to true if you already know the given $start is part of a loop
  3635. * (otherwise the returned array might include branches)
  3636. * @return mixed scalar ID of some arbitrary member of the loop, or array of IDs of all members of loop if $_return_loop
  3637. */
  3638. function wp_find_hierarchy_loop_tortoise_hare( $callback, $start, $override = array(), $callback_args = array(), $_return_loop = false ) {
  3639. $tortoise = $hare = $evanescent_hare = $start;
  3640. $return = array();
  3641. // Set evanescent_hare to one past hare
  3642. // Increment hare two steps
  3643. while (
  3644. $tortoise
  3645. &&
  3646. ( $evanescent_hare = isset( $override[$hare] ) ? $override[$hare] : call_user_func_array( $callback, array_merge( array( $hare ), $callback_args ) ) )
  3647. &&
  3648. ( $hare = isset( $override[$evanescent_hare] ) ? $override[$evanescent_hare] : call_user_func_array( $callback, array_merge( array( $evanescent_hare ), $callback_args ) ) )
  3649. ) {
  3650. if ( $_return_loop )
  3651. $return[$tortoise] = $return[$evanescent_hare] = $return[$hare] = true;
  3652. // tortoise got lapped - must be a loop
  3653. if ( $tortoise == $evanescent_hare || $tortoise == $hare )
  3654. return $_return_loop ? $return : $tortoise;
  3655. // Increment tortoise by one step
  3656. $tortoise = isset( $override[$tortoise] ) ? $override[$tortoise] : call_user_func_array( $callback, array_merge( array( $tortoise ), $callback_args ) );
  3657. }
  3658. return false;
  3659. }
  3660. /**
  3661. * Send a HTTP header to limit rendering of pages to same origin iframes.
  3662. *
  3663. * @link https://developer.mozilla.org/en/the_x-frame-options_response_header
  3664. *
  3665. * @since 3.1.3
  3666. * @return none
  3667. */
  3668. function send_frame_options_header() {
  3669. @header( 'X-Frame-Options: SAMEORIGIN' );
  3670. }
  3671. /**
  3672. * Retrieve a list of protocols to allow in HTML attributes.
  3673. *
  3674. * @since 3.3.0
  3675. * @see wp_kses()
  3676. * @see esc_url()
  3677. *
  3678. * @return array Array of allowed protocols
  3679. */
  3680. function wp_allowed_protocols() {
  3681. static $protocols;
  3682. if ( empty( $protocols ) ) {
  3683. $protocols = array( 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet', 'mms', 'rtsp', 'svn', 'tel', 'fax', 'xmpp' );
  3684. /**
  3685. * Filter the list of protocols allowed in HTML attributes.
  3686. *
  3687. * @since 3.0.0
  3688. *
  3689. * @param array $protocols Array of allowed protocols e.g. 'http', 'ftp', 'tel', and more.
  3690. */
  3691. $protocols = apply_filters( 'kses_allowed_protocols', $protocols );
  3692. }
  3693. return $protocols;
  3694. }
  3695. /**
  3696. * Return a comma separated string of functions that have been called to get to the current point in code.
  3697. *
  3698. * @link http://core.trac.wordpress.org/ticket/19589
  3699. * @since 3.4.0
  3700. *
  3701. * @param string $ignore_class A class to ignore all function calls within - useful when you want to just give info about the callee
  3702. * @param int $skip_frames A number of stack frames to skip - useful for unwinding back to the source of the issue
  3703. * @param bool $pretty Whether or not you want a comma separated string or raw array returned
  3704. * @return string|array Either a string containing a reversed comma separated trace or an array of individual calls.
  3705. */
  3706. function wp_debug_backtrace_summary( $ignore_class = null, $skip_frames = 0, $pretty = true ) {
  3707. if ( version_compare( PHP_VERSION, '5.2.5', '>=' ) )
  3708. $trace = debug_backtrace( false );
  3709. else
  3710. $trace = debug_backtrace();
  3711. $caller = array();
  3712. $check_class = ! is_null( $ignore_class );
  3713. $skip_frames++; // skip this function
  3714. foreach ( $trace as $call ) {
  3715. if ( $skip_frames > 0 ) {
  3716. $skip_frames--;
  3717. } elseif ( isset( $call['class'] ) ) {
  3718. if ( $check_class && $ignore_class == $call['class'] )
  3719. continue; // Filter out calls
  3720. $caller[] = "{$call['class']}{$call['type']}{$call['function']}";
  3721. } else {
  3722. if ( in_array( $call['function'], array( 'do_action', 'apply_filters' ) ) ) {
  3723. $caller[] = "{$call['function']}('{$call['args'][0]}')";
  3724. } elseif ( in_array( $call['function'], array( 'include', 'include_once', 'require', 'require_once' ) ) ) {
  3725. $caller[] = $call['function'] . "('" . str_replace( array( WP_CONTENT_DIR, ABSPATH ) , '', $call['args'][0] ) . "')";
  3726. } else {
  3727. $caller[] = $call['function'];
  3728. }
  3729. }
  3730. }
  3731. if ( $pretty )
  3732. return join( ', ', array_reverse( $caller ) );
  3733. else
  3734. return $caller;
  3735. }
  3736. /**
  3737. * Retrieve ids that are not already present in the cache
  3738. *
  3739. * @since 3.4.0
  3740. *
  3741. * @param array $object_ids ID list
  3742. * @param string $cache_key The cache bucket to check against
  3743. *
  3744. * @return array
  3745. */
  3746. function _get_non_cached_ids( $object_ids, $cache_key ) {
  3747. $clean = array();
  3748. foreach ( $object_ids as $id ) {
  3749. $id = (int) $id;
  3750. if ( !wp_cache_get( $id, $cache_key ) ) {
  3751. $clean[] = $id;
  3752. }
  3753. }
  3754. return $clean;
  3755. }
  3756. /**
  3757. * Test if the current device has the capability to upload files.
  3758. *
  3759. * @since 3.4.0
  3760. * @access private
  3761. *
  3762. * @return bool true|false
  3763. */
  3764. function _device_can_upload() {
  3765. if ( ! wp_is_mobile() )
  3766. return true;
  3767. $ua = $_SERVER['HTTP_USER_AGENT'];
  3768. if ( strpos($ua, 'iPhone') !== false
  3769. || strpos($ua, 'iPad') !== false
  3770. || strpos($ua, 'iPod') !== false ) {
  3771. return preg_match( '#OS ([\d_]+) like Mac OS X#', $ua, $version ) && version_compare( $version[1], '6', '>=' );
  3772. }
  3773. return true;
  3774. }
  3775. /**
  3776. * Test if a given path is a stream URL
  3777. *
  3778. * @param string $path The resource path or URL
  3779. * @return bool True if the path is a stream URL
  3780. */
  3781. function wp_is_stream( $path ) {
  3782. $wrappers = stream_get_wrappers();
  3783. $wrappers_re = '(' . join('|', $wrappers) . ')';
  3784. return preg_match( "!^$wrappers_re://!", $path ) === 1;
  3785. }
  3786. /**
  3787. * Test if the supplied date is valid for the Gregorian calendar
  3788. *
  3789. * @since 3.5.0
  3790. *
  3791. * @return bool true|false
  3792. */
  3793. function wp_checkdate( $month, $day, $year, $source_date ) {
  3794. /**
  3795. * Filter whether the given date is valid for the Gregorian calendar.
  3796. *
  3797. * @since 3.5.0
  3798. *
  3799. * @param bool $checkdate Whether the given date is valid.
  3800. * @param string $source_date Date to check.
  3801. */
  3802. return apply_filters( 'wp_checkdate', checkdate( $month, $day, $year ), $source_date );
  3803. }
  3804. /**
  3805. * Load the auth check for monitoring whether the user is still logged in.
  3806. *
  3807. * Can be disabled with remove_action( 'admin_enqueue_scripts', 'wp_auth_check_load' );
  3808. *
  3809. * This is disabled for certain screens where a login screen could cause an
  3810. * inconvenient interruption. A filter called wp_auth_check_load can be used
  3811. * for fine-grained control.
  3812. *
  3813. * @since 3.6.0
  3814. */
  3815. function wp_auth_check_load() {
  3816. if ( ! is_admin() && ! is_user_logged_in() )
  3817. return;
  3818. if ( defined( 'IFRAME_REQUEST' ) )
  3819. return;
  3820. $screen = get_current_screen();
  3821. $hidden = array( 'update', 'update-network', 'update-core', 'update-core-network', 'upgrade', 'upgrade-network', 'network' );
  3822. $show = ! in_array( $screen->id, $hidden );
  3823. /**
  3824. * Filter whether to load the authentication check.
  3825. *
  3826. * @since 3.6.0
  3827. *
  3828. * @param bool $show Whether to load the authentication check.
  3829. * @param WP_Screen $screen The current screen object.
  3830. */
  3831. if ( apply_filters( 'wp_auth_check_load', $show, $screen ) ) {
  3832. wp_enqueue_style( 'wp-auth-check' );
  3833. wp_enqueue_script( 'wp-auth-check' );
  3834. add_action( 'admin_print_footer_scripts', 'wp_auth_check_html', 5 );
  3835. add_action( 'wp_print_footer_scripts', 'wp_auth_check_html', 5 );
  3836. }
  3837. }
  3838. /**
  3839. * Output the HTML that shows the wp-login dialog when the user is no longer logged in.
  3840. *
  3841. * @since 3.6.0
  3842. */
  3843. function wp_auth_check_html() {
  3844. $login_url = wp_login_url();
  3845. $current_domain = ( is_ssl() ? 'https://' : 'http://' ) . $_SERVER['HTTP_HOST'];
  3846. $same_domain = ( strpos( $login_url, $current_domain ) === 0 );
  3847. /**
  3848. * Filter whether the authentication check originated at the same domain.
  3849. *
  3850. * @since 3.6.0
  3851. *
  3852. * @param bool $same_domain Whether the authentication check originated at the same domain.
  3853. */
  3854. $same_domain = apply_filters( 'wp_auth_check_same_domain', $same_domain );
  3855. $wrap_class = $same_domain ? 'hidden' : 'hidden fallback';
  3856. ?>
  3857. <div id="wp-auth-check-wrap" class="<?php echo $wrap_class; ?>">
  3858. <div id="wp-auth-check-bg"></div>
  3859. <div id="wp-auth-check">
  3860. <div class="wp-auth-check-close" tabindex="0" title="<?php esc_attr_e('Close'); ?>"></div>
  3861. <?php
  3862. if ( $same_domain ) {
  3863. ?>
  3864. <div id="wp-auth-check-form" data-src="<?php echo esc_url( add_query_arg( array( 'interim-login' => 1 ), $login_url ) ); ?>"></div>
  3865. <?php
  3866. }
  3867. ?>
  3868. <div class="wp-auth-fallback">
  3869. <p><b class="wp-auth-fallback-expired" tabindex="0"><?php _e('Session expired'); ?></b></p>
  3870. <p><a href="<?php echo esc_url( $login_url ); ?>" target="_blank"><?php _e('Please log in again.'); ?></a>
  3871. <?php _e('The login page will open in a new window. After logging in you can close it and return to this page.'); ?></p>
  3872. </div>
  3873. </div>
  3874. </div>
  3875. <?php
  3876. }
  3877. /**
  3878. * Check whether a user is still logged in, for the heartbeat.
  3879. *
  3880. * Send a result that shows a log-in box if the user is no longer logged in,
  3881. * or if their cookie is within the grace period.
  3882. *
  3883. * @since 3.6.0
  3884. */
  3885. function wp_auth_check( $response ) {
  3886. $response['wp-auth-check'] = is_user_logged_in() && empty( $GLOBALS['login_grace_period'] );
  3887. return $response;
  3888. }
  3889. /**
  3890. * Return RegEx body to liberally match an opening HTML tag that:
  3891. * 1. Is self-closing or
  3892. * 2. Has no body but has a closing tag of the same name or
  3893. * 3. Contains a body and a closing tag of the same name
  3894. *
  3895. * Note: this RegEx does not balance inner tags and does not attempt to produce valid HTML
  3896. *
  3897. * @since 3.6.0
  3898. *
  3899. * @param string $tag An HTML tag name. Example: 'video'
  3900. * @return string
  3901. */
  3902. function get_tag_regex( $tag ) {
  3903. if ( empty( $tag ) )
  3904. return;
  3905. return sprintf( '<%1$s[^<]*(?:>[\s\S]*<\/%1$s>|\s*\/>)', tag_escape( $tag ) );
  3906. }
  3907. /**
  3908. * Return a canonical form of the provided charset appropriate for passing to PHP
  3909. * functions such as htmlspecialchars() and charset html attributes.
  3910. *
  3911. * @link http://core.trac.wordpress.org/ticket/23688
  3912. * @since 3.6.0
  3913. *
  3914. * @param string A charset name
  3915. * @return string The canonical form of the charset
  3916. */
  3917. function _canonical_charset( $charset ) {
  3918. if ( 'UTF-8' === $charset || 'utf-8' === $charset || 'utf8' === $charset ||
  3919. 'UTF8' === $charset )
  3920. return 'UTF-8';
  3921. if ( 'ISO-8859-1' === $charset || 'iso-8859-1' === $charset ||
  3922. 'iso8859-1' === $charset || 'ISO8859-1' === $charset )
  3923. return 'ISO-8859-1';
  3924. return $charset;
  3925. }
  3926. /**
  3927. * Sets the mbstring internal encoding to a binary safe encoding when func_overload is enabled.
  3928. *
  3929. * When mbstring.func_overload is in use for multi-byte encodings, the results from strlen() and
  3930. * similar functions respect the utf8 characters, causing binary data to return incorrect lengths.
  3931. *
  3932. * This function overrides the mbstring encoding to a binary-safe encoding, and resets it to the
  3933. * users expected encoding afterwards through the `reset_mbstring_encoding` function.
  3934. *
  3935. * It is safe to recursively call this function, however each `mbstring_binary_safe_encoding()`
  3936. * call must be followed up with an equal number of `reset_mbstring_encoding()` calls.
  3937. *
  3938. * @see reset_mbstring_encoding()
  3939. *
  3940. * @since 3.7.0
  3941. *
  3942. * @param bool $reset Whether to reset the encoding back to a previously-set encoding.
  3943. */
  3944. function mbstring_binary_safe_encoding( $reset = false ) {
  3945. static $encodings = array();
  3946. static $overloaded = null;
  3947. if ( is_null( $overloaded ) )
  3948. $overloaded = function_exists( 'mb_internal_encoding' ) && ( ini_get( 'mbstring.func_overload' ) & 2 );
  3949. if ( false === $overloaded )
  3950. return;
  3951. if ( ! $reset ) {
  3952. $encoding = mb_internal_encoding();
  3953. array_push( $encodings, $encoding );
  3954. mb_internal_encoding( 'ISO-8859-1' );
  3955. }
  3956. if ( $reset && $encodings ) {
  3957. $encoding = array_pop( $encodings );
  3958. mb_internal_encoding( $encoding );
  3959. }
  3960. }
  3961. /**
  3962. * Resets the mbstring internal encoding to a users previously set encoding.
  3963. *
  3964. * @see mbstring_binary_safe_encoding()
  3965. *
  3966. * @since 3.7.0
  3967. */
  3968. function reset_mbstring_encoding() {
  3969. mbstring_binary_safe_encoding( true );
  3970. }
  3971. /**
  3972. * Alternative to filter_var( $var, FILTER_VALIDATE_BOOLEAN )
  3973. *
  3974. * @since 4.0.0
  3975. *
  3976. * @param mixed $var
  3977. * @return boolean
  3978. */
  3979. function wp_validate_boolean( $var ) {
  3980. if ( is_bool( $var ) ) {
  3981. return $var;
  3982. }
  3983. if ( 'false' === $var ) {
  3984. return false;
  3985. }
  3986. return (bool) $var;
  3987. }