public function do_analyze_page()
 {
     $rewrite_rules = $GLOBALS['wp_rewrite']->wp_rewrite_rules();
     $rewrite_rules_ui = array();
     $public_query_vars = apply_filters('query_vars', $GLOBALS['wp']->public_query_vars);
     $rewrite_patterns = array();
     // URL prefix
     $prefix = '';
     if (!got_mod_rewrite() && !iis7_supports_permalinks()) {
         $prefix = '/index.php';
     }
     $url_prefix = get_option('home') . $prefix . '/';
     $idx = 0;
     if ($rewrite_rules) {
         foreach ($rewrite_rules as $pattern => $substitution) {
             $idx++;
             $rewrite_patterns[$idx] = addslashes($pattern);
             $rewrite_rule_ui = array('pattern' => $pattern);
             try {
                 $regex_tree = Monkeyman_Regex::parse($pattern);
             } catch (Exception $e) {
                 $rewrite_rule_ui['error'] = $e;
             }
             $regex_groups = self::collect_groups($regex_tree);
             $rewrite_rule_ui['print'] = self::print_regex($regex_tree, $idx);
             $substitution_parts = self::parse_substitution($substitution);
             $substitution_parts_ui = array();
             foreach ($substitution_parts as $query_var => $query_value) {
                 $substitution_part_ui = array('query_var' => $query_var, 'query_value' => $query_value);
                 $query_value_ui = $query_value;
                 // Replace `$matches[DD]` with URL regex part
                 // This is so complicated to handle situations where `$query_value` contains multiple `$matches[DD]`
                 $query_value_replacements = array();
                 if (preg_match_all('/\\$matches\\[(\\d+)\\]/', $query_value, $matches, PREG_OFFSET_CAPTURE)) {
                     foreach ($matches[0] as $m_idx => $match) {
                         $regex_group_idx = $matches[1][$m_idx][0];
                         $query_value_replacements[$match[1]] = array('replacement' => self::print_regex($regex_groups[$regex_group_idx], $idx, true), 'length' => strlen($match[0]), 'offset' => $match[1]);
                     }
                 }
                 krsort($query_value_replacements);
                 foreach ($query_value_replacements as $query_value_replacement) {
                     $query_value_ui = substr_replace($query_value_ui, $query_value_replacement['replacement'], $query_value_replacement['offset'], $query_value_replacement['length']);
                 }
                 $substitution_part_ui['query_value_ui'] = $query_value_ui;
                 // Highlight non-public query vars
                 $substitution_part_ui['is_public'] = in_array($query_var, $public_query_vars);
                 $substitution_parts_ui[] = $substitution_part_ui;
             }
             $rewrite_rule_ui['substitution_parts'] = $substitution_parts_ui;
             $rewrite_rules_ui[$idx] = $rewrite_rule_ui;
         }
     }
     wp_localize_script($this->gettext_domain, 'Monkeyman_Rewrite_Analyzer_Regexes', $rewrite_patterns);
     $gettext_domain = $this->gettext_domain;
     include dirname($this->base_file) . '/ui/rewrite-analyzer.php';
 }
Beispiel #2
0
 /**
  * Update the permalink structure.
  *
  * ## DESCRIPTION
  *
  * Updates the post permalink structure.
  *
  * To regenerate a .htaccess file with WP-CLI, you'll need to add the mod_rewrite module
  * to your wp-cli.yml or config.yml. For example:
  *
  * apache_modules:
  *   - mod_rewrite
  *
  * ## OPTIONS
  *
  * <permastruct>
  * : The new permalink structure to apply.
  *
  * [--category-base=<base>]
  * : Set the base for category permalinks, i.e. '/category/'.
  *
  * [--tag-base=<base>]
  * : Set the base for tag permalinks, i.e. '/tag/'.
  *
  * [--hard]
  * : Perform a hard flush - update `.htaccess` rules as well as rewrite rules in database.
  *
  * ## EXAMPLES
  *
  *     wp rewrite structure '/%year%/%monthnum%/%postname%'
  */
 public function structure($args, $assoc_args)
 {
     global $wp_rewrite;
     // copypasta from /wp-admin/options-permalink.php
     $home_path = get_home_path();
     $iis7_permalinks = iis7_supports_permalinks();
     $prefix = $blog_prefix = '';
     if (!got_mod_rewrite() && !$iis7_permalinks) {
         $prefix = '/index.php';
     }
     if (is_multisite() && !is_subdomain_install() && is_main_site()) {
         $blog_prefix = '/blog';
     }
     $permalink_structure = $args[0] == 'default' ? '' : $args[0];
     if (!empty($permalink_structure)) {
         $permalink_structure = preg_replace('#/+#', '/', '/' . str_replace('#', '', $permalink_structure));
         if ($prefix && $blog_prefix) {
             $permalink_structure = $prefix . preg_replace('#^/?index\\.php#', '', $permalink_structure);
         } else {
             $permalink_structure = $blog_prefix . $permalink_structure;
         }
     }
     $wp_rewrite->set_permalink_structure($permalink_structure);
     // Update category or tag bases
     if (isset($assoc_args['category-base'])) {
         $category_base = $assoc_args['category-base'];
         if (!empty($category_base)) {
             $category_base = $blog_prefix . preg_replace('#/+#', '/', '/' . str_replace('#', '', $category_base));
         }
         $wp_rewrite->set_category_base($category_base);
     }
     if (isset($assoc_args['tag-base'])) {
         $tag_base = $assoc_args['tag-base'];
         if (!empty($tag_base)) {
             $tag_base = $blog_prefix . preg_replace('#/+#', '/', '/' . str_replace('#', '', $tag_base));
         }
         $wp_rewrite->set_tag_base($tag_base);
     }
     // make sure we detect mod_rewrite if configured in apache_modules in config
     self::apache_modules();
     // Launch a new process to flush rewrites because core expects flush
     // to happen after rewrites are set
     $new_assoc_args = array();
     if (\WP_CLI\Utils\get_flag_value($assoc_args, 'hard')) {
         $new_assoc_args['hard'] = true;
         if (!in_array('mod_rewrite', (array) WP_CLI::get_config('apache_modules'))) {
             WP_CLI::warning("Regenerating a .htaccess file requires special configuration. See usage docs.");
         }
     }
     $process_run = WP_CLI::launch_self('rewrite flush', array(), $new_assoc_args, true, true, array('apache_modules', WP_CLI::get_config('apache_modules')));
     if (!empty($process_run->stderr)) {
         // Strip "Warning: "
         WP_CLI::warning(substr($process_run->stderr, 9));
     }
     WP_CLI::success("Rewrite structure set.");
 }
Beispiel #3
0
 /**
  * Update the permalink structure.
  *
  * ## OPTIONS
  *
  * <permastruct>
  * : The new permalink structure to apply.
  *
  * [--category-base=<base>]
  * : Set the base for category permalinks, i.e. '/category/'.
  *
  * [--tag-base=<base>]
  * : Set the base for tag permalinks, i.e. '/tag/'.
  *
  * [--hard]
  * : Perform a hard flush - update `.htaccess` rules as well as rewrite rules in database.
  *
  * ## EXAMPLES
  *
  *     wp rewrite structure '/%year%/%monthnum%/%postname%'
  */
 public function structure($args, $assoc_args)
 {
     global $wp_rewrite;
     // copypasta from /wp-admin/options-permalink.php
     $home_path = get_home_path();
     $iis7_permalinks = iis7_supports_permalinks();
     $prefix = $blog_prefix = '';
     if (!got_mod_rewrite() && !$iis7_permalinks) {
         $prefix = '/index.php';
     }
     if (is_multisite() && !is_subdomain_install() && is_main_site()) {
         $blog_prefix = '/blog';
     }
     $permalink_structure = $args[0] == 'default' ? '' : $args[0];
     if (!empty($permalink_structure)) {
         $permalink_structure = preg_replace('#/+#', '/', '/' . str_replace('#', '', $permalink_structure));
         if ($prefix && $blog_prefix) {
             $permalink_structure = $prefix . preg_replace('#^/?index\\.php#', '', $permalink_structure);
         } else {
             $permalink_structure = $blog_prefix . $permalink_structure;
         }
     }
     $wp_rewrite->set_permalink_structure($permalink_structure);
     // Update category or tag bases
     if (isset($assoc_args['category-base'])) {
         $category_base = $assoc_args['category-base'];
         if (!empty($category_base)) {
             $category_base = $blog_prefix . preg_replace('#/+#', '/', '/' . str_replace('#', '', $category_base));
         }
         $wp_rewrite->set_category_base($category_base);
     }
     if (isset($assoc_args['tag-base'])) {
         $tag_base = $assoc_args['tag-base'];
         if (!empty($tag_base)) {
             $tag_base = $blog_prefix . preg_replace('#/+#', '/', '/' . str_replace('#', '', $tag_base));
         }
         $wp_rewrite->set_tag_base($tag_base);
     }
     // make sure we detect mod_rewrite if configured in apache_modules in config
     self::apache_modules();
     // Launch a new process to flush rewrites because core expects flush
     // to happen after rewrites are set
     $new_assoc_args = array();
     if (isset($assoc_args['hard'])) {
         $new_assoc_args['hard'] = true;
     }
     \WP_CLI::launch_self('rewrite flush', array(), $new_assoc_args);
     WP_CLI::success("Rewrite structure set.");
 }
Beispiel #4
0
 /**
  * Set permalink structure
  *
  * @param array $args
  * @param array $assoc_args
  */
 public function structure($args, $assoc_args)
 {
     if (!count($args) && !count($assoc_args)) {
         WP_CLI::line("usage: wp rewrite structure <new-permalink-structure>");
         exit;
     }
     global $wp_rewrite;
     // copypasta from /wp-admin/options-permalink.php
     $home_path = get_home_path();
     $iis7_permalinks = iis7_supports_permalinks();
     $prefix = $blog_prefix = '';
     if (!got_mod_rewrite() && !$iis7_permalinks) {
         $prefix = '/index.php';
     }
     if (is_multisite() && !is_subdomain_install() && is_main_site()) {
         $blog_prefix = '/blog';
     }
     // Update base permastruct if argument is provided
     if (isset($args[0])) {
         $permalink_structure = $args[0] == 'default' ? '' : $args[0];
         if (!empty($permalink_structure)) {
             $permalink_structure = preg_replace('#/+#', '/', '/' . str_replace('#', '', $permalink_structure));
             if ($prefix && $blog_prefix) {
                 $permalink_structure = $prefix . preg_replace('#^/?index\\.php#', '', $permalink_structure);
             } else {
                 $permalink_structure = $blog_prefix . $permalink_structure;
             }
         }
         $wp_rewrite->set_permalink_structure($permalink_structure);
     }
     // Update category or tag bases
     if (isset($assoc_args['category-base'])) {
         $category_base = $assoc_args['category-base'];
         if (!empty($category_base)) {
             $category_base = $blog_prefix . preg_replace('#/+#', '/', '/' . str_replace('#', '', $category_base));
         }
         $wp_rewrite->set_category_base($category_base);
     }
     if (isset($assoc_args['tag-base'])) {
         $tag_base = $assoc_args['tag-base'];
         if (!empty($tag_base)) {
             $tag_base = $blog_prefix . preg_replace('#/+#', '/', '/' . str_replace('#', '', $tag_base));
         }
         $wp_rewrite->set_tag_base($tag_base);
     }
     flush_rewrite_rules($hard);
 }
function bogo_post_rewrite_rules($post_rewrite)
{
    global $wp_rewrite;
    $permastruct = $wp_rewrite->permalink_structure;
    // from wp-admin/includes/misc.php
    $got_rewrite = apply_filters('got_rewrite', apache_mod_loaded('mod_rewrite', true));
    $got_url_rewrite = apply_filters('got_url_rewrite', $got_rewrite || $GLOBALS['is_nginx'] || iis7_supports_permalinks());
    if (!$got_url_rewrite) {
        $permastruct = preg_replace('#^/index\\.php#', '/index.php/%lang%', $permastruct);
    } elseif (is_multisite() && !is_subdomain_install() && is_main_site()) {
        $permastruct = preg_replace('#^/blog#', '/%lang%/blog', $permastruct);
    } else {
        $permastruct = preg_replace('#^/#', '/%lang%/', $permastruct);
    }
    $extra = bogo_generate_rewrite_rules($permastruct, array('ep_mask' => EP_PERMALINK, 'paged' => false));
    return array_merge($extra, $post_rewrite);
}
 function aletheme_activation_is_config_writable()
 {
     $home_path = get_home_path();
     $iis7_permalinks = iis7_supports_permalinks();
     if ($iis7_permalinks) {
         if (!file_exists($home_path . 'web.config') && win_is_writable($home_path) || win_is_writable($home_path . 'web.config')) {
             $config_writable = true;
         } else {
             $config_writable = false;
         }
     } else {
         if (!file_exists($home_path . '.htaccess') && is_writable($home_path) || is_writable($home_path . '.htaccess')) {
             $config_writable = true;
         } else {
             $config_writable = false;
         }
     }
     return $config_writable;
 }
function modify_permalinks($permalink_structure, $page_structure)
{
    require_once ABSPATH . 'wp-admin/includes/file.php';
    require_once ABSPATH . 'wp-admin/includes/misc.php';
    global $wp_rewrite;
    # set the structure
    $wp_rewrite->set_permalink_structure($permalink_structure);
    $wp_rewrite->page_structure = $page_structure;
    # get paths
    $home_path = get_home_path();
    $iis7_permalinks = iis7_supports_permalinks();
    # check if there is a file to rewrite
    if ($iis7_permalinks) {
        $writable = !file_exists($home_path . 'web.config') && win_is_writable($home_path);
        $writable = $writable || win_is_writable($home_path . 'web.config');
    } else {
        $writable = !file_exists($home_path . '.htaccess') && is_writable($home_path);
        $writable = $writable || is_writable($home_path . '.htaccess');
    }
    # flush the rules
    update_option('rewrite_rules', FALSE);
    $wp_rewrite->flush_rules($writable);
}
    function step_permalinks_save()
    {
        global $nxt_rewrite, $current_site, $current_blog;
        // Prevent debug notices
        $iis7_permalinks = $usingpi = $writable = false;
        if (isset($_POST['submit'])) {
            check_admin_referer('bpwizard_permalinks');
            $home_path = get_home_path();
            $iis7_permalinks = iis7_supports_permalinks();
            if (isset($_POST['permalink_structure'])) {
                $permalink_structure = $_POST['permalink_structure'];
                if (!empty($permalink_structure)) {
                    $permalink_structure = preg_replace('#/+#', '/', '/' . $_POST['permalink_structure']);
                }
                if (defined('VHOST') && constant('VHOST') == 'no' && $permalink_structure != '' && $current_site->domain . $current_site->path == $current_blog->domain . $current_blog->path) {
                    $permalink_structure = '/blog' . $permalink_structure;
                }
                $nxt_rewrite->set_permalink_structure($permalink_structure);
            }
            if (!empty($iis7_permalinks)) {
                if (!file_exists($home_path . 'web.config') && win_is_writable($home_path) || win_is_writable($home_path . 'web.config')) {
                    $writable = true;
                }
            } else {
                if (!file_exists($home_path . '.htaccess') && is_writable($home_path) || is_writable($home_path . '.htaccess')) {
                    $writable = true;
                }
            }
            if ($nxt_rewrite->using_index_permalinks()) {
                $usingpi = true;
            }
            $nxt_rewrite->flush_rules();
            if (!empty($iis7_permalinks) || empty($usingpi) && empty($writable)) {
                function _bp_core_wizard_step_permalinks_message()
                {
                    global $nxt_rewrite;
                    ?>

					<div id="message" class="updated fade"><p>

						<?php 
                    _e('Oops, there was a problem creating a configuration file. ', 'buddypress');
                    if (!empty($iis7_permalinks)) {
                        if (!empty($permalink_structure) && empty($usingpi) && empty($writable)) {
                            _e('If your <code>web.config</code> file were <a href="http://codex.nxtclass.org/Changing_File_Permissions">writable</a>, we could do this automatically, but it isn&#8217;t so this is the url rewrite rule you should have in your <code>web.config</code> file. Click in the field and press <kbd>CTRL + a</kbd> to select all. Then insert this rule inside of the <code>/&lt;configuration&gt;/&lt;system.webServer&gt;/&lt;rewrite&gt;/&lt;rules&gt;</code> element in <code>web.config</code> file.');
                            ?>

									<br /><br />

									<textarea rows="9" class="large-text readonly" style="background: #fff;" name="rules" id="rules" readonly="readonly"><?php 
                            echo esc_html($nxt_rewrite->iis7_url_rewrite_rules());
                            ?>
</textarea>

								<?php 
                        } else {
                            if (!empty($permalink_structure) && empty($usingpi) && !empty($writable)) {
                            }
                        }
                        _e('Permalink structure updated. Remove write access on web.config file now!');
                    } else {
                        _e('If your <code>.htaccess</code> file were <a href="http://codex.nxtclass.org/Changing_File_Permissions">writable</a>, we could do this automatically, but it isn&#8217;t so these are the mod_rewrite rules you should have in your <code>.htaccess</code> file. Click in the field and press <kbd>CTRL + a</kbd> to select all.');
                        ?>

								<br /><br />

								<textarea rows="6" class="large-text readonly" style="background: #fff;" name="rules" id="rules" readonly="readonly"><?php 
                        echo esc_html($nxt_rewrite->mod_rewrite_rules());
                        ?>
</textarea>

							<?php 
                    }
                    ?>

						<br /><br />

						<?php 
                    if (empty($iis7_permalinks)) {
                        _e('Paste all these rules into a new <code>.htaccess</code> file in the root of your NXTClass installation and save the file. Once you\'re done, please hit the "Save and Next" button to continue.', 'buddypress');
                    }
                    ?>

					</p></div>

				<?php 
                }
                if ('post' == strtolower($_SERVER['REQUEST_METHOD']) && !empty($_POST['skip-htaccess'])) {
                    return true;
                } else {
                    add_action('bp_admin_notices', '_bp_core_wizard_step_permalinks_message');
                    return false;
                }
            }
            return true;
        }
        return false;
    }
 function save_file_cache()
 {
     if (iis7_supports_permalinks()) {
         return;
     }
     global $rhc_plugin;
     if ('1' == $rhc_plugin->get_option('file_cache', '', true)) {
         $content = $this->get_htaccess();
         $rules_arr = explode("\n", $content);
     } else {
         $rules_arr = array();
     }
     $filename = get_home_path() . '.htaccess';
     if (file_exists($filename) && is_writeable($filename)) {
         $str = file_get_contents($filename);
         if (false === strpos($str, 'BEGIN RHC')) {
             $prepend = "# BEGIN RHC\n";
             $prepend .= "# END RHC\n";
             $str = $prepend . $str;
             file_put_contents($filename, $str);
         }
     }
     insert_with_markers($filename, 'RHC', $rules_arr);
 }
 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;
 }
Beispiel #11
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;
    }
}
function bps_check_iis_supports_permalinks()
{
    global $wp_rewrite, $is_IIS, $is_iis7, $current_user;
    $user_id = $current_user->ID;
    if (current_user_can('manage_options') && $is_IIS && !iis7_supports_permalinks()) {
        if (!get_user_meta($user_id, 'bps_ignore_iis_notice')) {
            if (esc_html($_SERVER['QUERY_STRING']) == '' && basename(esc_html($_SERVER['REQUEST_URI'])) != 'wp-admin') {
                $bps_base = basename(esc_html($_SERVER['REQUEST_URI'])) . '?';
            } elseif (esc_html($_SERVER['QUERY_STRING']) == '' && basename(esc_html($_SERVER['REQUEST_URI'])) == 'wp-admin') {
                $bps_base = basename(str_replace('wp-admin', 'index.php?', esc_html($_SERVER['REQUEST_URI'])));
            } else {
                $bps_base = str_replace(admin_url(), '', esc_html($_SERVER['REQUEST_URI'])) . '&';
            }
            $text = '<div class="update-nag" style="background-color:#ffffe0;font-size:1em;font-weight:bold;padding:2px 5px;margin-top:2px;"><font color="red">' . __('WARNING! BPS has detected that your Server is a Windows IIS Server that does not support htaccess rewriting.', 'bulletproof-security') . '</font><br>' . __('Do NOT activate BulletProof Modes unless you know what you are doing.', 'bulletproof-security') . '<br>' . __('Your Server Type is: ', 'bulletproof-security') . $_SERVER['SERVER_SOFTWARE'] . '<br><a href="http://codex.wordpress.org/Using_Permalinks" target="_blank" title="This link will open in a new browser window.">' . __('WordPress Codex - Using Permalinks - see IIS section', 'bulletproof-security') . '</a><br>' . __('To Dismiss this Notice click the Dismiss Notice button below. To Reset Dismiss Notices click the Reset|Recheck Dismiss Notices button on the Security Status page.', 'bulletproof-security') . '<br><div style="float:left;margin:3px 0px 3px 0px;padding:2px 6px 2px 6px;background-color:#e8e8e8;border:1px solid gray;"><a href="' . $bps_base . 'bps_iis_nag_ignore=0' . '" style="text-decoration:none;font-weight:bold;">' . __('Dismiss Notice', 'bulletproof-security') . '</a></div></div>';
            echo $text;
        }
    }
}
Beispiel #13
0
function bps_check_iis_supports_permalinks()
{
    global $wp_rewrite, $is_IIS, $is_iis7;
    if ($is_IIS && !iis7_supports_permalinks()) {
        $text = '<br><font color="red"><strong>' . __('WARNING! BPS has detected that your Server is a Windows IIS Server that does not support .htaccess rewriting. Do NOT activate BulletProof Security Modes unless you are absolutely sure you know what you are doing. Your Server Type is: ', 'bulletproof-security') . $_SERVER['SERVER_SOFTWARE'] . '</strong></font><br><strong><a href="http://codex.wordpress.org/Using_Permalinks" target="_blank">' . __(' WordPress Codex - Using Permalinks - see IIS section ', 'bulletproof-security') . '</a></strong><br><strong>' . __('This link will open in a new browser window. You will not be directed away from your WordPress Dashboard.', 'bulletproof-security') . '</strong><br>' . __('To remove this message permanently click ', 'bulletproof-security') . '<strong><a href="http://www.ait-pro.com/aitpro-blog/2566/bulletproof-security-plugin-support/bulletproof-security-error-messages" target="_blank">' . __('here.', 'bulletproof-security') . '</a></strong><br>';
        echo $text;
    } else {
        echo '';
    }
}
Beispiel #14
0
 * @subpackage Administration
 */
/** WordPress Administration Bootstrap */
require_once dirname(__FILE__) . '/admin.php';
if (!current_user_can('manage_options')) {
    wp_die(__('You do not have sufficient permissions to manage options for this site.'));
}
$title = __('Permalink Settings');
$parent_file = 'options-general.php';
get_current_screen()->add_help_tab(array('id' => 'overview', 'title' => __('Overview'), 'content' => '<p>' . __('Permalinks are the permanent URLs to your individual pages and blog posts, as well as your category and tag archives. A permalink is the web address used to link to your content. The URL to each post should be permanent, and never change &#8212; hence the name permalink.') . '</p>' . '<p>' . __('This screen allows you to choose your default permalink structure. You can choose from common settings or create custom URL structures.') . '</p>' . '<p>' . __('You must click the Save Changes button at the bottom of the screen for new settings to take effect.') . '</p>'));
get_current_screen()->add_help_tab(array('id' => 'common-settings', 'title' => __('Common Settings'), 'content' => '<p>' . __('Many people choose to use &#8220;pretty permalinks,&#8221; URLs that contain useful information such as the post title rather than generic post ID numbers. You can choose from any of the permalink formats under Common Settings, or can craft your own if you select Custom Structure.') . '</p>' . '<p>' . __('If you pick an option other than Default, your general URL path with structure tags, terms surrounded by <code>%</code>, will also appear in the custom structure field and your path can be further modified there.') . '</p>' . '<p>' . __('When you assign multiple categories or tags to a post, only one can show up in the permalink: the lowest numbered category. This applies if your custom structure includes <code>%category%</code> or <code>%tag%</code>.') . '</p>' . '<p>' . __('You must click the Save Changes button at the bottom of the screen for new settings to take effect.') . '</p>'));
get_current_screen()->add_help_tab(array('id' => 'custom-structures', 'title' => __('Custom Structures'), 'content' => '<p>' . __('The Optional fields let you customize the &#8220;category&#8221; and &#8220;tag&#8221; base names that will appear in archive URLs. For example, the page listing all posts in the &#8220;Uncategorized&#8221; category could be <code>/topics/uncategorized</code> instead of <code>/category/uncategorized</code>.') . '</p>' . '<p>' . __('You must click the Save Changes button at the bottom of the screen for new settings to take effect.') . '</p>'));
get_current_screen()->set_help_sidebar('<p><strong>' . __('For more information:') . '</strong></p>' . '<p>' . __('<a href="https://codex.wordpress.org/Settings_Permalinks_Screen" target="_blank">Documentation on Permalinks Settings</a>') . '</p>' . '<p>' . __('<a href="https://codex.wordpress.org/Using_Permalinks" target="_blank">Documentation on Using Permalinks</a>') . '</p>' . '<p>' . __('<a href="https://wordpress.org/support/" target="_blank">Support Forums</a>') . '</p>');
add_filter('admin_head', 'options_permalink_add_js');
$home_path = get_home_path();
$iis7_permalinks = iis7_supports_permalinks();
$prefix = $blog_prefix = '';
if (!got_url_rewrite()) {
    $prefix = '/index.php';
}
if (is_multisite() && !is_subdomain_install() && is_main_site()) {
    $blog_prefix = '/blog';
}
if (isset($_POST['permalink_structure']) || isset($_POST['category_base'])) {
    check_admin_referer('update-permalink');
    if (isset($_POST['permalink_structure'])) {
        if (isset($_POST['selection']) && 'custom' != $_POST['selection']) {
            $permalink_structure = $_POST['selection'];
        } else {
            $permalink_structure = $_POST['permalink_structure'];
        }
Beispiel #15
0
/**
 * Updates the IIS web.config file with the current rules if it is writable.
 * If the permalinks do not require rewrite rules then the rules are deleted from the web.config file.
 *
 * @since 2.8.0
 *
 * @global WP_Rewrite $wp_rewrite
 *
 * @return bool True if web.config was updated successfully
 */
function iis7_save_url_rewrite_rules()
{
    if (is_multisite()) {
        return;
    }
    global $wp_rewrite;
    $home_path = get_home_path();
    $web_config_file = $home_path . 'web.config';
    // Using win_is_writable() instead of is_writable() because of a bug in Windows PHP
    if (iis7_supports_permalinks() && (!file_exists($web_config_file) && win_is_writable($home_path) && $wp_rewrite->using_mod_rewrite_permalinks() || win_is_writable($web_config_file))) {
        $rule = $wp_rewrite->iis7_url_rewrite_rules(false, '', '');
        if (!empty($rule)) {
            return iis7_add_rewrite_rule($web_config_file, $rule);
        } else {
            return iis7_delete_rewrite_rule($web_config_file);
        }
    }
    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_iis7, $wp_query, $wpdb;
    if (is_trackback() || is_search() || is_comments_popup() || is_admin() || !empty($_POST) || is_preview() || is_robots() || $is_iis7 && !iis7_supports_permalinks()) {
        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']);
            }
        } 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 ($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'])) {
                    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_category_by_path(get_query_var('category_name'));
            $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() && get_query_var('page') && $redirect_url) {
            $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()) {
                $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("{$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'];
        }
    }
    // 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']);
            }
        }
        $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']), '&');
        // 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;
    }
}
//warn if max execution time is less than one minute
$max_execution_time = intval(ini_get('max_execution_time'));
if ($max_execution_time < 60) {
    echo "<span class='ns-cloner-warning-message'>";
    printf(__('This host\'s max_execution_time is set to %d seconds - we generally recommend at least 60 seconds for running the Cloner. You may want to increase the max_execution_time in php.ini (or wherever your host supports PHP configuration updates) to avoid any timeout errors.', 'ns-cloner'), $max_execution_time);
    echo "</span>";
}
//warn if memory limit is less than 128M
$memory_limit = intval(ini_get('memory_limit'));
if ($memory_limit < 128) {
    echo "<span class='ns-cloner-warning-message'>";
    printf(__('This host\'s memory_limit is set to %dMB - we generally recommend at least 128MB for running the Cloner. You may want to increase the memory_limit in php.ini (or wherever your host supports PHP configuration updates) to avoid any out-of-memory errors.', 'ns-cloner'), $memory_limit);
    echo "</span>";
}
// warn if .htaccess does not contain multisite file rewrite (but only if not on iis7)
if (!iis7_supports_permalinks()) {
    // foolproof htaccess path detection stolen from wp-admin/includes/network.php
    $slashed_home = trailingslashit(get_option('home'));
    $base = parse_url($slashed_home, PHP_URL_PATH);
    $document_root_fix = str_replace('\\', '/', realpath($_SERVER['DOCUMENT_ROOT']));
    $abspath_fix = str_replace('\\', '/', ABSPATH);
    $home_path = 0 === strpos($abspath_fix, $document_root_fix) ? $document_root_fix . $base : get_home_path();
    $htaccess = file_get_contents($home_path . '.htaccess');
    // set patterns which tell us that multisite file rewrite is there
    $pre_3_5_rewrite = 'wp-includes/ms-files.php';
    $post_3_5_rewrite = '(wp-(content|admin|includes)';
    // show error if neither pattern occurs
    if (strpos($htaccess, $pre_3_5_rewrite) === false && strpos($htaccess, $post_3_5_rewrite) === false) {
        echo "<span class='ns-cloner-warning-message'>";
        printf(__('It appears that you have a non-standard (possibly incorrect) .htaccess file for a multisite install. Cloned sites will not work if rewrites are not configured correctly. Please check the recommended htaccess settings <a href="%s" target="_blank">here</a> and make sure your .htaccess file matches.', 'ns-cloner'), admin_url('/network/setup.php'));
        echo "</span>";
Beispiel #18
0
 public static function regenerate_htaccess_file()
 {
     if (!function_exists('save_mod_rewrite_rules')) {
         if (!function_exists('mysql2date')) {
             require ABSPATH . '/wp-includes/functions.php';
         }
         if (!function_exists('get_home_path')) {
             require ABSPATH . '/wp-admin/includes/file.php';
         }
         require ABSPATH . '/wp-admin/includes/misc.php';
     }
     global $is_nginx, $wp_rewrite;
     $home_path = get_home_path();
     $htaccess_file = $home_path . '.htaccess';
     if (file_exists($htaccess_file)) {
         unlink($htaccess_file);
     }
     $home_path = get_home_path();
     $iis7_permalinks = iis7_supports_permalinks();
     $prefix = $blog_prefix = '';
     if (!got_url_rewrite()) {
         $prefix = '/index.php';
     }
     if (is_multisite() && !is_subdomain_install() && is_main_site()) {
         $blog_prefix = '/blog';
     }
     $permalink_structure = get_option('permalink_structure');
     $category_base = get_option('category_base');
     $tag_base = get_option('tag_base');
     $update_required = false;
     if ($iis7_permalinks) {
         if (!file_exists($home_path . 'web.config') && win_is_writable($home_path) || win_is_writable($home_path . 'web.config')) {
             $writable = true;
         } else {
             $writable = false;
         }
     } elseif ($is_nginx) {
         $writable = false;
     } else {
         if (!file_exists($home_path . '.htaccess') && is_writable($home_path) || is_writable($home_path . '.htaccess')) {
             $writable = true;
         } else {
             $writable = false;
             $existing_rules = array_filter(extract_from_markers($home_path . '.htaccess', 'WordPress'));
             $new_rules = array_filter(explode("\n", $wp_rewrite->mod_rewrite_rules()));
             $update_required = $new_rules !== $existing_rules;
         }
     }
     if ($wp_rewrite->using_index_permalinks()) {
         $usingpi = true;
     } else {
         $usingpi = false;
     }
     flush_rewrite_rules();
     save_mod_rewrite_rules();
 }
Beispiel #19
0
/**
 * Prints step 2 for Network installation process.
 *
 * @since 3.0.0
 */
function network_step2($errors = false)
{
    global $base, $wpdb;
    $hostname = get_clean_basedomain();
    if (!isset($base)) {
        $base = trailingslashit(stripslashes(dirname(dirname($_SERVER['SCRIPT_NAME']))));
    }
    // Wildcard DNS message.
    if (is_wp_error($errors)) {
        echo '<div class="error">' . $errors->get_error_message() . '</div>';
    }
    if ($_POST) {
        if (allow_subdomain_install()) {
            $subdomain_install = allow_subdirectory_install() ? !empty($_POST['subdomain_install']) : true;
        } else {
            $subdomain_install = false;
        }
    } else {
        if (is_multisite()) {
            $subdomain_install = is_subdomain_install();
            ?>
	<p><?php 
            _e('The original configuration steps are shown here for reference.');
            ?>
</p>
<?php 
        } else {
            $subdomain_install = (bool) $wpdb->get_var("SELECT meta_value FROM {$wpdb->sitemeta} WHERE site_id = 1 AND meta_key = 'subdomain_install'");
            ?>
	<div class="error"><p><strong><?php 
            _e('Warning:');
            ?>
</strong> <?php 
            _e('An existing WordPress network was detected.');
            ?>
</p></div>
	<p><?php 
            _e('Please complete the configuration steps. To create a new network, you will need to empty or remove the network database tables.');
            ?>
</p>
<?php 
        }
    }
    if ($_POST || !is_multisite()) {
        ?>
		<h3><?php 
        esc_html_e('Enabling the Network');
        ?>
</h3>
		<p><?php 
        _e('Complete the following steps to enable the features for creating a network of sites.');
        ?>
</p>
		<div class="updated inline"><p><?php 
        if (file_exists(ABSPATH . '.htaccess')) {
            printf(__('<strong>Caution:</strong> We recommend you back up your existing <code>wp-config.php</code> and <code>%s</code> files.'), '.htaccess');
        } elseif (file_exists(ABSPATH . 'web.config')) {
            printf(__('<strong>Caution:</strong> We recommend you back up your existing <code>wp-config.php</code> and <code>%s</code> files.'), 'web.config');
        } else {
            _e('<strong>Caution:</strong> We recommend you back up your existing <code>wp-config.php</code> file.');
        }
        ?>
</p></div>
<?php 
    }
    ?>
		<ol>
			<li><p><?php 
    printf(__('Create a <code>blogs.dir</code> directory at <code>%s/blogs.dir</code>. This directory is used to store uploaded media for your additional sites and must be writeable by the web server.'), WP_CONTENT_DIR);
    if (WP_CONTENT_DIR != ABSPATH . 'wp-content') {
        echo ' <strong>' . __('Warning:') . ' ' . __('Networks may not be fully compatible with custom wp-content directories.') . '</strong>';
    }
    ?>
</p></li>
			<li><p><?php 
    printf(__('Add the following to your <code>wp-config.php</code> file in <code>%s</code> <strong>above</strong> the line reading <code>/* That&#8217;s all, stop editing! Happy blogging. */</code>:'), ABSPATH);
    ?>
</p>
				<textarea class="code" readonly="readonly" cols="100" rows="7">
define('MULTISITE', true);
define('SUBDOMAIN_INSTALL', <?php 
    echo $subdomain_install ? 'true' : 'false';
    ?>
);
$base = '<?php 
    echo $base;
    ?>
';
define('DOMAIN_CURRENT_SITE', '<?php 
    echo $hostname;
    ?>
');
define('PATH_CURRENT_SITE', '<?php 
    echo $base;
    ?>
');
define('SITE_ID_CURRENT_SITE', 1);
define('BLOG_ID_CURRENT_SITE', 1);</textarea>
<?php 
    $keys_salts = array('AUTH_KEY' => '', 'SECURE_AUTH_KEY' => '', 'LOGGED_IN_KEY' => '', 'NONCE_KEY' => '', 'AUTH_SALT' => '', 'SECURE_AUTH_SALT' => '', 'LOGGED_IN_SALT' => '', 'NONCE_SALT' => '');
    foreach ($keys_salts as $c => $v) {
        if (defined($c)) {
            unset($keys_salts[$c]);
        }
    }
    if (!empty($keys_salts)) {
        $keys_salts_str = '';
        $from_api = wp_remote_get('https://api.wordpress.org/secret-key/1.1/salt/');
        if (is_wp_error($from_api)) {
            foreach ($keys_salts as $c => $v) {
                $keys_salts_str .= "\ndefine( '{$c}', '" . wp_generate_password(64, true, true) . "' );";
            }
        } else {
            $from_api = explode("\n", wp_remote_retrieve_body($from_api));
            foreach ($keys_salts as $c => $v) {
                $keys_salts_str .= "\ndefine( '{$c}', '" . substr(array_shift($from_api), 28, 64) . "' );";
            }
        }
        $num_keys_salts = count($keys_salts);
        ?>
	<p><?php 
        echo _n('This unique authentication key is also missing from your <code>wp-config.php</code> file.', 'These unique authentication keys are also missing from your <code>wp-config.php</code> file.', $num_keys_salts);
        ?>
 <?php 
        _e('To make your installation more secure, you should also add:');
        ?>
</p>
	<textarea class="code" readonly="readonly" cols="100" rows="<?php 
        echo $num_keys_salts;
        ?>
"><?php 
        echo esc_textarea($keys_salts_str);
        ?>
</textarea>
<?php 
    }
    ?>
</li>
<?php 
    if (iis7_supports_permalinks()) {
        if ($subdomain_install) {
            $web_config_file = '<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="WordPress Rule 1" stopProcessing="true">
                    <match url="^index\\.php$" ignoreCase="false" />
                    <action type="None" />
                </rule>
                <rule name="WordPress Rule 2" stopProcessing="true">
                    <match url="^files/(.+)" ignoreCase="false" />
                    <action type="Rewrite" url="wp-includes/ms-files.php?file={R:1}" appendQueryString="false" />
                </rule>
                <rule name="WordPress Rule 3" stopProcessing="true">
                    <match url="^" ignoreCase="false" />
                    <conditions logicalGrouping="MatchAny">
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" />
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" />
                    </conditions>
                    <action type="None" />
                </rule>
                <rule name="WordPress Rule 4" stopProcessing="true">
                    <match url="." ignoreCase="false" />
                    <action type="Rewrite" url="index.php" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>';
        } else {
            $web_config_file = '<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="WordPress Rule 1" stopProcessing="true">
                    <match url="^index\\.php$" ignoreCase="false" />
                    <action type="None" />
                </rule>
                <rule name="WordPress Rule 2" stopProcessing="true">
                    <match url="^([_0-9a-zA-Z-]+/)?files/(.+)" ignoreCase="false" />
                    <action type="Rewrite" url="wp-includes/ms-files.php?file={R:2}" appendQueryString="false" />
                </rule>
                <rule name="WordPress Rule 3" stopProcessing="true">
                    <match url="^([_0-9a-zA-Z-]+/)?wp-admin$" ignoreCase="false" />
                    <action type="Redirect" url="{R:1}wp-admin/" redirectType="Permanent" />
                </rule>
                <rule name="WordPress Rule 4" stopProcessing="true">
                    <match url="^" ignoreCase="false" />
                    <conditions logicalGrouping="MatchAny">
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" />
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" />
                    </conditions>
                    <action type="None" />
                </rule>
                <rule name="WordPress Rule 5" stopProcessing="true">
                    <match url="^[_0-9a-zA-Z-]+/(wp-(content|admin|includes).*)" ignoreCase="false" />
                    <action type="Rewrite" url="{R:1}" />
                </rule>
                <rule name="WordPress Rule 6" stopProcessing="true">
                    <match url="^([_0-9a-zA-Z-]+/)?(.*\\.php)$" ignoreCase="false" />
                    <action type="Rewrite" url="{R:2}" />
                </rule>
                <rule name="WordPress Rule 7" stopProcessing="true">
                    <match url="." ignoreCase="false" />
                    <action type="Rewrite" url="index.php" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>';
        }
        ?>
		<li><p><?php 
        printf(__('Add the following to your <code>web.config</code> file in <code>%s</code>, replacing other WordPress rules:'), ABSPATH);
        ?>
</p>
		<textarea class="code" readonly="readonly" cols="100" rows="20">
		<?php 
        echo esc_textarea($web_config_file);
        ?>
		</textarea></li>
		</ol>

	<?php 
    } else {
        // end iis7_supports_permalinks(). construct an htaccess file instead:
        $htaccess_file = 'RewriteEngine On
RewriteBase ' . $base . '
RewriteRule ^index\\.php$ - [L]

# uploaded files
RewriteRule ^' . ($subdomain_install ? '' : '([_0-9a-zA-Z-]+/)?') . 'files/(.+) wp-includes/ms-files.php?file=$' . ($subdomain_install ? 1 : 2) . ' [L]' . "\n";
        if (!$subdomain_install) {
            $htaccess_file .= "\n# add a trailing slash to /wp-admin\n" . 'RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L]' . "\n";
        }
        $htaccess_file .= "\n" . 'RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]';
        // @todo custom content dir.
        if (!$subdomain_install) {
            $htaccess_file .= "\nRewriteRule  ^[_0-9a-zA-Z-]+/(wp-(content|admin|includes).*) \$1 [L]\nRewriteRule  ^[_0-9a-zA-Z-]+/(.*\\.php)\$ \$1 [L]";
        }
        $htaccess_file .= "\nRewriteRule . index.php [L]";
        ?>
		<li><p><?php 
        printf(__('Add the following to your <code>.htaccess</code> file in <code>%s</code>, replacing other WordPress rules:'), ABSPATH);
        ?>
</p>
		<textarea class="code" readonly="readonly" cols="100" rows="<?php 
        echo $subdomain_install ? 11 : 16;
        ?>
">
<?php 
        echo esc_textarea($htaccess_file);
        ?>
</textarea></li>
		</ol>

	<?php 
    }
    // end IIS/Apache code branches.
    if (!is_multisite()) {
        ?>
		<p><?php 
        printf(__('Once you complete these steps, your network is enabled and configured. You will have to log in again.'));
        ?>
 <a href="<?php 
        echo esc_url(site_url('wp-login.php'));
        ?>
"><?php 
        _e('Log In');
        ?>
</a></p>
<?php 
    }
}
    public function init()
    {
        // always flush rewrite rules here for custom_episode_slug setting
        if ($this->is_active()) {
            set_transient('podlove_needs_to_flush_rewrite_rules', true);
        }
        add_settings_section('podlove_settings_general', __('', 'podlove'), function () {
            echo '<h3>' . __('Website Settings', 'podlove') . '</h3>';
        }, Settings::$pagehook);
        add_settings_section('podlove_settings_files', __('', 'podlove'), function () {
            echo '<h3>' . __('Files & Downloads', 'podlove') . '</h3>';
        }, Settings::$pagehook);
        add_settings_section('podlove_settings_feeds', __('', 'podlove'), function () {
            echo '<h3>' . __('Feeds', 'podlove') . '</h3>';
        }, Settings::$pagehook);
        add_settings_field('podlove_setting_merge_episodes', sprintf('<label for="merge_episodes">%s</label>', __('Combine blog & podcast', 'podlove')), function () {
            ?>
				<input name="podlove_website[merge_episodes]" id="merge_episodes" type="checkbox" <?php 
            checked(\Podlove\get_setting('website', 'merge_episodes'), 'on');
            ?>
>
				<?php 
            echo __('Include episode posts on the front page and in the blog feed', 'podlove');
        }, Settings::$pagehook, 'podlove_settings_general');
        add_settings_field('podlove_setting_hide_wp_feed_discovery', sprintf('<label for="hide_wp_feed_discovery">%s</label>', __('Hide blog feeds', 'podlove')), function () {
            ?>
				<input name="podlove_website[hide_wp_feed_discovery]" id="hide_wp_feed_discovery" type="checkbox" <?php 
            checked(\Podlove\get_setting('website', 'hide_wp_feed_discovery'), 'on');
            ?>
>
				<?php 
            echo __('Hide default WordPress feeds for blog and comments (no auto-discovery).', 'podlove');
        }, Settings::$pagehook, 'podlove_settings_general');
        add_settings_field('podlove_setting_custom_episode_slug', sprintf('<label for="custom_episode_slug">%s</label>', __('Permalink structure for episodes', 'podlove')), function () {
            $use_post_permastruct = \Podlove\get_setting('website', 'use_post_permastruct');
            $custom_episode_slug = \Podlove\get_setting('website', 'custom_episode_slug');
            if ($blog_prefix = \Podlove\get_blog_prefix()) {
                $custom_episode_slug = preg_replace('|^/?blog|', '', $custom_episode_slug);
            }
            ?>
				<input name="podlove_website[use_post_permastruct]" id="use_post_permastruct" type="checkbox" <?php 
            checked($use_post_permastruct, 'on');
            ?>
> <?php 
            _e('Use the same permalink structure as posts', 'podlove');
            ?>
				<div id="custom_podcast_permastruct"<?php 
            if ($use_post_permastruct) {
                echo ' style="display:none;"';
            }
            ?>
>
					<code><?php 
            echo get_option('home');
            ?>
</code>
					<input name="podlove_website[custom_episode_slug]" id="custom_episode_slug" type="text" value="<?php 
            echo $custom_episode_slug;
            ?>
">
					<p><span class="description">
						<?php 
            echo __('
							Placeholders: %podcast% (post name slug), %post_id%, %year%, %monthnum%, %day%, %hour%, %minute%, %second%, %category%, %author%<br>
							Example schemes: <code>/%podcast%</code>, <code>/episode/%podcast%</code>, <code>/%year%/%monthnum%/%podcast%</code>', 'podlove');
            ?>
					</span></p>
				</div>
				
				<script type="text/javascript">
				jQuery(function($) {
					$(document).ready(function() {

						function handle_permastruct_settings() {
							if ( $("#use_post_permastruct").is( ':checked' ) ) {
								$("#custom_podcast_permastruct").slideUp();
							} else {
								$("#custom_podcast_permastruct").slideDown();
							}
						}

						$("#use_post_permastruct").on("click", function(e) {
							handle_permastruct_settings();
						});

						handle_permastruct_settings();
					});
				});
				</script>

				<style type="text/css">
				#custom_podcast_permastruct {
					margin-top: 10px;
				}
				</style>
				<?php 
        }, Settings::$pagehook, 'podlove_settings_general');
        add_settings_field('podlove_setting_episode_archive', sprintf('<label for="episode_archive">%s</label>', __('Episode pages', 'podlove')), function () {
            $enable_episode_archive = \Podlove\get_setting('website', 'episode_archive');
            $episode_archive_slug = \Podlove\get_setting('website', 'episode_archive_slug');
            if ($blog_prefix = \Podlove\get_blog_prefix()) {
                $episode_archive_slug = preg_replace('|^/?blog|', '', $episode_archive_slug);
            }
            ?>
				<input name="podlove_website[episode_archive]" id="episode_archive" type="checkbox" <?php 
            checked($enable_episode_archive, 'on');
            ?>
> <?php 
            _e('Enable episode pages: a complete, paginated list of episodes, sorted by publishing date.', 'podlove');
            ?>
				<div id="episode_archive_slug_edit"<?php 
            if (!$enable_episode_archive) {
                echo ' style="display:none;"';
            }
            ?>
>
					<code><?php 
            echo get_option('home') . $blog_prefix;
            ?>
</code>
					<input class="podlove-check-input" name="podlove_website[episode_archive_slug]" id="episode_archive_slug" type="text" value="<?php 
            echo $episode_archive_slug;
            ?>
">
				</div>
				
				<script type="text/javascript">
				jQuery(function($) {
					$(document).ready(function() {
						$("#episode_archive").on("click", function(e) {
							if ( $(this).is( ':checked' ) ) {
								$("#episode_archive_slug_edit").slideDown();
							} else {
								$("#episode_archive_slug_edit").slideUp();
							}
						});
					});
				});
				</script>

				<style type="text/css">
				#episode_archive_slug_edit {
					margin-top: 10px;
				}
				</style>
				<?php 
        }, Settings::$pagehook, 'podlove_settings_general');
        add_settings_field('podlove_setting_landing_page', sprintf('<label for="landing_page">%s</label>', __('Podcast landing page', 'podlove')), function () {
            $landing_page = \Podlove\get_setting('website', 'landing_page');
            $landing_page_options = array(array('value' => 'homepage', 'text' => __('Front page', 'podlove')), array('value' => 'archive', 'text' => __('Episode pages', 'podlove')), array('text' => '––––––––––', 'disabled' => true));
            $pages_query = new \WP_Query(array('post_type' => 'page', 'nopaging' => true));
            if ($pages_query->have_posts()) {
                while ($pages_query->have_posts()) {
                    $pages_query->the_post();
                    $landing_page_options[] = array('value' => get_the_ID(), 'text' => get_the_title());
                }
            }
            wp_reset_postdata();
            ?>
				<select name="podlove_website[landing_page]" id="landing_page">
					<?php 
            foreach ($landing_page_options as $option) {
                ?>
						<option
							<?php 
                if (isset($option['value'])) {
                    ?>
								value="<?php 
                    echo $option['value'];
                    ?>
"
								<?php 
                    if ($landing_page == $option['value']) {
                        ?>
 selected<?php 
                    }
                    ?>
							<?php 
                }
                ?>
							<?php 
                if (isset($option['disabled']) && $option['disabled']) {
                    ?>
 disabled<?php 
                }
                ?>
						>
							<?php 
                echo $option['text'];
                ?>
						</option>
					<?php 
            }
            ?>
				</select>

				<script type="text/javascript">
				jQuery(function($) {
					$(document).ready(function() {
						var maybe_toggle_episode_archive_option = function() {
							var $archive = $("#episode_archive"),
								$archive_option = $("#landing_page option:eq(1)"),
								$home_option = $("#landing_page option:eq(0)");

							if ($archive.is(':checked')) {
								$archive_option.attr('disabled', false);
							} else {
								$archive_option.attr('disabled', 'disabled');
								// if it was selected before, unselect it
								if ($archive_option.attr('selected') == 'selected') {
									$archive_option.attr('selected', false);
									$home_option.attr('selected', 'selected');
								}
							}

						};

						$("#episode_archive").on("click", function(e) {
							maybe_toggle_episode_archive_option();
						});

						maybe_toggle_episode_archive_option();
					});
				});
				</script>
				<?php 
            echo __('This defines the landing page to your podcast. It is the site that the your podcast feeds link to.', 'podlove');
            ?>
				<?php 
        }, Settings::$pagehook, 'podlove_settings_general');
        add_settings_field('podlove_setting_url_template', sprintf('<label for="url_template">%s</label>', __('Episode Asset URL Template.', 'podlove')), function () {
            ?>
				<input name="podlove_website[url_template]" id="url_template" type="text" value="<?php 
            echo \Podlove\get_setting('website', 'url_template');
            ?>
" class="large-text podlove-check-input">
				<p>
					<span class="description">
						<?php 
            echo __('Is used to generate URLs. You probably don\'t want to change this.', 'podlove');
            ?>
					</span>
				</p>
				<?php 
        }, Settings::$pagehook, 'podlove_settings_files');
        add_settings_field('podlove_setting_ssl_verify_peer', sprintf('<label for="ssl_verify_peer">%s</label>', __('Check for Assets with SSL-peer-verification.', 'podlove')), function () {
            ?>
				<input name="podlove_website[ssl_verify_peer]" id="ssl_verify_peer" type="checkbox" <?php 
            checked(\Podlove\get_setting('website', 'ssl_verify_peer'), 'on');
            ?>
>
				<?php 
            echo __('If you provide your assets via https with a self-signed or not verifiable SSL-certificate, podlove should display your assets as non exiting. You might solve this by deactivating the ssl peer verification for asset checking. (Detailed: This sets "CURLOPT_SSL_VERIFYPEER" to FALSE.)', 'podlove');
            ?>
				<?php 
        }, Settings::$pagehook, 'podlove_settings_files');
        add_settings_field('podlove_setting_feeds_skip_redirect', sprintf('<label for="feeds_skip_redirect">%s</label>', __('Allow to skip feed redirects', 'podlove')), function () {
            ?>
				<input name="podlove_website[feeds_skip_redirect]" id="feeds_skip_redirect" type="checkbox" <?php 
            checked(\Podlove\get_setting('website', 'feeds_skip_redirect'), 'on');
            ?>
>
				<?php 
            echo __('If you need to debug you feeds while using a feed proxy, add <code>?redirect=no</code> to the feed URL to skip the redirect.', 'podlove');
            ?>
				<?php 
        }, Settings::$pagehook, 'podlove_settings_feeds');
        register_setting(Settings::$pagehook, 'podlove_website', function ($options) {
            /**
             * handle checkboxes
             */
            $checkboxes = array('merge_episodes', 'hide_wp_feed_discovery', 'use_post_permastruct', 'episode_archive', 'ssl_verify_peer', 'feeds_skip_redirect');
            foreach ($checkboxes as $checkbox_key) {
                if (!isset($options[$checkbox_key])) {
                    $options[$checkbox_key] = 'off';
                }
            }
            /**
             * handle permastructs
             */
            $prefix = $blog_prefix = '';
            $iis7_permalinks = iis7_supports_permalinks();
            if (!got_mod_rewrite() && !$iis7_permalinks) {
                $prefix = '/index.php';
            }
            if (is_multisite() && !is_subdomain_install() && is_main_site()) {
                $blog_prefix = '';
            }
            // Episode permastruct
            if (array_key_exists('custom_episode_slug', $options)) {
                $options['custom_episode_slug'] = preg_replace('#/+#', '/', '/' . str_replace('#', '', $options['custom_episode_slug']));
                if ($prefix && $blog_prefix) {
                    $options['custom_episode_slug'] = $prefix . preg_replace('#^/?index\\.php#', '', $options['custom_episode_slug']);
                } else {
                    $options['custom_episode_slug'] = $blog_prefix . $options['custom_episode_slug'];
                }
            }
            // Archive slug
            if (array_key_exists('episode_archive_slug', $options)) {
                $options['episode_archive_slug'] = preg_replace('#/+#', '/', '/' . str_replace('#', '', $options['episode_archive_slug']));
                if ($prefix && $blog_prefix) {
                    $options['episode_archive_slug'] = $prefix . preg_replace('#^/?index\\.php#', '', $options['episode_archive_slug']);
                } else {
                    $options['episode_archive_slug'] = $blog_prefix . $options['episode_archive_slug'];
                }
            }
            return $options;
        });
    }
/**
 * Prints step 2 for Network installation process.
 *
 * @since 3.0.0
 */
function network_step2($errors = false)
{
    global $wpdb;
    $hostname = get_clean_basedomain();
    $slashed_home = trailingslashit(get_option('home'));
    $base = parse_url($slashed_home, PHP_URL_PATH);
    $document_root_fix = str_replace('\\', '/', realpath($_SERVER['DOCUMENT_ROOT']));
    $abspath_fix = str_replace('\\', '/', ABSPATH);
    $home_path = 0 === strpos($abspath_fix, $document_root_fix) ? $document_root_fix . $base : get_home_path();
    $wp_siteurl_subdir = preg_replace('#^' . preg_quote($home_path, '#') . '#', '', $abspath_fix);
    $rewrite_base = !empty($wp_siteurl_subdir) ? ltrim(trailingslashit($wp_siteurl_subdir), '/') : '';
    $location_of_wp_config = ABSPATH;
    if (!file_exists(ABSPATH . 'wp-config.php') && file_exists(dirname(ABSPATH) . '/wp-config.php')) {
        $location_of_wp_config = trailingslashit(dirname(ABSPATH));
    }
    // Wildcard DNS message.
    if (is_wp_error($errors)) {
        echo '<div class="error">' . $errors->get_error_message() . '</div>';
    }
    if ($_POST) {
        if (allow_subdomain_install()) {
            $subdomain_install = allow_subdirectory_install() ? !empty($_POST['subdomain_install']) : true;
        } else {
            $subdomain_install = false;
        }
    } else {
        if (is_multisite()) {
            $subdomain_install = is_subdomain_install();
            ?>
	<p><?php 
            _e('The original configuration steps are shown here for reference.');
            ?>
</p>
<?php 
        } else {
            $subdomain_install = (bool) $wpdb->get_var("SELECT meta_value FROM {$wpdb->sitemeta} WHERE site_id = 1 AND meta_key = 'subdomain_install'");
            ?>
	<div class="error"><p><strong><?php 
            _e('Warning:');
            ?>
</strong> <?php 
            _e('An existing WordPress network was detected.');
            ?>
</p></div>
	<p><?php 
            _e('Please complete the configuration steps. To create a new network, you will need to empty or remove the network database tables.');
            ?>
</p>
<?php 
        }
    }
    $subdir_match = $subdomain_install ? '' : '([_0-9a-zA-Z-]+/)?';
    $subdir_replacement_01 = $subdomain_install ? '' : '$1';
    $subdir_replacement_12 = $subdomain_install ? '$1' : '$2';
    if ($_POST || !is_multisite()) {
        ?>
		<h3><?php 
        esc_html_e('Enabling the Network');
        ?>
</h3>
		<p><?php 
        _e('Complete the following steps to enable the features for creating a network of sites.');
        ?>
</p>
		<div class="updated inline"><p><?php 
        if (file_exists($home_path . '.htaccess')) {
            printf(__('<strong>Caution:</strong> We recommend you back up your existing <code>wp-config.php</code> and <code>%s</code> files.'), '.htaccess');
        } elseif (file_exists($home_path . 'web.config')) {
            printf(__('<strong>Caution:</strong> We recommend you back up your existing <code>wp-config.php</code> and <code>%s</code> files.'), 'web.config');
        } else {
            _e('<strong>Caution:</strong> We recommend you back up your existing <code>wp-config.php</code> file.');
        }
        ?>
</p></div>
<?php 
    }
    ?>
		<ol>
			<li><p><?php 
    printf(__('Add the following to your <code>wp-config.php</code> file in <code>%s</code> <strong>above</strong> the line reading <code>/* That&#8217;s all, stop editing! Happy blogging. */</code>:'), $location_of_wp_config);
    ?>
</p>
				<textarea class="code" readonly="readonly" cols="100" rows="6">
define('MULTISITE', true);
define('SUBDOMAIN_INSTALL', <?php 
    echo $subdomain_install ? 'true' : 'false';
    ?>
);
define('DOMAIN_CURRENT_SITE', '<?php 
    echo $hostname;
    ?>
');
define('PATH_CURRENT_SITE', '<?php 
    echo $base;
    ?>
');
define('SITE_ID_CURRENT_SITE', 1);
define('BLOG_ID_CURRENT_SITE', 1);</textarea>
<?php 
    $keys_salts = array('AUTH_KEY' => '', 'SECURE_AUTH_KEY' => '', 'LOGGED_IN_KEY' => '', 'NONCE_KEY' => '', 'AUTH_SALT' => '', 'SECURE_AUTH_SALT' => '', 'LOGGED_IN_SALT' => '', 'NONCE_SALT' => '');
    foreach ($keys_salts as $c => $v) {
        if (defined($c)) {
            unset($keys_salts[$c]);
        }
    }
    if (!empty($keys_salts)) {
        $keys_salts_str = '';
        $from_api = wp_remote_get('https://api.wordpress.org/secret-key/1.1/salt/');
        if (is_wp_error($from_api)) {
            foreach ($keys_salts as $c => $v) {
                $keys_salts_str .= "\ndefine( '{$c}', '" . wp_generate_password(64, true, true) . "' );";
            }
        } else {
            $from_api = explode("\n", wp_remote_retrieve_body($from_api));
            foreach ($keys_salts as $c => $v) {
                $keys_salts_str .= "\ndefine( '{$c}', '" . substr(array_shift($from_api), 28, 64) . "' );";
            }
        }
        $num_keys_salts = count($keys_salts);
        ?>
	<p><?php 
        echo _n('This unique authentication key is also missing from your <code>wp-config.php</code> file.', 'These unique authentication keys are also missing from your <code>wp-config.php</code> file.', $num_keys_salts);
        ?>
 <?php 
        _e('To make your installation more secure, you should also add:');
        ?>
</p>
	<textarea class="code" readonly="readonly" cols="100" rows="<?php 
        echo $num_keys_salts;
        ?>
"><?php 
        echo esc_textarea($keys_salts_str);
        ?>
</textarea>
<?php 
    }
    ?>
</li>
<?php 
    if (iis7_supports_permalinks()) {
        // IIS doesn't support RewriteBase, all your RewriteBase are belong to us
        $iis_subdir_match = ltrim($base, '/') . $subdir_match;
        $iis_rewrite_base = ltrim($base, '/') . $rewrite_base;
        $iis_subdir_replacement = $subdomain_install ? '' : '{R:1}';
        $web_config_file = '<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="WordPress Rule 1" stopProcessing="true">
                    <match url="^index\\.php$" ignoreCase="false" />
                    <action type="None" />
                </rule>';
        if (is_multisite() && get_site_option('ms_files_rewriting')) {
            $web_config_file .= '
                <rule name="WordPress Rule for Files" stopProcessing="true">
                    <match url="^' . $iis_subdir_match . 'files/(.+)" ignoreCase="false" />
                    <action type="Rewrite" url="' . $iis_rewrite_base . 'wp-includes/ms-files.php?file={R:1}" appendQueryString="false" />
                </rule>';
        }
        $web_config_file .= '
                <rule name="WordPress Rule 2" stopProcessing="true">
                    <match url="^' . $iis_subdir_match . 'wp-admin$" ignoreCase="false" />
                    <action type="Redirect" url="' . $iis_subdir_replacement . 'wp-admin/" redirectType="Permanent" />
                </rule>
                <rule name="WordPress Rule 3" stopProcessing="true">
                    <match url="^" ignoreCase="false" />
                    <conditions logicalGrouping="MatchAny">
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" />
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" />
                    </conditions>
                    <action type="None" />
                </rule>
                <rule name="WordPress Rule 4" stopProcessing="true">
                    <match url="^' . $iis_subdir_match . '(wp-(content|admin|includes).*)" ignoreCase="false" />
                    <action type="Rewrite" url="' . $iis_rewrite_base . '{R:1}" />
                </rule>
                <rule name="WordPress Rule 5" stopProcessing="true">
                    <match url="^' . $iis_subdir_match . '([_0-9a-zA-Z-]+/)?(.*\\.php)$" ignoreCase="false" />
                    <action type="Rewrite" url="' . $iis_rewrite_base . '{R:2}" />
                </rule>
                <rule name="WordPress Rule 6" stopProcessing="true">
                    <match url="." ignoreCase="false" />
                    <action type="Rewrite" url="index.php" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>';
        ?>
		<li><p><?php 
        printf(__('Add the following to your <code>web.config</code> file in <code>%s</code>, replacing other WordPress rules:'), $home_path);
        ?>
</p>
		<?php 
        if (!$subdomain_install && WP_CONTENT_DIR != ABSPATH . 'wp-content') {
            echo '<p><strong>' . __('Warning:') . ' ' . __('Subdirectory networks may not be fully compatible with custom wp-content directories.') . '</strong></p>';
        }
        ?>
		<textarea class="code" readonly="readonly" cols="100" rows="20"><?php 
        echo esc_textarea($web_config_file);
        ?>
		</textarea></li>
		</ol>

	<?php 
    } else {
        // end iis7_supports_permalinks(). construct an htaccess file instead:
        $ms_files_rewriting = '';
        if (is_multisite() && get_site_option('ms_files_rewriting')) {
            $ms_files_rewriting = "\n# uploaded files\nRewriteRule ^";
            $ms_files_rewriting .= $subdir_match . "files/(.+) {$rewrite_base}wp-includes/ms-files.php?file={$subdir_replacement_12} [L]" . "\n";
        }
        $htaccess_file = <<<EOF
RewriteEngine On
RewriteBase {$base}
RewriteRule ^index\\.php\$ - [L]
{$ms_files_rewriting}
# add a trailing slash to /wp-admin
RewriteRule ^{$subdir_match}wp-admin\$ {$subdir_replacement_01}wp-admin/ [R=301,L]

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^{$subdir_match}(wp-(content|admin|includes).*) {$rewrite_base}{$subdir_replacement_12} [L]
RewriteRule ^{$subdir_match}(.*\\.php)\$ {$rewrite_base}{$subdir_replacement_12} [L]
RewriteRule . index.php [L]
EOF;
        ?>
		<li><p><?php 
        printf(__('Add the following to your <code>.htaccess</code> file in <code>%s</code>, replacing other WordPress rules:'), $home_path);
        ?>
</p>
		<?php 
        if (!$subdomain_install && WP_CONTENT_DIR != ABSPATH . 'wp-content') {
            echo '<p><strong>' . __('Warning:') . ' ' . __('Subdirectory networks may not be fully compatible with custom wp-content directories.') . '</strong></p>';
        }
        ?>
		<textarea class="code" readonly="readonly" cols="100" rows="<?php 
        echo substr_count($htaccess_file, "\n") + 1;
        ?>
">
<?php 
        echo esc_textarea($htaccess_file);
        ?>
</textarea></li>
		</ol>

	<?php 
    }
    // end IIS/Apache code branches.
    if (!is_multisite()) {
        ?>
		<p><?php 
        printf(__('Once you complete these steps, your network is enabled and configured. You will have to log in again.'));
        ?>
 <a href="<?php 
        echo esc_url(site_url('wp-login.php'));
        ?>
"><?php 
        _e('Log In');
        ?>
</a></p>
<?php 
    }
}
 /**
  * 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;
 }