Dotclear

source: inc/core/class.dc.blog.php @ 3132:9d2359c597a1

Revision 3132:9d2359c597a1, 62.0 KB checked in by franck <carnet.franck.paul@…>, 10 years ago (diff)

Get public URL of a plugin file (similar to dcPage::getPF, but useable in public context)

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

Sites map