Dotclear

source: inc/core/class.dc.blog.php @ 2309:850b5f27bcad

Revision 2309:850b5f27bcad, 63.1 KB checked in by Eve Le Cellier <linux@…>, 12 years ago (diff)

Add attachment filter for post list, see ticket #989 -- thanks Franck for the patch

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

Sites map