Beispiel #1
0
 /**
  * Parse request to find correct WordPress query.
  *
  * Sets up the query variables based on the request. There are also many
  * filters and actions that can be used to further manipulate the result.
  *
  * @since 2.0.0
  *
  * @param array|string $extra_query_vars Set the extra query variables.
  */
 function parse_request($extra_query_vars = '')
 {
     global $wp_rewrite;
     /**
      * Filter whether to parse the request.
      *
      * @since 3.5.0
      *
      * @param bool         $bool             Whether or not to parse the request. Default true.
      * @param WP           $this             Current WordPress environment instance.
      * @param array|string $extra_query_vars Extra passed query variables.
      */
     if (!apply_filters('do_parse_request', true, $this, $extra_query_vars)) {
         return;
     }
     $this->query_vars = array();
     $post_type_query_vars = array();
     if (is_array($extra_query_vars)) {
         $this->extra_query_vars =& $extra_query_vars;
     } else {
         if (!empty($extra_query_vars)) {
             parse_str($extra_query_vars, $this->extra_query_vars);
         }
     }
     // Process PATH_INFO, REQUEST_URI, and 404 for permalinks.
     // Fetch the rewrite rules.
     $rewrite = $wp_rewrite->wp_rewrite_rules();
     if (!empty($rewrite)) {
         // If we match a rewrite rule, this will be cleared.
         $error = '404';
         $this->did_permalink = true;
         $pathinfo = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
         list($pathinfo) = explode('?', $pathinfo);
         $pathinfo = str_replace("%", "%25", $pathinfo);
         list($req_uri) = explode('?', $_SERVER['REQUEST_URI']);
         $self = $_SERVER['PHP_SELF'];
         $home_path = trim(parse_url(home_url(), PHP_URL_PATH), '/');
         // Trim path info from the end and the leading home path from the
         // front. For path info requests, this leaves us with the requesting
         // filename, if any. For 404 requests, this leaves us with the
         // requested permalink.
         $req_uri = str_replace($pathinfo, '', $req_uri);
         $req_uri = trim($req_uri, '/');
         $req_uri = preg_replace("|^{$home_path}|i", '', $req_uri);
         $req_uri = trim($req_uri, '/');
         $pathinfo = trim($pathinfo, '/');
         $pathinfo = preg_replace("|^{$home_path}|i", '', $pathinfo);
         $pathinfo = trim($pathinfo, '/');
         $self = trim($self, '/');
         $self = preg_replace("|^{$home_path}|i", '', $self);
         $self = trim($self, '/');
         // The requested permalink is in $pathinfo for path info requests and
         //  $req_uri for other requests.
         if (!empty($pathinfo) && !preg_match('|^.*' . $wp_rewrite->index . '$|', $pathinfo)) {
             $request = $pathinfo;
         } else {
             // If the request uri is the index, blank it out so that we don't try to match it against a rule.
             if ($req_uri == $wp_rewrite->index) {
                 $req_uri = '';
             }
             $request = $req_uri;
         }
         $this->request = $request;
         // Look for matches.
         $request_match = $request;
         if (empty($request_match)) {
             // An empty request could only match against ^$ regex
             if (isset($rewrite['$'])) {
                 $this->matched_rule = '$';
                 $query = $rewrite['$'];
                 $matches = array('');
             }
         } else {
             foreach ((array) $rewrite as $match => $query) {
                 // If the requesting file is the anchor of the match, prepend it to the path info.
                 if (!empty($req_uri) && strpos($match, $req_uri) === 0 && $req_uri != $request) {
                     $request_match = $req_uri . '/' . $request;
                 }
                 if (preg_match("#^{$match}#", $request_match, $matches) || preg_match("#^{$match}#", urldecode($request_match), $matches)) {
                     if ($wp_rewrite->use_verbose_page_rules && preg_match('/pagename=\\$matches\\[([0-9]+)\\]/', $query, $varmatch)) {
                         // this is a verbose page match, lets check to be sure about it
                         if (!get_page_by_path($matches[$varmatch[1]])) {
                             continue;
                         }
                     }
                     // Got a match.
                     $this->matched_rule = $match;
                     break;
                 }
             }
         }
         if (isset($this->matched_rule)) {
             // Trim the query of everything up to the '?'.
             $query = preg_replace("!^.+\\?!", '', $query);
             // Substitute the substring matches into the query.
             $query = addslashes(WP_MatchesMapRegex::apply($query, $matches));
             $this->matched_query = $query;
             // Parse the query.
             parse_str($query, $perma_query_vars);
             // If we're processing a 404 request, clear the error var since we found something.
             if ('404' == $error) {
                 unset($error, $_GET['error']);
             }
         }
         // If req_uri is empty or if it is a request for ourself, unset error.
         if (empty($request) || $req_uri == $self || strpos($_SERVER['PHP_SELF'], 'wp-admin/') !== false) {
             unset($error, $_GET['error']);
             if (isset($perma_query_vars) && strpos($_SERVER['PHP_SELF'], 'wp-admin/') !== false) {
                 unset($perma_query_vars);
             }
             $this->did_permalink = false;
         }
     }
     /**
      * Filter the query variables whitelist before processing.
      *
      * Allows (publicly allowed) query vars to be added, removed, or changed prior
      * to executing the query. Needed to allow custom rewrite rules using your own arguments
      * to work, or any other custom query variables you want to be publicly available.
      *
      * @since 1.5.2
      *
      * @param array $public_query_vars The array of whitelisted query variables.
      */
     $this->public_query_vars = apply_filters('query_vars', $this->public_query_vars);
     foreach (get_post_types(array(), 'objects') as $post_type => $t) {
         if ($t->query_var) {
             $post_type_query_vars[$t->query_var] = $post_type;
         }
     }
     foreach ($this->public_query_vars as $wpvar) {
         if (isset($this->extra_query_vars[$wpvar])) {
             $this->query_vars[$wpvar] = $this->extra_query_vars[$wpvar];
         } elseif (isset($_POST[$wpvar])) {
             $this->query_vars[$wpvar] = $_POST[$wpvar];
         } elseif (isset($_GET[$wpvar])) {
             $this->query_vars[$wpvar] = $_GET[$wpvar];
         } elseif (isset($perma_query_vars[$wpvar])) {
             $this->query_vars[$wpvar] = $perma_query_vars[$wpvar];
         }
         if (!empty($this->query_vars[$wpvar])) {
             if (!is_array($this->query_vars[$wpvar])) {
                 $this->query_vars[$wpvar] = (string) $this->query_vars[$wpvar];
             } else {
                 foreach ($this->query_vars[$wpvar] as $vkey => $v) {
                     if (!is_object($v)) {
                         $this->query_vars[$wpvar][$vkey] = (string) $v;
                     }
                 }
             }
             if (isset($post_type_query_vars[$wpvar])) {
                 $this->query_vars['post_type'] = $post_type_query_vars[$wpvar];
                 $this->query_vars['name'] = $this->query_vars[$wpvar];
             }
         }
     }
     // Convert urldecoded spaces back into +
     foreach (get_taxonomies(array(), 'objects') as $taxonomy => $t) {
         if ($t->query_var && isset($this->query_vars[$t->query_var])) {
             $this->query_vars[$t->query_var] = str_replace(' ', '+', $this->query_vars[$t->query_var]);
         }
     }
     // Limit publicly queried post_types to those that are publicly_queryable
     if (isset($this->query_vars['post_type'])) {
         $queryable_post_types = get_post_types(array('publicly_queryable' => true));
         if (!is_array($this->query_vars['post_type'])) {
             if (!in_array($this->query_vars['post_type'], $queryable_post_types)) {
                 unset($this->query_vars['post_type']);
             }
         } else {
             $this->query_vars['post_type'] = array_intersect($this->query_vars['post_type'], $queryable_post_types);
         }
     }
     foreach ((array) $this->private_query_vars as $var) {
         if (isset($this->extra_query_vars[$var])) {
             $this->query_vars[$var] = $this->extra_query_vars[$var];
         }
     }
     if (isset($error)) {
         $this->query_vars['error'] = $error;
     }
     /**
      * Filter the array of parsed query variables.
      *
      * @since 2.1.0
      *
      * @param array $query_vars The array of requested query variables.
      */
     $this->query_vars = apply_filters('request', $this->query_vars);
     /**
      * Fires once all query variables for the current request have been parsed.
      *
      * @since 2.1.0
      *
      * @param WP &$this Current WordPress environment instance (passed by reference).
      */
     do_action_ref_array('parse_request', array(&$this));
 }
Beispiel #2
0
/**
 * Examine a url and try to determine the post ID it represents.
 *
 * Checks are supposedly from the hosted site blog.
 *
 * @since 1.0.0
 *
 * @param string $url Permalink to check.
 * @return int Post ID, or 0 on failure.
 */
function url_to_postid($url)
{
    global $wp_rewrite;
    $url = apply_filters('url_to_postid', $url);
    // First, check to see if there is a 'p=N' or 'page_id=N' to match against
    if (preg_match('#[?&](p|page_id|attachment_id)=(\\d+)#', $url, $values)) {
        $id = absint($values[2]);
        if ($id) {
            return $id;
        }
    }
    // Check to see if we are using rewrite rules
    $rewrite = $wp_rewrite->wp_rewrite_rules();
    // Not using rewrite rules, and 'p=N' and 'page_id=N' methods failed, so we're out of options
    if (empty($rewrite)) {
        return 0;
    }
    // Get rid of the #anchor
    $url_split = explode('#', $url);
    $url = $url_split[0];
    // Get rid of URL ?query=string
    $url_split = explode('?', $url);
    $url = $url_split[0];
    // Add 'www.' if it is absent and should be there
    if (false !== strpos(home_url(), '://www.') && false === strpos($url, '://www.')) {
        $url = str_replace('://', '://www.', $url);
    }
    // Strip 'www.' if it is present and shouldn't be
    if (false === strpos(home_url(), '://www.')) {
        $url = str_replace('://www.', '://', $url);
    }
    // Strip 'index.php/' if we're not using path info permalinks
    if (!$wp_rewrite->using_index_permalinks()) {
        $url = str_replace('index.php/', '', $url);
    }
    if (false !== strpos($url, home_url())) {
        // Chop off http://domain.com
        $url = str_replace(home_url(), '', $url);
    } else {
        // Chop off /path/to/blog
        $home_path = parse_url(home_url());
        $home_path = isset($home_path['path']) ? $home_path['path'] : '';
        $url = str_replace($home_path, '', $url);
    }
    // Trim leading and lagging slashes
    $url = trim($url, '/');
    $request = $url;
    // Look for matches.
    $request_match = $request;
    foreach ((array) $rewrite as $match => $query) {
        // If the requesting file is the anchor of the match, prepend it
        // to the path info.
        if (!empty($url) && $url != $request && strpos($match, $url) === 0) {
            $request_match = $url . '/' . $request;
        }
        if (preg_match("!^{$match}!", $request_match, $matches)) {
            if ($wp_rewrite->use_verbose_page_rules && preg_match('/pagename=\\$matches\\[([0-9]+)\\]/', $query, $varmatch)) {
                // this is a verbose page match, lets check to be sure about it
                if (!get_page_by_path($matches[$varmatch[1]])) {
                    continue;
                }
            }
            // Got a match.
            // Trim the query of everything up to the '?'.
            $query = preg_replace("!^.+\\?!", '', $query);
            // Substitute the substring matches into the query.
            $query = addslashes(WP_MatchesMapRegex::apply($query, $matches));
            // Filter out non-public query vars
            global $wp;
            parse_str($query, $query_vars);
            $query = array();
            foreach ((array) $query_vars as $key => $value) {
                if (in_array($key, $wp->public_query_vars)) {
                    $query[$key] = $value;
                }
            }
            // Do the query
            $query = new WP_Query($query);
            if (!empty($query->posts) && $query->is_singular) {
                return $query->post->ID;
            } else {
                return 0;
            }
        }
    }
    return 0;
}
Beispiel #3
0
 /**
  * Parse request to find correct WordPress query.
  *
  * Sets up the query variables based on the request. There are also many
  * filters and actions that can be used to further manipulate the result.
  *
  * @since 2.0.0
  *
  * @param array|string $extra_query_vars Set the extra query variables.
  */
 function parse_request($extra_query_vars = '')
 {
     global $wp_rewrite;
     if (!apply_filters('do_parse_request', true, $this, $extra_query_vars)) {
         return;
     }
     $this->query_vars = array();
     $post_type_query_vars = array();
     if (is_array($extra_query_vars)) {
         $this->extra_query_vars =& $extra_query_vars;
     } else {
         if (!empty($extra_query_vars)) {
             parse_str($extra_query_vars, $this->extra_query_vars);
         }
     }
     // Process PATH_INFO, REQUEST_URI, and 404 for permalinks.
     // Fetch the rewrite rules.
     $rewrite = $wp_rewrite->wp_rewrite_rules();
     if (!empty($rewrite)) {
         // If we match a rewrite rule, this will be cleared.
         $error = '404';
         $this->did_permalink = true;
         if (isset($_SERVER['PATH_INFO'])) {
             $pathinfo = $_SERVER['PATH_INFO'];
         } else {
             $pathinfo = '';
         }
         $pathinfo_array = explode('?', $pathinfo);
         $pathinfo = str_replace("%", "%25", $pathinfo_array[0]);
         $req_uri = $_SERVER['REQUEST_URI'];
         $req_uri_array = explode('?', $req_uri);
         $req_uri = $req_uri_array[0];
         $self = $_SERVER['PHP_SELF'];
         $home_path = parse_url(home_url());
         if (isset($home_path['path'])) {
             $home_path = $home_path['path'];
         } else {
             $home_path = '';
         }
         $home_path = trim($home_path, '/');
         // Trim path info from the end and the leading home path from the
         // front. For path info requests, this leaves us with the requesting
         // filename, if any. For 404 requests, this leaves us with the
         // requested permalink.
         $req_uri = str_replace($pathinfo, '', $req_uri);
         $req_uri = trim($req_uri, '/');
         $req_uri = preg_replace("|^{$home_path}|i", '', $req_uri);
         $req_uri = trim($req_uri, '/');
         $pathinfo = trim($pathinfo, '/');
         $pathinfo = preg_replace("|^{$home_path}|i", '', $pathinfo);
         $pathinfo = trim($pathinfo, '/');
         $self = trim($self, '/');
         $self = preg_replace("|^{$home_path}|i", '', $self);
         $self = trim($self, '/');
         // The requested permalink is in $pathinfo for path info requests and
         //  $req_uri for other requests.
         if (!empty($pathinfo) && !preg_match('|^.*' . $wp_rewrite->index . '$|', $pathinfo)) {
             $request = $pathinfo;
         } else {
             // If the request uri is the index, blank it out so that we don't try to match it against a rule.
             if ($req_uri == $wp_rewrite->index) {
                 $req_uri = '';
             }
             $request = $req_uri;
         }
         $this->request = $request;
         // Look for matches.
         $request_match = $request;
         if (empty($request_match)) {
             // An empty request could only match against ^$ regex
             if (isset($rewrite['$'])) {
                 $this->matched_rule = '$';
                 $query = $rewrite['$'];
                 $matches = array('');
             }
         } else {
             foreach ((array) $rewrite as $match => $query) {
                 // If the requesting file is the anchor of the match, prepend it to the path info.
                 if (!empty($req_uri) && strpos($match, $req_uri) === 0 && $req_uri != $request) {
                     $request_match = $req_uri . '/' . $request;
                 }
                 if (preg_match("#^{$match}#", $request_match, $matches) || preg_match("#^{$match}#", urldecode($request_match), $matches)) {
                     if ($wp_rewrite->use_verbose_page_rules && preg_match('/pagename=\\$matches\\[([0-9]+)\\]/', $query, $varmatch)) {
                         // this is a verbose page match, lets check to be sure about it
                         if (!get_page_by_path($matches[$varmatch[1]])) {
                             continue;
                         }
                     }
                     // Got a match.
                     $this->matched_rule = $match;
                     break;
                 }
             }
         }
         if (isset($this->matched_rule)) {
             // Trim the query of everything up to the '?'.
             $query = preg_replace("!^.+\\?!", '', $query);
             // Substitute the substring matches into the query.
             $query = addslashes(WP_MatchesMapRegex::apply($query, $matches));
             $this->matched_query = $query;
             // Parse the query.
             parse_str($query, $perma_query_vars);
             // If we're processing a 404 request, clear the error var since we found something.
             if ('404' == $error) {
                 unset($error, $_GET['error']);
             }
         }
         // If req_uri is empty or if it is a request for ourself, unset error.
         if (empty($request) || $req_uri == $self || strpos($_SERVER['PHP_SELF'], 'wp-admin/') !== false) {
             unset($error, $_GET['error']);
             if (isset($perma_query_vars) && strpos($_SERVER['PHP_SELF'], 'wp-admin/') !== false) {
                 unset($perma_query_vars);
             }
             $this->did_permalink = false;
         }
     }
     $this->public_query_vars = apply_filters('query_vars', $this->public_query_vars);
     foreach ($GLOBALS['wp_post_types'] as $post_type => $t) {
         if ($t->query_var) {
             $post_type_query_vars[$t->query_var] = $post_type;
         }
     }
     foreach ($this->public_query_vars as $wpvar) {
         if (isset($this->extra_query_vars[$wpvar])) {
             $this->query_vars[$wpvar] = $this->extra_query_vars[$wpvar];
         } elseif (isset($_POST[$wpvar])) {
             $this->query_vars[$wpvar] = $_POST[$wpvar];
         } elseif (isset($_GET[$wpvar])) {
             $this->query_vars[$wpvar] = $_GET[$wpvar];
         } elseif (isset($perma_query_vars[$wpvar])) {
             $this->query_vars[$wpvar] = $perma_query_vars[$wpvar];
         }
         if (!empty($this->query_vars[$wpvar])) {
             if (!is_array($this->query_vars[$wpvar])) {
                 $this->query_vars[$wpvar] = (string) $this->query_vars[$wpvar];
             } else {
                 foreach ($this->query_vars[$wpvar] as $vkey => $v) {
                     if (!is_object($v)) {
                         $this->query_vars[$wpvar][$vkey] = (string) $v;
                     }
                 }
             }
             if (isset($post_type_query_vars[$wpvar])) {
                 $this->query_vars['post_type'] = $post_type_query_vars[$wpvar];
                 $this->query_vars['name'] = $this->query_vars[$wpvar];
             }
         }
     }
     // Convert urldecoded spaces back into +
     foreach ($GLOBALS['wp_taxonomies'] as $taxonomy => $t) {
         if ($t->query_var && isset($this->query_vars[$t->query_var])) {
             $this->query_vars[$t->query_var] = str_replace(' ', '+', $this->query_vars[$t->query_var]);
         }
     }
     // Limit publicly queried post_types to those that are publicly_queryable
     if (isset($this->query_vars['post_type'])) {
         $queryable_post_types = get_post_types(array('publicly_queryable' => true));
         if (!is_array($this->query_vars['post_type'])) {
             if (!in_array($this->query_vars['post_type'], $queryable_post_types)) {
                 unset($this->query_vars['post_type']);
             }
         } else {
             $this->query_vars['post_type'] = array_intersect($this->query_vars['post_type'], $queryable_post_types);
         }
     }
     foreach ((array) $this->private_query_vars as $var) {
         if (isset($this->extra_query_vars[$var])) {
             $this->query_vars[$var] = $this->extra_query_vars[$var];
         }
     }
     if (isset($error)) {
         $this->query_vars['error'] = $error;
     }
     $this->query_vars = apply_filters('request', $this->query_vars);
     do_action_ref_array('parse_request', array(&$this));
 }
 function _process_generic_text($source_text, &$alp_broken_links)
 {
     global $wpdb, $wp_rewrite, $sitepress, $sitepress_settings;
     $sitepress_settings = $sitepress->get_settings();
     $default_language = $sitepress->get_default_language();
     $current_language = $sitepress->get_current_language();
     $cache_key_args = array($default_language, $current_language, md5($source_text), md5(implode('', $alp_broken_links)));
     $cache_key = md5(json_encode($cache_key_args));
     $cache_group = '_process_generic_text';
     $found = false;
     $text = wp_cache_get($cache_key, $cache_group, false, $found);
     if ($found) {
         return $text;
     }
     $text = $source_text;
     if (!isset($wp_rewrite)) {
         require_once ABSPATH . WPINC . '/rewrite.php';
         $wp_rewrite = new WP_Rewrite();
     }
     if ($current_language == $default_language) {
         $rewrite = $wp_rewrite->wp_rewrite_rules();
     } else {
         remove_filter('option_rewrite_rules', array($sitepress, 'rewrite_rules_filter'));
         if (class_exists('WPML_Slug_Translation')) {
             remove_filter('option_rewrite_rules', array('WPML_Slug_Translation', 'rewrite_rules_filter'), 1);
         }
         $rewrite = $wp_rewrite->wp_rewrite_rules();
         add_filter('option_rewrite_rules', array($sitepress, 'rewrite_rules_filter'));
         if (class_exists('WPML_Slug_Translation')) {
             add_filter('option_rewrite_rules', array('WPML_Slug_Translation', 'rewrite_rules_filter'), 1, 1);
         }
     }
     $rewrite = $this->all_rewrite_rules($rewrite);
     $home_url = $sitepress->language_url(empty($_POST['icl_post_language']) ? false : $_POST['icl_post_language']);
     if ($sitepress_settings['language_negotiation_type'] == 3) {
         $home_url = preg_replace("#\\?lang=([a-z-]+)#i", '', $home_url);
     }
     $home_url = str_replace("?", "\\?", $home_url);
     if ($sitepress_settings['urls']['directory_for_default_language']) {
         $default_language = $sitepress->get_default_language();
         $home_url = str_replace($default_language . "/", "", $home_url);
     }
     $int1 = preg_match_all('@<a([^>]*)href="((' . rtrim($home_url, '/') . ')?/([^"^>^\\[^\\]]+))"([^>]*)>@i', $text, $alp_matches1);
     $int2 = preg_match_all('@<a([^>]*)href=\'((' . rtrim($home_url, '/') . ')?/([^\'^>^\\[^\\]]+))\'([^>]*)>@i', $text, $alp_matches2);
     $alp_matches = array();
     for ($i = 0; $i < 6; $i++) {
         $alp_matches[$i] = array_merge((array) $alp_matches1[$i], (array) $alp_matches2[$i]);
     }
     if ($int1 || $int2) {
         $url_parts = parse_url(rtrim(get_home_url(), '/') . '/');
         foreach ($alp_matches[4] as $k => $m) {
             if (0 === strpos($m, 'wp-content')) {
                 continue;
             }
             $lang = false;
             if ($sitepress_settings['language_negotiation_type'] == 1 && $sitepress_settings['urls']['directory_for_default_language'] != 1) {
                 $m_orig = $m;
                 $exp = explode('/', $m, 2);
                 $lang = $exp[0];
                 if ($wpdb->get_var("SELECT code FROM {$wpdb->prefix}icl_languages WHERE code='{$lang}'")) {
                     $m = $exp[1];
                 } else {
                     $m = $m_orig;
                     unset($m_orig);
                     $lang = false;
                 }
             }
             $pathinfo = '';
             $req_uri = '/' . $m;
             $req_uri_array = explode('?', $req_uri);
             $req_uri = $req_uri_array[0];
             $req_uri_params = '';
             if (isset($req_uri_array[1])) {
                 $req_uri_params = $req_uri_array[1];
             }
             // separate anchor
             $req_uri_array = explode('#', $req_uri);
             $req_uri = $req_uri_array[0];
             $anchor = isset($req_uri_array[1]) ? $req_uri_array[1] : false;
             $home_path = parse_url(get_home_url());
             if (isset($home_path['path'])) {
                 $home_path = $home_path['path'];
             } else {
                 $home_path = '';
             }
             $home_path = trim($home_path, '/');
             $req_uri = str_replace($pathinfo, '', rawurldecode($req_uri));
             $req_uri = trim($req_uri, '/');
             $req_uri = preg_replace("|^{$home_path}|", '', $req_uri);
             $req_uri = trim($req_uri, '/');
             $pathinfo = trim($pathinfo, '/');
             $pathinfo = preg_replace("|^{$home_path}|", '', $pathinfo);
             $pathinfo = trim($pathinfo, '/');
             if (!empty($pathinfo) && !preg_match('|^.*' . $wp_rewrite->index . '$|', $pathinfo)) {
                 $request = $pathinfo;
             } else {
                 // If the request uri is the index, blank it out so that we don't try to match it against a rule.
                 if ($req_uri == $wp_rewrite->index) {
                     $req_uri = '';
                 }
                 $request = $req_uri;
             }
             $request_match = $request;
             $permalink_query_vars = array();
             foreach ((array) $rewrite as $match => $query) {
                 // If the requesting file is the anchor of the match, prepend it
                 // to the path info.
                 if (!empty($req_uri) && strpos($match, $req_uri) === 0 && $req_uri != $request) {
                     $request_match = $req_uri . '/' . $request;
                 }
                 if (preg_match("!^{$match}!", $request_match, $matches) || preg_match("!^{$match}!", urldecode($request_match), $matches)) {
                     // Got a match.
                     // Trim the query of everything up to the '?'.
                     $query = preg_replace("!^.+\\?!", '', $query);
                     // Substitute the substring matches into the query.
                     $query = addslashes(WP_MatchesMapRegex::apply($query, $matches));
                     // Parse the query.
                     parse_str($query, $permalink_query_vars);
                     break;
                 }
             }
             $post_name = $category_name = $tax_name = false;
             if (isset($permalink_query_vars['pagename'])) {
                 $icl_post_lang = isset($_POST['icl_post_language']) ? $_POST['icl_post_language'] : $current_language;
                 $sitepress->switch_lang($icl_post_lang);
                 $page_by_path = get_page_by_path($permalink_query_vars['pagename']);
                 $sitepress->switch_lang($current_language);
                 if (!empty($page_by_path->post_type)) {
                     $post_name = $permalink_query_vars['pagename'];
                     $post_type = 'page';
                 } else {
                     $post_name = $permalink_query_vars['pagename'];
                     $post_type = 'post';
                 }
             } elseif (isset($permalink_query_vars['name'])) {
                 $post_name = $permalink_query_vars['name'];
                 $post_type = 'post';
             } elseif (isset($permalink_query_vars['category_name'])) {
                 $category_name = $permalink_query_vars['category_name'];
             } elseif (isset($permalink_query_vars['p'])) {
                 // case or /archives/%post_id
                 $post_data_prepared = $wpdb->prepare("SELECT post_type, post_name FROM {$wpdb->posts} WHERE id=%d", $permalink_query_vars['p']);
                 list($post_type, $post_name) = $wpdb->get_row($post_data_prepared, ARRAY_N);
             } else {
                 if (empty($this->custom_post_query_vars) or empty($this->taxonomies_query_vars)) {
                     $this->init_query_vars();
                 }
                 foreach ($this->custom_post_query_vars as $query_vars_key => $query_vars_value) {
                     if (isset($permalink_query_vars[$query_vars_value])) {
                         $post_name = $permalink_query_vars[$query_vars_value];
                         $post_type = $query_vars_key;
                         break;
                     }
                 }
                 foreach ($this->taxonomies_query_vars as $query_vars_value) {
                     if (isset($permalink_query_vars[$query_vars_value])) {
                         $tax_name = $permalink_query_vars[$query_vars_value];
                         $tax_type = $query_vars_value;
                         break;
                     }
                 }
             }
             if ($post_name && isset($post_type)) {
                 $icl_post_lang = isset($_POST['icl_post_language']) ? $_POST['icl_post_language'] : $current_language;
                 $sitepress->switch_lang($icl_post_lang);
                 $p = get_page_by_path($post_name, OBJECT, $post_type);
                 $sitepress->switch_lang($current_language);
                 if (empty($p)) {
                     // fail safe
                     if ($post_id = url_to_postid($home_path . '/' . $post_name)) {
                         $p = get_post($post_id);
                     }
                 }
                 if ($p) {
                     if ($post_type == 'page') {
                         $qvid = 'page_id';
                     } else {
                         $qvid = 'p';
                     }
                     if ($sitepress_settings['language_negotiation_type'] == 1 && $lang) {
                         $langprefix = '/' . $lang;
                     } else {
                         $langprefix = '';
                     }
                     $perm_url = '(' . rtrim($home_url, '/') . ')?' . $langprefix . '/' . str_replace('?', '\\?', $m);
                     $regk = '@href=["\'](' . $perm_url . ')["\']@i';
                     if ($anchor) {
                         $anchor = "#" . $anchor;
                     } else {
                         $anchor = "";
                     }
                     // check if this is an offsite url
                     if ($p->post_type == 'page' && ($offsite_url = get_post_meta($p->ID, '_cms_nav_offsite_url', true))) {
                         $regv = 'href="' . $offsite_url . $anchor . '"';
                     } else {
                         $regv = 'href="' . '/' . ltrim($url_parts['path'], '/') . '?' . $qvid . '=' . $p->ID;
                         if ($req_uri_params != '') {
                             $regv .= '&' . $req_uri_params;
                         }
                         $regv .= $anchor . '"';
                     }
                     $def_url[$regk] = $regv;
                 } else {
                     $alp_broken_links[$alp_matches[2][$k]] = array();
                     $name = esc_sql($post_name);
                     $p = $wpdb->get_results("SELECT ID, post_type FROM {$wpdb->posts} WHERE post_name LIKE '{$name}%' AND post_type IN('post','page')");
                     if ($p) {
                         foreach ($p as $post_suggestion) {
                             if ($post_suggestion->post_type == 'page') {
                                 $qvid = 'page_id';
                             } else {
                                 $qvid = 'p';
                             }
                             $alp_broken_links[$alp_matches[2][$k]]['suggestions'][] = array('absolute' => '/' . ltrim($url_parts['path'], '/') . '?' . $qvid . '=' . $post_suggestion->ID, 'perma' => '/' . ltrim(str_replace(site_url(), '', get_permalink($post_suggestion->ID)), '/'));
                         }
                     }
                 }
             } elseif ($category_name) {
                 if (false !== strpos($category_name, '/')) {
                     $splits = explode('/', $category_name);
                     $category_name = array_pop($splits);
                     $category_parent = array_pop($splits);
                     $category_parent_id = $wpdb->get_var($wpdb->prepare("SELECT term_id FROM {$wpdb->terms} WHERE slug=%s", $category_parent));
                     $c = $wpdb->get_row($wpdb->prepare("SELECT t.term_id FROM {$wpdb->terms} t JOIN {$wpdb->term_taxonomy} x ON x.term_id=t.term_id AND x.taxonomy='category' AND x.parent=%d AND t.slug=%s", $category_parent_id, $category_name));
                 } else {
                     $c = $wpdb->get_row($wpdb->prepare("SELECT term_id FROM {$wpdb->terms} WHERE slug=%s", $category_name));
                 }
                 if ($c) {
                     /* not used ?? */
                     if ($sitepress_settings['language_negotiation_type'] == 1 && $lang) {
                         $langprefix = '/' . $lang;
                     } else {
                         $langprefix = '';
                     }
                     /* not used ?? */
                     $perm_url = '(' . rtrim($home_url, '/') . ')?' . $langprefix . '/' . $m;
                     $regk = '@href=[\'"](' . $perm_url . ')[\'"]@i';
                     $url_parts = parse_url(rtrim(get_home_url(), '/') . '/');
                     $regv = 'href="' . '/' . ltrim($url_parts['path'], '/') . '?cat_ID=' . $c->term_id . '"';
                     $def_url[$regk] = $regv;
                 } elseif (isset($name)) {
                     $alp_broken_links[$alp_matches[2][$k]] = array();
                     $c_prepared = $wpdb->prepare("SELECT term_id FROM {$wpdb->terms} WHERE slug LIKE %s", array($name . '%'));
                     $c = $wpdb->get_results($c_prepared);
                     if ($c) {
                         foreach ($c as $cat_suggestion) {
                             $perma = '/' . ltrim(str_replace(get_home_url(), '', get_category_link($cat_suggestion->term_id)), '/');
                             $alp_broken_links[$alp_matches[2][$k]]['suggestions'][] = array('absolute' => '?cat_ID=' . $cat_suggestion->term_id, 'perma' => $perma);
                         }
                     }
                 }
             } elseif ($tax_name && isset($tax_type)) {
                 if ($sitepress_settings['language_negotiation_type'] == 1 && $lang) {
                     $langprefix = '/' . $lang;
                 } else {
                     $langprefix = '';
                 }
                 $perm_url = '(' . rtrim($home_url, '/') . ')?' . $langprefix . '/' . $m;
                 $regk = '@href=["\'](' . $perm_url . ')["\']@i';
                 if ($anchor) {
                     $anchor = "#" . $anchor;
                 } else {
                     $anchor = "";
                 }
                 $regv = 'href="' . '/' . ltrim($url_parts['path'], '/') . '?' . $tax_type . '=' . $tax_name . $anchor . '"';
                 $def_url[$regk] = $regv;
             }
         }
         if (!empty($def_url)) {
             $text = preg_replace(array_keys($def_url), array_values($def_url), $text);
         }
         $tx_qvs = !empty($this->taxonomies_query_vars) && is_array($this->taxonomies_query_vars) ? '|' . join('|', $this->taxonomies_query_vars) : '';
         $post_qvs = !empty($this->custom_posts_query_vars) && is_array($this->custom_posts_query_vars) ? '|' . join('|', $this->custom_posts_query_vars) : '';
         $int = preg_match_all('@href=[\'"](' . rtrim(get_home_url(), '/') . '/?\\?(p|page_id' . $tx_qvs . $post_qvs . ')=([0-9a-z-]+)(#.+)?)[\'"]@i', $text, $matches2);
         if ($int) {
             $url_parts = parse_url(rtrim(get_home_url(), '/') . '/');
             $text = preg_replace('@href=[\'"](' . rtrim(get_home_url(), '/') . '/?\\?(p|page_id' . $tx_qvs . $post_qvs . ')=([0-9a-z-]+)(#.+)?)[\'"]@i', 'href="' . '/' . ltrim($url_parts['path'], '/') . '?$2=$3$4"', $text);
         }
     }
     wp_cache_set($cache_key, $text, $cache_group);
     return $text;
 }
 function wpl_url_to_postid($url)
 {
     global $wp_rewrite;
     $url = apply_filters('url_to_postid', $url);
     $id = url_to_postid($url);
     if (isset($id) && $id > 0) {
         return $id;
     }
     // First, check to see if there is a 'p=N' or 'page_id=N' to match against
     if (preg_match('#[?&](p|page_id|attachment_id)=(\\d+)#', $url, $values)) {
         $id = absint($values[2]);
         if ($id) {
             return $id;
         }
     }
     //first check if URL is homepage
     $wordpress_url = get_bloginfo('url');
     if (substr($wordpress_url, -1, -1) != '/') {
         $wordpress_url = $wordpress_url . "/";
     }
     if (str_replace('/', '', $url) == str_replace('/', '', $wordpress_url)) {
         return get_option('page_on_front');
     }
     // Check to see if we are using rewrite rules
     $rewrite = $wp_rewrite->wp_rewrite_rules();
     // Not using rewrite rules, and 'p=N' and 'page_id=N' methods failed, so we're out of options
     if (empty($rewrite)) {
         return 0;
     }
     // Get rid of the #anchor
     $url_split = explode('#', $url);
     $url = $url_split[0];
     // Get rid of URL ?query=string
     $url_split = explode('?', $url);
     $url = $url_split[0];
     // Add 'www.' if it is absent and should be there
     if (false !== strpos(home_url(), '://www.') && false === strpos($url, '://www.')) {
         $url = str_replace('://', '://www.', $url);
     }
     // Strip 'www.' if it is present and shouldn't be
     if (false === strpos(home_url(), '://www.')) {
         $url = str_replace('://www.', '://', $url);
     }
     // Strip 'index.php/' if we're not using path info permalinks
     if (!$wp_rewrite->using_index_permalinks()) {
         $url = str_replace('index.php/', '', $url);
     }
     if (false !== strpos($url, home_url())) {
         // Chop off http://domain.com
         $url = str_replace(home_url(), '', $url);
     } else {
         // Chop off /path/to/blog
         $home_path = parse_url(home_url());
         $home_path = isset($home_path['path']) ? $home_path['path'] : '';
         $url = str_replace($home_path, '', $url);
     }
     // Trim leading and lagging slashes
     $url = trim($url, '/');
     $request = $url;
     // Look for matches.
     $request_match = $request;
     foreach ((array) $rewrite as $match => $query) {
         // If the requesting file is the anchor of the match, prepend it
         // to the path info.
         if (!empty($url) && $url != $request && strpos($match, $url) === 0) {
             $request_match = $url . '/' . $request;
         }
         if (preg_match("!^{$match}!", $request_match, $matches)) {
             // Got a match.
             // Trim the query of everything up to the '?'.
             $query = preg_replace("!^.+\\?!", '', $query);
             // Substitute the substring matches into the query.
             $query = addslashes(WP_MatchesMapRegex::apply($query, $matches));
             // Filter out non-public query vars
             global $wp;
             parse_str($query, $query_vars);
             $query = array();
             foreach ((array) $query_vars as $key => $value) {
                 if (in_array($key, $wp->public_query_vars)) {
                     $query[$key] = $value;
                 }
             }
             // Taken from class-wp.php
             foreach ($GLOBALS['wp_post_types'] as $post_type => $t) {
                 if ($t->query_var) {
                     $post_type_query_vars[$t->query_var] = $post_type;
                 }
             }
             foreach ($wp->public_query_vars as $wpvar) {
                 if (isset($wp->extra_query_vars[$wpvar])) {
                     $query[$wpvar] = $wp->extra_query_vars[$wpvar];
                 } elseif (isset($_POST[$wpvar])) {
                     $query[$wpvar] = $_POST[$wpvar];
                 } elseif (isset($_GET[$wpvar])) {
                     $query[$wpvar] = $_GET[$wpvar];
                 } elseif (isset($query_vars[$wpvar])) {
                     $query[$wpvar] = $query_vars[$wpvar];
                 }
                 if (!empty($query[$wpvar])) {
                     if (!is_array($query[$wpvar])) {
                         $query[$wpvar] = (string) $query[$wpvar];
                     } else {
                         foreach ($query[$wpvar] as $vkey => $v) {
                             if (!is_object($v)) {
                                 $query[$wpvar][$vkey] = (string) $v;
                             }
                         }
                     }
                     if (isset($post_type_query_vars[$wpvar])) {
                         $query['post_type'] = $post_type_query_vars[$wpvar];
                         $query['name'] = $query[$wpvar];
                     }
                 }
             }
             // Do the query
             $query = new WP_Query($query);
             if (!empty($query->posts) && $query->is_singular) {
                 return $query->post->ID;
             } else {
                 return 0;
             }
         }
     }
     return 0;
 }
Beispiel #6
0
 /**
  * Fix get_page_by_path when querying vars
  * 
  * @param $query_vars objec query vars founded
  * @return object $query_vars processed
  *
  * @since 1.0
  */
 public function query_vars($query_vars)
 {
     global $wp, $wp_rewrite;
     $wp->query_vars = array();
     $post_type_query_vars = array();
     // Fetch the rewrite rules.
     $rewrite = $wp_rewrite->wp_rewrite_rules();
     if (!empty($rewrite)) {
         // If we match a rewrite rule, this will be cleared.
         $error = '404';
         $wp->did_permalink = true;
         if (isset($_SERVER['PATH_INFO'])) {
             $pathinfo = $_SERVER['PATH_INFO'];
         } else {
             $pathinfo = '';
         }
         $pathinfo_array = explode('?', $pathinfo);
         $pathinfo = str_replace("%", "%25", $pathinfo_array[0]);
         $req_uri = $_SERVER['REQUEST_URI'];
         $req_uri_array = explode('?', $req_uri);
         $req_uri = $req_uri_array[0];
         $self = $_SERVER['PHP_SELF'];
         $home_path = parse_url(home_url());
         if (isset($home_path['path'])) {
             $home_path = $home_path['path'];
         } else {
             $home_path = '';
         }
         $home_path = trim($home_path, '/');
         // Trim path info from the end and the leading home path from the
         // front. For path info requests, this leaves us with the requesting
         // filename, if any. For 404 requests, this leaves us with the
         // requested permalink.
         $req_uri = str_replace($pathinfo, '', $req_uri);
         $req_uri = trim($req_uri, '/');
         $req_uri = preg_replace("|^{$home_path}|", '', $req_uri);
         $req_uri = trim($req_uri, '/');
         $pathinfo = trim($pathinfo, '/');
         $pathinfo = preg_replace("|^{$home_path}|", '', $pathinfo);
         $pathinfo = trim($pathinfo, '/');
         $self = trim($self, '/');
         $self = preg_replace("|^{$home_path}|", '', $self);
         $self = trim($self, '/');
         // The requested permalink is in $pathinfo for path info requests and
         //  $req_uri for other requests.
         if (!empty($pathinfo) && !preg_match('|^.*' . $wp_rewrite->index . '$|', $pathinfo)) {
             $request = $pathinfo;
         } else {
             // If the request uri is the index, blank it out so that we don't try to match it against a rule.
             if ($req_uri == $wp_rewrite->index) {
                 $req_uri = '';
             }
             $request = $req_uri;
         }
         $wp->request = $request;
         // Look for matches.
         $request_match = $request;
         if (empty($request_match)) {
             // An empty request could only match against ^$ regex
             if (isset($rewrite['$'])) {
                 $wp->matched_rule = '$';
                 $query = $rewrite['$'];
                 $matches = array('');
             }
         } else {
             if ($req_uri != 'wp-app.php') {
                 foreach ((array) $rewrite as $match => $query) {
                     // If the requesting file is the anchor of the match, prepend it to the path info.
                     if (!empty($req_uri) && strpos($match, $req_uri) === 0 && $req_uri != $request) {
                         $request_match = $req_uri . '/' . $request;
                     }
                     if (preg_match("#^{$match}#", $request_match, $matches) || preg_match("#^{$match}#", urldecode($request_match), $matches)) {
                         if ($wp_rewrite->use_verbose_page_rules && preg_match('/pagename=\\$matches\\[([0-9]+)\\]/', $query, $varmatch)) {
                             // this is a verbose page match, lets check to be sure about it
                             if (!($page_foundid = $this->get_page_by_path($matches[$varmatch[1]]))) {
                                 continue;
                             } else {
                                 wp_cache_set('qts_page_request', $page_foundid);
                                 // caching query :)
                             }
                         }
                         // Got a match.
                         $wp->matched_rule = $match;
                         break;
                     }
                 }
             }
         }
         if (isset($wp->matched_rule)) {
             // Trim the query of everything up to the '?'.
             $query = preg_replace("!^.+\\?!", '', $query);
             // Substitute the substring matches into the query.
             $query = addslashes(WP_MatchesMapRegex::apply($query, $matches));
             $wp->matched_query = $query;
             // Parse the query.
             parse_str($query, $perma_query_vars);
             // If we're processing a 404 request, clear the error var
             // since we found something.
             unset($_GET['error']);
             unset($error);
         }
         // If req_uri is empty or if it is a request for ourself, unset error.
         if (empty($request) || $req_uri == $self || strpos($_SERVER['PHP_SELF'], 'wp-admin/') !== false) {
             unset($_GET['error']);
             unset($error);
             if (isset($perma_query_vars) && strpos($_SERVER['PHP_SELF'], 'wp-admin/') !== false) {
                 unset($perma_query_vars);
             }
             $wp->did_permalink = false;
         }
     }
     return $wp->public_query_vars;
 }
/**
 * Examine a url and try to determine the post ID it represents.
 *
 * Checks are supposedly from the hosted site blog.
 *
 * @since 1.0.0
 *
 * @param string $url Permalink to check.
 * @return int Post ID, or 0 on failure.
 */
function url_to_postid($url)
{
    global $wp_rewrite;
    $url = apply_filters('url_to_postid', $url);
    // First, check to see if there is a 'p=N' or 'page_id=N' to match against
    if (preg_match('#[?&](p|page_id|attachment_id)=(\\d+)#', $url, $values)) {
        $id = absint($values[2]);
        if ($id) {
            return $id;
        }
    }
    // Check to see if we are using rewrite rules
    $rewrite = $wp_rewrite->wp_rewrite_rules();
    // Not using rewrite rules, and 'p=N' and 'page_id=N' methods failed, so we're out of options
    if (empty($rewrite)) {
        return 0;
    }
    // $url cleanup by Mark Jaquith
    // This fixes things like #anchors, ?query=strings, missing 'www.',
    // added 'www.', or added 'index.php/' that will mess up our WP_Query
    // and return a false negative
    // Get rid of the #anchor
    $url_split = explode('#', $url);
    $url = $url_split[0];
    // Get rid of URL ?query=string
    $url_split = explode('?', $url);
    $url = $url_split[0];
    // Add 'www.' if it is absent and should be there
    if (false !== strpos(get_option('home'), '://www.') && false === strpos($url, '://www.')) {
        $url = str_replace('://', '://www.', $url);
    }
    // Strip 'www.' if it is present and shouldn't be
    if (false === strpos(get_option('home'), '://www.')) {
        $url = str_replace('://www.', '://', $url);
    }
    // Strip 'index.php/' if we're not using path info permalinks
    if (!$wp_rewrite->using_index_permalinks()) {
        $url = str_replace('index.php/', '', $url);
    }
    if (false !== strpos($url, get_option('home'))) {
        // Chop off http://domain.com
        $url = str_replace(get_option('home'), '', $url);
    } else {
        // Chop off /path/to/blog
        $home_path = parse_url(get_option('home'));
        $home_path = $home_path['path'];
        $url = str_replace($home_path, '', $url);
    }
    // Trim leading and lagging slashes
    $url = trim($url, '/');
    $request = $url;
    // Done with cleanup
    // Look for matches.
    $request_match = $request;
    foreach ($rewrite as $match => $query) {
        // If the requesting file is the anchor of the match, prepend it
        // to the path info.
        if (!empty($url) && strpos($match, $url) === 0 && $url != $request) {
            $request_match = $url . '/' . $request;
        }
        if (preg_match("!^{$match}!", $request_match, $matches)) {
            // Got a match.
            // Trim the query of everything up to the '?'.
            $query = preg_replace("!^.+\\?!", '', $query);
            // Substitute the substring matches into the query.
            $query = addslashes(WP_MatchesMapRegex::apply($query, $matches));
            // Filter out non-public query vars
            global $wp;
            parse_str($query, $query_vars);
            $query = array();
            foreach ((array) $query_vars as $key => $value) {
                if (in_array($key, $wp->public_query_vars)) {
                    $query[$key] = $value;
                }
            }
            // Do the query
            $query = new WP_Query($query);
            if ($query->is_single || $query->is_page) {
                return $query->post->ID;
            } else {
                return 0;
            }
        }
    }
    return 0;
}
Beispiel #8
0
/**
 * Examine a url and try to determine the post ID it represents.
 *
 * Checks are supposedly from the hosted site blog.
 *
 * @since 1.0.0
 *
 * @global WP_Rewrite $wp_rewrite
 * @global WP         $wp
 *
 * @param string $url Permalink to check.
 * @return int Post ID, or 0 on failure.
 */
function url_to_postid( $url ) {
	global $wp_rewrite;

	/**
	 * Filter the URL to derive the post ID from.
	 *
	 * @since 2.2.0
	 *
	 * @param string $url The URL to derive the post ID from.
	 */
	$url = apply_filters( 'url_to_postid', $url );

	// First, check to see if there is a 'p=N' or 'page_id=N' to match against
	if ( preg_match('#[?&](p|page_id|attachment_id)=(\d+)#', $url, $values) )	{
		$id = absint($values[2]);
		if ( $id )
			return $id;
	}

	// Check to see if we are using rewrite rules
	$rewrite = $wp_rewrite->wp_rewrite_rules();

	// Not using rewrite rules, and 'p=N' and 'page_id=N' methods failed, so we're out of options
	if ( empty($rewrite) )
		return 0;

	// Get rid of the #anchor
	$url_split = explode('#', $url);
	$url = $url_split[0];

	// Get rid of URL ?query=string
	$url_split = explode('?', $url);
	$url = $url_split[0];

	// Add 'www.' if it is absent and should be there
	if ( false !== strpos(home_url(), '://www.') && false === strpos($url, '://www.') )
		$url = str_replace('://', '://www.', $url);

	// Strip 'www.' if it is present and shouldn't be
	if ( false === strpos(home_url(), '://www.') )
		$url = str_replace('://www.', '://', $url);

	// Strip 'index.php/' if we're not using path info permalinks
	if ( !$wp_rewrite->using_index_permalinks() )
		$url = str_replace( $wp_rewrite->index . '/', '', $url );

	if ( false !== strpos( trailingslashit( $url ), home_url( '/' ) ) ) {
		// Chop off http://domain.com/[path]
		$url = str_replace(home_url(), '', $url);
	} else {
		// Chop off /path/to/blog
		$home_path = parse_url( home_url( '/' ) );
		$home_path = isset( $home_path['path'] ) ? $home_path['path'] : '' ;
		$url = preg_replace( sprintf( '#^%s#', preg_quote( $home_path ) ), '', trailingslashit( $url ) );
	}

	// Trim leading and lagging slashes
	$url = trim($url, '/');

	$request = $url;
	$post_type_query_vars = array();

	foreach ( get_post_types( array() , 'objects' ) as $post_type => $t ) {
		if ( ! empty( $t->query_var ) )
			$post_type_query_vars[ $t->query_var ] = $post_type;
	}

	// Look for matches.
	$request_match = $request;
	foreach ( (array)$rewrite as $match => $query) {

		// If the requesting file is the anchor of the match, prepend it
		// to the path info.
		if ( !empty($url) && ($url != $request) && (strpos($match, $url) === 0) )
			$request_match = $url . '/' . $request;

		if ( preg_match("#^$match#", $request_match, $matches) ) {

			if ( $wp_rewrite->use_verbose_page_rules && preg_match( '/pagename=\$matches\[([0-9]+)\]/', $query, $varmatch ) ) {
				// This is a verbose page match, let's check to be sure about it.
				if ( ! get_page_by_path( $matches[ $varmatch[1] ] ) )
					continue;
			}

			// Got a match.
			// Trim the query of everything up to the '?'.
			$query = preg_replace("!^.+\?!", '', $query);

			// Substitute the substring matches into the query.
			$query = addslashes(WP_MatchesMapRegex::apply($query, $matches));

			// Filter out non-public query vars
			global $wp;
			parse_str( $query, $query_vars );
			$query = array();
			foreach ( (array) $query_vars as $key => $value ) {
				if ( in_array( $key, $wp->public_query_vars ) ){
					$query[$key] = $value;
					if ( isset( $post_type_query_vars[$key] ) ) {
						$query['post_type'] = $post_type_query_vars[$key];
						$query['name'] = $value;
					}
				}
			}

			// Resolve conflicts between posts with numeric slugs and date archive queries.
			$query = wp_resolve_numeric_slug_conflicts( $query );

			// Do the query
			$query = new WP_Query( $query );
			if ( ! empty( $query->posts ) && $query->is_singular )
				return $query->post->ID;
			else
				return 0;
		}
	}
	return 0;
}
 /**
  * Change Rules
  * Replace rewrite rules if subdomain is category
  * @param array $rules wordpress from get_option('rewrite_rules');
  * @return array Final rewrite rules
  */
 public function change_rules_array($rules)
 {
     if (is_array($rules)) {
         if ($this->settings['remove_category_permalink']) {
             /*
             Now We have to check that current request
             using rules without category or not,
             And the request what we are talking about should be "single" and its descendants (attachment, comment page, etc)
             by checking the real rules 
             */
             $without_category = true;
             if (2 == $this->settings['remove_category_permalink']) {
                 $request_match = $_SERVER['REQUEST_URI'];
                 $request_match = trim($request_match, '/');
                 $permalink_structure = get_option('permalink_structure');
                 $permalink_structure = trim($permalink_structure, '/');
                 /*
                  * only for single post, and there's no way 'slash' count would less than permalink structure
                  */
                 if (substr_count($request_match, '/') >= substr_count($permalink_structure, '/')) {
                     /*
                      *  the code below copied from class.wp.php
                      */
                     foreach ($rules as $match => $query) {
                         if (stripos($query, 'category_name') !== false) {
                             if (preg_match("#^{$match}#", $request_match, $matches) || preg_match("#^{$match}#", urldecode($request_match), $matches)) {
                                 // Trim the query of everything up to the '?'.
                                 $query_result = preg_replace("!^.+\\?!", '', $query);
                                 // Substitute the substring matches into the query.
                                 $query_result = addslashes(WP_MatchesMapRegex::apply($query_result, $matches));
                                 // Parse the query.
                                 parse_str($query_result, $perma_query_vars);
                                 if ((isset($perma_query_vars['name']) || isset($perma_query_vars['p'])) && isset($perma_query_vars['category_name'])) {
                                     $without_category = false;
                                     break;
                                 }
                             }
                         }
                     }
                 }
             }
             /*
              *update rules if we need to using rules without %category%
              */
             if ($without_category) {
                 $rules_removed_category = $this->get_rules_array_removed_category_permalink();
                 if ($rules_removed_category) {
                     $rules = $rules_removed_category;
                 }
             }
         }
         //replace all feed rules
         $rules["feed/(feed|rdf|rss|rss2|atom)/?\$"] = "index.php?category_name=" . $this->subdomain->slug . "&feed=\$matches[1]";
         $rules["(feed|rdf|rss|rss2|atom)/?\$"] = "index.php?category_name=" . $this->subdomain->slug . "&feed=\$matches[1]";
         if (0 == $this->settings['using_index']) {
             $rules2 = array();
             $rules2["\$"] = "index.php?category_name=" . $this->subdomain->slug;
             $rules2["page/?([0-9]{1,})/?\$"] = "index.php?category_name=" . $this->subdomain->slug . "&paged=\$matches[1]";
             $rules = $rules2 + $rules;
         }
     }
     return $rules;
 }
 /**
  * Parse request to find correct WordPress query.
  *
  * Sets up the query variables based on the request. There are also many
  * filters and actions that can be used to further manipulate the result.
  *
  * @since 2.0.0
  *
  * @param array|string $extra_query_vars Set the extra query variables.
  */
 function parse_request($extra_query_vars = '')
 {
     global $wp_rewrite;
     $this->query_vars = array();
     $taxonomy_query_vars = array();
     if (is_array($extra_query_vars)) {
         $this->extra_query_vars =& $extra_query_vars;
     } else {
         if (!empty($extra_query_vars)) {
             parse_str($extra_query_vars, $this->extra_query_vars);
         }
     }
     // Process PATH_INFO, REQUEST_URI, and 404 for permalinks.
     // Fetch the rewrite rules.
     $rewrite = $wp_rewrite->wp_rewrite_rules();
     if (!empty($rewrite)) {
         // If we match a rewrite rule, this will be cleared.
         $error = '404';
         $this->did_permalink = true;
         if (isset($_SERVER['PATH_INFO'])) {
             $pathinfo = $_SERVER['PATH_INFO'];
         } else {
             $pathinfo = '';
         }
         $pathinfo_array = explode('?', $pathinfo);
         $pathinfo = str_replace("%", "%25", $pathinfo_array[0]);
         $req_uri = $_SERVER['REQUEST_URI'];
         $req_uri_array = explode('?', $req_uri);
         $req_uri = $req_uri_array[0];
         $self = $_SERVER['PHP_SELF'];
         $home_path = parse_url(get_option('home'));
         if (isset($home_path['path'])) {
             $home_path = $home_path['path'];
         } else {
             $home_path = '';
         }
         $home_path = trim($home_path, '/');
         // Trim path info from the end and the leading home path from the
         // front.  For path info requests, this leaves us with the requesting
         // filename, if any.  For 404 requests, this leaves us with the
         // requested permalink.
         $req_uri = str_replace($pathinfo, '', rawurldecode($req_uri));
         $req_uri = trim($req_uri, '/');
         $req_uri = preg_replace("|^{$home_path}|", '', $req_uri);
         $req_uri = trim($req_uri, '/');
         $pathinfo = trim($pathinfo, '/');
         $pathinfo = preg_replace("|^{$home_path}|", '', $pathinfo);
         $pathinfo = trim($pathinfo, '/');
         $self = trim($self, '/');
         $self = preg_replace("|^{$home_path}|", '', $self);
         $self = trim($self, '/');
         // The requested permalink is in $pathinfo for path info requests and
         //  $req_uri for other requests.
         if (!empty($pathinfo) && !preg_match('|^.*' . $wp_rewrite->index . '$|', $pathinfo)) {
             $request = $pathinfo;
         } else {
             // If the request uri is the index, blank it out so that we don't try to match it against a rule.
             if ($req_uri == $wp_rewrite->index) {
                 $req_uri = '';
             }
             $request = $req_uri;
         }
         $this->request = $request;
         // Look for matches.
         $request_match = $request;
         foreach ((array) $rewrite as $match => $query) {
             // Don't try to match against AtomPub calls
             if ($req_uri == 'wp-app.php') {
                 break;
             }
             // If the requesting file is the anchor of the match, prepend it
             // to the path info.
             if (!empty($req_uri) && strpos($match, $req_uri) === 0 && $req_uri != $request) {
                 $request_match = $req_uri . '/' . $request;
             }
             if (preg_match("#^{$match}#", $request_match, $matches) || preg_match("#^{$match}#", urldecode($request_match), $matches)) {
                 // Got a match.
                 $this->matched_rule = $match;
                 // Trim the query of everything up to the '?'.
                 $query = preg_replace("!^.+\\?!", '', $query);
                 // Substitute the substring matches into the query.
                 $query = addslashes(WP_MatchesMapRegex::apply($query, $matches));
                 $this->matched_query = $query;
                 // Parse the query.
                 parse_str($query, $perma_query_vars);
                 // If we're processing a 404 request, clear the error var
                 // since we found something.
                 if (isset($_GET['error'])) {
                     unset($_GET['error']);
                 }
                 if (isset($error)) {
                     unset($error);
                 }
                 break;
             }
         }
         // If req_uri is empty or if it is a request for ourself, unset error.
         if (empty($request) || $req_uri == $self || strpos($_SERVER['PHP_SELF'], 'wp-admin/') !== false) {
             if (isset($_GET['error'])) {
                 unset($_GET['error']);
             }
             if (isset($error)) {
                 unset($error);
             }
             if (isset($perma_query_vars) && strpos($_SERVER['PHP_SELF'], 'wp-admin/') !== false) {
                 unset($perma_query_vars);
             }
             $this->did_permalink = false;
         }
     }
     $this->public_query_vars = apply_filters('query_vars', $this->public_query_vars);
     foreach ($GLOBALS['wp_taxonomies'] as $taxonomy => $t) {
         if ($t->query_var) {
             $taxonomy_query_vars[$t->query_var] = $taxonomy;
         }
     }
     for ($i = 0; $i < count($this->public_query_vars); $i += 1) {
         $wpvar = $this->public_query_vars[$i];
         if (isset($this->extra_query_vars[$wpvar])) {
             $this->query_vars[$wpvar] = $this->extra_query_vars[$wpvar];
         } elseif (isset($GLOBALS[$wpvar])) {
             $this->query_vars[$wpvar] = $GLOBALS[$wpvar];
         } elseif (!empty($_POST[$wpvar])) {
             $this->query_vars[$wpvar] = $_POST[$wpvar];
         } elseif (!empty($_GET[$wpvar])) {
             $this->query_vars[$wpvar] = $_GET[$wpvar];
         } elseif (!empty($perma_query_vars[$wpvar])) {
             $this->query_vars[$wpvar] = $perma_query_vars[$wpvar];
         }
         if (!empty($this->query_vars[$wpvar])) {
             $this->query_vars[$wpvar] = (string) $this->query_vars[$wpvar];
             if (in_array($wpvar, $taxonomy_query_vars)) {
                 $this->query_vars['taxonomy'] = $taxonomy_query_vars[$wpvar];
                 $this->query_vars['term'] = $this->query_vars[$wpvar];
             }
         }
     }
     foreach ((array) $this->private_query_vars as $var) {
         if (isset($this->extra_query_vars[$var])) {
             $this->query_vars[$var] = $this->extra_query_vars[$var];
         } elseif (isset($GLOBALS[$var]) && '' != $GLOBALS[$var]) {
             $this->query_vars[$var] = $GLOBALS[$var];
         }
     }
     if (isset($error)) {
         $this->query_vars['error'] = $error;
     }
     $this->query_vars = apply_filters('request', $this->query_vars);
     do_action_ref_array('parse_request', array(&$this));
 }
 function url_to_postid($url)
 {
     global $wp_rewrite;
     if (!empty($this->post_id)) {
         return $this->post_id;
     }
     if (isset($_GET['post']) && !empty($_GET['post']) && is_numeric($_GET['post'])) {
         return $_GET['post'];
     }
     // First, check to see if there is a 'p=N' or 'page_id=N' to match against
     if (preg_match('#[?&](p|page_id|attachment_id)=(\\d+)#', $url, $values)) {
         $id = absint($values[2]);
         if ($id) {
             return $id;
         }
     }
     // Check to see if we are using rewrite rules
     if (isset($wp_rewrite)) {
         $rewrite = $wp_rewrite->wp_rewrite_rules();
     }
     // Not using rewrite rules, and 'p=N' and 'page_id=N' methods failed, so we're out of options
     if (empty($rewrite)) {
         if (isset($_GET) && !empty($_GET)) {
             /************************************************************************
              * ADDED: Trys checks URL for ?posttype=postname
              *************************************************************************/
             // Assign $url to $tempURL just incase. :)
             $tempUrl = $url;
             // Get rid of the #anchor
             $url_split = explode('#', $tempUrl);
             $tempUrl = $url_split[0];
             // Get rid of URL ?query=string
             $url_query = explode('&', $tempUrl);
             $tempUrl = $url_query[0];
             // Get rid of ? mark
             $url_query = explode('?', $tempUrl);
             if (isset($url_query[1]) && !empty($url_query[1]) && strpos($url_query[1], '=')) {
                 $url_query = explode('=', $url_query[1]);
                 if (isset($url_query[0]) && isset($url_query[1])) {
                     $args = array('name' => $url_query[1], 'post_type' => $url_query[0], 'showposts' => 1);
                     if ($post = get_posts($args)) {
                         return $post[0]->ID;
                     }
                 }
             }
             //END ADDITION
             //print_r($GLOBALS['wp_post_types']);
             //if (isset($GLOBALS['wp_post_types']['acme_product']))
             // Add custom rules for non-rewrite URLs
             foreach ($GLOBALS['wp_post_types'] as $key => $value) {
                 if (isset($_GET[$key]) && !empty($_GET[$key])) {
                     $args = array('name' => $_GET[$key], 'post_type' => $key, 'showposts' => 1);
                     if ($post = get_posts($args)) {
                         return $post[0]->ID;
                     }
                 }
             }
         }
     }
     // Get rid of the #anchor
     $url_split = explode('#', $url);
     $url = $url_split[0];
     // Get rid of URL ?query=string
     $url_query = explode('?', $url);
     $url = $url_query[0];
     // Add 'www.' if it is absent and should be there
     if (false !== strpos(home_url(), '://www.') && false === strpos($url, '://www.')) {
         $url = str_replace('://', '://www.', $url);
     }
     // Strip 'www.' if it is present and shouldn't be
     if (false === strpos(home_url(), '://www.')) {
         $url = str_replace('://www.', '://', $url);
     }
     // Strip 'index.php/' if we're not using path info permalinks
     if (isset($wp_rewrite) && !$wp_rewrite->using_index_permalinks()) {
         $url = str_replace('index.php/', '', $url);
     }
     if (false !== strpos($url, home_url())) {
         // Chop off http://domain.com
         $url = str_replace(home_url(), '', $url);
     } else {
         // Chop off /path/to/blog
         $home_path = parse_url(home_url());
         $home_path = isset($home_path['path']) ? $home_path['path'] : '';
         $url = str_replace($home_path, '', $url);
     }
     // Trim leading and lagging slashes
     $url = trim($url, '/');
     $request = $url;
     if (empty($request) && (!isset($_GET) || empty($_GET))) {
         return get_option('page_on_front');
     }
     // Look for matches.
     $request_match = $request;
     foreach ((array) $rewrite as $match => $query) {
         // If the requesting file is the anchor of the match, prepend it
         // to the path info.
         if (!empty($url) && $url != $request && strpos($match, $url) === 0) {
             $request_match = $url . '/' . $request;
         }
         if (preg_match("!^{$match}!", $request_match, $matches)) {
             // Got a match.
             // Trim the query of everything up to the '?'.
             $query = preg_replace("!^.+\\?!", '', $query);
             // Substitute the substring matches into the query.
             $query = addslashes(WP_MatchesMapRegex::apply($query, $matches));
             // Filter out non-public query vars
             global $wp;
             parse_str($query, $query_vars);
             $query = array();
             foreach ((array) $query_vars as $key => $value) {
                 if (in_array($key, $wp->public_query_vars)) {
                     $query[$key] = $value;
                 }
             }
             /************************************************************************
              * ADDED: $GLOBALS['wp_post_types'] doesn't seem to have custom postypes
              * Trying below to find posttypes in $rewrite rules
              *************************************************************************/
             // PostType Array
             $custom_post_type = false;
             $post_types = array();
             foreach ($rewrite as $key => $value) {
                 if (preg_match('/post_type=([^&]+)/i', $value, $matched)) {
                     if (isset($matched[1]) && !in_array($matched[1], $post_types)) {
                         $post_types[] = $matched[1];
                     }
                 }
             }
             foreach ((array) $query_vars as $key => $value) {
                 if (in_array($key, $post_types)) {
                     $custom_post_type = true;
                     $query['post_type'] = $key;
                     $query['postname'] = $value;
                 }
             }
             // print_r($post_types);
             /************************************************************************
              * END ADD
              *************************************************************************/
             // Taken from class-wp.php
             foreach ($GLOBALS['wp_post_types'] as $post_type => $t) {
                 if ($t->query_var) {
                     $post_type_query_vars[$t->query_var] = $post_type;
                 }
             }
             foreach ($wp->public_query_vars as $wpvar) {
                 if (isset($wp->extra_query_vars[$wpvar])) {
                     $query[$wpvar] = $wp->extra_query_vars[$wpvar];
                 } elseif (isset($_POST[$wpvar])) {
                     $query[$wpvar] = $_POST[$wpvar];
                 } elseif (isset($_GET[$wpvar])) {
                     $query[$wpvar] = $_GET[$wpvar];
                 } elseif (isset($query_vars[$wpvar])) {
                     $query[$wpvar] = $query_vars[$wpvar];
                 }
                 if (!empty($query[$wpvar])) {
                     if (!is_array($query[$wpvar])) {
                         $query[$wpvar] = (string) $query[$wpvar];
                     } else {
                         foreach ($query[$wpvar] as $vkey => $v) {
                             if (!is_object($v)) {
                                 $query[$wpvar][$vkey] = (string) $v;
                             }
                         }
                     }
                     if (isset($post_type_query_vars[$wpvar])) {
                         $query['post_type'] = $post_type_query_vars[$wpvar];
                         $query['name'] = $query[$wpvar];
                     }
                 }
             }
             // Do the query
             if (isset($query['pagename']) && !empty($query['pagename'])) {
                 $args = array('name' => $query['pagename'], 'post_type' => 'page', 'showposts' => 1);
                 if ($post = get_posts($args)) {
                     return $post[0]->ID;
                 }
             }
             $query = new WP_Query($query);
             if (!empty($query->posts) && $query->is_singular) {
                 return $query->post->ID;
             } else {
                 return 0;
             }
         }
     }
     return 0;
 }
/**
 * Custom post type rewrite function 
 * @param unknown $url
 * @return number|Ambigous <string, NULL>
 */
function url_to_custompostid($url)
{
    global $wp_rewrite, $wpdb;
    $moreName = '';
    $url = apply_filters('url_to_postid', $url);
    $rewrite = $wp_rewrite->wp_rewrite_rules();
    if (empty($rewrite)) {
        return 0;
    }
    $url_split = explode('#', $url);
    $url = $url_split[0];
    $url_split = explode('?', $url);
    $url = $url_split[0];
    if (false !== strpos(home_url(), '://www.') && false === strpos($url, '://www.')) {
        $url = str_replace('://', '://www.', $url);
    }
    // Add 'www.' if it is absent and should be there
    if (false === strpos(home_url(), '://www.')) {
        $url = str_replace('://www.', '://', $url);
    }
    // Strip 'www.' if it is present and shouldn't be
    if (!$wp_rewrite->using_index_permalinks()) {
        $url = str_replace('index.php/', '', $url);
    }
    // Strip 'index.php/' if we're not using path info permalinks
    if (false !== strpos($url, home_url())) {
        $url = str_replace(home_url(), '', $url);
        // Chop off http://domain.com
    } else {
        $home_path = parse_url(home_url());
        // Chop off /path/to/blog
        $home_path = isset($home_path['path']) ? $home_path['path'] : '';
        $url = str_replace($home_path, '', $url);
    }
    $url = trim($url, '/');
    // Trim leading and lagging slashes
    $request = $url;
    $request_match = $request;
    // Look for matches.
    foreach ((array) $rewrite as $match => $query) {
        if (!empty($url) && $url != $request && strpos($match, $url) === 0) {
            $request_match = $url . '/' . $request;
        }
        if (preg_match("!^{$match}!", $request_match, $matches)) {
            if ($wp_rewrite->use_verbose_page_rules && preg_match('/pagename=\\$matches\\[([0-9]+)\\]/', $query, $varmatch)) {
                if (!get_page_by_path($matches[$varmatch[1]])) {
                    continue;
                }
            }
            $query = preg_replace('!^.+\\?!', '', $query);
            $query = addslashes(WP_MatchesMapRegex::apply($query, $matches));
            global $wp;
            global $wpdb;
            parse_str($query, $query_vars);
            $query = array();
            foreach ((array) $query_vars as $key => $value) {
                if (in_array($key, $wp->public_query_vars)) {
                    $query[$key] = $value;
                }
            }
            if (!empty($query['videogallery'])) {
                $moreName = $wpdb->get_var('SELECT ID FROM ' . $wpdb->prefix . 'posts WHERE post_name="' . $query['videogallery'] . '" LIMIT 1');
            }
            return $moreName;
        }
    }
    return 0;
}
 /**
  * Parse which page we are on using URL
  */
 public function getPageObject($pageUrl)
 {
     global $wp_rewrite;
     // If post type, we are using url_to_postid function
     $postId = url_to_postid($pageUrl);
     if ($postId) {
         $postType = get_post_type_object(get_post($postId)->post_type);
         return array('value' => $postId, 'title' => get_the_title($postId), 'type' => get_post($postId)->post_type, 'label' => is_array($postType->labels) ? $postType->labels['name'] : $postType->labels->name);
     }
     $path = str_replace(get_site_url(), '', $pageUrl);
     $path = trim($path, '/');
     // If path is empty, then it is front page
     if (empty($path)) {
         return array('value' => get_option('page_on_front') ? get_option('page_on_front') : '', 'title' => '', 'type' => 'front_page', 'label' => __('Home Page'));
     }
     // Otherwise, we will try to match through rewrite or by query
     $rewrite = $wp_rewrite->wp_rewrite_rules();
     if (is_array($rewrite) && count($rewrite) > 0) {
         foreach ($rewrite as $match => $query) {
             if (preg_match("#^{$match}#", $path, $matches) || preg_match("#^{$match}#", urldecode($path), $matches)) {
                 $query = preg_replace("!^.*\\?!", '', $query);
                 $query = addslashes(WP_MatchesMapRegex::apply($query, $matches));
                 parse_str($query, $query_vars);
                 break;
             }
         }
     } else {
         $query = preg_replace("!^.*\\?!", '', $path);
         parse_str($query, $query_vars);
     }
     // Workaround for fail pagename rewrite match
     if (isset($query_vars['pagename']) && strpos($query_vars['pagename'], '?') !== false) {
         $query = preg_replace("!^.*\\?!", '', $query_vars['pagename']);
         parse_str($query, $query_vars);
     }
     $querypost = new WP_Query($query_vars);
     if ($querypost->is_date()) {
         if ($querypost->query_vars['m']) {
             $date = $querypost->query_vars['m'];
         } else {
             if ($querypost->is_day()) {
                 $date = $querypost->query_vars['year'] . zeroise($querypost->query_vars['monthnum'], 2) . zeroise($querypost->query_vars['day'], 2);
             } else {
                 if ($querypost->is_month()) {
                     $date = $querypost->query_vars['year'] . zeroise($querypost->query_vars['monthnum'], 2);
                 } else {
                     if ($querypost->is_year()) {
                         $date = $querypost->query_vars['year'];
                     }
                 }
             }
         }
         return array('value' => $date, 'title' => '', 'type' => 'archive', 'label' => __("Archive"));
     } else {
         if ($querypost->is_category() || $querypost->is_tag() || $querypost->is_tax()) {
             $tax_query = $querypost->tax_query->queries;
             $taxonomy = get_taxonomy($tax_query[0]['taxonomy']);
             if ($tax_query[0]['field'] == 'term_id') {
                 $term_id = $tax_query[0]['terms'][0];
             } else {
                 if ($tax_query[0]['field'] == 'slug') {
                     $term_id = get_term_by('slug', $tax_query[0]['terms'][0], $taxonomy->name)->term_id;
                 }
             }
             return array('value' => $term_id, 'title' => get_term($term_id, $taxonomy->name)->name, 'type' => $taxonomy->name, 'label' => is_array($taxonomy->labels->name) ? $taxonomy->labels['name'] : $taxonomy->labels->name);
         } else {
             if ($querypost->is_search()) {
                 return array('value' => $querypost->query_vars['s'], 'title' => '', 'type' => 'search', 'label' => __("Search"));
             } else {
                 if ($querypost->is_home()) {
                     return array('value' => '', 'title' => '', 'type' => 'home', 'label' => __("Blog Home Page"));
                 }
             }
         }
     }
 }
 function _process_generic_text($source_text, &$alp_broken_links)
 {
     global $wpdb, $wp_rewrite, $sitepress, $sitepress_settings;
     $sitepress_settings = $sitepress->get_settings();
     $default_language = $sitepress->get_default_language();
     $current_language = $sitepress->get_current_language();
     $cache_key_args = array($default_language, $current_language, md5($source_text), md5(implode('', $alp_broken_links)));
     $cache_key = md5(json_encode($cache_key_args));
     $cache_group = '_process_generic_text';
     $found = false;
     $text = wp_cache_get($cache_key, $cache_group, false, $found);
     if ($found) {
         return $text;
     }
     $filtered_icl_post_language = filter_input(INPUT_POST, 'icl_post_language', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
     $text = $source_text;
     // We need to loop over each language so we create sticky links for all languages.
     $this->active_languages = array_keys($sitepress->get_active_languages());
     $current_language = empty($filtered_icl_post_language) ? $current_language : $filtered_icl_post_language;
     if (!empty($current_language)) {
         if (($key = array_search($current_language, $this->active_languages)) !== false) {
             unset($this->active_languages[$key]);
         }
         array_unshift($this->active_languages, $current_language);
     }
     foreach ($this->active_languages as $test_language) {
         $rewrite = $this->initialize_rewrite($current_language, $default_language, $sitepress);
         $home_url = $sitepress->language_url($test_language);
         if ($sitepress_settings['language_negotiation_type'] == 3) {
             $home_url = preg_replace("#\\?lang=([a-z-]+)#i", '', $home_url);
         }
         $home_url = str_replace("?", "\\?", $home_url);
         if ($sitepress_settings['urls']['directory_for_default_language'] && $test_language == $default_language) {
             $home_url = str_replace($default_language . "/", "", $home_url);
         }
         $int1 = preg_match_all('@<a([^>]*)href="((' . rtrim($home_url, '/') . ')?/([^"^>^\\[^\\]]+))"([^>]*)>@i', $text, $alp_matches1);
         $int2 = preg_match_all('@<a([^>]*)href=\'((' . rtrim($home_url, '/') . ')?/([^\'^>^\\[^\\]]+))\'([^>]*)>@i', $text, $alp_matches2);
         $alp_matches = array();
         for ($i = 0; $i < 6; $i++) {
             $alp_matches[$i] = array_merge((array) $alp_matches1[$i], (array) $alp_matches2[$i]);
         }
         if ($int1 || $int2) {
             $def_url = array();
             $url_parts = parse_url($this->get_home_url_with_no_lang_directory());
             $url_parts['path'] = isset($url_parts['path']) ? $url_parts['path'] : '';
             foreach ($alp_matches[4] as $k => $dir_path) {
                 if (0 === strpos($dir_path, 'wp-content')) {
                     continue;
                 }
                 list($lang, $dir_path) = $this->extract_lang_from_path($sitepress_settings, $default_language, $dir_path);
                 $req_uri = '/' . $dir_path;
                 $req_uri_array = explode('?', $req_uri);
                 $req_uri = $req_uri_array[0];
                 $req_uri_params = '';
                 if (isset($req_uri_array[1])) {
                     $req_uri_params = $req_uri_array[1];
                 }
                 // separate anchor
                 $req_uri_array = explode('#', $req_uri);
                 $req_uri = $req_uri_array[0];
                 $anchor_output = isset($req_uri_array[1]) ? "#" . $req_uri_array[1] : '';
                 $home_path = parse_url(get_home_url());
                 if (isset($home_path['path'])) {
                     $home_path = $home_path['path'];
                 } else {
                     $home_path = '';
                 }
                 $home_path = trim($home_path, '/');
                 $pathinfo = '';
                 $req_uri = str_replace($pathinfo, '', rawurldecode($req_uri));
                 $req_uri = trim($req_uri, '/');
                 $req_uri = preg_replace("|^{$home_path}|", '', $req_uri);
                 $req_uri = trim($req_uri, '/');
                 $pathinfo = trim($pathinfo, '/');
                 $pathinfo = preg_replace("|^{$home_path}|", '', $pathinfo);
                 $pathinfo = trim($pathinfo, '/');
                 if (!empty($pathinfo) && !preg_match('|^.*' . $wp_rewrite->index . '$|', $pathinfo)) {
                     $request = $pathinfo;
                 } else {
                     // If the request uri is the index, blank it out so that we don't try to match it against a rule.
                     if ($req_uri == $wp_rewrite->index) {
                         $req_uri = '';
                     }
                     $request = $req_uri;
                 }
                 if (!$request) {
                     continue;
                 }
                 $request_match = $request;
                 $permalink_query_vars = array();
                 foreach ((array) $rewrite as $match => $query) {
                     // If the requesting file is the anchor of the match, prepend it
                     // to the path info.
                     if (!empty($req_uri) && strpos($match, $req_uri) === 0 && $req_uri != $request) {
                         $request_match = $req_uri . '/' . $request;
                     }
                     if (preg_match("!^{$match}!", $request_match, $matches) || preg_match("!^{$match}!", urldecode($request_match), $matches)) {
                         // Got a match.
                         // Trim the query of everything up to the '?'.
                         $query = preg_replace("!^.+\\?!", '', $query);
                         // Substitute the substring matches into the query.
                         $query = addslashes(WP_MatchesMapRegex::apply($query, $matches));
                         // Parse the query.
                         parse_str($query, $permalink_query_vars);
                         break;
                     }
                 }
                 $post_name = $category_name = $tax_name = false;
                 if (isset($permalink_query_vars['pagename'])) {
                     $get_page_by_path = new WPML_Get_Page_By_Path($wpdb, $sitepress);
                     $page_by_path = $get_page_by_path->get($permalink_query_vars['pagename'], $test_language);
                     $post_name = $permalink_query_vars['pagename'];
                     if (!empty($page_by_path->post_type)) {
                         $post_type = 'page';
                     } else {
                         $post_type = 'post';
                     }
                 } elseif (isset($permalink_query_vars['name'])) {
                     $post_name = $permalink_query_vars['name'];
                     $post_type = 'post';
                 } elseif (isset($permalink_query_vars['category_name'])) {
                     $category_name = $permalink_query_vars['category_name'];
                 } elseif (isset($permalink_query_vars['p'])) {
                     // case or /archives/%post_id
                     $post_data_prepared = $wpdb->prepare("SELECT post_type, post_name FROM {$wpdb->posts} WHERE id=%d", $permalink_query_vars['p']);
                     list($post_type, $post_name) = $wpdb->get_row($post_data_prepared, ARRAY_N);
                 } else {
                     if (empty($this->custom_post_query_vars) or empty($this->taxonomies_query_vars)) {
                         $this->init_query_vars();
                     }
                     foreach ($this->custom_post_query_vars as $query_vars_key => $query_vars_value) {
                         if (isset($permalink_query_vars[$query_vars_value])) {
                             $post_name = $permalink_query_vars[$query_vars_value];
                             $post_type = $query_vars_key;
                             break;
                         }
                     }
                     foreach ($this->taxonomies_query_vars as $query_vars_value) {
                         if (isset($permalink_query_vars[$query_vars_value])) {
                             $tax_name = $permalink_query_vars[$query_vars_value];
                             $tax_type = $query_vars_value;
                             break;
                         }
                     }
                 }
                 if ($post_name && isset($post_type)) {
                     $get_page_by_path = new WPML_Get_Page_By_Path($wpdb, $sitepress);
                     $p = $get_page_by_path->get($post_name, $test_language, OBJECT, $post_type);
                     if (empty($p)) {
                         // fail safe
                         if ($post_id = url_to_postid($home_path . '/' . $post_name)) {
                             $p = get_post($post_id);
                         }
                     }
                     if ($p) {
                         if ($p->post_type == 'page' && ($offsite_url = get_post_meta($p->ID, '_cms_nav_offsite_url', true))) {
                             $def_url = $this->get_regex_replacement_offline($def_url, $offsite_url, $sitepress_settings['language_negotiation_type'], $lang, $dir_path, $home_url, $anchor_output);
                         } else {
                             $def_url = $this->get_regex_replacement($def_url, $p->post_type == 'page' ? 'page_id' : 'p', $p->ID, $sitepress_settings['language_negotiation_type'], $lang, $dir_path, $home_url, $url_parts, $req_uri_params, $anchor_output);
                         }
                     } else {
                         $alp_broken_links[$alp_matches[2][$k]] = array();
                         $name = wpml_like_escape($post_name);
                         $p = $this->_get_ids_and_post_types($name);
                         if ($p) {
                             foreach ($p as $post_suggestion) {
                                 if ($post_suggestion->post_type == 'page') {
                                     $qvid = 'page_id';
                                 } else {
                                     $qvid = 'p';
                                 }
                                 $alp_broken_links[$alp_matches[2][$k]]['suggestions'][] = array('absolute' => '/' . ltrim($url_parts['path'], '/') . '?' . $qvid . '=' . $post_suggestion->ID, 'perma' => '/' . ltrim(str_replace(site_url(), '', get_permalink($post_suggestion->ID)), '/'));
                             }
                         }
                     }
                 } elseif ($category_name) {
                     if (false !== strpos($category_name, '/')) {
                         $splits = explode('/', $category_name);
                         $category_name = array_pop($splits);
                         $category_parent = array_pop($splits);
                         $category_parent_id = $wpdb->get_var($wpdb->prepare("SELECT term_id FROM {$wpdb->terms} WHERE slug=%s", $category_parent));
                         $c = $wpdb->get_row($wpdb->prepare("SELECT t.term_id FROM {$wpdb->terms} t JOIN {$wpdb->term_taxonomy} x ON x.term_id=t.term_id AND x.taxonomy='category' AND x.parent=%d AND t.slug=%s", $category_parent_id, $category_name));
                     } else {
                         $c = $wpdb->get_row($wpdb->prepare("SELECT term_id FROM {$wpdb->terms} WHERE slug=%s", $category_name));
                     }
                     if ($c) {
                         $def_url = $this->get_regex_replacement($def_url, 'cat_ID', $c->term_id, $sitepress_settings['language_negotiation_type'], $lang, $dir_path, $home_url, $url_parts, $req_uri_params, $anchor_output);
                     } elseif (isset($name)) {
                         $alp_broken_links[$alp_matches[2][$k]] = array();
                         $c_prepared = $wpdb->prepare("SELECT term_id FROM {$wpdb->terms} WHERE slug LIKE %s", array($name . '%'));
                         $c = $wpdb->get_results($c_prepared);
                         if ($c) {
                             foreach ($c as $cat_suggestion) {
                                 $perma = '/' . ltrim(str_replace(get_home_url(), '', get_category_link($cat_suggestion->term_id)), '/');
                                 $alp_broken_links[$alp_matches[2][$k]]['suggestions'][] = array('absolute' => '?cat_ID=' . $cat_suggestion->term_id, 'perma' => $perma);
                             }
                         }
                     }
                 } elseif ($tax_name && isset($tax_type)) {
                     $def_url = $this->get_regex_replacement($def_url, $tax_type, $tax_name, $sitepress_settings['language_negotiation_type'], $lang, $dir_path, $home_url, $url_parts, $req_uri_params, $anchor_output);
                 }
             }
             if (!empty($def_url)) {
                 $text = preg_replace(array_keys($def_url), array_values($def_url), $text);
             }
             $tx_qvs = !empty($this->taxonomies_query_vars) && is_array($this->taxonomies_query_vars) ? '|' . join('|', $this->taxonomies_query_vars) : '';
             $post_qvs = !empty($this->custom_posts_query_vars) && is_array($this->custom_posts_query_vars) ? '|' . join('|', $this->custom_posts_query_vars) : '';
             $int = preg_match_all('@href=[\'"](' . rtrim(get_home_url(), '/') . '/?\\?(p|page_id' . $tx_qvs . $post_qvs . ')=([0-9a-z-]+)(#.+)?)[\'"]@i', $text, $matches2);
             if ($int) {
                 $url_parts = parse_url(rtrim(get_home_url(), '/') . '/');
                 $text = preg_replace('@href=[\'"](' . rtrim(get_home_url(), '/') . '/?\\?(p|page_id' . $tx_qvs . $post_qvs . ')=([0-9a-z-]+)(#.+)?)[\'"]@i', 'href="' . '/' . ltrim($url_parts['path'], '/') . '?$2=$3$4"', $text);
             }
         }
     }
     wp_cache_set($cache_key, $text, $cache_group);
     return $text;
 }
Beispiel #15
0
/**
 * 链接转换
 * src:外链,直接pass
 *     内链,通过url路由规则,检测出具体参数
 * type:1,外链
 *      2,文章链接
 *      3,菜单链接
 * return :json api link
 */
function convert_link2json($src, $type = 0)
{
    $dest = $src;
    switch ($type) {
        case 1:
            return $dest;
            break;
        case 2:
        case 3:
            global $wp_rewrite;
            $rewrite = $wp_rewrite->wp_rewrite_rules();
            if ($rewrite != false) {
                //自定义链接
                $home_path = trim(parse_url(home_url(), PHP_URL_PATH), '/');
                $req_uri = trim(parse_url($src, PHP_URL_PATH), '/');
                $req_uri = preg_replace("|^{$home_path}|i", '', $req_uri);
                $req_uri = trim($req_uri, '/');
                $matches = null;
                foreach ((array) $rewrite as $match => $query) {
                    if (preg_match("#^{$match}#", $req_uri, $matches) || preg_match("#^{$match}#", urldecode($req_uri), $matches)) {
                        break;
                    }
                }
                if ($matches) {
                    $query = preg_replace("!^.+\\?!", '', $query);
                    $query = addslashes(WP_MatchesMapRegex::apply($query, $matches));
                    parse_str($query, $param);
                    $filter = array();
                    foreach ($param as $key => $value) {
                        $filter["filter[{$key}]"] = $value;
                    }
                    $filter["filter[only_one]"] = 1;
                    $dest = get_json_url_posts_list(0, $filter);
                }
            }
            //默认链接
            $match = "p=([0-9]{1,})";
            if (preg_match("#{$match}#", $src, $matches)) {
                $dest = get_json_url_posts_list($matches[1]);
            }
            break;
        default:
    }
    return $dest;
}