]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/query.php
Wordpress 2.5.1
[autoinstalls/wordpress.git] / wp-includes / query.php
1 <?php
2
3 /*
4  * The Big Query.
5  */
6
7 function get_query_var($var) {
8         global $wp_query;
9
10         return $wp_query->get($var);
11 }
12
13 function set_query_var($var, $value) {
14         global $wp_query;
15
16         return $wp_query->set($var, $value);
17 }
18
19 function &query_posts($query) {
20         unset($GLOBALS['wp_query']);
21         $GLOBALS['wp_query'] =& new WP_Query();
22         return $GLOBALS['wp_query']->query($query);
23 }
24
25 function wp_reset_query() {
26         unset($GLOBALS['wp_query']);
27         $GLOBALS['wp_query'] =& $GLOBALS['wp_the_query'];
28         global $wp_query;
29         if ( !empty($wp_query->post) ) {
30                 $GLOBALS['post'] = $wp_query->post;
31                 setup_postdata($wp_query->post);
32         }
33 }
34
35 /*
36  * Query type checks.
37  */
38
39 function is_admin () {
40         if ( defined('WP_ADMIN') )
41                 return WP_ADMIN;
42         return false;
43 }
44
45 function is_archive () {
46         global $wp_query;
47
48         return $wp_query->is_archive;
49 }
50
51 function is_attachment () {
52         global $wp_query;
53
54         return $wp_query->is_attachment;
55 }
56
57 function is_author ($author = '') {
58         global $wp_query;
59
60         if ( !$wp_query->is_author )
61                 return false;
62
63         if ( empty($author) )
64                 return true;
65
66         $author_obj = $wp_query->get_queried_object();
67
68         $author = (array) $author;
69
70         if ( in_array( $author_obj->ID, $author ) )
71                 return true;
72         elseif ( in_array( $author_obj->nickname, $author ) )
73                 return true;
74         elseif ( in_array( $author_obj->user_nicename, $author ) )
75                 return true;
76
77         return false;
78 }
79
80 function is_category ($category = '') {
81         global $wp_query;
82
83         if ( !$wp_query->is_category )
84                 return false;
85
86         if ( empty($category) )
87                 return true;
88
89         $cat_obj = $wp_query->get_queried_object();
90
91         $category = (array) $category;
92
93         if ( in_array( $cat_obj->term_id, $category ) )
94                 return true;
95         elseif ( in_array( $cat_obj->name, $category ) )
96                 return true;
97         elseif ( in_array( $cat_obj->slug, $category ) )
98                 return true;
99
100         return false;
101 }
102
103 function is_tag( $slug = '' ) {
104         global $wp_query;
105
106         if ( !$wp_query->is_tag )
107                 return false;
108
109         if ( empty( $slug ) )
110                 return true;
111
112         $tag_obj = $wp_query->get_queried_object();
113
114         $slug = (array) $slug;
115
116         if ( in_array( $tag_obj->slug, $slug ) )
117                 return true;
118
119         return false;
120 }
121
122 function is_tax( $slug = '' ) {
123         global $wp_query;
124         
125         if ( !$wp_query->is_tax )
126                 return false;
127
128         if ( empty($slug) )
129                 return true;
130
131         $term = $wp_query->get_queried_object();
132
133         $slug = (array) $slug;
134
135         if ( in_array( $term->slug, $slug ) )
136                 return true;
137
138         return false;
139 }
140
141 function is_comments_popup () {
142         global $wp_query;
143
144         return $wp_query->is_comments_popup;
145 }
146
147 function is_date () {
148         global $wp_query;
149
150         return $wp_query->is_date;
151 }
152
153 function is_day () {
154         global $wp_query;
155
156         return $wp_query->is_day;
157 }
158
159 function is_feed () {
160         global $wp_query;
161
162         return $wp_query->is_feed;
163 }
164
165 /**
166  * is_front_page() - Is it the front of the site, whether blog view or a WP Page?
167  *
168  * @since 2.5
169  * @uses is_home
170  * @uses get_option
171  *
172  * @return bool True if front of site
173  */
174 function is_front_page () {
175         // most likely case
176         if ( 'posts' == get_option('show_on_front') && is_home() )
177                 return true;
178         elseif ( 'page' == get_option('show_on_front') && get_option('page_on_front') && is_page(get_option('page_on_front')) )
179                 return true;
180         else
181                 return false;
182 }
183
184 /**
185  * is_home() - Is it the blog view homepage?
186  *
187  * @since 2.1
188  * @global object $wp_query
189  *
190  * @return bool True if blog view homepage
191  */
192 function is_home () {
193         global $wp_query;
194
195         return $wp_query->is_home;
196 }
197
198 function is_month () {
199         global $wp_query;
200
201         return $wp_query->is_month;
202 }
203
204 function is_page ($page = '') {
205         global $wp_query;
206
207         if ( !$wp_query->is_page )
208                 return false;
209
210         if ( empty($page) )
211                 return true;
212
213         $page_obj = $wp_query->get_queried_object();
214
215         $page = (array) $page;
216
217     if ( in_array( $page_obj->ID, $page ) )
218                 return true;
219         elseif ( in_array( $page_obj->post_title, $page ) )
220                 return true;
221         else if ( in_array( $page_obj->post_name, $page ) )
222                 return true;
223
224         return false;
225 }
226
227 function is_paged () {
228         global $wp_query;
229
230         return $wp_query->is_paged;
231 }
232
233 function is_plugin_page() {
234         global $plugin_page;
235
236         if ( isset($plugin_page) )
237                 return true;
238
239         return false;
240 }
241
242 function is_preview() {
243         global $wp_query;
244
245         return $wp_query->is_preview;
246 }
247
248 function is_robots() {
249         global $wp_query;
250
251         return $wp_query->is_robots;
252 }
253
254 function is_search () {
255         global $wp_query;
256
257         return $wp_query->is_search;
258 }
259
260 function is_single ($post = '') {
261         global $wp_query;
262
263         if ( !$wp_query->is_single )
264                 return false;
265
266         if ( empty( $post) )
267                 return true;
268
269         $post_obj = $wp_query->get_queried_object();
270
271         $post = (array) $post;
272
273         if ( in_array( $post_obj->ID, $post ) )
274                 return true;
275         elseif ( in_array( $post_obj->post_title, $post ) )
276                 return true;
277         elseif ( in_array( $post_obj->post_name, $post ) )
278                 return true;
279
280         return false;
281 }
282
283 function is_singular() {
284         global $wp_query;
285
286         return $wp_query->is_singular;
287 }
288
289 function is_time () {
290         global $wp_query;
291
292         return $wp_query->is_time;
293 }
294
295 function is_trackback () {
296         global $wp_query;
297
298         return $wp_query->is_trackback;
299 }
300
301 function is_year () {
302         global $wp_query;
303
304         return $wp_query->is_year;
305 }
306
307 function is_404 () {
308         global $wp_query;
309
310         return $wp_query->is_404;
311 }
312
313 /*
314  * The Loop.  Post loop control.
315  */
316
317 function have_posts() {
318         global $wp_query;
319
320         return $wp_query->have_posts();
321 }
322
323 function in_the_loop() {
324         global $wp_query;
325
326         return $wp_query->in_the_loop;
327 }
328
329 function rewind_posts() {
330         global $wp_query;
331
332         return $wp_query->rewind_posts();
333 }
334
335 function the_post() {
336         global $wp_query;
337
338         $wp_query->the_post();
339 }
340
341 /*
342  * Comments loop.
343  */
344
345 function have_comments() {
346         global $wp_query;
347         return $wp_query->have_comments();
348 }
349
350 function the_comment() {
351         global $wp_query;
352         return $wp_query->the_comment();
353 }
354
355 /*
356  * WP_Query
357  */
358
359 class WP_Query {
360         var $query;
361         var $query_vars = array();
362         var $queried_object;
363         var $queried_object_id;
364         var $request;
365
366         var $posts;
367         var $post_count = 0;
368         var $current_post = -1;
369         var $in_the_loop = false;
370         var $post;
371
372         var $comments;
373         var $comment_count = 0;
374         var $current_comment = -1;
375         var $comment;
376
377         var $found_posts = 0;
378         var $max_num_pages = 0;
379
380         var $is_single = false;
381         var $is_preview = false;
382         var $is_page = false;
383         var $is_archive = false;
384         var $is_date = false;
385         var $is_year = false;
386         var $is_month = false;
387         var $is_day = false;
388         var $is_time = false;
389         var $is_author = false;
390         var $is_category = false;
391         var $is_tag = false;
392         var $is_tax = false;
393         var $is_search = false;
394         var $is_feed = false;
395         var $is_comment_feed = false;
396         var $is_trackback = false;
397         var $is_home = false;
398         var $is_404 = false;
399         var $is_comments_popup = false;
400         var $is_admin = false;
401         var $is_attachment = false;
402         var $is_singular = false;
403         var $is_robots = false;
404         var $is_posts_page = false;
405
406         function init_query_flags() {
407                 $this->is_single = false;
408                 $this->is_page = false;
409                 $this->is_archive = false;
410                 $this->is_date = false;
411                 $this->is_year = false;
412                 $this->is_month = false;
413                 $this->is_day = false;
414                 $this->is_time = false;
415                 $this->is_author = false;
416                 $this->is_category = false;
417                 $this->is_tag = false;
418                 $this->is_tax = false;
419                 $this->is_search = false;
420                 $this->is_feed = false;
421                 $this->is_comment_feed = false;
422                 $this->is_trackback = false;
423                 $this->is_home = false;
424                 $this->is_404 = false;
425                 $this->is_paged = false;
426                 $this->is_admin = false;
427                 $this->is_attachment = false;
428                 $this->is_singular = false;
429                 $this->is_robots = false;
430                 $this->is_posts_page = false;
431         }
432
433         function init () {
434                 unset($this->posts);
435                 unset($this->query);
436                 $this->query_vars = array();
437                 unset($this->queried_object);
438                 unset($this->queried_object_id);
439                 $this->post_count = 0;
440                 $this->current_post = -1;
441                 $this->in_the_loop = false;
442
443                 $this->init_query_flags();
444         }
445
446         // Reparse the query vars.
447         function parse_query_vars() {
448                 $this->parse_query('');
449         }
450
451         function fill_query_vars($array) {
452                 $keys = array(
453                         'error'
454                         , 'm'
455                         , 'p'
456                         , 'subpost'
457                         , 'subpost_id'
458                         , 'attachment'
459                         , 'attachment_id'
460                         , 'name'
461                         , 'hour'
462                         , 'static'
463                         , 'pagename'
464                         , 'page_id'
465                         , 'second'
466                         , 'minute'
467                         , 'hour'
468                         , 'day'
469                         , 'monthnum'
470                         , 'year'
471                         , 'w'
472                         , 'category_name'
473                         , 'tag'
474                         , 'tag_id'
475                         , 'author_name'
476                         , 'feed'
477                         , 'tb'
478                         , 'paged'
479                         , 'comments_popup'
480                         , 'preview'
481                 );
482
483                 foreach ($keys as $key) {
484                         if ( !isset($array[$key]))
485                                 $array[$key] = '';
486                 }
487
488                 $array_keys = array('category__in', 'category__not_in', 'category__and',
489                         'tag__in', 'tag__not_in', 'tag__and', 'tag_slug__in', 'tag_slug__and');
490
491                 foreach ( $array_keys as $key ) {
492                         if ( !isset($array[$key]))
493                                 $array[$key] = array();
494                 }
495                 return $array;
496         }
497
498         // Parse a query string and set query type booleans.
499         function parse_query ($query) {
500                 if ( !empty($query) || !isset($this->query) ) {
501                         $this->init();
502                         if ( is_array($query) )
503                                 $this->query_vars = $query;
504                         else
505                                 parse_str($query, $this->query_vars);
506                         $this->query = $query;
507                 }
508
509                 $this->query_vars = $this->fill_query_vars($this->query_vars);
510                 $qv = &$this->query_vars;
511
512                 if ( ! empty($qv['robots']) )
513                         $this->is_robots = true;
514
515                 $qv['p'] =  (int) $qv['p'];
516                 $qv['page_id'] =  (int) $qv['page_id'];
517                 $qv['year'] = (int) $qv['year'];
518                 $qv['monthnum'] = (int) $qv['monthnum'];
519                 $qv['day'] = (int) $qv['day'];
520                 $qv['w'] = (int) $qv['w'];
521                 $qv['m'] =  (int) $qv['m'];
522                 $qv['cat'] = preg_replace( '|[^0-9,-]|', '', $qv['cat'] ); // comma separated list of positive or negative integers
523                 if ( '' !== $qv['hour'] ) $qv['hour'] = (int) $qv['hour'];
524                 if ( '' !== $qv['minute'] ) $qv['minute'] = (int) $qv['minute'];
525                 if ( '' !== $qv['second'] ) $qv['second'] = (int) $qv['second'];
526
527                 // Compat.  Map subpost to attachment.
528                 if ( '' != $qv['subpost'] )
529                         $qv['attachment'] = $qv['subpost'];
530                 if ( '' != $qv['subpost_id'] )
531                         $qv['attachment_id'] = $qv['subpost_id'];
532
533                 $qv['attachment_id'] = (int) $qv['attachment_id'];
534
535                 if ( ('' != $qv['attachment']) || !empty($qv['attachment_id']) ) {
536                         $this->is_single = true;
537                         $this->is_attachment = true;
538                 } elseif ( '' != $qv['name'] ) {
539                         $this->is_single = true;
540                 } elseif ( $qv['p'] ) {
541                         $this->is_single = true;
542                 } elseif ( ('' !== $qv['hour']) && ('' !== $qv['minute']) &&('' !== $qv['second']) && ('' != $qv['year']) && ('' != $qv['monthnum']) && ('' != $qv['day']) ) {
543                         // If year, month, day, hour, minute, and second are set, a single
544                         // post is being queried.
545                         $this->is_single = true;
546                 } elseif ( '' != $qv['static'] || '' != $qv['pagename'] || !empty($qv['page_id']) ) {
547                         $this->is_page = true;
548                         $this->is_single = false;
549                 } elseif ( !empty($qv['s']) ) {
550                         $this->is_search = true;
551                 } else {
552                 // Look for archive queries.  Dates, categories, authors.
553
554                         if ( '' !== $qv['second'] ) {
555                                 $this->is_time = true;
556                                 $this->is_date = true;
557                         }
558
559                         if ( '' !== $qv['minute'] ) {
560                                 $this->is_time = true;
561                                 $this->is_date = true;
562                         }
563
564                         if ( '' !== $qv['hour'] ) {
565                                 $this->is_time = true;
566                                 $this->is_date = true;
567                         }
568
569                         if ( $qv['day'] ) {
570                                 if (! $this->is_date) {
571                                         $this->is_day = true;
572                                         $this->is_date = true;
573                                 }
574                         }
575
576                         if ( $qv['monthnum'] ) {
577                                 if (! $this->is_date) {
578                                         $this->is_month = true;
579                                         $this->is_date = true;
580                                 }
581                         }
582
583                         if ( $qv['year'] ) {
584                                 if (! $this->is_date) {
585                                         $this->is_year = true;
586                                         $this->is_date = true;
587                                 }
588                         }
589
590                         if ( $qv['m'] ) {
591                                 $this->is_date = true;
592                                 if (strlen($qv['m']) > 9) {
593                                         $this->is_time = true;
594                                 } else if (strlen($qv['m']) > 7) {
595                                         $this->is_day = true;
596                                 } else if (strlen($qv['m']) > 5) {
597                                         $this->is_month = true;
598                                 } else {
599                                         $this->is_year = true;
600                                 }
601                         }
602
603                         if ('' != $qv['w']) {
604                                 $this->is_date = true;
605                         }
606
607                         if ( empty($qv['cat']) || ($qv['cat'] == '0') ) {
608                                 $this->is_category = false;
609                         } else {
610                                 if (strpos($qv['cat'], '-') !== false) {
611                                         $this->is_category = false;
612                                 } else {
613                                         $this->is_category = true;
614                                 }
615                         }
616
617                         if ( '' != $qv['category_name'] ) {
618                                 $this->is_category = true;
619                         }
620
621                         if ( !is_array($qv['category__in']) || empty($qv['category__in']) ) {
622                                 $qv['category__in'] = array();
623                         } else {
624                                 $qv['category__in'] = array_map('intval', $qv['category__in']);
625                                 $this->is_category = true;
626                         }
627
628                         if ( !is_array($qv['category__not_in']) || empty($qv['category__not_in']) ) {
629                                 $qv['category__not_in'] = array();
630                         } else {
631                                 $qv['category__not_in'] = array_map('intval', $qv['category__not_in']);
632                         }
633
634                         if ( !is_array($qv['category__and']) || empty($qv['category__and']) ) {
635                                 $qv['category__and'] = array();
636                         } else {
637                                 $qv['category__and'] = array_map('intval', $qv['category__and']);
638                                 $this->is_category = true;
639                         }
640
641                         if (  '' != $qv['tag'] )
642                                 $this->is_tag = true;
643
644                         $qv['tag_id'] = (int) $qv['tag_id'];
645                         if (  !empty($qv['tag_id']) )
646                                 $this->is_tag = true;
647
648                         if ( !is_array($qv['tag__in']) || empty($qv['tag__in']) ) {
649                                 $qv['tag__in'] = array();
650                         } else {
651                                 $qv['tag__in'] = array_map('intval', $qv['tag__in']);
652                                 $this->is_tag = true;
653                         }
654
655                         if ( !is_array($qv['tag__not_in']) || empty($qv['tag__not_in']) ) {
656                                 $qv['tag__not_in'] = array();
657                         } else {
658                                 $qv['tag__not_in'] = array_map('intval', $qv['tag__not_in']);
659                         }
660
661                         if ( !is_array($qv['tag__and']) || empty($qv['tag__and']) ) {
662                                 $qv['tag__and'] = array();
663                         } else {
664                                 $qv['tag__and'] = array_map('intval', $qv['tag__and']);
665                                 $this->is_category = true;
666                         }
667
668                         if ( !is_array($qv['tag_slug__in']) || empty($qv['tag_slug__in']) ) {
669                                 $qv['tag_slug__in'] = array();
670                         } else {
671                                 $qv['tag_slug__in'] = array_map('sanitize_title', $qv['tag_slug__in']);
672                                 $this->is_tag = true;
673                         }
674
675                         if ( !is_array($qv['tag_slug__and']) || empty($qv['tag_slug__and']) ) {
676                                 $qv['tag_slug__and'] = array();
677                         } else {
678                                 $qv['tag_slug__and'] = array_map('sanitize_title', $qv['tag_slug__and']);
679                                 $this->is_tag = true;
680                         }
681
682                         if ( empty($qv['taxonomy']) || empty($qv['term']) ) {
683                                 $this->is_tax = false;
684                                 foreach ( $GLOBALS['wp_taxonomies'] as $t ) {
685                                         if ( isset($t->query_var) && '' != $qv[$t->query_var] ) {
686                                                 $this->is_tax = true;
687                                                 break;
688                                         }
689                                 }
690                         } else {
691                                 $this->is_tax = true;
692                         }
693
694                         if ( empty($qv['author']) || ($qv['author'] == '0') ) {
695                                 $this->is_author = false;
696                         } else {
697                                 $this->is_author = true;
698                         }
699
700                         if ( '' != $qv['author_name'] ) {
701                                 $this->is_author = true;
702                         }
703
704                         if ( ($this->is_date || $this->is_author || $this->is_category || $this->is_tag ) )
705                                 $this->is_archive = true;
706                 }
707
708                 if ( '' != $qv['feed'] )
709                         $this->is_feed = true;
710
711                 if ( '' != $qv['tb'] )
712                         $this->is_trackback = true;
713
714                 if ( '' != $qv['paged'] )
715                         $this->is_paged = true;
716
717                 if ( '' != $qv['comments_popup'] )
718                         $this->is_comments_popup = true;
719
720                 // if we're previewing inside the write screen
721                 if ('' != $qv['preview'])
722                         $this->is_preview = true;
723
724                 if ( is_admin() )
725                         $this->is_admin = true;
726
727                 if ( false !== strpos($qv['feed'], 'comments-') ) {
728                         $qv['feed'] = str_replace('comments-', '', $qv['feed']);
729                         $qv['withcomments'] = 1;
730                 }
731
732                 $this->is_singular = $this->is_single || $this->is_page || $this->is_attachment;
733
734                 if ( $this->is_feed && ( !empty($qv['withcomments']) || ( empty($qv['withoutcomments']) && $this->is_singular ) ) )
735                         $this->is_comment_feed = true;
736
737                 if ( !( $this->is_singular || $this->is_archive || $this->is_search || $this->is_feed || $this->is_trackback || $this->is_404 || $this->is_admin || $this->is_comments_popup ) )
738                         $this->is_home = true;
739
740                 // Correct is_* for page_on_front and page_for_posts
741                 if ( $this->is_home && ( empty($this->query) || $qv['preview'] == 'true' ) && 'page' == get_option('show_on_front') && get_option('page_on_front') ) {
742                         $this->is_page = true;
743                         $this->is_home = false;
744                         $qv['page_id'] = get_option('page_on_front');
745                 }
746
747                 if ( '' != $qv['pagename'] ) {
748                         $this->queried_object =& get_page_by_path($qv['pagename']);
749                         if ( !empty($this->queried_object) )
750                                 $this->queried_object_id = (int) $this->queried_object->ID;
751                         else
752                                 unset($this->queried_object);
753
754                         if  ( 'page' == get_option('show_on_front') && isset($this->queried_object_id) && $this->queried_object_id == get_option('page_for_posts') ) {
755                                 $this->is_page = false;
756                                 $this->is_home = true;
757                                 $this->is_posts_page = true;
758                         }
759                 }
760
761                 if ( $qv['page_id'] ) {
762                         if  ( 'page' == get_option('show_on_front') && $qv['page_id'] == get_option('page_for_posts') ) {
763                                 $this->is_page = false;
764                                 $this->is_home = true;
765                                 $this->is_posts_page = true;
766                         }
767                 }
768
769                 if ( !empty($qv['post_type']) )
770                         $qv['post_type'] = sanitize_user($qv['post_type'], true);
771
772                 if ( !empty($qv['post_status']) )
773                         $qv['post_status'] = sanitize_user($qv['post_status'], true);
774
775                 if ( $this->is_posts_page && !$qv['withcomments'] )
776                         $this->is_comment_feed = false;
777
778                 $this->is_singular = $this->is_single || $this->is_page || $this->is_attachment;
779                 // Done correcting is_* for page_on_front and page_for_posts
780
781                 if ('404' == $qv['error'])
782                         $this->set_404();
783
784                 if ( !empty($query) )
785                         do_action_ref_array('parse_query', array(&$this));
786         }
787
788         function set_404() {
789                 $is_feed = $this->is_feed;
790
791                 $this->init_query_flags();
792                 $this->is_404 = true;
793
794                 $this->is_feed = $is_feed;
795         }
796
797         function get($query_var) {
798                 if (isset($this->query_vars[$query_var])) {
799                         return $this->query_vars[$query_var];
800                 }
801
802                 return '';
803         }
804
805         function set($query_var, $value) {
806                 $this->query_vars[$query_var] = $value;
807         }
808
809         function &get_posts() {
810                 global $wpdb, $user_ID;
811
812                 do_action_ref_array('pre_get_posts', array(&$this));
813
814                 // Shorthand.
815                 $q = &$this->query_vars;
816
817                 $q = $this->fill_query_vars($q);
818
819                 // First let's clear some variables
820                 $distinct = '';
821                 $whichcat = '';
822                 $whichauthor = '';
823                 $whichmimetype = '';
824                 $where = '';
825                 $limits = '';
826                 $join = '';
827                 $search = '';
828                 $groupby = '';
829                 $post_status_join = false;
830
831                 if ( !isset($q['post_type']) ) {
832                         if ( $this->is_search )
833                                 $q['post_type'] = 'any';
834                         else
835                                 $q['post_type'] = 'post';
836                 }
837                 $post_type = $q['post_type'];
838                 if ( !isset($q['posts_per_page']) || $q['posts_per_page'] == 0 )
839                         $q['posts_per_page'] = get_option('posts_per_page');
840                 if ( isset($q['showposts']) && $q['showposts'] ) {
841                         $q['showposts'] = (int) $q['showposts'];
842                         $q['posts_per_page'] = $q['showposts'];
843                 }
844                 if ( (isset($q['posts_per_archive_page']) && $q['posts_per_archive_page'] != 0) && ($this->is_archive || $this->is_search) )
845                         $q['posts_per_page'] = $q['posts_per_archive_page'];
846                 if ( !isset($q['nopaging']) ) {
847                         if ($q['posts_per_page'] == -1) {
848                                 $q['nopaging'] = true;
849                         } else {
850                                 $q['nopaging'] = false;
851                         }
852                 }
853                 if ( $this->is_feed ) {
854                         $q['posts_per_page'] = get_option('posts_per_rss');
855                         $q['nopaging'] = false;
856                 }
857                 $q['posts_per_page'] = (int) $q['posts_per_page'];
858                 if ( $q['posts_per_page'] < -1 )
859                         $q['posts_per_page'] = abs($q['posts_per_page']);
860                 else if ( $q['posts_per_page'] == 0 )
861                         $q['posts_per_page'] = 1;
862
863                 if ( $this->is_home && (empty($this->query) || $q['preview'] == 'true') && ( 'page' == get_option('show_on_front') ) && get_option('page_on_front') ) {
864                         $this->is_page = true;
865                         $this->is_home = false;
866                         $q['page_id'] = get_option('page_on_front');
867                 }
868
869                 if (isset($q['page'])) {
870                         $q['page'] = trim($q['page'], '/');
871                         $q['page'] = (int) $q['page'];
872                         $q['page'] = abs($q['page']);
873                 }
874
875                 // If a month is specified in the querystring, load that month
876                 if ( $q['m'] ) {
877                         $q['m'] = '' . preg_replace('|[^0-9]|', '', $q['m']);
878                         $where .= " AND YEAR($wpdb->posts.post_date)=" . substr($q['m'], 0, 4);
879                         if (strlen($q['m'])>5)
880                                 $where .= " AND MONTH($wpdb->posts.post_date)=" . substr($q['m'], 4, 2);
881                         if (strlen($q['m'])>7)
882                                 $where .= " AND DAYOFMONTH($wpdb->posts.post_date)=" . substr($q['m'], 6, 2);
883                         if (strlen($q['m'])>9)
884                                 $where .= " AND HOUR($wpdb->posts.post_date)=" . substr($q['m'], 8, 2);
885                         if (strlen($q['m'])>11)
886                                 $where .= " AND MINUTE($wpdb->posts.post_date)=" . substr($q['m'], 10, 2);
887                         if (strlen($q['m'])>13)
888                                 $where .= " AND SECOND($wpdb->posts.post_date)=" . substr($q['m'], 12, 2);
889                 }
890
891                 if ( '' !== $q['hour'] )
892                         $where .= " AND HOUR($wpdb->posts.post_date)='" . $q['hour'] . "'";
893
894                 if ( '' !== $q['minute'] )
895                         $where .= " AND MINUTE($wpdb->posts.post_date)='" . $q['minute'] . "'";
896
897                 if ( '' !== $q['second'] )
898                         $where .= " AND SECOND($wpdb->posts.post_date)='" . $q['second'] . "'";
899
900                 if ( $q['year'] )
901                         $where .= " AND YEAR($wpdb->posts.post_date)='" . $q['year'] . "'";
902
903                 if ( $q['monthnum'] )
904                         $where .= " AND MONTH($wpdb->posts.post_date)='" . $q['monthnum'] . "'";
905
906                 if ( $q['day'] )
907                         $where .= " AND DAYOFMONTH($wpdb->posts.post_date)='" . $q['day'] . "'";
908
909                 if ('' != $q['name']) {
910                         $q['name'] = sanitize_title($q['name']);
911                         $where .= " AND $wpdb->posts.post_name = '" . $q['name'] . "'";
912                 } else if ('' != $q['pagename']) {
913                         if ( isset($this->queried_object_id) )
914                                 $reqpage = $this->queried_object_id;
915                         else {
916                                 $reqpage = get_page_by_path($q['pagename']);
917                                 if ( !empty($reqpage) )
918                                         $reqpage = $reqpage->ID;
919                                 else
920                                         $reqpage = 0;
921                         }
922
923                         if  ( ('page' != get_option('show_on_front') ) || ( $reqpage != get_option('page_for_posts') ) ) {
924                                 $q['pagename'] = str_replace('%2F', '/', urlencode(urldecode($q['pagename'])));
925                                 $page_paths = '/' . trim($q['pagename'], '/');
926                                 $q['pagename'] = sanitize_title(basename($page_paths));
927                                 $q['name'] = $q['pagename'];
928                                 $where .= " AND (ID = '$reqpage')";
929                                 $reqpage_obj = get_page($reqpage);
930                                 if ( 'attachment' == $reqpage_obj->post_type ) {
931                                         $this->is_attachment = true;
932                                         $this->is_page = true;
933                                         $q['attachment_id'] = $reqpage;
934                                 }
935                         }
936                 } elseif ('' != $q['attachment']) {
937                         $q['attachment'] = str_replace('%2F', '/', urlencode(urldecode($q['attachment'])));
938                         $attach_paths = '/' . trim($q['attachment'], '/');
939                         $q['attachment'] = sanitize_title(basename($attach_paths));
940                         $q['name'] = $q['attachment'];
941                         $where .= " AND $wpdb->posts.post_name = '" . $q['attachment'] . "'";
942                 }
943
944                 if ( $q['w'] )
945                         $where .= " AND WEEK($wpdb->posts.post_date, 1)='" . $q['w'] . "'";
946
947                 if ( intval($q['comments_popup']) )
948                         $q['p'] = intval($q['comments_popup']);
949
950                 // If an attachment is requested by number, let it supercede any post number.
951                 if ( $q['attachment_id'] )
952                         $q['p'] = $q['attachment_id'];
953
954                 // If a post number is specified, load that post
955                 if ( $q['p'] )
956                         $where = " AND {$wpdb->posts}.ID = " . $q['p'];
957
958                 if ( $q['page_id'] ) {
959                         if  ( ('page' != get_option('show_on_front') ) || ( $q['page_id'] != get_option('page_for_posts') ) ) {
960                                 $q['p'] = $q['page_id'];
961                                 $where = " AND {$wpdb->posts}.ID = " . $q['page_id'];
962                         }
963                 }
964
965                 // If a search pattern is specified, load the posts that match
966                 if ( !empty($q['s']) ) {
967                         // added slashes screw with quote grouping when done early, so done later
968                         $q['s'] = stripslashes($q['s']);
969                         if ($q['sentence']) {
970                                 $q['search_terms'] = array($q['s']);
971                         } else {
972                                 preg_match_all('/".*?("|$)|((?<=[\\s",+])|^)[^\\s",+]+/', $q[s], $matches);
973                                 $q['search_terms'] = array_map(create_function('$a', 'return trim($a, "\\"\'\\n\\r ");'), $matches[0]);
974                         }
975                         $n = ($q['exact']) ? '' : '%';
976                         $searchand = '';
977                         foreach((array)$q['search_terms'] as $term) {
978                                 $term = addslashes_gpc($term);
979                                 $search .= "{$searchand}(($wpdb->posts.post_title LIKE '{$n}{$term}{$n}') OR ($wpdb->posts.post_content LIKE '{$n}{$term}{$n}'))";
980                                 $searchand = ' AND ';
981                         }
982                         $term = $wpdb->escape($q['s']);
983                         if (!$q['sentence'] && count($q['search_terms']) > 1 && $q['search_terms'][0] != $q['s'] )
984                                 $search .= " OR ($wpdb->posts.post_title LIKE '{$n}{$term}{$n}') OR ($wpdb->posts.post_content LIKE '{$n}{$term}{$n}')";
985
986                         if ( !empty($search) )
987                                 $search = " AND ({$search}) ";
988                 }
989
990                 // Category stuff
991
992                 if ( empty($q['cat']) || ($q['cat'] == '0') ||
993                                 // Bypass cat checks if fetching specific posts
994                                 $this->is_singular ) {
995                         $whichcat = '';
996                 } else {
997                         $q['cat'] = ''.urldecode($q['cat']).'';
998                         $q['cat'] = addslashes_gpc($q['cat']);
999                         $cat_array = preg_split('/[,\s]+/', $q['cat']);
1000                         $q['cat'] = '';
1001                         $req_cats = array();
1002                         foreach ( $cat_array as $cat ) {
1003                                 $cat = intval($cat);
1004                                 $req_cats[] = $cat;
1005                                 $in = ($cat > 0);
1006                                 $cat = abs($cat);
1007                                 if ( $in ) {
1008                                         $q['category__in'][] = $cat;
1009                                         $q['category__in'] = array_merge($q['category__in'], get_term_children($cat, 'category'));
1010                                 } else {
1011                                         $q['category__not_in'][] = $cat;
1012                                         $q['category__not_in'] = array_merge($q['category__not_in'], get_term_children($cat, 'category'));
1013                                 }
1014                         }
1015                         $q['cat'] = implode(',', $req_cats);
1016                 }
1017
1018                 if ( !empty($q['category__in']) || !empty($q['category__not_in']) || !empty($q['category__and']) ) {
1019                         $groupby = "{$wpdb->posts}.ID";
1020                 }
1021
1022                 if ( !empty($q['category__in']) ) {
1023                         $join = " INNER JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id) INNER JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id) ";
1024                         $whichcat .= " AND $wpdb->term_taxonomy.taxonomy = 'category' ";
1025                         $include_cats = "'" . implode("', '", $q['category__in']) . "'";
1026                         $whichcat .= " AND $wpdb->term_taxonomy.term_id IN ($include_cats) ";
1027                 }
1028
1029                 if ( !empty($q['category__not_in']) ) {
1030                         $ids = get_objects_in_term($q['category__not_in'], 'category');
1031                         if ( is_wp_error( $ids ) )
1032                                 return $ids;
1033                         if ( is_array($ids) && count($ids > 0) ) {
1034                                 $out_posts = "'" . implode("', '", $ids) . "'";
1035                                 $whichcat .= " AND $wpdb->posts.ID NOT IN ($out_posts)";
1036                         }
1037                 }
1038
1039                 // Category stuff for nice URLs
1040                 if ( '' != $q['category_name'] && !$this->is_singular ) {
1041                         $reqcat = get_category_by_path($q['category_name']);
1042                         $q['category_name'] = str_replace('%2F', '/', urlencode(urldecode($q['category_name'])));
1043                         $cat_paths = '/' . trim($q['category_name'], '/');
1044                         $q['category_name'] = sanitize_title(basename($cat_paths));
1045
1046                         $cat_paths = '/' . trim(urldecode($q['category_name']), '/');
1047                         $q['category_name'] = sanitize_title(basename($cat_paths));
1048                         $cat_paths = explode('/', $cat_paths);
1049                         $cat_path = '';
1050                         foreach ( (array) $cat_paths as $pathdir )
1051                                 $cat_path .= ( $pathdir != '' ? '/' : '' ) . sanitize_title($pathdir);
1052
1053                         //if we don't match the entire hierarchy fallback on just matching the nicename
1054                         if ( empty($reqcat) )
1055                                 $reqcat = get_category_by_path($q['category_name'], false);
1056
1057                         if ( !empty($reqcat) )
1058                                 $reqcat = $reqcat->term_id;
1059                         else
1060                                 $reqcat = 0;
1061
1062                         $q['cat'] = $reqcat;
1063
1064                         $join = " INNER JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id) INNER JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id) ";
1065                         $whichcat = " AND $wpdb->term_taxonomy.taxonomy = 'category' ";
1066                         $in_cats = array($q['cat']);
1067                         $in_cats = array_merge($in_cats, get_term_children($q['cat'], 'category'));
1068                         $in_cats = "'" . implode("', '", $in_cats) . "'";
1069                         $whichcat .= "AND $wpdb->term_taxonomy.term_id IN ($in_cats)";
1070                         $groupby = "{$wpdb->posts}.ID";
1071                 }
1072
1073                 // Tags
1074                 if ( '' != $q['tag'] ) {
1075                         if ( strpos($q['tag'], ',') !== false ) {
1076                                 $tags = preg_split('/[,\s]+/', $q['tag']);
1077                                 foreach ( (array) $tags as $tag ) {
1078                                         $tag = sanitize_term_field('slug', $tag, 0, 'post_tag', 'db');
1079                                         $q['tag_slug__in'][] = $tag;
1080                                 }
1081                         } else if ( preg_match('/[+\s]+/', $q['tag']) ) {
1082                                 $tags = preg_split('/[+\s]+/', $q['tag']);
1083                                 foreach ( (array) $tags as $tag ) {
1084                                         $tag = sanitize_term_field('slug', $tag, 0, 'post_tag', 'db');
1085                                         $q['tag_slug__and'][] = $tag;
1086                                 }
1087                         } else {
1088                                 $q['tag'] = sanitize_term_field('slug', $q['tag'], 0, 'post_tag', 'db');
1089                                 $q['tag_slug__in'][] = $q['tag'];
1090                         }
1091                 }
1092
1093                 if ( !empty($q['tag__in']) || !empty($q['tag__not_in']) || !empty($q['tag__and']) ||
1094                         !empty($q['tag_slug__in']) || !empty($q['tag_slug__and']) ) {
1095                         $groupby = "{$wpdb->posts}.ID";
1096                 }
1097
1098                 if ( !empty($q['tag__in']) ) {
1099                         $join = " INNER JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id) INNER JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id) ";
1100                         $whichcat .= " AND $wpdb->term_taxonomy.taxonomy = 'post_tag' ";
1101                         $include_tags = "'" . implode("', '", $q['tag__in']) . "'";
1102                         $whichcat .= " AND $wpdb->term_taxonomy.term_id IN ($include_tags) ";
1103                         $reqtag = is_term( $q['tag__in'][0], 'post_tag' );
1104                         if ( !empty($reqtag) )
1105                                 $q['tag_id'] = $reqtag['term_id'];
1106                 }
1107
1108                 if ( !empty($q['tag_slug__in']) ) {
1109                         $join = " INNER JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id) INNER JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id) INNER JOIN $wpdb->terms ON ($wpdb->term_taxonomy.term_id = $wpdb->terms.term_id) ";
1110                         $whichcat .= " AND $wpdb->term_taxonomy.taxonomy = 'post_tag' ";
1111                         $include_tags = "'" . implode("', '", $q['tag_slug__in']) . "'";
1112                         $whichcat .= " AND $wpdb->terms.slug IN ($include_tags) ";
1113                         $reqtag = is_term( $q['tag_slug__in'][0], 'post_tag' );
1114                         if ( !empty($reqtag) )
1115                                 $q['tag_id'] = $reqtag['term_id'];
1116                 }
1117
1118                 if ( !empty($q['tag__not_in']) ) {
1119                         $ids = get_objects_in_term($q['tag__not_in'], 'post_tag');
1120                         if ( is_array($ids) && count($ids > 0) ) {
1121                                 $out_posts = "'" . implode("', '", $ids) . "'";
1122                                 $whichcat .= " AND $wpdb->posts.ID NOT IN ($out_posts)";
1123                         }
1124                 }
1125
1126                 // Tag and slug intersections.
1127                 $intersections = array('category__and' => 'category', 'tag__and' => 'post_tag', 'tag_slug__and' => 'post_tag');
1128                 foreach ($intersections as $item => $taxonomy) {
1129                         if ( empty($q[$item]) ) continue;
1130
1131                         if ( $item != 'category__and' ) {
1132                                 $reqtag = is_term( $q[$item][0], 'post_tag' );
1133                                 if ( !empty($reqtag) )
1134                                         $q['tag_id'] = $reqtag['term_id'];
1135                         }
1136
1137                         $taxonomy_field = $item == 'tag_slug__and' ? 'slug' : 'term_id';
1138
1139                         $q[$item] = array_unique($q[$item]);
1140                         $tsql = "SELECT p.ID FROM $wpdb->posts p INNER JOIN $wpdb->term_relationships tr ON (p.ID = tr.object_id) INNER JOIN $wpdb->term_taxonomy tt ON (tr.term_taxonomy_id = tt.term_taxonomy_id) INNER JOIN $wpdb->terms t ON (tt.term_id = t.term_id)";
1141                         $tsql .= " WHERE tt.taxonomy = '$taxonomy' AND t.$taxonomy_field IN ('" . implode("', '", $q[$item]) . "')";
1142                         $tsql .= " GROUP BY p.ID HAVING count(p.ID) = " . count($q[$item]);
1143
1144                         $post_ids = $wpdb->get_col($tsql);
1145
1146                         if ( count($post_ids) )
1147                                 $whichcat .= " AND $wpdb->posts.ID IN (" . implode(', ', $post_ids) . ") ";
1148                         else {
1149                                 $whichcat = " AND 0 = 1";
1150                                 break;
1151                         }
1152                 }
1153
1154                 // Taxonomies
1155                 if ( $this->is_tax ) {
1156                         if ( '' != $q['taxonomy'] ) {
1157                                 $taxonomy = $q['taxonomy'];
1158                                 $tt[$taxonomy] = $q['term'];
1159                                 $terms = get_terms($q['taxonomy'], array('slug'=>$q['term']));
1160                         } else {
1161                                 foreach ( $GLOBALS['wp_taxonomies'] as $taxonomy => $t ) {
1162                                         if ( isset($t->query_var) && '' != $q[$t->query_var] ) {
1163                                                 $terms = get_terms($taxonomy, array('slug'=>$q[$t->query_var]));
1164                                                 if ( !is_wp_error($terms) )
1165                                                         break;
1166                                         }
1167                                 }
1168                         }
1169                         if ( is_wp_error($terms) || empty($terms) ) {
1170                                 $whichcat = " AND 0 ";
1171                         } else {
1172                                 foreach ( $terms as $term )
1173                                         $term_ids[] = $term->term_id;
1174                                 $post_ids = get_objects_in_term($term_ids, $taxonomy);
1175                                 if ( !is_wp_error($post_ids) && count($post_ids) ) {
1176                                         $whichcat .= " AND $wpdb->posts.ID IN (" . implode(', ', $post_ids) . ") ";
1177                                         $post_type = 'any';
1178                                         $q['post_status'] = 'publish';
1179                                         $post_status_join = true;
1180                                 } else {
1181                                         $whichcat = " AND 0 ";
1182                                 }
1183                         }
1184                 }
1185
1186                 // Author/user stuff
1187
1188                 if ( empty($q['author']) || ($q['author'] == '0') ) {
1189                         $whichauthor='';
1190                 } else {
1191                         $q['author'] = ''.urldecode($q['author']).'';
1192                         $q['author'] = addslashes_gpc($q['author']);
1193                         if (strpos($q['author'], '-') !== false) {
1194                                 $eq = '!=';
1195                                 $andor = 'AND';
1196                                 $q['author'] = explode('-', $q['author']);
1197                                 $q['author'] = ''.intval($q['author'][1]);
1198                         } else {
1199                                 $eq = '=';
1200                                 $andor = 'OR';
1201                         }
1202                         $author_array = preg_split('/[,\s]+/', $q['author']);
1203                         $whichauthor .= " AND ($wpdb->posts.post_author ".$eq.' '.intval($author_array[0]);
1204                         for ($i = 1; $i < (count($author_array)); $i = $i + 1) {
1205                                 $whichauthor .= ' '.$andor." $wpdb->posts.post_author ".$eq.' '.intval($author_array[$i]);
1206                         }
1207                         $whichauthor .= ')';
1208                 }
1209
1210                 // Author stuff for nice URLs
1211
1212                 if ('' != $q['author_name']) {
1213                         if (strpos($q['author_name'], '/') !== false) {
1214                                 $q['author_name'] = explode('/',$q['author_name']);
1215                                 if ($q['author_name'][count($q['author_name'])-1]) {
1216                                         $q['author_name'] = $q['author_name'][count($q['author_name'])-1];#no trailing slash
1217                                 } else {
1218                                         $q['author_name'] = $q['author_name'][count($q['author_name'])-2];#there was a trailling slash
1219                                 }
1220                         }
1221                         $q['author_name'] = sanitize_title($q['author_name']);
1222                         $q['author'] = $wpdb->get_var("SELECT ID FROM $wpdb->users WHERE user_nicename='".$q['author_name']."'");
1223                         $whichauthor .= " AND ($wpdb->posts.post_author = ".intval($q['author']).')';
1224                 }
1225
1226                 // MIME-Type stuff for attachment browsing
1227
1228                 if ( isset($q['post_mime_type']) && '' != $q['post_mime_type'] )
1229                         $whichmimetype = wp_post_mime_type_where($q['post_mime_type']);
1230
1231                 $where .= $search.$whichcat.$whichauthor.$whichmimetype;
1232
1233                 if ( empty($q['order']) || ((strtoupper($q['order']) != 'ASC') && (strtoupper($q['order']) != 'DESC')) )
1234                         $q['order'] = 'DESC';
1235
1236                 // Order by
1237                 if ( empty($q['orderby']) ) {
1238                         $q['orderby'] = "$wpdb->posts.post_date ".$q['order'];
1239                 } else {
1240                         // Used to filter values
1241                         $allowed_keys = array('author', 'date', 'category', 'title', 'modified', 'menu_order', 'parent', 'ID', 'rand');
1242                         $q['orderby'] = urldecode($q['orderby']);
1243                         $q['orderby'] = addslashes_gpc($q['orderby']);
1244                         $orderby_array = explode(' ',$q['orderby']);
1245                         if ( empty($orderby_array) )
1246                                 $orderby_array[] = $q['orderby'];
1247                         $q['orderby'] = '';
1248                         for ($i = 0; $i < count($orderby_array); $i++) {
1249                                 // Only allow certain values for safety
1250                                 $orderby = $orderby_array[$i];
1251                                 switch ($orderby) {
1252                                         case 'menu_order':
1253                                                 break;
1254                                         case 'ID':
1255                                                 $orderby = "$wpdb->posts.ID";
1256                                                 break;
1257                                         case 'rand':
1258                                                 $orderby = 'RAND()';
1259                                                 break;
1260                                         default:
1261                                                 $orderby = "$wpdb->posts.post_" . $orderby;
1262                                 }
1263                                 if ( in_array($orderby_array[$i], $allowed_keys) )
1264                                         $q['orderby'] .= (($i == 0) ? '' : ',') . $orderby;
1265                         }
1266                         // append ASC or DESC at the end
1267                         if ( !empty($q['orderby']))
1268                                 $q['orderby'] .= " {$q['order']}";
1269
1270                         if ( empty($q['orderby']) )
1271                                 $q['orderby'] = "$wpdb->posts.post_date ".$q['order'];
1272                 }
1273
1274                 if ( $this->is_attachment ) {
1275                         $where .= " AND $wpdb->posts.post_type = 'attachment'";
1276                 } elseif ($this->is_page) {
1277                         $where .= " AND $wpdb->posts.post_type = 'page'";
1278                 } elseif ($this->is_single) {
1279                         $where .= " AND $wpdb->posts.post_type = 'post'";
1280                 } elseif ( 'any' == $post_type ) {
1281                         $where .= '';
1282                 } else {
1283                         $where .= " AND $wpdb->posts.post_type = '$post_type'";
1284                 }
1285
1286                 if ( isset($q['post_status']) && '' != $q['post_status'] ) {
1287                         $statuswheres = array();
1288                         $q_status = explode(',', $q['post_status']);
1289                         $r_status = array();
1290                         $p_status = array();
1291                         if ( in_array( 'draft'  , $q_status ) )
1292                                 $r_status[] = "$wpdb->posts.post_status = 'draft'";
1293                         if ( in_array( 'pending', $q_status ) )
1294                                 $r_status[] = "$wpdb->posts.post_status = 'pending'";
1295                         if ( in_array( 'future' , $q_status ) )
1296                                 $r_status[] = "$wpdb->posts.post_status = 'future'";
1297                         if ( in_array( 'inherit' , $q_status ) )
1298                                 $r_status[] = "$wpdb->posts.post_status = 'inherit'";
1299                         if ( in_array( 'private', $q_status ) )
1300                                 $p_status[] = "$wpdb->posts.post_status = 'private'";
1301                         if ( in_array( 'publish', $q_status ) )
1302                                 $r_status[] = "$wpdb->posts.post_status = 'publish'";
1303
1304                         if ( empty($q['perm'] ) || 'readable' != $q['perm'] ) {
1305                                 $r_status = array_merge($r_status, $p_status);
1306                                 unset($p_status);
1307                         }
1308
1309                         if ( !empty($r_status) ) {
1310                                 if ( !empty($q['perm'] ) && 'editable' == $q['perm'] && !current_user_can("edit_others_{$post_type}s") )
1311                                         $statuswheres[] = "($wpdb->posts.post_author = $user_ID " .  "AND (" . join( ' OR ', $r_status ) . "))";
1312                                 else
1313                                         $statuswheres[] = "(" . join( ' OR ', $r_status ) . ")";
1314                         }
1315                         if ( !empty($p_status) ) {
1316                                 if ( !empty($q['perm'] ) && 'readable' == $q['perm'] && !current_user_can("read_private_{$post_type}s") )
1317                                         $statuswheres[] = "($wpdb->posts.post_author = $user_ID " .  "AND (" . join( ' OR ', $p_status ) . "))";
1318                                 else
1319                                         $statuswheres[] = "(" . join( ' OR ', $p_status ) . ")";
1320                         }
1321                         if ( $post_status_join ) {
1322                                 $join .= " LEFT JOIN $wpdb->posts AS p2 ON ($wpdb->posts.post_parent = p2.ID) ";
1323                                 foreach ( $statuswheres as $index => $statuswhere )
1324                                         $statuswheres[$index] = "($statuswhere OR ($wpdb->posts.post_status = 'inherit' AND " . str_replace($wpdb->posts, 'p2', $statuswhere) . "))";
1325                         }
1326                         foreach ( $statuswheres as $statuswhere )
1327                                 $where .= " AND $statuswhere";
1328                 } elseif ( !$this->is_singular ) {
1329                         $where .= " AND ($wpdb->posts.post_status = 'publish'";
1330
1331                         if ( is_admin() )
1332                                 $where .= " OR $wpdb->posts.post_status = 'future' OR $wpdb->posts.post_status = 'draft' OR $wpdb->posts.post_status = 'pending'";
1333
1334                         if ( is_user_logged_in() ) {
1335                                 $where .= current_user_can( "read_private_{$post_type}s" ) ? " OR $wpdb->posts.post_status = 'private'" : " OR $wpdb->posts.post_author = $user_ID AND $wpdb->posts.post_status = 'private'";
1336                         }
1337
1338                         $where .= ')';
1339                 }
1340
1341                 // Apply filters on where and join prior to paging so that any
1342                 // manipulations to them are reflected in the paging by day queries.
1343                 $where = apply_filters('posts_where', $where);
1344                 $join = apply_filters('posts_join', $join);
1345
1346                 // Paging
1347                 if ( empty($q['nopaging']) && !$this->is_singular ) {
1348                         $page = absint($q['paged']);
1349                         if (empty($page)) {
1350                                 $page = 1;
1351                         }
1352
1353                         if ( empty($q['offset']) ) {
1354                                 $pgstrt = '';
1355                                 $pgstrt = (intval($page) -1) * $q['posts_per_page'] . ', ';
1356                                 $limits = 'LIMIT '.$pgstrt.$q['posts_per_page'];
1357                         } else { // we're ignoring $page and using 'offset'
1358                                 $q['offset'] = absint($q['offset']);
1359                                 $pgstrt = $q['offset'] . ', ';
1360                                 $limits = 'LIMIT ' . $pgstrt . $q['posts_per_page'];
1361                         }
1362                 }
1363
1364                 // Comments feeds
1365                 if ( $this->is_comment_feed && ( $this->is_archive || $this->is_search || !$this->is_singular ) ) {
1366                         if ( $this->is_archive || $this->is_search ) {
1367                                 $cjoin = "LEFT JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID = $wpdb->posts.ID) $join ";
1368                                 $cwhere = "WHERE comment_approved = '1' $where";
1369                                 $cgroupby = "GROUP BY $wpdb->comments.comment_id";
1370                         } else { // Other non singular e.g. front
1371                                 $cjoin = "LEFT JOIN $wpdb->posts ON ( $wpdb->comments.comment_post_ID = $wpdb->posts.ID )";
1372                                 $cwhere = "WHERE post_status = 'publish' AND comment_approved = '1'";
1373                                 $cgroupby = '';
1374                         }
1375
1376                         $cjoin = apply_filters('comment_feed_join', $cjoin);
1377                         $cwhere = apply_filters('comment_feed_where', $cwhere);
1378                         $cgroupby = apply_filters('comment_feed_groupby', $cgroupby);
1379
1380                         $this->comments = (array) $wpdb->get_results("SELECT $distinct $wpdb->comments.* FROM $wpdb->comments $cjoin $cwhere $cgroupby ORDER BY comment_date_gmt DESC LIMIT " . get_option('posts_per_rss'));
1381                         $this->comment_count = count($this->comments);
1382
1383                         $post_ids = array();
1384
1385                         foreach ($this->comments as $comment)
1386                                 $post_ids[] = (int) $comment->comment_post_ID;
1387
1388                         $post_ids = join(',', $post_ids);
1389                         $join = '';
1390                         if ( $post_ids )
1391                                 $where = "AND $wpdb->posts.ID IN ($post_ids) ";
1392                         else
1393                                 $where = "AND 0";
1394                 }
1395
1396                 // Apply post-paging filters on where and join.  Only plugins that
1397                 // manipulate paging queries should use these hooks.
1398
1399                 $where = apply_filters('posts_where_paged', $where);
1400                 $groupby = apply_filters('posts_groupby', $groupby);
1401                 $join = apply_filters('posts_join_paged', $join);
1402                 $orderby = apply_filters('posts_orderby', $q['orderby']);
1403                 $distinct = apply_filters('posts_distinct', $distinct);
1404                 $fields = apply_filters('posts_fields', "$wpdb->posts.*");
1405                 $limits = apply_filters( 'post_limits', $limits );
1406
1407                 // Announce current selection parameters.  For use by caching plugins.
1408                 do_action( 'posts_selection', $where . $groupby . $orderby . $limits . $join );
1409
1410                 // Filter again for the benefit of caching plugins.  Regular plugins should use the hooks above.
1411                 $where = apply_filters('posts_where_request', $where);
1412                 $groupby = apply_filters('posts_groupby_request', $groupby);
1413                 $join = apply_filters('posts_join_request', $join);
1414                 $orderby = apply_filters('posts_orderby_request', $orderby);
1415                 $distinct = apply_filters('posts_distinct_request', $distinct);
1416                 $fields = apply_filters('posts_fields_request', $fields);
1417                 $limits = apply_filters( 'post_limits_request', $limits );
1418
1419                 if ( ! empty($groupby) )
1420                         $groupby = 'GROUP BY ' . $groupby;
1421                 if ( !empty( $orderby ) )
1422                         $orderby = 'ORDER BY ' . $orderby;
1423                 $found_rows = '';
1424                 if ( !empty($limits) )
1425                         $found_rows = 'SQL_CALC_FOUND_ROWS';
1426
1427                 $request = " SELECT $found_rows $distinct $fields FROM $wpdb->posts $join WHERE 1=1 $where $groupby $orderby $limits";
1428                 $this->request = apply_filters('posts_request', $request);
1429
1430                 $this->posts = $wpdb->get_results($this->request);
1431                 // Raw results filter.  Prior to status checks.
1432                 $this->posts = apply_filters('posts_results', $this->posts);
1433
1434                 if ( !empty($this->posts) && $this->is_comment_feed && $this->is_singular ) {
1435                         $cjoin = apply_filters('comment_feed_join', '');
1436                         $cwhere = apply_filters('comment_feed_where', "WHERE comment_post_ID = '{$this->posts[0]->ID}' AND comment_approved = '1'");
1437                         $comments_request = "SELECT $wpdb->comments.* FROM $wpdb->comments $cjoin $cwhere ORDER BY comment_date_gmt DESC LIMIT " . get_option('posts_per_rss');
1438                         $this->comments = $wpdb->get_results($comments_request);
1439                         $this->comment_count = count($this->comments);
1440                 }
1441
1442                 if ( !empty($limits) ) {
1443                         $found_posts_query = apply_filters( 'found_posts_query', 'SELECT FOUND_ROWS()' );
1444                         $this->found_posts = $wpdb->get_var( $found_posts_query );
1445                         $this->found_posts = apply_filters( 'found_posts', $this->found_posts );
1446                         $this->max_num_pages = ceil($this->found_posts / $q['posts_per_page']);
1447                 }
1448
1449                 // Check post status to determine if post should be displayed.
1450                 if ( !empty($this->posts) && ($this->is_single || $this->is_page) ) {
1451                         $status = get_post_status($this->posts[0]);
1452                         //$type = get_post_type($this->posts[0]);
1453                         if ( ('publish' != $status) ) {
1454                                 if ( ! is_user_logged_in() ) {
1455                                         // User must be logged in to view unpublished posts.
1456                                         $this->posts = array();
1457                                 } else {
1458                                         if  (in_array($status, array('draft', 'pending')) ) {
1459                                                 // User must have edit permissions on the draft to preview.
1460                                                 if (! current_user_can('edit_post', $this->posts[0]->ID)) {
1461                                                         $this->posts = array();
1462                                                 } else {
1463                                                         $this->is_preview = true;
1464                                                         $this->posts[0]->post_date = current_time('mysql');
1465                                                 }
1466                                         }  else if ('future' == $status) {
1467                                                 $this->is_preview = true;
1468                                                 if (!current_user_can('edit_post', $this->posts[0]->ID)) {
1469                                                         $this->posts = array ( );
1470                                                 }
1471                                         } else {
1472                                                 if (! current_user_can('read_post', $this->posts[0]->ID))
1473                                                         $this->posts = array();
1474                                         }
1475                                 }
1476                         }
1477                 }
1478
1479                 $this->posts = apply_filters('the_posts', $this->posts);
1480
1481                 update_post_caches($this->posts);
1482
1483                 $this->post_count = count($this->posts);
1484                 if ($this->post_count > 0) {
1485                         $this->post = $this->posts[0];
1486                 }
1487
1488                 return $this->posts;
1489         }
1490
1491         function next_post() {
1492
1493                 $this->current_post++;
1494
1495                 $this->post = $this->posts[$this->current_post];
1496                 return $this->post;
1497         }
1498
1499         function the_post() {
1500                 global $post;
1501                 $this->in_the_loop = true;
1502                 $post = $this->next_post();
1503                 setup_postdata($post);
1504
1505                 if ( $this->current_post == 0 ) // loop has just started
1506                         do_action('loop_start');
1507         }
1508
1509         function have_posts() {
1510                 if ($this->current_post + 1 < $this->post_count) {
1511                         return true;
1512                 } elseif ($this->current_post + 1 == $this->post_count) {
1513                         do_action('loop_end');
1514                         // Do some cleaning up after the loop
1515                         $this->rewind_posts();
1516                 }
1517
1518                 $this->in_the_loop = false;
1519                 return false;
1520         }
1521
1522         function rewind_posts() {
1523                 $this->current_post = -1;
1524                 if ($this->post_count > 0) {
1525                         $this->post = $this->posts[0];
1526                 }
1527         }
1528
1529         function next_comment() {
1530                 $this->current_comment++;
1531
1532                 $this->comment = $this->comments[$this->current_comment];
1533                 return $this->comment;
1534         }
1535
1536         function the_comment() {
1537                 global $comment;
1538
1539                 $comment = $this->next_comment();
1540
1541                 if ($this->current_comment == 0) {
1542                         do_action('comment_loop_start');
1543                 }
1544         }
1545
1546         function have_comments() {
1547                 if ($this->current_comment + 1 < $this->comment_count) {
1548                         return true;
1549                 } elseif ($this->current_comment + 1 == $this->comment_count) {
1550                         $this->rewind_comments();
1551                 }
1552
1553                 return false;
1554         }
1555
1556         function rewind_comments() {
1557                 $this->current_comment = -1;
1558                 if ($this->comment_count > 0) {
1559                         $this->comment = $this->comments[0];
1560                 }
1561         }
1562
1563         function &query($query) {
1564                 $this->parse_query($query);
1565                 return $this->get_posts();
1566         }
1567
1568         function get_queried_object() {
1569                 if (isset($this->queried_object)) {
1570                         return $this->queried_object;
1571                 }
1572
1573                 $this->queried_object = NULL;
1574                 $this->queried_object_id = 0;
1575
1576                 if ($this->is_category) {
1577                         $cat = $this->get('cat');
1578                         $category = &get_category($cat);
1579                         $this->queried_object = &$category;
1580                         $this->queried_object_id = (int) $cat;
1581                 } else if ($this->is_tag) {
1582                         $tag_id = $this->get('tag_id');
1583                         $tag = &get_term($tag_id, 'post_tag');
1584                         if ( is_wp_error( $tag ) )
1585                                 return $tag;
1586                         $this->queried_object = &$tag;
1587                         $this->queried_object_id = (int) $tag_id;
1588                 } else if ($this->is_tax) {
1589                         $tax = $this->get('taxonomy');
1590                         $slug = $this->get('term');
1591                         $term = &get_terms($tax, array('slug'=>$slug));
1592                         if ( is_wp_error($term) )
1593                                 return $term;
1594                         $this->queried_object = $term;
1595                         $this->queried_object_id = $term->term_id;
1596                 } else if ($this->is_posts_page) {
1597                         $this->queried_object = & get_page(get_option('page_for_posts'));
1598                         $this->queried_object_id = (int) $this->queried_object->ID;
1599                 } else if ($this->is_single) {
1600                         $this->queried_object = $this->post;
1601                         $this->queried_object_id = (int) $this->post->ID;
1602                 } else if ($this->is_page) {
1603                         $this->queried_object = $this->post;
1604                         $this->queried_object_id = (int) $this->post->ID;
1605                 } else if ($this->is_author) {
1606                         $author_id = (int) $this->get('author');
1607                         $author = get_userdata($author_id);
1608                         $this->queried_object = $author;
1609                         $this->queried_object_id = $author_id;
1610                 }
1611
1612                 return $this->queried_object;
1613         }
1614
1615         function get_queried_object_id() {
1616                 $this->get_queried_object();
1617
1618                 if (isset($this->queried_object_id)) {
1619                         return $this->queried_object_id;
1620                 }
1621
1622                 return 0;
1623         }
1624
1625         function WP_Query ($query = '') {
1626                 if (! empty($query)) {
1627                         $this->query($query);
1628                 }
1629         }
1630 }
1631
1632
1633 // Redirect old slugs
1634 function wp_old_slug_redirect () {
1635         global $wp_query;
1636         if ( is_404() && '' != $wp_query->query_vars['name'] ) :
1637                 global $wpdb;
1638
1639                 $query = "SELECT post_id FROM $wpdb->postmeta, $wpdb->posts WHERE ID = post_id AND meta_key = '_wp_old_slug' AND meta_value='" . $wp_query->query_vars['name'] . "'";
1640
1641                 // if year, monthnum, or day have been specified, make our query more precise
1642                 // just in case there are multiple identical _wp_old_slug values
1643                 if ( '' != $wp_query->query_vars['year'] )
1644                         $query .= " AND YEAR(post_date) = '{$wp_query->query_vars['year']}'";
1645                 if ( '' != $wp_query->query_vars['monthnum'] )
1646                         $query .= " AND MONTH(post_date) = '{$wp_query->query_vars['monthnum']}'";
1647                 if ( '' != $wp_query->query_vars['day'] )
1648                         $query .= " AND DAYOFMONTH(post_date) = '{$wp_query->query_vars['day']}'";
1649
1650                 $id = (int) $wpdb->get_var($query);
1651
1652                 if ( !$id )
1653                         return;
1654
1655                 $link = get_permalink($id);
1656
1657                 if ( !$link )
1658                         return;
1659
1660                 wp_redirect($link, '301'); // Permanent redirect
1661                 exit;
1662         endif;
1663 }
1664
1665
1666 //
1667 // Private helper functions
1668 //
1669
1670 // Setup global post data.
1671 function setup_postdata($post) {
1672         global $id, $authordata, $day, $currentmonth, $page, $pages, $multipage, $more, $numpages;
1673
1674         $id = (int) $post->ID;
1675
1676         $authordata = get_userdata($post->post_author);
1677
1678         $day = mysql2date('d.m.y', $post->post_date);
1679         $currentmonth = mysql2date('m', $post->post_date);
1680         $numpages = 1;
1681         $page = get_query_var('page');
1682         if ( !$page )
1683                 $page = 1;
1684         if ( is_single() || is_page() || is_feed() )
1685                 $more = 1;
1686         $content = $post->post_content;
1687         if ( preg_match('/<!--nextpage-->/', $content) ) {
1688                 if ( $page > 1 )
1689                         $more = 1;
1690                 $multipage = 1;
1691                 $content = str_replace("\n<!--nextpage-->\n", '<!--nextpage-->', $content);
1692                 $content = str_replace("\n<!--nextpage-->", '<!--nextpage-->', $content);
1693                 $content = str_replace("<!--nextpage-->\n", '<!--nextpage-->', $content);
1694                 $pages = explode('<!--nextpage-->', $content);
1695                 $numpages = count($pages);
1696         } else {
1697                 $pages[0] = $post->post_content;
1698                 $multipage = 0;
1699         }
1700         return true;
1701 }
1702
1703 ?>