[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

/wp-includes/ -> class-wp-embed.php (source)

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


Generated: Thu Oct 1 01:00:03 2020 Cross-referenced by PHPXref 0.7.1