[ 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\.)?scribd\.com/(doc|document)/.*#i' => array( 'https://www.scribd.com/services/oembed', true ),
  63              '#https?://wordpress\.tv/.*#i'                 => array( 'https://wordpress.tv/oembed/', true ),
  64              '#https?://(.+\.)?polldaddy\.com/.*#i'         => array( 'https://api.crowdsignal.com/oembed', true ),
  65              '#https?://poll\.fm/.*#i'                      => array( 'https://api.crowdsignal.com/oembed', true ),
  66              '#https?://(.+\.)?survey\.fm/.*#i'             => array( 'https://api.crowdsignal.com/oembed', true ),
  67              '#https?://(www\.)?twitter\.com/\w{1,15}/status(es)?/.*#i' => array( 'https://publish.twitter.com/oembed', true ),
  68              '#https?://(www\.)?twitter\.com/\w{1,15}$#i'   => array( 'https://publish.twitter.com/oembed', true ),
  69              '#https?://(www\.)?twitter\.com/\w{1,15}/likes$#i' => array( 'https://publish.twitter.com/oembed', true ),
  70              '#https?://(www\.)?twitter\.com/\w{1,15}/lists/.*#i' => array( 'https://publish.twitter.com/oembed', true ),
  71              '#https?://(www\.)?twitter\.com/\w{1,15}/timelines/.*#i' => array( 'https://publish.twitter.com/oembed', true ),
  72              '#https?://(www\.)?twitter\.com/i/moments/.*#i' => array( 'https://publish.twitter.com/oembed', true ),
  73              '#https?://(www\.)?soundcloud\.com/.*#i'       => array( 'https://soundcloud.com/oembed', true ),
  74              '#https?://(.+?\.)?slideshare\.net/.*#i'       => array( 'https://www.slideshare.net/api/oembed/2', true ),
  75              '#https?://(open|play)\.spotify\.com/.*#i'     => array( 'https://embed.spotify.com/oembed/', true ),
  76              '#https?://(.+\.)?imgur\.com/.*#i'             => array( 'https://api.imgur.com/oembed', true ),
  77              '#https?://(www\.)?meetu(\.ps|p\.com)/.*#i'    => array( 'https://api.meetup.com/oembed', true ),
  78              '#https?://(www\.)?issuu\.com/.+/docs/.+#i'    => array( 'https://issuu.com/oembed_wp', true ),
  79              '#https?://(www\.)?mixcloud\.com/.*#i'         => array( 'https://www.mixcloud.com/oembed', true ),
  80              '#https?://(www\.|embed\.)?ted\.com/talks/.*#i' => array( 'https://www.ted.com/services/v1/oembed.{format}', true ),
  81              '#https?://(www\.)?(animoto|video214)\.com/play/.*#i' => array( 'https://animoto.com/oembeds/create', true ),
  82              '#https?://(.+)\.tumblr\.com/post/.*#i'        => array( 'https://www.tumblr.com/oembed/1.0', true ),
  83              '#https?://(www\.)?kickstarter\.com/projects/.*#i' => array( 'https://www.kickstarter.com/services/oembed', true ),
  84              '#https?://kck\.st/.*#i'                       => array( 'https://www.kickstarter.com/services/oembed', true ),
  85              '#https?://cloudup\.com/.*#i'                  => array( 'https://cloudup.com/oembed', true ),
  86              '#https?://(www\.)?reverbnation\.com/.*#i'     => array( 'https://www.reverbnation.com/oembed', true ),
  87              '#https?://videopress\.com/v/.*#'              => array( 'https://public-api.wordpress.com/oembed/?for=' . $host, true ),
  88              '#https?://(www\.)?reddit\.com/r/[^/]+/comments/.*#i' => array( 'https://www.reddit.com/oembed', true ),
  89              '#https?://(www\.)?speakerdeck\.com/.*#i'      => array( 'https://speakerdeck.com/oembed.{format}', true ),
  90              '#https?://(www\.)?screencast\.com/.*#i'       => array( 'https://api.screencast.com/external/oembed', true ),
  91              '#https?://([a-z0-9-]+\.)?amazon\.(com|com\.mx|com\.br|ca)/.*#i' => array( 'https://read.amazon.com/kp/api/oembed', true ),
  92              '#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 ),
  93              '#https?://([a-z0-9-]+\.)?amazon\.(co\.jp|com\.au)/.*#i' => array( 'https://read.amazon.com.au/kp/api/oembed', true ),
  94              '#https?://([a-z0-9-]+\.)?amazon\.cn/.*#i'     => array( 'https://read.amazon.cn/kp/api/oembed', true ),
  95              '#https?://(www\.)?a\.co/.*#i'                 => array( 'https://read.amazon.com/kp/api/oembed', true ),
  96              '#https?://(www\.)?amzn\.to/.*#i'              => array( 'https://read.amazon.com/kp/api/oembed', true ),
  97              '#https?://(www\.)?amzn\.eu/.*#i'              => array( 'https://read.amazon.co.uk/kp/api/oembed', true ),
  98              '#https?://(www\.)?amzn\.in/.*#i'              => array( 'https://read.amazon.in/kp/api/oembed', true ),
  99              '#https?://(www\.)?amzn\.asia/.*#i'            => array( 'https://read.amazon.com.au/kp/api/oembed', true ),
 100              '#https?://(www\.)?z\.cn/.*#i'                 => array( 'https://read.amazon.cn/kp/api/oembed', true ),
 101              '#https?://www\.someecards\.com/.+-cards/.+#i' => array( 'https://www.someecards.com/v2/oembed/', true ),
 102              '#https?://www\.someecards\.com/usercards/viewcard/.+#i' => array( 'https://www.someecards.com/v2/oembed/', true ),
 103              '#https?://some\.ly\/.+#i'                     => array( 'https://www.someecards.com/v2/oembed/', true ),
 104              '#https?://(www\.)?tiktok\.com/.*/video/.*#i'  => array( 'https://www.tiktok.com/oembed', true ),
 105              '#https?://([a-z]{2}|www)\.pinterest\.com(\.(au|mx))?/.*#i' => array( 'https://www.pinterest.com/oembed.json', true ),
 106          );
 107  
 108          if ( ! empty( self::$early_providers['add'] ) ) {
 109              foreach ( self::$early_providers['add'] as $format => $data ) {
 110                  $providers[ $format ] = $data;
 111              }
 112          }
 113  
 114          if ( ! empty( self::$early_providers['remove'] ) ) {
 115              foreach ( self::$early_providers['remove'] as $format ) {
 116                  unset( $providers[ $format ] );
 117              }
 118          }
 119  
 120          self::$early_providers = array();
 121  
 122          /**
 123           * Filters the list of sanctioned oEmbed providers.
 124           *
 125           * Since WordPress 4.4, oEmbed discovery is enabled for all users and allows embedding of sanitized
 126           * iframes. The providers in this list are sanctioned, meaning they are trusted and allowed to
 127           * embed any content, such as iframes, videos, JavaScript, and arbitrary HTML.
 128           *
 129           * Supported providers:
 130           *
 131           * |   Provider   |                     Flavor                |  Since  |
 132           * | ------------ | ----------------------------------------- | ------- |
 133           * | Dailymotion  | dailymotion.com                           | 2.9.0   |
 134           * | Flickr       | flickr.com                                | 2.9.0   |
 135           * | Scribd       | scribd.com                                | 2.9.0   |
 136           * | Vimeo        | vimeo.com                                 | 2.9.0   |
 137           * | WordPress.tv | wordpress.tv                              | 2.9.0   |
 138           * | YouTube      | youtube.com/watch                         | 2.9.0   |
 139           * | Crowdsignal  | polldaddy.com                             | 3.0.0   |
 140           * | SmugMug      | smugmug.com                               | 3.0.0   |
 141           * | YouTube      | youtu.be                                  | 3.0.0   |
 142           * | Twitter      | twitter.com                               | 3.4.0   |
 143           * | Slideshare   | slideshare.net                            | 3.5.0   |
 144           * | SoundCloud   | soundcloud.com                            | 3.5.0   |
 145           * | Dailymotion  | dai.ly                                    | 3.6.0   |
 146           * | Flickr       | flic.kr                                   | 3.6.0   |
 147           * | Spotify      | spotify.com                               | 3.6.0   |
 148           * | Imgur        | imgur.com                                 | 3.9.0   |
 149           * | Meetup.com   | meetup.com                                | 3.9.0   |
 150           * | Meetup.com   | meetu.ps                                  | 3.9.0   |
 151           * | Animoto      | animoto.com                               | 4.0.0   |
 152           * | Animoto      | video214.com                              | 4.0.0   |
 153           * | Issuu        | issuu.com                                 | 4.0.0   |
 154           * | Mixcloud     | mixcloud.com                              | 4.0.0   |
 155           * | Crowdsignal  | poll.fm                                   | 4.0.0   |
 156           * | TED          | ted.com                                   | 4.0.0   |
 157           * | YouTube      | youtube.com/playlist                      | 4.0.0   |
 158           * | Tumblr       | tumblr.com                                | 4.2.0   |
 159           * | Kickstarter  | kickstarter.com                           | 4.2.0   |
 160           * | Kickstarter  | kck.st                                    | 4.2.0   |
 161           * | Cloudup      | cloudup.com                               | 4.3.0   |
 162           * | ReverbNation | reverbnation.com                          | 4.4.0   |
 163           * | VideoPress   | videopress.com                            | 4.4.0   |
 164           * | Reddit       | reddit.com                                | 4.4.0   |
 165           * | Speaker Deck | speakerdeck.com                           | 4.4.0   |
 166           * | Twitter      | twitter.com/timelines                     | 4.5.0   |
 167           * | Twitter      | twitter.com/moments                       | 4.5.0   |
 168           * | Twitter      | twitter.com/user                          | 4.7.0   |
 169           * | Twitter      | twitter.com/likes                         | 4.7.0   |
 170           * | Twitter      | twitter.com/lists                         | 4.7.0   |
 171           * | Screencast   | screencast.com                            | 4.8.0   |
 172           * | Amazon       | amazon.com (com.mx, com.br, ca)           | 4.9.0   |
 173           * | Amazon       | amazon.de (fr, it, es, in, nl, ru, co.uk) | 4.9.0   |
 174           * | Amazon       | amazon.co.jp (com.au)                     | 4.9.0   |
 175           * | Amazon       | amazon.cn                                 | 4.9.0   |
 176           * | Amazon       | a.co                                      | 4.9.0   |
 177           * | Amazon       | amzn.to (eu, in, asia)                    | 4.9.0   |
 178           * | Amazon       | z.cn                                      | 4.9.0   |
 179           * | Someecards   | someecards.com                            | 4.9.0   |
 180           * | Someecards   | some.ly                                   | 4.9.0   |
 181           * | Crowdsignal  | survey.fm                                 | 5.1.0   |
 182           * | TikTok       | tiktok.com                                | 5.4.0   |
 183           * | Pinterest    | pinterest.com                             | 5.9.0   |
 184           *
 185           * No longer supported providers:
 186           *
 187           * |   Provider   |        Flavor        |   Since   |  Removed  |
 188           * | ------------ | -------------------- | --------- | --------- |
 189           * | Qik          | qik.com              | 2.9.0     | 3.9.0     |
 190           * | Viddler      | viddler.com          | 2.9.0     | 4.0.0     |
 191           * | Revision3    | revision3.com        | 2.9.0     | 4.2.0     |
 192           * | Blip         | blip.tv              | 2.9.0     | 4.4.0     |
 193           * | Rdio         | rdio.com             | 3.6.0     | 4.4.1     |
 194           * | Rdio         | rd.io                | 3.6.0     | 4.4.1     |
 195           * | Vine         | vine.co              | 4.1.0     | 4.9.0     |
 196           * | Photobucket  | photobucket.com      | 2.9.0     | 5.1.0     |
 197           * | Funny or Die | funnyordie.com       | 3.0.0     | 5.1.0     |
 198           * | CollegeHumor | collegehumor.com     | 4.0.0     | 5.3.1     |
 199           * | Hulu         | hulu.com             | 2.9.0     | 5.5.0     |
 200           * | Instagram    | instagram.com        | 3.5.0     | 5.5.2     |
 201           * | Instagram    | instagr.am           | 3.5.0     | 5.5.2     |
 202           * | Instagram TV | instagram.com        | 5.1.0     | 5.5.2     |
 203           * | Instagram TV | instagr.am           | 5.1.0     | 5.5.2     |
 204           * | Facebook     | facebook.com         | 4.7.0     | 5.5.2     |
 205           *
 206           * @see wp_oembed_add_provider()
 207           *
 208           * @since 2.9.0
 209           *
 210           * @param array[] $providers An array of arrays containing data about popular oEmbed providers.
 211           */
 212          $this->providers = apply_filters( 'oembed_providers', $providers );
 213  
 214          // Fix any embeds that contain new lines in the middle of the HTML which breaks wpautop().
 215          add_filter( 'oembed_dataparse', array( $this, '_strip_newlines' ), 10, 3 );
 216      }
 217  
 218      /**
 219       * Exposes private/protected methods for backward compatibility.
 220       *
 221       * @since 4.0.0
 222       *
 223       * @param string $name      Method to call.
 224       * @param array  $arguments Arguments to pass when calling.
 225       * @return mixed|false Return value of the callback, false otherwise.
 226       */
 227  	public function __call( $name, $arguments ) {
 228          if ( in_array( $name, $this->compat_methods, true ) ) {
 229              return $this->$name( ...$arguments );
 230          }
 231          return false;
 232      }
 233  
 234      /**
 235       * Takes a URL and returns the corresponding oEmbed provider's URL, if there is one.
 236       *
 237       * @since 4.0.0
 238       *
 239       * @see WP_oEmbed::discover()
 240       *
 241       * @param string       $url  The URL to the content.
 242       * @param string|array $args {
 243       *     Optional. Additional provider arguments. Default empty.
 244       *
 245       *     @type bool $discover Optional. Determines whether to attempt to discover link tags
 246       *                          at the given URL for an oEmbed provider when the provider URL
 247       *                          is not found in the built-in providers list. Default true.
 248       * }
 249       * @return string|false The oEmbed provider URL on success, false on failure.
 250       */
 251  	public function get_provider( $url, $args = '' ) {
 252          $args = wp_parse_args( $args );
 253  
 254          $provider = false;
 255  
 256          if ( ! isset( $args['discover'] ) ) {
 257              $args['discover'] = true;
 258          }
 259  
 260          foreach ( $this->providers as $matchmask => $data ) {
 261              list( $providerurl, $regex ) = $data;
 262  
 263              // Turn the asterisk-type provider URLs into regex.
 264              if ( ! $regex ) {
 265                  $matchmask = '#' . str_replace( '___wildcard___', '(.+)', preg_quote( str_replace( '*', '___wildcard___', $matchmask ), '#' ) ) . '#i';
 266                  $matchmask = preg_replace( '|^#http\\\://|', '#https?\://', $matchmask );
 267              }
 268  
 269              if ( preg_match( $matchmask, $url ) ) {
 270                  $provider = str_replace( '{format}', 'json', $providerurl ); // JSON is easier to deal with than XML.
 271                  break;
 272              }
 273          }
 274  
 275          if ( ! $provider && $args['discover'] ) {
 276              $provider = $this->discover( $url );
 277          }
 278  
 279          return $provider;
 280      }
 281  
 282      /**
 283       * Adds an oEmbed provider.
 284       *
 285       * The provider is added just-in-time when wp_oembed_add_provider() is called before
 286       * the {@see 'plugins_loaded'} hook.
 287       *
 288       * The just-in-time addition is for the benefit of the {@see 'oembed_providers'} filter.
 289       *
 290       * @since 4.0.0
 291       *
 292       * @see wp_oembed_add_provider()
 293       *
 294       * @param string $format   Format of URL that this provider can handle. You can use
 295       *                         asterisks as wildcards.
 296       * @param string $provider The URL to the oEmbed provider..
 297       * @param bool   $regex    Optional. Whether the $format parameter is in a regex format.
 298       *                         Default false.
 299       */
 300  	public static function _add_provider_early( $format, $provider, $regex = false ) {
 301          if ( empty( self::$early_providers['add'] ) ) {
 302              self::$early_providers['add'] = array();
 303          }
 304  
 305          self::$early_providers['add'][ $format ] = array( $provider, $regex );
 306      }
 307  
 308      /**
 309       * Removes an oEmbed provider.
 310       *
 311       * The provider is removed just-in-time when wp_oembed_remove_provider() is called before
 312       * the {@see 'plugins_loaded'} hook.
 313       *
 314       * The just-in-time removal is for the benefit of the {@see 'oembed_providers'} filter.
 315       *
 316       * @since 4.0.0
 317       *
 318       * @see wp_oembed_remove_provider()
 319       *
 320       * @param string $format The format of URL that this provider can handle. You can use
 321       *                       asterisks as wildcards.
 322       */
 323  	public static function _remove_provider_early( $format ) {
 324          if ( empty( self::$early_providers['remove'] ) ) {
 325              self::$early_providers['remove'] = array();
 326          }
 327  
 328          self::$early_providers['remove'][] = $format;
 329      }
 330  
 331      /**
 332       * Takes a URL and attempts to return the oEmbed data.
 333       *
 334       * @see WP_oEmbed::fetch()
 335       *
 336       * @since 4.8.0
 337       *
 338       * @param string       $url  The URL to the content that should be attempted to be embedded.
 339       * @param string|array $args Optional. Additional arguments for retrieving embed HTML.
 340       *                           See wp_oembed_get() for accepted arguments. Default empty.
 341       * @return object|false The result in the form of an object on success, false on failure.
 342       */
 343  	public function get_data( $url, $args = '' ) {
 344          $args = wp_parse_args( $args );
 345  
 346          $provider = $this->get_provider( $url, $args );
 347  
 348          if ( ! $provider ) {
 349              return false;
 350          }
 351  
 352          $data = $this->fetch( $provider, $url, $args );
 353  
 354          if ( false === $data ) {
 355              return false;
 356          }
 357  
 358          return $data;
 359      }
 360  
 361      /**
 362       * The do-it-all function that takes a URL and attempts to return the HTML.
 363       *
 364       * @see WP_oEmbed::fetch()
 365       * @see WP_oEmbed::data2html()
 366       *
 367       * @since 2.9.0
 368       *
 369       * @param string       $url  The URL to the content that should be attempted to be embedded.
 370       * @param string|array $args Optional. Additional arguments for retrieving embed HTML.
 371       *                           See wp_oembed_get() for accepted arguments. Default empty.
 372       * @return string|false The UNSANITIZED (and potentially unsafe) HTML that should be used to embed
 373       *                      on success, false on failure.
 374       */
 375  	public function get_html( $url, $args = '' ) {
 376          /**
 377           * Filters the oEmbed result before any HTTP requests are made.
 378           *
 379           * This allows one to short-circuit the default logic, perhaps by
 380           * replacing it with a routine that is more optimal for your setup.
 381           *
 382           * Returning a non-null value from the filter will effectively short-circuit retrieval
 383           * and return the passed value instead.
 384           *
 385           * @since 4.5.3
 386           *
 387           * @param null|string  $result The UNSANITIZED (and potentially unsafe) HTML that should be used to embed.
 388           *                             Default null to continue retrieving the result.
 389           * @param string       $url    The URL to the content that should be attempted to be embedded.
 390           * @param string|array $args   Optional. Additional arguments for retrieving embed HTML.
 391           *                             See wp_oembed_get() for accepted arguments. Default empty.
 392           */
 393          $pre = apply_filters( 'pre_oembed_result', null, $url, $args );
 394  
 395          if ( null !== $pre ) {
 396              return $pre;
 397          }
 398  
 399          $data = $this->get_data( $url, $args );
 400  
 401          if ( false === $data ) {
 402              return false;
 403          }
 404  
 405          /**
 406           * Filters the HTML returned by the oEmbed provider.
 407           *
 408           * @since 2.9.0
 409           *
 410           * @param string|false $data The returned oEmbed HTML (false if unsafe).
 411           * @param string       $url  URL of the content to be embedded.
 412           * @param string|array $args Optional. Additional arguments for retrieving embed HTML.
 413           *                           See wp_oembed_get() for accepted arguments. Default empty.
 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 string|array $args     Optional. Additional arguments for retrieving embed HTML.
 516       *                               See wp_oembed_get() for accepted arguments. Default empty.
 517       * @return object|false The result in the form of an object on success, false on failure.
 518       */
 519  	public function fetch( $provider, $url, $args = '' ) {
 520          $args = wp_parse_args( $args, wp_embed_defaults( $url ) );
 521  
 522          $provider = add_query_arg( 'maxwidth', (int) $args['width'], $provider );
 523          $provider = add_query_arg( 'maxheight', (int) $args['height'], $provider );
 524          $provider = add_query_arg( 'url', urlencode( $url ), $provider );
 525          $provider = add_query_arg( 'dnt', 1, $provider );
 526  
 527          /**
 528           * Filters the oEmbed URL to be fetched.
 529           *
 530           * @since 2.9.0
 531           * @since 4.9.0 The `dnt` (Do Not Track) query parameter was added to all oEmbed provider URLs.
 532           *
 533           * @param string $provider URL of the oEmbed provider.
 534           * @param string $url      URL of the content to be embedded.
 535           * @param array  $args     Optional. Additional arguments for retrieving embed HTML.
 536           *                         See wp_oembed_get() for accepted arguments. Default empty.
 537           */
 538          $provider = apply_filters( 'oembed_fetch_url', $provider, $url, $args );
 539  
 540          foreach ( array( 'json', 'xml' ) as $format ) {
 541              $result = $this->_fetch_with_format( $provider, $format );
 542              if ( is_wp_error( $result ) && 'not-implemented' === $result->get_error_code() ) {
 543                  continue;
 544              }
 545              return ( $result && ! is_wp_error( $result ) ) ? $result : false;
 546          }
 547          return false;
 548      }
 549  
 550      /**
 551       * Fetches result from an oEmbed provider for a specific format and complete provider URL
 552       *
 553       * @since 3.0.0
 554       *
 555       * @param string $provider_url_with_args URL to the provider with full arguments list (url, maxheight, etc.)
 556       * @param string $format                 Format to use.
 557       * @return object|false|WP_Error The result in the form of an object on success, false on failure.
 558       */
 559  	private function _fetch_with_format( $provider_url_with_args, $format ) {
 560          $provider_url_with_args = add_query_arg( 'format', $format, $provider_url_with_args );
 561  
 562          /** This filter is documented in wp-includes/class-wp-oembed.php */
 563          $args = apply_filters( 'oembed_remote_get_args', array(), $provider_url_with_args );
 564  
 565          $response = wp_safe_remote_get( $provider_url_with_args, $args );
 566          if ( 501 == wp_remote_retrieve_response_code( $response ) ) {
 567              return new WP_Error( 'not-implemented' );
 568          }
 569          $body = wp_remote_retrieve_body( $response );
 570          if ( ! $body ) {
 571              return false;
 572          }
 573          $parse_method = "_parse_$format";
 574          return $this->$parse_method( $body );
 575      }
 576  
 577      /**
 578       * Parses a json response body.
 579       *
 580       * @since 3.0.0
 581       *
 582       * @param string $response_body
 583       * @return object|false
 584       */
 585  	private function _parse_json( $response_body ) {
 586          $data = json_decode( trim( $response_body ) );
 587          return ( $data && is_object( $data ) ) ? $data : false;
 588      }
 589  
 590      /**
 591       * Parses an XML response body.
 592       *
 593       * @since 3.0.0
 594       *
 595       * @param string $response_body
 596       * @return object|false
 597       */
 598  	private function _parse_xml( $response_body ) {
 599          if ( ! function_exists( 'libxml_disable_entity_loader' ) ) {
 600              return false;
 601          }
 602  
 603          if ( PHP_VERSION_ID < 80000 ) {
 604              // This function has been deprecated in PHP 8.0 because in libxml 2.9.0, external entity loading
 605              // is disabled by default, so this function is no longer needed to protect against XXE attacks.
 606              // phpcs:ignore PHPCompatibility.FunctionUse.RemovedFunctions.libxml_disable_entity_loaderDeprecated
 607              $loader = libxml_disable_entity_loader( true );
 608          }
 609  
 610          $errors = libxml_use_internal_errors( true );
 611  
 612          $return = $this->_parse_xml_body( $response_body );
 613  
 614          libxml_use_internal_errors( $errors );
 615  
 616          if ( PHP_VERSION_ID < 80000 && isset( $loader ) ) {
 617              // phpcs:ignore PHPCompatibility.FunctionUse.RemovedFunctions.libxml_disable_entity_loaderDeprecated
 618              libxml_disable_entity_loader( $loader );
 619          }
 620  
 621          return $return;
 622      }
 623  
 624      /**
 625       * Serves as a helper function for parsing an XML response body.
 626       *
 627       * @since 3.6.0
 628       *
 629       * @param string $response_body
 630       * @return stdClass|false
 631       */
 632  	private function _parse_xml_body( $response_body ) {
 633          if ( ! function_exists( 'simplexml_import_dom' ) || ! class_exists( 'DOMDocument', false ) ) {
 634              return false;
 635          }
 636  
 637          $dom     = new DOMDocument;
 638          $success = $dom->loadXML( $response_body );
 639          if ( ! $success ) {
 640              return false;
 641          }
 642  
 643          if ( isset( $dom->doctype ) ) {
 644              return false;
 645          }
 646  
 647          foreach ( $dom->childNodes as $child ) {
 648              if ( XML_DOCUMENT_TYPE_NODE === $child->nodeType ) {
 649                  return false;
 650              }
 651          }
 652  
 653          $xml = simplexml_import_dom( $dom );
 654          if ( ! $xml ) {
 655              return false;
 656          }
 657  
 658          $return = new stdClass;
 659          foreach ( $xml as $key => $value ) {
 660              $return->$key = (string) $value;
 661          }
 662  
 663          return $return;
 664      }
 665  
 666      /**
 667       * Converts a data object from WP_oEmbed::fetch() and returns the HTML.
 668       *
 669       * @since 2.9.0
 670       *
 671       * @param object $data A data object result from an oEmbed provider.
 672       * @param string $url  The URL to the content that is desired to be embedded.
 673       * @return string|false The HTML needed to embed on success, false on failure.
 674       */
 675  	public function data2html( $data, $url ) {
 676          if ( ! is_object( $data ) || empty( $data->type ) ) {
 677              return false;
 678          }
 679  
 680          $return = false;
 681  
 682          switch ( $data->type ) {
 683              case 'photo':
 684                  if ( empty( $data->url ) || empty( $data->width ) || empty( $data->height ) ) {
 685                      break;
 686                  }
 687                  if ( ! is_string( $data->url ) || ! is_numeric( $data->width ) || ! is_numeric( $data->height ) ) {
 688                      break;
 689                  }
 690  
 691                  $title  = ! empty( $data->title ) && is_string( $data->title ) ? $data->title : '';
 692                  $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>';
 693                  break;
 694  
 695              case 'video':
 696              case 'rich':
 697                  if ( ! empty( $data->html ) && is_string( $data->html ) ) {
 698                      $return = $data->html;
 699                  }
 700                  break;
 701  
 702              case 'link':
 703                  if ( ! empty( $data->title ) && is_string( $data->title ) ) {
 704                      $return = '<a href="' . esc_url( $url ) . '">' . esc_html( $data->title ) . '</a>';
 705                  }
 706                  break;
 707  
 708              default:
 709                  $return = false;
 710          }
 711  
 712          /**
 713           * Filters the returned oEmbed HTML.
 714           *
 715           * Use this filter to add support for custom data types, or to filter the result.
 716           *
 717           * @since 2.9.0
 718           *
 719           * @param string $return The returned oEmbed HTML.
 720           * @param object $data   A data object result from an oEmbed provider.
 721           * @param string $url    The URL of the content to be embedded.
 722           */
 723          return apply_filters( 'oembed_dataparse', $return, $data, $url );
 724      }
 725  
 726      /**
 727       * Strips any new lines from the HTML.
 728       *
 729       * @since 2.9.0 as strip_scribd_newlines()
 730       * @since 3.0.0
 731       *
 732       * @param string $html Existing HTML.
 733       * @param object $data Data object from WP_oEmbed::data2html()
 734       * @param string $url The original URL passed to oEmbed.
 735       * @return string Possibly modified $html
 736       */
 737  	public function _strip_newlines( $html, $data, $url ) {
 738          if ( false === strpos( $html, "\n" ) ) {
 739              return $html;
 740          }
 741  
 742          $count     = 1;
 743          $found     = array();
 744          $token     = '__PRE__';
 745          $search    = array( "\t", "\n", "\r", ' ' );
 746          $replace   = array( '__TAB__', '__NL__', '__CR__', '__SPACE__' );
 747          $tokenized = str_replace( $search, $replace, $html );
 748  
 749          preg_match_all( '#(<pre[^>]*>.+?</pre>)#i', $tokenized, $matches, PREG_SET_ORDER );
 750          foreach ( $matches as $i => $match ) {
 751              $tag_html  = str_replace( $replace, $search, $match[0] );
 752              $tag_token = $token . $i;
 753  
 754              $found[ $tag_token ] = $tag_html;
 755              $html                = str_replace( $tag_html, $tag_token, $html, $count );
 756          }
 757  
 758          $replaced = str_replace( $replace, $search, $html );
 759          $stripped = str_replace( array( "\r\n", "\n" ), '', $replaced );
 760          $pre      = array_values( $found );
 761          $tokens   = array_keys( $found );
 762  
 763          return str_replace( $tokens, $pre, $stripped );
 764      }
 765  }


Generated: Fri Sep 24 01:00:04 2021 Cross-referenced by PHPXref 0.7.1