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


Generated: Sun May 22 01:00:03 2022 Cross-referenced by PHPXref 0.7.1