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


Generated : Tue Dec 3 08:20:01 2024 Cross-referenced by PHPXref