]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/query.php
Wordpress 2.6.2-scripts
[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                         , 'post_parent'
457                         , 'subpost'
458                         , 'subpost_id'
459                         , 'attachment'
460                         , 'attachment_id'
461                         , 'name'
462                         , 'hour'
463                         , 'static'
464                         , 'pagename'
465                         , 'page_id'
466                         , 'second'
467                         , 'minute'
468                         , 'hour'
469                         , 'day'
470                         , 'monthnum'
471                         , 'year'
472                         , 'w'
473                         , 'category_name'
474                         , 'tag'
475                         , 'tag_id'
476                         , 'author_name'
477                         , 'feed'
478                         , 'tb'
479                         , 'paged'
480                         , 'comments_popup'
481                         , 'meta_key'
482                         , 'meta_value'
483                         , 'preview'
484                 );
485
486                 foreach ($keys as $key) {
487                         if ( !isset($array[$key]))
488                                 $array[$key] = '';
489                 }
490
491                 $array_keys = array('category__in', 'category__not_in', 'category__and', 'post__in', 'post__not_in',
492                         'tag__in', 'tag__not_in', 'tag__and', 'tag_slug__in', 'tag_slug__and');
493
494                 foreach ( $array_keys as $key ) {
495                         if ( !isset($array[$key]))
496                                 $array[$key] = array();
497                 }
498                 return $array;
499         }
500
501         // Parse a query string and set query type booleans.
502         function parse_query ($query) {
503                 if ( !empty($query) || !isset($this->query) ) {
504                         $this->init();
505                         if ( is_array($query) )
506                                 $this->query_vars = $query;
507                         else
508                                 parse_str($query, $this->query_vars);
509                         $this->query = $query;
510                 }
511
512                 $this->query_vars = $this->fill_query_vars($this->query_vars);
513                 $qv = &$this->query_vars;
514
515                 if ( ! empty($qv['robots']) )
516                         $this->is_robots = true;
517
518                 $qv['p'] =  absint($qv['p']);
519                 $qv['page_id'] =  absint($qv['page_id']);
520                 $qv['year'] = absint($qv['year']);
521                 $qv['monthnum'] = absint($qv['monthnum']);
522                 $qv['day'] = absint($qv['day']);
523                 $qv['w'] = absint($qv['w']);
524                 $qv['m'] = absint($qv['m']);
525                 $qv['cat'] = preg_replace( '|[^0-9,-]|', '', $qv['cat'] ); // comma separated list of positive or negative integers
526                 if ( '' !== $qv['hour'] ) $qv['hour'] = absint($qv['hour']);
527                 if ( '' !== $qv['minute'] ) $qv['minute'] = absint($qv['minute']);
528                 if ( '' !== $qv['second'] ) $qv['second'] = absint($qv['second']);
529
530                 // Compat.  Map subpost to attachment.
531                 if ( '' != $qv['subpost'] )
532                         $qv['attachment'] = $qv['subpost'];
533                 if ( '' != $qv['subpost_id'] )
534                         $qv['attachment_id'] = $qv['subpost_id'];
535
536                 $qv['attachment_id'] = absint($qv['attachment_id']);
537
538                 if ( ('' != $qv['attachment']) || !empty($qv['attachment_id']) ) {
539                         $this->is_single = true;
540                         $this->is_attachment = true;
541                 } elseif ( '' != $qv['name'] ) {
542                         $this->is_single = true;
543                 } elseif ( $qv['p'] ) {
544                         $this->is_single = true;
545                 } elseif ( ('' !== $qv['hour']) && ('' !== $qv['minute']) &&('' !== $qv['second']) && ('' != $qv['year']) && ('' != $qv['monthnum']) && ('' != $qv['day']) ) {
546                         // If year, month, day, hour, minute, and second are set, a single
547                         // post is being queried.
548                         $this->is_single = true;
549                 } elseif ( '' != $qv['static'] || '' != $qv['pagename'] || !empty($qv['page_id']) ) {
550                         $this->is_page = true;
551                         $this->is_single = false;
552                 } elseif ( !empty($qv['s']) ) {
553                         $this->is_search = true;
554                 } else {
555                 // Look for archive queries.  Dates, categories, authors.
556
557                         if ( '' !== $qv['second'] ) {
558                                 $this->is_time = true;
559                                 $this->is_date = true;
560                         }
561
562                         if ( '' !== $qv['minute'] ) {
563                                 $this->is_time = true;
564                                 $this->is_date = true;
565                         }
566
567                         if ( '' !== $qv['hour'] ) {
568                                 $this->is_time = true;
569                                 $this->is_date = true;
570                         }
571
572                         if ( $qv['day'] ) {
573                                 if (! $this->is_date) {
574                                         $this->is_day = true;
575                                         $this->is_date = true;
576                                 }
577                         }
578
579                         if ( $qv['monthnum'] ) {
580                                 if (! $this->is_date) {
581                                         $this->is_month = true;
582                                         $this->is_date = true;
583                                 }
584                         }
585
586                         if ( $qv['year'] ) {
587                                 if (! $this->is_date) {
588                                         $this->is_year = true;
589                                         $this->is_date = true;
590                                 }
591                         }
592
593                         if ( $qv['m'] ) {
594                                 $this->is_date = true;
595                                 if (strlen($qv['m']) > 9) {
596                                         $this->is_time = true;
597                                 } else if (strlen($qv['m']) > 7) {
598                                         $this->is_day = true;
599                                 } else if (strlen($qv['m']) > 5) {
600                                         $this->is_month = true;
601                                 } else {
602                                         $this->is_year = true;
603                                 }
604                         }
605
606                         if ('' != $qv['w']) {
607                                 $this->is_date = true;
608                         }
609
610                         if ( empty($qv['cat']) || ($qv['cat'] == '0') ) {
611                                 $this->is_category = false;
612                         } else {
613                                 if (strpos($qv['cat'], '-') !== false) {
614                                         $this->is_category = false;
615                                 } else {
616                                         $this->is_category = true;
617                                 }
618                         }
619
620                         if ( '' != $qv['category_name'] ) {
621                                 $this->is_category = true;
622                         }
623
624                         if ( !is_array($qv['category__in']) || empty($qv['category__in']) ) {
625                                 $qv['category__in'] = array();
626                         } else {
627                                 $qv['category__in'] = array_map('absint', $qv['category__in']);
628                                 $this->is_category = true;
629                         }
630
631                         if ( !is_array($qv['category__not_in']) || empty($qv['category__not_in']) ) {
632                                 $qv['category__not_in'] = array();
633                         } else {
634                                 $qv['category__not_in'] = array_map('absint', $qv['category__not_in']);
635                         }
636
637                         if ( !is_array($qv['category__and']) || empty($qv['category__and']) ) {
638                                 $qv['category__and'] = array();
639                         } else {
640                                 $qv['category__and'] = array_map('absint', $qv['category__and']);
641                                 $this->is_category = true;
642                         }
643
644                         if (  '' != $qv['tag'] )
645                                 $this->is_tag = true;
646
647                         $qv['tag_id'] = absint($qv['tag_id']);
648                         if (  !empty($qv['tag_id']) )
649                                 $this->is_tag = true;
650
651                         if ( !is_array($qv['tag__in']) || empty($qv['tag__in']) ) {
652                                 $qv['tag__in'] = array();
653                         } else {
654                                 $qv['tag__in'] = array_map('absint', $qv['tag__in']);
655                                 $this->is_tag = true;
656                         }
657
658                         if ( !is_array($qv['tag__not_in']) || empty($qv['tag__not_in']) ) {
659                                 $qv['tag__not_in'] = array();
660                         } else {
661                                 $qv['tag__not_in'] = array_map('absint', $qv['tag__not_in']);
662                         }
663
664                         if ( !is_array($qv['tag__and']) || empty($qv['tag__and']) ) {
665                                 $qv['tag__and'] = array();
666                         } else {
667                                 $qv['tag__and'] = array_map('absint', $qv['tag__and']);
668                                 $this->is_category = true;
669                         }
670
671                         if ( !is_array($qv['tag_slug__in']) || empty($qv['tag_slug__in']) ) {
672                                 $qv['tag_slug__in'] = array();
673                         } else {
674                                 $qv['tag_slug__in'] = array_map('sanitize_title', $qv['tag_slug__in']);
675                                 $this->is_tag = true;
676                         }
677
678                         if ( !is_array($qv['tag_slug__and']) || empty($qv['tag_slug__and']) ) {
679                                 $qv['tag_slug__and'] = array();
680                         } else {
681                                 $qv['tag_slug__and'] = array_map('sanitize_title', $qv['tag_slug__and']);
682                                 $this->is_tag = true;
683                         }
684
685                         if ( empty($qv['taxonomy']) || empty($qv['term']) ) {
686                                 $this->is_tax = false;
687                                 foreach ( $GLOBALS['wp_taxonomies'] as $t ) {
688                                         if ( isset($t->query_var) && '' != $qv[$t->query_var] ) {
689                                                 $this->is_tax = true;
690                                                 break;
691                                         }
692                                 }
693                         } else {
694                                 $this->is_tax = true;
695                         }
696
697                         if ( empty($qv['author']) || ($qv['author'] == '0') ) {
698                                 $this->is_author = false;
699                         } else {
700                                 $this->is_author = true;
701                         }
702
703                         if ( '' != $qv['author_name'] ) {
704                                 $this->is_author = true;
705                         }
706
707                         if ( ($this->is_date || $this->is_author || $this->is_category || $this->is_tag ) )
708                                 $this->is_archive = true;
709                 }
710
711                 if ( '' != $qv['feed'] )
712                         $this->is_feed = true;
713
714                 if ( '' != $qv['tb'] )
715                         $this->is_trackback = true;
716
717                 if ( '' != $qv['paged'] )
718                         $this->is_paged = true;
719
720                 if ( '' != $qv['comments_popup'] )
721                         $this->is_comments_popup = true;
722
723                 // if we're previewing inside the write screen
724                 if ('' != $qv['preview'])
725                         $this->is_preview = true;
726
727                 if ( is_admin() )
728                         $this->is_admin = true;
729
730                 if ( false !== strpos($qv['feed'], 'comments-') ) {
731                         $qv['feed'] = str_replace('comments-', '', $qv['feed']);
732                         $qv['withcomments'] = 1;
733                 }
734
735                 $this->is_singular = $this->is_single || $this->is_page || $this->is_attachment;
736
737                 if ( $this->is_feed && ( !empty($qv['withcomments']) || ( empty($qv['withoutcomments']) && $this->is_singular ) ) )
738                         $this->is_comment_feed = true;
739
740                 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 ) )
741                         $this->is_home = true;
742
743                 // Correct is_* for page_on_front and page_for_posts
744                 if ( $this->is_home && ( empty($this->query) || $qv['preview'] == 'true' ) && 'page' == get_option('show_on_front') && get_option('page_on_front') ) {
745                         $this->is_page = true;
746                         $this->is_home = false;
747                         $qv['page_id'] = get_option('page_on_front');
748                 }
749
750                 if ( '' != $qv['pagename'] ) {
751                         $this->queried_object =& get_page_by_path($qv['pagename']);
752                         if ( !empty($this->queried_object) )
753                                 $this->queried_object_id = (int) $this->queried_object->ID;
754                         else
755                                 unset($this->queried_object);
756
757                         if  ( 'page' == get_option('show_on_front') && isset($this->queried_object_id) && $this->queried_object_id == get_option('page_for_posts') ) {
758                                 $this->is_page = false;
759                                 $this->is_home = true;
760                                 $this->is_posts_page = true;
761                         }
762                 }
763
764                 if ( $qv['page_id'] ) {
765                         if  ( 'page' == get_option('show_on_front') && $qv['page_id'] == get_option('page_for_posts') ) {
766                                 $this->is_page = false;
767                                 $this->is_home = true;
768                                 $this->is_posts_page = true;
769                         }
770                 }
771
772                 if ( !empty($qv['post_type']) )
773                         $qv['post_type'] = sanitize_user($qv['post_type'], true);
774
775                 if ( !empty($qv['post_status']) )
776                         $qv['post_status'] = preg_replace('|[^a-z0-9_,-]|', '', $qv['post_status']);
777
778                 if ( $this->is_posts_page && ( ! isset($qv['withcomments']) || ! $qv['withcomments'] ) )
779                         $this->is_comment_feed = false;
780
781                 $this->is_singular = $this->is_single || $this->is_page || $this->is_attachment;
782                 // Done correcting is_* for page_on_front and page_for_posts
783
784                 if ('404' == $qv['error'])
785                         $this->set_404();
786
787                 if ( !empty($query) )
788                         do_action_ref_array('parse_query', array(&$this));
789         }
790
791         function set_404() {
792                 $is_feed = $this->is_feed;
793
794                 $this->init_query_flags();
795                 $this->is_404 = true;
796
797                 $this->is_feed = $is_feed;
798         }
799
800         function get($query_var) {
801                 if (isset($this->query_vars[$query_var])) {
802                         return $this->query_vars[$query_var];
803                 }
804
805                 return '';
806         }
807
808         function set($query_var, $value) {
809                 $this->query_vars[$query_var] = $value;
810         }
811
812         function &get_posts() {
813                 global $wpdb, $user_ID;
814
815                 do_action_ref_array('pre_get_posts', array(&$this));
816
817                 // Shorthand.
818                 $q = &$this->query_vars;
819
820                 $q = $this->fill_query_vars($q);
821
822                 // First let's clear some variables
823                 $distinct = '';
824                 $whichcat = '';
825                 $whichauthor = '';
826                 $whichmimetype = '';
827                 $where = '';
828                 $limits = '';
829                 $join = '';
830                 $search = '';
831                 $groupby = '';
832                 $fields = "$wpdb->posts.*";
833                 $post_status_join = false;
834                 $page = 1;
835
836                 if ( !isset($q['suppress_filters']) )
837                         $q['suppress_filters'] = false;
838
839                 if ( !isset($q['post_type']) ) {
840                         if ( $this->is_search )
841                                 $q['post_type'] = 'any';
842                         else
843                                 $q['post_type'] = 'post';
844                 }
845                 $post_type = $q['post_type'];
846                 if ( !isset($q['posts_per_page']) || $q['posts_per_page'] == 0 )
847                         $q['posts_per_page'] = get_option('posts_per_page');
848                 if ( isset($q['showposts']) && $q['showposts'] ) {
849                         $q['showposts'] = (int) $q['showposts'];
850                         $q['posts_per_page'] = $q['showposts'];
851                 }
852                 if ( (isset($q['posts_per_archive_page']) && $q['posts_per_archive_page'] != 0) && ($this->is_archive || $this->is_search) )
853                         $q['posts_per_page'] = $q['posts_per_archive_page'];
854                 if ( !isset($q['nopaging']) ) {
855                         if ($q['posts_per_page'] == -1) {
856                                 $q['nopaging'] = true;
857                         } else {
858                                 $q['nopaging'] = false;
859                         }
860                 }
861                 if ( $this->is_feed ) {
862                         $q['posts_per_page'] = get_option('posts_per_rss');
863                         $q['nopaging'] = false;
864                 }
865                 $q['posts_per_page'] = (int) $q['posts_per_page'];
866                 if ( $q['posts_per_page'] < -1 )
867                         $q['posts_per_page'] = abs($q['posts_per_page']);
868                 else if ( $q['posts_per_page'] == 0 )
869                         $q['posts_per_page'] = 1;
870
871                 if ( $this->is_home && (empty($this->query) || $q['preview'] == 'true') && ( 'page' == get_option('show_on_front') ) && get_option('page_on_front') ) {
872                         $this->is_page = true;
873                         $this->is_home = false;
874                         $q['page_id'] = get_option('page_on_front');
875                 }
876
877                 if (isset($q['page'])) {
878                         $q['page'] = trim($q['page'], '/');
879                         $q['page'] = absint($q['page']);
880                 }
881
882                 // If a month is specified in the querystring, load that month
883                 if ( $q['m'] ) {
884                         $q['m'] = '' . preg_replace('|[^0-9]|', '', $q['m']);
885                         $where .= " AND YEAR($wpdb->posts.post_date)=" . substr($q['m'], 0, 4);
886                         if (strlen($q['m'])>5)
887                                 $where .= " AND MONTH($wpdb->posts.post_date)=" . substr($q['m'], 4, 2);
888                         if (strlen($q['m'])>7)
889                                 $where .= " AND DAYOFMONTH($wpdb->posts.post_date)=" . substr($q['m'], 6, 2);
890                         if (strlen($q['m'])>9)
891                                 $where .= " AND HOUR($wpdb->posts.post_date)=" . substr($q['m'], 8, 2);
892                         if (strlen($q['m'])>11)
893                                 $where .= " AND MINUTE($wpdb->posts.post_date)=" . substr($q['m'], 10, 2);
894                         if (strlen($q['m'])>13)
895                                 $where .= " AND SECOND($wpdb->posts.post_date)=" . substr($q['m'], 12, 2);
896                 }
897
898                 if ( '' !== $q['hour'] )
899                         $where .= " AND HOUR($wpdb->posts.post_date)='" . $q['hour'] . "'";
900
901                 if ( '' !== $q['minute'] )
902                         $where .= " AND MINUTE($wpdb->posts.post_date)='" . $q['minute'] . "'";
903
904                 if ( '' !== $q['second'] )
905                         $where .= " AND SECOND($wpdb->posts.post_date)='" . $q['second'] . "'";
906
907                 if ( $q['year'] )
908                         $where .= " AND YEAR($wpdb->posts.post_date)='" . $q['year'] . "'";
909
910                 if ( $q['monthnum'] )
911                         $where .= " AND MONTH($wpdb->posts.post_date)='" . $q['monthnum'] . "'";
912
913                 if ( $q['day'] )
914                         $where .= " AND DAYOFMONTH($wpdb->posts.post_date)='" . $q['day'] . "'";
915
916                 if ('' != $q['name']) {
917                         $q['name'] = sanitize_title($q['name']);
918                         $where .= " AND $wpdb->posts.post_name = '" . $q['name'] . "'";
919                 } else if ('' != $q['pagename']) {
920                         if ( isset($this->queried_object_id) )
921                                 $reqpage = $this->queried_object_id;
922                         else {
923                                 $reqpage = get_page_by_path($q['pagename']);
924                                 if ( !empty($reqpage) )
925                                         $reqpage = $reqpage->ID;
926                                 else
927                                         $reqpage = 0;
928                         }
929
930                         $page_for_posts = get_option('page_for_posts');
931                         if  ( ('page' != get_option('show_on_front') ) ||  empty($page_for_posts) || ( $reqpage != $page_for_posts ) ) {
932                                 $q['pagename'] = str_replace('%2F', '/', urlencode(urldecode($q['pagename'])));
933                                 $page_paths = '/' . trim($q['pagename'], '/');
934                                 $q['pagename'] = sanitize_title(basename($page_paths));
935                                 $q['name'] = $q['pagename'];
936                                 $where .= " AND ($wpdb->posts.ID = '$reqpage')";
937                                 $reqpage_obj = get_page($reqpage);
938                                 if ( 'attachment' == $reqpage_obj->post_type ) {
939                                         $this->is_attachment = true;
940                                         $this->is_page = true;
941                                         $q['attachment_id'] = $reqpage;
942                                 }
943                         }
944                 } elseif ('' != $q['attachment']) {
945                         $q['attachment'] = str_replace('%2F', '/', urlencode(urldecode($q['attachment'])));
946                         $attach_paths = '/' . trim($q['attachment'], '/');
947                         $q['attachment'] = sanitize_title(basename($attach_paths));
948                         $q['name'] = $q['attachment'];
949                         $where .= " AND $wpdb->posts.post_name = '" . $q['attachment'] . "'";
950                 }
951
952                 if ( $q['w'] )
953                         $where .= " AND WEEK($wpdb->posts.post_date, 1)='" . $q['w'] . "'";
954
955                 if ( intval($q['comments_popup']) )
956                         $q['p'] = absint($q['comments_popup']);
957
958                 // If an attachment is requested by number, let it supercede any post number.
959                 if ( $q['attachment_id'] )
960                         $q['p'] = absint($q['attachment_id']);
961
962                 // If a post number is specified, load that post
963                 if ( $q['p'] ) {
964                         $where .= " AND {$wpdb->posts}.ID = " . $q['p'];
965                 } elseif ( $q['post__in'] ) {
966                         $post__in = implode(',', array_map( 'absint', $q['post__in'] ));
967                         $where .= " AND {$wpdb->posts}.ID IN ($post__in)";
968                 } elseif ( $q['post__not_in'] ) {
969                         $post__not_in = implode(',',  array_map( 'absint', $q['post__not_in'] ));
970                         $where .= " AND {$wpdb->posts}.ID NOT IN ($post__not_in)";
971                 }
972
973                 if ( $q['post_parent'] )
974                         $where .= $wpdb->prepare( " AND $wpdb->posts.post_parent = %d ", $q['post_parent'] );
975
976                 if ( $q['page_id'] ) {
977                         if  ( ('page' != get_option('show_on_front') ) || ( $q['page_id'] != get_option('page_for_posts') ) ) {
978                                 $q['p'] = $q['page_id'];
979                                 $where = " AND {$wpdb->posts}.ID = " . $q['page_id'];
980                         }
981                 }
982
983                 // If a search pattern is specified, load the posts that match
984                 if ( !empty($q['s']) ) {
985                         // added slashes screw with quote grouping when done early, so done later
986                         $q['s'] = stripslashes($q['s']);
987                         if ($q['sentence']) {
988                                 $q['search_terms'] = array($q['s']);
989                         } else {
990                                 preg_match_all('/".*?("|$)|((?<=[\\s",+])|^)[^\\s",+]+/', $q[s], $matches);
991                                 $q['search_terms'] = array_map(create_function('$a', 'return trim($a, "\\"\'\\n\\r ");'), $matches[0]);
992                         }
993                         $n = ($q['exact']) ? '' : '%';
994                         $searchand = '';
995                         foreach((array)$q['search_terms'] as $term) {
996                                 $term = addslashes_gpc($term);
997                                 $search .= "{$searchand}(($wpdb->posts.post_title LIKE '{$n}{$term}{$n}') OR ($wpdb->posts.post_content LIKE '{$n}{$term}{$n}'))";
998                                 $searchand = ' AND ';
999                         }
1000                         $term = $wpdb->escape($q['s']);
1001                         if (!$q['sentence'] && count($q['search_terms']) > 1 && $q['search_terms'][0] != $q['s'] )
1002                                 $search .= " OR ($wpdb->posts.post_title LIKE '{$n}{$term}{$n}') OR ($wpdb->posts.post_content LIKE '{$n}{$term}{$n}')";
1003
1004                         if ( !empty($search) )
1005                                 $search = " AND ({$search}) ";
1006                 }
1007
1008                 // Category stuff
1009
1010                 if ( empty($q['cat']) || ($q['cat'] == '0') ||
1011                                 // Bypass cat checks if fetching specific posts
1012                                 $this->is_singular ) {
1013                         $whichcat = '';
1014                 } else {
1015                         $q['cat'] = ''.urldecode($q['cat']).'';
1016                         $q['cat'] = addslashes_gpc($q['cat']);
1017                         $cat_array = preg_split('/[,\s]+/', $q['cat']);
1018                         $q['cat'] = '';
1019                         $req_cats = array();
1020                         foreach ( $cat_array as $cat ) {
1021                                 $cat = intval($cat);
1022                                 $req_cats[] = $cat;
1023                                 $in = ($cat > 0);
1024                                 $cat = abs($cat);
1025                                 if ( $in ) {
1026                                         $q['category__in'][] = $cat;
1027                                         $q['category__in'] = array_merge($q['category__in'], get_term_children($cat, 'category'));
1028                                 } else {
1029                                         $q['category__not_in'][] = $cat;
1030                                         $q['category__not_in'] = array_merge($q['category__not_in'], get_term_children($cat, 'category'));
1031                                 }
1032                         }
1033                         $q['cat'] = implode(',', $req_cats);
1034                 }
1035
1036                 if ( !empty($q['category__in']) || !empty($q['category__not_in']) || !empty($q['category__and']) ) {
1037                         $groupby = "{$wpdb->posts}.ID";
1038                 }
1039
1040                 if ( !empty($q['category__in']) ) {
1041                         $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) ";
1042                         $whichcat .= " AND $wpdb->term_taxonomy.taxonomy = 'category' ";
1043                         $include_cats = "'" . implode("', '", $q['category__in']) . "'";
1044                         $whichcat .= " AND $wpdb->term_taxonomy.term_id IN ($include_cats) ";
1045                 }
1046
1047                 if ( !empty($q['category__not_in']) ) {
1048                         $ids = get_objects_in_term($q['category__not_in'], 'category');
1049                         if ( is_wp_error( $ids ) )
1050                                 return $ids;
1051                         if ( is_array($ids) && count($ids > 0) ) {
1052                                 $out_posts = "'" . implode("', '", $ids) . "'";
1053                                 $whichcat .= " AND $wpdb->posts.ID NOT IN ($out_posts)";
1054                         }
1055                 }
1056
1057                 // Category stuff for nice URLs
1058                 if ( '' != $q['category_name'] && !$this->is_singular ) {
1059                         $reqcat = get_category_by_path($q['category_name']);
1060                         $q['category_name'] = str_replace('%2F', '/', urlencode(urldecode($q['category_name'])));
1061                         $cat_paths = '/' . trim($q['category_name'], '/');
1062                         $q['category_name'] = sanitize_title(basename($cat_paths));
1063
1064                         $cat_paths = '/' . trim(urldecode($q['category_name']), '/');
1065                         $q['category_name'] = sanitize_title(basename($cat_paths));
1066                         $cat_paths = explode('/', $cat_paths);
1067                         $cat_path = '';
1068                         foreach ( (array) $cat_paths as $pathdir )
1069                                 $cat_path .= ( $pathdir != '' ? '/' : '' ) . sanitize_title($pathdir);
1070
1071                         //if we don't match the entire hierarchy fallback on just matching the nicename
1072                         if ( empty($reqcat) )
1073                                 $reqcat = get_category_by_path($q['category_name'], false);
1074
1075                         if ( !empty($reqcat) )
1076                                 $reqcat = $reqcat->term_id;
1077                         else
1078                                 $reqcat = 0;
1079
1080                         $q['cat'] = $reqcat;
1081
1082                         $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) ";
1083                         $whichcat = " AND $wpdb->term_taxonomy.taxonomy = 'category' ";
1084                         $in_cats = array($q['cat']);
1085                         $in_cats = array_merge($in_cats, get_term_children($q['cat'], 'category'));
1086                         $in_cats = "'" . implode("', '", $in_cats) . "'";
1087                         $whichcat .= "AND $wpdb->term_taxonomy.term_id IN ($in_cats)";
1088                         $groupby = "{$wpdb->posts}.ID";
1089                 }
1090
1091                 // Tags
1092                 if ( '' != $q['tag'] ) {
1093                         if ( strpos($q['tag'], ',') !== false ) {
1094                                 $tags = preg_split('/[,\s]+/', $q['tag']);
1095                                 foreach ( (array) $tags as $tag ) {
1096                                         $tag = sanitize_term_field('slug', $tag, 0, 'post_tag', 'db');
1097                                         $q['tag_slug__in'][] = $tag;
1098                                 }
1099                         } else if ( preg_match('/[+\s]+/', $q['tag']) ) {
1100                                 $tags = preg_split('/[+\s]+/', $q['tag']);
1101                                 foreach ( (array) $tags as $tag ) {
1102                                         $tag = sanitize_term_field('slug', $tag, 0, 'post_tag', 'db');
1103                                         $q['tag_slug__and'][] = $tag;
1104                                 }
1105                         } else {
1106                                 $q['tag'] = sanitize_term_field('slug', $q['tag'], 0, 'post_tag', 'db');
1107                                 $q['tag_slug__in'][] = $q['tag'];
1108                         }
1109                 }
1110
1111                 if ( !empty($q['tag__in']) || !empty($q['tag__not_in']) || !empty($q['tag__and']) ||
1112                         !empty($q['tag_slug__in']) || !empty($q['tag_slug__and']) ) {
1113                         $groupby = "{$wpdb->posts}.ID";
1114                 }
1115
1116                 if ( !empty($q['tag__in']) ) {
1117                         $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) ";
1118                         $whichcat .= " AND $wpdb->term_taxonomy.taxonomy = 'post_tag' ";
1119                         $include_tags = "'" . implode("', '", $q['tag__in']) . "'";
1120                         $whichcat .= " AND $wpdb->term_taxonomy.term_id IN ($include_tags) ";
1121                         $reqtag = is_term( $q['tag__in'][0], 'post_tag' );
1122                         if ( !empty($reqtag) )
1123                                 $q['tag_id'] = $reqtag['term_id'];
1124                 }
1125
1126                 if ( !empty($q['tag_slug__in']) ) {
1127                         $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) ";
1128                         $whichcat .= " AND $wpdb->term_taxonomy.taxonomy = 'post_tag' ";
1129                         $include_tags = "'" . implode("', '", $q['tag_slug__in']) . "'";
1130                         $whichcat .= " AND $wpdb->terms.slug IN ($include_tags) ";
1131                         $reqtag = get_term_by( 'slug', $q['tag_slug__in'][0], 'post_tag' );
1132                         if ( !empty($reqtag) )
1133                                 $q['tag_id'] = $reqtag->term_id;
1134                 }
1135
1136                 if ( !empty($q['tag__not_in']) ) {
1137                         $ids = get_objects_in_term($q['tag__not_in'], 'post_tag');
1138                         if ( is_array($ids) && count($ids > 0) ) {
1139                                 $out_posts = "'" . implode("', '", $ids) . "'";
1140                                 $whichcat .= " AND $wpdb->posts.ID NOT IN ($out_posts)";
1141                         }
1142                 }
1143
1144                 // Tag and slug intersections.
1145                 $intersections = array('category__and' => 'category', 'tag__and' => 'post_tag', 'tag_slug__and' => 'post_tag');
1146                 foreach ($intersections as $item => $taxonomy) {
1147                         if ( empty($q[$item]) ) continue;
1148
1149                         if ( $item != 'category__and' ) {
1150                                 $reqtag = is_term( $q[$item][0], 'post_tag' );
1151                                 if ( !empty($reqtag) )
1152                                         $q['tag_id'] = $reqtag['term_id'];
1153                         }
1154
1155                         $taxonomy_field = $item == 'tag_slug__and' ? 'slug' : 'term_id';
1156
1157                         $q[$item] = array_unique($q[$item]);
1158                         $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)";
1159                         $tsql .= " WHERE tt.taxonomy = '$taxonomy' AND t.$taxonomy_field IN ('" . implode("', '", $q[$item]) . "')";
1160                         $tsql .= " GROUP BY p.ID HAVING count(p.ID) = " . count($q[$item]);
1161
1162                         $post_ids = $wpdb->get_col($tsql);
1163
1164                         if ( count($post_ids) )
1165                                 $whichcat .= " AND $wpdb->posts.ID IN (" . implode(', ', $post_ids) . ") ";
1166                         else {
1167                                 $whichcat = " AND 0 = 1";
1168                                 break;
1169                         }
1170                 }
1171
1172                 // Taxonomies
1173                 if ( $this->is_tax ) {
1174                         if ( '' != $q['taxonomy'] ) {
1175                                 $taxonomy = $q['taxonomy'];
1176                                 $tt[$taxonomy] = $q['term'];
1177                                 $terms = get_terms($q['taxonomy'], array('slug'=>$q['term']));
1178                         } else {
1179                                 foreach ( $GLOBALS['wp_taxonomies'] as $taxonomy => $t ) {
1180                                         if ( isset($t->query_var) && '' != $q[$t->query_var] ) {
1181                                                 $terms = get_terms($taxonomy, array('slug'=>$q[$t->query_var]));
1182                                                 if ( !is_wp_error($terms) )
1183                                                         break;
1184                                         }
1185                                 }
1186                         }
1187                         if ( is_wp_error($terms) || empty($terms) ) {
1188                                 $whichcat = " AND 0 ";
1189                         } else {
1190                                 foreach ( $terms as $term )
1191                                         $term_ids[] = $term->term_id;
1192                                 $post_ids = get_objects_in_term($term_ids, $taxonomy);
1193                                 if ( !is_wp_error($post_ids) && count($post_ids) ) {
1194                                         $whichcat .= " AND $wpdb->posts.ID IN (" . implode(', ', $post_ids) . ") ";
1195                                         $post_type = 'any';
1196                                         $q['post_status'] = 'publish';
1197                                         $post_status_join = true;
1198                                 } else {
1199                                         $whichcat = " AND 0 ";
1200                                 }
1201                         }
1202                 }
1203
1204                 // Author/user stuff
1205
1206                 if ( empty($q['author']) || ($q['author'] == '0') ) {
1207                         $whichauthor='';
1208                 } else {
1209                         $q['author'] = ''.urldecode($q['author']).'';
1210                         $q['author'] = addslashes_gpc($q['author']);
1211                         if (strpos($q['author'], '-') !== false) {
1212                                 $eq = '!=';
1213                                 $andor = 'AND';
1214                                 $q['author'] = explode('-', $q['author']);
1215                                 $q['author'] = '' . absint($q['author'][1]);
1216                         } else {
1217                                 $eq = '=';
1218                                 $andor = 'OR';
1219                         }
1220                         $author_array = preg_split('/[,\s]+/', $q['author']);
1221                         $whichauthor .= " AND ($wpdb->posts.post_author ".$eq.' '.absint($author_array[0]);
1222                         for ($i = 1; $i < (count($author_array)); $i = $i + 1) {
1223                                 $whichauthor .= ' '.$andor." $wpdb->posts.post_author ".$eq.' '.absint($author_array[$i]);
1224                         }
1225                         $whichauthor .= ')';
1226                 }
1227
1228                 // Author stuff for nice URLs
1229
1230                 if ('' != $q['author_name']) {
1231                         if (strpos($q['author_name'], '/') !== false) {
1232                                 $q['author_name'] = explode('/',$q['author_name']);
1233                                 if ($q['author_name'][count($q['author_name'])-1]) {
1234                                         $q['author_name'] = $q['author_name'][count($q['author_name'])-1];#no trailing slash
1235                                 } else {
1236                                         $q['author_name'] = $q['author_name'][count($q['author_name'])-2];#there was a trailling slash
1237                                 }
1238                         }
1239                         $q['author_name'] = sanitize_title($q['author_name']);
1240                         $q['author'] = $wpdb->get_var("SELECT ID FROM $wpdb->users WHERE user_nicename='".$q['author_name']."'");
1241                         $whichauthor .= " AND ($wpdb->posts.post_author = ".absint($q['author']).')';
1242                 }
1243
1244                 // MIME-Type stuff for attachment browsing
1245
1246                 if ( isset($q['post_mime_type']) && '' != $q['post_mime_type'] )
1247                         $whichmimetype = wp_post_mime_type_where($q['post_mime_type']);
1248
1249                 $where .= $search.$whichcat.$whichauthor.$whichmimetype;
1250
1251                 if ( empty($q['order']) || ((strtoupper($q['order']) != 'ASC') && (strtoupper($q['order']) != 'DESC')) )
1252                         $q['order'] = 'DESC';
1253
1254                 // Order by
1255                 if ( empty($q['orderby']) ) {
1256                         $q['orderby'] = "$wpdb->posts.post_date ".$q['order'];
1257                 } else {
1258                         // Used to filter values
1259                         $allowed_keys = array('author', 'date', 'category', 'title', 'modified', 'menu_order', 'parent', 'ID', 'rand');
1260                         $q['orderby'] = urldecode($q['orderby']);
1261                         $q['orderby'] = addslashes_gpc($q['orderby']);
1262                         $orderby_array = explode(' ',$q['orderby']);
1263                         if ( empty($orderby_array) )
1264                                 $orderby_array[] = $q['orderby'];
1265                         $q['orderby'] = '';
1266                         for ($i = 0; $i < count($orderby_array); $i++) {
1267                                 // Only allow certain values for safety
1268                                 $orderby = $orderby_array[$i];
1269                                 switch ($orderby) {
1270                                         case 'menu_order':
1271                                                 break;
1272                                         case 'ID':
1273                                                 $orderby = "$wpdb->posts.ID";
1274                                                 break;
1275                                         case 'rand':
1276                                                 $orderby = 'RAND()';
1277                                                 break;
1278                                         default:
1279                                                 $orderby = "$wpdb->posts.post_" . $orderby;
1280                                 }
1281                                 if ( in_array($orderby_array[$i], $allowed_keys) )
1282                                         $q['orderby'] .= (($i == 0) ? '' : ',') . $orderby;
1283                         }
1284                         // append ASC or DESC at the end
1285                         if ( !empty($q['orderby']))
1286                                 $q['orderby'] .= " {$q['order']}";
1287
1288                         if ( empty($q['orderby']) )
1289                                 $q['orderby'] = "$wpdb->posts.post_date ".$q['order'];
1290                 }
1291
1292                 if ( $this->is_attachment ) {
1293                         $where .= " AND $wpdb->posts.post_type = 'attachment'";
1294                 } elseif ($this->is_page) {
1295                         $where .= " AND $wpdb->posts.post_type = 'page'";
1296                 } elseif ($this->is_single) {
1297                         $where .= " AND $wpdb->posts.post_type = 'post'";
1298                 } elseif ( 'any' == $post_type ) {
1299                         $where .= '';
1300                 } else {
1301                         $where .= " AND $wpdb->posts.post_type = '$post_type'";
1302                 }
1303
1304                 if ( isset($q['post_status']) && '' != $q['post_status'] ) {
1305                         $statuswheres = array();
1306                         $q_status = explode(',', $q['post_status']);
1307                         $r_status = array();
1308                         $p_status = array();
1309                         if ( in_array( 'draft'  , $q_status ) )
1310                                 $r_status[] = "$wpdb->posts.post_status = 'draft'";
1311                         if ( in_array( 'pending', $q_status ) )
1312                                 $r_status[] = "$wpdb->posts.post_status = 'pending'";
1313                         if ( in_array( 'future' , $q_status ) )
1314                                 $r_status[] = "$wpdb->posts.post_status = 'future'";
1315                         if ( in_array( 'inherit' , $q_status ) )
1316                                 $r_status[] = "$wpdb->posts.post_status = 'inherit'";
1317                         if ( in_array( 'private', $q_status ) )
1318                                 $p_status[] = "$wpdb->posts.post_status = 'private'";
1319                         if ( in_array( 'publish', $q_status ) )
1320                                 $r_status[] = "$wpdb->posts.post_status = 'publish'";
1321
1322                         if ( empty($q['perm'] ) || 'readable' != $q['perm'] ) {
1323                                 $r_status = array_merge($r_status, $p_status);
1324                                 unset($p_status);
1325                         }
1326
1327                         if ( !empty($r_status) ) {
1328                                 if ( !empty($q['perm'] ) && 'editable' == $q['perm'] && !current_user_can("edit_others_{$post_type}s") )
1329                                         $statuswheres[] = "($wpdb->posts.post_author = $user_ID " .  "AND (" . join( ' OR ', $r_status ) . "))";
1330                                 else
1331                                         $statuswheres[] = "(" . join( ' OR ', $r_status ) . ")";
1332                         }
1333                         if ( !empty($p_status) ) {
1334                                 if ( !empty($q['perm'] ) && 'readable' == $q['perm'] && !current_user_can("read_private_{$post_type}s") )
1335                                         $statuswheres[] = "($wpdb->posts.post_author = $user_ID " .  "AND (" . join( ' OR ', $p_status ) . "))";
1336                                 else
1337                                         $statuswheres[] = "(" . join( ' OR ', $p_status ) . ")";
1338                         }
1339                         if ( $post_status_join ) {
1340                                 $join .= " LEFT JOIN $wpdb->posts AS p2 ON ($wpdb->posts.post_parent = p2.ID) ";
1341                                 foreach ( $statuswheres as $index => $statuswhere )
1342                                         $statuswheres[$index] = "($statuswhere OR ($wpdb->posts.post_status = 'inherit' AND " . str_replace($wpdb->posts, 'p2', $statuswhere) . "))";
1343                         }
1344                         foreach ( $statuswheres as $statuswhere )
1345                                 $where .= " AND $statuswhere";
1346                 } elseif ( !$this->is_singular ) {
1347                         $where .= " AND ($wpdb->posts.post_status = 'publish'";
1348
1349                         if ( is_admin() )
1350                                 $where .= " OR $wpdb->posts.post_status = 'future' OR $wpdb->posts.post_status = 'draft' OR $wpdb->posts.post_status = 'pending'";
1351
1352                         if ( is_user_logged_in() ) {
1353                                 $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'";
1354                         }
1355
1356                         $where .= ')';
1357                 }
1358
1359                 // postmeta queries
1360                 if ( ! empty($q['meta_key']) || ! empty($q['meta_value']) )
1361                         $join .= " LEFT JOIN $wpdb->postmeta ON ($wpdb->posts.ID = $wpdb->postmeta.post_id) ";
1362                 if ( ! empty($q['meta_key']) ) 
1363                         $where .= $wpdb->prepare("AND $wpdb->postmeta.meta_key = %s ", $q['meta_key']);
1364                 if ( ! empty($q['meta_value']) )
1365                         $where .= $wpdb->prepare("AND $wpdb->postmeta.meta_value = %s ", $q['meta_value']);
1366
1367                 // Apply filters on where and join prior to paging so that any
1368                 // manipulations to them are reflected in the paging by day queries.
1369                 if ( !$q['suppress_filters'] ) {
1370                         $where = apply_filters('posts_where', $where);
1371                         $join = apply_filters('posts_join', $join);
1372                 }
1373
1374                 // Paging
1375                 if ( empty($q['nopaging']) && !$this->is_singular ) {
1376                         $page = absint($q['paged']);
1377                         if (empty($page)) {
1378                                 $page = 1;
1379                         }
1380
1381                         if ( empty($q['offset']) ) {
1382                                 $pgstrt = '';
1383                                 $pgstrt = ($page - 1) * $q['posts_per_page'] . ', ';
1384                                 $limits = 'LIMIT '.$pgstrt.$q['posts_per_page'];
1385                         } else { // we're ignoring $page and using 'offset'
1386                                 $q['offset'] = absint($q['offset']);
1387                                 $pgstrt = $q['offset'] . ', ';
1388                                 $limits = 'LIMIT ' . $pgstrt . $q['posts_per_page'];
1389                         }
1390                 }
1391
1392                 // Comments feeds
1393                 if ( $this->is_comment_feed && ( $this->is_archive || $this->is_search || !$this->is_singular ) ) {
1394                         if ( $this->is_archive || $this->is_search ) {
1395                                 $cjoin = "LEFT JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID = $wpdb->posts.ID) $join ";
1396                                 $cwhere = "WHERE comment_approved = '1' $where";
1397                                 $cgroupby = "GROUP BY $wpdb->comments.comment_id";
1398                         } else { // Other non singular e.g. front
1399                                 $cjoin = "LEFT JOIN $wpdb->posts ON ( $wpdb->comments.comment_post_ID = $wpdb->posts.ID )";
1400                                 $cwhere = "WHERE post_status = 'publish' AND comment_approved = '1'";
1401                                 $cgroupby = '';
1402                         }
1403
1404                         if ( !$q['suppress_filters'] ) {
1405                                 $cjoin = apply_filters('comment_feed_join', $cjoin);
1406                                 $cwhere = apply_filters('comment_feed_where', $cwhere);
1407                                 $cgroupby = apply_filters('comment_feed_groupby', $cgroupby);
1408                         }
1409
1410                         $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'));
1411                         $this->comment_count = count($this->comments);
1412
1413                         $post_ids = array();
1414
1415                         foreach ($this->comments as $comment)
1416                                 $post_ids[] = (int) $comment->comment_post_ID;
1417
1418                         $post_ids = join(',', $post_ids);
1419                         $join = '';
1420                         if ( $post_ids )
1421                                 $where = "AND $wpdb->posts.ID IN ($post_ids) ";
1422                         else
1423                                 $where = "AND 0";
1424                 }
1425
1426                 $orderby = $q['orderby'];
1427
1428                 // Apply post-paging filters on where and join.  Only plugins that
1429                 // manipulate paging queries should use these hooks.
1430                 if ( !$q['suppress_filters'] ) {
1431                         $where = apply_filters('posts_where_paged', $where);
1432                         $groupby = apply_filters('posts_groupby', $groupby);
1433                         $join = apply_filters('posts_join_paged', $join);
1434                         $orderby = apply_filters('posts_orderby', $orderby);
1435                         $distinct = apply_filters('posts_distinct', $distinct);
1436                         $fields = apply_filters('posts_fields', $fields);
1437                         $limits = apply_filters( 'post_limits', $limits );
1438                 }
1439
1440                 // Announce current selection parameters.  For use by caching plugins.
1441                 do_action( 'posts_selection', $where . $groupby . $orderby . $limits . $join );
1442
1443                 // Filter again for the benefit of caching plugins.  Regular plugins should use the hooks above.
1444                 if ( !$q['suppress_filters'] ) {
1445                         $where = apply_filters('posts_where_request', $where);
1446                         $groupby = apply_filters('posts_groupby_request', $groupby);
1447                         $join = apply_filters('posts_join_request', $join);
1448                         $orderby = apply_filters('posts_orderby_request', $orderby);
1449                         $distinct = apply_filters('posts_distinct_request', $distinct);
1450                         $fields = apply_filters('posts_fields_request', $fields);
1451                         $limits = apply_filters( 'post_limits_request', $limits );
1452                 }
1453
1454                 if ( ! empty($groupby) )
1455                         $groupby = 'GROUP BY ' . $groupby;
1456                 if ( !empty( $orderby ) )
1457                         $orderby = 'ORDER BY ' . $orderby;
1458                 $found_rows = '';
1459                 if ( !empty($limits) )
1460                         $found_rows = 'SQL_CALC_FOUND_ROWS';
1461
1462                 $this->request = " SELECT $found_rows $distinct $fields FROM $wpdb->posts $join WHERE 1=1 $where $groupby $orderby $limits";
1463                 if ( !$q['suppress_filters'] )
1464                         $this->request = apply_filters('posts_request', $this->request);
1465
1466                 $this->posts = $wpdb->get_results($this->request);
1467                 // Raw results filter.  Prior to status checks.
1468                 if ( !$q['suppress_filters'] )
1469                         $this->posts = apply_filters('posts_results', $this->posts);
1470
1471                 if ( !empty($this->posts) && $this->is_comment_feed && $this->is_singular ) {
1472                         $cjoin = apply_filters('comment_feed_join', '');
1473                         $cwhere = apply_filters('comment_feed_where', "WHERE comment_post_ID = '{$this->posts[0]->ID}' AND comment_approved = '1'");
1474                         $comments_request = "SELECT $wpdb->comments.* FROM $wpdb->comments $cjoin $cwhere ORDER BY comment_date_gmt DESC LIMIT " . get_option('posts_per_rss');
1475                         $this->comments = $wpdb->get_results($comments_request);
1476                         $this->comment_count = count($this->comments);
1477                 }
1478
1479                 if ( !empty($limits) ) {
1480                         $found_posts_query = apply_filters( 'found_posts_query', 'SELECT FOUND_ROWS()' );
1481                         $this->found_posts = $wpdb->get_var( $found_posts_query );
1482                         $this->found_posts = apply_filters( 'found_posts', $this->found_posts );
1483                         $this->max_num_pages = ceil($this->found_posts / $q['posts_per_page']);
1484                 }
1485
1486                 // Check post status to determine if post should be displayed.
1487                 if ( !empty($this->posts) && ($this->is_single || $this->is_page) ) {
1488                         $status = get_post_status($this->posts[0]);
1489                         //$type = get_post_type($this->posts[0]);
1490                         if ( ('publish' != $status) ) {
1491                                 if ( ! is_user_logged_in() ) {
1492                                         // User must be logged in to view unpublished posts.
1493                                         $this->posts = array();
1494                                 } else {
1495                                         if  (in_array($status, array('draft', 'pending')) ) {
1496                                                 // User must have edit permissions on the draft to preview.
1497                                                 if (! current_user_can('edit_post', $this->posts[0]->ID)) {
1498                                                         $this->posts = array();
1499                                                 } else {
1500                                                         $this->is_preview = true;
1501                                                         $this->posts[0]->post_date = current_time('mysql');
1502                                                 }
1503                                         }  else if ('future' == $status) {
1504                                                 $this->is_preview = true;
1505                                                 if (!current_user_can('edit_post', $this->posts[0]->ID)) {
1506                                                         $this->posts = array ( );
1507                                                 }
1508                                         } else {
1509                                                 if (! current_user_can('read_post', $this->posts[0]->ID))
1510                                                         $this->posts = array();
1511                                         }
1512                                 }
1513                         }
1514                 }
1515
1516                 if ( !$q['suppress_filters'] )
1517                         $this->posts = apply_filters('the_posts', $this->posts);
1518
1519                 update_post_caches($this->posts);
1520
1521                 $this->post_count = count($this->posts);
1522                 if ($this->post_count > 0) {
1523                         $this->post = $this->posts[0];
1524                 }
1525
1526                 return $this->posts;
1527         }
1528
1529         function next_post() {
1530
1531                 $this->current_post++;
1532
1533                 $this->post = $this->posts[$this->current_post];
1534                 return $this->post;
1535         }
1536
1537         function the_post() {
1538                 global $post;
1539                 $this->in_the_loop = true;
1540                 $post = $this->next_post();
1541                 setup_postdata($post);
1542
1543                 if ( $this->current_post == 0 ) // loop has just started
1544                         do_action('loop_start');
1545         }
1546
1547         function have_posts() {
1548                 if ($this->current_post + 1 < $this->post_count) {
1549                         return true;
1550                 } elseif ($this->current_post + 1 == $this->post_count && $this->post_count > 0) {
1551                         do_action('loop_end');
1552                         // Do some cleaning up after the loop
1553                         $this->rewind_posts();
1554                 }
1555
1556                 $this->in_the_loop = false;
1557                 return false;
1558         }
1559
1560         function rewind_posts() {
1561                 $this->current_post = -1;
1562                 if ($this->post_count > 0) {
1563                         $this->post = $this->posts[0];
1564                 }
1565         }
1566
1567         function next_comment() {
1568                 $this->current_comment++;
1569
1570                 $this->comment = $this->comments[$this->current_comment];
1571                 return $this->comment;
1572         }
1573
1574         function the_comment() {
1575                 global $comment;
1576
1577                 $comment = $this->next_comment();
1578
1579                 if ($this->current_comment == 0) {
1580                         do_action('comment_loop_start');
1581                 }
1582         }
1583
1584         function have_comments() {
1585                 if ($this->current_comment + 1 < $this->comment_count) {
1586                         return true;
1587                 } elseif ($this->current_comment + 1 == $this->comment_count) {
1588                         $this->rewind_comments();
1589                 }
1590
1591                 return false;
1592         }
1593
1594         function rewind_comments() {
1595                 $this->current_comment = -1;
1596                 if ($this->comment_count > 0) {
1597                         $this->comment = $this->comments[0];
1598                 }
1599         }
1600
1601         function &query($query) {
1602                 $this->parse_query($query);
1603                 return $this->get_posts();
1604         }
1605
1606         function get_queried_object() {
1607                 if (isset($this->queried_object)) {
1608                         return $this->queried_object;
1609                 }
1610
1611                 $this->queried_object = NULL;
1612                 $this->queried_object_id = 0;
1613
1614                 if ($this->is_category) {
1615                         $cat = $this->get('cat');
1616                         $category = &get_category($cat);
1617                         $this->queried_object = &$category;
1618                         $this->queried_object_id = (int) $cat;
1619                 } else if ($this->is_tag) {
1620                         $tag_id = $this->get('tag_id');
1621                         $tag = &get_term($tag_id, 'post_tag');
1622                         if ( is_wp_error( $tag ) )
1623                                 return $tag;
1624                         $this->queried_object = &$tag;
1625                         $this->queried_object_id = (int) $tag_id;
1626                 } else if ($this->is_tax) {
1627                         $tax = $this->get('taxonomy');
1628                         $slug = $this->get('term');
1629                         $term = &get_terms($tax, array('slug'=>$slug));
1630                         if ( is_wp_error($term) || empty($term) )
1631                                 return $term;
1632                         $term = $term[0];
1633                         $this->queried_object = $term;
1634                         $this->queried_object_id = $term->term_id;
1635                 } else if ($this->is_posts_page) {
1636                         $this->queried_object = & get_page(get_option('page_for_posts'));
1637                         $this->queried_object_id = (int) $this->queried_object->ID;
1638                 } else if ($this->is_single) {
1639                         $this->queried_object = $this->post;
1640                         $this->queried_object_id = (int) $this->post->ID;
1641                 } else if ($this->is_page) {
1642                         $this->queried_object = $this->post;
1643                         $this->queried_object_id = (int) $this->post->ID;
1644                 } else if ($this->is_author) {
1645                         $author_id = (int) $this->get('author');
1646                         $author = get_userdata($author_id);
1647                         $this->queried_object = $author;
1648                         $this->queried_object_id = $author_id;
1649                 }
1650
1651                 return $this->queried_object;
1652         }
1653
1654         function get_queried_object_id() {
1655                 $this->get_queried_object();
1656
1657                 if (isset($this->queried_object_id)) {
1658                         return $this->queried_object_id;
1659                 }
1660
1661                 return 0;
1662         }
1663
1664         function WP_Query ($query = '') {
1665                 if (! empty($query)) {
1666                         $this->query($query);
1667                 }
1668         }
1669 }
1670
1671
1672 // Redirect old slugs
1673 function wp_old_slug_redirect () {
1674         global $wp_query;
1675         if ( is_404() && '' != $wp_query->query_vars['name'] ) :
1676                 global $wpdb;
1677
1678                 $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'] . "'";
1679
1680                 // if year, monthnum, or day have been specified, make our query more precise
1681                 // just in case there are multiple identical _wp_old_slug values
1682                 if ( '' != $wp_query->query_vars['year'] )
1683                         $query .= " AND YEAR(post_date) = '{$wp_query->query_vars['year']}'";
1684                 if ( '' != $wp_query->query_vars['monthnum'] )
1685                         $query .= " AND MONTH(post_date) = '{$wp_query->query_vars['monthnum']}'";
1686                 if ( '' != $wp_query->query_vars['day'] )
1687                         $query .= " AND DAYOFMONTH(post_date) = '{$wp_query->query_vars['day']}'";
1688
1689                 $id = (int) $wpdb->get_var($query);
1690
1691                 if ( !$id )
1692                         return;
1693
1694                 $link = get_permalink($id);
1695
1696                 if ( !$link )
1697                         return;
1698
1699                 wp_redirect($link, '301'); // Permanent redirect
1700                 exit;
1701         endif;
1702 }
1703
1704
1705 //
1706 // Private helper functions
1707 //
1708
1709 // Setup global post data.
1710 function setup_postdata($post) {
1711         global $id, $authordata, $day, $currentmonth, $page, $pages, $multipage, $more, $numpages;
1712
1713         $id = (int) $post->ID;
1714
1715         $authordata = get_userdata($post->post_author);
1716
1717         $day = mysql2date('d.m.y', $post->post_date);
1718         $currentmonth = mysql2date('m', $post->post_date);
1719         $numpages = 1;
1720         $page = get_query_var('page');
1721         if ( !$page )
1722                 $page = 1;
1723         if ( is_single() || is_page() || is_feed() )
1724                 $more = 1;
1725         $content = $post->post_content;
1726         if ( preg_match('/<!--nextpage-->/', $content) ) {
1727                 if ( $page > 1 )
1728                         $more = 1;
1729                 $multipage = 1;
1730                 $content = str_replace("\n<!--nextpage-->\n", '<!--nextpage-->', $content);
1731                 $content = str_replace("\n<!--nextpage-->", '<!--nextpage-->', $content);
1732                 $content = str_replace("<!--nextpage-->\n", '<!--nextpage-->', $content);
1733                 $pages = explode('<!--nextpage-->', $content);
1734                 $numpages = count($pages);
1735         } else {
1736                 $pages[0] = $post->post_content;
1737                 $multipage = 0;
1738         }
1739         return true;
1740 }
1741
1742 ?>