public function test_unattached_link()
 {
     $attachment_id = self::factory()->attachment->create_object('image.jpg', 0, array('post_mime_type' => 'image/jpeg', 'post_type' => 'attachment'));
     $link = get_post_comments_feed_link($attachment_id);
     $expected = add_query_arg(array('feed' => get_default_feed(), 'attachment_id' => $attachment_id), home_url('/'));
     $this->assertEquals($expected, $link);
 }
Example #2
0
/**
 * Clean up wp_head()
 *
 * Remove unnecessary <link>'s
 * Remove inline CSS and JS from WP emoji support
 * Remove inline CSS used by Recent Comments widget
 * Remove inline CSS used by posts with galleries
 * Remove self-closing tag and change ''s to "'s on rel_canonical()
 *
 * You can enable/disable this feature in functions.php (or lib/setup.php if you're using Sage):
 * add_theme_support('soil-clean-up');
 */
function head_cleanup()
{
    // Originally from http://wpengineer.com/1438/wordpress-header/
    remove_action('wp_head', 'feed_links_extra', 3);
    add_action('wp_head', 'ob_start', 1, 0);
    add_action('wp_head', function () {
        $pattern = '/.*' . preg_quote(esc_url(get_feed_link('comments_' . get_default_feed())), '/') . '.*[\\r\\n]+/';
        echo preg_replace($pattern, '', ob_get_clean());
    }, 3, 0);
    remove_action('wp_head', 'rsd_link');
    remove_action('wp_head', 'wlwmanifest_link');
    remove_action('wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
    remove_action('wp_head', 'wp_generator');
    remove_action('wp_head', 'wp_shortlink_wp_head', 10, 0);
    remove_action('wp_head', 'print_emoji_detection_script', 7);
    remove_action('admin_print_scripts', 'print_emoji_detection_script');
    remove_action('wp_print_styles', 'print_emoji_styles');
    remove_action('admin_print_styles', 'print_emoji_styles');
    remove_action('wp_head', 'wp_oembed_add_discovery_links');
    remove_action('wp_head', 'wp_oembed_add_host_js');
    remove_action('wp_head', 'rest_output_link_wp_head', 10, 0);
    remove_filter('the_content_feed', 'wp_staticize_emoji');
    remove_filter('comment_text_rss', 'wp_staticize_emoji');
    remove_filter('wp_mail', 'wp_staticize_emoji_for_email');
    add_filter('use_default_gallery_style', '__return_false');
    global $wp_widget_factory;
    if (isset($wp_widget_factory->widgets['WP_Widget_Recent_Comments'])) {
        remove_action('wp_head', [$wp_widget_factory->widgets['WP_Widget_Recent_Comments'], 'recent_comments_style']);
    }
    if (!class_exists('WPSEO_Frontend')) {
        remove_action('wp_head', 'rel_canonical');
        add_action('wp_head', __NAMESPACE__ . '\\rel_canonical');
    }
}
Example #3
0
 /**
  * Class constructor.
  *
  * @since 150218 Refactoring cache clear/purge routines.
  */
 public function __construct()
 {
     $this->plugin = plugin();
     $this->home_url = home_url('/');
     $this->default_feed = get_default_feed();
     $this->seo_friendly_permalinks = (bool) get_option('permalink_structure');
     $this->feed_types = array_unique(array($this->default_feed, 'rdf', 'rss', 'rss2', 'atom'));
 }
Example #4
0
 /**
  * Class constructor.
  *
  * @since 150422 Rewrite.
  */
 public function __construct()
 {
     parent::__construct();
     $this->home_url = rtrim(home_url(), '/');
     $this->default_feed = get_default_feed();
     // Default feed type.
     $this->seo_friendly_permalinks = (bool) get_option('permalink_structure');
     $this->feed_types = array_unique([$this->default_feed, 'rdf', 'rss', 'rss2', 'atom']);
 }
Example #5
0
function thesis_feed_url($display = false)
{
    global $thesis;
    $feed_url = $thesis['feed']['url'] ? $thesis['feed']['url'] : get_bloginfo(get_default_feed() . '_url');
    if ($display) {
        echo $feed_url;
    } else {
        return $feed_url;
    }
}
Example #6
0
function thesis_feed_url($display = false)
{
    global $thesis_site;
    $feed_url = $thesis_site->head['feed']['url'] ? $thesis_site->head['feed']['url'] : get_bloginfo(get_default_feed() . '_url');
    $feed_url = apply_filters('thesis_feed_url', $feed_url);
    if ($display) {
        echo $feed_url;
    } else {
        return $feed_url;
    }
}
Example #7
0
function smittenkitchen_content_feed($feed_type = null)
{
    if (!$feed_type) {
        $feed_type = get_default_feed();
    }
    global $more;
    $more_restore = $more;
    $more = 0;
    $content = apply_filters('the_content', get_the_content());
    $more = $more_restore;
    $content = str_replace(']]>', ']]& gt;', $content);
    return $content;
}
Example #8
0
 /**
  * Page cache tab
  *
  * @return void
  */
 function view()
 {
     global $wp_rewrite;
     $feeds = $wp_rewrite->feeds;
     $feed_key = array_search('feed', $feeds);
     if ($feed_key !== false) {
         unset($feeds[$feed_key]);
     }
     $default_feed = get_default_feed();
     $pgcache_enabled = $this->_config->get_boolean('pgcache.enabled');
     $permalink_structure = get_option('permalink_structure');
     $varnish_enabled = $this->_config->get_boolean('varnish.enabled');
     $cdn_mirror_purge_enabled = Cdn_Util::is_engine_fsd($this->_config->get_string('cdn.engine')) && $this->_config->get_boolean('cdn.enabled');
     include W3TC_INC_DIR . '/options/pgcache.php';
 }
Example #9
0
 /**
  * Page cache tab
  *
  * @return void
  */
 function view()
 {
     global $wp_rewrite;
     $feeds = $wp_rewrite->feeds;
     $feed_key = array_search('feed', $feeds);
     if ($feed_key !== false) {
         unset($feeds[$feed_key]);
     }
     $default_feed = get_default_feed();
     $pgcache_enabled = $this->_config->get_boolean('pgcache.enabled');
     $permalink_structure = get_option('permalink_structure');
     $varnish_enabled = $this->_config->get_boolean('varnish.enabled');
     $cdn_mirror_purge_enabled = w3_is_cdn_mirror($this->_config->get_string('cdn.engine')) && $this->_config->get_string('cdn.engine') != 'mirror' && $this->_config->get_boolean('cdncache.enabled') && w3tc_edge_mode() && w3_is_pro($this->_config) || w3_is_enterprise();
     $disable_check_domain = w3_is_multisite() && w3_force_master();
     include W3TC_INC_DIR . '/options/pgcache.php';
 }
Example #10
0
/**
 * Display the links to the general feeds.
 *
 * @since 2.8.0
 *
 * @param array $args Optional arguments.
 */
function feed_links($args = array())
{
    if (!current_theme_supports('automatic-feed-links')) {
        return;
    }
    $defaults = array('separator' => _x('&raquo;', 'feed link'), 'feedtitle' => __('%1$s %2$s Feed'), 'comstitle' => __('%1$s %2$s Comments Feed'));
    $args = wp_parse_args($args, $defaults);
    echo '<link rel="alternate" type="' . feed_content_type() . '" title="' . esc_attr(sprintf($args['feedtitle'], get_bloginfo('name'), $args['separator'])) . '" href="' . esc_url(get_feed_link()) . "\" />\n";
    echo '<link rel="alternate" type="' . feed_content_type() . '" title="' . esc_attr(sprintf($args['comstitle'], get_bloginfo('name'), $args['separator'])) . '" href="' . esc_url(get_feed_link('comments_' . get_default_feed())) . "\" />\n";
}
Example #11
0
/**
 * Load the feed template from the use of an action hook.
 *
 * If the feed action does not have a hook, then the function will die with a
 * message telling the visitor that the feed is not valid.
 *
 * It is better to only have one hook for each feed.
 *
 * @since 2.1.0
 *
 * @global WP_Query $wp_query Used to tell if the use a comment feed.
 */
function do_feed()
{
    global $wp_query;
    // Determine if we are looking at the main comment feed
    $is_main_comments_feed = $wp_query->is_comment_feed() && !$wp_query->is_singular();
    /*
     * Check the queried object for the existence of posts if it is not a feed for an archive,
     * search result, or main comments. By checking for the absense of posts we can prevent rendering the feed
     * templates at invalid endpoints. e.g.) /wp-content/plugins/feed/
     */
    if (!$wp_query->have_posts() && !($wp_query->is_archive() || $wp_query->is_search() || $is_main_comments_feed)) {
        wp_die(__('ERROR: This is not a valid feed.'), '', array('response' => 404));
    }
    $feed = get_query_var('feed');
    // Remove the pad, if present.
    $feed = preg_replace('/^_+/', '', $feed);
    if ($feed == '' || $feed == 'feed') {
        $feed = get_default_feed();
    }
    if (!has_action("do_feed_{$feed}")) {
        wp_die(__('ERROR: This is not a valid feed template.'), '', array('response' => 404));
    }
    /**
     * Fires once the given feed is loaded.
     *
     * The dynamic portion of the hook name, `$feed`, refers to the feed template name.
     * Possible values include: 'rdf', 'rss', 'rss2', and 'atom'.
     *
     * @since 2.1.0
     * @since 4.4.0 The `$feed` parameter was added.
     *
     * @param bool   $is_comment_feed Whether the feed is a comment feed.
     * @param string $feed            The feed name.
     */
    do_action("do_feed_{$feed}", $wp_query->is_comment_feed, $feed);
}
Example #12
0
/**
 * Redirects incoming links to the proper URL based on the site url.
 *
 * Search engines consider www.somedomain.com and somedomain.com to be two
 * different URLs when they both go to the same location. This SEO enhancement
 * prevents penality for duplicate content by redirecting all incoming links to
 * one or the other.
 *
 * Prevents redirection for feeds, trackbacks, searches, comment popup, and
 * admin URLs. Does not redirect on IIS, page/post previews, and on form data.
 *
 * Will also attempt to find the correct link when a user enters a URL that does
 * not exist based on exact WordPress query. Will instead try to parse the URL
 * or query in an attempt to figure the correct page to go to.
 *
 * @since 2.3.0
 * @uses $wp_rewrite
 * @uses $is_IIS
 *
 * @param string $requested_url Optional. The URL that was requested, used to
 *		figure if redirect is needed.
 * @param bool $do_redirect Optional. Redirect to the new URL.
 * @return null|false|string Null, if redirect not needed. False, if redirect
 *		not needed or the string of the URL
 */
function redirect_canonical($requested_url = null, $do_redirect = true)
{
    global $wp_rewrite, $is_IIS, $wp_query, $wpdb;
    if (is_trackback() || is_search() || is_comments_popup() || is_admin() || $is_IIS || isset($_POST) && count($_POST) || is_preview() || is_robots()) {
        return;
    }
    if (!$requested_url) {
        // build the URL in the address bar
        $requested_url = is_ssl() ? 'https://' : 'http://';
        $requested_url .= $_SERVER['HTTP_HOST'];
        $requested_url .= $_SERVER['REQUEST_URI'];
    }
    $original = @parse_url($requested_url);
    if (false === $original) {
        return;
    }
    // Some PHP setups turn requests for / into /index.php in REQUEST_URI
    // See: http://trac.wordpress.org/ticket/5017
    // See: http://trac.wordpress.org/ticket/7173
    // Disabled, for now:
    // $original['path'] = preg_replace('|/index\.php$|', '/', $original['path']);
    $redirect = $original;
    $redirect_url = false;
    // Notice fixing
    if (!isset($redirect['path'])) {
        $redirect['path'] = '';
    }
    if (!isset($redirect['query'])) {
        $redirect['query'] = '';
    }
    if (is_singular() && 1 > $wp_query->post_count && ($id = get_query_var('p'))) {
        $vars = $wpdb->get_results($wpdb->prepare("SELECT post_type, post_parent FROM {$wpdb->posts} WHERE ID = %d", $id));
        if (isset($vars[0]) && ($vars = $vars[0])) {
            if ('revision' == $vars->post_type && $vars->post_parent > 0) {
                $id = $vars->post_parent;
            }
            if ($redirect_url = get_permalink($id)) {
                $redirect['query'] = remove_query_arg(array('p', 'page_id', 'attachment_id', 'post_type'), $redirect['query']);
            }
        }
    }
    // These tests give us a WP-generated permalink
    if (is_404()) {
        // Redirect ?page_id, ?p=, ?attachment_id= to their respective url's
        $id = max(get_query_var('p'), get_query_var('page_id'), get_query_var('attachment_id'));
        if ($id && ($redirect_post = get_post($id))) {
            $post_type_obj = get_post_type_object($redirect_post->post_type);
            if ($post_type_obj->public) {
                $redirect_url = get_permalink($redirect_post);
                $redirect['query'] = remove_query_arg(array('p', 'page_id', 'attachment_id', 'post_type'), $redirect['query']);
            }
        }
        if (!$redirect_url) {
            $redirect_url = redirect_guess_404_permalink();
        }
    } elseif (is_object($wp_rewrite) && $wp_rewrite->using_permalinks()) {
        // rewriting of old ?p=X, ?m=2004, ?m=200401, ?m=20040101
        if (is_attachment() && !empty($_GET['attachment_id']) && !$redirect_url) {
            if ($redirect_url = get_attachment_link(get_query_var('attachment_id'))) {
                $redirect['query'] = remove_query_arg('attachment_id', $redirect['query']);
            }
        } elseif (is_single() && !empty($_GET['p']) && !$redirect_url) {
            if ($redirect_url = get_permalink(get_query_var('p'))) {
                $redirect['query'] = remove_query_arg(array('p', 'post_type'), $redirect['query']);
            }
            if (get_query_var('page')) {
                $redirect_url = trailingslashit($redirect_url) . user_trailingslashit(get_query_var('page'), 'single_paged');
                $redirect['query'] = remove_query_arg('page', $redirect['query']);
            }
        } elseif (is_single() && !empty($_GET['name']) && !$redirect_url) {
            if ($redirect_url = get_permalink($wp_query->get_queried_object_id())) {
                $redirect['query'] = remove_query_arg('name', $redirect['query']);
            }
        } elseif (is_page() && !empty($_GET['page_id']) && !$redirect_url) {
            if ($redirect_url = get_permalink(get_query_var('page_id'))) {
                $redirect['query'] = remove_query_arg('page_id', $redirect['query']);
            }
        } elseif (is_page() && !is_feed() && isset($wp_query->queried_object) && 'page' == get_option('show_on_front') && $wp_query->queried_object->ID == get_option('page_on_front') && !$redirect_url) {
            $redirect_url = home_url('/');
        } elseif (is_home() && !empty($_GET['page_id']) && 'page' == get_option('show_on_front') && get_query_var('page_id') == get_option('page_for_posts') && !$redirect_url) {
            if ($redirect_url = get_permalink(get_option('page_for_posts'))) {
                $redirect['query'] = remove_query_arg('page_id', $redirect['query']);
            }
        } elseif (!empty($_GET['m']) && (is_year() || is_month() || is_day())) {
            $m = get_query_var('m');
            switch (strlen($m)) {
                case 4:
                    // Yearly
                    $redirect_url = get_year_link($m);
                    break;
                case 6:
                    // Monthly
                    $redirect_url = get_month_link(substr($m, 0, 4), substr($m, 4, 2));
                    break;
                case 8:
                    // Daily
                    $redirect_url = get_day_link(substr($m, 0, 4), substr($m, 4, 2), substr($m, 6, 2));
                    break;
            }
            if ($redirect_url) {
                $redirect['query'] = remove_query_arg('m', $redirect['query']);
            }
            // now moving on to non ?m=X year/month/day links
        } elseif (is_day() && get_query_var('year') && get_query_var('monthnum') && !empty($_GET['day'])) {
            if ($redirect_url = get_day_link(get_query_var('year'), get_query_var('monthnum'), get_query_var('day'))) {
                $redirect['query'] = remove_query_arg(array('year', 'monthnum', 'day'), $redirect['query']);
            }
        } elseif (is_month() && get_query_var('year') && !empty($_GET['monthnum'])) {
            if ($redirect_url = get_month_link(get_query_var('year'), get_query_var('monthnum'))) {
                $redirect['query'] = remove_query_arg(array('year', 'monthnum'), $redirect['query']);
            }
        } elseif (is_year() && !empty($_GET['year'])) {
            if ($redirect_url = get_year_link(get_query_var('year'))) {
                $redirect['query'] = remove_query_arg('year', $redirect['query']);
            }
        } elseif (is_author() && !empty($_GET['author']) && preg_match('|^[0-9]+$|', $_GET['author'])) {
            $author = get_userdata(get_query_var('author'));
            if (false !== $author && ($redirect_url = get_author_posts_url($author->ID, $author->user_nicename))) {
                $redirect['query'] = remove_query_arg('author', $redirect['query']);
            }
        } elseif (is_category() || is_tag() || is_tax()) {
            // Terms (Tags/categories)
            $term_count = 0;
            foreach (array('category__in', 'category__not_in', 'category__and', 'post__in', 'post__not_in', 'tag__in', 'tag__not_in', 'tag__and', 'tag_slug__in', 'tag_slug__and') as $key) {
                $term_count += count($wp_query->query_vars[$key]);
            }
            $obj = $wp_query->get_queried_object();
            if ($term_count <= 1 && !empty($obj->term_id) && ($tax_url = get_term_link((int) $obj->term_id, $obj->taxonomy)) && !is_wp_error($tax_url)) {
                if (is_category()) {
                    $redirect['query'] = remove_query_arg(array('category_name', 'category', 'cat'), $redirect['query']);
                } elseif (is_tag()) {
                    $redirect['query'] = remove_query_arg(array('tag', 'tag_id'), $redirect['query']);
                } elseif (is_tax()) {
                    // Custom taxonomies will have a custom query var, remove those too:
                    $tax = get_taxonomy($obj->taxonomy);
                    if (false !== $tax->query_var) {
                        $redirect['query'] = remove_query_arg($tax->query_var, $redirect['query']);
                    } else {
                        $redirect['query'] = remove_query_arg(array('term', 'taxonomy'), $redirect['query']);
                    }
                }
                $tax_url = parse_url($tax_url);
                if (!empty($tax_url['query'])) {
                    // Custom taxonomies may only be accessable via ?taxonomy=..&term=..
                    parse_str($tax_url['query'], $query_vars);
                    $redirect['query'] = add_query_arg($query_vars, $redirect['query']);
                } else {
                    // Taxonomy is accessable via a "pretty-URL"
                    $redirect['path'] = $tax_url['path'];
                }
            }
        } elseif (is_single() && strpos($wp_rewrite->permalink_structure, '%category%') !== false) {
            $category = get_term_by('slug', get_query_var('category_name'), 'category');
            $post_terms = wp_get_object_terms($wp_query->get_queried_object_id(), 'category', array('fields' => 'tt_ids'));
            if (!$category || is_wp_error($category) || !is_wp_error($post_terms) && !empty($post_terms) && !in_array($category->term_taxonomy_id, $post_terms)) {
                $redirect_url = get_permalink($wp_query->get_queried_object_id());
            }
        }
        // paging and feeds
        if (get_query_var('paged') || is_feed() || get_query_var('cpage')) {
            if (!$redirect_url) {
                $redirect_url = $requested_url;
            }
            $paged_redirect = @parse_url($redirect_url);
            while (preg_match('#/page/?[0-9]+?(/+)?$#', $paged_redirect['path']) || preg_match('#/(comments/?)?(feed|rss|rdf|atom|rss2)(/+)?$#', $paged_redirect['path']) || preg_match('#/comment-page-[0-9]+(/+)?$#', $paged_redirect['path'])) {
                // Strip off paging and feed
                $paged_redirect['path'] = preg_replace('#/page/?[0-9]+?(/+)?$#', '/', $paged_redirect['path']);
                // strip off any existing paging
                $paged_redirect['path'] = preg_replace('#/(comments/?)?(feed|rss2?|rdf|atom)(/+|$)#', '/', $paged_redirect['path']);
                // strip off feed endings
                $paged_redirect['path'] = preg_replace('#/comment-page-[0-9]+?(/+)?$#', '/', $paged_redirect['path']);
                // strip off any existing comment paging
            }
            $addl_path = '';
            if (is_feed()) {
                $addl_path = !empty($addl_path) ? trailingslashit($addl_path) : '';
                if (get_query_var('withcomments')) {
                    $addl_path .= 'comments/';
                }
                $addl_path .= user_trailingslashit('feed/' . (get_default_feed() == get_query_var('feed') || 'feed' == get_query_var('feed') ? '' : get_query_var('feed')), 'feed');
                $redirect['query'] = remove_query_arg('feed', $redirect['query']);
            }
            if (get_query_var('paged') > 0) {
                $paged = get_query_var('paged');
                $redirect['query'] = remove_query_arg('paged', $redirect['query']);
                if (!is_feed()) {
                    if ($paged > 1 && !is_single()) {
                        $addl_path = (!empty($addl_path) ? trailingslashit($addl_path) : '') . user_trailingslashit("page/{$paged}", 'paged');
                    } elseif (!is_single()) {
                        $addl_path = !empty($addl_path) ? trailingslashit($addl_path) : '';
                    }
                } elseif ($paged > 1) {
                    $redirect['query'] = add_query_arg('paged', $paged, $redirect['query']);
                }
            }
            if (get_option('page_comments') && ('newest' == get_option('default_comments_page') && get_query_var('cpage') > 0 || 'newest' != get_option('default_comments_page') && get_query_var('cpage') > 1)) {
                $addl_path = (!empty($addl_path) ? trailingslashit($addl_path) : '') . user_trailingslashit('comment-page-' . get_query_var('cpage'), 'commentpaged');
                $redirect['query'] = remove_query_arg('cpage', $redirect['query']);
            }
            $paged_redirect['path'] = user_trailingslashit(preg_replace('|/index.php/?$|', '/', $paged_redirect['path']));
            // strip off trailing /index.php/
            if (!empty($addl_path) && $wp_rewrite->using_index_permalinks() && strpos($paged_redirect['path'], '/index.php/') === false) {
                $paged_redirect['path'] = trailingslashit($paged_redirect['path']) . 'index.php/';
            }
            if (!empty($addl_path)) {
                $paged_redirect['path'] = trailingslashit($paged_redirect['path']) . $addl_path;
            }
            $redirect_url = $paged_redirect['scheme'] . '://' . $paged_redirect['host'] . $paged_redirect['path'];
            $redirect['path'] = $paged_redirect['path'];
        }
    }
    // tack on any additional query vars
    $redirect['query'] = preg_replace('#^\\??&*?#', '', $redirect['query']);
    if ($redirect_url && !empty($redirect['query'])) {
        if (strpos($redirect_url, '?') !== false) {
            $redirect_url .= '&';
        } else {
            $redirect_url .= '?';
        }
        $redirect_url .= $redirect['query'];
    }
    if ($redirect_url) {
        $redirect = @parse_url($redirect_url);
    }
    // www.example.com vs example.com
    $user_home = @parse_url(home_url());
    if (!empty($user_home['host'])) {
        $redirect['host'] = $user_home['host'];
    }
    if (empty($user_home['path'])) {
        $user_home['path'] = '/';
    }
    // Handle ports
    if (!empty($user_home['port'])) {
        $redirect['port'] = $user_home['port'];
    } else {
        unset($redirect['port']);
    }
    // trailing /index.php
    $redirect['path'] = preg_replace('|/index.php/*?$|', '/', $redirect['path']);
    // Remove trailing spaces from the path
    $redirect['path'] = preg_replace('#(%20| )+$#', '', $redirect['path']);
    if (!empty($redirect['query'])) {
        // Remove trailing spaces from certain terminating query string args
        $redirect['query'] = preg_replace('#((p|page_id|cat|tag)=[^&]*?)(%20| )+$#', '$1', $redirect['query']);
        // Clean up empty query strings
        $redirect['query'] = trim(preg_replace('#(^|&)(p|page_id|cat|tag)=?(&|$)#', '&', $redirect['query']), '&');
        // Remove redundant leading ampersands
        $redirect['query'] = preg_replace('#^\\??&*?#', '', $redirect['query']);
    }
    // strip /index.php/ when we're not using PATHINFO permalinks
    if (!$wp_rewrite->using_index_permalinks()) {
        $redirect['path'] = str_replace('/index.php/', '/', $redirect['path']);
    }
    // trailing slashes
    if (is_object($wp_rewrite) && $wp_rewrite->using_permalinks() && !is_404() && (!is_front_page() || is_front_page() && get_query_var('paged') > 1)) {
        $user_ts_type = '';
        if (get_query_var('paged') > 0) {
            $user_ts_type = 'paged';
        } else {
            foreach (array('single', 'category', 'page', 'day', 'month', 'year', 'home') as $type) {
                $func = 'is_' . $type;
                if (call_user_func($func)) {
                    $user_ts_type = $type;
                    break;
                }
            }
        }
        $redirect['path'] = user_trailingslashit($redirect['path'], $user_ts_type);
    } elseif (is_front_page()) {
        $redirect['path'] = trailingslashit($redirect['path']);
    }
    // Strip multiple slashes out of the URL
    if (strpos($redirect['path'], '//') > -1) {
        $redirect['path'] = preg_replace('|/+|', '/', $redirect['path']);
    }
    // Always trailing slash the Front Page URL
    if (trailingslashit($redirect['path']) == trailingslashit($user_home['path'])) {
        $redirect['path'] = trailingslashit($redirect['path']);
    }
    // Ignore differences in host capitalization, as this can lead to infinite redirects
    // Only redirect no-www <=> yes-www
    if (strtolower($original['host']) == strtolower($redirect['host']) || strtolower($original['host']) != 'www.' . strtolower($redirect['host']) && 'www.' . strtolower($original['host']) != strtolower($redirect['host'])) {
        $redirect['host'] = $original['host'];
    }
    $compare_original = array($original['host'], $original['path']);
    if (!empty($original['port'])) {
        $compare_original[] = $original['port'];
    }
    if (!empty($original['query'])) {
        $compare_original[] = $original['query'];
    }
    $compare_redirect = array($redirect['host'], $redirect['path']);
    if (!empty($redirect['port'])) {
        $compare_redirect[] = $redirect['port'];
    }
    if (!empty($redirect['query'])) {
        $compare_redirect[] = $redirect['query'];
    }
    if ($compare_original !== $compare_redirect) {
        $redirect_url = $redirect['scheme'] . '://' . $redirect['host'];
        if (!empty($redirect['port'])) {
            $redirect_url .= ':' . $redirect['port'];
        }
        $redirect_url .= $redirect['path'];
        if (!empty($redirect['query'])) {
            $redirect_url .= '?' . $redirect['query'];
        }
    }
    if (!$redirect_url || $redirect_url == $requested_url) {
        return false;
    }
    // Note that you can use the "redirect_canonical" filter to cancel a canonical redirect for whatever reason by returning FALSE
    $redirect_url = apply_filters('redirect_canonical', $redirect_url, $requested_url);
    if (!$redirect_url || $redirect_url == $requested_url) {
        // yes, again -- in case the filter aborted the request
        return false;
    }
    if ($do_redirect) {
        // protect against chained redirects
        if (!redirect_canonical($redirect_url, false)) {
            wp_redirect($redirect_url, 301);
            exit;
        } else {
            // Debug
            // die("1: $redirect_url<br />2: " . redirect_canonical( $redirect_url, false ) );
            return false;
        }
    } else {
        return $redirect_url;
    }
}
Example #13
0
 /**
  * Parses a Facetious query string such as '/keyword/hello+world/foo/bar/' and returns its
  * corresponding query variables
  *
  * @param $query string A Facetious query string
  * @return array An associative array of query variables
  * @author John Blackbourn
  **/
 function parse_search($query)
 {
     $return = array();
     $parts = explode('/', $query);
     # Strip accidental empty parts (such as '/foo//bar/'):
     $parts = array_filter($parts);
     $parts = array_values($parts);
     # If we've got a trailing '/feed/' we need to push the default feed name onto the end
     if ('feed' == end($parts)) {
         array_push($parts, get_default_feed());
     }
     # If we've got an odd number of parts then the first part is the keyword search so we prepend the 's' part.
     if (count($parts) % 2) {
         array_unshift($parts, 's');
     }
     # Loop over every even-indexed part and populate our query variable array
     for ($i = 0; $i < count($parts); $i = $i + 2) {
         $key = $this->get_search_var($parts[$i]);
         $val = $this->decode($parts[$i + 1]);
         $return[$key] = $val;
     }
     return $return;
 }
function get_search_comments_feed_link($search_query = '', $feed = '')
{
    if (empty($search_query)) {
        $search = attribute_escape(get_search_query());
    } else {
        $search = attribute_escape(stripslashes($search_query));
    }
    if (empty($feed)) {
        $feed = get_default_feed();
    }
    $link = get_option('home') . "?s={$search}&amp;feed=comments-{$feed}";
    $link = apply_filters('search_feed_link', $link);
    return $link;
}
Example #15
0
 /**
  * Sends additional HTTP headers for caching, content type, etc.
  *
  * Sets the Content-Type header. Sets the 'error' status (if passed) and optionally exits.
  * If showing a feed, it will also send Last-Modified, ETag, and 304 status if needed.
  *
  * @since 2.0.0
  * @since 4.4.0 `X-Pingback` header is added conditionally after posts have been queried in handle_404().
  * @access public
  */
 public function send_headers()
 {
     $headers = array();
     $status = null;
     $exit_required = false;
     if (is_user_logged_in()) {
         $headers = array_merge($headers, wp_get_nocache_headers());
     }
     if (!empty($this->query_vars['error'])) {
         $status = (int) $this->query_vars['error'];
         if (404 === $status) {
             if (!is_user_logged_in()) {
                 $headers = array_merge($headers, wp_get_nocache_headers());
             }
             $headers['Content-Type'] = get_option('html_type') . '; charset=' . get_option('blog_charset');
         } elseif (in_array($status, array(403, 500, 502, 503))) {
             $exit_required = true;
         }
     } elseif (empty($this->query_vars['feed'])) {
         $headers['Content-Type'] = get_option('html_type') . '; charset=' . get_option('blog_charset');
     } else {
         // Set the correct content type for feeds
         $type = $this->query_vars['feed'];
         if ('feed' == $this->query_vars['feed']) {
             $type = get_default_feed();
         }
         $headers['Content-Type'] = feed_content_type($type) . '; charset=' . get_option('blog_charset');
         // We're showing a feed, so WP is indeed the only thing that last changed
         if (!empty($this->query_vars['withcomments']) || false !== strpos($this->query_vars['feed'], 'comments-') || empty($this->query_vars['withoutcomments']) && (!empty($this->query_vars['p']) || !empty($this->query_vars['name']) || !empty($this->query_vars['page_id']) || !empty($this->query_vars['pagename']) || !empty($this->query_vars['attachment']) || !empty($this->query_vars['attachment_id']))) {
             $wp_last_modified = mysql2date('D, d M Y H:i:s', get_lastcommentmodified('GMT'), 0) . ' GMT';
         } else {
             $wp_last_modified = mysql2date('D, d M Y H:i:s', get_lastpostmodified('GMT'), 0) . ' GMT';
         }
         $wp_etag = '"' . md5($wp_last_modified) . '"';
         $headers['Last-Modified'] = $wp_last_modified;
         $headers['ETag'] = $wp_etag;
         // Support for Conditional GET
         if (isset($_SERVER['HTTP_IF_NONE_MATCH'])) {
             $client_etag = wp_unslash($_SERVER['HTTP_IF_NONE_MATCH']);
         } else {
             $client_etag = false;
         }
         $client_last_modified = empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? '' : trim($_SERVER['HTTP_IF_MODIFIED_SINCE']);
         // If string is empty, return 0. If not, attempt to parse into a timestamp
         $client_modified_timestamp = $client_last_modified ? strtotime($client_last_modified) : 0;
         // Make a timestamp for our most recent modification...
         $wp_modified_timestamp = strtotime($wp_last_modified);
         if ($client_last_modified && $client_etag ? $client_modified_timestamp >= $wp_modified_timestamp && $client_etag == $wp_etag : $client_modified_timestamp >= $wp_modified_timestamp || $client_etag == $wp_etag) {
             $status = 304;
             $exit_required = true;
         }
     }
     /**
      * Filter the HTTP headers before they're sent to the browser.
      *
      * @since 2.8.0
      *
      * @param array $headers The list of headers to be sent.
      * @param WP    $this    Current WordPress environment instance.
      */
     $headers = apply_filters('wp_headers', $headers, $this);
     if (!empty($status)) {
         status_header($status);
     }
     // If Last-Modified is set to false, it should not be sent (no-cache situation).
     if (isset($headers['Last-Modified']) && false === $headers['Last-Modified']) {
         unset($headers['Last-Modified']);
         // In PHP 5.3+, make sure we are not sending a Last-Modified header.
         if (function_exists('header_remove')) {
             @header_remove('Last-Modified');
         } else {
             // In PHP 5.2, send an empty Last-Modified header, but only as a
             // last resort to override a header already sent. #WP23021
             foreach (headers_list() as $header) {
                 if (0 === stripos($header, 'Last-Modified')) {
                     $headers['Last-Modified'] = '';
                     break;
                 }
             }
         }
     }
     foreach ((array) $headers as $name => $field_value) {
         @header("{$name}: {$field_value}");
     }
     if ($exit_required) {
         exit;
     }
     /**
      * Fires once the requested HTTP headers for caching, content type, etc. have been sent.
      *
      * @since 2.1.0
      *
      * @param WP &$this Current WordPress environment instance (passed by reference).
      */
     do_action_ref_array('send_headers', array(&$this));
 }
Example #16
0
/**
 * Load the feed template from the use of an action hook.
 *
 * If the feed action does not have a hook, then the function will die with a
 * message telling the visitor that the feed is not valid.
 *
 * It is better to only have one hook for each feed.
 *
 * @since 2.1.0
 *
 * @global WP_Query $wp_query Used to tell if the use a comment feed.
 */
function do_feed()
{
    global $wp_query;
    $feed = get_query_var('feed');
    // Remove the pad, if present.
    $feed = preg_replace('/^_+/', '', $feed);
    if ($feed == '' || $feed == 'feed') {
        $feed = get_default_feed();
    }
    if (!has_action("do_feed_{$feed}")) {
        wp_die(__('ERROR: This is not a valid feed template.'), '', array('response' => 404));
    }
    /**
     * Fires once the given feed is loaded.
     *
     * The dynamic portion of the hook name, `$feed`, refers to the feed template name.
     * Possible values include: 'rdf', 'rss', 'rss2', and 'atom'.
     *
     * @since 2.1.0
     * @since 4.4.0 The `$feed` parameter was added.
     *
     * @param bool   $is_comment_feed Whether the feed is a comment feed.
     * @param string $feed            The feed name.
     */
    do_action("do_feed_{$feed}", $wp_query->is_comment_feed, $feed);
}
Example #17
0
/**
 * Retrieve the permalink for the comments feed of the search results.
 *
 * @since 2.5.0
 *
 * @param string $search_query Optional. Search query.
 * @param string $feed Optional. Feed type.
 * @return string
 */
function get_search_comments_feed_link($search_query = '', $feed = '')
{
    global $wp_rewrite;
    if (empty($feed)) {
        $feed = get_default_feed();
    }
    $link = get_search_feed_link($search_query, $feed);
    $permastruct = $wp_rewrite->get_search_permastruct();
    if (empty($permastruct)) {
        $link = add_query_arg('feed', 'comments-' . $feed, $link);
    } else {
        $link = add_query_arg('withcomments', 1, $link);
    }
    $link = apply_filters('search_feed_link', $link, $feed, 'comments');
    return $link;
}
Example #18
0
/**
 * Redirects incoming links to the proper URL based on the site url.
 *
 * Search engines consider www.somedomain.com and somedomain.com to be two
 * different URLs when they both go to the same location. This SEO enhancement
 * prevents penalty for duplicate content by redirecting all incoming links to
 * one or the other.
 *
 * Prevents redirection for feeds, trackbacks, searches, comment popup, and
 * admin URLs. Does not redirect on non-pretty-permalink-supporting IIS 7+,
 * page/post previews, WP admin, Trackbacks, robots.txt, searches, or on POST
 * requests.
 *
 * Will also attempt to find the correct link when a user enters a URL that does
 * not exist based on exact WordPress query. Will instead try to parse the URL
 * or query in an attempt to figure the correct page to go to.
 *
 * @since 2.3.0
 *
 * @global WP_Rewrite $wp_rewrite
 * @global bool $is_IIS
 * @global WP_Query $wp_query
 * @global wpdb $wpdb WordPress database abstraction object.
 *
 * @param string $requested_url Optional. The URL that was requested, used to
 *		figure if redirect is needed.
 * @param bool $do_redirect Optional. Redirect to the new URL.
 * @return string|void The string of the URL, if redirect needed.
 */
function redirect_canonical($requested_url = null, $do_redirect = true)
{
    global $wp_rewrite, $is_IIS, $wp_query, $wpdb, $wp;
    if (isset($_SERVER['REQUEST_METHOD']) && !in_array(strtoupper($_SERVER['REQUEST_METHOD']), array('GET', 'HEAD'))) {
        return;
    }
    // If we're not in wp-admin and the post has been published and preview nonce
    // is non-existent or invalid then no need for preview in query
    if (is_preview() && get_query_var('p') && 'publish' == get_post_status(get_query_var('p'))) {
        if (!isset($_GET['preview_id']) || !isset($_GET['preview_nonce']) || !wp_verify_nonce($_GET['preview_nonce'], 'post_preview_' . (int) $_GET['preview_id'])) {
            $wp_query->is_preview = false;
        }
    }
    if (is_trackback() || is_search() || is_comments_popup() || is_admin() || is_preview() || is_robots() || $is_IIS && !iis7_supports_permalinks()) {
        return;
    }
    if (!$requested_url && isset($_SERVER['HTTP_HOST'])) {
        // build the URL in the address bar
        $requested_url = is_ssl() ? 'https://' : 'http://';
        $requested_url .= $_SERVER['HTTP_HOST'];
        $requested_url .= $_SERVER['REQUEST_URI'];
    }
    $original = @parse_url($requested_url);
    if (false === $original) {
        return;
    }
    $redirect = $original;
    $redirect_url = false;
    // Notice fixing
    if (!isset($redirect['path'])) {
        $redirect['path'] = '';
    }
    if (!isset($redirect['query'])) {
        $redirect['query'] = '';
    }
    // If the original URL ended with non-breaking spaces, they were almost
    // certainly inserted by accident. Let's remove them, so the reader doesn't
    // see a 404 error with no obvious cause.
    $redirect['path'] = preg_replace('|(%C2%A0)+$|i', '', $redirect['path']);
    // It's not a preview, so remove it from URL
    if (get_query_var('preview')) {
        $redirect['query'] = remove_query_arg('preview', $redirect['query']);
    }
    if (is_feed() && ($id = get_query_var('p'))) {
        if ($redirect_url = get_post_comments_feed_link($id, get_query_var('feed'))) {
            $redirect['query'] = _remove_qs_args_if_not_in_url($redirect['query'], array('p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type', 'feed'), $redirect_url);
            $redirect['path'] = parse_url($redirect_url, PHP_URL_PATH);
        }
    }
    if (is_singular() && 1 > $wp_query->post_count && ($id = get_query_var('p'))) {
        $vars = $wpdb->get_results($wpdb->prepare("SELECT post_type, post_parent FROM {$wpdb->posts} WHERE ID = %d", $id));
        if (isset($vars[0]) && ($vars = $vars[0])) {
            if ('revision' == $vars->post_type && $vars->post_parent > 0) {
                $id = $vars->post_parent;
            }
            if ($redirect_url = get_permalink($id)) {
                $redirect['query'] = _remove_qs_args_if_not_in_url($redirect['query'], array('p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type'), $redirect_url);
            }
        }
    }
    // These tests give us a WP-generated permalink
    if (is_404()) {
        // Redirect ?page_id, ?p=, ?attachment_id= to their respective url's
        $id = max(get_query_var('p'), get_query_var('page_id'), get_query_var('attachment_id'));
        if ($id && ($redirect_post = get_post($id))) {
            $post_type_obj = get_post_type_object($redirect_post->post_type);
            if ($post_type_obj->public) {
                $redirect_url = get_permalink($redirect_post);
                $redirect['query'] = _remove_qs_args_if_not_in_url($redirect['query'], array('p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type'), $redirect_url);
            }
        }
        if (get_query_var('day') && get_query_var('monthnum') && get_query_var('year')) {
            $year = get_query_var('year');
            $month = get_query_var('monthnum');
            $day = get_query_var('day');
            $date = sprintf('%04d-%02d-%02d', $year, $month, $day);
            if (!wp_checkdate($month, $day, $year, $date)) {
                $redirect_url = get_month_link($year, $month);
                $redirect['query'] = _remove_qs_args_if_not_in_url($redirect['query'], array('year', 'monthnum', 'day'), $redirect_url);
            }
        } elseif (get_query_var('monthnum') && get_query_var('year') && 12 < get_query_var('monthnum')) {
            $redirect_url = get_year_link(get_query_var('year'));
            $redirect['query'] = _remove_qs_args_if_not_in_url($redirect['query'], array('year', 'monthnum'), $redirect_url);
        }
        if (!$redirect_url) {
            if ($redirect_url = redirect_guess_404_permalink()) {
                $redirect['query'] = _remove_qs_args_if_not_in_url($redirect['query'], array('page', 'feed', 'p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type'), $redirect_url);
            }
        }
        if (get_query_var('page') && $wp_query->post && false !== strpos($wp_query->post->post_content, '<!--nextpage-->')) {
            $redirect['path'] = rtrim($redirect['path'], (int) get_query_var('page') . '/');
            $redirect['query'] = remove_query_arg('page', $redirect['query']);
            $redirect_url = get_permalink($wp_query->post->ID);
        }
    } elseif (is_object($wp_rewrite) && $wp_rewrite->using_permalinks()) {
        // rewriting of old ?p=X, ?m=2004, ?m=200401, ?m=20040101
        if (is_attachment() && !array_diff(array_keys($wp->query_vars), array('attachment', 'attachment_id')) && !$redirect_url) {
            if (!empty($_GET['attachment_id'])) {
                $redirect_url = get_attachment_link(get_query_var('attachment_id'));
                if ($redirect_url) {
                    $redirect['query'] = remove_query_arg('attachment_id', $redirect['query']);
                }
            } else {
                $redirect_url = get_attachment_link();
            }
        } elseif (is_single() && !empty($_GET['p']) && !$redirect_url) {
            if ($redirect_url = get_permalink(get_query_var('p'))) {
                $redirect['query'] = remove_query_arg(array('p', 'post_type'), $redirect['query']);
            }
        } elseif (is_single() && !empty($_GET['name']) && !$redirect_url) {
            if ($redirect_url = get_permalink($wp_query->get_queried_object_id())) {
                $redirect['query'] = remove_query_arg('name', $redirect['query']);
            }
        } elseif (is_page() && !empty($_GET['page_id']) && !$redirect_url) {
            if ($redirect_url = get_permalink(get_query_var('page_id'))) {
                $redirect['query'] = remove_query_arg('page_id', $redirect['query']);
            }
        } elseif (is_page() && !is_feed() && isset($wp_query->queried_object) && 'page' == get_option('show_on_front') && $wp_query->queried_object->ID == get_option('page_on_front') && !$redirect_url) {
            $redirect_url = home_url('/');
        } elseif (is_home() && !empty($_GET['page_id']) && 'page' == get_option('show_on_front') && get_query_var('page_id') == get_option('page_for_posts') && !$redirect_url) {
            if ($redirect_url = get_permalink(get_option('page_for_posts'))) {
                $redirect['query'] = remove_query_arg('page_id', $redirect['query']);
            }
        } elseif (!empty($_GET['m']) && (is_year() || is_month() || is_day())) {
            $m = get_query_var('m');
            switch (strlen($m)) {
                case 4:
                    // Yearly
                    $redirect_url = get_year_link($m);
                    break;
                case 6:
                    // Monthly
                    $redirect_url = get_month_link(substr($m, 0, 4), substr($m, 4, 2));
                    break;
                case 8:
                    // Daily
                    $redirect_url = get_day_link(substr($m, 0, 4), substr($m, 4, 2), substr($m, 6, 2));
                    break;
            }
            if ($redirect_url) {
                $redirect['query'] = remove_query_arg('m', $redirect['query']);
            }
            // now moving on to non ?m=X year/month/day links
        } elseif (is_day() && get_query_var('year') && get_query_var('monthnum') && !empty($_GET['day'])) {
            if ($redirect_url = get_day_link(get_query_var('year'), get_query_var('monthnum'), get_query_var('day'))) {
                $redirect['query'] = remove_query_arg(array('year', 'monthnum', 'day'), $redirect['query']);
            }
        } elseif (is_month() && get_query_var('year') && !empty($_GET['monthnum'])) {
            if ($redirect_url = get_month_link(get_query_var('year'), get_query_var('monthnum'))) {
                $redirect['query'] = remove_query_arg(array('year', 'monthnum'), $redirect['query']);
            }
        } elseif (is_year() && !empty($_GET['year'])) {
            if ($redirect_url = get_year_link(get_query_var('year'))) {
                $redirect['query'] = remove_query_arg('year', $redirect['query']);
            }
        } elseif (is_author() && !empty($_GET['author']) && preg_match('|^[0-9]+$|', $_GET['author'])) {
            $author = get_userdata(get_query_var('author'));
            if (false !== $author && $wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->posts} WHERE {$wpdb->posts}.post_author = %d AND {$wpdb->posts}.post_status = 'publish' LIMIT 1", $author->ID))) {
                if ($redirect_url = get_author_posts_url($author->ID, $author->user_nicename)) {
                    $redirect['query'] = remove_query_arg('author', $redirect['query']);
                }
            }
        } elseif (is_category() || is_tag() || is_tax()) {
            // Terms (Tags/categories)
            $term_count = 0;
            foreach ($wp_query->tax_query->queried_terms as $tax_query) {
                $term_count += count($tax_query['terms']);
            }
            $obj = $wp_query->get_queried_object();
            if ($term_count <= 1 && !empty($obj->term_id) && ($tax_url = get_term_link((int) $obj->term_id, $obj->taxonomy)) && !is_wp_error($tax_url)) {
                if (!empty($redirect['query'])) {
                    // Strip taxonomy query vars off the url.
                    $qv_remove = array('term', 'taxonomy');
                    if (is_category()) {
                        $qv_remove[] = 'category_name';
                        $qv_remove[] = 'cat';
                    } elseif (is_tag()) {
                        $qv_remove[] = 'tag';
                        $qv_remove[] = 'tag_id';
                    } else {
                        // Custom taxonomies will have a custom query var, remove those too:
                        $tax_obj = get_taxonomy($obj->taxonomy);
                        if (false !== $tax_obj->query_var) {
                            $qv_remove[] = $tax_obj->query_var;
                        }
                    }
                    $rewrite_vars = array_diff(array_keys($wp_query->query), array_keys($_GET));
                    if (!array_diff($rewrite_vars, array_keys($_GET))) {
                        // Check to see if all the Query vars are coming from the rewrite, none are set via $_GET
                        $redirect['query'] = remove_query_arg($qv_remove, $redirect['query']);
                        //Remove all of the per-tax qv's
                        // Create the destination url for this taxonomy
                        $tax_url = parse_url($tax_url);
                        if (!empty($tax_url['query'])) {
                            // Taxonomy accessible via ?taxonomy=..&term=.. or any custom qv..
                            parse_str($tax_url['query'], $query_vars);
                            $redirect['query'] = add_query_arg($query_vars, $redirect['query']);
                        } else {
                            // Taxonomy is accessible via a "pretty-URL"
                            $redirect['path'] = $tax_url['path'];
                        }
                    } else {
                        // Some query vars are set via $_GET. Unset those from $_GET that exist via the rewrite
                        foreach ($qv_remove as $_qv) {
                            if (isset($rewrite_vars[$_qv])) {
                                $redirect['query'] = remove_query_arg($_qv, $redirect['query']);
                            }
                        }
                    }
                }
            }
        } elseif (is_single() && strpos($wp_rewrite->permalink_structure, '%category%') !== false && ($cat = get_query_var('category_name'))) {
            $category = get_category_by_path($cat);
            $post_terms = wp_get_object_terms($wp_query->get_queried_object_id(), 'category', array('fields' => 'tt_ids'));
            if (!$category || is_wp_error($category) || !is_wp_error($post_terms) && !empty($post_terms) && !in_array($category->term_taxonomy_id, $post_terms)) {
                $redirect_url = get_permalink($wp_query->get_queried_object_id());
            }
        }
        // Post Paging
        if (is_singular() && !is_front_page() && get_query_var('page')) {
            if (!$redirect_url) {
                $redirect_url = get_permalink(get_queried_object_id());
            }
            $redirect_url = trailingslashit($redirect_url) . user_trailingslashit(get_query_var('page'), 'single_paged');
            $redirect['query'] = remove_query_arg('page', $redirect['query']);
        }
        // paging and feeds
        if (get_query_var('paged') || is_feed() || get_query_var('cpage')) {
            while (preg_match("#/{$wp_rewrite->pagination_base}/?[0-9]+?(/+)?\$#", $redirect['path']) || preg_match('#/(comments/?)?(feed|rss|rdf|atom|rss2)(/+)?$#', $redirect['path']) || preg_match("#/{$wp_rewrite->comments_pagination_base}-[0-9]+(/+)?\$#", $redirect['path'])) {
                // Strip off paging and feed
                $redirect['path'] = preg_replace("#/{$wp_rewrite->pagination_base}/?[0-9]+?(/+)?\$#", '/', $redirect['path']);
                // strip off any existing paging
                $redirect['path'] = preg_replace('#/(comments/?)?(feed|rss2?|rdf|atom)(/+|$)#', '/', $redirect['path']);
                // strip off feed endings
                $redirect['path'] = preg_replace("#/{$wp_rewrite->comments_pagination_base}-[0-9]+?(/+)?\$#", '/', $redirect['path']);
                // strip off any existing comment paging
            }
            $addl_path = '';
            if (is_feed() && in_array(get_query_var('feed'), $wp_rewrite->feeds)) {
                $addl_path = !empty($addl_path) ? trailingslashit($addl_path) : '';
                if (!is_singular() && get_query_var('withcomments')) {
                    $addl_path .= 'comments/';
                }
                if ('rss' == get_default_feed() && 'feed' == get_query_var('feed') || 'rss' == get_query_var('feed')) {
                    $addl_path .= user_trailingslashit('feed/' . (get_default_feed() == 'rss2' ? '' : 'rss2'), 'feed');
                } else {
                    $addl_path .= user_trailingslashit('feed/' . (get_default_feed() == get_query_var('feed') || 'feed' == get_query_var('feed') ? '' : get_query_var('feed')), 'feed');
                }
                $redirect['query'] = remove_query_arg('feed', $redirect['query']);
            } elseif (is_feed() && 'old' == get_query_var('feed')) {
                $old_feed_files = array('wp-atom.php' => 'atom', 'wp-commentsrss2.php' => 'comments_rss2', 'wp-feed.php' => get_default_feed(), 'wp-rdf.php' => 'rdf', 'wp-rss.php' => 'rss2', 'wp-rss2.php' => 'rss2');
                if (isset($old_feed_files[basename($redirect['path'])])) {
                    $redirect_url = get_feed_link($old_feed_files[basename($redirect['path'])]);
                    wp_redirect($redirect_url, 301);
                    die;
                }
            }
            if (get_query_var('paged') > 0) {
                $paged = get_query_var('paged');
                $redirect['query'] = remove_query_arg('paged', $redirect['query']);
                if (!is_feed()) {
                    if ($paged > 1 && !is_single()) {
                        $addl_path = (!empty($addl_path) ? trailingslashit($addl_path) : '') . user_trailingslashit("{$wp_rewrite->pagination_base}/{$paged}", 'paged');
                    } elseif (!is_single()) {
                        $addl_path = !empty($addl_path) ? trailingslashit($addl_path) : '';
                    }
                } elseif ($paged > 1) {
                    $redirect['query'] = add_query_arg('paged', $paged, $redirect['query']);
                }
            }
            if (get_option('page_comments') && ('newest' == get_option('default_comments_page') && get_query_var('cpage') > 0 || 'newest' != get_option('default_comments_page') && get_query_var('cpage') > 1)) {
                $addl_path = (!empty($addl_path) ? trailingslashit($addl_path) : '') . user_trailingslashit($wp_rewrite->comments_pagination_base . '-' . get_query_var('cpage'), 'commentpaged');
                $redirect['query'] = remove_query_arg('cpage', $redirect['query']);
            }
            $redirect['path'] = user_trailingslashit(preg_replace('|/' . preg_quote($wp_rewrite->index, '|') . '/?$|', '/', $redirect['path']));
            // strip off trailing /index.php/
            if (!empty($addl_path) && $wp_rewrite->using_index_permalinks() && strpos($redirect['path'], '/' . $wp_rewrite->index . '/') === false) {
                $redirect['path'] = trailingslashit($redirect['path']) . $wp_rewrite->index . '/';
            }
            if (!empty($addl_path)) {
                $redirect['path'] = trailingslashit($redirect['path']) . $addl_path;
            }
            $redirect_url = $redirect['scheme'] . '://' . $redirect['host'] . $redirect['path'];
        }
        if ('wp-register.php' == basename($redirect['path'])) {
            if (is_multisite()) {
                /** This filter is documented in wp-login.php */
                $redirect_url = apply_filters('wp_signup_location', network_site_url('wp-signup.php'));
            } else {
                $redirect_url = wp_registration_url();
            }
            wp_redirect($redirect_url, 301);
            die;
        }
    }
    // tack on any additional query vars
    $redirect['query'] = preg_replace('#^\\??&*?#', '', $redirect['query']);
    if ($redirect_url && !empty($redirect['query'])) {
        parse_str($redirect['query'], $_parsed_query);
        $redirect = @parse_url($redirect_url);
        if (!empty($_parsed_query['name']) && !empty($redirect['query'])) {
            parse_str($redirect['query'], $_parsed_redirect_query);
            if (empty($_parsed_redirect_query['name'])) {
                unset($_parsed_query['name']);
            }
        }
        $_parsed_query = rawurlencode_deep($_parsed_query);
        $redirect_url = add_query_arg($_parsed_query, $redirect_url);
    }
    if ($redirect_url) {
        $redirect = @parse_url($redirect_url);
    }
    // www.example.com vs example.com
    $user_home = @parse_url(home_url());
    if (!empty($user_home['host'])) {
        $redirect['host'] = $user_home['host'];
    }
    if (empty($user_home['path'])) {
        $user_home['path'] = '/';
    }
    // Handle ports
    if (!empty($user_home['port'])) {
        $redirect['port'] = $user_home['port'];
    } else {
        unset($redirect['port']);
    }
    // trailing /index.php
    $redirect['path'] = preg_replace('|/' . preg_quote($wp_rewrite->index, '|') . '/*?$|', '/', $redirect['path']);
    // Remove trailing spaces from the path
    $redirect['path'] = preg_replace('#(%20| )+$#', '', $redirect['path']);
    if (!empty($redirect['query'])) {
        // Remove trailing spaces from certain terminating query string args
        $redirect['query'] = preg_replace('#((p|page_id|cat|tag)=[^&]*?)(%20| )+$#', '$1', $redirect['query']);
        // Clean up empty query strings
        $redirect['query'] = trim(preg_replace('#(^|&)(p|page_id|cat|tag)=?(&|$)#', '&', $redirect['query']), '&');
        // Redirect obsolete feeds
        $redirect['query'] = preg_replace('#(^|&)feed=rss(&|$)#', '$1feed=rss2$2', $redirect['query']);
        // Remove redundant leading ampersands
        $redirect['query'] = preg_replace('#^\\??&*?#', '', $redirect['query']);
    }
    // strip /index.php/ when we're not using PATHINFO permalinks
    if (!$wp_rewrite->using_index_permalinks()) {
        $redirect['path'] = str_replace('/' . $wp_rewrite->index . '/', '/', $redirect['path']);
    }
    // trailing slashes
    if (is_object($wp_rewrite) && $wp_rewrite->using_permalinks() && !is_404() && (!is_front_page() || is_front_page() && get_query_var('paged') > 1)) {
        $user_ts_type = '';
        if (get_query_var('paged') > 0) {
            $user_ts_type = 'paged';
        } else {
            foreach (array('single', 'category', 'page', 'day', 'month', 'year', 'home') as $type) {
                $func = 'is_' . $type;
                if (call_user_func($func)) {
                    $user_ts_type = $type;
                    break;
                }
            }
        }
        $redirect['path'] = user_trailingslashit($redirect['path'], $user_ts_type);
    } elseif (is_front_page()) {
        $redirect['path'] = trailingslashit($redirect['path']);
    }
    // Strip multiple slashes out of the URL
    if (strpos($redirect['path'], '//') > -1) {
        $redirect['path'] = preg_replace('|/+|', '/', $redirect['path']);
    }
    // Always trailing slash the Front Page URL
    if (trailingslashit($redirect['path']) == trailingslashit($user_home['path'])) {
        $redirect['path'] = trailingslashit($redirect['path']);
    }
    // Ignore differences in host capitalization, as this can lead to infinite redirects
    // Only redirect no-www <=> yes-www
    if (strtolower($original['host']) == strtolower($redirect['host']) || strtolower($original['host']) != 'www.' . strtolower($redirect['host']) && 'www.' . strtolower($original['host']) != strtolower($redirect['host'])) {
        $redirect['host'] = $original['host'];
    }
    $compare_original = array($original['host'], $original['path']);
    if (!empty($original['port'])) {
        $compare_original[] = $original['port'];
    }
    if (!empty($original['query'])) {
        $compare_original[] = $original['query'];
    }
    $compare_redirect = array($redirect['host'], $redirect['path']);
    if (!empty($redirect['port'])) {
        $compare_redirect[] = $redirect['port'];
    }
    if (!empty($redirect['query'])) {
        $compare_redirect[] = $redirect['query'];
    }
    if ($compare_original !== $compare_redirect) {
        $redirect_url = $redirect['scheme'] . '://' . $redirect['host'];
        if (!empty($redirect['port'])) {
            $redirect_url .= ':' . $redirect['port'];
        }
        $redirect_url .= $redirect['path'];
        if (!empty($redirect['query'])) {
            $redirect_url .= '?' . $redirect['query'];
        }
    }
    if (!$redirect_url || $redirect_url == $requested_url) {
        return;
    }
    // Hex encoded octets are case-insensitive.
    if (false !== strpos($requested_url, '%')) {
        if (!function_exists('lowercase_octets')) {
            function lowercase_octets($matches)
            {
                return strtolower($matches[0]);
            }
        }
        $requested_url = preg_replace_callback('|%[a-fA-F0-9][a-fA-F0-9]|', 'lowercase_octets', $requested_url);
    }
    /**
     * Filter the canonical redirect URL.
     *
     * Returning false to this filter will cancel the redirect.
     *
     * @since 2.3.0
     *
     * @param string $redirect_url  The redirect URL.
     * @param string $requested_url The requested URL.
     */
    $redirect_url = apply_filters('redirect_canonical', $redirect_url, $requested_url);
    // yes, again -- in case the filter aborted the request
    if (!$redirect_url || $redirect_url == $requested_url) {
        return;
    }
    if ($do_redirect) {
        // protect against chained redirects
        if (!redirect_canonical($redirect_url, false)) {
            wp_redirect($redirect_url, 301);
            exit;
        } else {
            // Debug
            // die("1: $redirect_url<br />2: " . redirect_canonical( $redirect_url, false ) );
            return;
        }
    } else {
        return $redirect_url;
    }
}
Example #19
0
/**
 * Loads the feed template from the use of an action hook.
 *
 * If the feed action does not have a hook, then the function will die with a
 * message telling the visitor that the feed is not valid.
 *
 * It is better to only have one hook for each feed.
 *
 * @since 2.1.0
 * @uses $wp_query Used to tell if the use a comment feed.
 * @uses do_action() Calls 'do_feed_$feed' hook, if a hook exists for the feed.
 */
function do_feed()
{
    global $wp_query;
    $feed = get_query_var('feed');
    // Remove the pad, if present.
    $feed = preg_replace('/^_+/', '', $feed);
    if ($feed == '' || $feed == 'feed') {
        $feed = get_default_feed();
    }
    $hook = 'do_feed_' . $feed;
    if (!has_action($hook)) {
        $message = sprintf(__('ERROR: %s is not a valid feed template'), wp_specialchars($feed));
        wp_die($message);
    }
    do_action($hook, $wp_query->is_comment_feed);
}
/**
 * Redirects incoming links to the proper URL based on the site url.
 *
 * Search engines consider www.somedomain.com and somedomain.com to be two
 * different URLs when they both go to the same location. This SEO enhancement
 * prevents penalty for duplicate content by redirecting all incoming links to
 * one or the other.
 *
 * Prevents redirection for feeds, trackbacks, searches, comment popup, and
 * admin URLs. Does not redirect on IIS, page/post previews, and on form data.
 *
 * Will also attempt to find the correct link when a user enters a URL that does
 * not exist based on exact WordPress query. Will instead try to parse the URL
 * or query in an attempt to figure the correct page to go to.
 *
 * @since 2.3.0
 * @uses $wp_rewrite
 * @uses $is_IIS
 *
 * @param string $requested_url Optional. The URL that was requested, used to
 *		figure if redirect is needed.
 * @param bool $do_redirect Optional. Redirect to the new URL.
 * @return null|false|string Null, if redirect not needed. False, if redirect
 *		not needed or the string of the URL
 */
function redirect_canonical( $requested_url = null, $do_redirect = true ) {
	global $wp_rewrite, $is_IIS, $wp_query, $wpdb;

	if ( is_trackback() || is_search() || is_comments_popup() || is_admin() || !empty($_POST) || is_preview() || is_robots() || $is_IIS )
		return;

	if ( !$requested_url ) {
		// build the URL in the address bar
		$requested_url  = is_ssl() ? 'https://' : 'http://';
		$requested_url .= $_SERVER['HTTP_HOST'];
		$requested_url .= $_SERVER['REQUEST_URI'];
	}

	$original = @parse_url($requested_url);
	if ( false === $original )
		return;

	// Some PHP setups turn requests for / into /index.php in REQUEST_URI
	// See: http://trac.wordpress.org/ticket/5017
	// See: http://trac.wordpress.org/ticket/7173
	// Disabled, for now:
	// $original['path'] = preg_replace('|/index\.php$|', '/', $original['path']);

	$redirect = $original;
	$redirect_url = false;

	// Notice fixing
	if ( !isset($redirect['path']) )
		$redirect['path'] = '';
	if ( !isset($redirect['query']) )
		$redirect['query'] = '';

	if ( is_feed() && ( $id = get_query_var( 'p' ) ) ) {
		if ( $redirect_url = get_post_comments_feed_link( $id, get_query_var( 'feed' ) ) ) {
			$redirect['query'] = _remove_qs_args_if_not_in_url( $redirect['query'], array( 'p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type', 'feed'), $redirect_url );
			$redirect['path'] = parse_url( $redirect_url, PHP_URL_PATH );
		}
	}

	if ( is_singular() && 1 > $wp_query->post_count && ($id = get_query_var('p')) ) {

		$vars = $wpdb->get_results( $wpdb->prepare("SELECT post_type, post_parent FROM $wpdb->posts WHERE ID = %d", $id) );

		if ( isset($vars[0]) && $vars = $vars[0] ) {
			if ( 'revision' == $vars->post_type && $vars->post_parent > 0 )
				$id = $vars->post_parent;

			if ( $redirect_url = get_permalink($id) )
				$redirect['query'] = _remove_qs_args_if_not_in_url( $redirect['query'], array( 'p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type' ), $redirect_url );
		}
	}

	// These tests give us a WP-generated permalink
	if ( is_404() ) {

		// Redirect ?page_id, ?p=, ?attachment_id= to their respective url's
		$id = max( get_query_var('p'), get_query_var('page_id'), get_query_var('attachment_id') );
		if ( $id && $redirect_post = get_post($id) ) {
			$post_type_obj = get_post_type_object($redirect_post->post_type);
			if ( $post_type_obj->public ) {
				$redirect_url = get_permalink($redirect_post);
				$redirect['query'] = _remove_qs_args_if_not_in_url( $redirect['query'], array( 'p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type' ), $redirect_url );
			}
		}

		if ( ! $redirect_url ) {
			if ( $redirect_url = redirect_guess_404_permalink( $requested_url ) ) {
				$redirect['query'] = _remove_qs_args_if_not_in_url( $redirect['query'], array( 'page', 'feed', 'p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type' ), $redirect_url );
			}
		}

	} elseif ( is_object($wp_rewrite) && $wp_rewrite->using_permalinks() ) {
		// rewriting of old ?p=X, ?m=2004, ?m=200401, ?m=20040101
		if ( is_attachment() && !empty($_GET['attachment_id']) && ! $redirect_url ) {
			if ( $redirect_url = get_attachment_link(get_query_var('attachment_id')) )
				$redirect['query'] = remove_query_arg('attachment_id', $redirect['query']);
		} elseif ( is_single() && !empty($_GET['p']) && ! $redirect_url ) {
			if ( $redirect_url = get_permalink(get_query_var('p')) )
				$redirect['query'] = remove_query_arg(array('p', 'post_type'), $redirect['query']);
		} elseif ( is_single() && !empty($_GET['name'])  && ! $redirect_url ) {
			if ( $redirect_url = get_permalink( $wp_query->get_queried_object_id() ) )
				$redirect['query'] = remove_query_arg('name', $redirect['query']);
		} elseif ( is_page() && !empty($_GET['page_id']) && ! $redirect_url ) {
			if ( $redirect_url = get_permalink(get_query_var('page_id')) )
				$redirect['query'] = remove_query_arg('page_id', $redirect['query']);
		} elseif ( is_page() && !is_feed() && isset($wp_query->queried_object) && 'page' == get_option('show_on_front') && $wp_query->queried_object->ID == get_option('page_on_front')  && ! $redirect_url ) {
			$redirect_url = home_url('/');
		} elseif ( is_home() && !empty($_GET['page_id']) && 'page' == get_option('show_on_front') && get_query_var('page_id') == get_option('page_for_posts')  && ! $redirect_url ) {
			if ( $redirect_url = get_permalink(get_option('page_for_posts')) )
				$redirect['query'] = remove_query_arg('page_id', $redirect['query']);
		} elseif ( !empty($_GET['m']) && ( is_year() || is_month() || is_day() ) ) {
			$m = get_query_var('m');
			switch ( strlen($m) ) {
				case 4: // Yearly
					$redirect_url = get_year_link($m);
					break;
				case 6: // Monthly
					$redirect_url = get_month_link( substr($m, 0, 4), substr($m, 4, 2) );
					break;
				case 8: // Daily
					$redirect_url = get_day_link(substr($m, 0, 4), substr($m, 4, 2), substr($m, 6, 2));
					break;
			}
			if ( $redirect_url )
				$redirect['query'] = remove_query_arg('m', $redirect['query']);
		// now moving on to non ?m=X year/month/day links
		} elseif ( is_day() && get_query_var('year') && get_query_var('monthnum') && !empty($_GET['day']) ) {
			if ( $redirect_url = get_day_link(get_query_var('year'), get_query_var('monthnum'), get_query_var('day')) )
				$redirect['query'] = remove_query_arg(array('year', 'monthnum', 'day'), $redirect['query']);
		} elseif ( is_month() && get_query_var('year') && !empty($_GET['monthnum']) ) {
			if ( $redirect_url = get_month_link(get_query_var('year'), get_query_var('monthnum')) )
				$redirect['query'] = remove_query_arg(array('year', 'monthnum'), $redirect['query']);
		} elseif ( is_year() && !empty($_GET['year']) ) {
			if ( $redirect_url = get_year_link(get_query_var('year')) )
				$redirect['query'] = remove_query_arg('year', $redirect['query']);
		} elseif ( is_author() && !empty($_GET['author']) && preg_match( '|^[0-9]+$|', $_GET['author'] ) ) {
			$author = get_userdata(get_query_var('author'));
			if ( ( false !== $author ) && $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE $wpdb->posts.post_author = %d AND $wpdb->posts.post_status = 'publish' LIMIT 1", $author->ID ) ) ) {
				if ( $redirect_url = get_author_posts_url($author->ID, $author->user_nicename) )
					$redirect['query'] = remove_query_arg('author', $redirect['query']);
			}
		} elseif ( is_category() || is_tag() || is_tax() ) { // Terms (Tags/categories)

			$term_count = 0;
			foreach ( $wp_query->tax_query->queries as $tax_query )
				$term_count += count( $tax_query['terms'] );

			$obj = $wp_query->get_queried_object();
			if ( $term_count <= 1 && !empty($obj->term_id) && ( $tax_url = get_term_link((int)$obj->term_id, $obj->taxonomy) ) && !is_wp_error($tax_url) ) {
				if ( !empty($redirect['query']) ) {
					// Strip taxonomy query vars off the url.
					$qv_remove = array( 'term', 'taxonomy');
					if ( is_category() ) {
						$qv_remove[] = 'category_name';
						$qv_remove[] = 'cat';
					} elseif ( is_tag() ) {
						$qv_remove[] = 'tag';
						$qv_remove[] = 'tag_id';
					} else { // Custom taxonomies will have a custom query var, remove those too:
						$tax_obj = get_taxonomy( $obj->taxonomy );
						if ( false !== $tax_obj->query_var )
							$qv_remove[] = $tax_obj->query_var;
					}

					$rewrite_vars = array_diff( array_keys($wp_query->query), array_keys($_GET) );

					if ( !array_diff($rewrite_vars, array_keys($_GET))  ) { // Check to see if all the Query vars are coming from the rewrite, none are set via $_GET
						$redirect['query'] = remove_query_arg($qv_remove, $redirect['query']); //Remove all of the per-tax qv's

						// Create the destination url for this taxonomy
						$tax_url = parse_url($tax_url);
						if ( ! empty($tax_url['query']) ) { // Taxonomy accessible via ?taxonomy=..&term=.. or any custom qv..
							parse_str($tax_url['query'], $query_vars);
							$redirect['query'] = add_query_arg($query_vars, $redirect['query']);
						} else { // Taxonomy is accessible via a "pretty-URL"
							$redirect['path'] = $tax_url['path'];
						}

					} else { // Some query vars are set via $_GET. Unset those from $_GET that exist via the rewrite
						foreach ( $qv_remove as $_qv ) {
							if ( isset($rewrite_vars[$_qv]) )
								$redirect['query'] = remove_query_arg($_qv, $redirect['query']);
						}
					}
				}

			}
		} elseif ( is_single() && strpos($wp_rewrite->permalink_structure, '%category%') !== false && $cat = get_query_var( 'category_name' ) ) {
			$category = get_category_by_path( $cat );
			$post_terms = wp_get_object_terms($wp_query->get_queried_object_id(), 'category', array('fields' => 'tt_ids'));
			if ( (!$category || is_wp_error($category)) || ( !is_wp_error($post_terms) && !empty($post_terms) && !in_array($category->term_taxonomy_id, $post_terms) ) )
				$redirect_url = get_permalink($wp_query->get_queried_object_id());
		}

		// Post Paging
		if ( is_singular() && ! is_front_page() && get_query_var('page') ) {
			if ( !$redirect_url )
				$redirect_url = get_permalink( get_queried_object_id() );
			$redirect_url = trailingslashit( $redirect_url ) . user_trailingslashit( get_query_var( 'page' ), 'single_paged' );
			$redirect['query'] = remove_query_arg( 'page', $redirect['query'] );
		}

		// paging and feeds
		if ( get_query_var('paged') || is_feed() || get_query_var('cpage') ) {
			while ( preg_match( "#/$wp_rewrite->pagination_base/?[0-9]+?(/+)?$#", $redirect['path'] ) || preg_match( '#/(comments/?)?(feed|rss|rdf|atom|rss2)(/+)?$#', $redirect['path'] ) || preg_match( '#/comment-page-[0-9]+(/+)?$#', $redirect['path'] ) ) {
				// Strip off paging and feed
				$redirect['path'] = preg_replace("#/$wp_rewrite->pagination_base/?[0-9]+?(/+)?$#", '/', $redirect['path']); // strip off any existing paging
				$redirect['path'] = preg_replace('#/(comments/?)?(feed|rss2?|rdf|atom)(/+|$)#', '/', $redirect['path']); // strip off feed endings
				$redirect['path'] = preg_replace('#/comment-page-[0-9]+?(/+)?$#', '/', $redirect['path']); // strip off any existing comment paging
			}

			$addl_path = '';
			if ( is_feed() && in_array( get_query_var('feed'), $wp_rewrite->feeds ) ) {
				$addl_path = !empty( $addl_path ) ? trailingslashit($addl_path) : '';
				if ( !is_singular() && get_query_var( 'withcomments' ) )
					$addl_path .= 'comments/';
				if ( ( 'rss' == get_default_feed() && 'feed' == get_query_var('feed') ) || 'rss' == get_query_var('feed') )
					$addl_path .= user_trailingslashit( 'feed/' . ( ( get_default_feed() == 'rss2' ) ? '' : 'rss2' ), 'feed' );
				else
					$addl_path .= user_trailingslashit( 'feed/' . ( ( get_default_feed() ==  get_query_var('feed') || 'feed' == get_query_var('feed') ) ? '' : get_query_var('feed') ), 'feed' );
				$redirect['query'] = remove_query_arg( 'feed', $redirect['query'] );
			} elseif ( is_feed() && 'old' == get_query_var('feed') ) {
				$old_feed_files = array(
					'wp-atom.php'         => 'atom',
					'wp-commentsrss2.php' => 'comments_rss2',
					'wp-feed.php'         => get_default_feed(),
					'wp-rdf.php'          => 'rdf',
					'wp-rss.php'          => 'rss2',
					'wp-rss2.php'         => 'rss2',
				);
				if ( isset( $old_feed_files[ basename( $redirect['path'] ) ] ) ) {
					$redirect_url = get_feed_link( $old_feed_files[ basename( $redirect['path'] ) ] );
					wp_redirect( $redirect_url, 301 );
					die();
				}
			}

			if ( get_query_var('paged') > 0 ) {
				$paged = get_query_var('paged');
				$redirect['query'] = remove_query_arg( 'paged', $redirect['query'] );
				if ( !is_feed() ) {
					if ( $paged > 1 && !is_single() ) {
						$addl_path = ( !empty( $addl_path ) ? trailingslashit($addl_path) : '' ) . user_trailingslashit("$wp_rewrite->pagination_base/$paged", 'paged');
					} elseif ( !is_single() ) {
						$addl_path = !empty( $addl_path ) ? trailingslashit($addl_path) : '';
					}
				} elseif ( $paged > 1 ) {
					$redirect['query'] = add_query_arg( 'paged', $paged, $redirect['query'] );
				}
			}

			if ( get_option('page_comments') && ( ( 'newest' == get_option('default_comments_page') && get_query_var('cpage') > 0 ) || ( 'newest' != get_option('default_comments_page') && get_query_var('cpage') > 1 ) ) ) {
				$addl_path = ( !empty( $addl_path ) ? trailingslashit($addl_path) : '' ) . user_trailingslashit( 'comment-page-' . get_query_var('cpage'), 'commentpaged' );
				$redirect['query'] = remove_query_arg( 'cpage', $redirect['query'] );
			}

			$redirect['path'] = user_trailingslashit( preg_replace('|/index.php/?$|', '/', $redirect['path']) ); // strip off trailing /index.php/
			if ( !empty( $addl_path ) && $wp_rewrite->using_index_permalinks() && strpos($redirect['path'], '/index.php/') === false )
				$redirect['path'] = trailingslashit($redirect['path']) . 'index.php/';
			if ( !empty( $addl_path ) )
				$redirect['path'] = trailingslashit($redirect['path']) . $addl_path;
			$redirect_url = $redirect['scheme'] . '://' . $redirect['host'] . $redirect['path'];
		}

		if ( 'wp-register.php' == basename( $redirect['path'] ) ) {
			if ( is_multisite() )
				$redirect_url = apply_filters( 'wp_signup_location', site_url( 'wp-signup.php' ) );
			else
				$redirect_url = site_url( 'wp-login.php?action=register' );
			wp_redirect( $redirect_url, 301 );
			die();
		}
	}

	// tack on any additional query vars
	$redirect['query'] = preg_replace( '#^\??&*?#', '', $redirect['query'] );
	if ( $redirect_url && !empty($redirect['query']) ) {
		parse_str( $redirect['query'], $_parsed_query );
		$redirect = @parse_url($redirect_url);

		if ( ! empty( $_parsed_query['name'] ) && ! empty( $redirect['query'] ) ) {
			parse_str( $redirect['query'], $_parsed_redirect_query );

			if ( empty( $_parsed_redirect_query['name'] ) )
				unset( $_parsed_query['name'] );
		}

		$_parsed_query = rawurlencode_deep( $_parsed_query );
		$redirect_url = add_query_arg( $_parsed_query, $redirect_url );
	}

	if ( $redirect_url )
		$redirect = @parse_url($redirect_url);

	// www.example.com vs example.com
	$user_home = @parse_url(home_url());
	if ( !empty($user_home['host']) )
		$redirect['host'] = $user_home['host'];
	if ( empty($user_home['path']) )
		$user_home['path'] = '/';

	// Handle ports
	if ( !empty($user_home['port']) )
		$redirect['port'] = $user_home['port'];
	else
		unset($redirect['port']);

	// trailing /index.php
	$redirect['path'] = preg_replace('|/index.php/*?$|', '/', $redirect['path']);

	// Remove trailing spaces from the path
	$redirect['path'] = preg_replace( '#(%20| )+$#', '', $redirect['path'] );

	if ( !empty( $redirect['query'] ) ) {
		// Remove trailing spaces from certain terminating query string args
		$redirect['query'] = preg_replace( '#((p|page_id|cat|tag)=[^&]*?)(%20| )+$#', '$1', $redirect['query'] );

		// Clean up empty query strings
		$redirect['query'] = trim(preg_replace( '#(^|&)(p|page_id|cat|tag)=?(&|$)#', '&', $redirect['query']), '&');

		// Redirect obsolete feeds
		$redirect['query'] = preg_replace( '#(^|&)feed=rss(&|$)#', '$1feed=rss2$3', $redirect['query'] );

		// Remove redundant leading ampersands
		$redirect['query'] = preg_replace( '#^\??&*?#', '', $redirect['query'] );
	}

	// strip /index.php/ when we're not using PATHINFO permalinks
	if ( !$wp_rewrite->using_index_permalinks() )
		$redirect['path'] = str_replace('/index.php/', '/', $redirect['path']);

	// trailing slashes
	if ( is_object($wp_rewrite) && $wp_rewrite->using_permalinks() && !is_404() && (!is_front_page() || ( is_front_page() && (get_query_var('paged') > 1) ) ) ) {
		$user_ts_type = '';
		if ( get_query_var('paged') > 0 ) {
			$user_ts_type = 'paged';
		} else {
			foreach ( array('single', 'category', 'page', 'day', 'month', 'year', 'home') as $type ) {
				$func = 'is_' . $type;
				if ( call_user_func($func) ) {
					$user_ts_type = $type;
					break;
				}
			}
		}
		$redirect['path'] = user_trailingslashit($redirect['path'], $user_ts_type);
	} elseif ( is_front_page() ) {
		$redirect['path'] = trailingslashit($redirect['path']);
	}

	// Strip multiple slashes out of the URL
	if ( strpos($redirect['path'], '//') > -1 )
		$redirect['path'] = preg_replace('|/+|', '/', $redirect['path']);

	// Always trailing slash the Front Page URL
	if ( trailingslashit( $redirect['path'] ) == trailingslashit( $user_home['path'] ) )
		$redirect['path'] = trailingslashit($redirect['path']);

	// Ignore differences in host capitalization, as this can lead to infinite redirects
	// Only redirect no-www <=> yes-www
	if ( strtolower($original['host']) == strtolower($redirect['host']) ||
		( strtolower($original['host']) != 'www.' . strtolower($redirect['host']) && 'www.' . strtolower($original['host']) != strtolower($redirect['host']) ) )
		$redirect['host'] = $original['host'];

	$compare_original = array($original['host'], $original['path']);

	if ( !empty( $original['port'] ) )
		$compare_original[] = $original['port'];

	if ( !empty( $original['query'] ) )
		$compare_original[] = $original['query'];

	$compare_redirect = array($redirect['host'], $redirect['path']);

	if ( !empty( $redirect['port'] ) )
		$compare_redirect[] = $redirect['port'];

	if ( !empty( $redirect['query'] ) )
		$compare_redirect[] = $redirect['query'];

	if ( $compare_original !== $compare_redirect ) {
		$redirect_url = $redirect['scheme'] . '://' . $redirect['host'];
		if ( !empty($redirect['port']) )
			$redirect_url .= ':' . $redirect['port'];
		$redirect_url .= $redirect['path'];
		if ( !empty($redirect['query']) )
			$redirect_url .= '?' . $redirect['query'];
	}

	if ( !$redirect_url || $redirect_url == $requested_url )
		return false;

	// Hex encoded octets are case-insensitive.
	if ( false !== strpos($requested_url, '%') ) {
		if ( !function_exists('lowercase_octets') ) {
			function lowercase_octets($matches) {
				return strtolower( $matches[0] );
			}
		}
		$requested_url = preg_replace_callback('|%[a-fA-F0-9][a-fA-F0-9]|', 'lowercase_octets', $requested_url);
	}

	// Note that you can use the "redirect_canonical" filter to cancel a canonical redirect for whatever reason by returning false
	$redirect_url = apply_filters('redirect_canonical', $redirect_url, $requested_url);

	if ( !$redirect_url || $redirect_url == $requested_url ) // yes, again -- in case the filter aborted the request
		return false;

	if ( $do_redirect ) {
		// protect against chained redirects
		if ( !redirect_canonical($redirect_url, false) ) {
			wp_redirect($redirect_url, 301);
			exit();
		} else {
			// Debug
			// die("1: $redirect_url<br />2: " . redirect_canonical( $redirect_url, false ) );
			return false;
		}
	} else {
		return $redirect_url;
	}
}
Example #21
0
/**
 * Return the content type for specified feed type.
 *
 * @package WordPress
 * @subpackage Feed
 * @since 2.8.0
 */
function feed_content_type($type = '')
{
    if (empty($type)) {
        $type = get_default_feed();
    }
    $types = array('rss' => 'application/rss+xml', 'rss2' => 'application/rss+xml', 'rss-http' => 'text/xml', 'atom' => 'application/atom+xml', 'rdf' => 'application/rdf+xml');
    $content_type = !empty($types[$type]) ? $types[$type] : 'application/octet-stream';
    return apply_filters('feed_content_type', $content_type, $type);
}
/**
 * Universal Feed Loader
 * hooked function
 * supports custom settings
 * NOTE uses just-in-time initialization
 * @see     functions.php, feed-links include module
 * @uses    Universal Feed Writer class
 */
function tLoadFeed()
{
    global $tFeeds, $tCurrentFeed, $wp_query, $post;
    $tCurrentFeed = get_query_var('feed');
    // FB::trace($tCurrentFeed);
    if (empty($tCurrentFeed) || $tCurrentFeed == 'feed') {
        $tCurrentFeed = get_default_feed();
        # rss2
    }
    $args =& $tFeeds[$tCurrentFeed];
    $defaults = array('num_entries' => get_option('posts_per_rss'), 'do_images' => true, 'size_image' => 'large', 'feed_type' => defined('TFEED') ? TFEED : 'atom', 'feed_title' => 'Recent Posts', 'feed_description' => 'An unfiltered list limited to ' . $num_entries . ' posts');
    $args = apply_filters('t_load_feed_args', $args);
    $args = wp_parse_args($args, $defaults);
    # customizing default info
    if (is_category()) {
        $category = t_get_term_name(get_query_var('cat'), 'category');
        $args['feed_title'] = 'Feed for ' . $category;
        $args['feed_description'] = 'A list limited to ' . $args['num_entries'] . ' posts categorized under ' . $category;
    }
    if ($wp_query->is_comment_feed) {
        # comment feed
        if (is_singular()) {
            $args['feed_title'] = 'Recent comments on ' . get_the_title_rss();
        } elseif (is_search()) {
            $args['feed_title'] = 'Comments for search on ' . attribute_escape($wp_query->query_vars['s']);
        } else {
            $args['feed_title'] = 'Recent comments for ' . get_wp_title_rss();
        }
        $args['feed_title'] = ent2ncr($args['feed_title']);
        $args['feed_description'] = 'A list limited to ' . $args['num_entries'] . ' comments';
    }
    $args['query'] = tGetFeedQuery();
    if (is_array($args['query'])) {
        $args['query']['showposts'] =& $args['num_entries'];
    }
    if ($tCurrentFeed == 'rss' || $tCurrentFeed == 'rss2' || $tCurrentFeed == 'atom') {
        $args['feed_type'] = $tCurrentFeed;
    } else {
        $args['feed_title'] = ucwords(str_replace('_', ' ', $tCurrentFeed));
    }
    extract($args);
    # namespacing
    switch ($feed_type) {
        case 'rss2':
            $namespace = '
                 xmlns:dc="http://purl.org/dc/elements/1.1/"
                 xmlns:atom="http://www.w3.org/2005/Atom"
                 xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
                ';
            $feedType = RSS2;
            break;
        case 'rss':
            $namespace = '
                 xmlns:dc="http://purl.org/dc/elements/1.1/"
                 xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
                 xmlns:admin="http://webns.net/mvcb/"
                 xmlns:content="http://purl.org/rss/1.0/modules/content/"
                ';
            $feedType = RSS1;
            break;
        case 'atom':
        default:
            $namespace = '
                 xmlns:thr="http://purl.org/syndication/thread/1.0"
                 xml:lang="' . get_option('rss_language') . '"
                 xml:base="' . get_bloginfo_rss('url') . '"
                 ';
            $feedType = ATOM;
            break;
    }
    $GLOBALS['t_feed_ns'] = $namespace;
    # for use in FeedWriter
    add_filter('t_feed_ns', create_function('$default', 'return $default . $GLOBALS["t_feed_ns"];'));
    # start
    $feedWriter = new FeedWriter($feedType);
    require TDIR . TMODINC . 'feed-head.php';
    require TDIR . TMODINC . 'feed-body.php';
    # output
    $out = ob_get_contents();
    $out = str_replace(array("\n", "\r", "\t", ' '), '', $input);
    ob_end_clean();
    $feedWriter->generateFeed();
    // lifestream_rss_feed();
    // FB::info($args);
}
Example #23
0
/**
 * Retrieve the permalink for a post type archive feed.
 *
 * @since 3.1.0
 *
 * @param string $post_type Post type
 * @param string $feed Optional. Feed type
 * @return string
 */
function get_post_type_archive_feed_link($post_type, $feed = '')
{
    $default_feed = get_default_feed();
    if (empty($feed)) {
        $feed = $default_feed;
    }
    if (!($link = get_post_type_archive_link($post_type))) {
        return false;
    }
    $post_type_obj = get_post_type_object($post_type);
    if ($post_type_obj->rewrite['feeds'] && get_option('permalink_structure')) {
        $link = trailingslashit($link);
        $link .= 'feed/';
        if ($feed != $default_feed) {
            $link .= "{$feed}/";
        }
    } else {
        $link = add_query_arg('feed', $feed, $link);
    }
    return apply_filters('post_type_archive_feed_link', $link, $feed);
}
Example #24
0
/**
 * Display the links to the general feeds.
 *
 * @since 2.8.0
 *
 * @param array $args Optional arguments.
 */
function feed_links($args = array())
{
    if (!current_theme_supports('automatic-feed-links')) {
        return;
    }
    $defaults = array('separator' => _x('&raquo;', 'feed link'), 'feedtitle' => __('%1$s %2$s Feed'), 'comstitle' => __('%1$s %2$s Comments Feed'));
    $args = wp_parse_args($args, $defaults);
    /**
     * Filter whether to display the posts feed link.
     *
     * @since 4.4.0
     *
     * @param bool $show Whether to display the posts feed link. Default true.
     */
    if (apply_filters('feed_links_show_posts_feed', true)) {
        echo '<link rel="alternate" type="' . feed_content_type() . '" title="' . esc_attr(sprintf($args['feedtitle'], get_bloginfo('name'), $args['separator'])) . '" href="' . esc_url(get_feed_link()) . "\" />\n";
    }
    /**
     * Filter whether to display the comments feed link.
     *
     * @since 4.4.0
     *
     * @param bool $show Whether to display the comments feed link. Default true.
     */
    if (apply_filters('feed_links_show_comments_feed', true)) {
        echo '<link rel="alternate" type="' . feed_content_type() . '" title="' . esc_attr(sprintf($args['comstitle'], get_bloginfo('name'), $args['separator'])) . '" href="' . esc_url(get_feed_link('comments_' . get_default_feed())) . "\" />\n";
    }
}
Example #25
0
 /**
  * Is the query for a feed?
  *
  * @since 3.1.0
  *
  * @param string|array $feeds Optional feed types to check.
  * @return bool
  */
 public function is_feed($feeds = '')
 {
     if (empty($feeds) || !$this->is_feed) {
         return (bool) $this->is_feed;
     }
     $qv = $this->get('feed');
     if ('feed' == $qv) {
         $qv = get_default_feed();
     }
     return in_array($qv, (array) $feeds);
 }
Example #26
0
File: feed.php Project: RA2WP/RA2WP
/**
 * Return the content type for specified feed type.
 *
 * @since 2.8.0
 */
function feed_content_type($type = '')
{
    if (empty($type)) {
        $type = get_default_feed();
    }
    $types = array('rss' => 'application/rss+xml', 'rss2' => 'application/rss+xml', 'rss-http' => 'text/xml', 'atom' => 'application/atom+xml', 'rdf' => 'application/rdf+xml');
    $content_type = !empty($types[$type]) ? $types[$type] : 'application/octet-stream';
    /**
     * Filter the content type for a specific feed type.
     *
     * @since 2.8.0
     *
     * @param string $content_type Content type indicating the type of data that a feed contains.
     * @param string $type         Type of feed. Possible values include 'rss2', 'atom'.
     *                             Default 'rss2'.
     */
    return apply_filters('feed_content_type', $content_type, $type);
}
Example #27
0
/**
 * Load the feed template from the use of an action hook.
 *
 * If the feed action does not have a hook, then the function will die with a
 * message telling the visitor that the feed is not valid.
 *
 * It is better to only have one hook for each feed.
 *
 * @since 2.1.0
 *
 * @global WP_Query $wp_query Used to tell if the use a comment feed.
 */
function do_feed()
{
    global $wp_query;
    $feed = get_query_var('feed');
    // Remove the pad, if present.
    $feed = preg_replace('/^_+/', '', $feed);
    if ($feed == '' || $feed == 'feed') {
        $feed = get_default_feed();
    }
    $hook = 'do_feed_' . $feed;
    if (!has_action($hook)) {
        wp_die(__('ERROR: This is not a valid feed template.'), '', array('response' => 404));
    }
    /**
     * Fires once the given feed is loaded.
     *
     * The dynamic hook name, $hook, refers to the feed name.
     *
     * @since 2.1.0
     *
     * @param bool $is_comment_feed Whether the feed is a comment feed.
     */
    do_action($hook, $wp_query->is_comment_feed);
}
Example #28
0
function woo_feedburner_link($output, $feed = null)
{
    global $woo_options;
    $default = get_default_feed();
    if (!$feed) {
        $feed = $default;
    }
    if (isset($woo_options['woo_feed_url']) && $woo_options['woo_feed_url'] && $feed == $default && !stristr($output, 'comments')) {
        $output = esc_url($woo_options['woo_feed_url']);
    }
    return $output;
}
Example #29
0
/**
 * Retrieve the permalink for a post type archive feed.
 *
 * @since 3.1.0
 *
 * @param string $post_type Post type
 * @param string $feed      Optional. Feed type
 * @return string|false The post type feed permalink.
 */
function get_post_type_archive_feed_link($post_type, $feed = '')
{
    $default_feed = get_default_feed();
    if (empty($feed)) {
        $feed = $default_feed;
    }
    if (!($link = get_post_type_archive_link($post_type))) {
        return false;
    }
    $post_type_obj = get_post_type_object($post_type);
    if (get_option('permalink_structure') && is_array($post_type_obj->rewrite) && $post_type_obj->rewrite['feeds']) {
        $link = trailingslashit($link);
        $link .= 'feed/';
        if ($feed != $default_feed) {
            $link .= "{$feed}/";
        }
    } else {
        $link = add_query_arg('feed', $feed, $link);
    }
    /**
     * Filter the post type archive feed link.
     *
     * @since 3.1.0
     *
     * @param string $link The post type archive feed link.
     * @param string $feed Feed type.
     */
    return apply_filters('post_type_archive_feed_link', $link, $feed);
}
Example #30
0
]" value="1" <?php 
echo $Checked;
?>
 /> <?php 
_e('Hide');
?>
</label>
												<p class="description"><?php 
_e('Extra feed', $this->ltd);
?>
</p>
												<p class="description"><?php 
_e('Tag to be output', $this->ltd);
?>
 : <code><?php 
echo esc_html('<link rel="alternate" type="' . feed_content_type() . '" title="' . esc_attr(sprintf(__('%1$s %2$s Comments Feed'), get_bloginfo('name'), '&amp;raquo&#059;')) . '" href="' . get_feed_link(get_default_feed() . '&#038;p=***') . ' />');
?>
</code></p>
											</td>
										</tr>
									</tbody>
								</table>
							</div>
						</div>

					</div>

				</div>

				<div id="postbox-container-2" class="postbox-container">