Dotclear

source: inc/core/class.dc.core.php @ 3030:1c346de31ad1

Revision 3030:1c346de31ad1, 38.8 KB checked in by franck <carnet.franck.paul@…>, 10 years ago (diff)

Add an blog option to disable internal search (404 on ?q= queries, search widget hidden), fixes #1888

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               'toolbar_bottom' => false,
877               'editor' => array('xhtml' => 'dcCKEditor', 'wiki' => 'dcLegacyEditor'),
878               'post_format' => 'wiki'
879          );
880     }
881     //@}
882
883     /// @name Blog management methods
884     //@{
885     /**
886     Returns all blog permissions (users) as an array which looks like:
887
888      - [user_id]
889        - [name] => User name
890        - [firstname] => User firstname
891        - [displayname] => User displayname
892        - [super] => (true|false) super admin
893        - [p]
894          - [permission] => true
895          - ...
896
897     @param    id             <b>string</b>       Blog ID
898     @param    with_super     <b>boolean</b>      Includes super admins in result
899     @return   <b>array</b>
900     */
901     public function getBlogPermissions($id,$with_super=true)
902     {
903          $strReq =
904          'SELECT U.user_id AS user_id, user_super, user_name, user_firstname, '.
905          'user_displayname, user_email, permissions '.
906          'FROM '.$this->prefix.'user U '.
907          'JOIN '.$this->prefix.'permissions P ON U.user_id = P.user_id '.
908          "WHERE blog_id = '".$this->con->escape($id)."' ";
909
910          if ($with_super) {
911               $strReq .=
912               'UNION '.
913               'SELECT U.user_id AS user_id, user_super, user_name, user_firstname, '.
914               "user_displayname, user_email, NULL AS permissions ".
915               'FROM '.$this->prefix.'user U '.
916               'WHERE user_super = 1 ';
917          }
918
919          $rs = $this->con->select($strReq);
920
921          $res = array();
922
923          while ($rs->fetch())
924          {
925               $res[$rs->user_id] = array(
926                    'name' => $rs->user_name,
927                    'firstname' => $rs->user_firstname,
928                    'displayname' => $rs->user_displayname,
929                    'email' => $rs->user_email,
930                    'super' => (boolean) $rs->user_super,
931                    'p' => $this->auth->parsePermissions($rs->permissions)
932               );
933          }
934
935          return $res;
936     }
937
938     /**
939     Returns a blog of given ID.
940
941     @param    id        <b>string</b>       Blog ID
942     @return   <b>record</b>
943     */
944     public function getBlog($id)
945     {
946          $blog = $this->getBlogs(array('blog_id'=>$id));
947
948          if ($blog->isEmpty()) {
949               return false;
950          }
951
952          return $blog;
953     }
954
955     /**
956     Returns a record of blogs. <b>$params</b> is an array with the following
957     optionnal parameters:
958
959      - <var>blog_id</var>: Blog ID
960      - <var>q</var>: Search string on blog_id, blog_name and blog_url
961      - <var>limit</var>: limit results
962
963     @param    params         <b>array</b>        Parameters
964     @param    count_only     <b>boolean</b>      Count only results
965     @return   <b>record</b>
966     */
967     public function getBlogs($params=array(),$count_only=false)
968     {
969          $join = '';    // %1$s
970          $where = '';   // %2$s
971
972          if ($count_only)
973          {
974               $strReq = 'SELECT count(B.blog_id) '.
975                         'FROM '.$this->prefix.'blog B '.
976                         '%1$s '.
977                         'WHERE NULL IS NULL '.
978                         '%2$s ';
979          }
980          else
981          {
982               $strReq =
983               'SELECT B.blog_id, blog_uid, blog_url, blog_name, blog_desc, blog_creadt, '.
984               'blog_upddt, blog_status '.
985               'FROM '.$this->prefix.'blog B '.
986               '%1$s '.
987               'WHERE NULL IS NULL '.
988               '%2$s ';
989
990               if (!empty($params['order'])) {
991                    $strReq .= 'ORDER BY '.$this->con->escape($params['order']).' ';
992               } else {
993                    $strReq .= 'ORDER BY B.blog_id ASC ';
994               }
995
996               if (!empty($params['limit'])) {
997                    $strReq .= $this->con->limit($params['limit']);
998               }
999          }
1000
1001          if ($this->auth->userID() && !$this->auth->isSuperAdmin())
1002          {
1003               $join = 'INNER JOIN '.$this->prefix.'permissions PE ON B.blog_id = PE.blog_id ';
1004               $where =
1005               "AND PE.user_id = '".$this->con->escape($this->auth->userID())."' ".
1006               "AND (permissions LIKE '%|usage|%' OR permissions LIKE '%|admin|%' OR permissions LIKE '%|contentadmin|%') ".
1007               "AND blog_status IN (1,0) ";
1008          } elseif (!$this->auth->userID()) {
1009               $where = 'AND blog_status IN (1,0) ';
1010          }
1011
1012          if (!empty($params['blog_id'])) {
1013               $where .= "AND B.blog_id = '".$this->con->escape($params['blog_id'])."' ";
1014          }
1015
1016          if (!empty($params['q'])) {
1017               $params['q'] = strtolower(str_replace('*','%',$params['q']));
1018               $where .=
1019               'AND ('.
1020               "LOWER(B.blog_id) LIKE '".$this->con->escape($params['q'])."' ".
1021               "OR LOWER(B.blog_name) LIKE '".$this->con->escape($params['q'])."' ".
1022               "OR LOWER(B.blog_url) LIKE '".$this->con->escape($params['q'])."' ".
1023               ') ';
1024          }
1025
1026          $strReq = sprintf($strReq,$join,$where);
1027          return $this->con->select($strReq);
1028     }
1029
1030     /**
1031     Creates a new blog.
1032
1033     @param    cur            <b>cursor</b>       Blog cursor
1034     */
1035     public function addBlog($cur)
1036     {
1037          if (!$this->auth->isSuperAdmin()) {
1038               throw new Exception(__('You are not an administrator'));
1039          }
1040
1041          $this->getBlogCursor($cur);
1042
1043          $cur->blog_creadt = date('Y-m-d H:i:s');
1044          $cur->blog_upddt = date('Y-m-d H:i:s');
1045          $cur->blog_uid = md5(uniqid());
1046
1047          $cur->insert();
1048     }
1049
1050     /**
1051     Updates a given blog.
1052
1053     @param    id        <b>string</b>       Blog ID
1054     @param    cur       <b>cursor</b>       Blog cursor
1055     */
1056     public function updBlog($id,$cur)
1057     {
1058          $this->getBlogCursor($cur);
1059
1060          $cur->blog_upddt = date('Y-m-d H:i:s');
1061
1062          $cur->update("WHERE blog_id = '".$this->con->escape($id)."'");
1063     }
1064
1065     private function getBlogCursor($cur)
1066     {
1067          if (($cur->blog_id !== null
1068               && !preg_match('/^[A-Za-z0-9._-]{2,}$/',$cur->blog_id)) ||
1069               (!$cur->blog_id)) {
1070               throw new Exception(__('Blog ID must contain at least 2 characters using letters, numbers or symbols.'));
1071          }
1072
1073          if (($cur->blog_name !== null && $cur->blog_name == '') ||
1074               (!$cur->blog_name)) {
1075               throw new Exception(__('No blog name'));
1076          }
1077
1078          if (($cur->blog_url !== null && $cur->blog_url == '') ||
1079               (!$cur->blog_url)) {
1080               throw new Exception(__('No blog URL'));
1081          }
1082
1083          if ($cur->blog_desc !== null) {
1084               $cur->blog_desc = html::clean($cur->blog_desc);
1085          }
1086     }
1087
1088     /**
1089     Removes a given blog.
1090     @warning This will remove everything related to the blog (posts,
1091     categories, comments, links...)
1092
1093     @param    id        <b>string</b>       Blog ID
1094     */
1095     public function delBlog($id)
1096     {
1097          if (!$this->auth->isSuperAdmin()) {
1098               throw new Exception(__('You are not an administrator'));
1099          }
1100
1101          $strReq = 'DELETE FROM '.$this->prefix.'blog '.
1102                    "WHERE blog_id = '".$this->con->escape($id)."' ";
1103
1104          $this->con->execute($strReq);
1105     }
1106
1107     /**
1108     Checks if a blog exist.
1109
1110     @param    id        <b>string</b>       Blog ID
1111     @return   <b>boolean</b>
1112     */
1113     public function blogExists($id)
1114     {
1115          $strReq = 'SELECT blog_id '.
1116                    'FROM '.$this->prefix.'blog '.
1117                    "WHERE blog_id = '".$this->con->escape($id)."' ";
1118
1119          $rs = $this->con->select($strReq);
1120
1121          return !$rs->isEmpty();
1122     }
1123
1124     /**
1125     Count posts on a blog
1126
1127     @param    id        <b>string</b>       Blog ID
1128     @param    type      <b>string</b>       Post type
1129     @return   <b>boolean</b>
1130     */
1131     public function countBlogPosts($id,$type=null)
1132     {
1133          $strReq = 'SELECT COUNT(post_id) '.
1134                    'FROM '.$this->prefix.'post '.
1135                    "WHERE blog_id = '".$this->con->escape($id)."' ";
1136
1137          if ($type) {
1138               $strReq .= "AND post_type = '".$this->con->escape($type)."' ";
1139          }
1140
1141          return $this->con->select($strReq)->f(0);
1142     }
1143     //@}
1144
1145     /// @name HTML Filter methods
1146     //@{
1147     /**
1148     Calls HTML filter to drop bad tags and produce valid XHTML output (if
1149     tidy extension is present). If <b>enable_html_filter</b> blog setting is
1150     false, returns not filtered string.
1151
1152     @param    str  <b>string</b>       String to filter
1153     @return   <b>string</b> Filtered string.
1154     */
1155     public function HTMLfilter($str)
1156     {
1157          if ($this->blog instanceof dcBlog && !$this->blog->settings->system->enable_html_filter) {
1158               return $str;
1159          }
1160
1161          $filter = new htmlFilter;
1162          $str = trim($filter->apply($str));
1163          return $str;
1164     }
1165     //@}
1166
1167     /// @name wiki2xhtml methods
1168     //@{
1169     private function initWiki()
1170     {
1171          $this->wiki2xhtml = new wiki2xhtml;
1172     }
1173
1174     /**
1175     Returns a transformed string with wiki2xhtml.
1176
1177     @param    str       <b>string</b>       String to transform
1178     @return   <b>string</b>  Transformed string
1179     */
1180     public function wikiTransform($str)
1181     {
1182          if (!($this->wiki2xhtml instanceof wiki2xhtml)) {
1183               $this->initWiki();
1184          }
1185          return $this->wiki2xhtml->transform($str);
1186     }
1187
1188     /**
1189     Inits <var>wiki2xhtml</var> property for blog post.
1190     */
1191     public function initWikiPost()
1192     {
1193          $this->initWiki();
1194
1195          $this->wiki2xhtml->setOpts(array(
1196               'active_title' => 1,
1197               'active_setext_title' => 0,
1198               'active_hr' => 1,
1199               'active_lists' => 1,
1200               'active_quote' => 1,
1201               'active_pre' => 1,
1202               'active_empty' => 1,
1203               'active_auto_br' => 0,
1204               'active_auto_urls' => 0,
1205               'active_urls' => 1,
1206               'active_auto_img' => 0,
1207               'active_img' => 1,
1208               'active_anchor' => 1,
1209               'active_em' => 1,
1210               'active_strong' => 1,
1211               'active_br' => 1,
1212               'active_q' => 1,
1213               'active_code' => 1,
1214               'active_acronym' => 1,
1215               'active_ins' => 1,
1216               'active_del' => 1,
1217               'active_footnotes' => 1,
1218               'active_wikiwords' => 0,
1219               'active_macros' => 1,
1220               'parse_pre' => 1,
1221               'active_fr_syntax' => 0,
1222               'first_title_level' => 3,
1223               'note_prefix' => 'wiki-footnote',
1224               'note_str' => '<div class="footnotes"><h4>Notes</h4>%s</div>'
1225          ));
1226
1227          $this->wiki2xhtml->registerFunction('url:post',array($this,'wikiPostLink'));
1228
1229          # --BEHAVIOR-- coreWikiPostInit
1230          $this->callBehavior('coreInitWikiPost',$this->wiki2xhtml);
1231     }
1232
1233     /**
1234     Inits <var>wiki2xhtml</var> property for simple blog comment (basic syntax).
1235     */
1236     public function initWikiSimpleComment()
1237     {
1238          $this->initWiki();
1239
1240          $this->wiki2xhtml->setOpts(array(
1241               'active_title' => 0,
1242               'active_setext_title' => 0,
1243               'active_hr' => 0,
1244               'active_lists' => 0,
1245               'active_quote' => 0,
1246               'active_pre' => 0,
1247               'active_empty' => 0,
1248               'active_auto_br' => 1,
1249               'active_auto_urls' => 1,
1250               'active_urls' => 0,
1251               'active_auto_img' => 0,
1252               'active_img' => 0,
1253               'active_anchor' => 0,
1254               'active_em' => 0,
1255               'active_strong' => 0,
1256               'active_br' => 0,
1257               'active_q' => 0,
1258               'active_code' => 0,
1259               'active_acronym' => 0,
1260               'active_ins' => 0,
1261               'active_del' => 0,
1262               'active_footnotes' => 0,
1263               'active_wikiwords' => 0,
1264               'active_macros' => 0,
1265               'parse_pre' => 0,
1266               'active_fr_syntax' => 0
1267          ));
1268
1269          # --BEHAVIOR-- coreInitWikiSimpleComment
1270          $this->callBehavior('coreInitWikiSimpleComment',$this->wiki2xhtml);
1271     }
1272
1273     /**
1274     Inits <var>wiki2xhtml</var> property for blog comment.
1275     */
1276     public function initWikiComment()
1277     {
1278          $this->initWiki();
1279
1280          $this->wiki2xhtml->setOpts(array(
1281               'active_title' => 0,
1282               'active_setext_title' => 0,
1283               'active_hr' => 0,
1284               'active_lists' => 1,
1285               'active_quote' => 0,
1286               'active_pre' => 1,
1287               'active_empty' => 0,
1288               'active_auto_br' => 1,
1289               'active_auto_urls' => 1,
1290               'active_urls' => 1,
1291               'active_auto_img' => 0,
1292               'active_img' => 0,
1293               'active_anchor' => 0,
1294               'active_em' => 1,
1295               'active_strong' => 1,
1296               'active_br' => 1,
1297               'active_q' => 1,
1298               'active_code' => 1,
1299               'active_acronym' => 1,
1300               'active_ins' => 1,
1301               'active_del' => 1,
1302               'active_footnotes' => 0,
1303               'active_wikiwords' => 0,
1304               'active_macros' => 0,
1305               'parse_pre' => 0,
1306               'active_fr_syntax' => 0
1307          ));
1308
1309          # --BEHAVIOR-- coreInitWikiComment
1310          $this->callBehavior('coreInitWikiComment',$this->wiki2xhtml);
1311     }
1312
1313     public function wikiPostLink($url,$content)
1314     {
1315          if (!($this->blog instanceof dcBlog)) {
1316               return array();
1317          }
1318
1319          $post_id = abs((integer) substr($url,5));
1320          if (!$post_id) {
1321               return array();
1322          }
1323
1324          $post = $this->blog->getPosts(array('post_id'=>$post_id));
1325          if ($post->isEmpty()) {
1326               return array();
1327          }
1328
1329          $res = array('url' => $post->getURL());
1330          $post_title = $post->post_title;
1331
1332          if ($content != $url) {
1333               $res['title'] = html::escapeHTML($post->post_title);
1334          }
1335
1336          if ($content == '' || $content == $url) {
1337               $res['content'] = html::escapeHTML($post->post_title);
1338          }
1339
1340          if ($post->post_lang) {
1341               $res['lang'] = $post->post_lang;
1342          }
1343
1344          return $res;
1345     }
1346     //@}
1347
1348     /// @name Maintenance methods
1349     //@{
1350     /**
1351     Creates default settings for active blog. Optionnal parameter
1352     <var>defaults</var> replaces default params while needed.
1353
1354     @param    defaults       <b>array</b>   Default parameters
1355     */
1356     public function blogDefaults($defaults=null)
1357     {
1358          if (!is_array($defaults))
1359          {
1360               $defaults = array(
1361                    array('allow_comments','boolean',true,
1362                    'Allow comments on blog'),
1363                    array('allow_trackbacks','boolean',true,
1364                    'Allow trackbacks on blog'),
1365                    array('blog_timezone','string','Europe/London',
1366                    'Blog timezone'),
1367                    array('comments_nofollow','boolean',true,
1368                    'Add rel="nofollow" to comments URLs'),
1369                    array('comments_pub','boolean',true,
1370                    'Publish comments immediately'),
1371                    array('comments_ttl','integer',0,
1372                    'Number of days to keep comments open (0 means no ttl)'),
1373                    array('copyright_notice','string','','Copyright notice (simple text)'),
1374                    array('date_format','string','%A, %B %e %Y',
1375                    'Date format. See PHP strftime function for patterns'),
1376                    array('editor','string','',
1377                    'Person responsible of the content'),
1378                    array('enable_html_filter','boolean',0,
1379                    'Enable HTML filter'),
1380                    array('enable_xmlrpc','boolean',0,
1381                    'Enable XML/RPC interface'),
1382                    array('lang','string','en',
1383                    'Default blog language'),
1384                    array('media_exclusion','string','/\.php[0-9]*$/i',
1385                    'File name exclusion pattern in media manager. (PCRE value)'),
1386                    array('media_img_m_size','integer',448,
1387                    'Image medium size in media manager'),
1388                    array('media_img_s_size','integer',240,
1389                    'Image small size in media manager'),
1390                    array('media_img_t_size','integer',100,
1391                    'Image thumbnail size in media manager'),
1392                    array('media_img_title_pattern','string','Title ;; Date(%b %Y) ;; separator(, )',
1393                    'Pattern to set image title when you insert it in a post'),
1394                    array('nb_post_for_home','integer',20,
1395                    'Number of entries on first home page'),
1396                    array('nb_post_per_page','integer',20,
1397                    'Number of entries on home pages and category pages'),
1398                    array('nb_post_per_feed','integer',20,
1399                    'Number of entries on feeds'),
1400                    array('nb_comment_per_feed','integer',20,
1401                    'Number of comments on feeds'),
1402                    array('post_url_format','string','{y}/{m}/{d}/{t}',
1403                    'Post URL format. {y}: year, {m}: month, {d}: day, {id}: post id, {t}: entry title'),
1404                    array('public_path','string','public',
1405                    'Path to public directory, begins with a / for a full system path'),
1406                    array('public_url','string','/public',
1407                    'URL to public directory'),
1408                    array('robots_policy','string','INDEX,FOLLOW',
1409                    'Search engines robots policy'),
1410                    array('short_feed_items','boolean',false,
1411                    'Display short feed items'),
1412                    array('theme','string','berlin',
1413                    'Blog theme'),
1414                    array('themes_path','string','themes',
1415                    'Themes root path'),
1416                    array('themes_url','string','/themes',
1417                    'Themes root URL'),
1418                    array('time_format','string','%H:%M',
1419                    'Time format. See PHP strftime function for patterns'),
1420                    array('tpl_allow_php','boolean',false,
1421                    'Allow PHP code in templates'),
1422                    array('tpl_use_cache','boolean',true,
1423                    'Use template caching'),
1424                    array('trackbacks_pub','boolean',true,
1425                    'Publish trackbacks immediately'),
1426                    array('trackbacks_ttl','integer',0,
1427                    'Number of days to keep trackbacks open (0 means no ttl)'),
1428                    array('url_scan','string','query_string',
1429                    'URL handle mode (path_info or query_string)'),
1430                    array('use_smilies','boolean',false,
1431                    'Show smilies on entries and comments'),
1432                    array('no_search','boolean',false,
1433                    'Disable search'),
1434                    array('inc_subcats','boolean',false,
1435                    'Include sub-categories in category page and category posts feed'),
1436                    array('wiki_comments','boolean',false,
1437                    'Allow commenters to use a subset of wiki syntax')
1438               );
1439          }
1440
1441          $settings = new dcSettings($this,null);
1442          $settings->addNamespace('system');
1443
1444          foreach ($defaults as $v) {
1445               $settings->system->put($v[0],$v[2],$v[1],$v[3],false,true);
1446          }
1447     }
1448
1449     /**
1450     Recreates entries search engine index.
1451
1452     @param    start     <b>integer</b>      Start entry index
1453     @param    limit     <b>integer</b>      Number of entry to index
1454
1455     @return   <b>integer</b>      <var>$start</var> and <var>$limit</var> sum
1456     */
1457     public function indexAllPosts($start=null,$limit=null)
1458     {
1459          $strReq = 'SELECT COUNT(post_id) '.
1460                    'FROM '.$this->prefix.'post';
1461          $rs = $this->con->select($strReq);
1462          $count = $rs->f(0);
1463
1464          $strReq = 'SELECT post_id, post_title, post_excerpt_xhtml, post_content_xhtml '.
1465                    'FROM '.$this->prefix.'post ';
1466
1467          if ($start !== null && $limit !== null) {
1468               $strReq .= $this->con->limit($start,$limit);
1469          }
1470
1471          $rs = $this->con->select($strReq,true);
1472
1473          $cur = $this->con->openCursor($this->prefix.'post');
1474
1475          while ($rs->fetch())
1476          {
1477               $words = $rs->post_title.' '. $rs->post_excerpt_xhtml.' '.
1478               $rs->post_content_xhtml;
1479
1480               $cur->post_words = implode(' ',text::splitWords($words));
1481               $cur->update('WHERE post_id = '.(integer) $rs->post_id);
1482               $cur->clean();
1483          }
1484
1485          if ($start+$limit > $count) {
1486               return null;
1487          }
1488          return $start+$limit;
1489     }
1490
1491     /**
1492     Recreates comments search engine index.
1493
1494     @param    start     <b>integer</b>      Start comment index
1495     @param    limit     <b>integer</b>      Number of comments to index
1496
1497     @return   <b>integer</b>      <var>$start</var> and <var>$limit</var> sum
1498     */
1499     public function indexAllComments($start=null,$limit=null)
1500     {
1501          $strReq = 'SELECT COUNT(comment_id) '.
1502                    'FROM '.$this->prefix.'comment';
1503          $rs = $this->con->select($strReq);
1504          $count = $rs->f(0);
1505
1506          $strReq = 'SELECT comment_id, comment_content '.
1507                    'FROM '.$this->prefix.'comment ';
1508
1509          if ($start !== null && $limit !== null) {
1510               $strReq .= $this->con->limit($start,$limit);
1511          }
1512
1513          $rs = $this->con->select($strReq);
1514
1515          $cur = $this->con->openCursor($this->prefix.'comment');
1516
1517          while ($rs->fetch())
1518          {
1519               $cur->comment_words = implode(' ',text::splitWords($rs->comment_content));
1520               $cur->update('WHERE comment_id = '.(integer) $rs->comment_id);
1521               $cur->clean();
1522          }
1523
1524          if ($start+$limit > $count) {
1525               return null;
1526          }
1527          return $start+$limit;
1528     }
1529
1530     /**
1531     Reinits nb_comment and nb_trackback in post table.
1532     */
1533     public function countAllComments()
1534     {
1535
1536          $updCommentReq = 'UPDATE '.$this->prefix.'post P '.
1537               'SET nb_comment = ('.
1538                    'SELECT COUNT(C.comment_id) from '.$this->prefix.'comment C '.
1539                    'WHERE C.post_id = P.post_id AND C.comment_trackback <> 1 '.
1540                    'AND C.comment_status = 1 '.
1541               ')';
1542          $updTrackbackReq = 'UPDATE '.$this->prefix.'post P '.
1543               'SET nb_trackback = ('.
1544                    'SELECT COUNT(C.comment_id) from '.$this->prefix.'comment C '.
1545                    'WHERE C.post_id = P.post_id AND C.comment_trackback = 1 '.
1546                    'AND C.comment_status = 1 '.
1547               ')';
1548          $this->con->execute($updCommentReq);
1549          $this->con->execute($updTrackbackReq);
1550     }
1551
1552     /**
1553     Empty templates cache directory
1554     */
1555     public function emptyTemplatesCache()
1556     {
1557          if (is_dir(DC_TPL_CACHE.'/cbtpl')) {
1558               files::deltree(DC_TPL_CACHE.'/cbtpl');
1559          }
1560     }
1561
1562     /**
1563      Return elapsed time since script has been started
1564      @param     $mtime <b>float</b> timestamp (microtime format) to evaluate delta from
1565                                          current time is taken if null
1566      @return <b>float</b>          elapsed time
1567      */
1568     public function getElapsedTime ($mtime=null) {
1569          if ($mtime !== null) {
1570               return $mtime-$this->stime;
1571          } else {
1572               return microtime(true)-$this->stime;
1573          }
1574     }
1575     //@}
1576
1577
1578
1579}
Note: See TracBrowser for help on using the repository browser.

Sites map