root/branches/release-40/php/lib/mtdb_base.php @ 2589

Revision 2589, 122.5 kB (checked in by takayama, 18 months ago)

Fixed BugId:80146
* Applied patch (again..)

  • Property svn:keywords set to Author Date Id Revision
Line 
1<?php
2# Movable Type (r) Open Source (C) 2001-2008 Six Apart, Ltd.
3# This program is distributed under the terms of the
4# GNU General Public License, version 2.
5#
6# $Id$
7
8class MTDatabaseBase extends ezsql {
9    var $savedqueries = array();
10    var $_entry_id_cache = array();
11    var $_author_id_cache = array();
12    var $_comment_count_cache = array();
13    var $_ping_count_cache = array();
14    var $_cat_id_cache = array();
15    var $_tag_id_cache = array();
16    var $_blog_id_cache = array();
17    var $_entry_link_cache = array();
18    var $_cat_link_cache = array();
19    var $_archive_link_cache = array();
20    var $_entry_tag_cache = array();
21    var $_blog_tag_cache = array();
22    var $_asset_tag_cache = array();
23    var $_blog_asset_tag_cache = array();
24    var $serializer;
25    var $id;
26
27    ## temporary until we class our objects properly
28    var $object_meta = array(
29        'blog' => array(
30            'commenter_authenticators:vchar',
31            'nofollow_urls:vinteger',
32            'follow_auth_links:vinteger',
33            'captcha_provider:vchar',
34            'template_set:vchar',
35            'page_layout:vchar',
36            'include_system:vinteger',
37            'include_cache:vinteger'),
38        'template' => array(
39            'page_layout:vchar',
40            'include_with_ssi:vinteger',
41            'cache_expire_type:vinteger',
42            'cache_expire_interval:vinteger',
43            'cache_expire_event:vchar'),
44        'asset' => array('image_width:vinteger',
45            'image_height:vinteger')
46    );
47    var $_meta_cache = array();
48
49    function MTDatabaseBase($dbuser, $dbpassword = '', $dbname = '',
50        $dbhost = '', $dbport = '', $dbsocket = '') {
51        $this->id = md5(uniqid('MTDatabaseBase',true));
52        $this->hide_errors();
53        $this->db($dbuser, $dbpassword, $dbname, $dbhost, $dbport, $dbsocket);
54    }
55
56    function unserialize($data) {
57        if (!$this->serializer) {
58            require_once("MTSerialize.php");
59            $this->serializer =& new MTSerialize();
60        }
61        return $this->serializer->unserialize($data);
62    }
63
64    function query($query) {
65        $this->savedqueries[] = $query;
66        parent::query($query);
67    }
68
69    function &resolve_url($path, $blog_id) {
70        $path = preg_replace('!/$!', '', $path);
71        $path = $this->escape($path);
72        $blog_id = intval($blog_id);
73        # resolve for $path -- one of:
74        #      /path/to/file.html
75        #      /path/to/index.html
76        #      /path/to/
77        #      /path/to
78        global $mt;
79        $index = $this->escape($mt->config('IndexBasename'));
80        $escindex = $this->escape($index);
81        foreach ( array($path, urldecode($path), urlencode($path)) as $p ) {
82            $sql = "
83                select *
84                  from mt_blog, mt_template, mt_fileinfo
85                  left outer join mt_templatemap on templatemap_id = fileinfo_templatemap_id
86                 where fileinfo_blog_id = $blog_id
87                       and ((fileinfo_url = '%1\$s' or fileinfo_url = '%1\$s/') or (fileinfo_url like '%1\$s/$escindex%%'))
88                   and blog_id = fileinfo_blog_id
89                   and template_id = fileinfo_template_id
90                 order by length(fileinfo_url) asc
91            ";
92            $rows = $this->get_results(sprintf($sql,$p), ARRAY_A);
93            if ($rows) {
94                break;
95            }
96        }
97        $path = $p;
98        if (!$rows) return null;
99
100        $found = false;
101        foreach ($rows as $row) {
102            $fiurl = $row['fileinfo_url'];
103            if ($fiurl == $path) {
104                $found = true;
105                break;
106            }
107            if ($fiurl == "$path/") {
108                $found = true;
109                break;
110            }
111            $ext = $row['blog_file_extension'];
112            if (!empty($ext)) $ext = '.' . $ext;
113            if ($fiurl == ($path.'/'.$index.$ext)) {
114                $found = true; break;
115            }
116            if ($found) break;
117        }
118        if (!$found) return null;
119        $data = array();
120        foreach ($row as $key => $value) {
121            if (preg_match('/^([a-z]+)/', $key, $matches)) {
122                $data[$matches[1]][$key] = $value;
123            }
124        }
125        $this->_blog_id_cache[$data['blog']['blog_id']] =& $data['blog'];
126        return $data;
127    }
128
129    function fetch_blogs($args) {
130        if ($blog_ids = $this->include_exclude_blogs($args)) {
131            $where = ' where blog_id ' . $blog_ids;
132        }
133        $sql = 'select * from mt_blog'
134            . $where . ' order by blog_name';
135        $res = $this->get_results($sql, ARRAY_A);
136        return $res;
137    }
138
139    function fetch_templates($args) {
140        if (isset($args['type'])) {
141            $type_filter = 'and template_type = \'' . $this->escape($args['type']) . '\'';
142        }
143        if (isset($args['blog_id'])) {
144            $blog_filter = 'and template_blog_id = ' . intval($args['blog_id']);
145        }
146        $sql = "select *
147                  from mt_template
148                 where 1 = 1
149                       $blog_filter
150                       $type_filter
151              order by template_name";
152        $result = $this->get_results($sql, ARRAY_A);
153        return $result;
154    }
155
156    function fetch_template_meta($type, $name, $blog_id, $global) {
157        if ($type === 'identifier') {
158            $col = 'template_identifier';
159            $type_filter = "";
160        } else {
161            $col = 'template_name';
162            $type_filter = "and template_type='$type'";
163        }
164        if (!isset($global)) {
165            $blog_filter = "and template_blog_id in (".$this->escape($blog_id).",0)";
166        } elseif ($global) {
167            $blog_filter = "and template_blog_id=0";
168        } else {
169            $blog_filter = "and template_blog_id=".$this->escape($blog_id);
170        }
171
172        $tmpl_name = $this->escape($name);
173
174        $sql = "
175            select
176                template_id, template_name, template_modified_on
177            from
178                mt_template
179            where
180                $col = '$tmpl_name'
181                $blog_filter
182                $type_filter
183            order by
184                template_blog_id desc";
185        $row = $this->get_row($sql, ARRAY_A);
186        if (!$row) return '';
187
188        $data = $this->get_meta('template', $row['template_id']);
189        return array_merge($row, $data);
190    }
191
192    function load_index_template(&$ctx, $tmpl, $blog_id = null) {
193        return $this->load_special_template($ctx, $tmpl, 'index');
194    }
195
196    function load_special_template(&$ctx, $tmpl, $type, $blog_id = null) {
197        $blog_id or $blog_id = $ctx->stash('blog_id');
198        $tmpl_name = $this->escape($tmpl);
199        $sql = "select * from mt_template" .
200            " where template_blog_id=$blog_id ".
201            ($tmpl ? " and (template_name='". $tmpl_name . "'" .
202            " or template_outfile='" . $tmpl_name ."'" .
203            " or template_identifier='" . $tmpl_name . "')" : "").
204            " and template_type='".$this->escape($type)."'";
205        list($row) = $this->get_results($sql, ARRAY_A);
206        if (!$row) return null;
207        return $row;
208    }
209
210    function fetch_config() {
211        $sql = "select * from mt_config";
212        list($row) = $this->get_results($sql, ARRAY_A);
213        if (!$row) return null;
214        return $row;
215    }
216
217    function category_link($cid, $args = null) {
218        if (isset($this->_cat_link_cache[$cid])) {
219            $url = $this->_cat_link_cache[$cid];
220        } else {
221            $sql = "select fileinfo_url, fileinfo_blog_id
222                      from mt_fileinfo, mt_templatemap
223                     where fileinfo_category_id = $cid
224                       and fileinfo_archive_type = 'Category'
225                       and templatemap_id = fileinfo_templatemap_id
226                       and templatemap_is_preferred = 1";
227            $rows = $this->get_results($sql, ARRAY_A);
228            if (count($rows)) {
229                $link =& $rows[0];
230            } else {
231                return null;
232            }
233            $blog =& $this->fetch_blog($link['fileinfo_blog_id']);
234            $blog_url = $blog['blog_archive_url'];
235            $blog_url or $blog_url = $blog['blog_site_url'];
236            $blog_url = preg_replace('!(https?://(?:[^/]+))/.*!', '$1', $blog_url);
237            $url = $blog_url . $link['fileinfo_url'];
238            $url = _strip_index($url, $blog);
239            $this->_cat_link_cache[$cid] = $url;
240        }
241        return $url;
242    }
243
244    function archive_link($ts, $at, $sql, $args) {
245        $blog_id = intval($args['blog_id']);
246        if (isset($this->_archive_link_cache[$blog_id.';'.$ts.';'.$at])) {
247            $url = $this->_archive_link_cache[$blog_id.';'.$ts.';'.$at];
248        } else {
249            if ($sql == '') {
250                $sql = "select fileinfo_url
251                          from mt_fileinfo, mt_templatemap
252                         where fileinfo_startdate = '$ts'
253                           and fileinfo_blog_id = $blog_id
254                           and fileinfo_archive_type = '".$this->escape($at)."'
255                           and templatemap_id = fileinfo_templatemap_id
256                           and templatemap_is_preferred = 1";
257            }
258            $rows = $this->get_results($sql, ARRAY_A);
259            if (count($rows)) {
260                $link =& $rows[0];
261            } else {
262                return null;
263            }
264            $blog =& $this->fetch_blog($blog_id);
265            if ($at == 'Page') {
266                $blog_url = $blog['blog_site_url'];
267            } else {
268                $blog_url = $blog['blog_archive_url'];
269                $blog_url or $blog_url = $blog['blog_site_url'];
270            }
271            $blog_url = preg_replace('!(https?://(?:[^/]+))/.*!', '$1', $blog_url);
272            $url = $blog_url . $link['fileinfo_url'];
273            $url = _strip_index($url, $blog);
274            $this->_archive_link_cache[$ts.';'.$at] = $url;
275        }
276        return $url;
277    }
278
279    function entry_link($eid, $at = "Individual", $args = null) {
280        $blog_id = intval($args['blog_id']);
281        if (isset($this->_entry_link_cache[$eid.';'.$at])) {
282            $url = $this->_entry_link_cache[$eid.';'.$at];
283        } else {
284            if (preg_match('/Category/', $at)) {
285                $table = ", mt_placement";
286                $filter = "and placement_entry_id = $eid
287                           and fileinfo_category_id = placement_category_id
288                           and placement_is_primary = 1";
289            }
290            if (preg_match('/Page/', $at)) {
291                $entry = $this->fetch_page($eid);
292            } else {
293                $entry = $this->fetch_entry($eid);
294            }
295            $ts = $entry['entry_authored_on'];
296            if (preg_match('/Monthly$/', $at)) {
297                $ts = substr($ts, 0, 6) . '01000000';
298            } elseif (preg_match('/Daily$/', $at)) {
299                $ts = substr($ts, 0, 8) . '000000';
300            } elseif (preg_match('/Weekly$/', $at)) {
301                require_once("MTUtil.php");
302                list($ws, $we) = start_end_week($ts);
303                $ts = $ws;
304            } elseif (preg_match('/Yearly$/', $at)) {
305                $ts = substr($ts, 0, 4) . '0101000000';
306            } elseif ($at == 'Individual' || $at == 'Page') {
307                $filter .= "and fileinfo_entry_id = $eid";
308            }
309            if ($ts != $entry['entry_authored_on']) {
310                $filter .= " and fileinfo_startdate = '$ts'";
311            }
312            if (preg_match('/Author/', $at)) {
313                $filter .= " and fileinfo_author_id = ". $entry['entry_author_id'];
314            }
315            $sql = "select fileinfo_url, fileinfo_blog_id
316                     from mt_fileinfo, mt_templatemap $table
317                    where templatemap_id = fileinfo_templatemap_id
318                      and fileinfo_blog_id = $blog_id
319                      $filter
320                      and templatemap_archive_type = '$at'
321                      and templatemap_is_preferred = 1";
322            $rows = $this->get_results($sql, ARRAY_A);
323            if (count($rows)) {
324                $link =& $rows[0];
325            } else {
326                return null;
327            }
328            $blog =& $this->fetch_blog($link['fileinfo_blog_id']);
329            if ($at == 'Page') {
330                $blog_url = $blog['blog_site_url'];
331            } else {
332                $blog_url = $blog['blog_archive_url'];
333                $blog_url or $blog_url = $blog['blog_site_url'];
334            }
335            $blog_url = preg_replace('!(https?://(?:[^/]+))/.*!', '$1', $blog_url);
336            $url = $blog_url . $link['fileinfo_url'];
337            $url = _strip_index($url, $blog);
338            $this->_entry_link_cache[$eid.';'.$at] = $url;
339        }
340        if ($at != 'Individual' && $at != 'Page') {
341            if (!$args || !isset($args['no_anchor'])) {
342                $url .= '#' . (!$args || isset($args['valid_html']) ? 'a' : '') .
343                        sprintf("%06d", $eid);
344            }
345        }
346        return $url;
347    }
348
349    /* recreation of generic load method functionality from MT::Object */
350    function &load($class, $terms = null, $args = null) {
351        $sql = "select * from mt_$class";
352        $where = '';
353        if ($terms) {
354            if (is_array($terms)) {
355                foreach ($terms as $col => $val) {
356                    $column = $class . '_' . $col;
357                    if (isset($args['range']) && isset($args['range'][$col])) {
358                        $range = '';
359                        if (isset($val[0]))
360                            $range = "$column > '" . $this->escape($val[0]) . "' ";
361                        if (isset($val[1])) {
362                            if ($range != '') $range .= ' and ';
363                            $range .= "$column < '" . $this->escape($val[0]) . "'";
364                        }
365                        $where .= " and ($range)";
366                    } elseif (isset($args['range_incl']) && isset($args['range_incl'][$col])) {
367                        $range = '';
368                        if (isset($val[0]))
369                            $range = "$column >= '" . $this->escape($val[0]) . "' ";
370                        if (isset($val[1])) {
371                            if ($range != '') $range .= ' and ';
372                            $range .= "$column <= '" . $this->escape($val[0]) . "'";
373                        }
374                        $where .= " and ($range)";
375                    } else {
376                        if (is_array($val)) {
377                            $list = '';
378                            foreach ($val as $item) {
379                                if ($list != '') $list .= ',';
380                                $list .= "'" . $this->escape($item). "'";
381                            }
382                            $where .= " and ($column in ($list))";
383                        } else {
384                            $where .= " and ($column='".$this->escape($val)."')";
385                        }
386                    }
387                }
388                $where = preg_replace('/^ and/', '', $where);
389            } else {
390                $where = " ($class"."_id=".intval($terms).")";
391            }
392            $sql .= ' where ' . $where;
393        }
394        if (isset($args['sort']) or isset($args['direction'])) {
395            $order = $args['sort'];
396            $order or $order = 'id';
397            $dir = $args['direction'] == 'descend' ? 'desc' : 'asc';
398            $sql .= " order by " . $class . "_" . $order . " $dir";
399        }
400        if (isset($args['limit']) or isset($args['offset'])) {
401            $sql .= ' <LIMIT>';
402            $sql = $this->apply_limit_sql($sql, $args['limit'], $args['offset']);
403        }
404        return $this->get_results($sql, ARRAY_A);
405    }
406
407    function get_template_text($ctx, $module, $blog_id = null, $type = 'custom', $global = null) {
408        $blog_id or $blog_id = $ctx->stash('blog_id');
409        if ($type === 'custom' || $type === 'widget'|| $type === 'widgetset') {
410            $col = 'template_name';
411            $type_filter = "and template_type='$type'";
412        } else {
413            $col = 'template_identifier';
414            $type_filter = "";
415        }
416        if (!isset($global)) {
417            $blog_filter = "template_blog_id in (".$this->escape($blog_id).",0)";
418        } elseif ($global) {
419            $blog_filter = "template_blog_id=0";
420        } else {
421            $blog_filter = "template_blog_id=".$this->escape($blog_id);
422        }
423        $row = $this->get_row("
424            select template_text, template_modified_on, template_linked_file, template_linked_file_mtime, template_linked_file_size
425              from mt_template
426             where $blog_filter
427               and $col='".$this->escape($module)."'
428               $type_filter
429               order by template_blog_id desc", ARRAY_N);
430        if (!$row) return '';
431        list($tmpl, $ts, $file, $mtime, $size) = $row;
432        if ($file) {
433            if (!file_exists($file)) {
434                $blog = $ctx->stash('blog');
435                if ($blog['blog_id'] != $blog_id) {
436                    $blog = $this->fetch_blog($blog_id);
437                }
438                $path = $blog['blog_site_path'];
439                if (!preg_match('![\\/]$!', $path))
440                    $path .= '/';
441                $path .= $file;
442                if (is_file($path) && is_readable($path))
443                    $file = $path;
444                else
445                    $file = '';
446            }
447            if ($file) {
448                if ((filemtime($file) > $mtime) || (filesize($file) != $size)) {
449                    $contents = @file($file);
450                    $tmpl = implode('', $contents);
451                }
452            }
453        }
454        return $tmpl;
455    }
456
457    function &fetch_pages($args) {
458        $args['class'] = 'page';
459        return $this->fetch_entries($args);
460    }
461
462    function &fetch_entries($args, $total_count = NULL) {
463        if ($sql = $this->include_exclude_blogs($args)) {
464            $blog_filter = 'and entry_blog_id ' . $sql;
465        } elseif (isset($args['blog_id'])) {
466            $blog_id = intval($args['blog_id']);
467            $blog_filter = 'and entry_blog_id = ' . $blog_id;
468            $blog = $this->fetch_blog($blog_id);
469        }
470
471        if ( !$blog ) {
472            global $mt;
473            $blog = $this->fetch_blog($mt->blog_id);
474        }
475
476        // determine any custom fields that we should filter on
477        $fields = array();
478        foreach ($args as $name => $v)
479            if (preg_match('/^field___(\w+)$/', $name, $m))
480                $fields[$m[1]] = $v;
481
482        # automatically include offset if in request
483        if ($args['offset'] == 'auto') {
484            $args['offset'] = 0;
485            if ($args['limit'] || $args['lastn']) {
486                if ($_REQUEST['offset'] > 0) {
487                    $args['offset'] = $_REQUEST['offset'];
488                }
489            }
490        }
491
492        if ($args['limit'] > 0) {
493            $args['lastn'] = $args['limit'];
494        } elseif (!isset($args['days']) && !isset($args['lastn'])) {
495#            if ($days = $blog['blog_days_on_index']) {
496#                if (!isset($args['recently_commented_on'])) {
497#                    $args['days'] = $days;
498#                }
499#            } elseif ($posts = $blog['blog_entries_on_index']) {
500#                $args['lastn'] = $posts;
501#            }
502        }
503        if ($args['limit'] == 'auto') {
504            if (($_REQUEST['limit'] > 0) && ($_REQUEST['limit'] < $args['lastn'])) {
505                $args['lastn'] = intval($_REQUEST['limit']);
506            } elseif (!isset($args['days']) && !isset($args['lastn'])) {
507               if ($days = $blog['blog_days_on_index']) {
508                    if (!isset($args['recently_commented_on'])) {
509                        $args['days'] = $days;
510                    }
511                } elseif ($posts = $blog['blog_entries_on_index']) {
512                    $args['lastn'] = $posts;
513                }           
514            }
515        }
516
517        if (isset($args['include_blogs']) or isset($args['exclude_blogs'])) {
518            $blog_ctx_arg = isset($args['include_blogs']) ?
519                array('include_blogs' => $args['include_blogs']) :
520                array('exclude_blogs' => $args['exclude_blogs']);
521        }
522
523        # a context hash for filter routines
524        $ctx = array();
525        $filters = array();
526
527        if (!isset($_REQUEST['entry_ids_published'])) {
528            $_REQUEST['entry_ids_published'] = array();
529        }
530
531        if (isset($args['unique'])) {
532            $filters[] = create_function('$e,$ctx', 'return !isset($ctx["entry_ids_published"][$e["entry_id"]]);');
533            $ctx['entry_ids_published'] = &$_REQUEST['entry_ids_published'];
534        }
535
536        # special case for selecting a particular entry
537        if (isset($args['entry_id'])) {
538            $entry_filter = 'and entry_id = '.$args['entry_id'];
539            $start = ''; $end = ''; $limit = 1; $blog_filter = ''; $day_filter = '';
540        } else {
541            $entry_filter = '';
542        }
543
544        # special case for excluding a particular entry
545        if (isset($args['not_entry_id'])) {
546            $entry_filter .= ' and entry_id != '.$args['not_entry_id'];
547        }
548
549        $entry_list = array();
550
551        # Adds a category filter to the filters list.
552        $cat_class = 'category';
553        if (!isset($args['class']))
554            $args['class'] = 'entry';
555        if ($args['class'] == 'page')
556            $cat_class = 'folder';
557
558        if (isset($args['category']) or isset($args['categories'])) {
559            $category_arg = isset($args['category']) ? $args['category'] : $args['categories'];
560            require_once("MTUtil.php");
561            if (!preg_match('/\b(AND|OR|NOT)\b|\(|\)/i', $category_arg)) {
562                $not_clause = false;
563                $cats = cat_path_to_category($category_arg, $blog_ctx_arg, $cat_class);
564                if (count($cats)) {
565                    $category_arg = '';
566                    foreach ($cats as $cat) {
567                        if ($category_arg != '')
568                            $category_arg .= '|| ';
569                        $category_arg .= '#' . $cat['category_id'];
570                    }
571                    $category_arg = '(' . $category_arg . ')';
572                }
573            } else {
574                $not_clause = preg_match('/\bNOT\b/i', $category_arg);
575                if ($blog_ctx_arg)
576                    $cats =& $this->fetch_categories(array_merge($blog_ctx_arg, array('show_empty' => 1, 'class' => $cat_class)));
577                else
578                    $cats =& $this->fetch_categories(array('blog_id' => $blog_id, 'show_empty' => 1, 'class' => $cat_class));
579            }
580            if (!is_array($cats)) $cats = array();
581            $cexpr = create_cat_expr_function($category_arg, $cats, array('children' => $args['include_subcategories']));
582            if ($cexpr) {
583                $cmap = array();
584                $cat_list = array();
585                foreach ($cats as $cat)
586                    $cat_list[] = $cat['category_id'];
587                $pl =& $this->fetch_placements(array('category_id' => $cat_list));
588                if ($pl) {
589                    foreach ($pl as $p) {
590                        $cmap[$p['placement_entry_id']][$p['placement_category_id']]++;
591                        if (!$not_clause)
592                            $entry_list[$p['placement_entry_id']] = 1;
593                    }
594                }
595                $ctx['p'] =& $cmap;
596                $filters[] = $cexpr;
597            } else {
598                return null;
599            }
600        } elseif (isset($args['category_id'])) {
601            require_once("MTUtil.php");
602            $cat = $this->fetch_category($args['category_id']);
603            if ($cat) {
604                $cats = array($cat);
605                $cmap = array();
606                $cexpr = create_cat_expr_function($cat['category_label'], $cats, array('children' => $args['include_subcategories']));
607                $pl =& $this->fetch_placements(array('category_id' => array($cat['category_id'])));
608                if ($pl) {
609                    foreach ($pl as $p) {
610                        $cmap[$p['placement_entry_id']][$p['placement_category_id']]++;
611                    }
612                    $ctx['p'] =& $cmap;
613                    $filters[] = $cexpr;
614                } else {
615                    # this category have no entries (or pages)
616                    return null;
617                }
618            }
619        }
620        if ((0 == count($filters)) && (isset($args['show_empty']) && (1 == $args['show_empty']))) {
621            return null;
622        }
623
624        # Adds a tag filter to the filters list.
625        if (isset($args['tags']) or isset($args['tag'])) {
626            $tag_arg = isset($args['tag']) ? $args['tag'] : $args['tags'];
627            require_once("MTUtil.php");
628            $not_clause = preg_match('/\bNOT\b/i', $tag_arg);
629
630            require_once("MTUtil.php");
631            $include_private = 0;
632            $tag_array = tag_split($tag_arg);
633            foreach ($tag_array as $tag) {
634                if ($tag && (substr($tag,0,1) == '@')) {
635                    $include_private = 1;
636                }
637            }
638            if (isset($blog_ctx_arg))
639                $tags =& $this->fetch_entry_tags(array($blog_ctx_arg, 'tag' => $tag_arg, 'include_private' => $include_private, 'class' => $args['class']));
640            else
641                $tags =& $this->fetch_entry_tags(array('blog_id' => $blog_id, 'tag' => $tag_arg, 'include_private' => $include_private, 'class' => $args['class']));
642            if (!is_array($tags)) $tags = array();
643            $cexpr = create_tag_expr_function($tag_arg, $tags);
644
645            if ($cexpr) {
646                $tmap = array();
647                $tag_list = array();
648                foreach ($tags as $tag) {
649                    $tag_list[] = $tag['tag_id'];
650                }
651                if (isset($blog_ctx_arg))
652                    $ot =& $this->fetch_objecttags(array('tag_id' => $tag_list, 'datasource' => 'entry', $blog_ctx_arg));
653                elseif ($args['blog_id'])
654                    $ot =& $this->fetch_objecttags(array('tag_id' => $tag_list, 'datasource' => 'entry', 'blog_id' => $args['blog_id']));
655                if ($ot) {
656                    foreach ($ot as $o) {
657                            $tmap[$o['objecttag_object_id']][$o['objecttag_tag_id']]++;
658                        if (!$not_clause)
659                            $entry_list[$o['objecttag_object_id']] = 1;
660                    }
661                }
662                $ctx['t'] =& $tmap;
663                $filters[] = $cexpr;
664            } else {
665                return null;
666            }
667        }
668
669        # Adds a score or rate filter to the filters list.
670        if (isset($args['namespace'])) {
671            require_once("MTUtil.php");
672            $arg_names = array('min_score', 'max_score', 'min_rate', 'max_rate', 'min_count', 'max_count' );
673            foreach ($arg_names as $n) {
674                if (isset($args[$n])) {
675                    $rating_args = $args[$n];
676                    $cexpr = create_rating_expr_function($rating_args, $n, $args['namespace']);
677                    if ($cexpr) {
678                        $filters[] = $cexpr;
679                    } else {
680                        return null;
681                    }
682                }
683            }
684
685            if (isset($args['scored_by'])) {
686                $voter = $this->fetch_author_by_name($args['scored_by']);
687                if (!$voter) {
688                    echo "Invalid scored by filter: ".$args['scored_by'];
689                    return null;
690                }
691                $cexpr = create_rating_expr_function($voter['author_id'], 'scored_by', $args['namespace']);
692                if ($cexpr) {
693                    $filters[] = $cexpr;
694                } else {
695                    return null;
696                }
697            }
698        }
699
700        if (count($entry_list) && ($entry_filter == '')) {
701            $entry_list = implode(",", array_keys($entry_list));
702            # set a reasonable cap on the entry list cache. if
703            # user is selecting something too big, then they'll
704            # just have to wait through a scan.
705            if (strlen($entry_list) < 2048)
706                $entry_filter = "and entry_id in ($entry_list)";
707        }
708
709        if (isset($args['author']))
710            $author_filter = 'and author_name = \'' .
711                $this->escape($args['author']) . "'";
712
713        $start = isset($args['current_timestamp'])
714            ? $args['current_timestamp'] : null;
715        $end = isset($args['current_timestamp_end'])
716            ? $args['current_timestamp_end'] : null;
717        if ($start and $end) {
718            $start = $this->ts2db($start);
719            $end = $this->ts2db($end);
720            $date_filter = "and entry_authored_on between '$start' and '$end'";
721        } elseif ($start) {
722            $start = $this->ts2db($start);
723            $date_filter = "and entry_authored_on >= '$start'";
724        } elseif ($end) {
725            $end = $this->ts2db($end);
726            $date_filter = "and entry_authored_on <= '$end'";
727        } else {
728            $date_filter = '';
729        }
730
731        if (isset($args['lastn'])) {
732            if (!isset($args['entry_id'])) $limit = $args['lastn'];
733        } elseif (isset($args['days']) && !$date_filter) {
734            $day_filter = 'and ' . $this->limit_by_day_sql('entry_authored_on', intval($args['days']));
735        } else {
736            $found_valid_args = 0;
737            foreach ( array(
738                'lastn', 'days',
739                'category', 'categories', 'category_id',
740                'tag', 'tags',
741                'author',
742                'min_score',  'max_score',
743                'min_rate',    'max_rate',
744                'min_count',  'max_count'
745              ) as $valid_key )
746            {
747                if (array_key_exists($valid_key, $args)) {
748                    $found_valid_args = 1;
749                    break;
750                }
751            }
752            if ((!isset($args['current_timestamp']) &&
753                !isset($args['current_timestamp_end'])) &&
754                ($limit <= 0) &&
755                (!$found_valid_args) &&
756                (isset($blog))) {
757                if ($days = $blog['blog_days_on_index']) {
758                    if (!isset($args['recently_commented_on'])) {
759                        $day_filter = 'and ' . $this->limit_by_day_sql('entry_authored_on', $days);
760                    }
761                } elseif ($posts = $blog['blog_entries_on_index']) {
762                    $limit = $posts;
763                }
764            }
765        }
766
767        if (isset($args['sort_order'])) {
768            if ($args['sort_order'] == 'ascend') {
769                $order = 'asc';
770            } else if ($args['sort_order'] == 'descend') {
771                $order = 'desc';
772            }
773        } 
774        if (!isset($order)) {
775            $order = 'desc';
776            if (isset($blog) && isset($blog['blog_sort_order_posts'])) {
777                if ($blog['blog_sort_order_posts'] == 'ascend') {
778                    $order = 'asc';
779                }
780            }
781        }
782
783        if (isset($args['class'])) {
784            $class = $this->escape($args['class']);
785        } else {
786            $class = 'entry';
787        }
788        $class_filter = "and entry_class='$class'";
789        if ($args['class'] == '*') $class_filter = '';
790       
791        $join_score = "";
792        $distinct = "";
793        if ( isset($args['sort_by'])
794          && (($args['sort_by'] == 'score') || ($args['sort_by'] == 'rate')) ) {
795            $join_score = "left join mt_objectscore on objectscore_object_id = entry_id and objectscore_namespace='"
796                . $args['namespace']."' and objectscore_object_ds='".$class."'";
797            $distinct = " distinct";
798        }
799
800        if (isset($args['offset']))
801            $offset = $args['offset'];
802
803        if (isset($args['limit'])) {
804            if (isset($args['sort_by'])) { 
805                if ($args['sort_by'] == 'title') { 
806                    $sort_field = 'entry_title'; 
807                } elseif ($args['sort_by'] == 'id') { 
808                    $sort_field = 'entry_id'; 
809                } elseif ($args['sort_by'] == 'status') { 
810                    $sort_field = 'entry_status'; 
811                } elseif ($args['sort_by'] == 'modified_on') { 
812                    $sort_field = 'entry_modified_on'; 
813                } elseif ($args['sort_by'] == 'author_id') { 
814                    $sort_field = 'entry_author_id'; 
815                } elseif ($args['sort_by'] == 'excerpt') { 
816                    $sort_field = 'entry_excerpt'; 
817                } elseif ($args['sort_by'] == 'comment_created_on') { 
818                    $sort_field = $args['sort_by']; 
819                } elseif ($args['sort_by'] == 'score' || $args['sort_by'] == 'rate') { 
820                    $post_sort_limit = $limit;
821                    $post_sort_offset = $offset;
822                    $limit = 0; $offset = 0;
823                } elseif ($args['sort_by'] == 'trackback_count') {
824                    $sort_field = 'entry_ping_count'; 
825                } elseif (preg_match('/field[:\.]/', $args['sort_by'])) {
826                    $no_resort = 0;
827                } else { 
828                    $sort_field = 'entry_' . $args['sort_by']; 
829                } 
830                if ($sort_field) $no_resort = 1; 
831            } 
832            else {
833                $sort_field ='entry_authored_on';
834            }
835            if ($sort_field) {
836                $base_order = ($args['sort_order'] == 'ascend' ? 'asc' : 'desc');
837                $base_order or $base_order = 'desc';
838            }
839        } else {
840            $base_order = 'desc';
841            if (isset($args['base_sort_order'])) {
842                if ($args['base_sort_order'] == 'ascend')
843                    $base_order = 'asc';
844            }
845            $sort_field ='entry_authored_on'; 
846            $no_resort = 0;
847        }
848
849        if (count($filters)) {
850            $post_select_limit = $limit;
851            $post_select_offset = $offset;
852            $limit = 0; $offset = 0;
853        }
854
855        if (count($fields)) {
856            $meta_join_num = 1;
857            $meta_join = "";
858            $entry_meta = array();
859            foreach ($this->object_meta['entry'] as $meta) {
860                list($meta_key, $meta_type) = preg_split('/:/', $meta);
861                $entry_meta[$meta_key] = $meta_type;
862            }
863            foreach ($fields as $name => $value) {
864                $meta_col = $entry_meta['field.' . $name];
865                if (!$meta_col) return null; # invalid column; can't select
866
867                $value = $this->escape($value);
868                $meta_join .= " join mt_entry_meta entry_meta$meta_join_num on (entry_meta$meta_join_num.entry_meta_entry_id = entry_id
869                and entry_meta$meta_join_num.entry_meta_type = 'field.$name'
870                and entry_meta$meta_join_num.entry_meta_$meta_col='$value')\n";
871                $meta_join_num++;
872            }
873        }
874
875        $sql = "
876            select$distinct mt_entry.*, mt_placement.*, mt_author.*,
877                   mt_trackback.*
878              from mt_entry
879              left outer join mt_trackback on trackback_entry_id = entry_id
880              $meta_join
881              $join_score
882              left outer join mt_placement on (placement_entry_id = entry_id
883                and placement_is_primary = 1),
884                   mt_author
885             where entry_status = 2
886               and entry_author_id = author_id
887                   $blog_filter
888                   $entry_filter
889                   $author_filter
890                   $date_filter
891                   $day_filter
892                   $class_filter
893        ";
894
895        if ($sort_field) {
896            $sql .= "
897                order by $sort_field $base_order";
898        }
899        if (isset($args['recently_commented_on'])) {
900            $rco = $args['recently_commented_on'];
901            $sql = $this->entries_recently_commented_on_sql($sql);
902            $sql = $this->apply_limit_sql($sql, count($filters) ? null : $rco);
903            $args['sort_by'] or $args['sort_by'] = 'comment_created_on';
904            $args['sort_order'] or $args['sort_order'] = 'descend';
905            $post_select_limit = $rco;
906            $no_resort = 1;
907        } elseif ( !is_null($total_count) ) {
908            $orig_offset = $post_select_offset ? $post_select_offset : $orig_offset;
909            $orig_limit = $post_select_limit ? $post_select_limit : $limit;
910        } else {
911            $sql = $this->apply_limit_sql($sql . " <LIMIT>", $limit, $offset);
912        }
913
914        $result = $this->query_start($sql);
915        if (!$result) return null;
916
917        $entries = array();
918        $j = 0;
919        $offset = $post_select_offset ? $post_select_offset : $orig_offset;
920        $limit = $post_select_limit ? $post_select_limit : 0;
921        $id_list = array();
922        $_total_count = 0;
923        while (true) {
924            $e = $this->query_fetch(ARRAY_A);
925            if (!isset($e)) break;
926            if (count($filters)) {
927                foreach ($filters as $f) {
928                    $old_result = $this->result;
929                    if (!$f($e, $ctx)) {
930                        $this->result = $old_result;
931                        continue 2;
932                    }
933                    $this->result = $old_result;
934                }
935            }
936            $_total_count++;
937            if ( !is_null($total_count) ) {
938                if ( ($orig_limit > 0)
939                  && ( ($_total_count-$offset) > $orig_limit) ) {
940                    // collected all the entries; only count numbers;
941                    continue;
942                }
943            }
944            if ($offset && ($j++ < $offset)) continue;
945            $e['entry_authored_on'] = $this->db2ts($e['entry_authored_on']);
946            $e['entry_modified_on'] = $this->db2ts($e['entry_modified_on']);
947            $e = $this->expand_meta($e);
948            $id_list[] = $e['entry_id'];
949            $entries[] = $e;
950            $this->_comment_count_cache[$e['entry_id']] = $e['entry_comment_count'];
951            $this->_ping_count_cache[$e['entry_id']] = $e['entry_ping_count'];
952            if ( is_null($total_count) ) {
953                // the request does not want total count; break early
954                if (($limit > 0) && (count($entries) >= $limit)) break;
955            }
956        }
957        if ( !is_null($total_count) )
958            $total_count = $_total_count;
959
960        if (!$no_resort) {
961            $sort_field = '';
962            if (isset($args['sort_by'])) {
963                if ($args['sort_by'] == 'title') {
964                    $sort_field = 'entry_title';
965                } elseif ($args['sort_by'] == 'id') {
966                    $sort_field = 'entry_id';
967                } elseif ($args['sort_by'] == 'status') {
968                    $sort_field = 'entry_status';
969                } elseif ($args['sort_by'] == 'modified_on') {
970                    $sort_field = 'entry_modified_on';
971                } elseif ($args['sort_by'] == 'author_id') {
972                    $sort_field = 'entry_author_id';
973                } elseif ($args['sort_by'] == 'excerpt') {
974                    $sort_field = 'entry_excerpt';
975                } elseif ($args['sort_by'] == 'comment_created_on') {
976                    $sort_field = $args['sort_by'];
977                } elseif ($args['sort_by'] == 'score') {
978                    $sort_field = $args['sort_by'];
979                } elseif ($args['sort_by'] == 'rate') {
980                    $sort_field = $args['sort_by'];
981                } elseif ($args['sort_by'] == 'trackback_count') {
982                    $sort_field = 'entry_ping_count'; 
983                } elseif (preg_match('/^field[:\.](.+)$/', $args['sort_by'], $match)) {
984                    $sort_field = 'entry_field.' . $match[1];
985                } else {
986                    $sort_field = 'entry_' . $args['sort_by'];
987                }
988            } else {
989                $sort_field = 'entry_authored_on';
990            }
991            if ($sort_field) {
992                if ($sort_field == 'score') {
993                    $offset = $post_sort_offset ? $post_sort_offset : 0;
994                    $limit = $post_sort_limit ? $post_sort_limit : 0;
995                    $entries_tmp = array();
996                    foreach ($entries as $e) {
997                        $entries_tmp[$e['entry_id']] = $e;
998                    }
999                    $scores = $this->fetch_sum_scores($args['namespace'], 'entry', $order,
1000                        $blog_filter . "\n" .
1001                        $entry_filter . "\n" .
1002                        $author_filter . "\n" .
1003                        $date_filter . "\n" .
1004                        $day_filter . "\n" .
1005                        $class_filter . "\n"
1006                    );
1007                    $entries_sorted = array();
1008                    foreach($scores as $score) {
1009                        if (--$offset >= 0) continue;
1010                        if (array_key_exists($score['objectscore_object_id'], $entries_tmp)) {
1011                            array_push($entries_sorted, $entries_tmp[$score['objectscore_object_id']]);
1012                            unset($entries_tmp[$score['objectscore_object_id']]);
1013                            if (--$limit == 0) break;
1014                        }
1015                    }
1016                    foreach ($entries_tmp as $et) {
1017                        if ($limit == 0) break;
1018                        if ($order == 'asc')
1019                            array_unshift($entries_sorted, $et);
1020                        else
1021                            array_push($entries_sorted, $et);
1022                        $limit--;
1023                    }
1024                    $entries = $entries_sorted;
1025                } elseif ($sort_field == 'rate') {
1026                    $offset = $post_sort_offset ? $post_sort_offset : 0;
1027                    $limit = $post_sort_limit ? $post_sort_limit : 0;
1028                    $entries_tmp = array();
1029                    foreach ($entries as $e) {
1030                        $entries_tmp[$e['entry_id']] = $e;
1031                    }
1032                    $scores = $this->fetch_avg_scores($args['namespace'], 'entry', $order,
1033                        $blog_filter . "\n" .
1034                        $entry_filter . "\n" .
1035                        $author_filter . "\n" .
1036                        $date_filter . "\n" .
1037                        $day_filter . "\n" .
1038                        $class_filter . "\n"
1039                    );
1040                    $entries_sorted = array();
1041                    foreach($scores as $score) {
1042                        if (--$offset >= 0) continue;
1043                        if (array_key_exists($score['objectscore_object_id'], $entries_tmp)) {
1044                            array_push($entries_sorted, $entries_tmp[$score['objectscore_object_id']]);
1045                            unset($entries_tmp[$score['objectscore_object_id']]);
1046                            if (--$limit == 0) break;
1047                        }
1048                    }
1049                    foreach ($entries_tmp as $et) {
1050                        if ($limit == 0) break;
1051                        if ($order == 'asc')
1052                            array_unshift($entries_sorted, $et);
1053                        else
1054                            array_push($entries_sorted, $et);
1055                        $limit--;
1056                    }
1057                    $entries = $entries_sorted;
1058                } else {
1059                    if (($sort_field == 'entry_status') || ($sort_field == 'entry_author_id') || ($sort_field == 'entry_id')
1060                          || ($sort_field == 'entry_comment_count') || ($sort_field == 'entry_ping_count')) {
1061                        $sort_fn = "if (\$a['$sort_field'] == \$b['$sort_field']) return 0; return \$a['$sort_field'] < \$b['$sort_field'] ? -1 : 1;";
1062                    } else {
1063                        $sort_fn = "return strcmp(\$a['$sort_field'],\$b['$sort_field']);";
1064                    }
1065                    $sorter = create_function(
1066                        $order == 'asc' ? '$a,$b' : '$b,$a',
1067                        $sort_fn);
1068                    usort($entries, $sorter);
1069                }
1070            }
1071        }
1072
1073        if (count($id_list) <= 30) { # TODO: find a good upper limit
1074            # pre-cache comment counts and categories for these entries
1075            $this->cache_categories($id_list);
1076            $this->cache_permalinks($id_list);
1077        }
1078
1079        return $entries;
1080    }
1081
1082    function fetch_plugin_config($plugin, $scope = "system") {
1083        if ($scope != 'system') {
1084            $key = 'configuration:'.$scope;
1085        } else {
1086            $key = 'configuration';
1087        }
1088        return $this->fetch_plugin_data($plugin, $key);
1089    }
1090
1091    function fetch_plugin_data($plugin, $key) {
1092        $plugin = $this->escape($plugin);
1093        $key = $this->escape($key);
1094        $sql = "
1095            select plugindata_data from mt_plugindata
1096             where plugindata_plugin = '$plugin'
1097               and plugindata_key = '$key'";
1098        $data = $this->get_var($sql);
1099        if ($data) {
1100            return $this->unserialize($data);
1101        }
1102        return null;
1103    }
1104
1105    function &fetch_entry_tags($args) {
1106        $class = 'entry';
1107        if (isset($args['class'])) {
1108            $class = $args['class'];
1109        }
1110
1111        # load tags
1112        if (isset($args['entry_id'])) {
1113            if (!isset($args['tags']) && !isset($args['tag'])) {
1114                if (isset($this->_entry_tag_cache[$args['entry_id']])) {
1115                    return $this->_entry_tag_cache[$args['entry_id']];
1116                }
1117            }
1118            $entry_filter = 'and objecttag_tag_id in (select objecttag_tag_id from mt_objecttag where objecttag_object_id='.intval($args['entry_id']).')';
1119        }
1120
1121        $blog_filter = $this->include_exclude_blogs($args);
1122        if ($blog_filter == '' and isset($args['blog_id'])) {
1123            if (!isset($args['tags']) && !isset($args['tag'])) {
1124                if (!isset($args['entry_id'])) {
1125                    if (isset($this->_blog_tag_cache[$args['blog_id'].":$class"])) {
1126                        return $this->_blog_tag_cache[$args['blog_id'].":$class"];
1127                    }
1128                }
1129            }
1130            $blog_filter = ' = '. intval($args['blog_id']);
1131        }
1132        if ($blog_filter != '') 
1133            $blog_filter = 'and objecttag_blog_id ' . $blog_filter;
1134
1135        if (!isset($args['include_private'])) {
1136            $private_filter = 'and (tag_is_private = 0 or tag_is_private is null)';
1137        }
1138        if (isset($args['tags']) && ($args['tags'] != '')) {
1139            $tag_list = '';
1140            require_once("MTUtil.php");
1141            $tag_array = tag_split($args['tags']);
1142            foreach ($tag_array as $tag) {
1143                if ($tag_list != '') $tag_list .= ',';
1144                $tag_list .= "'" . $this->escape($tag) . "'";
1145            }
1146            if ($tag_list != '') {
1147                $tag_filter = 'and (tag_name in (' . $tag_list . '))';
1148                $private_filter = '';
1149            }
1150        }
1151
1152        $sort_col = isset($args['sort_by']) ? $args['sort_by'] : 'name';
1153        $sort_col = "tag_$sort_col";
1154        if (isset($args['sort_order']) and $args['sort_order'] == 'descend') {
1155            $order = 'desc';
1156        } else {
1157            $order = 'asc';
1158        }
1159        $id_order = '';
1160        if ($sort_col == 'tag_name') {
1161            $sort_col = 'lower(tag_name)';
1162        }else{
1163            $id_order = ', lower(tag_name)';
1164        }
1165
1166        $sql = "
1167            select tag_id, tag_name, count(*) as tag_count
1168             from mt_tag, mt_objecttag, mt_entry
1169             where objecttag_tag_id = tag_id
1170               and entry_id = objecttag_object_id and objecttag_object_datasource='entry'
1171               and entry_status = 2
1172                   and entry_class = '$class'
1173                   $blog_filter
1174                   $tag_filter
1175                   $entry_filter
1176                   $private_filter
1177            group by tag_id, tag_name
1178            order by $sort_col $order $id_order";
1179        $tags = $this->get_results($sql, ARRAY_A);
1180        if (!isset($args['tag'])) {
1181            if ($args['entry_id'])
1182                $this->_entry_tag_cache[$args['entry_id']] = $tags;
1183            elseif ($args['blog_id'])
1184                $this->_blog_tag_cache[$args['blog_id'].":$class"] = $tags;
1185        }
1186        return $tags;
1187    }
1188
1189    function &fetch_asset_tags($args) {
1190
1191        # load tags by asset
1192        if (!isset($args['include_private'])) {
1193            $private_filter = 'and (tag_is_private = 0 or tag_is_private is null)';
1194        }
1195
1196        if (isset($args['asset_id'])) {
1197            if (isset($args['tags'])) {
1198                if (isset($this->_asset_tag_cache[$args['asset_id']]))
1199                    return $this->_asset_tag_cache[$args['asset_id']];
1200            }
1201            $asset_filter = 'and objecttag_object_id = '.intval($args['asset_id']);
1202        }
1203       
1204        if (isset($args['blog_id'])) {
1205            if (!isset($args['tags'])) {
1206                if (isset($this->_blog_asset_tag_cache[$args['blog_id']]))
1207                    return $this->_blog_asset_tag_cache[$args['blog_id']];
1208            }
1209            $blog_filter = 'and objecttag_blog_id = '.intval($args['blog_id']);
1210        }
1211
1212        if (isset($args['tags']) && ($args['tags'] != '')) {
1213            $tag_list = '';
1214            require_once("MTUtil.php");
1215            $tag_array = tag_split($args['tags']);
1216            foreach ($tag_array as $tag) {
1217                if ($tag_list != '') $tag_list .= ',';
1218                $tag_list .= "'" . $this->escape($tag) . "'";
1219            }
1220            if ($tag_list != '') {
1221                $tag_filter = 'and (tag_name in (' . $tag_list . '))';
1222                $private_filter = '';
1223            }
1224        }
1225
1226        $sort_col = isset($args['sort_by']) ? $args['sort_by'] : 'name';
1227        $sort_col = "tag_$sort_col";
1228        if (isset($args['sort_order']) and $args['sort_order'] == 'descend')
1229            $order = 'desc';
1230        else
1231            $order = 'asc';
1232
1233        $id_order = '';
1234        if ($sort_col == 'tag_name')
1235            $sort_col = 'lower(tag_name)';
1236        else
1237            $id_order = ', lower(tag_name)';
1238
1239        $sql = "
1240            select tag_id, tag_name, count(*) as tag_count
1241            from mt_tag, mt_objecttag, mt_asset
1242            where objecttag_tag_id = tag_id
1243                and asset_id = objecttag_object_id and objecttag_object_datasource='asset'
1244                $blog_filter
1245                $private_filter
1246                $tag_filter
1247                $asset_filter
1248            group by tag_id, tag_name
1249            order by $sort_col $order $id_order
1250        ";
1251        $tags = $this->get_results($sql, ARRAY_A);
1252        if (isset($args['tags'])) {
1253            if ($args['asset_id'])
1254                $this->_asset_tag_cache[$args['asset_id']] = $tags;
1255            elseif ($args['blog_id'])
1256                $this->_blog_asset_tag_cache[$args['blog_id']] = $tags;
1257        }
1258        return $tags;
1259    }
1260
1261    function &fetch_folders($args) {
1262        $args['class'] = 'folder';
1263        return $this->fetch_categories($args);
1264    }
1265
1266    function &fetch_categories($args) {
1267        # load categories
1268
1269        if ($blog_filter = $this->include_exclude_blogs($args)) {
1270             $blog_filter = 'and category_blog_id '. $blog_filter;
1271        } elseif (isset($args['blog_id'])) {
1272            $blog_filter = 'and category_blog_id = '.intval($args['blog_id']);
1273        }
1274        if (isset($args['parent'])) {
1275            $parent = $args['parent'];
1276            if (is_array($parent)) {
1277                $parent_filter = 'and category_parent in (' . implode(',', $parent) . ')';
1278            } else {
1279                $parent_filter = 'and category_parent = '.intval($parent);
1280            }
1281        }
1282        if (isset($args['category_id'])) {
1283            if (isset($args['children'])) {
1284                if (isset($this->_cat_id_cache['c'.$args['category_id']])) {
1285                    $cat = $this->_cat_id_cache['c'.$args['category_id']];
1286                    if (isset($cat['_children'])) {
1287                        $children = $cat['_children'];
1288                        if ($children === false) {
1289                            return null;
1290                        } else {
1291                            return $children;
1292                        }
1293                    }
1294                }
1295
1296                $cat_filter = 'and category_parent = '.intval($args['category_id']);
1297            } else {
1298                $cat_filter = 'and category_id = '.intval($args['category_id']);
1299                $limit = 1;
1300            }
1301        } elseif (isset($args['label'])) {
1302            $cat_filter = 'and category_label = \''.$this->escape($args['label']).'\'';
1303        } else {
1304            $limit = $args['lastn'];
1305            if (isset($args['sort_order'])) {
1306                if ($args['sort_order'] == 'ascend') {
1307                    $sort_order = 'asc';
1308                } elseif ($args['sort_order'] == 'descend') {
1309                    $sort_order = 'desc';
1310                }
1311            } else {
1312                $sort_order = '';
1313            }
1314        }
1315        $count_column = 'placement_id';
1316        if ($args['show_empty']) {
1317            $join_clause = 'left outer join mt_placement on placement_category_id = category_id';
1318            if (isset($args['entry_id'])) {
1319                $join_clause .= ' left outer join mt_entry on placement_entry_id = entry_id and entry_id = '.intval($args['entry_id']);
1320            } else {
1321                $join_clause .= ' left outer join mt_entry on placement_entry_id = entry_id and entry_status = 2';
1322            }
1323            $count_column = 'entry_id';
1324        } else {
1325            $join_clause = ', mt_entry, mt_placement';
1326            $cat_filter .= ' and placement_category_id = category_id';
1327            if (isset($args['entry_id'])) {
1328                $entry_filter = 'and placement_entry_id = entry_id and placement_entry_id = '.intval($args['entry_id']);
1329            } else {
1330                $entry_filter = 'and placement_entry_id = entry_id and entry_status = 2';
1331            }
1332        }
1333
1334        if (isset($args['class'])) {
1335            $class = $this->escape($args['class']);
1336        } else {
1337            $class = "category";
1338        }
1339        $class_filter = "and category_class='$class'";
1340
1341        $sql = "
1342            select category_id, count($count_column) as category_count
1343              from mt_category $join_clause
1344             where 1 = 1
1345                   $cat_filter
1346                   $entry_filter
1347                   $blog_filter
1348                   $parent_filter
1349                   $class_filter
1350             group by category_id
1351                   <LIMIT>
1352        ";
1353        $sql = $this->apply_limit_sql($sql, $limit, $offset);
1354
1355        $categories = $this->get_results($sql, ARRAY_A);
1356        if (!$categories) {
1357            return null;
1358        }
1359        if (isset($args['children']) && isset($parent_cat)) {
1360            $parent_cat['_children'] =& $categories;
1361        } else {
1362            $ids = array();
1363            $counts = array();
1364            foreach ($categories as $cid => $cat) {
1365                $counts[$cat['category_id']] = $cat['category_count'];
1366                $ids[] = $cat['category_id'];
1367            }
1368            $list = implode(",", $ids);
1369            $sql2 = "
1370                select mt_category.*, mt_trackback.*
1371                    from mt_category left outer join mt_trackback on trackback_category_id = category_id
1372                   where category_id in ($list)
1373                order by category_label $sort_order
1374            ";
1375            $categories = $this->get_results($sql2, ARRAY_A);
1376            $id_list = array();
1377            foreach ($categories as $cid => $cat) {
1378                $cat_id = $cat['category_id'];
1379                $categories[$cid]['category_count'] = $counts[$cat_id];
1380                if (isset($args['top_level_categories']) || !isset($this->_cat_id_cache['c'.$cat_id])) {
1381                    $id_list[] = $cat_id;
1382                    $this->_cat_id_cache['c'.$cat_id] = $categories[$cid];
1383                }
1384                if (isset($args['top_level_categories'])) {
1385                    $this->_cat_id_cache['c'.$cat_id]['_children'] = false;
1386                }
1387            }
1388
1389            $top_cats = array();
1390            foreach ($categories as $cid => $cat) {
1391                if ($cat['category_parent'] > 0) {
1392                    $parent_id = $cat['category_parent'];
1393                    if (isset($this->_cat_id_cache['c'.$parent_id])) {
1394                        if (isset($args['top_level_categories'])) {
1395                            $parent =& $this->fetch_category($categories[$cid]['category_parent']);
1396                            if (!isset($parent['_children']) || ($parent['_children'] === false)) {
1397                                $parent['_children'] = array(&$categories[$cid]);
1398                            } else {
1399                                $parent['_children'][] = $categories[$cid];
1400                            }
1401                        }
1402                    }
1403                }
1404                if ((!$cat['category_parent']) && (isset($args['top_level_categories']))) {
1405                    $top_cats[] = $categories[$cid];
1406                }
1407            }
1408            $this->cache_category_links($id_list);
1409            if (isset($args['top_level_categories'])) {
1410                return $top_cats;
1411            }
1412        }
1413        return $categories;
1414    }
1415
1416    function &fetch_entry($entry_id) {
1417        if (isset($this->_entry_id_cache['entry_id'])) {
1418            return $this->_entry_id_cache[$entry_id];
1419        }
1420        list($entry) = $this->fetch_entries(array('entry_id' => $entry_id));
1421        $this->_entry_id_cache[$entry_id] = $entry;
1422        return $entry;
1423    }
1424
1425    function &fetch_page($entry_id) {
1426        if (isset($this->_entry_id_cache['entry_id'])) {
1427            return $this->_entry_id_cache[$entry_id];
1428        }
1429        list($entry) = $this->fetch_pages(array('entry_id' => $entry_id));
1430        $this->_entry_id_cache[$entry_id] = $entry;
1431        return $entry;
1432    }
1433
1434    function &fetch_author($author_id) {
1435        if (isset($this->_author_id_cache[$author_id])) {
1436            return $this->_author_id_cache[$author_id];
1437        }
1438        $args['author_id'] = $author_id;
1439        $args['any_type'] = 1;
1440        $result = $this->fetch_authors($args);
1441        $author = null;
1442        if (is_array($result)) {
1443            $author = $result[0];
1444            $this->_author_id_cache[$author_id] = $author;
1445        }
1446        return $author;
1447    }
1448
1449    function &fetch_author_by_name($author_name) {
1450        global $mt;
1451        $args['blog_id'] = $mt->blog_id;
1452        $args['author_name'] = $this->escape($author_name);
1453        $result = $this->fetch_authors($args);
1454        $author = null;
1455        if (is_array($result)) {
1456            $author = $result[0];
1457            $this->_author_id_cache[$author['author_id']] = $author;
1458        }
1459        return $author;
1460    }
1461
1462    function &fetch_authors($args) {
1463        # Adds blog join
1464        $extend_column = '';
1465        if ($sql = $this->include_exclude_blogs($args)) {
1466            $blog_join = 'join mt_permission on permission_author_id = author_id and permission_blog_id ' . $sql;
1467            $unique_filter = 'distinct';
1468        } elseif (isset($args['blog_id'])) {
1469            $blog_id = intval($args['blog_id']);
1470            $blog_join = "join mt_permission on permission_author_id = author_id and permission_blog_id = $blog_id";
1471        }
1472
1473        # Adds author filter
1474        if (isset($args['author_id'])) {
1475            $author_id = intval($args['author_id']);
1476            $author_filter = " and author_id = $author_id";
1477        }
1478        if (isset($args['author_nickname'])) {
1479            $author_filter .= " and author_nickname = '".$args['author_nickname']."'";
1480        }
1481        if (isset($args['author_name'])) {
1482            $author_filter .= " and author_name = '".$args['author_name']."'";
1483        }
1484
1485        # Adds entry join and filter
1486        if ($args['need_entry']) {
1487            $entry_join = 'join mt_entry on author_id = entry_author_id';
1488            $unique_filter = 'distinct';
1489            $entry_filter = " and entry_status = 2";
1490            if ($blog_join) {
1491                $entry_filter .= " and entry_blog_id = permission_blog_id";
1492            } else {
1493                $entry_filter .= " and entry_blog_id = ".$args['blog_id'];
1494            }
1495        } else {
1496            if ( ! $args['any_type'] )
1497                $author_filter .= " and author_type = 1";
1498        }
1499
1500        # a context hash for filter routines
1501        $ctx = array();
1502        $filters = array();
1503
1504        if (isset($args['status'])) {
1505            $status_arg = $args['status'];
1506            require_once("MTUtil.php");
1507            $status = array(
1508                array('name' => 'enabled', 'id' => 1),
1509                array('name' => 'disabled', 'id' => 2));
1510
1511            $cexpr = create_status_expr_function($status_arg, $status);
1512            if ($cexpr) {
1513                $filters[] = $cexpr;
1514            }
1515        }
1516
1517        if (isset($args['roles']) or isset($args['role'])) {
1518            $role_arg = isset($args['role']) ? $args['role'] : $args['roles'];
1519            require_once("MTUtil.php");
1520            $roles =& $this->fetch_all_roles();
1521            if (!is_array($roles)) $roles = array();
1522
1523            $cexpr = create_role_expr_function($role_arg, $roles);
1524            if ($cexpr) {
1525                $rmap = array();
1526                $role_list = array();
1527                foreach ($roles as $role) {
1528                    $role_list[] = $role['role_id'];
1529                }
1530                $as =& $this->fetch_associations(array('blog_id' => $blog_id, 'role_id' => $role_list));
1531                if ($as) {
1532                    foreach ($as as $a) {
1533                        $rmap[$a['association_author_id']][$a['association_role_id']]++;
1534                    }
1535                }
1536                $ctx['r'] =& $rmap;
1537                $filters[] = $cexpr;
1538            }
1539        }
1540
1541        # Adds a score or rate filter to the filters list.
1542        $re_sort = false;
1543        if (isset($args['namespace'])) {
1544            require_once("MTUtil.php");
1545            $arg_names = array('min_score', 'max_score', 'min_rate', 'max_rate', 'min_count', 'max_count' );
1546            foreach ($arg_names as $n) {
1547                if (isset($args[$n])) {
1548                    $rating_args = $args[$n];
1549                    $cexpr = create_rating_expr_function($rating_args, $n, $args['namespace'], 'author');
1550                    if ($cexpr) {
1551                        $filters[] = $cexpr;
1552                        $re_sort = true;
1553                    } else {
1554                        return null;
1555                    }
1556                }
1557            }
1558        }
1559
1560        # sort
1561        $join_score = "";
1562        if (isset($args['sort_by'])) {
1563            if (($args['sort_by'] == 'score') || ($args['sort_by'] == 'rate')) {
1564                $join_score = "join mt_objectscore on objectscore_object_id = author_id and objectscore_namespace='".$args['namespace']."' and objectscore_object_ds='author'";
1565                $unique_filter = 'distinct';
1566                $order_sql = "order by author_created_on desc";
1567                $re_sort = true;
1568            } else {
1569                $sort_col = $args['sort_by'];
1570                $order = '';
1571                if (isset($args['sort_order'])) {
1572                    if ($args['sort_order'] == 'ascend')
1573                        $order = 'asc';
1574                    else
1575                        $order = 'desc';
1576                }
1577                $order_sql = "order by $sort_col $order";
1578   
1579                if (isset($args['start_string'])) {
1580                    $val = $args['start_string'];
1581                    if ($order == 'asc')
1582                        $val_order = '>';
1583                    else
1584                        $val_order = '<';
1585                    $sort_filter =  " and $sort_col $val_order '$val'";
1586                }
1587   
1588                if (isset($args['start_num'])) {
1589                    $val = $args['start_num'];
1590                    if ($order == 'asc')
1591                        $val_order = '>';
1592                    else
1593                        $val_order = '<';
1594                    $sort_filter .= " and $sort_col $val_order $val";
1595                }
1596            }
1597        }
1598
1599        $limit = 0;
1600        $offset = 0;
1601        if (isset($args['lastn']))
1602            $limit = $args['lastn'];
1603        if (isset($args['offset']))
1604            $limit = $args['offset'];
1605
1606        if ($re_sort) {
1607            $post_select_limit = $limit;
1608            $post_select_offset = $offset;
1609            $limit = 0; $offset = 0;
1610        }
1611       
1612        $sql = "
1613            select $unique_filter
1614                   mt_author.*
1615                   $extend_column
1616              from mt_author
1617                   $blog_join
1618                   $entry_join
1619                   $join_score
1620              where 1 = 1
1621                $author_filter
1622                $entry_filter
1623                $sort_filter
1624              $order_sql
1625                   <LIMIT>
1626        ";
1627        $sql = $this->apply_limit_sql($sql, $limit, $offset);
1628
1629        $result = $this->query_start($sql);
1630        if (!$result) return null;
1631
1632        $authors = array();
1633        if ($args['sort_by'] != 'score' && $args['sort_by'] != 'rate') {
1634            $offset = $post_select_offset ? $post_select_offset : 0;
1635            $limit = $post_select_limit ? $post_select_limit : 0;
1636        }
1637        $j = 0;
1638        while (true) {
1639            $e = $this->query_fetch(ARRAY_A);
1640            if ($offset && ($j++ < $offset)) continue;
1641            if (!isset($e)) break;
1642            if (count($filters)) {
1643                foreach ($filters as $f) {
1644                    if (!$f($e, $ctx)) continue 2;
1645                }
1646            }
1647            $authors[] = $e;
1648            if (($limit > 0) && (count($authors) >= $limit)) break;
1649        }
1650
1651        if (isset($args['sort_by']) && ('score' == $args['sort_by'])) {
1652            $authors_tmp = array();
1653            $order = 'asc';
1654            if (isset($args['sort_order']))
1655                $order = $args['sort_order'] == 'ascend' ? 'asc' : 'desc';
1656            foreach ($authors as $a) {
1657                $authors_tmp[$a['author_id']] = $a;
1658            }
1659            $scores = $this->fetch_sum_scores($args['namespace'], 'author', $order,
1660                $author_filter
1661            );
1662            $offset = $post_select_offset ? $post_select_offset : 0;
1663            $limit = $post_select_limit ? $post_select_limit : 0;
1664            $j = 0;
1665            $authors_sorted = array();
1666            foreach($scores as $score) {
1667                if (array_key_exists($score['objectscore_object_id'], $authors_tmp)) {
1668                    if ($offset && ($j++ < $offset)) continue;
1669                    array_push($authors_sorted, $authors_tmp[$score['objectscore_object_id']]);
1670                    unset($authors_tmp[$score['objectscore_object_id']]);
1671                    if (($limit > 0) && (count($authors_sorted) >= $limit)) break;
1672                }
1673            }
1674            $authors = $authors_sorted;
1675
1676        } elseif (isset($args['sort_by']) && ('rate' == $args['sort_by'])) {
1677            $authors_tmp = array();
1678            $order = 'asc';
1679            if (isset($args['sort_order']))
1680                $order = $args['sort_order'] == 'ascend' ? 'asc' : 'desc';
1681            foreach ($authors as $a) {
1682                $authors_tmp[$a['author_id']] = $a;
1683            }
1684            $scores = $this->fetch_avg_scores($args['namespace'], 'author', $order,
1685                $author_filter
1686            );
1687            $offset = $post_select_offset ? $post_select_offset : 0;
1688            $limit = $post_select_limit ? $post_select_limit : 0;
1689            $j = 0;
1690            $authors_sorted = array();
1691            foreach($scores as $score) {
1692                if (array_key_exists($score['objectscore_object_id'], $authors_tmp)) {
1693                    if ($offset && ($j++ < $offset)) continue;
1694                    array_push($authors_sorted, $authors_tmp[$score['objectscore_object_id']]);
1695                    unset($authors_tmp[$score['objectscore_object_id']]);
1696                    if (($limit > 0) && (count($authors_sorted) >= $limit)) break;
1697                }
1698            }
1699            $authors = $authors_sorted;
1700
1701        }
1702
1703        return $authors;
1704    }
1705
1706    function &fetch_permission($args) {
1707        if ($sql = $this->include_exclude_blogs($args)) {
1708            $blog_filter = 'permission_blog_id ' . $sql;
1709        } elseif (isset($args['blog_id'])) {
1710            $blog_id = intval($args['blog_id']);
1711            $blog_filter = "and permission_blog_id = $blog_id";
1712        }
1713        if (isset($args['id'])) {
1714          $id_filter = 'and permission_author_id in ('.$args['id'].')';
1715        }
1716
1717        $sql = "select
1718                    *
1719                from
1720                    mt_permission
1721                where
1722                    1 = 1
1723                    $blog_filter
1724                    $id_filter";
1725
1726        $result = $this->get_results($sql, ARRAY_A);
1727        return $result;
1728    }
1729
1730    function &fetch_all_roles() {
1731        $sql = "select *
1732                  from mt_role
1733              order by role_name";
1734        $result = $this->get_results($sql, ARRAY_A);
1735        return $result;
1736    }
1737
1738    function &fetch_associations($args) {
1739        $id_list = implode(",", $args['role_id']);
1740        if (empty($id_list))
1741            return;
1742        if ($sql = $this->include_exclude_blogs($args)) {
1743            $blog_filter = 'and association_blog_id  ' . $sql;
1744        } elseif (isset($args['blog_id'])) {
1745            $blog_filter = 'and association_blog_id = ' . intval($args['blog_id']);
1746        }
1747        $sql = "select *
1748                  from mt_association
1749                 where association_role_id in ($id_list)
1750                   $blog_filter";
1751        $result = $this->get_results($sql, ARRAY_A);
1752        return $result;
1753    }
1754
1755    function &fetch_tag($tag_id) {
1756        $tag_id = intval($tag_id);
1757        if (isset($this->_tag_id_cache[$tag_id])) {
1758            return $this->_tag_id_cache[$tag_id];
1759        }
1760        $tag = $this->get_row("
1761            select *
1762              from mt_tag
1763             where tag_id=$tag_id
1764        ", ARRAY_A);
1765        $this->_tag_id_cache[$tag_id] = $tag;
1766        return $tag;
1767    }
1768
1769    function &fetch_tag_by_name($tag_name) {
1770        $tag_name = $this->escape($tag_name);
1771        $tag = $this->get_row("
1772            select *
1773              from mt_tag
1774             where tag_name='$tag_name'
1775        ", ARRAY_A);
1776        $this->_tag_id_cache[$tag['tag_id']] = $tag;
1777        return $tag;
1778    }
1779
1780    function fetch_scores($namespace, $obj_id, $datasource) {
1781        $scores = $this->get_results("
1782            select * from mt_objectscore
1783            where objectscore_namespace='$namespace'
1784            and objectscore_object_id='$obj_id'
1785            and objectscore_object_ds='$datasource'
1786        ", ARRAY_A);
1787        return $scores;
1788    }
1789
1790    function fetch_score($namespace, $obj_id, $user_id, $datasource) {
1791        list($score) = $this->get_results("
1792            select * from mt_objectscore
1793            where objectscore_namespace='$namespace'
1794            and objectscore_object_id='$obj_id'
1795            and objectscore_object_ds='$datasource'
1796            and objectscore_author_id='$user_id'
1797        ", ARRAY_A);
1798        return $score;
1799    }
1800
1801    function fetch_sum_scores($namespace, $datasource, $order, $filters) {
1802        $othertables = '';
1803        $otherwhere = '';
1804        if ($datasource == 'asset') {
1805            $othertables = ', mt_author';
1806            $otherwhere = 'AND (objectscore_author_id = author_id)';
1807        }
1808        $join_column = $datasource . '_id';
1809        $join_where = "AND ($join_column = objectscore_object_id)";
1810        $sql_scores = 
1811            "SELECT SUM(objectscore_score) AS sum_objectscore_score, objectscore_object_id
1812             FROM mt_objectscore, mt_$datasource $othertables
1813             WHERE (objectscore_namespace = '$namespace')
1814             AND (objectscore_object_ds = '$datasource')
1815             $join_where
1816             $otherwhere
1817             $filters
1818             GROUP BY objectscore_object_id
1819             ORDER BY sum_objectscore_score " . $order;
1820        $scores = $this->get_results($sql_scores, ARRAY_A);
1821        return $scores;
1822    }
1823
1824    function fetch_avg_scores($namespace, $datasource, $order, $filters) {
1825        $othertables = '';
1826        $otherwhere = '';
1827        if ($datasource == 'asset') {
1828            $othertables = ', mt_author';
1829            $otherwhere = 'AND (objectscore_author_id = author_id)';
1830        }
1831        $join_column = $datasource . '_id';
1832        $join_where = "AND ($join_column = objectscore_object_id)";
1833        $sql_scores = 
1834            "SELECT AVG(objectscore_score) AS sum_objectscore_score, objectscore_object_id
1835             FROM mt_objectscore, mt_$datasource $othertables
1836             WHERE (objectscore_namespace = '$namespace')
1837             AND (objectscore_object_ds = '$datasource')
1838             $join_where
1839             $otherwhere
1840             $filters
1841             GROUP BY objectscore_object_id
1842             ORDER BY sum_objectscore_score " . $order;
1843        $scores = $this->get_results($sql_scores, ARRAY_A);
1844        return $scores;
1845    }
1846
1847    function cache_permalinks(&$entry_list) {
1848        $id_list = '';
1849        foreach ($entry_list as $entry_id) {
1850            if (!isset($this->_entry_link_cache[$entry_id.';Individual'])) {
1851                $id_list .= ','.$entry_id;
1852                $this->_entry_link_cache[$entry_id.';Individual'] = ''; 
1853            }
1854        }
1855        if (empty($id_list))
1856            return;
1857        $id_list = substr($id_list, 1);
1858        $query = "
1859            select fileinfo_entry_id, fileinfo_url, blog_site_url, blog_file_extension, blog_archive_url
1860              from mt_fileinfo, mt_templatemap, mt_blog
1861             where fileinfo_entry_id in ($id_list)
1862               and fileinfo_archive_type = 'Individual'
1863               and blog_id = fileinfo_blog_id
1864               and templatemap_id = fileinfo_templatemap_id
1865               and templatemap_is_preferred = 1
1866        ";
1867        $results = $this->get_results($query, ARRAY_N);
1868        if ($results) {
1869
1870            foreach ($results as $row) {
1871                $blog_url = $row[4];
1872                $blog_url or $blog_url = $row[2];
1873                $blog_url = preg_replace('!(https?://(?:[^/]+))/.*!', '$1', $blog_url);
1874                $url = $blog_url . $row[1];
1875                $url = _strip_index($url, array('blog_file_extension' => $row[3]));
1876                $this->_entry_link_cache[$row[0].';Individual'] = $url;
1877            }
1878        }
1879    }
1880
1881    function cache_category_links(&$cat_list) {
1882        $id_list = '';
1883        foreach ($cat_list as $cat_id) {
1884            if (!isset($this->_cat_link_cache[$cat_id])) {
1885                $id_list .= ','.$cat_id;
1886                $this->_cat_link_cache[$cat_id] = '';
1887            }
1888        }
1889        if (empty($id_list))
1890            return;
1891        $id_list = substr($id_list, 1);
1892        $query = "
1893            select fileinfo_category_id, fileinfo_url, blog_site_url, blog_file_extension, blog_archive_url
1894              from mt_fileinfo, mt_templatemap, mt_blog
1895             where fileinfo_category_id in ($id_list)
1896               and fileinfo_archive_type = 'Category'
1897               and blog_id = fileinfo_blog_id
1898               and templatemap_id = fileinfo_templatemap_id
1899               and templatemap_is_preferred = 1
1900        ";
1901        $results = $this->get_results($query, ARRAY_N);
1902        if ($results) {
1903            foreach ($results as $row) {
1904                $blog_url = $row[4];
1905                $blog_url or $blog_url = $row[2];
1906                $blog_url = preg_replace('!(https?://(?:[^/]+))/.*!', '$1', $blog_url);
1907                $url = $blog_url . $row[1];
1908                $url = _strip_index($url, array('blog_file_extension' => $row[3]));
1909                $this->_cat_link_cache[$row[0]] = $url;
1910            }
1911        }
1912    }
1913
1914    function cache_comment_counts(&$entry_list) {
1915        $id_list = '';
1916        foreach ($entry_list as $entry_id) {
1917            if (!isset($this->_comment_count_cache[$entry_id])) {
1918                $id_list .= ','.$entry_id;
1919                $this->_comment_count_cache[$entry_id] = 0;
1920            }
1921        }
1922        if (empty($id_list))
1923            return;
1924        $id_list = substr($id_list, 1);
1925        $query = "
1926            select entry_id, entry_comment_count
1927              from mt_entry
1928             where entry_id in ($id_list)
1929        ";
1930        $results = $this->get_results($query, ARRAY_N);
1931        if ($results) {
1932            foreach ($results as $row) {
1933                $this->_comment_count_cache[$row[0]] = $row[1];
1934            }
1935        }
1936    }
1937
1938    function blog_entry_count($args) {
1939
1940        if ($sql = $this->include_exclude_blogs($args)) {
1941            $blog_filter = 'and entry_blog_id ' . $sql;
1942        } elseif (isset($args['blog_id'])) {
1943            $blog_id = intval($args['blog_id']);
1944            $blog_filter = 'and entry_blog_id = ' . $blog_id;
1945        }
1946        $class = 'entry';
1947        if (isset($args['class'])) {
1948            $class = $args['class'];
1949        }
1950        $count = $this->get_var("
1951          select count(*)
1952            from mt_entry
1953            where entry_status = 2
1954            and entry_class='$class'
1955            $blog_filter
1956            ");
1957        return $count;
1958    }
1959
1960    function blog_comment_count($args) {
1961
1962        if ($sql = $this->include_exclude_blogs($args)) {
1963            $blog_filter = 'and comment_blog_id ' . $sql;
1964        } elseif (isset($args['blog_id'])) {
1965            $blog_id = intval($args['blog_id']);
1966            $blog_filter = 'and comment_blog_id = ' . $blog_id;
1967        }
1968
1969        $count = $this->get_var("
1970            select count(*)
1971              from mt_entry, mt_comment
1972             where entry_status = 2
1973               and comment_visible = 1
1974               and comment_entry_id = entry_id
1975               $blog_filter
1976        ");
1977        return $count;
1978    }
1979
1980    function category_comment_count($args) {
1981        $cat_id = (int)$args['category_id'];
1982        $sql = "select count(*)
1983             from mt_placement, mt_comment, mt_entry
1984            where placement_category_id=$cat_id
1985              and entry_id=placement_entry_id
1986              and entry_status=2
1987              and comment_entry_id=entry_id
1988              and comment_visible=1";
1989        return $this->get_var($sql);
1990    }
1991
1992    function blog_ping_count($args) {
1993
1994        if ($sql = $this->include_exclude_blogs($args)) {
1995            $blog_filter = 'and tbping_blog_id ' . $sql;
1996        } elseif (isset($args['blog_id'])) {
1997            $blog_id = intval($args['blog_id']);
1998            $blog_filter = 'and tbping_blog_id = ' . $blog_id;
1999        }
2000
2001        $count = $this->get_var("
2002            select count(*)
2003              from mt_tbping, mt_trackback
2004             where tbping_visible = 1
2005               and tbping_tb_id = trackback_id
2006                   $blog_filter
2007        ");
2008        return $count;
2009    }
2010
2011    function blog_category_count($args) {
2012
2013        if ($sql = $this->include_exclude_blogs($args)) {
2014            $blog_filter = 'and category_blog_id ' . $sql;
2015        } elseif (isset($args['blog_id'])) {
2016            $blog_id = intval($args['blog_id']);
2017            $blog_filter = 'and category_blog_id = ' . $blog_id;
2018        }
2019        $count = $this->get_var("
2020            select count(*)
2021              from mt_category
2022             where 1 = 1
2023             $blog_filter
2024        ");
2025        return $count;
2026    }
2027
2028    function tags_entry_count($tag_id, $class = 'entry') {
2029        $count = $this->get_var("
2030          select count(*)
2031            from mt_objecttag, mt_entry
2032           where objecttag_tag_id = " . intval($tag_id) . "
2033             and entry_id = objecttag_object_id and objecttag_object_datasource='entry'
2034             and entry_status = 2
2035             and entry_class = '$class'
2036        ");
2037        return $count;
2038    }
2039
2040    function entry_comment_count($entry_id) {
2041        if (isset($this->_comment_count_cache[$entry_id])) {
2042            return $this->_comment_count_cache[$entry_id];
2043        }
2044        $entry = $this->fetch_entry($entry_id);
2045        $count = $entry['entry_comment_count'];
2046        $this->_comment_count_cache[$entry_id] = $count;
2047        return $count;
2048    }
2049
2050    function author_entry_count($args) {
2051        if ($sql = $this->include_exclude_blogs($args)) {
2052            $blog_filter = 'and entry_blog_id ' . $sql;
2053        } elseif (isset($args['blog_id'])) {
2054            $blog_id = intval($args['blog_id']);
2055            $blog_filter = 'and entry_blog_id = ' . $blog_id;
2056        }
2057        if (isset($args['author_id'])) {
2058            $author_id = intval($args['author_id']);
2059            $author_filter = " and entry_author_id = $author_id";
2060        }
2061        if (isset($args['class'])) {
2062            $class = $args['class'];
2063        }
2064        $count = $this->get_var("
2065          select count(*)
2066            from mt_entry
2067            where entry_status = 2
2068            and entry_class='$class'
2069            $blog_filter
2070            $author_filter
2071            ");
2072        return $count;
2073    }
2074
2075    function &fetch_placements($args) {
2076        $category_id_list = $args['category_id'];
2077        $id_list = '';
2078        foreach ($category_id_list as $cat_id) {
2079            $id_list .= ',' . $cat_id;
2080        }
2081        if (empty($id_list))
2082            return;
2083        $id_list = substr($id_list, 1);
2084        $sql = "
2085            select mt_placement.*
2086              from mt_placement, mt_entry
2087              where placement_category_id in ($id_list)
2088               and entry_id = placement_entry_id and entry_status = 2
2089        ";
2090        $results = $this->get_results($sql, ARRAY_A);
2091        return $results;
2092    }
2093
2094    function &fetch_objecttags($args) {
2095        $tag_id_list = $args['tag_id'];
2096        $id_list = '';
2097        foreach ($tag_id_list as $tag_id) {
2098            $id_list .= ',' . $tag_id;
2099        }
2100        if (empty($id_list))
2101            return;
2102        $id_list = substr($id_list, 1);
2103
2104        $blog_filter = $this->include_exclude_blogs($args);
2105        if ($blog_filter == '' and $args['blog_id'])
2106            $blog_filter = intval($args['blog_id']);
2107        if ($blog_filter != '') 
2108            $blog_filter = 'and objecttag_blog_id = ' . $blog_filter;
2109
2110        if (isset($args['datasource']) && strtolower($args['datasource']) == 'asset') {
2111            $datasource = $args['datasource'];
2112            $from_object = 'mt_asset';
2113            $object_filter = 'and asset_id = objecttag_object_id';
2114        } else {
2115            $datasource = 'entry';
2116            $from_object = 'mt_entry';
2117            $object_filter = 'and entry_id = objecttag_object_id and entry_status = 2';
2118        }
2119        $sql = "
2120            select mt_objecttag.*
2121              from mt_objecttag, $from_object
2122              where
2123                objecttag_object_datasource ='$datasource'
2124                and objecttag_tag_id in ($id_list)
2125                $blog_filter
2126                $object_filter
2127        ";
2128        $results = $this->get_results($sql, ARRAY_A);
2129        return $results;
2130    }
2131
2132    function &fetch_comments($args) {
2133        # load comments
2134        $entry_id = intval($args['entry_id']);
2135
2136        $sql = $this->include_exclude_blogs($args);
2137        if ($sql != '') {
2138            $blog_filter = 'and comment_blog_id ' . $sql;
2139            if (isset($args['blog_id']))
2140                $blog =& $this->fetch_blog($args['blog_id']);
2141        } elseif ($args['blog_id']) {
2142            $blog =& $this->fetch_blog($args['blog_id']);
2143            $blog_filter = ' and comment_blog_id = ' . $blog['blog_id'];
2144        }
2145
2146        # Adds a score or rate filter to the filters list.
2147        if (isset($args['namespace'])) {
2148            require_once("MTUtil.php");
2149            $arg_names = array('min_score', 'max_score', 'min_rate', 'max_rate', 'min_count', 'max_count' );
2150            foreach ($arg_names as $n) {
2151                if (isset($args[$n])) {
2152                    $comment_args = $args[$n];
2153                    $cexpr = create_rating_expr_function($comment_args, $n, $args['namespace'], 'comment');
2154                    if ($cexpr) {
2155                        $filters[] = $cexpr;
2156                    } else {
2157                        return null;
2158                    }
2159                }
2160            }
2161            if (isset($args['scored_by'])) {
2162                $voter = $this->fetch_author_by_name($args['scored_by']);
2163                if (!$voter) {
2164                    echo "Invalid scored by filter: ".$args['scored_by'];
2165                    return null;
2166                }
2167                $cexpr = create_rating_expr_function($voter['author_id'], 'scored_by', $args['namespace'], 'comment');
2168                if ($cexpr) {
2169                    $filters[] = $cexpr;
2170                } else {
2171                    return null;
2172                }
2173            }
2174        }
2175
2176        $order = $query_order = 'desc';
2177        if (isset($args['sort_order'])) {
2178            if ($args['sort_order'] == 'ascend') {
2179                $order = $query_order = 'asc';
2180            }
2181        } elseif (isset($blog) && isset($blog['blog_sort_order_comments'])) {
2182            if ($blog['blog_sort_order_comments'] == 'ascend') {
2183                $order = $query_order = 'asc';
2184            }
2185        }
2186        if ($order == 'asc' && (isset($args['lastn']) || isset($args['offset']))) {
2187            $reorder = 1;
2188            $query_order = 'desc';
2189        }
2190
2191        if ($entry_id) {
2192            $entry_filter = " and comment_entry_id = $entry_id";
2193            $entry_join = "join mt_entry on entry_id = comment_entry_id";
2194        } else {
2195            $entry_join = "join mt_entry on entry_id = comment_entry_id and entry_status = 2";
2196        }
2197
2198        $join_score = "";
2199        $distinct = "";
2200        if ( isset($args['sort_by'])
2201          && (($args['sort_by'] == 'score') || ($args['sort_by'] == 'rate')) ) {
2202            $join_score = "join mt_objectscore on objectscore_object_id = comment_id and objectscore_namespace='".$args['namespace']."' and objectscore_object_ds='comment'";
2203            $distinct = " distinct";
2204        }
2205
2206        $limit = 0;
2207        $offset = 0;
2208        if (isset($args['lastn']))
2209            $limit = $args['lastn'];
2210        if (isset($args['limit']))
2211