Advertisement
Guest User

Untitled

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