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


Generated: Wed Nov 20 01:00:03 2019 Cross-referenced by PHPXref 0.7.1