PageRenderTime 46ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-includes/class-wp-embed.php

https://gitlab.com/code26/selah
PHP | 479 lines | 222 code | 66 blank | 191 comment | 35 complexity | dc585b8ff55341bd21e573696ea76192 MD5 | raw file
  1. <?php
  2. /**
  3. * API for easily embedding rich media such as videos and images into content.
  4. *
  5. * @package WordPress
  6. * @subpackage Embed
  7. * @since 2.9.0
  8. */
  9. class WP_Embed {
  10. public $handlers = array();
  11. public $post_ID;
  12. public $usecache = true;
  13. public $linkifunknown = true;
  14. public $last_attr = array();
  15. public $last_url = '';
  16. /**
  17. * When a URL cannot be embedded, return false instead of returning a link
  18. * or the URL.
  19. *
  20. * Bypasses the {@see 'embed_maybe_make_link'} filter.
  21. *
  22. * @var bool
  23. */
  24. public $return_false_on_fail = false;
  25. /**
  26. * Constructor
  27. */
  28. public function __construct() {
  29. // Hack to get the [embed] shortcode to run before wpautop()
  30. add_filter( 'the_content', array( $this, 'run_shortcode' ), 8 );
  31. add_filter( 'widget_text_content', array( $this, 'run_shortcode' ), 8 );
  32. // Shortcode placeholder for strip_shortcodes()
  33. add_shortcode( 'embed', '__return_false' );
  34. // Attempts to embed all URLs in a post
  35. add_filter( 'the_content', array( $this, 'autoembed' ), 8 );
  36. add_filter( 'widget_text_content', array( $this, 'autoembed' ), 8 );
  37. // After a post is saved, cache oEmbed items via Ajax
  38. add_action( 'edit_form_advanced', array( $this, 'maybe_run_ajax_cache' ) );
  39. add_action( 'edit_page_form', array( $this, 'maybe_run_ajax_cache' ) );
  40. }
  41. /**
  42. * Process the [embed] shortcode.
  43. *
  44. * Since the [embed] shortcode needs to be run earlier than other shortcodes,
  45. * this function removes all existing shortcodes, registers the [embed] shortcode,
  46. * calls do_shortcode(), and then re-registers the old shortcodes.
  47. *
  48. * @global array $shortcode_tags
  49. *
  50. * @param string $content Content to parse
  51. * @return string Content with shortcode parsed
  52. */
  53. public function run_shortcode( $content ) {
  54. global $shortcode_tags;
  55. // Back up current registered shortcodes and clear them all out
  56. $orig_shortcode_tags = $shortcode_tags;
  57. remove_all_shortcodes();
  58. add_shortcode( 'embed', array( $this, 'shortcode' ) );
  59. // Do the shortcode (only the [embed] one is registered)
  60. $content = do_shortcode( $content, true );
  61. // Put the original shortcodes back
  62. $shortcode_tags = $orig_shortcode_tags;
  63. return $content;
  64. }
  65. /**
  66. * If a post/page was saved, then output JavaScript to make
  67. * an Ajax request that will call WP_Embed::cache_oembed().
  68. */
  69. public function maybe_run_ajax_cache() {
  70. $post = get_post();
  71. if ( ! $post || empty( $_GET['message'] ) )
  72. return;
  73. ?>
  74. <script type="text/javascript">
  75. jQuery(document).ready(function($){
  76. $.get("<?php echo admin_url( 'admin-ajax.php?action=oembed-cache&post=' . $post->ID, 'relative' ); ?>");
  77. });
  78. </script>
  79. <?php
  80. }
  81. /**
  82. * Registers an embed handler.
  83. *
  84. * Do not use this function directly, use wp_embed_register_handler() instead.
  85. *
  86. * This function should probably also only be used for sites that do not support oEmbed.
  87. *
  88. * @param string $id An internal ID/name for the handler. Needs to be unique.
  89. * @param string $regex The regex that will be used to see if this handler should be used for a URL.
  90. * @param callable $callback The callback function that will be called if the regex is matched.
  91. * @param int $priority Optional. Used to specify the order in which the registered handlers will be tested (default: 10). Lower numbers correspond with earlier testing, and handlers with the same priority are tested in the order in which they were added to the action.
  92. */
  93. public function register_handler( $id, $regex, $callback, $priority = 10 ) {
  94. $this->handlers[$priority][$id] = array(
  95. 'regex' => $regex,
  96. 'callback' => $callback,
  97. );
  98. }
  99. /**
  100. * Unregisters a previously-registered embed handler.
  101. *
  102. * Do not use this function directly, use wp_embed_unregister_handler() instead.
  103. *
  104. * @param string $id The handler ID that should be removed.
  105. * @param int $priority Optional. The priority of the handler to be removed (default: 10).
  106. */
  107. public function unregister_handler( $id, $priority = 10 ) {
  108. unset( $this->handlers[ $priority ][ $id ] );
  109. }
  110. /**
  111. * The do_shortcode() callback function.
  112. *
  113. * Attempts to convert a URL into embed HTML. Starts by checking the URL against the regex of
  114. * the registered embed handlers. If none of the regex matches and it's enabled, then the URL
  115. * will be given to the WP_oEmbed class.
  116. *
  117. * @param array $attr {
  118. * Shortcode attributes. Optional.
  119. *
  120. * @type int $width Width of the embed in pixels.
  121. * @type int $height Height of the embed in pixels.
  122. * }
  123. * @param string $url The URL attempting to be embedded.
  124. * @return string|false The embed HTML on success, otherwise the original URL.
  125. * `->maybe_make_link()` can return false on failure.
  126. */
  127. public function shortcode( $attr, $url = '' ) {
  128. $post = get_post();
  129. if ( empty( $url ) && ! empty( $attr['src'] ) ) {
  130. $url = $attr['src'];
  131. }
  132. $this->last_url = $url;
  133. if ( empty( $url ) ) {
  134. $this->last_attr = $attr;
  135. return '';
  136. }
  137. $rawattr = $attr;
  138. $attr = wp_parse_args( $attr, wp_embed_defaults( $url ) );
  139. $this->last_attr = $attr;
  140. // kses converts & into &amp; and we need to undo this
  141. // See https://core.trac.wordpress.org/ticket/11311
  142. $url = str_replace( '&amp;', '&', $url );
  143. // Look for known internal handlers
  144. ksort( $this->handlers );
  145. foreach ( $this->handlers as $priority => $handlers ) {
  146. foreach ( $handlers as $id => $handler ) {
  147. if ( preg_match( $handler['regex'], $url, $matches ) && is_callable( $handler['callback'] ) ) {
  148. if ( false !== $return = call_user_func( $handler['callback'], $matches, $attr, $url, $rawattr ) )
  149. /**
  150. * Filters the returned embed handler.
  151. *
  152. * @since 2.9.0
  153. *
  154. * @see WP_Embed::shortcode()
  155. *
  156. * @param mixed $return The shortcode callback function to call.
  157. * @param string $url The attempted embed URL.
  158. * @param array $attr An array of shortcode attributes.
  159. */
  160. return apply_filters( 'embed_handler_html', $return, $url, $attr );
  161. }
  162. }
  163. }
  164. $post_ID = ( ! empty( $post->ID ) ) ? $post->ID : null;
  165. // Potentially set by WP_Embed::cache_oembed().
  166. if ( ! empty( $this->post_ID ) ) {
  167. $post_ID = $this->post_ID;
  168. }
  169. // Check for a cached result (stored as custom post or in the post meta).
  170. $key_suffix = md5( $url . serialize( $attr ) );
  171. $cachekey = '_oembed_' . $key_suffix;
  172. $cachekey_time = '_oembed_time_' . $key_suffix;
  173. /**
  174. * Filters the oEmbed TTL value (time to live).
  175. *
  176. * @since 4.0.0
  177. *
  178. * @param int $time Time to live (in seconds).
  179. * @param string $url The attempted embed URL.
  180. * @param array $attr An array of shortcode attributes.
  181. * @param int $post_ID Post ID.
  182. */
  183. $ttl = apply_filters( 'oembed_ttl', DAY_IN_SECONDS, $url, $attr, $post_ID );
  184. $cache = '';
  185. $cache_time = 0;
  186. $cached_post_id = $this->find_oembed_post_id( $key_suffix );
  187. if ( $post_ID ) {
  188. $cache = get_post_meta( $post_ID, $cachekey, true );
  189. $cache_time = get_post_meta( $post_ID, $cachekey_time, true );
  190. if ( ! $cache_time ) {
  191. $cache_time = 0;
  192. }
  193. } elseif ( $cached_post_id ) {
  194. $cached_post = get_post( $cached_post_id );
  195. $cache = $cached_post->post_content;
  196. $cache_time = strtotime( $cached_post->post_modified_gmt );
  197. }
  198. $cached_recently = ( time() - $cache_time ) < $ttl;
  199. if ( $this->usecache || $cached_recently ) {
  200. // Failures are cached. Serve one if we're using the cache.
  201. if ( '{{unknown}}' === $cache ) {
  202. return $this->maybe_make_link( $url );
  203. }
  204. if ( ! empty( $cache ) ) {
  205. /**
  206. * Filters the cached oEmbed HTML.
  207. *
  208. * @since 2.9.0
  209. *
  210. * @see WP_Embed::shortcode()
  211. *
  212. * @param mixed $cache The cached HTML result, stored in post meta.
  213. * @param string $url The attempted embed URL.
  214. * @param array $attr An array of shortcode attributes.
  215. * @param int $post_ID Post ID.
  216. */
  217. return apply_filters( 'embed_oembed_html', $cache, $url, $attr, $post_ID );
  218. }
  219. }
  220. /**
  221. * Filters whether to inspect the given URL for discoverable link tags.
  222. *
  223. * @since 2.9.0
  224. * @since 4.4.0 The default value changed to true.
  225. *
  226. * @see WP_oEmbed::discover()
  227. *
  228. * @param bool $enable Whether to enable `<link>` tag discovery. Default true.
  229. */
  230. $attr['discover'] = apply_filters( 'embed_oembed_discover', true );
  231. // Use oEmbed to get the HTML.
  232. $html = wp_oembed_get( $url, $attr );
  233. if ( $post_ID ) {
  234. if ( $html ) {
  235. update_post_meta( $post_ID, $cachekey, $html );
  236. update_post_meta( $post_ID, $cachekey_time, time() );
  237. } elseif ( ! $cache ) {
  238. update_post_meta( $post_ID, $cachekey, '{{unknown}}' );
  239. }
  240. } else {
  241. $has_kses = false !== has_filter( 'content_save_pre', 'wp_filter_post_kses' );
  242. if ( $has_kses ) {
  243. // Prevent KSES from corrupting JSON in post_content.
  244. kses_remove_filters();
  245. }
  246. $insert_post_args = array(
  247. 'post_name' => $key_suffix,
  248. 'post_status' => 'publish',
  249. 'post_type' => 'oembed_cache',
  250. );
  251. if ( $html ) {
  252. if ( $cached_post_id ) {
  253. wp_update_post( wp_slash( array(
  254. 'ID' => $cached_post_id,
  255. 'post_content' => $html,
  256. ) ) );
  257. } else {
  258. wp_insert_post( wp_slash( array_merge(
  259. $insert_post_args,
  260. array(
  261. 'post_content' => $html,
  262. )
  263. ) ) );
  264. }
  265. } elseif ( ! $cache ) {
  266. wp_insert_post( wp_slash( array_merge(
  267. $insert_post_args,
  268. array(
  269. 'post_content' => '{{unknown}}',
  270. )
  271. ) ) );
  272. }
  273. if ( $has_kses ) {
  274. kses_init_filters();
  275. }
  276. }
  277. // If there was a result, return it.
  278. if ( $html ) {
  279. /** This filter is documented in wp-includes/class-wp-embed.php */
  280. return apply_filters( 'embed_oembed_html', $html, $url, $attr, $post_ID );
  281. }
  282. // Still unknown
  283. return $this->maybe_make_link( $url );
  284. }
  285. /**
  286. * Delete all oEmbed caches. Unused by core as of 4.0.0.
  287. *
  288. * @param int $post_ID Post ID to delete the caches for.
  289. */
  290. public function delete_oembed_caches( $post_ID ) {
  291. $post_metas = get_post_custom_keys( $post_ID );
  292. if ( empty($post_metas) )
  293. return;
  294. foreach ( $post_metas as $post_meta_key ) {
  295. if ( '_oembed_' == substr( $post_meta_key, 0, 8 ) )
  296. delete_post_meta( $post_ID, $post_meta_key );
  297. }
  298. }
  299. /**
  300. * Triggers a caching of all oEmbed results.
  301. *
  302. * @param int $post_ID Post ID to do the caching for.
  303. */
  304. public function cache_oembed( $post_ID ) {
  305. $post = get_post( $post_ID );
  306. $post_types = get_post_types( array( 'show_ui' => true ) );
  307. /**
  308. * Filters the array of post types to cache oEmbed results for.
  309. *
  310. * @since 2.9.0
  311. *
  312. * @param array $post_types Array of post types to cache oEmbed results for. Defaults to post types with `show_ui` set to true.
  313. */
  314. if ( empty( $post->ID ) || ! in_array( $post->post_type, apply_filters( 'embed_cache_oembed_types', $post_types ) ) ){
  315. return;
  316. }
  317. // Trigger a caching
  318. if ( ! empty( $post->post_content ) ) {
  319. $this->post_ID = $post->ID;
  320. $this->usecache = false;
  321. $content = $this->run_shortcode( $post->post_content );
  322. $this->autoembed( $content );
  323. $this->usecache = true;
  324. }
  325. }
  326. /**
  327. * Passes any unlinked URLs that are on their own line to WP_Embed::shortcode() for potential embedding.
  328. *
  329. * @see WP_Embed::autoembed_callback()
  330. *
  331. * @param string $content The content to be searched.
  332. * @return string Potentially modified $content.
  333. */
  334. public function autoembed( $content ) {
  335. // Replace line breaks from all HTML elements with placeholders.
  336. $content = wp_replace_in_html_tags( $content, array( "\n" => '<!-- wp-line-break -->' ) );
  337. if ( preg_match( '#(^|\s|>)https?://#i', $content ) ) {
  338. // Find URLs on their own line.
  339. $content = preg_replace_callback( '|^(\s*)(https?://[^\s<>"]+)(\s*)$|im', array( $this, 'autoembed_callback' ), $content );
  340. // Find URLs in their own paragraph.
  341. $content = preg_replace_callback( '|(<p(?: [^>]*)?>\s*)(https?://[^\s<>"]+)(\s*<\/p>)|i', array( $this, 'autoembed_callback' ), $content );
  342. }
  343. // Put the line breaks back.
  344. return str_replace( '<!-- wp-line-break -->', "\n", $content );
  345. }
  346. /**
  347. * Callback function for WP_Embed::autoembed().
  348. *
  349. * @param array $match A regex match array.
  350. * @return string The embed HTML on success, otherwise the original URL.
  351. */
  352. public function autoembed_callback( $match ) {
  353. $oldval = $this->linkifunknown;
  354. $this->linkifunknown = false;
  355. $return = $this->shortcode( array(), $match[2] );
  356. $this->linkifunknown = $oldval;
  357. return $match[1] . $return . $match[3];
  358. }
  359. /**
  360. * Conditionally makes a hyperlink based on an internal class variable.
  361. *
  362. * @param string $url URL to potentially be linked.
  363. * @return false|string Linked URL or the original URL. False if 'return_false_on_fail' is true.
  364. */
  365. public function maybe_make_link( $url ) {
  366. if ( $this->return_false_on_fail ) {
  367. return false;
  368. }
  369. $output = ( $this->linkifunknown ) ? '<a href="' . esc_url($url) . '">' . esc_html($url) . '</a>' : $url;
  370. /**
  371. * Filters the returned, maybe-linked embed URL.
  372. *
  373. * @since 2.9.0
  374. *
  375. * @param string $output The linked or original URL.
  376. * @param string $url The original URL.
  377. */
  378. return apply_filters( 'embed_maybe_make_link', $output, $url );
  379. }
  380. /**
  381. * Find the oEmbed cache post ID for a given cache key.
  382. *
  383. * @since 4.9.0
  384. *
  385. * @param string $cache_key oEmbed cache key.
  386. * @return int|null Post ID on success, null on failure.
  387. */
  388. public function find_oembed_post_id( $cache_key ) {
  389. $cache_group = 'oembed_cache_post';
  390. $oembed_post_id = wp_cache_get( $cache_key, $cache_group );
  391. if ( $oembed_post_id && 'oembed_cache' === get_post_type( $oembed_post_id ) ) {
  392. return $oembed_post_id;
  393. }
  394. $oembed_post_query = new WP_Query( array(
  395. 'post_type' => 'oembed_cache',
  396. 'post_status' => 'publish',
  397. 'name' => $cache_key,
  398. 'posts_per_page' => 1,
  399. 'no_found_rows' => true,
  400. 'cache_results' => true,
  401. 'update_post_meta_cache' => false,
  402. 'update_post_term_cache' => false,
  403. 'lazy_load_term_meta' => false,
  404. ) );
  405. if ( ! empty( $oembed_post_query->posts ) ) {
  406. // Note: 'fields'=>'ids' is not being used in order to cache the post object as it will be needed.
  407. $oembed_post_id = $oembed_post_query->posts[0]->ID;
  408. wp_cache_set( $cache_key, $oembed_post_id, $cache_group );
  409. return $oembed_post_id;
  410. }
  411. return null;
  412. }
  413. }