예제 #1
0
 /**
  * Set the messages array from a vulnerabilities array.
  *
  * @param array $vulnerabilities Array of vulnerability objects.
  */
 public function set_from_vulnerabilities_array(array $vulnerabilities)
 {
     $this->messages = [];
     if (empty($vulnerabilities)) {
         return;
     }
     foreach ($vulnerabilities as $vulnerability) {
         $message = ['title' => $vulnerability->title, 'meta' => [], 'links' => []];
         if (!is_null($vulnerability->published_date)) {
             $message['meta'][] = sprintf('Published %s', $vulnerability->published_date->format('d M Y'));
         }
         if (isset($vulnerability->references->url)) {
             foreach ($vulnerability->references->url as $url) {
                 $parsed = wp_parse_url($url);
                 $host = isset($parsed['host']) ? $parsed['host'] : $url;
                 $message['links'][$url] = $host;
             }
         }
         $message['links'][sprintf('https://wpvulndb.com/vulnerabilities/%s', $vulnerability->id)] = 'wpvulndb.com';
         if (is_null($vulnerability->fixed_in)) {
             $message['meta'][] = 'Not fixed yet';
         } else {
             $message['meta'][] = sprintf('Fixed in v%s', $vulnerability->fixed_in);
         }
         $this->messages[] = $message;
     }
 }
예제 #2
0
 protected function is_same_origin($src)
 {
     $script_url = wp_parse_url($src);
     $home_url = wp_parse_url(home_url());
     // Bad URL.
     if (!isset($script_url['host']) || !isset($home_url['host'])) {
         return true;
     }
     return $script_url['host'] === $home_url['host'];
 }
예제 #3
0
 /**
  * @param $twitter_profile
  *
  * @return mixed
  * @since 2.3.5
  * @since 2.3.5.1 Bail if < WordPress 4.4 for now.
  */
 public static function twitter_url_to_user($twitter_profile)
 {
     // If they're below 4.4 (no wp_parse_url) bail. We can improve this for <4.4 later or just hold out until we drop 4.4 support.
     if (!function_exists('wp_parse_url')) {
         return $twitter_profile;
     }
     //extract the twitter username from the url
     $parsed_twitter_profile = wp_parse_url($twitter_profile);
     $path = $parsed_twitter_profile['path'];
     $path_parts = explode('/', $path);
     $twitter_profile = $path_parts[1];
     return $twitter_profile;
 }
예제 #4
0
 /**
  * Convert a "watch" url into an "embed"
  * Eg https://www.youtube.com/watch?v=OQZKh8Bjdv0 to https://www.youtube.com/embed/OQZKh8Bjdv0
  * Or https://vimeo.com/155086124 to https://player.vimeo.com/video/155086124
  *
  * @param string $url The video url.
  * @return string
  */
 public static function get_video_embed_url($url)
 {
     if (strpos($url, 'youtube') !== false && strpos($url, 'watch') !== false) {
         $parts = wp_parse_url($url);
         if (is_array($parts) && isset($parts['query'])) {
             parse_str($parts['query']);
             if (isset($v)) {
                 return 'https://www.youtube.com/embed/' . $v;
             }
         }
     }
     if (strpos($url, 'vimeo') !== false && strpos($url, 'player') === false) {
         $parts = wp_parse_url($url);
         if (is_array($parts) && isset($parts['path'])) {
             return 'https://player.vimeo.com/video' . $parts['path'];
         }
     }
     return $url;
 }
예제 #5
0
파일: CDN.php 프로젝트: ssnepenthe/metis
 /**
  * Class constructor.
  *
  * @param array $args Configuration array.
  *
  * @throws \RuntimeException If home_url() cannot be parsed properly.
  */
 public function __construct(array $args = [])
 {
     // Revisit - at a minimum this won't hold up against ccSLDs.
     $host = wp_parse_url(home_url());
     if (!isset($host['host'])) {
         // @todo
         throw new \RuntimeException();
     }
     $host = $host['host'];
     $host_parts = explode('.', $host);
     $tld = array_pop($host_parts);
     $domain = array_pop($host_parts);
     $defaults = ['aggressive' => apply_filters('metis.cdn.aggressive.default', true), 'domain' => apply_filters('metis.cdn.domain.default', sprintf('static.%s.%s', $domain, $tld)), 'extensions' => apply_filters('metis.cdn.extensions.default', ['css', 'gif', 'ico', 'jpe?g', 'js', 'png', 'svg'])];
     $this->args = wp_parse_args($args, $defaults);
     $this->assert_string($this->args['domain']);
     $this->assert_array_of_strings($this->args['extensions']);
     $this->elements = ['img' => ['src', 'srcset'], 'link' => ['href'], 'meta' => ['content'], 'script' => ['src']];
     $this->replace = sprintf('\\1%s\\2\\3', $this->args['domain']);
     $this->search = sprintf('/(https?\\:(?:\\\\)?\\/(?:\\\\)?\\/)%s((?:\\\\)?\\/[^\'"]*?)(\\.(?:%s))/', preg_quote($host), implode('|', $this->args['extensions']));
 }
 public function get_related_events($request)
 {
     $context = !empty($request['context']) ? $request['context'] : 'view';
     $url = wp_parse_url($_SERVER['REQUEST_URI']);
     $events_index = preg_match('/events$/', $url['path']);
     if ($context === 'embed' && $events_index) {
         return [];
         // when hitting the events index, we don't need the related events data
     }
     $event_id = $request['event_id'];
     $genre = get_post_meta($event_id, 'event_genre', true);
     $events_in_genre_args = array('post_type' => 'event', 'post_status' => array('publish'), 'posts_per_page' => -1, 'post__not_in' => array($event_id), 'meta_query' => array('relation' => 'AND', 'genre_clause' => array('key' => 'event_genre', 'value' => $genre, 'compare' => '='), 'last_event_instance_clause' => array('key' => 'last_event_instance', 'value' => date('Y-m-d H:i:s'), 'type' => 'DATETIME', 'compare' => '>=')), 'orderby' => 'last_event_instance_clause', 'order' => 'ASC');
     $related_events = get_posts($events_in_genre_args);
     $related_event_ids = array_map(function ($event) {
         return $event->ID;
     }, $related_events);
     if (count($related_event_ids)) {
         $request->set_param('filter', array('orderby' => 'post__in', 'post__in' => array_values($related_event_ids), 'post_type' => 'event', 'post__not_in' => array($event_id)));
         $request->set_param('per_page', 3);
         return $this->get_items($request);
     } else {
         return [];
     }
 }
예제 #7
0
/**
 * Adds dns-prefetch for all scripts and styles enqueued from external hosts.
 *
 * @since 4.6.0
 */
function wp_resource_hints_scripts_styles()
{
    global $wp_scripts, $wp_styles;
    $unique_hosts = array();
    if (is_object($wp_scripts) && !empty($wp_scripts->registered)) {
        foreach ($wp_scripts->registered as $registered_script) {
            $parsed = wp_parse_url($registered_script->src);
            if (!empty($parsed['host']) && !in_array($parsed['host'], $unique_hosts) && $parsed['host'] !== $_SERVER['SERVER_NAME']) {
                $unique_hosts[] = $parsed['host'];
            }
        }
    }
    if (is_object($wp_styles) && !empty($wp_styles->registered)) {
        foreach ($wp_styles->registered as $registered_style) {
            $parsed = wp_parse_url($registered_style->src);
            if (!empty($parsed['host']) && !in_array($parsed['host'], $unique_hosts) && $parsed['host'] !== $_SERVER['SERVER_NAME']) {
                $unique_hosts[] = $parsed['host'];
            }
        }
    }
    return $unique_hosts;
}
 /**
  * Remove all admin bar nodes that have links and which aren't for snapshots.
  *
  * @param \WP_Admin_Bar $wp_admin_bar Admin bar.
  */
 public function remove_all_non_snapshot_admin_bar_links($wp_admin_bar)
 {
     if (empty($this->snapshot)) {
         return;
     }
     $snapshot_admin_bar_node_ids = array('customize', 'exit-customize-snapshot', 'inspect-customize-snapshot');
     foreach ($wp_admin_bar->get_nodes() as $node) {
         if (in_array($node->id, $snapshot_admin_bar_node_ids, true) || '#' === substr($node->href, 0, 1)) {
             continue;
         }
         $parsed_link_url = wp_parse_url($node->href);
         $parsed_home_url = wp_parse_url(home_url('/'));
         $is_external_link = isset($parsed_link_url['host']) && $parsed_link_url['host'] !== $parsed_home_url['host'] || isset($parsed_link_url['path']) && 0 !== strpos($parsed_link_url['path'], $parsed_home_url['path']) || (!isset($parsed_link_url['query']) || !preg_match('#(^|&)customize_snapshot_uuid=#', $parsed_link_url['query']));
         if ($is_external_link) {
             $wp_admin_bar->remove_node($node->id);
         }
     }
 }
예제 #9
0
/**
 * Send back to donation form..
 *
 * Used to redirect a user back to the donation form if there are errors present.
 *
 * @param array $args
 *
 * @access public
 * @since  1.0
 * @return Void
 */
function give_send_back_to_checkout($args = array())
{
    $url = isset($_POST['give-current-url']) ? sanitize_text_field($_POST['give-current-url']) : '';
    //Set the form_id.
    if (isset($_POST['give-form-id'])) {
        $form_id = sanitize_text_field($_POST['give-form-id']);
    } else {
        $form_id = 0;
    }
    //Need a URL to continue. If none, redirect back to single form.
    if (empty($url)) {
        wp_safe_redirect(get_permalink($form_id));
        give_die();
    }
    $defaults = array('form-id' => (int) $form_id);
    // Check for backward compatibility.
    if (is_string($args)) {
        $args = str_replace('?', '', $args);
    }
    $args = wp_parse_args($args, $defaults);
    // Merge URL query with $args to maintain third-party URL parameters after redirect.
    $url_data = wp_parse_url($url);
    //Check if an array to prevent notices before parsing.
    if (isset($url_data['query']) && !empty($url_data['query'])) {
        parse_str($url_data['query'], $query);
        //Precaution: don't allow any CC info.
        unset($query['card_number']);
        unset($query['card_cvc']);
    } else {
        //No $url_data so pass empty array.
        $query = array();
    }
    $new_query = array_merge($args, $query);
    $new_query_string = http_build_query($new_query);
    // Assemble URL parts.
    $redirect = home_url('/' . $url_data['path'] . '?' . $new_query_string . '#give-form-' . $form_id . '-wrap');
    //Redirect them.
    wp_safe_redirect(apply_filters('give_send_back_to_checkout', $redirect, $args));
    give_die();
}
 /**
  * @ticket 30937
  * @covers wp_admin_bar_customize_menu()
  */
 public function test_customize_link()
 {
     global $wp_customize;
     require_once ABSPATH . WPINC . '/class-wp-customize-manager.php';
     $uuid = wp_generate_uuid4();
     $this->go_to(home_url("/?customize_changeset_uuid={$uuid}"));
     wp_set_current_user(self::$admin_id);
     $this->factory()->post->create(array('post_type' => 'customize_changeset', 'post_status' => 'auto-draft', 'post_name' => $uuid));
     $wp_customize = new WP_Customize_Manager(array('changeset_uuid' => $uuid));
     $wp_customize->start_previewing_theme();
     set_current_screen('front');
     $wp_admin_bar = $this->get_standard_admin_bar();
     $node = $wp_admin_bar->get_node('customize');
     $this->assertNotEmpty($node);
     $parsed_url = wp_parse_url($node->href);
     $query_params = array();
     wp_parse_str($parsed_url['query'], $query_params);
     $this->assertEquals($uuid, $query_params['changeset_uuid']);
     $this->assertNotContains('changeset_uuid', $query_params['url']);
 }
 /**
  * Test replace_customize_link.
  *
  * @covers CustomizeSnapshots\Customize_Snapshot_Manager::replace_customize_link()
  */
 public function test_replace_customize_link()
 {
     global $wp_admin_bar;
     set_current_screen('front');
     require_once ABSPATH . WPINC . '/class-wp-admin-bar.php';
     remove_all_actions('admin_bar_menu');
     $this->go_to(home_url('?customize_snapshot_uuid=' . self::UUID));
     $_REQUEST['customize_snapshot_uuid'] = self::UUID;
     $manager = new Customize_Snapshot_Manager($this->plugin);
     $manager->init();
     // Ensure customize link remains unknown if user lacks cap.
     wp_set_current_user(0);
     $wp_admin_bar = new \WP_Admin_Bar();
     // WPCS: Override OK.
     $wp_admin_bar->initialize();
     $wp_admin_bar->add_menus();
     do_action_ref_array('admin_bar_menu', array(&$wp_admin_bar));
     $this->assertEmpty($wp_admin_bar->get_node('customize'));
     // Ensure customize link modified.
     wp_set_current_user($this->user_id);
     $wp_admin_bar = new \WP_Admin_Bar();
     // WPCS: Override OK.
     $wp_admin_bar->initialize();
     $wp_admin_bar->add_menus();
     do_action_ref_array('admin_bar_menu', array(&$wp_admin_bar));
     $node = $wp_admin_bar->get_node('customize');
     $this->assertTrue(is_object($node));
     $parsed_url = wp_parse_url($node->href);
     $query_params = array();
     parse_str($parsed_url['query'], $query_params);
     $this->assertArrayHasKey('customize_snapshot_uuid', $query_params);
     $this->assertEquals(self::UUID, $query_params['customize_snapshot_uuid']);
     $this->assertArrayHasKey('url', $query_params);
     $parsed_preview_url = wp_parse_url($query_params['url']);
     $this->assertArrayNotHasKey('query', $parsed_preview_url);
 }
예제 #12
0
 /**
  * Fetch an image with wp_remote_get(), save it to $fullpath with a unique name.
  * Will return an empty string if something went wrong.
  *
  * @param $url string
  * @param $fullpath string
  *
  * @return string filename
  */
 protected function fetchAndSaveUniqueImage($url, $fullpath)
 {
     if (isset($this->fetchedImageCache[$url])) {
         return $this->fetchedImageCache[$url];
     }
     $response = wp_remote_get($url, array('timeout' => $this->timeout));
     // WordPress error?
     if (is_wp_error($response)) {
         try {
             // protocol relative urls handed to wp_remote_get will fail
             // try adding a protocol
             $protocol_relative = wp_parse_url($url);
             if (!isset($protocol_relative['scheme'])) {
                 if (true === is_ssl()) {
                     $url = 'https:' . $url;
                 } else {
                     $url = 'http:' . $url;
                 }
             }
             $response = wp_remote_get($url, array('timeout' => $this->timeout));
             if (is_wp_error($response)) {
                 throw new \Exception('Bad URL: ' . $url);
             }
         } catch (\Exception $exc) {
             $this->fetchedImageCache[$url] = '';
             error_log('\\PressBooks\\Export\\Epub201\\fetchAndSaveUniqueImage wp_error on wp_remote_get() - ' . $response->get_error_message() . ' - ' . $exc->getMessage());
             return '';
         }
     }
     // Basename without query string
     $filename = explode('?', basename($url));
     // isolate latex image service from WP, add file extension
     if ('s.wordpress.com' == parse_url($url, PHP_URL_HOST) && 'latex.php' == $filename[0]) {
         $filename = md5(array_pop($filename));
         // content-type = 'image/png'
         $type = explode('/', $response['headers']['content-type']);
         $type = array_pop($type);
         $filename = $filename . '.' . $type;
     } else {
         $filename = array_shift($filename);
         $filename = sanitize_file_name(urldecode($filename));
         $filename = Sanitize\force_ascii($filename);
     }
     $tmp_file = \Pressbooks\Utility\create_tmp_file();
     file_put_contents($tmp_file, wp_remote_retrieve_body($response));
     if (!\Pressbooks\Image\is_valid_image($tmp_file, $filename)) {
         $this->fetchedImageCache[$url] = '';
         error_log('\\PressBooks\\Export\\Epub201\\fetchAndSaveUniqueImage is_valid_image, not a valid image ');
         return '';
         // Not an image
     }
     if ($this->compressImages) {
         $format = explode('.', $filename);
         $format = strtolower(end($format));
         // Extension
         \Pressbooks\Image\resize_down($format, $tmp_file);
     }
     // Check for duplicates, save accordingly
     if (!file_exists("{$fullpath}/{$filename}")) {
         copy($tmp_file, "{$fullpath}/{$filename}");
     } elseif (md5(file_get_contents($tmp_file)) != md5(file_get_contents("{$fullpath}/{$filename}"))) {
         $filename = wp_unique_filename($fullpath, $filename);
         copy($tmp_file, "{$fullpath}/{$filename}");
     }
     $this->fetchedImageCache[$url] = $filename;
     return $filename;
 }
 /**
  * Determines whether the admin and the frontend are on different domains.
  *
  * @since 4.7.0
  * @access public
  *
  * @return bool Whether cross-domain.
  */
 public function is_cross_domain()
 {
     $admin_origin = wp_parse_url(admin_url());
     $home_origin = wp_parse_url(home_url());
     $cross_domain = strtolower($admin_origin['host']) !== strtolower($home_origin['host']);
     return $cross_domain;
 }
예제 #14
0
 /**
  * Edits the robots.txt output
  *
  * Requires not to have a robots.txt file in the root directory
  *
  * @uses robots_txt filter located at WP core
  *
  * @since 2.2.9
  *
  * @global int $blog_id;
  *
  * @todo maybe combine with noindex/noarchive/(nofollow) -> only when object caching?
  */
 public function robots_txt($robots_txt = '', $public = '')
 {
     global $blog_id;
     /**
      * Don't do anything if the blog isn't public
      */
     if ('0' === $public) {
         return $robots_txt;
     }
     $revision = '1';
     $cache_key = 'robots_txt_output_' . $revision . $blog_id;
     $output = $this->object_cache_get($cache_key);
     if (false === $output) {
         $output = '';
         /**
          * Apply filters the_seo_framework_robots_txt_pre & the_seo_framework_robots_txt_pro
          * 		: Add custom cacheable lines.
          *		: Don't forget to add line breaks ( "\r\n" | PHP_EOL )
          *
          * @since 2.5.0
          */
         $pre = (string) apply_filters('the_seo_framework_robots_txt_pre', '');
         $pro = (string) apply_filters('the_seo_framework_robots_txt_pro', '');
         $site_url = wp_parse_url(site_url());
         $path = !empty($site_url['path']) ? $site_url['path'] : '';
         $output .= $pre;
         //* Output defaults
         $output .= "User-agent: *\r\n";
         $output .= "Disallow: {$path}/wp-admin/\r\n";
         $output .= "Allow: {$path}/wp-admin/admin-ajax.php\r\n";
         /**
          * Prevents query indexing
          * @since 2.2.9
          *
          * Applies filters the_seo_framework_robots_disallow_queries : Whether to allow queries for robots.
          * @since 2.5.0
          */
         if (apply_filters('the_seo_framework_robots_disallow_queries', false)) {
             $home_url = wp_parse_url(rtrim($this->the_home_url_from_cache(), ' /\\'));
             $home_path = !empty($home_url['path']) ? $home_url['path'] : '';
             $output .= "Disallow: {$home_path}/*?*\r\n";
         }
         $output .= $pro;
         if ($this->get_option('sitemaps_robots') && $this->can_do_sitemap_robots()) {
             //* Add whitespace before sitemap.
             $output .= "\r\n";
             //* Add sitemap full url
             $output .= 'Sitemap: ' . $this->the_home_url_from_cache(true) . "sitemap.xml\r\n";
         }
         $this->object_cache_set($cache_key, $output, 86400);
     }
     /**
      * Completely override robots with output.
      * @since 2.5.0
      */
     $robots_txt = $output;
     return $robots_txt;
 }
예제 #15
0
 function true_purge_all()
 {
     global $rt_wp_nginx_helper;
     $prefix = trim($rt_wp_nginx_helper->options['redis_prefix']);
     $this->log('* * * * *');
     // If Purge Cache link click from network admin then purge all
     if (is_network_admin()) {
         delete_keys_by_wildcard($prefix . '*');
         $this->log('* Purged Everything! * ');
     } else {
         // Else purge only site specific cache
         $parse = wp_parse_url(get_site_url());
         $parse['path'] = empty($parse['path']) ? '/' : $parse['path'];
         delete_keys_by_wildcard($prefix . $parse['scheme'] . 'GET' . $parse['host'] . $parse['path'] . '*');
         $this->log('* ' . get_site_url() . ' Purged! * ');
     }
     $this->log('* * * * *');
 }
 /**
  * Test WP_Customize_Manager::add_state_query_params().
  *
  * @ticket 30937
  * @covers WP_Customize_Manager::add_state_query_params()
  */
 function test_add_state_query_params()
 {
     $preview_theme = $this->get_inactive_core_theme();
     $uuid = wp_generate_uuid4();
     $messenger_channel = 'preview-0';
     $wp_customize = new WP_Customize_Manager(array('changeset_uuid' => $uuid, 'messenger_channel' => $messenger_channel));
     $url = $wp_customize->add_state_query_params(home_url('/'));
     $parsed_url = wp_parse_url($url);
     parse_str($parsed_url['query'], $query_params);
     $this->assertArrayHasKey('customize_messenger_channel', $query_params);
     $this->assertArrayHasKey('customize_changeset_uuid', $query_params);
     $this->assertArrayNotHasKey('customize_theme', $query_params);
     $this->assertEquals($uuid, $query_params['customize_changeset_uuid']);
     $this->assertEquals($messenger_channel, $query_params['customize_messenger_channel']);
     $uuid = wp_generate_uuid4();
     $wp_customize = new WP_Customize_Manager(array('changeset_uuid' => $uuid, 'messenger_channel' => null, 'theme' => $preview_theme));
     $url = $wp_customize->add_state_query_params(home_url('/'));
     $parsed_url = wp_parse_url($url);
     parse_str($parsed_url['query'], $query_params);
     $this->assertArrayNotHasKey('customize_messenger_channel', $query_params);
     $this->assertArrayHasKey('customize_changeset_uuid', $query_params);
     $this->assertArrayHasKey('customize_theme', $query_params);
     $this->assertEquals($uuid, $query_params['customize_changeset_uuid']);
     $this->assertEquals($preview_theme, $query_params['customize_theme']);
     $uuid = wp_generate_uuid4();
     $wp_customize = new WP_Customize_Manager(array('changeset_uuid' => $uuid, 'messenger_channel' => null, 'theme' => $preview_theme));
     $url = $wp_customize->add_state_query_params('http://not-allowed.example.com/?q=1');
     $parsed_url = wp_parse_url($url);
     parse_str($parsed_url['query'], $query_params);
     $this->assertArrayNotHasKey('customize_messenger_channel', $query_params);
     $this->assertArrayNotHasKey('customize_changeset_uuid', $query_params);
     $this->assertArrayNotHasKey('customize_theme', $query_params);
 }
예제 #17
0
 /**
  * Determine whether the given asset source is local.
  *
  * @param string $src Asset URL.
  *
  * @return boolean
  */
 protected function is_same_origin($src)
 {
     $script_url = wp_parse_url($src);
     $home_url = wp_parse_url(home_url());
     if (!isset($script_url['host']) || !isset($home_url['host'])) {
         // Something is wrong...
         return true;
     }
     return $script_url === $home_url;
 }
예제 #18
0
/**
 * Retrieves a list of unique hosts of all enqueued scripts and styles.
 *
 * @since 4.6.0
 *
 * @return array A list of unique hosts of enqueued scripts and styles.
 */
function wp_dependencies_unique_hosts()
{
    global $wp_scripts, $wp_styles;
    $unique_hosts = array();
    foreach (array($wp_scripts, $wp_styles) as $dependencies) {
        if ($dependencies instanceof WP_Dependencies && !empty($dependencies->queue)) {
            foreach ($dependencies->queue as $handle) {
                if (!isset($dependencies->registered[$handle])) {
                    continue;
                }
                /* @var _WP_Dependency $dependency */
                $dependency = $dependencies->registered[$handle];
                $parsed = wp_parse_url($dependency->src);
                if (!empty($parsed['host']) && !in_array($parsed['host'], $unique_hosts) && $parsed['host'] !== $_SERVER['SERVER_NAME']) {
                    $unique_hosts[] = $parsed['host'];
                }
            }
        }
    }
    return $unique_hosts;
}
 /**
  * Logout action listener
  */
 public function logout_action()
 {
     $parsed = wp_parse_url(home_url());
     setcookie($this->cookie_name, '', strtotime('-1 day'), '/', '.' . $parsed['host']);
 }
예제 #20
0
 /**
  * @ticket 36356
  *
  * @dataProvider parse_url_component_testcases
  */
 function test_wp_parse_url_with_component($url, $component, $expected)
 {
     $actual = wp_parse_url($url, $component);
     $this->assertSame($expected, $actual);
 }
 function scrape_instagram($username, $slice = 9)
 {
     $username = strtolower($username);
     $username = str_replace('@', '', $username);
     if (false === ($instagram = get_transient('instagram-a2-' . sanitize_title_with_dashes($username)))) {
         $remote = wp_remote_get('http://instagram.com/' . trim($username));
         if (is_wp_error($remote)) {
             return new WP_Error('site_down', esc_html__('Unable to communicate with Instagram.', 'wp-instagram-widget'));
         }
         if (200 != wp_remote_retrieve_response_code($remote)) {
             return new WP_Error('invalid_response', esc_html__('Instagram did not return a 200.', 'wp-instagram-widget'));
         }
         $shards = explode('window._sharedData = ', $remote['body']);
         $insta_json = explode(';</script>', $shards[1]);
         $insta_array = json_decode($insta_json[0], TRUE);
         if (!$insta_array) {
             return new WP_Error('bad_json', esc_html__('Instagram has returned invalid data.', 'wp-instagram-widget'));
         }
         if (isset($insta_array['entry_data']['ProfilePage'][0]['user']['media']['nodes'])) {
             $images = $insta_array['entry_data']['ProfilePage'][0]['user']['media']['nodes'];
         } else {
             return new WP_Error('bad_json_2', esc_html__('Instagram has returned invalid data.', 'wp-instagram-widget'));
         }
         if (!is_array($images)) {
             return new WP_Error('bad_array', esc_html__('Instagram has returned invalid data.', 'wp-instagram-widget'));
         }
         $instagram = array();
         foreach ($images as $image) {
             $image['thumbnail_src'] = preg_replace('/^https?\\:/i', '', $image['thumbnail_src']);
             $image['display_src'] = preg_replace('/^https?\\:/i', '', $image['display_src']);
             // handle both types of CDN url
             if (strpos($image['thumbnail_src'], 's640x640') !== false) {
                 $image['thumbnail'] = str_replace('s640x640', 's160x160', $image['thumbnail_src']);
                 $image['small'] = str_replace('s640x640', 's320x320', $image['thumbnail_src']);
             } else {
                 $urlparts = wp_parse_url($image['thumbnail_src']);
                 $pathparts = explode('/', $urlparts['path']);
                 $pathparts[3] = 's160x160';
                 $image['thumbnail'] = '//' . $urlparts['host'] . implode('/', $pathparts);
                 $pathparts[3] = 's320x320';
                 $image['small'] = '//' . $urlparts['host'] . implode('/', $pathparts);
             }
             $image['large'] = $image['thumbnail_src'];
             if ($image['is_video'] == true) {
                 $type = 'video';
             } else {
                 $type = 'image';
             }
             $caption = __('Instagram Image', 'wp-instagram-widget');
             if (!empty($image['caption'])) {
                 $caption = $image['caption'];
             }
             $instagram[] = array('description' => $caption, 'link' => '//instagram.com/p/' . $image['code'], 'time' => $image['date'], 'comments' => $image['comments']['count'], 'likes' => $image['likes']['count'], 'thumbnail' => $image['thumbnail'], 'small' => $image['small'], 'large' => $image['large'], 'original' => $image['display_src'], 'type' => $type);
         }
         // do not set an empty transient - should help catch private or empty accounts
         if (!empty($instagram)) {
             $instagram = base64_encode(serialize($instagram));
             set_transient('instagram-a2-' . sanitize_title_with_dashes($username), $instagram, apply_filters('null_instagram_cache_time', HOUR_IN_SECONDS * 2));
         }
     }
     if (!empty($instagram)) {
         $instagram = unserialize(base64_decode($instagram));
         return array_slice($instagram, 0, $slice);
     } else {
         return new WP_Error('no_images', esc_html__('Instagram did not return any images.', 'wp-instagram-widget'));
     }
 }
예제 #22
0
function extauth_replacementLink($type, $url)
{
    $url = esc_url($url, ['http', 'https', 'ftp', 'ftps', 'mailto']);
    $types = array('email' => __('your email address', 'wp-extauth'), 'password' => __('your password', 'wp-extauth'));
    $links = array('absolute' => _x('here', 'You can change your X here.', 'wp-extauth'), 'relative' => _x('on', 'You can change your X on domain.com.', 'wp-extauth'));
    if (!preg_match('/(https?|ftp|mailto):\\/\\//', $url)) {
        $link = $links['absolute'];
        $url = home_url($url);
    } else {
        $domain = wp_parse_url($url);
        $link = $links['relative'] . ' ' . $domain['host'];
    }
    $text = sprintf(__('You can change %s <a href="%s">%s</a>.', 'wp-extauth'), $types[$type], $url, $link);
    return $text;
}
예제 #23
0
 public static function extract_domain_name($url, $subdomain = false)
 {
     $parse = wp_parse_url($url);
     if ($subdomain) {
         return preg_replace('/^www\\./', '', $parse['host']);
     }
     return preg_replace('/^([a-zA-Z0-9].*\\.)?([a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\\.[a-zA-Z.]{2,})$/', '$2', $parse['host']);
 }
예제 #24
0
 /**
  * Normalizes a url by doing three things:
  *  - Strips protocol
  *  - Strips www
  *  - Adds a trailing slash
  *
  * @since 4.4.0
  * @param string $url
  * @return WP_Error|string
  */
 public static function normalize_url_protocol_agnostic($url)
 {
     $parsed_url = wp_parse_url(trailingslashit(esc_url_raw($url)));
     if (!$parsed_url) {
         return new WP_Error('cannot_parse_url', sprintf(esc_html__('Cannot parse URL %s', 'jetpack'), $url));
     }
     // Strip www and protocols
     $url = preg_replace('/^www\\./i', '', $parsed_url['host'] . $parsed_url['path']);
     return $url;
 }
예제 #25
0
 /**
  * Used as a wrapper for PHP's parse_url() function that handles edgecases in < PHP 5.4.7.
  *
  * @access protected
  * @deprecated 4.4.0 Use wp_parse_url()
  * @see wp_parse_url()
  *
  * @param string $url The URL to parse.
  * @return bool|array False on failure; Array of URL components on success;
  *                    See parse_url()'s return values.
  */
 protected static function parse_url($url)
 {
     _deprecated_function(__METHOD__, '4.4.0', 'wp_parse_url()');
     return wp_parse_url($url);
 }
예제 #26
0
/**
 * Checks and cleans a URL.
 *
 * A number of characters are removed from the URL. If the URL is for displaying
 * (the default behaviour) ampersands are also replaced. The 'clean_url' filter
 * is applied to the returned cleaned URL.
 *
 * @since 2.8.0
 *
 * @param string $url       The URL to be cleaned.
 * @param array  $protocols Optional. An array of acceptable protocols.
 *		                    Defaults to return value of wp_allowed_protocols()
 * @param string $_context  Private. Use esc_url_raw() for database usage.
 * @return string The cleaned $url after the 'clean_url' filter is applied.
 */
function esc_url($url, $protocols = null, $_context = 'display')
{
    $original_url = $url;
    if ('' == $url) {
        return $url;
    }
    $url = str_replace(' ', '%20', $url);
    $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\\|*\'()\\[\\]\\x80-\\xff]|i', '', $url);
    if ('' === $url) {
        return $url;
    }
    if (0 !== stripos($url, 'mailto:')) {
        $strip = array('%0d', '%0a', '%0D', '%0A');
        $url = _deep_replace($strip, $url);
    }
    $url = str_replace(';//', '://', $url);
    /* If the URL doesn't appear to contain a scheme, we
     * presume it needs http:// prepended (unless a relative
     * link starting with /, # or ? or a php file).
     */
    if (strpos($url, ':') === false && !in_array($url[0], array('/', '#', '?')) && !preg_match('/^[a-z0-9-]+?\\.php/i', $url)) {
        $url = 'http://' . $url;
    }
    // Replace ampersands and single quotes only when displaying.
    if ('display' == $_context) {
        $url = wp_kses_normalize_entities($url);
        $url = str_replace('&amp;', '&#038;', $url);
        $url = str_replace("'", '&#039;', $url);
    }
    if (false !== strpos($url, '[') || false !== strpos($url, ']')) {
        $parsed = wp_parse_url($url);
        $front = '';
        if (isset($parsed['scheme'])) {
            $front .= $parsed['scheme'] . '://';
        } elseif ('/' === $url[0]) {
            $front .= '//';
        }
        if (isset($parsed['user'])) {
            $front .= $parsed['user'];
        }
        if (isset($parsed['pass'])) {
            $front .= ':' . $parsed['pass'];
        }
        if (isset($parsed['user']) || isset($parsed['pass'])) {
            $front .= '@';
        }
        if (isset($parsed['host'])) {
            $front .= $parsed['host'];
        }
        if (isset($parsed['port'])) {
            $front .= ':' . $parsed['port'];
        }
        $end_dirty = str_replace($front, '', $url);
        $end_clean = str_replace(array('[', ']'), array('%5B', '%5D'), $end_dirty);
        $url = str_replace($end_dirty, $end_clean, $url);
    }
    if ('/' === $url[0]) {
        $good_protocol_url = $url;
    } else {
        if (!is_array($protocols)) {
            $protocols = wp_allowed_protocols();
        }
        $good_protocol_url = wp_kses_bad_protocol($url, $protocols);
        if (strtolower($good_protocol_url) != strtolower($url)) {
            return '';
        }
    }
    /**
     * Filter a string cleaned and escaped for output as a URL.
     *
     * @since 2.3.0
     *
     * @param string $good_protocol_url The cleaned URL to be returned.
     * @param string $original_url      The URL prior to cleaning.
     * @param string $_context          If 'display', replace ampersands and single quotes only.
     */
    return apply_filters('clean_url', $good_protocol_url, $original_url, $_context);
}
 /**
  * Check whether a callback is valid for a given consumer.
  *
  * @param string $url Supplied callback.
  * @param int|WP_Post $consumer_id Consumer post ID or object.
  * @return bool True if valid, false otherwise.
  */
 public function check_callback($url, $consumer_id)
 {
     $consumer = get_post($consumer_id);
     if (empty($consumer) || $consumer->post_type !== 'json_consumer' || $consumer->type !== $this->type) {
         return false;
     }
     $registered = $consumer->callback;
     if (empty($registered)) {
         return false;
     }
     // Out-of-band isn't a URL, but is still valid
     if ($registered === 'oob' || $url === 'oob') {
         // Ensure both the registered URL and requested are 'oob'
         return $registered === $url;
     }
     // Validate the supplied URL
     if (!$this->validate_callback($url)) {
         return false;
     }
     $registered = wp_parse_url($registered);
     $supplied = wp_parse_url($url);
     // Check all components except query and fragment
     $parts = array('scheme', 'host', 'port', 'user', 'pass', 'path');
     $valid = true;
     foreach ($parts as $part) {
         if (isset($registered[$part]) !== isset($supplied[$part])) {
             $valid = false;
             break;
         }
         if (!isset($registered[$part])) {
             continue;
         }
         if ($registered[$part] !== $supplied[$part]) {
             $valid = false;
             break;
         }
     }
     /**
      * Filter whether a callback is counted as valid.
      *
      * By default, the URLs must match scheme, host, port, user, pass, and
      * path. Query and fragment segments are allowed to be different.
      *
      * To change this behaviour, filter this value. Note that consumers must
      * have a callback registered, even if you relax this restruction. It is
      * highly recommended not to change this behaviour, as clients will
      * expect the same behaviour across all WP sites.
      *
      * @param boolean $valid True if the callback URL is valid, false otherwise.
      * @param string $url Supplied callback URL.
      * @param WP_Post $consumer Consumer post; stored callback saved as `consumer` meta value.
      */
     return apply_filters('rest_oauth.check_callback', $valid, $url, $consumer);
 }
예제 #28
0
 /**
  * @dataProvider parse_url_testcases
  */
 function test_wp_parse_url($url, $expected)
 {
     $actual = wp_parse_url($url);
     $this->assertEquals($expected, $actual);
 }
 /**
  * Converts a relative URL to an absolute URL relative to a given URL.
  *
  * If an Absolute URL is provided, no processing of that URL is done.
  *
  * @since 3.4.0
  *
  * @static
  * @access public
  *
  * @param string $maybe_relative_path The URL which might be relative
  * @param string $url                 The URL which $maybe_relative_path is relative to
  * @return string An Absolute URL, in a failure condition where the URL cannot be parsed, the relative URL will be returned.
  */
 public static function make_absolute_url($maybe_relative_path, $url)
 {
     if (empty($url)) {
         return $maybe_relative_path;
     }
     if (!($url_parts = wp_parse_url($url))) {
         return $maybe_relative_path;
     }
     if (!($relative_url_parts = wp_parse_url($maybe_relative_path))) {
         return $maybe_relative_path;
     }
     // Check for a scheme on the 'relative' url
     if (!empty($relative_url_parts['scheme'])) {
         return $maybe_relative_path;
     }
     $absolute_path = $url_parts['scheme'] . '://';
     // Schemeless URL's will make it this far, so we check for a host in the relative url and convert it to a protocol-url
     if (isset($relative_url_parts['host'])) {
         $absolute_path .= $relative_url_parts['host'];
         if (isset($relative_url_parts['port'])) {
             $absolute_path .= ':' . $relative_url_parts['port'];
         }
     } else {
         $absolute_path .= $url_parts['host'];
         if (isset($url_parts['port'])) {
             $absolute_path .= ':' . $url_parts['port'];
         }
     }
     // Start off with the Absolute URL path.
     $path = !empty($url_parts['path']) ? $url_parts['path'] : '/';
     // If it's a root-relative path, then great.
     if (!empty($relative_url_parts['path']) && '/' == $relative_url_parts['path'][0]) {
         $path = $relative_url_parts['path'];
         // Else it's a relative path.
     } elseif (!empty($relative_url_parts['path'])) {
         // Strip off any file components from the absolute path.
         $path = substr($path, 0, strrpos($path, '/') + 1);
         // Build the new path.
         $path .= $relative_url_parts['path'];
         // Strip all /path/../ out of the path.
         while (strpos($path, '../') > 1) {
             $path = preg_replace('![^/]+/\\.\\./!', '', $path);
         }
         // Strip any final leading ../ from the path.
         $path = preg_replace('!^/(\\.\\./)+!', '', $path);
     }
     // Add the Query string.
     if (!empty($relative_url_parts['query'])) {
         $path .= '?' . $relative_url_parts['query'];
     }
     return $absolute_path . '/' . ltrim($path, '/');
 }
예제 #30
0
 /**
  * Sanitize the Redirect URL
  *
  * @since 2.2.4
  *
  * @param string $new_value String with potentially unwanted redirect URL.
  * @return string The Sanitized Redirect URL
  */
 protected function s_redirect_url($new_value)
 {
     $url = strip_tags($new_value);
     if ($url) {
         $allow_external = $this->allow_external_redirect();
         /**
          * Sanitize the redirect URL to only a relative link and removes first slash
          * @requires WP 4.1.0 and up to prevent adding upon itself.
          */
         if (!$allow_external) {
             $url = $this->s_relative_url($url);
         }
         //* Find a path.
         if (_wp_can_use_pcre_u()) {
             //* URL pattern excluding path.
             $pattern = '/' . '((((http)(s)?)?)\\:)?' . '(\\/\\/)?' . '((www.)?)' . '(.*\\.[a-zA-Z0-9]*)' . '(?:\\/)?' . '/';
             $is_path = !preg_match($pattern, $url);
         } else {
             $parsed_url = wp_parse_url($url);
             $is_path = !isset($parsed_url['host']) && isset($parsed_url['path']);
         }
         //* If link is relative, make it full again
         if ($is_path) {
             //* The url is a relative path
             $path = $url;
             //* Try WPMUdev Domain Mapping.
             $wpmu_url = $this->the_url_wpmudev_domainmap($path, true);
             if ($wpmu_url && is_array($wpmu_url)) {
                 $url = $wpmu_url[0];
                 $scheme = $wpmu_url[1];
             }
             //* Try Donncha Domain Mapping.
             if (!isset($scheme)) {
                 $dm_url = $this->the_url_donncha_domainmap($path, true);
                 if ($dm_url && is_array($dm_url)) {
                     $url = $dm_url[0];
                     $scheme = $dm_url[1];
                 }
             }
             //* Everything else.
             if (!isset($scheme)) {
                 $url = $this->the_home_url_from_cache(true) . ltrim($path, ' /');
                 $scheme = is_ssl() ? 'https' : 'http';
             }
             //* When nothing is found, fall back on WP defaults (is_ssl).
             $scheme = isset($scheme) ? $scheme : '';
             $url = $this->set_url_scheme($url, $scheme);
         }
     }
     /**
      * Applies filters the_seo_framework_301_noqueries : bool remove query args from 301
      * @since 2.5.0
      */
     $noqueries = (bool) apply_filters('the_seo_framework_301_noqueries', true);
     /**
      * Remove queries from the URL
      *
      * Returns plain Home URL if $allow_external is set to false and only a query has been supplied
      * But that's okay. The URL was rogue anyway :)
      */
     if ($noqueries) {
         /**
          * Remove query args
          *
          * @see The_SEO_Framework_Sanitize::s_url
          * @since 2.2.4
          */
         $new_value = $this->s_url($url);
     } else {
         /**
          * Allow query string parameters. XSS safe.
          */
         $new_value = esc_url_raw($url);
     }
     //* Save url
     return $new_value;
 }