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


Generated: Sun Apr 5 01:00:03 2020 Cross-referenced by PHPXref 0.7.1