PageRenderTime 78ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/functions.php

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