PageRenderTime 82ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-includes/functions.php

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