public function convert($amp_attributes = array()) { if (!$this->has_tag(self::$tag)) { return $this->content; } $matches = $this->get_tags(self::$tag); if (empty($matches)) { return $this->content; } $this->did_convert_elements = true; $content = $this->content; foreach ($matches as $match) { $old_element = $match[0]; $old_attr = isset($match[2]) ? $match[2] : ''; $new_element = ''; $attributes = wp_kses_hair($old_attr, array('http', 'https')); $attributes = $this->filter_attributes($attributes); $attributes = array_merge($attributes, $amp_attributes); // TODO: limit child nodes too (only allowed source, div+fallback, and div+placeholder) $child_nodes = isset($match[4]) ? $match[4] : ''; $new_element .= sprintf('<amp-audio %s>%s</amp-audio>', $this->build_attributes_string($attributes), $child_nodes); $old_pattern = '~' . preg_quote($old_element, '~') . '~'; $content = preg_replace($old_pattern, $new_element, $content, 1); } return $content; }
public function convert($amp_attributes = array()) { if (!$this->has_tag(self::$tag)) { return $this->content; } $matches = $this->get_tags(self::$tag); if (empty($matches)) { return $this->content; } $content = $this->content; foreach ($matches as $match) { $old_img = $match[0]; $old_img_attr = isset($match[2]) ? $match[2] : ''; $new_img = ''; $attributes = wp_kses_hair($old_img_attr, array('http', 'https')); if (!empty($attributes['src'])) { $attributes = $this->filter_attributes($attributes); $attributes = array_merge($attributes, $amp_attributes); // Workaround for https://github.com/Automattic/amp-wp/issues/20 // responsive + float don't mix if (isset($attributes['class']) && (false !== strpos($attributes['class'], 'alignleft') || false !== strpos($attributes['class'], 'alignright'))) { unset($attributes['layout']); } $new_img .= sprintf('<amp-img %s></amp-img>', $this->build_attributes_string($attributes)); } $old_img_pattern = '~' . preg_quote($old_img, '~') . '~'; $content = preg_replace($old_img_pattern, $new_img, $content, 1); } return $content; }
/** * Blip.tv embed code: * <embed src="http://blip.tv/play/g8sVgpfaCgI%2Em4v" type="application/x-shockwave-flash" width="480" height="255" allowscriptaccess="always" allowfullscreen="true"></embed> * Blip.tv shortcode is: [blip.tv url-or-something-else] * */ function blip_embed_to_shortcode($content) { if (false === stripos($content, '/blip.tv/play/')) { return $content; } $regexp = '!<embed((?:\\s+\\w+="[^"]*")*)\\s+src="http(?:\\:|�*58;)//(blip\\.tv/play/[^"]*)"((?:\\s+\\w+="[^"]*")*)\\s*(?:/>|>\\s*</embed>)!'; $regexp_ent = str_replace('&#0*58;', '&#0*58;|�*58;', htmlspecialchars($regexp, ENT_NOQUOTES)); foreach (array('regexp', 'regexp_ent') as $reg) { if (!preg_match_all(${$reg}, $content, $matches, PREG_SET_ORDER)) { continue; } foreach ($matches as $match) { $src = 'http://' . html_entity_decode($match[2]); $params = $match[1] . $match[3]; if ('regexp_ent' == $reg) { $src = html_entity_decode($src); $params = html_entity_decode($params); } $params = wp_kses_hair($params, array('http')); if (!isset($params['type']) || 'application/x-shockwave-flash' != $params['type']['value']) { continue; } $content = str_replace($match[0], "[blip.tv {$src}]", $content); } } return $content; }
function vimeo_embed_to_shortcode($content) { if (false === stripos($content, 'player.vimeo.com/video/')) { return $content; } $regexp = '!<iframe\\s+src="http://player.vimeo.com/video/(\\d+)"((?:\\s+\\w+="[^"]*")*)></iframe>!i'; $regexp_ent = str_replace('&#0*58;', '&#0*58;|�*58;', htmlspecialchars($regexp, ENT_NOQUOTES)); foreach (array('regexp', 'regexp_ent') as $reg) { if (!preg_match_all(${$reg}, $content, $matches, PREG_SET_ORDER)) { continue; } foreach ($matches as $match) { $id = (int) $match[1]; $params = $match[2]; if ('regexp_ent' == $reg) { $params = html_entity_decode($params); } $params = wp_kses_hair($params, array('http')); $width = isset($params['width']) ? (int) $params['width']['value'] : 0; $height = isset($params['height']) ? (int) $params['height']['value'] : 0; $wh = ''; if ($width && $height) { $wh = ' w=' . $width . ' h=' . $height; } $shortcode = '[vimeo ' . $id . $wh . ']'; $content = str_replace($match[0], $shortcode, $content); } } return $content; }
public function convert($amp_attributes = array()) { if (!$this->has_tag(self::$tag)) { return $this->content; } $iframes = $this->get_tags(self::$tag); if (empty($iframes)) { return $this->content; } $content = $this->content; foreach ($iframes as $iframe) { $old_iframe = $iframe[0]; $old_iframe_attr = isset($iframe[1]) ? $iframe[1] : ''; $new_iframe = ''; $attributes = wp_kses_hair($old_iframe_attr, array('http', 'https')); if (!empty($attributes['src'])) { $attributes = $this->filter_attributes($attributes); $attributes = array_merge($attributes, $amp_attributes); $new_iframe .= sprintf('<amp-iframe %s></amp-iframe>', $this->build_attributes_string($attributes)); } $old_iframe_pattern = '~' . preg_quote($old_iframe, '~') . '~'; $content = preg_replace($old_iframe_pattern, $new_iframe, $content, 1); } return $content; }
/** * Original codes: * * <embed height="270" type="application/x-shockwave-flash" width="480" src="http://www.dailymotion.com/swf/video/xekmrq?additionalInfos=0" wmode="opaque" pluginspage="http://www.macromedia.com/go/getflashplayer" allowscriptaccess="never" allownetworking="internal" /> * * <object width="480" height="240"><param name="movie" value="http://www.dailymotion.com/swf/video/xen4ms_ghinzu-cold-love-mirror-mirror_music?additionalInfos=0"></param><param name="allowFullScreen" value="true"></param><param name="allowScriptAccess" value="always"></param> * <embed type="application/x-shockwave-flash" src="http://www.dailymotion.com/swf/video/xen4ms_ghinzu-cold-love-mirror-mirror_music?additionalInfos=0" width="480" height="240" allowfullscreen="true" allowscriptaccess="always"></embed> * </object><br /><b><a href="http://www.dailymotion.com/video/xen4ms_ghinzu-cold-love-mirror-mirror_music">Ghinzu - Cold Love (Mirror Mirror)</a></b><br /><i>Uploaded by <a href="http://www.dailymotion.com/GhinzuTV">GhinzuTV</a>. - <a href="http://www.dailymotion.com/us/channel/music">Watch more music videos, in HD!</a></i> * * Code as of 01.01.11: * <object width="560" height="421"><param name="movie" value="http://www.dailymotion.com/swf/video/xaose5?width=560&theme=denim&foreground=%2392ADE0&highlight=%23A2ACBF&background=%23202226&start=&animatedTitle=&iframe=0&additionalInfos=0&autoPlay=0&hideInfos=0"></param><param name="allowFullScreen" value="true"></param><param name="allowScriptAccess" value="always"></param><embed type="application/x-shockwave-flash" src="http://www.dailymotion.com/swf/video/xaose5?width=560&theme=denim&foreground=%2392ADE0&highlight=%23A2ACBF&background=%23202226&start=&animatedTitle=&iframe=0&additionalInfos=0&autoPlay=0&hideInfos=0" width="560" height="421" allowfullscreen="true" allowscriptaccess="always"></embed></object><br /><b><a href="http://www.dailymotion.com/video/xaose5_sexy-surprise_na">Sexy Surprise</a></b><br /><i>Uploaded by <a href="http://www.dailymotion.com/GilLavie">GilLavie</a>. - <a target="_self" href="http://www.dailymotion.com/channel/sexy/featured/1">Find more steamy, sexy videos.</a></i> * movie param enforces anti-xss protection */ function dailymotion_embed_to_shortcode($content) { if (false === stripos($content, 'www.dailymotion.com/swf/')) { return $content; } $regexp = '!<object.*>\\s*(<param.*></param>\\s*)*<embed((?:\\s+\\w+="[^"]*")*)\\s+src="http(?:\\:|�*58;)//(www\\.dailymotion\\.com/swf/[^"]*)"((?:\\s+\\w+="[^"]*")*)\\s*(?:/>|>\\s*</embed>)\\s*</object><br /><b><a .*>.*</a></b><br /><i>.*</i>!'; $regexp_ent = str_replace('&#0*58;', '&#0*58;|�*58;', htmlspecialchars($regexp, ENT_NOQUOTES)); foreach (array('regexp', 'regexp_ent') as $reg) { if (!preg_match_all(${$reg}, $content, $matches, PREG_SET_ORDER)) { continue; } foreach ($matches as $match) { $src = html_entity_decode($match[3]); $params = $match[2] . $match[4]; if ('regexp_ent' == $reg) { $src = html_entity_decode($src); $params = html_entity_decode($params); } $params = wp_kses_hair($params, array('http')); if (!isset($params['type']) || 'application/x-shockwave-flash' != $params['type']['value']) { continue; } $id = basename(substr($src, strlen('www.dailymotion.com/swf'))); $id = preg_replace('/[^a-z0-9].*$/i', '', $id); $content = str_replace($match[0], "[dailymotion id={$id}]", $content); } } return $content; }
function youtube_embed_to_short_code($content) { if (false === strpos($content, 'youtube.com')) { return $content; } //older codes $regexp = '!<object width="\\d+" height="\\d+"><param name="movie" value="https?://www\\.youtube\\.com/v/([^"]+)"></param>(?:<param name="\\w+" value="[^"]*"></param>)*<embed src="https?://www\\.youtube\\.com/v/(.+)" type="application/x-shockwave-flash"(?: \\w+="[^"]*")* width="\\d+" height="\\d+"></embed></object>!i'; $regexp_ent = htmlspecialchars($regexp, ENT_NOQUOTES); $old_regexp = '!<embed(?:\\s+\\w+="[^"]*")*\\s+src="https?(?:\\:|�*58;)//www\\.youtube\\.com/v/([^"]+)"(?:\\s+\\w+="[^"]*")*\\s*(?:/>|>\\s*</embed>)!'; $old_regexp_ent = str_replace('&#0*58;', '&#0*58;|�*58;', htmlspecialchars($old_regexp, ENT_NOQUOTES)); //new code $ifr_regexp = '!<iframe((?:\\s+\\w+="[^"]*")*?)\\s+src="(https?:)?//(?:www\\.)*youtube.com/embed/([^"]+)".*?</iframe>!i'; $ifr_regexp_ent = str_replace('&#0*58;', '&#0*58;|�*58;', htmlspecialchars($ifr_regexp, ENT_NOQUOTES)); foreach (array('regexp', 'regexp_ent', 'old_regexp', 'old_regexp_ent', 'ifr_regexp', 'ifr_regexp_ent') as $reg) { if (!preg_match_all(${$reg}, $content, $matches, PREG_SET_ORDER)) { continue; } foreach ($matches as $match) { // Hack, but '?' should only ever appear once, and // it should be for the 1st field-value pair in query string, // if it is present // YouTube changed their embed code. // Example of how it is now: // <object width="640" height="385"><param name="movie" value="http://www.youtube.com/v/aP9AaD4tgBY?fs=1&hl=en_US"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/aP9AaD4tgBY?fs=1&hl=en_US" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="640" height="385"></embed></object> // As shown at the start of function, previous YouTube didn't '?' // the 1st field-value pair. if (in_array($reg, array('ifr_regexp', 'ifr_regexp_ent'))) { $params = $match[1]; if ('ifr_regexp_ent' == $reg) { $params = html_entity_decode($params); } $params = wp_kses_hair($params, array('http')); $width = isset($params['width']) ? (int) $params['width']['value'] : 0; $height = isset($params['height']) ? (int) $params['height']['value'] : 0; $wh = ''; if ($width && $height) { $wh = "&w={$width}&h={$height}"; } $url = esc_url_raw("https://www.youtube.com/watch?v={$match[3]}{$wh}"); } else { $match[1] = str_replace('?', '&', $match[1]); $url = esc_url_raw("https://www.youtube.com/watch?v=" . html_entity_decode($match[1])); } $content = str_replace($match[0], "[youtube {$url}]", $content); /** * Fires before the YouTube embed is transformed into a shortcode. * * @module shortcodes * * @since 1.2.0 * * @param string youtube Shortcode name. * @param string $url YouTube video URL. */ do_action('jetpack_embed_to_shortcode', 'youtube', $url); } } return $content; }
function wp_kses_attr($element, $attr, $allowed_html, $allowed_protocols) { # Is there a closing XHTML slash at the end of the attributes? $xhtml_slash = ''; if (preg_match('%\\s/\\s*$%', $attr)) { $xhtml_slash = ' /'; } # Are any attributes allowed at all for this element? if (@count($allowed_html[strtolower($element)]) == 0) { return "<{$element}{$xhtml_slash}>"; } # Split it $attrarr = wp_kses_hair($attr, $allowed_protocols); # Go through $attrarr, and save the allowed attributes for this element # in $attr2 $attr2 = ''; foreach ($attrarr as $arreach) { if (!@isset($allowed_html[strtolower($element)][strtolower($arreach['name'])])) { continue; } # the attribute is not allowed $current = $allowed_html[strtolower($element)][strtolower($arreach['name'])]; if ($current == '') { continue; } # the attribute is not allowed if (!is_array($current)) { $attr2 .= ' ' . $arreach['whole']; } else { # there are some checks $ok = true; foreach ($current as $currkey => $currval) { if (!wp_kses_check_attr_val($arreach['value'], $arreach['vless'], $currkey, $currval)) { $ok = false; break; } } if ($ok) { $attr2 .= ' ' . $arreach['whole']; } # it passed them } # if !is_array($current) } # foreach # Remove any "<" or ">" characters $attr2 = preg_replace('/[<>]/', '', $attr2); return "<{$element}{$attr2}{$xhtml_slash}>"; }
function flickr_embed_to_shortcode($content) { if (false === stripos($content, '/www.flickr.com/apps/video/stewart.swf')) { return $content; } $regexp = '%(<object.*?(?:<(?!/?(?:object|embed)\\s+).*?)*?)?<embed((?:\\s+\\w+="[^"]*")*)\\s+src="http(?:\\:|�*58;)//www.flickr.com/apps/video/stewart.swf[^"]*"((?:\\s+\\w+="[^"]*")*)\\s*(?:/>|>\\s*</embed>)(?(1)\\s*</object>)%'; $regexp_ent = str_replace(array('&#0*58;', '[^>]*', '[^<]*'), array('&#0*58;|�*58;', '[^&]*(?:&(?!gt;)[^&]*)*', '[^&]*(?:&(?!lt;)[^&]*)*'), htmlspecialchars($regexp, ENT_NOQUOTES)); foreach (array('regexp', 'regexp_ent') as $reg) { if (!preg_match_all(${$reg}, $content, $matches, PREG_SET_ORDER)) { continue; } foreach ($matches as $match) { $params = $match[2] . $match[3]; if ('regexp_ent' == $reg) { $params = html_entity_decode($params); } $params = wp_kses_hair($params, array('http')); if (!isset($params['type']) || 'application/x-shockwave-flash' != $params['type']['value'] || !isset($params['flashvars'])) { continue; } wp_parse_str(html_entity_decode($params['flashvars']['value']), $flashvars); if (!isset($flashvars['photo_id'])) { continue; } $code_atts = array('video' => $flashvars['photo_id']); if (isset($flashvars['flickr_show_info_box']) && 'true' == $flashvars['flickr_show_info_box']) { $code_atts['show_info'] = 'true'; } if (!empty($flashvars['photo_secret'])) { $code_atts['secret'] = $flashvars['photo_secret']; } if (!empty($params['width']['value'])) { $code_atts['w'] = (int) $params['width']['value']; } if (!empty($params['height']['value'])) { $code_atts['h'] = (int) $params['height']['value']; } $code = '[flickr'; foreach ($code_atts as $k => $v) { $code .= " {$k}={$v}"; } $code .= ']'; $content = str_replace($match[0], $code, $content); /** This action is documented in modules/shortcodes/youtube.php */ do_action('jetpack_embed_to_shortcode', 'flickr_video', $flashvars['photo_id']); } } return $content; }
/** * slideshow and slideguest shortcodes for slide.com * [slideshow id=2233785415202545677&w=426&h=320] */ function jetpack_slide_embed_to_short_code($content) { global $content_width; if (false === strpos($content, 'slide.com/widgets')) { return $content; } $regexp = '!<div><embed((?:\\s+\\w+="[^"]*")*)\\s+src="http://widget[^"]+slide\\.com/widgets/slideticker\\.swf"((?:\\s+\\w+="[^"]*")*)\\s*(?:/?>|>\\s*</embed>)\\s*<div(?:\\s+[^>]+).*?slide\\.com/p1/.*?slide\\.com/p2.*?</div>\\s*</div>!i'; $regexp_ent = htmlspecialchars($regexp, ENT_NOQUOTES); foreach (array('regexp', 'regexp_ent') as $reg) { if (!preg_match_all(${$reg}, $content, $matches, PREG_SET_ORDER)) { continue; } foreach ($matches as $match) { $params = $match[1] . $match[2]; if ('regexp_ent' == $reg) { $params = html_entity_decode($params); } $params = wp_kses_hair($params, array('http')); if (!isset($params['type']) || 'application/x-shockwave-flash' != $params['type']['value'] || !isset($params['flashvars'])) { continue; } wp_parse_str(html_entity_decode($params['flashvars']['value']), $flashvars); if (empty($flashvars['channel'])) { continue; } $id = $flashvars['channel']; $width = 400; if (!empty($params['width']['value'])) { $width = (int) $params['width']['value']; } elseif (!empty($params['style']['value']) && preg_match('/width\\s*:\\s*(\\d+)/i', $params['style']['value'], $width_match)) { $width = (int) $width_match[1]; } $height = 300; if (!empty($params['height']['value'])) { $height = (int) $params['height']['value']; } elseif (!empty($params['style']['value']) && preg_match('/height\\s*:\\s*(\\d+)/i', $params['style']['value'], $height_match)) { $height = (int) $height_match[1]; } if ($content_width && $width > $content_width) { $height = intval($height * $content_width / $width); $width = $content_width; } $content = str_replace($match[0], "[slideshow id={$id}&w={$width}&h={$height}]", $content); do_action('jetpack_embed_to_shortcode', 'slideshow', $id); } } return $content; }
public static function add_image_placeholders($content) { // Don't load for feeds, previews, attachment pages, non-mobile views if (is_preview() || is_feed() || is_attachment() || function_exists('jetpack_is_mobile') && !jetpack_is_mobile()) { return $content; } // In case you want to change the placeholder image $placeholder_image = apply_filters('responsive_images_placeholder_image', self::get_url('images/1x1.trans.gif')); preg_match_all('#<img[^>]+?[\\/]?>#', $content, $images, PREG_SET_ORDER); if (empty($images)) { return $content; } foreach ($images as $image) { $attributes = wp_kses_hair($image[0], array('http', 'https')); $new_image = '<img'; $new_image_src = ''; foreach ($attributes as $attribute) { $name = $attribute['name']; $value = $attribute['value']; // Remove the width and height attributes if (in_array($name, array('width', 'height'))) { continue; } // Move the src to a data attribute and replace with a placeholder if ('src' == $name) { $new_image_src = html_entity_decode(urldecode($value)); parse_str(parse_url($new_image_src, PHP_URL_QUERY), $image_args); $new_image_src = remove_query_arg('h', $new_image_src); $new_image_src = remove_query_arg('w', $new_image_src); $new_image .= sprintf(' data-full-src="%s"', esc_url($new_image_src)); if (isset($image_args['w'])) { $new_image .= sprintf(' data-full-width="%s"', esc_attr($image_args['w'])); } if (isset($image_args['h'])) { $new_image .= sprintf(' data-full-height="%s"', esc_attr($image_args['h'])); } // replace actual src with our placeholder $value = $placeholder_image; } $new_image .= sprintf(' %s="%s"', $name, esc_attr($value)); } $new_image .= '/>'; $new_image .= sprintf('<noscript><img src="%s" /></noscript>', $new_image_src); // compat for no-js and better crawling $content = str_replace($image[0], $new_image, $content); } return $content; }
/** * Search post content for a link * This is used for "link" post formats, so we can automatically link from the archive page to the link itself. */ function apostrophe_get_url() { $post_link = get_the_permalink(); if (preg_match('/<a (.+?)>/', get_the_content(), $match)) { $link = array(); foreach (wp_kses_hair($match[1], array('http')) as $attr) { $link[$attr['name']] = $attr['value']; } $post_link = $link['href']; } return $post_link; }
function sfc_publish_automatic($id, $post) { // check to make sure post is published if ($post->post_status !== 'publish') { return; } // check options to see if we need to send to FB at all $options = get_option('sfc_options'); if (!$options['autopublish_app'] && !$options['autopublish_profile']) { return; } // load facebook platform include_once 'facebook-platform/facebook.php'; $fb = new Facebook($options['api_key'], $options['app_secret']); // to do this autopublish, we might need to switch users if ($options['user'] && $options['session_key']) { $tempuser = $fb->user; $tempkey = $fb->api_client->session_key = $session_key; $fb->set_user($options['user'], $options['session_key']); } else { return; // safety net: if we don't have a user and session key, we can't publish properly. } // build the post to send to FB // apply the content filters, in case some plugin is doing weird image stuff $content = apply_filters('the_content', $post->post_content); // look for the images to add with image_src $images = array(); // get the post thumbnail, put it first in the image list if (current_theme_supports('post-thumbnails')) { if (has_post_thumbnail($post->ID)) { $thumbid = get_post_thumbnail_id($post->ID); $att = wp_get_attachment_image_src($thumbid, 'full'); $images[] = $att[0]; } } // look for any images in the content if (preg_match_all('/<img (.+?)>/', $content, $matches)) { foreach ($matches[1] as $match) { foreach (wp_kses_hair($match, array('http')) as $attr) { $img[$attr['name']] = $attr['value']; } if (isset($img['src'])) { if (isset($img['class']) && false === strpos($img['class'], 'wp-smiley')) { // ignore smilies $images[] = $img['src']; } } } } // build the attachment $permalink = get_permalink($post->ID); $attachment['name'] = $post->post_title; $attachment['href'] = $permalink; $attachment['description'] = sfc_publish_make_excerpt($post->post_content); $attachment['comments_xid'] = urlencode($permalink); // image attachments (up to 5, as that's all FB allows) $count = 0; foreach ($images as $image) { $attachment['media'][$count]['type'] = 'image'; $attachment['media'][$count]['src'] = $image; $attachment['media'][$count]['href'] = $permalink; $count++; if ($count == 5) { break; } } // Read Post link $action_links[0]['text'] = 'Read Post'; $action_links[0]['href'] = $permalink; // Link to comments $action_links[1]['text'] = 'See Comments'; $action_links[1]['href'] = get_comments_link($post->ID); // publish to page if ($options['autopublish_app'] && !get_post_meta($id, '_fb_post_id_app', true) && $options['fanpage']) { if ($options['fanpage']) { $who = $options['fanpage']; } else { $who = $options['appid']; } // check to see if we can send to FB at all $result = $fb->api_client->users_hasAppPermission('publish_stream', $who); if (!$result) { break; } $fb_post_id = $fb->api_client->stream_publish(null, json_encode($attachment), json_encode($action_links), null, $who); if ($fb_post_id) { // update the post id so as to prevent automatically posting it twice update_post_meta($id, '_fb_post_id_app', $fb_post_id); } } // publish to profile if ($options['autopublish_profile'] && !get_post_meta($id, '_fb_post_id_profile', true)) { // check to see if we can send to FB at all $result = $fb->api_client->users_hasAppPermission('publish_stream'); if (!$result) { break; } $fb_post_prof_id = $fb->api_client->stream_publish(null, json_encode($attachment), json_encode($action_links)); if ($fb_post_prof_id) { // update the post id so as to prevent automatically posting it twice update_post_meta($id, '_fb_post_id_profile', $fb_post_prof_id); } } // switch users back, just in case if ($tempuser) { $fb->set_user($tempuser, $tempkey); } }
/** * Fetch a subset of posts from a tumblr blog * * @param $start index to start at * @param $count how many posts to get (max 50) * @param $state can be empty for normal posts, or "draft", "queue", or "submission" to get those posts * @returns false on error, array of posts on success */ function fetch_posts($url, $start=0, $count = 50, $email = null, $password = null, $state = null) { $url = trailingslashit($url).'api/read'; $params = array( 'start'=>$start, 'num'=>$count, ); if ( !empty($email) && !empty($password) ) { $params['email'] = $email; $params['password'] = $password; } if ( !empty($state) ) $params['state'] = $state; $options = array( 'body' => $params ); // fetch the posts $out = wp_remote_post($url,$options); if (wp_remote_retrieve_response_code($out) != 200) return false; $body = wp_remote_retrieve_body($out); // parse the XML into something useful $xml = simplexml_load_string($body); if (!isset($xml->posts->post)) return false; $tposts = $xml->posts; $posts = array(); foreach($tposts->post as $tpost) { $post = array(); $post['tumblr_id'] = (string) $tpost['id']; $post['tumblr_url'] = (string) $tpost['url-with-slug']; $post['post_date'] = date( 'Y-m-d H:i:s', strtotime ( (string) $tpost['date'] ) ); $post['post_date_gmt'] = date( 'Y-m-d H:i:s', strtotime ( (string) $tpost['date-gmt'] ) ); $post['post_name'] = (string) $tpost['slug']; if ( isset($tpost['private']) ) $post['private'] = (string) $tpost['private']; // set the various post info for each special format tumblr offers // TODO reorg this as needed switch ((string) $tpost['type']) { case 'photo': $post['format'] = 'image'; $post['media']['src'] = (string) $tpost->{'photo-url'}[0]; $post['media']['link'] =(string) $tpost->{'photo-link-url'}; $post['media']['width'] = (string) $tpost['width']; $post['media']['height'] = (string) $tpost['height']; $content = ''; if ( !empty( $post['media']['link'] ) ) $content .= "<a href='{$post['media']['link']}'>"; $content .= "<img src='{$post['media']['src']}' width='{$post['media']['width']}' height='{$post['media']['height']}' />"; if ( !empty( $link ) ) $content .= "</a>"; $post['post_content'] = $content; $post['post_content'] .= "\n\n" . (string) $tpost->{'photo-caption'}; $post['post_title'] = ''; if ( !empty( $tpost->{'photoset'} ) ) { foreach ( $tpost->{'photoset'}->{'photo'} as $photo ) { $post['gallery'][] = array ( 'src'=>$photo->{'photo-url'}[0], 'width'=>$photo['width'], 'height'=>$photo['height'], 'caption'=>$photo['caption'], ); } } break; case 'quote': $post['format'] = 'quote'; $post['post_content'] = (string) $tpost->{'quote-text'}; $post['post_title'] = (string) $tpost->{'quote-source'}; break; case 'link': $post['format'] = 'link'; $linkurl = (string) $tpost->{'link-url'}; $linktext = (string) $tpost->{'link-text'}; $post['post_content'] = "<a href='{$linkurl}'>{$linktext}</a>"; $post['post_title'] = (string) $tpost->{'link-description'}; break; case 'conversation': $post['format'] = 'chat'; $post['post_title'] = (string) $tpost->{'conversation-title'}; $post['post_content'] = (string) $tpost->{'conversation-text'}; break; case 'audio': $post['format'] = 'audio'; $post['media']['filename'] = basename( (string) $tpost->{'authorized-download-url'} ) . '.mp3'; $post['media']['audio'] = (string) $tpost->{'authorized-download-url'} .'?plead=please-dont-download-this-or-our-lawyers-wont-let-us-host-audio'; $post['post_content'] = (string) $tpost->{'authorized-download-url'}; $post['post_content'] .= "\n\n" . (string) $tpost->{'audio-caption'}; $post['post_title'] = ''; break; case 'video': $post['format'] = 'video'; if ( is_serialized( (string) $tpost->{'video-source'} ) ) { if ( preg_match('|\'(http://.*video_file.*)\'|U', $tpost->{'video-player'}[0], $matches) ) { $post['media']['video'] = $matches[1]; $val = unserialize( (string) $tpost->{'video-source'} ); $vidmeta = $val['o1']; $post['media']['filename'] = basename($post['media']['video']) . '.' . $vidmeta['extension']; $post['media']['width'] = $vidmeta['width']; $post['media']['height'] = $vidmeta['height']; } } else if ( false !== strpos( (string) $tpost->{'video-source'}, 'embed' ) ) { if ( preg_match_all('/<embed (.+?)>/', (string) $tpost->{'video-source'}, $matches) ) { foreach ($matches[1] as $match) { foreach ( wp_kses_hair($match, array('http')) as $attr) $embed[$attr['name']] = $attr['value']; } // special case for weird youtube vids $embed['src'] = preg_replace('|http://www.youtube.com/v/([a-zA-Z0-9_]+).*|i', 'http://www.youtube.com/watch?v=$1', $embed['src']); // TODO find other special cases, since tumblr is full of them $post['post_content'] = $embed['src']; } } else { $post['post_content'] = (string) $tpost->{'video-player'}[0]; $post['post_content'] .= (string) $tpost->{'video-source'}; } $post['post_content'] .= "\n\n" . (string) $tpost->{'video-caption'}; $post['post_title'] = ''; break; case 'answer': $post['post_title'] = (string) $tpost->{'question'}; $post['post_content'] = (string) $tpost->{'answer'}; break; case 'regular': default: $post['post_title'] = (string) $tpost->{'regular-title'}; $post['post_content'] = (string) $tpost->{'regular-body'}; break; } $posts[] = $post; } return $posts; }
/** * Removes all attributes, if none are allowed for this element. * * If some are allowed it calls wp_kses_hair() to split them further, and then * it builds up new HTML code from the data that kses_hair() returns. It also * removes "<" and ">" characters, if there are any left. One more thing it does * is to check if the tag has a closing XHTML slash, and if it does, it puts one * in the returned code as well. * * @since 1.0.0 * * @param string $element HTML element/tag * @param string $attr HTML attributes from HTML element to closing HTML element tag * @param array $allowed_html Allowed HTML elements * @param array $allowed_protocols Allowed protocols to keep * @return string Sanitized HTML element */ function wp_kses_attr($element, $attr, $allowed_html, $allowed_protocols) { // Is there a closing XHTML slash at the end of the attributes? if ( ! is_array( $allowed_html ) ) $allowed_html = wp_kses_allowed_html( $allowed_html ); $xhtml_slash = ''; if (preg_match('%\s*/\s*$%', $attr)) $xhtml_slash = ' /'; // Are any attributes allowed at all for this element? if ( ! isset($allowed_html[strtolower($element)]) || count($allowed_html[strtolower($element)]) == 0 ) return "<$element$xhtml_slash>"; // Split it $attrarr = wp_kses_hair($attr, $allowed_protocols); // Go through $attrarr, and save the allowed attributes for this element // in $attr2 $attr2 = ''; $allowed_attr = $allowed_html[strtolower($element)]; foreach ($attrarr as $arreach) { if ( ! isset( $allowed_attr[strtolower($arreach['name'])] ) ) continue; // the attribute is not allowed $current = $allowed_attr[strtolower($arreach['name'])]; if ( $current == '' ) continue; // the attribute is not allowed if ( strtolower( $arreach['name'] ) == 'style' ) { $orig_value = $arreach['value']; $value = safecss_filter_attr( $orig_value ); if ( empty( $value ) ) continue; $arreach['value'] = $value; $arreach['whole'] = str_replace( $orig_value, $value, $arreach['whole'] ); } if ( ! is_array($current) ) { $attr2 .= ' '.$arreach['whole']; // there are no checks } else { // there are some checks $ok = true; foreach ($current as $currkey => $currval) { if ( ! wp_kses_check_attr_val($arreach['value'], $arreach['vless'], $currkey, $currval) ) { $ok = false; break; } } if ( $ok ) $attr2 .= ' '.$arreach['whole']; // it passed them } // if !is_array($current) } // foreach // Remove any "<" or ">" characters $attr2 = preg_replace('/[<>]/', '', $attr2); return "<$element$attr2$xhtml_slash>"; }
/** * Fetch a subset of posts from a tumblr blog * * @param $start index to start at * @param $count how many posts to get (max 50) * @param $state can be empty for normal posts, or "draft", "queue", or "submission" to get those posts * @returns false on error, array of posts on success */ function fetch_posts($url, $start=0, $count = 50, $email = null, $password = null, $state = null ) { $url = parse_url( $url, PHP_URL_HOST ); $post_type = apply_filters( 'tumblr_post_type', '' ); $url = trailingslashit( "http://api.tumblr.com/v2/blog/$url/posts/$post_type" ); do_action( 'tumblr_importer_pre_fetch_posts' ); // These extra params hose up the auth if passed for oauth requests e.g. for drafts, so use them only for normal posts. if ( '' == $post_type ) { $params = array( 'offset' => $start, 'limit' => $count, 'api_key' => apply_filters( 'tumblr_importer_get_consumer_key', '' ), ); $url = add_query_arg( $params, $url ); } $response = $this->oauth_get_request($url); switch ( $response->meta->status ) { case 200: // OK break; default: $_error = sprintf( __( 'Tumblr replied with an error: %s', 'tumblr-importer' ), $response->meta->msg ); do_action( 'tumblr_importer_handle_error', 'response_' . $response->meta->status ); return new WP_Error('tumblr_error', $_error ); } $posts = array(); $tposts = $response->response->posts; foreach( $tposts as $tpost ) { $post = array(); $post['tumblr_id'] = (string) $tpost->id; $post['tumblr_url'] = (string) $tpost->post_url; $post['post_date'] = date( 'Y-m-d H:i:s', strtotime ( (string) $tpost->date ) ); $post['post_date_gmt'] = date( 'Y-m-d H:i:s', strtotime ( (string) $tpost->date ) ); $post['post_name'] = (string) $tpost->slug; if ( 'private' == $tpost->state ) $post['private'] = (string) $tpost->state; if ( isset( $tpost->tags ) ) { $post['tags_input'] = array(); foreach ( $tpost->tags as $tag ) $post['tags_input'][] = rtrim( (string) $tag, ','); // Strip trailing Commas off it too. } switch ( (string) $tpost->type ) { case 'photo': $post['format'] = 'image'; $post['media']['src'] = (string) $tpost->photos[0]->original_size->url; $post['media']['link'] = '';//TODO: Find out what to use here.(string) $tpost->{'photo-link-url'}; $post['media']['width'] = (string) $tpost->photos[0]->original_size->width; $post['media']['height'] = (string) $tpost->photos[0]->original_size->height; $post['post_content'] = (string) $tpost->caption; if ( ! empty( $tpost->photos ) ) { $post['format'] = 'gallery'; foreach ( $tpost->photos as $photo ) { $post['gallery'][] = array ( 'src' => $photo->original_size->url, 'width' => $photo->original_size->width, 'height' => $photo->original_size->height, 'caption' => $photo->caption, ); } } break; case 'quote': $post['format'] = 'quote'; $post['post_content'] = '<blockquote>' . (string) $tpost->text . '</blockquote>'; $post['post_content'] .= "\n\n<div class='attribution'>" . (string) $tpost->source . '</div>'; break; case 'link': $post['format'] = 'link'; $linkurl = (string) $tpost->url; $linktext = (string) $tpost->title; $post['post_content'] = "<a href='$linkurl'>$linktext</a>"; if ( ! empty( $tpost->description ) ) $post['post_content'] .= '<div class="link_description">' . (string) $tpost->description . '</div>'; $post['post_title'] = (string) $tpost->title; break; case 'chat': $post['format'] = 'chat'; $post['post_title'] = (string) $tpost->title; $post['post_content'] = (string) $tpost->body; break; case 'audio': $post['format'] = 'audio'; $post['media']['filename'] = basename( (string) $tpost->audio_url ); // If no .mp3 extension, add one so that sideloading works. if ( ! preg_match( '/\.mp3$/', $post['media']['filename'] ) ) $post['media']['filename'] .= '.mp3'; $post['media']['audio'] = (string) $tpost->audio_url .'?plead=please-dont-download-this-or-our-lawyers-wont-let-us-host-audio'; $post['post_content'] = (string) $tpost->player . "\n" . (string) $tpost->caption; break; case 'video': $post['format'] = 'video'; $post['post_content'] = ''; $video = array_shift( $tpost->player ); if ( false !== strpos( (string) $video->embed_code, 'embed' ) ) { if ( preg_match_all('/<embed (.+?)>/', (string) $video->embed_code, $matches) ) { foreach ($matches[1] as $match) { foreach ( wp_kses_hair( $match, array( 'http' ) ) as $attr ) $embed[ $attr['name'] ] = $attr['value']; } // special case for weird youtube vids $embed['src'] = preg_replace( '|http://www.youtube.com/v/([a-zA-Z0-9_]+).*|i', 'http://www.youtube.com/watch?v=$1', $embed['src'] ); // TODO find other special cases, since tumblr is full of them $post['post_content'] = $embed['src']; } // Sometimes, video-source contains iframe markup. if ( preg_match( '/<iframe/', $video->embed_code ) ) { $embed['src'] = preg_replace( '|<iframe.*src="http://www.youtube.com/embed/([a-zA-Z0-9_\-]+)\??.*".*</iframe>|', 'http://www.youtube.com/watch?v=$1', $video->embed_code ); $post['post_content'] = $embed['src']; } } elseif ( preg_match( '/<iframe.*vimeo/', $video->embed_code ) ) { $embed['src'] = preg_replace( '|<iframe.*src="(http://player.vimeo.com/video/([a-zA-Z0-9_\-]+))\??.*".*</iframe>.*|', 'http://vimeo.com/$2', $video->embed_code ); $post['post_content'] = $embed['src']; } else { // @todo: See if the video source is going to be oEmbed'able before adding the flash player $post['post_content'] .= $video->embed_code; } $post['post_content'] .= "\n" . (string) $tpost->caption; break; case 'answer': // TODO: Include asking_name and asking_url values? $post['post_title'] = (string) $tpost->question; $post['post_content'] = (string) $tpost->answer; break; case 'regular': case 'text': default: $post['post_title'] = (string) $tpost->title; $post['post_content'] = (string) $tpost->body; break; } $posts[] = $post; } return $posts; }
function wp_kses_attr($element, $attr, $allowed_html, $allowed_protocols) ############################################################################### # This function removes all attributes, if none are allowed for this element. # If some are allowed it calls wp_kses_hair() to split them further, and then it # builds up new HTML code from the data that kses_hair() returns. It also # removes "<" and ">" characters, if there are any left. One more thing it # does is to check if the tag has a closing XHTML slash, and if it does, # it puts one in the returned code as well. ############################################################################### { # Is there a closing XHTML slash at the end of the attributes? $xhtml_slash = ''; if (preg_match('%\s/\s*$%', $attr)) $xhtml_slash = ' /'; # Are any attributes allowed at all for this element? if (@ count($allowed_html[strtolower($element)]) == 0) return "<$element$xhtml_slash>"; # Split it $attrarr = wp_kses_hair($attr, $allowed_protocols); # Go through $attrarr, and save the allowed attributes for this element # in $attr2 $attr2 = ''; foreach ($attrarr as $arreach) { if (!@ isset ($allowed_html[strtolower($element)][strtolower($arreach['name'])])) continue; # the attribute is not allowed $current = $allowed_html[strtolower($element)][strtolower($arreach['name'])]; if ($current == '') continue; # the attribute is not allowed if (!is_array($current)) $attr2 .= ' '.$arreach['whole']; # there are no checks else { # there are some checks $ok = true; foreach ($current as $currkey => $currval) if (!wp_kses_check_attr_val($arreach['value'], $arreach['vless'], $currkey, $currval)) { $ok = false; break; } if ($ok) $attr2 .= ' '.$arreach['whole']; # it passed them } # if !is_array($current) } # foreach # Remove any "<" or ">" characters $attr2 = preg_replace('/[<>]/', '', $attr2); return "<$element$attr2$xhtml_slash>"; } # function wp_kses_attr
function sfc_media_find_video($post, $content = '') { if (empty($content)) { $content = apply_filters('the_content', $post->post_content); } $og = array(); // look for iframes if (preg_match('/<iframe\\s+(.+?)>/i', $content, $matches)) { // parse out the params foreach (wp_kses_hair($matches[1], array('http')) as $attr) { $embed[strtolower($attr['name'])] = $attr['value']; } if (!empty($embed['src'])) { $save = false; // first, check post meta, maybe we already did this URL once $hash = md5($embed['src']); $meta = get_post_meta($post->ID, '_sfc_embed_' . $hash, true); if (!empty($meta)) { // we have done this before, use the saved data instead of reprocessing $og = $meta; } else { // youtube iframes have srcs that start with http://www.youtube.com/embed/(id) if (preg_match('@http://[^/]*?youtube\\.com/embed/([^?&#]+)@i', $embed['src'], $matches)) { // this is what youtube's own opengraph data looks like $og['og:video'] = 'http://www.youtube.com/v/' . $matches[1] . '?version=3&autohide=1'; $og['og:video:height'] = 398; $og['og:video:width'] = 224; $og['og:video:type'] = "application/x-shockwave-flash"; $og['og:image'][] = "http://img.youtube.com/vi/{$matches[1]}/0.jpg"; } else { // vimeo iframes have srcs that start with http://player.vimeo.com/video/(id) if (preg_match('@http://[^/]*?vimeo\\.com/video/([^?&#]+)@i', $embed['src'], $matches)) { // this is what vimeo's own opengraph data looks like $og['og:video'] = 'http://vimeo.com/moogaloop.swf?clip_id=' . $matches[1]; $og['og:video:height'] = 640; $og['og:video:width'] = 360; $og['og:video:type'] = "application/x-shockwave-flash"; $resp = wp_remote_get("http://vimeo.com/api/v2/video/{$matches[1]}.json"); if (!is_wp_error($resp) && 200 == wp_remote_retrieve_response_code($resp)) { $data = json_decode(wp_remote_retrieve_body($resp), true); if (!empty($data[0]['thumbnail_large'])) { $thumb = $data[0]['thumbnail_large']; } } if (isset($thumb)) { $og['og:image'][] = $thumb; $save = true; } } else { // dailymotion iframe src's look like http://www.dailymotion.com/embed/video/(id) if (preg_match('@http://[^/]*?dailymotion\\.com/embed/video/([^?&#]+)@i', $embed['src'], $matches)) { // this is what dailymotion's own opengraph data looks like $og['og:video'] = 'http://www.dailymotion.com/swf/video/' . $matches[1] . '?autoPlay=1'; $og['og:video:height'] = 1280; $og['og:video:width'] = 720; $og['og:video:type'] = "application/x-shockwave-flash"; $resp = wp_remote_get("https://api.dailymotion.com/video/{$matches[1]}?fields=thumbnail_large_url", array('sslverify' => false)); if (!is_wp_error($resp) && 200 == wp_remote_retrieve_response_code($resp)) { $data = json_decode(wp_remote_retrieve_body($resp), true); if (!empty($data['thumbnail_large_url'])) { $thumb = $data['thumbnail_large_url']; } } if (isset($thumb)) { $og['og:image'][] = $thumb; $save = true; } } else { // blip.tv urls look like http://blip.tv/play/(id).html if (preg_match('@http://[^/]*?blip\\.tv/play/([^?&#]+).html@i', $embed['src'], $matches)) { // this is what blip.tv's own opengraph data looks like $og['og:video'] = 'http://blip.tv/play/' . $matches[1]; $og['og:video:type'] = "application/x-shockwave-flash"; $resp = wp_remote_get("http://blip.tv/players/episode/{$matches[1]}?skin=json"); if (!is_wp_error($resp) && 200 == wp_remote_retrieve_response_code($resp)) { $body = wp_remote_retrieve_body($resp); if (preg_match("/blip_ws_results\\((.*)\\)\\;/ms", $body, $matches)) { $data = json_decode($matches[1], true); if (!empty($data[0]["Post"]["thumbnailUrl"])) { $thumb = $data[0]["Post"]["thumbnailUrl"]; } } } if (isset($thumb)) { $og['og:image'][] = $thumb; $save = true; } } } } } } // TODO add new providers with weird stuff here as needed /* Quick documentation for hackers who want to screw around with this: For Facebook to properly use video information, all four video fields *and* the image must be populated. So if you're going to try to do some url magic, then you may need to make an API call somewhere to get the image for the video thumbnail (or other things, conceivably). If you do, then setting the $save=true like I did above will make the below line of code save your results in post meta and then they won't have to be re-retrieved from whatever API you're hitting. There's a call up at the top to handle retreiving those meta results and using them, thus bypassing all the parsing nonsense. But, ONLY set $save to true if you're making external API calls. If you can get the image info without making an external hit, then leave it false so as to not waste space in the DB with the meta information. Notice how I don't save the YouTube info because it's not necessary. In actual fact, that image isn't the exact same as the one they use on their data, and I could make an oEmbed API call to get their image, but it's pointless since that image URL I'm generating always works anyway. */ // save whatever we found so we don't have to do it again if ($save) { update_post_meta($post->ID, '_sfc_embed_' . $hash, $og); } } } else { // TODO: This is crap and it rarely works. Think harder. // look for an embed to add with video_src (simple, just add first embed) if (preg_match('/<embed\\s+(.+?)>/i', $content, $matches)) { foreach (wp_kses_hair($matches[1], array('http')) as $attr) { $embed[strtolower($attr['name'])] = $attr['value']; } $embed['src'] = preg_replace('/&.*$/', '', $embed['src']); if (preg_match('@http://[^/]*?youtube\\.com/@i', $embed['src'])) { $embed['src'] = preg_replace('/[?&#].*$/', '', $embed['src']); } // it's amazing how often this works if (!empty($embed['flashvars'])) { $embed['src'] .= '&' . $embed['flashvars']; } if (isset($embed['src'])) { $og['og:video'] = $embed['src']; } if (isset($embed['height'])) { $og['og:video:height'] = $embed['height']; } if (isset($embed['width'])) { $og['og:video:width'] = $embed['width']; } if (isset($embed['type'])) { $og['og:video:type'] = $embed['type']; } } } return $og; }
public function get_post_image($content) { $image = ''; if (function_exists('has_post_thumbnail') && has_post_thumbnail()) { $thumb_id = get_post_thumbnail_id(); $thumb = wp_get_attachment_image_src($thumb_id); $image = remove_query_arg(array('w', 'h'), $thumb[0]); } else { if (preg_match_all('/<img (.+?)>/', $content, $matches)) { foreach ($matches[1] as $attrs) { $media = $img = array(); foreach (wp_kses_hair($attrs, array('http', 'https')) as $attr) { $img[$attr['name']] = $attr['value']; } if (!isset($img['src']) || 0 !== strpos($img['src'], 'http')) { continue; } else { $image = htmlspecialchars_decode($img['src']); break; } } } } return $image; }
public function get_post_image($content) { $image = ''; if (class_exists('Jetpack_PostImages')) { global $post; $img = Jetpack_PostImages::from_html($post->ID); if (!empty($img['src'])) { return $img['src']; } } if (function_exists('has_post_thumbnail') && has_post_thumbnail()) { $thumb_id = get_post_thumbnail_id(); $thumb = wp_get_attachment_image_src($thumb_id, 'full'); // This shouldn't be necessary, since has_post_thumbnail() is true, // but... see http://wordpress.org/support/topic/jetpack-youtube-embeds if (!$thumb) { return ''; } $image = remove_query_arg(array('w', 'h'), $thumb[0]); } else { if (preg_match_all('/<img (.+?)>/', $content, $matches)) { foreach ($matches[1] as $attrs) { $media = $img = array(); foreach (wp_kses_hair($attrs, array('http', 'https')) as $attr) { $img[$attr['name']] = $attr['value']; } if (!isset($img['src']) || 0 !== strpos($img['src'], 'http')) { continue; } else { $image = htmlspecialchars_decode($img['src']); break; } } } } return $image; }
/** * Method for filtering the media's 'width' and 'height' attributes so that the theme can handle the * dimensions how it sees fit. * * @since 1.6.0 * @access public * @param string $html * @return string */ public function filter_dimensions($html) { $_html = strip_tags($html, '<object><embed><iframe><video>'); /* Find the attributes of the media. */ $atts = wp_kses_hair($_html, array('http', 'https')); /* Loop through the media attributes and add them in key/value pairs. */ foreach ($atts as $att) { $media_atts[$att['name']] = $att['value']; } /* If no dimensions are found, just return the HTML. */ if (empty($media_atts) || !isset($media_atts['width']) || !isset($media_atts['height'])) { return $html; } /* Set the max width. */ $max_width = $this->args['width']; /* Set the max height based on the max width and original width/height ratio. */ $max_height = round($max_width / ($media_atts['width'] / $media_atts['height'])); /* Fix for Spotify embeds. */ if (!empty($media_atts['src']) && preg_match('#https?://(embed)\\.spotify\\.com/.*#i', $media_atts['src'], $matches)) { list($max_width, $max_height) = $this->spotify_dimensions($media_atts); } /* Calculate new media dimensions. */ $dimensions = wp_expand_dimensions($media_atts['width'], $media_atts['height'], $max_width, $max_height); /* Allow devs to filter the final width and height of the media. */ list($width, $height) = apply_filters('hybrid_media_grabber_dimensions', $dimensions, $media_atts, $this); /* Set up the patterns for the 'width' and 'height' attributes. */ $patterns = array('/(width=[\'"]).+?([\'"])/i', '/(height=[\'"]).+?([\'"])/i', '/(<div.+?style=[\'"].*?width:.+?).+?(px;.+?[\'"].*?>)/i'); /* Set up the replacements for the 'width' and 'height' attributes. */ $replacements = array('${1}' . $width . '${2}', '${1}' . $height . '${2}', '${1}' . $width . '${2}'); /* Filter the dimensions and return the media HTML. */ return preg_replace($patterns, $replacements, $html); }
if ($post_author === '') { $post_author_byline = ''; } else { $post_author_byline = 'by ' . $post_author; } } $post_date = get_the_date('F j, Y'); $post_content = apply_filters('the_content', $post->post_content); if (is_footer_included($post_content)) { $post_footer = split_footer($post_content); $post_content = content_without_footer($post_content); } $post_link = get_the_permalink(); if (preg_match('/<a (.+?)>/', get_the_content(), $match)) { $link = array(); foreach (wp_kses_hair($match[1], array('http')) as $attr) { $link[$attr['name']] = $attr['value']; } $post_link = $link['href']; $related_postid = url_to_postid($post_link); $related_image_url = wp_get_attachment_image_src(get_post_thumbnail_id($related_postid), 'full'); $related_title = get_the_title($related_postid); $related_excerpt = get_the_excerpt_by_id($related_postid); $post_content = insert_related_article($post_content, $post_link, $related_image_url[0], $related_title, $related_excerpt); } if (is_brightcove_included($post_content)) { $post_content = replace_brightcove_ids($post_content, $bcpid, $bckey); } if (class_exists('RDMGalleryImport')) { if (is_gallery_included($post_content)) { $post_content = replace_gallery_ids($post_content);
function all_images_shopp() { // Gets all the images of a product of Shopp $the_images = array(); if (preg_match_all('/<img (.+?)>/', shopp('product', 'coverimage', 'width=320&height=200&fit=all&quality=100&return=1'), $matches)) { // Gets the images in the post content foreach ($matches[1] as $match) { foreach (wp_kses_hair($match, array('http')) as $attr) { $img[$attr['name']] = $attr['value']; } $the_images[] = "<meta property='og:image' content='" . $img['src'] . "' />\n"; } } else { $the_images[] = "<meta property='og:image' content='" . get_bloginfo('template_directory') . "/images/facebook-default.jpg' />\n"; // Default image if none } return $the_images; }
/** * Returns the image HTML or image array. * * @since 1.0.0 * @access public * @return void */ public function get_image() { /* Allow plugins/theme to override the final output. */ $image_html = apply_filters('get_the_image', $this->image); /* If $format is set to 'array', return an array of image attributes. */ if ('array' === $this->args['format']) { /* Set up a default empty array. */ $out = array(); /* Get the image attributes. */ $atts = wp_kses_hair($image_html, array('http', 'https')); /* Loop through the image attributes and add them in key/value pairs for the return array. */ foreach ($atts as $att) { $out[$att['name']] = $att['value']; } /* Return the array of attributes. */ return $out; } elseif (false === $this->args['echo']) { return !empty($image_html) ? $this->args['before'] . $image_html . $this->args['after'] : $image_html; } /* If there is a $post_thumbnail_id, do the actions associated with get_the_post_thumbnail(). */ if (isset($this->image_args['post_thumbnail_id'])) { do_action('begin_fetch_post_thumbnail_html', $this->args['post_id'], $this->image_args['post_thumbnail_id'], $this->args['size']); } /* Display the image if we get to this point. */ echo !empty($image_html) ? $this->args['before'] . $image_html . $this->args['after'] : $image_html; /* If there is a $post_thumbnail_id, do the actions associated with get_the_post_thumbnail(). */ if (isset($this->image_args['post_thumbnail_id'])) { do_action('end_fetch_post_thumbnail_html', $this->args['post_id'], $this->image_args['post_thumbnail_id'], $this->args['size']); } }
/** * This is a highly intuitive function that gets images. It first calls for custom field keys. If no * custom field key is set, check for the_post_thumbnail(). If no post image, check for images * attached to post. Check for image order if looking for attached images. Scan the post for * images if $image_scan = true. Check for default image if $default_image = true. If an image * is found, call sslider_display_the_image() to format it. * * @since 0.1 * @global $post The current post's DB object. * @param array $args Parameters for what image to get. * @return string|array The HTML for the image. | Image attributes in an array. */ function sslider_get_the_image($args = array()) { global $post; $post_id = $post->ID; $permalink = get_permalink($post_id); /* Set the default arguments. */ $defaults = array('custom_key' => array('Thumbnail', 'thumbnail'), 'post_id' => $post->ID, 'attachment' => true, 'the_post_thumbnail' => true, 'default_size' => false, 'size' => 'thumbnail', 'default_image' => false, 'order_of_image' => 1, 'link_to_post' => true, 'image_class' => false, 'image_scan' => false, 'width' => false, 'height' => false, 'format' => 'img', 'echo' => true, 'permalink' => $permalink); /* Allow plugins/themes to filter the arguments. */ $args = apply_filters('sslider_get_the_image_args', $args); /* Merge the input arguments and the defaults. */ $args = wp_parse_args($args, $defaults); /*print_r($args);*/ /* If $default_size is given, overwrite $size. */ if (!empty($args['default_size'])) { $args['size'] = $args['default_size']; } /* If $format is set to 'array', don't link to the post. */ if ('array' == $args['format']) { $args['link_to_post'] = false; } /* Extract the array to allow easy use of variables. */ extract($args); /* Check for a cached image. */ $cache = wp_cache_get('sslider_get_the_image'); if (!is_array($cache)) { $cache = array(); } /* If there is no cached image, let's see if one exists. */ if (!isset($cache[$post_id][$size])) { /* If a custom field key (array) is defined, check for images by custom field. */ if ($custom_key) { $image = sslider_image_by_custom_field($args); } /* If no image found and $the_post_thumbnail is set to true, check for a post image (WP feature). */ if (!$image && $the_post_thumbnail) { $image = sslider_image_by_the_post_thumbnail($args); } /* If no image found and $attachment is set to true, check for an image by attachment. */ if (!$image && $attachment) { $image = sslider_image_by_attachment($args); } /* If no image found and $image_scan is set to true, scan the post for images. */ if (!$image && $image_scan) { $image = sslider_image_by_scan($args); } /* If no image found and a $default_image is set, get the default image. */ if (!$image && $default_image) { $image = sslider_image_by_default($args); } /* If an image is returned, run it through the display function. */ if ($image) { $image = sslider_display_the_image($args, $image); } $cache[$post_id][$size] = $image; wp_cache_set('sslider_get_the_image', $cache); } else { $image = $cache[$post_id][$size]; } /* Allow plugins/theme to override the final output. */ $image = apply_filters('sslider_get_the_image', $image); /*print_r($image);*/ /* Display the image if $echo is set to true and the $format isn't an array. Else, return the image. */ if ('array' == $format) { $atts = wp_kses_hair($image, array('http')); foreach ($atts as $att) { $out[$att['name']] = $att['value']; } $out['url'] = $out['src']; // @deprecated 0.5 Use 'src' instead of 'url'. return $out; } elseif ($echo) { echo $image; } else { return $image; } }
/** * Add the MRSS info to the feed * * Based upon the MRSS plugin developed by Andy Skelton * * @since 0.1 * @copyright Andy Skelton */ public function mrss_item() { global $mrss_gallery_lookup; $media = array(); $lookup = array(); // Honor the feed settings. Don't include any media that isn't in the feed. if (get_option('rss_use_excerpt') || !strlen(get_the_content())) { ob_start(); the_excerpt_rss(); $content = ob_get_clean(); } else { // If any galleries are processed, we need to capture the attachment IDs. add_filter('wp_get_attachment_link', array($this, 'mrss_gallery_lookup'), 10, 5); $content = apply_filters('the_content', get_the_content()); remove_filter('wp_get_attachment_link', array($this, 'mrss_gallery_lookup'), 10, 5); $lookup = $mrss_gallery_lookup; unset($mrss_gallery_lookup); } // img tags $images = 0; if (preg_match_all('`<img ([^>]+)>`', $content, $matches)) { foreach ($matches[1] as $attrs) { $item = $img = array(); // Construct $img array from <img> attributes $attributes = wp_kses_hair($attrs, array('http')); foreach ($attributes as $attr) { $img[$attr['name']] = $attr['value']; } unset($attributes); // Skip emoticons and images without source attribute if (!isset($img['src']) || isset($img['class']) && false !== strpos($img['class'], 'wp-smiley')) { continue; } $img['src'] = $this->mrss_url($img['src']); $id = false; if (isset($lookup[$img['src']])) { $id = $lookup[$img['src']]; } elseif (isset($img['class']) && preg_match('`wp-image-(\\d+)`', $img['class'], $match)) { $id = $match[1]; } if ($id) { // It's an attachment, so we will get the URLs, title, and description from functions $attachment =& get_post($id); $src = wp_get_attachment_image_src($id, 'full'); if (!empty($src[0])) { $img['src'] = $src[0]; } $thumbnail = wp_get_attachment_image_src($id, 'thumbnail'); if (!empty($thumbnail[0]) && $thumbnail[0] != $img['src']) { $img['thumbnail'] = $thumbnail[0]; } $title = get_the_title($id); if (!empty($title)) { $img['title'] = trim($title); } if (!empty($attachment->post_excerpt)) { $img['description'] = trim($attachment->post_excerpt); } } // If this is the first image in the markup, make it the post thumbnail if (++$images == 1) { if (isset($img['thumbnail'])) { $media[]['thumbnail']['attr']['url'] = $img['thumbnail']; } else { $media[]['thumbnail']['attr']['url'] = $img['src']; } } $item['content']['attr']['url'] = $img['src']; $item['content']['attr']['medium'] = 'image'; if (!empty($img['title'])) { $item['content']['children']['title']['attr']['type'] = 'html'; $item['content']['children']['title']['children'][] = $img['title']; } elseif (!empty($img['alt'])) { $item['content']['children']['title']['attr']['type'] = 'html'; $item['content']['children']['title']['children'][] = $img['alt']; } if (!empty($img['description'])) { $item['content']['children']['description']['attr']['type'] = 'html'; $item['content']['children']['description']['children'][] = $img['description']; } if (!empty($img['thumbnail'])) { $item['content']['children']['thumbnail']['attr']['url'] = $img['thumbnail']; } $media[] = $item; } } $media = apply_filters('mrss_media', $media); $this->mrss_print($media); }
function sfc_base_find_video($post) { $vid = array(); // first we apply the filters to the content, just in case they're using shortcodes or oembed to display videos $content = apply_filters('the_content', $post->post_content); // look for an embed to add with video_src (simple, just add first embed) if (preg_match('/<embed (.+?)>/', $content, $matches)) { foreach (wp_kses_hair($matches[1], array('http')) as $attr) { $embed[$attr['name']] = $attr['value']; } if (isset($embed['src'])) { $vid[''] = $embed['src']; } if (isset($embed['height'])) { $vid[':height'] = $embed['height']; } if (isset($embed['width'])) { $vid[':width'] = $embed['width']; } if (isset($embed['type'])) { $vid[':type'] = $embed['type']; } } return $vid; }
/** * The main image function for displaying an image. It supports several arguments that allow developers to * customize how the script outputs the image. * * The image check order is important to note here. If an image is found by any specific check, the script * will no longer look for images. The check order is 'meta_key', 'the_post_thumbnail', 'attachment', * 'image_scan', 'callback', and 'default_image'. * * @since 0.1.0 * @access public * @global $post The current post's database object. * @param array $args Arguments for how to load and display the image. * @return string|array The HTML for the image. | Image attributes in an array. */ function get_the_image($args = array()) { /* Set the default arguments. */ $defaults = array('meta_key' => array('Thumbnail', 'thumbnail'), 'post_id' => get_the_ID(), 'attachment' => true, 'the_post_thumbnail' => true, 'size' => 'thumbnail', 'default_image' => false, 'order_of_image' => 1, 'link_to_post' => true, 'image_class' => false, 'image_scan' => false, 'width' => false, 'height' => false, 'format' => 'img', 'meta_key_save' => false, 'thumbnail_id_save' => false, 'callback' => null, 'cache' => true, 'before' => '', 'after' => '', 'echo' => true, 'custom_key' => null, 'default_size' => null); /* Allow plugins/themes to filter the arguments. */ $args = apply_filters('get_the_image_args', $args); /* Merge the input arguments and the defaults. */ $args = wp_parse_args($args, $defaults); /* If $default_size is given, overwrite $size. */ if (!is_null($args['default_size'])) { $args['size'] = $args['default_size']; } // Deprecated 0.5 in favor of $size /* If $custom_key is set, overwrite $meta_key. */ if (!is_null($args['custom_key'])) { $args['meta_key'] = $args['custom_key']; } // Deprecated 0.6 in favor of $meta_key /* If $format is set to 'array', don't link to the post. */ if ('array' == $args['format']) { $args['link_to_post'] = false; } /* Extract the array to allow easy use of variables. */ extract($args); /* Get cache key based on $args. */ $key = md5(serialize(compact(array_keys($args)))); /* Check for a cached image. */ $image_cache = wp_cache_get($post_id, 'get_the_image'); if (!is_array($image_cache)) { $image_cache = array(); } /* Set up a default, empty $image_html variable. */ $image_html = ''; /* If there is no cached image, let's see if one exists. */ if (!isset($image_cache[$key]) || empty($cache)) { /* If a custom field key (array) is defined, check for images by custom field. */ if (!empty($meta_key)) { $image = get_the_image_by_meta_key($args); } /* If no image found and $the_post_thumbnail is set to true, check for a post image (WP feature). */ if (empty($image) && !empty($the_post_thumbnail)) { $image = get_the_image_by_post_thumbnail($args); } /* If no image found and $attachment is set to true, check for an image by attachment. */ if (empty($image) && !empty($attachment)) { $image = get_the_image_by_attachment($args); } /* If no image found and $image_scan is set to true, scan the post for images. */ if (empty($image) && !empty($image_scan)) { $image = get_the_image_by_scan($args); } /* If no image found and a callback function was given. Callback function must pass back array of <img> attributes. */ if (empty($image) && !is_null($callback) && function_exists($callback)) { $image = call_user_func($callback, $args); } /* If no image found and a $default_image is set, get the default image. */ if (empty($image) && !empty($default_image)) { $image = get_the_image_by_default($args); } /* If an image was found. */ if (!empty($image)) { /* If $meta_key_save was set, save the image to a custom field. */ if (!empty($meta_key_save)) { get_the_image_meta_key_save($args, $image); } /* Format the image HTML. */ $image_html = get_the_image_format($args, $image); /* Set the image cache for the specific post. */ $image_cache[$key] = $image_html; wp_cache_set($post_id, $image_cache, 'get_the_image'); } } else { $image_html = $image_cache[$key]; } /* Allow plugins/theme to override the final output. */ $image_html = apply_filters('get_the_image', $image_html); /* If $format is set to 'array', return an array of image attributes. */ if ('array' == $format) { /* Set up a default empty array. */ $out = array(); /* Get the image attributes. */ $atts = wp_kses_hair($image_html, array('http')); /* Loop through the image attributes and add them in key/value pairs for the return array. */ foreach ($atts as $att) { $out[$att['name']] = $att['value']; } $out['url'] = $out['src']; // @deprecated 0.5 Use 'src' instead of 'url'. /* Return the array of attributes. */ return $out; } elseif (false === $echo) { return !empty($image_html) ? $args['before'] . $image_html . $args['after'] : $image_html; } /* If there is a $post_thumbnail_id, do the actions associated with get_the_post_thumbnail(). */ if (isset($image['post_thumbnail_id'])) { do_action('begin_fetch_post_thumbnail_html', $post_id, $image['post_thumbnail_id'], $size); } /* Display the image if we get to this point. */ echo !empty($image_html) ? $args['before'] . $image_html . $args['after'] : $image_html; /* If there is a $post_thumbnail_id, do the actions associated with get_the_post_thumbnail(). */ if (isset($image['post_thumbnail_id'])) { do_action('end_fetch_post_thumbnail_html', $post_id, $image['post_thumbnail_id'], $size); } }
/** * Removes all attributes, if none are allowed for this element. * * If some are allowed it calls wp_kses_hair() to split them further, and then * it builds up new HTML code from the data that kses_hair() returns. It also * removes "<" and ">" characters, if there are any left. One more thing it does * is to check if the tag has a closing XHTML slash, and if it does, it puts one * in the returned code as well. * * @since 1.0.0 * * @param string $element HTML element/tag * @param string $attr HTML attributes from HTML element to closing HTML element tag * @param array $allowed_html Allowed HTML elements * @param array $allowed_protocols Allowed protocols to keep * @return string Sanitized HTML element */ function wp_kses_attr($element, $attr, $allowed_html, $allowed_protocols) { if (!is_array($allowed_html)) { $allowed_html = wp_kses_allowed_html($allowed_html); } // Is there a closing XHTML slash at the end of the attributes? $xhtml_slash = ''; if (preg_match('%\\s*/\\s*$%', $attr)) { $xhtml_slash = ' /'; } // Are any attributes allowed at all for this element? if (!isset($allowed_html[strtolower($element)]) || count($allowed_html[strtolower($element)]) == 0) { return "<{$element}{$xhtml_slash}>"; } // Split it $attrarr = wp_kses_hair($attr, $allowed_protocols); // Go through $attrarr, and save the allowed attributes for this element // in $attr2 $attr2 = ''; foreach ($attrarr as $arreach) { if (wp_kses_attr_check($arreach['name'], $arreach['value'], $arreach['whole'], $arreach['vless'], $element, $allowed_html)) { $attr2 .= ' ' . $arreach['whole']; } } // Remove any "<" or ">" characters $attr2 = preg_replace('/[<>]/', '', $attr2); return "<{$element}{$attr2}{$xhtml_slash}>"; }
public function get_post_image($content) { $image = ''; if (class_exists('Jetpack_PostImages')) { // Use the full stack of methods to find an image, except for HTML, which can cause loops $img = Jetpack_PostImages::get_image($content->ID); if (!empty($img['src'])) { return $img['src']; } } // If we have to fall back to the following, we only do a few basic image checks $content = $content->post_content; if (function_exists('has_post_thumbnail') && has_post_thumbnail()) { $thumb_id = get_post_thumbnail_id(); $thumb = wp_get_attachment_image_src($thumb_id, 'full'); // This shouldn't be necessary, since has_post_thumbnail() is true, // but... see http://wordpress.org/support/topic/jetpack-youtube-embeds if (!$thumb) { return ''; } $image = remove_query_arg(array('w', 'h'), $thumb[0]); } else { if (preg_match_all('/<img (.+?)>/', $content, $matches)) { foreach ($matches[1] as $attrs) { $media = $img = array(); foreach (wp_kses_hair($attrs, array('http', 'https')) as $attr) { $img[$attr['name']] = $attr['value']; } if (!isset($img['src']) || 0 !== strpos($img['src'], 'http')) { continue; } else { $image = htmlspecialchars_decode($img['src']); break; } } } } return $image; }