Dotclear

source: inc/core/class.dc.blog.php @ 734:db4200975aa1

Revision 734:db4200975aa1, 53.9 KB checked in by franck <carnet.franck.paul@…>, 14 years ago (diff)

triggerBlog missing after reset order of categories - thank's adjaya

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

Sites map