[ Index ]

Source Code Reference for V1.00

title

Body

[close]

/classes/ -> w2p.class.php (source)

   1  <?php /* $Id: w2p.class.php 135 2008-04-04 13:49:13Z pedroix $ $URL: https://web2project.svn.sourceforge.net/svnroot/web2project/trunk/classes/w2p.class.php $ */
   2  
   3  /**
   4   *    @package web2project
   5   *    @subpackage modules
   6   *    @version $Revision: 135 $
   7   */
   8  
   9  if (!defined('W2P_BASE_DIR')) {
  10      die('You should not access this file directly.');
  11  }
  12  
  13  require_once $AppUI->getSystemClass('query');
  14  
  15  /**
  16   *    CW2pObject Abstract Class.
  17   *
  18   *    Parent class to all database table derived objects
  19   *    @author Andrew Eddie <eddieajau@users.sourceforge.net>
  20   *    @abstract
  21   */
  22  class CW2pObject {
  23      /**
  24       *    @var string Name of the table prefix in the db schema
  25       */
  26      var $_tbl_prefix = '';
  27      /**
  28       *    @var string Name of the table in the db schema relating to child class
  29       */
  30      var $_tbl = '';
  31      /**
  32       *    @var string Name of the primary key field in the table
  33       */
  34      var $_tbl_key = '';
  35      /**
  36       *    @var string Error message
  37       */
  38      var $_error = '';
  39  
  40      /**
  41       * @var object Query Handler
  42       */
  43      var $_query;
  44  
  45      /**
  46       *    Object constructor to set table and key field
  47       *
  48       *    Can be overloaded/supplemented by the child class
  49       *    @param string $table name of the table in the db schema relating to child class
  50       *    @param string $key name of the primary key field in the table
  51       */
  52  	function CW2pObject($table, $key) {
  53          $this->_tbl = $table;
  54          $this->_tbl_key = $key;
  55          $this->_tbl_prefix = w2PgetConfig('dbprefix', '');
  56          $this->_query = &new DBQuery;
  57      }
  58      /**
  59       *    @return string Returns the error message
  60       */
  61  	function getError() {
  62          return $this->_error;
  63      }
  64      /**
  65       *    Binds a named array/hash to this object
  66       *
  67       *    can be overloaded/supplemented by the child class
  68       *    @param array $hash named array
  69       *    @return null|string    null is operation was satisfactory, otherwise returns an error
  70       */
  71  	function bind($hash) {
  72          if (!is_array($hash)) {
  73              $this->_error = get_class($this) . '::bind failed.';
  74              return false;
  75          } else {
  76              /*
  77              * We need to filter out any object values from the array/hash so the bindHashToObject()
  78              * doesn't die. We also avoid issues such as passing objects to non-object functions 
  79              * and copying object references instead of cloning objects. Object cloning (if needed) 
  80              * should be handled seperatly anyway.
  81              */
  82              foreach ($hash as $k => $v) {
  83                  if (!(is_object($hash[$k]))) {
  84                      $filtered_hash[$k] = $v;
  85                  }
  86              }
  87              $this->_query->bindHashToObject($filtered_hash, $this);
  88              $this->_query->clear();
  89              return true;
  90          }
  91      }
  92  
  93      /**
  94       *    Binds an array/hash to this object
  95       *    @param int $oid optional argument, if not specifed then the value of current key is used
  96       *    @return any result from the database operation
  97       */
  98  	function load($oid = null, $strip = true) {
  99          $k = $this->_tbl_key;
 100          if ($oid) {
 101              $this->$k = intval($oid);
 102          }
 103          $oid = $this->$k;
 104          if ($oid === null) {
 105              return false;
 106          }
 107          $this->_query->clear();
 108          $this->_query->addTable($this->_tbl);
 109          $this->_query->addWhere($this->_tbl_key . ' = ' . $oid);
 110          $hash = $this->_query->loadHash();
 111          //If no record was found send false because there is no data
 112          if (!$hash) {
 113              return false;
 114          }
 115          $this->_query->bindHashToObject($hash, $this, null, $strip);
 116          $this->_query->clear();
 117          return $this;
 118      }
 119  
 120      /**
 121       *    Returns an array, keyed by the key field, of all elements that meet
 122       *    the where clause provided. Ordered by $order key.
 123       */
 124  	function loadAll($order = null, $where = null) {
 125          $this->_query->clear();
 126          $this->_query->addTable($this->_tbl);
 127          if ($order) {
 128              $this->_query->addOrder($order);
 129          }
 130          if ($where) {
 131              $this->_query->addWhere($where);
 132          }
 133          $result = $this->_query->loadHashList($this->_tbl_key);
 134          $this->_query->clear();
 135          return $result;
 136      }
 137  
 138      /**
 139       *    Return a DBQuery object seeded with the table name.
 140       *    @param string $alias optional alias for table queries.
 141       *    @return DBQuery object
 142       */
 143      function &getQuery($alias = null) {
 144          $this->_query->clear();
 145          $this->_query->addTable($this->_tbl, $alias);
 146          return $this->_query;
 147      }
 148  
 149      /**
 150       *    Generic check method
 151       *
 152       *    Can be overloaded/supplemented by the child class
 153       *    @return null if the object is ok
 154       */
 155  	function check() {
 156          return null;
 157      }
 158  
 159      /**
 160       *    Clone the current record
 161       *
 162       *    @author    handco <handco@users.sourceforge.net>
 163       *    @return    object    The new record object or null if error
 164       **/
 165  	function duplicate() {
 166          $_key = $this->_tbl_key;
 167  
 168          // In php4 assignment does a shallow copy
 169          // in php5 clone is required
 170          if (version_compare(phpversion(), '5') >= 0) {
 171              $newObj = clone($this);
 172          } else {
 173              $newObj = $this;
 174          }
 175          // blanking the primary key to ensure that's a new record
 176          $newObj->$_key = '';
 177  
 178          return $newObj;
 179      }
 180  
 181      /**
 182       *    Default trimming method for class variables of type string
 183       *
 184       *    @param object Object to trim class variables for
 185       *    Can be overloaded/supplemented by the child class
 186       *    @return none
 187       */
 188  	function w2PTrimAll() {
 189          $trim_arr = get_object_vars($this);
 190          foreach ($trim_arr as $trim_key => $trim_val) {
 191              if (!(strcasecmp(gettype($trim_val), 'string'))) {
 192                  $this->{$trim_key} = trim($trim_val);
 193              }
 194          }
 195      }
 196  
 197      /**
 198       *    Inserts a new row if id is zero or updates an existing row in the database table
 199       *
 200       *    Can be overloaded/supplemented by the child class
 201       *    @return null|string null if successful otherwise returns and error message
 202       */
 203  	function store($updateNulls = false) {
 204          global $AppUI;
 205  
 206          $this->w2PTrimAll();
 207  
 208          $msg = $this->check();
 209          if ($msg) {
 210              return get_class($this) . '::store-check failed ' . $msg;
 211          }
 212          $k = $this->_tbl_key;
 213          if ($this->$k) {
 214              $store_type = 'update';
 215              $q = new DBQuery;
 216              $ret = $q->updateObject($this->_tbl, $this, $this->_tbl_key, $updateNulls);
 217              $q->clear();
 218          } else {
 219              $store_type = 'add';
 220              $q = new DBQuery;
 221              $ret = $q->insertObject($this->_tbl, $this, $this->_tbl_key);
 222              $q->clear();
 223          }
 224  
 225          if ($ret) {
 226              // only record history if an update or insert actually occurs.
 227              addHistory($this->_tbl, $this->$k, $store_type, $AppUI->_('ACTION') . ': ' . $store_type . ' ' . $AppUI->_('TABLE') . ': ' . $this->_tbl . ' ' . $AppUI->_('ID') . ': ' . $this->$k);
 228          }
 229          return ((!$ret) ? (get_class($this) . '::store failed ' . db_error()) : null);
 230      }
 231  
 232      /**
 233       *    Generic check for whether dependencies exist for this object in the db schema
 234       *
 235       *    Can be overloaded/supplemented by the child class
 236       *    @param string $msg Error message returned
 237       *    @param int Optional key index
 238       *    @param array Optional array to compiles standard joins: format [label=>'Label',name=>'table name',idfield=>'field',joinfield=>'field']
 239       *    @return true|false
 240       */
 241  	function canDelete(&$msg, $oid = null, $joins = null) {
 242          global $AppUI;
 243  
 244          // First things first.  Are we allowed to delete?
 245          $acl = &$AppUI->acl();
 246          if (!$acl->checkModuleItem($this->_tbl, 'delete', $oid)) {
 247              $msg = $AppUI->_('noDeletePermission');
 248              return false;
 249          }
 250  
 251          $k = $this->_tbl_key;
 252          if ($oid) {
 253              $this->$k = intval($oid);
 254          }
 255          if (is_array($joins)) {
 256              $select = $k;
 257              $join = '';
 258  
 259              $q = new DBQuery;
 260              $q->addTable($this->_tbl);
 261              $q->addWhere($k . ' = \'' . $this->$k . '\'');
 262              $q->addGroup($k);
 263              foreach ($joins as $table) {
 264                  $q->addQuery('COUNT(DISTINCT ' . $table['idfield'] . ') AS ' . $table['idfield']);
 265                  $q->addJoin($table['name'], $table['name'], $table['joinfield'] . ' = ' . $k);
 266              }
 267              $obj = null;
 268              $q->loadObject($obj);
 269              $q->clear();
 270  
 271              if (!$obj) {
 272                  $msg = db_error();
 273                  return false;
 274              }
 275              $msg = array();
 276              foreach ($joins as $table) {
 277                  $k = $table['idfield'];
 278                  if ($obj->$k) {
 279                      $msg[] = $AppUI->_($table['label']);
 280                  }
 281              }
 282  
 283              if (count($msg)) {
 284                  $msg = $AppUI->_('noDeleteRecord') . ': ' . implode(', ', $msg);
 285                  return false;
 286              } else {
 287                  return true;
 288              }
 289          }
 290  
 291          return true;
 292      }
 293  
 294      /**
 295       *    Default delete method
 296       *
 297       *    Can be overloaded/supplemented by the child class
 298       *    @return null|string null if successful otherwise returns and error message
 299       */
 300  	function delete($oid = null) {
 301          $k = $this->_tbl_key;
 302          if ($oid) {
 303              $this->$k = intval($oid);
 304          }
 305          if (!$this->canDelete($msg)) {
 306              return $msg;
 307          }
 308  
 309          $q = new DBQuery;
 310          $q->setDelete($this->_tbl);
 311          $q->addWhere($this->_tbl_key . ' = \'' . $this->$k . '\'');
 312          $result = ((!$q->exec()) ? db_error() : null);
 313          if (!$result) {
 314              // only record history if deletion actually occurred
 315              addHistory($this->_tbl, $this->$k, 'delete');
 316          }
 317          $q->clear();
 318          return $result;
 319      }
 320  
 321      /**
 322       *    Get specifically denied records from a table/module based on a user
 323       *    @param int User id number
 324       *    @return array
 325       */
 326  	function getDeniedRecords($uid) {
 327          $uid = intval($uid);
 328          $uid || exit('FATAL ERROR ' . get_class($this) . '::getDeniedRecords failed, user id = 0');
 329  
 330          $perms = &$GLOBALS['AppUI']->acl();
 331          return $perms->getDeniedItems($this->_tbl, $uid);
 332      }
 333  
 334      /**
 335       *    Returns a list of records exposed to the user
 336       *    @param int User id number
 337       *    @param string Optional fields to be returned by the query, default is all
 338       *    @param string Optional sort order for the query
 339       *    @param string Optional name of field to index the returned array
 340       *    @param array Optional array of additional sql parameters (from and where supported)
 341       *    @return array
 342       */
 343      // returns a list of records exposed to the user
 344  	function getAllowedRecords($uid, $fields = '*', $orderby = '', $index = null, $extra = null, $table_alias = '') {
 345          $perms = &$GLOBALS['AppUI']->acl();
 346          $uid = intval($uid);
 347          $uid || exit('FATAL ERROR ' . get_class($this) . '::getAllowedRecords failed');
 348          $deny = &$perms->getDeniedItems($this->_tbl, $uid);
 349          $allow = &$perms->getAllowedItems($this->_tbl, $uid);
 350          /*print_r('Deny:');
 351          print_r($deny);
 352          print_r('Allow:');
 353          print_r($allow);*/
 354          //if (! $perms->checkModule($this->_tbl, 'view', $uid )) {
 355          //  if (! count($allow))
 356          //    return array();    // No access, and no allow overrides, so nothing to show.
 357          //} else {
 358          //  $allow = array();    // Full access, allow overrides don't mean anything.
 359          //}
 360          $this->_query->clear();
 361          $this->_query->addQuery($fields);
 362          $this->_query->addTable($this->_tbl);
 363  
 364          if ($extra['from']) {
 365              $this->_query->addTable($extra['from']);
 366          }
 367  
 368          if ($extra['join'] && $extra['on']) {
 369              $this->_query->addJoin($extra['join'], $extra['join'], $extra['on']);
 370          }
 371  
 372          if (count($allow)) {
 373              if ((array_search('0', $allow)) === false) {
 374                  //If 0 (All Items of a module) are not permited then just add the allowed items only
 375                  $this->_query->addWhere(($table_alias ? $table_alias . '.' : '') . $this->_tbl_key . ' IN (' . implode(',', $allow) . ')');
 376              } else {
 377                  //If 0 (All Items of a module) are permited then don't add a where clause so the user is permitted to see all
 378              }
 379              //Denials are only required if we were able to see anything in the first place so now we handle the denials
 380              if (count($deny)) {
 381                  if ((array_search('0', $deny)) === false) {
 382                      //If 0 (All Items of a module) are not on the denial array then just deny the denied items
 383                      $this->_query->addWhere(($table_alias ? $table_alias . '.' : '') . $this->_tbl_key . ' NOT IN (' . implode(',', $deny) . ')');
 384                  } elseif ((array_search('0', $allow)) === false) {
 385                      //If 0 (All Items of a module) are denied and we have granted some then implicit denial to everything else is already in place
 386                  } else {
 387                      //if we allow everything and deny everything then denials have higher priority... Deny Everything!
 388                      $this->_query->addWhere('0=1');
 389                  }
 390              }
 391          } else {
 392              //if there are no allowances, deny!
 393              $this->_query->addWhere('0=1');
 394          }
 395  
 396          if (isset($extra['where'])) {
 397              $this->_query->addWhere($extra['where']);
 398          }
 399  
 400          if ($orderby) {
 401              $this->_query->addOrder($orderby);
 402          }
 403          //print_r($this->_query->prepare());
 404          return $this->_query->loadHashList($index);
 405      }
 406  
 407  	function getAllowedSQL($uid, $index = null) {
 408          $perms = &$GLOBALS['AppUI']->acl();
 409          $uid = intval($uid);
 410          $uid || exit('FATAL ERROR ' . get_class($this) . '::getAllowedSQL failed');
 411          $deny = &$perms->getDeniedItems($this->_tbl, $uid);
 412          $allow = &$perms->getAllowedItems($this->_tbl, $uid);
 413          /*        print_r('allow:');
 414          print_r($allow);
 415          print_r('deny:');
 416          print_r($deny);
 417          print_r('deny:');
 418          print_r($deny);
 419          if (! $perms->checkModule($this->_tbl, 'view', $uid )) {
 420          if (! count($allow))
 421          return array('1=0');*/ // No access, and no allow overrides, so nothing to show.
 422          //} else {
 423          //  $allow = array();    // Full access, allow overrides don't mean anything.
 424          //}
 425  
 426          if (!isset($index)) {
 427              $index = $this->_tbl_key;
 428          }
 429          $where = array();
 430          if (count($allow)) {
 431              if ((array_search('0', $allow)) === false) {
 432                  //If 0 (All Items of a module) are not permited then just add the allowed items only
 433                  $where[] = $index  . ' IN (' . implode(',', $allow) . ')';
 434              } else {
 435                  //If 0 (All Items of a module) are permited then don't add a where clause so the user is permitted to see all
 436              }
 437              //Denials are only required if we were able to see anything in the first place so now we handle the denials
 438              if (count($deny)) {
 439                  if ((array_search('0', $deny)) === false) {
 440                      //If 0 (All Items of a module) are not on the denial array then just deny the denied items
 441                      $where[] = $index . ' NOT IN (' . implode(',', $deny) . ')';
 442                  } elseif ((array_search('0', $allow)) === false) {
 443                      //If 0 (All Items of a module) are denied and we have granted some then implicit denial to everything else is already in place
 444                  } else {
 445                      //if we allow everything and deny everything then denials have higher priority... Deny Everything!
 446                      $where[] = '0=1';
 447                  }
 448              }
 449          } else {
 450              //if there are no allowances, deny!
 451              $where[] = '0=1';
 452          }
 453          return $where;
 454      }
 455  
 456  	function setAllowedSQL($uid, &$query, $index = null, $key = null) {
 457          $perms = &$GLOBALS['AppUI']->acl();
 458          $uid = intval($uid);
 459          $uid || exit('FATAL ERROR ' . get_class($this) . '::getAllowedSQL failed');
 460          $deny = &$perms->getDeniedItems($this->_tbl, $uid);
 461          $allow = &$perms->getAllowedItems($this->_tbl, $uid);
 462          // Make sure that we add the table otherwise dependencies break
 463          if (isset($index)) {
 464              if (!