public function setUp() { parent::setUp(); require_once ABSPATH . WPINC . '/class-oembed.php'; $this->oembed = _wp_oembed_get_object(); $this->pre_oembed_result_filtered = false; }
function callback($path = '', $blog_id = 0) { $blog_id = $this->api->switch_to_blog_and_validate_user($this->api->get_blog_id($blog_id)); if (is_wp_error($blog_id)) { return $blog_id; } // permissions check if (!current_user_can('edit_posts')) { return new WP_Error('unauthorized', 'Your token must have permission to post on this blog.', 403); } // list em $output = array('embeds' => array()); if (!function_exists('_wp_oembed_get_object')) { require_once ABSPATH . WPINC . '/class-oembed.php'; } global $wp_embed; $oembed = _wp_oembed_get_object(); foreach ($wp_embed->handlers as $priority => $handlers) { foreach ($handlers as $handler) { if (!empty($handler['regex'])) { $output['embeds'][] = $handler['regex']; } } } foreach ($oembed->providers as $regex => $oembed_info) { if (!empty($regex)) { $output['embeds'][] = $regex; } } return $output; }
public function __construct() { // Does not extend oEmbed in order to not initialize it a second time. require_once ABSPATH . '/' . WPINC . '/class-oembed.php'; $this->oembed = _wp_oembed_get_object(); add_filter('oembed_fetch_url', array($this, 'additional_arguments'), 10, 3); }
public function __construct($url = false) { if (!function_exists('_wp_oembed_get_object')) { require_once ABSPATH . WPINC . '/class-oembed.php'; } $this->_wp_oembed = _wp_oembed_get_object(); $this->set_url($url); }
/** * Test if the site was added as an oEmbed provider. */ function test_add_oembed_provider() { $oembed = _wp_oembed_get_object(); wp_oembed_remove_provider(home_url('/*')); $this->assertArrayNotHasKey(home_url('/*'), $oembed->providers); $this->plugin()->add_oembed_provider(); $this->assertArrayHasKey(home_url('/*'), $oembed->providers); $this->assertEquals(array(esc_url(rest_url('wp/v2/oembed')), false), $oembed->providers[home_url('/*')]); }
/** * Test if the site was added as an oEmbed provider. */ function test_add_oembed_provider() { $oembed = _wp_oembed_get_object(); wp_oembed_remove_provider(home_url('/*')); $this->assertArrayNotHasKey(home_url('/*'), $oembed->providers); wp_oembed_add_site_as_provider(); $this->assertArrayHasKey(home_url('/*'), $oembed->providers); $this->assertEquals(array(get_oembed_endpoint_url(), false), $oembed->providers[home_url('/*')]); }
public function paragraph_not_contains_element($paragraph) { require_once ABSPATH . WPINC . '/class-oembed.php'; $wp_oembed = _wp_oembed_get_object(); preg_match_all('|^\\s*(https?://[^\\s"]+)\\s*$|im', $paragraph, $matches); foreach ($matches[1] as $match) { if ($wp_oembed->get_provider($match, array('discover' => false))) { return false; } } return true; }
/** * Render only field html * * @return string */ public function render_field() { if ($this->get_value()) { require_once ABSPATH . WPINC . '/class-oembed.php'; /* @var \WP_oEmbed $oembed */ $oembed = _wp_oembed_get_object(); $provider = $oembed->get_provider($this->get_value()); $data = $oembed->fetch($provider, $this->get_value()); $this->_video = $data; } return sprintf('<input type="text" name="%s" id="%s" class="video_field %s" value="%s" placeholder="%s" %s /> %s<div class="video_info">%s</div>', $this->get_name(), $this->get_id(), $this->_get_classes(), $this->get_value(), $this->get_placeholder(), $this->_get_attributes(), $this->_get_description(), $this->_get_video_info()); }
function jetpack_houzz_shortcode($atts, $content = null) { $url = substr($atts[0], 1); $args = array(); if (isset($atts['w']) && is_numeric($atts['w'])) { $args['width'] = $atts['w']; } if (isset($atts['h']) && is_numeric($atts['h'])) { $args['height'] = $atts['h']; } $oembed = _wp_oembed_get_object(); return $oembed->get_html($url, $args); }
function mk_theme_oembed_audios() { global $post; if ($post && $post->post_content) { global $shortcode_tags; // Make a copy of global shortcode tags - we'll temporarily overwrite it. $theme_shortcode_tags = $shortcode_tags; // The shortcodes we're interested in. $shortcode_tags = array('audio' => $theme_shortcode_tags['audio'], 'embed' => $theme_shortcode_tags['embed']); // Get the absurd shortcode regexp. $audio_regex = '#' . get_shortcode_regex() . '#i'; // Restore global shortcode tags. $shortcode_tags = $theme_shortcode_tags; $pattern_array = array($audio_regex); // Get the patterns from the embed object. if (!function_exists('_wp_oembed_get_object')) { include ABSPATH . WPINC . '/class-oembed.php'; } $oembed = _wp_oembed_get_object(); $pattern_array = array_merge($pattern_array, array_keys($oembed->providers)); // Or all the patterns together. $pattern = '#(' . array_reduce($pattern_array, function ($carry, $item) { if (strpos($item, '#') === 0) { // Assuming '#...#i' regexps. $item = substr($item, 1, -2); } else { // Assuming glob patterns. $item = str_replace('*', '(.+)', $item); } return $carry ? $carry . ')|(' . $item : $item; }) . ')#is'; // Simplistic parse of content line by line. $lines = explode("\n", $post->post_content); foreach ($lines as $line) { $line = trim($line); if (preg_match($pattern, $line, $matches)) { if (strpos($matches[0], '[') === 0) { $ret = do_shortcode($matches[0]); } else { $ret = wp_oembed_get($matches[0]); } return $ret; } } } }
/** * Gets the specified meta info from the given post content. * NOTE: If you want IMAGES, call extract( $blog_id, $post_id, ...) which will give you more/better image extraction * This method will give you an error if you ask for IMAGES. * * @param $content The HTML post_content of a post * @param $what_to_extract (int) A mask of things to extract, e.g. Jetpack_Media_Meta_Extractor::IMAGES | Jetpack_Media_Meta_Extractor::MENTIONS * @param $already_extracted (array) Previously extracted things, e.g. images from extract(), which can be used for x-referencing here * @returns a structure containing metadata about the embedded things, or empty array if nothing found, or WP_Error on error */ public static function extract_from_content($content, $what_to_extract = self::ALL, $already_extracted = array()) { $stripped_content = self::get_stripped_content($content); // Maybe start with some previously extracted things (e.g. images from extract() $extracted = $already_extracted; // Embedded media objects will have already been converted to shortcodes by pre_kses hooks on save. if (self::IMAGES & $what_to_extract) { $images = Jetpack_Media_Meta_Extractor::extract_images_from_content($stripped_content); $extracted = array_merge($extracted, $images); } // ----------------------------------- MENTIONS ------------------------------ if (self::MENTIONS & $what_to_extract) { if (preg_match_all('/(^|\\s)@(\\w+)/u', $stripped_content, $matches)) { $mentions = array_values(array_unique($matches[2])); //array_unique() retains the keys! $mentions = array_map('strtolower', $mentions); $extracted['mention'] = array('name' => $mentions); if (!isset($extracted['has'])) { $extracted['has'] = array(); } $extracted['has']['mention'] = count($mentions); } } // ----------------------------------- HASHTAGS ------------------------------ /* Some hosts may not compile with --enable-unicode-properties and kick a warning Warning: preg_match_all() [function.preg-match-all]: Compilation failed: support for \P, \p, and \X has not been compiled if ( self::HASHTAGS & $what_to_extract ) { //This regex does not exactly match Twitter's // if there are problems/complaints we should implement this: // https://github.com/twitter/twitter-text-java/blob/master/src/com/twitter/Regex.java if ( preg_match_all( '/(?:^|\s)#(\w*\p{L}+\w*)/u', $stripped_content, $matches ) ) { $hashtags = array_values( array_unique( $matches[1] ) ); //array_unique() retains the keys! $hashtags = array_map( 'strtolower', $hashtags ); $extracted['hashtag'] = array( 'name' => $hashtags ); if ( !isset( $extracted['has'] ) ) $extracted['has'] = array(); $extracted['has']['hashtag'] = count( $hashtags ); } } */ // ----------------------------------- SHORTCODES ------------------------------ // Always look for shortcodes. // If we don't want them, we'll just remove them, so we don't grab them as links below $shortcode_pattern = '/' . get_shortcode_regex() . '/s'; if (preg_match_all($shortcode_pattern, $content, $matches)) { $shortcode_total_count = 0; $shortcode_type_counts = array(); $shortcode_types = array(); $shortcode_details = array(); if (self::SHORTCODES & $what_to_extract) { foreach ($matches[2] as $key => $shortcode) { //Elasticsearch (and probably other things) doesn't deal well with some chars as key names $shortcode_name = preg_replace('/[.,*"\'\\/\\\\#+ ]/', '_', $shortcode); $attr = shortcode_parse_atts($matches[3][$key]); $shortcode_total_count++; if (!isset($shortcode_type_counts[$shortcode_name])) { $shortcode_type_counts[$shortcode_name] = 0; } $shortcode_type_counts[$shortcode_name]++; // Store (uniquely) presence of all shortcode regardless of whether it's a keeper (for those, get ID below) // @todo Store number of occurrences? if (!in_array($shortcode_name, $shortcode_types)) { $shortcode_types[] = $shortcode_name; } // For keeper shortcodes, also store the id/url of the object (e.g. youtube video, TED talk, etc.) if (in_array($shortcode, self::$KEEPER_SHORTCODES)) { unset($id); // Clear shortcode ID data left from the last shortcode // We'll try to get the salient ID from the function jetpack_shortcode_get_xyz_id() // If the shortcode is a class, we'll call XyzShortcode::get_xyz_id() $shortcode_get_id_func = "jetpack_shortcode_get_{$shortcode}_id"; $shortcode_class_name = ucfirst($shortcode) . 'Shortcode'; $shortcode_get_id_method = "get_{$shortcode}_id"; if (function_exists($shortcode_get_id_func)) { $id = call_user_func($shortcode_get_id_func, $attr); } else { if (method_exists($shortcode_class_name, $shortcode_get_id_method)) { $id = call_user_func(array($shortcode_class_name, $shortcode_get_id_method), $attr); } } if (!empty($id) && (!isset($shortcode_details[$shortcode_name]) || !in_array($id, $shortcode_details[$shortcode_name]))) { $shortcode_details[$shortcode_name][] = $id; } } } if ($shortcode_total_count > 0) { // Add the shortcode info to the $extracted array if (!isset($extracted['has'])) { $extracted['has'] = array(); } $extracted['has']['shortcode'] = $shortcode_total_count; $extracted['shortcode'] = array(); foreach ($shortcode_type_counts as $type => $count) { $extracted['shortcode'][$type] = array('count' => $count); } if (!empty($shortcode_types)) { $extracted['shortcode_types'] = $shortcode_types; } foreach ($shortcode_details as $type => $id) { $extracted['shortcode'][$type]['id'] = $id; } } } // Remove the shortcodes form our copy of $content, so we don't count links in them as links below. $content = preg_replace($shortcode_pattern, ' ', $content); } // ----------------------------------- LINKS ------------------------------ if (self::LINKS & $what_to_extract) { // To hold the extracted stuff we find $links = array(); // @todo Get the text inside the links? // Grab any links, whether in <a href="..." or not, but subtract those from shortcodes and images // (we treat embed links as just another link) if (preg_match_all('#(?:^|\\s|"|\')(https?://([^\\s()<>]+(?:\\([\\w\\d]+\\)|([^[:punct:]\\s]|/))))#', $content, $matches)) { foreach ($matches[1] as $link_raw) { $url = parse_url($link_raw); // Build a simple form of the URL so we can compare it to ones we found in IMAGES or SHORTCODES and exclude those $simple_url = $url['scheme'] . '://' . $url['host'] . (!empty($url['path']) ? $url['path'] : ''); if (isset($extracted['image']['url'])) { if (in_array($simple_url, (array) $extracted['image']['url'])) { continue; } } list($proto, $link_all_but_proto) = explode('://', $link_raw); // Build a reversed hostname $host_parts = array_reverse(explode('.', $url['host'])); $host_reversed = ''; foreach ($host_parts as $part) { $host_reversed .= (!empty($host_reversed) ? '.' : '') . $part; } $link_analyzed = ''; if (!empty($url['path'])) { // The whole path (no query args or fragments) $path = substr($url['path'], 1); // strip the leading '/' $link_analyzed .= (!empty($link_analyzed) ? ' ' : '') . $path; // The path split by / $path_split = explode('/', $path); if (count($path_split) > 1) { $link_analyzed .= ' ' . implode(' ', $path_split); } // The fragment if (!empty($url['fragment'])) { $link_analyzed .= (!empty($link_analyzed) ? ' ' : '') . $url['fragment']; } } // @todo Check unique before adding $links[] = array('url' => $link_all_but_proto, 'host_reversed' => $host_reversed, 'host' => $url['host']); } } $link_count = count($links); $extracted['link'] = $links; if ($link_count) { if (!isset($extracted['has'])) { $extracted['has'] = array(); } $extracted['has']['link'] = $link_count; } } // ----------------------------------- EMBEDS ------------------------------ //Embeds are just individual links on their own line if (self::EMBEDS & $what_to_extract) { if (!function_exists('_wp_oembed_get_object')) { include ABSPATH . WPINC . '/class-oembed.php'; } // get an oembed object $oembed = _wp_oembed_get_object(); // Grab any links on their own lines that may be embeds if (preg_match_all('|^\\s*(https?://[^\\s"]+)\\s*$|im', $content, $matches)) { // To hold the extracted stuff we find $embeds = array(); foreach ($matches[1] as $link_raw) { $url = parse_url($link_raw); list($proto, $link_all_but_proto) = explode('://', $link_raw); // Check whether this "link" is really an embed. foreach ($oembed->providers as $matchmask => $data) { list($providerurl, $regex) = $data; // Turn the asterisk-type provider URLs into regex if (!$regex) { $matchmask = '#' . str_replace('___wildcard___', '(.+)', preg_quote(str_replace('*', '___wildcard___', $matchmask), '#')) . '#i'; $matchmask = preg_replace('|^#http\\\\://|', '#https?\\://', $matchmask); } if (preg_match($matchmask, $link_raw)) { $provider = str_replace('{format}', 'json', $providerurl); // JSON is easier to deal with than XML $embeds[] = $link_all_but_proto; // @todo Check unique before adding // @todo Try to get ID's for the ones we care about (shortcode_keepers) break; } } } if (!empty($embeds)) { if (!isset($extracted['has'])) { $extracted['has'] = array(); } $extracted['has']['embed'] = count($embeds); $extracted['embed'] = array('url' => array()); foreach ($embeds as $e) { $extracted['embed']['url'][] = $e; } } } } return $extracted; }
public static function wpSetUpBeforeClass() { self::$oembed = _wp_oembed_get_object(); }
/** * The {@link do_shortcode()} callback function. * * Attempts to convert a URL into embed HTML. Starts by checking the * URL against the regex of the registered embed handlers. Next, checks * the URL against the regex of registered {@link WP_oEmbed} providers * if oEmbed discovery is false. If none of the regex matches and it's * enabled, then the URL will be passed to {@link BP_Embed::parse_oembed()} * for oEmbed parsing. * * @uses wp_parse_args() * @uses wp_embed_defaults() * @uses current_user_can() * @uses _wp_oembed_get_object() * @uses WP_Embed::maybe_make_link() * * @param array $attr Shortcode attributes. * @param string $url The URL attempting to be embeded. * @return string The embed HTML on success, otherwise the original URL. */ public function shortcode($attr, $url = '') { if (empty($url)) { return ''; } $rawattr = $attr; $attr = wp_parse_args($attr, wp_embed_defaults()); // Use kses to convert & into & and we need to undo this // See https://core.trac.wordpress.org/ticket/11311. $url = str_replace('&', '&', $url); // Look for known internal handlers. ksort($this->handlers); foreach ($this->handlers as $priority => $handlers) { foreach ($handlers as $hid => $handler) { if (preg_match($handler['regex'], $url, $matches) && is_callable($handler['callback'])) { if (false !== ($return = call_user_func($handler['callback'], $matches, $attr, $url, $rawattr))) { /** * Filters the oEmbed handler result for the provided URL. * * @since 1.5.0 * * @param string $return Handler callback for the oEmbed. * @param string $url URL attempting to be embedded. * @param array $attr Shortcode attributes. */ return apply_filters('embed_handler_html', $return, $url, $attr); } } } } /** * Filters the embed object ID. * * @since 1.5.0 * * @param int $value Value of zero. */ $id = apply_filters('embed_post_id', 0); $unfiltered_html = current_user_can('unfiltered_html'); $default_discovery = false; // Since 4.4, WordPress is now an oEmbed provider. if (function_exists('wp_oembed_register_route')) { $unfiltered_html = true; $default_discovery = true; } /** * Filters whether or not oEmbed discovery is on. * * @since 1.5.0 * @since 2.5.0 Default status of oEmbed discovery has been switched * to true to apply changes introduced in WordPress 4.4 * * @param bool $default_discovery Current status of oEmbed discovery. */ $attr['discover'] = apply_filters('bp_embed_oembed_discover', $default_discovery) && $unfiltered_html; // Set up a new WP oEmbed object to check URL with registered oEmbed providers. require_once ABSPATH . WPINC . '/class-oembed.php'; $oembed_obj = _wp_oembed_get_object(); // If oEmbed discovery is true, skip oEmbed provider check. $is_oembed_link = false; if (!$attr['discover']) { foreach ((array) $oembed_obj->providers as $provider_matchmask => $provider) { $regex = ($is_regex = $provider[1]) ? $provider_matchmask : '#' . str_replace('___wildcard___', '(.+)', preg_quote(str_replace('*', '___wildcard___', $provider_matchmask), '#')) . '#i'; if (preg_match($regex, $url)) { $is_oembed_link = true; } } // If url doesn't match a WP oEmbed provider, stop parsing. if (!$is_oembed_link) { return $this->maybe_make_link($url); } } return $this->parse_oembed($id, $url, $attr, $rawattr); }
/** * Limit embed source URLs to specific providers. * * Not all core oEmbed providers are supported. Supported providers include YouTube, Vimeo, * Vine, Daily Motion, SoundCloud, and Twitter. * * @ignore * @since 4.2.0 * * @param string $src Embed source URL. * @return string If not from a supported provider, an empty string. Otherwise, a reformattd embed URL. */ private function _limit_embed($src) { $src = $this->_limit_url($src); if (empty($src)) { return ''; } if (preg_match('!//(m|www)\\.youtube\\.com/(embed|v)/([^?]+)\\?.+$!i', $src, $src_matches)) { // Embedded Youtube videos (www or mobile) $src = 'https://www.youtube.com/watch?v=' . $src_matches[3]; } else { if (preg_match('!//player\\.vimeo\\.com/video/([\\d]+)([?/].*)?$!i', $src, $src_matches)) { // Embedded Vimeo iframe videos $src = 'https://vimeo.com/' . (int) $src_matches[1]; } else { if (preg_match('!//vimeo\\.com/moogaloop\\.swf\\?clip_id=([\\d]+)$!i', $src, $src_matches)) { // Embedded Vimeo Flash videos $src = 'https://vimeo.com/' . (int) $src_matches[1]; } else { if (preg_match('!//vine\\.co/v/([^/]+)/embed!i', $src, $src_matches)) { // Embedded Vine videos $src = 'https://vine.co/v/' . $src_matches[1]; } else { if (preg_match('!//(www\\.)?dailymotion\\.com/embed/video/([^/?]+)([/?].+)?!i', $src, $src_matches)) { // Embedded Daily Motion videos $src = 'https://www.dailymotion.com/video/' . $src_matches[2]; } else { $oembed = _wp_oembed_get_object(); if (!$oembed->get_provider($src, array('discover' => false))) { $src = ''; } } } } } } return $src; }
/** * Save via AJAX the height of the preview wrap. * * @since 2.0.1 */ public function filter_content($content) { global $post; $typenow = get_post_type(); $editor = get_post_meta($post->ID, 'pixBuilderDisable', true); if ($typenow == 'page') { $display = true; } else { $display = false; } $row_open = apply_filters('pixgridder_row_open', "<div class=\"row\" data-cols=\"\$1\">"); $row_close = apply_filters('pixgridder_row_close', "</div><!--.row[data-cols=\"\$1\"]-->"); $column_open = apply_filters('pixgridder_column_open', "<div class=\"column\" data-col=\"\$1\">"); $column_close = apply_filters('pixgridder_column_close', "</div><!--.column[data-col=\"\$1\"]-->"); if ($display == true) { require_once ABSPATH . WPINC . '/class-oembed.php'; $oembed = _wp_oembed_get_object(); $providers = $oembed->providers; if (!function_exists('pixgridder_match_oembed')) { function pixgridder_match_oembed($matches) { $var = preg_replace('/<p>/', '', $matches[0]); $var = preg_replace('/<\\/p>/', '', $var); global $wp_embed; return $wp_embed->autoembed($var); } } foreach ($providers as $key => $value) { if (substr($key, 0, 1) == '#') { $content = preg_replace_callback("{$key}", 'pixgridder_match_oembed', $content); } } $content = preg_replace('/data-id\\[(.+?)\\]/', 'id="$1"', $content); $content = preg_replace('/data-class\\[(.+?)\\]/', 'class="$1"', $content); $content = preg_replace('/<!--pixgridder:column\\[(.?[^\\]\\s]+)\\]--><!--\\/pixgridder:column(.+?)-->/', '', $content); $content = preg_replace('/<!--pixgridder:row\\[(.?[^\\]\\s]+)\\]--><!--\\/pixgridder:row(.+?)-->/', '', $content); $content = preg_replace('/<p><!--pixgridder:(.+?)-->(?!<!--)/', '<!--pixgridder:$1--><p>', $content); $content = preg_replace('/<p><!--\\/pixgridder:(.+?)-->(?!<!--)/', '<!--/pixgridder:$1--><p>', $content); $content = preg_replace('/<p><!--pixgridder:(.+?)--><\\/p>/', '<!--pixgridder:$1-->', $content); $content = preg_replace('/<p><!--\\/pixgridder:(.+?)--><\\/p>/', '<!--/pixgridder:$1-->', $content); $content = preg_replace('/<!--\\/pixgridder:(.+?)--><p><\\/p>/', '<!--/pixgridder:$1-->', $content); if (strpos($column_open, ' class=') !== false) { preg_match('/ class=[\'"](.+?)[\'"]/', $column_open, $class); $column_open = preg_replace('/ class=[\'"](.+?)[\'"]/', ' class="$1 dollar2"', $column_open); $column_open = str_replace("dollar2", "\$2", $column_open); $content = preg_replace('/<!--pixgridder:column(.+?) class="(.+?)"-->/', $column_open, $content); $column_open = str_replace(" \$2", "", $column_open); $content = preg_replace('/<!--pixgridder:column(.+?)-->/', $column_open, $content); $content = preg_replace('/data-col="\\[col=(.?[^\\]\\s]+)\\] id="(.+?)""/', 'data-col="$1" id="$2"', $content); $content = preg_replace('/data-col="\\[col=(.+?)\\]"/', 'data-col="$1"', $content); } else { $content = preg_replace('/<!--pixgridder:column\\[col=(.+?)\\]-->/', $column_open, $content); $column_open = preg_replace('/<(.+?)>/', '<$1 dollar2>', $column_open); $column_open = str_replace("dollar2", "\$2", $column_open); $content = preg_replace('/<!--pixgridder:column\\[col=(.?[^\\]\\s]+)\\](.+?)-->/', $column_open, $content); } $content = preg_replace('/ class=/', ' class=', $content); if (strpos($row_open, ' class=') !== false) { preg_match('/ class=[\'"](.+?)[\'"]/', $row_open, $class); $row_open = preg_replace('/ class=[\'"](.+?)[\'"]/', ' class="$1 dollar2"', $row_open); $row_open = str_replace("dollar2", "\$2", $row_open); $content = preg_replace('/<!--pixgridder:row(.+?) class="(.+?)"-->/', $row_open, $content); $row_open = str_replace(" \$2", "", $row_open); $content = preg_replace('/<!--pixgridder:row(.+?)-->/', $row_open, $content); $content = preg_replace('/data-cols="\\[cols=(.?[^\\]\\s]+)\\] id="(.+?)""/', 'data-cols="$1" id="$2"', $content); $content = preg_replace('/data-cols="\\[cols=(.+?)\\]"/', 'data-cols="$1"', $content); } else { $content = preg_replace('/<!--pixgridder:row\\[cols=(.+?)\\]-->/', $row_open, $content); $row_open = preg_replace('/<(.+?)>/', '<$1 dollar2>', $row_open); $row_open = str_replace("dollar2", "\$2", $row_open); $content = preg_replace('/<!--pixgridder:row\\[cols=(.?[^\\]\\s]+)\\](.+?)-->/', $row_open, $content); } $content = preg_replace('/<!--\\/pixgridder:row\\[cols=(.+?)\\]-->/', $row_close, $content); $content = preg_replace('/<!--\\/pixgridder:column\\[col=(.+?)\\]-->/', $column_close, $content); $content = preg_replace('/ class=/', ' class=', $content); $content = preg_replace('/<p><\\/p>/', '', $content); } else { $content = preg_replace('/<!--pixgridder(.+?)-->/', '', $content); $content = preg_replace('/<!--\\/pixgridder(.+?)-->/', '', $content); } return $content; }
function jetpack_flickr_oembed_handler($matches, $attr, $url) { // Legacy slideshow embeds end with /show/ // e.g. http://www.flickr.com/photos/yarnaholic/sets/72157615194738969/show/ if ('/show/' !== substr($url, -strlen('/show/'))) { // These lookups need cached, as they don't use WP_Embed (which caches) $found = false; $cache_key = md5($url . serialize($attr)); $cache_group = 'oembed_flickr'; $html = wp_cache_get($cache_key, $cache_group, null, $found); if (false === $found) { $html = _wp_oembed_get_object()->get_html($url, $attr); wp_cache_set($cache_key, $html, $cache_group, 60 * MINUTE_IN_SECONDS); } return $html; } return flickr_shortcode_handler(array('photo' => $url)); }
/** * Adds a URL format and oEmbed provider URL pair. * * @since 2.9.0 * @see WP_oEmbed * * @uses _wp_oembed_get_object() * * @param string $format The format of URL that this provider can handle. You can use asterisks as wildcards. * @param string $provider The URL to the oEmbed provider. * @param boolean $regex Whether the $format parameter is in a regex format. */ function wp_oembed_add_provider($format, $provider, $regex = false) { require_once ABSPATH . WPINC . '/class-oembed.php'; $oembed = _wp_oembed_get_object(); $oembed->providers[$format] = array($provider, $regex); }
/** * The {@link do_shortcode()} callback function. * * Attempts to convert a URL into embed HTML. Starts by checking the URL against the regex of the registered embed handlers. * Next, checks the URL against the regex of registered {@link WP_oEmbed} providers if oEmbed discovery is false. * If none of the regex matches and it's enabled, then the URL will be passed to {@link BP_Embed::parse_oembed()} for oEmbed parsing. * * @uses wp_parse_args() * @uses wp_embed_defaults() * @uses current_user_can() * @uses _wp_oembed_get_object() * @uses WP_Embed::maybe_make_link() * * @param array $attr Shortcode attributes. * @param string $url The URL attempting to be embeded. * @return string The embed HTML on success, otherwise the original URL. */ function shortcode($attr, $url = '') { if (empty($url)) { return ''; } $rawattr = $attr; $attr = wp_parse_args($attr, wp_embed_defaults()); // kses converts & into & and we need to undo this // See http://core.trac.wordpress.org/ticket/11311 $url = str_replace('&', '&', $url); // Look for known internal handlers ksort($this->handlers); foreach ($this->handlers as $priority => $handlers) { foreach ($handlers as $hid => $handler) { if (preg_match($handler['regex'], $url, $matches) && is_callable($handler['callback'])) { if (false !== ($return = call_user_func($handler['callback'], $matches, $attr, $url, $rawattr))) { return apply_filters('embed_handler_html', $return, $url, $attr); } } } } // Get object ID $id = apply_filters('embed_post_id', 0); // Is oEmbed discovery on? $attr['discover'] = apply_filters('bp_embed_oembed_discover', false) && current_user_can('unfiltered_html'); // Set up a new WP oEmbed object to check URL with registered oEmbed providers require_once ABSPATH . WPINC . '/class-oembed.php'; $oembed_obj = _wp_oembed_get_object(); // If oEmbed discovery is true, skip oEmbed provider check $is_oembed_link = false; if (!$attr['discover']) { foreach ((array) $oembed_obj->providers as $provider_matchmask => $provider) { $regex = ($is_regex = $provider[1]) ? $provider_matchmask : '#' . str_replace('___wildcard___', '(.+)', preg_quote(str_replace('*', '___wildcard___', $provider_matchmask), '#')) . '#i'; if (preg_match($regex, $url)) { $is_oembed_link = true; } } // If url doesn't match a WP oEmbed provider, stop parsing if (!$is_oembed_link) { return $this->maybe_make_link($url); } } return $this->parse_oembed($id, $url, $attr, $rawattr); }
/** * Filters the oEmbed result before any HTTP requests are made. * * If the URL belongs to the current site, the result is fetched directly instead of * going through the oEmbed discovery process. * * @since 4.5.3 * * @param null|string $result The UNSANITIZED (and potentially unsafe) HTML that should be used to embed. Default null. * @param string $url The URL that should be inspected for discovery `<link>` tags. * @param array $args oEmbed remote get arguments. * @return null|string The UNSANITIZED (and potentially unsafe) HTML that should be used to embed. * Null if the URL does not belong to the current site. */ function wp_filter_pre_oembed_result($result, $url, $args) { $post_id = url_to_postid($url); /** This filter is documented in wp-includes/class-wp-oembed-controller.php */ $post_id = apply_filters('oembed_request_post_id', $post_id, $url); if (!$post_id) { return $result; } $width = isset($args['width']) ? $args['width'] : 0; $data = get_oembed_response_data($post_id, $width); $data = _wp_oembed_get_object()->data2html((object) $data, $url); if (!$data) { return $result; } return $data; }
/** * Extract any URL, matching a registered oEmbed endpoint, from text. * * @since 2.3.0 * * @param string $richtext Content to parse. * @param string $plaintext Sanitized version of the content. * @param array $extra_args Bespoke data for a particular extractor (optional). * * @return array { * @type array $has Extracted media counts. { * @type int $embeds * } * @type array $embeds Extracted oEmbeds. { * Array of extracted media. * * @type string $url oEmbed link. * } * } */ protected function extract_embeds($richtext, $plaintext, $extra_args = array()) { $data = array('has' => array('embeds' => 0), 'embeds' => array()); $embeds = array(); if (!function_exists('_wp_oembed_get_object')) { require ABSPATH . WPINC . '/class-oembed.php'; } // Matches any links on their own lines. They may be oEmbeds. if (stripos($richtext, 'http') !== false) { preg_match_all('#^\\s*(https?://[^\\s"]+)\\s*$#im', $richtext, $matches); if (!empty($matches[1])) { $matches[1] = array_unique($matches[1]); $oembed = _wp_oembed_get_object(); foreach ($matches[1] as $link) { // Skip data URIs. if (strtolower(substr($link, 0, 5)) === 'data:') { continue; } foreach ($oembed->providers as $matchmask => $oembed_data) { list(, $is_regex) = $oembed_data; // Turn asterisk-type provider URLs into regexs. if (!$is_regex) { $matchmask = '#' . str_replace('___wildcard___', '(.+)', preg_quote(str_replace('*', '___wildcard___', $matchmask), '#')) . '#i'; $matchmask = preg_replace('|^#http\\\\://|', '#https?\\://', $matchmask); } // Check whether this "link" is really an oEmbed. if (preg_match($matchmask, $link)) { $data['embeds'][] = array('url' => $link); break; } } } } } $data['has']['embeds'] = count($data['embeds']); /** * Filters embeds extracted from text. * * @since 2.3.0 * * @param array $data Extracted embeds. See {@link BP_Media_Extractor::extract_embeds()} for format. * @param string $richtext Content to parse. * @param string $plaintext Copy of $richtext without any markup. * @param array $extra_args Bespoke data for a particular extractor. */ return apply_filters('bp_media_extractor_embeds', $data, $richtext, $plaintext, $extra_args); }
/** * Limit embed source URLs to specific providers. * * Not all core oEmbed providers are supported. Supported providers include YouTube, Vimeo, * Vine, Daily Motion, SoundCloud, and Twitter. * * @ignore * @since 4.2.0 * * @param string $src Embed source URL. * @return string If not from a supported provider, an empty string. Otherwise, a reformattd embed URL. */ private function _limit_embed($src) { $src = $this->_limit_url($src); if (empty($src)) { return ''; } if (preg_match('/\\/\\/(m|www)\\.youtube\\.com\\/(embed|v)\\/([^\\?]+)\\?.+$/', $src, $src_matches)) { // Embedded Youtube videos (www or mobile) $src = 'https://www.youtube.com/watch?v=' . $src_matches[3]; } else { if (preg_match('/\\/\\/player\\.vimeo\\.com\\/video\\/([\\d]+)([\\?\\/]{1}.*)?$/', $src, $src_matches)) { // Embedded Vimeo iframe videos $src = 'https://vimeo.com/' . (int) $src_matches[1]; } else { if (preg_match('/\\/\\/vimeo\\.com\\/moogaloop\\.swf\\?clip_id=([\\d]+)$/', $src, $src_matches)) { // Embedded Vimeo Flash videos $src = 'https://vimeo.com/' . (int) $src_matches[1]; } else { if (preg_match('/\\/\\/vine\\.co\\/v\\/([^\\/]+)\\/embed/', $src, $src_matches)) { // Embedded Vine videos $src = 'https://vine.co/v/' . $src_matches[1]; } else { if (preg_match('/\\/\\/(www\\.)?dailymotion\\.com\\/embed\\/video\\/([^\\/\\?]+)([\\/\\?]{1}.+)?/', $src, $src_matches)) { // Embedded Daily Motion videos $src = 'https://www.dailymotion.com/video/' . $src_matches[2]; } else { require_once ABSPATH . WPINC . '/class-oembed.php'; $oembed = _wp_oembed_get_object(); if (!$oembed->get_provider($src, array('discover' => false))) { $src = ''; } } } } } } return $src; }
/** * Removes an oEmbed provider. * * @since 3.5.0 * * @see WP_oEmbed * * @param string $format The URL format for the oEmbed provider to remove. * @return bool Was the provider removed successfully? */ function wp_oembed_remove_provider($format) { require_once ABSPATH . WPINC . '/class-oembed.php'; if (did_action('plugins_loaded')) { $oembed = _wp_oembed_get_object(); if (isset($oembed->providers[$format])) { unset($oembed->providers[$format]); return true; } } else { WP_oEmbed::_remove_provider_early($format); } return false; }
public static function doftpostimgfor($post) { $search_content = isset($post->post_content) ? $post->post_content : ''; $search_content = substr(wp_strip_all_tags($search_content), 0, 4000); $search_content = apply_filters('youtube_embedplus_video_content', $search_content); $vid_match = null; if ($search_content && $post->ID && !has_post_thumbnail($post->ID) && preg_match(self::$justurlregex, $search_content, $vid_match)) { $first_vid_link = trim(str_replace(self::$badentities, self::$goodliterals, $vid_match[0])); $first_vid_link = preg_replace('/\\s/', '', $first_vid_link); $linkparamstemp = explode('?', $first_vid_link); $linkparams = array(); if (count($linkparamstemp) > 1) { $linkparams = self::keyvalue($linkparamstemp[1], true); } if (strpos($linkparamstemp[0], 'youtu.be') !== false && !isset($linkparams['v'])) { $vtemp = explode('/', $linkparamstemp[0]); $linkparams['v'] = array_pop($vtemp); } $just_id = $linkparams['v']; $ftimgurl = "https://img.youtube.com/vi/" . $just_id . "/maxresdefault.jpg"; $ftimgid = self::media_sideload($ftimgurl, $post->ID, sanitize_title(preg_replace("/[^a-zA-Z0-9\\s]/", "-", $post->title))); if (!ftimgid || is_wp_error($ftimgid)) { $ftimgurl = null; $ftimgid = 0; if ($just_id) { require_once ABSPATH . WPINC . '/class-oembed.php'; $oembed = _wp_oembed_get_object(); $args = array(); $args['width'] = 1920; $args['height'] = 1080; $args['discover'] = false; $odata = $oembed->fetch('https://www.youtube.com/oembed', 'http://youtube.com/watch?v=' . $just_id, $args); if ($odata) { $ftimgurl = $odata->thumbnail_url; } } $ftimgid = $ftimgurl && !is_wp_error($ftimgurl) ? self::media_sideload($ftimgurl, $post->ID, sanitize_title(preg_replace("/[^a-zA-Z0-9\\s]/", "-", $post->title))) : 0; if (!$ftimgid || is_wp_error($ftimgid)) { return; } } set_post_thumbnail($post->ID, $ftimgid); } }
/** * Does the work of adding the Embedly providers to wp_oembed */ function add_embedly_providers($the_content) { $services = get_embedly_selected_services(); $embedly_key = get_option('embedly_key'); require_once ABSPATH . WPINC . '/class-oembed.php'; $oembed = _wp_oembed_get_object(); $oembed->providers = array(); if ($services && get_option('embedly_active')) { foreach ($services as $service) { foreach (json_decode($service->regex) as $sre) { if ($embedly_key) { wp_oembed_add_provider($sre, 'http://api.embed.ly/1/oembed?key=' . $embedly_key, true); } else { wp_oembed_add_provider($sre, 'http://api.embed.ly/1/oembed', true); } } } } }
function oembed_discover_url($url) { $data = array(); if (!empty($url)) { $parse_url = parse_url(str_replace(':////', '://', esc_url_raw($url))); if (empty($parse_url['scheme'])) { $parse_url['scheme'] = 'http'; } $url = $this->unparse_url($parse_url); include_once ABSPATH . 'wp-includes/class-oembed.php'; $wp_oembed = _wp_oembed_get_object(); $provider = false; foreach ($wp_oembed->providers as $matchmask => $d) { list($providerurl, $regex) = $d; if (!$regex) { $matchmask = '#' . str_replace('___wildcard___', '(.+)', preg_quote(str_replace('*', '___wildcard___', $matchmask), '#')) . '#i'; $matchmask = preg_replace('|^#http\\\\://|', '#https?\\://', $matchmask); } if (preg_match($matchmask, $url)) { $provider = str_replace('{format}', 'json', $providerurl); // JSON is easier to deal with than XML break; } } if (empty($provider)) { $provider = $wp_oembed->discover($url); } if (!empty($provider)) { $data = $wp_oembed->fetch($provider, $url, array('discover' => true)); } } return $data; }
/** * Attempts to fetch an oembed object with metadata for a provided URL using oEmbed. */ static function get_oembed_object($url) { require_once ABSPATH . WPINC . '/class-oembed.php'; $oembed = _wp_oembed_get_object(); $oembed_provider_url = $oembed->discover($url); $oembed_object = $oembed->fetch($oembed_provider_url, $url); return empty($oembed_object) ? false : $oembed_object; }
/** * check host and get data for a given url * @return encode_json(associative array of data) on success * @return encode_json(array[false, "error message"]) on failure * * EMBED TYPES * * EMBED_OEMBED_YOUTUBE_VIDEO * EMBED_OEMBED_VIMEO_VIDEO * EMBED_OEMBED_DAILYMOTION_VIDEO * EMBED_OEMBED_INSTAGRAM_IMAGE * EMBED_OEMBED_INSTAGRAM_VIDEO * EMBED_OEMBED_INSTAGRAM_POST * EMBED_OEMBED_FLICKR_IMAGE * * RULES FOR NEW TYPES * * 1. begin type name with EMBED_ * 2. if using WP native OEMBED class, add _OEMBED then * 3. add provider name * 4. add _VIDEO, _IMAGE FOR embedded media containing only video or image * 5. add _DIRECT_URL from static URL of image (not implemented yet) * */ public static function add_embed($url) { $url = sanitize_text_field(urldecode($url)); $embed_type = ''; $host = ''; /*returns this array*/ $embedData = array('name' => '', 'description' => '', 'filename' => '', 'url' => '', 'reliative_url' => '', 'thumb_url' => '', 'thumb' => '', 'size' => '', 'filetype' => '', 'date_modified' => '', 'resolution' => '', 'redirect_url' => ''); $accepted_oembeds = array('YOUTUBE' => '/youtube/', 'VIMEO' => '/vimeo/', 'FLICKR' => '/flickr/', 'INSTAGRAM' => '/instagram/', 'DAILYMOTION' => '/dailymotion/'); /*check if we can embed this using wordpress class WP_oEmbed */ if (!function_exists('_wp_oembed_get_object')) { include ABSPATH . WPINC . '/class-oembed.php'; } // get an oembed object $oembed = _wp_oembed_get_object(); $provider = $oembed->get_provider($url); foreach ($accepted_oembeds as $oembed_provider => $regex) { if (preg_match($regex, $provider) == 1) { $host = $oembed_provider; } } /*return json_encode($host); for test*/ /*handling oembed cases*/ if ($host) { /*instagram is exception*/ /*standard oembed fetching does not return thumbnail_url! so we do it manually*/ if ($host == 'INSTAGRAM' && substr($url, -4) != 'post' && substr($url, -4 != 'POST')) { $embed_type = 'EMBED_OEMBED_INSTAGRAM'; $insta_host_and_id = strtok($url, '/') . "/" . strtok('/') . "/" . strtok('/') . "/" . strtok('/'); $insta_host = strtok($url, '/') . "/" . strtok('/') . "/" . strtok('/') . "/"; $filename = str_replace($insta_host, "", $insta_host_and_id); $get_embed_data = wp_remote_get("http://api.instagram.com/oembed?url=http://instagram.com/p/" . $filename); if (is_wp_error($get_embed_data)) { return json_encode(array("error", "cannot get Instagram data")); } $result = json_decode(wp_remote_retrieve_body($get_embed_data)); if (empty($result)) { return json_encode(array("error", wp_remote_retrieve_body($get_embed_data))); } $embedData = array('name' => htmlspecialchars($result->title), 'description' => htmlspecialchars($result->title), 'filename' => $filename, 'url' => $url, 'reliative_url' => $url, 'thumb_url' => $result->thumbnail_url, 'thumb' => $result->thumbnail_url, 'size' => '', 'filetype' => $embed_type, 'date_modified' => date('d F Y, H:i'), 'resolution' => $result->thumbnail_width . " x " . $result->thumbnail_height . " px", 'redirect_url' => ''); /*get instagram post html page, parse its DOM to find video URL*/ $DOM = new DOMDocument(); libxml_use_internal_errors(true); $html_code = wp_remote_get($url); if (is_wp_error($html_code)) { return json_encode(array("error", "cannot get Instagram data")); } $html_body = wp_remote_retrieve_body($html_code); if (empty($html_body)) { return json_encode(array("error", wp_remote_retrieve_body($html_code))); } $DOM->loadHTML($html_body); $finder = new DomXPath($DOM); $query = "//meta[@property='og:video']"; $nodes = $finder->query($query); $node = $nodes->item(0); if ($node) { $length = $node->attributes->length; for ($i = 0; $i < $length; ++$i) { $name = $node->attributes->item($i)->name; $value = $node->attributes->item($i)->value; if ($name == 'content') { $filename = $value; } } $embedData['filename'] = $filename; $embedData['filetype'] .= '_VIDEO'; } else { $embedData['filetype'] .= '_IMAGE'; } return json_encode($embedData); } if ($host == 'INSTAGRAM' && (substr($url, -4) == 'post' || substr($url, -4) == 'POST')) { /*check if instagram post*/ $url = substr($url, 0, -4); $embed_type = 'EMBED_OEMBED_INSTAGRAM_POST'; parse_str(parse_url($url, PHP_URL_QUERY), $my_array_of_vars); $matches = array(); $filename = ''; $regex = "/^.*?instagram\\.com\\/p\\/(.*?)[\\/]?\$/"; if (preg_match($regex, $url, $matches)) { $filename = $matches[1]; } $get_embed_data = wp_remote_get("http://api.instagram.com/oembed?url=http://instagram.com/p/" . $filename); if (is_wp_error($get_embed_data)) { return json_encode(array("error", "cannot get Instagram data")); } $result = json_decode(wp_remote_retrieve_body($get_embed_data)); if (empty($result)) { return json_encode(array("error", wp_remote_retrieve_body($get_embed_data))); } $embedData = array('name' => htmlspecialchars($result->title), 'description' => htmlspecialchars($result->title), 'filename' => $filename, 'url' => $url, 'reliative_url' => $url, 'thumb_url' => $result->thumbnail_url, 'thumb' => $result->thumbnail_url, 'size' => '', 'filetype' => $embed_type, 'date_modified' => date('d F Y, H:i'), 'resolution' => $result->width . " x " . $result->width . " px", 'redirect_url' => ''); return json_encode($embedData); } $result = $oembed->fetch($provider, $url); /*no data fetched for a known provider*/ if (!$result) { return json_encode(array("error", "please enter " . $host . " correct single media URL")); } else { /*one of known oembed types*/ $embed_type = 'EMBED_OEMBED_' . $host; switch ($embed_type) { case 'EMBED_OEMBED_YOUTUBE': parse_str(parse_url($url, PHP_URL_QUERY), $my_array_of_vars); $filename = $my_array_of_vars['v']; $embedData = array('name' => htmlspecialchars($result->title), 'description' => htmlspecialchars($result->title), 'filename' => $filename, 'url' => $url, 'reliative_url' => $url, 'thumb_url' => $result->thumbnail_url, 'thumb' => $result->thumbnail_url, 'size' => '', 'filetype' => $embed_type . "_VIDEO", 'date_modified' => date('d F Y, H:i'), 'resolution' => $result->width . " x " . $result->height . " px", 'redirect_url' => ''); return json_encode($embedData); break; case 'EMBED_OEMBED_VIMEO': $embedData = array('name' => htmlspecialchars($result->title), 'description' => htmlspecialchars($result->title), 'filename' => $result->video_id, 'url' => $url, 'reliative_url' => $url, 'thumb_url' => $result->thumbnail_url, 'thumb' => $result->thumbnail_url, 'size' => '', 'filetype' => $embed_type . "_VIDEO", 'date_modified' => date('d F Y, H:i'), 'resolution' => $result->width . " x " . $result->height . " px", 'redirect_url' => ''); return json_encode($embedData); break; case 'EMBED_OEMBED_FLICKR': $matches = preg_match('~^.+/(\\d+)~', $url, $matches); $filename = $matches[1]; /*if($result->type =='photo') $embed_type .= '_IMAGE'; if($result->type =='video') $embed_type .= '_VIDEO';*/ /*flickr video type not implemented yet*/ $embed_type .= '_IMAGE'; $embedData = array('name' => htmlspecialchars($result->title), 'description' => htmlspecialchars($result->title), 'filename' => substr($result->thumbnail_url, 0, -5) . "b.jpg", 'url' => $url, 'reliative_url' => $url, 'thumb_url' => $result->thumbnail_url, 'thumb' => $result->thumbnail_url, 'size' => '', 'filetype' => $embed_type, 'date_modified' => date('d F Y, H:i'), 'resolution' => $result->width . " x " . $result->height . " px", 'redirect_url' => ''); return json_encode($embedData); break; case 'EMBED_OEMBED_DAILYMOTION': $filename = strtok(basename($url), '_'); $embedData = array('name' => htmlspecialchars($result->title), 'description' => htmlspecialchars($result->title), 'filename' => $filename, 'url' => $url, 'reliative_url' => $url, 'thumb_url' => $result->thumbnail_url, 'thumb' => $result->thumbnail_url, 'size' => '', 'filetype' => $embed_type . "_VIDEO", 'date_modified' => date('d F Y, H:i'), 'resolution' => $result->width . " x " . $result->height . " px", 'redirect_url' => ''); return json_encode($embedData); break; case 'EMBED_OEMBED_GETTYIMAGES': /*not working yet*/ $filename = strtok(basename($url), '_'); $embedData = array('name' => htmlspecialchars($result->title), 'description' => htmlspecialchars($result->title), 'filename' => $filename, 'url' => $url, 'reliative_url' => $url, 'thumb_url' => $result->thumbnail_url, 'thumb' => $result->thumbnail_url, 'size' => '', 'filetype' => $embed_type, 'date_modified' => date('d F Y, H:i'), 'resolution' => $result->width . " x " . $result->height . " px", 'redirect_url' => ''); return json_encode($embedData); default: return json_encode(array("error", "unknown URL host")); break; } } } else { /*check for direct image url*/ /*check if something else*/ /*not implemented yet*/ return json_encode(array("error", "unknown URL")); } return json_encode(array("error", "unknown URL")); }
/** * Removes an oEmbed provider. * * @since 3.5.0 * @see WP_oEmbed * * @uses _wp_oembed_get_object() * * @param string $format The URL format for the oEmbed provider to remove. */ function wp_oembed_remove_provider($format) { require_once ABSPATH . WPINC . '/class-oembed.php'; $oembed = _wp_oembed_get_object(); if (isset($oembed->providers[$format])) { unset($oembed->providers[$format]); return true; } return false; }
/** * Filters the given oEmbed HTML. * * If the `$url` isn't on the trusted providers list, * we need to filter the HTML heavily for security. * * Only filters 'rich' and 'html' response types. * * @since 4.4.0 * * @param string $result The oEmbed HTML result. * @param object $data A data object result from an oEmbed provider. * @param string $url The URL of the content to be embedded. * @return string The filtered and sanitized oEmbed result. */ function wp_filter_oembed_result($result, $data, $url) { if (false === $result || !in_array($data->type, array('rich', 'video'))) { return $result; } require_once ABSPATH . WPINC . '/class-oembed.php'; $wp_oembed = _wp_oembed_get_object(); // Don't modify the HTML for trusted providers. if (false !== $wp_oembed->get_provider($url, array('discover' => false))) { return $result; } $allowed_html = array('a' => array('href' => true), 'blockquote' => array(), 'iframe' => array('src' => true, 'width' => true, 'height' => true, 'frameborder' => true, 'marginwidth' => true, 'marginheight' => true, 'scrolling' => true, 'title' => true)); $html = wp_kses($result, $allowed_html); preg_match('|(<blockquote>.*?</blockquote>)?.*(<iframe.*?></iframe>)|ms', $html, $content); // We require at least the iframe to exist. if (empty($content[2])) { return false; } $html = $content[1] . $content[2]; if (!empty($content[1])) { // We have a blockquote to fall back on. Hide the iframe by default. $html = str_replace('<iframe', '<iframe style="display:none;"', $html); $html = str_replace('<blockquote', '<blockquote class="wp-embedded-content"', $html); } $html = str_replace('<iframe', '<iframe class="wp-embedded-content" sandbox="allow-scripts" security="restricted"', $html); preg_match('/ src=[\'"]([^\'"]*)[\'"]/', $html, $results); if (!empty($results)) { $secret = wp_generate_password(10, false); $url = esc_url("{$results[1]}#?secret={$secret}"); $html = str_replace($results[0], " src=\"{$url}\" data-secret=\"{$secret}\"", $html); $html = str_replace('<blockquote', "<blockquote data-secret=\"{$secret}\"", $html); } return $html; }
/** * Filters the returned oEmbed HTML. * * If the $url isn't on the trusted providers list, * we need to filter the HTML heavily for security. * * @param string $return The returned oEmbed HTML. * @param object $data A data object result from an oEmbed provider. * @param string $url The URL of the content to be embedded. * @return string The filtered and sanitized oEmbed result. */ function wp_filter_oembed_result($return, $data, $url) { if (false === $return || !in_array($data->type, array('rich', 'video'))) { return $return; } require_once ABSPATH . WPINC . '/class-oembed.php'; $wp_oembed = _wp_oembed_get_object(); // Don't modify the HTML for trusted providers. if (false !== $wp_oembed->get_provider($url, array('discover' => false))) { return $return; } $allowed_html = array('iframe' => array('src' => true, 'width' => true, 'height' => true, 'frameborder' => true, 'marginwidth' => true, 'marginheight' => true, 'scrolling' => true, 'title' => true, 'class' => true)); $html = wp_kses($return, $allowed_html); preg_match('|^.*(<iframe.*?></iframe>).*$|m', $html, $iframes); if (empty($iframes)) { return false; } $html = str_replace('<iframe', '<iframe sandbox="allow-scripts" security="restricted"', $iframes[1]); preg_match('/ src=[\'"]([^\'"]*)[\'"]/', $html, $results); if (!empty($results)) { $secret = wp_generate_password(10, false); $url = esc_url("{$results[1]}#?secret={$secret}"); $html = str_replace($results[0], " src=\"{$url}\" data-secret=\"{$secret}\"", $html); } if (!$html || false === strpos($html, '<iframe')) { return false; } return $html; }