]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/classes.php
Wordpress 2.0.11
[autoinstalls/wordpress.git] / wp-includes / classes.php
1 <?php
2
3 class WP_Query {
4         var $query;
5         var $query_vars;
6         var $queried_object;
7         var $queried_object_id;
8         var $request;
9
10         var $posts;
11         var $post_count = 0;
12         var $current_post = -1;
13         var $in_the_loop = false;
14         var $post;
15
16         var $is_single = false;
17         var $is_preview = false;
18         var $is_page = false;
19         var $is_archive = false;
20         var $is_date = false;
21         var $is_year = false;
22         var $is_month = false;
23         var $is_day = false;
24         var $is_time = false;
25         var $is_author = false;
26         var $is_category = false;
27         var $is_search = false;
28         var $is_feed = false;
29         var $is_trackback = false;
30         var $is_home = false;
31         var $is_404 = false;
32         var $is_comments_popup = false;
33         var $is_admin = false;
34         var $is_attachment = false;
35
36         function init_query_flags() {
37                 $this->is_single = false;
38                 $this->is_page = false;
39                 $this->is_archive = false;
40                 $this->is_date = false;
41                 $this->is_year = false;
42                 $this->is_month = false;
43                 $this->is_day = false;
44                 $this->is_time = false;
45                 $this->is_author = false;
46                 $this->is_category = false;
47                 $this->is_search = false;
48                 $this->is_feed = false;
49                 $this->is_trackback = false;
50                 $this->is_home = false;
51                 $this->is_404 = false;
52                 $this->is_paged = false;
53                 $this->is_admin = false;
54                 $this->is_attachment = false;
55         }
56         
57         function init () {
58                 unset($this->posts);
59                 unset($this->query);
60                 unset($this->query_vars);
61                 unset($this->queried_object);
62                 unset($this->queried_object_id);
63                 $this->post_count = 0;
64                 $this->current_post = -1;
65                 $this->in_the_loop = false;
66                 
67                 $this->init_query_flags();
68         }
69
70         // Reparse the query vars.
71         function parse_query_vars() {
72                 $this->parse_query('');
73         }
74
75         // Parse a query string and set query type booleans.
76         function parse_query ($query) {
77                 if ( !empty($query) || !isset($this->query) ) {
78                         $this->init();
79                         parse_str($query, $qv);
80                         $this->query = $query;
81                         $this->query_vars = $qv;
82                 }
83
84                 if ('404' == $qv['error']) {
85                         $this->is_404 = true;
86                         if ( !empty($query) ) {
87                                 do_action('parse_query', array(&$this));
88                         }
89                         return;
90                 }
91
92                 $qv['m'] =  (int) $qv['m'];
93                 $qv['p'] =  (int) $qv['p'];
94
95                 // Compat.  Map subpost to attachment.
96                 if ( '' != $qv['subpost'] )
97                         $qv['attachment'] = $qv['subpost'];
98                 if ( '' != $qv['subpost_id'] )
99                         $qv['attachment_id'] = $qv['subpost_id'];
100                         
101                 if ( ('' != $qv['attachment']) || (int) $qv['attachment_id'] ) {
102                         $this->is_single = true;
103                         $this->is_attachment = true;
104                 } elseif ('' != $qv['name']) {
105                         $this->is_single = true;
106                 } elseif ( $qv['p'] ) {
107                         $this->is_single = true;
108                 } elseif (('' != $qv['hour']) && ('' != $qv['minute']) &&('' != $qv['second']) && ('' != $qv['year']) && ('' != $qv['monthnum']) && ('' != $qv['day'])) {
109                         // If year, month, day, hour, minute, and second are set, a single 
110                         // post is being queried.        
111                         $this->is_single = true;
112                 } elseif ('' != $qv['static'] || '' != $qv['pagename'] || (int) $qv['page_id']) {
113                         $this->is_page = true;
114                         $this->is_single = false;
115                 } elseif (!empty($qv['s'])) {
116                         $this->is_search = true;
117                         switch ($qv['show_post_type']) {
118                         case 'page' :
119                                 $this->is_page = true;
120                                 break;
121                         case 'attachment' :
122                                 $this->is_attachment = true;
123                                 break;
124                         }
125                 } else {
126                 // Look for archive queries.  Dates, categories, authors.
127
128                         if ( (int) $qv['second']) {
129                                 $this->is_time = true;
130                                 $this->is_date = true;
131                         }
132
133                         if ( (int) $qv['minute']) {
134                                 $this->is_time = true;
135                                 $this->is_date = true;
136                         }
137
138                         if ( (int) $qv['hour']) {
139                                 $this->is_time = true;
140                                 $this->is_date = true;
141                         }
142
143                         if ( (int) $qv['day']) {
144                                 if (! $this->is_date) {
145                                         $this->is_day = true;
146                                         $this->is_date = true;
147                                 }
148                         }
149
150                         if ( (int)  $qv['monthnum']) {
151                                 if (! $this->is_date) {
152                                         $this->is_month = true;
153                                         $this->is_date = true;
154                                 }
155                         }
156
157                         if ( (int)  $qv['year']) {
158                                 if (! $this->is_date) {
159                                         $this->is_year = true;
160                                         $this->is_date = true;
161                                 }
162                         }
163
164                         if ( (int)  $qv['m']) {
165                                 $this->is_date = true;
166                                 if (strlen($qv['m']) > 9) {
167                                         $this->is_time = true;
168                                 } else if (strlen($qv['m']) > 7) {
169                                         $this->is_day = true;
170                                 } else if (strlen($qv['m']) > 5) {
171                                         $this->is_month = true;
172                                 } else {
173                                         $this->is_year = true;
174                                 }
175                         }
176
177                         if ('' != $qv['w']) {
178                                 $this->is_date = true;
179                         }
180
181                         if (empty($qv['cat']) || ($qv['cat'] == '0')) {
182                                 $this->is_category = false;
183                         } else {
184                                 if (stristr($qv['cat'],'-')) {
185                                         $this->is_category = false;
186                                 } else {
187                                         $this->is_category = true;
188                                 }
189                         }
190
191                         if ('' != $qv['category_name']) {
192                                 $this->is_category = true;
193                         }
194             
195                         if ((empty($qv['author'])) || ($qv['author'] == '0')) {
196                                 $this->is_author = false;
197                         } else {
198                                 $this->is_author = true;
199                         }
200
201                         if ('' != $qv['author_name']) {
202                                 $this->is_author = true;
203                         }
204
205                         if ( ($this->is_date || $this->is_author || $this->is_category)) {
206                                 $this->is_archive = true;
207                         }
208
209                         if ( 'attachment' == $qv['show_post_type'] ) {
210                                 $this->is_attachment = true;
211                         }
212                 }
213
214                 if ('' != $qv['feed']) {
215                         $this->is_feed = true;
216                 }
217
218                 if ('' != $qv['tb']) {
219                         $this->is_trackback = true;
220                 }
221
222                 if ('' != $qv['paged']) {
223                         $this->is_paged = true;
224                 }
225
226                 if ('' != $qv['comments_popup']) {
227                         $this->is_comments_popup = true;
228                 }
229                 
230                 //if we're previewing inside the write screen
231                 if ('' != $qv['preview']) {
232                         $this->is_preview = true;
233                 }
234
235                 if (strstr($_SERVER['PHP_SELF'], 'wp-admin/')) {
236                         $this->is_admin = true;
237                 }
238
239                 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)) {
240                         $this->is_home = true;
241                 }
242
243                 if ( !empty($query) ) {
244                         do_action('parse_query', array(&$this));
245                 }
246         }
247
248         function set_404() {
249                 $is_feed = $this->is_feed;
250
251                 $this->init_query_flags();
252                 $this->is_404 = true;
253
254                 $this->is_feed = $is_feed;
255         }
256         
257         function get($query_var) {
258                 if (isset($this->query_vars[$query_var])) {
259                         return $this->query_vars[$query_var];
260                 }
261
262                 return '';
263         }
264
265         function set($query_var, $value) {
266                 $this->query_vars[$query_var] = $value;
267         }
268
269         function &get_posts() {
270                 global $wpdb, $pagenow, $user_ID;
271
272                 do_action('pre_get_posts', array(&$this));
273
274                 // Shorthand.
275                 $q = $this->query_vars; 
276
277                 // First let's clear some variables
278                 $whichcat = '';
279                 $whichauthor = '';
280                 $whichpage = '';
281                 $result = '';
282                 $where = '';
283                 $limits = '';
284                 $distinct = '';
285                 $join = '';
286
287                 if ( !isset($q['posts_per_page']) || $q['posts_per_page'] == 0 )
288                         $q['posts_per_page'] = get_settings('posts_per_page');
289                 if ( !isset($q['what_to_show']) )
290                         $q['what_to_show'] = get_settings('what_to_show');
291                 if ( isset($q['showposts']) && $q['showposts'] ) {
292                         $q['showposts'] = (int) $q['showposts'];
293                         $q['posts_per_page'] = $q['showposts'];
294                 }
295                 if ( (isset($q['posts_per_archive_page']) && $q['posts_per_archive_page'] != 0) && ($this->is_archive || $this->is_search) )
296                         $q['posts_per_page'] = $q['posts_per_archive_page'];
297                 if ( !isset($q['nopaging']) ) {
298                         if ($q['posts_per_page'] == -1) {
299                                 $q['nopaging'] = true;
300                         } else {
301                                 $q['nopaging'] = false;
302                         }
303                 }
304                 if ( $this->is_feed ) {
305                         $q['posts_per_page'] = get_settings('posts_per_rss');
306                         $q['what_to_show'] = 'posts';
307                 }
308
309                 if (isset($q['page'])) {
310                         $q['page'] = trim($q['page'], '/');
311                         $q['page'] = (int) $q['page'];
312                         $q['page'] = abs($q['page']);
313                 }
314         
315                 $add_hours = intval(get_settings('gmt_offset'));
316                 $add_minutes = intval(60 * (get_settings('gmt_offset') - $add_hours));
317                 $wp_posts_post_date_field = "post_date"; // "DATE_ADD(post_date, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)";
318
319                 // If a month is specified in the querystring, load that month
320                 if ( (int) $q['m'] ) {
321                         $q['m'] = '' . preg_replace('|[^0-9]|', '', $q['m']);
322                         $where .= ' AND YEAR(post_date)=' . substr($q['m'], 0, 4);
323                         if (strlen($q['m'])>5)
324                                 $where .= ' AND MONTH(post_date)=' . substr($q['m'], 4, 2);
325                         if (strlen($q['m'])>7)
326                                 $where .= ' AND DAYOFMONTH(post_date)=' . substr($q['m'], 6, 2);
327                         if (strlen($q['m'])>9)
328                                 $where .= ' AND HOUR(post_date)=' . substr($q['m'], 8, 2);
329                         if (strlen($q['m'])>11)
330                                 $where .= ' AND MINUTE(post_date)=' . substr($q['m'], 10, 2);
331                         if (strlen($q['m'])>13)
332                                 $where .= ' AND SECOND(post_date)=' . substr($q['m'], 12, 2);
333                 }
334
335                 if ( (int) $q['hour'] ) {
336                         $q['hour'] = '' . intval($q['hour']);
337                         $where .= " AND HOUR(post_date)='" . $q['hour'] . "'";
338                 }
339
340                 if ( (int) $q['minute'] ) {
341                         $q['minute'] = '' . intval($q['minute']);
342                         $where .= " AND MINUTE(post_date)='" . $q['minute'] . "'";
343                 }
344
345                 if ( (int) $q['second'] ) {
346                         $q['second'] = '' . intval($q['second']);
347                         $where .= " AND SECOND(post_date)='" . $q['second'] . "'";
348                 }
349
350                 if ( (int) $q['year'] ) {
351                         $q['year'] = '' . intval($q['year']);
352                         $where .= " AND YEAR(post_date)='" . $q['year'] . "'";
353                 }
354
355                 if ( (int) $q['monthnum'] ) {
356                         $q['monthnum'] = '' . intval($q['monthnum']);
357                         $where .= " AND MONTH(post_date)='" . $q['monthnum'] . "'";
358                 }
359
360                 if ( (int) $q['day'] ) {
361                         $q['day'] = '' . intval($q['day']);
362                         $where .= " AND DAYOFMONTH(post_date)='" . $q['day'] . "'";
363                 }
364
365                 // Compat.  Map subpost to attachment.
366                 if ( '' != $q['subpost'] )
367                         $q['attachment'] = $q['subpost'];
368                 if ( '' != $q['subpost_id'] )
369                         $q['attachment_id'] = $q['subpost_id'];
370
371                 if ('' != $q['name']) {
372                         $q['name'] = sanitize_title($q['name']);
373                         $where .= " AND post_name = '" . $q['name'] . "'";
374                 } else if ('' != $q['pagename']) {
375                         $q['pagename'] = str_replace('%2F', '/', urlencode(urldecode($q['pagename'])));
376                         $page_paths = '/' . trim($q['pagename'], '/');
377                         $q['pagename'] = sanitize_title(basename($page_paths));
378                         $q['name'] = $q['pagename'];
379                         $page_paths = explode('/', $page_paths);
380                         foreach($page_paths as $pathdir)
381                                 $page_path .= ($pathdir!=''?'/':'') . sanitize_title($pathdir);
382                                 
383                         $all_page_ids = get_all_page_ids();
384                         $reqpage = 0;
385                         if (is_array($all_page_ids)) { foreach ( $all_page_ids as $page_id ) {
386                                 $page = get_page($page_id);
387                                 if ( $page->fullpath == $page_path ) {
388                                         $reqpage = $page_id;
389                                         break;
390                                 }
391                         } }
392                         
393                         $where .= " AND (ID = '$reqpage')";
394                 } elseif ('' != $q['attachment']) {
395                         $q['attachment'] = str_replace('%2F', '/', urlencode(urldecode($q['attachment'])));
396                         $attach_paths = '/' . trim($q['attachment'], '/');
397                         $q['attachment'] = sanitize_title(basename($attach_paths));
398                         $q['name'] = $q['attachment'];
399                         $where .= " AND post_name = '" . $q['attachment'] . "'";
400                 }
401
402                 if ( (int) $q['w'] ) {
403                         $q['w'] = ''.intval($q['w']);
404                         $where .= " AND WEEK(post_date, 1)='" . $q['w'] . "'";
405                 }
406
407                 if ( intval($q['comments_popup']) )
408                         $q['p'] = intval($q['comments_popup']);
409
410                 // If a attachment is requested by number, let it supercede any post number.
411                 if ( ($q['attachment_id'] != '') && (intval($q['attachment_id']) != 0) )
412                         $q['p'] = (int) $q['attachment_id'];
413
414                 // If a post number is specified, load that post
415                 if (($q['p'] != '') && intval($q['p']) != 0) {
416                         $q['p'] =  (int) $q['p'];
417                         $where = ' AND ID = ' . $q['p'];
418                 }
419
420                 if (($q['page_id'] != '') && (intval($q['page_id']) != 0)) {
421                         $q['page_id'] = intval($q['page_id']);
422                         $q['p'] = $q['page_id'];
423                         $where = ' AND ID = '.$q['page_id'];
424                 }
425
426                 // If a search pattern is specified, load the posts that match
427                 if (!empty($q['s'])) {
428                         $q['s'] = addslashes_gpc($q['s']);
429                         $search = ' AND (';
430                         $q['s'] = preg_replace('/, +/', ' ', $q['s']);
431                         $q['s'] = str_replace(',', ' ', $q['s']);
432                         $q['s'] = str_replace('"', ' ', $q['s']);
433                         $q['s'] = trim($q['s']);
434                         if ($q['exact']) {
435                                 $n = '';
436                         } else {
437                                 $n = '%';
438                         }
439                         if (!$q['sentence']) {
440                                 $s_array = explode(' ',$q['s']);
441                                 $q['search_terms'] = $s_array;
442                                 $search .= '((post_title LIKE \''.$n.$s_array[0].$n.'\') OR (post_content LIKE \''.$n.$s_array[0].$n.'\'))';
443                                 for ( $i = 1; $i < count($s_array); $i = $i + 1) {
444                                         $search .= ' AND ((post_title LIKE \''.$n.$s_array[$i].$n.'\') OR (post_content LIKE \''.$n.$s_array[$i].$n.'\'))';
445                                 }
446                                 $search .= ' OR (post_title LIKE \''.$n.$q['s'].$n.'\') OR (post_content LIKE \''.$n.$q['s'].$n.'\')';
447                                 $search .= ')';
448                         } else {
449                                 $search = ' AND ((post_title LIKE \''.$n.$q['s'].$n.'\') OR (post_content LIKE \''.$n.$q['s'].$n.'\'))';
450                         }
451                 }
452
453                 // Category stuff
454
455                 if ((empty($q['cat'])) || ($q['cat'] == '0') || 
456                                 // Bypass cat checks if fetching specific posts
457                                 ( $this->is_single || $this->is_page )) {
458                         $whichcat='';
459                 } else {
460                         $q['cat'] = ''.urldecode($q['cat']).'';
461                         $q['cat'] = addslashes_gpc($q['cat']);
462                         if (stristr($q['cat'],'-')) {
463                                 // Note: if we have a negative, we ignore all the positives. It must
464                                 // always mean 'everything /except/ this one'. We should be able to do
465                                 // multiple negatives but we don't :-(
466                                 $eq = '!=';
467                                 $andor = 'AND';
468                                 $q['cat'] = explode('-',$q['cat']);
469                                 $q['cat'] = intval($q['cat'][1]);
470                         } else {
471                                 $eq = '=';
472                                 $andor = 'OR';
473                         }
474                         $join = " LEFT JOIN $wpdb->post2cat ON ($wpdb->posts.ID = $wpdb->post2cat.post_id) ";
475                         $cat_array = preg_split('/[,\s]+/', $q['cat']);
476                         $whichcat .= ' AND (category_id '.$eq.' '.intval($cat_array[0]);
477                         $whichcat .= get_category_children($cat_array[0], ' '.$andor.' category_id '.$eq.' ');
478                         for ($i = 1; $i < (count($cat_array)); $i = $i + 1) {
479                                 $whichcat .= ' '.$andor.' category_id '.$eq.' '.intval($cat_array[$i]);
480                                 $whichcat .= get_category_children($cat_array[$i], ' '.$andor.' category_id '.$eq.' ');
481                         }
482                         $whichcat .= ')';
483                         if ($eq == '!=') {
484                                 $q['cat'] = '-'.$q['cat']; // Put back the knowledge that we are excluding a category.
485                         }
486                 }
487
488                 // Category stuff for nice URIs
489
490                 global $cache_categories;
491                 if ('' != $q['category_name']) {
492                         $cat_paths = '/' . trim(urldecode($q['category_name']), '/');
493                         $q['category_name'] = sanitize_title(basename($cat_paths));
494                         $cat_paths = explode('/', $cat_paths);
495                         foreach($cat_paths as $pathdir)
496                                 $cat_path .= ($pathdir!=''?'/':'') . sanitize_title($pathdir);
497
498                         $all_cat_ids = get_all_category_ids();
499                         $q['cat'] = 0; $partial_match = 0;
500                         foreach ( $all_cat_ids as $cat_id ) {
501                                 $cat = get_category($cat_id);
502                                 if ( $cat->fullpath == $cat_path ) {
503                                         $q['cat'] = $cat_id;
504                                         break;
505                                 } elseif ( $cat->category_nicename == $q['category_name'] ) {
506                                         $partial_match = $cat_id;
507                                 }
508                         }
509                         
510                         //if we don't match the entire hierarchy fallback on just matching the nicename
511                         if (!$q['cat'] && $partial_match) {
512                                 $q['cat'] = $partial_match;
513                         }                       
514
515                         $tables = ", $wpdb->post2cat, $wpdb->categories";
516                         $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) ";
517                         $whichcat = " AND (category_id = '" . $q['cat'] . "'";
518                         $whichcat .= get_category_children($q['cat'], " OR category_id = ");
519                         $whichcat .= ")";
520                 }
521
522                 // Author/user stuff
523
524                 if ((empty($q['author'])) || ($q['author'] == '0')) {
525                         $whichauthor='';
526                 } else {
527                         $q['author'] = ''.urldecode($q['author']).'';
528                         $q['author'] = addslashes_gpc($q['author']);
529                         if (stristr($q['author'], '-')) {
530                                 $eq = '!=';
531                                 $andor = 'AND';
532                                 $q['author'] = explode('-', $q['author']);
533                                 $q['author'] = ''.intval($q['author'][1]);
534                         } else {
535                                 $eq = '=';
536                                 $andor = 'OR';
537                         }
538                         $author_array = preg_split('/[,\s]+/', $q['author']);
539                         $whichauthor .= ' AND (post_author '.$eq.' '.intval($author_array[0]);
540                         for ($i = 1; $i < (count($author_array)); $i = $i + 1) {
541                                 $whichauthor .= ' '.$andor.' post_author '.$eq.' '.intval($author_array[$i]);
542                         }
543                         $whichauthor .= ')';
544                 }
545
546                 // Author stuff for nice URIs
547
548                 if ('' != $q['author_name']) {
549                         if (stristr($q['author_name'],'/')) {
550                                 $q['author_name'] = explode('/',$q['author_name']);
551                                 if ($q['author_name'][count($q['author_name'])-1]) {
552                                         $q['author_name'] = $q['author_name'][count($q['author_name'])-1];#no trailing slash
553                                 } else {
554                                         $q['author_name'] = $q['author_name'][count($q['author_name'])-2];#there was a trailling slash
555                                 }
556                         }
557                         $q['author_name'] = sanitize_title($q['author_name']);
558                         $q['author'] = $wpdb->get_var("SELECT ID FROM $wpdb->users WHERE user_nicename='".$q['author_name']."'");
559                         $whichauthor .= ' AND (post_author = '.intval($q['author']).')';
560                 }
561                 
562                 $where .= $search.$whichcat.$whichauthor;
563
564                 if ((empty($q['order'])) || ((strtoupper($q['order']) != 'ASC') && (strtoupper($q['order']) != 'DESC'))) {
565                         $q['order']='DESC';
566                 }
567
568                 // Order by
569                 if (empty($q['orderby'])) {
570                         $q['orderby']='date '.$q['order'];
571                 } else {
572                         // Used to filter values
573                         $allowed_keys = array('author', 'date', 'category', 'title', 'modified');
574                         $q['orderby'] = urldecode($q['orderby']);
575                         $q['orderby'] = addslashes_gpc($q['orderby']);
576                         $orderby_array = explode(' ',$q['orderby']);
577                         if (!in_array($orderby_array[0],$allowed_keys)) {
578                                 $orderby_array[0] = 'date';
579                         }
580                         $q['orderby'] = $orderby_array[0].' '.$q['order'];
581                         if (count($orderby_array)>1) {
582                                 for ($i = 1; $i < (count($orderby_array)); $i = $i + 1) {
583                                         // Only allow certain values for safety
584                                         if (in_array($orderby_array[$i],$allowed_keys)) {
585                                                 $q['orderby'] .= ',post_'.$orderby_array[$i].' '.$q['order'];
586                                         }
587                                 }
588                         }
589                 }
590
591                 $now = gmdate('Y-m-d H:i:59');
592                 
593                 //only select past-dated posts, except if a logged in user is viewing a single: then, if they
594                 //can edit the post, we let them through
595                 if ($pagenow != 'post.php' && $pagenow != 'edit.php' && !($this->is_single && $user_ID)) {
596                         $where .= " AND post_date_gmt <= '$now'";
597                         $distinct = 'DISTINCT';
598                 }
599
600                 if ( $this->is_attachment ) {
601                         $where .= " AND (post_status = 'attachment')";
602                 } elseif ($this->is_page) {
603                         $where .= " AND (post_status = 'static')";
604                 } elseif ($this->is_single) {
605                         $where .= " AND (post_status != 'static')";
606                 } else {
607                         $where .= " AND (post_status = 'publish'";
608
609                         if (isset($user_ID) && ('' != intval($user_ID)))
610                                 $where .= " OR post_author = $user_ID AND post_status != 'draft' AND post_status != 'static')";
611                         else
612                                 $where .= ')';                          
613                 }
614
615                 if (! $this->is_attachment )
616                         $where .= " AND post_status != 'attachment'";
617
618                 // Apply filters on where and join prior to paging so that any
619                 // manipulations to them are reflected in the paging by day queries.
620                 $where = apply_filters('posts_where', $where);
621                 $join = apply_filters('posts_join', $join);
622
623                 // Paging
624                 if (empty($q['nopaging']) && ! $this->is_single && ! $this->is_page) {
625                         $page = abs(intval($q['paged']));
626                         if (empty($page)) {
627                                 $page = 1;
628                         }
629
630                         if (($q['what_to_show'] == 'posts')) {
631                                 $q['offset'] = abs(intval($q['offset']));
632                                 if ( empty($q['offset']) ) {
633                                         $pgstrt = '';
634                                         $pgstrt = (intval($page) -1) * $q['posts_per_page'] . ', ';
635                                         $limits = 'LIMIT '.$pgstrt.$q['posts_per_page'];
636                                 } else { // we're ignoring $page and using 'offset'
637                                         $pgstrt = $q['offset'] . ', ';
638                                         $limits = 'LIMIT ' . $pgstrt . $q['posts_per_page'];
639                                 }
640                         } elseif ($q['what_to_show'] == 'days') {
641                                 $startrow = $q['posts_per_page'] * (intval($page)-1);
642                                 $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");
643                                 $endrow = $startrow + $q['posts_per_page'] - 1;
644                                 $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");
645
646                                 if ($page > 1) {
647                                         $where .= " AND post_date >= '$end_date' AND post_date <= '$start_date'";
648                                 } else {
649                                         $where .= " AND post_date >= '$end_date'";
650                                 }
651                         }
652                 }
653
654                 // Apply post-paging filters on where and join.  Only plugins that
655                 // manipulate paging queries should use these hooks.
656                 $where = apply_filters('posts_where_paged', $where);
657                 $groupby = " $wpdb->posts.ID ";
658                 $groupby = apply_filters('posts_groupby', $groupby);
659                 $join = apply_filters('posts_join_paged', $join);
660                 $orderby = "post_" . $q['orderby'];
661                 $orderby = apply_filters('posts_orderby', $orderby); 
662                 $request = " SELECT $distinct * FROM $wpdb->posts $join WHERE 1=1" . $where . " GROUP BY " . $groupby . " ORDER BY " . $orderby . " $limits";
663                 $this->request = apply_filters('posts_request', $request);
664
665                 $this->posts = $wpdb->get_results($this->request);
666
667                 // Check post status to determine if post should be displayed.
668                 if ( !empty($this->posts) && $this->is_single ) {
669                         $status = get_post_status($this->posts[0]);
670                         if ( ('publish' != $status) && ('static' != $status) ) {
671                                 if ( ! (isset($user_ID) && ('' != intval($user_ID))) ) {
672                                         // User must be logged in to view unpublished posts.
673                                         $this->posts = array();
674                                 } else {
675                                         if ('draft' == $status) {
676                                                 // User must have edit permissions on the draft to preview.
677                                                 if (! current_user_can('edit_post', $this->posts[0]->ID)) {
678                                                         $this->posts = array();
679                                                 } else {
680                                                         $this->is_preview = true;
681                                                         $this->posts[0]->post_date = current_time('mysql');
682                                                 }
683                                         } else {
684                                                 if (! current_user_can('read_post', $this->posts[0]->ID))
685                                                         $this->posts = array();
686                                         }
687                                 }
688                         } else {
689                                 if (mysql2date('U', $this->posts[0]->post_date_gmt) > mysql2date('U', $now)) { //it's future dated
690                                         $this->is_preview = true;
691                                         if (!current_user_can('edit_post', $this->posts[0]->ID)) {
692                                                 $this->posts = array ( );
693                                         }
694                                 }
695                         }
696                 }
697
698                 update_post_caches($this->posts);
699
700                 $this->posts = apply_filters('the_posts', $this->posts);
701                 $this->post_count = count($this->posts);
702                 if ($this->post_count > 0) {
703                         $this->post = $this->posts[0];
704                 }
705                 
706                 // Save any changes made to the query vars.
707                 $this->query_vars = $q;
708                 return $this->posts;
709         }
710
711         function next_post() {
712         
713                 $this->current_post++;
714
715                 $this->post = $this->posts[$this->current_post];
716                 return $this->post;
717         }
718
719         function the_post() {
720                 global $post;
721                 $this->in_the_loop = true;
722                 $post = $this->next_post();
723                 setup_postdata($post);
724
725                 if ( $this->current_post == 0 ) // loop has just started
726                         do_action('loop_start');
727         }
728
729         function have_posts() {
730                 if ($this->current_post + 1 < $this->post_count) {
731                         return true;
732                 } elseif ($this->current_post + 1 == $this->post_count) {
733                         do_action('loop_end');
734                         // Do some cleaning up after the loop
735                         $this->rewind_posts();
736                 }
737
738                 $this->in_the_loop = false;
739                 return false;
740         }
741
742         function rewind_posts() {
743                 $this->current_post = -1;
744                 if ($this->post_count > 0) {
745                         $this->post = $this->posts[0];
746                 }
747         }
748     
749         function &query($query) {
750                 $this->parse_query($query);
751                 return $this->get_posts();
752         }
753
754         function get_queried_object() {
755                 if (isset($this->queried_object)) {
756                         return $this->queried_object;
757                 }
758
759                 $this->queried_object = NULL;
760                 $this->queried_object_id = 0;
761
762                 if ($this->is_category) {
763                         $cat = $this->get('cat');
764                         $category = &get_category($cat);
765                         $this->queried_object = &$category;
766                         $this->queried_object_id = $cat;
767                 } else if ($this->is_single) {
768                         $this->queried_object = $this->post;
769                         $this->queried_object_id = $this->post->ID;
770                 } else if ($this->is_page) {
771                         $this->queried_object = $this->post;
772                         $this->queried_object_id = $this->post->ID;
773                 } else if ($this->is_author) {
774                         $author_id = $this->get('author');
775                         $author = get_userdata($author_id);
776                         $this->queried_object = $author;
777                         $this->queried_object_id = $author_id;
778                 }
779
780                 return $this->queried_object;
781         }
782
783         function get_queried_object_id() {
784                 $this->get_queried_object();
785
786                 if (isset($this->queried_object_id)) {
787                         return $this->queried_object_id;
788                 }
789
790                 return 0;
791         }
792
793         function WP_Query ($query = '') {
794                 if (! empty($query)) {
795                         $this->query($query);
796                 }
797         }
798 }
799
800 class retrospam_mgr {
801         var $spam_words;
802         var $comments_list;
803         var $found_comments;
804
805         function retrospam_mgr() {
806                 global $wpdb;
807
808                 $list = explode("\n", get_settings('moderation_keys') );
809                 $list = array_unique( $list );
810                 $this->spam_words = $list;
811
812                 $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");
813         }       // End of class constructor
814
815         function move_spam( $id_list ) {
816                 global $wpdb;
817                 $cnt = 0;
818                 $id_list = explode( ',', $id_list );
819
820                 foreach ( $id_list as $comment ) {
821                         if ( $wpdb->query("update $wpdb->comments set comment_approved = '0' where comment_ID = '$comment'") ) {
822                                 $cnt++;
823                         }
824                 }
825                 echo "<div class='updated'><p> ";
826                 printf(__('%d comment(s) moved to the moderation queue.'), $cnt);
827                 echo "</p></div>\n";
828         }       // End function move_spam
829
830         function find_spam() {
831                 $in_queue = 0;
832
833                 foreach( $this->comment_list as $comment ) {
834                         if( $comment->approved == 1 ) {
835                                 foreach( $this->spam_words as $word ) {
836                                         $word = trim($word);
837                                         if ( empty( $word ) )
838                                                 continue;
839                                         $fulltext = strtolower($comment->email.' '.$comment->url.' '.$comment->ip.' '.$comment->text);
840                                         if( false !== strpos( $fulltext, strtolower($word) ) ) {
841                                                 $this->found_comments[] = $comment->ID;
842                                                 break;
843                                         }
844                                 }
845                         } else {
846                                 $in_queue++;
847                         }
848                 }
849                 return array( 'found' => $this->found_comments, 'in_queue' => $in_queue );
850         }       // End function find_spam
851
852         function display_edit_form( $counters ) {
853                 $numfound = count($counters[found]);
854                 $numqueue = $counters[in_queue];
855
856                 $body = '<p>' . sprintf(__('Suspected spam comments: %s'), "<strong>$numfound</strong>") . '</p>';
857
858                 if ( count($counters[found]) > 0 ) {
859                         $id_list = implode( ',', $counters[found] );
860                         $body .= '<p><a href="options-discussion.php?action=retrospam&amp;move=true&amp;ids='.$id_list.'">'. __('Move suspect comments to moderation queue &raquo;') . '</a></p>';
861
862                 }
863                 $head = '<div class="wrap"><h2>' . __('Check Comments Results:') . '</h2>';
864
865                 $foot .= '<p><a href="options-discussion.php">' . __('&laquo; Return to Discussion Options page.') . '</a></p></div>';
866                 
867                 return $head . $body . $foot;
868         }       // End function display_edit_form
869
870 }
871
872 class WP_Rewrite {
873         var $permalink_structure;
874         var $category_base;
875         var $category_structure;
876         var $author_base = 'author';
877         var $author_structure;
878         var $date_structure;
879         var $page_structure;
880         var $search_base = 'search';
881         var $search_structure;
882         var $comments_base = 'comments';
883         var $feed_base = 'feed';
884         var $comments_feed_structure;
885         var $feed_structure;
886         var $front;
887         var $root = '';
888         var $index = 'index.php';
889         var $matches = '';
890         var $rules;
891         var $use_verbose_rules = false;
892         var $rewritecode = 
893                 array(
894                                         '%year%',
895                                         '%monthnum%',
896                                         '%day%',
897                                         '%hour%',
898                                         '%minute%',
899                                         '%second%',
900                                         '%postname%',
901                                         '%post_id%',
902                                         '%category%',
903                                         '%author%',
904                                         '%pagename%',
905                                         '%search%'
906                                         );
907
908         var $rewritereplace = 
909                 array(
910                                         '([0-9]{4})',
911                                         '([0-9]{1,2})',
912                                         '([0-9]{1,2})',
913                                         '([0-9]{1,2})',
914                                         '([0-9]{1,2})',
915                                         '([0-9]{1,2})',
916                                         '([^/]+)',
917                                         '([0-9]+)',
918                                         '(.+?)',
919                                         '([^/]+)',
920                                         '([^/]+)',
921                                         '(.+)'
922                                         );
923
924         var $queryreplace = 
925                 array (
926                                         'year=',
927                                         'monthnum=',
928                                         'day=',
929                                         'hour=',
930                                         'minute=',
931                                         'second=',
932                                         'name=',
933                                         'p=',
934                                         'category_name=',
935                                         'author_name=',
936                                         'pagename=',
937                                         's='
938                                         );
939
940         var $feeds = array ('feed', 'rdf', 'rss', 'rss2', 'atom');
941
942         function using_permalinks() {
943                 if (empty($this->permalink_structure))
944                         return false;
945                 else
946                         return true;
947         }                                       
948
949         function using_index_permalinks() {
950                 if (empty($this->permalink_structure)) {
951                         return false;
952                 }
953
954                 // If the index is not in the permalink, we're using mod_rewrite.
955                 if (preg_match('#^/*' . $this->index . '#', $this->permalink_structure)) {
956                         return true;
957                 }
958     
959                 return false;
960         }
961
962         function using_mod_rewrite_permalinks() {
963                 if ( $this->using_permalinks() && ! $this->using_index_permalinks())
964                         return true;
965                 else
966                         return false;
967         }                                       
968
969         function preg_index($number) {
970                 $match_prefix = '$';
971                 $match_suffix = '';
972
973                 if (! empty($this->matches)) {
974                         $match_prefix = '$' . $this->matches . '['; 
975                         $match_suffix = ']';
976                 }        
977
978                 return "$match_prefix$number$match_suffix";        
979         }
980
981         function page_rewrite_rules() {
982                 $uris = get_settings('page_uris');
983                 $attachment_uris = get_settings('page_attachment_uris');
984
985                 $rewrite_rules = array();
986                 $page_structure = $this->get_page_permastruct();
987                 if( is_array( $attachment_uris ) ) {
988                         foreach ($attachment_uris as $uri => $pagename) {
989                                 $this->add_rewrite_tag('%pagename%', "($uri)", 'attachment=');
990                                 $rewrite_rules = array_merge($rewrite_rules, $this->generate_rewrite_rules($page_structure));
991                         }
992                 }
993                 if( is_array( $uris ) ) {
994                         foreach ($uris as $uri => $pagename) {
995                                 $this->add_rewrite_tag('%pagename%', "($uri)", 'pagename=');
996                                 $rewrite_rules = array_merge($rewrite_rules, $this->generate_rewrite_rules($page_structure));
997                         }
998                 }
999
1000                 return $rewrite_rules;
1001         }
1002
1003         function get_date_permastruct() {
1004                 if (isset($this->date_structure)) {
1005                         return $this->date_structure;
1006                 }
1007
1008                 if (empty($this->permalink_structure)) {
1009                         $this->date_structure = '';
1010                         return false;
1011                 }
1012                 
1013                 // The date permalink must have year, month, and day separated by slashes.
1014                 $endians = array('%year%/%monthnum%/%day%', '%day%/%monthnum%/%year%', '%monthnum%/%day%/%year%');
1015
1016                 $this->date_structure = '';
1017                 $date_endian = '';
1018
1019                 foreach ($endians as $endian) {
1020                         if (false !== strpos($this->permalink_structure, $endian)) {
1021                                 $date_endian= $endian;
1022                                 break;
1023                         }
1024                 } 
1025
1026                 if ( empty($date_endian) )
1027                         $date_endian = '%year%/%monthnum%/%day%';
1028
1029                 // Do not allow the date tags and %post_id% to overlap in the permalink
1030                 // structure. If they do, move the date tags to $front/date/.  
1031                 $front = $this->front;
1032                 preg_match_all('/%.+?%/', $this->permalink_structure, $tokens);
1033                 $tok_index = 1;
1034                 foreach ($tokens[0] as $token) {
1035                         if ( ($token == '%post_id%') && ($tok_index <= 3) ) {
1036                                 $front = $front . 'date/';
1037                                 break;
1038                         }
1039                         $tok_index++;
1040                 }
1041
1042                 $this->date_structure = $front . $date_endian;
1043
1044                 return $this->date_structure;
1045         }
1046
1047         function get_year_permastruct() {
1048                 $structure = $this->get_date_permastruct($this->permalink_structure);
1049
1050                 if (empty($structure)) {
1051                         return false;
1052                 }
1053
1054                 $structure = str_replace('%monthnum%', '', $structure);
1055                 $structure = str_replace('%day%', '', $structure);
1056
1057                 $structure = preg_replace('#/+#', '/', $structure);
1058
1059                 return $structure;
1060         }
1061
1062         function get_month_permastruct() {
1063                 $structure = $this->get_date_permastruct($this->permalink_structure);
1064
1065                 if (empty($structure)) {
1066                         return false;
1067                 }
1068
1069                 $structure = str_replace('%day%', '', $structure);
1070
1071                 $structure = preg_replace('#/+#', '/', $structure);
1072
1073                 return $structure;
1074         }
1075
1076         function get_day_permastruct() {
1077                 return $this->get_date_permastruct($this->permalink_structure);
1078         }
1079
1080         function get_category_permastruct() {
1081                 if (isset($this->category_structure)) {
1082                         return $this->category_structure;
1083                 }
1084
1085                 if (empty($this->permalink_structure)) {
1086                         $this->category_structure = '';
1087                         return false;
1088                 }
1089
1090                 if (empty($this->category_base))
1091                         $this->category_structure = $this->front . 'category/';
1092                 else
1093                         $this->category_structure = $this->category_base . '/';
1094
1095                 $this->category_structure .= '%category%';
1096                 
1097                 return $this->category_structure;
1098         }
1099
1100         function get_author_permastruct() {
1101                 if (isset($this->author_structure)) {
1102                         return $this->author_structure;
1103                 }
1104
1105                 if (empty($this->permalink_structure)) {
1106                         $this->author_structure = '';
1107                         return false;
1108                 }
1109
1110                 $this->author_structure = $this->front . $this->author_base . '/%author%';
1111
1112                 return $this->author_structure;
1113         }
1114
1115         function get_search_permastruct() {
1116                 if (isset($this->search_structure)) {
1117                         return $this->search_structure;
1118                 }
1119
1120                 if (empty($this->permalink_structure)) {
1121                         $this->search_structure = '';
1122                         return false;
1123                 }
1124
1125                 $this->search_structure = $this->root . $this->search_base . '/%search%';
1126
1127                 return $this->search_structure;
1128         }
1129
1130         function get_page_permastruct() {
1131                 if (isset($this->page_structure)) {
1132                         return $this->page_structure;
1133                 }
1134
1135                 if (empty($this->permalink_structure)) {
1136                         $this->page_structure = '';
1137                         return false;
1138                 }
1139
1140                 $this->page_structure = $this->root . '%pagename%';
1141
1142                 return $this->page_structure;
1143         }
1144
1145         function get_feed_permastruct() {
1146                 if (isset($this->feed_structure)) {
1147                         return $this->feed_structure;
1148                 }
1149
1150                 if (empty($this->permalink_structure)) {
1151                         $this->feed_structure = '';
1152                         return false;
1153                 }
1154
1155                 $this->feed_structure = $this->root . $this->feed_base . '/%feed%';
1156
1157                 return $this->feed_structure;
1158         }
1159
1160         function get_comment_feed_permastruct() {
1161                 if (isset($this->comment_feed_structure)) {
1162                         return $this->comment_feed_structure;
1163                 }
1164
1165                 if (empty($this->permalink_structure)) {
1166                         $this->comment_feed_structure = '';
1167                         return false;
1168                 }
1169
1170                 $this->comment_feed_structure = $this->root . $this->comments_base . '/' . $this->feed_base . '/%feed%';
1171
1172                 return $this->comment_feed_structure;
1173         }
1174
1175         function add_rewrite_tag($tag, $pattern, $query) {
1176                 // If the tag already exists, replace the existing pattern and query for
1177                 // that tag, otherwise add the new tag, pattern, and query to the end of
1178                 // the arrays.
1179                 $position = array_search($tag, $this->rewritecode);             
1180                 if (FALSE !== $position && NULL !== $position) {
1181                         $this->rewritereplace[$position] = $pattern;
1182                         $this->queryreplace[$position] = $query;                        
1183                 } else {
1184                         $this->rewritecode[] = $tag;
1185                         $this->rewritereplace[] = $pattern;
1186                         $this->queryreplace[] = $query;
1187                 }
1188         }
1189
1190         function generate_rewrite_rules($permalink_structure, $paged = true, $feed = true, $forcomments = false, $walk_dirs = true) {
1191                 $feedregex2 = '';
1192                 foreach ($this->feeds as $feed_name) {
1193                         $feedregex2 .= $feed_name . '|';
1194                 }
1195                 $feedregex2 = '(' . trim($feedregex2, '|') .  ')/?$';
1196                 $feedregex = $this->feed_base  . '/' . $feedregex2;
1197
1198                 $trackbackregex = 'trackback/?$';
1199                 $pageregex = 'page/?([0-9]{1,})/?$';
1200                 
1201                 $front = substr($permalink_structure, 0, strpos($permalink_structure, '%'));
1202                 preg_match_all('/%.+?%/', $permalink_structure, $tokens);
1203
1204                 $num_tokens = count($tokens[0]);
1205
1206                 $index = $this->index;
1207                 $feedindex = $index;
1208                 $trackbackindex = $index;
1209                 for ($i = 0; $i < $num_tokens; ++$i) {
1210                         if (0 < $i) {
1211                                 $queries[$i] = $queries[$i - 1] . '&';
1212                         }
1213              
1214                         $query_token = str_replace($this->rewritecode, $this->queryreplace, $tokens[0][$i]) . $this->preg_index($i+1);
1215                         $queries[$i] .= $query_token;
1216                 }
1217
1218                 $structure = $permalink_structure;
1219                 if ($front != '/') {
1220                         $structure = str_replace($front, '', $structure);
1221                 }
1222                 $structure = trim($structure, '/');
1223                 if ($walk_dirs) {
1224                         $dirs = explode('/', $structure);
1225                 } else {
1226                         $dirs[] = $structure;
1227                 }
1228                 $num_dirs = count($dirs);
1229
1230                 $front = preg_replace('|^/+|', '', $front);
1231
1232                 $post_rewrite = array();
1233                 $struct = $front;
1234                 for ($j = 0; $j < $num_dirs; ++$j) {
1235                         $struct .= $dirs[$j] . '/';
1236                         $struct = ltrim($struct, '/');
1237                         $match = str_replace($this->rewritecode, $this->rewritereplace, $struct);
1238                         $num_toks = preg_match_all('/%.+?%/', $struct, $toks);
1239                         $query = $queries[$num_toks - 1];
1240
1241                         $pagematch = $match . $pageregex;
1242                         $pagequery = $index . '?' . $query . '&paged=' . $this->preg_index($num_toks + 1);
1243
1244                         $feedmatch = $match . $feedregex;
1245                         $feedquery = $feedindex . '?' . $query . '&feed=' . $this->preg_index($num_toks + 1);
1246
1247                         $feedmatch2 = $match . $feedregex2;
1248                         $feedquery2 = $feedindex . '?' . $query . '&feed=' . $this->preg_index($num_toks + 1);
1249
1250                         if ($forcomments) {
1251                                 $feedquery .= '&withcomments=1';
1252                                 $feedquery2 .= '&withcomments=1';
1253                         }
1254
1255                         $rewrite = array();
1256                         if ($feed) 
1257                                 $rewrite = array($feedmatch => $feedquery, $feedmatch2 => $feedquery2);
1258                         if ($paged)
1259                                 $rewrite = array_merge($rewrite, array($pagematch => $pagequery));
1260
1261                         if ($num_toks) {
1262                                 $post = false;
1263                                 $page = false;
1264                                 if (strstr($struct, '%postname%') || strstr($struct, '%post_id%')
1265                                                 || strstr($struct, '%pagename%')
1266                                                 || (strstr($struct, '%year%') &&  strstr($struct, '%monthnum%') && strstr($struct, '%day%') && strstr($struct, '%hour%') && strstr($struct, '%minute') && strstr($struct, '%second%'))) {
1267                                         $post = true;
1268                                         if  ( strstr($struct, '%pagename%') )
1269                                                 $page = true;
1270                                         $trackbackmatch = $match . $trackbackregex;
1271                                         $trackbackquery = $trackbackindex . '?' . $query . '&tb=1';
1272                                         $match = rtrim($match, '/');
1273                                         $submatchbase = str_replace(array('(',')'),'',$match);
1274                                         $sub1 = $submatchbase . '/([^/]+)/';
1275                                         $sub1tb = $sub1 . $trackbackregex;
1276                                         $sub1feed = $sub1 . $feedregex;
1277                                         $sub1feed2 = $sub1 . $feedregex2;
1278                                         $sub1 .= '?$';
1279                                         $sub2 = $submatchbase . '/attachment/([^/]+)/';
1280                                         $sub2tb = $sub2 . $trackbackregex;
1281                                         $sub2feed = $sub2 . $feedregex;
1282                                         $sub2feed2 = $sub2 . $feedregex2;
1283                                         $sub2 .= '?$';
1284                                         $subquery = $index . '?attachment=' . $this->preg_index(1);
1285                                         $subtbquery = $subquery . '&tb=1';
1286                                         $subfeedquery = $subquery . '&feed=' . $this->preg_index(2);
1287                                         $match = $match . '(/[0-9]+)?/?$';
1288                                         $query = $index . '?' . $query . '&page=' . $this->preg_index($num_toks + 1);
1289                                 } else {
1290                                         $match .= '?$';
1291                                         $query = $index . '?' . $query;
1292                                 }
1293                                         
1294                                 $rewrite = array_merge($rewrite, array($match => $query));
1295
1296                                 if ($post) {
1297                                         $rewrite = array_merge(array($trackbackmatch => $trackbackquery), $rewrite);
1298                                         if ( ! $page )
1299                                                 $rewrite = array_merge($rewrite, array($sub1 => $subquery, $sub1tb => $subtbquery, $sub1feed => $subfeedquery, $sub1feed2 => $subfeedquery));
1300                                         $rewrite = array_merge($rewrite, array($sub2 => $subquery, $sub2tb => $subtbquery, $sub2feed => $subfeedquery, $sub2feed2 => $subfeedquery));
1301                                 }
1302                         }
1303                         $post_rewrite = array_merge($rewrite, $post_rewrite);
1304                 }
1305                 return $post_rewrite;
1306         }
1307
1308         function generate_rewrite_rule($permalink_structure, $walk_dirs = false) {
1309                 return $this->generate_rewrite_rules($permalink_structure, false, false, false, $walk_dirs);
1310         }
1311
1312         /* rewrite_rules
1313          * Construct rewrite matches and queries from permalink structure.
1314          * Returns an associate array of matches and queries.
1315          */
1316         function rewrite_rules() {
1317                 $rewrite = array();
1318
1319                 if (empty($this->permalink_structure)) {
1320                         return $rewrite;
1321                 }
1322                 //Default Feed rules - These are require to allow for the direct access files to work with permalink structure starting with %category%
1323                 $default_feeds = array( 'wp-atom.php$'  =>      $this->index .'?feed=atom',
1324                                                                 'wp-rdf.php$'   =>      $this->index .'?feed=rdf',
1325                                                                 'wp-rss.php$'   =>      $this->index .'?feed=rss',
1326                                                                 'wp-rss2.php$'  =>      $this->index .'?feed=rss2',
1327                                                                 'wp-feed.php$'  =>      $this->index .'?feed=feed',
1328                                                                 'wp-commentsrss2.php$'  =>      $this->index . '?feed=rss2&withcomments=1');
1329
1330
1331                 // Post
1332                 $post_rewrite = $this->generate_rewrite_rules($this->permalink_structure);
1333                 $post_rewrite = apply_filters('post_rewrite_rules', $post_rewrite);
1334
1335                 // Date
1336                 $date_rewrite = $this->generate_rewrite_rules($this->get_date_permastruct());
1337                 $date_rewrite = apply_filters('date_rewrite_rules', $date_rewrite);
1338                 
1339                 // Root
1340                 $root_rewrite = $this->generate_rewrite_rules($this->root . '/');
1341                 $root_rewrite = apply_filters('root_rewrite_rules', $root_rewrite);
1342
1343                 // Comments
1344                 $comments_rewrite = $this->generate_rewrite_rules($this->root . $this->comments_base, true, true, true, false);
1345                 $comments_rewrite = apply_filters('comments_rewrite_rules', $comments_rewrite);
1346
1347                 // Search
1348                 $search_structure = $this->get_search_permastruct();
1349                 $search_rewrite = $this->generate_rewrite_rules($search_structure);
1350                 $search_rewrite = apply_filters('search_rewrite_rules', $search_rewrite);
1351
1352                 // Categories
1353                 $category_rewrite = $this->generate_rewrite_rules($this->get_category_permastruct());
1354                 $category_rewrite = apply_filters('category_rewrite_rules', $category_rewrite);
1355
1356                 // Authors
1357                 $author_rewrite = $this->generate_rewrite_rules($this->get_author_permastruct());
1358                 $author_rewrite = apply_filters('author_rewrite_rules', $author_rewrite);
1359
1360                 // Pages
1361                 $page_rewrite = $this->page_rewrite_rules();
1362                 $page_rewrite = apply_filters('page_rewrite_rules', $page_rewrite);
1363
1364                 // Put them together.
1365                 $this->rules = array_merge($default_feeds, $page_rewrite, $root_rewrite, $comments_rewrite, $search_rewrite, $category_rewrite, $author_rewrite, $date_rewrite, $post_rewrite);
1366
1367                 do_action('generate_rewrite_rules', array(&$this));
1368                 $this->rules = apply_filters('rewrite_rules_array', $this->rules);
1369
1370                 return $this->rules;
1371         }
1372
1373         function wp_rewrite_rules() {
1374                 $this->rules = get_option('rewrite_rules');
1375                 if ( empty($this->rules) ) {
1376                         $this->matches = 'matches';
1377                         $this->rewrite_rules();
1378                         update_option('rewrite_rules', $this->rules);
1379                 }
1380
1381                 return $this->rules;
1382         }
1383
1384         function mod_rewrite_rules() {
1385                 if ( ! $this->using_permalinks()) {
1386                         return '';
1387                 }
1388
1389                 $site_root = parse_url(get_settings('siteurl'));
1390                 $site_root = trailingslashit($site_root['path']);
1391
1392                 $home_root = parse_url(get_settings('home'));
1393                 $home_root = trailingslashit($home_root['path']);
1394     
1395                 $rules = "<IfModule mod_rewrite.c>\n";
1396                 $rules .= "RewriteEngine On\n";
1397                 $rules .= "RewriteBase $home_root\n";
1398
1399                 if ($this->use_verbose_rules) {
1400                         $this->matches = '';
1401                         $rewrite = $this->rewrite_rules();
1402                         $num_rules = count($rewrite);
1403                         $rules .= "RewriteCond %{REQUEST_FILENAME} -f [OR]\n" .
1404                                 "RewriteCond %{REQUEST_FILENAME} -d\n" .
1405                                 "RewriteRule ^.*$ - [S=$num_rules]\n";
1406                 
1407                         foreach ($rewrite as $match => $query) {
1408                                 // Apache 1.3 does not support the reluctant (non-greedy) modifier.
1409                                 $match = str_replace('.+?', '.+', $match);
1410
1411                                 // If the match is unanchored and greedy, prepend rewrite conditions
1412                                 // to avoid infinite redirects and eclipsing of real files.
1413                                 if ($match == '(.+)/?$' || $match == '([^/]+)/?$' ) {
1414                                         //nada.
1415                                 }
1416                         
1417                                 if (strstr($query, $this->index)) {
1418                                         $rules .= 'RewriteRule ^' . $match . ' ' . $home_root . $query . " [QSA,L]\n";
1419                                 } else {
1420                                         $rules .= 'RewriteRule ^' . $match . ' ' . $site_root . $query . " [QSA,L]\n";
1421                                 }
1422                         }
1423                 } else {
1424                         $rules .= "RewriteCond %{REQUEST_FILENAME} !-f\n" .
1425                                 "RewriteCond %{REQUEST_FILENAME} !-d\n" .
1426                                 "RewriteRule . {$home_root}{$this->index} [L]\n";
1427                 }
1428
1429                 $rules .= "</IfModule>\n";
1430
1431                 $rules = apply_filters('mod_rewrite_rules', $rules);
1432                 $rules = apply_filters('rewrite_rules', $rules);  // Deprecated
1433
1434                 return $rules;
1435         }
1436
1437         function flush_rules() {
1438                 generate_page_rewrite_rules();
1439                 delete_option('rewrite_rules');
1440                 $this->wp_rewrite_rules();
1441                 if ( function_exists('save_mod_rewrite_rules') )
1442                         save_mod_rewrite_rules();
1443         }
1444
1445         function init() {
1446                 $this->permalink_structure = get_settings('permalink_structure');
1447                 $this->front = substr($this->permalink_structure, 0, strpos($this->permalink_structure, '%'));          
1448                 $this->root = '';
1449                 if ($this->using_index_permalinks()) {
1450                         $this->root = $this->index . '/';
1451                 }
1452                 $this->category_base = get_settings('category_base');
1453                 unset($this->category_structure);
1454                 unset($this->author_structure);
1455                 unset($this->date_structure);
1456                 unset($this->page_structure);
1457                 unset($this->search_structure);
1458                 unset($this->feed_structure);
1459                 unset($this->comment_feed_structure);
1460         }
1461
1462         function set_permalink_structure($permalink_structure) {
1463                 if ($permalink_structure != $this->permalink_structure) {
1464                         update_option('permalink_structure', $permalink_structure);
1465                         $this->init();
1466                 }
1467         }
1468
1469         function set_category_base($category_base) {
1470                 if ($category_base != $this->category_base) {
1471                         update_option('category_base', $category_base);
1472                         $this->init();
1473                 }
1474         }
1475
1476         function WP_Rewrite() {
1477                 $this->init();
1478         }
1479 }
1480
1481 class WP {
1482         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');
1483
1484         var $private_query_vars = array('posts_per_page', 'posts_per_archive_page', 'what_to_show', 'showposts', 'nopaging', 'show_post_type');
1485
1486         var $query_vars;
1487         var $query_string;
1488         var $request;
1489         var $matched_rule;
1490         var $matched_query;
1491         var $did_permalink = false;
1492
1493         function parse_request($extra_query_vars = '') {
1494                 global $wp_rewrite;
1495
1496                 $this->query_vars = array();
1497
1498                 if (! empty($extra_query_vars))
1499                         parse_str($extra_query_vars, $extra_query_vars);
1500                 else
1501                         $extra_query_vars = array();
1502
1503                 // Process PATH_INFO, REQUEST_URI, and 404 for permalinks.
1504
1505                 // Fetch the rewrite rules.
1506                 $rewrite = $wp_rewrite->wp_rewrite_rules();
1507
1508                 if (! empty($rewrite)) {
1509                         // If we match a rewrite rule, this will be cleared.
1510                         $error = '404';
1511                         $this->did_permalink = true;
1512
1513                         $pathinfo = $_SERVER['PATH_INFO'];
1514                         $pathinfo_array = explode('?', $pathinfo);
1515                         $pathinfo = str_replace("%", "%25", $pathinfo_array[0]);
1516                         $req_uri = $_SERVER['REQUEST_URI'];
1517                         $req_uri_array = explode('?', $req_uri);
1518                         $req_uri = $req_uri_array[0];
1519                         $self = $_SERVER['PHP_SELF'];
1520                         $home_path = parse_url(get_settings('home'));
1521                         $home_path = $home_path['path'];
1522                         $home_path = trim($home_path, '/');
1523
1524                         // Trim path info from the end and the leading home path from the
1525                         // front.  For path info requests, this leaves us with the requesting
1526                         // filename, if any.  For 404 requests, this leaves us with the
1527                         // requested permalink. 
1528                         $req_uri = str_replace($pathinfo, '', $req_uri);
1529                         $req_uri = trim($req_uri, '/');
1530                         $req_uri = preg_replace("|^$home_path|", '', $req_uri);
1531                         $req_uri = trim($req_uri, '/');
1532                         $pathinfo = trim($pathinfo, '/');
1533                         $pathinfo = preg_replace("|^$home_path|", '', $pathinfo);
1534                         $pathinfo = trim($pathinfo, '/');
1535                         $self = trim($self, '/');
1536                         $self = preg_replace("|^$home_path|", '', $self);
1537                         $self = str_replace($home_path, '', $self);
1538                         $self = trim($self, '/');
1539
1540                         // The requested permalink is in $pathinfo for path info requests and
1541                         //  $req_uri for other requests.
1542                         if ( ! empty($pathinfo) && !preg_match('|^.*' . $wp_rewrite->index . '$|', $pathinfo) ) {
1543                                 $request = $pathinfo;
1544                         } else {
1545                                 // If the request uri is the index, blank it out so that we don't try to match it against a rule.
1546                                 if ( $req_uri == $wp_rewrite->index )
1547                                         $req_uri = '';
1548                                 $request = $req_uri;
1549                         }
1550
1551                         $this->request = $request;
1552
1553                         // Look for matches.
1554                         $request_match = $request;
1555                         foreach ($rewrite as $match => $query) {
1556                                 // If the requesting file is the anchor of the match, prepend it
1557                                 // to the path info.
1558                                 if ((! empty($req_uri)) && (strpos($match, $req_uri) === 0) && ($req_uri != $request)) {
1559                                         $request_match = $req_uri . '/' . $request;
1560                                 }
1561
1562                                 if (preg_match("!^$match!", $request_match, $matches) ||
1563                                         preg_match("!^$match!", urldecode($request_match), $matches)) {
1564                                         // Got a match.
1565                                         $this->matched_rule = $match;
1566
1567                                         // Trim the query of everything up to the '?'.
1568                                         $query = preg_replace("!^.+\?!", '', $query);
1569
1570                                         // Substitute the substring matches into the query.
1571                                         eval("\$query = \"$query\";");
1572                                         $this->matched_query = $query;
1573
1574                                         // Parse the query.
1575                                         parse_str($query, $query_vars);
1576
1577                                         // If we're processing a 404 request, clear the error var
1578                                         // since we found something.
1579                                         if (isset($_GET['error']))
1580                                                 unset($_GET['error']);
1581
1582                                         if (isset($error))
1583                                                 unset($error);
1584
1585                                         break;
1586                                 }
1587                         }
1588
1589                         // If req_uri is empty or if it is a request for ourself, unset error.
1590                         if ( empty($request) || $req_uri == $self || strstr($_SERVER['PHP_SELF'], 'wp-admin/') ) {
1591                                 if (isset($_GET['error']))
1592                                         unset($_GET['error']);
1593
1594                                 if (isset($error))
1595                                         unset($error);
1596                                         
1597                                 if ( isset($query_vars) && strstr($_SERVER['PHP_SELF'], 'wp-admin/') )
1598                                         unset($query_vars);
1599                                         
1600                                 $this->did_permalink = false;
1601                         }
1602                 }
1603
1604                 $this->public_query_vars = apply_filters('query_vars', $this->public_query_vars);
1605
1606                 for ($i=0; $i<count($this->public_query_vars); $i += 1) {
1607                         $wpvar = $this->public_query_vars[$i];
1608                         if (isset($extra_query_vars[$wpvar]))
1609                                 $this->query_vars[$wpvar] = $extra_query_vars[$wpvar];
1610                         elseif (isset($GLOBALS[$wpvar]))
1611                                 $this->query_vars[$wpvar] = $GLOBALS[$wpvar];
1612                         elseif (!empty($_POST[$wpvar]))
1613                                 $this->query_vars[$wpvar] = $_POST[$wpvar];
1614                         elseif (!empty($_GET[$wpvar]))
1615                                 $this->query_vars[$wpvar] = $_GET[$wpvar];
1616                         elseif (!empty($query_vars[$wpvar]))
1617                                 $this->query_vars[$wpvar] = $query_vars[$wpvar];
1618                         else
1619                                 $this->query_vars[$wpvar] = '';
1620
1621                         if ( !empty( $this->query_vars[$wpvar] ) )
1622                                 $this->query_vars[$wpvar] = (string) $this->query_vars[$wpvar];
1623                 }
1624
1625                 if ( isset($error) )
1626                         $this->query_vars['error'] = $error;
1627         }
1628
1629         function send_headers() {
1630                 @header('X-Pingback: '. get_bloginfo('pingback_url'));
1631                 if ( is_user_logged_in() )
1632                         nocache_headers();
1633                 if ( !empty($this->query_vars['error']) && '404' == $this->query_vars['error'] ) {
1634                         status_header( 404 );
1635                         if ( !is_user_logged_in() )
1636                                 nocache_headers();
1637                         @header('Content-type: ' . get_option('html_type') . '; charset=' . get_option('blog_charset'));
1638                 } else if ( empty($this->query_vars['feed']) ) {
1639                         @header('Content-type: ' . get_option('html_type') . '; charset=' . get_option('blog_charset'));
1640                 } else {
1641                         // We're showing a feed, so WP is indeed the only thing that last changed
1642                         if ( $this->query_vars['withcomments'] )
1643                                 $wp_last_modified = mysql2date('D, d M Y H:i:s', get_lastcommentmodified('GMT'), 0).' GMT';
1644                         else 
1645                                 $wp_last_modified = mysql2date('D, d M Y H:i:s', get_lastpostmodified('GMT'), 0).' GMT';
1646                         $wp_etag = '"' . md5($wp_last_modified) . '"';
1647                         @header("Last-Modified: $wp_last_modified");
1648                         @header("ETag: $wp_etag");
1649
1650                         // Support for Conditional GET
1651                         if (isset($_SERVER['HTTP_IF_NONE_MATCH']))
1652                                 $client_etag = stripslashes(stripslashes($_SERVER['HTTP_IF_NONE_MATCH']));
1653                         else $client_etag = false;
1654
1655                         $client_last_modified = trim( $_SERVER['HTTP_IF_MODIFIED_SINCE']);
1656                         // If string is empty, return 0. If not, attempt to parse into a timestamp
1657                         $client_modified_timestamp = $client_last_modified ? strtotime($client_last_modified) : 0;
1658
1659                         // Make a timestamp for our most recent modification... 
1660                         $wp_modified_timestamp = strtotime($wp_last_modified);
1661
1662                         if ( ($client_last_modified && $client_etag) ?
1663                                          (($client_modified_timestamp >= $wp_modified_timestamp) && ($client_etag == $wp_etag)) :
1664                                          (($client_modified_timestamp >= $wp_modified_timestamp) || ($client_etag == $wp_etag)) ) {
1665                                 status_header( 304 );
1666                                 exit;
1667                         }
1668                 }
1669         }
1670
1671         function build_query_string() {
1672                 $this->query_string = '';
1673
1674                 foreach ($this->public_query_vars as $wpvar) {
1675                         if (isset($this->query_vars[$wpvar]) && '' != $this->query_vars[$wpvar]) {
1676                                 $this->query_string .= (strlen($this->query_string) < 1) ? '' : '&';
1677                                 if ( !is_scalar($this->query_vars[$wpvar]) ) // Discard non-scalars.
1678                                         continue;
1679                                 $this->query_string .= $wpvar . '=' . rawurlencode($this->query_vars[$wpvar]);
1680                         }
1681                 }
1682
1683                 foreach ($this->private_query_vars as $wpvar) {
1684                         if (isset($GLOBALS[$wpvar]) && '' != $GLOBALS[$wpvar]) {
1685                                 $this->query_string .= (strlen($this->query_string) < 1) ? '' : '&';
1686                                 $this->query_string .= $wpvar . '=' . rawurlencode($GLOBALS[$wpvar]);
1687                         }
1688                 }
1689
1690                 $this->query_string = apply_filters('query_string', $this->query_string);
1691         }
1692
1693         function register_globals() {
1694                 global $wp_query;
1695                 // Extract updated query vars back into global namespace.
1696                 foreach ($wp_query->query_vars as $key => $value) {
1697                         $GLOBALS[$key] = $value;
1698                 }
1699
1700                 $GLOBALS['query_string'] = & $this->query_string;
1701                 $GLOBALS['posts'] = & $wp_query->posts;
1702                 $GLOBALS['post'] = & $wp_query->post;
1703                 $GLOBALS['request'] = & $wp_query->request;
1704
1705                 if ( is_single() || is_page() ) {
1706                         $GLOBALS['more'] = 1;
1707                         $GLOBALS['single'] = 1;
1708                 }
1709         }
1710
1711         function init() {
1712                 wp_get_current_user();
1713         }
1714
1715         function query_posts() {
1716                 $this->build_query_string();
1717                 query_posts($this->query_string);
1718         }
1719
1720         function handle_404() {
1721                 global $wp_query;
1722                 // Issue a 404 if a permalink request doesn't match any posts.  Don't
1723                 // issue a 404 if one was already issued, if the request was a search,
1724                 // or if the request was a regular query string request rather than a
1725                 // permalink request.
1726                 if ( (0 == count($wp_query->posts)) && !is_404() && !is_search() && ( $this->did_permalink || (!empty($_SERVER['QUERY_STRING']) && (false === strpos($_SERVER['REQUEST_URI'], '?'))) ) ) {
1727                         $wp_query->set_404();
1728                         status_header( 404 );
1729                         nocache_headers();
1730                 }       elseif( is_404() != true ) {
1731                         status_header( 200 );
1732                 }
1733         }
1734
1735         function main($query_args = '') {
1736                 $this->init();
1737                 $this->parse_request($query_args);
1738                 $this->send_headers();
1739                 $this->query_posts();
1740                 $this->handle_404();
1741                 $this->register_globals();
1742         }
1743
1744         function WP() {
1745                 // Empty.
1746         }
1747 }
1748
1749 ?>