PageRenderTime 68ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-includes/functions.php

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