root/branches/release-39/php/lib/mtdb_base.php @ 2519

Revision 2519, 122.0 kB (checked in by fumiakiy, 18 months ago)

Fixed when to apply the value from entries_on_index in PHP. BugId:80044

  • 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        // determine any custom fields that we should filter on
472        $fields = array();
473        foreach ($args as $name => $v)
474            if (preg_match('/^field___(\w+)$/', $name, $m))
475                $fields[$m[1]] = $v;
476
477        # automatically include offset if in request
478        if ($args['offset'] == 'auto') {
479            $args['offset'] = 0;
480            if ($args['limit'] || $args['lastn']) {
481                if ($_REQUEST['offset'] > 0) {
482                    $args['offset'] = $_REQUEST['offset'];
483                }
484            }
485        }
486
487        if ($args['limit'] > 0) {
488            $args['lastn'] = $args['limit'];
489        } elseif (!isset($args['days']) && !isset($args['lastn'])) {
490        #    if ($days = $blog['blog_days_on_index']) {
491        #        if (!isset($args['recently_commented_on'])) {
492        #            $args['days'] = $days;
493        #        }
494        #    } elseif ($posts = $blog['blog_entries_on_index']) {
495        #        $args['lastn'] = $posts;
496        #    }
497            if ($posts = $blog['blog_entries_on_index']) {
498                $limit = $posts;
499            }
500        }
501        if ($args['limit'] == 'auto') {
502            if (($_REQUEST['limit'] > 0) && ($_REQUEST['limit'] < $args['lastn'])) {
503                $args['lastn'] = intval($_REQUEST['limit']);
504            }
505        }
506
507        if (isset($args['include_blogs']) or isset($args['exclude_blogs'])) {
508            $blog_ctx_arg = isset($args['include_blogs']) ?
509                array('include_blogs' => $args['include_blogs']) :
510                array('exclude_blogs' => $args['exclude_blogs']);
511        }
512
513        # a context hash for filter routines
514        $ctx = array();
515        $filters = array();
516
517        if (!isset($_REQUEST['entry_ids_published'])) {
518            $_REQUEST['entry_ids_published'] = array();
519        }
520
521        if (isset($args['unique'])) {
522            $filters[] = create_function('$e,$ctx', 'return !isset($ctx["entry_ids_published"][$e["entry_id"]]);');
523            $ctx['entry_ids_published'] = &$_REQUEST['entry_ids_published'];
524        }
525
526        # special case for selecting a particular entry
527        if (isset($args['entry_id'])) {
528            $entry_filter = 'and entry_id = '.$args['entry_id'];
529            $start = ''; $end = ''; $limit = 1; $blog_filter = ''; $day_filter = '';
530        } else {
531            $entry_filter = '';
532        }
533
534        # special case for excluding a particular entry
535        if (isset($args['not_entry_id'])) {
536            $entry_filter .= ' and entry_id != '.$args['not_entry_id'];
537        }
538
539        $entry_list = array();
540
541        # Adds a category filter to the filters list.
542        $cat_class = 'category';
543        if (!isset($args['class']))
544            $args['class'] = 'entry';
545        if ($args['class'] == 'page')
546            $cat_class = 'folder';
547
548        if (isset($args['category']) or isset($args['categories'])) {
549            $category_arg = isset($args['category']) ? $args['category'] : $args['categories'];
550            require_once("MTUtil.php");
551            if (!preg_match('/\b(AND|OR|NOT)\b|\(|\)/i', $category_arg)) {
552                $not_clause = false;
553                $cats = cat_path_to_category($category_arg, $blog_ctx_arg, $cat_class);
554                if (count($cats)) {
555                    $category_arg = '';
556                    foreach ($cats as $cat) {
557                        if ($category_arg != '')
558                            $category_arg .= '|| ';
559                        $category_arg .= '#' . $cat['category_id'];
560                    }
561                    $category_arg = '(' . $category_arg . ')';
562                }
563            } else {
564                $not_clause = preg_match('/\bNOT\b/i', $category_arg);
565                if ($blog_ctx_arg)
566                    $cats =& $this->fetch_categories(array_merge($blog_ctx_arg, array('show_empty' => 1, 'class' => $cat_class)));
567                else
568                    $cats =& $this->fetch_categories(array('blog_id' => $blog_id, 'show_empty' => 1, 'class' => $cat_class));
569            }
570            if (!is_array($cats)) $cats = array();
571            $cexpr = create_cat_expr_function($category_arg, $cats, array('children' => $args['include_subcategories']));
572            if ($cexpr) {
573                $cmap = array();
574                $cat_list = array();
575                foreach ($cats as $cat)
576                    $cat_list[] = $cat['category_id'];
577                $pl =& $this->fetch_placements(array('category_id' => $cat_list));
578                if ($pl) {
579                    foreach ($pl as $p) {
580                        $cmap[$p['placement_entry_id']][$p['placement_category_id']]++;
581                        if (!$not_clause)
582                            $entry_list[$p['placement_entry_id']] = 1;
583                    }
584                }
585                $ctx['p'] =& $cmap;
586                $filters[] = $cexpr;
587            } else {
588                return null;
589            }
590        } elseif (isset($args['category_id'])) {
591            require_once("MTUtil.php");
592            $cat = $this->fetch_category($args['category_id']);
593            if ($cat) {
594                $cats = array($cat);
595                $cmap = array();
596                $cexpr = create_cat_expr_function($cat['category_label'], $cats, array('children' => $args['include_subcategories']));
597                $pl =& $this->fetch_placements(array('category_id' => array($cat['category_id'])));
598                if ($pl) {
599                    foreach ($pl as $p) {
600                        $cmap[$p['placement_entry_id']][$p['placement_category_id']]++;
601                    }
602                    $ctx['p'] =& $cmap;
603                    $filters[] = $cexpr;
604                } else {
605                    # this category have no entries (or pages)
606                    return null;
607                }
608            }
609        }
610        if ((0 == count($filters)) && (isset($args['show_empty']) && (1 == $args['show_empty']))) {
611            return null;
612        }
613
614        # Adds a tag filter to the filters list.
615        if (isset($args['tags']) or isset($args['tag'])) {
616            $tag_arg = isset($args['tag']) ? $args['tag'] : $args['tags'];
617            require_once("MTUtil.php");
618            $not_clause = preg_match('/\bNOT\b/i', $tag_arg);
619
620            require_once("MTUtil.php");
621            $include_private = 0;
622            $tag_array = tag_split($tag_arg);
623            foreach ($tag_array as $tag) {
624                if ($tag && (substr($tag,0,1) == '@')) {
625                    $include_private = 1;
626                }
627            }
628            if (isset($blog_ctx_arg))
629                $tags =& $this->fetch_entry_tags(array($blog_ctx_arg, 'tag' => $tag_arg, 'include_private' => $include_private, 'class' => $args['class']));
630            else
631                $tags =& $this->fetch_entry_tags(array('blog_id' => $blog_id, 'tag' => $tag_arg, 'include_private' => $include_private, 'class' => $args['class']));
632            if (!is_array($tags)) $tags = array();
633            $cexpr = create_tag_expr_function($tag_arg, $tags);
634
635            if ($cexpr) {
636                $tmap = array();
637                $tag_list = array();
638                foreach ($tags as $tag) {
639                    $tag_list[] = $tag['tag_id'];
640                }
641                if (isset($blog_ctx_arg))
642                    $ot =& $this->fetch_objecttags(array('tag_id' => $tag_list, 'datasource' => 'entry', $blog_ctx_arg));
643                elseif ($args['blog_id'])
644                    $ot =& $this->fetch_objecttags(array('tag_id' => $tag_list, 'datasource' => 'entry', 'blog_id' => $args['blog_id']));
645                if ($ot) {
646                    foreach ($ot as $o) {
647                            $tmap[$o['objecttag_object_id']][$o['objecttag_tag_id']]++;
648                        if (!$not_clause)
649                            $entry_list[$o['objecttag_object_id']] = 1;
650                    }
651                }
652                $ctx['t'] =& $tmap;
653                $filters[] = $cexpr;
654            } else {
655                return null;
656            }
657        }
658
659        # Adds a score or rate filter to the filters list.
660        if (isset($args['namespace'])) {
661            require_once("MTUtil.php");
662            $arg_names = array('min_score', 'max_score', 'min_rate', 'max_rate', 'min_count', 'max_count' );
663            foreach ($arg_names as $n) {
664                if (isset($args[$n])) {
665                    $rating_args = $args[$n];
666                    $cexpr = create_rating_expr_function($rating_args, $n, $args['namespace']);
667                    if ($cexpr) {
668                        $filters[] = $cexpr;
669                    } else {
670                        return null;
671                    }
672                }
673            }
674
675            if (isset($args['scored_by'])) {
676                $voter = $this->fetch_author_by_name($args['scored_by']);
677                if (!$voter) {
678                    echo "Invalid scored by filter: ".$args['scored_by'];
679                    return null;
680                }
681                $cexpr = create_rating_expr_function($voter['author_id'], 'scored_by', $args['namespace']);
682                if ($cexpr) {
683                    $filters[] = $cexpr;
684                } else {
685                    return null;
686                }
687            }
688        }
689
690        if (count($entry_list) && ($entry_filter == '')) {
691            $entry_list = implode(",", array_keys($entry_list));
692            # set a reasonable cap on the entry list cache. if
693            # user is selecting something too big, then they'll
694            # just have to wait through a scan.
695            if (strlen($entry_list) < 2048)
696                $entry_filter = "and entry_id in ($entry_list)";
697        }
698
699        if (isset($args['author']))
700            $author_filter = 'and author_name = \'' .
701                $this->escape($args['author']) . "'";
702
703        $start = isset($args['current_timestamp'])
704            ? $args['current_timestamp'] : null;
705        $end = isset($args['current_timestamp_end'])
706            ? $args['current_timestamp_end'] : null;
707        if ($start and $end) {
708            $start = $this->ts2db($start);
709            $end = $this->ts2db($end);
710            $date_filter = "and entry_authored_on between '$start' and '$end'";
711        } elseif ($start) {
712            $start = $this->ts2db($start);
713            $date_filter = "and entry_authored_on >= '$start'";
714        } elseif ($end) {
715            $end = $this->ts2db($end);
716            $date_filter = "and entry_authored_on <= '$end'";
717        } else {
718            $date_filter = '';
719        }
720
721        if (isset($args['lastn'])) {
722            if (!isset($args['entry_id'])) $limit = $args['lastn'];
723        } elseif (isset($args['days']) && !$date_filter) {
724            $day_filter = 'and ' . $this->limit_by_day_sql('entry_authored_on', intval($args['days']));
725        } else {
726            $found_valid_args = 0;
727            foreach ( array(
728                'lastn', 'days',
729                'category', 'categories', 'category_id',
730                'tag', 'tags',
731                'author',
732                'min_score',  'max_score',
733                'min_rate',    'max_rate',
734                'min_count',  'max_count'
735              ) as $valid_key )
736            {
737                if (array_key_exists($valid_key, $args)) {
738                    $found_valid_args = 1;
739                    break;
740                }
741            }
742            if ((!isset($args['current_timestamp']) &&
743                !isset($args['current_timestamp_end'])) &&
744                ($limit <= 0) &&
745                (!$found_valid_args) &&
746                (isset($blog))) {
747                if ($days = $blog['blog_days_on_index']) {
748                    if (!isset($args['recently_commented_on'])) {
749                        $day_filter = 'and ' . $this->limit_by_day_sql('entry_authored_on', $days);
750                    }
751                } elseif ($posts = $blog['blog_entries_on_index']) {
752                    $limit = $posts;
753                }
754            }
755        }
756
757        if (isset($args['sort_order'])) {
758            if ($args['sort_order'] == 'ascend') {
759                $order = 'asc';
760            } else if ($args['sort_order'] == 'descend') {
761                $order = 'desc';
762            }
763        } 
764        if (!isset($order)) {
765            $order = 'desc';
766            if (isset($blog) && isset($blog['blog_sort_order_posts'])) {
767                if ($blog['blog_sort_order_posts'] == 'ascend') {
768                    $order = 'asc';
769                }
770            }
771        }
772
773        if (isset($args['class'])) {
774            $class = $this->escape($args['class']);
775        } else {
776            $class = 'entry';
777        }
778        $class_filter = "and entry_class='$class'";
779        if ($args['class'] == '*') $class_filter = '';
780       
781        $join_score = "";
782        $distinct = "";
783        if ( isset($args['sort_by'])
784          && (($args['sort_by'] == 'score') || ($args['sort_by'] == 'rate')) ) {
785            $join_score = "left join mt_objectscore on objectscore_object_id = entry_id and objectscore_namespace='"
786                . $args['namespace']."' and objectscore_object_ds='".$class."'";
787            $distinct = " distinct";
788        }
789
790        if (isset($args['offset']))
791            $offset = $args['offset'];
792
793        if (isset($args['limit'])) {
794            if (isset($args['sort_by'])) { 
795                if ($args['sort_by'] == 'title') { 
796                    $sort_field = 'entry_title'; 
797                } elseif ($args['sort_by'] == 'id') { 
798                    $sort_field = 'entry_id'; 
799                } elseif ($args['sort_by'] == 'status') { 
800                    $sort_field = 'entry_status'; 
801                } elseif ($args['sort_by'] == 'modified_on') { 
802                    $sort_field = 'entry_modified_on'; 
803                } elseif ($args['sort_by'] == 'author_id') { 
804                    $sort_field = 'entry_author_id'; 
805                } elseif ($args['sort_by'] == 'excerpt') { 
806                    $sort_field = 'entry_excerpt'; 
807                } elseif ($args['sort_by'] == 'comment_created_on') { 
808                    $sort_field = $args['sort_by']; 
809                } elseif ($args['sort_by'] == 'score' || $args['sort_by'] == 'rate') { 
810                    $post_sort_limit = $limit;
811                    $post_sort_offset = $offset;
812                    $limit = 0; $offset = 0;
813                } elseif ($args['sort_by'] == 'trackback_count') {
814                    $sort_field = 'entry_ping_count'; 
815                } elseif (preg_match('/field[:\.]/', $args['sort_by'])) {
816                    $no_resort = 0;
817                } else { 
818                    $sort_field = 'entry_' . $args['sort_by']; 
819                } 
820                if ($sort_field) $no_resort = 1; 
821            } 
822            else {
823                $sort_field ='entry_authored_on';
824            }
825            if ($sort_field) {
826                $base_order = ($args['sort_order'] == 'ascend' ? 'asc' : 'desc');
827                $base_order or $base_order = 'desc';
828            }
829        } else {
830            $base_order = 'desc';
831            if (isset($args['base_sort_order'])) {
832                if ($args['base_sort_order'] == 'ascend')
833                    $base_order = 'asc';
834            }
835            $sort_field ='entry_authored_on'; 
836            $no_resort = 0;
837        }
838
839        if (count($filters)) {
840            $post_select_limit = $limit;
841            $post_select_offset = $offset;
842            $limit = 0; $offset = 0;
843        }
844
845        if (count($fields)) {
846            $meta_join_num = 1;
847            $meta_join = "";
848            $entry_meta = array();
849            foreach ($this->object_meta['entry'] as $meta) {
850                list($meta_key, $meta_type) = preg_split('/:/', $meta);
851                $entry_meta[$meta_key] = $meta_type;
852            }
853            foreach ($fields as $name => $value) {
854                $meta_col = $entry_meta['field.' . $name];
855                if (!$meta_col) return null; # invalid column; can't select
856
857                $value = $this->escape($value);
858                $meta_join .= " join mt_entry_meta entry_meta$meta_join_num on (entry_meta$meta_join_num.entry_meta_entry_id = entry_id
859                and entry_meta$meta_join_num.entry_meta_type = 'field.$name'
860                and entry_meta$meta_join_num.entry_meta_$meta_col='$value')\n";
861                $meta_join_num++;
862            }
863        }
864
865        $sql = "
866            select$distinct mt_entry.*, mt_placement.*, mt_author.*,
867                   mt_trackback.*
868              from mt_entry
869              left outer join mt_trackback on trackback_entry_id = entry_id
870              $meta_join
871              $join_score
872              left outer join mt_placement on (placement_entry_id = entry_id
873                and placement_is_primary = 1),
874                   mt_author
875             where entry_status = 2
876               and entry_author_id = author_id
877                   $blog_filter
878                   $entry_filter
879                   $author_filter
880                   $date_filter
881                   $day_filter
882                   $class_filter
883        ";
884
885        if ($sort_field) {
886            $sql .= "
887                order by $sort_field $base_order";
888        }
889        if (isset($args['recently_commented_on'])) {
890            $rco = $args['recently_commented_on'];
891            $sql = $this->entries_recently_commented_on_sql($sql);
892            $sql = $this->apply_limit_sql($sql, count($filters) ? null : $rco);
893            $args['sort_by'] or $args['sort_by'] = 'comment_created_on';
894            $args['sort_order'] or $args['sort_order'] = 'descend';
895            $post_select_limit = $rco;
896            $no_resort = 1;
897        } elseif ( !is_null($total_count) ) {
898            $orig_limit = $limit;
899            $orig_offset = $offset;
900        } else {
901            $sql = $this->apply_limit_sql($sql . " <LIMIT>", $limit, $offset);
902        }
903
904        $result = $this->query_start($sql);
905        if (!$result) return null;
906
907        $entries = array();
908        $j = 0;
909        $offset = $post_select_offset ? $post_select_offset : $orig_offset;
910        $limit = $post_select_limit ? $post_select_limit : 0;
911        $id_list = array();
912        $_total_count = 0;
913        while (true) {
914            $e = $this->query_fetch(ARRAY_A);
915            if (!isset($e)) break;
916            if (count($filters)) {
917                foreach ($filters as $f) {
918                    $old_result = $this->result;
919                    if (!$f($e, $ctx)) {
920                        $this->result = $old_result;
921                        continue 2;
922                    }
923                    $this->result = $old_result;
924                }
925            }
926            $_total_count++;
927            if ( !is_null($total_count) ) {
928                if ( ($orig_limit > 0)
929                  && ( ($_total_count-$offset) > $orig_limit) ) {
930                    // collected all the entries; only count numbers;
931                    continue;
932                }
933            }
934            if ($offset && ($j++ < $offset)) continue;
935            $e['entry_authored_on'] = $this->db2ts($e['entry_authored_on']);
936            $e['entry_modified_on'] = $this->db2ts($e['entry_modified_on']);
937            $e = $this->expand_meta($e);
938            $id_list[] = $e['entry_id'];
939            $entries[] = $e;
940            $this->_comment_count_cache[$e['entry_id']] = $e['entry_comment_count'];
941            $this->_ping_count_cache[$e['entry_id']] = $e['entry_ping_count'];
942            if ( is_null($total_count) ) {
943                // the request does not want total count; break early
944                if (($limit > 0) && (count($entries) >= $limit)) break;
945            }
946        }
947        if ( !is_null($total_count) )
948            $total_count = $_total_count;
949
950        if (!$no_resort) {
951            $sort_field = '';
952            if (isset($args['sort_by'])) {
953                if ($args['sort_by'] == 'title') {
954                    $sort_field = 'entry_title';
955                } elseif ($args['sort_by'] == 'id') {
956                    $sort_field = 'entry_id';
957                } elseif ($args['sort_by'] == 'status') {
958                    $sort_field = 'entry_status';
959                } elseif ($args['sort_by'] == 'modified_on') {
960                    $sort_field = 'entry_modified_on';
961                } elseif ($args['sort_by'] == 'author_id') {
962                    $sort_field = 'entry_author_id';
963                } elseif ($args['sort_by'] == 'excerpt') {
964                    $sort_field = 'entry_excerpt';
965                } elseif ($args['sort_by'] == 'comment_created_on') {
966                    $sort_field = $args['sort_by'];
967                } elseif ($args['sort_by'] == 'score') {
968                    $sort_field = $args['sort_by'];
969                } elseif ($args['sort_by'] == 'rate') {
970                    $sort_field = $args['sort_by'];
971                } elseif ($args['sort_by'] == 'trackback_count') {
972                    $sort_field = 'entry_ping_count'; 
973                } elseif (preg_match('/^field[:\.](.+)$/', $args['sort_by'], $match)) {
974                    $sort_field = 'entry_field.' . $match[1];
975                } else {
976                    $sort_field = 'entry_' . $args['sort_by'];
977                }
978            } else {
979                $sort_field = 'entry_authored_on';
980            }
981            if ($sort_field) {
982                if ($sort_field == 'score') {
983                    $offset = $post_sort_offset ? $post_sort_offset : 0;
984                    $limit = $post_sort_limit ? $post_sort_limit : 0;
985                    $entries_tmp = array();
986                    foreach ($entries as $e) {
987                        $entries_tmp[$e['entry_id']] = $e;
988                    }
989                    $scores = $this->fetch_sum_scores($args['namespace'], 'entry', $order,
990                        $blog_filter . "\n" .
991                        $entry_filter . "\n" .
992                        $author_filter . "\n" .
993                        $date_filter . "\n" .
994                        $day_filter . "\n" .
995                        $class_filter . "\n"
996                    );
997                    $entries_sorted = array();
998                    foreach($scores as $score) {
999                        if (--$offset >= 0) continue;
1000                        if (array_key_exists($score['objectscore_object_id'], $entries_tmp)) {
1001                            array_push($entries_sorted, $entries_tmp[$score['objectscore_object_id']]);
1002                            unset($entries_tmp[$score['objectscore_object_id']]);
1003                            if (--$limit == 0) break;
1004                        }
1005                    }
1006                    foreach ($entries_tmp as $et) {
1007                        if ($limit == 0) break;
1008                        if ($order == 'asc')
1009                            array_unshift($entries_sorted, $et);
1010                        else
1011                            array_push($entries_sorted, $et);
1012                        $limit--;
1013                    }
1014                    $entries = $entries_sorted;
1015                } elseif ($sort_field == 'rate') {
1016                    $offset = $post_sort_offset ? $post_sort_offset : 0;
1017                    $limit = $post_sort_limit ? $post_sort_limit : 0;
1018                    $entries_tmp = array();
1019                    foreach ($entries as $e) {
1020                        $entries_tmp[$e['entry_id']] = $e;
1021                    }
1022                    $scores = $this->fetch_avg_scores($args['namespace'], 'entry', $order,
1023                        $blog_filter . "\n" .
1024                        $entry_filter . "\n" .
1025                        $author_filter . "\n" .
1026                        $date_filter . "\n" .
1027                        $day_filter . "\n" .
1028                        $class_filter . "\n"
1029                    );
1030                    $entries_sorted = array();
1031                    foreach($scores as $score) {
1032                        if (--$offset >= 0) continue;
1033                        if (array_key_exists($score['objectscore_object_id'], $entries_tmp)) {
1034                            array_push($entries_sorted, $entries_tmp[$score['objectscore_object_id']]);
1035                            unset($entries_tmp[$score['objectscore_object_id']]);
1036                            if (--$limit == 0) break;
1037                        }
1038                    }
1039                    foreach ($entries_tmp as $et) {
1040                        if ($limit == 0) break;
1041                        if ($order == 'asc')
1042                            array_unshift($entries_sorted, $et);
1043                        else
1044                            array_push($entries_sorted, $et);
1045                        $limit--;
1046                    }
1047                    $entries = $entries_sorted;
1048                } else {
1049                    if (($sort_field == 'entry_status') || ($sort_field == 'entry_author_id') || ($sort_field == 'entry_id')
1050                          || ($sort_field == 'entry_comment_count') || ($sort_field == 'entry_ping_count')) {
1051                        $sort_fn = "if (\$a['$sort_field'] == \$b['$sort_field']) return 0; return \$a['$sort_field'] < \$b['$sort_field'] ? -1 : 1;";
1052                    } else {
1053                        $sort_fn = "return strcmp(\$a['$sort_field'],\$b['$sort_field']);";
1054                    }
1055                    $sorter = create_function(
1056                        $order == 'asc' ? '$a,$b' : '$b,$a',
1057                        $sort_fn);
1058                    usort($entries, $sorter);
1059                }
1060            }
1061        }
1062
1063        if (count($id_list) <= 30) { # TODO: find a good upper limit
1064            # pre-cache comment counts and categories for these entries
1065            $this->cache_categories($id_list);
1066            $this->cache_permalinks($id_list);
1067        }
1068
1069        return $entries;
1070    }
1071
1072    function fetch_plugin_config($plugin, $scope = "system") {
1073        if ($scope != 'system') {
1074            $key = 'configuration:'.$scope;
1075        } else {
1076            $key = 'configuration';
1077        }
1078        return $this->fetch_plugin_data($plugin, $key);
1079    }
1080
1081    function fetch_plugin_data($plugin, $key) {
1082        $plugin = $this->escape($plugin);
1083        $key = $this->escape($key);
1084        $sql = "
1085            select plugindata_data from mt_plugindata
1086             where plugindata_plugin = '$plugin'
1087               and plugindata_key = '$key'";
1088        $data = $this->get_var($sql);
1089        if ($data) {
1090            return $this->unserialize($data);
1091        }
1092        return null;
1093    }
1094
1095    function &fetch_entry_tags($args) {
1096        $class = 'entry';
1097        if (isset($args['class'])) {
1098            $class = $args['class'];
1099        }
1100
1101        # load tags
1102        if (isset($args['entry_id'])) {
1103            if (!isset($args['tags']) && !isset($args['tag'])) {
1104                if (isset($this->_entry_tag_cache[$args['entry_id']])) {
1105                    return $this->_entry_tag_cache[$args['entry_id']];
1106                }
1107            }
1108            $entry_filter = 'and objecttag_tag_id in (select objecttag_tag_id from mt_objecttag where objecttag_object_id='.intval($args['entry_id']).')';
1109        }
1110
1111        $blog_filter = $this->include_exclude_blogs($args);
1112        if ($blog_filter == '' and isset($args['blog_id'])) {
1113            if (!isset($args['tags']) && !isset($args['tag'])) {
1114                if (!isset($args['entry_id'])) {
1115                    if (isset($this->_blog_tag_cache[$args['blog_id'].":$class"])) {
1116                        return $this->_blog_tag_cache[$args['blog_id'].":$class"];
1117                    }
1118                }
1119            }
1120            $blog_filter = ' = '. intval($args['blog_id']);
1121        }
1122        if ($blog_filter != '') 
1123            $blog_filter = 'and objecttag_blog_id ' . $blog_filter;
1124
1125        if (!isset($args['include_private'])) {
1126            $private_filter = 'and (tag_is_private = 0 or tag_is_private is null)';
1127        }
1128        if (isset($args['tags']) && ($args['tags'] != '')) {
1129            $tag_list = '';
1130            require_once("MTUtil.php");
1131            $tag_array = tag_split($args['tags']);
1132            foreach ($tag_array as $tag) {
1133                if ($tag_list != '') $tag_list .= ',';
1134                $tag_list .= "'" . $this->escape($tag) . "'";
1135            }
1136            if ($tag_list != '') {
1137                $tag_filter = 'and (tag_name in (' . $tag_list . '))';
1138                $private_filter = '';
1139            }
1140        }
1141
1142        $sort_col = isset($args['sort_by']) ? $args['sort_by'] : 'name';
1143        $sort_col = "tag_$sort_col";
1144        if (isset($args['sort_order']) and $args['sort_order'] == 'descend') {
1145            $order = 'desc';
1146        } else {
1147            $order = 'asc';
1148        }
1149        $id_order = '';
1150        if ($sort_col == 'tag_name') {
1151            $sort_col = 'lower(tag_name)';
1152        }else{
1153            $id_order = ', lower(tag_name)';
1154        }
1155
1156        $sql = "
1157            select tag_id, tag_name, count(*) as tag_count
1158             from mt_tag, mt_objecttag, mt_entry
1159             where objecttag_tag_id = tag_id
1160               and entry_id = objecttag_object_id and objecttag_object_datasource='entry'
1161               and entry_status = 2
1162                   and entry_class = '$class'
1163                   $blog_filter
1164                   $tag_filter
1165                   $entry_filter
1166                   $private_filter
1167            group by tag_id, tag_name
1168            order by $sort_col $order $id_order";
1169        $tags = $this->get_results($sql, ARRAY_A);
1170        if (!isset($args['tag'])) {
1171            if ($args['entry_id'])
1172                $this->_entry_tag_cache[$args['entry_id']] = $tags;
1173            elseif ($args['blog_id'])
1174                $this->_blog_tag_cache[$args['blog_id'].":$class"] = $tags;
1175        }
1176        return $tags;
1177    }
1178
1179    function &fetch_asset_tags($args) {
1180
1181        # load tags by asset
1182        if (!isset($args['include_private'])) {
1183            $private_filter = 'and (tag_is_private = 0 or tag_is_private is null)';
1184        }
1185
1186        if (isset($args['asset_id'])) {
1187            if (isset($args['tags'])) {
1188                if (isset($this->_asset_tag_cache[$args['asset_id']]))
1189                    return $this->_asset_tag_cache[$args['asset_id']];
1190            }
1191            $asset_filter = 'and objecttag_object_id = '.intval($args['asset_id']);
1192        }
1193       
1194        if (isset($args['blog_id'])) {
1195            if (!isset($args['tags'])) {
1196                if (isset($this->_blog_asset_tag_cache[$args['blog_id']]))
1197                    return $this->_blog_asset_tag_cache[$args['blog_id']];
1198            }
1199            $blog_filter = 'and objecttag_blog_id = '.intval($args['blog_id']);
1200        }
1201
1202        if (isset($args['tags']) && ($args['tags'] != '')) {
1203            $tag_list = '';
1204            require_once("MTUtil.php");
1205            $tag_array = tag_split($args['tags']);
1206            foreach ($tag_array as $tag) {
1207                if ($tag_list != '') $tag_list .= ',';
1208                $tag_list .= "'" . $this->escape($tag) . "'";
1209            }
1210            if ($tag_list != '') {
1211                $tag_filter = 'and (tag_name in (' . $tag_list . '))';
1212                $private_filter = '';
1213            }
1214        }
1215
1216        $sort_col = isset($args['sort_by']) ? $args['sort_by'] : 'name';
1217        $sort_col = "tag_$sort_col";
1218        if (isset($args['sort_order']) and $args['sort_order'] == 'descend')
1219            $order = 'desc';
1220        else
1221            $order = 'asc';
1222
1223        $id_order = '';
1224        if ($sort_col == 'tag_name')
1225            $sort_col = 'lower(tag_name)';
1226        else
1227            $id_order = ', lower(tag_name)';
1228
1229        $sql = "
1230            select tag_id, tag_name, count(*) as tag_count
1231            from mt_tag, mt_objecttag, mt_asset
1232            where objecttag_tag_id = tag_id
1233                and asset_id = objecttag_object_id and objecttag_object_datasource='asset'
1234                $blog_filter
1235                $private_filter
1236                $tag_filter
1237                $asset_filter
1238            group by tag_id, tag_name
1239            order by $sort_col $order $id_order
1240        ";
1241        $tags = $this->get_results($sql, ARRAY_A);
1242        if (isset($args['tags'])) {
1243            if ($args['asset_id'])
1244                $this->_asset_tag_cache[$args['asset_id']] = $tags;
1245            elseif ($args['blog_id'])
1246                $this->_blog_asset_tag_cache[$args['blog_id']] = $tags;
1247        }
1248        return $tags;
1249    }
1250
1251    function &fetch_folders($args) {
1252        $args['class'] = 'folder';
1253        return $this->fetch_categories($args);
1254    }
1255
1256    function &fetch_categories($args) {
1257        # load categories
1258
1259        if ($blog_filter = $this->include_exclude_blogs($args)) {
1260             $blog_filter = 'and category_blog_id '. $blog_filter;
1261        } elseif (isset($args['blog_id'])) {
1262            $blog_filter = 'and category_blog_id = '.intval($args['blog_id']);
1263        }
1264        if (isset($args['parent'])) {
1265            $parent = $args['parent'];
1266            if (is_array($parent)) {
1267                $parent_filter = 'and category_parent in (' . implode(',', $parent) . ')';
1268            } else {
1269                $parent_filter = 'and category_parent = '.intval($parent);
1270            }
1271        }
1272        if (isset($args['category_id'])) {
1273            if (isset($args['children'])) {
1274                if (isset($this->_cat_id_cache['c'.$args['category_id']])) {
1275                    $cat = $this->_cat_id_cache['c'.$args['category_id']];
1276                    if (isset($cat['_children'])) {
1277                        $children = $cat['_children'];
1278                        if ($children === false) {
1279                            return null;
1280                        } else {
1281                            return $children;
1282                        }
1283                    }
1284                }
1285
1286                $cat_filter = 'and category_parent = '.intval($args['category_id']);
1287            } else {
1288                $cat_filter = 'and category_id = '.intval($args['category_id']);
1289                $limit = 1;
1290            }
1291        } elseif (isset($args['label'])) {
1292            $cat_filter = 'and category_label = \''.$this->escape($args['label']).'\'';
1293        } else {
1294            $limit = $args['lastn'];
1295            if (isset($args['sort_order'])) {
1296                if ($args['sort_order'] == 'ascend') {
1297                    $sort_order = 'asc';
1298                } elseif ($args['sort_order'] == 'descend') {
1299                    $sort_order = 'desc';
1300                }
1301            } else {
1302                $sort_order = '';
1303            }
1304        }
1305        $count_column = 'placement_id';
1306        if ($args['show_empty']) {
1307            $join_clause = 'left outer join mt_placement on placement_category_id = category_id';
1308            if (isset($args['entry_id'])) {
1309                $join_clause .= ' left outer join mt_entry on placement_entry_id = entry_id and entry_id = '.intval($args['entry_id']);
1310            } else {
1311                $join_clause .= ' left outer join mt_entry on placement_entry_id = entry_id and entry_status = 2';
1312            }
1313            $count_column = 'entry_id';
1314        } else {
1315            $join_clause = ', mt_entry, mt_placement';
1316            $cat_filter .= ' and placement_category_id = category_id';
1317            if (isset($args['entry_id'])) {
1318                $entry_filter = 'and placement_entry_id = entry_id and placement_entry_id = '.intval($args['entry_id']);
1319            } else {
1320                $entry_filter = 'and placement_entry_id = entry_id and entry_status = 2';
1321            }
1322        }
1323
1324        if (isset($args['class'])) {
1325            $class = $this->escape($args['class']);
1326        } else {
1327            $class = "category";
1328        }
1329        $class_filter = "and category_class='$class'";
1330
1331        $sql = "
1332            select category_id, count($count_column) as category_count
1333              from mt_category $join_clause
1334             where 1 = 1
1335                   $cat_filter
1336                   $entry_filter
1337                   $blog_filter
1338                   $parent_filter
1339                   $class_filter
1340             group by category_id
1341                   <LIMIT>
1342        ";
1343        $sql = $this->apply_limit_sql($sql, $limit, $offset);
1344
1345        $categories = $this->get_results($sql, ARRAY_A);
1346        if (!$categories) {
1347            return null;
1348        }
1349        if (isset($args['children']) && isset($parent_cat)) {
1350            $parent_cat['_children'] =& $categories;
1351        } else {
1352            $ids = array();
1353            $counts = array();
1354            foreach ($categories as $cid => $cat) {
1355                $counts[$cat['category_id']] = $cat['category_count'];
1356                $ids[] = $cat['category_id'];
1357            }
1358            $list = implode(",", $ids);
1359            $sql2 = "
1360                select mt_category.*, mt_trackback.*
1361                    from mt_category left outer join mt_trackback on trackback_category_id = category_id
1362                   where category_id in ($list)
1363                order by category_label $sort_order
1364            ";
1365            $categories = $this->get_results($sql2, ARRAY_A);
1366            $id_list = array();
1367            foreach ($categories as $cid => $cat) {
1368                $cat_id = $cat['category_id'];
1369                $categories[$cid]['category_count'] = $counts[$cat_id];
1370                if (isset($args['top_level_categories']) || !isset($this->_cat_id_cache['c'.$cat_id])) {
1371                    $id_list[] = $cat_id;
1372                    $this->_cat_id_cache['c'.$cat_id] = $categories[$cid];
1373                }
1374                if (isset($args['top_level_categories'])) {
1375                    $this->_cat_id_cache['c'.$cat_id]['_children'] = false;
1376                }
1377            }
1378
1379            $top_cats = array();
1380            foreach ($categories as $cid => $cat) {
1381                if ($cat['category_parent'] > 0) {
1382                    $parent_id = $cat['category_parent'];
1383                    if (isset($this->_cat_id_cache['c'.$parent_id])) {
1384                        if (isset($args['top_level_categories'])) {
1385                            $parent =& $this->fetch_category($categories[$cid]['category_parent']);
1386                            if (!isset($parent['_children']) || ($parent['_children'] === false)) {
1387                                $parent['_children'] = array(&$categories[$cid]);
1388                            } else {
1389                                $parent['_children'][] = $categories[$cid];
1390                            }
1391                        }
1392                    }
1393                }
1394                if ((!$cat['category_parent']) && (isset($args['top_level_categories']))) {
1395                    $top_cats[] = $categories[$cid];
1396                }
1397            }
1398            $this->cache_category_links($id_list);
1399            if (isset($args['top_level_categories'])) {
1400                return $top_cats;
1401            }
1402        }
1403        return $categories;
1404    }
1405
1406    function &fetch_entry($entry_id) {
1407        if (isset($this->_entry_id_cache['entry_id'])) {
1408            return $this->_entry_id_cache[$entry_id];
1409        }
1410        list($entry) = $this->fetch_entries(array('entry_id' => $entry_id));
1411        $this->_entry_id_cache[$entry_id] = $entry;
1412        return $entry;
1413    }
1414
1415    function &fetch_page($entry_id) {
1416        if (isset($this->_entry_id_cache['entry_id'])) {
1417            return $this->_entry_id_cache[$entry_id];
1418        }
1419        list($entry) = $this->fetch_pages(array('entry_id' => $entry_id));
1420        $this->_entry_id_cache[$entry_id] = $entry;
1421        return $entry;
1422    }
1423
1424    function &fetch_author($author_id) {
1425        if (isset($this->_author_id_cache[$author_id])) {
1426            return $this->_author_id_cache[$author_id];
1427        }
1428        $args['author_id'] = $author_id;
1429        $args['any_type'] = 1;
1430        $result = $this->fetch_authors($args);
1431        $author = null;
1432        if (is_array($result)) {
1433            $author = $result[0];
1434            $this->_author_id_cache[$author_id] = $author;
1435        }
1436        return $author;
1437    }
1438
1439    function &fetch_author_by_name($author_name) {
1440        global $mt;
1441        $args['blog_id'] = $mt->blog_id;
1442        $args['author_name'] = $this->escape($author_name);
1443        $result = $this->fetch_authors($args);
1444        $author = null;
1445        if (is_array($result)) {
1446            $author = $result[0];
1447            $this->_author_id_cache[$author['author_id']] = $author;
1448        }
1449        return $author;
1450    }
1451
1452    function &fetch_authors($args) {
1453        # Adds blog join
1454        $extend_column = '';
1455        if ($sql = $this->include_exclude_blogs($args)) {
1456            $blog_join = 'join mt_permission on permission_author_id = author_id and permission_blog_id ' . $sql;
1457            $unique_filter = 'distinct';
1458        } elseif (isset($args['blog_id'])) {
1459            $blog_id = intval($args['blog_id']);
1460            $blog_join = "join mt_permission on permission_author_id = author_id and permission_blog_id = $blog_id";
1461        }
1462
1463        # Adds author filter
1464        if (isset($args['author_id'])) {
1465            $author_id = intval($args['author_id']);
1466            $author_filter = " and author_id = $author_id";
1467        }
1468        if (isset($args['author_nickname'])) {
1469            $author_filter .= " and author_nickname = '".$args['author_nickname']."'";
1470        }
1471        if (isset($args['author_name'])) {
1472            $author_filter .= " and author_name = '".$args['author_name']."'";
1473        }
1474
1475        # Adds entry join and filter
1476        if ($args['need_entry']) {
1477            $entry_join = 'join mt_entry on author_id = entry_author_id';
1478            $unique_filter = 'distinct';
1479            $entry_filter = " and entry_status = 2";
1480            if ($blog_join) {
1481                $entry_filter .= " and entry_blog_id = permission_blog_id";
1482            } else {
1483                $entry_filter .= " and entry_blog_id = ".$args['blog_id'];
1484            }
1485        } else {
1486            if ( ! $args['any_type'] )
1487                $author_filter .= " and author_type = 1";
1488        }
1489
1490        # a context hash for filter routines
1491        $ctx = array();
1492        $filters = array();
1493
1494        if (isset($args['status'])) {
1495            $status_arg = $args['status'];
1496            require_once("MTUtil.php");
1497            $status = array(
1498                array('name' => 'enabled', 'id' => 1),
1499                array('name' => 'disabled', 'id' => 2));
1500
1501            $cexpr = create_status_expr_function($status_arg, $status);
1502            if ($cexpr) {
1503                $filters[] = $cexpr;
1504            }
1505        }
1506
1507        if (isset($args['roles']) or isset($args['role'])) {
1508            $role_arg = isset($args['role']) ? $args['role'] : $args['roles'];
1509            require_once("MTUtil.php");
1510            $roles =& $this->fetch_all_roles();
1511            if (!is_array($roles)) $roles = array();
1512
1513            $cexpr = create_role_expr_function($role_arg, $roles);
1514            if ($cexpr) {
1515                $rmap = array();
1516                $role_list = array();
1517                foreach ($roles as $role) {
1518                    $role_list[] = $role['role_id'];
1519                }
1520                $as =& $this->fetch_associations(array('blog_id' => $blog_id, 'role_id' => $role_list));
1521                if ($as) {
1522                    foreach ($as as $a) {
1523                        $rmap[$a['association_author_id']][$a['association_role_id']]++;
1524                    }
1525                }
1526                $ctx['r'] =& $rmap;
1527                $filters[] = $cexpr;
1528            }
1529        }
1530
1531        # Adds a score or rate filter to the filters list.
1532        $re_sort = false;
1533        if (isset($args['namespace'])) {
1534            require_once("MTUtil.php");
1535            $arg_names = array('min_score', 'max_score', 'min_rate', 'max_rate', 'min_count', 'max_count' );
1536            foreach ($arg_names as $n) {
1537                if (isset($args[$n])) {
1538                    $rating_args = $args[$n];
1539                    $cexpr = create_rating_expr_function($rating_args, $n, $args['namespace'], 'author');
1540                    if ($cexpr) {
1541                        $filters[] = $cexpr;
1542                        $re_sort = true;
1543                    } else {
1544                        return null;
1545                    }
1546                }
1547            }
1548        }
1549
1550        # sort
1551        $join_score = "";
1552        if (isset($args['sort_by'])) {
1553            if (($args['sort_by'] == 'score') || ($args['sort_by'] == 'rate')) {
1554                $join_score = "join mt_objectscore on objectscore_object_id = author_id and objectscore_namespace='".$args['namespace']."' and objectscore_object_ds='author'";
1555                $unique_filter = 'distinct';
1556                $order_sql = "order by author_created_on desc";
1557                $re_sort = true;
1558            } else {
1559                $sort_col = $args['sort_by'];
1560                $order = '';
1561                if (isset($args['sort_order'])) {
1562                    if ($args['sort_order'] == 'ascend')
1563                        $order = 'asc';
1564                    else
1565                        $order = 'desc';
1566                }
1567                $order_sql = "order by $sort_col $order";
1568   
1569                if (isset($args['start_string'])) {
1570                    $val = $args['start_string'];
1571                    if ($order == 'asc')
1572                        $val_order = '>';
1573                    else
1574                        $val_order = '<';
1575                    $sort_filter =  " and $sort_col $val_order '$val'";
1576                }
1577   
1578                if (isset($args['start_num'])) {
1579                    $val = $args['start_num'];
1580                    if ($order == 'asc')
1581                        $val_order = '>';
1582                    else
1583                        $val_order = '<';
1584                    $sort_filter .= " and $sort_col $val_order $val";
1585                }
1586            }
1587        }
1588
1589        $limit = 0;
1590        $offset = 0;
1591        if (isset($args['lastn']))
1592            $limit = $args['lastn'];
1593        if (isset($args['offset']))
1594            $limit = $args['offset'];
1595
1596        if ($re_sort) {
1597            $post_select_limit = $limit;
1598            $post_select_offset = $offset;
1599            $limit = 0; $offset = 0;
1600        }
1601       
1602        $sql = "
1603            select $unique_filter
1604                   mt_author.*
1605                   $extend_column
1606              from mt_author
1607                   $blog_join
1608                   $entry_join
1609                   $join_score
1610              where 1 = 1
1611                $author_filter
1612                $entry_filter
1613                $sort_filter
1614              $order_sql
1615                   <LIMIT>
1616        ";
1617        $sql = $this->apply_limit_sql($sql, $limit, $offset);
1618
1619        $result = $this->query_start($sql);
1620        if (!$result) return null;
1621
1622        $authors = array();
1623        if ($args['sort_by'] != 'score' && $args['sort_by'] != 'rate') {
1624            $offset = $post_select_offset ? $post_select_offset : 0;
1625            $limit = $post_select_limit ? $post_select_limit : 0;
1626        }
1627        $j = 0;
1628        while (true) {
1629            $e = $this->query_fetch(ARRAY_A);
1630            if ($offset && ($j++ < $offset)) continue;
1631            if (!isset($e)) break;
1632            if (count($filters)) {
1633                foreach ($filters as $f) {
1634                    if (!$f($e, $ctx)) continue 2;
1635                }
1636            }
1637            $authors[] = $e;
1638            if (($limit > 0) && (count($authors) >= $limit)) break;
1639        }
1640
1641        if (isset($args['sort_by']) && ('score' == $args['sort_by'])) {
1642            $authors_tmp = array();
1643            $order = 'asc';
1644            if (isset($args['sort_order']))
1645                $order = $args['sort_order'] == 'ascend' ? 'asc' : 'desc';
1646            foreach ($authors as $a) {
1647                $authors_tmp[$a['author_id']] = $a;
1648            }
1649            $scores = $this->fetch_sum_scores($args['namespace'], 'author', $order,
1650                $author_filter
1651            );
1652            $offset = $post_select_offset ? $post_select_offset : 0;
1653            $limit = $post_select_limit ? $post_select_limit : 0;
1654            $j = 0;
1655            $authors_sorted = array();
1656            foreach($scores as $score) {
1657                if (array_key_exists($score['objectscore_object_id'], $authors_tmp)) {
1658                    if ($offset && ($j++ < $offset)) continue;
1659                    array_push($authors_sorted, $authors_tmp[$score['objectscore_object_id']]);
1660                    unset($authors_tmp[$score['objectscore_object_id']]);
1661                    if (($limit > 0) && (count($authors_sorted) >= $limit)) break;
1662                }
1663            }
1664            $authors = $authors_sorted;
1665
1666        } elseif (isset($args['sort_by']) && ('rate' == $args['sort_by'])) {
1667            $authors_tmp = array();
1668            $order = 'asc';
1669            if (isset($args['sort_order']))
1670                $order = $args['sort_order'] == 'ascend' ? 'asc' : 'desc';
1671            foreach ($authors as $a) {
1672                $authors_tmp[$a['author_id']] = $a;
1673            }
1674            $scores = $this->fetch_avg_scores($args['namespace'], 'author', $order,
1675                $author_filter
1676            );
1677            $offset = $post_select_offset ? $post_select_offset : 0;
1678            $limit = $post_select_limit ? $post_select_limit : 0;
1679            $j = 0;
1680            $authors_sorted = array();
1681            foreach($scores as $score) {
1682                if (array_key_exists($score['objectscore_object_id'], $authors_tmp)) {
1683                    if ($offset && ($j++ < $offset)) continue;
1684                    array_push($authors_sorted, $authors_tmp[$score['objectscore_object_id']]);
1685                    unset($authors_tmp[$score['objectscore_object_id']]);
1686                    if (($limit > 0) && (count($authors_sorted) >= $limit)) break;
1687                }
1688            }
1689            $authors = $authors_sorted;
1690
1691        }
1692
1693        return $authors;
1694    }
1695
1696    function &fetch_permission($args) {
1697        if ($sql = $this->include_exclude_blogs($args)) {
1698            $blog_filter = 'permission_blog_id ' . $sql;
1699        } elseif (isset($args['blog_id'])) {
1700            $blog_id = intval($args['blog_id']);
1701            $blog_filter = "and permission_blog_id = $blog_id";
1702        }
1703        if (isset($args['id'])) {
1704          $id_filter = 'and permission_author_id in ('.$args['id'].')';
1705        }
1706
1707        $sql = "select
1708                    *
1709                from
1710                    mt_permission
1711                where
1712                    1 = 1
1713                    $blog_filter
1714                    $id_filter";
1715
1716        $result = $this->get_results($sql, ARRAY_A);
1717        return $result;
1718    }
1719
1720    function &fetch_all_roles() {
1721        $sql = "select *
1722                  from mt_role
1723              order by role_name";
1724        $result = $this->get_results($sql, ARRAY_A);
1725        return $result;
1726    }
1727
1728    function &fetch_associations($args) {
1729        $id_list = implode(",", $args['role_id']);
1730        if (empty($id_list))
1731            return;
1732        if ($sql = $this->include_exclude_blogs($args)) {
1733            $blog_filter = 'and association_blog_id  ' . $sql;
1734        } elseif (isset($args['blog_id'])) {
1735            $blog_filter = 'and association_blog_id = ' . intval($args['blog_id']);
1736        }
1737        $sql = "select *
1738                  from mt_association
1739                 where association_role_id in ($id_list)
1740                   $blog_filter";
1741        $result = $this->get_results($sql, ARRAY_A);
1742        return $result;
1743    }
1744
1745    function &fetch_tag($tag_id) {
1746        $tag_id = intval($tag_id);
1747        if (isset($this->_tag_id_cache[$tag_id])) {
1748            return $this->_tag_id_cache[$tag_id];
1749        }
1750        $tag = $this->get_row("
1751            select *
1752              from mt_tag
1753             where tag_id=$tag_id
1754        ", ARRAY_A);
1755        $this->_tag_id_cache[$tag_id] = $tag;
1756        return $tag;
1757    }
1758
1759    function &fetch_tag_by_name($tag_name) {
1760        $tag_name = $this->escape($tag_name);
1761        $tag = $this->get_row("
1762            select *
1763              from mt_tag
1764             where tag_name='$tag_name'
1765        ", ARRAY_A);
1766        $this->_tag_id_cache[$tag['tag_id']] = $tag;
1767        return $tag;
1768    }
1769
1770    function fetch_scores($namespace, $obj_id, $datasource) {
1771        $scores = $this->get_results("
1772            select * from mt_objectscore
1773            where objectscore_namespace='$namespace'
1774            and objectscore_object_id='$obj_id'
1775            and objectscore_object_ds='$datasource'
1776        ", ARRAY_A);
1777        return $scores;
1778    }
1779
1780    function fetch_score($namespace, $obj_id, $user_id, $datasource) {
1781        list($score) = $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            and objectscore_author_id='$user_id'
1787        ", ARRAY_A);
1788        return $score;
1789    }
1790
1791    function fetch_sum_scores($namespace, $datasource, $order, $filters) {
1792        $othertables = '';
1793        $otherwhere = '';
1794        if ($datasource == 'asset') {
1795            $othertables = ', mt_author';
1796            $otherwhere = 'AND (objectscore_author_id = author_id)';
1797        }
1798        $join_column = $datasource . '_id';
1799        $join_where = "AND ($join_column = objectscore_object_id)";
1800        $sql_scores = 
1801            "SELECT SUM(objectscore_score) AS sum_objectscore_score, objectscore_object_id
1802             FROM mt_objectscore, mt_$datasource $othertables
1803             WHERE (objectscore_namespace = '$namespace')
1804             AND (objectscore_object_ds = '$datasource')
1805             $join_where
1806             $otherwhere
1807             $filters
1808             GROUP BY objectscore_object_id
1809             ORDER BY sum_objectscore_score " . $order;
1810        $scores = $this->get_results($sql_scores, ARRAY_A);
1811        return $scores;
1812    }
1813
1814    function fetch_avg_scores($namespace, $datasource, $order, $filters) {
1815        $othertables = '';
1816        $otherwhere = '';
1817        if ($datasource == 'asset') {
1818            $othertables = ', mt_author';
1819            $otherwhere = 'AND (objectscore_author_id = author_id)';
1820        }
1821        $join_column = $datasource . '_id';
1822        $join_where = "AND ($join_column = objectscore_object_id)";
1823        $sql_scores = 
1824            "SELECT AVG(objectscore_score) AS sum_objectscore_score, objectscore_object_id
1825             FROM mt_objectscore, mt_$datasource $othertables
1826             WHERE (objectscore_namespace = '$namespace')
1827             AND (objectscore_object_ds = '$datasource')
1828             $join_where
1829             $otherwhere
1830             $filters
1831             GROUP BY objectscore_object_id
1832             ORDER BY sum_objectscore_score " . $order;
1833        $scores = $this->get_results($sql_scores, ARRAY_A);
1834        return $scores;
1835    }
1836
1837    function cache_permalinks(&$entry_list) {
1838        $id_list = '';
1839        foreach ($entry_list as $entry_id) {
1840            if (!isset($this->_entry_link_cache[$entry_id.';Individual'])) {
1841                $id_list .= ','.$entry_id;
1842                $this->_entry_link_cache[$entry_id.';Individual'] = ''; 
1843            }
1844        }
1845        if (empty($id_list))
1846            return;
1847        $id_list = substr($id_list, 1);
1848        $query = "
1849            select fileinfo_entry_id, fileinfo_url, blog_site_url, blog_file_extension, blog_archive_url
1850              from mt_fileinfo, mt_templatemap, mt_blog
1851             where fileinfo_entry_id in ($id_list)
1852               and fileinfo_archive_type = 'Individual'
1853               and blog_id = fileinfo_blog_id
1854               and templatemap_id = fileinfo_templatemap_id
1855               and templatemap_is_preferred = 1
1856        ";
1857        $results = $this->get_results($query, ARRAY_N);
1858        if ($results) {
1859
1860            foreach ($results as $row) {
1861                $blog_url = $row[4];
1862                $blog_url or $blog_url = $row[2];
1863                $blog_url = preg_replace('!(https?://(?:[^/]+))/.*!', '$1', $blog_url);
1864                $url = $blog_url . $row[1];
1865                $url = _strip_index($url, array('blog_file_extension' => $row[3]));
1866                $this->_entry_link_cache[$row[0].';Individual'] = $url;
1867            }
1868        }
1869    }
1870
1871    function cache_category_links(&$cat_list) {
1872        $id_list = '';
1873        foreach ($cat_list as $cat_id) {
1874            if (!isset($this->_cat_link_cache[$cat_id])) {
1875                $id_list .= ','.$cat_id;
1876                $this->_cat_link_cache[$cat_id] = '';
1877            }
1878        }
1879        if (empty($id_list))
1880            return;
1881        $id_list = substr($id_list, 1);
1882        $query = "
1883            select fileinfo_category_id, fileinfo_url, blog_site_url, blog_file_extension, blog_archive_url
1884              from mt_fileinfo, mt_templatemap, mt_blog
1885             where fileinfo_category_id in ($id_list)
1886               and fileinfo_archive_type = 'Category'
1887               and blog_id = fileinfo_blog_id
1888               and templatemap_id = fileinfo_templatemap_id
1889               and templatemap_is_preferred = 1
1890        ";
1891        $results = $this->get_results($query, ARRAY_N);
1892        if ($results) {
1893            foreach ($results as $row) {
1894                $blog_url = $row[4];
1895                $blog_url or $blog_url = $row[2];
1896                $blog_url = preg_replace('!(https?://(?:[^/]+))/.*!', '$1', $blog_url);
1897                $url = $blog_url . $row[1];
1898                $url = _strip_index($url, array('blog_file_extension' => $row[3]));
1899                $this->_cat_link_cache[$row[0]] = $url;
1900            }
1901        }
1902    }
1903
1904    function cache_comment_counts(&$entry_list) {
1905        $id_list = '';
1906        foreach ($entry_list as $entry_id) {
1907            if (!isset($this->_comment_count_cache[$entry_id])) {
1908                $id_list .= ','.$entry_id;
1909                $this->_comment_count_cache[$entry_id] = 0;
1910            }
1911        }
1912        if (empty($id_list))
1913            return;
1914        $id_list = substr($id_list, 1);
1915        $query = "
1916            select entry_id, entry_comment_count
1917              from mt_entry
1918             where entry_id in ($id_list)
1919        ";
1920        $results = $this->get_results($query, ARRAY_N);
1921        if ($results) {
1922            foreach ($results as $row) {
1923                $this->_comment_count_cache[$row[0]] = $row[1];
1924            }
1925        }
1926    }
1927
1928    function blog_entry_count($args) {
1929
1930        if ($sql = $this->include_exclude_blogs($args)) {
1931            $blog_filter = 'and entry_blog_id ' . $sql;
1932        } elseif (isset($args['blog_id'])) {
1933            $blog_id = intval($args['blog_id']);
1934            $blog_filter = 'and entry_blog_id = ' . $blog_id;
1935        }
1936        $class = 'entry';
1937        if (isset($args['class'])) {
1938            $class = $args['class'];
1939        }
1940        $count = $this->get_var("
1941          select count(*)
1942            from mt_entry
1943            where entry_status = 2
1944            and entry_class='$class'
1945            $blog_filter
1946            ");
1947        return $count;
1948    }
1949
1950    function blog_comment_count($args) {
1951
1952        if ($sql = $this->include_exclude_blogs($args)) {
1953            $blog_filter = 'and comment_blog_id ' . $sql;
1954        } elseif (isset($args['blog_id'])) {
1955            $blog_id = intval($args['blog_id']);
1956            $blog_filter = 'and comment_blog_id = ' . $blog_id;
1957        }
1958
1959        $count = $this->get_var("
1960            select count(*)
1961              from mt_entry, mt_comment
1962             where entry_status = 2
1963               and comment_visible = 1
1964               and comment_entry_id = entry_id
1965               $blog_filter
1966        ");
1967        return $count;
1968    }
1969
1970    function category_comment_count($args) {
1971        $cat_id = (int)$args['category_id'];
1972        $sql = "select count(*)
1973             from mt_placement, mt_comment, mt_entry
1974            where placement_category_id=$cat_id
1975              and entry_id=placement_entry_id
1976              and entry_status=2
1977              and comment_entry_id=entry_id
1978              and comment_visible=1";
1979        return $this->get_var($sql);
1980    }
1981
1982    function blog_ping_count($args) {
1983
1984        if ($sql = $this->include_exclude_blogs($args)) {
1985            $blog_filter = 'and tbping_blog_id ' . $sql;
1986        } elseif (isset($args['blog_id'])) {
1987            $blog_id = intval($args['blog_id']);
1988            $blog_filter = 'and tbping_blog_id = ' . $blog_id;
1989        }
1990
1991        $count = $this->get_var("
1992            select count(*)
1993              from mt_tbping, mt_trackback
1994             where tbping_visible = 1
1995               and tbping_tb_id = trackback_id
1996                   $blog_filter
1997        ");
1998        return $count;
1999    }
2000
2001    function blog_category_count($args) {
2002
2003        if ($sql = $this->include_exclude_blogs($args)) {
2004            $blog_filter = 'and category_blog_id ' . $sql;
2005        } elseif (isset($args['blog_id'])) {
2006            $blog_id = intval($args['blog_id']);
2007            $blog_filter = 'and category_blog_id = ' . $blog_id;
2008        }
2009        $count = $this->get_var("
2010            select count(*)
2011              from mt_category
2012             where 1 = 1
2013             $blog_filter
2014        ");
2015        return $count;
2016    }
2017
2018    function tags_entry_count($tag_id, $class = 'entry') {
2019        $count = $this->get_var("
2020          select count(*)
2021            from mt_objecttag, mt_entry
2022           where objecttag_tag_id = " . intval($tag_id) . "
2023             and entry_id = objecttag_object_id and objecttag_object_datasource='entry'
2024             and entry_status = 2
2025             and entry_class = '$class'
2026        ");
2027        return $count;
2028    }
2029
2030    function entry_comment_count($entry_id) {
2031        if (isset($this->_comment_count_cache[$entry_id])) {
2032            return $this->_comment_count_cache[$entry_id];
2033        }
2034        $entry = $this->fetch_entry($entry_id);
2035        $count = $entry['entry_comment_count'];
2036        $this->_comment_count_cache[$entry_id] = $count;
2037        return $count;
2038    }
2039
2040    function author_entry_count($args) {
2041        if ($sql = $this->include_exclude_blogs($args)) {
2042            $blog_filter = 'and entry_blog_id ' . $sql;
2043        } elseif (isset($args['blog_id'])) {
2044            $blog_id = intval($args['blog_id']);
2045            $blog_filter = 'and entry_blog_id = ' . $blog_id;
2046        }
2047        if (isset($args['author_id'])) {
2048            $author_id = intval($args['author_id']);
2049            $author_filter = " and entry_author_id = $author_id";
2050        }
2051        if (isset($args['class'])) {
2052            $class = $args['class'];
2053        }
2054        $count = $this->get_var("
2055          select count(*)
2056            from mt_entry
2057            where entry_status = 2
2058            and entry_class='$class'
2059            $blog_filter
2060            $author_filter
2061            ");
2062        return $count;
2063    }
2064
2065    function &fetch_placements($args) {
2066        $category_id_list = $args['category_id'];
2067        $id_list = '';
2068        foreach ($category_id_list as $cat_id) {
2069            $id_list .= ',' . $cat_id;
2070        }
2071        if (empty($id_list))
2072            return;
2073        $id_list = substr($id_list, 1);
2074        $sql = "
2075            select mt_placement.*
2076              from mt_placement, mt_entry
2077              where placement_category_id in ($id_list)
2078               and entry_id = placement_entry_id and entry_status = 2
2079        ";
2080        $results = $this->get_results($sql, ARRAY_A);
2081        return $results;
2082    }
2083
2084    function &fetch_objecttags($args) {
2085        $tag_id_list = $args['tag_id'];
2086        $id_list = '';
2087        foreach ($tag_id_list as $tag_id) {
2088            $id_list .= ',' . $tag_id;
2089        }
2090        if (empty($id_list))
2091            return;
2092        $id_list = substr($id_list, 1);
2093
2094        $blog_filter = $this->include_exclude_blogs($args);
2095        if ($blog_filter == '' and $args['blog_id'])
2096            $blog_filter = intval($args['blog_id']);
2097        if ($blog_filter != '') 
2098            $blog_filter = 'and objecttag_blog_id = ' . $blog_filter;
2099
2100        if (isset($args['datasource']) && strtolower($args['datasource']) == 'asset') {
2101            $datasource = $args['datasource'];
2102            $from_object = 'mt_asset';
2103            $object_filter = 'and asset_id = objecttag_object_id';
2104        } else {
2105            $datasource = 'entry';
2106            $from_object = 'mt_entry';
2107            $object_filter = 'and entry_id = objecttag_object_id and entry_status = 2';
2108        }
2109        $sql = "
2110            select mt_objecttag.*
2111              from mt_objecttag, $from_object
2112              where
2113                objecttag_object_datasource ='$datasource'
2114                and objecttag_tag_id in ($id_list)
2115                $blog_filter
2116                $object_filter
2117        ";
2118        $results = $this->get_results($sql, ARRAY_A);
2119        return $results;
2120    }
2121
2122    function &fetch_comments($args) {
2123        # load comments
2124        $entry_id = intval($args['entry_id']);
2125
2126        $sql = $this->include_exclude_blogs($args);
2127        if ($sql != '') {
2128            $blog_filter = 'and comment_blog_id ' . $sql;
2129            if (isset($args['blog_id']))
2130                $blog =& $this->fetch_blog($args['blog_id']);
2131        } elseif ($args['blog_id']) {
2132            $blog =& $this->fetch_blog($args['blog_id']);
2133            $blog_filter = ' and comment_blog_id = ' . $blog['blog_id'];
2134        }
2135
2136        # Adds a score or rate filter to the filters list.
2137        if (isset($args['namespace'])) {
2138            require_once("MTUtil.php");
2139            $arg_names = array('min_score', 'max_score', 'min_rate', 'max_rate', 'min_count', 'max_count' );
2140            foreach ($arg_names as $n) {
2141                if (isset($args[$n])) {
2142                    $comment_args = $args[$n];
2143                    $cexpr = create_rating_expr_function($comment_args, $n, $args['namespace'], 'comment');
2144                    if ($cexpr) {
2145                        $filters[] = $cexpr;
2146                    } else {
2147                        return null;
2148                    }
2149                }
2150            }
2151            if (isset($args['scored_by'])) {
2152                $voter = $this->fetch_author_by_name($args['scored_by']);
2153                if (!$voter) {
2154                    echo "Invalid scored by filter: ".$args['scored_by'];
2155                    return null;
2156                }
2157                $cexpr = create_rating_expr_function($voter['author_id'], 'scored_by', $args['namespace'], 'comment');
2158                if ($cexpr) {
2159                    $filters[] = $cexpr;
2160                } else {
2161                    return null;
2162                }
2163            }
2164        }
2165
2166        $order = $query_order = 'desc';
2167        if (isset($args['sort_order'])) {
2168            if ($args['sort_order'] == 'ascend') {
2169                $order = $query_order = 'asc';
2170            }
2171        } elseif (isset($blog) && isset($blog['blog_sort_order_comments'])) {
2172            if ($blog['blog_sort_order_comments'] == 'ascend') {
2173                $order = $query_order = 'asc';
2174            }
2175        }
2176        if ($order == 'asc' && (isset($args['lastn']) || isset($args['offset']))) {
2177            $reorder = 1;
2178            $query_order = 'desc';
2179        }
2180
2181        if ($entry_id) {
2182            $entry_filter = " and comment_entry_id = $entry_id";
2183            $entry_join = "join mt_entry on entry_id = comment_entry_id";
2184        } else {
2185            $entry_join = "join mt_entry on entry_id = comment_entry_id and entry_status = 2";
2186        }
2187
2188        $join_score = "";
2189        $distinct = "";
2190        if ( isset($args['sort_by'])
2191          && (($args['sort_by'] == 'score') || ($args['sort_by'] == 'rate')) ) {
2192            $join_score = "join mt_objectscore on objectscore_object_id = comment_id and objectscore_namespace='".$args['namespace']."' and objectscore_object_ds='comment'";
2193            $distinct = " distinct";
2194        }
2195
2196        $limit = 0;
2197        $offset = 0;
2198        if (isset($args['lastn']))
2199            $limit = $args['lastn'];
2200        if (isset($args['limit']))
2201            $limit = $args['limit'];
2202        if (isset($args['offset']))
2203            $offset = $args['offset'];
2204        if (count($filters)) {
2205            $post_select_limit = $limit;
2206            $post_select_offset = $offset;
2207            $limit = 0; $offset = 0;
2208        }
2209
2210        $sql = "
2211            select $distinct
2212                   mt_comment.*,
2213                   mt_entry.*
2214              from mt_comment
2215                   $entry_join
2216                   $join_score