Dotclear

source: inc/core/class.dc.blog.php @ 2800:92f82976773e

Revision 2800:92f82976773e, 61.7 KB checked in by franck <carnet.franck.paul@…>, 11 years ago (diff)

Add a jQuery js library selector in blog pref, closes #1897

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

Sites map