class-wp-embed.php 16 KB

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