home *** CD-ROM | disk | FTP | other *** search
/ HTML Examples / WP.iso / wordpress / wp-includes / class-wp-embed.php < prev    next >
Encoding:
PHP Script  |  2017-10-24  |  14.2 KB  |  480 lines

  1. <?php
  2. /**
  3.  * API for easily embedding rich media such as videos and images into content.
  4.  *
  5.  * @package WordPress
  6.  * @subpackage Embed
  7.  * @since 2.9.0
  8.  */
  9. class WP_Embed {
  10.     public $handlers = array();
  11.     public $post_ID;
  12.     public $usecache = true;
  13.     public $linkifunknown = true;
  14.     public $last_attr = array();
  15.     public $last_url = '';
  16.  
  17.     /**
  18.      * When a URL cannot be embedded, return false instead of returning a link
  19.      * or the URL.
  20.      *
  21.      * Bypasses the {@see 'embed_maybe_make_link'} filter.
  22.      *
  23.      * @var bool
  24.      */
  25.     public $return_false_on_fail = false;
  26.  
  27.     /**
  28.      * Constructor
  29.      */
  30.     public function __construct() {
  31.         // Hack to get the [embed] shortcode to run before wpautop()
  32.         add_filter( 'the_content', array( $this, 'run_shortcode' ), 8 );
  33.         add_filter( 'widget_text_content', array( $this, 'run_shortcode' ), 8 );
  34.  
  35.         // Shortcode placeholder for strip_shortcodes()
  36.         add_shortcode( 'embed', '__return_false' );
  37.  
  38.         // Attempts to embed all URLs in a post
  39.         add_filter( 'the_content', array( $this, 'autoembed' ), 8 );
  40.         add_filter( 'widget_text_content', array( $this, 'autoembed' ), 8 );
  41.  
  42.         // After a post is saved, cache oEmbed items via Ajax
  43.         add_action( 'edit_form_advanced', array( $this, 'maybe_run_ajax_cache' ) );
  44.         add_action( 'edit_page_form', array( $this, 'maybe_run_ajax_cache' ) );
  45.     }
  46.  
  47.     /**
  48.      * Process the [embed] shortcode.
  49.      *
  50.      * Since the [embed] shortcode needs to be run earlier than other shortcodes,
  51.      * this function removes all existing shortcodes, registers the [embed] shortcode,
  52.      * calls do_shortcode(), and then re-registers the old shortcodes.
  53.      *
  54.      * @global array $shortcode_tags
  55.      *
  56.      * @param string $content Content to parse
  57.      * @return string Content with shortcode parsed
  58.      */
  59.     public function run_shortcode( $content ) {
  60.         global $shortcode_tags;
  61.  
  62.         // Back up current registered shortcodes and clear them all out
  63.         $orig_shortcode_tags = $shortcode_tags;
  64.         remove_all_shortcodes();
  65.  
  66.         add_shortcode( 'embed', array( $this, 'shortcode' ) );
  67.  
  68.         // Do the shortcode (only the [embed] one is registered)
  69.         $content = do_shortcode( $content, true );
  70.  
  71.         // Put the original shortcodes back
  72.         $shortcode_tags = $orig_shortcode_tags;
  73.  
  74.         return $content;
  75.     }
  76.  
  77.     /**
  78.      * If a post/page was saved, then output JavaScript to make
  79.      * an Ajax request that will call WP_Embed::cache_oembed().
  80.      */
  81.     public function maybe_run_ajax_cache() {
  82.         $post = get_post();
  83.  
  84.         if ( ! $post || empty( $_GET['message'] ) )
  85.             return;
  86.  
  87. ?>
  88. <script type="text/javascript">
  89.     jQuery(document).ready(function($){
  90.         $.get("<?php echo admin_url( 'admin-ajax.php?action=oembed-cache&post=' . $post->ID, 'relative' ); ?>");
  91.     });
  92. </script>
  93. <?php
  94.     }
  95.  
  96.     /**
  97.      * Registers an embed handler.
  98.      *
  99.      * Do not use this function directly, use wp_embed_register_handler() instead.
  100.      *
  101.      * This function should probably also only be used for sites that do not support oEmbed.
  102.      *
  103.      * @param string $id An internal ID/name for the handler. Needs to be unique.
  104.      * @param string $regex The regex that will be used to see if this handler should be used for a URL.
  105.      * @param callable $callback The callback function that will be called if the regex is matched.
  106.      * @param int $priority Optional. Used to specify the order in which the registered handlers will be tested (default: 10). Lower numbers correspond with earlier testing, and handlers with the same priority are tested in the order in which they were added to the action.
  107.      */
  108.     public function register_handler( $id, $regex, $callback, $priority = 10 ) {
  109.         $this->handlers[$priority][$id] = array(
  110.             'regex'    => $regex,
  111.             'callback' => $callback,
  112.         );
  113.     }
  114.  
  115.     /**
  116.      * Unregisters a previously-registered embed handler.
  117.      *
  118.      * Do not use this function directly, use wp_embed_unregister_handler() instead.
  119.      *
  120.      * @param string $id The handler ID that should be removed.
  121.      * @param int $priority Optional. The priority of the handler to be removed (default: 10).
  122.      */
  123.     public function unregister_handler( $id, $priority = 10 ) {
  124.         unset( $this->handlers[ $priority ][ $id ] );
  125.     }
  126.  
  127.     /**
  128.      * The do_shortcode() callback function.
  129.      *
  130.      * Attempts to convert a URL into embed HTML. Starts by checking the URL against the regex of
  131.      * the registered embed handlers. If none of the regex matches and it's enabled, then the URL
  132.      * will be given to the WP_oEmbed class.
  133.      *
  134.      * @param array $attr {
  135.      *     Shortcode attributes. Optional.
  136.      *
  137.      *     @type int $width  Width of the embed in pixels.
  138.      *     @type int $height Height of the embed in pixels.
  139.      * }
  140.      * @param string $url The URL attempting to be embedded.
  141.      * @return string|false The embed HTML on success, otherwise the original URL.
  142.      *                      `->maybe_make_link()` can return false on failure.
  143.      */
  144.     public function shortcode( $attr, $url = '' ) {
  145.         $post = get_post();
  146.  
  147.         if ( empty( $url ) && ! empty( $attr['src'] ) ) {
  148.             $url = $attr['src'];
  149.         }
  150.  
  151.         $this->last_url = $url;
  152.  
  153.         if ( empty( $url ) ) {
  154.             $this->last_attr = $attr;
  155.             return '';
  156.         }
  157.  
  158.         $rawattr = $attr;
  159.         $attr = wp_parse_args( $attr, wp_embed_defaults( $url ) );
  160.  
  161.         $this->last_attr = $attr;
  162.  
  163.         // kses converts & into & and we need to undo this
  164.         // See https://core.trac.wordpress.org/ticket/11311
  165.         $url = str_replace( '&', '&', $url );
  166.  
  167.         // Look for known internal handlers
  168.         ksort( $this->handlers );
  169.         foreach ( $this->handlers as $priority => $handlers ) {
  170.             foreach ( $handlers as $id => $handler ) {
  171.                 if ( preg_match( $handler['regex'], $url, $matches ) && is_callable( $handler['callback'] ) ) {
  172.                     if ( false !== $return = call_user_func( $handler['callback'], $matches, $attr, $url, $rawattr ) )
  173.                         /**
  174.                          * Filters the returned embed handler.
  175.                          *
  176.                          * @since 2.9.0
  177.                          *
  178.                          * @see WP_Embed::shortcode()
  179.                          *
  180.                          * @param mixed  $return The shortcode callback function to call.
  181.                          * @param string $url    The attempted embed URL.
  182.                          * @param array  $attr   An array of shortcode attributes.
  183.                          */
  184.                         return apply_filters( 'embed_handler_html', $return, $url, $attr );
  185.                 }
  186.             }
  187.         }
  188.  
  189.         $post_ID = ( ! empty( $post->ID ) ) ? $post->ID : null;
  190.  
  191.         // Potentially set by WP_Embed::cache_oembed().
  192.         if ( ! empty( $this->post_ID ) ) {
  193.             $post_ID = $this->post_ID;
  194.         }
  195.  
  196.         // Check for a cached result (stored as custom post or in the post meta).
  197.         $key_suffix    = md5( $url . serialize( $attr ) );
  198.         $cachekey      = '_oembed_' . $key_suffix;
  199.         $cachekey_time = '_oembed_time_' . $key_suffix;
  200.  
  201.         /**
  202.          * Filters the oEmbed TTL value (time to live).
  203.          *
  204.          * @since 4.0.0
  205.          *
  206.          * @param int    $time    Time to live (in seconds).
  207.          * @param string $url     The attempted embed URL.
  208.          * @param array  $attr    An array of shortcode attributes.
  209.          * @param int    $post_ID Post ID.
  210.          */
  211.         $ttl = apply_filters( 'oembed_ttl', DAY_IN_SECONDS, $url, $attr, $post_ID );
  212.  
  213.         $cache      = '';
  214.         $cache_time = 0;
  215.  
  216.         $cached_post_id = $this->find_oembed_post_id( $key_suffix );
  217.  
  218.         if ( $post_ID ) {
  219.             $cache = get_post_meta( $post_ID, $cachekey, true );
  220.             $cache_time = get_post_meta( $post_ID, $cachekey_time, true );
  221.  
  222.             if ( ! $cache_time ) {
  223.                 $cache_time = 0;
  224.             }
  225.         } elseif ( $cached_post_id ) {
  226.             $cached_post = get_post( $cached_post_id );
  227.  
  228.             $cache      = $cached_post->post_content;
  229.             $cache_time = strtotime( $cached_post->post_modified_gmt );
  230.         }
  231.  
  232.         $cached_recently = ( time() - $cache_time ) < $ttl;
  233.  
  234.         if ( $this->usecache || $cached_recently ) {
  235.             // Failures are cached. Serve one if we're using the cache.
  236.             if ( '{{unknown}}' === $cache ) {
  237.                 return $this->maybe_make_link( $url );
  238.             }
  239.  
  240.             if ( ! empty( $cache ) ) {
  241.                 /**
  242.                  * Filters the cached oEmbed HTML.
  243.                  *
  244.                  * @since 2.9.0
  245.                  *
  246.                  * @see WP_Embed::shortcode()
  247.                  *
  248.                  * @param mixed  $cache   The cached HTML result, stored in post meta.
  249.                  * @param string $url     The attempted embed URL.
  250.                  * @param array  $attr    An array of shortcode attributes.
  251.                  * @param int    $post_ID Post ID.
  252.                  */
  253.                 return apply_filters( 'embed_oembed_html', $cache, $url, $attr, $post_ID );
  254.             }
  255.         }
  256.  
  257.         /**
  258.          * Filters whether to inspect the given URL for discoverable link tags.
  259.          *
  260.          * @since 2.9.0
  261.          * @since 4.4.0 The default value changed to true.
  262.          *
  263.          * @see WP_oEmbed::discover()
  264.          *
  265.          * @param bool $enable Whether to enable `<link>` tag discovery. Default true.
  266.          */
  267.         $attr['discover'] = apply_filters( 'embed_oembed_discover', true );
  268.  
  269.         // Use oEmbed to get the HTML.
  270.         $html = wp_oembed_get( $url, $attr );
  271.  
  272.         if ( $post_ID ) {
  273.             if ( $html ) {
  274.                 update_post_meta( $post_ID, $cachekey, $html );
  275.                 update_post_meta( $post_ID, $cachekey_time, time() );
  276.             } elseif ( ! $cache ) {
  277.                 update_post_meta( $post_ID, $cachekey, '{{unknown}}' );
  278.             }
  279.         } else {
  280.             $has_kses = false !== has_filter( 'content_save_pre', 'wp_filter_post_kses' );
  281.  
  282.             if ( $has_kses ) {
  283.                 // Prevent KSES from corrupting JSON in post_content.
  284.                 kses_remove_filters();
  285.             }
  286.  
  287.             $insert_post_args = array(
  288.                 'post_name' => $key_suffix,
  289.                 'post_status' => 'publish',
  290.                 'post_type' => 'oembed_cache',
  291.             );
  292.  
  293.             if ( $html ) {
  294.                 if ( $cached_post_id ) {
  295.                     wp_update_post( wp_slash( array(
  296.                         'ID' => $cached_post_id,
  297.                         'post_content' => $html,
  298.                     ) ) );
  299.                 } else {
  300.                     wp_insert_post( wp_slash( array_merge(
  301.                         $insert_post_args,
  302.                         array(
  303.                             'post_content' => $html,
  304.                         )
  305.                     ) ) );
  306.                 }
  307.             } elseif ( ! $cache ) {
  308.                 wp_insert_post( wp_slash( array_merge(
  309.                     $insert_post_args,
  310.                     array(
  311.                         'post_content' => '{{unknown}}',
  312.                     )
  313.                 ) ) );
  314.             }
  315.  
  316.             if ( $has_kses ) {
  317.                 kses_init_filters();
  318.             }
  319.         }
  320.  
  321.         // If there was a result, return it.
  322.         if ( $html ) {
  323.             /** This filter is documented in wp-includes/class-wp-embed.php */
  324.             return apply_filters( 'embed_oembed_html', $html, $url, $attr, $post_ID );
  325.         }
  326.  
  327.         // Still unknown
  328.         return $this->maybe_make_link( $url );
  329.     }
  330.  
  331.     /**
  332.      * Delete all oEmbed caches. Unused by core as of 4.0.0.
  333.      *
  334.      * @param int $post_ID Post ID to delete the caches for.
  335.      */
  336.     public function delete_oembed_caches( $post_ID ) {
  337.         $post_metas = get_post_custom_keys( $post_ID );
  338.         if ( empty($post_metas) )
  339.             return;
  340.  
  341.         foreach ( $post_metas as $post_meta_key ) {
  342.             if ( '_oembed_' == substr( $post_meta_key, 0, 8 ) )
  343.                 delete_post_meta( $post_ID, $post_meta_key );
  344.         }
  345.     }
  346.  
  347.     /**
  348.      * Triggers a caching of all oEmbed results.
  349.      *
  350.      * @param int $post_ID Post ID to do the caching for.
  351.      */
  352.     public function cache_oembed( $post_ID ) {
  353.         $post = get_post( $post_ID );
  354.  
  355.         $post_types = get_post_types( array( 'show_ui' => true ) );
  356.         /**
  357.          * Filters the array of post types to cache oEmbed results for.
  358.          *
  359.          * @since 2.9.0
  360.          *
  361.          * @param array $post_types Array of post types to cache oEmbed results for. Defaults to post types with `show_ui` set to true.
  362.          */
  363.         if ( empty( $post->ID ) || ! in_array( $post->post_type, apply_filters( 'embed_cache_oembed_types', $post_types ) ) ){
  364.             return;
  365.         }
  366.  
  367.         // Trigger a caching
  368.         if ( ! empty( $post->post_content ) ) {
  369.             $this->post_ID = $post->ID;
  370.             $this->usecache = false;
  371.  
  372.             $content = $this->run_shortcode( $post->post_content );
  373.             $this->autoembed( $content );
  374.  
  375.             $this->usecache = true;
  376.         }
  377.     }
  378.  
  379.     /**
  380.      * Passes any unlinked URLs that are on their own line to WP_Embed::shortcode() for potential embedding.
  381.      *
  382.      * @see WP_Embed::autoembed_callback()
  383.      *
  384.      * @param string $content The content to be searched.
  385.      * @return string Potentially modified $content.
  386.      */
  387.     public function autoembed( $content ) {
  388.         // Replace line breaks from all HTML elements with placeholders.
  389.         $content = wp_replace_in_html_tags( $content, array( "\n" => '<!-- wp-line-break -->' ) );
  390.  
  391.         if ( preg_match( '#(^|\s|>)https?://#i', $content ) ) {
  392.             // Find URLs on their own line.
  393.             $content = preg_replace_callback( '|^(\s*)(https?://[^\s<>"]+)(\s*)$|im', array( $this, 'autoembed_callback' ), $content );
  394.             // Find URLs in their own paragraph.
  395.             $content = preg_replace_callback( '|(<p(?: [^>]*)?>\s*)(https?://[^\s<>"]+)(\s*<\/p>)|i', array( $this, 'autoembed_callback' ), $content );
  396.         }
  397.  
  398.         // Put the line breaks back.
  399.         return str_replace( '<!-- wp-line-break -->', "\n", $content );
  400.     }
  401.  
  402.     /**
  403.      * Callback function for WP_Embed::autoembed().
  404.      *
  405.      * @param array $match A regex match array.
  406.      * @return string The embed HTML on success, otherwise the original URL.
  407.      */
  408.     public function autoembed_callback( $match ) {
  409.         $oldval = $this->linkifunknown;
  410.         $this->linkifunknown = false;
  411.         $return = $this->shortcode( array(), $match[2] );
  412.         $this->linkifunknown = $oldval;
  413.  
  414.         return $match[1] . $return . $match[3];
  415.     }
  416.  
  417.     /**
  418.      * Conditionally makes a hyperlink based on an internal class variable.
  419.      *
  420.      * @param string $url URL to potentially be linked.
  421.      * @return false|string Linked URL or the original URL. False if 'return_false_on_fail' is true.
  422.      */
  423.     public function maybe_make_link( $url ) {
  424.         if ( $this->return_false_on_fail ) {
  425.             return false;
  426.         }
  427.  
  428.         $output = ( $this->linkifunknown ) ? '<a href="' . esc_url($url) . '">' . esc_html($url) . '</a>' : $url;
  429.  
  430.         /**
  431.          * Filters the returned, maybe-linked embed URL.
  432.          *
  433.          * @since 2.9.0
  434.          *
  435.          * @param string $output The linked or original URL.
  436.          * @param string $url    The original URL.
  437.          */
  438.         return apply_filters( 'embed_maybe_make_link', $output, $url );
  439.     }
  440.  
  441.     /**
  442.      * Find the oEmbed cache post ID for a given cache key.
  443.      *
  444.      * @since 4.9.0
  445.      *
  446.      * @param string $cache_key oEmbed cache key.
  447.      * @return int|null Post ID on success, null on failure.
  448.      */
  449.     public function find_oembed_post_id( $cache_key ) {
  450.         $cache_group    = 'oembed_cache_post';
  451.         $oembed_post_id = wp_cache_get( $cache_key, $cache_group );
  452.  
  453.         if ( $oembed_post_id && 'oembed_cache' === get_post_type( $oembed_post_id ) ) {
  454.             return $oembed_post_id;
  455.         }
  456.  
  457.         $oembed_post_query = new WP_Query( array(
  458.             'post_type'              => 'oembed_cache',
  459.             'post_status'            => 'publish',
  460.             'name'                   => $cache_key,
  461.             'posts_per_page'         => 1,
  462.             'no_found_rows'          => true,
  463.             'cache_results'          => true,
  464.             'update_post_meta_cache' => false,
  465.             'update_post_term_cache' => false,
  466.             'lazy_load_term_meta'    => false,
  467.         ) );
  468.  
  469.         if ( ! empty( $oembed_post_query->posts ) ) {
  470.             // Note: 'fields'=>'ids' is not being used in order to cache the post object as it will be needed.
  471.             $oembed_post_id = $oembed_post_query->posts[0]->ID;
  472.             wp_cache_set( $cache_key, $oembed_post_id, $cache_group );
  473.  
  474.             return $oembed_post_id;
  475.         }
  476.  
  477.         return null;
  478.     }
  479. }
  480.