PageRenderTime 60ms CodeModel.GetById 12ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-includes/functions.php

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