PageRenderTime 71ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/blog/wp-includes/functions.php

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