Dotclear

source: inc/core/class.dc.blog.php @ 778:2761063e54b2

Revision 778:2761063e54b2, 54.2 KB checked in by Dsls <dsls@…>, 14 years ago (diff)

OOps, missed 1 file...

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

Sites map