Dotclear

source: inc/core/class.dc.blog.php @ 1262:ec1e7bef6c1f

Revision 1262:ec1e7bef6c1f, 60.5 KB checked in by Denis Jean-Christian <contact@…>, 12 years ago (diff)

Fix post comments number on comments deletion, fixes #1401, thanks sogos/sogox for patch and tests

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

Sites map