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