예제 #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;
 }
예제 #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, '/');
        }
    }
}
예제 #4
0
/**
 *
 *
 * @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) {
        }
    }
}
예제 #5
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";
         }
     }
 }
예제 #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>";
    }
}
예제 #7
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;
 }
예제 #8
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>";
    }
}
예제 #9
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>";
 }
예제 #10
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;
 }
 /**
  * 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;
     }
 }
예제 #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 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;
    }
}
예제 #13
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);
    }
}
		exit;
	} else if ( is_date() && get_date_template() ) {
		include(get_date_template());
		exit;
	} else if ( is_archive() && get_archive_template() ) {
		include(get_archive_template());
		exit;
	} else if ( is_comments_popup() && get_comments_popup_template() ) {
		include(get_comments_popup_template());
		exit;
	} else if ( is_paged() && get_paged_template() ) {
		include(get_paged_template());
		exit;
	} else if ( file_exists(TEMPLATEPATH . "/index.php") ) {
		include(TEMPLATEPATH . "/index.php");
		exit;
	}
} else {
	// Process feeds and trackbacks even if not using themes.
	if ( is_feed() && empty($doing_rss) ) {
		include(ABSPATH . '/wp-feed.php');
		exit;
	} else if ( is_trackback() && empty($doing_trackback) ) {
		include(ABSPATH . '/wp-trackback.php');
		exit;
	}
}

endif;
?>
예제 #15
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;
 }
예제 #16
0
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;
} elseif (is_feed()) {
    do_feed();
    return;
} elseif (is_trackback()) {
    include ABSPATH . 'wp-trackback.php';
    return;
}
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())) {
 /**
  * If the language code is not in agreement with the language of the content
  * redirects incoming links to the proper URL to avoid duplicate content
  *
  * @since 0.9.6
  *
  * @param string $requested_url optional
  * @param bool   $do_redirect   optional, whether to perform the redirection or not
  * @return string if redirect is not performed
  */
 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_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;
     }
     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->post->get_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->term->get_language((int) $obj->term_id);
         }
     } elseif ($wp_query->is_posts_page) {
         $obj = $wp_query->get_queried_object();
         $language = $this->model->post->get_language((int) $obj->ID);
     } elseif (is_404() && !empty($wp_query->query['page_id']) && ($id = get_query_var('page_id'))) {
         // Special case for page shortlinks when using subdomains or multiple domains
         // Needed because redirect_canonical doesn't accept to change the domain name
         $language = $this->model->post->get_language((int) $id);
     }
     if (empty($language)) {
         $language = $this->curlang;
         $redirect_url = $requested_url;
     } else {
         // First get the canonical url evaluated by WP
         // Workaround a WP bug wich removes the port for some urls and get it back at second call to redirect_canonical
         $_redirect_url = !($_redirect_url = redirect_canonical($requested_url, false)) ? $requested_url : $_redirect_url;
         $redirect_url = !($redirect_url = redirect_canonical($_redirect_url, false)) ? $_redirect_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
     }
     /**
      * Filters the canonical url detected by Polylang
      *
      * @since 1.6
      *
      * @param bool|string $redirect_url false or the url to redirect to
      * @param object      $language the language detected
      */
     $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;
 }
 /**
  * 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;
     }
 }
예제 #19
0
function sandbox_comment_class($print = true)
{
    global $comment, $post, $sandbox_comment_alt;
    $c = array($comment->comment_type, "c{$sandbox_comment_alt}");
    if ($comment->user_id > 0) {
        $user = get_userdata($comment->user_id);
        $c[] = "byuser commentauthor-{$user->user_login}";
        if ($comment->user_id === $post->post_author) {
            $c[] = 'bypostauthor';
        }
    }
    sandbox_date_classes(mysql2date('U', $comment->comment_date), $c, 'c-');
    if (++$sandbox_comment_alt % 2) {
        $c[] = 'alt';
    }
    if (is_trackback()) {
        $c[] = 'trackback';
    }
    $c = join(' ', apply_filters('comment_class', $c));
    return $print ? print $c : $c;
}
예제 #20
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;
}
예제 #21
0
function rs_wpss_misc_form_spam_check()
{
    /***
     * Checks all miscellaneous form POST submissions for spam
     * Added 1.8.9.9
     ***/
    if (rs_wpss_is_user_admin() || rs_wpss_is_admin_sproc()) {
        return;
    }
    global $spamshield_options;
    if (empty($spamshield_options)) {
        $spamshield_options = get_option('spamshield_options');
    }
    rs_wpss_update_session_data($spamshield_options);
    if (!empty($spamshield_options['disable_misc_form_shield'])) {
        return;
    }
    $url = rs_wpss_get_url();
    $url_lc = rs_wpss_casetrans('lower', $url);
    $req_uri = $_SERVER['REQUEST_URI'];
    $req_uri_lc = rs_wpss_casetrans('lower', $req_uri);
    /* BYPASS - GENERAL */
    if (empty($_POST) || 'POST' !== $_SERVER['REQUEST_METHOD'] || isset($_POST[WPSS_REF2XJS]) || isset($_POST[WPSS_JSONST]) || isset($_POST['wpss_contact_message']) || isset($_POST['signup_username']) || isset($_POST['signup_email']) || isset($_POST['ws_plugin__s2member_registration']) || isset($_POST['_wpcf7_version']) || isset($_POST['gform_submit']) || isset($_POST['gform_unique_id'])) {
        return;
    }
    if (is_admin() && !rs_wpss_is_login_page()) {
        return;
    }
    if (rs_wpss_is_login_page() && (!isset($_GET['action']) || $_GET['action'] !== 'register')) {
        return;
    }
    if (rs_wpss_is_doing_ajax() || rs_wpss_is_doing_cron() || rs_wpss_is_xmlrpc() || defined('WP_INSTALLING')) {
        return;
    }
    if (rs_wpss_is_ajax_request() || rs_wpss_is_comment_request() || is_trackback()) {
        return;
    }
    if (current_user_can('moderate_comments')) {
        return;
    }
    if (is_user_logged_in()) {
        return;
    }
    /* May remove later */
    $post_count = count($_POST);
    if ($post_count == 4 && isset($_POST['excerpt'], $_POST['url'], $_POST['title'], $_POST['blog_name'])) {
        return;
    }
    $ip = rs_wpss_get_ip_addr();
    if ($ip === WPSS_SERVER_ADDR) {
        return;
    }
    /* Skip website IP address */
    if (strpos($ip, '.') !== FALSE) {
        $ip_arr = explode('.', $ip);
        unset($ip_arr[3]);
        $ip_c = implode('.', $ip_arr) . '.';
        if (strpos(WPSS_SERVER_ADDR, $ip_c) === 0) {
            return;
        }
        /* Skip anything on same C-Block as website */
    }
    $ecom_urls = array('/checkout/', '/store/', '/shop/', '/cart/');
    foreach ($ecom_urls as $k => $u) {
        if (strpos($req_uri, $u) !== FALSE) {
            return;
        }
    }
    $admin_url = WPSS_ADMIN_URL . '/';
    if ($post_count >= 5 && isset($_POST['log'], $_POST['pwd'], $_POST['wp-submit'], $_POST['testcookie'], $_POST['redirect_to']) && $_POST['redirect_to'] === $admin_url) {
        return;
    }
    if ($post_count >= 5 && isset($_POST['log'], $_POST['pwd'], $_POST['login'], $_POST['testcookie'], $_POST['redirect_to'])) {
        return;
    }
    if ($post_count >= 5 && isset($_POST['username'], $_POST['password'], $_POST['login'], $_POST['_wpnonce'], $_POST['_wp_http_referer']) && rs_wpss_is_wc_login_page()) {
        return;
    }
    if (WPSS_Compatibility::misc_form_bypass()) {
        return;
    }
    /* BYPASS - HOOK */
    $mfsc_bypass = apply_filters('wpss_misc_form_spam_check_bypass', FALSE);
    if (!empty($mfsc_bypass)) {
        return;
    }
    $msc_filter_status = $wpss_error_code = $log_pref = '';
    $msc_jsck_error = $msc_badrobot_error = FALSE;
    $form_type = 'misc form';
    $pref = 'MSC-';
    $errors_3p = array();
    $error_txt = rs_wpss_error_txt();
    $server_name = WPSS_SERVER_NAME;
    $server_email_domain = rs_wpss_get_email_domain($server_name);
    $msc_serial_post = serialize($_POST);
    $form_auth_dat = array('comment_author' => '', 'comment_author_email' => '', 'comment_author_url' => '');
    /* Check for Specific Contact Form Plugins */
    if (defined('JETPACK__VERSION') && isset($_POST['action']) && $_POST['action'] === 'grunion-contact-form') {
        $form_type = 'jetpack form';
        $pref = 'JP-';
    } elseif (defined('NF_PLUGIN_VERSION') && isset($_POST['_ninja_forms_display_submit'])) {
        $form_type = 'ninja forms';
        $pref = 'NF-';
    } elseif ((defined('MC4WP_VERSION') || defined('MC4WP_LITE_VERSION')) && (isset($_POST['_mc4wp_form_id']) || isset($_POST['_mc4wp_form_submit']))) {
        $form_type = 'mailchimp form';
        $pref = 'MCF-';
    }
    /* JS/JQUERY CHECK */
    $wpss_key_values = rs_wpss_get_key_values();
    $wpss_jq_key = $wpss_key_values['wpss_jq_key'];
    $wpss_jq_val = $wpss_key_values['wpss_jq_val'];
    if (TRUE === WPSS_COMPAT_MODE || defined('WPSS_SOFT_COMPAT_MODE')) {
        /* Fall back to FVFJS Keys instead of jQuery keys from jscripts.php */
        $wpss_jq_key = $wpss_key_values['wpss_js_key'];
        $wpss_jq_val = $wpss_key_values['wpss_js_val'];
    }
    $wpss_jsck_jquery_val = !empty($_POST[$wpss_jq_key]) ? $_POST[$wpss_jq_key] : '';
    if ($wpss_jsck_jquery_val !== $wpss_jq_val) {
        $wpss_error_code .= ' ' . $pref . 'JQHFT-5';
        $msc_jsck_error = TRUE;
        $err_cod = 'jsck_error';
        $err_msg = __('Sorry, there was an error. Please be sure JavaScript and Cookies are enabled in your browser and try again.', WPSS_PLUGIN_NAME);
        $errors_3p[$err_cod] = $err_msg;
    }
    if (!isset($_POST['wp-submit'])) {
        /* Don't use on default WordPress Login, Registration, or Forgot Email pages
        
        		/* EMAIL BLACKLIST */
        if ($form_type === 'mailchimp form') {
            foreach ($_POST as $k => $v) {
                if (!is_string($v)) {
                    continue;
                }
                $k_lc = rs_wpss_casetrans('lower', $k);
                $v_lc = rs_wpss_casetrans('lower', trim(stripslashes($v)));
                if (strpos($k_lc, 'email') !== FALSE) {
                    if (!is_email($v_lc)) {
                        $wpss_error_code .= ' ' . $pref . '9200E-BL';
                        if ($msc_jsck_error !== TRUE) {
                            $err_cod = 'blacklist_email_error';
                            $err_msg = __('Sorry, that email address is not allowed!') . ' ' . __('Please enter a valid email address.');
                            $errors_3p[$err_cod] = $err_msg;
                        }
                        break;
                    } elseif (is_email($v_lc)) {
                        $email_domain = rs_wpss_parse_email($v_lc, 'domain');
                        if ($email_domain === $server_email_domain) {
                            continue;
                        }
                        if (rs_wpss_email_blacklist_chk($v_lc)) {
                            $wpss_error_code .= ' ' . $pref . '9200E-BL';
                            if ($msc_jsck_error !== TRUE) {
                                $err_cod = 'blacklist_email_error';
                                $err_msg = __('Sorry, that email address is not allowed!') . ' ' . __('Please enter a valid email address.');
                                $errors_3p[$err_cod] = $err_msg;
                            }
                            break;
                        }
                    }
                }
            }
        } else {
            foreach ($_POST as $k => $v) {
                if (!is_string($v)) {
                    continue;
                }
                $k_lc = rs_wpss_casetrans('lower', $k);
                $v_lc = rs_wpss_casetrans('lower', trim(stripslashes($v)));
                if (strpos($k_lc, 'email') !== FALSE && is_email($v_lc)) {
                    $email_domain = rs_wpss_parse_email($v_lc, 'domain');
                    if ($email_domain === $server_email_domain) {
                        continue;
                    }
                    if (rs_wpss_email_blacklist_chk($v_lc)) {
                        $wpss_error_code .= ' ' . $pref . '9200E-BL';
                        if ($msc_jsck_error !== TRUE) {
                            $err_cod = 'blacklist_email_error';
                            $err_msg = __('Sorry, that email address is not allowed!') . ' ' . __('Please enter a valid email address.');
                            $errors_3p[$err_cod] = $err_msg;
                        }
                        break;
                    }
                }
            }
        }
        if ($form_type === 'jetpack form' || $form_type === 'ninja forms') {
            /* CONTACT FORM CONTENT BLACKLIST */
            foreach ($_POST as $k => $v) {
                if (!is_string($v)) {
                    continue;
                }
                $k_lc = rs_wpss_casetrans('lower', $k);
                $v_lc = rs_wpss_casetrans('lower', trim(stripslashes($v)));
                if ((strpos($k_lc, 'message') !== FALSE || strpos($k_lc, 'comment') !== FALSE) && rs_wpss_cf_content_blacklist_chk($v_lc)) {
                    $wpss_error_code .= ' ' . $pref . '10400C-BL';
                    if ($msc_jsck_error !== TRUE) {
                        $err_cod = 'blacklist_content_error';
                        $err_msg = __('Message appears to be spam.', WPSS_PLUGIN_NAME);
                        $errors_3p[$err_cod] = $err_msg;
                    }
                    break;
                }
            }
        }
        /* BAD ROBOT BLACKLIST */
        $bad_robot_filter_data = rs_wpss_bad_robot_blacklist_chk($form_type, $msc_filter_status);
        $msc_filter_status = $bad_robot_filter_data['status'];
        $bad_robot_blacklisted = $bad_robot_filter_data['blacklisted'];
        if (!empty($bad_robot_blacklisted)) {
            $wpss_error_code .= $bad_robot_filter_data['error_code'];
            $msc_badrobot_error = TRUE;
            if ($msc_jsck_error !== TRUE) {
                $err_cod = 'badrobot_error';
                $err_msg = __('That action is currently not allowed.');
                $errors_3p[$err_cod] = $err_msg;
            }
        }
        /* BLACKLISTED USER */
        if (empty($wpss_error_code) && rs_wpss_ubl_cache()) {
            $wpss_error_code .= ' ' . $pref . '0-BL';
            $err_cod = 'blacklisted_user_error';
            $err_msg = __('That action is currently not allowed.');
            /* TO DO: TRANSLATE */
            $errors_3p[$err_cod] = $err_msg;
        }
    }
    /* Done with Tests */
    $wpss_error_code = trim($wpss_error_code);
    if (strpos($wpss_error_code, '0-BL') !== FALSE) {
        rs_wpss_append_log_data('Blacklisted user detected. Miscellaneous forms have been temporarily disabled to prevent spam. ERROR CODE: ' . $wpss_error_code, FALSE);
    }
    if (!empty($wpss_error_code)) {
        rs_wpss_update_accept_status($form_auth_dat, 'r', 'Line: ' . __LINE__, $wpss_error_code);
        /* If enabled, run security check to make sure this POST submission wasn't a security threat: vulnerability probe or hack attempt */
        if (TRUE === WPSS_IP_BAN_ENABLE) {
            $wpss_security = new WPSS_Security();
            if ($wpss_security->check_post_sec()) {
                global $wpss_sec_threat;
                $wpss_sec_threat = TRUE;
            }
        }
        if (!empty($spamshield_options['comment_logging'])) {
            rs_wpss_log_data($form_auth_dat, $wpss_error_code, $form_type, $msc_serial_post);
        }
        if (TRUE === WPSS_IP_BAN_ENABLE) {
            if (!empty($wpss_sec_threat)) {
                $wpss_security->ip_ban();
            }
        }
    } else {
        rs_wpss_update_accept_status($form_auth_dat, 'a', 'Line: ' . __LINE__);
        if (!empty($spamshield_options['comment_logging']) && !empty($spamshield_options['comment_logging_all'])) {
            rs_wpss_log_data($form_auth_dat, $wpss_error_code, $form_type, $msc_serial_post);
        }
    }
    /* Now output error message */
    if (!empty($wpss_error_code)) {
        $error_msg = '';
        foreach ($errors_3p as $c => $m) {
            $error_msg .= '<strong>' . $error_txt . ':</strong> ' . $m . '<br /><br />' . WPSS_EOL;
        }
        $args = array('response' => '403');
        wp_die($error_msg, '', $args);
    }
}
예제 #22
0
 /**
  * HideMyWP::wp()
  * 
  * Disable WP components when permalink is enabled
  * @return
  */
 function wp()
 {
     if ((is_feed() || is_comment_feed()) && !isset($_GET['feed']) && !$this->opt('feed_enable')) {
         $this->block_access();
     }
     if (is_author() && !isset($_GET['author']) && !isset($_GET['author']) && !$this->opt('author_enable')) {
         $this->block_access();
     }
     if (is_search() && !isset($_GET['s']) && !$this->opt('search_enable')) {
         $this->block_access();
     }
     if (is_paged() && !isset($_GET['paged']) && !$this->opt('paginate_enable')) {
         $this->block_access();
     }
     if (is_page() && !isset($_GET['page_id']) && !isset($_GET['pagename']) && !$this->opt('page_enable')) {
         $this->block_access();
     }
     if (is_single() && !isset($_GET['p']) && !$this->opt('post_enable')) {
         $this->block_access();
     }
     if (is_category() && !isset($_GET['cat']) && !$this->opt('category_enable')) {
         $this->block_access();
     }
     if (is_tag() && !isset($_GET['tag']) && !$this->opt('tag_enable')) {
         $this->block_access();
     }
     if ((is_date() || is_time()) && !isset($_GET['monthnum']) && !isset($_GET['m']) && !isset($_GET['w']) && !isset($_GET['second']) && !isset($_GET['year']) && !isset($_GET['day']) && !isset($_GET['hour']) && !isset($_GET['second']) && !isset($_GET['minute']) && !isset($_GET['calendar']) && $this->opt('disable_archive')) {
         $this->block_access();
     }
     if ((is_tax() || is_post_type_archive() || is_trackback() || is_comments_popup() || is_attachment()) && !isset($_GET['post_type']) && !isset($_GET['taxonamy']) && !isset($_GET['attachment']) && !isset($_GET['attachment_id']) && !isset($_GET['preview']) && $this->opt('disable_other_wp')) {
         $this->block_access();
     }
     if (!is_404() && !is_home() && (stristr($_SERVER['HTTP_USER_AGENT'], 'BuiltWith') || stristr($_SERVER['HTTP_USER_AGENT'], '2ip.ru'))) {
         wp_redirect(home_url());
     }
 }
예제 #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;
     }
 }
예제 #24
0
function redirect_canonical($requested_url = NULL, $do_redirect = true)
{
    global $wp_rewrite, $posts, $is_IIS;
    if (is_feed() || is_trackback() || is_search() || is_comments_popup() || is_admin() || $is_IIS || isset($_POST) && count($_POST)) {
        return;
    }
    if (!$requested_url) {
        // build the URL in the address bar
        $requested_url = isset($_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
    $original['path'] = preg_replace('|/index\\.php$|', '/', $original['path']);
    $redirect = $original;
    $redirect_url = false;
    // 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() && isset($_GET['p'])) {
            if ($redirect_url = get_permalink(get_query_var('p'))) {
                $redirect['query'] = remove_query_arg('p', $redirect['query']);
            }
        } elseif (is_page() && isset($_GET['page_id'])) {
            if ($redirect_url = get_permalink(get_query_var('page_id'))) {
                $redirect['query'] = remove_query_arg('page_id', $redirect['query']);
            }
        } elseif (isset($_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') && isset($_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') && isset($_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() && isset($_GET['year'])) {
            if ($redirect_url = get_year_link(get_query_var('year'))) {
                $redirect['query'] = remove_query_arg('year', $redirect['query']);
            }
        } elseif (is_category() && isset($_GET['cat'])) {
            if ($redirect_url = get_category_link(get_query_var('cat'))) {
                $redirect['query'] = remove_query_arg('cat', $redirect['query']);
            }
        } elseif (is_author() && isset($_GET['author'])) {
            $author = get_userdata(get_query_var('author'));
            if (false !== $author && ($redirect_url = get_author_link(false, $author->ID, $author->user_nicename))) {
                $redirect['query'] = remove_query_arg('author', $redirect['author']);
            }
        }
        // paging
        if ($paged = get_query_var('paged')) {
            if ($paged > 0) {
                if (!$redirect_url) {
                    $redirect_url = $requested_url;
                }
                $paged_redirect = @parse_url($redirect_url);
                $paged_redirect['path'] = preg_replace('|/page/[0-9]+?(/+)?$|', '/', $paged_redirect['path']);
                // strip off any existing paging
                $paged_redirect['path'] = preg_replace('|/index.php/?$|', '/', $paged_redirect['path']);
                // strip off trailing /index.php/
                if ($paged > 1 && !is_single()) {
                    $paged_redirect['path'] = trailingslashit($paged_redirect['path']);
                    if ($wp_rewrite->using_index_permalinks() && strpos($paged_redirect['path'], '/index.php/') === false) {
                        $paged_redirect['path'] .= 'index.php/';
                    }
                    $paged_redirect['path'] .= user_trailingslashit("page/{$paged}", 'paged');
                } elseif (!is_home() && !is_single()) {
                    $paged_redirect['path'] = user_trailingslashit($paged_redirect['path'], 'paged');
                }
                $redirect_url = $paged_redirect['scheme'] . '://' . $paged_redirect['host'] . $paged_redirect['path'];
                $redirect['path'] = $paged_redirect['path'];
            }
            $redirect['query'] = remove_query_arg('paged', $redirect['query']);
        }
    }
    // tack on any additional query vars
    if ($redirect_url && $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'));
    $redirect['host'] = $user_home['host'];
    // Handle ports
    if (isset($user_home['port'])) {
        $redirect['port'] = $user_home['port'];
    } else {
        unset($redirect['port']);
    }
    // trailing /index.php/
    $redirect['path'] = preg_replace('|/index.php/$|', '/', $redirect['path']);
    // 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_home() || is_home() && 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') 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_home()) {
        $redirect['path'] = trailingslashit($redirect['path']);
    }
    // Always trailing slash the 'home' URL
    if ($redirect['path'] == $user_home['path']) {
        $redirect['path'] = trailingslashit($redirect['path']);
    }
    // Ignore differences in host capitalization, as this can lead to infinite redirects
    if (strtolower($original['host']) == strtolower($redirect['host'])) {
        $redirect['host'] = $original['host'];
    }
    if (array($original['host'], $original['port'], $original['path'], $original['query']) !== array($redirect['host'], $redirect['port'], $redirect['path'], $redirect['query'])) {
        $redirect_url = $redirect['scheme'] . '://' . $redirect['host'];
        if (isset($redirect['port'])) {
            $redirect_url .= ':' . $redirect['port'];
        }
        $redirect_url .= $redirect['path'];
        if ($redirect['query']) {
            $redirect_url .= '?' . $redirect['query'];
        }
    }
    if ($redirect_url && $redirect_url != $requested_url) {
        // var_dump($redirect_url); die();
        $redirect_url = apply_filters('redirect_canonical', $redirect_url, $requested_url);
        if ($do_redirect) {
            // protect against chained redirects
            if (!redirect_canonical($redirect_url, false)) {
                wp_redirect($redirect_url, 301);
                exit;
            } else {
                return false;
            }
        } else {
            return $redirect_url;
        }
    } else {
        return false;
    }
}
/**
 * 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;
	}
}
예제 #26
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');
 }
예제 #27
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;
    }
}
/**
 * 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;
}
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
} 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;
            }
        }
    }
}
/**
 * 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;
	}
}