PageRenderTime 57ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/functions.php

https://github.com/webgefrickel/frckl-init-wordpress
PHP | 4206 lines | 2168 code | 450 blank | 1588 comment | 496 complexity | f9867e1fc6476cf9fe8ce3989bc3c59c MD5 | raw file
Possible License(s): LGPL-3.0, LGPL-2.1, GPL-2.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * Main WordPress API
  4. *
  5. * @package WordPress
  6. */
  7. require( ABSPATH . WPINC . '/option.php' );
  8. /**
  9. * Converts given date string into a different format.
  10. *
  11. * $format should be either a PHP date format string, e.g. 'U' for a Unix
  12. * timestamp, or 'G' for a Unix timestamp assuming that $date is GMT.
  13. *
  14. * If $translate is true then the given date and format string will
  15. * be passed to date_i18n() for translation.
  16. *
  17. * @since 0.71
  18. *
  19. * @param string $format Format of the date to return.
  20. * @param string $date Date string to convert.
  21. * @param bool $translate Whether the return date should be translated. Default is true.
  22. * @return string|int Formatted date string, or Unix timestamp.
  23. */
  24. function mysql2date( $format, $date, $translate = true ) {
  25. if ( empty( $date ) )
  26. return false;
  27. if ( 'G' == $format )
  28. return strtotime( $date . ' +0000' );
  29. $i = strtotime( $date );
  30. if ( 'U' == $format )
  31. return $i;
  32. if ( $translate )
  33. return date_i18n( $format, $i );
  34. else
  35. return date( $format, $i );
  36. }
  37. /**
  38. * Retrieve the current time based on specified type.
  39. *
  40. * The 'mysql' type will return the time in the format for MySQL DATETIME field.
  41. * The 'timestamp' type will return the current timestamp.
  42. *
  43. * If $gmt is set to either '1' or 'true', then both types will use GMT time.
  44. * if $gmt is false, the output is adjusted with the GMT offset in the WordPress option.
  45. *
  46. * @since 1.0.0
  47. *
  48. * @param string $type Either 'mysql' or 'timestamp'.
  49. * @param int|bool $gmt Optional. Whether to use GMT timezone. Default is false.
  50. * @return int|string String if $type is 'gmt', int if $type is 'timestamp'.
  51. */
  52. function current_time( $type, $gmt = 0 ) {
  53. switch ( $type ) {
  54. case 'mysql':
  55. return ( $gmt ) ? gmdate( 'Y-m-d H:i:s' ) : gmdate( 'Y-m-d H:i:s', ( time() + ( get_option( 'gmt_offset' ) * HOUR_IN_SECONDS ) ) );
  56. break;
  57. case 'timestamp':
  58. return ( $gmt ) ? time() : time() + ( get_option( 'gmt_offset' ) * HOUR_IN_SECONDS );
  59. break;
  60. }
  61. }
  62. /**
  63. * Retrieve the date in localized format, based on timestamp.
  64. *
  65. * If the locale specifies the locale month and weekday, then the locale will
  66. * take over the format for the date. If it isn't, then the date format string
  67. * will be used instead.
  68. *
  69. * @since 0.71
  70. *
  71. * @param string $dateformatstring Format to display the date.
  72. * @param int $unixtimestamp Optional. Unix timestamp.
  73. * @param bool $gmt Optional, default is false. Whether to convert to GMT for time.
  74. * @return string The date, translated if locale specifies it.
  75. */
  76. function date_i18n( $dateformatstring, $unixtimestamp = false, $gmt = false ) {
  77. global $wp_locale;
  78. $i = $unixtimestamp;
  79. if ( false === $i ) {
  80. if ( ! $gmt )
  81. $i = current_time( 'timestamp' );
  82. else
  83. $i = time();
  84. // we should not let date() interfere with our
  85. // specially computed timestamp
  86. $gmt = true;
  87. }
  88. // store original value for language with untypical grammars
  89. // see http://core.trac.wordpress.org/ticket/9396
  90. $req_format = $dateformatstring;
  91. $datefunc = $gmt? 'gmdate' : 'date';
  92. if ( ( !empty( $wp_locale->month ) ) && ( !empty( $wp_locale->weekday ) ) ) {
  93. $datemonth = $wp_locale->get_month( $datefunc( 'm', $i ) );
  94. $datemonth_abbrev = $wp_locale->get_month_abbrev( $datemonth );
  95. $dateweekday = $wp_locale->get_weekday( $datefunc( 'w', $i ) );
  96. $dateweekday_abbrev = $wp_locale->get_weekday_abbrev( $dateweekday );
  97. $datemeridiem = $wp_locale->get_meridiem( $datefunc( 'a', $i ) );
  98. $datemeridiem_capital = $wp_locale->get_meridiem( $datefunc( 'A', $i ) );
  99. $dateformatstring = ' '.$dateformatstring;
  100. $dateformatstring = preg_replace( "/([^\\\])D/", "\\1" . backslashit( $dateweekday_abbrev ), $dateformatstring );
  101. $dateformatstring = preg_replace( "/([^\\\])F/", "\\1" . backslashit( $datemonth ), $dateformatstring );
  102. $dateformatstring = preg_replace( "/([^\\\])l/", "\\1" . backslashit( $dateweekday ), $dateformatstring );
  103. $dateformatstring = preg_replace( "/([^\\\])M/", "\\1" . backslashit( $datemonth_abbrev ), $dateformatstring );
  104. $dateformatstring = preg_replace( "/([^\\\])a/", "\\1" . backslashit( $datemeridiem ), $dateformatstring );
  105. $dateformatstring = preg_replace( "/([^\\\])A/", "\\1" . backslashit( $datemeridiem_capital ), $dateformatstring );
  106. $dateformatstring = substr( $dateformatstring, 1, strlen( $dateformatstring ) -1 );
  107. }
  108. $timezone_formats = array( 'P', 'I', 'O', 'T', 'Z', 'e' );
  109. $timezone_formats_re = implode( '|', $timezone_formats );
  110. if ( preg_match( "/$timezone_formats_re/", $dateformatstring ) ) {
  111. $timezone_string = get_option( 'timezone_string' );
  112. if ( $timezone_string ) {
  113. $timezone_object = timezone_open( $timezone_string );
  114. $date_object = date_create( null, $timezone_object );
  115. foreach( $timezone_formats as $timezone_format ) {
  116. if ( false !== strpos( $dateformatstring, $timezone_format ) ) {
  117. $formatted = date_format( $date_object, $timezone_format );
  118. $dateformatstring = ' '.$dateformatstring;
  119. $dateformatstring = preg_replace( "/([^\\\])$timezone_format/", "\\1" . backslashit( $formatted ), $dateformatstring );
  120. $dateformatstring = substr( $dateformatstring, 1, strlen( $dateformatstring ) -1 );
  121. }
  122. }
  123. }
  124. }
  125. $j = @$datefunc( $dateformatstring, $i );
  126. // allow plugins to redo this entirely for languages with untypical grammars
  127. $j = apply_filters('date_i18n', $j, $req_format, $i, $gmt);
  128. return $j;
  129. }
  130. /**
  131. * Convert integer number to format based on the locale.
  132. *
  133. * @since 2.3.0
  134. *
  135. * @param int $number The number to convert based on locale.
  136. * @param int $decimals Precision of the number of decimal places.
  137. * @return string Converted number in string format.
  138. */
  139. function number_format_i18n( $number, $decimals = 0 ) {
  140. global $wp_locale;
  141. $formatted = number_format( $number, absint( $decimals ), $wp_locale->number_format['decimal_point'], $wp_locale->number_format['thousands_sep'] );
  142. return apply_filters( 'number_format_i18n', $formatted );
  143. }
  144. /**
  145. * Convert number of bytes largest unit bytes will fit into.
  146. *
  147. * It is easier to read 1kB than 1024 bytes and 1MB than 1048576 bytes. Converts
  148. * number of bytes to human readable number by taking the number of that unit
  149. * that the bytes will go into it. Supports TB value.
  150. *
  151. * Please note that integers in PHP are limited to 32 bits, unless they are on
  152. * 64 bit architecture, then they have 64 bit size. If you need to place the
  153. * larger size then what PHP integer type will hold, then use a string. It will
  154. * be converted to a double, which should always have 64 bit length.
  155. *
  156. * Technically the correct unit names for powers of 1024 are KiB, MiB etc.
  157. * @link http://en.wikipedia.org/wiki/Byte
  158. *
  159. * @since 2.3.0
  160. *
  161. * @param int|string $bytes Number of bytes. Note max integer size for integers.
  162. * @param int $decimals Precision of number of decimal places. Deprecated.
  163. * @return bool|string False on failure. Number string on success.
  164. */
  165. function size_format( $bytes, $decimals = 0 ) {
  166. $quant = array(
  167. // ========================= Origin ====
  168. 'TB' => 1099511627776, // pow( 1024, 4)
  169. 'GB' => 1073741824, // pow( 1024, 3)
  170. 'MB' => 1048576, // pow( 1024, 2)
  171. 'kB' => 1024, // pow( 1024, 1)
  172. 'B ' => 1, // pow( 1024, 0)
  173. );
  174. foreach ( $quant as $unit => $mag )
  175. if ( doubleval($bytes) >= $mag )
  176. return number_format_i18n( $bytes / $mag, $decimals ) . ' ' . $unit;
  177. return false;
  178. }
  179. /**
  180. * Get the week start and end from the datetime or date string from mysql.
  181. *
  182. * @since 0.71
  183. *
  184. * @param string $mysqlstring Date or datetime field type from mysql.
  185. * @param int $start_of_week Optional. Start of the week as an integer.
  186. * @return array Keys are 'start' and 'end'.
  187. */
  188. function get_weekstartend( $mysqlstring, $start_of_week = '' ) {
  189. $my = substr( $mysqlstring, 0, 4 ); // Mysql string Year
  190. $mm = substr( $mysqlstring, 8, 2 ); // Mysql string Month
  191. $md = substr( $mysqlstring, 5, 2 ); // Mysql string day
  192. $day = mktime( 0, 0, 0, $md, $mm, $my ); // The timestamp for mysqlstring day.
  193. $weekday = date( 'w', $day ); // The day of the week from the timestamp
  194. if ( !is_numeric($start_of_week) )
  195. $start_of_week = get_option( 'start_of_week' );
  196. if ( $weekday < $start_of_week )
  197. $weekday += 7;
  198. $start = $day - DAY_IN_SECONDS * ( $weekday - $start_of_week ); // The most recent week start day on or before $day
  199. $end = $start + 7 * DAY_IN_SECONDS - 1; // $start + 7 days - 1 second
  200. return compact( 'start', 'end' );
  201. }
  202. /**
  203. * Unserialize value only if it was serialized.
  204. *
  205. * @since 2.0.0
  206. *
  207. * @param string $original Maybe unserialized original, if is needed.
  208. * @return mixed Unserialized data can be any type.
  209. */
  210. function maybe_unserialize( $original ) {
  211. if ( is_serialized( $original ) ) // don't attempt to unserialize data that wasn't serialized going in
  212. return @unserialize( $original );
  213. return $original;
  214. }
  215. /**
  216. * Check value to find if it was serialized.
  217. *
  218. * If $data is not an string, then returned value will always be false.
  219. * Serialized data is always a string.
  220. *
  221. * @since 2.0.5
  222. *
  223. * @param mixed $data Value to check to see if was serialized.
  224. * @param bool $strict Optional. Whether to be strict about the end of the string. Defaults true.
  225. * @return bool False if not serialized and true if it was.
  226. */
  227. function is_serialized( $data, $strict = true ) {
  228. // if it isn't a string, it isn't serialized
  229. if ( ! is_string( $data ) )
  230. return false;
  231. $data = trim( $data );
  232. if ( 'N;' == $data )
  233. return true;
  234. $length = strlen( $data );
  235. if ( $length < 4 )
  236. return false;
  237. if ( ':' !== $data[1] )
  238. return false;
  239. if ( $strict ) {
  240. $lastc = $data[ $length - 1 ];
  241. if ( ';' !== $lastc && '}' !== $lastc )
  242. return false;
  243. } else {
  244. $semicolon = strpos( $data, ';' );
  245. $brace = strpos( $data, '}' );
  246. // Either ; or } must exist.
  247. if ( false === $semicolon && false === $brace )
  248. return false;
  249. // But neither must be in the first X characters.
  250. if ( false !== $semicolon && $semicolon < 3 )
  251. return false;
  252. if ( false !== $brace && $brace < 4 )
  253. return false;
  254. }
  255. $token = $data[0];
  256. switch ( $token ) {
  257. case 's' :
  258. if ( $strict ) {
  259. if ( '"' !== $data[ $length - 2 ] )
  260. return false;
  261. } elseif ( false === strpos( $data, '"' ) ) {
  262. return false;
  263. }
  264. // or else fall through
  265. case 'a' :
  266. case 'O' :
  267. return (bool) preg_match( "/^{$token}:[0-9]+:/s", $data );
  268. case 'b' :
  269. case 'i' :
  270. case 'd' :
  271. $end = $strict ? '$' : '';
  272. return (bool) preg_match( "/^{$token}:[0-9.E-]+;$end/", $data );
  273. }
  274. return false;
  275. }
  276. /**
  277. * Check whether serialized data is of string type.
  278. *
  279. * @since 2.0.5
  280. *
  281. * @param mixed $data Serialized data
  282. * @return bool False if not a serialized string, true if it is.
  283. */
  284. function is_serialized_string( $data ) {
  285. // if it isn't a string, it isn't a serialized string
  286. if ( !is_string( $data ) )
  287. return false;
  288. $data = trim( $data );
  289. $length = strlen( $data );
  290. if ( $length < 4 )
  291. return false;
  292. elseif ( ':' !== $data[1] )
  293. return false;
  294. elseif ( ';' !== $data[$length-1] )
  295. return false;
  296. elseif ( $data[0] !== 's' )
  297. return false;
  298. elseif ( '"' !== $data[$length-2] )
  299. return false;
  300. else
  301. return true;
  302. }
  303. /**
  304. * Serialize data, if needed.
  305. *
  306. * @since 2.0.5
  307. *
  308. * @param mixed $data Data that might be serialized.
  309. * @return mixed A scalar data
  310. */
  311. function maybe_serialize( $data ) {
  312. if ( is_array( $data ) || is_object( $data ) )
  313. return serialize( $data );
  314. // Double serialization is required for backward compatibility.
  315. // See http://core.trac.wordpress.org/ticket/12930
  316. if ( is_serialized( $data, false ) )
  317. return serialize( $data );
  318. return $data;
  319. }
  320. /**
  321. * Retrieve post title from XMLRPC XML.
  322. *
  323. * If the title element is not part of the XML, then the default post title from
  324. * the $post_default_title will be used instead.
  325. *
  326. * @package WordPress
  327. * @subpackage XMLRPC
  328. * @since 0.71
  329. *
  330. * @global string $post_default_title Default XMLRPC post title.
  331. *
  332. * @param string $content XMLRPC XML Request content
  333. * @return string Post title
  334. */
  335. function xmlrpc_getposttitle( $content ) {
  336. global $post_default_title;
  337. if ( preg_match( '/<title>(.+?)<\/title>/is', $content, $matchtitle ) ) {
  338. $post_title = $matchtitle[1];
  339. } else {
  340. $post_title = $post_default_title;
  341. }
  342. return $post_title;
  343. }
  344. /**
  345. * Retrieve the post category or categories from XMLRPC XML.
  346. *
  347. * If the category element is not found, then the default post category will be
  348. * used. The return type then would be what $post_default_category. If the
  349. * category is found, then it will always be an array.
  350. *
  351. * @package WordPress
  352. * @subpackage XMLRPC
  353. * @since 0.71
  354. *
  355. * @global string $post_default_category Default XMLRPC post category.
  356. *
  357. * @param string $content XMLRPC XML Request content
  358. * @return string|array List of categories or category name.
  359. */
  360. function xmlrpc_getpostcategory( $content ) {
  361. global $post_default_category;
  362. if ( preg_match( '/<category>(.+?)<\/category>/is', $content, $matchcat ) ) {
  363. $post_category = trim( $matchcat[1], ',' );
  364. $post_category = explode( ',', $post_category );
  365. } else {
  366. $post_category = $post_default_category;
  367. }
  368. return $post_category;
  369. }
  370. /**
  371. * XMLRPC XML content without title and category elements.
  372. *
  373. * @package WordPress
  374. * @subpackage XMLRPC
  375. * @since 0.71
  376. *
  377. * @param string $content XMLRPC XML Request content
  378. * @return string XMLRPC XML Request content without title and category elements.
  379. */
  380. function xmlrpc_removepostdata( $content ) {
  381. $content = preg_replace( '/<title>(.+?)<\/title>/si', '', $content );
  382. $content = preg_replace( '/<category>(.+?)<\/category>/si', '', $content );
  383. $content = trim( $content );
  384. return $content;
  385. }
  386. /**
  387. * Use RegEx to extract URLs from arbitrary content
  388. *
  389. * @since 3.7.0
  390. *
  391. * @param string $content
  392. * @return array URLs found in passed string
  393. */
  394. function wp_extract_urls( $content ) {
  395. preg_match_all(
  396. "#((?:[\w-]+://?|[\w\d]+[.])[^\s()<>]+[.](?:\([\w\d]+\)|(?:[^`!()\[\]{};:'\".,<>?«»“”‘’\s]|(?:[:]\d+)?/?)+))#",
  397. $content,
  398. $post_links
  399. );
  400. $post_links = array_unique( array_map( 'html_entity_decode', $post_links[0] ) );
  401. return array_values( $post_links );
  402. }
  403. /**
  404. * Check content for video and audio links to add as enclosures.
  405. *
  406. * Will not add enclosures that have already been added and will
  407. * remove enclosures that are no longer in the post. This is called as
  408. * pingbacks and trackbacks.
  409. *
  410. * @package WordPress
  411. * @since 1.5.0
  412. *
  413. * @uses $wpdb
  414. *
  415. * @param string $content Post Content
  416. * @param int $post_ID Post ID
  417. */
  418. function do_enclose( $content, $post_ID ) {
  419. global $wpdb;
  420. //TODO: Tidy this ghetto code up and make the debug code optional
  421. include_once( ABSPATH . WPINC . '/class-IXR.php' );
  422. $post_links = array();
  423. $pung = get_enclosed( $post_ID );
  424. $post_links_temp = wp_extract_urls( $content );
  425. foreach ( $pung as $link_test ) {
  426. if ( ! in_array( $link_test, $post_links_temp ) ) { // link no longer in post
  427. $mids = $wpdb->get_col( $wpdb->prepare("SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = 'enclosure' AND meta_value LIKE (%s)", $post_ID, like_escape( $link_test ) . '%') );
  428. foreach ( $mids as $mid )
  429. delete_metadata_by_mid( 'post', $mid );
  430. }
  431. }
  432. foreach ( (array) $post_links_temp as $link_test ) {
  433. if ( !in_array( $link_test, $pung ) ) { // If we haven't pung it already
  434. $test = @parse_url( $link_test );
  435. if ( false === $test )
  436. continue;
  437. if ( isset( $test['query'] ) )
  438. $post_links[] = $link_test;
  439. elseif ( isset($test['path']) && ( $test['path'] != '/' ) && ($test['path'] != '' ) )
  440. $post_links[] = $link_test;
  441. }
  442. }
  443. foreach ( (array) $post_links as $url ) {
  444. if ( $url != '' && !$wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = 'enclosure' AND meta_value LIKE (%s)", $post_ID, like_escape( $url ) . '%' ) ) ) {
  445. if ( $headers = wp_get_http_headers( $url) ) {
  446. $len = isset( $headers['content-length'] ) ? (int) $headers['content-length'] : 0;
  447. $type = isset( $headers['content-type'] ) ? $headers['content-type'] : '';
  448. $allowed_types = array( 'video', 'audio' );
  449. // Check to see if we can figure out the mime type from
  450. // the extension
  451. $url_parts = @parse_url( $url );
  452. if ( false !== $url_parts ) {
  453. $extension = pathinfo( $url_parts['path'], PATHINFO_EXTENSION );
  454. if ( !empty( $extension ) ) {
  455. foreach ( wp_get_mime_types() as $exts => $mime ) {
  456. if ( preg_match( '!^(' . $exts . ')$!i', $extension ) ) {
  457. $type = $mime;
  458. break;
  459. }
  460. }
  461. }
  462. }
  463. if ( in_array( substr( $type, 0, strpos( $type, "/" ) ), $allowed_types ) ) {
  464. add_post_meta( $post_ID, 'enclosure', "$url\n$len\n$mime\n" );
  465. }
  466. }
  467. }
  468. }
  469. }
  470. /**
  471. * Perform a HTTP HEAD or GET request.
  472. *
  473. * If $file_path is a writable filename, this will do a GET request and write
  474. * the file to that path.
  475. *
  476. * @since 2.5.0
  477. *
  478. * @param string $url URL to fetch.
  479. * @param string|bool $file_path Optional. File path to write request to.
  480. * @param int $red (private) The number of Redirects followed, Upon 5 being hit, returns false.
  481. * @return bool|string False on failure and string of headers if HEAD request.
  482. */
  483. function wp_get_http( $url, $file_path = false, $red = 1 ) {
  484. @set_time_limit( 60 );
  485. if ( $red > 5 )
  486. return false;
  487. $options = array();
  488. $options['redirection'] = 5;
  489. if ( false == $file_path )
  490. $options['method'] = 'HEAD';
  491. else
  492. $options['method'] = 'GET';
  493. $response = wp_safe_remote_request( $url, $options );
  494. if ( is_wp_error( $response ) )
  495. return false;
  496. $headers = wp_remote_retrieve_headers( $response );
  497. $headers['response'] = wp_remote_retrieve_response_code( $response );
  498. // WP_HTTP no longer follows redirects for HEAD requests.
  499. if ( 'HEAD' == $options['method'] && in_array($headers['response'], array(301, 302)) && isset( $headers['location'] ) ) {
  500. return wp_get_http( $headers['location'], $file_path, ++$red );
  501. }
  502. if ( false == $file_path )
  503. return $headers;
  504. // GET request - write it to the supplied filename
  505. $out_fp = fopen($file_path, 'w');
  506. if ( !$out_fp )
  507. return $headers;
  508. fwrite( $out_fp, wp_remote_retrieve_body( $response ) );
  509. fclose($out_fp);
  510. clearstatcache();
  511. return $headers;
  512. }
  513. /**
  514. * Retrieve HTTP Headers from URL.
  515. *
  516. * @since 1.5.1
  517. *
  518. * @param string $url
  519. * @param bool $deprecated Not Used.
  520. * @return bool|string False on failure, headers on success.
  521. */
  522. function wp_get_http_headers( $url, $deprecated = false ) {
  523. if ( !empty( $deprecated ) )
  524. _deprecated_argument( __FUNCTION__, '2.7' );
  525. $response = wp_safe_remote_head( $url );
  526. if ( is_wp_error( $response ) )
  527. return false;
  528. return wp_remote_retrieve_headers( $response );
  529. }
  530. /**
  531. * Whether today is a new day.
  532. *
  533. * @since 0.71
  534. * @uses $day Today
  535. * @uses $previousday Previous day
  536. *
  537. * @return int 1 when new day, 0 if not a new day.
  538. */
  539. function is_new_day() {
  540. global $currentday, $previousday;
  541. if ( $currentday != $previousday )
  542. return 1;
  543. else
  544. return 0;
  545. }
  546. /**
  547. * Build URL query based on an associative and, or indexed array.
  548. *
  549. * This is a convenient function for easily building url queries. It sets the
  550. * separator to '&' and uses _http_build_query() function.
  551. *
  552. * @see _http_build_query() Used to build the query
  553. * @link http://us2.php.net/manual/en/function.http-build-query.php more on what
  554. * http_build_query() does.
  555. *
  556. * @since 2.3.0
  557. *
  558. * @param array $data URL-encode key/value pairs.
  559. * @return string URL encoded string
  560. */
  561. function build_query( $data ) {
  562. return _http_build_query( $data, null, '&', '', false );
  563. }
  564. // from php.net (modified by Mark Jaquith to behave like the native PHP5 function)
  565. function _http_build_query($data, $prefix=null, $sep=null, $key='', $urlencode=true) {
  566. $ret = array();
  567. foreach ( (array) $data as $k => $v ) {
  568. if ( $urlencode)
  569. $k = urlencode($k);
  570. if ( is_int($k) && $prefix != null )
  571. $k = $prefix.$k;
  572. if ( !empty($key) )
  573. $k = $key . '%5B' . $k . '%5D';
  574. if ( $v === null )
  575. continue;
  576. elseif ( $v === FALSE )
  577. $v = '0';
  578. if ( is_array($v) || is_object($v) )
  579. array_push($ret,_http_build_query($v, '', $sep, $k, $urlencode));
  580. elseif ( $urlencode )
  581. array_push($ret, $k.'='.urlencode($v));
  582. else
  583. array_push($ret, $k.'='.$v);
  584. }
  585. if ( null === $sep )
  586. $sep = ini_get('arg_separator.output');
  587. return implode($sep, $ret);
  588. }
  589. /**
  590. * Retrieve a modified URL query string.
  591. *
  592. * You can rebuild the URL and append a new query variable to the URL query by
  593. * using this function. You can also retrieve the full URL with query data.
  594. *
  595. * Adding a single key & value or an associative array. Setting a key value to
  596. * an empty string removes the key. Omitting oldquery_or_uri uses the $_SERVER
  597. * value. Additional values provided are expected to be encoded appropriately
  598. * with urlencode() or rawurlencode().
  599. *
  600. * @since 1.5.0
  601. *
  602. * @param mixed $param1 Either newkey or an associative_array
  603. * @param mixed $param2 Either newvalue or oldquery or uri
  604. * @param mixed $param3 Optional. Old query or uri
  605. * @return string New URL query string.
  606. */
  607. function add_query_arg() {
  608. $ret = '';
  609. $args = func_get_args();
  610. if ( is_array( $args[0] ) ) {
  611. if ( count( $args ) < 2 || false === $args[1] )
  612. $uri = $_SERVER['REQUEST_URI'];
  613. else
  614. $uri = $args[1];
  615. } else {
  616. if ( count( $args ) < 3 || false === $args[2] )
  617. $uri = $_SERVER['REQUEST_URI'];
  618. else
  619. $uri = $args[2];
  620. }
  621. if ( $frag = strstr( $uri, '#' ) )
  622. $uri = substr( $uri, 0, -strlen( $frag ) );
  623. else
  624. $frag = '';
  625. if ( 0 === stripos( $uri, 'http://' ) ) {
  626. $protocol = 'http://';
  627. $uri = substr( $uri, 7 );
  628. } elseif ( 0 === stripos( $uri, 'https://' ) ) {
  629. $protocol = 'https://';
  630. $uri = substr( $uri, 8 );
  631. } else {
  632. $protocol = '';
  633. }
  634. if ( strpos( $uri, '?' ) !== false ) {
  635. list( $base, $query ) = explode( '?', $uri, 2 );
  636. $base .= '?';
  637. } elseif ( $protocol || strpos( $uri, '=' ) === false ) {
  638. $base = $uri . '?';
  639. $query = '';
  640. } else {
  641. $base = '';
  642. $query = $uri;
  643. }
  644. wp_parse_str( $query, $qs );
  645. $qs = urlencode_deep( $qs ); // this re-URL-encodes things that were already in the query string
  646. if ( is_array( $args[0] ) ) {
  647. $kayvees = $args[0];
  648. $qs = array_merge( $qs, $kayvees );
  649. } else {
  650. $qs[ $args[0] ] = $args[1];
  651. }
  652. foreach ( $qs as $k => $v ) {
  653. if ( $v === false )
  654. unset( $qs[$k] );
  655. }
  656. $ret = build_query( $qs );
  657. $ret = trim( $ret, '?' );
  658. $ret = preg_replace( '#=(&|$)#', '$1', $ret );
  659. $ret = $protocol . $base . $ret . $frag;
  660. $ret = rtrim( $ret, '?' );
  661. return $ret;
  662. }
  663. /**
  664. * Removes an item or list from the query string.
  665. *
  666. * @since 1.5.0
  667. *
  668. * @param string|array $key Query key or keys to remove.
  669. * @param bool $query When false uses the $_SERVER value.
  670. * @return string New URL query string.
  671. */
  672. function remove_query_arg( $key, $query=false ) {
  673. if ( is_array( $key ) ) { // removing multiple keys
  674. foreach ( $key as $k )
  675. $query = add_query_arg( $k, false, $query );
  676. return $query;
  677. }
  678. return add_query_arg( $key, false, $query );
  679. }
  680. /**
  681. * Walks the array while sanitizing the contents.
  682. *
  683. * @since 0.71
  684. *
  685. * @param array $array Array to walk while sanitizing contents.
  686. * @return array Sanitized $array.
  687. */
  688. function add_magic_quotes( $array ) {
  689. foreach ( (array) $array as $k => $v ) {
  690. if ( is_array( $v ) ) {
  691. $array[$k] = add_magic_quotes( $v );
  692. } else {
  693. $array[$k] = addslashes( $v );
  694. }
  695. }
  696. return $array;
  697. }
  698. /**
  699. * HTTP request for URI to retrieve content.
  700. *
  701. * @since 1.5.1
  702. * @uses wp_remote_get()
  703. *
  704. * @param string $uri URI/URL of web page to retrieve.
  705. * @return bool|string HTTP content. False on failure.
  706. */
  707. function wp_remote_fopen( $uri ) {
  708. $parsed_url = @parse_url( $uri );
  709. if ( !$parsed_url || !is_array( $parsed_url ) )
  710. return false;
  711. $options = array();
  712. $options['timeout'] = 10;
  713. $response = wp_safe_remote_get( $uri, $options );
  714. if ( is_wp_error( $response ) )
  715. return false;
  716. return wp_remote_retrieve_body( $response );
  717. }
  718. /**
  719. * Set up the WordPress query.
  720. *
  721. * @since 2.0.0
  722. *
  723. * @param string $query_vars Default WP_Query arguments.
  724. */
  725. function wp( $query_vars = '' ) {
  726. global $wp, $wp_query, $wp_the_query;
  727. $wp->main( $query_vars );
  728. if ( !isset($wp_the_query) )
  729. $wp_the_query = $wp_query;
  730. }
  731. /**
  732. * Retrieve the description for the HTTP status.
  733. *
  734. * @since 2.3.0
  735. *
  736. * @param int $code HTTP status code.
  737. * @return string Empty string if not found, or description if found.
  738. */
  739. function get_status_header_desc( $code ) {
  740. global $wp_header_to_desc;
  741. $code = absint( $code );
  742. if ( !isset( $wp_header_to_desc ) ) {
  743. $wp_header_to_desc = array(
  744. 100 => 'Continue',
  745. 101 => 'Switching Protocols',
  746. 102 => 'Processing',
  747. 200 => 'OK',
  748. 201 => 'Created',
  749. 202 => 'Accepted',
  750. 203 => 'Non-Authoritative Information',
  751. 204 => 'No Content',
  752. 205 => 'Reset Content',
  753. 206 => 'Partial Content',
  754. 207 => 'Multi-Status',
  755. 226 => 'IM Used',
  756. 300 => 'Multiple Choices',
  757. 301 => 'Moved Permanently',
  758. 302 => 'Found',
  759. 303 => 'See Other',
  760. 304 => 'Not Modified',
  761. 305 => 'Use Proxy',
  762. 306 => 'Reserved',
  763. 307 => 'Temporary Redirect',
  764. 400 => 'Bad Request',
  765. 401 => 'Unauthorized',
  766. 402 => 'Payment Required',
  767. 403 => 'Forbidden',
  768. 404 => 'Not Found',
  769. 405 => 'Method Not Allowed',
  770. 406 => 'Not Acceptable',
  771. 407 => 'Proxy Authentication Required',
  772. 408 => 'Request Timeout',
  773. 409 => 'Conflict',
  774. 410 => 'Gone',
  775. 411 => 'Length Required',
  776. 412 => 'Precondition Failed',
  777. 413 => 'Request Entity Too Large',
  778. 414 => 'Request-URI Too Long',
  779. 415 => 'Unsupported Media Type',
  780. 416 => 'Requested Range Not Satisfiable',
  781. 417 => 'Expectation Failed',
  782. 422 => 'Unprocessable Entity',
  783. 423 => 'Locked',
  784. 424 => 'Failed Dependency',
  785. 426 => 'Upgrade Required',
  786. 500 => 'Internal Server Error',
  787. 501 => 'Not Implemented',
  788. 502 => 'Bad Gateway',
  789. 503 => 'Service Unavailable',
  790. 504 => 'Gateway Timeout',
  791. 505 => 'HTTP Version Not Supported',
  792. 506 => 'Variant Also Negotiates',
  793. 507 => 'Insufficient Storage',
  794. 510 => 'Not Extended'
  795. );
  796. }
  797. if ( isset( $wp_header_to_desc[$code] ) )
  798. return $wp_header_to_desc[$code];
  799. else
  800. return '';
  801. }
  802. /**
  803. * Set HTTP status header.
  804. *
  805. * @since 2.0.0
  806. * @uses apply_filters() Calls 'status_header' on status header string, HTTP
  807. * HTTP code, HTTP code description, and protocol string as separate
  808. * parameters.
  809. *
  810. * @param int $header HTTP status code
  811. * @return unknown
  812. */
  813. function status_header( $header ) {
  814. $text = get_status_header_desc( $header );
  815. if ( empty( $text ) )
  816. return false;
  817. $protocol = $_SERVER["SERVER_PROTOCOL"];
  818. if ( 'HTTP/1.1' != $protocol && 'HTTP/1.0' != $protocol )
  819. $protocol = 'HTTP/1.0';
  820. $status_header = "$protocol $header $text";
  821. if ( function_exists( 'apply_filters' ) )
  822. $status_header = apply_filters( 'status_header', $status_header, $header, $text, $protocol );
  823. return @header( $status_header, true, $header );
  824. }
  825. /**
  826. * Gets the header information to prevent caching.
  827. *
  828. * The several different headers cover the different ways cache prevention is handled
  829. * by different browsers
  830. *
  831. * @since 2.8.0
  832. *
  833. * @uses apply_filters()
  834. * @return array The associative array of header names and field values.
  835. */
  836. function wp_get_nocache_headers() {
  837. $headers = array(
  838. 'Expires' => 'Wed, 11 Jan 1984 05:00:00 GMT',
  839. 'Cache-Control' => 'no-cache, must-revalidate, max-age=0',
  840. 'Pragma' => 'no-cache',
  841. );
  842. if ( function_exists('apply_filters') ) {
  843. $headers = (array) apply_filters('nocache_headers', $headers);
  844. }
  845. $headers['Last-Modified'] = false;
  846. return $headers;
  847. }
  848. /**
  849. * Sets the headers to prevent caching for the different browsers.
  850. *
  851. * Different browsers support different nocache headers, so several headers must
  852. * be sent so that all of them get the point that no caching should occur.
  853. *
  854. * @since 2.0.0
  855. * @uses wp_get_nocache_headers()
  856. */
  857. function nocache_headers() {
  858. $headers = wp_get_nocache_headers();
  859. unset( $headers['Last-Modified'] );
  860. // In PHP 5.3+, make sure we are not sending a Last-Modified header.
  861. if ( function_exists( 'header_remove' ) ) {
  862. @header_remove( 'Last-Modified' );
  863. } else {
  864. // In PHP 5.2, send an empty Last-Modified header, but only as a
  865. // last resort to override a header already sent. #WP23021
  866. foreach ( headers_list() as $header ) {
  867. if ( 0 === stripos( $header, 'Last-Modified' ) ) {
  868. $headers['Last-Modified'] = '';
  869. break;
  870. }
  871. }
  872. }
  873. foreach( $headers as $name => $field_value )
  874. @header("{$name}: {$field_value}");
  875. }
  876. /**
  877. * Set the headers for caching for 10 days with JavaScript content type.
  878. *
  879. * @since 2.1.0
  880. */
  881. function cache_javascript_headers() {
  882. $expiresOffset = 10 * DAY_IN_SECONDS;
  883. header( "Content-Type: text/javascript; charset=" . get_bloginfo( 'charset' ) );
  884. header( "Vary: Accept-Encoding" ); // Handle proxies
  885. header( "Expires: " . gmdate( "D, d M Y H:i:s", time() + $expiresOffset ) . " GMT" );
  886. }
  887. /**
  888. * Retrieve the number of database queries during the WordPress execution.
  889. *
  890. * @since 2.0.0
  891. *
  892. * @return int Number of database queries
  893. */
  894. function get_num_queries() {
  895. global $wpdb;
  896. return $wpdb->num_queries;
  897. }
  898. /**
  899. * Whether input is yes or no. Must be 'y' to be true.
  900. *
  901. * @since 1.0.0
  902. *
  903. * @param string $yn Character string containing either 'y' or 'n'
  904. * @return bool True if yes, false on anything else
  905. */
  906. function bool_from_yn( $yn ) {
  907. return ( strtolower( $yn ) == 'y' );
  908. }
  909. /**
  910. * Loads the feed template from the use of an action hook.
  911. *
  912. * If the feed action does not have a hook, then the function will die with a
  913. * message telling the visitor that the feed is not valid.
  914. *
  915. * It is better to only have one hook for each feed.
  916. *
  917. * @since 2.1.0
  918. * @uses $wp_query Used to tell if the use a comment feed.
  919. * @uses do_action() Calls 'do_feed_$feed' hook, if a hook exists for the feed.
  920. */
  921. function do_feed() {
  922. global $wp_query;
  923. $feed = get_query_var( 'feed' );
  924. // Remove the pad, if present.
  925. $feed = preg_replace( '/^_+/', '', $feed );
  926. if ( $feed == '' || $feed == 'feed' )
  927. $feed = get_default_feed();
  928. $hook = 'do_feed_' . $feed;
  929. if ( ! has_action( $hook ) )
  930. wp_die( __( 'ERROR: This is not a valid feed template.' ), '', array( 'response' => 404 ) );
  931. do_action( $hook, $wp_query->is_comment_feed );
  932. }
  933. /**
  934. * Load the RDF RSS 0.91 Feed template.
  935. *
  936. * @since 2.1.0
  937. */
  938. function do_feed_rdf() {
  939. load_template( ABSPATH . WPINC . '/feed-rdf.php' );
  940. }
  941. /**
  942. * Load the RSS 1.0 Feed Template.
  943. *
  944. * @since 2.1.0
  945. */
  946. function do_feed_rss() {
  947. load_template( ABSPATH . WPINC . '/feed-rss.php' );
  948. }
  949. /**
  950. * Load either the RSS2 comment feed or the RSS2 posts feed.
  951. *
  952. * @since 2.1.0
  953. *
  954. * @param bool $for_comments True for the comment feed, false for normal feed.
  955. */
  956. function do_feed_rss2( $for_comments ) {
  957. if ( $for_comments )
  958. load_template( ABSPATH . WPINC . '/feed-rss2-comments.php' );
  959. else
  960. load_template( ABSPATH . WPINC . '/feed-rss2.php' );
  961. }
  962. /**
  963. * Load either Atom comment feed or Atom posts feed.
  964. *
  965. * @since 2.1.0
  966. *
  967. * @param bool $for_comments True for the comment feed, false for normal feed.
  968. */
  969. function do_feed_atom( $for_comments ) {
  970. if ($for_comments)
  971. load_template( ABSPATH . WPINC . '/feed-atom-comments.php');
  972. else
  973. load_template( ABSPATH . WPINC . '/feed-atom.php' );
  974. }
  975. /**
  976. * Display the robots.txt file content.
  977. *
  978. * The echo content should be with usage of the permalinks or for creating the
  979. * robots.txt file.
  980. *
  981. * @since 2.1.0
  982. * @uses do_action() Calls 'do_robotstxt' hook for displaying robots.txt rules.
  983. */
  984. function do_robots() {
  985. header( 'Content-Type: text/plain; charset=utf-8' );
  986. do_action( 'do_robotstxt' );
  987. $output = "User-agent: *\n";
  988. $public = get_option( 'blog_public' );
  989. if ( '0' == $public ) {
  990. $output .= "Disallow: /\n";
  991. } else {
  992. $site_url = parse_url( site_url() );
  993. $path = ( !empty( $site_url['path'] ) ) ? $site_url['path'] : '';
  994. $output .= "Disallow: $path/wp-admin/\n";
  995. $output .= "Disallow: $path/wp-includes/\n";
  996. }
  997. echo apply_filters('robots_txt', $output, $public);
  998. }
  999. /**
  1000. * Test whether blog is already installed.
  1001. *
  1002. * The cache will be checked first. If you have a cache plugin, which saves the
  1003. * cache values, then this will work. If you use the default WordPress cache,
  1004. * and the database goes away, then you might have problems.
  1005. *
  1006. * Checks for the option siteurl for whether WordPress is installed.
  1007. *
  1008. * @since 2.1.0
  1009. * @uses $wpdb
  1010. *
  1011. * @return bool Whether blog is already installed.
  1012. */
  1013. function is_blog_installed() {
  1014. global $wpdb;
  1015. // Check cache first. If options table goes away and we have true cached, oh well.
  1016. if ( wp_cache_get( 'is_blog_installed' ) )
  1017. return true;
  1018. $suppress = $wpdb->suppress_errors();
  1019. if ( ! defined( 'WP_INSTALLING' ) ) {
  1020. $alloptions = wp_load_alloptions();
  1021. }
  1022. // If siteurl is not set to autoload, check it specifically
  1023. if ( !isset( $alloptions['siteurl'] ) )
  1024. $installed = $wpdb->get_var( "SELECT option_value FROM $wpdb->options WHERE option_name = 'siteurl'" );
  1025. else
  1026. $installed = $alloptions['siteurl'];
  1027. $wpdb->suppress_errors( $suppress );
  1028. $installed = !empty( $installed );
  1029. wp_cache_set( 'is_blog_installed', $installed );
  1030. if ( $installed )
  1031. return true;
  1032. // If visiting repair.php, return true and let it take over.
  1033. if ( defined( 'WP_REPAIRING' ) )
  1034. return true;
  1035. $suppress = $wpdb->suppress_errors();
  1036. // Loop over the WP tables. If none exist, then scratch install is allowed.
  1037. // If one or more exist, suggest table repair since we got here because the options
  1038. // table could not be accessed.
  1039. $wp_tables = $wpdb->tables();
  1040. foreach ( $wp_tables as $table ) {
  1041. // The existence of custom user tables shouldn't suggest an insane state or prevent a clean install.
  1042. if ( defined( 'CUSTOM_USER_TABLE' ) && CUSTOM_USER_TABLE == $table )
  1043. continue;
  1044. if ( defined( 'CUSTOM_USER_META_TABLE' ) && CUSTOM_USER_META_TABLE == $table )
  1045. continue;
  1046. if ( ! $wpdb->get_results( "DESCRIBE $table;" ) )
  1047. continue;
  1048. // One or more tables exist. We are insane.
  1049. wp_load_translations_early();
  1050. // Die with a DB error.
  1051. $wpdb->error = sprintf( __( 'One or more database tables are unavailable. The database may need to be <a href="%s">repaired</a>.' ), 'maint/repair.php?referrer=is_blog_installed' );
  1052. dead_db();
  1053. }
  1054. $wpdb->suppress_errors( $suppress );
  1055. wp_cache_set( 'is_blog_installed', false );
  1056. return false;
  1057. }
  1058. /**
  1059. * Retrieve URL with nonce added to URL query.
  1060. *
  1061. * @package WordPress
  1062. * @subpackage Security
  1063. * @since 2.0.4
  1064. *
  1065. * @param string $actionurl URL to add nonce action.
  1066. * @param string $action Optional. Nonce action name.
  1067. * @param string $name Optional. Nonce name.
  1068. * @return string URL with nonce action added.
  1069. */
  1070. function wp_nonce_url( $actionurl, $action = -1, $name = '_wpnonce' ) {
  1071. $actionurl = str_replace( '&amp;', '&', $actionurl );
  1072. return esc_html( add_query_arg( $name, wp_create_nonce( $action ), $actionurl ) );
  1073. }
  1074. /**
  1075. * Retrieve or display nonce hidden field for forms.
  1076. *
  1077. * The nonce field is used to validate that the contents of the form came from
  1078. * the location on the current site and not somewhere else. The nonce does not
  1079. * offer absolute protection, but should protect against most cases. It is very
  1080. * important to use nonce field in forms.
  1081. *
  1082. * The $action and $name are optional, but if you want to have better security,
  1083. * it is strongly suggested to set those two parameters. It is easier to just
  1084. * call the function without any parameters, because validation of the nonce
  1085. * doesn't require any parameters, but since crackers know what the default is
  1086. * it won't be difficult for them to find a way around your nonce and cause
  1087. * damage.
  1088. *
  1089. * The input name will be whatever $name value you gave. The input value will be
  1090. * the nonce creation value.
  1091. *
  1092. * @package WordPress
  1093. * @subpackage Security
  1094. * @since 2.0.4
  1095. *
  1096. * @param string $action Optional. Action name.
  1097. * @param string $name Optional. Nonce name.
  1098. * @param bool $referer Optional, default true. Whether to set the referer field for validation.
  1099. * @param bool $echo Optional, default true. Whether to display or return hidden form field.
  1100. * @return string Nonce field.
  1101. */
  1102. function wp_nonce_field( $action = -1, $name = "_wpnonce", $referer = true , $echo = true ) {
  1103. $name = esc_attr( $name );
  1104. $nonce_field = '<input type="hidden" id="' . $name . '" name="' . $name . '" value="' . wp_create_nonce( $action ) . '" />';
  1105. if ( $referer )
  1106. $nonce_field .= wp_referer_field( false );
  1107. if ( $echo )
  1108. echo $nonce_field;
  1109. return $nonce_field;
  1110. }
  1111. /**
  1112. * Retrieve or display referer hidden field for forms.
  1113. *
  1114. * The referer link is the current Request URI from the server super global. The
  1115. * input name is '_wp_http_referer', in case you wanted to check manually.
  1116. *
  1117. * @package WordPress
  1118. * @subpackage Security
  1119. * @since 2.0.4
  1120. *
  1121. * @param bool $echo Whether to echo or return the referer field.
  1122. * @return string Referer field.
  1123. */
  1124. function wp_referer_field( $echo = true ) {
  1125. $referer_field = '<input type="hidden" name="_wp_http_referer" value="'. esc_attr( wp_unslash( $_SERVER['REQUEST_URI'] ) ) . '" />';
  1126. if ( $echo )
  1127. echo $referer_field;
  1128. return $referer_field;
  1129. }
  1130. /**
  1131. * Retrieve or display original referer hidden field for forms.
  1132. *
  1133. * The input name is '_wp_original_http_referer' and will be either the same
  1134. * value of {@link wp_referer_field()}, if that was posted already or it will
  1135. * be the current page, if it doesn't exist.
  1136. *
  1137. * @package WordPress
  1138. * @subpackage Security
  1139. * @since 2.0.4
  1140. *
  1141. * @param bool $echo Whether to echo the original http referer
  1142. * @param string $jump_back_to Optional, default is 'current'. Can be 'previous' or page you want to jump back to.
  1143. * @return string Original referer field.
  1144. */
  1145. function wp_original_referer_field( $echo = true, $jump_back_to = 'current' ) {
  1146. if ( ! $ref = wp_get_original_referer() ) {
  1147. $ref = 'previous' == $jump_back_to ? wp_get_referer() : wp_unslash( $_SERVER['REQUEST_URI'] );
  1148. }
  1149. $orig_referer_field = '<input type="hidden" name="_wp_original_http_referer" value="' . esc_attr( $ref ) . '" />';
  1150. if ( $echo )
  1151. echo $orig_referer_field;
  1152. return $orig_referer_field;
  1153. }
  1154. /**
  1155. * Retrieve referer from '_wp_http_referer' or HTTP referer. If it's the same
  1156. * as the current request URL, will return false.
  1157. *
  1158. * @package WordPress
  1159. * @subpackage Security
  1160. * @since 2.0.4
  1161. *
  1162. * @return string|bool False on failure. Referer URL on success.
  1163. */
  1164. function wp_get_referer() {
  1165. if ( ! function_exists( 'wp_validate_redirect' ) )
  1166. return false;
  1167. $ref = false;
  1168. if ( ! empty( $_REQUEST['_wp_http_referer'] ) )
  1169. $ref = wp_unslash( $_REQUEST['_wp_http_referer'] );
  1170. else if ( ! empty( $_SERVER['HTTP_REFERER'] ) )
  1171. $ref = wp_unslash( $_SERVER['HTTP_REFERER'] );
  1172. if ( $ref && $ref !== wp_unslash( $_SERVER['REQUEST_URI'] ) )
  1173. return wp_validate_redirect( $ref, false );
  1174. return false;
  1175. }
  1176. /**
  1177. * Retrieve original referer that was posted, if it exists.
  1178. *
  1179. * @package WordPress
  1180. * @subpackage Security
  1181. * @since 2.0.4
  1182. *
  1183. * @return string|bool False if no original referer or original referer if set.
  1184. */
  1185. function wp_get_original_referer() {
  1186. if ( ! empty( $_REQUEST['_wp_original_http_referer'] ) && function_exists( 'wp_validate_redirect' ) )
  1187. return wp_validate_redirect( wp_unslash( $_REQUEST['_wp_original_http_referer'] ), false );
  1188. return false;
  1189. }
  1190. /**
  1191. * Recursive directory creation based on full path.
  1192. *
  1193. * Will attempt to set permissions on folders.
  1194. *
  1195. * @since 2.0.1
  1196. *
  1197. * @param string $target Full path to attempt to create.
  1198. * @return bool Whether the path was created. True if path already exists.
  1199. */
  1200. function wp_mkdir_p( $target ) {
  1201. $wrapper = null;
  1202. // strip the protocol
  1203. if( wp_is_stream( $target ) ) {
  1204. list( $wrapper, $target ) = explode( '://', $target, 2 );
  1205. }
  1206. // from php.net/mkdir user contributed notes
  1207. $target = str_replace( '//', '/', $target );
  1208. // put the wrapper back on the target
  1209. if( $wrapper !== null ) {
  1210. $target = $wrapper . '://' . $target;
  1211. }
  1212. // safe mode fails with a trailing slash under certain PHP versions.
  1213. $target = rtrim($target, '/'); // Use rtrim() instead of untrailingslashit to avoid formatting.php dependency.
  1214. if ( empty($target) )
  1215. $target = '/';
  1216. if ( file_exists( $target ) )
  1217. return @is_dir( $target );
  1218. // We need to find the permissions of the parent folder that exists and inherit that.
  1219. $target_parent = dirname( $target );
  1220. while ( '.' != $target_parent && ! is_dir( $target_parent ) ) {
  1221. $target_parent = dirname( $target_parent );
  1222. }
  1223. // Get the permission bits.
  1224. if ( $target_parent && '.' != $target_parent ) {
  1225. $stat = @stat( $target_parent );
  1226. $dir_perms = $stat['mode'] & 0007777;
  1227. } else {
  1228. $dir_perms = 0777;
  1229. }
  1230. if ( @mkdir( $target, $dir_perms, true ) ) {
  1231. return true;
  1232. }
  1233. return false;
  1234. }
  1235. /**
  1236. * Test if a give filesystem path is absolute ('/foo/bar', 'c:\windows').
  1237. *
  1238. * @since 2.5.0
  1239. *
  1240. * @param string $path File path
  1241. * @return bool True if path is absolute, false is not absolute.
  1242. */
  1243. function path_is_absolute( $path ) {
  1244. // this is definitive if true but fails if $path does not exist or contains a symbolic link
  1245. if ( realpath($path) == $path )
  1246. return true;
  1247. if ( strlen($path) == 0 || $path[0] == '.' )
  1248. return false;
  1249. // windows allows absolute paths like this
  1250. if ( preg_match('#^[a-zA-Z]:\\\\#', $path) )
  1251. return true;
  1252. // a path starting with / or \ is absolute; anything else is relative
  1253. return ( $path[0] == '/' || $path[0] == '\\' );
  1254. }
  1255. /**
  1256. * Join two filesystem paths together (e.g. 'give me $path relative to $base').
  1257. *
  1258. * If the $path is absolute, then it the full path is returned.
  1259. *
  1260. * @since 2.5.0
  1261. *
  1262. * @param string $base
  1263. * @param string $path
  1264. * @return string The path with the base or absolute path.
  1265. */
  1266. function path_join( $base, $path ) {
  1267. if ( path_is_absolute($path) )
  1268. return $path;
  1269. return rtrim($base, '/') . '/' . ltrim($path, '/');
  1270. }
  1271. /**
  1272. * Determines a writable directory for temporary files.
  1273. * Function's preference is the return value of <code>sys_get_temp_dir()</code>,
  1274. * followed by your PHP temporary upload directory, followed by WP_CONTENT_DIR,
  1275. * before finally defaulting to /tmp/
  1276. *
  1277. * In the event that this function does not find a writable location,
  1278. * It may be overridden by the <code>WP_TEMP_DIR</code> constant in
  1279. * your <code>wp-config.php</code> file.
  1280. *
  1281. * @since 2.5.0
  1282. *
  1283. * @return string Writable temporary directory
  1284. */
  1285. function get_temp_dir() {
  1286. static $temp;
  1287. if ( defined('WP_TEMP_DIR') )
  1288. return trailingslashit(WP_TEMP_DIR);
  1289. if ( $temp )
  1290. return trailingslashit( rtrim( $temp, '\\' ) );
  1291. if ( function_exists('sys_get_temp_dir') ) {
  1292. $temp = sys_get_temp_dir();
  1293. if ( @is_dir( $temp ) && wp_is_writable( $temp ) )
  1294. return trailingslashit( rtrim( $temp, '\\' ) );
  1295. }
  1296. $temp = ini_get('upload_tmp_dir');
  1297. if ( @is_dir( $temp ) && wp_is_writable( $temp ) )
  1298. return trailingslashit( rtrim( $temp, '\\' ) );
  1299. $temp = WP_CONTENT_DIR . '/';
  1300. if ( is_dir( $temp ) && wp_is_writable( $temp ) )
  1301. return $temp;
  1302. $temp = '/tmp/';
  1303. return $temp;
  1304. }
  1305. /**
  1306. * Determine if a directory is writable.
  1307. *
  1308. * This function is used to work around certain ACL issues
  1309. * in PHP primarily affecting Windows Servers.
  1310. *
  1311. * @see win_is_writable()
  1312. *
  1313. * @since 3.6.0
  1314. *
  1315. * @param string $path
  1316. * @return bool
  1317. */
  1318. function wp_is_writable( $path ) {
  1319. if ( 'WIN' === strtoupper( substr( PHP_OS, 0, 3 ) ) )
  1320. return win_is_writable( $path );
  1321. else
  1322. return @is_writable( $path );
  1323. }
  1324. /**
  1325. * Workaround for Windows bug in is_writable() function
  1326. *
  1327. * PHP has issues with Windows ACL's for determine if a
  1328. * directory is writable or not, this works around them by
  1329. * checking the ability to open files rather than relying
  1330. * upon PHP to interprate the OS ACL.
  1331. *
  1332. * @link http://bugs.php.net/bug.php?id=27609
  1333. * @link http://bugs.php.net/bug.php?id=30931
  1334. *
  1335. * @since 2.8.0
  1336. *
  1337. * @param string $path
  1338. * @return bool
  1339. */
  1340. function win_is_writable( $path ) {
  1341. if ( $path[strlen( $path ) - 1] == '/' ) // if it looks like a directory, check a random file within the directory
  1342. return win_is_writable( $path . uniqid( mt_rand() ) . '.tmp');
  1343. else if ( is_dir( $path ) ) // If it's a directory (and not a file) check a random file within the directory
  1344. return win_is_writable( $path . '/' . uniqid( mt_rand() ) . '.tmp' );
  1345. // check tmp file for read/write capabilities
  1346. $should_delete_tmp_file = !file_exists( $path );
  1347. $f = @fopen( $path, 'a' );
  1348. if ( $f === false )
  1349. return false;
  1350. fclose( $f );
  1351. if ( $should_delete_tmp_file )
  1352. unlink( $path );
  1353. return true;
  1354. }
  1355. /**
  1356. * Get an array containing the current upload directory's path and url.
  1357. *
  1358. * Checks the 'upload_path' option, which should be from the web root folder,
  1359. * and if it isn't empty it will be used. If it is empty, then the path will be
  1360. * 'WP_CONTENT_DIR/uploads'. If the 'UPLOADS' constant is defined, then it will
  1361. * override the 'upload_path' option and 'WP_CONTENT_DIR/uploads' path.
  1362. *
  1363. * The upload URL path is set either by the 'upload_url_path' option or by using
  1364. * the 'WP_CONTENT_URL' constant and appending '/uploads' to the path.
  1365. *
  1366. * If the 'uploads_use_yearmonth_folders' is set to true (checkbox if checked in
  1367. * the administration settings panel), then the time will be used. The format
  1368. * will be year first and then month.
  1369. *
  1370. * If the path couldn't be created, then an error will be returned with the key
  1371. * 'error' containing the error message. The error suggests that the parent
  1372. * directory is not writable by the server.
  1373. *
  1374. * On success, the returned array will have many indices:
  1375. * 'path' - base directory and sub directory or full path to upload directory.
  1376. * 'url' - base url and sub directory or absolute URL to upload directory.
  1377. * 'subdir' - sub directory if uploads use year/month folders option is on.
  1378. * 'basedir' - path without subdir.
  1379. * 'baseurl' - URL path without subdir.
  1380. * 'error' - set to false.
  1381. *
  1382. * @since 2.0.0
  1383. * @uses apply_filters() Calls 'upload_dir' on returned array.
  1384. *
  1385. * @param string $time Optional. Time formatted in 'yyyy/mm'.
  1386. * @return array See above for description.
  1387. */
  1388. function wp_upload_dir( $time = null ) {
  1389. $siteurl = get_option( 'siteurl' );
  1390. $upload_path = trim( get_option( 'upload_path' ) );
  1391. if ( empty( $upload_path ) || 'wp-content/uploads' == $upload_path ) {
  1392. $dir = WP_CONTENT_DIR . '/uploads';
  1393. } elseif ( 0 !== strpos( $upload_path, ABSPATH ) ) {
  1394. // $dir is absolute, $upload_path is (maybe) relative to ABSPATH
  1395. $dir = path_join( ABSPATH, $upload_path );
  1396. } else {
  1397. $dir = $upload_path;
  1398. }
  1399. if ( !$url = get_option( 'upload_url_path' ) ) {
  1400. if ( empty($upload_path) || ( 'wp-content/uploads' == $upload_path ) || ( $upload_path == $dir ) )
  1401. $url = WP_CONTENT_URL . '/uploads';
  1402. else
  1403. $url = trailingslashit( $siteurl ) . $upload_path;
  1404. }
  1405. // Obey the value of UPLOADS. This happens as long as ms-files rewriting is disabled.
  1406. // We also sometimes obey UPLOADS when rewriting is enabled -- see the next block.
  1407. if ( defined( 'UPLOADS' ) && ! ( is_multisite() && get_site_option( 'ms_files_rewriting' ) ) ) {
  1408. $dir = ABSPATH . UPLOADS;
  1409. $url = trailingslashit( $siteurl ) . UPLOADS;
  1410. }
  1411. // If multisite (and if not the main site in a post-MU network)
  1412. if ( is_multisite() && ! ( is_main_network() && is_main_site() && defined( 'MULTISITE' ) ) ) {
  1413. if ( ! get_site_option( 'ms_files_rewriting' ) ) {
  1414. // If ms-files rewriting is disabled (networks created post-3.5), it is fairly straightforward:
  1415. // Append sites/%d if we're not on the main site (for post-MU networks). (The extra directory
  1416. // prevents a four-digit ID from conflicting with a year-based directory for the main site.
  1417. // But if a MU-era network has disabled ms-files rewriting manually, they don't need the extra
  1418. // directory, as they never had wp-content/uploads for the main site.)
  1419. if ( defined( 'MULTISITE' ) )
  1420. $ms_dir = '/sites/' . get_current_blog_id();
  1421. else
  1422. $ms_dir = '/' . get_current_blog_id();
  1423. $dir .= $ms_dir;
  1424. $url .= $ms_dir;
  1425. } elseif ( defined( 'UPLOADS' ) && ! ms_is_switched() ) {
  1426. // Handle the old-form ms-files.php rewriting if the network still has that enabled.
  1427. // When ms-files rewriting is enabled, then we only listen to UPLOADS when:
  1428. // 1) we are not on the main site in a post-MU network,
  1429. // as wp-content/uploads is used there, and
  1430. // 2) we are not switched, as ms_upload_constants() hardcodes
  1431. // these constants to reflect the original blog ID.
  1432. //
  1433. // Rather than UPLOADS, we actually use BLOGUPLOADDIR if it is set, as it is absolute.
  1434. // (And it will be set, see ms_upload_constants().) Otherwise, UPLOADS can be used, as
  1435. // as it is relative to ABSPATH. For the final piece: when UPLOADS is used with ms-files
  1436. // rewriting in multisite, the resulting URL is /files. (#WP22702 for background.)
  1437. if ( defined( 'BLOGUPLOADDIR' ) )
  1438. $dir = untrailingslashit( BLOGUPLOADDIR );
  1439. else
  1440. $dir = ABSPATH . UPLOADS;
  1441. $url = trailingslashit( $siteurl ) . 'files';
  1442. }
  1443. }
  1444. $basedir = $dir;
  1445. $baseurl = $url;
  1446. $subdir = '';
  1447. if ( get_option( 'uploads_use_yearmonth_folders' ) ) {
  1448. // Generate the yearly and monthly dirs
  1449. if ( !$time )
  1450. $time = current_time( 'mysql' );
  1451. $y = substr( $time, 0, 4 );
  1452. $m = substr( $time, 5, 2 );
  1453. $subdir = "/$y/$m";
  1454. }
  1455. $dir .= $subdir;
  1456. $url .= $subdir;
  1457. $uploads = apply_filters( 'upload_dir',
  1458. array(
  1459. 'path' => $dir,
  1460. 'url' => $url,
  1461. 'subdir' => $subdir,
  1462. 'basedir' => $basedir,
  1463. 'baseurl' => $baseurl,
  1464. 'error' => false,
  1465. ) );
  1466. // Make sure we have an uploads dir
  1467. if ( ! wp_mkdir_p( $uploads['path'] ) ) {
  1468. if ( 0 === strpos( $uploads['basedir'], ABSPATH ) )
  1469. $error_path = str_replace( ABSPATH, '', $uploads['basedir'] ) . $uploads['subdir'];
  1470. else
  1471. $error_path = basename( $uploads['basedir'] ) . $uploads['subdir'];
  1472. $message = sprintf( __( 'Unable to create directory %s. Is its parent directory writable by the server?' ), $error_path );
  1473. $uploads['error'] = $message;
  1474. }
  1475. return $uploads;
  1476. }
  1477. /**
  1478. * Get a filename that is sanitized and unique for the given directory.
  1479. *
  1480. * If the filename is not u…

Large files files are truncated, but you can click here to view the full file