PageRenderTime 84ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/functions.php

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