[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

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


Generated : Mon Mar 18 08:20:01 2024 Cross-referenced by PHPXref