Dotclear

source: inc/core/class.dc.core.php @ 1179:a43a29427ef3

Revision 1179:a43a29427ef3, 35.6 KB checked in by franck <carnet.franck.paul@…>, 11 years ago (diff)

Update copyright notice

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

Sites map