Dotclear

source: inc/core/class.dc.blog.php @ 407:eb5bd0f66932

Revision 407:eb5bd0f66932, 53.9 KB checked in by Dsls <dsls@…>, 14 years ago (diff)
  • Re-enabled blank post_type required by media.php in class dcBlog
  • Attachments are now handled by a plugins/attachments/_admin.php
  • Added core dcPostMedia multi-purpose class, and 'link_type' in post_media table
  • Added new behavior : tplIfConditions, to enable to add new attributes to tpl:XXXIf tags
  • Moved tpl:SysIf has_tag attribute to Tags plugin
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     }
586     
587     private function checkCategory($title,$url,$id=null)
588     {
589          $strReq = 'SELECT cat_id '.
590                    'FROM '.$this->prefix.'category '.
591                    "WHERE cat_url = '".$this->con->escape($url)."' ".
592                    "AND blog_id = '".$this->con->escape($this->id)."' ";
593         
594          if ($id !== null) {
595               $strReq .= 'AND cat_id <> '.(integer) $id.' ';
596          }
597         
598          $rs = $this->con->select($strReq);
599         
600          if (!$rs->isEmpty()) {
601               throw new Exception(__('Category URL must be unique.'));
602          }
603     }
604     
605     private function getCategoryCursor($cur,$id=null)
606     {
607          if ($cur->cat_title == '') {
608               throw new Exception(__('You must provide a category title'));
609          }
610         
611          # If we don't have any cat_url, let's do one
612          if ($cur->cat_url == '') {
613               $cur->cat_url = text::tidyURL($cur->cat_title,false);
614          }
615         
616          # Still empty ?
617          if ($cur->cat_url == '') {
618               throw new Exception(__('You must provide a category URL'));
619          } else {
620               $cur->cat_url = text::tidyURL($cur->cat_url,true);
621          }
622         
623          # Check if title or url are unique
624          $this->checkCategory($cur->cat_title,$cur->cat_url,$id);
625         
626          if ($cur->cat_desc !== null) {
627               $cur->cat_desc = $this->core->HTMLfilter($cur->cat_desc);
628          }
629     }
630     //@}
631     
632     /// @name Entries management methods
633     //@{
634     /**
635     Retrieves entries. <b>$params</b> is an array taking the following
636     optionnal parameters:
637     
638     - no_content: Don't retrieve entry content (excerpt and content)
639     - post_type: Get only entries with given type (default "post", array for many types and '' for no type)
640     - post_id: (integer) Get entry with given post_id
641     - post_url: Get entry with given post_url field
642     - user_id: (integer) Get entries belonging to given user ID
643     - cat_id: (string or array) Get entries belonging to given category ID
644     - cat_id_not: deprecated (use cat_id with "id ?not" instead)
645     - cat_url: (string or array) Get entries belonging to given category URL
646     - cat_url_not: deprecated (use cat_url with "url ?not" instead)
647     - post_status: (integer) Get entries with given post_status
648     - post_selected: (boolean) Get select flaged entries
649     - post_year: (integer) Get entries with given year
650     - post_month: (integer) Get entries with given month
651     - post_day: (integer) Get entries with given day
652     - post_lang: Get entries with given language code
653     - search: Get entries corresponding of the following search string
654     - columns: (array) More columns to retrieve
655     - sql: Append SQL string at the end of the query
656     - from: Append SQL string after "FROM" statement in query
657     - order: Order of results (default "ORDER BY post_dt DES")
658     - limit: Limit parameter
659     
660     Please note that on every cat_id or cat_url, you can add ?not to exclude
661     the category and ?sub to get subcategories.
662     
663     @param    params         <b>array</b>        Parameters
664     @param    count_only     <b>boolean</b>      Only counts results
665     @param    sql_only  <b>boolean</b>      Only return SQL request
666     @return   <b>record</b>  A record with some more capabilities or the SQL request
667     */
668     public function getPosts($params=array(),$count_only=false,$sql_only=false)
669     {
670          if ($count_only)
671          {
672               $strReq = 'SELECT count(P.post_id) ';
673          }
674          else
675          {
676               if (!empty($params['no_content'])) {
677                    $content_req = '';
678               } else {
679                    $content_req =
680                    'post_excerpt, post_excerpt_xhtml, '.
681                    'post_content, post_content_xhtml, post_notes, ';
682               }
683               
684               if (!empty($params['columns']) && is_array($params['columns'])) {
685                    $content_req .= implode(', ',$params['columns']).', ';
686               }
687               
688               $strReq =
689               'SELECT P.post_id, P.blog_id, P.user_id, P.cat_id, post_dt, '.
690               'post_tz, post_creadt, post_upddt, post_format, post_password, '.
691               'post_url, post_lang, post_title, '.$content_req.
692               'post_type, post_meta, post_status, post_selected, post_position, '.
693               'post_open_comment, post_open_tb, nb_comment, nb_trackback, '.
694               'U.user_name, U.user_firstname, U.user_displayname, U.user_email, '.
695               'U.user_url, '.
696               'C.cat_title, C.cat_url, C.cat_desc ';
697          }
698         
699          $strReq .=
700          'FROM '.$this->prefix.'post P '.
701          'INNER JOIN '.$this->prefix.'user U ON U.user_id = P.user_id '.
702          'LEFT OUTER JOIN '.$this->prefix.'category C ON P.cat_id = C.cat_id ';
703         
704          if (!empty($params['from'])) {
705               $strReq .= $params['from'].' ';
706          }
707         
708          $strReq .=
709          "WHERE P.blog_id = '".$this->con->escape($this->id)."' ";
710         
711          if (!$this->core->auth->check('contentadmin',$this->id)) {
712               $strReq .= 'AND ((post_status = 1 ';
713               
714               if ($this->without_password) {
715                    $strReq .= 'AND post_password IS NULL ';
716               }
717               $strReq .= ') ';
718               
719               if ($this->core->auth->userID()) {
720                    $strReq .= "OR P.user_id = '".$this->con->escape($this->core->auth->userID())."')";
721               } else {
722                    $strReq .= ') ';
723               }
724          }
725         
726          #Adding parameters
727          if (isset($params['post_type']))
728          {
729               if (is_array($params['post_type']) || $params['post_type'] != '') {
730                    $strReq .= 'AND post_type '.$this->con->in($params['post_type']);
731               }
732          }
733          else
734          {
735               $strReq .= "AND post_type = 'post' ";
736          }
737         
738          if (!empty($params['post_id'])) {
739               if (is_array($params['post_id'])) {
740                    array_walk($params['post_id'],create_function('&$v,$k','if($v!==null){$v=(integer)$v;}'));
741               } else {
742                    $params['post_id'] = array((integer) $params['post_id']);
743               }
744               $strReq .= 'AND P.post_id '.$this->con->in($params['post_id']);
745          }
746         
747          if (!empty($params['post_url'])) {
748               $strReq .= "AND post_url = '".$this->con->escape($params['post_url'])."' ";
749          }
750         
751          if (!empty($params['user_id'])) {
752               $strReq .= "AND U.user_id = '".$this->con->escape($params['user_id'])."' ";
753          }
754         
755          if (!empty($params['cat_id']))
756          {
757               if (!is_array($params['cat_id'])) {
758                    $params['cat_id'] = array($params['cat_id']);
759               }
760               if (!empty($params['cat_id_not'])) {
761                    array_walk($params['cat_id'],create_function('&$v,$k','$v=$v." ?not";'));
762               }
763               $strReq .= 'AND '.$this->getPostsCategoryFilter($params['cat_id'],'cat_id').' ';
764          }
765          elseif (!empty($params['cat_url']))
766          {
767               if (!is_array($params['cat_url'])) {
768                    $params['cat_url'] = array($params['cat_url']);
769               }
770               if (!empty($params['cat_url_not'])) {
771                    array_walk($params['cat_url'],create_function('&$v,$k','$v=$v." ?not";'));
772               }
773               $strReq .= 'AND '.$this->getPostsCategoryFilter($params['cat_url'],'cat_url').' ';
774          }
775         
776          /* Other filters */
777          if (isset($params['post_status'])) {
778               $strReq .= 'AND post_status = '.(integer) $params['post_status'].' ';
779          }
780         
781          if (isset($params['post_selected'])) {
782               $strReq .= 'AND post_selected = '.(integer) $params['post_selected'].' ';
783          }
784         
785          if (!empty($params['post_year'])) {
786               $strReq .= 'AND '.$this->con->dateFormat('post_dt','%Y').' = '.
787               "'".sprintf('%04d',$params['post_year'])."' ";
788          }
789         
790          if (!empty($params['post_month'])) {
791               $strReq .= 'AND '.$this->con->dateFormat('post_dt','%m').' = '.
792               "'".sprintf('%02d',$params['post_month'])."' ";
793          }
794         
795          if (!empty($params['post_day'])) {
796               $strReq .= 'AND '.$this->con->dateFormat('post_dt','%d').' = '.
797               "'".sprintf('%02d',$params['post_day'])."' ";
798          }
799         
800          if (!empty($params['post_lang'])) {
801               $strReq .= "AND P.post_lang = '".$this->con->escape($params['post_lang'])."' ";
802          }
803         
804          if (!empty($params['search']))
805          {
806               $words = text::splitWords($params['search']);
807               
808               if (!empty($words))
809               {
810                    # --BEHAVIOR-- corePostSearch
811                    if ($this->core->hasBehavior('corePostSearch')) {
812                         $this->core->callBehavior('corePostSearch',$this->core,array(&$words,&$strReq,&$params));
813                    }
814                   
815                    if ($words)
816                    {
817                         foreach ($words as $i => $w) {
818                              $words[$i] = "post_words LIKE '%".$this->con->escape($w)."%'";
819                         }
820                         $strReq .= 'AND '.implode(' AND ',$words).' ';
821                    }
822               }
823          }
824         
825          if (!empty($params['sql'])) {
826               $strReq .= $params['sql'].' ';
827          }
828         
829          if (!$count_only)
830          {
831               if (!empty($params['order'])) {
832                    $strReq .= 'ORDER BY '.$this->con->escape($params['order']).' ';
833               } else {
834                    $strReq .= 'ORDER BY post_dt DESC ';
835               }
836          }
837         
838          if (!$count_only && !empty($params['limit'])) {
839               $strReq .= $this->con->limit($params['limit']);
840          }
841         
842          if ($sql_only) {
843               return $strReq;
844          }
845         
846          $rs = $this->con->select($strReq);
847          $rs->core = $this->core;
848          $rs->_nb_media = array();
849          $rs->extend('rsExtPost');
850         
851          # --BEHAVIOR-- coreBlogGetPosts
852          $this->core->callBehavior('coreBlogGetPosts',$rs);
853         
854          return $rs;
855     }
856     
857     /**
858     Returns a record with post id, title and date for next or previous post
859     according to the post ID.
860     $dir could be 1 (next post) or -1 (previous post).
861     
862     @param    post_id                  <b>integer</b>      Post ID
863     @param    dir                      <b>integer</b>      Search direction
864     @param    restrict_to_category     <b>boolean</b>      Restrict to post with same category
865     @param    restrict_to_lang         <b>boolean</b>      Restrict to post with same lang
866     @return   record
867     */
868     public function getNextPost($post,$dir,$restrict_to_category=false, $restrict_to_lang=false)
869     {
870          $dt = $post->post_dt;
871          $post_id = (integer) $post->post_id;
872         
873          if($dir > 0) {
874               $sign = '>';
875               $order = 'ASC';
876          }
877          else {
878               $sign = '<';
879               $order = 'DESC';
880          }
881         
882          $params['post_type'] = $post->post_type;
883          $params['limit'] = 1;
884          $params['order'] = 'post_dt '.$order.', P.post_id '.$order;
885          $params['sql'] =
886          'AND ( '.
887          "    (post_dt = '".$this->con->escape($dt)."' AND P.post_id ".$sign." ".$post_id.") ".
888          "    OR post_dt ".$sign." '".$this->con->escape($dt)."' ".
889          ') ';
890         
891          if ($restrict_to_category) {
892               $params['sql'] .= $post->cat_id ? 'AND P.cat_id = '.(integer) $post->cat_id.' ' : 'AND P.cat_id IS NULL ';
893          }
894         
895          if ($restrict_to_lang) {
896               $params['sql'] .= $post->post_lang ? 'AND P.post_lang = \''. $this->con->escape($post->post_lang) .'\' ': 'AND P.post_lang IS NULL ';
897          }
898         
899          $rs = $this->getPosts($params);
900         
901          if ($rs->isEmpty()) {
902               return null;
903          }
904         
905          return $rs;
906     }
907     
908     /**
909     Retrieves different languages and post count on blog, based on post_lang
910     field. <var>$params</var> is an array taking the following optionnal
911     parameters:
912     
913     - post_type: Get only entries with given type (default "post", '' for no type)
914     - lang: retrieve post count for selected lang
915     - order: order statement (default post_lang DESC)
916     
917     @param    params    <b>array</b>        Parameters
918     @return   record
919     */
920     public function getLangs($params=array())
921     {
922          $strReq = 'SELECT COUNT(post_id) as nb_post, post_lang '.
923                    'FROM '.$this->prefix.'post '.
924                    "WHERE blog_id = '".$this->con->escape($this->id)."' ".
925                    "AND post_lang <> '' ".
926                    "AND post_lang IS NOT NULL ";
927         
928          if (!$this->core->auth->check('contentadmin',$this->id)) {
929               $strReq .= 'AND ((post_status = 1 ';
930               
931               if ($this->without_password) {
932                    $strReq .= 'AND post_password IS NULL ';
933               }
934               $strReq .= ') ';
935               
936               if ($this->core->auth->userID()) {
937                    $strReq .= "OR user_id = '".$this->con->escape($this->core->auth->userID())."')";
938               } else {
939                    $strReq .= ') ';
940               }
941          }
942         
943          if (isset($params['post_type'])) {
944               if ($params['post_type'] != '') {
945                    $strReq .= "AND post_type = '".$this->con->escape($params['post_type'])."' ";
946               }
947          } else {
948               $strReq .= "AND post_type = 'post' ";
949          }
950         
951          if (isset($params['lang'])) {
952               $strReq .= "AND post_lang = '".$this->con->escape($params['lang'])."' ";
953          }
954         
955          $strReq .= 'GROUP BY post_lang ';
956         
957          $order = 'desc';
958          if (!empty($params['order']) && preg_match('/^(desc|asc)$/i',$params['order'])) {
959               $order = $params['order'];
960          }
961          $strReq .= 'ORDER BY post_lang '.$order.' ';
962         
963          return $this->con->select($strReq);
964     }
965     
966     /**
967     Returns a record with all distinct blog dates and post count.
968     <var>$params</var> is an array taking the following optionnal parameters:
969     
970     - type: (day|month|year) Get days, months or years
971     - year: (integer) Get dates for given year
972     - month: (integer) Get dates for given month
973     - day: (integer) Get dates for given day
974     - cat_id: (integer) Category ID filter
975     - cat_url: Category URL filter
976     - post_lang: lang of the posts
977     - next: Get date following match
978     - previous: Get date before match
979     - order: Sort by date "ASC" or "DESC"
980     
981     @param    params    <b>array</b>        Parameters array
982     @return   record
983     */
984     public function getDates($params=array())
985     {
986          $dt_f = '%Y-%m-%d';
987          $dt_fc = '%Y%m%d';
988          if (isset($params['type'])) {
989               if ($params['type'] == 'year') {
990                    $dt_f = '%Y-01-01';
991                    $dt_fc = '%Y0101';
992               } elseif ($params['type'] == 'month') {
993                    $dt_f = '%Y-%m-01';
994                    $dt_fc = '%Y%m01';
995               }
996          }
997          $dt_f .= ' 00:00:00';
998          $dt_fc .= '000000';
999         
1000          $cat_field = $catReq = $limit = '';
1001         
1002          if (!empty($params['cat_id'])) {
1003               $catReq = 'AND P.cat_id = '.(integer) $params['cat_id'].' ';
1004               $cat_field = ', C.cat_url ';
1005          } elseif (!empty($params['cat_url'])) {
1006               $catReq = "AND C.cat_url = '".$this->con->escape($params['cat_url'])."' ";
1007               $cat_field = ', C.cat_url ';
1008          }
1009          if (!empty($params['post_lang'])) {
1010               $catReq = 'AND P.post_lang = \''. $params['post_lang'].'\' ';
1011          }
1012         
1013          $strReq = 'SELECT DISTINCT('.$this->con->dateFormat('post_dt',$dt_f).') AS dt '.
1014                    $cat_field.
1015                    ',COUNT(P.post_id) AS nb_post '.
1016                    'FROM '.$this->prefix.'post P LEFT JOIN '.$this->prefix.'category C '.
1017                    'ON P.cat_id = C.cat_id '.
1018                    "WHERE P.blog_id = '".$this->con->escape($this->id)."' ".
1019                    $catReq;
1020         
1021          if (!$this->core->auth->check('contentadmin',$this->id)) {
1022               $strReq .= 'AND ((post_status = 1 ';
1023               
1024               if ($this->without_password) {
1025                    $strReq .= 'AND post_password IS NULL ';
1026               }
1027               $strReq .= ') ';
1028               
1029               if ($this->core->auth->userID()) {
1030                    $strReq .= "OR P.user_id = '".$this->con->escape($this->core->auth->userID())."')";
1031               } else {
1032                    $strReq .= ') ';
1033               }
1034          }
1035         
1036          if (!empty($params['post_type'])) {
1037               $strReq .= "AND post_type ".$this->con->in($params['post_type'])." ";
1038          } else {
1039               $strReq .= "AND post_type = 'post' ";
1040          }
1041         
1042          if (!empty($params['year'])) {
1043               $strReq .= 'AND '.$this->con->dateFormat('post_dt','%Y')." = '".sprintf('%04d',$params['year'])."' ";
1044          }
1045         
1046          if (!empty($params['month'])) {
1047               $strReq .= 'AND '.$this->con->dateFormat('post_dt','%m')." = '".sprintf('%02d',$params['month'])."' ";
1048          }
1049         
1050          if (!empty($params['day'])) {
1051               $strReq .= 'AND '.$this->con->dateFormat('post_dt','%d')." = '".sprintf('%02d',$params['day'])."' ";
1052          }
1053         
1054          # Get next or previous date
1055          if (!empty($params['next']) || !empty($params['previous']))
1056          {
1057               if (!empty($params['next'])) {
1058                    $pdir = ' > ';
1059                    $params['order'] = 'asc';
1060                    $dt = $params['next'];
1061               } else {
1062                    $pdir = ' < ';
1063                    $params['order'] = 'desc';
1064                    $dt = $params['previous'];
1065               }
1066               
1067               $dt = date('YmdHis',strtotime($dt));
1068               
1069               $strReq .= 'AND '.$this->con->dateFormat('post_dt',$dt_fc).$pdir."'".$dt."' ";
1070               $limit = $this->con->limit(1);
1071          }
1072         
1073          $strReq .= 'GROUP BY dt '.$cat_field;
1074         
1075          $order = 'desc';
1076          if (!empty($params['order']) && preg_match('/^(desc|asc)$/i',$params['order'])) {
1077               $order = $params['order'];
1078          }
1079         
1080          $strReq .=
1081          'ORDER BY dt '.$order.' '.
1082          $limit;
1083         
1084          $rs = $this->con->select($strReq);
1085          $rs->extend('rsExtDates');
1086          return $rs;
1087     }
1088     
1089     /**
1090     Creates a new entry. Takes a cursor as input and returns the new entry
1091     ID.
1092     
1093     @param    cur       <b>cursor</b>       Post cursor
1094     @return   <b>integer</b>      New post ID
1095     */
1096     public function addPost($cur)
1097     {
1098          if (!$this->core->auth->check('usage,contentadmin',$this->id)) {
1099               throw new Exception(__('You are not allowed to create an entry'));
1100          }
1101         
1102          $this->con->writeLock($this->prefix.'post');
1103          try
1104          {
1105               # Get ID
1106               $rs = $this->con->select(
1107                    'SELECT MAX(post_id) '.
1108                    'FROM '.$this->prefix.'post ' 
1109                    );
1110               
1111               $cur->post_id = (integer) $rs->f(0) + 1;
1112               $cur->blog_id = (string) $this->id;
1113               $cur->post_creadt = date('Y-m-d H:i:s');
1114               $cur->post_upddt = date('Y-m-d H:i:s');
1115               $cur->post_tz = $this->core->auth->getInfo('user_tz');
1116               
1117               # Post excerpt and content
1118               $this->getPostContent($cur,$cur->post_id);
1119               
1120               $this->getPostCursor($cur);
1121               
1122               $cur->post_url = $this->getPostURL($cur->post_url,$cur->post_dt,$cur->post_title,$cur->post_id);
1123               
1124               if (!$this->core->auth->check('publish,contentadmin',$this->id)) {
1125                    $cur->post_status = -2;
1126               }
1127               
1128               # --BEHAVIOR-- coreBeforePostCreate
1129               $this->core->callBehavior('coreBeforePostCreate',$this,$cur);
1130               
1131               $cur->insert();
1132               $this->con->unlock();
1133          }
1134          catch (Exception $e)
1135          {
1136               $this->con->unlock();
1137               throw $e;
1138          }
1139         
1140          # --BEHAVIOR-- coreAfterPostCreate
1141          $this->core->callBehavior('coreAfterPostCreate',$this,$cur);
1142         
1143          $this->triggerBlog();
1144         
1145          return $cur->post_id;
1146     }
1147     
1148     /**
1149     Updates an existing post.
1150     
1151     @param    id        <b>integer</b>      Post ID
1152     @param    cur       <b>cursor</b>       Post cursor
1153     */
1154     public function updPost($id,$cur)
1155     {
1156          if (!$this->core->auth->check('usage,contentadmin',$this->id)) {
1157               throw new Exception(__('You are not allowed to update entries'));
1158          }
1159         
1160          $id = (integer) $id;
1161         
1162          if (empty($id)) {
1163               throw new Exception(__('No such entry ID'));
1164          }
1165         
1166          # Post excerpt and content
1167          $this->getPostContent($cur,$id);
1168         
1169          $this->getPostCursor($cur);
1170         
1171          if ($cur->post_url !== null) {
1172               $cur->post_url = $this->getPostURL($cur->post_url,$cur->post_dt,$cur->post_title,$id);
1173          }
1174         
1175          if (!$this->core->auth->check('publish,contentadmin',$this->id)) {
1176               $cur->unsetField('post_status');
1177          }
1178         
1179          $cur->post_upddt = date('Y-m-d H:i:s');
1180         
1181          #If user is only "usage", we need to check the post's owner
1182          if (!$this->core->auth->check('contentadmin',$this->id))
1183          {
1184               $strReq = 'SELECT post_id '.
1185                         'FROM '.$this->prefix.'post '.
1186                         'WHERE post_id = '.$id.' '.
1187                         "AND user_id = '".$this->con->escape($this->core->auth->userID())."' ";
1188               
1189               $rs = $this->con->select($strReq);
1190               
1191               if ($rs->isEmpty()) {
1192                    throw new Exception(__('You are not allowed to edit this entry'));
1193               }
1194          }
1195         
1196          # --BEHAVIOR-- coreBeforePostUpdate
1197          $this->core->callBehavior('coreBeforePostUpdate',$this,$cur);
1198         
1199          $cur->update('WHERE post_id = '.$id.' ');
1200         
1201          # --BEHAVIOR-- coreAfterPostUpdate
1202          $this->core->callBehavior('coreAfterPostUpdate',$this,$cur);
1203         
1204          $this->triggerBlog();
1205     }
1206     
1207     /**
1208     Updates post status.
1209     
1210     @param    id        <b>integer</b>      Post ID
1211     @param    status    <b>integer</b>      Post status
1212     */
1213     public function updPostStatus($id,$status)
1214     {
1215          if (!$this->core->auth->check('publish,contentadmin',$this->id)) {
1216               throw new Exception(__('You are not allowed to change this entry status'));
1217          }
1218         
1219          $id = (integer) $id;
1220          $status = (integer) $status;
1221         
1222          #If user can only publish, we need to check the post's owner
1223          if (!$this->core->auth->check('contentadmin',$this->id))
1224          {
1225               $strReq = 'SELECT post_id '.
1226                         'FROM '.$this->prefix.'post '.
1227                         'WHERE post_id = '.$id.' '.
1228                         "AND blog_id = '".$this->con->escape($this->id)."' ".
1229                         "AND user_id = '".$this->con->escape($this->core->auth->userID())."' ";
1230               
1231               $rs = $this->con->select($strReq);
1232               
1233               if ($rs->isEmpty()) {
1234                    throw new Exception(__('You are not allowed to change this entry status'));
1235               }
1236          }
1237         
1238          $cur = $this->con->openCursor($this->prefix.'post');
1239         
1240          $cur->post_status = $status;
1241          $cur->post_upddt = date('Y-m-d H:i:s');
1242         
1243          $cur->update(
1244               'WHERE post_id = '.$id.' '.
1245               "AND blog_id = '".$this->con->escape($this->id)."' "
1246               );
1247          $this->triggerBlog();
1248     }
1249     
1250     public function updPostSelected($id,$selected)
1251     {
1252          if (!$this->core->auth->check('usage,contentadmin',$this->id)) {
1253               throw new Exception(__('You are not allowed to change this entry category'));
1254          }
1255         
1256          $id = (integer) $id;
1257          $selected = (boolean) $selected;
1258         
1259          # If user is only usage, we need to check the post's owner
1260          if (!$this->core->auth->check('contentadmin',$this->id))
1261          {
1262               $strReq = 'SELECT post_id '.
1263                         'FROM '.$this->prefix.'post '.
1264                         'WHERE post_id = '.$id.' '.
1265                         "AND blog_id = '".$this->con->escape($this->id)."' ".
1266                         "AND user_id = '".$this->con->escape($this->core->auth->userID())."' ";
1267               
1268               $rs = $this->con->select($strReq);
1269               
1270               if ($rs->isEmpty()) {
1271                    throw new Exception(__('You are not allowed to mark this entry as selected'));
1272               }
1273          }
1274         
1275          $cur = $this->con->openCursor($this->prefix.'post');
1276         
1277          $cur->post_selected = (integer) $selected;
1278          $cur->post_upddt = date('Y-m-d H:i:s');
1279         
1280          $cur->update(
1281               'WHERE post_id = '.$id.' '.
1282               "AND blog_id = '".$this->con->escape($this->id)."' "
1283          );
1284          $this->triggerBlog();
1285     }
1286     
1287     /**
1288     Updates post category. <var>$cat_id</var> can be null.
1289     
1290     @param    id        <b>integer</b>      Post ID
1291     @param    cat_id    <b>integer</b>      Category ID
1292     */
1293     public function updPostCategory($id,$cat_id)
1294     {
1295          if (!$this->core->auth->check('usage,contentadmin',$this->id)) {
1296               throw new Exception(__('You are not allowed to change this entry category'));
1297          }
1298         
1299          $id = (integer) $id;
1300          $cat_id = (integer) $cat_id;
1301         
1302          # If user is only usage, we need to check the post's owner
1303          if (!$this->core->auth->check('contentadmin',$this->id))
1304          {
1305               $strReq = 'SELECT post_id '.
1306                         'FROM '.$this->prefix.'post '.
1307                         'WHERE post_id = '.$id.' '.
1308                         "AND blog_id = '".$this->con->escape($this->id)."' ".
1309                         "AND user_id = '".$this->con->escape($this->core->auth->userID())."' ";
1310               
1311               $rs = $this->con->select($strReq);
1312               
1313               if ($rs->isEmpty()) {
1314                    throw new Exception(__('You are not allowed to change this entry category'));
1315               }
1316          }
1317         
1318          $cur = $this->con->openCursor($this->prefix.'post');
1319         
1320          $cur->cat_id = ($cat_id ? $cat_id : null);
1321          $cur->post_upddt = date('Y-m-d H:i:s');
1322         
1323          $cur->update(
1324               'WHERE post_id = '.$id.' '.
1325               "AND blog_id = '".$this->con->escape($this->id)."' "
1326          );
1327          $this->triggerBlog();
1328     }
1329     
1330     /**
1331     Deletes a post.
1332     
1333     @param    id        <b>integer</b>      Post ID
1334     */
1335     public function delPost($id)
1336     {
1337          if (!$this->core->auth->check('delete,contentadmin',$this->id)) {
1338               throw new Exception(__('You are not allowed to delete entries'));
1339          }
1340         
1341          $id = (integer) $id;
1342         
1343          if (empty($id)) {
1344               throw new Exception(__('No such entry ID'));
1345          }
1346         
1347          #If user can only delete, we need to check the post's owner
1348          if (!$this->core->auth->check('contentadmin',$this->id))
1349          {
1350               $strReq = 'SELECT post_id '.
1351                         'FROM '.$this->prefix.'post '.
1352                         'WHERE post_id = '.$id.' '.
1353                         "AND blog_id = '".$this->con->escape($this->id)."' ".
1354                         "AND user_id = '".$this->con->escape($this->core->auth->userID())."' ";
1355               
1356               $rs = $this->con->select($strReq);
1357               
1358               if ($rs->isEmpty()) {
1359                    throw new Exception(__('You are not allowed to delete this entry'));
1360               }
1361          }
1362         
1363         
1364          $strReq = 'DELETE FROM '.$this->prefix.'post '.
1365                    'WHERE post_id = '.$id.' '.
1366                    "AND blog_id = '".$this->con->escape($this->id)."' ";
1367         
1368          $this->con->execute($strReq);
1369          $this->triggerBlog();
1370     }
1371     
1372     /**
1373     Publishes all entries flaged as "scheduled".
1374     */
1375     public function publishScheduledEntries()
1376     {
1377          $strReq = 'SELECT post_id, post_dt, post_tz '.
1378                    'FROM '.$this->prefix.'post '.
1379                    'WHERE post_status = -1 '.
1380                    "AND blog_id = '".$this->con->escape($this->id)."' ";
1381         
1382          $rs = $this->con->select($strReq);
1383         
1384          $now = dt::toUTC(time());
1385          $to_change = array();
1386         
1387          if ($rs->isEmpty()) {
1388               return;
1389          }
1390         
1391          while ($rs->fetch())
1392          {
1393               # Now timestamp with post timezone
1394               $now_tz = $now + dt::getTimeOffset($rs->post_tz,$now);
1395               
1396               # Post timestamp
1397               $post_ts = strtotime($rs->post_dt);
1398               
1399               # If now_tz >= post_ts, we publish the entry
1400               if ($now_tz >= $post_ts) {
1401                    $to_change[] = (integer) $rs->post_id;
1402               }
1403          }
1404         
1405          if (!empty($to_change))
1406          {
1407               $strReq =
1408               'UPDATE '.$this->prefix.'post SET '.
1409               'post_status = 1 '.
1410               "WHERE blog_id = '".$this->con->escape($this->id)."' ".
1411               'AND post_id '.$this->con->in($to_change).' ';
1412               
1413               $this->con->execute($strReq);
1414               $this->triggerBlog();
1415          }
1416     }
1417     
1418     /**
1419     Retrieves all users having posts on current blog.
1420     
1421     @param    post_type      <b>string</b>       post_type filter (post)
1422     @return   record
1423     */
1424     public function getPostsUsers($post_type='post')
1425     {
1426          $strReq = 'SELECT P.user_id, user_name, user_firstname, '.
1427                    'user_displayname, user_email '.
1428                    'FROM '.$this->prefix.'post P, '.$this->prefix.'user U '.
1429                    'WHERE P.user_id = U.user_id '.
1430                    "AND blog_id = '".$this->con->escape($this->id)."' ";
1431         
1432          if ($post_type) {
1433               $strReq .= "AND post_type = '".$this->con->escape($post_type)."' ";
1434          }
1435         
1436          $strReq .= 'GROUP BY P.user_id, user_name, user_firstname, user_displayname, user_email ';
1437         
1438          return $this->con->select($strReq);
1439     }
1440     
1441     private function getPostsCategoryFilter($arr,$field='cat_id')
1442     {
1443          $field = $field == 'cat_id' ? 'cat_id' : 'cat_url';
1444         
1445          $sub = array();
1446          $not = array();
1447          $queries = array();
1448         
1449          foreach ($arr as $v)
1450          {
1451               $v = trim($v);
1452               $args = preg_split('/\s*[?]\s*/',$v,-1,PREG_SPLIT_NO_EMPTY);
1453               $id = array_shift($args);
1454               $args = array_flip($args);
1455               
1456               if (isset($args['not'])) { $not[$id] = 1; }
1457               if (isset($args['sub'])) { $sub[$id] = 1; }
1458               if ($field == 'cat_id') {
1459                    if (preg_match('/^null$/i',$id)) {
1460                         $queries[$id] = 'P.cat_id IS NULL';
1461                    }
1462                    else {
1463                         $queries[$id] = 'P.cat_id = '.(integer) $id;
1464                    }
1465               } else {
1466                    $queries[$id] = "C.cat_url = '".$this->con->escape($id)."' ";
1467               }
1468          }
1469         
1470          if (!empty($sub)) {
1471               $rs = $this->con->select(
1472                    'SELECT cat_id, cat_url, cat_lft, cat_rgt FROM '.$this->prefix.'category '.
1473                    "WHERE blog_id = '".$this->con->escape($this->id)."' ".
1474                    'AND '.$field.' '.$this->con->in(array_keys($sub))
1475               );
1476               
1477               while ($rs->fetch()) {
1478                    $queries[$rs->f($field)] = '(C.cat_lft BETWEEN '.$rs->cat_lft.' AND '.$rs->cat_rgt.')';
1479               }
1480          }
1481         
1482          # Create queries
1483          $sql = array(
1484               0 => array(), # wanted categories
1485               1 => array()  # excluded categories
1486          );
1487         
1488          foreach ($queries as $id => $q) {
1489               $sql[(integer) isset($not[$id])][] = $q;
1490          }
1491         
1492          $sql[0] = implode(' OR ',$sql[0]);
1493          $sql[1] = implode(' OR ',$sql[1]);
1494         
1495          if ($sql[0]) {
1496               $sql[0] = '('.$sql[0].')';
1497          } else {
1498               unset($sql[0]);
1499          }
1500         
1501          if ($sql[1]) {
1502               $sql[1] = '(P.cat_id IS NULL OR NOT('.$sql[1].'))';
1503          } else {
1504               unset($sql[1]);
1505          }
1506         
1507          return implode(' AND ',$sql);
1508     }
1509     
1510     private function getPostCursor($cur,$post_id=null)
1511     {
1512          if ($cur->post_title == '') {
1513               throw new Exception(__('No entry title'));
1514          }
1515         
1516          if ($cur->post_content == '') {
1517               throw new Exception(__('No entry content'));
1518          }
1519         
1520          if ($cur->post_password === '') {
1521               $cur->post_password = null;
1522          }
1523         
1524          if ($cur->post_dt == '') {
1525               $offset = dt::getTimeOffset($this->core->auth->getInfo('user_tz'));
1526               $now = time() + $offset;
1527               $cur->post_dt = date('Y-m-d H:i:00',$now);
1528          }
1529         
1530          $post_id = is_int($post_id) ? $post_id : $cur->post_id;
1531         
1532          if ($cur->post_content_xhtml == '') {
1533               throw new Exception(__('No entry content'));
1534          }
1535         
1536          # Words list
1537          if ($cur->post_title !== null && $cur->post_excerpt_xhtml !== null
1538          && $cur->post_content_xhtml !== null)
1539          {
1540               $words =
1541               $cur->post_title.' '.
1542               $cur->post_excerpt_xhtml.' '.
1543               $cur->post_content_xhtml;
1544               
1545               $cur->post_words = implode(' ',text::splitWords($words));
1546          }
1547     }
1548     
1549     private function getPostContent($cur,$post_id)
1550     {
1551          $post_excerpt = $cur->post_excerpt;
1552          $post_excerpt_xhtml = $cur->post_excerpt_xhtml;
1553          $post_content = $cur->post_content;
1554          $post_content_xhtml = $cur->post_content_xhtml;
1555         
1556          $this->setPostContent(
1557               $post_id,$cur->post_format,$cur->post_lang,
1558               $post_excerpt,$post_excerpt_xhtml,
1559               $post_content,$post_content_xhtml
1560          );
1561         
1562          $cur->post_excerpt = $post_excerpt;
1563          $cur->post_excerpt_xhtml = $post_excerpt_xhtml;
1564          $cur->post_content = $post_content;
1565          $cur->post_content_xhtml = $post_content_xhtml;
1566     }
1567     
1568     /**
1569     Creates post HTML content, taking format and lang into account.
1570     
1571     @param         post_id        <b>integer</b>      Post ID
1572     @param         format         <b>string</b>       Post format
1573     @param         lang           <b>string</b>       Post lang
1574     @param         excerpt        <b>string</b>       Post excerpt
1575     @param[out]    excerpt_xhtml  <b>string</b>       Post excerpt HTML
1576     @param         content        <b>string</b>       Post content
1577     @param[out]    content_xhtml  <b>string</b>       Post content HTML
1578     */
1579     public function setPostContent($post_id,$format,$lang,&$excerpt,&$excerpt_xhtml,&$content,&$content_xhtml)
1580     {
1581          if ($format == 'wiki')
1582          {
1583               $this->core->initWikiPost();
1584               $this->core->wiki2xhtml->setOpt('note_prefix','pnote-'.$post_id);
1585               if (strpos($lang,'fr') === 0) {
1586                    $this->core->wiki2xhtml->setOpt('active_fr_syntax',1);
1587               }
1588          }
1589         
1590          if ($excerpt) {
1591               $excerpt_xhtml = $this->core->callFormater($format,$excerpt);
1592               $excerpt_xhtml = $this->core->HTMLfilter($excerpt_xhtml);
1593          } else {
1594               $excerpt_xhtml = '';
1595          }
1596         
1597          if ($content) {
1598               $content_xhtml = $this->core->callFormater($format,$content);
1599               $content_xhtml = $this->core->HTMLfilter($content_xhtml);
1600          } else {
1601               $content_xhtml = '';
1602          }
1603         
1604          # --BEHAVIOR-- coreAfterPostContentFormat
1605          $this->core->callBehavior('coreAfterPostContentFormat',array(
1606               'excerpt' => &$excerpt,
1607               'content' => &$content,
1608               'excerpt_xhtml' => &$excerpt_xhtml,
1609               'content_xhtml' => &$content_xhtml
1610          ));
1611     }
1612     
1613     /**
1614     Returns URL for a post according to blog setting <var>post_url_format</var>.
1615     It will try to guess URL and append some figures if needed.
1616     
1617     @param    url            <b>string</b>       Origin URL, could be empty
1618     @param    post_dt        <b>string</b>       Post date (in YYYY-MM-DD HH:mm:ss)
1619     @param    post_title     <b>string</b>       Post title
1620     @param    post_id        <b>integer</b>      Post ID
1621     @return   <b>string</b>  result URL
1622     */
1623     public function getPostURL($url,$post_dt,$post_title,$post_id)
1624     {
1625          $url = trim($url);
1626         
1627          $url_patterns = array(
1628          '{y}' => date('Y',strtotime($post_dt)),
1629          '{m}' => date('m',strtotime($post_dt)),
1630          '{d}' => date('d',strtotime($post_dt)),
1631          '{t}' => text::tidyURL($post_title),
1632          '{id}' => (integer) $post_id
1633          );
1634         
1635          # If URL is empty, we create a new one
1636          if ($url == '')
1637          {
1638               # Transform with format
1639               $url = str_replace(
1640                    array_keys($url_patterns),
1641                    array_values($url_patterns),
1642                    $this->settings->system->post_url_format
1643               );
1644          }
1645          else
1646          {
1647               $url = text::tidyURL($url);
1648          }
1649         
1650          # Let's check if URL is taken...
1651          $strReq = 'SELECT post_url FROM '.$this->prefix.'post '.
1652                    "WHERE post_url = '".$this->con->escape($url)."' ".
1653                    'AND post_id <> '.(integer) $post_id. ' '.
1654                    "AND blog_id = '".$this->con->escape($this->id)."' ".
1655                    'ORDER BY post_url DESC';
1656         
1657          $rs = $this->con->select($strReq);
1658         
1659          if (!$rs->isEmpty())
1660          {
1661               if ($this->con->driver() == 'mysql') {
1662                    $clause = "REGEXP '^".$this->con->escape($url)."[0-9]+$'";
1663               } elseif ($this->con->driver() == 'pgsql') {
1664                    $clause = "~ '^".$this->con->escape($url)."[0-9]+$'";
1665               } else {
1666                    $clause = "LIKE '".$this->con->escape($url)."%'";
1667               }
1668               $strReq = 'SELECT post_url FROM '.$this->prefix.'post '.
1669                         "WHERE post_url ".$clause.' '.
1670                         'AND post_id <> '.(integer) $post_id.' '.
1671                         "AND blog_id = '".$this->con->escape($this->id)."' ".
1672                         'ORDER BY post_url DESC ';
1673               
1674               $rs = $this->con->select($strReq);
1675               $a = array();
1676               while ($rs->fetch()) {
1677                    $a[] = $rs->post_url;
1678               }
1679               
1680               natsort($a);
1681               $t_url = end($a);
1682               
1683               if (preg_match('/(.*?)([0-9]+)$/',$t_url,$m)) {
1684                    $i = (integer) $m[2];
1685                    $url = $m[1];
1686               } else {
1687                    $i = 1;
1688               }
1689               
1690               return $url.($i+1);
1691          }
1692         
1693          # URL is empty?
1694          if ($url == '') {
1695               throw new Exception(__('Empty entry URL'));
1696          }
1697         
1698          return $url;
1699     }
1700     //@}
1701     
1702     /// @name Comments management methods
1703     //@{
1704     /**
1705     Retrieves comments. <b>$params</b> is an array taking the following
1706     optionnal parameters:
1707     
1708     - no_content: Don't retrieve comment content
1709     - post_type: Get only entries with given type (default no type, array for many types)
1710     - post_id: (integer) Get comments belonging to given post_id
1711     - cat_id: (integer or array) Get comments belonging to entries of given category ID
1712     - comment_id: (integer) Get comment with given ID
1713     - comment_status: (integer) Get comments with given comment_status
1714     - comment_trackback: (integer) Get only comments (0) or trackbacks (1)
1715     - comment_ip: (string) Get comments with given IP address
1716     - post_url: Get entry with given post_url field
1717     - user_id: (integer) Get entries belonging to given user ID
1718     - q_author: Search comments by author
1719     - sql: Append SQL string at the end of the query
1720     - from: Append SQL string after "FROM" statement in query
1721     - order: Order of results (default "ORDER BY comment_dt DES")
1722     - limit: Limit parameter
1723     
1724     @param    params         <b>array</b>        Parameters
1725     @param    count_only     <b>boolean</b>      Only counts results
1726     @return   <b>record</b>  A record with some more capabilities
1727     */
1728     public function getComments($params=array(),$count_only=false)
1729     {
1730          if ($count_only)
1731          {
1732               $strReq = 'SELECT count(comment_id) ';
1733          }
1734          else
1735          {
1736               if (!empty($params['no_content'])) {
1737                    $content_req = '';
1738               } else {
1739                    $content_req = 'comment_content, ';
1740               }
1741               
1742               if (!empty($params['columns']) && is_array($params['columns'])) {
1743                    $content_req .= implode(', ',$params['columns']).', ';
1744               }
1745               
1746               $strReq =
1747               'SELECT C.comment_id, comment_dt, comment_tz, comment_upddt, '.
1748               'comment_author, comment_email, comment_site, '.
1749               $content_req.' comment_trackback, comment_status, '.
1750               'comment_spam_status, comment_spam_filter, comment_ip, '.
1751               'P.post_title, P.post_url, P.post_id, P.post_password, P.post_type, '.
1752               'P.post_dt, P.user_id, U.user_email, U.user_url ';
1753          }
1754         
1755          $strReq .=
1756          'FROM '.$this->prefix.'comment C '.
1757          'INNER JOIN '.$this->prefix.'post P ON C.post_id = P.post_id '.
1758          'INNER JOIN '.$this->prefix.'user U ON P.user_id = U.user_id ';
1759         
1760          if (!empty($params['from'])) {
1761               $strReq .= $params['from'].' ';
1762          }
1763         
1764          $strReq .=
1765          "WHERE P.blog_id = '".$this->con->escape($this->id)."' ";
1766         
1767          if (!$this->core->auth->check('contentadmin',$this->id)) {
1768               $strReq .= 'AND ((comment_status = 1 AND P.post_status = 1 ';
1769               
1770               if ($this->without_password) {
1771                    $strReq .= 'AND post_password IS NULL ';
1772               }
1773               $strReq .= ') ';
1774               
1775               if ($this->core->auth->userID()) {
1776                    $strReq .= "OR P.user_id = '".$this->con->escape($this->core->auth->userID())."')";
1777               } else {
1778                    $strReq .= ') ';
1779               }
1780          }
1781         
1782          if (!empty($params['post_type']))
1783          {
1784               $strReq .= 'AND post_type '.$this->con->in($params['post_type']);
1785          }
1786         
1787          if (!empty($params['post_id'])) {
1788               $strReq .= 'AND P.post_id = '.(integer) $params['post_id'].' ';
1789          }
1790         
1791          if (!empty($params['cat_id'])) {
1792               $strReq .= 'AND P.cat_id = '.(integer) $params['cat_id'].' ';
1793          }
1794         
1795          if (!empty($params['comment_id'])) {
1796               $strReq .= 'AND comment_id = '.(integer) $params['comment_id'].' ';
1797          }
1798         
1799          if (isset($params['comment_status'])) {
1800               $strReq .= 'AND comment_status = '.(integer) $params['comment_status'].' ';
1801          }
1802         
1803          if (!empty($params['comment_status_not']))
1804          {
1805               $strReq .= 'AND comment_status <> '.(integer) $params['comment_status_not'].' ';
1806          }
1807         
1808          if (isset($params['comment_trackback'])) {
1809               $strReq .= 'AND comment_trackback = '.(integer) (boolean) $params['comment_trackback'].' ';
1810          }
1811         
1812          if (isset($params['comment_ip'])) {
1813               $strReq .= "AND comment_ip = '".$this->con->escape($params['comment_ip'])."' ";
1814          }
1815         
1816          if (isset($params['q_author'])) {
1817               $q_author = $this->con->escape(str_replace('*','%',strtolower($params['q_author'])));
1818               $strReq .= "AND LOWER(comment_author) LIKE '".$q_author."' ";
1819          }
1820         
1821          if (!empty($params['search']))
1822          {
1823               $words = text::splitWords($params['search']);
1824               
1825               if (!empty($words))
1826               {
1827                    # --BEHAVIOR coreCommentSearch
1828                    if ($this->core->hasBehavior('coreCommentSearch')) {
1829                         $this->core->callBehavior('coreCommentSearch',$this->core,array(&$words,&$strReq,&$params));
1830                    }
1831                   
1832                    if ($words)
1833                    {
1834                         foreach ($words as $i => $w) {
1835                              $words[$i] = "comment_words LIKE '%".$this->con->escape($w)."%'";
1836                         }
1837                         $strReq .= 'AND '.implode(' AND ',$words).' ';
1838                    }
1839               }
1840          }
1841         
1842          if (!empty($params['sql'])) {
1843               $strReq .= $params['sql'].' ';
1844          }
1845         
1846          if (!$count_only)
1847          {
1848               if (!empty($params['order'])) {
1849                    $strReq .= 'ORDER BY '.$this->con->escape($params['order']).' ';
1850               } else {
1851                    $strReq .= 'ORDER BY comment_dt DESC ';
1852               }
1853          }
1854         
1855          if (!$count_only && !empty($params['limit'])) {
1856               $strReq .= $this->con->limit($params['limit']);
1857          }
1858         
1859          $rs = $this->con->select($strReq);
1860          $rs->core = $this->core;
1861          $rs->extend('rsExtComment');
1862         
1863          # --BEHAVIOR-- coreBlogGetComments
1864          $this->core->callBehavior('coreBlogGetComments',$rs);
1865         
1866          return $rs;
1867     }
1868     
1869     /**
1870     Creates a new comment. Takes a cursor as input and returns the new comment
1871     ID.
1872     
1873     @param    cur       <b>cursor</b>       Comment cursor
1874     @return   <b>integer</b>      New comment ID
1875     */
1876     public function addComment($cur)
1877     {
1878          $this->con->writeLock($this->prefix.'comment');
1879          try
1880          {
1881               # Get ID
1882               $rs = $this->con->select(
1883                    'SELECT MAX(comment_id) '.
1884                    'FROM '.$this->prefix.'comment ' 
1885               );
1886               
1887               $cur->comment_id = (integer) $rs->f(0) + 1;
1888               $cur->comment_upddt = date('Y-m-d H:i:s');
1889               
1890               $offset = dt::getTimeOffset($this->settings->system->blog_timezone);
1891               $cur->comment_dt = date('Y-m-d H:i:s',time() + $offset);
1892               $cur->comment_tz = $this->settings->system->blog_timezone;
1893               
1894               $this->getCommentCursor($cur);
1895               
1896               if ($cur->comment_ip === null) {
1897                    $cur->comment_ip = http::realIP();
1898               }
1899               
1900               # --BEHAVIOR-- coreBeforeCommentCreate
1901               $this->core->callBehavior('coreBeforeCommentCreate',$this,$cur);
1902               
1903               $cur->insert();
1904               $this->con->unlock();
1905          }
1906          catch (Exception $e)
1907          {
1908               $this->con->unlock();
1909               throw $e;
1910          }
1911         
1912          # --BEHAVIOR-- coreAfterCommentCreate
1913          $this->core->callBehavior('coreAfterCommentCreate',$this,$cur);
1914         
1915          $this->triggerComment($cur->comment_id);
1916          if ($cur->comment_status != -2) {
1917               $this->triggerBlog();
1918          }   
1919          return $cur->comment_id;
1920     }
1921     
1922     /**
1923     Updates an existing comment.
1924     
1925     @param    id        <b>integer</b>      Comment ID
1926     @param    cur       <b>cursor</b>       Comment cursor
1927     */
1928     public function updComment($id,$cur)
1929     {
1930          if (!$this->core->auth->check('usage,contentadmin',$this->id)) {
1931               throw new Exception(__('You are not allowed to update comments'));
1932          }
1933         
1934          $id = (integer) $id;
1935         
1936          if (empty($id)) {
1937               throw new Exception(__('No such comment ID'));
1938          }
1939         
1940          $rs = $this->getComments(array('comment_id' => $id));
1941         
1942          if ($rs->isEmpty()) {
1943               throw new Exception(__('No such comment ID'));
1944          }
1945         
1946          #If user is only usage, we need to check the post's owner
1947          if (!$this->core->auth->check('contentadmin',$this->id))
1948          {
1949               if ($rs->user_id != $this->core->auth->userID()) {
1950                    throw new Exception(__('You are not allowed to update this comment'));
1951               }
1952          }
1953         
1954          $this->getCommentCursor($cur);
1955         
1956          $cur->comment_upddt = date('Y-m-d H:i:s');
1957         
1958          if (!$this->core->auth->check('publish,contentadmin',$this->id)) {
1959               $cur->unsetField('comment_status');
1960          }
1961         
1962          # --BEHAVIOR-- coreBeforeCommentUpdate
1963          $this->core->callBehavior('coreBeforeCommentUpdate',$this,$cur,$rs);
1964         
1965          $cur->update('WHERE comment_id = '.$id.' ');
1966         
1967          # --BEHAVIOR-- coreAfterCommentUpdate
1968          $this->core->callBehavior('coreAfterCommentUpdate',$this,$cur,$rs);
1969         
1970          $this->triggerComment($id);
1971          $this->triggerBlog();
1972     }
1973     
1974     /**
1975     Updates comment status.
1976     
1977     @param    id        <b>integer</b>      Comment ID
1978     @param    status    <b>integer</b>      Comment status
1979     */
1980     public function updCommentStatus($id,$status)
1981     {
1982          if (!$this->core->auth->check('publish,contentadmin',$this->id)) {
1983               throw new Exception(__("You are not allowed to change this comment's status"));
1984          }
1985         
1986          $cur = $this->con->openCursor($this->prefix.'comment');
1987          $cur->comment_status = (integer) $status;
1988          $this->updComment($id,$cur);
1989     }
1990     
1991     /**
1992     Delete a comment
1993     
1994     @param    id        <b>integer</b>      Comment ID
1995     */
1996     public function delComment($id)
1997     {
1998          if (!$this->core->auth->check('delete,contentadmin',$this->id)) {
1999               throw new Exception(__('You are not allowed to delete comments'));
2000          }
2001         
2002          $id = (integer) $id;
2003         
2004          if (empty($id)) {
2005               throw new Exception(__('No such comment ID'));
2006          }
2007         
2008          #If user can only delete, we need to check the post's owner
2009          if (!$this->core->auth->check('contentadmin',$this->id))
2010          {
2011               $strReq = 'SELECT P.post_id '.
2012                         'FROM '.$this->prefix.'post P, '.$this->prefix.'comment C '.
2013                         'WHERE P.post_id = C.post_id '.
2014                         "AND P.blog_id = '".$this->con->escape($this->id)."' ".
2015                         'AND comment_id = '.$id.' '.
2016                         "AND user_id = '".$this->con->escape($this->core->auth->userID())."' ";
2017               
2018               $rs = $this->con->select($strReq);
2019               
2020               if ($rs->isEmpty()) {
2021                    throw new Exception(__('You are not allowed to delete this comment'));
2022               }
2023          }
2024         
2025          $strReq = 'DELETE FROM '.$this->prefix.'comment '.
2026                    'WHERE comment_id = '.$id.' ';
2027         
2028          $this->triggerComment($id,true);
2029          $this->con->execute($strReq);
2030          $this->triggerBlog();
2031     }
2032     
2033     private function getCommentCursor($cur)
2034     {
2035          if ($cur->comment_content !== null && $cur->comment_content == '') {
2036               throw new Exception(__('You must provide a comment'));
2037          }
2038         
2039          if ($cur->comment_author !== null && $cur->comment_author == '') {
2040               throw new Exception(__('You must provide an author name'));
2041          }
2042         
2043          if ($cur->comment_email != '' && !text::isEmail($cur->comment_email)) {
2044               throw new Exception(__('Email address is not valid.'));
2045          }
2046         
2047          if ($cur->comment_site !== null && $cur->comment_site != '') {
2048               if (!preg_match('|^http(s?)://|',$cur->comment_site)) {
2049                    $cur->comment_site = 'http://'.$cur->comment_site;
2050               }
2051          }
2052         
2053          if ($cur->comment_status === null) {
2054               $cur->comment_status = (integer) $this->settings->system->comments_pub;
2055          }
2056         
2057          # Words list
2058          if ($cur->comment_content !== null)
2059          {
2060               $cur->comment_words = implode(' ',text::splitWords($cur->comment_content));
2061          }
2062     }
2063     //@}
2064}
2065?>
Note: See TracBrowser for help on using the repository browser.

Sites map