X-Git-Url: https://scripts.mit.edu/gitweb/autoinstalls/wordpress.git/blobdiff_plain/0f29eadd474473203a1182f52af1aa82721cecbd..2376fb745f4ae8c6bd2353127524e0b28005143d:/wp-includes/classes.php diff --git a/wp-includes/classes.php b/wp-includes/classes.php index 2af152fc..f24a6ec2 100644 --- a/wp-includes/classes.php +++ b/wp-includes/classes.php @@ -1,1749 +1,1700 @@ is_single = false; - $this->is_page = false; - $this->is_archive = false; - $this->is_date = false; - $this->is_year = false; - $this->is_month = false; - $this->is_day = false; - $this->is_time = false; - $this->is_author = false; - $this->is_category = false; - $this->is_search = false; - $this->is_feed = false; - $this->is_trackback = false; - $this->is_home = false; - $this->is_404 = false; - $this->is_paged = false; - $this->is_admin = false; - $this->is_attachment = false; - } - - function init () { - unset($this->posts); - unset($this->query); - unset($this->query_vars); - unset($this->queried_object); - unset($this->queried_object_id); - $this->post_count = 0; - $this->current_post = -1; - $this->in_the_loop = false; - - $this->init_query_flags(); - } + /** + * Extra query variables set by the user. + * + * @since 2.1.0 + * @var array + */ + var $extra_query_vars = array(); - // Reparse the query vars. - function parse_query_vars() { - $this->parse_query(''); - } + /** + * Query variables for setting up the WordPress Query Loop. + * + * @since 2.0.0 + * @var array + */ + var $query_vars; - // Parse a query string and set query type booleans. - function parse_query ($query) { - if ( !empty($query) || !isset($this->query) ) { - $this->init(); - parse_str($query, $qv); - $this->query = $query; - $this->query_vars = $qv; - } + /** + * String parsed to set the query variables. + * + * @since 2.0.0 + * @var string + */ + var $query_string; - if ('404' == $qv['error']) { - $this->is_404 = true; - if ( !empty($query) ) { - do_action('parse_query', array(&$this)); - } - return; - } + /** + * Permalink or requested URI. + * + * @since 2.0.0 + * @var string + */ + var $request; - $qv['m'] = (int) $qv['m']; - $qv['p'] = (int) $qv['p']; - - // Compat. Map subpost to attachment. - if ( '' != $qv['subpost'] ) - $qv['attachment'] = $qv['subpost']; - if ( '' != $qv['subpost_id'] ) - $qv['attachment_id'] = $qv['subpost_id']; - - if ( ('' != $qv['attachment']) || (int) $qv['attachment_id'] ) { - $this->is_single = true; - $this->is_attachment = true; - } elseif ('' != $qv['name']) { - $this->is_single = true; - } elseif ( $qv['p'] ) { - $this->is_single = true; - } elseif (('' != $qv['hour']) && ('' != $qv['minute']) &&('' != $qv['second']) && ('' != $qv['year']) && ('' != $qv['monthnum']) && ('' != $qv['day'])) { - // If year, month, day, hour, minute, and second are set, a single - // post is being queried. - $this->is_single = true; - } elseif ('' != $qv['static'] || '' != $qv['pagename'] || (int) $qv['page_id']) { - $this->is_page = true; - $this->is_single = false; - } elseif (!empty($qv['s'])) { - $this->is_search = true; - switch ($qv['show_post_type']) { - case 'page' : - $this->is_page = true; - break; - case 'attachment' : - $this->is_attachment = true; - break; - } - } else { - // Look for archive queries. Dates, categories, authors. + /** + * Rewrite rule the request matched. + * + * @since 2.0.0 + * @var string + */ + var $matched_rule; - if ( (int) $qv['second']) { - $this->is_time = true; - $this->is_date = true; - } + /** + * Rewrite query the request matched. + * + * @since 2.0.0 + * @var string + */ + var $matched_query; - if ( (int) $qv['minute']) { - $this->is_time = true; - $this->is_date = true; - } + /** + * Whether already did the permalink. + * + * @since 2.0.0 + * @var bool + */ + var $did_permalink = false; - if ( (int) $qv['hour']) { - $this->is_time = true; - $this->is_date = true; - } + /** + * Add name to list of public query variables. + * + * @since 2.1.0 + * + * @param string $qv Query variable name. + */ + function add_query_var($qv) { + if ( !in_array($qv, $this->public_query_vars) ) + $this->public_query_vars[] = $qv; + } - if ( (int) $qv['day']) { - if (! $this->is_date) { - $this->is_day = true; - $this->is_date = true; - } - } + /** + * Set the value of a query variable. + * + * @since 2.3.0 + * + * @param string $key Query variable name. + * @param mixed $value Query variable value. + */ + function set_query_var($key, $value) { + $this->query_vars[$key] = $value; + } - if ( (int) $qv['monthnum']) { - if (! $this->is_date) { - $this->is_month = true; - $this->is_date = true; - } - } + /** + * 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 ( (int) $qv['year']) { - if (! $this->is_date) { - $this->is_year = true; - $this->is_date = true; - } - } + $this->query_vars = array(); + $taxonomy_query_vars = array(); + $post_type_query_vars = array(); - if ( (int) $qv['m']) { - $this->is_date = true; - if (strlen($qv['m']) > 9) { - $this->is_time = true; - } else if (strlen($qv['m']) > 7) { - $this->is_day = true; - } else if (strlen($qv['m']) > 5) { - $this->is_month = true; - } else { - $this->is_year = true; - } - } + 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); - if ('' != $qv['w']) { - $this->is_date = true; - } + // Process PATH_INFO, REQUEST_URI, and 404 for permalinks. - if (empty($qv['cat']) || ($qv['cat'] == '0')) { - $this->is_category = false; - } else { - if (stristr($qv['cat'],'-')) { - $this->is_category = false; - } else { - $this->is_category = true; - } - } + // Fetch the rewrite rules. + $rewrite = $wp_rewrite->wp_rewrite_rules(); - if ('' != $qv['category_name']) { - $this->is_category = true; - } - - if ((empty($qv['author'])) || ($qv['author'] == '0')) { - $this->is_author = false; - } else { - $this->is_author = true; - } + if ( ! empty($rewrite) ) { + // If we match a rewrite rule, this will be cleared. + $error = '404'; + $this->did_permalink = true; - if ('' != $qv['author_name']) { - $this->is_author = 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, '/'); - if ( ($this->is_date || $this->is_author || $this->is_category)) { - $this->is_archive = true; - } + // 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, '/'); - if ( 'attachment' == $qv['show_post_type'] ) { - $this->is_attachment = true; + // 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; } - } - - if ('' != $qv['feed']) { - $this->is_feed = true; - } - - if ('' != $qv['tb']) { - $this->is_trackback = true; - } - if ('' != $qv['paged']) { - $this->is_paged = true; - } - - if ('' != $qv['comments_popup']) { - $this->is_comments_popup = true; - } - - //if we're previewing inside the write screen - if ('' != $qv['preview']) { - $this->is_preview = true; - } - - if (strstr($_SERVER['PHP_SELF'], 'wp-admin/')) { - $this->is_admin = true; - } - - if ( ! ($this->is_attachment || $this->is_archive || $this->is_single || $this->is_page || $this->is_search || $this->is_feed || $this->is_trackback || $this->is_404 || $this->is_admin || $this->is_comments_popup)) { - $this->is_home = true; - } - - if ( !empty($query) ) { - do_action('parse_query', array(&$this)); - } - } - - function set_404() { - $is_feed = $this->is_feed; - - $this->init_query_flags(); - $this->is_404 = true; - - $this->is_feed = $is_feed; - } - - function get($query_var) { - if (isset($this->query_vars[$query_var])) { - return $this->query_vars[$query_var]; - } - - return ''; - } + $this->request = $request; - function set($query_var, $value) { - $this->query_vars[$query_var] = $value; - } + // 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; - function &get_posts() { - global $wpdb, $pagenow, $user_ID; - - do_action('pre_get_posts', array(&$this)); - - // Shorthand. - $q = $this->query_vars; - - // First let's clear some variables - $whichcat = ''; - $whichauthor = ''; - $whichpage = ''; - $result = ''; - $where = ''; - $limits = ''; - $distinct = ''; - $join = ''; - - if ( !isset($q['posts_per_page']) || $q['posts_per_page'] == 0 ) - $q['posts_per_page'] = get_settings('posts_per_page'); - if ( !isset($q['what_to_show']) ) - $q['what_to_show'] = get_settings('what_to_show'); - if ( isset($q['showposts']) && $q['showposts'] ) { - $q['showposts'] = (int) $q['showposts']; - $q['posts_per_page'] = $q['showposts']; - } - if ( (isset($q['posts_per_archive_page']) && $q['posts_per_archive_page'] != 0) && ($this->is_archive || $this->is_search) ) - $q['posts_per_page'] = $q['posts_per_archive_page']; - if ( !isset($q['nopaging']) ) { - if ($q['posts_per_page'] == -1) { - $q['nopaging'] = true; - } else { - $q['nopaging'] = false; - } - } - if ( $this->is_feed ) { - $q['posts_per_page'] = get_settings('posts_per_rss'); - $q['what_to_show'] = 'posts'; - } + // 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 (isset($q['page'])) { - $q['page'] = trim($q['page'], '/'); - $q['page'] = (int) $q['page']; - $q['page'] = abs($q['page']); - } - - $add_hours = intval(get_settings('gmt_offset')); - $add_minutes = intval(60 * (get_settings('gmt_offset') - $add_hours)); - $wp_posts_post_date_field = "post_date"; // "DATE_ADD(post_date, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)"; - - // If a month is specified in the querystring, load that month - if ( (int) $q['m'] ) { - $q['m'] = '' . preg_replace('|[^0-9]|', '', $q['m']); - $where .= ' AND YEAR(post_date)=' . substr($q['m'], 0, 4); - if (strlen($q['m'])>5) - $where .= ' AND MONTH(post_date)=' . substr($q['m'], 4, 2); - if (strlen($q['m'])>7) - $where .= ' AND DAYOFMONTH(post_date)=' . substr($q['m'], 6, 2); - if (strlen($q['m'])>9) - $where .= ' AND HOUR(post_date)=' . substr($q['m'], 8, 2); - if (strlen($q['m'])>11) - $where .= ' AND MINUTE(post_date)=' . substr($q['m'], 10, 2); - if (strlen($q['m'])>13) - $where .= ' AND SECOND(post_date)=' . substr($q['m'], 12, 2); - } + if ( preg_match("#^$match#", $request_match, $matches) || + preg_match("#^$match#", urldecode($request_match), $matches) ) { + // Got a match. + $this->matched_rule = $match; - if ( (int) $q['hour'] ) { - $q['hour'] = '' . intval($q['hour']); - $where .= " AND HOUR(post_date)='" . $q['hour'] . "'"; - } + // Trim the query of everything up to the '?'. + $query = preg_replace("!^.+\?!", '', $query); - if ( (int) $q['minute'] ) { - $q['minute'] = '' . intval($q['minute']); - $where .= " AND MINUTE(post_date)='" . $q['minute'] . "'"; - } + // Substitute the substring matches into the query. + $query = addslashes(WP_MatchesMapRegex::apply($query, $matches)); - if ( (int) $q['second'] ) { - $q['second'] = '' . intval($q['second']); - $where .= " AND SECOND(post_date)='" . $q['second'] . "'"; - } + $this->matched_query = $query; - if ( (int) $q['year'] ) { - $q['year'] = '' . intval($q['year']); - $where .= " AND YEAR(post_date)='" . $q['year'] . "'"; - } + // Parse the query. + parse_str($query, $perma_query_vars); - if ( (int) $q['monthnum'] ) { - $q['monthnum'] = '' . intval($q['monthnum']); - $where .= " AND MONTH(post_date)='" . $q['monthnum'] . "'"; - } + // If we're processing a 404 request, clear the error var + // since we found something. + if ( isset($_GET['error']) ) + unset($_GET['error']); - if ( (int) $q['day'] ) { - $q['day'] = '' . intval($q['day']); - $where .= " AND DAYOFMONTH(post_date)='" . $q['day'] . "'"; - } + if ( isset($error) ) + unset($error); - // Compat. Map subpost to attachment. - if ( '' != $q['subpost'] ) - $q['attachment'] = $q['subpost']; - if ( '' != $q['subpost_id'] ) - $q['attachment_id'] = $q['subpost_id']; - - if ('' != $q['name']) { - $q['name'] = sanitize_title($q['name']); - $where .= " AND post_name = '" . $q['name'] . "'"; - } else if ('' != $q['pagename']) { - $q['pagename'] = str_replace('%2F', '/', urlencode(urldecode($q['pagename']))); - $page_paths = '/' . trim($q['pagename'], '/'); - $q['pagename'] = sanitize_title(basename($page_paths)); - $q['name'] = $q['pagename']; - $page_paths = explode('/', $page_paths); - foreach($page_paths as $pathdir) - $page_path .= ($pathdir!=''?'/':'') . sanitize_title($pathdir); - - $all_page_ids = get_all_page_ids(); - $reqpage = 0; - if (is_array($all_page_ids)) { foreach ( $all_page_ids as $page_id ) { - $page = get_page($page_id); - if ( $page->fullpath == $page_path ) { - $reqpage = $page_id; break; } - } } - - $where .= " AND (ID = '$reqpage')"; - } elseif ('' != $q['attachment']) { - $q['attachment'] = str_replace('%2F', '/', urlencode(urldecode($q['attachment']))); - $attach_paths = '/' . trim($q['attachment'], '/'); - $q['attachment'] = sanitize_title(basename($attach_paths)); - $q['name'] = $q['attachment']; - $where .= " AND post_name = '" . $q['attachment'] . "'"; - } + } - if ( (int) $q['w'] ) { - $q['w'] = ''.intval($q['w']); - $where .= " AND WEEK(post_date, 1)='" . $q['w'] . "'"; - } + // 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 ( intval($q['comments_popup']) ) - $q['p'] = intval($q['comments_popup']); + if ( isset($error) ) + unset($error); - // If a attachment is requested by number, let it supercede any post number. - if ( ($q['attachment_id'] != '') && (intval($q['attachment_id']) != 0) ) - $q['p'] = (int) $q['attachment_id']; + if ( isset($perma_query_vars) && strpos($_SERVER['PHP_SELF'], 'wp-admin/') !== false ) + unset($perma_query_vars); - // If a post number is specified, load that post - if (($q['p'] != '') && intval($q['p']) != 0) { - $q['p'] = (int) $q['p']; - $where = ' AND ID = ' . $q['p']; + $this->did_permalink = false; + } } - if (($q['page_id'] != '') && (intval($q['page_id']) != 0)) { - $q['page_id'] = intval($q['page_id']); - $q['p'] = $q['page_id']; - $where = ' AND ID = '.$q['page_id']; - } + $this->public_query_vars = apply_filters('query_vars', $this->public_query_vars); - // If a search pattern is specified, load the posts that match - if (!empty($q['s'])) { - $q['s'] = addslashes_gpc($q['s']); - $search = ' AND ('; - $q['s'] = preg_replace('/, +/', ' ', $q['s']); - $q['s'] = str_replace(',', ' ', $q['s']); - $q['s'] = str_replace('"', ' ', $q['s']); - $q['s'] = trim($q['s']); - if ($q['exact']) { - $n = ''; - } else { - $n = '%'; - } - if (!$q['sentence']) { - $s_array = explode(' ',$q['s']); - $q['search_terms'] = $s_array; - $search .= '((post_title LIKE \''.$n.$s_array[0].$n.'\') OR (post_content LIKE \''.$n.$s_array[0].$n.'\'))'; - for ( $i = 1; $i < count($s_array); $i = $i + 1) { - $search .= ' AND ((post_title LIKE \''.$n.$s_array[$i].$n.'\') OR (post_content LIKE \''.$n.$s_array[$i].$n.'\'))'; - } - $search .= ' OR (post_title LIKE \''.$n.$q['s'].$n.'\') OR (post_content LIKE \''.$n.$q['s'].$n.'\')'; - $search .= ')'; - } else { - $search = ' AND ((post_title LIKE \''.$n.$q['s'].$n.'\') OR (post_content LIKE \''.$n.$q['s'].$n.'\'))'; - } - } + foreach ( $GLOBALS['wp_taxonomies'] as $taxonomy => $t ) + if ( $t->query_var ) + $taxonomy_query_vars[$t->query_var] = $taxonomy; - // Category stuff + foreach ( $GLOBALS['wp_post_types'] as $post_type => $t ) + if ( $t->query_var ) + $post_type_query_vars[$t->query_var] = $post_type; - if ((empty($q['cat'])) || ($q['cat'] == '0') || - // Bypass cat checks if fetching specific posts - ( $this->is_single || $this->is_page )) { - $whichcat=''; - } else { - $q['cat'] = ''.urldecode($q['cat']).''; - $q['cat'] = addslashes_gpc($q['cat']); - if (stristr($q['cat'],'-')) { - // Note: if we have a negative, we ignore all the positives. It must - // always mean 'everything /except/ this one'. We should be able to do - // multiple negatives but we don't :-( - $eq = '!='; - $andor = 'AND'; - $q['cat'] = explode('-',$q['cat']); - $q['cat'] = intval($q['cat'][1]); - } else { - $eq = '='; - $andor = 'OR'; - } - $join = " LEFT JOIN $wpdb->post2cat ON ($wpdb->posts.ID = $wpdb->post2cat.post_id) "; - $cat_array = preg_split('/[,\s]+/', $q['cat']); - $whichcat .= ' AND (category_id '.$eq.' '.intval($cat_array[0]); - $whichcat .= get_category_children($cat_array[0], ' '.$andor.' category_id '.$eq.' '); - for ($i = 1; $i < (count($cat_array)); $i = $i + 1) { - $whichcat .= ' '.$andor.' category_id '.$eq.' '.intval($cat_array[$i]); - $whichcat .= get_category_children($cat_array[$i], ' '.$andor.' category_id '.$eq.' '); - } - $whichcat .= ')'; - if ($eq == '!=') { - $q['cat'] = '-'.$q['cat']; // Put back the knowledge that we are excluding a category. - } - } + 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]; - // Category stuff for nice URIs - - global $cache_categories; - if ('' != $q['category_name']) { - $cat_paths = '/' . trim(urldecode($q['category_name']), '/'); - $q['category_name'] = sanitize_title(basename($cat_paths)); - $cat_paths = explode('/', $cat_paths); - foreach($cat_paths as $pathdir) - $cat_path .= ($pathdir!=''?'/':'') . sanitize_title($pathdir); - - $all_cat_ids = get_all_category_ids(); - $q['cat'] = 0; $partial_match = 0; - foreach ( $all_cat_ids as $cat_id ) { - $cat = get_category($cat_id); - if ( $cat->fullpath == $cat_path ) { - $q['cat'] = $cat_id; - break; - } elseif ( $cat->category_nicename == $q['category_name'] ) { - $partial_match = $cat_id; + if ( !empty( $this->query_vars[$wpvar] ) ) { + $this->query_vars[$wpvar] = (string) $this->query_vars[$wpvar]; + if ( isset( $taxonomy_query_vars[$wpvar] ) ) { + $this->query_vars['taxonomy'] = $taxonomy_query_vars[$wpvar]; + $this->query_vars['term'] = $this->query_vars[$wpvar]; + } elseif ( isset($post_type_query_vars[$wpvar] ) ) { + $this->query_vars['post_type'] = $post_type_query_vars[$wpvar]; + $this->query_vars['name'] = $this->query_vars[$wpvar]; } } - - //if we don't match the entire hierarchy fallback on just matching the nicename - if (!$q['cat'] && $partial_match) { - $q['cat'] = $partial_match; - } - - $tables = ", $wpdb->post2cat, $wpdb->categories"; - $join = " LEFT JOIN $wpdb->post2cat ON ($wpdb->posts.ID = $wpdb->post2cat.post_id) LEFT JOIN $wpdb->categories ON ($wpdb->post2cat.category_id = $wpdb->categories.cat_ID) "; - $whichcat = " AND (category_id = '" . $q['cat'] . "'"; - $whichcat .= get_category_children($q['cat'], " OR category_id = "); - $whichcat .= ")"; } - // Author/user stuff - - if ((empty($q['author'])) || ($q['author'] == '0')) { - $whichauthor=''; - } else { - $q['author'] = ''.urldecode($q['author']).''; - $q['author'] = addslashes_gpc($q['author']); - if (stristr($q['author'], '-')) { - $eq = '!='; - $andor = 'AND'; - $q['author'] = explode('-', $q['author']); - $q['author'] = ''.intval($q['author'][1]); - } else { - $eq = '='; - $andor = 'OR'; - } - $author_array = preg_split('/[,\s]+/', $q['author']); - $whichauthor .= ' AND (post_author '.$eq.' '.intval($author_array[0]); - for ($i = 1; $i < (count($author_array)); $i = $i + 1) { - $whichauthor .= ' '.$andor.' post_author '.$eq.' '.intval($author_array[$i]); - } - $whichauthor .= ')'; + // 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 ( ! in_array( $this->query_vars['post_type'], $queryable_post_types ) ) + unset( $this->query_vars['post_type'] ); } - // Author stuff for nice URIs - - if ('' != $q['author_name']) { - if (stristr($q['author_name'],'/')) { - $q['author_name'] = explode('/',$q['author_name']); - if ($q['author_name'][count($q['author_name'])-1]) { - $q['author_name'] = $q['author_name'][count($q['author_name'])-1];#no trailing slash - } else { - $q['author_name'] = $q['author_name'][count($q['author_name'])-2];#there was a trailling slash - } - } - $q['author_name'] = sanitize_title($q['author_name']); - $q['author'] = $wpdb->get_var("SELECT ID FROM $wpdb->users WHERE user_nicename='".$q['author_name']."'"); - $whichauthor .= ' AND (post_author = '.intval($q['author']).')'; + 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]; } - - $where .= $search.$whichcat.$whichauthor; - if ((empty($q['order'])) || ((strtoupper($q['order']) != 'ASC') && (strtoupper($q['order']) != 'DESC'))) { - $q['order']='DESC'; - } + if ( isset($error) ) + $this->query_vars['error'] = $error; - // Order by - if (empty($q['orderby'])) { - $q['orderby']='date '.$q['order']; - } else { - // Used to filter values - $allowed_keys = array('author', 'date', 'category', 'title', 'modified'); - $q['orderby'] = urldecode($q['orderby']); - $q['orderby'] = addslashes_gpc($q['orderby']); - $orderby_array = explode(' ',$q['orderby']); - if (!in_array($orderby_array[0],$allowed_keys)) { - $orderby_array[0] = 'date'; - } - $q['orderby'] = $orderby_array[0].' '.$q['order']; - if (count($orderby_array)>1) { - for ($i = 1; $i < (count($orderby_array)); $i = $i + 1) { - // Only allow certain values for safety - if (in_array($orderby_array[$i],$allowed_keys)) { - $q['orderby'] .= ',post_'.$orderby_array[$i].' '.$q['order']; - } - } - } - } + $this->query_vars = apply_filters('request', $this->query_vars); - $now = gmdate('Y-m-d H:i:59'); - - //only select past-dated posts, except if a logged in user is viewing a single: then, if they - //can edit the post, we let them through - if ($pagenow != 'post.php' && $pagenow != 'edit.php' && !($this->is_single && $user_ID)) { - $where .= " AND post_date_gmt <= '$now'"; - $distinct = 'DISTINCT'; - } + do_action_ref_array('parse_request', array(&$this)); + } - if ( $this->is_attachment ) { - $where .= " AND (post_status = 'attachment')"; - } elseif ($this->is_page) { - $where .= " AND (post_status = 'static')"; - } elseif ($this->is_single) { - $where .= " AND (post_status != 'static')"; - } else { - $where .= " AND (post_status = 'publish'"; + /** + * Send additional HTTP headers for caching, content type, etc. + * + * Sets the X-Pingback header, 404 status (if 404), Content-type. If showing + * a feed, it will also send last-modified, etag, and 304 status if needed. + * + * @since 2.0.0 + */ + function send_headers() { + $headers = array('X-Pingback' => get_bloginfo('pingback_url')); + $status = null; + $exit_required = false; - if (isset($user_ID) && ('' != intval($user_ID))) - $where .= " OR post_author = $user_ID AND post_status != 'draft' AND post_status != 'static')"; + if ( is_user_logged_in() ) + $headers = array_merge($headers, wp_get_nocache_headers()); + if ( !empty($this->query_vars['error']) && '404' == $this->query_vars['error'] ) { + $status = 404; + if ( !is_user_logged_in() ) + $headers = array_merge($headers, wp_get_nocache_headers()); + $headers['Content-Type'] = get_option('html_type') . '; charset=' . get_option('blog_charset'); + } else if ( empty($this->query_vars['feed']) ) { + $headers['Content-Type'] = get_option('html_type') . '; charset=' . get_option('blog_charset'); + } else { + // We're showing a feed, so WP is indeed the only thing that last changed + if ( !empty($this->query_vars['withcomments']) + || ( empty($this->query_vars['withoutcomments']) + && ( !empty($this->query_vars['p']) + || !empty($this->query_vars['name']) + || !empty($this->query_vars['page_id']) + || !empty($this->query_vars['pagename']) + || !empty($this->query_vars['attachment']) + || !empty($this->query_vars['attachment_id']) + ) + ) + ) + $wp_last_modified = mysql2date('D, d M Y H:i:s', get_lastcommentmodified('GMT'), 0).' GMT'; else - $where .= ')'; - } - - if (! $this->is_attachment ) - $where .= " AND post_status != 'attachment'"; + $wp_last_modified = mysql2date('D, d M Y H:i:s', get_lastpostmodified('GMT'), 0).' GMT'; + $wp_etag = '"' . md5($wp_last_modified) . '"'; + $headers['Last-Modified'] = $wp_last_modified; + $headers['ETag'] = $wp_etag; - // Apply filters on where and join prior to paging so that any - // manipulations to them are reflected in the paging by day queries. - $where = apply_filters('posts_where', $where); - $join = apply_filters('posts_join', $join); + // Support for Conditional GET + if (isset($_SERVER['HTTP_IF_NONE_MATCH'])) + $client_etag = stripslashes(stripslashes($_SERVER['HTTP_IF_NONE_MATCH'])); + else $client_etag = false; - // Paging - if (empty($q['nopaging']) && ! $this->is_single && ! $this->is_page) { - $page = abs(intval($q['paged'])); - if (empty($page)) { - $page = 1; - } + $client_last_modified = empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? '' : trim($_SERVER['HTTP_IF_MODIFIED_SINCE']); + // If string is empty, return 0. If not, attempt to parse into a timestamp + $client_modified_timestamp = $client_last_modified ? strtotime($client_last_modified) : 0; - if (($q['what_to_show'] == 'posts')) { - $q['offset'] = abs(intval($q['offset'])); - if ( empty($q['offset']) ) { - $pgstrt = ''; - $pgstrt = (intval($page) -1) * $q['posts_per_page'] . ', '; - $limits = 'LIMIT '.$pgstrt.$q['posts_per_page']; - } else { // we're ignoring $page and using 'offset' - $pgstrt = $q['offset'] . ', '; - $limits = 'LIMIT ' . $pgstrt . $q['posts_per_page']; - } - } elseif ($q['what_to_show'] == 'days') { - $startrow = $q['posts_per_page'] * (intval($page)-1); - $start_date = $wpdb->get_var("SELECT max(post_date) FROM $wpdb->posts $join WHERE (1=1) $where GROUP BY year(post_date), month(post_date), dayofmonth(post_date) ORDER BY post_date DESC LIMIT $startrow,1"); - $endrow = $startrow + $q['posts_per_page'] - 1; - $end_date = $wpdb->get_var("SELECT min(post_date) FROM $wpdb->posts $join WHERE (1=1) $where GROUP BY year(post_date), month(post_date), dayofmonth(post_date) ORDER BY post_date DESC LIMIT $endrow,1"); - - if ($page > 1) { - $where .= " AND post_date >= '$end_date' AND post_date <= '$start_date'"; - } else { - $where .= " AND post_date >= '$end_date'"; - } - } - } + // Make a timestamp for our most recent modification... + $wp_modified_timestamp = strtotime($wp_last_modified); - // Apply post-paging filters on where and join. Only plugins that - // manipulate paging queries should use these hooks. - $where = apply_filters('posts_where_paged', $where); - $groupby = " $wpdb->posts.ID "; - $groupby = apply_filters('posts_groupby', $groupby); - $join = apply_filters('posts_join_paged', $join); - $orderby = "post_" . $q['orderby']; - $orderby = apply_filters('posts_orderby', $orderby); - $request = " SELECT $distinct * FROM $wpdb->posts $join WHERE 1=1" . $where . " GROUP BY " . $groupby . " ORDER BY " . $orderby . " $limits"; - $this->request = apply_filters('posts_request', $request); - - $this->posts = $wpdb->get_results($this->request); - - // Check post status to determine if post should be displayed. - if ( !empty($this->posts) && $this->is_single ) { - $status = get_post_status($this->posts[0]); - if ( ('publish' != $status) && ('static' != $status) ) { - if ( ! (isset($user_ID) && ('' != intval($user_ID))) ) { - // User must be logged in to view unpublished posts. - $this->posts = array(); - } else { - if ('draft' == $status) { - // User must have edit permissions on the draft to preview. - if (! current_user_can('edit_post', $this->posts[0]->ID)) { - $this->posts = array(); - } else { - $this->is_preview = true; - $this->posts[0]->post_date = current_time('mysql'); - } - } else { - if (! current_user_can('read_post', $this->posts[0]->ID)) - $this->posts = array(); - } - } - } else { - if (mysql2date('U', $this->posts[0]->post_date_gmt) > mysql2date('U', $now)) { //it's future dated - $this->is_preview = true; - if (!current_user_can('edit_post', $this->posts[0]->ID)) { - $this->posts = array ( ); - } - } + if ( ($client_last_modified && $client_etag) ? + (($client_modified_timestamp >= $wp_modified_timestamp) && ($client_etag == $wp_etag)) : + (($client_modified_timestamp >= $wp_modified_timestamp) || ($client_etag == $wp_etag)) ) { + $status = 304; + $exit_required = true; } } - update_post_caches($this->posts); + $headers = apply_filters('wp_headers', $headers, $this); - $this->posts = apply_filters('the_posts', $this->posts); - $this->post_count = count($this->posts); - if ($this->post_count > 0) { - $this->post = $this->posts[0]; - } - - // Save any changes made to the query vars. - $this->query_vars = $q; - return $this->posts; - } + if ( ! empty( $status ) ) + status_header( $status ); + foreach( (array) $headers as $name => $field_value ) + @header("{$name}: {$field_value}"); - function next_post() { - - $this->current_post++; + if ($exit_required) + exit(); - $this->post = $this->posts[$this->current_post]; - return $this->post; + do_action_ref_array('send_headers', array(&$this)); } - function the_post() { - global $post; - $this->in_the_loop = true; - $post = $this->next_post(); - setup_postdata($post); - - if ( $this->current_post == 0 ) // loop has just started - do_action('loop_start'); - } - - function have_posts() { - if ($this->current_post + 1 < $this->post_count) { - return true; - } elseif ($this->current_post + 1 == $this->post_count) { - do_action('loop_end'); - // Do some cleaning up after the loop - $this->rewind_posts(); + /** + * Sets the query string property based off of the query variable property. + * + * The 'query_string' filter is deprecated, but still works. Plugins should + * use the 'request' filter instead. + * + * @since 2.0.0 + */ + function build_query_string() { + $this->query_string = ''; + foreach ( (array) array_keys($this->query_vars) as $wpvar) { + if ( '' != $this->query_vars[$wpvar] ) { + $this->query_string .= (strlen($this->query_string) < 1) ? '' : '&'; + if ( !is_scalar($this->query_vars[$wpvar]) ) // Discard non-scalars. + continue; + $this->query_string .= $wpvar . '=' . rawurlencode($this->query_vars[$wpvar]); + } } - $this->in_the_loop = false; - return false; - } - - function rewind_posts() { - $this->current_post = -1; - if ($this->post_count > 0) { - $this->post = $this->posts[0]; + // query_string filter deprecated. Use request filter instead. + if ( has_filter('query_string') ) { // Don't bother filtering and parsing if no plugins are hooked in. + $this->query_string = apply_filters('query_string', $this->query_string); + parse_str($this->query_string, $this->query_vars); } } - - function &query($query) { - $this->parse_query($query); - return $this->get_posts(); - } - - function get_queried_object() { - if (isset($this->queried_object)) { - return $this->queried_object; - } - $this->queried_object = NULL; - $this->queried_object_id = 0; - - if ($this->is_category) { - $cat = $this->get('cat'); - $category = &get_category($cat); - $this->queried_object = &$category; - $this->queried_object_id = $cat; - } else if ($this->is_single) { - $this->queried_object = $this->post; - $this->queried_object_id = $this->post->ID; - } else if ($this->is_page) { - $this->queried_object = $this->post; - $this->queried_object_id = $this->post->ID; - } else if ($this->is_author) { - $author_id = $this->get('author'); - $author = get_userdata($author_id); - $this->queried_object = $author; - $this->queried_object_id = $author_id; + /** + * Set up the WordPress Globals. + * + * The query_vars property will be extracted to the GLOBALS. So care should + * be taken when naming global variables that might interfere with the + * WordPress environment. + * + * @global string $query_string Query string for the loop. + * @global int $more Only set, if single page or post. + * @global int $single If single page or post. Only set, if single page or post. + * + * @since 2.0.0 + */ + function register_globals() { + global $wp_query; + // Extract updated query vars back into global namespace. + foreach ( (array) $wp_query->query_vars as $key => $value) { + $GLOBALS[$key] = $value; } - return $this->queried_object; - } - - function get_queried_object_id() { - $this->get_queried_object(); + $GLOBALS['query_string'] = $this->query_string; + $GLOBALS['posts'] = & $wp_query->posts; + $GLOBALS['post'] = $wp_query->post; + $GLOBALS['request'] = $wp_query->request; - if (isset($this->queried_object_id)) { - return $this->queried_object_id; + if ( is_single() || is_page() ) { + $GLOBALS['more'] = 1; + $GLOBALS['single'] = 1; } - - return 0; } - function WP_Query ($query = '') { - if (! empty($query)) { - $this->query($query); - } + /** + * Set up the current user. + * + * @since 2.0.0 + */ + function init() { + wp_get_current_user(); } -} - -class retrospam_mgr { - var $spam_words; - var $comments_list; - var $found_comments; - function retrospam_mgr() { - global $wpdb; - - $list = explode("\n", get_settings('moderation_keys') ); - $list = array_unique( $list ); - $this->spam_words = $list; - - $this->comment_list = (array) $wpdb->get_results("SELECT comment_ID AS ID, comment_content AS text, comment_approved AS approved, comment_author_url AS url, comment_author_ip AS ip, comment_author_email AS email FROM $wpdb->comments ORDER BY comment_ID ASC"); - } // End of class constructor + /** + * Set up the Loop based on the query variables. + * + * @uses WP::$query_vars + * @since 2.0.0 + */ + function query_posts() { + global $wp_the_query; + $this->build_query_string(); + $wp_the_query->query($this->query_vars); + } - function move_spam( $id_list ) { - global $wpdb; - $cnt = 0; - $id_list = explode( ',', $id_list ); + /** + * Set the Headers for 404, if nothing is found for requested URL. + * + * Issue a 404 if a request doesn't match any posts and doesn't match + * any object (e.g. an existing-but-empty category, tag, author) and a 404 was not already + * issued, and if the request was not a search or the homepage. + * + * Otherwise, issue a 200. + * + * @since 2.0.0 + */ + function handle_404() { + global $wp_query; - foreach ( $id_list as $comment ) { - if ( $wpdb->query("update $wpdb->comments set comment_approved = '0' where comment_ID = '$comment'") ) { - $cnt++; + if ( !is_admin() && ( 0 == count( $wp_query->posts ) ) && !is_404() && !is_robots() && !is_search() && !is_home() ) { + // Don't 404 for these queries if they matched an object. + if ( ( is_tag() || is_category() || is_tax() || is_author() ) && $wp_query->get_queried_object() && !is_paged() ) { + if ( !is_404() ) + status_header( 200 ); + return; } + $wp_query->set_404(); + status_header( 404 ); + nocache_headers(); + } elseif ( !is_404() ) { + status_header( 200 ); } - echo "

"; - printf(__('%d comment(s) moved to the moderation queue.'), $cnt); - echo "

\n"; - } // End function move_spam - - function find_spam() { - $in_queue = 0; - - foreach( $this->comment_list as $comment ) { - if( $comment->approved == 1 ) { - foreach( $this->spam_words as $word ) { - $word = trim($word); - if ( empty( $word ) ) - continue; - $fulltext = strtolower($comment->email.' '.$comment->url.' '.$comment->ip.' '.$comment->text); - if( false !== strpos( $fulltext, strtolower($word) ) ) { - $this->found_comments[] = $comment->ID; - break; - } - } - } else { - $in_queue++; - } - } - return array( 'found' => $this->found_comments, 'in_queue' => $in_queue ); - } // End function find_spam - - function display_edit_form( $counters ) { - $numfound = count($counters[found]); - $numqueue = $counters[in_queue]; - - $body = '

' . sprintf(__('Suspected spam comments: %s'), "$numfound") . '

'; - - if ( count($counters[found]) > 0 ) { - $id_list = implode( ',', $counters[found] ); - $body .= '

'. __('Move suspect comments to moderation queue »') . '

'; - - } - $head = '

' . __('Check Comments Results:') . '

'; - - $foot .= '

' . __('« Return to Discussion Options page.') . '

'; - - return $head . $body . $foot; - } // End function display_edit_form - -} - -class WP_Rewrite { - var $permalink_structure; - var $category_base; - var $category_structure; - var $author_base = 'author'; - var $author_structure; - var $date_structure; - var $page_structure; - var $search_base = 'search'; - var $search_structure; - var $comments_base = 'comments'; - var $feed_base = 'feed'; - var $comments_feed_structure; - var $feed_structure; - var $front; - var $root = ''; - var $index = 'index.php'; - var $matches = ''; - var $rules; - var $use_verbose_rules = false; - var $rewritecode = - array( - '%year%', - '%monthnum%', - '%day%', - '%hour%', - '%minute%', - '%second%', - '%postname%', - '%post_id%', - '%category%', - '%author%', - '%pagename%', - '%search%' - ); - - var $rewritereplace = - array( - '([0-9]{4})', - '([0-9]{1,2})', - '([0-9]{1,2})', - '([0-9]{1,2})', - '([0-9]{1,2})', - '([0-9]{1,2})', - '([^/]+)', - '([0-9]+)', - '(.+?)', - '([^/]+)', - '([^/]+)', - '(.+)' - ); - - var $queryreplace = - array ( - 'year=', - 'monthnum=', - 'day=', - 'hour=', - 'minute=', - 'second=', - 'name=', - 'p=', - 'category_name=', - 'author_name=', - 'pagename=', - 's=' - ); - - var $feeds = array ('feed', 'rdf', 'rss', 'rss2', 'atom'); - - function using_permalinks() { - if (empty($this->permalink_structure)) - return false; - else - return true; - } - - function using_index_permalinks() { - if (empty($this->permalink_structure)) { - return false; - } - - // If the index is not in the permalink, we're using mod_rewrite. - if (preg_match('#^/*' . $this->index . '#', $this->permalink_structure)) { - return true; - } - - return false; } - function using_mod_rewrite_permalinks() { - if ( $this->using_permalinks() && ! $this->using_index_permalinks()) - return true; - else - return false; - } - - function preg_index($number) { - $match_prefix = '$'; - $match_suffix = ''; - - if (! empty($this->matches)) { - $match_prefix = '$' . $this->matches . '['; - $match_suffix = ']'; - } - - return "$match_prefix$number$match_suffix"; + /** + * Sets up all of the variables required by the WordPress environment. + * + * The action 'wp' has one parameter that references the WP object. It + * allows for accessing the properties and methods to further manipulate the + * object. + * + * @since 2.0.0 + * + * @param string|array $query_args Passed to {@link parse_request()} + */ + function main($query_args = '') { + $this->init(); + $this->parse_request($query_args); + $this->send_headers(); + $this->query_posts(); + $this->handle_404(); + $this->register_globals(); + do_action_ref_array('wp', array(&$this)); } - function page_rewrite_rules() { - $uris = get_settings('page_uris'); - $attachment_uris = get_settings('page_attachment_uris'); - - $rewrite_rules = array(); - $page_structure = $this->get_page_permastruct(); - if( is_array( $attachment_uris ) ) { - foreach ($attachment_uris as $uri => $pagename) { - $this->add_rewrite_tag('%pagename%', "($uri)", 'attachment='); - $rewrite_rules = array_merge($rewrite_rules, $this->generate_rewrite_rules($page_structure)); - } - } - if( is_array( $uris ) ) { - foreach ($uris as $uri => $pagename) { - $this->add_rewrite_tag('%pagename%', "($uri)", 'pagename='); - $rewrite_rules = array_merge($rewrite_rules, $this->generate_rewrite_rules($page_structure)); - } - } - - return $rewrite_rules; + /** + * PHP4 Constructor - Does nothing. + * + * Call main() method when ready to run setup. + * + * @since 2.0.0 + * + * @return WP + */ + function WP() { + // Empty. } +} - function get_date_permastruct() { - if (isset($this->date_structure)) { - return $this->date_structure; - } - - if (empty($this->permalink_structure)) { - $this->date_structure = ''; - return false; - } - - // The date permalink must have year, month, and day separated by slashes. - $endians = array('%year%/%monthnum%/%day%', '%day%/%monthnum%/%year%', '%monthnum%/%day%/%year%'); - - $this->date_structure = ''; - $date_endian = ''; - - foreach ($endians as $endian) { - if (false !== strpos($this->permalink_structure, $endian)) { - $date_endian= $endian; - break; - } - } - - if ( empty($date_endian) ) - $date_endian = '%year%/%monthnum%/%day%'; - - // Do not allow the date tags and %post_id% to overlap in the permalink - // structure. If they do, move the date tags to $front/date/. - $front = $this->front; - preg_match_all('/%.+?%/', $this->permalink_structure, $tokens); - $tok_index = 1; - foreach ($tokens[0] as $token) { - if ( ($token == '%post_id%') && ($tok_index <= 3) ) { - $front = $front . 'date/'; - break; - } - $tok_index++; - } +/** + * WordPress Error class. + * + * Container for checking for WordPress errors and error messages. Return + * WP_Error and use {@link is_wp_error()} to check if this class is returned. + * Many core WordPress functions pass this class in the event of an error and + * if not handled properly will result in code errors. + * + * @package WordPress + * @since 2.1.0 + */ +class WP_Error { + /** + * Stores the list of errors. + * + * @since 2.1.0 + * @var array + * @access private + */ + var $errors = array(); + + /** + * Stores the list of data for error codes. + * + * @since 2.1.0 + * @var array + * @access private + */ + var $error_data = array(); + + /** + * PHP4 Constructor - Sets up error message. + * + * If code parameter is empty then nothing will be done. It is possible to + * add multiple messages to the same code, but with other methods in the + * class. + * + * All parameters are optional, but if the code parameter is set, then the + * data parameter is optional. + * + * @since 2.1.0 + * + * @param string|int $code Error code + * @param string $message Error message + * @param mixed $data Optional. Error data. + * @return WP_Error + */ + function WP_Error($code = '', $message = '', $data = '') { + if ( empty($code) ) + return; - $this->date_structure = $front . $date_endian; + $this->errors[$code][] = $message; - return $this->date_structure; + if ( ! empty($data) ) + $this->error_data[$code] = $data; } - function get_year_permastruct() { - $structure = $this->get_date_permastruct($this->permalink_structure); - - if (empty($structure)) { - return false; - } - - $structure = str_replace('%monthnum%', '', $structure); - $structure = str_replace('%day%', '', $structure); - - $structure = preg_replace('#/+#', '/', $structure); + /** + * Retrieve all error codes. + * + * @since 2.1.0 + * @access public + * + * @return array List of error codes, if avaiable. + */ + function get_error_codes() { + if ( empty($this->errors) ) + return array(); - return $structure; + return array_keys($this->errors); } - function get_month_permastruct() { - $structure = $this->get_date_permastruct($this->permalink_structure); - - if (empty($structure)) { - return false; - } - - $structure = str_replace('%day%', '', $structure); - - $structure = preg_replace('#/+#', '/', $structure); + /** + * Retrieve first error code available. + * + * @since 2.1.0 + * @access public + * + * @return string|int Empty string, if no error codes. + */ + function get_error_code() { + $codes = $this->get_error_codes(); - return $structure; - } + if ( empty($codes) ) + return ''; - function get_day_permastruct() { - return $this->get_date_permastruct($this->permalink_structure); + return $codes[0]; } - function get_category_permastruct() { - if (isset($this->category_structure)) { - return $this->category_structure; - } + /** + * Retrieve all error messages or error messages matching code. + * + * @since 2.1.0 + * + * @param string|int $code Optional. Retrieve messages matching code, if exists. + * @return array Error strings on success, or empty array on failure (if using codee parameter). + */ + function get_error_messages($code = '') { + // Return all messages if no code specified. + if ( empty($code) ) { + $all_messages = array(); + foreach ( (array) $this->errors as $code => $messages ) + $all_messages = array_merge($all_messages, $messages); - if (empty($this->permalink_structure)) { - $this->category_structure = ''; - return false; + return $all_messages; } - if (empty($this->category_base)) - $this->category_structure = $this->front . 'category/'; + if ( isset($this->errors[$code]) ) + return $this->errors[$code]; else - $this->category_structure = $this->category_base . '/'; - - $this->category_structure .= '%category%'; - - return $this->category_structure; - } - - function get_author_permastruct() { - if (isset($this->author_structure)) { - return $this->author_structure; - } - - if (empty($this->permalink_structure)) { - $this->author_structure = ''; - return false; - } - - $this->author_structure = $this->front . $this->author_base . '/%author%'; - - return $this->author_structure; + return array(); } - function get_search_permastruct() { - if (isset($this->search_structure)) { - return $this->search_structure; - } - - if (empty($this->permalink_structure)) { - $this->search_structure = ''; - return false; - } - - $this->search_structure = $this->root . $this->search_base . '/%search%'; - - return $this->search_structure; + /** + * Get single error message. + * + * This will get the first message available for the code. If no code is + * given then the first code available will be used. + * + * @since 2.1.0 + * + * @param string|int $code Optional. Error code to retrieve message. + * @return string + */ + function get_error_message($code = '') { + if ( empty($code) ) + $code = $this->get_error_code(); + $messages = $this->get_error_messages($code); + if ( empty($messages) ) + return ''; + return $messages[0]; } - function get_page_permastruct() { - if (isset($this->page_structure)) { - return $this->page_structure; - } - - if (empty($this->permalink_structure)) { - $this->page_structure = ''; - return false; - } - - $this->page_structure = $this->root . '%pagename%'; + /** + * Retrieve error data for error code. + * + * @since 2.1.0 + * + * @param string|int $code Optional. Error code. + * @return mixed Null, if no errors. + */ + function get_error_data($code = '') { + if ( empty($code) ) + $code = $this->get_error_code(); - return $this->page_structure; + if ( isset($this->error_data[$code]) ) + return $this->error_data[$code]; + return null; } - function get_feed_permastruct() { - if (isset($this->feed_structure)) { - return $this->feed_structure; - } - - if (empty($this->permalink_structure)) { - $this->feed_structure = ''; - return false; - } - - $this->feed_structure = $this->root . $this->feed_base . '/%feed%'; - - return $this->feed_structure; + /** + * Append more error messages to list of error messages. + * + * @since 2.1.0 + * @access public + * + * @param string|int $code Error code. + * @param string $message Error message. + * @param mixed $data Optional. Error data. + */ + function add($code, $message, $data = '') { + $this->errors[$code][] = $message; + if ( ! empty($data) ) + $this->error_data[$code] = $data; } - function get_comment_feed_permastruct() { - if (isset($this->comment_feed_structure)) { - return $this->comment_feed_structure; - } - - if (empty($this->permalink_structure)) { - $this->comment_feed_structure = ''; - return false; - } - - $this->comment_feed_structure = $this->root . $this->comments_base . '/' . $this->feed_base . '/%feed%'; - - return $this->comment_feed_structure; - } + /** + * Add data for error code. + * + * The error code can only contain one error data. + * + * @since 2.1.0 + * + * @param mixed $data Error data. + * @param string|int $code Error code. + */ + function add_data($data, $code = '') { + if ( empty($code) ) + $code = $this->get_error_code(); - function add_rewrite_tag($tag, $pattern, $query) { - // If the tag already exists, replace the existing pattern and query for - // that tag, otherwise add the new tag, pattern, and query to the end of - // the arrays. - $position = array_search($tag, $this->rewritecode); - if (FALSE !== $position && NULL !== $position) { - $this->rewritereplace[$position] = $pattern; - $this->queryreplace[$position] = $query; - } else { - $this->rewritecode[] = $tag; - $this->rewritereplace[] = $pattern; - $this->queryreplace[] = $query; - } + $this->error_data[$code] = $data; } +} - function generate_rewrite_rules($permalink_structure, $paged = true, $feed = true, $forcomments = false, $walk_dirs = true) { - $feedregex2 = ''; - foreach ($this->feeds as $feed_name) { - $feedregex2 .= $feed_name . '|'; - } - $feedregex2 = '(' . trim($feedregex2, '|') . ')/?$'; - $feedregex = $this->feed_base . '/' . $feedregex2; - - $trackbackregex = 'trackback/?$'; - $pageregex = 'page/?([0-9]{1,})/?$'; - - $front = substr($permalink_structure, 0, strpos($permalink_structure, '%')); - preg_match_all('/%.+?%/', $permalink_structure, $tokens); - - $num_tokens = count($tokens[0]); - - $index = $this->index; - $feedindex = $index; - $trackbackindex = $index; - for ($i = 0; $i < $num_tokens; ++$i) { - if (0 < $i) { - $queries[$i] = $queries[$i - 1] . '&'; - } - - $query_token = str_replace($this->rewritecode, $this->queryreplace, $tokens[0][$i]) . $this->preg_index($i+1); - $queries[$i] .= $query_token; - } +/** + * Check whether variable is a WordPress Error. + * + * Looks at the object and if a WP_Error class. Does not check to see if the + * parent is also WP_Error, so can't inherit WP_Error and still use this + * function. + * + * @since 2.1.0 + * + * @param mixed $thing Check if unknown variable is WordPress Error object. + * @return bool True, if WP_Error. False, if not WP_Error. + */ +function is_wp_error($thing) { + if ( is_object($thing) && is_a($thing, 'WP_Error') ) + return true; + return false; +} - $structure = $permalink_structure; - if ($front != '/') { - $structure = str_replace($front, '', $structure); - } - $structure = trim($structure, '/'); - if ($walk_dirs) { - $dirs = explode('/', $structure); - } else { - $dirs[] = $structure; - } - $num_dirs = count($dirs); +/** + * A class for displaying various tree-like structures. + * + * Extend the Walker class to use it, see examples at the below. Child classes + * do not need to implement all of the abstract methods in the class. The child + * only needs to implement the methods that are needed. Also, the methods are + * not strictly abstract in that the parameter definition needs to be followed. + * The child classes can have additional parameters. + * + * @package WordPress + * @since 2.1.0 + * @abstract + */ +class Walker { + /** + * What the class handles. + * + * @since 2.1.0 + * @var string + * @access public + */ + var $tree_type; + + /** + * DB fields to use. + * + * @since 2.1.0 + * @var array + * @access protected + */ + var $db_fields; + + /** + * Max number of pages walked by the paged walker + * + * @since 2.7.0 + * @var int + * @access protected + */ + var $max_pages = 1; + + /** + * Starts the list before the elements are added. + * + * Additional parameters are used in child classes. The args parameter holds + * additional values that may be used with the child class methods. This + * method is called at the start of the output list. + * + * @since 2.1.0 + * @abstract + * + * @param string $output Passed by reference. Used to append additional content. + */ + function start_lvl(&$output) {} + + /** + * Ends the list of after the elements are added. + * + * Additional parameters are used in child classes. The args parameter holds + * additional values that may be used with the child class methods. This + * method finishes the list at the end of output of the elements. + * + * @since 2.1.0 + * @abstract + * + * @param string $output Passed by reference. Used to append additional content. + */ + function end_lvl(&$output) {} + + /** + * Start the element output. + * + * Additional parameters are used in child classes. The args parameter holds + * additional values that may be used with the child class methods. Includes + * the element output also. + * + * @since 2.1.0 + * @abstract + * + * @param string $output Passed by reference. Used to append additional content. + */ + function start_el(&$output) {} + + /** + * Ends the element output, if needed. + * + * Additional parameters are used in child classes. The args parameter holds + * additional values that may be used with the child class methods. + * + * @since 2.1.0 + * @abstract + * + * @param string $output Passed by reference. Used to append additional content. + */ + function end_el(&$output) {} + + /** + * Traverse elements to create list from elements. + * + * Display one element if the element doesn't have any children otherwise, + * display the element and its children. Will only traverse up to the max + * depth and no ignore elements under that depth. It is possible to set the + * max depth to include all depths, see walk() method. + * + * This method shouldn't be called directly, use the walk() method instead. + * + * @since 2.5.0 + * + * @param object $element Data object + * @param array $children_elements List of elements to continue traversing. + * @param int $max_depth Max depth to traverse. + * @param int $depth Depth of current element. + * @param array $args + * @param string $output Passed by reference. Used to append additional content. + * @return null Null on failure with no changes to parameters. + */ + function display_element( $element, &$children_elements, $max_depth, $depth=0, $args, &$output ) { - $front = preg_replace('|^/+|', '', $front); + if ( !$element ) + return; - $post_rewrite = array(); - $struct = $front; - for ($j = 0; $j < $num_dirs; ++$j) { - $struct .= $dirs[$j] . '/'; - $struct = ltrim($struct, '/'); - $match = str_replace($this->rewritecode, $this->rewritereplace, $struct); - $num_toks = preg_match_all('/%.+?%/', $struct, $toks); - $query = $queries[$num_toks - 1]; + $id_field = $this->db_fields['id']; - $pagematch = $match . $pageregex; - $pagequery = $index . '?' . $query . '&paged=' . $this->preg_index($num_toks + 1); + //display this element + if ( is_array( $args[0] ) ) + $args[0]['has_children'] = ! empty( $children_elements[$element->$id_field] ); + $cb_args = array_merge( array(&$output, $element, $depth), $args); + call_user_func_array(array(&$this, 'start_el'), $cb_args); - $feedmatch = $match . $feedregex; - $feedquery = $feedindex . '?' . $query . '&feed=' . $this->preg_index($num_toks + 1); + $id = $element->$id_field; - $feedmatch2 = $match . $feedregex2; - $feedquery2 = $feedindex . '?' . $query . '&feed=' . $this->preg_index($num_toks + 1); + // descend only when the depth is right and there are childrens for this element + if ( ($max_depth == 0 || $max_depth > $depth+1 ) && isset( $children_elements[$id]) ) { - if ($forcomments) { - $feedquery .= '&withcomments=1'; - $feedquery2 .= '&withcomments=1'; - } + foreach( $children_elements[ $id ] as $child ){ - $rewrite = array(); - if ($feed) - $rewrite = array($feedmatch => $feedquery, $feedmatch2 => $feedquery2); - if ($paged) - $rewrite = array_merge($rewrite, array($pagematch => $pagequery)); - - if ($num_toks) { - $post = false; - $page = false; - if (strstr($struct, '%postname%') || strstr($struct, '%post_id%') - || strstr($struct, '%pagename%') - || (strstr($struct, '%year%') && strstr($struct, '%monthnum%') && strstr($struct, '%day%') && strstr($struct, '%hour%') && strstr($struct, '%minute') && strstr($struct, '%second%'))) { - $post = true; - if ( strstr($struct, '%pagename%') ) - $page = true; - $trackbackmatch = $match . $trackbackregex; - $trackbackquery = $trackbackindex . '?' . $query . '&tb=1'; - $match = rtrim($match, '/'); - $submatchbase = str_replace(array('(',')'),'',$match); - $sub1 = $submatchbase . '/([^/]+)/'; - $sub1tb = $sub1 . $trackbackregex; - $sub1feed = $sub1 . $feedregex; - $sub1feed2 = $sub1 . $feedregex2; - $sub1 .= '?$'; - $sub2 = $submatchbase . '/attachment/([^/]+)/'; - $sub2tb = $sub2 . $trackbackregex; - $sub2feed = $sub2 . $feedregex; - $sub2feed2 = $sub2 . $feedregex2; - $sub2 .= '?$'; - $subquery = $index . '?attachment=' . $this->preg_index(1); - $subtbquery = $subquery . '&tb=1'; - $subfeedquery = $subquery . '&feed=' . $this->preg_index(2); - $match = $match . '(/[0-9]+)?/?$'; - $query = $index . '?' . $query . '&page=' . $this->preg_index($num_toks + 1); - } else { - $match .= '?$'; - $query = $index . '?' . $query; - } - - $rewrite = array_merge($rewrite, array($match => $query)); - - if ($post) { - $rewrite = array_merge(array($trackbackmatch => $trackbackquery), $rewrite); - if ( ! $page ) - $rewrite = array_merge($rewrite, array($sub1 => $subquery, $sub1tb => $subtbquery, $sub1feed => $subfeedquery, $sub1feed2 => $subfeedquery)); - $rewrite = array_merge($rewrite, array($sub2 => $subquery, $sub2tb => $subtbquery, $sub2feed => $subfeedquery, $sub2feed2 => $subfeedquery)); + if ( !isset($newlevel) ) { + $newlevel = true; + //start the child delimiter + $cb_args = array_merge( array(&$output, $depth), $args); + call_user_func_array(array(&$this, 'start_lvl'), $cb_args); } + $this->display_element( $child, $children_elements, $max_depth, $depth + 1, $args, $output ); } - $post_rewrite = array_merge($rewrite, $post_rewrite); + unset( $children_elements[ $id ] ); } - return $post_rewrite; - } - function generate_rewrite_rule($permalink_structure, $walk_dirs = false) { - return $this->generate_rewrite_rules($permalink_structure, false, false, false, $walk_dirs); + if ( isset($newlevel) && $newlevel ){ + //end the child delimiter + $cb_args = array_merge( array(&$output, $depth), $args); + call_user_func_array(array(&$this, 'end_lvl'), $cb_args); + } + + //end this element + $cb_args = array_merge( array(&$output, $element, $depth), $args); + call_user_func_array(array(&$this, 'end_el'), $cb_args); } - /* rewrite_rules - * Construct rewrite matches and queries from permalink structure. - * Returns an associate array of matches and queries. + /** + * Display array of elements hierarchically. + * + * It is a generic function which does not assume any existing order of + * elements. max_depth = -1 means flatly display every element. max_depth = + * 0 means display all levels. max_depth > 0 specifies the number of + * display levels. + * + * @since 2.1.0 + * + * @param array $elements + * @param int $max_depth + * @return string */ - function rewrite_rules() { - $rewrite = array(); - - if (empty($this->permalink_structure)) { - return $rewrite; + function walk( $elements, $max_depth) { + + $args = array_slice(func_get_args(), 2); + $output = ''; + + if ($max_depth < -1) //invalid parameter + return $output; + + if (empty($elements)) //nothing to walk + return $output; + + $id_field = $this->db_fields['id']; + $parent_field = $this->db_fields['parent']; + + // flat display + if ( -1 == $max_depth ) { + $empty_array = array(); + foreach ( $elements as $e ) + $this->display_element( $e, $empty_array, 1, 0, $args, $output ); + return $output; + } + + /* + * need to display in hierarchical order + * separate elements into two buckets: top level and children elements + * children_elements is two dimensional array, eg. + * children_elements[10][] contains all sub-elements whose parent is 10. + */ + $top_level_elements = array(); + $children_elements = array(); + foreach ( $elements as $e) { + if ( 0 == $e->$parent_field ) + $top_level_elements[] = $e; + else + $children_elements[ $e->$parent_field ][] = $e; } - //Default Feed rules - These are require to allow for the direct access files to work with permalink structure starting with %category% - $default_feeds = array( 'wp-atom.php$' => $this->index .'?feed=atom', - 'wp-rdf.php$' => $this->index .'?feed=rdf', - 'wp-rss.php$' => $this->index .'?feed=rss', - 'wp-rss2.php$' => $this->index .'?feed=rss2', - 'wp-feed.php$' => $this->index .'?feed=feed', - 'wp-commentsrss2.php$' => $this->index . '?feed=rss2&withcomments=1'); - - - // Post - $post_rewrite = $this->generate_rewrite_rules($this->permalink_structure); - $post_rewrite = apply_filters('post_rewrite_rules', $post_rewrite); - - // Date - $date_rewrite = $this->generate_rewrite_rules($this->get_date_permastruct()); - $date_rewrite = apply_filters('date_rewrite_rules', $date_rewrite); - - // Root - $root_rewrite = $this->generate_rewrite_rules($this->root . '/'); - $root_rewrite = apply_filters('root_rewrite_rules', $root_rewrite); - - // Comments - $comments_rewrite = $this->generate_rewrite_rules($this->root . $this->comments_base, true, true, true, false); - $comments_rewrite = apply_filters('comments_rewrite_rules', $comments_rewrite); - - // Search - $search_structure = $this->get_search_permastruct(); - $search_rewrite = $this->generate_rewrite_rules($search_structure); - $search_rewrite = apply_filters('search_rewrite_rules', $search_rewrite); - - // Categories - $category_rewrite = $this->generate_rewrite_rules($this->get_category_permastruct()); - $category_rewrite = apply_filters('category_rewrite_rules', $category_rewrite); - - // Authors - $author_rewrite = $this->generate_rewrite_rules($this->get_author_permastruct()); - $author_rewrite = apply_filters('author_rewrite_rules', $author_rewrite); - - // Pages - $page_rewrite = $this->page_rewrite_rules(); - $page_rewrite = apply_filters('page_rewrite_rules', $page_rewrite); - - // Put them together. - $this->rules = array_merge($default_feeds, $page_rewrite, $root_rewrite, $comments_rewrite, $search_rewrite, $category_rewrite, $author_rewrite, $date_rewrite, $post_rewrite); - - do_action('generate_rewrite_rules', array(&$this)); - $this->rules = apply_filters('rewrite_rules_array', $this->rules); - - return $this->rules; - } - function wp_rewrite_rules() { - $this->rules = get_option('rewrite_rules'); - if ( empty($this->rules) ) { - $this->matches = 'matches'; - $this->rewrite_rules(); - update_option('rewrite_rules', $this->rules); + /* + * when none of the elements is top level + * assume the first one must be root of the sub elements + */ + if ( empty($top_level_elements) ) { + + $first = array_slice( $elements, 0, 1 ); + $root = $first[0]; + + $top_level_elements = array(); + $children_elements = array(); + foreach ( $elements as $e) { + if ( $root->$parent_field == $e->$parent_field ) + $top_level_elements[] = $e; + else + $children_elements[ $e->$parent_field ][] = $e; + } } - return $this->rules; + foreach ( $top_level_elements as $e ) + $this->display_element( $e, $children_elements, $max_depth, 0, $args, $output ); + + /* + * if we are displaying all levels, and remaining children_elements is not empty, + * then we got orphans, which should be displayed regardless + */ + if ( ( $max_depth == 0 ) && count( $children_elements ) > 0 ) { + $empty_array = array(); + foreach ( $children_elements as $orphans ) + foreach( $orphans as $op ) + $this->display_element( $op, $empty_array, 1, 0, $args, $output ); + } + + return $output; } - function mod_rewrite_rules() { - if ( ! $this->using_permalinks()) { + /** + * paged_walk() - produce a page of nested elements + * + * Given an array of hierarchical elements, the maximum depth, a specific page number, + * and number of elements per page, this function first determines all top level root elements + * belonging to that page, then lists them and all of their children in hierarchical order. + * + * @package WordPress + * @since 2.7 + * @param $max_depth = 0 means display all levels; $max_depth > 0 specifies the number of display levels. + * @param $page_num the specific page number, beginning with 1. + * @return XHTML of the specified page of elements + */ + function paged_walk( $elements, $max_depth, $page_num, $per_page ) { + + /* sanity check */ + if ( empty($elements) || $max_depth < -1 ) return ''; - } - $site_root = parse_url(get_settings('siteurl')); - $site_root = trailingslashit($site_root['path']); - - $home_root = parse_url(get_settings('home')); - $home_root = trailingslashit($home_root['path']); - - $rules = "\n"; - $rules .= "RewriteEngine On\n"; - $rules .= "RewriteBase $home_root\n"; - - if ($this->use_verbose_rules) { - $this->matches = ''; - $rewrite = $this->rewrite_rules(); - $num_rules = count($rewrite); - $rules .= "RewriteCond %{REQUEST_FILENAME} -f [OR]\n" . - "RewriteCond %{REQUEST_FILENAME} -d\n" . - "RewriteRule ^.*$ - [S=$num_rules]\n"; - - foreach ($rewrite as $match => $query) { - // Apache 1.3 does not support the reluctant (non-greedy) modifier. - $match = str_replace('.+?', '.+', $match); - - // If the match is unanchored and greedy, prepend rewrite conditions - // to avoid infinite redirects and eclipsing of real files. - if ($match == '(.+)/?$' || $match == '([^/]+)/?$' ) { - //nada. - } - - if (strstr($query, $this->index)) { - $rules .= 'RewriteRule ^' . $match . ' ' . $home_root . $query . " [QSA,L]\n"; - } else { - $rules .= 'RewriteRule ^' . $match . ' ' . $site_root . $query . " [QSA,L]\n"; - } - } + $args = array_slice( func_get_args(), 4 ); + $output = ''; + + $id_field = $this->db_fields['id']; + $parent_field = $this->db_fields['parent']; + + $count = -1; + if ( -1 == $max_depth ) + $total_top = count( $elements ); + if ( $page_num < 1 || $per_page < 0 ) { + // No paging + $paging = false; + $start = 0; + if ( -1 == $max_depth ) + $end = $total_top; + $this->max_pages = 1; } else { - $rules .= "RewriteCond %{REQUEST_FILENAME} !-f\n" . - "RewriteCond %{REQUEST_FILENAME} !-d\n" . - "RewriteRule . {$home_root}{$this->index} [L]\n"; + $paging = true; + $start = ( (int)$page_num - 1 ) * (int)$per_page; + $end = $start + $per_page; + if ( -1 == $max_depth ) + $this->max_pages = ceil($total_top / $per_page); + } + + // flat display + if ( -1 == $max_depth ) { + if ( !empty($args[0]['reverse_top_level']) ) { + $elements = array_reverse( $elements ); + $oldstart = $start; + $start = $total_top - $end; + $end = $total_top - $oldstart; + } + + $empty_array = array(); + foreach ( $elements as $e ) { + $count++; + if ( $count < $start ) + continue; + if ( $count >= $end ) + break; + $this->display_element( $e, $empty_array, 1, 0, $args, $output ); + } + return $output; + } + + /* + * separate elements into two buckets: top level and children elements + * children_elements is two dimensional array, eg. + * children_elements[10][] contains all sub-elements whose parent is 10. + */ + $top_level_elements = array(); + $children_elements = array(); + foreach ( $elements as $e) { + if ( 0 == $e->$parent_field ) + $top_level_elements[] = $e; + else + $children_elements[ $e->$parent_field ][] = $e; } - $rules .= "\n"; + $total_top = count( $top_level_elements ); + if ( $paging ) + $this->max_pages = ceil($total_top / $per_page); + else + $end = $total_top; - $rules = apply_filters('mod_rewrite_rules', $rules); - $rules = apply_filters('rewrite_rules', $rules); // Deprecated + if ( !empty($args[0]['reverse_top_level']) ) { + $top_level_elements = array_reverse( $top_level_elements ); + $oldstart = $start; + $start = $total_top - $end; + $end = $total_top - $oldstart; + } + if ( !empty($args[0]['reverse_children']) ) { + foreach ( $children_elements as $parent => $children ) + $children_elements[$parent] = array_reverse( $children ); + } - return $rules; - } + foreach ( $top_level_elements as $e ) { + $count++; - function flush_rules() { - generate_page_rewrite_rules(); - delete_option('rewrite_rules'); - $this->wp_rewrite_rules(); - if ( function_exists('save_mod_rewrite_rules') ) - save_mod_rewrite_rules(); - } + //for the last page, need to unset earlier children in order to keep track of orphans + if ( $end >= $total_top && $count < $start ) + $this->unset_children( $e, $children_elements ); - function init() { - $this->permalink_structure = get_settings('permalink_structure'); - $this->front = substr($this->permalink_structure, 0, strpos($this->permalink_structure, '%')); - $this->root = ''; - if ($this->using_index_permalinks()) { - $this->root = $this->index . '/'; + if ( $count < $start ) + continue; + + if ( $count >= $end ) + break; + + $this->display_element( $e, $children_elements, $max_depth, 0, $args, $output ); } - $this->category_base = get_settings('category_base'); - unset($this->category_structure); - unset($this->author_structure); - unset($this->date_structure); - unset($this->page_structure); - unset($this->search_structure); - unset($this->feed_structure); - unset($this->comment_feed_structure); - } - function set_permalink_structure($permalink_structure) { - if ($permalink_structure != $this->permalink_structure) { - update_option('permalink_structure', $permalink_structure); - $this->init(); + if ( $end >= $total_top && count( $children_elements ) > 0 ) { + $empty_array = array(); + foreach ( $children_elements as $orphans ) + foreach( $orphans as $op ) + $this->display_element( $op, $empty_array, 1, 0, $args, $output ); } + + return $output; } - function set_category_base($category_base) { - if ($category_base != $this->category_base) { - update_option('category_base', $category_base); - $this->init(); + function get_number_of_root_elements( $elements ){ + + $num = 0; + $parent_field = $this->db_fields['parent']; + + foreach ( $elements as $e) { + if ( 0 == $e->$parent_field ) + $num++; } + return $num; } - function WP_Rewrite() { - $this->init(); + // unset all the children for a given top level element + function unset_children( $e, &$children_elements ){ + + if ( !$e || !$children_elements ) + return; + + $id_field = $this->db_fields['id']; + $id = $e->$id_field; + + if ( !empty($children_elements[$id]) && is_array($children_elements[$id]) ) + foreach ( (array) $children_elements[$id] as $child ) + $this->unset_children( $child, $children_elements ); + + if ( isset($children_elements[$id]) ) + unset( $children_elements[$id] ); + } } -class WP { - var $public_query_vars = array('m', 'p', 'posts', 'w', 'cat', 'withcomments', 's', 'search', 'exact', 'sentence', 'debug', 'calendar', 'page', 'paged', 'more', 'tb', 'pb', 'author', 'order', 'orderby', 'year', 'monthnum', 'day', 'hour', 'minute', 'second', 'name', 'category_name', 'feed', 'author_name', 'static', 'pagename', 'page_id', 'error', 'comments_popup', 'attachment', 'attachment_id', 'subpost', 'subpost_id', 'preview'); +/** + * Create HTML list of pages. + * + * @package WordPress + * @since 2.1.0 + * @uses Walker + */ +class Walker_Page extends Walker { + /** + * @see Walker::$tree_type + * @since 2.1.0 + * @var string + */ + var $tree_type = 'page'; - var $private_query_vars = array('posts_per_page', 'posts_per_archive_page', 'what_to_show', 'showposts', 'nopaging', 'show_post_type'); + /** + * @see Walker::$db_fields + * @since 2.1.0 + * @todo Decouple this. + * @var array + */ + var $db_fields = array ('parent' => 'post_parent', 'id' => 'ID'); + + /** + * @see Walker::start_lvl() + * @since 2.1.0 + * + * @param string $output Passed by reference. Used to append additional content. + * @param int $depth Depth of page. Used for padding. + */ + function start_lvl(&$output, $depth) { + $indent = str_repeat("\t", $depth); + $output .= "\n$indent\n"; + } - function parse_request($extra_query_vars = '') { - global $wp_rewrite; + /** + * @see Walker::start_el() + * @since 2.1.0 + * + * @param string $output Passed by reference. Used to append additional content. + * @param object $page Page data object. + * @param int $depth Depth of page. Used for padding. + * @param int $current_page Page ID. + * @param array $args + */ + function start_el(&$output, $page, $depth, $args, $current_page) { + if ( $depth ) + $indent = str_repeat("\t", $depth); + else + $indent = ''; - $this->query_vars = array(); + extract($args, EXTR_SKIP); + $css_class = array('page_item', 'page-item-'.$page->ID); + if ( !empty($current_page) ) { + $_current_page = get_page( $current_page ); + if ( isset($_current_page->ancestors) && in_array($page->ID, (array) $_current_page->ancestors) ) + $css_class[] = 'current_page_ancestor'; + if ( $page->ID == $current_page ) + $css_class[] = 'current_page_item'; + elseif ( $_current_page && $page->ID == $_current_page->post_parent ) + $css_class[] = 'current_page_parent'; + } elseif ( $page->ID == get_option('page_for_posts') ) { + $css_class[] = 'current_page_parent'; + } - if (! empty($extra_query_vars)) - parse_str($extra_query_vars, $extra_query_vars); - else - $extra_query_vars = array(); + $css_class = implode(' ', apply_filters('page_css_class', $css_class, $page)); - // Process PATH_INFO, REQUEST_URI, and 404 for permalinks. + $output .= $indent . '
  • ' . $link_before . apply_filters( 'the_title', $page->post_title, $page->ID ) . $link_after . ''; - // Fetch the rewrite rules. - $rewrite = $wp_rewrite->wp_rewrite_rules(); + if ( !empty($show_date) ) { + if ( 'modified' == $show_date ) + $time = $page->post_modified; + else + $time = $page->post_date; - if (! empty($rewrite)) { - // If we match a rewrite rule, this will be cleared. - $error = '404'; - $this->did_permalink = true; + $output .= " " . mysql2date($date_format, $time); + } + } - $pathinfo = $_SERVER['PATH_INFO']; - $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_settings('home')); - $home_path = $home_path['path']; - $home_path = trim($home_path, '/'); + /** + * @see Walker::end_el() + * @since 2.1.0 + * + * @param string $output Passed by reference. Used to append additional content. + * @param object $page Page data object. Not used. + * @param int $depth Depth of page. Not Used. + */ + function end_el(&$output, $page, $depth) { + $output .= "
  • \n"; + } - // 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 = str_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; - } +/** + * Create HTML dropdown list of pages. + * + * @package WordPress + * @since 2.1.0 + * @uses Walker + */ +class Walker_PageDropdown extends Walker { + /** + * @see Walker::$tree_type + * @since 2.1.0 + * @var string + */ + var $tree_type = 'page'; - $this->request = $request; + /** + * @see Walker::$db_fields + * @since 2.1.0 + * @todo Decouple this + * @var array + */ + var $db_fields = array ('parent' => 'post_parent', 'id' => 'ID'); + + /** + * @see Walker::start_el() + * @since 2.1.0 + * + * @param string $output Passed by reference. Used to append additional content. + * @param object $page Page data object. + * @param int $depth Depth of page in reference to parent pages. Used for padding. + * @param array $args Uses 'selected' argument for selected page to set selected HTML attribute for option element. + */ + function start_el(&$output, $page, $depth, $args) { + $pad = str_repeat(' ', $depth * 3); + + $output .= "\t\n"; + } +} - // 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($req_uri)) && (strpos($match, $req_uri) === 0) && ($req_uri != $request)) { - $request_match = $req_uri . '/' . $request; - } +/** + * Create HTML list of categories. + * + * @package WordPress + * @since 2.1.0 + * @uses Walker + */ +class Walker_Category extends Walker { + /** + * @see Walker::$tree_type + * @since 2.1.0 + * @var string + */ + var $tree_type = 'category'; - if (preg_match("!^$match!", $request_match, $matches) || - preg_match("!^$match!", urldecode($request_match), $matches)) { - // Got a match. - $this->matched_rule = $match; + /** + * @see Walker::$db_fields + * @since 2.1.0 + * @todo Decouple this + * @var array + */ + var $db_fields = array ('parent' => 'parent', 'id' => 'term_id'); + + /** + * @see Walker::start_lvl() + * @since 2.1.0 + * + * @param string $output Passed by reference. Used to append additional content. + * @param int $depth Depth of category. Used for tab indentation. + * @param array $args Will only append content if style argument value is 'list'. + */ + function start_lvl(&$output, $depth, $args) { + if ( 'list' != $args['style'] ) + return; - // Trim the query of everything up to the '?'. - $query = preg_replace("!^.+\?!", '', $query); + $indent = str_repeat("\t", $depth); + $output .= "$indent\n"; + } - // If we're processing a 404 request, clear the error var - // since we found something. - if (isset($_GET['error'])) - unset($_GET['error']); + /** + * @see Walker::start_el() + * @since 2.1.0 + * + * @param string $output Passed by reference. Used to append additional content. + * @param object $category Category data object. + * @param int $depth Depth of category in reference to parents. + * @param array $args + */ + function start_el(&$output, $category, $depth, $args) { + extract($args); + + $cat_name = esc_attr( $category->name); + $cat_name = apply_filters( 'list_cats', $cat_name, $category ); + $link = 'description) ) + $link .= 'title="' . sprintf(__( 'View all posts filed under %s' ), $cat_name) . '"'; + else + $link .= 'title="' . esc_attr( strip_tags( apply_filters( 'category_description', $category->description, $category ) ) ) . '"'; + $link .= '>'; + $link .= $cat_name . ''; - if (isset($error)) - unset($error); + if ( (! empty($feed_image)) || (! empty($feed)) ) { + $link .= ' '; - break; - } - } + if ( empty($feed_image) ) + $link .= '('; - // If req_uri is empty or if it is a request for ourself, unset error. - if ( empty($request) || $req_uri == $self || strstr($_SERVER['PHP_SELF'], 'wp-admin/') ) { - if (isset($_GET['error'])) - unset($_GET['error']); + $link .= 'did_permalink = false; + if ( empty($feed) ) + $alt = ' alt="' . sprintf(__( 'Feed for all posts filed under %s' ), $cat_name ) . '"'; + else { + $title = ' title="' . $feed . '"'; + $alt = ' alt="' . $feed . '"'; + $name = $feed; + $link .= $title; } - } - $this->public_query_vars = apply_filters('query_vars', $this->public_query_vars); + $link .= '>'; - for ($i=0; $ipublic_query_vars); $i += 1) { - $wpvar = $this->public_query_vars[$i]; - if (isset($extra_query_vars[$wpvar])) - $this->query_vars[$wpvar] = $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($query_vars[$wpvar])) - $this->query_vars[$wpvar] = $query_vars[$wpvar]; + if ( empty($feed_image) ) + $link .= $name; else - $this->query_vars[$wpvar] = ''; + $link .= "'; + $link .= ''; + if ( empty($feed_image) ) + $link .= ')'; + } - if ( !empty( $this->query_vars[$wpvar] ) ) - $this->query_vars[$wpvar] = (string) $this->query_vars[$wpvar]; + if ( isset($show_count) && $show_count ) + $link .= ' (' . intval($category->count) . ')'; + + if ( isset($show_date) && $show_date ) { + $link .= ' ' . gmdate('Y-m-d', $category->last_update_timestamp); } - if ( isset($error) ) - $this->query_vars['error'] = $error; - } + if ( isset($current_category) && $current_category ) + $_current_category = get_category( $current_category ); - function send_headers() { - @header('X-Pingback: '. get_bloginfo('pingback_url')); - if ( is_user_logged_in() ) - nocache_headers(); - if ( !empty($this->query_vars['error']) && '404' == $this->query_vars['error'] ) { - status_header( 404 ); - if ( !is_user_logged_in() ) - nocache_headers(); - @header('Content-type: ' . get_option('html_type') . '; charset=' . get_option('blog_charset')); - } else if ( empty($this->query_vars['feed']) ) { - @header('Content-type: ' . get_option('html_type') . '; charset=' . get_option('blog_charset')); + if ( 'list' == $args['style'] ) { + $output .= "\tterm_id; + if ( isset($current_category) && $current_category && ($category->term_id == $current_category) ) + $class .= ' current-cat'; + elseif ( isset($_current_category) && $_current_category && ($category->term_id == $_current_category->parent) ) + $class .= ' current-cat-parent'; + $output .= ' class="'.$class.'"'; + $output .= ">$link\n"; } else { - // We're showing a feed, so WP is indeed the only thing that last changed - if ( $this->query_vars['withcomments'] ) - $wp_last_modified = mysql2date('D, d M Y H:i:s', get_lastcommentmodified('GMT'), 0).' GMT'; - else - $wp_last_modified = mysql2date('D, d M Y H:i:s', get_lastpostmodified('GMT'), 0).' GMT'; - $wp_etag = '"' . md5($wp_last_modified) . '"'; - @header("Last-Modified: $wp_last_modified"); - @header("ETag: $wp_etag"); + $output .= "\t$link
    \n"; + } + } - // Support for Conditional GET - if (isset($_SERVER['HTTP_IF_NONE_MATCH'])) - $client_etag = stripslashes(stripslashes($_SERVER['HTTP_IF_NONE_MATCH'])); - else $client_etag = false; + /** + * @see Walker::end_el() + * @since 2.1.0 + * + * @param string $output Passed by reference. Used to append additional content. + * @param object $page Not used. + * @param int $depth Depth of category. Not used. + * @param array $args Only uses 'list' for whether should append to output. + */ + function end_el(&$output, $page, $depth, $args) { + if ( 'list' != $args['style'] ) + return; - $client_last_modified = trim( $_SERVER['HTTP_IF_MODIFIED_SINCE']); - // If string is empty, return 0. If not, attempt to parse into a timestamp - $client_modified_timestamp = $client_last_modified ? strtotime($client_last_modified) : 0; + $output .= "\n"; + } - // Make a timestamp for our most recent modification... - $wp_modified_timestamp = strtotime($wp_last_modified); +} - if ( ($client_last_modified && $client_etag) ? - (($client_modified_timestamp >= $wp_modified_timestamp) && ($client_etag == $wp_etag)) : - (($client_modified_timestamp >= $wp_modified_timestamp) || ($client_etag == $wp_etag)) ) { - status_header( 304 ); - exit; - } - } +/** + * Create HTML dropdown list of Categories. + * + * @package WordPress + * @since 2.1.0 + * @uses Walker + */ +class Walker_CategoryDropdown extends Walker { + /** + * @see Walker::$tree_type + * @since 2.1.0 + * @var string + */ + var $tree_type = 'category'; + + /** + * @see Walker::$db_fields + * @since 2.1.0 + * @todo Decouple this + * @var array + */ + var $db_fields = array ('parent' => 'parent', 'id' => 'term_id'); + + /** + * @see Walker::start_el() + * @since 2.1.0 + * + * @param string $output Passed by reference. Used to append additional content. + * @param object $category Category data object. + * @param int $depth Depth of category. Used for padding. + * @param array $args Uses 'selected', 'show_count', and 'show_last_update' keys, if they exist. + */ + function start_el(&$output, $category, $depth, $args) { + $pad = str_repeat(' ', $depth * 3); + + $cat_name = apply_filters('list_cats', $category->name, $category); + $output .= "\t\n"; } +} - function build_query_string() { - $this->query_string = ''; +/** + * Send XML response back to AJAX request. + * + * @package WordPress + * @since 2.1.0 + */ +class WP_Ajax_Response { + /** + * Store XML responses to send. + * + * @since 2.1.0 + * @var array + * @access private + */ + var $responses = array(); + + /** + * PHP4 Constructor - Passes args to {@link WP_Ajax_Response::add()}. + * + * @since 2.1.0 + * @see WP_Ajax_Response::add() + * + * @param string|array $args Optional. Will be passed to add() method. + * @return WP_Ajax_Response + */ + function WP_Ajax_Response( $args = '' ) { + if ( !empty($args) ) + $this->add($args); + } - foreach ($this->public_query_vars as $wpvar) { - if (isset($this->query_vars[$wpvar]) && '' != $this->query_vars[$wpvar]) { - $this->query_string .= (strlen($this->query_string) < 1) ? '' : '&'; - if ( !is_scalar($this->query_vars[$wpvar]) ) // Discard non-scalars. + /** + * Append to XML response based on given arguments. + * + * The arguments that can be passed in the $args parameter are below. It is + * also possible to pass a WP_Error object in either the 'id' or 'data' + * argument. The parameter isn't actually optional, content should be given + * in order to send the correct response. + * + * 'what' argument is a string that is the XMLRPC response type. + * 'action' argument is a boolean or string that acts like a nonce. + * 'id' argument can be WP_Error or an integer. + * 'old_id' argument is false by default or an integer of the previous ID. + * 'position' argument is an integer or a string with -1 = top, 1 = bottom, + * html ID = after, -html ID = before. + * 'data' argument is a string with the content or message. + * 'supplemental' argument is an array of strings that will be children of + * the supplemental element. + * + * @since 2.1.0 + * + * @param string|array $args Override defaults. + * @return string XML response. + */ + function add( $args = '' ) { + $defaults = array( + 'what' => 'object', 'action' => false, + 'id' => '0', 'old_id' => false, + 'position' => 1, + 'data' => '', 'supplemental' => array() + ); + + $r = wp_parse_args( $args, $defaults ); + extract( $r, EXTR_SKIP ); + $position = preg_replace( '/[^a-z0-9:_-]/i', '', $position ); + + if ( is_wp_error($id) ) { + $data = $id; + $id = 0; + } + + $response = ''; + if ( is_wp_error($data) ) { + foreach ( (array) $data->get_error_codes() as $code ) { + $response .= "get_error_message($code) . "]]>"; + if ( !$error_data = $data->get_error_data($code) ) continue; - $this->query_string .= $wpvar . '=' . rawurlencode($this->query_vars[$wpvar]); - } - } + $class = ''; + if ( is_object($error_data) ) { + $class = ' class="' . get_class($error_data) . '"'; + $error_data = get_object_vars($error_data); + } - foreach ($this->private_query_vars as $wpvar) { - if (isset($GLOBALS[$wpvar]) && '' != $GLOBALS[$wpvar]) { - $this->query_string .= (strlen($this->query_string) < 1) ? '' : '&'; - $this->query_string .= $wpvar . '=' . rawurlencode($GLOBALS[$wpvar]); + $response .= ""; + + if ( is_scalar($error_data) ) { + $response .= ""; + } elseif ( is_array($error_data) ) { + foreach ( $error_data as $k => $v ) + $response .= "<$k>"; + } + + $response .= ""; } + } else { + $response = ""; } - $this->query_string = apply_filters('query_string', $this->query_string); - } - - function register_globals() { - global $wp_query; - // Extract updated query vars back into global namespace. - foreach ($wp_query->query_vars as $key => $value) { - $GLOBALS[$key] = $value; + $s = ''; + if ( is_array($supplemental) ) { + foreach ( $supplemental as $k => $v ) + $s .= "<$k>"; + $s = "$s"; } - $GLOBALS['query_string'] = & $this->query_string; - $GLOBALS['posts'] = & $wp_query->posts; - $GLOBALS['post'] = & $wp_query->post; - $GLOBALS['request'] = & $wp_query->request; + if ( false === $action ) + $action = $_POST['action']; - if ( is_single() || is_page() ) { - $GLOBALS['more'] = 1; - $GLOBALS['single'] = 1; - } + $x = ''; + $x .= ""; // The action attribute in the xml output is formatted like a nonce action + $x .= "<$what id='$id' " . ( false === $old_id ? '' : "old_id='$old_id' " ) . "position='$position'>"; + $x .= $response; + $x .= $s; + $x .= ""; + $x .= ""; + + $this->responses[] = $x; + return $x; } - function init() { - wp_get_current_user(); + /** + * Display XML formatted responses. + * + * Sets the content type header to text/xml. + * + * @since 2.1.0 + */ + function send() { + header('Content-Type: text/xml'); + echo ""; + foreach ( (array) $this->responses as $response ) + echo $response; + echo ''; + die(); } +} - function query_posts() { - $this->build_query_string(); - query_posts($this->query_string); - } +/** + * Helper class to remove the need to use eval to replace $matches[] in query strings. + * + * @since 2.9.0 + */ +class WP_MatchesMapRegex { + /** + * store for matches + * + * @access private + * @var array + */ + var $_matches; - function handle_404() { - global $wp_query; - // Issue a 404 if a permalink request doesn't match any posts. Don't - // issue a 404 if one was already issued, if the request was a search, - // or if the request was a regular query string request rather than a - // permalink request. - if ( (0 == count($wp_query->posts)) && !is_404() && !is_search() && ( $this->did_permalink || (!empty($_SERVER['QUERY_STRING']) && (false === strpos($_SERVER['REQUEST_URI'], '?'))) ) ) { - $wp_query->set_404(); - status_header( 404 ); - nocache_headers(); - } elseif( is_404() != true ) { - status_header( 200 ); - } + /** + * store for mapping result + * + * @access public + * @var string + */ + var $output; + + /** + * subject to perform mapping on (query string containing $matches[] references + * + * @access private + * @var string + */ + var $_subject; + + /** + * regexp pattern to match $matches[] references + * + * @var string + */ + var $_pattern = '(\$matches\[[1-9]+[0-9]*\])'; // magic number + + /** + * constructor + * + * @param string $subject subject if regex + * @param array $matches data to use in map + * @return self + */ + function WP_MatchesMapRegex($subject, $matches) { + $this->_subject = $subject; + $this->_matches = $matches; + $this->output = $this->_map(); } - function main($query_args = '') { - $this->init(); - $this->parse_request($query_args); - $this->send_headers(); - $this->query_posts(); - $this->handle_404(); - $this->register_globals(); + /** + * Substitute substring matches in subject. + * + * static helper function to ease use + * + * @access public + * @param string $subject subject + * @param array $matches data used for subsitution + * @return string + */ + function apply($subject, $matches) { + $oSelf =& new WP_MatchesMapRegex($subject, $matches); + return $oSelf->output; } - function WP() { - // Empty. + /** + * do the actual mapping + * + * @access private + * @return string + */ + function _map() { + $callback = array(&$this, 'callback'); + return preg_replace_callback($this->_pattern, $callback, $this->_subject); } + + /** + * preg_replace_callback hook + * + * @access public + * @param array $matches preg_replace regexp matches + * @return string + */ + function callback($matches) { + $index = intval(substr($matches[0], 9, -1)); + return ( isset( $this->_matches[$index] ) ? urlencode($this->_matches[$index]) : '' ); + } + } ?>