Dotclear

source: inc/core/class.dc.blog.php @ 1315:220e119ae6c8

Revision 1315:220e119ae6c8, 59.7 KB checked in by Dsls, 12 years ago (diff)

Merge with default

Line 
1<?php
2# -- BEGIN LICENSE BLOCK ---------------------------------------
3#
4# This file is part of Dotclear 2.
5#
6# Copyright (c) 2003-2011 Olivier Meunier & Association Dotclear
7# Licensed under the GPL version 2.0 license.
8# See LICENSE file or
9# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
10#
11# -- END LICENSE BLOCK -----------------------------------------
12if (!defined('DC_RC_PATH')) { return; }
13
14/**
15@ingroup DC_CORE
16@nosubgrouping
17@brief Dotclear blog class.
18
19Dotclear blog class instance is provided by dcCore $blog property.
20*/
21class dcBlog
22{
23     /** @var dcCore dcCore instance */
24     protected $core;
25     /** @var connection Database connection object */
26     public $con;
27     /** @var string Database table prefix */
28     public $prefix;
29     
30     /** @var string Blog ID */
31     public $id;
32     /** @var string Blog unique ID */
33     public $uid;
34     /** @var string Blog name */
35     public $name;
36     /** @var string Blog description */
37     public $desc;
38     /** @var string Blog URL */
39     public $url;
40     /** @var string Blog host */
41     public $host;
42     /** @var string Blog creation date */
43     public $creadt;
44     /** @var string Blog last update date */
45     public $upddt;
46     /** @var string Blog status */
47     public $status;
48     
49     /** @var dcSettings dcSettings object */
50     public $settings;
51     /** @var string Blog theme path */
52     public $themes_path;
53     /** @var string Blog public path */
54     public $public_path;
55     
56     private $post_status = array();
57     private $comment_status = array();
58     
59     private $categories;
60     
61     /** @var boolean Disallow entries password protection */
62     public $without_password = true;
63     
64     /**
65     Inits dcBlog object
66     
67     @param    core      <b>dcCore</b>       Dotclear core reference
68     @param    id        <b>string</b>       Blog ID
69     */
70     public function __construct($core, $id)
71     {
72          $this->con =& $core->con;
73          $this->prefix = $core->prefix;
74          $this->core =& $core;
75         
76          if (($b = $this->core->getBlog($id)) !== false)
77          {
78               $this->id = $id;
79               $this->uid = $b->blog_uid;
80               $this->name = $b->blog_name;
81               $this->desc = $b->blog_desc;
82               $this->url = $b->blog_url;
83               $this->host = preg_replace('|^([a-z]{3,}://)(.*?)/.*$|','$1$2',$this->url);
84               $this->creadt = strtotime($b->blog_creadt);
85               $this->upddt = strtotime($b->blog_upddt);
86               $this->status = $b->blog_status;
87               
88               $this->settings = new dcSettings($this->core,$this->id);
89               
90               $this->themes_path = path::fullFromRoot($this->settings->system->themes_path,DC_ROOT);
91               $this->public_path = path::fullFromRoot($this->settings->system->public_path,DC_ROOT);
92               
93               $this->post_status['-2'] = __('pending');
94               $this->post_status['-1'] = __('scheduled');
95               $this->post_status['0'] = __('unpublished');
96               $this->post_status['1'] = __('published');
97               
98               $this->comment_status['-2'] = __('junk');
99               $this->comment_status['-1'] = __('pending');
100               $this->comment_status['0'] = __('unpublished');
101               $this->comment_status['1'] = __('published');
102               
103               # --BEHAVIOR-- coreBlogConstruct
104               $this->core->callBehavior('coreBlogConstruct',$this);
105          }
106     }
107     
108     /// @name Common public methods
109     //@{
110     /**
111     Returns blog URL ending with a question mark.
112     */
113     public function getQmarkURL()
114     {
115          if (substr($this->url,-1) != '?') {
116               return $this->url.'?';
117          }
118         
119          return $this->url;
120     }
121     
122     /**
123     Returns an entry status name given to a code. Status are translated, never
124     use it for tests. If status code does not exist, returns <i>unpublished</i>.
125     
126     @param    s    <b>integer</b> Status code
127     @return   <b>string</b> Blog status name
128     */
129     public function getPostStatus($s)
130     {
131          if (isset($this->post_status[$s])) {
132               return $this->post_status[$s];
133          }
134          return $this->post_status['0'];
135     }
136     
137     /**
138     Returns an array of available entry status codes and names.
139     
140     @return   <b>array</b> Simple array with codes in keys and names in value
141     */
142     public function getAllPostStatus()
143     {
144          return $this->post_status;
145     }
146     
147     /**
148     Returns an array of available comment status codes and names.
149     
150     @return   <b>array</b> Simple array with codes in keys and names in value
151     */
152     public function getAllCommentStatus()
153     {
154          return $this->comment_status;
155     }
156     
157     /**
158     Disallows entries password protection. You need to set it to
159     <var>false</var> while serving a public blog.
160     
161     @param    v         <b>boolean</b>
162     */
163     public function withoutPassword($v)
164     {
165          $this->without_password = (boolean) $v;
166     }
167     //@}
168     
169     /// @name Triggers methods
170     //@{
171     /**
172     Updates blog last update date. Should be called every time you change
173     an element related to the blog.
174     */
175     public function triggerBlog()
176     {
177          $cur = $this->con->openCursor($this->prefix.'blog');
178         
179          $cur->blog_upddt = date('Y-m-d H:i:s');
180         
181          $cur->update("WHERE blog_id = '".$this->con->escape($this->id)."' ");
182         
183          # --BEHAVIOR-- coreBlogAfterTriggerBlog
184          $this->core->callBehavior('coreBlogAfterTriggerBlog',$cur);
185     }
186     
187     /**
188     Updates comment and trackback counters in post table. Should be called
189     every time a comment or trackback is added, removed or changed its status.
190     
191     @param    id        <b>integer</b>      Comment ID
192     @param    del       <b>boolean</b>      If comment is delete, set this to true
193     */
194     public function triggerComment($id,$del=false)
195     {
196          $this->triggerComments($id,$del);
197     }
198     
199     /**
200     Updates comments and trackbacks counters in post table. Should be called
201     every time comments or trackbacks are added, removed or changed there status.
202     
203     @param    ids       <b>mixed</b>        Comment(s) ID(s)
204     @param    del       <b>boolean</b>      If comment is delete, set this to true
205     */
206     public function triggerComments($ids,$del=false)
207     {
208          $co_ids = dcUtils::cleanIds($ids);
209         
210          # a) Retrieve posts affected by comments edition
211          $strReq = 
212               'SELECT post_id, comment_trackback '.
213               'FROM '.$this->prefix.'comment '.
214               'WHERE comment_id'.$this->con->in($co_ids).
215               'GROUP BY post_id,comment_trackback';
216         
217          $rs = $this->con->select($strReq);
218         
219          $a_ids = $a_tbs = array();
220          while ($rs->fetch()) {
221               $a_ids[] = (integer) $rs->post_id;
222               $a_tbs[] = (integer) $rs->comment_trackback;
223          }
224         
225          # b) Count comments of each posts previously retrieved
226          # Note that this does not return posts without comment
227          $strReq = 
228               'SELECT post_id, COUNT(post_id) AS nb_comment,comment_trackback '.
229               'FROM '.$this->prefix.'comment '.
230               'WHERE comment_status = 1 '.
231               (count($a_ids) > 0 ? 'AND post_id'.$this->con->in($a_ids) : ' ');
232         
233          if ($del) {
234               $strReq .= 
235                    'AND comment_id NOT'.$this->con->in($co_ids);
236          }
237         
238          $strReq .= 
239               'GROUP BY post_id,comment_trackback';
240         
241          $rs = $this->con->select($strReq);
242         
243          $b_ids = $b_tbs = $b_nbs = array();
244          while ($rs->fetch()) {
245               $b_ids[] = (integer) $rs->post_id;
246               $b_tbs[] = (integer) $rs->comment_trackback;
247               $b_nbs[] = (integer) $rs->nb_comment;
248          }
249         
250          # c) Update comments numbers on posts
251          # This compare previous requests to update also posts without comment
252          $cur = $this->con->openCursor($this->prefix.'post');
253         
254          foreach($a_ids as $a_key => $a_id)
255          {
256               $nb_comment = $nb_trackback = 0;
257               foreach($b_ids as $b_key => $b_id)
258               {
259                    if ($a_id != $b_id || $a_tbs[$a_key] != $b_tbs[$b_key]) {
260                         continue;
261                    }
262                   
263                    if ($b_tbs[$b_key]) {
264                         $nb_trackback = $b_nbs[$b_key];
265                    } else {
266                         $nb_comment = $b_nbs[$b_key];
267                    }
268               }
269               
270               if ($a_tbs[$a_key]) {
271                    $cur->nb_trackback = $nb_trackback;
272               } else {
273                    $cur->nb_comment = $nb_comment;
274               }
275               $cur->update('WHERE post_id = '.$a_id);
276          }
277     }
278     //@}
279     
280     /// @name Categories management methods
281     //@{
282     public function categories()
283     {
284          if (!($this->categories instanceof dcCategories)) {
285               $this->categories = new dcCategories($this->core);
286          }
287         
288          return $this->categories;
289     }
290     
291     /**
292     Retrieves categories. <var>$params</var> is an associative array which can
293     take the following parameters:
294     
295     - post_type: Get only entries with given type (default "post")
296     - cat_url: filter on cat_url field
297     - cat_id: filter on cat_id field
298     - start: start with a given category
299     - level: categories level to retrieve
300     
301     @param    params    <b>array</b>        Parameters
302     @return   <b>record</b>
303     */
304     public function getCategories($params=array())
305     {
306          $c_params = array();
307          if (isset($params['post_type'])) {
308               $c_params['post_type'] = $params['post_type'];
309               unset($params['post_type']);
310          }
311          $counter = $this->getCategoriesCounter($c_params);
312         
313          $without_empty = $this->core->auth->userID() == false; # For public display
314         
315          $start = isset($params['start']) ? (integer) $params['start'] : 0;
316          $l = isset($params['level']) ? (integer) $params['level'] : 0;
317         
318          $rs = $this->categories()->getChildren($start,null,'desc');
319         
320          # Get each categories total posts count
321          $data = array();
322          $stack = array();
323          $level = 0;
324          $cols = $rs->columns();
325          while ($rs->fetch())
326          {
327               $nb_post = isset($counter[$rs->cat_id]) ? (integer) $counter[$rs->cat_id] : 0;
328               
329               if ($rs->level > $level) {
330                    $nb_total = $nb_post;
331                    $stack[$rs->level] = (integer) $nb_post;
332               } elseif ($rs->level == $level) {
333                    $nb_total = $nb_post;
334                    $stack[$rs->level] += $nb_post;
335               } else {
336                    $nb_total = $stack[$rs->level+1] + $nb_post;
337                    if (isset($stack[$rs->level])) {
338                         $stack[$rs->level] += $nb_total;
339                    } else {
340                         $stack[$rs->level] = $nb_total;
341                    }
342                    unset($stack[$rs->level+1]);
343               }
344               
345               if ($nb_total == 0 && $without_empty) {
346                    continue;
347               }
348               
349               $level = $rs->level;
350               
351               $t = array();
352               foreach ($cols as $c) {
353                    $t[$c] = $rs->f($c);
354               }
355               $t['nb_post'] = $nb_post;
356               $t['nb_total'] = $nb_total;
357               
358               if ($l == 0 || ($l > 0 && $l == $rs->level)) {
359                    array_unshift($data,$t);
360               }
361          }
362         
363          # We need to apply filter after counting
364          if (isset($params['cat_id']) && $params['cat_id'] !== '')
365          {
366               $found = false;
367               foreach ($data as $v) {
368                    if ($v['cat_id'] == $params['cat_id']) {
369                         $found = true;
370                         $data = array($v);
371                         break;
372                    }
373               }
374               if (!$found) {
375                    $data = array();
376               }
377          }
378         
379          if (isset($params['cat_url']) && ($params['cat_url'] !== '') 
380               && !isset($params['cat_id']))
381          {
382               $found = false;
383               foreach ($data as $v) {
384                    if ($v['cat_url'] == $params['cat_url']) {
385                         $found = true;
386                         $data = array($v);
387                         break;
388                    }
389               }
390               if (!$found) {
391                    $data = array();
392               }
393          }
394         
395          return staticRecord::newFromArray($data);
396     }
397     
398     /**
399     Retrieves a category by its ID.
400     
401     @param    id        <b>integer</b>      Category ID
402     @return   <b>record</b>
403     */
404     public function getCategory($id)
405     {
406          return $this->getCategories(array('cat_id' => $id));
407     }
408     
409     /**
410     Retrieves parents of a given category.
411     
412     @param    id        <b>integer</b>      Category ID
413     @return   <b>record</b>
414     */
415     public function getCategoryParents($id)
416     {
417          return $this->categories()->getParents($id);
418     }
419     
420     /**
421     Retrieves first parent of a given category.
422     
423     @param    id        <b>integer</b>      Category ID
424     @return   <b>record</b>
425     */
426     public function getCategoryParent($id)
427     {
428          return $this->categories()->getParent($id);
429     }
430     
431     /**
432     Retrieves all category's first children
433     
434     @param    id        <b>integer</b>      Category ID
435     @return   <b>record</b>
436     */
437     public function getCategoryFirstChildren($id)
438     {
439          return $this->getCategories(array('start' => $id,'level' => $id == 0 ? 1 : 2));
440     }
441     
442     private function getCategoriesCounter($params=array())
443     {
444          $strReq =
445          'SELECT  C.cat_id, COUNT(P.post_id) AS nb_post '.
446          'FROM '.$this->prefix.'category AS C '.
447          'JOIN '.$this->prefix."post P ON (C.cat_id = P.cat_id AND P.blog_id = '".$this->con->escape($this->id)."' ) ".
448          "WHERE C.blog_id = '".$this->con->escape($this->id)."' ";
449         
450          if (!$this->core->auth->userID()) {
451               $strReq .= 'AND P.post_status = 1 ';
452          }
453         
454          if (!empty($params['post_type'])) {
455               $strReq .= 'AND P.post_type '.$this->con->in($params['post_type']);
456          }
457         
458          $strReq .= 'GROUP BY C.cat_id ';
459         
460          $rs = $this->con->select($strReq);
461          $counters = array();
462          while ($rs->fetch()) {
463               $counters[$rs->cat_id] = $rs->nb_post;
464          }
465         
466          return $counters;
467     }
468     
469     /**
470     Creates a new category. Takes a cursor as input and returns the new category
471     ID.
472     
473     @param    cur       <b>cursor</b>       Category cursor
474     @return   <b>integer</b>      New category ID
475     */
476     public function addCategory($cur,$parent=0)
477     {
478          if (!$this->core->auth->check('categories',$this->id)) {
479               throw new Exception(__('You are not allowed to add categories'));
480          }
481         
482          $url = array();
483          if ($parent != 0)
484          {
485               $rs = $this->getCategory($parent);
486               if ($rs->isEmpty()) {
487                    $url = array();
488               } else {
489                    $url[] = $rs->cat_url;
490               }
491          }
492         
493          if ($cur->cat_url == '') {
494               $url[] = text::tidyURL($cur->cat_title,false);
495          } else {
496               $url[] = $cur->cat_url;
497          }
498         
499          $cur->cat_url = implode('/',$url);
500         
501          $this->getCategoryCursor($cur);
502          $cur->blog_id = (string) $this->id;
503         
504          # --BEHAVIOR-- coreBeforeCategoryCreate
505          $this->core->callBehavior('coreBeforeCategoryCreate',$this,$cur);
506         
507          $this->categories()->addNode($cur,$parent);
508         
509          # --BEHAVIOR-- coreAfterCategoryCreate
510          $this->core->callBehavior('coreAfterCategoryCreate',$this,$cur);
511          $this->triggerBlog();
512         
513          return $cur->cat_id;
514     }
515     
516     /**
517     Updates an existing category.
518     
519     @param    id        <b>integer</b>      Category ID
520     @param    cur       <b>cursor</b>       Category cursor
521     */
522     public function updCategory($id,$cur)
523     {
524          if (!$this->core->auth->check('categories',$this->id)) {
525               throw new Exception(__('You are not allowed to update categories'));
526          }
527         
528          if ($cur->cat_url == '')
529          {
530               $url = array();
531               $rs = $this->categories()->getParents($id);
532               while ($rs->fetch()) {
533                    if ($rs->index() == $rs->count()-1) {
534                         $url[] = $rs->cat_url;
535                    }
536               }
537               
538               
539               $url[] = text::tidyURL($cur->cat_title,false);
540               $cur->cat_url = implode('/',$url);
541          }
542         
543          $this->getCategoryCursor($cur,$id);
544         
545          # --BEHAVIOR-- coreBeforeCategoryUpdate
546          $this->core->callBehavior('coreBeforeCategoryUpdate',$this,$cur);
547         
548          $cur->update(
549          'WHERE cat_id = '.(integer) $id.' '.
550          "AND blog_id = '".$this->con->escape($this->id)."' ");
551         
552          # --BEHAVIOR-- coreAfterCategoryUpdate
553          $this->core->callBehavior('coreAfterCategoryUpdate',$this,$cur);
554         
555          $this->triggerBlog();
556     }
557     
558     /**
559     DEPRECATED METHOD. Use dcBlog::setCategoryParent and dcBlog::moveCategory
560     instead.
561     
562     @param    id        <b>integer</b>      Category ID
563     @param    order     <b>integer</b>      Category position
564     */
565     public function updCategoryOrder($id,$order)
566     {
567          return;
568     }
569     
570     /**
571     Set a category parent
572     
573     @param    id        <b>integer</b>      Category ID
574     @param    parent    <b>integer</b>      Parent Category ID
575     */
576     public function setCategoryParent($id,$parent)
577     {
578          $this->categories()->setNodeParent($id,$parent);
579          $this->triggerBlog();
580     }
581     
582     /**
583     Set category position
584     
585     @param    id        <b>integer</b>      Category ID
586     @param    sibling   <b>integer</b>      Sibling Category ID
587     @param    move      <b>integer</b>      Order (before|after)
588     */
589     public function setCategoryPosition($id,$sibling,$move)
590     {
591          $this->categories()->setNodePosition($id,$sibling,$move);
592          $this->triggerBlog();
593     }
594     
595     /**
596     Deletes a category.
597     
598     @param    id        <b>integer</b>      Category ID
599     */
600     public function delCategory($id)
601     {
602          if (!$this->core->auth->check('categories',$this->id)) {
603               throw new Exception(__('You are not allowed to delete categories'));
604          }
605         
606          $strReq = 'SELECT COUNT(post_id) AS nb_post '.
607                    'FROM '.$this->prefix.'post '.
608                    'WHERE cat_id = '.(integer) $id.' '.
609                    "AND blog_id = '".$this->con->escape($this->id)."' ";
610         
611          $rs = $this->con->select($strReq);
612         
613          if ($rs->nb_post > 0) {
614               throw new Exception(__('This category is not empty.'));
615          }
616         
617          $this->categories()->deleteNode($id,true);
618          $this->triggerBlog();
619     }
620     
621     /**
622     Reset categories order and relocate them to first level
623     */
624     public function resetCategoriesOrder()
625     {
626          if (!$this->core->auth->check('categories',$this->id)) {
627               throw new Exception(__('You are not allowed to reset categories order'));
628          }
629         
630          $this->categories()->resetOrder();
631          $this->triggerBlog();
632     }
633     
634     private function checkCategory($title,$url,$id=null)
635     {
636          $strReq = 'SELECT cat_id '.
637                    'FROM '.$this->prefix.'category '.
638                    "WHERE cat_url = '".$this->con->escape($url)."' ".
639                    "AND blog_id = '".$this->con->escape($this->id)."' ";
640         
641          if ($id !== null) {
642               $strReq .= 'AND cat_id <> '.(integer) $id.' ';
643          }
644         
645          $rs = $this->con->select($strReq);
646         
647          if (!$rs->isEmpty()) {
648               throw new Exception(__('Category URL must be unique.'));
649          }
650     }
651     
652     private function getCategoryCursor($cur,$id=null)
653     {
654          if ($cur->cat_title == '') {
655               throw new Exception(__('You must provide a category title'));
656          }
657         
658          # If we don't have any cat_url, let's do one
659          if ($cur->cat_url == '') {
660               $cur->cat_url = text::tidyURL($cur->cat_title,false);
661          }
662         
663          # Still empty ?
664          if ($cur->cat_url == '') {
665               throw new Exception(__('You must provide a category URL'));
666          } else {
667               $cur->cat_url = text::tidyURL($cur->cat_url,true);
668          }
669         
670          # Check if title or url are unique
671          $this->checkCategory($cur->cat_title,$cur->cat_url,$id);
672         
673          if ($cur->cat_desc !== null) {
674               $cur->cat_desc = $this->core->HTMLfilter($cur->cat_desc);
675          }
676     }
677     //@}
678     
679     /// @name Entries management methods
680     //@{
681     /**
682     Retrieves entries. <b>$params</b> is an array taking the following
683     optionnal parameters:
684     
685     - no_content: Don't retrieve entry content (excerpt and content)
686     - post_type: Get only entries with given type (default "post", array for many types and '' for no type)
687     - post_id: (integer) Get entry with given post_id
688     - post_url: Get entry with given post_url field
689     - user_id: (integer) Get entries belonging to given user ID
690     - cat_id: (string or array) Get entries belonging to given category ID
691     - cat_id_not: deprecated (use cat_id with "id ?not" instead)
692     - cat_url: (string or array) Get entries belonging to given category URL
693     - cat_url_not: deprecated (use cat_url with "url ?not" instead)
694     - post_status: (integer) Get entries with given post_status
695     - post_selected: (boolean) Get select flaged entries
696     - post_year: (integer) Get entries with given year
697     - post_month: (integer) Get entries with given month
698     - post_day: (integer) Get entries with given day
699     - post_lang: Get entries with given language code
700     - search: Get entries corresponding of the following search string
701     - columns: (array) More columns to retrieve
702     - sql: Append SQL string at the end of the query
703     - from: Append SQL string after "FROM" statement in query
704     - order: Order of results (default "ORDER BY post_dt DES")
705     - limit: Limit parameter
706     - sql_only : return the sql request instead of results. Only ids are selected
707     
708     Please note that on every cat_id or cat_url, you can add ?not to exclude
709     the category and ?sub to get subcategories.
710     
711     @param    params         <b>array</b>        Parameters
712     @param    count_only     <b>boolean</b>      Only counts results
713     @return   <b>record</b>  A record with some more capabilities or the SQL request
714     */
715     public function getPosts($params=array(),$count_only=false)
716     {
717          # --BEHAVIOR-- coreBlogBeforeGetPosts
718          $params = new ArrayObject($params);
719          $this->core->callBehavior('coreBlogBeforeGetPosts',$params);
720
721          if ($count_only)
722          {
723               $strReq = 'SELECT count(P.post_id) ';
724          }
725          elseif (!empty($params['sql_only'])) 
726          {
727               $strReq = 'SELECT P.post_id ';
728          }
729          else
730          {
731               if (!empty($params['no_content'])) {
732                    $content_req = '';
733               } else {
734                    $content_req =
735                    'post_excerpt, post_excerpt_xhtml, '.
736                    'post_content, post_content_xhtml, post_notes, ';
737               }
738               
739               if (!empty($params['columns']) && is_array($params['columns'])) {
740                    $content_req .= implode(', ',$params['columns']).', ';
741               }
742               
743               $strReq =
744               'SELECT P.post_id, P.blog_id, P.user_id, P.cat_id, post_dt, '.
745               'post_tz, post_creadt, post_upddt, post_format, post_password, '.
746               'post_url, post_lang, post_title, '.$content_req.
747               'post_type, post_meta, post_status, post_selected, post_position, '.
748               'post_open_comment, post_open_tb, nb_comment, nb_trackback, '.
749               'U.user_name, U.user_firstname, U.user_displayname, U.user_email, '.
750               'U.user_url, '.
751               'C.cat_title, C.cat_url, C.cat_desc ';
752          }
753         
754          $strReq .=
755          'FROM '.$this->prefix.'post P '.
756          'INNER JOIN '.$this->prefix.'user U ON U.user_id = P.user_id '.
757          'LEFT OUTER JOIN '.$this->prefix.'category C ON P.cat_id = C.cat_id ';
758         
759          if (!empty($params['from'])) {
760               $strReq .= $params['from'].' ';
761          }
762         
763          $strReq .=
764          "WHERE P.blog_id = '".$this->con->escape($this->id)."' ";
765         
766          if (!$this->core->auth->check('contentadmin',$this->id)) {
767               $strReq .= 'AND ((post_status = 1 ';
768               
769               if ($this->without_password) {
770                    $strReq .= 'AND post_password IS NULL ';
771               }
772               $strReq .= ') ';
773               
774               if ($this->core->auth->userID()) {
775                    $strReq .= "OR P.user_id = '".$this->con->escape($this->core->auth->userID())."')";
776               } else {
777                    $strReq .= ') ';
778               }
779          }
780         
781          #Adding parameters
782          if (isset($params['post_type']))
783          {
784               if (is_array($params['post_type']) || $params['post_type'] != '') {
785                    $strReq .= 'AND post_type '.$this->con->in($params['post_type']);
786               }
787          }
788          else
789          {
790               $strReq .= "AND post_type = 'post' ";
791          }
792         
793          if (isset($params['post_id']) && $params['post_id'] !== '') {
794               if (is_array($params['post_id'])) {
795                    array_walk($params['post_id'],create_function('&$v,$k','if($v!==null){$v=(integer)$v;}'));
796               } else {
797                    $params['post_id'] = array((integer) $params['post_id']);
798               }
799               $strReq .= 'AND P.post_id '.$this->con->in($params['post_id']);
800          }
801         
802          if (isset($params['post_url']) && $params['post_url'] !== '') {
803               $strReq .= "AND post_url = '".$this->con->escape($params['post_url'])."' ";
804          }
805         
806          if (!empty($params['user_id'])) {
807               $strReq .= "AND U.user_id ".$this->con->in($params['user_id'])." ";
808          }
809         
810          if (isset($params['cat_id']) && $params['cat_id'] !== '')
811          {
812               if (!is_array($params['cat_id'])) {
813                    $params['cat_id'] = array($params['cat_id']);
814               }
815               if (!empty($params['cat_id_not'])) {
816                    array_walk($params['cat_id'],create_function('&$v,$k','$v=$v." ?not";'));
817               }
818               $strReq .= 'AND '.$this->getPostsCategoryFilter($params['cat_id'],'cat_id').' ';
819          }
820          elseif (isset($params['cat_url']) && $params['cat_url'] !== '')
821          {
822               if (!is_array($params['cat_url'])) {
823                    $params['cat_url'] = array($params['cat_url']);
824               }
825               if (!empty($params['cat_url_not'])) {
826                    array_walk($params['cat_url'],create_function('&$v,$k','$v=$v." ?not";'));
827               }
828               $strReq .= 'AND '.$this->getPostsCategoryFilter($params['cat_url'],'cat_url').' ';
829          }
830         
831          /* Other filters */
832          if (isset($params['post_status'])) {
833               $strReq .= 'AND post_status = '.(integer) $params['post_status'].' ';
834          }
835         
836          if (isset($params['post_selected'])) {
837               $strReq .= 'AND post_selected = '.(integer) $params['post_selected'].' ';
838          }
839         
840          if (!empty($params['post_year'])) {
841               $strReq .= 'AND '.$this->con->dateFormat('post_dt','%Y').' = '.
842               "'".sprintf('%04d',$params['post_year'])."' ";
843          }
844         
845          if (!empty($params['post_month'])) {
846               $strReq .= 'AND '.$this->con->dateFormat('post_dt','%m').' = '.
847               "'".sprintf('%02d',$params['post_month'])."' ";
848          }
849         
850          if (!empty($params['post_day'])) {
851               $strReq .= 'AND '.$this->con->dateFormat('post_dt','%d').' = '.
852               "'".sprintf('%02d',$params['post_day'])."' ";
853          }
854         
855          if (!empty($params['post_lang'])) {
856               $strReq .= "AND P.post_lang = '".$this->con->escape($params['post_lang'])."' ";
857          }
858         
859          if (!empty($params['search']))
860          {
861               $words = text::splitWords($params['search']);
862               
863               if (!empty($words))
864               {
865                    # --BEHAVIOR-- corePostSearch
866                    if ($this->core->hasBehavior('corePostSearch')) {
867                         $this->core->callBehavior('corePostSearch',$this->core,array(&$words,&$strReq,&$params));
868                    }
869                   
870                    if ($words)
871                    {
872                         foreach ($words as $i => $w) {
873                              $words[$i] = "post_words LIKE '%".$this->con->escape($w)."%'";
874                         }
875                         $strReq .= 'AND '.implode(' AND ',$words).' ';
876                    }
877               }
878          }
879         
880          if (!empty($params['sql'])) {
881               $strReq .= $params['sql'].' ';
882          }
883         
884          if (!$count_only)
885          {
886               if (!empty($params['order'])) {
887                    $strReq .= 'ORDER BY '.$this->con->escape($params['order']).' ';
888               } else {
889                    $strReq .= 'ORDER BY post_dt DESC ';
890               }
891               if (!empty($params['limit'])) {
892                    $strReq .= $this->con->limit($params['limit']);
893               }
894          }
895         
896          if (!empty($params['sql_only'])) {
897               return $strReq;
898          }
899         
900          $rs = $this->con->select($strReq);
901          $rs->core = $this->core;
902          $rs->_nb_media = array();
903          $rs->extend('rsExtPost');
904         
905          # --BEHAVIOR-- coreBlogGetPosts
906          $this->core->callBehavior('coreBlogGetPosts',$rs);
907         
908          return $rs;
909     }
910     
911     /**
912     Returns a record with post id, title and date for next or previous post
913     according to the post ID.
914     $dir could be 1 (next post) or -1 (previous post).
915     
916     @param    post_id                  <b>integer</b>      Post ID
917     @param    dir                      <b>integer</b>      Search direction
918     @param    restrict_to_category     <b>boolean</b>      Restrict to post with same category
919     @param    restrict_to_lang         <b>boolean</b>      Restrict to post with same lang
920     @return   record
921     */
922     public function getNextPost($post,$dir,$restrict_to_category=false, $restrict_to_lang=false)
923     {
924          $dt = $post->post_dt;
925          $post_id = (integer) $post->post_id;
926         
927          if($dir > 0) {
928               $sign = '>';
929               $order = 'ASC';
930          }
931          else {
932               $sign = '<';
933               $order = 'DESC';
934          }
935         
936          $params['post_type'] = $post->post_type;
937          $params['limit'] = 1;
938          $params['order'] = 'post_dt '.$order.', P.post_id '.$order;
939          $params['sql'] =
940          'AND ( '.
941          "    (post_dt = '".$this->con->escape($dt)."' AND P.post_id ".$sign." ".$post_id.") ".
942          "    OR post_dt ".$sign." '".$this->con->escape($dt)."' ".
943          ') ';
944         
945          if ($restrict_to_category) {
946               $params['sql'] .= $post->cat_id ? 'AND P.cat_id = '.(integer) $post->cat_id.' ' : 'AND P.cat_id IS NULL ';
947          }
948         
949          if ($restrict_to_lang) {
950               $params['sql'] .= $post->post_lang ? 'AND P.post_lang = \''. $this->con->escape($post->post_lang) .'\' ': 'AND P.post_lang IS NULL ';
951          }
952         
953          $rs = $this->getPosts($params);
954         
955          if ($rs->isEmpty()) {
956               return null;
957          }
958         
959          return $rs;
960     }
961     
962     /**
963     Retrieves different languages and post count on blog, based on post_lang
964     field. <var>$params</var> is an array taking the following optionnal
965     parameters:
966     
967     - post_type: Get only entries with given type (default "post", '' for no type)
968     - lang: retrieve post count for selected lang
969     - order: order statement (default post_lang DESC)
970     
971     @param    params    <b>array</b>        Parameters
972     @return   record
973     */
974     public function getLangs($params=array())
975     {
976          $strReq = 'SELECT COUNT(post_id) as nb_post, post_lang '.
977                    'FROM '.$this->prefix.'post '.
978                    "WHERE blog_id = '".$this->con->escape($this->id)."' ".
979                    "AND post_lang <> '' ".
980                    "AND post_lang IS NOT NULL ";
981         
982          if (!$this->core->auth->check('contentadmin',$this->id)) {
983               $strReq .= 'AND ((post_status = 1 ';
984               
985               if ($this->without_password) {
986                    $strReq .= 'AND post_password IS NULL ';
987               }
988               $strReq .= ') ';
989               
990               if ($this->core->auth->userID()) {
991                    $strReq .= "OR user_id = '".$this->con->escape($this->core->auth->userID())."')";
992               } else {
993                    $strReq .= ') ';
994               }
995          }
996         
997          if (isset($params['post_type'])) {
998               if ($params['post_type'] != '') {
999                    $strReq .= "AND post_type = '".$this->con->escape($params['post_type'])."' ";
1000               }
1001          } else {
1002               $strReq .= "AND post_type = 'post' ";
1003          }
1004         
1005          if (isset($params['lang'])) {
1006               $strReq .= "AND post_lang = '".$this->con->escape($params['lang'])."' ";
1007          }
1008         
1009          $strReq .= 'GROUP BY post_lang ';
1010         
1011          $order = 'desc';
1012          if (!empty($params['order']) && preg_match('/^(desc|asc)$/i',$params['order'])) {
1013               $order = $params['order'];
1014          }
1015          $strReq .= 'ORDER BY post_lang '.$order.' ';
1016         
1017          return $this->con->select($strReq);
1018     }
1019     
1020     /**
1021     Returns a record with all distinct blog dates and post count.
1022     <var>$params</var> is an array taking the following optionnal parameters:
1023     
1024     - type: (day|month|year) Get days, months or years
1025     - year: (integer) Get dates for given year
1026     - month: (integer) Get dates for given month
1027     - day: (integer) Get dates for given day
1028     - cat_id: (integer) Category ID filter
1029     - cat_url: Category URL filter
1030     - post_lang: lang of the posts
1031     - next: Get date following match
1032     - previous: Get date before match
1033     - order: Sort by date "ASC" or "DESC"
1034     
1035     @param    params    <b>array</b>        Parameters array
1036     @return   record
1037     */
1038     public function getDates($params=array())
1039     {
1040          $dt_f = '%Y-%m-%d';
1041          $dt_fc = '%Y%m%d';
1042          if (isset($params['type'])) {
1043               if ($params['type'] == 'year') {
1044                    $dt_f = '%Y-01-01';
1045                    $dt_fc = '%Y0101';
1046               } elseif ($params['type'] == 'month') {
1047                    $dt_f = '%Y-%m-01';
1048                    $dt_fc = '%Y%m01';
1049               }
1050          }
1051          $dt_f .= ' 00:00:00';
1052          $dt_fc .= '000000';
1053         
1054          $cat_field = $catReq = $limit = '';
1055         
1056          if (isset($params['cat_id']) && $params['cat_id'] !== '') {
1057               $catReq = 'AND P.cat_id = '.(integer) $params['cat_id'].' ';
1058               $cat_field = ', C.cat_url ';
1059          } elseif (isset($params['cat_url']) && $params['cat_url'] !== '') {
1060               $catReq = "AND C.cat_url = '".$this->con->escape($params['cat_url'])."' ";
1061               $cat_field = ', C.cat_url ';
1062          }
1063          if (!empty($params['post_lang'])) {
1064               $catReq = 'AND P.post_lang = \''. $params['post_lang'].'\' ';
1065          }
1066         
1067          $strReq = 'SELECT DISTINCT('.$this->con->dateFormat('post_dt',$dt_f).') AS dt '.
1068                    $cat_field.
1069                    ',COUNT(P.post_id) AS nb_post '.
1070                    'FROM '.$this->prefix.'post P LEFT JOIN '.$this->prefix.'category C '.
1071                    'ON P.cat_id = C.cat_id '.
1072                    "WHERE P.blog_id = '".$this->con->escape($this->id)."' ".
1073                    $catReq;
1074         
1075          if (!$this->core->auth->check('contentadmin',$this->id)) {
1076               $strReq .= 'AND ((post_status = 1 ';
1077               
1078               if ($this->without_password) {
1079                    $strReq .= 'AND post_password IS NULL ';
1080               }
1081               $strReq .= ') ';
1082               
1083               if ($this->core->auth->userID()) {
1084                    $strReq .= "OR P.user_id = '".$this->con->escape($this->core->auth->userID())."')";
1085               } else {
1086                    $strReq .= ') ';
1087               }
1088          }
1089         
1090          if (!empty($params['post_type'])) {
1091               $strReq .= "AND post_type ".$this->con->in($params['post_type'])." ";
1092          } else {
1093               $strReq .= "AND post_type = 'post' ";
1094          }
1095         
1096          if (!empty($params['year'])) {
1097               $strReq .= 'AND '.$this->con->dateFormat('post_dt','%Y')." = '".sprintf('%04d',$params['year'])."' ";
1098          }
1099         
1100          if (!empty($params['month'])) {
1101               $strReq .= 'AND '.$this->con->dateFormat('post_dt','%m')." = '".sprintf('%02d',$params['month'])."' ";
1102          }
1103         
1104          if (!empty($params['day'])) {
1105               $strReq .= 'AND '.$this->con->dateFormat('post_dt','%d')." = '".sprintf('%02d',$params['day'])."' ";
1106          }
1107         
1108          # Get next or previous date
1109          if (!empty($params['next']) || !empty($params['previous']))
1110          {
1111               if (!empty($params['next'])) {
1112                    $pdir = ' > ';
1113                    $params['order'] = 'asc';
1114                    $dt = $params['next'];
1115               } else {
1116                    $pdir = ' < ';
1117                    $params['order'] = 'desc';
1118                    $dt = $params['previous'];
1119               }
1120               
1121               $dt = date('YmdHis',strtotime($dt));
1122               
1123               $strReq .= 'AND '.$this->con->dateFormat('post_dt',$dt_fc).$pdir."'".$dt."' ";
1124               $limit = $this->con->limit(1);
1125          }
1126         
1127          $strReq .= 'GROUP BY dt '.$cat_field;
1128         
1129          $order = 'desc';
1130          if (!empty($params['order']) && preg_match('/^(desc|asc)$/i',$params['order'])) {
1131               $order = $params['order'];
1132          }
1133         
1134          $strReq .=
1135          'ORDER BY dt '.$order.' '.
1136          $limit;
1137         
1138          $rs = $this->con->select($strReq);
1139          $rs->extend('rsExtDates');
1140          return $rs;
1141     }
1142     
1143     /**
1144     Creates a new entry. Takes a cursor as input and returns the new entry
1145     ID.
1146     
1147     @param    cur       <b>cursor</b>       Post cursor
1148     @return   <b>integer</b>      New post ID
1149     */
1150     public function addPost($cur)
1151     {
1152          if (!$this->core->auth->check('usage,contentadmin',$this->id)) {
1153               throw new Exception(__('You are not allowed to create an entry'));
1154          }
1155         
1156          $this->con->writeLock($this->prefix.'post');
1157          try
1158          {
1159               # Get ID
1160               $rs = $this->con->select(
1161                    'SELECT MAX(post_id) '.
1162                    'FROM '.$this->prefix.'post ' 
1163                    );
1164               
1165               $cur->post_id = (integer) $rs->f(0) + 1;
1166               $cur->blog_id = (string) $this->id;
1167               $cur->post_creadt = date('Y-m-d H:i:s');
1168               $cur->post_upddt = date('Y-m-d H:i:s');
1169               $cur->post_tz = $this->core->auth->getInfo('user_tz');
1170               
1171               # Post excerpt and content
1172               $this->getPostContent($cur,$cur->post_id);
1173               
1174               $this->getPostCursor($cur);
1175               
1176               $cur->post_url = $this->getPostURL($cur->post_url,$cur->post_dt,$cur->post_title,$cur->post_id);
1177               
1178               if (!$this->core->auth->check('publish,contentadmin',$this->id)) {
1179                    $cur->post_status = -2;
1180               }
1181               
1182               # --BEHAVIOR-- coreBeforePostCreate
1183               $this->core->callBehavior('coreBeforePostCreate',$this,$cur);
1184               
1185               $cur->insert();
1186               $this->con->unlock();
1187          }
1188          catch (Exception $e)
1189          {
1190               $this->con->unlock();
1191               throw $e;
1192          }
1193         
1194          # --BEHAVIOR-- coreAfterPostCreate
1195          $this->core->callBehavior('coreAfterPostCreate',$this,$cur);
1196         
1197          $this->triggerBlog();
1198         
1199          return $cur->post_id;
1200     }
1201     
1202     /**
1203     Updates an existing post.
1204     
1205     @param    id        <b>integer</b>      Post ID
1206     @param    cur       <b>cursor</b>       Post cursor
1207     */
1208     public function updPost($id,$cur)
1209     {
1210          if (!$this->core->auth->check('usage,contentadmin',$this->id)) {
1211               throw new Exception(__('You are not allowed to update entries'));
1212          }
1213         
1214          $id = (integer) $id;
1215         
1216          if (empty($id)) {
1217               throw new Exception(__('No such entry ID'));
1218          }
1219         
1220          # Post excerpt and content
1221          $this->getPostContent($cur,$id);
1222         
1223          $this->getPostCursor($cur);
1224         
1225          if ($cur->post_url !== null) {
1226               $cur->post_url = $this->getPostURL($cur->post_url,$cur->post_dt,$cur->post_title,$id);
1227          }
1228         
1229          if (!$this->core->auth->check('publish,contentadmin',$this->id)) {
1230               $cur->unsetField('post_status');
1231          }
1232         
1233          $cur->post_upddt = date('Y-m-d H:i:s');
1234         
1235          #If user is only "usage", we need to check the post's owner
1236          if (!$this->core->auth->check('contentadmin',$this->id))
1237          {
1238               $strReq = 'SELECT post_id '.
1239                         'FROM '.$this->prefix.'post '.
1240                         'WHERE post_id = '.$id.' '.
1241                         "AND user_id = '".$this->con->escape($this->core->auth->userID())."' ";
1242               
1243               $rs = $this->con->select($strReq);
1244               
1245               if ($rs->isEmpty()) {
1246                    throw new Exception(__('You are not allowed to edit this entry'));
1247               }
1248          }
1249         
1250          # --BEHAVIOR-- coreBeforePostUpdate
1251          $this->core->callBehavior('coreBeforePostUpdate',$this,$cur);
1252         
1253          $cur->update('WHERE post_id = '.$id.' ');
1254         
1255          # --BEHAVIOR-- coreAfterPostUpdate
1256          $this->core->callBehavior('coreAfterPostUpdate',$this,$cur);
1257         
1258          $this->triggerBlog();
1259     }
1260     
1261     /**
1262     Updates post status.
1263     
1264     @param    id        <b>integer</b>      Post ID
1265     @param    status    <b>integer</b>      Post status
1266     */
1267     public function updPostStatus($id,$status)
1268     {
1269          $this->updPostsStatus($id,$status);
1270     }
1271     
1272     /**
1273     Updates posts status.
1274     
1275     @param    ids       <b>mixed</b>        Post(s) ID(s)
1276     @param    status    <b>integer</b>      Post status
1277     */
1278     public function updPostsStatus($ids,$status)
1279     {
1280          if (!$this->core->auth->check('publish,contentadmin',$this->id)) {
1281               throw new Exception(__('You are not allowed to change this entry status'));
1282          }
1283         
1284          $posts_ids = dcUtils::cleanIds($ids);
1285          $status = (integer) $status;
1286         
1287          $strReq = "WHERE blog_id = '".$this->con->escape($this->id)."' ".
1288                    "AND post_id ".$this->con->in($posts_ids);
1289         
1290          #If user can only publish, we need to check the post's owner
1291          if (!$this->core->auth->check('contentadmin',$this->id))
1292          {
1293               $strReq .= "AND user_id = '".$this->con->escape($this->core->auth->userID())."' ";
1294          }
1295         
1296          $cur = $this->con->openCursor($this->prefix.'post');
1297         
1298          $cur->post_status = $status;
1299          $cur->post_upddt = date('Y-m-d H:i:s');
1300         
1301          $cur->update($strReq);
1302          $this->triggerBlog();
1303     }
1304     
1305     /**
1306     Updates post selection.
1307     
1308     @param    id        <b>integer</b>      Post ID
1309     @param    selected  <b>integer</b>      Is selected post
1310     */
1311     public function updPostSelected($id,$selected)
1312     {
1313          $this->updPostsSelected($id,$selected);
1314     }
1315     
1316     /**
1317     Updates posts selection.
1318     
1319     @param    ids       <b>mixed</b>        Post(s) ID(s)
1320     @param    selected  <b>integer</b>      Is selected post(s)
1321     */
1322     public function updPostsSelected($ids,$selected)
1323     {
1324          if (!$this->core->auth->check('usage,contentadmin',$this->id)) {
1325               throw new Exception(__('You are not allowed to change this entry category'));
1326          }
1327         
1328          $posts_ids = dcUtils::cleanIds($ids);
1329          $selected = (boolean) $selected;
1330         
1331          $strReq = "WHERE blog_id = '".$this->con->escape($this->id)."' ".
1332                    "AND post_id ".$this->con->in($posts_ids);
1333         
1334          # If user is only usage, we need to check the post's owner
1335          if (!$this->core->auth->check('contentadmin',$this->id))
1336          {
1337               $strReq .= "AND user_id = '".$this->con->escape($this->core->auth->userID())."' ";
1338          }
1339         
1340          $cur = $this->con->openCursor($this->prefix.'post');
1341         
1342          $cur->post_selected = (integer) $selected;
1343          $cur->post_upddt = date('Y-m-d H:i:s');
1344         
1345          $cur->update($strReq);
1346          $this->triggerBlog();
1347     }
1348     
1349     /**
1350     Updates post category. <var>$cat_id</var> can be null.
1351     
1352     @param    id        <b>integer</b>      Post ID
1353     @param    cat_id    <b>integer</b>      Category ID
1354     */
1355     public function updPostCategory($id,$cat_id)
1356     {
1357          $this->updPostsCategory($id,$cat_id);
1358     }
1359     
1360     /**
1361     Updates posts category. <var>$cat_id</var> can be null.
1362     
1363     @param    ids       <b>mixed</b>        Post(s) ID(s)
1364     @param    cat_id    <b>integer</b>      Category ID
1365     */
1366     public function updPostsCategory($ids,$cat_id)
1367     {
1368          if (!$this->core->auth->check('usage,contentadmin',$this->id)) {
1369               throw new Exception(__('You are not allowed to change this entry category'));
1370          }
1371         
1372          $posts_ids = dcUtils::cleanIds($ids);
1373          $cat_id = (integer) $cat_id;
1374         
1375          $strReq = "WHERE blog_id = '".$this->con->escape($this->id)."' ".
1376                    "AND post_id ".$this->con->in($posts_ids);
1377         
1378          # If user is only usage, we need to check the post's owner
1379          if (!$this->core->auth->check('contentadmin',$this->id))
1380          {
1381               $strReq .= "AND user_id = '".$this->con->escape($this->core->auth->userID())."' ";
1382          }
1383         
1384          $cur = $this->con->openCursor($this->prefix.'post');
1385         
1386          $cur->cat_id = ($cat_id ? $cat_id : null);
1387          $cur->post_upddt = date('Y-m-d H:i:s');
1388         
1389          $cur->update($strReq);
1390          $this->triggerBlog();
1391     }
1392     
1393     /**
1394     Updates posts category. <var>$new_cat_id</var> can be null.
1395     
1396     @param    old_cat_id     <b>integer</b>      Old category ID
1397     @param    new_cat_id     <b>integer</b>      New category ID
1398     */
1399     public function changePostsCategory($old_cat_id,$new_cat_id)
1400     {
1401          if (!$this->core->auth->check('contentadmin,categories',$this->id)) {
1402               throw new Exception(__('You are not allowed to change entries category'));
1403          }
1404         
1405          $old_cat_id = (integer) $old_cat_id;
1406          $new_cat_id = (integer) $new_cat_id;
1407         
1408          $cur = $this->con->openCursor($this->prefix.'post');
1409         
1410          $cur->cat_id = ($new_cat_id ? $new_cat_id : null);
1411          $cur->post_upddt = date('Y-m-d H:i:s');
1412         
1413          $cur->update(
1414               'WHERE cat_id = '.$old_cat_id.' '.
1415               "AND blog_id = '".$this->con->escape($this->id)."' "
1416          );
1417          $this->triggerBlog();
1418     }
1419     
1420     /**
1421     Deletes a post.
1422     
1423     @param    id        <b>integer</b>      Post ID
1424     */
1425     public function delPost($id)
1426     {
1427          $this->delPosts($id);
1428     }
1429     
1430     /**
1431     Deletes multiple posts.
1432     
1433     @param    ids       <b>mixed</b>        Post(s) ID(s)
1434     */
1435     public function delPosts($ids)
1436     {
1437          if (!$this->core->auth->check('delete,contentadmin',$this->id)) {
1438               throw new Exception(__('You are not allowed to delete entries'));
1439          }
1440         
1441          $posts_ids = dcUtils::cleanIds($ids);
1442         
1443          if (empty($posts_ids)) {
1444               throw new Exception(__('No such entry ID'));
1445          }
1446         
1447          $strReq = 'DELETE FROM '.$this->prefix.'post '.
1448                    "WHERE blog_id = '".$this->con->escape($this->id)."' ".
1449                    "AND post_id ".$this->con->in($posts_ids);
1450         
1451          #If user can only delete, we need to check the post's owner
1452          if (!$this->core->auth->check('contentadmin',$this->id))
1453          {
1454               $strReq .= "AND user_id = '".$this->con->escape($this->core->auth->userID())."' ";
1455          }
1456         
1457          $this->con->execute($strReq);
1458          $this->triggerBlog();
1459     }
1460     
1461     /**
1462     Publishes all entries flaged as "scheduled".
1463     */
1464     public function publishScheduledEntries()
1465     {
1466          $strReq = 'SELECT post_id, post_dt, post_tz '.
1467                    'FROM '.$this->prefix.'post '.
1468                    'WHERE post_status = -1 '.
1469                    "AND blog_id = '".$this->con->escape($this->id)."' ";
1470         
1471          $rs = $this->con->select($strReq);
1472         
1473          $now = dt::toUTC(time());
1474          $to_change = new ArrayObject();
1475
1476          if ($rs->isEmpty()) {
1477               return;
1478          }
1479         
1480          while ($rs->fetch())
1481          {
1482               # Now timestamp with post timezone
1483               $now_tz = $now + dt::getTimeOffset($rs->post_tz,$now);
1484               
1485               # Post timestamp
1486               $post_ts = strtotime($rs->post_dt);
1487               
1488               # If now_tz >= post_ts, we publish the entry
1489               if ($now_tz >= $post_ts) {
1490                    $to_change[] = (integer) $rs->post_id;
1491               }
1492          }
1493          if (count($to_change))
1494          {
1495               # --BEHAVIOR-- coreBeforeScheduledEntriesPublish
1496               $this->core->callBehavior('coreBeforeScheduledEntriesPublish',$this,$to_change);
1497
1498               $strReq =
1499               'UPDATE '.$this->prefix.'post SET '.
1500               'post_status = 1 '.
1501               "WHERE blog_id = '".$this->con->escape($this->id)."' ".
1502               'AND post_id '.$this->con->in((array)$to_change).' ';
1503               $this->con->execute($strReq);
1504               $this->triggerBlog();
1505
1506               # --BEHAVIOR-- coreAfterScheduledEntriesPublish
1507               $this->core->callBehavior('coreAfterScheduledEntriesPublish',$this,$to_change);
1508          }
1509         
1510     }
1511     
1512     /**
1513     Retrieves all users having posts on current blog.
1514     
1515     @param    post_type      <b>string</b>       post_type filter (post)
1516     @return   record
1517     */
1518     public function getPostsUsers($post_type='post')
1519     {
1520          $strReq = 'SELECT P.user_id, user_name, user_firstname, '.
1521                    'user_displayname, user_email '.
1522                    'FROM '.$this->prefix.'post P, '.$this->prefix.'user U '.
1523                    'WHERE P.user_id = U.user_id '.
1524                    "AND blog_id = '".$this->con->escape($this->id)."' ";
1525         
1526          if ($post_type) {
1527               $strReq .= "AND post_type = '".$this->con->escape($post_type)."' ";
1528          }
1529         
1530          $strReq .= 'GROUP BY P.user_id, user_name, user_firstname, user_displayname, user_email ';
1531         
1532          return $this->con->select($strReq);
1533     }
1534     
1535     private function getPostsCategoryFilter($arr,$field='cat_id')
1536     {
1537          $field = $field == 'cat_id' ? 'cat_id' : 'cat_url';
1538         
1539          $sub = array();
1540          $not = array();
1541          $queries = array();
1542         
1543          foreach ($arr as $v)
1544          {
1545               $v = trim($v);
1546               $args = preg_split('/\s*[?]\s*/',$v,-1,PREG_SPLIT_NO_EMPTY);
1547               $id = array_shift($args);
1548               $args = array_flip($args);
1549               
1550               if (isset($args['not'])) { $not[$id] = 1; }
1551               if (isset($args['sub'])) { $sub[$id] = 1; }
1552               if ($field == 'cat_id') {
1553                    if (preg_match('/^null$/i',$id)) {
1554                         $queries[$id] = 'P.cat_id IS NULL';
1555                    }
1556                    else {
1557                         $queries[$id] = 'P.cat_id = '.(integer) $id;
1558                    }
1559               } else {
1560                    $queries[$id] = "C.cat_url = '".$this->con->escape($id)."' ";
1561               }
1562          }
1563         
1564          if (!empty($sub)) {
1565               $rs = $this->con->select(
1566                    'SELECT cat_id, cat_url, cat_lft, cat_rgt FROM '.$this->prefix.'category '.
1567                    "WHERE blog_id = '".$this->con->escape($this->id)."' ".
1568                    'AND '.$field.' '.$this->con->in(array_keys($sub))
1569               );
1570               
1571               while ($rs->fetch()) {
1572                    $queries[$rs->f($field)] = '(C.cat_lft BETWEEN '.$rs->cat_lft.' AND '.$rs->cat_rgt.')';
1573               }
1574          }
1575         
1576          # Create queries
1577          $sql = array(
1578               0 => array(), # wanted categories
1579               1 => array()  # excluded categories
1580          );
1581         
1582          foreach ($queries as $id => $q) {
1583               $sql[(integer) isset($not[$id])][] = $q;
1584          }
1585         
1586          $sql[0] = implode(' OR ',$sql[0]);
1587          $sql[1] = implode(' OR ',$sql[1]);
1588         
1589          if ($sql[0]) {
1590               $sql[0] = '('.$sql[0].')';
1591          } else {
1592               unset($sql[0]);
1593          }
1594         
1595          if ($sql[1]) {
1596               $sql[1] = '(P.cat_id IS NULL OR NOT('.$sql[1].'))';
1597          } else {
1598               unset($sql[1]);
1599          }
1600         
1601          return implode(' AND ',$sql);
1602     }
1603     
1604     private function getPostCursor($cur,$post_id=null)
1605     {
1606          if ($cur->post_title == '') {
1607               throw new Exception(__('No entry title'));
1608          }
1609         
1610          if ($cur->post_content == '') {
1611               throw new Exception(__('No entry content'));
1612          }
1613         
1614          if ($cur->post_password === '') {
1615               $cur->post_password = null;
1616          }
1617         
1618          if ($cur->post_dt == '') {
1619               $offset = dt::getTimeOffset($this->core->auth->getInfo('user_tz'));
1620               $now = time() + $offset;
1621               $cur->post_dt = date('Y-m-d H:i:00',$now);
1622          }
1623         
1624          $post_id = is_int($post_id) ? $post_id : $cur->post_id;
1625         
1626          if ($cur->post_content_xhtml == '') {
1627               throw new Exception(__('No entry content'));
1628          }
1629         
1630          # Words list
1631          if ($cur->post_title !== null && $cur->post_excerpt_xhtml !== null
1632          && $cur->post_content_xhtml !== null)
1633          {
1634               $words =
1635               $cur->post_title.' '.
1636               $cur->post_excerpt_xhtml.' '.
1637               $cur->post_content_xhtml;
1638               
1639               $cur->post_words = implode(' ',text::splitWords($words));
1640          }
1641     }
1642     
1643     private function getPostContent($cur,$post_id)
1644     {
1645          $post_excerpt = $cur->post_excerpt;
1646          $post_excerpt_xhtml = $cur->post_excerpt_xhtml;
1647          $post_content = $cur->post_content;
1648          $post_content_xhtml = $cur->post_content_xhtml;
1649         
1650          $this->setPostContent(
1651               $post_id,$cur->post_format,$cur->post_lang,
1652               $post_excerpt,$post_excerpt_xhtml,
1653               $post_content,$post_content_xhtml
1654          );
1655         
1656          $cur->post_excerpt = $post_excerpt;
1657          $cur->post_excerpt_xhtml = $post_excerpt_xhtml;
1658          $cur->post_content = $post_content;
1659          $cur->post_content_xhtml = $post_content_xhtml;
1660     }
1661     
1662     /**
1663     Creates post HTML content, taking format and lang into account.
1664     
1665     @param         post_id        <b>integer</b>      Post ID
1666     @param         format         <b>string</b>       Post format
1667     @param         lang           <b>string</b>       Post lang
1668     @param         excerpt        <b>string</b>       Post excerpt
1669     @param[out]    excerpt_xhtml  <b>string</b>       Post excerpt HTML
1670     @param         content        <b>string</b>       Post content
1671     @param[out]    content_xhtml  <b>string</b>       Post content HTML
1672     */
1673     public function setPostContent($post_id,$format,$lang,&$excerpt,&$excerpt_xhtml,&$content,&$content_xhtml)
1674     {
1675          if ($format == 'wiki')
1676          {
1677               $this->core->initWikiPost();
1678               $this->core->wiki2xhtml->setOpt('note_prefix','pnote-'.$post_id);
1679               switch ($this->settings->system->note_title_tag) {
1680                    case 1:
1681                         $tag = 'h3';
1682                         break;
1683                    case 2:
1684                         $tag = 'p';
1685                         break;
1686                    default:
1687                         $tag = 'h4';
1688                         break;
1689               }
1690               $this->core->wiki2xhtml->setOpt('note_str','<div class="footnotes"><'.$tag.' class="footnotes-title">'.
1691                    __('Notes').'</'.$tag.'>%s</div>');
1692               $this->core->wiki2xhtml->setOpt('note_str_single','<div class="footnotes"><'.$tag.' class="footnotes-title">'.
1693                    __('Note').'</'.$tag.'>%s</div>');
1694               if (strpos($lang,'fr') === 0) {
1695                    $this->core->wiki2xhtml->setOpt('active_fr_syntax',1);
1696               }
1697          }
1698         
1699          if ($excerpt) {
1700               $excerpt_xhtml = $this->core->callFormater($format,$excerpt);
1701               $excerpt_xhtml = $this->core->HTMLfilter($excerpt_xhtml);
1702          } else {
1703               $excerpt_xhtml = '';
1704          }
1705         
1706          if ($content) {
1707               $content_xhtml = $this->core->callFormater($format,$content);
1708               $content_xhtml = $this->core->HTMLfilter($content_xhtml);
1709          } else {
1710               $content_xhtml = '';
1711          }
1712         
1713          # --BEHAVIOR-- coreAfterPostContentFormat
1714          $this->core->callBehavior('coreAfterPostContentFormat',array(
1715               'excerpt' => &$excerpt,
1716               'content' => &$content,
1717               'excerpt_xhtml' => &$excerpt_xhtml,
1718               'content_xhtml' => &$content_xhtml
1719          ));
1720     }
1721     
1722     /**
1723     Returns URL for a post according to blog setting <var>post_url_format</var>.
1724     It will try to guess URL and append some figures if needed.
1725     
1726     @param    url            <b>string</b>       Origin URL, could be empty
1727     @param    post_dt        <b>string</b>       Post date (in YYYY-MM-DD HH:mm:ss)
1728     @param    post_title     <b>string</b>       Post title
1729     @param    post_id        <b>integer</b>      Post ID
1730     @return   <b>string</b>  result URL
1731     */
1732     public function getPostURL($url,$post_dt,$post_title,$post_id)
1733     {
1734          $url = trim($url);
1735         
1736          $url_patterns = array(
1737          '{y}' => date('Y',strtotime($post_dt)),
1738          '{m}' => date('m',strtotime($post_dt)),
1739          '{d}' => date('d',strtotime($post_dt)),
1740          '{t}' => text::tidyURL($post_title),
1741          '{id}' => (integer) $post_id
1742          );
1743         
1744          # If URL is empty, we create a new one
1745          if ($url == '')
1746          {
1747               # Transform with format
1748               $url = str_replace(
1749                    array_keys($url_patterns),
1750                    array_values($url_patterns),
1751                    $this->settings->system->post_url_format
1752               );
1753          }
1754          else
1755          {
1756               $url = text::tidyURL($url);
1757          }
1758         
1759          # Let's check if URL is taken...
1760          $strReq = 'SELECT post_url FROM '.$this->prefix.'post '.
1761                    "WHERE post_url = '".$this->con->escape($url)."' ".
1762                    'AND post_id <> '.(integer) $post_id. ' '.
1763                    "AND blog_id = '".$this->con->escape($this->id)."' ".
1764                    'ORDER BY post_url DESC';
1765         
1766          $rs = $this->con->select($strReq);
1767         
1768          if (!$rs->isEmpty())
1769          {
1770               if ($this->con->driver() == 'mysql') {
1771                    $clause = "REGEXP '^".$this->con->escape($url)."[0-9]+$'";
1772               } elseif ($this->con->driver() == 'pgsql') {
1773                    $clause = "~ '^".$this->con->escape($url)."[0-9]+$'";
1774               } else {
1775                    $clause = "LIKE '".$this->con->escape($url)."%'";
1776               }
1777               $strReq = 'SELECT post_url FROM '.$this->prefix.'post '.
1778                         "WHERE post_url ".$clause.' '.
1779                         'AND post_id <> '.(integer) $post_id.' '.
1780                         "AND blog_id = '".$this->con->escape($this->id)."' ".
1781                         'ORDER BY post_url DESC ';
1782               
1783               $rs = $this->con->select($strReq);
1784               $a = array();
1785               while ($rs->fetch()) {
1786                    $a[] = $rs->post_url;
1787               }
1788               
1789               natsort($a);
1790               $t_url = end($a);
1791               
1792               if (preg_match('/(.*?)([0-9]+)$/',$t_url,$m)) {
1793                    $i = (integer) $m[2];
1794                    $url = $m[1];
1795               } else {
1796                    $i = 1;
1797               }
1798               
1799               return $url.($i+1);
1800          }
1801         
1802          # URL is empty?
1803          if ($url == '') {
1804               throw new Exception(__('Empty entry URL'));
1805          }
1806         
1807          return $url;
1808     }
1809     //@}
1810     
1811     /// @name Comments management methods
1812     //@{
1813     /**
1814     Retrieves comments. <b>$params</b> is an array taking the following
1815     optionnal parameters:
1816     
1817     - no_content: Don't retrieve comment content
1818     - post_type: Get only entries with given type (default no type, array for many types)
1819     - post_id: (integer) Get comments belonging to given post_id
1820     - cat_id: (integer or array) Get comments belonging to entries of given category ID
1821     - comment_id: (integer) Get comment with given ID
1822     - comment_status: (integer) Get comments with given comment_status
1823     - comment_trackback: (integer) Get only comments (0) or trackbacks (1)
1824     - comment_ip: (string) Get comments with given IP address
1825     - post_url: Get entry with given post_url field
1826     - user_id: (integer) Get entries belonging to given user ID
1827     - q_author: Search comments by author
1828     - sql: Append SQL string at the end of the query
1829     - from: Append SQL string after "FROM" statement in query
1830     - order: Order of results (default "ORDER BY comment_dt DES")
1831     - limit: Limit parameter
1832     - sql_only : return the sql request instead of results. Only ids are selected
1833     
1834     @param    params         <b>array</b>        Parameters
1835     @param    count_only     <b>boolean</b>      Only counts results
1836     @return   <b>record</b>  A record with some more capabilities
1837     */
1838     public function getComments($params=array(),$count_only=false)
1839     {
1840          if ($count_only)
1841          {
1842               $strReq = 'SELECT count(comment_id) ';
1843          }
1844          elseif (!empty($params['sql_only'])) 
1845          {
1846               $strReq = 'SELECT P.post_id ';
1847          }
1848          else
1849          {
1850               if (!empty($params['no_content'])) {
1851                    $content_req = '';
1852               } else {
1853                    $content_req = 'comment_content, ';
1854               }
1855               
1856               if (!empty($params['columns']) && is_array($params['columns'])) {
1857                    $content_req .= implode(', ',$params['columns']).', ';
1858               }
1859               
1860               $strReq =
1861               'SELECT C.comment_id, comment_dt, comment_tz, comment_upddt, '.
1862               'comment_author, comment_email, comment_site, '.
1863               $content_req.' comment_trackback, comment_status, '.
1864               'comment_spam_status, comment_spam_filter, comment_ip, '.
1865               'P.post_title, P.post_url, P.post_id, P.post_password, P.post_type, '.
1866               'P.post_dt, P.user_id, U.user_email, U.user_url ';
1867          }
1868         
1869          $strReq .=
1870          'FROM '.$this->prefix.'comment C '.
1871          'INNER JOIN '.$this->prefix.'post P ON C.post_id = P.post_id '.
1872          'INNER JOIN '.$this->prefix.'user U ON P.user_id = U.user_id ';
1873         
1874          if (!empty($params['from'])) {
1875               $strReq .= $params['from'].' ';
1876          }
1877         
1878          $strReq .=
1879          "WHERE P.blog_id = '".$this->con->escape($this->id)."' ";
1880         
1881          if (!$this->core->auth->check('contentadmin',$this->id)) {
1882               $strReq .= 'AND ((comment_status = 1 AND P.post_status = 1 ';
1883               
1884               if ($this->without_password) {
1885                    $strReq .= 'AND post_password IS NULL ';
1886               }
1887               $strReq .= ') ';
1888               
1889               if ($this->core->auth->userID()) {
1890                    $strReq .= "OR P.user_id = '".$this->con->escape($this->core->auth->userID())."')";
1891               } else {
1892                    $strReq .= ') ';
1893               }
1894          }
1895         
1896          if (!empty($params['post_type']))
1897          {
1898               $strReq .= 'AND post_type '.$this->con->in($params['post_type']);
1899          }
1900         
1901          if (isset($params['post_id']) && $params['post_id'] !== '') {
1902               $strReq .= 'AND P.post_id = '.(integer) $params['post_id'].' ';
1903          }
1904         
1905          if (isset($params['cat_id']) && $params['cat_id'] !== '') {
1906               $strReq .= 'AND P.cat_id = '.(integer) $params['cat_id'].' ';
1907          }
1908         
1909          if (isset($params['comment_id']) && $params['comment_id'] !== '') {
1910               $strReq .= 'AND comment_id = '.(integer) $params['comment_id'].' ';
1911          }
1912         
1913          if (isset($params['comment_status'])) {
1914               $strReq .= 'AND comment_status = '.(integer) $params['comment_status'].' ';
1915          }
1916         
1917          if (!empty($params['comment_status_not']))
1918          {
1919               $strReq .= 'AND comment_status <> '.(integer) $params['comment_status_not'].' ';
1920          }
1921         
1922          if (isset($params['comment_trackback'])) {
1923               $strReq .= 'AND comment_trackback = '.(integer) (boolean) $params['comment_trackback'].' ';
1924          }
1925         
1926          if (isset($params['comment_ip'])) {
1927               $comment_ip = $this->con->escape(str_replace('*','%',$params['comment_ip']));
1928               $strReq .= "AND comment_ip LIKE '".$comment_ip."' ";
1929          }
1930         
1931          if (isset($params['q_author'])) {
1932               $q_author = $this->con->escape(str_replace('*','%',strtolower($params['q_author'])));
1933               $strReq .= "AND LOWER(comment_author) LIKE '".$q_author."' ";
1934          }
1935         
1936          if (!empty($params['search']))
1937          {
1938               $words = text::splitWords($params['search']);
1939               
1940               if (!empty($words))
1941               {
1942                    # --BEHAVIOR coreCommentSearch
1943                    if ($this->core->hasBehavior('coreCommentSearch')) {
1944                         $this->core->callBehavior('coreCommentSearch',$this->core,array(&$words,&$strReq,&$params));
1945                    }
1946                   
1947                    if ($words)
1948                    {
1949                         foreach ($words as $i => $w) {
1950                              $words[$i] = "comment_words LIKE '%".$this->con->escape($w)."%'";
1951                         }
1952                         $strReq .= 'AND '.implode(' AND ',$words).' ';
1953                    }
1954               }
1955          }
1956         
1957          if (!empty($params['sql'])) {
1958               $strReq .= $params['sql'].' ';
1959          }
1960         
1961          if (!$count_only)
1962          {
1963               if (!empty($params['order'])) {
1964                    $strReq .= 'ORDER BY '.$this->con->escape($params['order']).' ';
1965               } else {
1966                    $strReq .= 'ORDER BY comment_dt DESC ';
1967               }
1968          }
1969         
1970          if (!$count_only && !empty($params['limit'])) {
1971               $strReq .= $this->con->limit($params['limit']);
1972          }
1973
1974          if (!empty($params['sql_only'])) {
1975               return $strReq;
1976          }
1977         
1978          $rs = $this->con->select($strReq);
1979          $rs->core = $this->core;
1980          $rs->extend('rsExtComment');
1981         
1982          # --BEHAVIOR-- coreBlogGetComments
1983          $this->core->callBehavior('coreBlogGetComments',$rs);
1984         
1985          return $rs;
1986     }
1987     
1988     /**
1989     Creates a new comment. Takes a cursor as input and returns the new comment
1990     ID.
1991     
1992     @param    cur       <b>cursor</b>       Comment cursor
1993     @return   <b>integer</b>      New comment ID
1994     */
1995     public function addComment($cur)
1996     {
1997          $this->con->writeLock($this->prefix.'comment');
1998          try
1999          {
2000               # Get ID
2001               $rs = $this->con->select(
2002                    'SELECT MAX(comment_id) '.
2003                    'FROM '.$this->prefix.'comment ' 
2004               );
2005               
2006               $cur->comment_id = (integer) $rs->f(0) + 1;
2007               $cur->comment_upddt = date('Y-m-d H:i:s');
2008               
2009               $offset = dt::getTimeOffset($this->settings->system->blog_timezone);
2010               $cur->comment_dt = date('Y-m-d H:i:s',time() + $offset);
2011               $cur->comment_tz = $this->settings->system->blog_timezone;
2012               
2013               $this->getCommentCursor($cur);
2014               
2015               if ($cur->comment_ip === null) {
2016                    $cur->comment_ip = http::realIP();
2017               }
2018               
2019               # --BEHAVIOR-- coreBeforeCommentCreate
2020               $this->core->callBehavior('coreBeforeCommentCreate',$this,$cur);
2021               
2022               $cur->insert();
2023               $this->con->unlock();
2024          }
2025          catch (Exception $e)
2026          {
2027               $this->con->unlock();
2028               throw $e;
2029          }
2030         
2031          # --BEHAVIOR-- coreAfterCommentCreate
2032          $this->core->callBehavior('coreAfterCommentCreate',$this,$cur);
2033         
2034          $this->triggerComment($cur->comment_id);
2035          if ($cur->comment_status != -2) {
2036               $this->triggerBlog();
2037          }   
2038          return $cur->comment_id;
2039     }
2040     
2041     /**
2042     Updates an existing comment.
2043     
2044     @param    id        <b>integer</b>      Comment ID
2045     @param    cur       <b>cursor</b>       Comment cursor
2046     */
2047     public function updComment($id,$cur)
2048     {
2049          if (!$this->core->auth->check('usage,contentadmin',$this->id)) {
2050               throw new Exception(__('You are not allowed to update comments'));
2051          }
2052         
2053          $id = (integer) $id;
2054         
2055          if (empty($id)) {
2056               throw new Exception(__('No such comment ID'));
2057          }
2058         
2059          $rs = $this->getComments(array('comment_id' => $id));
2060         
2061          if ($rs->isEmpty()) {
2062               throw new Exception(__('No such comment ID'));
2063          }
2064         
2065          #If user is only usage, we need to check the post's owner
2066          if (!$this->core->auth->check('contentadmin',$this->id))
2067          {
2068               if ($rs->user_id != $this->core->auth->userID()) {
2069                    throw new Exception(__('You are not allowed to update this comment'));
2070               }
2071          }
2072         
2073          $this->getCommentCursor($cur);
2074         
2075          $cur->comment_upddt = date('Y-m-d H:i:s');
2076         
2077          if (!$this->core->auth->check('publish,contentadmin',$this->id)) {
2078               $cur->unsetField('comment_status');
2079          }
2080         
2081          # --BEHAVIOR-- coreBeforeCommentUpdate
2082          $this->core->callBehavior('coreBeforeCommentUpdate',$this,$cur,$rs);
2083         
2084          $cur->update('WHERE comment_id = '.$id.' ');
2085         
2086          # --BEHAVIOR-- coreAfterCommentUpdate
2087          $this->core->callBehavior('coreAfterCommentUpdate',$this,$cur,$rs);
2088         
2089          $this->triggerComment($id);
2090          $this->triggerBlog();
2091     }
2092     
2093     /**
2094     Updates comment status.
2095     
2096     @param    id        <b>integer</b>      Comment ID
2097     @param    status    <b>integer</b>      Comment status
2098     */
2099     public function updCommentStatus($id,$status)
2100     {
2101          $this->updCommentsStatus($id,$status);
2102     }
2103     
2104     /**
2105     Updates comments status.
2106     
2107     @param    ids       <b>mixed</b>        Comment(s) ID(s)
2108     @param    status    <b>integer</b>      Comment status
2109     */
2110     public function updCommentsStatus($ids,$status)
2111     {
2112          if (!$this->core->auth->check('publish,contentadmin',$this->id)) {
2113               throw new Exception(__("You are not allowed to change this comment's status"));
2114          }
2115         
2116          $co_ids = dcUtils::cleanIds($ids);
2117          $status = (integer) $status;
2118         
2119          $strReq = 
2120               'UPDATE '.$this->prefix.'comment tc ';
2121         
2122          # mySQL uses "JOIN" synthax
2123          if ($this->con->driver() == 'mysql') {
2124               $strReq .= 
2125                    'JOIN '.$this->prefix.'post tp ON tc.post_id = tp.post_id ';
2126          }
2127         
2128          $strReq .= 
2129               'SET comment_status = '.$status.' ';
2130         
2131          # pgSQL uses "FROM" synthax
2132          if ($this->con->driver() != 'mysql') {
2133               $strReq .= 
2134                    'FROM '.$this->prefix.'post tp ';
2135          }
2136         
2137          $strReq .=
2138               "WHERE blog_id = '".$this->con->escape($this->id)."' ".
2139               'AND comment_id'.$this->con->in($co_ids);
2140         
2141          # add pgSQL "WHERE" clause
2142          if ($this->con->driver() != 'mysql') {
2143               $strReq .= 
2144                    'AND tc.post_id = tp.post_id ';
2145          }
2146         
2147          #If user is only usage, we need to check the post's owner
2148          if (!$this->core->auth->check('contentadmin',$this->id))
2149          {
2150               $strReq .= 
2151                    "AND user_id = '".$this->con->escape($this->core->auth->userID())."' ";
2152          }
2153         
2154          $this->con->execute($strReq);
2155          $this->triggerComments($co_ids);
2156          $this->triggerBlog();
2157     }
2158     
2159     /**
2160     Delete a comment
2161     
2162     @param    id        <b>integer</b>      Comment ID
2163     */
2164     public function delComment($id)
2165     {
2166          $this->delComments($id);
2167     }
2168     
2169     /**
2170     Delete comments
2171     
2172     @param    ids       <b>mixed</b>        Comment(s) ID(s)
2173     */
2174     public function delComments($ids)
2175     {
2176          if (!$this->core->auth->check('delete,contentadmin',$this->id)) {
2177               throw new Exception(__('You are not allowed to delete comments'));
2178          }
2179         
2180          $co_ids = dcUtils::cleanIds($ids);
2181         
2182          if (empty($ids)) {
2183               throw new Exception(__('No such comment ID'));
2184          }
2185         
2186          # mySQL uses "INNER JOIN" synthax
2187          if ($this->con->driver() == 'mysql') {
2188               $strReq = 
2189                    'DELETE FROM tc '.
2190                    'USING '.$this->prefix.'comment tc '.
2191                    'INNER JOIN '.$this->prefix.'post tp ';
2192          }
2193          # pgSQL uses nothing special
2194          else {
2195               $strReq = 
2196                    'DELETE FROM '.$this->prefix.'comment tc '.
2197                    'USING '.$this->prefix.'post tp ';
2198          }
2199         
2200          $strReq .= 
2201               'WHERE tc.post_id = tp.post_id '.
2202               "AND tp.blog_id = '".$this->con->escape($this->id)."' ".
2203               'AND comment_id'.$this->con->in($co_ids);
2204         
2205          #If user can only delete, we need to check the post's owner
2206          if (!$this->core->auth->check('contentadmin',$this->id))
2207          {
2208               $strReq .= 
2209                    "AND user_id = '".$this->con->escape($this->core->auth->userID())."' ";
2210          }
2211         
2212          $this->con->execute($strReq);
2213          $this->triggerComments($co_ids,true);
2214          $this->triggerBlog();
2215     }
2216
2217     public function delJunkComments()
2218     {
2219          if (!$this->core->auth->check('delete,contentadmin',$this->id)) {
2220               throw new Exception(__('You are not allowed to delete comments'));
2221          }
2222         
2223          # mySQL uses "INNER JOIN" synthax
2224          if ($this->con->driver() == 'mysql') {
2225               $strReq = 
2226                    'DELETE FROM tc '.
2227                    'USING '.$this->prefix.'comment tc '.
2228                    'INNER JOIN '.$this->prefix.'post tp ';
2229          }
2230          # pgSQL uses nothing special
2231          else {
2232               $strReq = 
2233                    'DELETE FROM '.$this->prefix.'comment tc '.
2234                    'USING '.$this->prefix.'post tp ';
2235          }
2236         
2237          $strReq .= 
2238               'WHERE tc.post_id = tp.post_id '.
2239               "AND tp.blog_id = '".$this->con->escape($this->id)."' ".
2240               'AND comment_status = -2';
2241         
2242          #If user can only delete, we need to check the post's owner
2243          if (!$this->core->auth->check('contentadmin',$this->id))
2244          {
2245               $strReq .= 
2246                    "AND user_id = '".$this->con->escape($this->core->auth->userID())."' ";
2247          }
2248         
2249          $this->con->execute($strReq);
2250          $this->triggerBlog();
2251     }
2252     
2253     private function getCommentCursor($cur)
2254     {
2255          if ($cur->comment_content !== null && $cur->comment_content == '') {
2256               throw new Exception(__('You must provide a comment'));
2257          }
2258         
2259          if ($cur->comment_author !== null && $cur->comment_author == '') {
2260               throw new Exception(__('You must provide an author name'));
2261          }
2262         
2263          if ($cur->comment_email != '' && !text::isEmail($cur->comment_email)) {
2264               throw new Exception(__('Email address is not valid.'));
2265          }
2266         
2267          if ($cur->comment_site !== null && $cur->comment_site != '') {
2268               if (!preg_match('|^http(s?)://|',$cur->comment_site)) {
2269                    $cur->comment_site = 'http://'.$cur->comment_site;
2270               }
2271          }
2272         
2273          if ($cur->comment_status === null) {
2274               $cur->comment_status = (integer) $this->settings->system->comments_pub;
2275          }
2276         
2277          # Words list
2278          if ($cur->comment_content !== null)
2279          {
2280               $cur->comment_words = implode(' ',text::splitWords($cur->comment_content));
2281          }
2282     }
2283     //@}
2284}
2285?>
Note: See TracBrowser for help on using the repository browser.

Sites map