PageRenderTime 80ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 1ms

/APP/wp-includes/functions.php

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