Dotclear

source: inc/core/class.dc.core.php @ 2999:7a766509c5aa

Revision 2999:7a766509c5aa, 38.7 KB checked in by Nicolas <nikrou77@…>, 10 years ago (diff)

Fix #2087 - Ambiguous column name for SQLite

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

Sites map