PageRenderTime 51ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/php/wp-includes/functions.php

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