PageRenderTime 73ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-includes/functions.php

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