Esempio n. 1
0
 /**
  * Add custom javascript within head section.
  *
  * @since 1.0.0
  */
 public function add_snippet()
 {
     if (\is_admin()) {
         return;
     }
     if (\is_feed()) {
         return;
     }
     if (\is_robots()) {
         return;
     }
     if (\is_trackback()) {
         return;
     }
     $disable_recording = boolval(\get_post_meta(\get_the_id(), 'smartlook_disable_rec', true));
     // Disable recording for this content type
     if ($disable_recording) {
         return;
     }
     $snippet = trim(\get_option('smartlook_snippet'));
     if (empty($snippet)) {
         return;
     }
     echo $snippet;
 }
Esempio n. 2
0
function my_template_redirect()
{
    global $wp, $ocmx_post_types;
    $wp->query_vars["post_type"] = "";
    $ocmx_post_types = array();
    $ocmx_post_types[] = "quote";
    $ocmx_post_types[] = "info-box";
    $ocmx_post_types[] = "portfolio";
    if (in_array($wp->query_vars["post_type"], $ocmx_post_types)) {
        if (is_robots()) {
            do_action('do_robots');
            return;
        } elseif (is_feed()) {
            do_feed();
            return;
        } elseif (is_trackback()) {
            include ABSPATH . 'wp-trackback.php';
            return;
        } elseif ($wp->query_vars["name"]) {
            include TEMPLATEPATH . "/single-" . $wp->query_vars["post_type"] . ".php";
            die;
        } else {
            include TEMPLATEPATH . "/" . $wp->query_vars["post_type"] . ".php";
            die;
        }
    }
}
function bogo_init()
{
    bogo_languages();
    if (!(is_admin() || is_robots() || is_feed() || is_trackback())) {
        $locale = get_locale();
        if (!isset($_COOKIE['lang']) || $_COOKIE['lang'] != $locale) {
            setcookie('lang', $locale, 0, '/');
        }
    }
}
Esempio n. 4
0
 function wp_footer()
 {
     if (!is_admin() && !is_feed() && !is_robots() && !is_trackback()) {
         $text = get_option('shfs_insert_footer', '');
         $text = convert_smilies($text);
         $text = do_shortcode($text);
         if ($text != '') {
             echo $text, "\n";
         }
     }
 }
/**
 *
 *
 * @desc Display blog footer. Show Publishthis logo if needed
 */
function pt_footer()
{
    global $publishthis;
    if (!is_admin() && !is_feed() && !is_robots() && !is_trackback()) {
        try {
            echo pt_curated_by(), "\n";
            echo "<script type='text/javascript' src='http://curateby.publishthis.com/clients.js'></script>";
        } catch (Exception $ex) {
        }
    }
}
Esempio n. 6
0
function stats_template_redirect()
{
    global $wp_the_query, $current_user, $stats_footer;
    if (is_feed() || is_robots() || is_trackback()) {
        return;
    }
    $options = stats_get_options();
    // Ensure this is always setup for the check below
    $options['reg_users'] = empty($options['reg_users']) ? false : true;
    if (!$options['reg_users'] && !empty($current_user->ID)) {
        return;
    }
    add_action('wp_footer', 'stats_footer', 101);
    add_action('wp_head', 'stats_add_shutdown_action');
    $blog = Jetpack::get_option('id');
    $tz = get_option('gmt_offset');
    $v = 'ext';
    $j = sprintf('%s:%s', JETPACK__API_VERSION, JETPACK__VERSION);
    if ($wp_the_query->is_single || $wp_the_query->is_page || $wp_the_query->is_posts_page) {
        // Store and reset the queried_object and queried_object_id
        // Otherwise, redirect_canonical() will redirect to home_url( '/' ) for show_on_front = page sites where home_url() is not all lowercase.
        // Repro:
        // 1. Set home_url = http://ExamPle.com/
        // 2. Set show_on_front = page
        // 3. Set page_on_front = something
        // 4. Visit http://example.com/
        $queried_object = isset($wp_the_query->queried_object) ? $wp_the_query->queried_object : null;
        $queried_object_id = isset($wp_the_query->queried_object_id) ? $wp_the_query->queried_object_id : null;
        $post = $wp_the_query->get_queried_object_id();
        $wp_the_query->queried_object = $queried_object;
        $wp_the_query->queried_object_id = $queried_object_id;
    } else {
        $post = '0';
    }
    $http = is_ssl() ? 'https' : 'http';
    $week = gmdate('YW');
    $data = stats_array(compact('v', 'j', 'blog', 'post', 'tz'));
    $stats_footer = <<<END

\t<script src="{$http}://stats.wordpress.com/e-{$week}.js" type="text/javascript"></script>
\t<script type="text/javascript">
\tst_go({{$data}});
\tvar load_cmc = function(){linktracker_init({$blog},{$post},2);};
\tif ( typeof addLoadEvent != 'undefined' ) addLoadEvent(load_cmc);
\telse load_cmc();
\t</script>
END;
    if (isset($options['hide_smile']) && $options['hide_smile']) {
        $stats_footer .= "\n<style type='text/css'>img#wpstats{display:none}</style>";
    }
}
 /**
  * Is Active?
  */
 function is_active()
 {
     // Always allow access to robots.txt
     if (is_robots()) {
         return false;
     }
     if ((bool) get_option('password_protected_status')) {
         if (!defined('DONOTCACHEPAGE')) {
             define('DONOTCACHEPAGE', true);
         }
         return true;
     }
     return false;
 }
Esempio n. 8
0
 /**
  * Add custom javascript within head section.
  *
  * @since 1.0.0
  */
 public function add_snippet()
 {
     if (\is_admin()) {
         return;
     }
     if (\is_feed()) {
         return;
     }
     if (\is_robots()) {
         return;
     }
     if (\is_trackback()) {
         return;
     }
     $snippet = trim(\get_option('jaco_snippet'));
     if (empty($snippet)) {
         return;
     }
     echo $snippet;
 }
Esempio n. 9
0
function stats_template_redirect()
{
    global $wp_the_query, $current_user, $stats_footer;
    if (is_feed() || is_robots() || is_trackback()) {
        return;
    }
    $options = stats_get_options();
    // Ensure this is always setup for the check below
    $options['reg_users'] = empty($options['reg_users']) ? false : true;
    if (!$options['reg_users'] && !empty($current_user->ID)) {
        return;
    }
    add_action('wp_footer', 'stats_footer', 101);
    add_action('wp_head', 'stats_add_shutdown_action');
    $blog = Jetpack::get_option('id');
    $v = 'ext';
    $j = sprintf('%s:%s', JETPACK__API_VERSION, JETPACK__VERSION);
    if ($wp_the_query->is_single || $wp_the_query->is_page || $wp_the_query->is_posts_page) {
        $post = $wp_the_query->get_queried_object_id();
    } else {
        $post = '0';
    }
    $http = is_ssl() ? 'https' : 'http';
    $week = gmdate('YW');
    $data = stats_array(compact('v', 'j', 'blog', 'post'));
    $stats_footer = <<<END

\t<script src="{$http}://stats.wordpress.com/e-{$week}.js" type="text/javascript"></script>
\t<script type="text/javascript">
\tst_go({{$data}});
\tvar load_cmc = function(){linktracker_init({$blog},{$post},2);};
\tif ( typeof addLoadEvent != 'undefined' ) addLoadEvent(load_cmc);
\telse load_cmc();
\t</script>
END;
    if (isset($options['hide_smile']) && $options['hide_smile']) {
        $stats_footer .= "\n<style type='text/css'>img#wpstats{display:none}</style>";
    }
}
Esempio n. 10
0
 /**
  * Add custom javascript within footer section.
  *
  * Note: I'm using double quotes instead of single quotes to maintain the script's original structure.
  *
  * @since 1.0.0
  */
 public function add_snippet()
 {
     if (\is_admin()) {
         return;
     }
     if (\is_feed()) {
         return;
     }
     if (\is_robots()) {
         return;
     }
     if (\is_trackback()) {
         return;
     }
     echo "<script><!--//--><![CDATA[//><!—\r\n";
     /**
      * Filter the default netscope analytics variable.
      *
      * @since  1.1.0
      * @param  string Default variable name.
      * @return string Possibly-modified variable name.
      */
     $netscope_var = \apply_filters('wpnetscope_default_netscope_var', 'GEMIUS');
     // netScope analytics tag
     printf("var %s = '%s';", \esc_html($netscope_var), \esc_html($this->get_netscope_tag()));
     // netScope account ID
     $identifier = trim(\get_option('netscope_gemius_identifier'));
     if (!empty($identifier)) {
         printf("var pp_gemius_identifier = '%s';", \esc_html($identifier));
     }
     // netScope extra parameters
     $extraparameters = $netscope_var;
     printf("var pp_gemius_extraparameters = new Array('gA='+%s);", \esc_html($extraparameters));
     echo "var pp_gemius_event = pp_gemius_event || function() {var x = window.gemius_sevents = window.gemius_sevents || []; x[x.length]=arguments;}; ( function(d,t) { var ex; try { var gt=d.createElement(t),s=d.getElementsByTagName(t)[0],l='http'+((location.protocol=='https:')?'s://secure':'://data'); gt.async='true'; gt.src=l+'.netscope.marktest.pt/netscope-gemius.js'; s.parentNode.appendChild(gt);} catch (ex){}}(document,'script'));";
     echo "\r\n//--><!]]></script>";
 }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
} else {
    // Process feeds and trackbacks even if not using themes.
    if (is_robots()) {
        do_action('do_robots');
        return;
    } else {
        if (is_feed()) {
            do_feed();
            return;
        } else {
            if (is_trackback()) {
                include ABSPATH . '/wp-trackback.php';
                return;
            }
        }
    }
}
Esempio n. 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;
    }
}
/**
 * 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  = ( !empty($_SERVER['HTTPS'] ) && strtolower($_SERVER['HTTPS']) == 'on' ) ? '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'), $redirect['query']);
		}
	}

	// These tests give us a WP-generated permalink
	if ( is_404() ) {
		$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_single() && !empty($_GET['p']) && ! $redirect_url ) {
			if ( $redirect_url = get_permalink(get_query_var('p')) )
				$redirect['query'] = remove_query_arg('p', $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_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 ( !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_category() && !empty($_GET['cat']) ) {
			if ( $redirect_url = get_category_link(get_query_var('cat')) )
				$redirect['query'] = remove_query_arg('cat', $redirect['query']);
		} elseif ( is_author() && !empty($_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['author']);
		}

	// 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/' . ( ( 'rss2' ==  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) : '' ) . user_trailingslashit($paged_redirect['path'], 'paged');
					}
				} 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(get_option('home'));
	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']);
	}

	// 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;
	}
}
Esempio n. 14
0
function stats_template_redirect()
{
    global $current_user, $stats_footer;
    if (is_feed() || is_robots() || is_trackback() || is_preview()) {
        return;
    }
    // Should we be counting this user's views?
    if (!empty($current_user->ID)) {
        $count_roles = stats_get_option('count_roles');
        if (!array_intersect($current_user->roles, $count_roles)) {
            return;
        }
    }
    add_action('wp_footer', 'stats_footer', 101);
    add_action('wp_head', 'stats_add_shutdown_action');
    $script = set_url_scheme('//stats.wp.com/e-' . gmdate('YW') . '.js');
    $data = stats_build_view_data();
    $data_stats_array = stats_array($data);
    $stats_footer = <<<END
<script type='text/javascript' src='{$script}' async defer></script>
<script type='text/javascript'>
\t_stq = window._stq || [];
\t_stq.push([ 'view', {{$data_stats_array}} ]);
\t_stq.push([ 'clickTrackerInit', '{$data['blog']}', '{$data['post']}' ]);
</script>

END;
}
Esempio n. 15
0
function wpcf7_cleanup_upload_files()
{
    if (is_admin() || 'GET' != $_SERVER['REQUEST_METHOD'] || is_robots() || is_feed() || is_trackback()) {
        return;
    }
    $dir = trailingslashit(wpcf7_upload_tmp_dir());
    if (!is_dir($dir) || !is_readable($dir) || !wp_is_writable($dir)) {
        return;
    }
    if ($handle = @opendir($dir)) {
        while (false !== ($file = readdir($handle))) {
            if ($file == "." || $file == ".." || $file == ".htaccess") {
                continue;
            }
            $mtime = @filemtime($dir . $file);
            if ($mtime && time() < $mtime + 60) {
                // less than 60 secs old
                continue;
            }
            wpcf7_rmdir_p(path_join($dir, $file));
        }
        closedir($handle);
    }
}
Esempio n. 16
0
 function mf_change_template()
 {
     global $post;
     // Check global post
     if (empty($post)) {
         return;
     }
     // Process feeds and trackbacks even if not using themes.
     if (is_robots()) {
         do_action('do_robots');
         return;
     } elseif (is_feed()) {
         do_feed();
         return;
     } elseif (is_trackback()) {
         include ABSPATH . 'wp-trackback.php';
         return;
     }
     // Check if the post has a special template
     $template = get_post_meta($post->ID, '_wp_mf_page_template', true);
     if (!$template || $template == 'default') {
         return;
     }
     $template = TEMPLATEPATH . '/' . $template;
     if ($template = apply_filters('template_include', $template)) {
         include $template;
         die;
     }
     return;
 }
Esempio n. 17
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;
    }
}
 /**
  * Gets post/page ID if current page is singular
  *
  * @since	3.1.2
  */
 public function is_single()
 {
     if ((is_single() || is_page()) && !is_front_page() && !is_preview() && !is_trackback() && !is_feed() && !is_robots()) {
         global $post;
         $this->current_post_id = is_object($post) ? $post->ID : 0;
     } else {
         $this->current_post_id = 0;
     }
 }
Esempio n. 19
0
 public function check_canonical_url($requested_url = '', $do_redirect = true)
 {
     global $wp_query, $post, $is_IIS;
     // don't redirect in same cases as WP
     if (is_trackback() || is_search() || is_comments_popup() || is_admin() || is_preview() || is_robots() || $is_IIS && !iis7_supports_permalinks()) {
         return;
     }
     // don't redirect mysite.com/?attachment_id= to mysite.com/en/?attachment_id=
     if (1 == $this->options['force_lang'] && is_attachment() && isset($_GET['attachment_id'])) {
         return;
     }
     // if the default language code is not hidden and the static front page url contains the page name
     // the customizer lands here and the code below would redirect to the list of posts
     if (isset($_POST['wp_customize'], $_POST['customized'])) {
         return;
     }
     // don't redirect if we are on a static front page
     if ($this->options['redirect_lang'] && isset($this->page_on_front) && is_page($this->page_on_front)) {
         return;
     }
     if (empty($requested_url)) {
         $requested_url = (is_ssl() ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
     }
     if (is_single() || is_page()) {
         if (isset($post->ID) && $this->model->is_translated_post_type($post->post_type)) {
             $language = $this->model->get_post_language((int) $post->ID);
         }
     } elseif (is_category() || is_tag() || is_tax()) {
         $obj = $wp_query->get_queried_object();
         if ($this->model->is_translated_taxonomy($obj->taxonomy)) {
             $language = $this->model->get_term_language((int) $obj->term_id);
         }
     } elseif ($wp_query->is_posts_page) {
         $obj = $wp_query->get_queried_object();
         $language = $this->model->get_post_language((int) $obj->ID);
     }
     if (empty($language)) {
         $language = $this->curlang;
         $redirect_url = $requested_url;
     } else {
         // first get the canonical url evaluated by WP
         $redirect_url = !($redirect_url = redirect_canonical($requested_url, false)) ? $requested_url : $redirect_url;
         // then get the right language code in url
         $redirect_url = $this->options['force_lang'] ? $this->links_model->switch_language_in_link($redirect_url, $language) : $this->links_model->remove_language_from_link($redirect_url);
         // works only for default permalinks
     }
     // allow plugins to change the redirection or even cancel it by setting $redirect_url to false
     $redirect_url = apply_filters('pll_check_canonical_url', $redirect_url, $language);
     // the language is not correctly set so let's redirect to the correct url for this object
     if ($do_redirect && $redirect_url && $requested_url != $redirect_url) {
         wp_redirect($redirect_url, 301);
         exit;
     }
     return $redirect_url;
 }
Esempio n. 20
0
 /**
  * Set the Headers for 404, if nothing is found for requested URL.
  *
  * Issue a 404 if a request doesn't match any posts and doesn't match
  * any object (e.g. an existing-but-empty category, tag, author) and a 404 was not already
  * issued, and if the request was not a search or the homepage.
  *
  * Otherwise, issue a 200.
  *
  * This sets headers after posts have been queried. handle_404() really means "handle status."
  * By inspecting the result of querying posts, seemingly successful requests can be switched to
  * a 404 so that canonical redirection logic can kick in.
  *
  * @since 2.0.0
  * @access public
  *
  * @global WP_Query $wp_query
  */
 public function handle_404()
 {
     global $wp_query;
     /**
      * Filter whether to short-circuit default header status handling.
      *
      * Returning a non-false value from the filter will short-circuit the handling
      * and return early.
      *
      * @since 4.5.0
      *
      * @param bool     $preempt  Whether to short-circuit default header status handling. Default false.
      * @param WP_Query $wp_query WordPress Query object.
      */
     if (false !== apply_filters('pre_handle_404', false, $wp_query)) {
         return;
     }
     // If we've already issued a 404, bail.
     if (is_404()) {
         return;
     }
     // Never 404 for the admin, robots, or if we found posts.
     if (is_admin() || is_robots() || $wp_query->posts) {
         $success = true;
         if (is_singular()) {
             $p = false;
             if ($wp_query->post instanceof WP_Post) {
                 $p = clone $wp_query->post;
             }
             // Only set X-Pingback for single posts that allow pings.
             if ($p && pings_open($p)) {
                 @header('X-Pingback: ' . get_bloginfo('pingback_url'));
             }
             // check for paged content that exceeds the max number of pages
             $next = '<!--nextpage-->';
             if ($p && false !== strpos($p->post_content, $next) && !empty($this->query_vars['page'])) {
                 $page = trim($this->query_vars['page'], '/');
                 $success = (int) $page <= substr_count($p->post_content, $next) + 1;
             }
         }
         if ($success) {
             status_header(200);
             return;
         }
     }
     // We will 404 for paged queries, as no posts were found.
     if (!is_paged()) {
         // Don't 404 for authors without posts as long as they matched an author on this site.
         $author = get_query_var('author');
         if (is_author() && is_numeric($author) && $author > 0 && is_user_member_of_blog($author)) {
             status_header(200);
             return;
         }
         // Don't 404 for these queries if they matched an object.
         if ((is_tag() || is_category() || is_tax() || is_post_type_archive()) && get_queried_object()) {
             status_header(200);
             return;
         }
         // Don't 404 for these queries either.
         if (is_home() || is_search() || is_feed()) {
             status_header(200);
             return;
         }
     }
     // Guess it's time to 404.
     $wp_query->set_404();
     status_header(404);
     nocache_headers();
 }
Esempio n. 21
0
 public function clean_permalink($headers)
 {
     if (is_robots() || get_query_var('sitemap')) {
         return;
     }
     global $wp_query;
     $options = get_wpseo_options();
     // Recreate current URL
     $cururl = 'http';
     if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") {
         $cururl .= "s";
     }
     $cururl .= "://";
     if ($_SERVER["SERVER_PORT"] != "80") {
         $cururl .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
     } else {
         $cururl .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
     }
     $properurl = '';
     if (is_singular()) {
         global $post;
         if (empty($post)) {
             $post = $wp_query->get_queried_object();
         }
         $properurl = get_permalink($post->ID);
         $page = get_query_var('page');
         if ($page && $page != 1) {
             $post = get_post($post->ID);
             $page_count = substr_count($post->post_content, '<!--nextpage-->');
             if ($page > $page_count + 1) {
                 $properurl = user_trailingslashit(trailingslashit($properurl) . ($page_count + 1));
             } else {
                 $properurl = user_trailingslashit(trailingslashit($properurl) . $page);
             }
         }
         // Fix reply to comment links, whoever decided this should be a GET variable?
         $result = preg_match('/(\\?replytocom=[^&]+)/', $_SERVER["REQUEST_URI"], $matches);
         if ($result) {
             $properurl .= str_replace('?replytocom=', '#comment-', $matches[0]);
         }
         // Prevent cleaning out posts & page previews for people capable of viewing them
         if (isset($_GET['preview']) && isset($_GET['preview_nonce']) && current_user_can('edit_post')) {
             $properurl = '';
         }
     } else {
         if (is_front_page()) {
             if ('posts' == get_option('show_on_front') && is_home()) {
                 $properurl = get_bloginfo('url') . '/';
             } elseif ('page' == get_option('show_on_front')) {
                 $properurl = get_permalink(get_option('page_on_front'));
             }
         } else {
             if (is_category() || is_tag() || is_tax()) {
                 $term = $wp_query->get_queried_object();
                 if (is_feed()) {
                     $properurl = get_term_feed_link($term, $term->taxonomy);
                 } else {
                     $properurl = get_term_link($term, $term->taxonomy);
                 }
             } else {
                 if (is_search()) {
                     $s = preg_replace('/(%20|\\+)/', ' ', get_search_query());
                     $properurl = get_bloginfo('url') . '/?s=' . rawurlencode($s);
                 } else {
                     if (is_404()) {
                         if (function_exists('is_multisite') && is_multisite() && !is_subdomain_install() && is_main_site()) {
                             if ($cururl == get_bloginfo('url') . '/blog/' || $cururl == get_bloginfo('url') . '/blog') {
                                 if (get_option('show_on_front') == 'page' && get_option('page_for_posts') != 0) {
                                     $properurl = get_permalink(get_option('page_for_posts'));
                                 } else {
                                     $properurl = get_bloginfo('url') . '/';
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     if (!empty($properurl) && $wp_query->query_vars['paged'] != 0 && $wp_query->post_count != 0) {
         if (is_search()) {
             $properurl = get_bloginfo('url') . '/page/' . $wp_query->query_vars['paged'] . '/?s=' . rawurlencode($s);
         } else {
             $properurl = user_trailingslashit(trailingslashit($properurl) . 'page/' . $wp_query->query_vars['paged']);
         }
     }
     // Prevent cleaning out the WP Subscription managers interface for everyone
     foreach (array('wp-subscription-manager') as $get) {
         if (isset($_GET[$get])) {
             $properurl = '';
         }
     }
     // Allow plugins to register their own variables not to clean
     $whitelisted_extravars = apply_filters('wpseo_whitelist_permalink_vars', array());
     if (isset($options['cleanpermalink-googlesitesearch']) && $options['cleanpermalink-googlesitesearch']) {
         // Prevent cleaning out Google Site searches
         $whitelisted_extravars = array_merge($whitelisted_extravars, array('q', 'cx', 'debug', 'cof', 'ie', 'sa'));
     }
     if (isset($options['cleanpermalink-googlecampaign']) && $options['cleanpermalink-googlecampaign']) {
         // Prevent cleaning out Google Analytics campaign variables
         $whitelisted_extravars = array_merge($whitelisted_extravars, array('utm_campaign', 'utm_medium', 'utm_source', 'utm_content', 'utm_term'));
     }
     if (isset($options['cleanpermalink-extravars']) && strlen($options['cleanpermalink-extravars']) > 0) {
         $whitelisted_extravars = array_merge($whitelisted_extravars, explode(',', $options['cleanpermalink-extravars']));
     }
     foreach ($whitelisted_extravars as $get) {
         if (isset($_GET[trim($get)])) {
             $properurl = '';
         }
     }
     if (!empty($properurl) && $cururl != $properurl) {
         wp_redirect($properurl, 301);
         exit;
     }
 }
Esempio n. 22
0
 function hook_template_redirect()
 {
     global $cache_stop, $hyper_cache_stop, $lite_cache_stop;
     if ($this->ob_started) {
         return;
     }
     $home_root = parse_url(get_option('home'), PHP_URL_PATH);
     if ($cache_stop || $hyper_cache_stop || $lite_cache_stop) {
     } else {
         if ($_SERVER['REQUEST_METHOD'] == 'POST') {
             $cache_stop = true;
         } else {
             if (!empty($_SERVER['QUERY_STRING'])) {
                 $cache_stop = true;
             } else {
                 if (is_user_logged_in()) {
                     $cache_stop = true;
                 } else {
                     if (is_trackback()) {
                         $cache_stop = true;
                     } else {
                         if (isset($this->options['reject_feeds']) && is_feed()) {
                             $cache_stop = true;
                         } else {
                             if (isset($this->options['reject_comment_feeds']) && is_comment_feed()) {
                                 $cache_stop = true;
                             } else {
                                 if (isset($this->options['reject_home']) && is_front_page()) {
                                     $cache_stop = true;
                                 } else {
                                     if (is_robots()) {
                                         $cache_stop = true;
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     if (defined('SID') && SID != '') {
         $cache_stop = true;
     } else {
         if (substr($_SERVER['REQUEST_URI'], 0, strlen($home_root) + 8) == $home_root . '/sitemap') {
             $cache_stop = true;
         } else {
             if (is_404()) {
                 if (isset($this->options['reject_404'])) {
                     $cache_stop = true;
                 } else {
                     $file = $this->get_folder() . '/' . substr(get_option('home'), strpos(get_option('home'), '://') + 3) . '/404.html';
                     if (file_exists($file) && ($this->options['max_age'] == 0 || filemtime($file) > time() - $this->options['max_age'] * 3600)) {
                         header('Content-Type: text/html;charset=UTF-8');
                         // For some reason it seems more performant than readfile...
                         header('X-Hyper-Cache: hit,404');
                         echo file_get_contents($file);
                         die;
                     }
                 }
             }
         }
     }
     if (!$cache_stop && substr($_SERVER['REQUEST_URI'], 0, strlen($home_root) + 4) == $home_root . '/wp-') {
         $cache_stop = true;
     }
     // URLs to reject (exact)
     if (!$cache_stop && isset($this->options['reject_uris_exact_enabled'])) {
         if (is_array($this->options['reject_uris_exact'])) {
             foreach ($this->options['reject_uris_exact'] as &$uri) {
                 if ($_SERVER['REQUEST_URI'] == $uri) {
                     $cache_stop = true;
                     break;
                 }
             }
         }
     }
     // URLs to reject
     if (!$cache_stop && isset($this->options['reject_uris_enabled'])) {
         if (is_array($this->options['reject_uris'])) {
             foreach ($this->options['reject_uris'] as &$uri) {
                 if (strpos($_SERVER['REQUEST_URI'], $uri) === 0) {
                     $cache_stop = true;
                     break;
                 }
             }
         }
     }
     if (!$cache_stop && !empty($this->options['reject_old_posts']) && is_single()) {
         global $post;
         if (strtotime($post->post_date_gmt) < time() - 86400 * $this->options['reject_old_posts']) {
             return;
         }
     }
     // If is not require to bypass the comment authors, remove the cookies so the page is generated without
     // comment moderation noticies
     if (!isset($this->options['reject_comment_authors'])) {
         foreach ($_COOKIE as $n => $v) {
             if (substr($n, 0, 14) == 'comment_author') {
                 unset($_COOKIE[$n]);
             }
         }
     }
     $this->ob_started = true;
     ob_start('hyper_cache_callback');
 }
Esempio n. 23
0
 public function templateLoad($defaultView = '')
 {
     global $posts, $post, $wp_did_header, $wp_query, $wp_rewrite, $wpdb, $wp_version, $wp, $id, $comment, $user_ID;
     $content = '';
     /**
      * Loads the correct template based on the visitor's url
      * @package WordPress
      */
     if (defined('WP_USE_THEMES') && WP_USE_THEMES) {
         do_action('template_redirect');
     }
     /**
      * Filter whether to allow 'HEAD' requests to generate content.
      *
      * Provides a significant performance bump by exiting before the page
      * content loads for 'HEAD' requests. See #14348.
      *
      * @since 3.5.0
      *
      * @param bool $exit Whether to exit without generating any content for 'HEAD' requests. Default true.
      */
     if ('HEAD' === $_SERVER['REQUEST_METHOD'] && apply_filters('exit_on_http_head', true)) {
         exit;
     }
     // Process feeds and trackbacks even if not using themes.
     if (is_robots()) {
         /**
          * Fired when the template loader determines a robots.txt request.
          *
          * @since 2.1.0
          */
         do_action('do_robots');
         return $content;
     } elseif (is_feed()) {
         do_feed();
         return $content;
     } elseif (is_trackback()) {
         include ABSPATH . 'wp-trackback.php';
         return $content;
     }
     if (defined('WP_USE_THEMES') && WP_USE_THEMES) {
         $template = false;
         if (is_404() && ($template = get_404_template())) {
         } elseif (is_search() && ($template = get_search_template())) {
         } elseif (is_front_page() && ($template = get_front_page_template())) {
         } elseif (is_home() && ($template = get_home_template())) {
         } elseif (is_post_type_archive() && ($template = get_post_type_archive_template())) {
         } elseif (is_tax() && ($template = get_taxonomy_template())) {
         } elseif (is_attachment() && ($template = get_attachment_template())) {
             remove_filter('the_content', 'prepend_attachment');
         } elseif (is_single() && ($template = get_single_template())) {
         } elseif (is_page() && ($template = get_page_template())) {
         } elseif (is_category() && ($template = get_category_template())) {
         } elseif (is_tag() && ($template = get_tag_template())) {
         } elseif (is_author() && ($template = get_author_template())) {
         } elseif (is_date() && ($template = get_date_template())) {
         } elseif (is_archive() && ($template = get_archive_template())) {
         } elseif (is_comments_popup() && ($template = get_comments_popup_template())) {
         } elseif (is_paged() && ($template = get_paged_template())) {
         } else {
             $template = get_index_template();
         }
         /**
          * Filter the path of the current template before including it.
          *
          * @since 3.0.0
          *
          * @param string $template The path of the template to include.
          */
         if ($template = apply_filters('template_include', $this->defaultView ?: $template)) {
             load_template($template, false);
         }
         return $content;
     }
 }
 /**
  * Is Active?
  *
  * @return  boolean  Is password protection active?
  */
 function is_active()
 {
     global $wp_query;
     // Always allow access to robots.txt
     if (isset($wp_query) && is_robots()) {
         return false;
     }
     if ((bool) get_option('password_protected_status')) {
         return true;
     }
     return false;
 }
 /**
  * Gets post/page ID if current page is singular
  *
  * @since	3.1.2
  */
 public function is_single()
 {
     $trackable = array();
     $registered_post_types = get_post_types(array('public' => true), 'names');
     foreach ($registered_post_types as $post_type) {
         $trackable[] = $post_type;
     }
     $trackable = apply_filters('wpp_trackable_post_types', $trackable);
     if (is_singular($trackable) && !is_front_page() && !is_preview() && !is_trackback() && !is_feed() && !is_robots()) {
         global $post;
         $this->current_post_id = is_object($post) ? $post->ID : 0;
     } else {
         $this->current_post_id = 0;
     }
 }
Esempio n. 26
0
 /**
  * Set the Headers for 404, if nothing is found for requested URL.
  *
  * Issue a 404 if a request doesn't match any posts and doesn't match
  * any object (e.g. an existing-but-empty category, tag, author) and a 404 was not already
  * issued, and if the request was not a search or the homepage.
  *
  * Otherwise, issue a 200.
  *
  * @since 2.0.0
  *
  * @global WP_Query $wp_query
  */
 public function handle_404()
 {
     global $wp_query;
     // If we've already issued a 404, bail.
     if (is_404()) {
         return;
     }
     // Never 404 for the admin, robots, or if we found posts.
     if (is_admin() || is_robots() || $wp_query->posts) {
         status_header(200);
         return;
     }
     // We will 404 for paged queries, as no posts were found.
     if (!is_paged()) {
         // Don't 404 for authors without posts as long as they matched an author on this site.
         $author = get_query_var('author');
         if (is_author() && is_numeric($author) && $author > 0 && is_user_member_of_blog($author)) {
             status_header(200);
             return;
         }
         // Don't 404 for these queries if they matched an object.
         if ((is_tag() || is_category() || is_tax() || is_post_type_archive()) && get_queried_object()) {
             status_header(200);
             return;
         }
         // Don't 404 for these queries either.
         if (is_home() || is_search() || is_feed()) {
             status_header(200);
             return;
         }
     }
     // Guess it's time to 404.
     $wp_query->set_404();
     status_header(404);
     nocache_headers();
 }
Esempio n. 27
0
 /**
  * Set the Headers for 404, if nothing is found for requested URL.
  *
  * Issue a 404 if a request doesn't match any posts and doesn't match
  * any object (e.g. an existing-but-empty category, tag, author) and a 404 was not already
  * issued, and if the request was not a search or the homepage.
  *
  * Otherwise, issue a 200.
  *
  * @since 2.0.0
  */
 function handle_404()
 {
     global $wp_query;
     // If we've already issued a 404, bail.
     if (is_404()) {
         return;
     }
     // Never 404 for the admin, robots, or if we found posts.
     if (is_admin() || is_robots() || $wp_query->posts) {
         status_header(200);
         return;
     }
     // We will 404 for paged queries, as no posts were found.
     if (!is_paged()) {
         // Don't 404 for these queries if they matched an object.
         if ((is_tag() || is_category() || is_tax() || is_author() || is_post_type_archive()) && $wp_query->get_queried_object()) {
             status_header(200);
             return;
         }
         // Don't 404 for these queries either.
         if (is_home() || is_search()) {
             status_header(200);
             return;
         }
     }
     // Guess it's time to 404.
     $wp_query->set_404();
     status_header(404);
     nocache_headers();
 }
/**
 * Outputs the given setting, if conditions are met
 *
 * @param string $option Option Name
 * @return output
 *
 * @since 3.0
 */
function HFScriptsIns_output($option)
{
    // Ignore admin, feed, robots or trackbacks
    if (is_admin() || is_feed() || is_robots() || is_trackback()) {
        return;
    }
    // Read options from BD and declare variables
    $options = get_option('HFScriptsIns_settings');
    $data = $options[$option];
    // If data is empty then exit
    if (empty($data)) {
        return;
    }
    // Add comments to output
    $data_out = "\n<!-- [BEGIN] Scripts added via Head-and-Footer-Scripts-Inserter plugin by Arthur Gareginyan. -->\n";
    $data_out .= $data;
    $data_out .= "\n<!-- [END] Scripts added via Head-and-Footer-Scripts-Inserter plugin by Arthur Gareginyan. -->\n\n";
    // Output
    echo $data_out;
}
Esempio n. 29
0
 /**
  * Removes unneeded query variables from the URL.
  * @return boolean
  */
 public function clean_permalink()
 {
     if (is_robots() || get_query_var('sitemap')) {
         return false;
     }
     global $wp_query;
     // Recreate current URL
     $cururl = 'http';
     if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
         $cururl .= 's';
     }
     $cururl .= '://';
     if ($_SERVER['SERVER_PORT'] != '80' && $_SERVER['SERVER_PORT'] != '443') {
         $cururl .= $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT'] . $_SERVER['REQUEST_URI'];
     } else {
         $cururl .= $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
     }
     $properurl = '';
     if (is_singular()) {
         global $post;
         if (empty($post)) {
             $post = $wp_query->get_queried_object();
         }
         $properurl = get_permalink($post->ID);
         $page = get_query_var('page');
         if ($page && $page != 1) {
             $post = get_post($post->ID);
             $page_count = substr_count($post->post_content, '<!--nextpage-->');
             if ($page > $page_count + 1) {
                 $properurl = user_trailingslashit(trailingslashit($properurl) . ($page_count + 1));
             } else {
                 $properurl = user_trailingslashit(trailingslashit($properurl) . $page);
             }
         }
         // Fix reply to comment links, whoever decided this should be a GET variable?
         $result = preg_match('`(\\?replytocom=[^&]+)`', $_SERVER['REQUEST_URI'], $matches);
         if ($result) {
             $properurl .= str_replace('?replytocom=', '#comment-', $matches[0]);
         }
         // Prevent cleaning out posts & page previews for people capable of viewing them
         if (isset($_GET['preview']) && isset($_GET['preview_nonce']) && current_user_can('edit_post')) {
             $properurl = '';
         }
     } elseif (is_front_page()) {
         if ($this->is_home_posts_page()) {
             $properurl = get_bloginfo('url') . '/';
         } elseif ($this->is_home_static_page()) {
             global $post;
             $properurl = get_permalink($post->ID);
         }
     } elseif (is_category() || is_tag() || is_tax()) {
         $term = $wp_query->get_queried_object();
         if (is_feed()) {
             $properurl = get_term_feed_link($term->term_id, $term->taxonomy);
         } else {
             $properurl = get_term_link($term, $term->taxonomy);
         }
     } elseif (is_search()) {
         $s = preg_replace('`(%20|\\+)`', ' ', get_search_query());
         $properurl = get_bloginfo('url') . '/?s=' . rawurlencode($s);
     } elseif (is_404()) {
         if (function_exists('is_multisite') && is_multisite() && !is_subdomain_install() && is_main_site()) {
             if ($cururl == get_bloginfo('url') . '/blog/' || $cururl == get_bloginfo('url') . '/blog') {
                 if ($this->is_home_static_page()) {
                     $properurl = get_permalink(get_option('page_for_posts'));
                 } else {
                     $properurl = get_bloginfo('url') . '/';
                 }
             }
         }
     }
     if (!empty($properurl) && $wp_query->query_vars['paged'] != 0 && $wp_query->post_count != 0) {
         if (is_search()) {
             $properurl = get_bloginfo('url') . '/page/' . $wp_query->query_vars['paged'] . '/?s=' . rawurlencode(get_search_query());
         } else {
             $properurl = user_trailingslashit(trailingslashit($properurl) . 'page/' . $wp_query->query_vars['paged']);
         }
     }
     // Prevent cleaning out the WP Subscription managers interface for everyone
     if (isset($_GET['wp-subscription-manager'])) {
         $properurl = '';
     }
     /**
      * Filter: 'wpseo_whitelist_permalink_vars' - Allow plugins to register their own variables not to clean
      *
      * @api array $unsigned Array of permalink variables _not_ to clean. Empty by default.
      */
     $whitelisted_extravars = apply_filters('wpseo_whitelist_permalink_vars', array());
     if ($this->options['cleanpermalink-googlesitesearch'] === true) {
         // Prevent cleaning out Google Site searches
         $whitelisted_extravars = array_merge($whitelisted_extravars, array('q', 'cx', 'debug', 'cof', 'ie', 'sa'));
     }
     if ($this->options['cleanpermalink-googlecampaign'] === true) {
         // Prevent cleaning out Google Analytics campaign variables
         $whitelisted_extravars = array_merge($whitelisted_extravars, array('utm_campaign', 'utm_medium', 'utm_source', 'utm_content', 'utm_term', 'utm_id', 'gclid'));
     }
     if ($this->options['cleanpermalink-extravars'] !== '') {
         $extravars = explode(',', $this->options['cleanpermalink-extravars']);
         $extravars = array_map('trim', $extravars);
         $whitelisted_extravars = array_merge($whitelisted_extravars, $extravars);
         unset($extravars);
     }
     foreach ($whitelisted_extravars as $get) {
         if (isset($_GET[trim($get)])) {
             $properurl = '';
         }
     }
     if (!empty($properurl) && $cururl != $properurl) {
         wp_safe_redirect($properurl, 301);
         exit;
     }
 }
/**
 * 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;
	}
}