PageRenderTime 79ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/functions.php

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