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


Generated: Fri Jul 3 01:00:03 2020 Cross-referenced by PHPXref 0.7.1