Dotclear

source: inc/core/class.dc.blog.php @ 3263:a2e2eabd0f86

Revision 3263:a2e2eabd0f86, 62.7 KB checked in by franck <carnet.franck.paul@…>, 9 years ago (diff)

Add email and web site filters on comments list (admin), closes #995

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

Sites map