Dotclear

source: inc/core/class.dc.core.php @ 3269:da4849c1ad84

Revision 3269:da4849c1ad84, 39.8 KB checked in by franck <carnet.franck.paul@…>, 9 years ago (diff)

Prevents SSRF/XSPA on Feed import, thanks wiswat for reporting this.

Line 
1<?php
2# -- BEGIN LICENSE BLOCK ---------------------------------------
3#
4# This file is part of Dotclear 2.
5#
6# Copyright (c) 2003-2015 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 -----------------------------------------
12
13/**
14@defgroup DC_CORE Dotclear Core Classes
15*/
16
17/**
18@ingroup DC_CORE
19@nosubgrouping
20@brief Dotclear core class
21
22True to its name dcCore is the core of Dotclear. It handles everything related
23to blogs, database connection, plugins...
24*/
25class dcCore
26{
27     public $con;        ///< <b>connection</b>        Database connection object
28     public $prefix;          ///< <b>string</b>            Database tables prefix
29     public $blog;       ///< <b>dcBlog</b>            dcBlog object
30     public $error;      ///< <b>dcError</b>           dcError object
31     public $auth;       ///< <b>dcAuth</b>            dcAuth object
32     public $session;    ///< <b>sessionDB</b>         sessionDB object
33     public $url;        ///< <b>urlHandler</b>        urlHandler object
34     public $wiki2xhtml; ///< <b>wiki2xhtml</b>        wiki2xhtml object
35     public $plugins;    ///< <b>dcModules</b>         dcModules object
36     public $media;      ///< <b>dcMedia</b>           dcMedia object
37     public $postmedia;  ///< <b>dcPostMedia</b>       dcPostMedia object
38     public $rest;       ///< <b>dcRestServer</b> dcRestServer object
39     public $log;        ///< <b>dcLog</b>             dcLog object
40     public $stime;      ///< <b>float</b>             starting time
41
42     private $versions = null;
43     private $formaters = array();
44     private $behaviors = array();
45     private $post_types = array();
46
47     /**
48     dcCore constructor inits everything related to Dotclear. It takes arguments
49     to init database connection.
50
51     @param    driver    <b>string</b>  Database driver name
52     @param    host      <b>string</b>  Database hostname
53     @param    db        <b>string</b>  Database name
54     @param    user      <b>string</b>  Database username
55     @param    password  <b>string</b>  Database password
56     @param    prefix    <b>string</b>  DotClear tables prefix
57     @param    persist   <b>boolean</b> Persistent database connection
58     */
59     public function __construct($driver, $host, $db, $user, $password, $prefix, $persist)
60     {
61          if (defined('DC_START_TIME')) {
62               $this->stime = DC_START_TIME;
63          } else {
64               $this->stime = microtime(true);
65          }
66
67          $this->con = dbLayer::init($driver,$host,$db,$user,$password,$persist);
68
69          # define weak_locks for mysql
70          if ($this->con instanceof mysqlConnection) {
71               mysqlConnection::$weak_locks = true;
72          } elseif ($this->con instanceof mysqliConnection) {
73               mysqliConnection::$weak_locks = true;
74          }
75
76          # define searchpath for postgresql
77          if ($this->con instanceof pgsqlConnection)
78          {
79               $searchpath = explode ('.',$prefix,2);
80               if (count($searchpath) > 1)
81               {
82                    $prefix = $searchpath[1];
83                    $sql = 'SET search_path TO '.$searchpath[0].',public;';
84                    $this->con->execute($sql);
85               }
86          }
87
88          $this->prefix = $prefix;
89
90          $ttl = DC_SESSION_TTL;
91          if (!is_null($ttl)) {
92               if (substr(trim($ttl),0,1) != '-') {
93                    // Clearbricks requires negative session TTL
94                    $ttl = '-'.trim($ttl);
95               }
96          }
97
98          $this->error = new dcError();
99          $this->auth = $this->authInstance();
100          $this->session = new sessionDB($this->con,$this->prefix.'session',DC_SESSION_NAME,'',null,DC_ADMIN_SSL,$ttl);
101          $this->url = new dcUrlHandlers();
102
103          $this->plugins = new dcPlugins($this);
104
105          $this->rest = new dcRestServer($this);
106
107          $this->meta = new dcMeta($this);
108
109          $this->log = new dcLog($this);
110     }
111
112     private function authInstance()
113     {
114          # You can set DC_AUTH_CLASS to whatever you want.
115          # Your new class *should* inherits dcAuth.
116          if (!defined('DC_AUTH_CLASS')) {
117               $c = 'dcAuth';
118          } else {
119               $c = DC_AUTH_CLASS;
120          }
121
122          if (!class_exists($c)) {
123               throw new Exception('Authentication class '.$c.' does not exist.');
124          }
125
126          if ($c != 'dcAuth' && !is_subclass_of($c,'dcAuth')) {
127               throw new Exception('Authentication class '.$c.' does not inherit dcAuth.');
128          }
129
130          return new $c($this);
131     }
132
133
134     /// @name Blog init methods
135     //@{
136     /**
137     Sets a blog to use in <var>blog</var> property.
138
139     @param    id        <b>string</b>       Blog ID
140     */
141     public function setBlog($id)
142     {
143          $this->blog = new dcBlog($this, $id);
144     }
145
146     /**
147     Unsets <var>blog</var> property.
148     */
149     public function unsetBlog()
150     {
151          $this->blog = null;
152     }
153     //@}
154
155
156     /// @name Blog status methods
157     //@{
158     /**
159     Returns an array of available blog status codes and names.
160
161     @return   <b>array</b> Simple array with codes in keys and names in value
162     */
163     public function getAllBlogStatus()
164     {
165          return array(
166               1 => __('online'),
167               0 => __('offline'),
168               -1 => __('removed')
169          );
170     }
171
172     /**
173     Returns a blog status name given to a code. This is intended to be
174     human-readable and will be translated, so never use it for tests.
175     If status code does not exist, returns <i>offline</i>.
176
177     @param    s    <b>integer</b> Status code
178     @return   <b>string</b> Blog status name
179     */
180     public function getBlogStatus($s)
181     {
182          $r = $this->getAllBlogStatus();
183          if (isset($r[$s])) {
184               return $r[$s];
185          }
186          return $r[0];
187     }
188     //@}
189
190     /// @name Admin nonce secret methods
191     //@{
192
193     public function getNonce()
194     {
195          return $this->auth->crypt(session_id());
196     }
197
198     public function checkNonce($secret)
199     {
200          // 40 alphanumeric characters min
201          if (!preg_match('/^([0-9a-f]{40,})$/i',$secret)) {
202               return false;
203          }
204
205          return $secret == $this->auth->crypt(session_id());
206     }
207
208     public function formNonce()
209     {
210          if (!session_id()) {
211               return;
212          }
213
214          return form::hidden(array('xd_check'),$this->getNonce());
215     }
216     //@}
217
218     /// @name Text Formatters methods
219     //@{
220     /**
221     Adds a new text formater which will call the function <var>$func</var> to
222     transform text. The function must be a valid callback and takes one
223     argument: the string to transform. It returns the transformed string.
224
225     @param    editor_id <b>string</b>  Editor id (dcLegacyEditor, dcCKEditor, ...)
226     @param    name      <b>string</b>  Formater name
227     @param    func      <b>callback</b>     Function to use, must be a valid and callable callback
228     */
229     public function addEditorFormater($editor_id,$name,$func)
230     {
231          if (is_callable($func)) {
232               $this->formaters[$editor_id][$name] = $func;
233          }
234     }
235
236     /// @name Text Formatters methods
237     //@{
238     /**
239     Adds a new text formater which will call the function <var>$func</var> to
240     transform text. The function must be a valid callback and takes one
241     argument: the string to transform. It returns the transformed string.
242
243     @param    name      <b>string</b>       Formater name
244     @param    func      <b>callback</b>     Function to use, must be a valid and callable callback
245     */
246     public function addFormater($name,$func)
247     {
248          $this->addEditorFormater('dcLegacyEditor',$name,$func);
249     }
250
251     /**
252     Returns editors list
253
254     @return   <b>array</b> An array of editors values.
255     */
256     public function getEditors()
257     {
258          $editors = array();
259
260          foreach (array_keys($this->formaters) as $editor_id) {
261               $editors[$editor_id] = $this->plugins->moduleInfo($editor_id,'name');
262          }
263
264          return $editors;
265     }
266
267     /**
268     Returns formaters list by editor
269
270     @param    editor_id <b>string</b>  Editor id (dcLegacyEditor, dcCKEditor, ...)
271     @return   <b>array</b> An array of formaters names in values.
272
273     /**
274     if @param editor_id is empty:
275     return all formaters sorted by actives editors
276
277     if @param editor_id is not empty
278     return formaters for an editor if editor is active
279     return empty() array if editor is not active.
280     It can happens when a user choose an editor and admin deactivate that editor later
281     */
282     public function getFormaters($editor_id='')
283     {
284          $formaters_list = array();
285
286          if (!empty($editor_id)) {
287            if (isset($this->formaters[$editor_id])) {
288                $formaters_list = array_keys($this->formaters[$editor_id]);
289            }
290          } else {
291               foreach ($this->formaters as $editor => $formaters) {
292                    $formaters_list[$editor] = array_keys($formaters);
293               }
294          }
295
296          return $formaters_list;
297     }
298
299     /**
300     If <var>$name</var> is a valid formater, it returns <var>$str</var>
301     transformed using that formater.
302
303     @param    editor_id <b>string</b>  Editor id (dcLegacyEditor, dcCKEditor, ...)
304     @param    name      <b>string</b>  Formater name
305     @param    str            <b>string</b>  String to transform
306     @return   <b>string</b>  String transformed
307     */
308     public function callEditorFormater($editor_id,$name,$str)
309     {
310          if (isset($this->formaters[$editor_id]) && isset($this->formaters[$editor_id][$name])) {
311               return call_user_func($this->formaters[$editor_id][$name],$str);
312          }
313
314          return $str;
315     }
316     //@}
317
318     /**
319     If <var>$name</var> is a valid formater, it returns <var>$str</var>
320     transformed using that formater.
321
322     @param    name      <b>string</b>       Formater name
323     @param    str           <b>string</b>        String to transform
324     @return   <b>string</b>  String transformed
325     */
326     public function callFormater($name,$str)
327     {
328          return $this->callEditorFormater('dcLegacyEditor',$name,$str);
329     }
330     //@}
331
332
333     /// @name Behaviors methods
334     //@{
335     /**
336     Adds a new behavior to behaviors stack. <var>$func</var> must be a valid
337     and callable callback.
338
339     @param    behavior  <b>string</b>       Behavior name
340     @param    func      <b>callback</b>     Function to call
341     */
342     public function addBehavior($behavior,$func)
343     {
344          if (is_callable($func)) {
345               $this->behaviors[$behavior][] = $func;
346          }
347     }
348
349     /**
350     Tests if a particular behavior exists in behaviors stack.
351
352     @param    behavior  <b>string</b>  Behavior name
353     @return   <b>boolean</b>
354     */
355     public function hasBehavior($behavior)
356     {
357          return isset($this->behaviors[$behavior]);
358     }
359
360     /**
361     Get behaviors stack (or part of).
362
363     @param    behavior  <b>string</b>       Behavior name
364     @return   <b>array</b>
365     */
366     public function getBehaviors($behavior='')
367     {
368          if (empty($this->behaviors)) return null;
369
370          if ($behavior == '') {
371               return $this->behaviors;
372          } elseif (isset($this->behaviors[$behavior])) {
373               return $this->behaviors[$behavior];
374          }
375
376          return array();
377     }
378
379     /**
380     Calls every function in behaviors stack for a given behavior and returns
381     concatened result of each function.
382
383     Every parameters added after <var>$behavior</var> will be pass to
384     behavior calls.
385
386     @param    behavior  <b>string</b>  Behavior name
387     @return   <b>string</b> Behavior concatened result
388     */
389     public function callBehavior($behavior)
390     {
391          if (isset($this->behaviors[$behavior]))
392          {
393               $args = func_get_args();
394               array_shift($args);
395
396               $res = '';
397
398               foreach ($this->behaviors[$behavior] as $f) {
399                    $res .= call_user_func_array($f,$args);
400               }
401
402               return $res;
403          }
404     }
405     //@}
406
407     /// @name Post types URLs management
408     //@{
409     public function getPostAdminURL($type,$post_id,$escaped=true)
410     {
411          if (!isset($this->post_types[$type])) {
412               $type = 'post';
413          }
414
415          $url = sprintf($this->post_types[$type]['admin_url'],$post_id);
416          return $escaped ? html::escapeURL($url) : $url;
417     }
418
419     public function getPostPublicURL($type,$post_url,$escaped=true)
420     {
421          if (!isset($this->post_types[$type])) {
422               $type = 'post';
423          }
424
425          $url = sprintf($this->post_types[$type]['public_url'],$post_url);
426          return $escaped ? html::escapeURL($url) : $url;
427     }
428
429     public function setPostType($type,$admin_url,$public_url,$label='')
430     {
431          $this->post_types[$type] = array(
432               'admin_url' => $admin_url,
433               'public_url' => $public_url,
434               'label' => ($label != '' ? $label : $type)
435          );
436     }
437
438     public function getPostTypes()
439     {
440          return $this->post_types;
441     }
442     //@}
443
444     /// @name Versions management methods
445     //@{
446     /**
447     Returns a given $module version.
448
449     @param    module    <b>string</b>  Module name
450     @return   <b>string</b>  Module version
451     */
452     public function getVersion($module='core')
453     {
454          # Fetch versions if needed
455          if (!is_array($this->versions))
456          {
457               $strReq = 'SELECT module, version FROM '.$this->prefix.'version';
458               $rs = $this->con->select($strReq);
459
460               while ($rs->fetch()) {
461                    $this->versions[$rs->module] = $rs->version;
462               }
463          }
464
465          if (isset($this->versions[$module])) {
466               return $this->versions[$module];
467          } else {
468               return null;
469          }
470     }
471
472     /**
473     Sets $version to given $module.
474
475     @param    module    <b>string</b>  Module name
476     @param    version   <b>string</b>  Module version
477     */
478     public function setVersion($module,$version)
479     {
480          $cur_version = $this->getVersion($module);
481
482          $cur = $this->con->openCursor($this->prefix.'version');
483          $cur->module = (string) $module;
484          $cur->version = (string) $version;
485
486          if ($cur_version === null) {
487               $cur->insert();
488          } else {
489               $cur->update("WHERE module='".$this->con->escape($module)."'");
490          }
491
492          $this->versions[$module] = $version;
493     }
494
495     /**
496     Removes given $module version entry.
497
498     @param    module    <b>string</b>  Module name
499     */
500     public function delVersion($module)
501     {
502          $strReq =
503          'DELETE FROM '.$this->prefix.'version '.
504          "WHERE module = '".$this->con->escape($module)."' ";
505
506          $this->con->execute($strReq);
507
508          if (is_array($this->versions)) {
509               unset($this->versions[$module]);
510          }
511     }
512
513     //@}
514
515     /// @name Users management methods
516     //@{
517     /**
518     Returns a user by its ID.
519
520     @param    id        <b>string</b>       User ID
521     @return   <b>record</b>
522     */
523     public function getUser($id)
524     {
525          $params['user_id'] = $id;
526
527          return $this->getUsers($params);
528     }
529
530     /**
531     Returns a users list. <b>$params</b> is an array with the following
532     optionnal parameters:
533
534      - <var>q</var>: search string (on user_id, user_name, user_firstname)
535      - <var>user_id</var>: user ID
536      - <var>order</var>: ORDER BY clause (default: user_id ASC)
537      - <var>limit</var>: LIMIT clause (should be an array ![limit,offset])
538
539     @param    params         <b>array</b>        Parameters
540     @param    count_only     <b>boolean</b>      Only counts results
541     @return   <b>record</b>
542     */
543     public function getUsers($params=array(),$count_only=false)
544     {
545          if ($count_only)
546          {
547               $strReq =
548               'SELECT count(U.user_id) '.
549               'FROM '.$this->prefix.'user U '.
550               'WHERE NULL IS NULL ';
551          }
552          else
553          {
554               $strReq =
555               'SELECT U.user_id,user_super,user_status,user_pwd,user_change_pwd,'.
556               'user_name,user_firstname,user_displayname,user_email,user_url,'.
557               'user_desc, user_lang,user_tz, user_post_status,user_options, '.
558               'count(P.post_id) AS nb_post '.
559               'FROM '.$this->prefix.'user U '.
560                    'LEFT JOIN '.$this->prefix.'post P ON U.user_id = P.user_id '.
561               'WHERE NULL IS NULL ';
562          }
563
564          if (!empty($params['q'])) {
565               $q = $this->con->escape(str_replace('*','%',strtolower($params['q'])));
566               $strReq .= 'AND ('.
567                    "LOWER(U.user_id) LIKE '".$q."' ".
568                    "OR LOWER(user_name) LIKE '".$q."' ".
569                    "OR LOWER(user_firstname) LIKE '".$q."' ".
570                    ') ';
571          }
572
573          if (!empty($params['user_id'])) {
574               $strReq .= "AND U.user_id = '".$this->con->escape($params['user_id'])."' ";
575          }
576
577          if (!$count_only) {
578               $strReq .= 'GROUP BY U.user_id,user_super,user_status,user_pwd,user_change_pwd,'.
579               'user_name,user_firstname,user_displayname,user_email,user_url,'.
580               'user_desc, user_lang,user_tz,user_post_status,user_options ';
581
582               if (!empty($params['order']) && !$count_only) {
583                    if (preg_match('`^([^. ]+) (?:asc|desc)`i',$params['order'],$matches)) {
584                         if (in_array($matches[1],array('user_id','user_name','user_firstname','user_displayname'))) {
585                              $table_prefix = 'U.';
586                         } else {
587                              $table_prefix = ''; // order = nb_post (asc|desc)
588                         }
589                         $strReq .= 'ORDER BY '.$table_prefix.$this->con->escape($params['order']).' ';
590                    } else {
591                         $strReq .= 'ORDER BY '.$this->con->escape($params['order']).' ';
592                    }
593               } else {
594                    $strReq .= 'ORDER BY U.user_id ASC ';
595               }
596          }
597
598          if (!$count_only && !empty($params['limit'])) {
599               $strReq .= $this->con->limit($params['limit']);
600          }
601          $rs = $this->con->select($strReq);
602          $rs->extend('rsExtUser');
603          return $rs;
604     }
605
606     /**
607     Create a new user. Takes a cursor as input and returns the new user ID.
608
609     @param    cur       <b>cursor</b>       User cursor
610     @return   <b>string</b>
611     */
612     public function addUser($cur)
613     {
614          if (!$this->auth->isSuperAdmin()) {
615               throw new Exception(__('You are not an administrator'));
616          }
617
618          if ($cur->user_id == '') {
619               throw new Exception(__('No user ID given'));
620          }
621
622          if ($cur->user_pwd == '') {
623               throw new Exception(__('No password given'));
624          }
625
626          $this->getUserCursor($cur);
627
628          if ($cur->user_creadt === null) {
629               $cur->user_creadt = date('Y-m-d H:i:s');
630          }
631
632          $cur->insert();
633
634          $this->auth->afterAddUser($cur);
635
636          return $cur->user_id;
637     }
638
639     /**
640     Updates an existing user. Returns the user ID.
641
642     @param    id        <b>string</b>       User ID
643     @param    cur       <b>cursor</b>       User cursor
644     @return   <b>string</b>
645     */
646     public function updUser($id,$cur)
647     {
648          $this->getUserCursor($cur);
649
650          if (($cur->user_id !== null || $id != $this->auth->userID()) &&
651          !$this->auth->isSuperAdmin()) {
652               throw new Exception(__('You are not an administrator'));
653          }
654
655          $cur->update("WHERE user_id = '".$this->con->escape($id)."' ");
656
657          $this->auth->afterUpdUser($id,$cur);
658
659          if ($cur->user_id !== null) {
660               $id = $cur->user_id;
661          }
662
663          # Updating all user's blogs
664          $rs = $this->con->select(
665               'SELECT DISTINCT(blog_id) FROM '.$this->prefix.'post '.
666               "WHERE user_id = '".$this->con->escape($id)."' "
667               );
668
669          while ($rs->fetch()) {
670               $b = new dcBlog($this,$rs->blog_id);
671               $b->triggerBlog();
672               unset($b);
673          }
674
675          return $id;
676     }
677
678     /**
679     Deletes a user.
680
681     @param    id        <b>string</b>       User ID
682     */
683     public function delUser($id)
684     {
685          if (!$this->auth->isSuperAdmin()) {
686               throw new Exception(__('You are not an administrator'));
687          }
688
689          if ($id == $this->auth->userID()) {
690               return;
691          }
692
693          $rs = $this->getUser($id);
694
695          if ($rs->nb_post > 0) {
696               return;
697          }
698
699          $strReq = 'DELETE FROM '.$this->prefix.'user '.
700                    "WHERE user_id = '".$this->con->escape($id)."' ";
701
702          $this->con->execute($strReq);
703
704          $this->auth->afterDelUser($id);
705     }
706
707     /**
708     Checks whether a user exists.
709
710     @param    id        <b>string</b>       User ID
711     @return   <b>boolean</b>
712     */
713     public function userExists($id)
714     {
715          $strReq = 'SELECT user_id '.
716                    'FROM '.$this->prefix.'user '.
717                    "WHERE user_id = '".$this->con->escape($id)."' ";
718
719          $rs = $this->con->select($strReq);
720
721          return !$rs->isEmpty();
722     }
723
724     /**
725     Returns all user permissions as an array which looks like:
726
727      - [blog_id]
728        - [name] => Blog name
729        - [url] => Blog URL
730        - [p]
731          - [permission] => true
732          - ...
733
734     @param    id        <b>string</b>       User ID
735     @return   <b>array</b>
736     */
737     public function getUserPermissions($id)
738     {
739          $strReq = 'SELECT B.blog_id, blog_name, blog_url, permissions '.
740                    'FROM '.$this->prefix.'permissions P '.
741                    'INNER JOIN '.$this->prefix.'blog B ON P.blog_id = B.blog_id '.
742                    "WHERE user_id = '".$this->con->escape($id)."' ";
743
744          $rs = $this->con->select($strReq);
745
746          $res = array();
747
748          while ($rs->fetch())
749          {
750               $res[$rs->blog_id] = array(
751                    'name' => $rs->blog_name,
752                    'url' => $rs->blog_url,
753                    'p' => $this->auth->parsePermissions($rs->permissions)
754               );
755          }
756
757          return $res;
758     }
759
760     /**
761     Sets user permissions. The <var>$perms</var> array looks like:
762
763      - [blog_id] => '|perm1|perm2|'
764      - ...
765
766     @param    id        <b>string</b>       User ID
767     @param    perms     <b>array</b>        Permissions array
768     */
769     public function setUserPermissions($id,$perms)
770     {
771          if (!$this->auth->isSuperAdmin()) {
772               throw new Exception(__('You are not an administrator'));
773          }
774
775          $strReq = 'DELETE FROM '.$this->prefix.'permissions '.
776                    "WHERE user_id = '".$this->con->escape($id)."' ";
777
778          $this->con->execute($strReq);
779
780          foreach ($perms as $blog_id => $p) {
781               $this->setUserBlogPermissions($id, $blog_id, $p, false);
782          }
783     }
784
785     /**
786     Sets user permissions for a given blog. <var>$perms</var> is an array with
787     permissions in values
788
789     @param    id             <b>string</b>       User ID
790     @param    blog_id        <b>string</b>       Blog ID
791     @param    perms          <b>array</b>        Permissions
792     @param    delete_first   <b>boolean</b>      Delete permissions before
793     */
794     public function setUserBlogPermissions($id, $blog_id, $perms, $delete_first=true)
795     {
796          if (!$this->auth->isSuperAdmin()) {
797               throw new Exception(__('You are not an administrator'));
798          }
799
800          $no_perm = empty($perms);
801
802          $perms = '|'.implode('|',array_keys($perms)).'|';
803
804          $cur = $this->con->openCursor($this->prefix.'permissions');
805
806          $cur->user_id = (string) $id;
807          $cur->blog_id = (string) $blog_id;
808          $cur->permissions = $perms;
809
810          if ($delete_first || $no_perm)
811          {
812               $strReq = 'DELETE FROM '.$this->prefix.'permissions '.
813                         "WHERE blog_id = '".$this->con->escape($blog_id)."' ".
814                         "AND user_id = '".$this->con->escape($id)."' ";
815
816               $this->con->execute($strReq);
817          }
818
819          if (!$no_perm) {
820               $cur->insert();
821          }
822     }
823
824     /**
825     Sets a user default blog. This blog will be selected when user log in.
826
827     @param    id             <b>string</b>       User ID
828     @param    blog_id        <b>string</b>       Blog ID
829     */
830     public function setUserDefaultBlog($id, $blog_id)
831     {
832          $cur = $this->con->openCursor($this->prefix.'user');
833
834          $cur->user_default_blog = (string) $blog_id;
835
836          $cur->update("WHERE user_id = '".$this->con->escape($id)."'");
837     }
838
839     private function getUserCursor($cur)
840     {
841          if ($cur->isField('user_id')
842          && !preg_match('/^[A-Za-z0-9@._-]{2,}$/',$cur->user_id)) {
843               throw new Exception(__('User ID must contain at least 2 characters using letters, numbers or symbols.'));
844          }
845
846          if ($cur->user_url !== null && $cur->user_url != '') {
847               if (!preg_match('|^http(s?)://|',$cur->user_url)) {
848                    $cur->user_url = 'http://'.$cur->user_url;
849               }
850          }
851
852          if ($cur->isField('user_pwd')) {
853               if (strlen($cur->user_pwd) < 6) {
854                    throw new Exception(__('Password must contain at least 6 characters.'));
855               }
856               $cur->user_pwd = $this->auth->crypt($cur->user_pwd);
857          }
858
859          if ($cur->user_lang !== null && !preg_match('/^[a-z]{2}(-[a-z]{2})?$/',$cur->user_lang)) {
860               throw new Exception(__('Invalid user language code'));
861          }
862
863          if ($cur->user_upddt === null) {
864               $cur->user_upddt = date('Y-m-d H:i:s');
865          }
866
867          if ($cur->user_options !== null) {
868               $cur->user_options = serialize((array) $cur->user_options);
869          }
870     }
871
872     /**
873     Returns user default settings in an associative array with setting names in
874     keys.
875
876     @return   <b>array</b>
877     */
878     public function userDefaults()
879     {
880          return array(
881               'edit_size' => 24,
882               'enable_wysiwyg' => true,
883               'toolbar_bottom' => false,
884               'editor' => array('xhtml' => 'dcCKEditor', 'wiki' => 'dcLegacyEditor'),
885               'post_format' => 'wiki'
886          );
887     }
888     //@}
889
890     /// @name Blog management methods
891     //@{
892     /**
893     Returns all blog permissions (users) as an array which looks like:
894
895      - [user_id]
896        - [name] => User name
897        - [firstname] => User firstname
898        - [displayname] => User displayname
899        - [super] => (true|false) super admin
900        - [p]
901          - [permission] => true
902          - ...
903
904     @param    id             <b>string</b>       Blog ID
905     @param    with_super     <b>boolean</b>      Includes super admins in result
906     @return   <b>array</b>
907     */
908     public function getBlogPermissions($id,$with_super=true)
909     {
910          $strReq =
911          'SELECT U.user_id AS user_id, user_super, user_name, user_firstname, '.
912          'user_displayname, user_email, permissions '.
913          'FROM '.$this->prefix.'user U '.
914          'JOIN '.$this->prefix.'permissions P ON U.user_id = P.user_id '.
915          "WHERE blog_id = '".$this->con->escape($id)."' ";
916
917          if ($with_super) {
918               $strReq .=
919               'UNION '.
920               'SELECT U.user_id AS user_id, user_super, user_name, user_firstname, '.
921               "user_displayname, user_email, NULL AS permissions ".
922               'FROM '.$this->prefix.'user U '.
923               'WHERE user_super = 1 ';
924          }
925
926          $rs = $this->con->select($strReq);
927
928          $res = array();
929
930          while ($rs->fetch())
931          {
932               $res[$rs->user_id] = array(
933                    'name' => $rs->user_name,
934                    'firstname' => $rs->user_firstname,
935                    'displayname' => $rs->user_displayname,
936                    'email' => $rs->user_email,
937                    'super' => (boolean) $rs->user_super,
938                    'p' => $this->auth->parsePermissions($rs->permissions)
939               );
940          }
941
942          return $res;
943     }
944
945     /**
946     Returns a blog of given ID.
947
948     @param    id        <b>string</b>       Blog ID
949     @return   <b>record</b>
950     */
951     public function getBlog($id)
952     {
953          $blog = $this->getBlogs(array('blog_id'=>$id));
954
955          if ($blog->isEmpty()) {
956               return false;
957          }
958
959          return $blog;
960     }
961
962     /**
963     Returns a record of blogs. <b>$params</b> is an array with the following
964     optionnal parameters:
965
966      - <var>blog_id</var>: Blog ID
967      - <var>q</var>: Search string on blog_id, blog_name and blog_url
968      - <var>limit</var>: limit results
969
970     @param    params         <b>array</b>        Parameters
971     @param    count_only     <b>boolean</b>      Count only results
972     @return   <b>record</b>
973     */
974     public function getBlogs($params=array(),$count_only=false)
975     {
976          $join = '';    // %1$s
977          $where = '';   // %2$s
978
979          if ($count_only)
980          {
981               $strReq = 'SELECT count(B.blog_id) '.
982                         'FROM '.$this->prefix.'blog B '.
983                         '%1$s '.
984                         'WHERE NULL IS NULL '.
985                         '%2$s ';
986          }
987          else
988          {
989               $strReq =
990               'SELECT B.blog_id, blog_uid, blog_url, blog_name, blog_desc, blog_creadt, '.
991               'blog_upddt, blog_status '.
992               'FROM '.$this->prefix.'blog B '.
993               '%1$s '.
994               'WHERE NULL IS NULL '.
995               '%2$s ';
996
997               if (!empty($params['order'])) {
998                    $strReq .= 'ORDER BY '.$this->con->escape($params['order']).' ';
999               } else {
1000                    $strReq .= 'ORDER BY B.blog_id ASC ';
1001               }
1002
1003               if (!empty($params['limit'])) {
1004                    $strReq .= $this->con->limit($params['limit']);
1005               }
1006          }
1007
1008          if ($this->auth->userID() && !$this->auth->isSuperAdmin())
1009          {
1010               $join = 'INNER JOIN '.$this->prefix.'permissions PE ON B.blog_id = PE.blog_id ';
1011               $where =
1012               "AND PE.user_id = '".$this->con->escape($this->auth->userID())."' ".
1013               "AND (permissions LIKE '%|usage|%' OR permissions LIKE '%|admin|%' OR permissions LIKE '%|contentadmin|%') ".
1014               "AND blog_status IN (1,0) ";
1015          } elseif (!$this->auth->userID()) {
1016               $where = 'AND blog_status IN (1,0) ';
1017          }
1018
1019          if (!empty($params['blog_id'])) {
1020               $where .= "AND B.blog_id = '".$this->con->escape($params['blog_id'])."' ";
1021          }
1022
1023          if (!empty($params['q'])) {
1024               $params['q'] = strtolower(str_replace('*','%',$params['q']));
1025               $where .=
1026               'AND ('.
1027               "LOWER(B.blog_id) LIKE '".$this->con->escape($params['q'])."' ".
1028               "OR LOWER(B.blog_name) LIKE '".$this->con->escape($params['q'])."' ".
1029               "OR LOWER(B.blog_url) LIKE '".$this->con->escape($params['q'])."' ".
1030               ') ';
1031          }
1032
1033          $strReq = sprintf($strReq,$join,$where);
1034          return $this->con->select($strReq);
1035     }
1036
1037     /**
1038     Creates a new blog.
1039
1040     @param    cur            <b>cursor</b>       Blog cursor
1041     */
1042     public function addBlog($cur)
1043     {
1044          if (!$this->auth->isSuperAdmin()) {
1045               throw new Exception(__('You are not an administrator'));
1046          }
1047
1048          $this->getBlogCursor($cur);
1049
1050          $cur->blog_creadt = date('Y-m-d H:i:s');
1051          $cur->blog_upddt = date('Y-m-d H:i:s');
1052          $cur->blog_uid = md5(uniqid());
1053
1054          $cur->insert();
1055     }
1056
1057     /**
1058     Updates a given blog.
1059
1060     @param    id        <b>string</b>       Blog ID
1061     @param    cur       <b>cursor</b>       Blog cursor
1062     */
1063     public function updBlog($id,$cur)
1064     {
1065          $this->getBlogCursor($cur);
1066
1067          $cur->blog_upddt = date('Y-m-d H:i:s');
1068
1069          $cur->update("WHERE blog_id = '".$this->con->escape($id)."'");
1070     }
1071
1072     private function getBlogCursor($cur)
1073     {
1074          if (($cur->blog_id !== null
1075               && !preg_match('/^[A-Za-z0-9._-]{2,}$/',$cur->blog_id)) ||
1076               (!$cur->blog_id)) {
1077               throw new Exception(__('Blog ID must contain at least 2 characters using letters, numbers or symbols.'));
1078          }
1079
1080          if (($cur->blog_name !== null && $cur->blog_name == '') ||
1081               (!$cur->blog_name)) {
1082               throw new Exception(__('No blog name'));
1083          }
1084
1085          if (($cur->blog_url !== null && $cur->blog_url == '') ||
1086               (!$cur->blog_url)) {
1087               throw new Exception(__('No blog URL'));
1088          }
1089
1090          if ($cur->blog_desc !== null) {
1091               $cur->blog_desc = html::clean($cur->blog_desc);
1092          }
1093     }
1094
1095     /**
1096     Removes a given blog.
1097     @warning This will remove everything related to the blog (posts,
1098     categories, comments, links...)
1099
1100     @param    id        <b>string</b>       Blog ID
1101     */
1102     public function delBlog($id)
1103     {
1104          if (!$this->auth->isSuperAdmin()) {
1105               throw new Exception(__('You are not an administrator'));
1106          }
1107
1108          $strReq = 'DELETE FROM '.$this->prefix.'blog '.
1109                    "WHERE blog_id = '".$this->con->escape($id)."' ";
1110
1111          $this->con->execute($strReq);
1112     }
1113
1114     /**
1115     Checks if a blog exist.
1116
1117     @param    id        <b>string</b>       Blog ID
1118     @return   <b>boolean</b>
1119     */
1120     public function blogExists($id)
1121     {
1122          $strReq = 'SELECT blog_id '.
1123                    'FROM '.$this->prefix.'blog '.
1124                    "WHERE blog_id = '".$this->con->escape($id)."' ";
1125
1126          $rs = $this->con->select($strReq);
1127
1128          return !$rs->isEmpty();
1129     }
1130
1131     /**
1132     Count posts on a blog
1133
1134     @param    id        <b>string</b>       Blog ID
1135     @param    type      <b>string</b>       Post type
1136     @return   <b>boolean</b>
1137     */
1138     public function countBlogPosts($id,$type=null)
1139     {
1140          $strReq = 'SELECT COUNT(post_id) '.
1141                    'FROM '.$this->prefix.'post '.
1142                    "WHERE blog_id = '".$this->con->escape($id)."' ";
1143
1144          if ($type) {
1145               $strReq .= "AND post_type = '".$this->con->escape($type)."' ";
1146          }
1147
1148          return $this->con->select($strReq)->f(0);
1149     }
1150     //@}
1151
1152     /// @name HTML Filter methods
1153     //@{
1154     /**
1155     Calls HTML filter to drop bad tags and produce valid XHTML output (if
1156     tidy extension is present). If <b>enable_html_filter</b> blog setting is
1157     false, returns not filtered string.
1158
1159     @param    str  <b>string</b>       String to filter
1160     @return   <b>string</b> Filtered string.
1161     */
1162     public function HTMLfilter($str)
1163     {
1164          if ($this->blog instanceof dcBlog && !$this->blog->settings->system->enable_html_filter) {
1165               return $str;
1166          }
1167
1168          $filter = new htmlFilter;
1169          $str = trim($filter->apply($str));
1170          return $str;
1171     }
1172     //@}
1173
1174     /// @name wiki2xhtml methods
1175     //@{
1176     private function initWiki()
1177     {
1178          $this->wiki2xhtml = new wiki2xhtml;
1179     }
1180
1181     /**
1182     Returns a transformed string with wiki2xhtml.
1183
1184     @param    str       <b>string</b>       String to transform
1185     @return   <b>string</b>  Transformed string
1186     */
1187     public function wikiTransform($str)
1188     {
1189          if (!($this->wiki2xhtml instanceof wiki2xhtml)) {
1190               $this->initWiki();
1191          }
1192          return $this->wiki2xhtml->transform($str);
1193     }
1194
1195     /**
1196     Inits <var>wiki2xhtml</var> property for blog post.
1197     */
1198     public function initWikiPost()
1199     {
1200          $this->initWiki();
1201
1202          $this->wiki2xhtml->setOpts(array(
1203               'active_title' => 1,
1204               'active_setext_title' => 0,
1205               'active_hr' => 1,
1206               'active_lists' => 1,
1207               'active_quote' => 1,
1208               'active_pre' => 1,
1209               'active_aside' => 1,
1210               'active_empty' => 1,
1211               'active_auto_br' => 0,
1212               'active_auto_urls' => 0,
1213               'active_urls' => 1,
1214               'active_auto_img' => 0,
1215               'active_img' => 1,
1216               'active_anchor' => 1,
1217               'active_em' => 1,
1218               'active_strong' => 1,
1219               'active_br' => 1,
1220               'active_q' => 1,
1221               'active_code' => 1,
1222               'active_acronym' => 1,
1223               'active_ins' => 1,
1224               'active_del' => 1,
1225               'active_footnotes' => 1,
1226               'active_wikiwords' => 0,
1227               'active_macros' => 1,
1228               'active_mark' => 1,
1229               'parse_pre' => 1,
1230               'active_fr_syntax' => 0,
1231               'first_title_level' => 3,
1232               'note_prefix' => 'wiki-footnote',
1233               'note_str' => '<div class="footnotes"><h4>Notes</h4>%s</div>',
1234               'img_style_center' => 'display:table; margin:0 auto;'
1235          ));
1236
1237          $this->wiki2xhtml->registerFunction('url:post',array($this,'wikiPostLink'));
1238
1239          # --BEHAVIOR-- coreWikiPostInit
1240          $this->callBehavior('coreInitWikiPost',$this->wiki2xhtml);
1241     }
1242
1243     /**
1244     Inits <var>wiki2xhtml</var> property for simple blog comment (basic syntax).
1245     */
1246     public function initWikiSimpleComment()
1247     {
1248          $this->initWiki();
1249
1250          $this->wiki2xhtml->setOpts(array(
1251               'active_title' => 0,
1252               'active_setext_title' => 0,
1253               'active_hr' => 0,
1254               'active_lists' => 0,
1255               'active_quote' => 0,
1256               'active_pre' => 0,
1257               'active_aside' => 0,
1258               'active_empty' => 0,
1259               'active_auto_br' => 1,
1260               'active_auto_urls' => 1,
1261               'active_urls' => 0,
1262               'active_auto_img' => 0,
1263               'active_img' => 0,
1264               'active_anchor' => 0,
1265               'active_em' => 0,
1266               'active_strong' => 0,
1267               'active_br' => 0,
1268               'active_q' => 0,
1269               'active_code' => 0,
1270               'active_acronym' => 0,
1271               'active_ins' => 0,
1272               'active_del' => 0,
1273               'active_footnotes' => 0,
1274               'active_wikiwords' => 0,
1275               'active_macros' => 0,
1276               'active_mark' => 0,
1277               'parse_pre' => 0,
1278               'active_fr_syntax' => 0
1279          ));
1280
1281          # --BEHAVIOR-- coreInitWikiSimpleComment
1282          $this->callBehavior('coreInitWikiSimpleComment',$this->wiki2xhtml);
1283     }
1284
1285     /**
1286     Inits <var>wiki2xhtml</var> property for blog comment.
1287     */
1288     public function initWikiComment()
1289     {
1290          $this->initWiki();
1291
1292          $this->wiki2xhtml->setOpts(array(
1293               'active_title' => 0,
1294               'active_setext_title' => 0,
1295               'active_hr' => 0,
1296               'active_lists' => 1,
1297               'active_quote' => 0,
1298               'active_pre' => 1,
1299               'active_aside' => 0,
1300               'active_empty' => 0,
1301               'active_auto_br' => 1,
1302               'active_auto_urls' => 1,
1303               'active_urls' => 1,
1304               'active_auto_img' => 0,
1305               'active_img' => 0,
1306               'active_anchor' => 0,
1307               'active_em' => 1,
1308               'active_strong' => 1,
1309               'active_br' => 1,
1310               'active_q' => 1,
1311               'active_code' => 1,
1312               'active_acronym' => 1,
1313               'active_ins' => 1,
1314               'active_del' => 1,
1315               'active_footnotes' => 0,
1316               'active_wikiwords' => 0,
1317               'active_macros' => 0,
1318               'active_mark' => 1,
1319               'parse_pre' => 0,
1320               'active_fr_syntax' => 0
1321          ));
1322
1323          # --BEHAVIOR-- coreInitWikiComment
1324          $this->callBehavior('coreInitWikiComment',$this->wiki2xhtml);
1325     }
1326
1327     public function wikiPostLink($url,$content)
1328     {
1329          if (!($this->blog instanceof dcBlog)) {
1330               return array();
1331          }
1332
1333          $post_id = abs((integer) substr($url,5));
1334          if (!$post_id) {
1335               return array();
1336          }
1337
1338          $post = $this->blog->getPosts(array('post_id'=>$post_id));
1339          if ($post->isEmpty()) {
1340               return array();
1341          }
1342
1343          $res = array('url' => $post->getURL());
1344          $post_title = $post->post_title;
1345
1346          if ($content != $url) {
1347               $res['title'] = html::escapeHTML($post->post_title);
1348          }
1349
1350          if ($content == '' || $content == $url) {
1351               $res['content'] = html::escapeHTML($post->post_title);
1352          }
1353
1354          if ($post->post_lang) {
1355               $res['lang'] = $post->post_lang;
1356          }
1357
1358          return $res;
1359     }
1360     //@}
1361
1362     /// @name Maintenance methods
1363     //@{
1364     /**
1365     Creates default settings for active blog. Optionnal parameter
1366     <var>defaults</var> replaces default params while needed.
1367
1368     @param    defaults       <b>array</b>   Default parameters
1369     */
1370     public function blogDefaults($defaults=null)
1371     {
1372          if (!is_array($defaults))
1373          {
1374               $defaults = array(
1375                    array('allow_comments','boolean',true,
1376                    'Allow comments on blog'),
1377                    array('allow_trackbacks','boolean',true,
1378                    'Allow trackbacks on blog'),
1379                    array('blog_timezone','string','Europe/London',
1380                    'Blog timezone'),
1381                    array('comments_nofollow','boolean',true,
1382                    'Add rel="nofollow" to comments URLs'),
1383                    array('comments_pub','boolean',true,
1384                    'Publish comments immediately'),
1385                    array('comments_ttl','integer',0,
1386                    'Number of days to keep comments open (0 means no ttl)'),
1387                    array('copyright_notice','string','','Copyright notice (simple text)'),
1388                    array('date_format','string','%A, %B %e %Y',
1389                    'Date format. See PHP strftime function for patterns'),
1390                    array('editor','string','',
1391                    'Person responsible of the content'),
1392                    array('enable_html_filter','boolean',0,
1393                    'Enable HTML filter'),
1394                    array('enable_xmlrpc','boolean',0,
1395                    'Enable XML/RPC interface'),
1396                    array('lang','string','en',
1397                    'Default blog language'),
1398                    array('media_exclusion','string','/\.(phps?|pht(ml)?|phl|s?html?|js|htaccess)[0-9]*$/i',
1399                    'File name exclusion pattern in media manager. (PCRE value)'),
1400                    array('media_img_m_size','integer',448,
1401                    'Image medium size in media manager'),
1402                    array('media_img_s_size','integer',240,
1403                    'Image small size in media manager'),
1404                    array('media_img_t_size','integer',100,
1405                    'Image thumbnail size in media manager'),
1406                    array('media_img_title_pattern','string','Title ;; Date(%b %Y) ;; separator(, )',
1407                    'Pattern to set image title when you insert it in a post'),
1408                    array('media_video_width','integer',400,
1409                    'Video width in media manager'),
1410                    array('media_video_height','integer',300,
1411                    'Video height in media manager'),
1412                    array('media_flash_fallback','boolean',true,
1413                    'Flash player fallback for audio and video media'),
1414                    array('nb_post_for_home','integer',20,
1415                    'Number of entries on first home page'),
1416                    array('nb_post_per_page','integer',20,
1417                    'Number of entries on home pages and category pages'),
1418                    array('nb_post_per_feed','integer',20,
1419                    'Number of entries on feeds'),
1420                    array('nb_comment_per_feed','integer',20,
1421                    'Number of comments on feeds'),
1422                    array('post_url_format','string','{y}/{m}/{d}/{t}',
1423                    'Post URL format. {y}: year, {m}: month, {d}: day, {id}: post id, {t}: entry title'),
1424                    array('public_path','string','public',
1425                    'Path to public directory, begins with a / for a full system path'),
1426                    array('public_url','string','/public',
1427                    'URL to public directory'),
1428                    array('robots_policy','string','INDEX,FOLLOW',
1429                    'Search engines robots policy'),
1430                    array('short_feed_items','boolean',false,
1431                    'Display short feed items'),
1432                    array('theme','string','berlin',
1433                    'Blog theme'),
1434                    array('themes_path','string','themes',
1435                    'Themes root path'),
1436                    array('themes_url','string','/themes',
1437                    'Themes root URL'),
1438                    array('time_format','string','%H:%M',
1439                    'Time format. See PHP strftime function for patterns'),
1440                    array('tpl_allow_php','boolean',false,
1441                    'Allow PHP code in templates'),
1442                    array('tpl_use_cache','boolean',true,
1443                    'Use template caching'),
1444                    array('trackbacks_pub','boolean',true,
1445                    'Publish trackbacks immediately'),
1446                    array('trackbacks_ttl','integer',0,
1447                    'Number of days to keep trackbacks open (0 means no ttl)'),
1448                    array('url_scan','string','query_string',
1449                    'URL handle mode (path_info or query_string)'),
1450                    array('use_smilies','boolean',false,
1451                    'Show smilies on entries and comments'),
1452                    array('no_search','boolean',false,
1453                    'Disable search'),
1454                    array('inc_subcats','boolean',false,
1455                    'Include sub-categories in category page and category posts feed'),
1456                    array('wiki_comments','boolean',false,
1457                    'Allow commenters to use a subset of wiki syntax'),
1458                    array('import_feed_url_control','boolean',true,
1459                    'Control feed URL before import'),
1460                    array('import_feed_no_private_ip','boolean',true,
1461                    'Prevent import feed from private IP'),
1462                    array('import_feed_ip_regexp','string','',
1463                    'Authorize import feed only from this IP regexp'),
1464                    array('import_feed_port_regexp','string','/^(80|443)$/',
1465                    'Authorize import feed only from this port regexp')
1466               );
1467          }
1468
1469          $settings = new dcSettings($this,null);
1470          $settings->addNamespace('system');
1471
1472          foreach ($defaults as $v) {
1473               $settings->system->put($v[0],$v[2],$v[1],$v[3],false,true);
1474          }
1475     }
1476
1477     /**
1478     Recreates entries search engine index.
1479
1480     @param    start     <b>integer</b>      Start entry index
1481     @param    limit     <b>integer</b>      Number of entry to index
1482
1483     @return   <b>integer</b>      <var>$start</var> and <var>$limit</var> sum
1484     */
1485     public function indexAllPosts($start=null,$limit=null)
1486     {
1487          $strReq = 'SELECT COUNT(post_id) '.
1488                    'FROM '.$this->prefix.'post';
1489          $rs = $this->con->select($strReq);
1490          $count = $rs->f(0);
1491
1492          $strReq = 'SELECT post_id, post_title, post_excerpt_xhtml, post_content_xhtml '.
1493                    'FROM '.$this->prefix.'post ';
1494
1495          if ($start !== null && $limit !== null) {
1496               $strReq .= $this->con->limit($start,$limit);
1497          }
1498
1499          $rs = $this->con->select($strReq,true);
1500
1501          $cur = $this->con->openCursor($this->prefix.'post');
1502
1503          while ($rs->fetch())
1504          {
1505               $words = $rs->post_title.' '. $rs->post_excerpt_xhtml.' '.
1506               $rs->post_content_xhtml;
1507
1508               $cur->post_words = implode(' ',text::splitWords($words));
1509               $cur->update('WHERE post_id = '.(integer) $rs->post_id);
1510               $cur->clean();
1511          }
1512
1513          if ($start+$limit > $count) {
1514               return null;
1515          }
1516          return $start+$limit;
1517     }
1518
1519     /**
1520     Recreates comments search engine index.
1521
1522     @param    start     <b>integer</b>      Start comment index
1523     @param    limit     <b>integer</b>      Number of comments to index
1524
1525     @return   <b>integer</b>      <var>$start</var> and <var>$limit</var> sum
1526     */
1527     public function indexAllComments($start=null,$limit=null)
1528     {
1529          $strReq = 'SELECT COUNT(comment_id) '.
1530                    'FROM '.$this->prefix.'comment';
1531          $rs = $this->con->select($strReq);
1532          $count = $rs->f(0);
1533
1534          $strReq = 'SELECT comment_id, comment_content '.
1535                    'FROM '.$this->prefix.'comment ';
1536
1537          if ($start !== null && $limit !== null) {
1538               $strReq .= $this->con->limit($start,$limit);
1539          }
1540
1541          $rs = $this->con->select($strReq);
1542
1543          $cur = $this->con->openCursor($this->prefix.'comment');
1544
1545          while ($rs->fetch())
1546          {
1547               $cur->comment_words = implode(' ',text::splitWords($rs->comment_content));
1548               $cur->update('WHERE comment_id = '.(integer) $rs->comment_id);
1549               $cur->clean();
1550          }
1551
1552          if ($start+$limit > $count) {
1553               return null;
1554          }
1555          return $start+$limit;
1556     }
1557
1558     /**
1559     Reinits nb_comment and nb_trackback in post table.
1560     */
1561     public function countAllComments()
1562     {
1563
1564          $updCommentReq = 'UPDATE '.$this->prefix.'post P '.
1565               'SET nb_comment = ('.
1566                    'SELECT COUNT(C.comment_id) from '.$this->prefix.'comment C '.
1567                    'WHERE C.post_id = P.post_id AND C.comment_trackback <> 1 '.
1568                    'AND C.comment_status = 1 '.
1569               ')';
1570          $updTrackbackReq = 'UPDATE '.$this->prefix.'post P '.
1571               'SET nb_trackback = ('.
1572                    'SELECT COUNT(C.comment_id) from '.$this->prefix.'comment C '.
1573                    'WHERE C.post_id = P.post_id AND C.comment_trackback = 1 '.
1574                    'AND C.comment_status = 1 '.
1575               ')';
1576          $this->con->execute($updCommentReq);
1577          $this->con->execute($updTrackbackReq);
1578     }
1579
1580     /**
1581     Empty templates cache directory
1582     */
1583     public function emptyTemplatesCache()
1584     {
1585          if (is_dir(DC_TPL_CACHE.'/cbtpl')) {
1586               files::deltree(DC_TPL_CACHE.'/cbtpl');
1587          }
1588     }
1589
1590     /**
1591      Return elapsed time since script has been started
1592      @param     $mtime <b>float</b> timestamp (microtime format) to evaluate delta from
1593                                          current time is taken if null
1594      @return <b>float</b>          elapsed time
1595      */
1596     public function getElapsedTime ($mtime=null) {
1597          if ($mtime !== null) {
1598               return $mtime-$this->stime;
1599          } else {
1600               return microtime(true)-$this->stime;
1601          }
1602     }
1603     //@}
1604
1605
1606
1607}
Note: See TracBrowser for help on using the repository browser.

Sites map