[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

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

   1  <?php
   2  /**
   3   * API for fetching the HTML to embed remote content based on a provided URL
   4   *
   5   * Used internally by the WP_Embed class, but is designed to be generic.
   6   *
   7   * @link https://wordpress.org/support/article/embeds/
   8   * @link http://oembed.com/
   9   *
  10   * @package WordPress
  11   * @subpackage oEmbed
  12   */
  13  
  14  /**
  15   * Core class used to implement oEmbed functionality.
  16   *
  17   * @since 2.9.0
  18   */
  19  class WP_oEmbed {
  20  
  21      /**
  22       * A list of oEmbed providers.
  23       *
  24       * @since 2.9.0
  25       * @var array
  26       */
  27      public $providers = array();
  28  
  29      /**
  30       * A list of an early oEmbed providers.
  31       *
  32       * @since 4.0.0
  33       * @var array
  34       */
  35      public static $early_providers = array();
  36  
  37      /**
  38       * A list of private/protected methods, used for backward compatibility.
  39       *
  40       * @since 4.2.0
  41       * @var array
  42       */
  43      private $compat_methods = array( '_fetch_with_format', '_parse_json', '_parse_xml', '_parse_xml_body' );
  44  
  45      /**
  46       * Constructor.
  47       *
  48       * @since 2.9.0
  49       */
  50  	public function __construct() {
  51          $host      = urlencode( home_url() );
  52          $providers = array(
  53              '#https?://((m|www)\.)?youtube\.com/watch.*#i' => array( 'https://www.youtube.com/oembed', true ),
  54              '#https?://((m|www)\.)?youtube\.com/playlist.*#i' => array( 'https://www.youtube.com/oembed', true ),
  55              '#https?://youtu\.be/.*#i'                     => array( 'https://www.youtube.com/oembed', true ),
  56              '#https?://(.+\.)?vimeo\.com/.*#i'             => array( 'https://vimeo.com/api/oembed.{format}', true ),
  57              '#https?://(www\.)?dailymotion\.com/.*#i'      => array( 'https://www.dailymotion.com/services/oembed', true ),
  58              '#https?://dai\.ly/.*#i'                       => array( 'https://www.dailymotion.com/services/oembed', true ),
  59              '#https?://(www\.)?flickr\.com/.*#i'           => array( 'https://www.flickr.com/services/oembed/', true ),
  60              '#https?://flic\.kr/.*#i'                      => array( 'https://www.flickr.com/services/oembed/', true ),
  61              '#https?://(.+\.)?smugmug\.com/.*#i'           => array( 'https://api.smugmug.com/services/oembed/', true ),
  62              '#https?://(www\.)?hulu\.com/watch/.*#i'       => array( 'https://www.hulu.com/api/oembed.{format}', true ),
  63              '#https?://(www\.)?scribd\.com/(doc|document)/.*#i' => array( 'https://www.scribd.com/services/oembed', true ),
  64              '#https?://wordpress\.tv/.*#i'                 => array( 'https://wordpress.tv/oembed/', true ),
  65              '#https?://(.+\.)?polldaddy\.com/.*#i'         => array( 'https://api.crowdsignal.com/oembed', true ),
  66              '#https?://poll\.fm/.*#i'                      => array( 'https://api.crowdsignal.com/oembed', true ),
  67              '#https?://(.+\.)?survey\.fm/.*#i'             => array( 'https://api.crowdsignal.com/oembed', true ),
  68              '#https?://(www\.)?twitter\.com/\w{1,15}/status(es)?/.*#i' => array( 'https://publish.twitter.com/oembed', true ),
  69              '#https?://(www\.)?twitter\.com/\w{1,15}$#i'   => array( 'https://publish.twitter.com/oembed', true ),
  70              '#https?://(www\.)?twitter\.com/\w{1,15}/likes$#i' => array( 'https://publish.twitter.com/oembed', true ),
  71              '#https?://(www\.)?twitter\.com/\w{1,15}/lists/.*#i' => array( 'https://publish.twitter.com/oembed', true ),
  72              '#https?://(www\.)?twitter\.com/\w{1,15}/timelines/.*#i' => array( 'https://publish.twitter.com/oembed', true ),
  73              '#https?://(www\.)?twitter\.com/i/moments/.*#i' => array( 'https://publish.twitter.com/oembed', true ),
  74              '#https?://(www\.)?soundcloud\.com/.*#i'       => array( 'https://soundcloud.com/oembed', true ),
  75              '#https?://(.+?\.)?slideshare\.net/.*#i'       => array( 'https://www.slideshare.net/api/oembed/2', true ),
  76              '#https?://(www\.)?instagr(\.am|am\.com)/(p|tv)/.*#i' => array( 'https://api.instagram.com/oembed', true ),
  77              '#https?://(open|play)\.spotify\.com/.*#i'     => array( 'https://embed.spotify.com/oembed/', true ),
  78              '#https?://(.+\.)?imgur\.com/.*#i'             => array( 'https://api.imgur.com/oembed', true ),
  79              '#https?://(www\.)?meetu(\.ps|p\.com)/.*#i'    => array( 'https://api.meetup.com/oembed', true ),
  80              '#https?://(www\.)?issuu\.com/.+/docs/.+#i'    => array( 'https://issuu.com/oembed_wp', true ),
  81              '#https?://(www\.)?mixcloud\.com/.*#i'         => array( 'https://www.mixcloud.com/oembed', true ),
  82              '#https?://(www\.|embed\.)?ted\.com/talks/.*#i' => array( 'https://www.ted.com/services/v1/oembed.{format}', true ),
  83              '#https?://(www\.)?(animoto|video214)\.com/play/.*#i' => array( 'https://animoto.com/oembeds/create', true ),
  84              '#https?://(.+)\.tumblr\.com/post/.*#i'        => array( 'https://www.tumblr.com/oembed/1.0', true ),
  85              '#https?://(www\.)?kickstarter\.com/projects/.*#i' => array( 'https://www.kickstarter.com/services/oembed', true ),
  86              '#https?://kck\.st/.*#i'                       => array( 'https://www.kickstarter.com/services/oembed', true ),
  87              '#https?://cloudup\.com/.*#i'                  => array( 'https://cloudup.com/oembed', true ),
  88              '#https?://(www\.)?reverbnation\.com/.*#i'     => array( 'https://www.reverbnation.com/oembed', true ),
  89              '#https?://videopress\.com/v/.*#'              => array( 'https://public-api.wordpress.com/oembed/?for=' . $host, true ),
  90              '#https?://(www\.)?reddit\.com/r/[^/]+/comments/.*#i' => array( 'https://www.reddit.com/oembed', true ),
  91              '#https?://(www\.)?speakerdeck\.com/.*#i'      => array( 'https://speakerdeck.com/oembed.{format}', true ),
  92              '#https?://www\.facebook\.com/.*/posts/.*#i'   => array( 'https://www.facebook.com/plugins/post/oembed.json/', true ),
  93              '#https?://www\.facebook\.com/.*/activity/.*#i' => array( 'https://www.facebook.com/plugins/post/oembed.json/', true ),
  94              '#https?://www\.facebook\.com/.*/photos/.*#i'  => array( 'https://www.facebook.com/plugins/post/oembed.json/', true ),
  95              '#https?://www\.facebook\.com/photo(s/|\.php).*#i' => array( 'https://www.facebook.com/plugins/post/oembed.json/', true ),
  96              '#https?://www\.facebook\.com/permalink\.php.*#i' => array( 'https://www.facebook.com/plugins/post/oembed.json/', true ),
  97              '#https?://www\.facebook\.com/media/.*#i'      => array( 'https://www.facebook.com/plugins/post/oembed.json/', true ),
  98              '#https?://www\.facebook\.com/questions/.*#i'  => array( 'https://www.facebook.com/plugins/post/oembed.json/', true ),
  99              '#https?://www\.facebook\.com/notes/.*#i'      => array( 'https://www.facebook.com/plugins/post/oembed.json/', true ),
 100              '#https?://www\.facebook\.com/.*/videos/.*#i'  => array( 'https://www.facebook.com/plugins/video/oembed.json/', true ),
 101              '#https?://www\.facebook\.com/video\.php.*#i'  => array( 'https://www.facebook.com/plugins/video/oembed.json/', true ),
 102              '#https?://(www\.)?screencast\.com/.*#i'       => array( 'https://api.screencast.com/external/oembed', true ),
 103              '#https?://([a-z0-9-]+\.)?amazon\.(com|com\.mx|com\.br|ca)/.*#i' => array( 'https://read.amazon.com/kp/api/oembed', true ),
 104              '#https?://([a-z0-9-]+\.)?amazon\.(co\.uk|de|fr|it|es|in|nl|ru)/.*#i' => array( 'https://read.amazon.co.uk/kp/api/oembed', true ),
 105              '#https?://([a-z0-9-]+\.)?amazon\.(co\.jp|com\.au)/.*#i' => array( 'https://read.amazon.com.au/kp/api/oembed', true ),
 106              '#https?://([a-z0-9-]+\.)?amazon\.cn/.*#i'     => array( 'https://read.amazon.cn/kp/api/oembed', true ),
 107              '#https?://(www\.)?a\.co/.*#i'                 => array( 'https://read.amazon.com/kp/api/oembed', true ),
 108              '#https?://(www\.)?amzn\.to/.*#i'              => array( 'https://read.amazon.com/kp/api/oembed', true ),
 109              '#https?://(www\.)?amzn\.eu/.*#i'              => array( 'https://read.amazon.co.uk/kp/api/oembed', true ),
 110              '#https?://(www\.)?amzn\.in/.*#i'              => array( 'https://read.amazon.in/kp/api/oembed', true ),
 111              '#https?://(www\.)?amzn\.asia/.*#i'            => array( 'https://read.amazon.com.au/kp/api/oembed', true ),
 112              '#https?://(www\.)?z\.cn/.*#i'                 => array( 'https://read.amazon.cn/kp/api/oembed', true ),
 113              '#https?://www\.someecards\.com/.+-cards/.+#i' => array( 'https://www.someecards.com/v2/oembed/', true ),
 114              '#https?://www\.someecards\.com/usercards/viewcard/.+#i' => array( 'https://www.someecards.com/v2/oembed/', true ),
 115              '#https?://some\.ly\/.+#i'                     => array( 'https://www.someecards.com/v2/oembed/', true ),
 116          );
 117  
 118          if ( ! empty( self::$early_providers['add'] ) ) {
 119              foreach ( self::$early_providers['add'] as $format => $data ) {
 120                  $providers[ $format ] = $data;
 121              }
 122          }
 123  
 124          if ( ! empty( self::$early_providers['remove'] ) ) {
 125              foreach ( self::$early_providers['remove'] as $format ) {
 126                  unset( $providers[ $format ] );
 127              }
 128          }
 129  
 130          self::$early_providers = array();
 131  
 132          /**
 133           * Filters the list of whitelisted oEmbed providers.
 134           *
 135           * Since WordPress 4.4, oEmbed discovery is enabled for all users and allows embedding of sanitized
 136           * iframes. The providers in this list are whitelisted, meaning they are trusted and allowed to
 137           * embed any content, such as iframes, videos, JavaScript, and arbitrary HTML.
 138           *
 139           * Supported providers:
 140           *
 141           * |   Provider   |                     Flavor                |  Since  |
 142           * | ------------ | ----------------------------------------- | ------- |
 143           * | Dailymotion  | dailymotion.com                           | 2.9.0   |
 144           * | Flickr       | flickr.com                                | 2.9.0   |
 145           * | Hulu         | hulu.com                                  | 2.9.0   |
 146           * | Scribd       | scribd.com                                | 2.9.0   |
 147           * | Vimeo        | vimeo.com                                 | 2.9.0   |
 148           * | WordPress.tv | wordpress.tv                              | 2.9.0   |
 149           * | YouTube      | youtube.com/watch                         | 2.9.0   |
 150           * | Crowdsignal  | polldaddy.com                             | 3.0.0   |
 151           * | SmugMug      | smugmug.com                               | 3.0.0   |
 152           * | YouTube      | youtu.be                                  | 3.0.0   |
 153           * | Twitter      | twitter.com                               | 3.4.0   |
 154           * | Instagram    | instagram.com                             | 3.5.0   |
 155           * | Instagram    | instagr.am                                | 3.5.0   |
 156           * | Slideshare   | slideshare.net                            | 3.5.0   |
 157           * | SoundCloud   | soundcloud.com                            | 3.5.0   |
 158           * | Dailymotion  | dai.ly                                    | 3.6.0   |
 159           * | Flickr       | flic.kr                                   | 3.6.0   |
 160           * | Spotify      | spotify.com                               | 3.6.0   |
 161           * | Imgur        | imgur.com                                 | 3.9.0   |
 162           * | Meetup.com   | meetup.com                                | 3.9.0   |
 163           * | Meetup.com   | meetu.ps                                  | 3.9.0   |
 164           * | Animoto      | animoto.com                               | 4.0.0   |
 165           * | Animoto      | video214.com                              | 4.0.0   |
 166           * | Issuu        | issuu.com                                 | 4.0.0   |
 167           * | Mixcloud     | mixcloud.com                              | 4.0.0   |
 168           * | Crowdsignal  | poll.fm                                   | 4.0.0   |
 169           * | TED          | ted.com                                   | 4.0.0   |
 170           * | YouTube      | youtube.com/playlist                      | 4.0.0   |
 171           * | Tumblr       | tumblr.com                                | 4.2.0   |
 172           * | Kickstarter  | kickstarter.com                           | 4.2.0   |
 173           * | Kickstarter  | kck.st                                    | 4.2.0   |
 174           * | Cloudup      | cloudup.com                               | 4.3.0   |
 175           * | ReverbNation | reverbnation.com                          | 4.4.0   |
 176           * | VideoPress   | videopress.com                            | 4.4.0   |
 177           * | Reddit       | reddit.com                                | 4.4.0   |
 178           * | Speaker Deck | speakerdeck.com                           | 4.4.0   |
 179           * | Twitter      | twitter.com/timelines                     | 4.5.0   |
 180           * | Twitter      | twitter.com/moments                       | 4.5.0   |
 181           * | Facebook     | facebook.com                              | 4.7.0   |
 182           * | Twitter      | twitter.com/user                          | 4.7.0   |
 183           * | Twitter      | twitter.com/likes                         | 4.7.0   |
 184           * | Twitter      | twitter.com/lists                         | 4.7.0   |
 185           * | Screencast   | screencast.com                            | 4.8.0   |
 186           * | Amazon       | amazon.com (com.mx, com.br, ca)           | 4.9.0   |
 187           * | Amazon       | amazon.de (fr, it, es, in, nl, ru, co.uk) | 4.9.0   |
 188           * | Amazon       | amazon.co.jp (com.au)                     | 4.9.0   |
 189           * | Amazon       | amazon.cn                                 | 4.9.0   |
 190           * | Amazon       | a.co                                      | 4.9.0   |
 191           * | Amazon       | amzn.to (eu, in, asia)                    | 4.9.0   |
 192           * | Amazon       | z.cn                                      | 4.9.0   |
 193           * | Someecards   | someecards.com                            | 4.9.0   |
 194           * | Someecards   | some.ly                                   | 4.9.0   |
 195           * | Crowdsignal  | survey.fm                                 | 5.1.0   |
 196           * | Instagram TV | instagram.com                             | 5.1.0   |
 197           * | Instagram TV | instagr.am                                | 5.1.0   |
 198           *
 199           * No longer supported providers:
 200           *
 201           * |   Provider   |        Flavor        |   Since   |  Removed  |
 202           * | ------------ | -------------------- | --------- | --------- |
 203           * | Qik          | qik.com              | 2.9.0     | 3.9.0     |
 204           * | Viddler      | viddler.com          | 2.9.0     | 4.0.0     |
 205           * | Revision3    | revision3.com        | 2.9.0     | 4.2.0     |
 206           * | Blip         | blip.tv              | 2.9.0     | 4.4.0     |
 207           * | Rdio         | rdio.com             | 3.6.0     | 4.4.1     |
 208           * | Rdio         | rd.io                | 3.6.0     | 4.4.1     |
 209           * | Vine         | vine.co              | 4.1.0     | 4.9.0     |
 210           * | Photobucket  | photobucket.com      | 2.9.0     | 5.1.0     |
 211           * | Funny or Die | funnyordie.com       | 3.0.0     | 5.1.0     |
 212           * | CollegeHumor | collegehumor.com     | 4.0.0     | 5.3.1     |
 213           *
 214           * @see wp_oembed_add_provider()
 215           *
 216           * @since 2.9.0
 217           *
 218           * @param array[] $providers An array of arrays containing data about popular oEmbed providers.
 219           */
 220          $this->providers = apply_filters( 'oembed_providers', $providers );
 221  
 222          // Fix any embeds that contain new lines in the middle of the HTML which breaks wpautop().
 223          add_filter( 'oembed_dataparse', array( $this, '_strip_newlines' ), 10, 3 );
 224      }
 225  
 226      /**
 227       * Exposes private/protected methods for backward compatibility.
 228       *
 229       * @since 4.0.0
 230       *
 231       * @param string   $name      Method to call.
 232       * @param array    $arguments Arguments to pass when calling.
 233       * @return mixed|bool Return value of the callback, false otherwise.
 234       */
 235  	public function __call( $name, $arguments ) {
 236          if ( in_array( $name, $this->compat_methods ) ) {
 237              return $this->$name( ...$arguments );
 238          }
 239          return false;
 240      }
 241  
 242      /**
 243       * Takes a URL and returns the corresponding oEmbed provider's URL, if there is one.
 244       *
 245       * @since 4.0.0
 246       *
 247       * @see WP_oEmbed::discover()
 248       *
 249       * @param string        $url  The URL to the content.
 250       * @param string|array  $args Optional provider arguments.
 251       * @return false|string False on failure, otherwise the oEmbed provider URL.
 252       */
 253  	public function get_provider( $url, $args = '' ) {
 254          $args = wp_parse_args( $args );
 255  
 256          $provider = false;
 257  
 258          if ( ! isset( $args['discover'] ) ) {
 259              $args['discover'] = true;
 260          }
 261  
 262          foreach ( $this->providers as $matchmask => $data ) {
 263              list( $providerurl, $regex ) = $data;
 264  
 265              // Turn the asterisk-type provider URLs into regex
 266              if ( ! $regex ) {
 267                  $matchmask = '#' . str_replace( '___wildcard___', '(.+)', preg_quote( str_replace( '*', '___wildcard___', $matchmask ), '#' ) ) . '#i';
 268                  $matchmask = preg_replace( '|^#http\\\://|', '#https?\://', $matchmask );
 269              }
 270  
 271              if ( preg_match( $matchmask, $url ) ) {
 272                  $provider = str_replace( '{format}', 'json', $providerurl ); // JSON is easier to deal with than XML
 273                  break;
 274              }
 275          }
 276  
 277          if ( ! $provider && $args['discover'] ) {
 278              $provider = $this->discover( $url );
 279          }
 280  
 281          return $provider;
 282      }
 283  
 284      /**
 285       * Adds an oEmbed provider.
 286       *
 287       * The provider is added just-in-time when wp_oembed_add_provider() is called before
 288       * the {@see 'plugins_loaded'} hook.
 289       *
 290       * The just-in-time addition is for the benefit of the {@see 'oembed_providers'} filter.
 291       *
 292       * @since 4.0.0
 293       *
 294       * @see wp_oembed_add_provider()
 295       *
 296       * @param string $format   Format of URL that this provider can handle. You can use
 297       *                         asterisks as wildcards.
 298       * @param string $provider The URL to the oEmbed provider..
 299       * @param bool   $regex    Optional. Whether the $format parameter is in a regex format.
 300       *                         Default false.
 301       */
 302  	public static function _add_provider_early( $format, $provider, $regex = false ) {
 303          if ( empty( self::$early_providers['add'] ) ) {
 304              self::$early_providers['add'] = array();
 305          }
 306  
 307          self::$early_providers['add'][ $format ] = array( $provider, $regex );
 308      }
 309  
 310      /**
 311       * Removes an oEmbed provider.
 312       *
 313       * The provider is removed just-in-time when wp_oembed_remove_provider() is called before
 314       * the {@see 'plugins_loaded'} hook.
 315       *
 316       * The just-in-time removal is for the benefit of the {@see 'oembed_providers'} filter.
 317       *
 318       * @since 4.0.0
 319       *
 320       * @see wp_oembed_remove_provider()
 321       *
 322       * @param string $format The format of URL that this provider can handle. You can use
 323       *                       asterisks as wildcards.
 324       */
 325  	public static function _remove_provider_early( $format ) {
 326          if ( empty( self::$early_providers['remove'] ) ) {
 327              self::$early_providers['remove'] = array();
 328          }
 329  
 330          self::$early_providers['remove'][] = $format;
 331      }
 332  
 333      /**
 334       * Takes a URL and attempts to return the oEmbed data.
 335       *
 336       * @see WP_oEmbed::fetch()
 337       *
 338       * @since 4.8.0
 339       *
 340       * @param string       $url  The URL to the content that should be attempted to be embedded.
 341       * @param array|string $args Optional. Arguments, usually passed from a shortcode. Default empty.
 342       * @return false|object False on failure, otherwise the result in the form of an object.
 343       */
 344  	public function get_data( $url, $args = '' ) {
 345          $args = wp_parse_args( $args );
 346  
 347          $provider = $this->get_provider( $url, $args );
 348  
 349          if ( ! $provider ) {
 350              return false;
 351          }
 352  
 353          $data = $this->fetch( $provider, $url, $args );
 354  
 355          if ( false === $data ) {
 356              return false;
 357          }
 358  
 359          return $data;
 360      }
 361  
 362      /**
 363       * The do-it-all function that takes a URL and attempts to return the HTML.
 364       *
 365       * @see WP_oEmbed::fetch()
 366       * @see WP_oEmbed::data2html()
 367       *
 368       * @since 2.9.0
 369       *
 370       * @param string       $url  The URL to the content that should be attempted to be embedded.
 371       * @param array|string $args Optional. Arguments, usually passed from a shortcode. Default empty.
 372       * @return false|string False on failure, otherwise the UNSANITIZED (and potentially unsafe) HTML that should be used to embed.
 373       */
 374  	public function get_html( $url, $args = '' ) {
 375          /**
 376           * Filters the oEmbed result before any HTTP requests are made.
 377           *
 378           * This allows one to short-circuit the default logic, perhaps by
 379           * replacing it with a routine that is more optimal for your setup.
 380           *
 381           * Passing a non-null value to the filter will effectively short-circuit retrieval,
 382           * returning the passed value instead.
 383           *
 384           * @since 4.5.3
 385           *
 386           * @param null|string $result The UNSANITIZED (and potentially unsafe) HTML that should be used to embed. Default null.
 387           * @param string      $url    The URL to the content that should be attempted to be embedded.
 388           * @param array       $args   Optional. Arguments, usually passed from a shortcode. Default empty.
 389           */
 390          $pre = apply_filters( 'pre_oembed_result', null, $url, $args );
 391  
 392          if ( null !== $pre ) {
 393              return $pre;
 394          }
 395  
 396          $data = $this->get_data( $url, $args );
 397  
 398          if ( false === $data ) {
 399              return false;
 400          }
 401  
 402          /**
 403           * Filters the HTML returned by the oEmbed provider.
 404           *
 405           * @since 2.9.0
 406           *
 407           * @param string|false $data The returned oEmbed HTML (false if unsafe).
 408           * @param string       $url  URL of the content to be embedded.
 409           * @param array        $args Optional arguments, usually passed from a shortcode.
 410           */
 411          return apply_filters( 'oembed_result', $this->data2html( $data, $url ), $url, $args );
 412      }
 413  
 414      /**
 415       * Attempts to discover link tags at the given URL for an oEmbed provider.
 416       *
 417       * @since 2.9.0
 418       *
 419       * @param string $url The URL that should be inspected for discovery `<link>` tags.
 420       * @return false|string False on failure, otherwise the oEmbed provider URL.
 421       */
 422  	public function discover( $url ) {
 423          $providers = array();
 424          $args      = array(
 425              'limit_response_size' => 153600, // 150 KB
 426          );
 427  
 428          /**
 429           * Filters oEmbed remote get arguments.
 430           *
 431           * @since 4.0.0
 432           *
 433           * @see WP_Http::request()
 434           *
 435           * @param array  $args oEmbed remote get arguments.
 436           * @param string $url  URL to be inspected.
 437           */
 438          $args = apply_filters( 'oembed_remote_get_args', $args, $url );
 439  
 440          // Fetch URL content
 441          $request = wp_safe_remote_get( $url, $args );
 442          $html    = wp_remote_retrieve_body( $request );
 443          if ( $html ) {
 444  
 445              /**
 446               * Filters the link types that contain oEmbed provider URLs.
 447               *
 448               * @since 2.9.0
 449               *
 450               * @param string[] $format Array of oEmbed link types. Accepts 'application/json+oembed',
 451               *                         'text/xml+oembed', and 'application/xml+oembed' (incorrect,
 452               *                         used by at least Vimeo).
 453               */
 454              $linktypes = apply_filters(
 455                  'oembed_linktypes',
 456                  array(
 457                      'application/json+oembed' => 'json',
 458                      'text/xml+oembed'         => 'xml',
 459                      'application/xml+oembed'  => 'xml',
 460                  )
 461              );
 462  
 463              // Strip <body>
 464              $html_head_end = stripos( $html, '</head>' );
 465              if ( $html_head_end ) {
 466                  $html = substr( $html, 0, $html_head_end );
 467              }
 468  
 469              // Do a quick check
 470              $tagfound = false;
 471              foreach ( $linktypes as $linktype => $format ) {
 472                  if ( stripos( $html, $linktype ) ) {
 473                      $tagfound = true;
 474                      break;
 475                  }
 476              }
 477  
 478              if ( $tagfound && preg_match_all( '#<link([^<>]+)/?>#iU', $html, $links ) ) {
 479                  foreach ( $links[1] as $link ) {
 480                      $atts = shortcode_parse_atts( $link );
 481  
 482                      if ( ! empty( $atts['type'] ) && ! empty( $linktypes[ $atts['type'] ] ) && ! empty( $atts['href'] ) ) {
 483                          $providers[ $linktypes[ $atts['type'] ] ] = htmlspecialchars_decode( $atts['href'] );
 484  
 485                          // Stop here if it's JSON (that's all we need)
 486                          if ( 'json' == $linktypes[ $atts['type'] ] ) {
 487                              break;
 488                          }
 489                      }
 490                  }
 491              }
 492          }
 493  
 494          // JSON is preferred to XML
 495          if ( ! empty( $providers['json'] ) ) {
 496              return $providers['json'];
 497          } elseif ( ! empty( $providers['xml'] ) ) {
 498              return $providers['xml'];
 499          } else {
 500              return false;
 501          }
 502      }
 503  
 504      /**
 505       * Connects to a oEmbed provider and returns the result.
 506       *
 507       * @since 2.9.0
 508       *
 509       * @param string       $provider The URL to the oEmbed provider.
 510       * @param string       $url      The URL to the content that is desired to be embedded.
 511       * @param array|string $args     Optional. Arguments, usually passed from a shortcode. Default empty.
 512       * @return false|object False on failure, otherwise the result in the form of an object.
 513       */
 514  	public function fetch( $provider, $url, $args = '' ) {
 515          $args = wp_parse_args( $args, wp_embed_defaults( $url ) );
 516  
 517          $provider = add_query_arg( 'maxwidth', (int) $args['width'], $provider );
 518          $provider = add_query_arg( 'maxheight', (int) $args['height'], $provider );
 519          $provider = add_query_arg( 'url', urlencode( $url ), $provider );
 520          $provider = add_query_arg( 'dnt', 1, $provider );
 521  
 522          /**
 523           * Filters the oEmbed URL to be fetched.
 524           *
 525           * @since 2.9.0
 526           * @since 4.9.0 The `dnt` (Do Not Track) query parameter was added to all oEmbed provider URLs.
 527           *
 528           * @param string $provider URL of the oEmbed provider.
 529           * @param string $url      URL of the content to be embedded.
 530           * @param array  $args     Optional arguments, usually passed from a shortcode.
 531           */
 532          $provider = apply_filters( 'oembed_fetch_url', $provider, $url, $args );
 533  
 534          foreach ( array( 'json', 'xml' ) as $format ) {
 535              $result = $this->_fetch_with_format( $provider, $format );
 536              if ( is_wp_error( $result ) && 'not-implemented' == $result->get_error_code() ) {
 537                  continue;
 538              }
 539              return ( $result && ! is_wp_error( $result ) ) ? $result : false;
 540          }
 541          return false;
 542      }
 543  
 544      /**
 545       * Fetches result from an oEmbed provider for a specific format and complete provider URL
 546       *
 547       * @since 3.0.0
 548       *
 549       * @param string $provider_url_with_args URL to the provider with full arguments list (url, maxheight, etc.)
 550       * @param string $format Format to use
 551       * @return false|object|WP_Error False on failure, otherwise the result in the form of an object.
 552       */
 553  	private function _fetch_with_format( $provider_url_with_args, $format ) {
 554          $provider_url_with_args = add_query_arg( 'format', $format, $provider_url_with_args );
 555  
 556          /** This filter is documented in wp-includes/class-wp-oembed.php */
 557          $args = apply_filters( 'oembed_remote_get_args', array(), $provider_url_with_args );
 558  
 559          $response = wp_safe_remote_get( $provider_url_with_args, $args );
 560          if ( 501 == wp_remote_retrieve_response_code( $response ) ) {
 561              return new WP_Error( 'not-implemented' );
 562          }
 563          $body = wp_remote_retrieve_body( $response );
 564          if ( ! $body ) {
 565              return false;
 566          }
 567          $parse_method = "_parse_$format";
 568          return $this->$parse_method( $body );
 569      }
 570  
 571      /**
 572       * Parses a json response body.
 573       *
 574       * @since 3.0.0
 575       *
 576       * @param string $response_body
 577       * @return object|false
 578       */
 579  	private function _parse_json( $response_body ) {
 580          $data = json_decode( trim( $response_body ) );
 581          return ( $data && is_object( $data ) ) ? $data : false;
 582      }
 583  
 584      /**
 585       * Parses an XML response body.
 586       *
 587       * @since 3.0.0
 588       *
 589       * @param string $response_body
 590       * @return object|false
 591       */
 592  	private function _parse_xml( $response_body ) {
 593          if ( ! function_exists( 'libxml_disable_entity_loader' ) ) {
 594              return false;
 595          }
 596  
 597          $loader = libxml_disable_entity_loader( true );
 598          $errors = libxml_use_internal_errors( true );
 599  
 600          $return = $this->_parse_xml_body( $response_body );
 601  
 602          libxml_use_internal_errors( $errors );
 603          libxml_disable_entity_loader( $loader );
 604  
 605          return $return;
 606      }
 607  
 608      /**
 609       * Serves as a helper function for parsing an XML response body.
 610       *
 611       * @since 3.6.0
 612       *
 613       * @param string $response_body
 614       * @return stdClass|false
 615       */
 616  	private function _parse_xml_body( $response_body ) {
 617          if ( ! function_exists( 'simplexml_import_dom' ) || ! class_exists( 'DOMDocument', false ) ) {
 618              return false;
 619          }
 620  
 621          $dom     = new DOMDocument;
 622          $success = $dom->loadXML( $response_body );
 623          if ( ! $success ) {
 624              return false;
 625          }
 626  
 627          if ( isset( $dom->doctype ) ) {
 628              return false;
 629          }
 630  
 631          foreach ( $dom->childNodes as $child ) {
 632              if ( XML_DOCUMENT_TYPE_NODE === $child->nodeType ) {
 633                  return false;
 634              }
 635          }
 636  
 637          $xml = simplexml_import_dom( $dom );
 638          if ( ! $xml ) {
 639              return false;
 640          }
 641  
 642          $return = new stdClass;
 643          foreach ( $xml as $key => $value ) {
 644              $return->$key = (string) $value;
 645          }
 646  
 647          return $return;
 648      }
 649  
 650      /**
 651       * Converts a data object from WP_oEmbed::fetch() and returns the HTML.
 652       *
 653       * @since 2.9.0
 654       *
 655       * @param object $data A data object result from an oEmbed provider.
 656       * @param string $url The URL to the content that is desired to be embedded.
 657       * @return false|string False on error, otherwise the HTML needed to embed.
 658       */
 659  	public function data2html( $data, $url ) {
 660          if ( ! is_object( $data ) || empty( $data->type ) ) {
 661              return false;
 662          }
 663  
 664          $return = false;
 665  
 666          switch ( $data->type ) {
 667              case 'photo':
 668                  if ( empty( $data->url ) || empty( $data->width ) || empty( $data->height ) ) {
 669                      break;
 670                  }
 671                  if ( ! is_string( $data->url ) || ! is_numeric( $data->width ) || ! is_numeric( $data->height ) ) {
 672                      break;
 673                  }
 674  
 675                  $title  = ! empty( $data->title ) && is_string( $data->title ) ? $data->title : '';
 676                  $return = '<a href="' . esc_url( $url ) . '"><img src="' . esc_url( $data->url ) . '" alt="' . esc_attr( $title ) . '" width="' . esc_attr( $data->width ) . '" height="' . esc_attr( $data->height ) . '" /></a>';
 677                  break;
 678  
 679              case 'video':
 680              case 'rich':
 681                  if ( ! empty( $data->html ) && is_string( $data->html ) ) {
 682                      $return = $data->html;
 683                  }
 684                  break;
 685  
 686              case 'link':
 687                  if ( ! empty( $data->title ) && is_string( $data->title ) ) {
 688                      $return = '<a href="' . esc_url( $url ) . '">' . esc_html( $data->title ) . '</a>';
 689                  }
 690                  break;
 691  
 692              default:
 693                  $return = false;
 694          }
 695  
 696          /**
 697           * Filters the returned oEmbed HTML.
 698           *
 699           * Use this filter to add support for custom data types, or to filter the result.
 700           *
 701           * @since 2.9.0
 702           *
 703           * @param string $return The returned oEmbed HTML.
 704           * @param object $data   A data object result from an oEmbed provider.
 705           * @param string $url    The URL of the content to be embedded.
 706           */
 707          return apply_filters( 'oembed_dataparse', $return, $data, $url );
 708      }
 709  
 710      /**
 711       * Strips any new lines from the HTML.
 712       *
 713       * @since 2.9.0 as strip_scribd_newlines()
 714       * @since 3.0.0
 715       *
 716       * @param string $html Existing HTML.
 717       * @param object $data Data object from WP_oEmbed::data2html()
 718       * @param string $url The original URL passed to oEmbed.
 719       * @return string Possibly modified $html
 720       */
 721  	public function _strip_newlines( $html, $data, $url ) {
 722          if ( false === strpos( $html, "\n" ) ) {
 723              return $html;
 724          }
 725  
 726          $count     = 1;
 727          $found     = array();
 728          $token     = '__PRE__';
 729          $search    = array( "\t", "\n", "\r", ' ' );
 730          $replace   = array( '__TAB__', '__NL__', '__CR__', '__SPACE__' );
 731          $tokenized = str_replace( $search, $replace, $html );
 732  
 733          preg_match_all( '#(<pre[^>]*>.+?</pre>)#i', $tokenized, $matches, PREG_SET_ORDER );
 734          foreach ( $matches as $i => $match ) {
 735              $tag_html  = str_replace( $replace, $search, $match[0] );
 736              $tag_token = $token . $i;
 737  
 738              $found[ $tag_token ] = $tag_html;
 739              $html                = str_replace( $tag_html, $tag_token, $html, $count );
 740          }
 741  
 742          $replaced = str_replace( $replace, $search, $html );
 743          $stripped = str_replace( array( "\r\n", "\n" ), '', $replaced );
 744          $pre      = array_values( $found );
 745          $tokens   = array_keys( $found );
 746  
 747          return str_replace( $tokens, $pre, $stripped );
 748      }
 749  }


Generated: Mon Dec 16 01:00:04 2019 Cross-referenced by PHPXref 0.7.1