Dotclear

source: inc/core/class.dc.blog.php @ 2313:ef1db3d7c388

Revision 2313:ef1db3d7c388, 63.2 KB checked in by Dsls, 12 years ago (diff)

Twig merge - lots of things to adapt yet

Line 
1<?php
2# -- BEGIN LICENSE BLOCK ---------------------------------------
3#
4# This file is part of Dotclear 2.
5#
6# Copyright (c) 2003-2011 Olivier Meunier & Association Dotclear
7# Licensed under the GPL version 2.0 license.
8# See LICENSE file or
9# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
10#
11# -- END LICENSE BLOCK -----------------------------------------
12if (!defined('DC_RC_PATH')) { return; }
13
14/**
15@ingroup DC_CORE
16@nosubgrouping
17@brief Dotclear blog class.
18
19Dotclear blog class instance is provided by dcCore $blog property.
20*/
21class dcBlog
22{
23     /** @var dcCore dcCore instance */
24     protected $core;
25     /** @var connection Database connection object */
26     public $con;
27     /** @var string Database table prefix */
28     public $prefix;
29     
30     /** @var string Blog ID */
31     public $id;
32     /** @var string Blog unique ID */
33     public $uid;
34     /** @var string Blog name */
35     public $name;
36     /** @var string Blog description */
37     public $desc;
38     /** @var string Blog URL */
39     public $url;
40     /** @var string Blog host */
41     public $host;
42     /** @var string Blog creation date */
43     public $creadt;
44     /** @var string Blog last update date */
45     public $upddt;
46     /** @var string Blog status */
47     public $status;
48     
49     /** @var dcSettings dcSettings object */
50     public $settings;
51     /** @var string Blog theme path */
52     public $themes_path;
53     /** @var string Blog public path */
54     public $public_path;
55     
56     private $post_status = array();
57     private $comment_status = array();
58     
59     private $categories;
60     
61     /** @var boolean Disallow entries password protection */
62     public $without_password = true;
63     
64     /**
65     Inits dcBlog object
66     
67     @param    core      <b>dcCore</b>       Dotclear core reference
68     @param    id        <b>string</b>       Blog ID
69     */
70     public function __construct($core, $id)
71     {
72          $this->con =& $core->con;
73          $this->prefix = $core->prefix;
74          $this->core =& $core;
75         
76          if (($b = $this->core->getBlog($id)) !== false)
77          {
78               $this->id = $id;
79               $this->uid = $b->blog_uid;
80               $this->name = $b->blog_name;
81               $this->desc = $b->blog_desc;
82               $this->url = $b->blog_url;
83               $this->host = preg_replace('|^([a-z]{3,}://)(.*?)/.*$|','$1$2',$this->url);
84               $this->creadt = strtotime($b->blog_creadt);
85               $this->upddt = strtotime($b->blog_upddt);
86               $this->status = $b->blog_status;
87               
88               $this->settings = new dcSettings($this->core,$this->id);
89               
90               $this->themes_path = path::fullFromRoot($this->settings->system->themes_path,DC_ROOT);
91               $this->public_path = path::fullFromRoot($this->settings->system->public_path,DC_ROOT);
92               
93               $this->post_status['-2'] = __('Pending');
94               $this->post_status['-1'] = __('Scheduled');
95               $this->post_status['0'] = __('Unpublished');
96               $this->post_status['1'] = __('Published');
97               
98               $this->comment_status['-2'] = __('Junk');
99               $this->comment_status['-1'] = __('Pending');
100               $this->comment_status['0'] = __('Unpublished');
101               $this->comment_status['1'] = __('Published');
102               
103               # --BEHAVIOR-- coreBlogConstruct
104               $this->core->callBehavior('coreBlogConstruct',$this);
105          }
106     }
107     
108     /// @name Common public methods
109     //@{
110     /**
111     Returns blog URL ending with a question mark.
112     */
113     public function getQmarkURL()
114     {
115          if (substr($this->url,-1) != '?') {
116               return $this->url.'?';
117          }
118         
119          return $this->url;
120     }
121     
122     /**
123     Returns an entry status name given to a code. Status are translated, never
124     use it for tests. If status code does not exist, returns <i>unpublished</i>.
125     
126     @param    s    <b>integer</b> Status code
127     @return   <b>string</b> Blog status name
128     */
129     public function getPostStatus($s)
130     {
131          if (isset($this->post_status[$s])) {
132               return $this->post_status[$s];
133          }
134          return $this->post_status['0'];
135     }
136     
137     /**
138     Returns an array of available entry status codes and names.
139     
140     @return   <b>array</b> Simple array with codes in keys and names in value
141     */
142     public function getAllPostStatus()
143     {
144          return $this->post_status;
145     }
146     
147     /**
148     Returns an array of available comment status codes and names.
149     
150     @return   <b>array</b> Simple array with codes in keys and names in value
151     */
152     public function getAllCommentStatus()
153     {
154          return $this->comment_status;
155     }
156     
157     /**
158     Disallows entries password protection. You need to set it to
159     <var>false</var> while serving a public blog.
160     
161     @param    v         <b>boolean</b>
162     */
163     public function withoutPassword($v)
164     {
165          $this->without_password = (boolean) $v;
166     }
167     //@}
168     
169     /// @name Triggers methods
170     //@{
171     /**
172     Updates blog last update date. Should be called every time you change
173     an element related to the blog.
174     */
175     public function triggerBlog()
176     {
177          $cur = $this->con->openCursor($this->prefix.'blog');
178         
179          $cur->blog_upddt = date('Y-m-d H:i:s');
180         
181          $cur->update("WHERE blog_id = '".$this->con->escape($this->id)."' ");
182         
183          # --BEHAVIOR-- coreBlogAfterTriggerBlog
184          $this->core->callBehavior('coreBlogAfterTriggerBlog',$cur);
185     }
186     
187     /**
188     Updates comment and trackback counters in post table. Should be called
189     every time a comment or trackback is added, removed or changed its status.
190     
191     @param    id        <b>integer</b>      Comment ID
192     @param    del       <b>boolean</b>      If comment is delete, set this to true
193     */
194     public function triggerComment($id,$del=false)
195     {
196          $this->triggerComments($id,$del);
197     }
198     
199     /**
200     Updates comments and trackbacks counters in post table. Should be called
201     every time comments or trackbacks are added, removed or changed 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               if (isset($params['link_type'])) {
816                    $strReq .= " and M.link_type ".$this->con->in($params['link_type'])." ";
817               }
818          }
819         
820          if (!empty($params['from'])) {
821               $strReq .= $params['from'].' ';
822          }
823         
824          $strReq .=
825          "WHERE P.blog_id = '".$this->con->escape($this->id)."' ";
826         
827          if (!$this->core->auth->check('contentadmin',$this->id)) {
828               $strReq .= 'AND ((post_status = 1 ';
829               
830               if ($this->without_password) {
831                    $strReq .= 'AND post_password IS NULL ';
832               }
833               $strReq .= ') ';
834               
835               if ($this->core->auth->userID()) {
836                    $strReq .= "OR P.user_id = '".$this->con->escape($this->core->auth->userID())."')";
837               } else {
838                    $strReq .= ') ';
839               }
840          }
841         
842          #Adding parameters
843          if (isset($params['post_type']))
844          {
845               if (is_array($params['post_type']) || $params['post_type'] != '') {
846                    $strReq .= 'AND post_type '.$this->con->in($params['post_type']);
847               }
848          }
849          else
850          {
851               $strReq .= "AND post_type = 'post' ";
852          }
853         
854          if (isset($params['post_id']) && $params['post_id'] !== '') {
855               if (is_array($params['post_id'])) {
856                    array_walk($params['post_id'],create_function('&$v,$k','if($v!==null){$v=(integer)$v;}'));
857               } else {
858                    $params['post_id'] = array((integer) $params['post_id']);
859               }
860               $strReq .= 'AND P.post_id '.$this->con->in($params['post_id']);
861          }
862         
863          if (isset($params['exclude_post_id']) && $params['exclude_post_id'] !== '') {
864               if (is_array($params['exclude_post_id'])) {
865                    array_walk($params['exclude_post_id'],create_function('&$v,$k','if($v!==null){$v=(integer)$v;}'));
866               } else {
867                    $params['exclude_post_id'] = array((integer) $params['exclude_post_id']);
868               }
869               $strReq .= 'AND P.post_id NOT '.$this->con->in($params['exclude_post_id']);
870          }
871         
872          if (isset($params['post_url']) && $params['post_url'] !== '') {
873               $strReq .= "AND post_url = '".$this->con->escape($params['post_url'])."' ";
874          }
875         
876          if (!empty($params['user_id'])) {
877               $strReq .= "AND U.user_id ".$this->con->in($params['user_id'])." ";
878          }
879         
880          if (isset($params['cat_id']) && $params['cat_id'] !== '')
881          {
882               if (!is_array($params['cat_id'])) {
883                    $params['cat_id'] = array($params['cat_id']);
884               }
885               if (!empty($params['cat_id_not'])) {
886                    array_walk($params['cat_id'],create_function('&$v,$k','$v=$v." ?not";'));
887               }
888               $strReq .= 'AND '.$this->getPostsCategoryFilter($params['cat_id'],'cat_id').' ';
889          }
890          elseif (isset($params['cat_url']) && $params['cat_url'] !== '')
891          {
892               if (!is_array($params['cat_url'])) {
893                    $params['cat_url'] = array($params['cat_url']);
894               }
895               if (!empty($params['cat_url_not'])) {
896                    array_walk($params['cat_url'],create_function('&$v,$k','$v=$v." ?not";'));
897               }
898               $strReq .= 'AND '.$this->getPostsCategoryFilter($params['cat_url'],'cat_url').' ';
899          }
900         
901          /* Other filters */
902          if (isset($params['post_status'])) {
903               $strReq .= 'AND post_status = '.(integer) $params['post_status'].' ';
904          }
905         
906          if (isset($params['post_selected'])) {
907               $strReq .= 'AND post_selected = '.(integer) $params['post_selected'].' ';
908          }
909         
910          if (!empty($params['post_year'])) {
911               $strReq .= 'AND '.$this->con->dateFormat('post_dt','%Y').' = '.
912               "'".sprintf('%04d',$params['post_year'])."' ";
913          }
914         
915          if (!empty($params['post_month'])) {
916               $strReq .= 'AND '.$this->con->dateFormat('post_dt','%m').' = '.
917               "'".sprintf('%02d',$params['post_month'])."' ";
918          }
919         
920          if (!empty($params['post_day'])) {
921               $strReq .= 'AND '.$this->con->dateFormat('post_dt','%d').' = '.
922               "'".sprintf('%02d',$params['post_day'])."' ";
923          }
924         
925          if (!empty($params['post_lang'])) {
926               $strReq .= "AND P.post_lang = '".$this->con->escape($params['post_lang'])."' ";
927          }
928         
929          if (!empty($params['search']))
930          {
931               $words = text::splitWords($params['search']);
932               
933               if (!empty($words))
934               {
935                    # --BEHAVIOR-- corePostSearch
936                    if ($this->core->hasBehavior('corePostSearch')) {
937                         $this->core->callBehavior('corePostSearch',$this->core,array(&$words,&$strReq,&$params));
938                    }
939                   
940                    if ($words)
941                    {
942                         foreach ($words as $i => $w) {
943                              $words[$i] = "post_words LIKE '%".$this->con->escape($w)."%'";
944                         }
945                         $strReq .= 'AND '.implode(' AND ',$words).' ';
946                    }
947               }
948          }
949         
950          if (isset($params['media'])) {
951               if ($params['media'] == '0') {
952                    $strReq .= ' AND M.post_id IS NULL ';
953               }
954          }
955
956          if (!empty($params['sql'])) {
957               $strReq .= $params['sql'].' ';
958          }
959         
960          if (!$count_only && isset($params['media'])) {
961               $strReq .= ' GROUP BY P.post_id ';
962          }
963
964          if (!$count_only)
965          {
966               if (!empty($params['order'])) {
967                    $strReq .= 'ORDER BY '.$this->con->escape($params['order']).' ';
968               } else {
969                    $strReq .= 'ORDER BY post_dt DESC ';
970               }
971               if (!empty($params['limit'])) {
972                    $strReq .= $this->con->limit($params['limit']);
973               }
974          }
975         
976          if (!empty($params['sql_only'])) {
977               return $strReq;
978          }
979
980          $rs = $this->con->select($strReq);
981          $rs->core = $this->core;
982          $rs->_nb_media = array();
983          $rs->extend('rsExtPost');
984         
985          # --BEHAVIOR-- coreBlogGetPosts
986          $this->core->callBehavior('coreBlogGetPosts',$rs);
987         
988          return $rs;
989     }
990     
991     /**
992     Returns a record with post id, title and date for next or previous post
993     according to the post ID.
994     $dir could be 1 (next post) or -1 (previous post).
995     
996     @param    post_id                  <b>integer</b>      Post ID
997     @param    dir                      <b>integer</b>      Search direction
998     @param    restrict_to_category     <b>boolean</b>      Restrict to post with same category
999     @param    restrict_to_lang         <b>boolean</b>      Restrict to post with same lang
1000     @return   record
1001     */
1002     public function getNextPost($post,$dir,$restrict_to_category=false, $restrict_to_lang=false)
1003     {
1004          $dt = $post->post_dt;
1005          $post_id = (integer) $post->post_id;
1006         
1007          if($dir > 0) {
1008               $sign = '>';
1009               $order = 'ASC';
1010          }
1011          else {
1012               $sign = '<';
1013               $order = 'DESC';
1014          }
1015         
1016          $params['post_type'] = $post->post_type;
1017          $params['limit'] = 1;
1018          $params['order'] = 'post_dt '.$order.', P.post_id '.$order;
1019          $params['sql'] =
1020          'AND ( '.
1021          "    (post_dt = '".$this->con->escape($dt)."' AND P.post_id ".$sign." ".$post_id.") ".
1022          "    OR post_dt ".$sign." '".$this->con->escape($dt)."' ".
1023          ') ';
1024         
1025          if ($restrict_to_category) {
1026               $params['sql'] .= $post->cat_id ? 'AND P.cat_id = '.(integer) $post->cat_id.' ' : 'AND P.cat_id IS NULL ';
1027          }
1028         
1029          if ($restrict_to_lang) {
1030               $params['sql'] .= $post->post_lang ? 'AND P.post_lang = \''. $this->con->escape($post->post_lang) .'\' ': 'AND P.post_lang IS NULL ';
1031          }
1032         
1033          $rs = $this->getPosts($params);
1034         
1035          if ($rs->isEmpty()) {
1036               return null;
1037          }
1038         
1039          return $rs;
1040     }
1041     
1042     /**
1043     Retrieves different languages and post count on blog, based on post_lang
1044     field. <var>$params</var> is an array taking the following optionnal
1045     parameters:
1046     
1047     - post_type: Get only entries with given type (default "post", '' for no type)
1048     - lang: retrieve post count for selected lang
1049     - order: order statement (default post_lang DESC)
1050     
1051     @param    params    <b>array</b>        Parameters
1052     @return   record
1053     */
1054     public function getLangs($params=array())
1055     {
1056          $strReq = 'SELECT COUNT(post_id) as nb_post, post_lang '.
1057                    'FROM '.$this->prefix.'post '.
1058                    "WHERE blog_id = '".$this->con->escape($this->id)."' ".
1059                    "AND post_lang <> '' ".
1060                    "AND post_lang IS NOT NULL ";
1061         
1062          if (!$this->core->auth->check('contentadmin',$this->id)) {
1063               $strReq .= 'AND ((post_status = 1 ';
1064               
1065               if ($this->without_password) {
1066                    $strReq .= 'AND post_password IS NULL ';
1067               }
1068               $strReq .= ') ';
1069               
1070               if ($this->core->auth->userID()) {
1071                    $strReq .= "OR user_id = '".$this->con->escape($this->core->auth->userID())."')";
1072               } else {
1073                    $strReq .= ') ';
1074               }
1075          }
1076         
1077          if (isset($params['post_type'])) {
1078               if ($params['post_type'] != '') {
1079                    $strReq .= "AND post_type = '".$this->con->escape($params['post_type'])."' ";
1080               }
1081          } else {
1082               $strReq .= "AND post_type = 'post' ";
1083          }
1084         
1085          if (isset($params['lang'])) {
1086               $strReq .= "AND post_lang = '".$this->con->escape($params['lang'])."' ";
1087          }
1088         
1089          $strReq .= 'GROUP BY post_lang ';
1090         
1091          $order = 'desc';
1092          if (!empty($params['order']) && preg_match('/^(desc|asc)$/i',$params['order'])) {
1093               $order = $params['order'];
1094          }
1095          $strReq .= 'ORDER BY post_lang '.$order.' ';
1096         
1097          return $this->con->select($strReq);
1098     }
1099     
1100     /**
1101     Returns a record with all distinct blog dates and post count.
1102     <var>$params</var> is an array taking the following optionnal parameters:
1103     
1104     - type: (day|month|year) Get days, months or years
1105     - year: (integer) Get dates for given year
1106     - month: (integer) Get dates for given month
1107     - day: (integer) Get dates for given day
1108     - cat_id: (integer) Category ID filter
1109     - cat_url: Category URL filter
1110     - post_lang: lang of the posts
1111     - next: Get date following match
1112     - previous: Get date before match
1113     - order: Sort by date "ASC" or "DESC"
1114     
1115     @param    params    <b>array</b>        Parameters array
1116     @return   record
1117     */
1118     public function getDates($params=array())
1119     {
1120          $dt_f = '%Y-%m-%d';
1121          $dt_fc = '%Y%m%d';
1122          if (isset($params['type'])) {
1123               if ($params['type'] == 'year') {
1124                    $dt_f = '%Y-01-01';
1125                    $dt_fc = '%Y0101';
1126               } elseif ($params['type'] == 'month') {
1127                    $dt_f = '%Y-%m-01';
1128                    $dt_fc = '%Y%m01';
1129               }
1130          }
1131          $dt_f .= ' 00:00:00';
1132          $dt_fc .= '000000';
1133         
1134          $cat_field = $catReq = $limit = '';
1135         
1136          if (isset($params['cat_id']) && $params['cat_id'] !== '') {
1137               $catReq = 'AND P.cat_id = '.(integer) $params['cat_id'].' ';
1138               $cat_field = ', C.cat_url ';
1139          } elseif (isset($params['cat_url']) && $params['cat_url'] !== '') {
1140               $catReq = "AND C.cat_url = '".$this->con->escape($params['cat_url'])."' ";
1141               $cat_field = ', C.cat_url ';
1142          }
1143          if (!empty($params['post_lang'])) {
1144               $catReq = 'AND P.post_lang = \''. $params['post_lang'].'\' ';
1145          }
1146         
1147          $strReq = 'SELECT DISTINCT('.$this->con->dateFormat('post_dt',$dt_f).') AS dt '.
1148                    $cat_field.
1149                    ',COUNT(P.post_id) AS nb_post '.
1150                    'FROM '.$this->prefix.'post P LEFT JOIN '.$this->prefix.'category C '.
1151                    'ON P.cat_id = C.cat_id '.
1152                    "WHERE P.blog_id = '".$this->con->escape($this->id)."' ".
1153                    $catReq;
1154         
1155          if (!$this->core->auth->check('contentadmin',$this->id)) {
1156               $strReq .= 'AND ((post_status = 1 ';
1157               
1158               if ($this->without_password) {
1159                    $strReq .= 'AND post_password IS NULL ';
1160               }
1161               $strReq .= ') ';
1162               
1163               if ($this->core->auth->userID()) {
1164                    $strReq .= "OR P.user_id = '".$this->con->escape($this->core->auth->userID())."')";
1165               } else {
1166                    $strReq .= ') ';
1167               }
1168          }
1169         
1170          if (!empty($params['post_type'])) {
1171               $strReq .= "AND post_type ".$this->con->in($params['post_type'])." ";
1172          } else {
1173               $strReq .= "AND post_type = 'post' ";
1174          }
1175         
1176          if (!empty($params['year'])) {
1177               $strReq .= 'AND '.$this->con->dateFormat('post_dt','%Y')." = '".sprintf('%04d',$params['year'])."' ";
1178          }
1179         
1180          if (!empty($params['month'])) {
1181               $strReq .= 'AND '.$this->con->dateFormat('post_dt','%m')." = '".sprintf('%02d',$params['month'])."' ";
1182          }
1183         
1184          if (!empty($params['day'])) {
1185               $strReq .= 'AND '.$this->con->dateFormat('post_dt','%d')." = '".sprintf('%02d',$params['day'])."' ";
1186          }
1187         
1188          # Get next or previous date
1189          if (!empty($params['next']) || !empty($params['previous']))
1190          {
1191               if (!empty($params['next'])) {
1192                    $pdir = ' > ';
1193                    $params['order'] = 'asc';
1194                    $dt = $params['next'];
1195               } else {
1196                    $pdir = ' < ';
1197                    $params['order'] = 'desc';
1198                    $dt = $params['previous'];
1199               }
1200               
1201               $dt = date('YmdHis',strtotime($dt));
1202               
1203               $strReq .= 'AND '.$this->con->dateFormat('post_dt',$dt_fc).$pdir."'".$dt."' ";
1204               $limit = $this->con->limit(1);
1205          }
1206         
1207          $strReq .= 'GROUP BY dt '.$cat_field;
1208         
1209          $order = 'desc';
1210          if (!empty($params['order']) && preg_match('/^(desc|asc)$/i',$params['order'])) {
1211               $order = $params['order'];
1212          }
1213         
1214          $strReq .=
1215          'ORDER BY dt '.$order.' '.
1216          $limit;
1217         
1218          $rs = $this->con->select($strReq);
1219          $rs->extend('rsExtDates');
1220          return $rs;
1221     }
1222     
1223     /**
1224     Creates a new entry. Takes a cursor as input and returns the new entry
1225     ID.
1226     
1227     @param    cur       <b>cursor</b>       Post cursor
1228     @return   <b>integer</b>      New post ID
1229     */
1230     public function addPost($cur)
1231     {
1232          if (!$this->core->auth->check('usage,contentadmin',$this->id)) {
1233               throw new Exception(__('You are not allowed to create an entry'));
1234          }
1235         
1236          $this->con->writeLock($this->prefix.'post');
1237          try
1238          {
1239               # Get ID
1240               $rs = $this->con->select(
1241                    'SELECT MAX(post_id) '.
1242                    'FROM '.$this->prefix.'post ' 
1243                    );
1244               
1245               $cur->post_id = (integer) $rs->f(0) + 1;
1246               $cur->blog_id = (string) $this->id;
1247               $cur->post_creadt = date('Y-m-d H:i:s');
1248               $cur->post_upddt = date('Y-m-d H:i:s');
1249               $cur->post_tz = $this->core->auth->getInfo('user_tz');
1250               
1251               # Post excerpt and content
1252               $this->getPostContent($cur,$cur->post_id);
1253               
1254               $this->getPostCursor($cur);
1255               
1256               $cur->post_url = $this->getPostURL($cur->post_url,$cur->post_dt,$cur->post_title,$cur->post_id);
1257               
1258               if (!$this->core->auth->check('publish,contentadmin',$this->id)) {
1259                    $cur->post_status = -2;
1260               }
1261               
1262               # --BEHAVIOR-- coreBeforePostCreate
1263               $this->core->callBehavior('coreBeforePostCreate',$this,$cur);
1264               
1265               $cur->insert();
1266               $this->con->unlock();
1267          }
1268          catch (Exception $e)
1269          {
1270               $this->con->unlock();
1271               throw $e;
1272          }
1273         
1274          # --BEHAVIOR-- coreAfterPostCreate
1275          $this->core->callBehavior('coreAfterPostCreate',$this,$cur);
1276         
1277          $this->triggerBlog();
1278         
1279          return $cur->post_id;
1280     }
1281     
1282     /**
1283     Updates an existing post.
1284     
1285     @param    id        <b>integer</b>      Post ID
1286     @param    cur       <b>cursor</b>       Post cursor
1287     */
1288     public function updPost($id,$cur)
1289     {
1290          if (!$this->core->auth->check('usage,contentadmin',$this->id)) {
1291               throw new Exception(__('You are not allowed to update entries'));
1292          }
1293         
1294          $id = (integer) $id;
1295         
1296          if (empty($id)) {
1297               throw new Exception(__('No such entry ID'));
1298          }
1299         
1300          # Post excerpt and content
1301          $this->getPostContent($cur,$id);
1302         
1303          $this->getPostCursor($cur);
1304         
1305          if ($cur->post_url !== null) {
1306               $cur->post_url = $this->getPostURL($cur->post_url,$cur->post_dt,$cur->post_title,$id);
1307          }
1308         
1309          if (!$this->core->auth->check('publish,contentadmin',$this->id)) {
1310               $cur->unsetField('post_status');
1311          }
1312         
1313          $cur->post_upddt = date('Y-m-d H:i:s');
1314         
1315          #If user is only "usage", we need to check the post's owner
1316          if (!$this->core->auth->check('contentadmin',$this->id))
1317          {
1318               $strReq = 'SELECT post_id '.
1319                         'FROM '.$this->prefix.'post '.
1320                         'WHERE post_id = '.$id.' '.
1321                         "AND user_id = '".$this->con->escape($this->core->auth->userID())."' ";
1322               
1323               $rs = $this->con->select($strReq);
1324               
1325               if ($rs->isEmpty()) {
1326                    throw new Exception(__('You are not allowed to edit this entry'));
1327               }
1328          }
1329         
1330          # --BEHAVIOR-- coreBeforePostUpdate
1331          $this->core->callBehavior('coreBeforePostUpdate',$this,$cur);
1332         
1333          $cur->update('WHERE post_id = '.$id.' ');
1334         
1335          # --BEHAVIOR-- coreAfterPostUpdate
1336          $this->core->callBehavior('coreAfterPostUpdate',$this,$cur);
1337         
1338          $this->triggerBlog();
1339     }
1340     
1341     /**
1342     Updates post status.
1343     
1344     @param    id        <b>integer</b>      Post ID
1345     @param    status    <b>integer</b>      Post status
1346     */
1347     public function updPostStatus($id,$status)
1348     {
1349          $this->updPostsStatus($id,$status);
1350     }
1351     
1352     /**
1353     Updates posts status.
1354     
1355     @param    ids       <b>mixed</b>        Post(s) ID(s)
1356     @param    status    <b>integer</b>      Post status
1357     */
1358     public function updPostsStatus($ids,$status)
1359     {
1360          if (!$this->core->auth->check('publish,contentadmin',$this->id)) {
1361               throw new Exception(__('You are not allowed to change this entry status'));
1362          }
1363         
1364          $posts_ids = dcUtils::cleanIds($ids);
1365          $status = (integer) $status;
1366         
1367          $strReq = "WHERE blog_id = '".$this->con->escape($this->id)."' ".
1368                    "AND post_id ".$this->con->in($posts_ids);
1369         
1370          #If user can only publish, we need to check the post's owner
1371          if (!$this->core->auth->check('contentadmin',$this->id))
1372          {
1373               $strReq .= "AND user_id = '".$this->con->escape($this->core->auth->userID())."' ";
1374          }
1375         
1376          $cur = $this->con->openCursor($this->prefix.'post');
1377         
1378          $cur->post_status = $status;
1379          $cur->post_upddt = date('Y-m-d H:i:s');
1380         
1381          $cur->update($strReq);
1382          $this->triggerBlog();
1383     }
1384     
1385     /**
1386     Updates post selection.
1387     
1388     @param    id        <b>integer</b>      Post ID
1389     @param    selected  <b>integer</b>      Is selected post
1390     */
1391     public function updPostSelected($id,$selected)
1392     {
1393          $this->updPostsSelected($id,$selected);
1394     }
1395     
1396     /**
1397     Updates posts selection.
1398     
1399     @param    ids       <b>mixed</b>        Post(s) ID(s)
1400     @param    selected  <b>integer</b>      Is selected post(s)
1401     */
1402     public function updPostsSelected($ids,$selected)
1403     {
1404          if (!$this->core->auth->check('usage,contentadmin',$this->id)) {
1405               throw new Exception(__('You are not allowed to change this entry category'));
1406          }
1407         
1408          $posts_ids = dcUtils::cleanIds($ids);
1409          $selected = (boolean) $selected;
1410         
1411          $strReq = "WHERE blog_id = '".$this->con->escape($this->id)."' ".
1412                    "AND post_id ".$this->con->in($posts_ids);
1413         
1414          # If user is only usage, we need to check the post's owner
1415          if (!$this->core->auth->check('contentadmin',$this->id))
1416          {
1417               $strReq .= "AND user_id = '".$this->con->escape($this->core->auth->userID())."' ";
1418          }
1419         
1420          $cur = $this->con->openCursor($this->prefix.'post');
1421         
1422          $cur->post_selected = (integer) $selected;
1423          $cur->post_upddt = date('Y-m-d H:i:s');
1424         
1425          $cur->update($strReq);
1426          $this->triggerBlog();
1427     }
1428     
1429     /**
1430     Updates post category. <var>$cat_id</var> can be null.
1431     
1432     @param    id        <b>integer</b>      Post ID
1433     @param    cat_id    <b>integer</b>      Category ID
1434     */
1435     public function updPostCategory($id,$cat_id)
1436     {
1437          $this->updPostsCategory($id,$cat_id);
1438     }
1439     
1440     /**
1441     Updates posts category. <var>$cat_id</var> can be null.
1442     
1443     @param    ids       <b>mixed</b>        Post(s) ID(s)
1444     @param    cat_id    <b>integer</b>      Category ID
1445     */
1446     public function updPostsCategory($ids,$cat_id)
1447     {
1448          if (!$this->core->auth->check('usage,contentadmin',$this->id)) {
1449               throw new Exception(__('You are not allowed to change this entry category'));
1450          }
1451         
1452          $posts_ids = dcUtils::cleanIds($ids);
1453          $cat_id = (integer) $cat_id;
1454         
1455          $strReq = "WHERE blog_id = '".$this->con->escape($this->id)."' ".
1456                    "AND post_id ".$this->con->in($posts_ids);
1457         
1458          # If user is only usage, we need to check the post's owner
1459          if (!$this->core->auth->check('contentadmin',$this->id))
1460          {
1461               $strReq .= "AND user_id = '".$this->con->escape($this->core->auth->userID())."' ";
1462          }
1463         
1464          $cur = $this->con->openCursor($this->prefix.'post');
1465         
1466          $cur->cat_id = ($cat_id ? $cat_id : null);
1467          $cur->post_upddt = date('Y-m-d H:i:s');
1468         
1469          $cur->update($strReq);
1470          $this->triggerBlog();
1471     }
1472     
1473     /**
1474     Updates posts category. <var>$new_cat_id</var> can be null.
1475     
1476     @param    old_cat_id     <b>integer</b>      Old category ID
1477     @param    new_cat_id     <b>integer</b>      New category ID
1478     */
1479     public function changePostsCategory($old_cat_id,$new_cat_id)
1480     {
1481          if (!$this->core->auth->check('contentadmin,categories',$this->id)) {
1482               throw new Exception(__('You are not allowed to change entries category'));
1483          }
1484         
1485          $old_cat_id = (integer) $old_cat_id;
1486          $new_cat_id = (integer) $new_cat_id;
1487         
1488          $cur = $this->con->openCursor($this->prefix.'post');
1489         
1490          $cur->cat_id = ($new_cat_id ? $new_cat_id : null);
1491          $cur->post_upddt = date('Y-m-d H:i:s');
1492         
1493          $cur->update(
1494               'WHERE cat_id = '.$old_cat_id.' '.
1495               "AND blog_id = '".$this->con->escape($this->id)."' "
1496          );
1497          $this->triggerBlog();
1498     }
1499     
1500     /**
1501     Deletes a post.
1502     
1503     @param    id        <b>integer</b>      Post ID
1504     */
1505     public function delPost($id)
1506     {
1507          $this->delPosts($id);
1508     }
1509     
1510     /**
1511     Deletes multiple posts.
1512     
1513     @param    ids       <b>mixed</b>        Post(s) ID(s)
1514     */
1515     public function delPosts($ids)
1516     {
1517          if (!$this->core->auth->check('delete,contentadmin',$this->id)) {
1518               throw new Exception(__('You are not allowed to delete entries'));
1519          }
1520         
1521          $posts_ids = dcUtils::cleanIds($ids);
1522         
1523          if (empty($posts_ids)) {
1524               throw new Exception(__('No such entry ID'));
1525          }
1526         
1527          $strReq = 'DELETE FROM '.$this->prefix.'post '.
1528                    "WHERE blog_id = '".$this->con->escape($this->id)."' ".
1529                    "AND post_id ".$this->con->in($posts_ids);
1530         
1531          #If user can only delete, we need to check the post's owner
1532          if (!$this->core->auth->check('contentadmin',$this->id))
1533          {
1534               $strReq .= "AND user_id = '".$this->con->escape($this->core->auth->userID())."' ";
1535          }
1536         
1537          $this->con->execute($strReq);
1538          $this->triggerBlog();
1539     }
1540     
1541     /**
1542     Publishes all entries flaged as "scheduled".
1543     */
1544     public function publishScheduledEntries()
1545     {
1546          $strReq = 'SELECT post_id, post_dt, post_tz '.
1547                    'FROM '.$this->prefix.'post '.
1548                    'WHERE post_status = -1 '.
1549                    "AND blog_id = '".$this->con->escape($this->id)."' ";
1550         
1551          $rs = $this->con->select($strReq);
1552         
1553          $now = dt::toUTC(time());
1554          $to_change = new ArrayObject();
1555
1556          if ($rs->isEmpty()) {
1557               return;
1558          }
1559         
1560          while ($rs->fetch())
1561          {
1562               # Now timestamp with post timezone
1563               $now_tz = $now + dt::getTimeOffset($rs->post_tz,$now);
1564               
1565               # Post timestamp
1566               $post_ts = strtotime($rs->post_dt);
1567               
1568               # If now_tz >= post_ts, we publish the entry
1569               if ($now_tz >= $post_ts) {
1570                    $to_change[] = (integer) $rs->post_id;
1571               }
1572          }
1573          if (count($to_change))
1574          {
1575               # --BEHAVIOR-- coreBeforeScheduledEntriesPublish
1576               $this->core->callBehavior('coreBeforeScheduledEntriesPublish',$this,$to_change);
1577
1578               $strReq =
1579               'UPDATE '.$this->prefix.'post SET '.
1580               'post_status = 1 '.
1581               "WHERE blog_id = '".$this->con->escape($this->id)."' ".
1582               'AND post_id '.$this->con->in((array)$to_change).' ';
1583               $this->con->execute($strReq);
1584               $this->triggerBlog();
1585
1586               # --BEHAVIOR-- coreAfterScheduledEntriesPublish
1587               $this->core->callBehavior('coreAfterScheduledEntriesPublish',$this,$to_change);
1588          }
1589         
1590     }
1591     
1592     /**
1593     Retrieves all users having posts on current blog.
1594     
1595     @param    post_type      <b>string</b>       post_type filter (post)
1596     @return   record
1597     */
1598     public function getPostsUsers($post_type='post')
1599     {
1600          $strReq = 'SELECT P.user_id, user_name, user_firstname, '.
1601                    'user_displayname, user_email '.
1602                    'FROM '.$this->prefix.'post P, '.$this->prefix.'user U '.
1603                    'WHERE P.user_id = U.user_id '.
1604                    "AND blog_id = '".$this->con->escape($this->id)."' ";
1605         
1606          if ($post_type) {
1607               $strReq .= "AND post_type = '".$this->con->escape($post_type)."' ";
1608          }
1609         
1610          $strReq .= 'GROUP BY P.user_id, user_name, user_firstname, user_displayname, user_email ';
1611         
1612          return $this->con->select($strReq);
1613     }
1614     
1615     private function getPostsCategoryFilter($arr,$field='cat_id')
1616     {
1617          $field = $field == 'cat_id' ? 'cat_id' : 'cat_url';
1618         
1619          $sub = array();
1620          $not = array();
1621          $queries = array();
1622         
1623          foreach ($arr as $v)
1624          {
1625               $v = trim($v);
1626               $args = preg_split('/\s*[?]\s*/',$v,-1,PREG_SPLIT_NO_EMPTY);
1627               $id = array_shift($args);
1628               $args = array_flip($args);
1629               
1630               if (isset($args['not'])) { $not[$id] = 1; }
1631               if (isset($args['sub'])) { $sub[$id] = 1; }
1632               if ($field == 'cat_id') {
1633                    if (preg_match('/^null$/i',$id)) {
1634                         $queries[$id] = 'P.cat_id IS NULL';
1635                    }
1636                    else {
1637                         $queries[$id] = 'P.cat_id = '.(integer) $id;
1638                    }
1639               } else {
1640                    $queries[$id] = "C.cat_url = '".$this->con->escape($id)."' ";
1641               }
1642          }
1643         
1644          if (!empty($sub)) {
1645               $rs = $this->con->select(
1646                    'SELECT cat_id, cat_url, cat_lft, cat_rgt FROM '.$this->prefix.'category '.
1647                    "WHERE blog_id = '".$this->con->escape($this->id)."' ".
1648                    'AND '.$field.' '.$this->con->in(array_keys($sub))
1649               );
1650               
1651               while ($rs->fetch()) {
1652                    $queries[$rs->f($field)] = '(C.cat_lft BETWEEN '.$rs->cat_lft.' AND '.$rs->cat_rgt.')';
1653               }
1654          }
1655         
1656          # Create queries
1657          $sql = array(
1658               0 => array(), # wanted categories
1659               1 => array()  # excluded categories
1660          );
1661         
1662          foreach ($queries as $id => $q) {
1663               $sql[(integer) isset($not[$id])][] = $q;
1664          }
1665         
1666          $sql[0] = implode(' OR ',$sql[0]);
1667          $sql[1] = implode(' OR ',$sql[1]);
1668         
1669          if ($sql[0]) {
1670               $sql[0] = '('.$sql[0].')';
1671          } else {
1672               unset($sql[0]);
1673          }
1674         
1675          if ($sql[1]) {
1676               $sql[1] = '(P.cat_id IS NULL OR NOT('.$sql[1].'))';
1677          } else {
1678               unset($sql[1]);
1679          }
1680         
1681          return implode(' AND ',$sql);
1682     }
1683     
1684     private function getPostCursor($cur,$post_id=null)
1685     {
1686          if ($cur->post_title == '') {
1687               throw new Exception(__('No entry title'));
1688          }
1689         
1690          if ($cur->post_content == '') {
1691               throw new Exception(__('No entry content'));
1692          }
1693         
1694          if ($cur->post_password === '') {
1695               $cur->post_password = null;
1696          }
1697         
1698          if ($cur->post_dt == '') {
1699               $offset = dt::getTimeOffset($this->core->auth->getInfo('user_tz'));
1700               $now = time() + $offset;
1701               $cur->post_dt = date('Y-m-d H:i:00',$now);
1702          }
1703         
1704          $post_id = is_int($post_id) ? $post_id : $cur->post_id;
1705         
1706          if ($cur->post_content_xhtml == '') {
1707               throw new Exception(__('No entry content'));
1708          }
1709         
1710          # Words list
1711          if ($cur->post_title !== null && $cur->post_excerpt_xhtml !== null
1712          && $cur->post_content_xhtml !== null)
1713          {
1714               $words =
1715               $cur->post_title.' '.
1716               $cur->post_excerpt_xhtml.' '.
1717               $cur->post_content_xhtml;
1718               
1719               $cur->post_words = implode(' ',text::splitWords($words));
1720          }
1721     }
1722     
1723     private function getPostContent($cur,$post_id)
1724     {
1725          $post_excerpt = $cur->post_excerpt;
1726          $post_excerpt_xhtml = $cur->post_excerpt_xhtml;
1727          $post_content = $cur->post_content;
1728          $post_content_xhtml = $cur->post_content_xhtml;
1729         
1730          $this->setPostContent(
1731               $post_id,$cur->post_format,$cur->post_lang,
1732               $post_excerpt,$post_excerpt_xhtml,
1733               $post_content,$post_content_xhtml
1734          );
1735         
1736          $cur->post_excerpt = $post_excerpt;
1737          $cur->post_excerpt_xhtml = $post_excerpt_xhtml;
1738          $cur->post_content = $post_content;
1739          $cur->post_content_xhtml = $post_content_xhtml;
1740     }
1741     
1742     /**
1743     Creates post HTML content, taking format and lang into account.
1744     
1745     @param         post_id        <b>integer</b>      Post ID
1746     @param         format         <b>string</b>       Post format
1747     @param         lang           <b>string</b>       Post lang
1748     @param         excerpt        <b>string</b>       Post excerpt
1749     @param[out]    excerpt_xhtml  <b>string</b>       Post excerpt HTML
1750     @param         content        <b>string</b>       Post content
1751     @param[out]    content_xhtml  <b>string</b>       Post content HTML
1752     */
1753     public function setPostContent($post_id,$format,$lang,&$excerpt,&$excerpt_xhtml,&$content,&$content_xhtml)
1754     {
1755          if ($format == 'wiki')
1756          {
1757               $this->core->initWikiPost();
1758               $this->core->wiki2xhtml->setOpt('note_prefix','pnote-'.$post_id);
1759               switch ($this->settings->system->note_title_tag) {
1760                    case 1:
1761                         $tag = 'h3';
1762                         break;
1763                    case 2:
1764                         $tag = 'p';
1765                         break;
1766                    default:
1767                         $tag = 'h4';
1768                         break;
1769               }
1770               $this->core->wiki2xhtml->setOpt('note_str','<div class="footnotes"><'.$tag.' class="footnotes-title">'.
1771                    __('Notes').'</'.$tag.'>%s</div>');
1772               $this->core->wiki2xhtml->setOpt('note_str_single','<div class="footnotes"><'.$tag.' class="footnotes-title">'.
1773                    __('Note').'</'.$tag.'>%s</div>');
1774               if (strpos($lang,'fr') === 0) {
1775                    $this->core->wiki2xhtml->setOpt('active_fr_syntax',1);
1776               }
1777          }
1778         
1779          if ($excerpt) {
1780               $excerpt_xhtml = $this->core->callFormater($format,$excerpt);
1781               $excerpt_xhtml = $this->core->HTMLfilter($excerpt_xhtml);
1782          } else {
1783               $excerpt_xhtml = '';
1784          }
1785         
1786          if ($content) {
1787               $content_xhtml = $this->core->callFormater($format,$content);
1788               $content_xhtml = $this->core->HTMLfilter($content_xhtml);
1789          } else {
1790               $content_xhtml = '';
1791          }
1792         
1793          # --BEHAVIOR-- coreAfterPostContentFormat
1794          $this->core->callBehavior('coreAfterPostContentFormat',array(
1795               'excerpt' => &$excerpt,
1796               'content' => &$content,
1797               'excerpt_xhtml' => &$excerpt_xhtml,
1798               'content_xhtml' => &$content_xhtml
1799          ));
1800     }
1801     
1802     /**
1803     Returns URL for a post according to blog setting <var>post_url_format</var>.
1804     It will try to guess URL and append some figures if needed.
1805     
1806     @param    url            <b>string</b>       Origin URL, could be empty
1807     @param    post_dt        <b>string</b>       Post date (in YYYY-MM-DD HH:mm:ss)
1808     @param    post_title     <b>string</b>       Post title
1809     @param    post_id        <b>integer</b>      Post ID
1810     @return   <b>string</b>  result URL
1811     */
1812     public function getPostURL($url,$post_dt,$post_title,$post_id)
1813     {
1814          $url = trim($url);
1815         
1816          $url_patterns = array(
1817          '{y}' => date('Y',strtotime($post_dt)),
1818          '{m}' => date('m',strtotime($post_dt)),
1819          '{d}' => date('d',strtotime($post_dt)),
1820          '{t}' => text::tidyURL($post_title),
1821          '{id}' => (integer) $post_id
1822          );
1823         
1824          # If URL is empty, we create a new one
1825          if ($url == '')
1826          {
1827               # Transform with format
1828               $url = str_replace(
1829                    array_keys($url_patterns),
1830                    array_values($url_patterns),
1831                    $this->settings->system->post_url_format
1832               );
1833          }
1834          else
1835          {
1836               $url = text::tidyURL($url);
1837          }
1838         
1839          # Let's check if URL is taken...
1840          $strReq = 'SELECT post_url FROM '.$this->prefix.'post '.
1841                    "WHERE post_url = '".$this->con->escape($url)."' ".
1842                    'AND post_id <> '.(integer) $post_id. ' '.
1843                    "AND blog_id = '".$this->con->escape($this->id)."' ".
1844                    'ORDER BY post_url DESC';
1845         
1846          $rs = $this->con->select($strReq);
1847         
1848          if (!$rs->isEmpty())
1849          {
1850               if ($this->con->driver() == 'mysql' || $this->con->driver() == 'mysqli') {
1851                    $clause = "REGEXP '^".$this->con->escape($url)."[0-9]+$'";
1852               } elseif ($this->con->driver() == 'pgsql') {
1853                    $clause = "~ '^".$this->con->escape($url)."[0-9]+$'";
1854               } else {
1855                    $clause = "LIKE '".$this->con->escape($url)."%'";
1856               }
1857               $strReq = 'SELECT post_url FROM '.$this->prefix.'post '.
1858                         "WHERE post_url ".$clause.' '.
1859                         'AND post_id <> '.(integer) $post_id.' '.
1860                         "AND blog_id = '".$this->con->escape($this->id)."' ".
1861                         'ORDER BY post_url DESC ';
1862               
1863               $rs = $this->con->select($strReq);
1864               $a = array();
1865               while ($rs->fetch()) {
1866                    $a[] = $rs->post_url;
1867               }
1868               
1869               natsort($a);
1870               $t_url = end($a);
1871               
1872               if (preg_match('/(.*?)([0-9]+)$/',$t_url,$m)) {
1873                    $i = (integer) $m[2];
1874                    $url = $m[1];
1875               } else {
1876                    $i = 1;
1877               }
1878               
1879               return $url.($i+1);
1880          }
1881         
1882          # URL is empty?
1883          if ($url == '') {
1884               throw new Exception(__('Empty entry URL'));
1885          }
1886         
1887          return $url;
1888     }
1889     //@}
1890     
1891     /// @name Comments management methods
1892     //@{
1893     /**
1894     Retrieves comments. <b>$params</b> is an array taking the following
1895     optionnal parameters:
1896     
1897     - no_content: Don't retrieve comment content
1898     - post_type: Get only entries with given type (default no type, array for many types)
1899     - post_id: (integer) Get comments belonging to given post_id
1900     - cat_id: (integer or array) Get comments belonging to entries of given category ID
1901     - comment_id: (integer) Get comment with given ID
1902     - comment_site: (string) Get comments with given comment_site
1903     - comment_status: (integer) Get comments with given comment_status
1904     - comment_trackback: (integer) Get only comments (0) or trackbacks (1)
1905     - comment_ip: (string) Get comments with given IP address
1906     - post_url: Get entry with given post_url field
1907     - user_id: (integer) Get entries belonging to given user ID
1908     - q_author: Search comments by author
1909     - sql: Append SQL string at the end of the query
1910     - from: Append SQL string after "FROM" statement in query
1911     - order: Order of results (default "ORDER BY comment_dt DES")
1912     - limit: Limit parameter
1913     - sql_only : return the sql request instead of results. Only ids are selected
1914     
1915     @param    params         <b>array</b>        Parameters
1916     @param    count_only     <b>boolean</b>      Only counts results
1917     @return   <b>record</b>  A record with some more capabilities
1918     */
1919     public function getComments($params=array(),$count_only=false)
1920     {
1921          if ($count_only)
1922          {
1923               $strReq = 'SELECT count(comment_id) ';
1924          }
1925          elseif (!empty($params['sql_only'])) 
1926          {
1927               $strReq = 'SELECT P.post_id ';
1928          }
1929          else
1930          {
1931               if (!empty($params['no_content'])) {
1932                    $content_req = '';
1933               } else {
1934                    $content_req = 'comment_content, ';
1935               }
1936               
1937               if (!empty($params['columns']) && is_array($params['columns'])) {
1938                    $content_req .= implode(', ',$params['columns']).', ';
1939               }
1940               
1941               $strReq =
1942               'SELECT C.comment_id, comment_dt, comment_tz, comment_upddt, '.
1943               'comment_author, comment_email, comment_site, '.
1944               $content_req.' comment_trackback, comment_status, '.
1945               'comment_spam_status, comment_spam_filter, comment_ip, '.
1946               'P.post_title, P.post_url, P.post_id, P.post_password, P.post_type, '.
1947               'P.post_dt, P.user_id, U.user_email, U.user_url ';
1948          }
1949         
1950          $strReq .=
1951          'FROM '.$this->prefix.'comment C '.
1952          'INNER JOIN '.$this->prefix.'post P ON C.post_id = P.post_id '.
1953          'INNER JOIN '.$this->prefix.'user U ON P.user_id = U.user_id ';
1954         
1955          if (!empty($params['from'])) {
1956               $strReq .= $params['from'].' ';
1957          }
1958         
1959          $strReq .=
1960          "WHERE P.blog_id = '".$this->con->escape($this->id)."' ";
1961         
1962          if (!$this->core->auth->check('contentadmin',$this->id)) {
1963               $strReq .= 'AND ((comment_status = 1 AND P.post_status = 1 ';
1964               
1965               if ($this->without_password) {
1966                    $strReq .= 'AND post_password IS NULL ';
1967               }
1968               $strReq .= ') ';
1969               
1970               if ($this->core->auth->userID()) {
1971                    $strReq .= "OR P.user_id = '".$this->con->escape($this->core->auth->userID())."')";
1972               } else {
1973                    $strReq .= ') ';
1974               }
1975          }
1976         
1977          if (!empty($params['post_type']))
1978          {
1979               $strReq .= 'AND post_type '.$this->con->in($params['post_type']);
1980          }
1981         
1982          if (isset($params['post_id']) && $params['post_id'] !== '') {
1983               $strReq .= 'AND P.post_id = '.(integer) $params['post_id'].' ';
1984          }
1985         
1986          if (isset($params['cat_id']) && $params['cat_id'] !== '') {
1987               $strReq .= 'AND P.cat_id = '.(integer) $params['cat_id'].' ';
1988          }
1989         
1990          if (isset($params['comment_id']) && $params['comment_id'] !== '') {
1991               $strReq .= 'AND comment_id = '.(integer) $params['comment_id'].' ';
1992          }
1993         
1994          if (isset($params['comment_site'])) {
1995               $comment_site = $this->con->escape(str_replace('*','%',$params['comment_site']));
1996               $strReq .= "AND comment_site LIKE '".$comment_site."' ";
1997          }
1998         
1999          if (isset($params['comment_status'])) {
2000               $strReq .= 'AND comment_status = '.(integer) $params['comment_status'].' ';
2001          }
2002         
2003          if (!empty($params['comment_status_not']))
2004          {
2005               $strReq .= 'AND comment_status <> '.(integer) $params['comment_status_not'].' ';
2006          }
2007         
2008          if (isset($params['comment_trackback'])) {
2009               $strReq .= 'AND comment_trackback = '.(integer) (boolean) $params['comment_trackback'].' ';
2010          }
2011         
2012          if (isset($params['comment_ip'])) {
2013               $comment_ip = $this->con->escape(str_replace('*','%',$params['comment_ip']));
2014               $strReq .= "AND comment_ip LIKE '".$comment_ip."' ";
2015          }
2016         
2017          if (isset($params['q_author'])) {
2018               $q_author = $this->con->escape(str_replace('*','%',strtolower($params['q_author'])));
2019               $strReq .= "AND LOWER(comment_author) LIKE '".$q_author."' ";
2020          }
2021         
2022          if (!empty($params['search']))
2023          {
2024               $words = text::splitWords($params['search']);
2025               
2026               if (!empty($words))
2027               {
2028                    # --BEHAVIOR coreCommentSearch
2029                    if ($this->core->hasBehavior('coreCommentSearch')) {
2030                         $this->core->callBehavior('coreCommentSearch',$this->core,array(&$words,&$strReq,&$params));
2031                    }
2032                   
2033                    if ($words)
2034                    {
2035                         foreach ($words as $i => $w) {
2036                              $words[$i] = "comment_words LIKE '%".$this->con->escape($w)."%'";
2037                         }
2038                         $strReq .= 'AND '.implode(' AND ',$words).' ';
2039                    }
2040               }
2041          }
2042         
2043          if (!empty($params['sql'])) {
2044               $strReq .= $params['sql'].' ';
2045          }
2046         
2047          if (!$count_only)
2048          {
2049               if (!empty($params['order'])) {
2050                    $strReq .= 'ORDER BY '.$this->con->escape($params['order']).' ';
2051               } else {
2052                    $strReq .= 'ORDER BY comment_dt DESC ';
2053               }
2054          }
2055         
2056          if (!$count_only && !empty($params['limit'])) {
2057               $strReq .= $this->con->limit($params['limit']);
2058          }
2059
2060          if (!empty($params['sql_only'])) {
2061               return $strReq;
2062          }
2063         
2064          $rs = $this->con->select($strReq);
2065          $rs->core = $this->core;
2066          $rs->extend('rsExtComment');
2067         
2068          # --BEHAVIOR-- coreBlogGetComments
2069          $this->core->callBehavior('coreBlogGetComments',$rs);
2070         
2071          return $rs;
2072     }
2073     
2074     /**
2075     Creates a new comment. Takes a cursor as input and returns the new comment
2076     ID.
2077     
2078     @param    cur       <b>cursor</b>       Comment cursor
2079     @return   <b>integer</b>      New comment ID
2080     */
2081     public function addComment($cur)
2082     {
2083          $this->con->writeLock($this->prefix.'comment');
2084          try
2085          {
2086               # Get ID
2087               $rs = $this->con->select(
2088                    'SELECT MAX(comment_id) '.
2089                    'FROM '.$this->prefix.'comment ' 
2090               );
2091               
2092               $cur->comment_id = (integer) $rs->f(0) + 1;
2093               $cur->comment_upddt = date('Y-m-d H:i:s');
2094               
2095               $offset = dt::getTimeOffset($this->settings->system->blog_timezone);
2096               $cur->comment_dt = date('Y-m-d H:i:s',time() + $offset);
2097               $cur->comment_tz = $this->settings->system->blog_timezone;
2098               
2099               $this->getCommentCursor($cur);
2100               
2101               if ($cur->comment_ip === null) {
2102                    $cur->comment_ip = http::realIP();
2103               }
2104               
2105               # --BEHAVIOR-- coreBeforeCommentCreate
2106               $this->core->callBehavior('coreBeforeCommentCreate',$this,$cur);
2107               
2108               $cur->insert();
2109               $this->con->unlock();
2110          }
2111          catch (Exception $e)
2112          {
2113               $this->con->unlock();
2114               throw $e;
2115          }
2116         
2117          # --BEHAVIOR-- coreAfterCommentCreate
2118          $this->core->callBehavior('coreAfterCommentCreate',$this,$cur);
2119         
2120          $this->triggerComment($cur->comment_id);
2121          if ($cur->comment_status != -2) {
2122               $this->triggerBlog();
2123          }   
2124          return $cur->comment_id;
2125     }
2126     
2127     /**
2128     Updates an existing comment.
2129     
2130     @param    id        <b>integer</b>      Comment ID
2131     @param    cur       <b>cursor</b>       Comment cursor
2132     */
2133     public function updComment($id,$cur)
2134     {
2135          if (!$this->core->auth->check('usage,contentadmin',$this->id)) {
2136               throw new Exception(__('You are not allowed to update comments'));
2137          }
2138         
2139          $id = (integer) $id;
2140         
2141          if (empty($id)) {
2142               throw new Exception(__('No such comment ID'));
2143          }
2144         
2145          $rs = $this->getComments(array('comment_id' => $id));
2146         
2147          if ($rs->isEmpty()) {
2148               throw new Exception(__('No such comment ID'));
2149          }
2150         
2151          #If user is only usage, we need to check the post's owner
2152          if (!$this->core->auth->check('contentadmin',$this->id))
2153          {
2154               if ($rs->user_id != $this->core->auth->userID()) {
2155                    throw new Exception(__('You are not allowed to update this comment'));
2156               }
2157          }
2158         
2159          $this->getCommentCursor($cur);
2160         
2161          $cur->comment_upddt = date('Y-m-d H:i:s');
2162         
2163          if (!$this->core->auth->check('publish,contentadmin',$this->id)) {
2164               $cur->unsetField('comment_status');
2165          }
2166         
2167          # --BEHAVIOR-- coreBeforeCommentUpdate
2168          $this->core->callBehavior('coreBeforeCommentUpdate',$this,$cur,$rs);
2169         
2170          $cur->update('WHERE comment_id = '.$id.' ');
2171         
2172          # --BEHAVIOR-- coreAfterCommentUpdate
2173          $this->core->callBehavior('coreAfterCommentUpdate',$this,$cur,$rs);
2174         
2175          $this->triggerComment($id);
2176          $this->triggerBlog();
2177     }
2178     
2179     /**
2180     Updates comment status.
2181     
2182     @param    id        <b>integer</b>      Comment ID
2183     @param    status    <b>integer</b>      Comment status
2184     */
2185     public function updCommentStatus($id,$status)
2186     {
2187          $this->updCommentsStatus($id,$status);
2188     }
2189     
2190     /**
2191     Updates comments status.
2192     
2193     @param    ids       <b>mixed</b>        Comment(s) ID(s)
2194     @param    status    <b>integer</b>      Comment status
2195     */
2196     public function updCommentsStatus($ids,$status)
2197     {
2198          if (!$this->core->auth->check('publish,contentadmin',$this->id)) {
2199               throw new Exception(__("You are not allowed to change this comment's status"));
2200          }
2201         
2202          $co_ids = dcUtils::cleanIds($ids);
2203          $status = (integer) $status;
2204         
2205          $strReq = 
2206               'UPDATE '.$this->prefix.'comment tc ';
2207         
2208          # mySQL uses "JOIN" synthax
2209          if ($this->con->driver() == 'mysql' || $this->con->driver() == 'mysqli') {
2210               $strReq .= 
2211                    'JOIN '.$this->prefix.'post tp ON tc.post_id = tp.post_id ';
2212          }
2213         
2214          $strReq .= 
2215               'SET comment_status = '.$status.' ';
2216         
2217          # pgSQL uses "FROM" synthax
2218          if ($this->con->driver() != 'mysql' && $this->con->driver() != 'mysqli') {
2219               $strReq .= 
2220                    'FROM '.$this->prefix.'post tp ';
2221          }
2222         
2223          $strReq .=
2224               "WHERE blog_id = '".$this->con->escape($this->id)."' ".
2225               'AND comment_id'.$this->con->in($co_ids);
2226         
2227          # add pgSQL "WHERE" clause
2228          if ($this->con->driver() != 'mysql' && $this->con->driver() != 'mysqli') {
2229               $strReq .= 
2230                    'AND tc.post_id = tp.post_id ';
2231          }
2232         
2233          #If user is only usage, we need to check the post's owner
2234          if (!$this->core->auth->check('contentadmin',$this->id))
2235          {
2236               $strReq .= 
2237                    "AND user_id = '".$this->con->escape($this->core->auth->userID())."' ";
2238          }
2239         
2240          $this->con->execute($strReq);
2241          $this->triggerComments($co_ids);
2242          $this->triggerBlog();
2243     }
2244     
2245     /**
2246     Delete a comment
2247     
2248     @param    id        <b>integer</b>      Comment ID
2249     */
2250     public function delComment($id)
2251     {
2252          $this->delComments($id);
2253     }
2254     
2255     /**
2256     Delete comments
2257     
2258     @param    ids       <b>mixed</b>        Comment(s) ID(s)
2259     */
2260     public function delComments($ids)
2261     {
2262          if (!$this->core->auth->check('delete,contentadmin',$this->id)) {
2263               throw new Exception(__('You are not allowed to delete comments'));
2264          }
2265         
2266          $co_ids = dcUtils::cleanIds($ids);
2267         
2268          if (empty($co_ids)) {
2269               throw new Exception(__('No such comment ID'));
2270          }
2271         
2272          # Retrieve posts affected by comments edition
2273          $affected_posts = array();
2274          $strReq =
2275               'SELECT post_id '.
2276               'FROM '.$this->prefix.'comment '.
2277               'WHERE comment_id'.$this->con->in($co_ids).
2278               'GROUP BY post_id';
2279         
2280          $rs = $this->con->select($strReq);
2281         
2282          while ($rs->fetch()) {
2283               $affected_posts[] = (integer) $rs->post_id;
2284          }
2285         
2286          # mySQL uses "INNER JOIN" synthax
2287          if ($this->con->driver() == 'mysql' || $this->con->driver() == 'mysqli') {
2288               $strReq = 
2289                    'DELETE FROM tc '.
2290                    'USING '.$this->prefix.'comment tc '.
2291                    'INNER JOIN '.$this->prefix.'post tp ';
2292          }
2293          # pgSQL uses nothing special
2294          else {
2295               $strReq = 
2296                    'DELETE FROM '.$this->prefix.'comment tc '.
2297                    'USING '.$this->prefix.'post tp ';
2298          }
2299         
2300          $strReq .= 
2301               'WHERE tc.post_id = tp.post_id '.
2302               "AND tp.blog_id = '".$this->con->escape($this->id)."' ".
2303               'AND comment_id'.$this->con->in($co_ids);
2304         
2305          #If user can only delete, we need to check the post's owner
2306          if (!$this->core->auth->check('contentadmin',$this->id))
2307          {
2308               $strReq .= 
2309                    "AND user_id = '".$this->con->escape($this->core->auth->userID())."' ";
2310          }
2311         
2312          $this->con->execute($strReq);
2313          $this->triggerComments($co_ids, true, $affected_posts);
2314          $this->triggerBlog();
2315     }
2316
2317     public function delJunkComments()
2318     {
2319          if (!$this->core->auth->check('delete,contentadmin',$this->id)) {
2320               throw new Exception(__('You are not allowed to delete comments'));
2321          }
2322         
2323          # mySQL uses "INNER JOIN" synthax
2324          if ($this->con->driver() == 'mysql' || $this->con->driver() == 'mysqli') {
2325               $strReq = 
2326                    'DELETE FROM tc '.
2327                    'USING '.$this->prefix.'comment tc '.
2328                    'INNER JOIN '.$this->prefix.'post tp ';
2329          }
2330          # pgSQL uses nothing special
2331          else {
2332               $strReq = 
2333                    'DELETE FROM '.$this->prefix.'comment tc '.
2334                    'USING '.$this->prefix.'post tp ';
2335          }
2336         
2337          $strReq .= 
2338               'WHERE tc.post_id = tp.post_id '.
2339               "AND tp.blog_id = '".$this->con->escape($this->id)."' ".
2340               'AND comment_status = -2';
2341         
2342          #If user can only delete, we need to check the post's owner
2343          if (!$this->core->auth->check('contentadmin',$this->id))
2344          {
2345               $strReq .= 
2346                    "AND user_id = '".$this->con->escape($this->core->auth->userID())."' ";
2347          }
2348         
2349          $this->con->execute($strReq);
2350          $this->triggerBlog();
2351     }
2352     
2353     private function getCommentCursor($cur)
2354     {
2355          if ($cur->comment_content !== null && $cur->comment_content == '') {
2356               throw new Exception(__('You must provide a comment'));
2357          }
2358         
2359          if ($cur->comment_author !== null && $cur->comment_author == '') {
2360               throw new Exception(__('You must provide an author name'));
2361          }
2362         
2363          if ($cur->comment_email != '' && !text::isEmail($cur->comment_email)) {
2364               throw new Exception(__('Email address is not valid.'));
2365          }
2366         
2367          if ($cur->comment_site !== null && $cur->comment_site != '') {
2368               if (!preg_match('|^http(s?)://|i',$cur->comment_site, $matches)) {
2369                    $cur->comment_site = 'http://'.$cur->comment_site;
2370               }else{
2371                    $cur->comment_site = strtolower($matches[0]).substr($cur->comment_site, strlen($matches[0]));
2372               }
2373          }
2374         
2375          if ($cur->comment_status === null) {
2376               $cur->comment_status = (integer) $this->settings->system->comments_pub;
2377          }
2378         
2379          # Words list
2380          if ($cur->comment_content !== null)
2381          {
2382               $cur->comment_words = implode(' ',text::splitWords($cur->comment_content));
2383          }
2384     }
2385     //@}
2386}
2387?>
Note: See TracBrowser for help on using the repository browser.

Sites map