[ Index ]
 

Code source de Dotclear 2.0-beta6

Accédez au Source d'autres logiciels libresSoutenez Angelica Josefina !

title

Body

[fermer]

/inc/core/ -> class.dc.core.php (source)

   1  <?php
   2  # ***** BEGIN LICENSE BLOCK *****
   3  # This file is part of DotClear.
   4  # Copyright (c) 2005 Olivier Meunier and contributors. All rights
   5  # reserved.
   6  #
   7  # DotClear is free software; you can redistribute it and/or modify
   8  # it under the terms of the GNU General Public License as published by
   9  # the Free Software Foundation; either version 2 of the License, or
  10  # (at your option) any later version.
  11  # 
  12  # DotClear is distributed in the hope that it will be useful,
  13  # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  15  # GNU General Public License for more details.
  16  # 
  17  # You should have received a copy of the GNU General Public License
  18  # along with DotClear; if not, write to the Free Software
  19  # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  20  #
  21  # ***** END LICENSE BLOCK *****
  22  
  23  /**
  24  @defgroup DC_CORE Dotclear Core Classes
  25  */
  26  
  27  /**
  28  @ingroup DC_CORE
  29  @nosubgrouping
  30  @brief Dotclear core class
  31  
  32  True to its name dcCore is the core of Dotclear. It handles everything related
  33  to blogs, database connection, plugins...
  34  */
  35  class dcCore
  36  {
  37      public $con;        ///< <b>connection</b>        Database connection object
  38      public $prefix;    ///< <b>string</b>            Database tables prefix
  39      public $blog;        ///< <b>dcBlog</b>            dcBlog object
  40      public $error;        ///< <b>dcError</b>            dcError object
  41      public $auth;        ///< <b>dcAuth</b>            dcAuth object
  42      public $session;    ///< <b>sessionDB</b>        sessionDB object
  43      public $url;        ///< <b>urlHandler</b>        urlHandler object
  44      public $wiki2xhtml;    ///< <b>wiki2xhtml</b>        wiki2xhtml object
  45      public $plugins;    ///< <b>dcModules</b>        dcModules object
  46      public $media;        ///< <b>dcMedia</b>            dcMedia object
  47      public $rest;        ///< <b>dcRestServer</b>        dcRestServer object
  48      public $blogs;        ///< <b>array</b>            Available blogs list
  49      
  50      private $formaters = array();
  51      private $behaviors = array();
  52      
  53      /**
  54      dcCore constructor inits everything related to Dotclear. It takes arguments
  55      to init database connection.
  56      
  57      @param    driver    <b>string</b>    Database driver name
  58      @param    host        <b>string</b>    Database hostname
  59      @param    db        <b>string</b>    Database name
  60      @param    user        <b>string</b>    Database username
  61      @param    password    <b>string</b>    Database password
  62      @param    prefix    <b>string</b>    DotClear tables prefix
  63      */
  64  	public function __construct($driver, $host, $db, $user, $password, $prefix)
  65      {
  66          $this->con = dbLayer::init($driver,$host,$db,$user,$password);
  67          
  68          $this->prefix = $prefix;
  69          
  70          $this->error = new dcError();
  71          $this->auth = $this->authInstance();
  72          $this->session = new sessionDB($this->con,$this->prefix.'session',DC_SESSION_NAME);
  73          $this->url = new urlHandler();
  74          
  75          $this->plugins = new dcModules($this);
  76          
  77          $this->rest = new dcRestServer($this);
  78          
  79          $this->addFormater('xhtml', create_function('$s','return $s;'));
  80          $this->addFormater('wiki', array($this,'wikiTransform'));
  81      }
  82      
  83  	private function authInstance()
  84      {
  85          # You can set DC_AUTH_CLASS to whatever you want.
  86          # Your new class *should* inherits dcAuth.
  87          if (!defined('DC_AUTH_CLASS')) {
  88              $c = 'dcAuth';
  89          } else {
  90              $c = DC_AUTH_CLASS;
  91          }
  92          
  93          if (!class_exists($c)) {
  94              throw new Exception('Authentication class '.$c.' does not exists.');
  95          }
  96          
  97          if ($c != 'dcAuth')
  98          {
  99              $r = new ReflectionClass($c);
 100              $p = $r->getParentClass();
 101              
 102              if (!$p || $p->name != 'dcAuth') {
 103                  throw new Exception('Authentication class '.$c.' does not inherit dcAuth.');
 104              }
 105          }
 106          
 107          return new $c($this);
 108      }
 109      
 110      
 111      /// @name Blog init methods
 112      //@{
 113      /**
 114      Sets a blog to use in <var>blog</var> property.
 115      
 116      @param    id        <b>string</b>        Blog ID
 117      */
 118  	public function setBlog($id)
 119      {
 120          $this->blog = new dcBlog($this, $id);
 121      }
 122      
 123      /**
 124      Unsets <var>blog</var> property.
 125      */
 126  	public function unsetBlog()
 127      {
 128          $this->blog = null;
 129      }
 130      //@}
 131      
 132      
 133      /// @name Blog status methods
 134      //@{
 135      /**
 136      Returns an array of available blog status codes and names.
 137      
 138      @return    <b>array</b> Simple array with codes in keys and names in value
 139      */
 140  	public function getAllBlogStatus()
 141      {
 142          return array(
 143              1 => __('online'),
 144              0 => __('offline'),
 145              -1 => __('removed')
 146          );
 147      }
 148      
 149      /**
 150      Returns a blog status name given to a code. This is intended to be
 151      human-readable and will be translated, so never use it for tests.
 152      If status code does not exist, returns <i>offline</i>.
 153      
 154      @param    s    <b>integer</b> Status code
 155      @return    <b>string</b> Blog status name
 156      */
 157  	public function getBlogStatus($s)
 158      {
 159          $r = $this->getAllBlogStatus();
 160          if (isset($r[$s])) {
 161              return $r[$s];
 162          }
 163          return $r[0];
 164      }
 165      //@}
 166      
 167      
 168      /// @name Text Formatters methods
 169      //@{
 170      /**
 171      Adds a new text formater which will call the function <var>$func</var> to
 172      transform text. The function must be a valid callback and takes one
 173      argument: the string to transform. It returns the transformed string.
 174      
 175      @param    name        <b>string</b>        Formater name
 176      @param    func        <b>callback</b>    Function to use, must be a valid and callable callback
 177      */
 178  	public function addFormater($name,$func)
 179      {
 180          if (is_callable($func)) {
 181              $this->formaters[$name] = $func;
 182          }
 183      }
 184      
 185      /**
 186      Returns formaters list.
 187      
 188      @return    <b>array</b> An array of formaters names in values.
 189      */
 190  	public function getFormaters()
 191      {
 192          return array_keys($this->formaters);
 193      }
 194      
 195      /**
 196      If <var>$name</var> is a valid formater, it returns <var>$str</var>
 197      transformed using that formater.
 198      
 199      @param    name        <b>string</b>        Formater name
 200      @param    str        <b>string</b>        String to transform
 201      @return    <b>string</b>    String transformed
 202      */
 203  	public function callFormater($name,$str)
 204      {
 205          if (isset($this->formaters[$name])) {
 206              return call_user_func($this->formaters[$name],$str);
 207          }
 208          
 209          return $str;
 210      }
 211      //@}
 212      
 213      
 214      /// @name Behaviors methods
 215      //@{
 216      /**
 217      Adds a new behavior to behaviors stack. <var>$func</var> must be a valid
 218      and callable callback.
 219      
 220      @param    behavior    <b>string</b>        Behavior name
 221      @param    func        <b>callback</b>    Function to call
 222      */
 223  	public function addBehavior($behavior,$func)
 224      {
 225          if (is_callable($func)) {
 226              $this->behaviors[$behavior][] = $func;
 227          }
 228      }
 229  
 230      /**
 231      Tests if a particular behavior exists in behaviors stack.
 232  
 233      @param    behavior    <b>string</b>    Behavior name
 234      @return    <b>boolean</b>
 235      */
 236  	public function hasBehavior($behavior)
 237      {
 238          return isset($this->behaviors[$behavior]);
 239      }
 240  
 241      /**
 242      Get behaviors stack (or part of).
 243  
 244      @param    behavior    <b>string</b>        Behavior name
 245      @return    <b>array</b>
 246      */
 247  	public function getBehaviors($behavior='')
 248      {
 249          if (empty($this->behaviors)) return null;
 250  
 251          if ($behavior == '') {
 252              return $this->behaviors;
 253          } elseif (isset($this->behaviors[$behavior])) {
 254              return $this->behaviors[$behavior];
 255          }
 256          
 257          return array();
 258      }
 259      
 260      /**
 261      Calls every function in behaviors stack for a given behavior and returns
 262      concatened result of each function.
 263      
 264      Every parameters added after <var>$behavior</var> will be pass to
 265      behavior calls.
 266      
 267      @param    behavior    <b>string</b>    Behavior name
 268      @return    <b>string</b> Behavior concatened result
 269      */
 270  	public function callBehavior($behavior)
 271      {
 272          if (isset($this->behaviors[$behavior]))
 273          {
 274              $args = func_get_args();
 275              array_shift($args);
 276              
 277              $res = '';
 278              
 279              foreach ($this->behaviors[$behavior] as $f) {
 280                  $res .= call_user_func_array($f,$args);
 281              }
 282              
 283              return $res;
 284          }
 285      }
 286      //@}
 287      
 288      
 289      /// @name Users management methods
 290      //@{
 291      /**
 292      Returns a user by its ID.
 293      
 294      @param    id        <b>string</b>        User ID
 295      @return    <b>record</b>
 296      */
 297  	public function getUser($id)
 298      {
 299          $params['user_id'] = $id;
 300          
 301          return $this->getUsers($params);
 302      }
 303      
 304      /**
 305      Returns a users list. <b>$params</b> is an array with the following
 306      optionnal parameters:
 307      
 308       - <var>q</var>: search string (on user_id, user_name, user_firstname)
 309       - <var>user_id</var>: user ID
 310       - <var>order</var>: ORDER BY clause (default: user_id ASC)
 311       - <var>limit</var>: LIMIT clause (should be an array ![limit,offset])
 312      
 313      @param    params        <b>array</b>        Parameters
 314      @param    count_only    <b>boolean</b>        Only counts results
 315      @return    <b>record</b>
 316      */
 317  	public function getUsers($params=array(),$count_only=false)
 318      {
 319          if ($count_only)
 320          {
 321              $strReq =
 322              'SELECT count(U.user_id) '.
 323              'FROM '.$this->prefix.'user U '.
 324              'WHERE NULL IS NULL ';
 325          }
 326          else
 327          {
 328              $strReq =
 329              'SELECT U.user_id,user_super,user_status,user_pwd,user_name,'.
 330              'user_firstname,user_displayname,user_email,user_url,'.
 331              'user_desc, user_lang,user_tz, user_post_status,user_options, '.
 332              'count(P.post_id) AS nb_post '.
 333              'FROM '.$this->prefix.'user U '.
 334                  'LEFT JOIN '.$this->prefix.'post P ON U.user_id = P.user_id '.
 335              'WHERE NULL IS NULL ';
 336          }
 337          
 338          if (!empty($params['q'])) {
 339              $q = $this->con->escape(str_replace('*','%',strtolower($params['q'])));
 340              $strReq .= 'AND ('.
 341                  "LOWER(U.user_id) LIKE '".$q."' ".
 342                  "OR LOWER(user_name) LIKE '".$q."' ".
 343                  "OR LOWER(user_firstname) LIKE '".$q."' ".
 344                  ') ';
 345          }
 346          
 347          if (!empty($params['user_id'])) {
 348              $strReq .= "AND U.user_id = '".$this->con->escape($params['user_id'])."' ";
 349          }
 350          
 351          if (!$count_only) {
 352              $strReq .= 'GROUP BY U.user_id,user_super,user_status,user_pwd,user_name,'.
 353              'user_firstname,user_displayname,user_email,user_url,'.
 354              'user_desc, user_lang,user_tz,user_post_status,user_options ';
 355              
 356              if (!empty($params['order']) && !$count_only) {
 357                  $strReq .= 'ORDER BY '.$this->con->escape($params['order']).' ';
 358              } else {
 359                  $strReq .= 'ORDER BY U.user_id ASC ';
 360              }
 361          }
 362          
 363          if (!$count_only && !empty($params['limit'])) {
 364              $strReq .= $this->con->limit($params['limit']);
 365          }
 366          
 367          $rs = $this->con->select($strReq);
 368          $rs->extend('rsExtUser');
 369          return $rs;
 370      }
 371      
 372      /**
 373      Create a new user. Takes a cursor as input and returns the new user ID.
 374      
 375      @param    cur        <b>cursor</b>        User cursor
 376      @return    <b>string</b>
 377      */
 378  	public function addUser(&$cur)
 379      {
 380          if (!$this->auth->isSuperAdmin()) {
 381              throw new Exception(__('You are not an administrator'));
 382          }
 383          
 384          if ($cur->user_id == '') {
 385              throw new Exception(__('No user ID given'));
 386          }
 387          
 388          if ($cur->user_pwd == '') {
 389              throw new Exception(__('No password given'));
 390          }
 391          
 392          $this->getUserCursor($cur);
 393          
 394          if ($cur->user_creadt === null) {
 395              $cur->user_creadt = array('NOW()');
 396          }
 397          
 398          $cur->insert();
 399          
 400          $this->auth->afterAddUser($cur);
 401          
 402          return $cur->user_id;
 403      }
 404      
 405      /**
 406      Updates an existing user. Returns the user ID.
 407      
 408      @param    id        <b>string</b>        User ID
 409      @param    cur        <b>cursor</b>        User cursor
 410      @return    <b>string</b>
 411      */
 412  	public function updUser($id,&$cur)
 413      {
 414          $this->getUserCursor($cur);
 415          
 416          if (($cur->user_id !== null || $id != $this->auth->userID()) &&
 417          !$this->auth->isSuperAdmin()) {
 418              throw new Exception(__('You are not an administrator'));
 419          }
 420          
 421          $cur->update("WHERE user_id = '".$this->con->escape($id)."' ");
 422          
 423          $this->auth->afterUpdUser($id,$cur);
 424          
 425          if ($cur->user_id !== null) {
 426              return $cur->user_id;
 427          }
 428          
 429          return $id;
 430      }
 431      
 432      /**
 433      Deletes a user.
 434      
 435      @param    id        <b>string</b>        User ID
 436      */
 437  	public function delUser($id)
 438      {
 439          if (!$this->auth->isSuperAdmin()) {
 440              throw new Exception(__('You are not an administrator'));
 441          }
 442          
 443          $rs = $this->getUser($id);
 444          
 445          if ($rs->nb_post == 0)
 446          {
 447              $strReq = 'DELETE FROM '.$this->prefix.'user '.
 448                      "WHERE user_id = '".$this->con->escape($id)."' ";
 449              
 450              $this->con->execute($strReq);
 451          }
 452          
 453          $this->auth->afterDelUser($id);
 454      }
 455      
 456      /**
 457      Checks whether a user exists.
 458      
 459      @param    id        <b>string</b>        User ID
 460      @return    <b>boolean</b>
 461      */
 462  	public function userExists($id)
 463      {
 464          $strReq = 'SELECT user_id '.
 465                  'FROM '.$this->prefix.'user '.
 466                  "WHERE user_id = '".$this->con->escape($id)."' ";
 467          
 468          $rs = $this->con->select($strReq);
 469          
 470          return !$rs->isEmpty();
 471      }
 472      
 473      /**
 474      Returns all user permissions as an array which looks like:
 475      
 476       - [blog_id]
 477         - [name] => Blog name
 478         - [url] => Blog URL
 479         - [p]
 480             - [permission] => true
 481          - ...
 482      
 483      @param    id        <b>string</b>        User ID
 484      @return    <b>array</b>
 485      */
 486  	public function getUserPermissions($id)
 487      {
 488          $strReq = 'SELECT B.blog_id, blog_name, blog_url, permissions '.
 489                  'FROM '.$this->prefix.'permissions P '.
 490                  'INNER JOIN '.$this->prefix.'blog B ON P.blog_id = B.blog_id '.
 491                  "WHERE user_id = '".$this->con->escape($id)."' ";
 492          
 493          $rs = $this->con->select($strReq);
 494          
 495          $res = array();
 496          
 497          while ($rs->fetch())
 498          {
 499              $res[$rs->blog_id] = array(
 500                  'name' => $rs->blog_name,
 501                  'url' => $rs->blog_url,
 502                  'p' => $this->auth->parsePermissions($rs->permissions)
 503              );
 504          }
 505          
 506          return $res;
 507      }
 508      
 509      /**
 510      Sets user permissions. The <var>$perms</var> array looks like:
 511      
 512       - [blog_id] => '|perm1|perm2|'
 513       - ...
 514      
 515      @param    id        <b>string</b>        User ID
 516      @param    perms    <b>array</b>        Permissions array
 517      */
 518  	public function setUserPermissions($id,$perms)
 519      {
 520          if (!$this->auth->isSuperAdmin()) {
 521              throw new Exception(__('You are not an administrator'));
 522          }
 523          
 524          $strReq = 'DELETE FROM '.$this->prefix.'permissions '.
 525                  "WHERE user_id = '".$this->con->escape($id)."' ";
 526          
 527          $this->con->execute($strReq);
 528          
 529          foreach ($perms as $blog_id => $p) {
 530              $this->setUserBlogPermissions($id, $blog_id, $p, false);
 531          }
 532      }
 533      
 534      /**
 535      Sets user permissions for a given blog. <var>$perms</var> is an array with
 536      permissions in values
 537      
 538      @param    id            <b>string</b>        User ID
 539      @param    blog_id        <b>string</b>        Blog ID
 540      @param    perms        <b>array</b>        Permissions
 541      @param    delete_first    <b>boolean</b>        Delete permissions before
 542      */
 543  	public function setUserBlogPermissions($id, $blog_id, $perms, $delete_first=true)
 544      {
 545          if (!$this->auth->isSuperAdmin()) {
 546              throw new Exception(__('You are not an administrator'));
 547          }
 548          
 549          $no_perm = empty($perms);
 550          
 551          $perms = '|'.implode('|',array_keys($perms)).'|';
 552          
 553          $cur = $this->con->openCursor($this->prefix.'permissions');
 554          
 555          $cur->user_id = (string) $id;
 556          $cur->blog_id = (string) $blog_id;
 557          $cur->permissions = $perms;
 558          
 559          if ($delete_first || $no_perm)
 560          {
 561              $strReq = 'DELETE FROM '.$this->prefix.'permissions '.
 562                      "WHERE blog_id = '".$this->con->escape($blog_id)."' ".
 563                      "AND user_id = '".$this->con->escape($id)."' ";
 564              
 565              $this->con->execute($strReq);
 566          }
 567          
 568          if (!$no_perm) {
 569              $cur->insert();
 570          }
 571      }
 572      
 573      /**
 574      Sets a user default blog. This blog will be selected when user log in.
 575      
 576      @param    id            <b>string</b>        User ID
 577      @param    blog_id        <b>string</b>        Blog ID
 578      */
 579  	public function setUserDefaultBlog($id, $blog_id)
 580      {
 581          $cur = $this->con->openCursor($this->prefix.'user');
 582          
 583          $cur->user_default_blog = (string) $blog_id;
 584          
 585          $cur->update("WHERE user_id = '".$this->con->escape($id)."'");
 586      }
 587      
 588  	private function getUserCursor(&$cur)
 589      {
 590          if ($cur->isField('user_id')
 591          && !preg_match('/^[A-Za-z0-9._-]{2,}$/',$cur->user_id)) {
 592              throw new Exception(__('User ID must contain at least 2 characters using letters, numbers or symbols.'));
 593          }
 594          
 595          if ($cur->user_url !== null && $cur->user_url != '') {
 596              if (!preg_match('|^http(s?)://|',$cur->user_url)) {
 597                  $cur->user_url = 'http://'.$cur->user_url;
 598              }
 599          }
 600          
 601          if ($cur->isField('user_pwd')) {
 602              if (strlen($cur->user_pwd) < 6) {
 603                  throw new Exception(__('Password must contain at least 6 characters.'));
 604              }
 605              $cur->user_pwd = crypt::hmac(DC_MASTER_KEY,$cur->user_pwd);
 606          }
 607          
 608          if ($cur->user_upddt === null) {
 609              $cur->user_upddt = array('NOW()');
 610          }
 611          
 612          if ($cur->user_options !== null) {
 613              $cur->user_options = serialize((array) $cur->user_options);
 614          }
 615      }
 616      
 617      /**
 618      Returns user default settings in an associative array with setting names in
 619      keys.
 620      
 621      @return    <b>array</b>
 622      */
 623  	public function userDefaults()
 624      {
 625          return array(
 626              'edit_size' => 24,
 627              'enable_wysiwyg' => true,
 628              'post_format' => 'wiki',
 629          );
 630      }
 631      
 632      /**
 633      Sets blogs user can access in <var>blogs</var> property.
 634      */
 635  	public function getUserBlogs()
 636      {
 637          $blogs = $this->auth->getPermissions();
 638          
 639          foreach ($blogs as $b => $p) {
 640              if (!$this->auth->check('usage,admin,contentadmin',$b)) {
 641                  unset($blogs[$b]);
 642              }
 643          }
 644          
 645          $this->blogs = $blogs;
 646      }
 647      //@}
 648      
 649      /// @name Blog management methods
 650      //@{
 651      /**
 652      Returns all blog permissions (users) as an array which looks like:
 653      
 654       - [user_id]
 655         - [name] => User name
 656         - [firstname] => User firstname
 657         - [displayname] => User displayname
 658         - [super] => (true|false) super admin
 659         - [p]
 660             - [permission] => true
 661          - ...
 662      
 663      @param    id            <b>string</b>        Blog ID
 664      @param    with_super    <b>boolean</b>        Includes super admins in result
 665      @return    <b>array</b>
 666      */
 667  	public function getBlogPermissions($id,$with_super=true)
 668      {
 669          $strReq =
 670          'SELECT U.user_id AS user_id, user_super, user_name, user_firstname, '.
 671          'user_displayname, permissions '.
 672          'FROM '.$this->prefix.'user U '.
 673          'JOIN '.$this->prefix.'permissions P ON U.user_id = P.user_id '.
 674          "WHERE blog_id = '".$this->con->escape($id)."' ";
 675          
 676          if ($with_super) {
 677              $strReq .=
 678              'UNION '.
 679              'SELECT U.user_id AS user_id, user_super, user_name, user_firstname, '.
 680              "user_displayname, NULL AS permissions ".
 681              'FROM '.$this->prefix.'user U '.
 682              'WHERE user_super = 1 ';
 683          }
 684          
 685          $rs = $this->con->select($strReq);
 686          
 687          $res = array();
 688          
 689          while ($rs->fetch())
 690          {
 691              $res[$rs->user_id] = array(
 692                  'name' => $rs->user_name,
 693                  'firstname' => $rs->user_firstname,
 694                  'displayname' => $rs->user_displayname,
 695                  'super' => (boolean) $rs->user_super,
 696                  'p' => $this->auth->parsePermissions($rs->permissions)
 697              );
 698          }
 699          
 700          return $res;
 701      }
 702      
 703      /**
 704      Returns a blog of given ID.
 705      
 706      @param    id        <b>string</b>        Blog ID
 707      @return    <b>record</b>
 708      */
 709  	public function getBlog($id)
 710      {
 711          $blog = $this->getBlogs(array('blog_id'=>$id));
 712          
 713          if ($blog->isEmpty()) {
 714              return false;
 715          }
 716          
 717          return $blog;
 718      }
 719      
 720      /**
 721      Returns a record of blogs. <b>$params</b> is an array with the following
 722      optionnal parameters:
 723      
 724       - <var>blog_id</var>: Blog ID
 725       - <var>q</var>: Search string on blog_id, blog_name and blog_url
 726       - <var>limit</var>: limit results
 727      
 728      @param    params        <b>array</b>        Parameters
 729      @param    count_only    <b>boolean</b>        Count only results
 730      @return    <b>record</b>
 731      */
 732  	public function getBlogs($params=array(),$count_only=false)
 733      {
 734          if ($count_only)
 735          {
 736              $strReq = 'SELECT count(B.blog_id) '.
 737                      'FROM '.$this->prefix.'blog B '.
 738                      'WHERE NULL IS NULL ';
 739          }
 740          else
 741          {
 742              $strReq =
 743              'SELECT B.blog_id, blog_uid, blog_url, blog_name, blog_desc, blog_creadt, '.
 744              'blog_upddt, blog_status, COUNT(post_id) AS nb_post '.
 745              'FROM '.$this->prefix.'blog B '.
 746                  'LEFT JOIN '.$this->prefix.'post P ON B.blog_id = P.blog_id '.
 747              'WHERE NULL IS NULL ';
 748          }
 749          
 750          if (!empty($params['blog_id'])) {
 751              $strReq .= "AND B.blog_id = '".$this->con->escape($params['blog_id'])."' ";
 752          }
 753          
 754          # If logged in and not super admin, get only user's blogs with status 1 or 0
 755          if ($this->auth->userID() && !$this->auth->isSuperAdmin()) {
 756              $inReq = array();
 757              foreach (array_keys($this->blogs) as $v) {
 758                  $inReq[] = $this->con->escape($v);
 759              }
 760              $strReq .=
 761              "AND B.blog_id IN ('".implode("','",$inReq)."') ".
 762              "AND blog_status IN (1,0) ";
 763          } elseif (!$this->auth->userID()) {
 764              $strReq .= 'AND blog_status = 1 ';
 765          }
 766          
 767          if (!empty($params['q'])) {
 768              $params['q'] = str_replace('*','%',$params['q']);
 769              $strReq .=
 770              'AND ('.
 771              "LOWER(B.blog_id) LIKE '".$this->con->escape($params['q'])."' ".
 772              "OR LOWER(B.blog_name) LIKE '".$this->con->escape($params['q'])."'".
 773              "OR LOWER(B.blog_url) LIKE '".$this->con->escape($params['q'])."' ".
 774              ') ';
 775          }
 776          
 777          if (!$count_only) {
 778              $strReq .= 'GROUP BY B.blog_id, blog_uid, blog_url, blog_name, '.
 779              'blog_desc, blog_creadt, blog_upddt, blog_status ';
 780              
 781              if (!empty($params['order'])) {
 782                  $strReq .= 'ORDER BY '.$this->con->escape($params['order']).' ';
 783              } else {
 784                  $strReq .= 'ORDER BY B.blog_id ASC ';
 785              }
 786          }
 787          
 788          if (!$count_only && !empty($params['limit'])) {
 789              $strReq .= $this->con->limit($params['limit']);
 790          }
 791          
 792          return $this->con->select($strReq);
 793      }
 794      
 795      /**
 796      Creates a new blog.
 797      
 798      @param    cur            <b>cursor</b>        Blog cursor
 799      */
 800  	public function addBlog($cur)
 801      {
 802          if (!$this->auth->isSuperAdmin()) {
 803              throw new Exception(__('You are not an administrator'));
 804          }
 805          
 806          $this->getBlogCursor($cur);
 807          
 808          $cur->blog_creadt = date('Y-m-d H:i:s');
 809          $cur->blog_upddt = date('Y-m-d H:i:s');
 810          $cur->blog_uid = md5(uniqid());
 811          
 812          $cur->insert();
 813      }
 814      
 815      /**
 816      Updates a given blog.
 817      
 818      @param    id        <b>string</b>        Blog ID
 819      @param    cur        <b>cursor</b>        Blog cursor
 820      */
 821  	public function updBlog($id,$cur)
 822      {
 823          $this->getBlogCursor($cur);
 824          
 825          $cur->blog_upddt = date('Y-m-d H:i:s');
 826          
 827          $cur->update("WHERE blog_id = '".$this->con->escape($id)."'");
 828      }
 829      
 830  	private function getBlogCursor(&$cur)
 831      {
 832          if ($cur->blog_id !== null
 833          && !preg_match('/^[A-Za-z0-9._-]{2,}$/',$cur->blog_id)) {
 834              throw new Exception(__('Blog ID must contain at least 2 characters using letters, numbers or symbols.')); 
 835          }
 836          
 837          if ($cur->blog_name !== null && $cur->blog_name == '') {
 838              throw new Exception(__('No blog name'));
 839          }
 840          
 841          if ($cur->blog_url !== null && $cur->blog_url == '') {
 842              throw new Exception(__('No blog URL'));
 843          }
 844          
 845          if ($cur->blog_desc !== null) {
 846              $cur->blog_desc = html::clean($cur->blog_desc);
 847          }
 848      }
 849      
 850      /**
 851      Removes a given blog.
 852      @warning This will remove everything related to the blog (posts,
 853      categories, comments, links...)
 854      
 855      @param    id        <b>string</b>        Blog ID
 856      */
 857  	public function delBlog($id)
 858      {
 859          if (!$this->auth->isSuperAdmin()) {
 860              throw new Exception(__('You are not an administrator'));
 861          }
 862          
 863          $strReq = 'DELETE FROM '.$this->prefix.'blog '.
 864                  "WHERE blog_id = '".$this->con->escape($id)."' ";
 865          
 866          $this->con->execute($strReq);
 867      }
 868      
 869      /**
 870      Checks if a blog exist.
 871      
 872      @param    id        <b>string</b>        Blog ID
 873      @return    <b>boolean</b>
 874      */
 875  	public function blogExists($id)
 876      {
 877          $strReq = 'SELECT blog_id '.
 878                  'FROM '.$this->prefix.'blog '.
 879                  "WHERE blog_id = '".$this->con->escape($id)."' ";
 880          
 881          $rs = $this->con->select($strReq);
 882          
 883          return !$rs->isEmpty();
 884      }
 885      //@}
 886      
 887      /// @name HTML Filter methods
 888      //@{
 889      /**
 890      Calls HTML filter to drop bad tags and produce valid XHTML output (if
 891      tidy extension is present). If <b>enable_html_filter</b> blog setting is
 892      false, returns not filtered string.
 893      
 894      @param    str    <b>string</b>        String to filter
 895      @return    <b>string</b> Filtered string.
 896      */
 897  	public function HTMLfilter($str)
 898      {
 899          if ($this->blog instanceof dcBlog && !$this->blog->settings->enable_html_filter) {
 900              return $str;
 901          }
 902          
 903          $filter = new htmlFilter;
 904          $str = trim($filter->apply($str));
 905          return $str;
 906      }
 907      //@}
 908      
 909      /// @name wiki2xhtml methods
 910      //@{
 911  	private function initWiki()
 912      {
 913          $this->wiki2xhtml = new wiki2xhtml;
 914      }
 915      
 916      /**
 917      Returns a transformed string with wiki2xhtml.
 918      
 919      @param    str        <b>string</b>        String to transform
 920      @return    <b>string</b>    Transformed string
 921      */
 922  	public function wikiTransform($str)
 923      {
 924          if (!($this->wiki2xhtml instanceof wiki2xhtml)) {
 925              $this->initWiki();
 926          }
 927          return $this->wiki2xhtml->transform($str);
 928      }
 929      
 930      /**
 931      Inits <var>wiki2xhtml</var> property for blog post.
 932      */
 933  	public function initWikiPost()
 934      {
 935          $this->initWiki();
 936          
 937          $this->wiki2xhtml->setOpts(array(
 938              'active_title' => 1,
 939              'active_setext_title' => 0,
 940              'active_hr' => 1,
 941              'active_lists' => 1,
 942              'active_quote' => 1,
 943              'active_pre' => 1,
 944              'active_empty' => 1,
 945              'active_auto_br' => 0,
 946              'active_auto_urls' => 0,
 947              'active_urls' => 1,
 948              'active_auto_img' => 0,
 949              'active_img' => 1,
 950              'active_anchor' => 1,
 951              'active_em' => 1,
 952              'active_strong' => 1,
 953              'active_br' => 1,
 954              'active_q' => 1,
 955              'active_code' => 1,
 956              'active_acronym' => 1,
 957              'active_ins' => 1,
 958              'active_del' => 1,
 959              'active_footnotes' => 1,
 960              'active_wikiwords' => 0,
 961              'active_macros' => 1,
 962              'parse_pre' => 1,
 963              'active_fr_syntax' => 0,
 964              'first_title_level' => 3,
 965              'note_prefix' => 'wiki-footnote',
 966              'note_str' => '<div class="footnotes"><h4>Notes</h4>%s</div>'
 967          ));
 968          
 969          # --BEHAVIOR-- coreWikiPostInit
 970          $this->callBehavior('coreInitWikiPost',$this->wiki2xhtml);
 971      }
 972      
 973      /**
 974      Inits <var>wiki2xhtml</var> property for simple blog comment (basic syntax).
 975      */
 976  	public function initWikiSimpleComment()
 977      {
 978          $this->initWiki();
 979          
 980          $this->wiki2xhtml->setOpts(array(
 981              'active_title' => 0,
 982              'active_setext_title' => 0,
 983              'active_hr' => 0,
 984              'active_lists' => 0,
 985              'active_quote' => 0,
 986              'active_pre' => 0,
 987              'active_empty' => 0,
 988              'active_auto_br' => 1,
 989              'active_auto_urls' => 1,
 990              'active_urls' => 0,
 991              'active_auto_img' => 0,
 992              'active_img' => 0,
 993              'active_anchor' => 0,
 994              'active_em' => 0,
 995              'active_strong' => 0,
 996              'active_br' => 0,
 997              'active_q' => 0,
 998              'active_code' => 0,
 999              'active_acronym' => 0,
1000              'active_ins' => 0,
1001              'active_del' => 0,
1002              'active_footnotes' => 0,
1003              'active_wikiwords' => 0,
1004              'active_macros' => 0,
1005              'parse_pre' => 0,
1006              'active_fr_syntax' => 0
1007          ));
1008          
1009          # --BEHAVIOR-- coreInitWikiSimpleComment
1010          $this->callBehavior('coreInitWikiSimpleComment',$this->wiki2xhtml);
1011      }
1012      
1013      /**
1014      Inits <var>wiki2xhtml</var> property for blog comment.
1015      */
1016  	public function initWikiComment()
1017      {
1018          $this->initWiki();
1019          
1020          $this->wiki2xhtml->setOpts(array(
1021              'active_title' => 0,
1022              'active_setext_title' => 0,
1023              'active_hr' => 0,
1024              'active_lists' => 1,
1025              'active_quote' => 0,
1026              'active_pre' => 1,
1027              'active_empty' => 0,
1028              'active_auto_br' => 1,
1029              'active_auto_urls' => 1,
1030              'active_urls' => 1,
1031              'active_auto_img' => 0,
1032              'active_img' => 0,
1033              'active_anchor' => 0,
1034              'active_em' => 1,
1035              'active_strong' => 1,
1036              'active_br' => 1,
1037              'active_q' => 1,
1038              'active_code' => 1,
1039              'active_acronym' => 1,
1040              'active_ins' => 1,
1041              'active_del' => 1,
1042              'active_footnotes' => 0,
1043              'active_wikiwords' => 0,
1044              'active_macros' => 0,
1045              'parse_pre' => 0,
1046              'active_fr_syntax' => 0
1047          ));
1048          
1049          # --BEHAVIOR-- coreInitWikiComment
1050          $this->callBehavior('coreInitWikiComment',$this->wiki2xhtml);
1051      }
1052      //@}
1053      
1054      /// @name Maintenance methods
1055      //@{
1056      /**
1057      Creates default settings for active blog. Optionnal parameter
1058      <var>defaults</var> replaces default params while needed.
1059      
1060      @param    defaults        <b>array</b>    Default parameters
1061      */
1062  	public function blogDefaults($defaults=null)
1063      {
1064          if (!is_array($defaults))
1065          {
1066              $defaults = array(
1067                  array('allow_comments','boolean',true,
1068                  'Allow comments on blog'),
1069                  array('allow_trackbacks','boolean',true,
1070                  'Allow trackbacks on blog'),
1071                  array('blog_timezone','string','Europe/London',
1072                  'Blog timezone'),
1073                  array('comments_nofollow','boolean',true,
1074                  'Add rel="nofollow" to comments URLs'),
1075                  array('comments_pub','boolean',true,
1076                  'Publish comments immediatly'),
1077                  array('comments_ttl','integer',0,
1078                  'Number of days to keep comments and trackbacks open (0 means no ttl)'),
1079                  array('copyright_notice','string','','Copyright notice (simple text)'),
1080                  array('date_format','string','%A, %B %e %Y',
1081                  'Date format. See PHP strftime function for patterns'),
1082                  array('editor','string','',
1083                  'Person responsible of the content'),
1084                  array('enable_html_filter','boolean',0,
1085                  'Enable HTML filter'),
1086                  array('enable_xmlrpc','boolean',0,
1087                  'Enable XML/RPC interface'),
1088                  array('lang','string','en',
1089                  'Default blog language'),
1090                  array('nb_post_per_page','integer',20,
1091                  'Number of entries on home page and category pages'),
1092                  array('post_url_format','string','{y}/{m}/{d}/{t}',
1093                  'Post URL format. {y}: year, {m}: month, {d}: day, {id}: post id, {t}: entry title'),
1094                  array('public_path','string','public',
1095                  'Path to public directory, begins with a / for a full system path'),
1096                  array('public_url','string','/public',
1097                  'URL to public directory'),
1098                  array('theme','string','default',
1099                  'Blog theme'),
1100                  array('themes_path','string','themes',
1101                  'Themes root path'),
1102                  array('themes_url','string','/themes',
1103                  'Themes root URL'),
1104                  array('time_format','string','%H:%M',
1105                  'Time format. See PHP strftime function for patterns'),
1106                  array('tpl_allow_php','boolean',false,
1107                  'Allow PHP code in templates'),
1108                  array('tpl_use_cache','boolean',true,
1109                  'Use template caching'),
1110                  array('url_scan','string','query_string',
1111                  'URL handle mode (path_info or query_string)'),
1112                  array('use_smilies','boolean',false,
1113                  'Show smilies on entries and comments'),
1114                  array('wiki_comments','boolean',false,
1115                  'Allow commenters to use a subset of wiki syntax')
1116              );
1117          }
1118          
1119          $settings = new dcSettings($this,null);
1120          $settings->setNameSpace('system');
1121          
1122          foreach ($defaults as $v) {
1123              $settings->put($v[0],$v[2],$v[1],$v[3],false,true);
1124          }
1125      }
1126      
1127      /**
1128      Recreates entries search engine index.
1129      
1130      @param    start    <b>integer</b>        Start entry index
1131      @param    limit    <b>integer</b>        Number of entry to index
1132      
1133      @return    <b>integer</b>        <var>$start</var> and <var>$limit</var> sum
1134      */
1135  	public function indexAllPosts($start=null,$limit=null)
1136      {
1137          $strReq = 'SELECT COUNT(post_id) '.
1138                  'FROM '.$this->prefix.'post';
1139          $rs = $this->con->select($strReq);
1140          $count = $rs->f(0);
1141          
1142          $strReq = 'SELECT post_id, post_title, post_excerpt_xhtml, post_content_xhtml '.
1143                  'FROM '.$this->prefix.'post ';
1144          
1145          if ($start !== null && $limit !== null) {
1146              $strReq .= $this->con->limit($start,$limit);
1147          }
1148          
1149          $rs = $this->con->select($strReq,true);
1150          
1151          $cur = $this->con->openCursor($this->prefix.'post');
1152          
1153          while ($rs->fetch())
1154          {
1155              $words = $rs->post_title.' '.    $rs->post_excerpt_xhtml.' '.
1156              $rs->post_content_xhtml;
1157              
1158              $cur->post_words = implode(' ',text::splitWords($words));
1159              $cur->update('WHERE post_id = '.(integer) $rs->post_id);
1160              $cur->clean();
1161          }
1162          
1163          if ($start+$limit > $count) {
1164              return null;
1165          }
1166          return $start+$limit;
1167      }
1168      
1169      /**
1170      Recreates comments search engine index.
1171      
1172      @param    start    <b>integer</b>        Start comment index
1173      @param    limit    <b>integer</b>        Number of comments to index
1174      
1175      @return    <b>integer</b>        <var>$start</var> and <var>$limit</var> sum
1176      */
1177  	public function indexAllComments($start=null,$limit=null)
1178      {
1179          $strReq = 'SELECT COUNT(comment_id) '.
1180                  'FROM '.$this->prefix.'comment';
1181          $rs = $this->con->select($strReq);
1182          $count = $rs->f(0);
1183          
1184          $strReq = 'SELECT comment_id, comment_content '.
1185                  'FROM '.$this->prefix.'comment ';
1186          
1187          if ($start !== null && $limit !== null) {
1188              $strReq .= $this->con->limit($start,$limit);
1189          }
1190          
1191          $rs = $this->con->select($strReq);
1192          
1193          $cur = $this->con->openCursor($this->prefix.'comment');
1194          
1195          while ($rs->fetch())
1196          {
1197              $cur->comment_words = implode(' ',text::splitWords($rs->comment_content));
1198              $cur->update('WHERE comment_id = '.(integer) $rs->comment_id);
1199              $cur->clean();
1200          }
1201          
1202          if ($start+$limit > $count) {
1203              return null;
1204          }
1205          return $start+$limit;
1206      }
1207      
1208      /**
1209      Reinits nb_comment and nb_trackback in post table.
1210      */
1211  	public function countAllComments()
1212      {
1213          $strReq = 'SELECT COUNT(comment_id) AS nb, post_id '.
1214                  'FROM '.$this->prefix.'comment '.
1215                  'WHERE comment_trackback %s 1 '.
1216                  'AND comment_status = 1 '.
1217                  'GROUP BY post_id ';
1218          
1219          $rsC = $this->con->select(sprintf($strReq,'<>'));
1220          $rsT = $this->con->select(sprintf($strReq,'='));
1221          
1222          $cur = $this->con->openCursor($this->prefix.'post');
1223          while ($rsC->fetch()) {
1224              $cur->nb_comment = (integer) $rsC->nb;
1225              $cur->update('WHERE post_id = '.(integer) $rsC->post_id);
1226              $cur->clean();
1227          }
1228          
1229          while ($rsT->fetch()) {
1230              $cur->nb_trackback = (integer) $rsT->nb;
1231              $cur->update('WHERE post_id = '.(integer) $rsT->post_id);
1232              $cur->clean();
1233          }
1234      }
1235      //@}
1236  }
1237  ?>


Généré le : Fri Feb 23 22:16:06 2007 par Balluche grâce à PHPXref 0.7