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