Dotclear

source: inc/core/class.dc.core.php @ 1092:f550e0726d86

Revision 1092:f550e0726d86, 36.8 KB checked in by JcDenis, 13 years ago (diff)

Added page tabs extension (with very simple exemple in aboutConfig)

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

Sites map