PageRenderTime 329ms CodeModel.GetById 26ms RepoModel.GetById 155ms app.codeStats 12ms

/wp-includes/functions.php

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