Bez popisu

class-wp-embed.php 16KB

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