You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

5641 lines
171 KiB

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