MODX Revolution PHP Cross Reference Content Management Systems

Source: /core/xpdo/xpdo.class.php - 3098 lines - 132617 bytes - Summary - Text - Print

Description: This is the main file to include in your scripts to use xPDO.

   1  <?php
   2  /*
   3   * OpenExpedio ("xPDO") is an ultra-light, PHP 5.2+ compatible ORB (Object-
   4   * Relational Bridge) library based around PDO (http://php.net/pdo/).
   5   *
   6   * Copyright 2010-2013 by MODX, LLC.
   7   *
   8   * This file is part of xPDO.
   9   *
  10   * xPDO is free software; you can redistribute it and/or modify it under the
  11   * terms of the GNU General Public License as published by the Free Software
  12   * Foundation; either version 2 of the License, or (at your option) any later
  13   * version.
  14   *
  15   * xPDO is distributed in the hope that it will be useful, but WITHOUT ANY
  16   * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  17   * A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  18   *
  19   * You should have received a copy of the GNU General Public License along with
  20   * xPDO; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
  21   * Suite 330, Boston, MA 02111-1307 USA
  22   */
  23  
  24  /**
  25   * This is the main file to include in your scripts to use xPDO.
  26   *
  27   * @author Jason Coward <xpdo@opengeek.com>
  28   * @copyright Copyright (C) 2006-2013, Jason Coward
  29   * @license http://opensource.org/licenses/gpl-2.0.php GNU Public License v2
  30   * @package xpdo
  31   */
  32  
  33  if (!defined('XPDO_PHP_VERSION')) {
  34      /**
  35       * Defines the PHP version string xPDO is running under.
  36       */
  37      define('XPDO_PHP_VERSION', phpversion());
  38  }
  39  if (!defined('XPDO_CLI_MODE')) {
  40      if (php_sapi_name() == 'cli') {
  41          /**
  42           * This constant defines if xPDO is operating from the CLI.
  43           */
  44          define('XPDO_CLI_MODE', true);
  45      } else {
  46          /** @ignore */
  47          define('XPDO_CLI_MODE', false);
  48      }
  49  }
  50  if (!defined('XPDO_CORE_PATH')) {
  51      /**
  52       * @internal This global variable is only used to set the {@link
  53       * XPDO_CORE_PATH} value upon initial include of this file.  Not meant for
  54       * external use.
  55       * @var string
  56       * @access private
  57       */
  58      $xpdo_core_path= strtr(realpath(dirname(__FILE__)), '\\', '/') . '/';
  59      /**
  60       * @var string The full path to the xPDO root directory.
  61       *
  62       * Use of this constant is recommended for use when building any path in
  63       * your xPDO code.
  64       *
  65       * @access public
  66       */
  67      define('XPDO_CORE_PATH', $xpdo_core_path);
  68  }
  69  
  70  if (!class_exists('PDO')) {
  71      //@todo Handle PDO configuration errors here.
  72  }
  73  
  74  /**
  75   * A wrapper for PDO that powers an object-relational data model.
  76   *
  77   * xPDO provides centralized data access via a simple object-oriented API, to
  78   * a defined data structure. It provides the de facto methods for connecting
  79   * to a data source, getting persistence metadata for any class extended from
  80   * the {@link xPDOObject} class (core or custom), loading data source managers
  81   * when needed to manage table structures, and retrieving instances (or rows) of
  82   * any object in the model.
  83   *
  84   * Through various extensions, you can also reverse and forward engineer classes
  85   * and metadata maps for xPDO, have classes, models, and properties maintain
  86   * their own containers (databases, tables, columns, etc.) or changes to them,
  87   * and much more.
  88   *
  89   * @package xpdo
  90   */
  91  class xPDO {
  92      /**#@+
  93       * Constants
  94       */
  95      const OPT_AUTO_CREATE_TABLES = 'auto_create_tables';
  96      const OPT_BASE_CLASSES = 'base_classes';
  97      const OPT_BASE_PACKAGES = 'base_packages';
  98      const OPT_CACHE_COMPRESS = 'cache_compress';
  99      const OPT_CACHE_DB = 'cache_db';
 100      const OPT_CACHE_DB_COLLECTIONS = 'cache_db_collections';
 101      const OPT_CACHE_DB_OBJECTS_BY_PK = 'cache_db_objects_by_pk';
 102      const OPT_CACHE_DB_EXPIRES = 'cache_db_expires';
 103      const OPT_CACHE_DB_HANDLER = 'cache_db_handler';
 104      const OPT_CACHE_DB_SIG_CLASS = 'cache_db_sig_class';
 105      const OPT_CACHE_DB_SIG_GRAPH = 'cache_db_sig_graph';
 106      const OPT_CACHE_EXPIRES = 'cache_expires';
 107      const OPT_CACHE_FORMAT = 'cache_format';
 108      const OPT_CACHE_HANDLER = 'cache_handler';
 109      const OPT_CACHE_KEY = 'cache_key';
 110      const OPT_CACHE_PATH = 'cache_path';
 111      const OPT_CACHE_PREFIX = 'cache_prefix';
 112      const OPT_CACHE_ATTEMPTS = 'cache_attempts';
 113      const OPT_CACHE_ATTEMPT_DELAY = 'cache_attempt_delay';
 114      const OPT_CALLBACK_ON_REMOVE = 'callback_on_remove';
 115      const OPT_CALLBACK_ON_SAVE = 'callback_on_save';
 116      const OPT_CONNECTIONS = 'connections';
 117      const OPT_CONN_INIT = 'connection_init';
 118      const OPT_CONN_MUTABLE = 'connection_mutable';
 119      const OPT_HYDRATE_FIELDS = 'hydrate_fields';
 120      const OPT_HYDRATE_ADHOC_FIELDS = 'hydrate_adhoc_fields';
 121      const OPT_HYDRATE_RELATED_OBJECTS = 'hydrate_related_objects';
 122      const OPT_LOCKFILE_EXTENSION = 'lockfile_extension';
 123      const OPT_USE_FLOCK = 'use_flock';
 124      /**
 125       * @deprecated
 126       * @see call()
 127       */
 128      const OPT_LOADER_CLASSES = 'loader_classes';
 129      const OPT_ON_SET_STRIPSLASHES = 'on_set_stripslashes';
 130      const OPT_SETUP = 'setup';
 131      const OPT_TABLE_PREFIX = 'table_prefix';
 132      const OPT_VALIDATE_ON_SAVE = 'validate_on_save';
 133      const OPT_VALIDATOR_CLASS = 'validator_class';
 134  
 135      const LOG_LEVEL_FATAL = 0;
 136      const LOG_LEVEL_ERROR = 1;
 137      const LOG_LEVEL_WARN = 2;
 138      const LOG_LEVEL_INFO = 3;
 139      const LOG_LEVEL_DEBUG = 4;
 140  
 141      const SCHEMA_VERSION = '1.1';
 142  
 143      /**
 144       * @var PDO A reference to the PDO instance used by the current xPDOConnection.
 145       */
 146      public $pdo= null;
 147      /**
 148       * @var array Configuration options for the xPDO instance.
 149       */
 150      public $config= null;
 151      /**
 152       * @var xPDODriver An xPDODriver instance for the xPDOConnection instances to use.
 153       */
 154      public $driver= null;
 155      /**
 156       * A map of data source meta data for all loaded classes.
 157       * @var array
 158       * @access public
 159       */
 160      public $map= array ();
 161      /**
 162       * A default package for specifying classes by name.
 163       * @var string
 164       * @access public
 165       */
 166      public $package= '';
 167      /**
 168       * An array storing packages and package-specific information.
 169       * @var array
 170       * @access public
 171       */
 172      public $packages= array ();
 173      /**
 174       * {@link xPDOManager} instance, loaded only if needed to manage datasource
 175       * containers, data structures, etc.
 176       * @var xPDOManager
 177       * @access public
 178       */
 179      public $manager= null;
 180      /**
 181       * @var xPDOCacheManager The cache service provider registered for this xPDO
 182       * instance.
 183       */
 184      public $cacheManager= null;
 185      /**
 186       * @var string A root path for file-based caching services to use.
 187       */
 188      private $cachePath= null;
 189      /**
 190       * @var array An array of supplemental service classes for this xPDO instance.
 191       */
 192      public $services= array ();
 193      /**
 194       * @var float Start time of the request, initialized when the constructor is
 195       * called.
 196       */
 197      public $startTime= 0;
 198      /**
 199       * @var int The number of direct DB queries executed during a request.
 200       */
 201      public $executedQueries= 0;
 202      /**
 203       * @var int The amount of request handling time spent with DB queries.
 204       */
 205      public $queryTime= 0;
 206  
 207      public $classMap = array();
 208  
 209      /**
 210       * @var xPDOConnection The current xPDOConnection for this xPDO instance.
 211       */
 212      public $connection = null;
 213      /**
 214       * @var array PDO connections managed by this xPDO instance.
 215       */
 216      private $_connections = array();
 217  
 218      /**
 219       * @var integer The logging level for the xPDO instance.
 220       */
 221      protected $logLevel= xPDO::LOG_LEVEL_FATAL;
 222  
 223      /**
 224       * @var string The default logging target for the xPDO instance.
 225       */
 226      protected $logTarget= 'ECHO';
 227  
 228      /**
 229       * Indicates the debug state of this instance.
 230       * @var boolean Default is false.
 231       * @access protected
 232       */
 233      protected $_debug= false;
 234      /**
 235       * A global cache flag that can be used to enable/disable all xPDO caching.
 236       * @var boolean All caching is disabled by default.
 237       * @access public
 238       */
 239      public $_cacheEnabled= false;
 240      /**
 241       * Indicates the opening escape character used for a particular database engine.
 242       * @var string
 243       * @access public
 244       */
 245      public $_escapeCharOpen= '';
 246      /**
 247       * Indicates the closing escape character used for a particular database engine.
 248       * @var string
 249       * @access public
 250       */
 251      public $_escapeCharClose= '';
 252  
 253      /**
 254       * Represents the character used for quoting strings for a particular driver.
 255       * @var string
 256       */
 257      public $_quoteChar= "'";
 258  
 259      /**
 260       * @var array A static collection of xPDO instances.
 261       */
 262      protected static $instances = array();
 263  
 264      /**
 265       * Create, retrieve, or update specific xPDO instances.
 266       *
 267       * @static
 268       * @param string|int|null $id An optional identifier for the instance. If not set
 269       * a uniqid will be generated and used as the key for the instance.
 270       * @param array|null $config An optional array of config data for the instance.
 271       * @param bool $forceNew If true a new instance will be created even if an instance
 272       * with the provided $id already exists in xPDO::$instances.
 273       * @throws xPDOException If a valid instance is not retrieved.
 274       * @return xPDO An instance of xPDO.
 275       */
 276      public static function getInstance($id = null, $config = null, $forceNew = false) {
 277          $instances =& self::$instances;
 278          if (is_null($id)) {
 279              if (!is_null($config) || $forceNew || empty($instances)) {
 280                  $id = uniqid(__CLASS__);
 281              } else {
 282                  $id = key($instances);
 283              }
 284          }
 285          if ($forceNew || !array_key_exists($id, $instances) || !($instances[$id] instanceof xPDO)) {
 286              $instances[$id] = new xPDO(null, null, null, $config);
 287          } elseif ($instances[$id] instanceof xPDO && is_array($config)) {
 288              $instances[$id]->config = array_merge($instances[$id]->config, $config);
 289          }
 290          if (!($instances[$id] instanceof xPDO)) {
 291              throw new xPDOException("Error getting " . __CLASS__ . " instance, id = {$id}");
 292          }
 293          return $instances[$id];
 294      }
 295  
 296      /**
 297       * The xPDO Constructor.
 298       *
 299       * This method is used to create a new xPDO object with a connection to a
 300       * specific database container.
 301       *
 302       * @param mixed $dsn A valid DSN connection string.
 303       * @param string $username The database username with proper permissions.
 304       * @param string $password The password for the database user.
 305       * @param array|string $options An array of xPDO options. For compatibility with previous
 306       * releases, this can also be a single string representing a prefix to be applied to all
 307       * database container (i. e. table) names, to isolate multiple installations or conflicting
 308       * table names that might need to coexist in a single database container. It is preferrable to
 309       * include the table_prefix option in the array for future compatibility.
 310       * @param array|null $driverOptions Driver-specific PDO options.
 311       * @throws xPDOException If an error occurs creating the instance.
 312       * @return xPDO A unique xPDO instance.
 313       */
 314      public function __construct($dsn, $username= '', $password= '', $options= array(), $driverOptions= null) {
 315          try {
 316              $this->config = $this->initConfig($options);
 317              $this->setLogLevel($this->getOption('log_level', null, xPDO::LOG_LEVEL_FATAL, true));
 318              $this->setLogTarget($this->getOption('log_target', null, XPDO_CLI_MODE ? 'ECHO' : 'HTML', true));
 319              if (!empty($dsn)) {
 320                  $this->addConnection($dsn, $username, $password, $this->config, $driverOptions);
 321              }
 322              if (isset($this->config[xPDO::OPT_CONNECTIONS])) {
 323                  $connections = $this->config[xPDO::OPT_CONNECTIONS];
 324                  if (is_string($connections)) {
 325                      $connections = $this->fromJSON($connections);
 326                  }
 327                  if (is_array($connections)) {
 328                      foreach ($connections as $connection) {
 329                          $this->addConnection(
 330                              $connection['dsn'],
 331                              $connection['username'],
 332                              $connection['password'],
 333                              $connection['options'],
 334                              $connection['driverOptions']
 335                          );
 336                      }
 337                  }
 338              }
 339              $initOptions = $this->getOption(xPDO::OPT_CONN_INIT, null, array());
 340              $this->config = array_merge($this->config, $this->getConnection($initOptions)->config);
 341              $this->getDriver();
 342              $this->setPackage('om', XPDO_CORE_PATH, $this->config[xPDO::OPT_TABLE_PREFIX]);
 343              if (isset($this->config[xPDO::OPT_BASE_PACKAGES]) && !empty($this->config[xPDO::OPT_BASE_PACKAGES])) {
 344                  $basePackages= explode(',', $this->config[xPDO::OPT_BASE_PACKAGES]);
 345                  foreach ($basePackages as $basePackage) {
 346                      $exploded= explode(':', $basePackage, 2);
 347                      if ($exploded) {
 348                          $path= $exploded[1];
 349                          $prefix= null;
 350                          if (strpos($path, ';')) {
 351                              $details= explode(';', $path);
 352                              if ($details && count($details) == 2) {
 353                                  $path= $details[0];
 354                                  $prefix = $details[1];
 355                              }
 356                          }
 357                          $this->addPackage($exploded[0], $path, $prefix);
 358                      }
 359                  }
 360              }
 361              $this->loadClass('xPDOObject');
 362              $this->loadClass('xPDOSimpleObject');
 363              if (isset($this->config[xPDO::OPT_BASE_CLASSES])) {
 364                  foreach (array_keys($this->config[xPDO::OPT_BASE_CLASSES]) as $baseClass) {
 365                      $this->loadClass($baseClass);
 366                  }
 367              }
 368              if (isset($this->config[xPDO::OPT_CACHE_PATH])) {
 369                  $this->cachePath = $this->config[xPDO::OPT_CACHE_PATH];
 370              }
 371          } catch (Exception $e) {
 372              throw new xPDOException("Could not instantiate xPDO: " . $e->getMessage());
 373          }
 374      }
 375  
 376      /**
 377       * Initialize an xPDO config array.
 378       *
 379       * @param string|array $data The config input source. Currently accepts a PHP array,
 380       * or a PHP string representing xPDO::OPT_TABLE_PREFIX (deprecated).
 381       * @return array An array of xPDO config data.
 382       */
 383      protected function initConfig($data) {
 384          if (is_string($data)) {
 385              $data= array(xPDO::OPT_TABLE_PREFIX => $data);
 386          } elseif (!is_array($data)) {
 387              $data= array(xPDO::OPT_TABLE_PREFIX => '');
 388          }
 389          return $data;
 390      }
 391  
 392      /**
 393       * Add an xPDOConnection instance to the xPDO connection pool.
 394       *
 395       * @param string $dsn A PDO DSN representing the connection details.
 396       * @param string $username The username credentials for the connection.
 397       * @param string $password The password credentials for the connection.
 398       * @param array $options An array of options for the connection.
 399       * @param null $driverOptions An array of PDO driver options for the connection.
 400       * @return boolean True if a valid connection was added.
 401       */
 402      public function addConnection($dsn, $username= '', $password= '', array $options= array(), $driverOptions= null) {
 403          $added = false;
 404          $connection= new xPDOConnection($this, $dsn, $username, $password, $options, $driverOptions);
 405          if ($connection instanceof xPDOConnection) {
 406              $this->_connections[]= $connection;
 407              $added= true;
 408          }
 409          return $added;
 410      }
 411  
 412      /**
 413       * Get an xPDOConnection from the xPDO connection pool.
 414       *
 415       * @param array $options An array of options for getting the connection.
 416       * @return xPDOConnection|null An xPDOConnection instance or null if no connection could be retrieved.
 417       */
 418      public function &getConnection(array $options = array()) {
 419          $conn =& $this->connection;
 420          $mutable = $this->getOption(xPDO::OPT_CONN_MUTABLE, $options, null);
 421          if (!($conn instanceof xPDOConnection) || ($mutable !== null && (($mutable == true && !$conn->isMutable()) || ($mutable == false && $conn->isMutable())))) {
 422              if (!empty($this->_connections)) {
 423                  shuffle($this->_connections);
 424                  $conn = reset($this->_connections);
 425                  while ($conn) {
 426                      if ($mutable !== null && (($mutable == true && !$conn->isMutable()) || ($mutable == false && $conn->isMutable()))) {
 427                          $conn = next($this->_connections);
 428                          continue;
 429                      }
 430                      $this->connection =& $conn;
 431                      break;
 432                  }
 433              } else {
 434                  $this->log(xPDO::LOG_LEVEL_ERROR, "Could not get a valid xPDOConnection", '', __METHOD__, __FILE__, __LINE__);
 435              }
 436          }
 437          return $this->connection;
 438      }
 439  
 440      /**
 441       * Get or create a PDO connection to a database specified in the configuration.
 442       *
 443       * @param array $driverOptions An optional array of driver options to use
 444       * when creating the connection.
 445       * @param array $options An array of xPDO options for the connection.
 446       * @return boolean Returns true if the PDO connection was created successfully.
 447       */
 448      public function connect($driverOptions= array (), array $options= array()) {
 449          $connected = false;
 450          $this->getConnection($options);
 451          if ($this->connection instanceof xPDOConnection) {
 452              $connected = $this->connection->connect($driverOptions);
 453              if ($connected) {
 454                  $this->pdo =& $this->connection->pdo;
 455              }
 456          }
 457          return $connected;
 458      }
 459  
 460      /**
 461       * Sets a specific model package to use when looking up classes.
 462       *
 463       * This package is of the form package.subpackage.subsubpackage and will be
 464       * added to the beginning of every xPDOObject class that is referenced in
 465       * xPDO methods such as {@link xPDO::loadClass()}, {@link xPDO::getObject()},
 466       * {@link xPDO::getCollection()}, {@link xPDOObject::getOne()}, {@link
 467       * xPDOObject::addOne()}, etc.
 468       *
 469       * @param string $pkg A package name to use when looking up classes in xPDO.
 470       * @param string $path The root path for looking up classes in this package.
 471       * @param string|null $prefix Provide a string to define a package-specific table_prefix.
 472       * @return bool
 473       */
 474      public function setPackage($pkg= '', $path= '', $prefix= null) {
 475          if (empty($path) && isset($this->packages[$pkg])) {
 476              $path= $this->packages[$pkg]['path'];
 477              $prefix= !is_string($prefix) && array_key_exists('prefix', $this->packages[$pkg]) ? $this->packages[$pkg]['prefix'] : $prefix;
 478          }
 479          $set= $this->addPackage($pkg, $path, $prefix);
 480          $this->package= $set == true ? $pkg : $this->package;
 481          if ($set && is_string($prefix)) $this->config[xPDO::OPT_TABLE_PREFIX]= $prefix;
 482          return $set;
 483      }
 484  
 485      /**
 486       * Adds a model package and base class path for including classes and/or maps from.
 487       *
 488       * @param string $pkg A package name to use when looking up classes/maps in xPDO.
 489       * @param string $path The root path for looking up classes in this package.
 490       * @param string|null $prefix Provide a string to define a package-specific table_prefix.
 491       * @return bool
 492       */
 493      public function addPackage($pkg= '', $path= '', $prefix= null) {
 494          $added= false;
 495          if (is_string($pkg) && !empty($pkg)) {
 496              if (!is_string($path) || empty($path)) {
 497                  $this->log(xPDO::LOG_LEVEL_ERROR, "Invalid path specified for package: {$pkg}; using default xpdo model path: " . XPDO_CORE_PATH . 'om/');
 498                  $path= XPDO_CORE_PATH . 'om/';
 499              }
 500              if (!is_dir($path)) {
 501                  $this->log(xPDO::LOG_LEVEL_ERROR, "Path specified for package {$pkg} is not a valid or accessible directory: {$path}");
 502              } else {
 503                  $prefix= !is_string($prefix) ? $this->config[xPDO::OPT_TABLE_PREFIX] : $prefix;
 504                  if (!array_key_exists($pkg, $this->packages) || $this->packages[$pkg]['path'] !== $path || $this->packages[$pkg]['prefix'] !== $prefix) {
 505                      $this->packages[$pkg]= array('path' => $path, 'prefix' => $prefix);
 506                      $this->setPackageMeta($pkg, $path);
 507                  }
 508                  $added= true;
 509              }
 510          } else {
 511              $this->log(xPDO::LOG_LEVEL_ERROR, 'addPackage called with an invalid package name.');
 512          }
 513          return $added;
 514      }
 515  
 516      /**
 517       * Adds metadata information about a package and loads the xPDO::$classMap.
 518       *
 519       * @param string $pkg A package name to use when looking up classes/maps in xPDO.
 520       * @param string $path The root path for looking up classes in this package.
 521       * @return bool
 522       */
 523      public function setPackageMeta($pkg, $path = '') {
 524          $set = false;
 525          if (is_string($pkg) && !empty($pkg)) {
 526              $pkgPath = str_replace('.', '/', $pkg);
 527              $mapFile = $path . $pkgPath . '/metadata.' . $this->config['dbtype'] . '.php';
 528              if (file_exists($mapFile)) {
 529                  $xpdo_meta_map = '';
 530                  include $mapFile;
 531                  if (!empty($xpdo_meta_map)) {
 532                      foreach ($xpdo_meta_map as $className => $extends) {
 533                          if (!isset($this->classMap[$className])) {
 534                              $this->classMap[$className] = array();
 535                          }
 536                          $this->classMap[$className] = array_unique(array_merge($this->classMap[$className],$extends));
 537                      }
 538                      $set = true;
 539                  }
 540              } else {
 541                  $this->log(xPDO::LOG_LEVEL_WARN, "Could not load package metadata for package {$pkg}.");
 542              }
 543          } else {
 544              $this->log(xPDO::LOG_LEVEL_ERROR, 'setPackageMeta called with an invalid package name.');
 545          }
 546          return $set;
 547      }
 548  
 549      /**
 550       * Gets a list of derivative classes for the specified className.
 551       *
 552       * The specified className must be xPDOObject or a derivative class.
 553       *
 554       * @param string $className The name of the class to retrieve derivatives for.
 555       * @return array An array of derivative classes or an empty array.
 556       */
 557      public function getDescendants($className) {
 558          $descendants = array();
 559          if (isset($this->classMap[$className])) {
 560              $descendants = $this->classMap[$className];
 561              if ($descendants) {
 562                  foreach ($descendants as $descendant) {
 563                      $descendants = array_merge($descendants, $this->getDescendants($descendant));
 564                  }
 565              }
 566          }
 567          return $descendants;
 568      }
 569  
 570      /**
 571       * Load a class by fully qualified name.
 572       *
 573       * The $fqn should in the format:
 574       *
 575       *    dir_a.dir_b.dir_c.classname
 576       *
 577       * which will translate to:
 578       *
 579       *    XPDO_CORE_PATH/om/dir_a/dir_b/dir_c/dbtype/classname.class.php
 580       *
 581       * @param string $fqn The fully-qualified name of the class to load.
 582       * @param string $path An optional path to start the search from.
 583       * @param bool $ignorePkg True if currently loaded packages should be ignored.
 584       * @param bool $transient True if the class is not a persistent table class.
 585       * @return string|boolean The actual classname if successful, or false if
 586       * not.
 587       */
 588      public function loadClass($fqn, $path= '', $ignorePkg= false, $transient= false) {
 589          if (empty($fqn)) {
 590              $this->log(xPDO::LOG_LEVEL_ERROR, "No class specified for loadClass");
 591              return false;
 592          }
 593          if (!$transient) {
 594              $typePos= strrpos($fqn, '_' . $this->config['dbtype']);
 595              if ($typePos !== false) {
 596                  $fqn= substr($fqn, 0, $typePos);
 597          }
 598          }
 599          $pos= strrpos($fqn, '.');
 600          if ($pos === false) {
 601              $class= $fqn;
 602              if ($transient) {
 603                  $fqn= strtolower($class);
 604              } else {
 605                  $fqn= $this->config['dbtype'] . '.' . strtolower($class);
 606              }
 607          } else {
 608              $class= substr($fqn, $pos +1);
 609              if ($transient) {
 610                  $fqn= substr($fqn, 0, $pos) . '.' . strtolower($class);
 611              } else {
 612                  $fqn= substr($fqn, 0, $pos) . '.' . $this->config['dbtype'] . '.' . strtolower($class);
 613              }
 614          }
 615          // check if class exists
 616          if (!$transient && isset ($this->map[$class])) return $class;
 617          $included= class_exists($class, false);
 618          if ($included) {
 619              if ($transient || (!$transient && isset ($this->map[$class]))) {
 620                  return $class;
 621              }
 622          }
 623          $classname= $class;
 624          if (!empty($path) || $ignorePkg) {
 625              $class= $this->_loadClass($class, $fqn, $included, $path, $transient);
 626          } elseif (isset ($this->packages[$this->package])) {
 627              $pqn= $this->package . '.' . $fqn;
 628              if (!$pkgClass= $this->_loadClass($class, $pqn, $included, $this->packages[$this->package]['path'], $transient)) {
 629                  foreach ($this->packages as $pkg => $pkgDef) {
 630                      if ($pkg === $this->package) continue;
 631                      $pqn= $pkg . '.' . $fqn;
 632                      if ($pkgClass= $this->_loadClass($class, $pqn, $included, $pkgDef['path'], $transient)) {
 633                          break;
 634                      }
 635                  }
 636              }
 637              $class= $pkgClass;
 638          } else {
 639              $class= false;
 640          }
 641          if ($class === false) {
 642              $this->log(xPDO::LOG_LEVEL_ERROR, "Could not load class: {$classname} from {$fqn}.");
 643          }
 644          return $class;
 645      }
 646  
 647      protected function _loadClass($class, $fqn, $included= false, $path= '', $transient= false) {
 648          if (empty($path)) $path= XPDO_CORE_PATH;
 649          if (!$included) {
 650              /* turn to filesystem path and enforce all lower-case paths and filenames */
 651              $fqcn= str_replace('.', '/', $fqn) . '.class.php';
 652              /* include class */
 653              if (!file_exists($path . $fqcn)) return false;
 654              if (!$rt= include_once ($path . $fqcn)) {
 655                  $this->log(xPDO::LOG_LEVEL_WARN, "Could not load class: {$class} from {$path}{$fqcn}");
 656                  $class= false;
 657              }
 658          }
 659          if ($class && !$transient && !isset ($this->map[$class])) {
 660              $mapfile= strtr($fqn, '.', '/') . '.map.inc.php';
 661              if (file_exists($path . $mapfile)) {
 662                  $xpdo_meta_map= & $this->map;
 663                  $rt= include ($path . $mapfile);
 664                  if (!$rt || !isset($this->map[$class])) {
 665                      $this->log(xPDO::LOG_LEVEL_WARN, "Could not load metadata map {$mapfile} for class {$class} from {$fqn}");
 666                  } else {
 667                      if (!array_key_exists('fieldAliases', $this->map[$class])) {
 668                          $this->map[$class]['fieldAliases'] = array();
 669                      }
 670                  }
 671              }
 672          }
 673          return $class;
 674      }
 675  
 676      /**
 677       * Get an xPDO configuration option value by key.
 678       *
 679       * @param string $key The option key.
 680       * @param array $options A set of options to override those from xPDO.
 681       * @param mixed $default An optional default value to return if no value is found.
 682       * @return mixed The configuration option value.
 683       */
 684      public function getOption($key, $options = null, $default = null, $skipEmpty = false) {
 685          $option= $default;
 686          if (is_array($key)) {
 687              if (!is_array($option)) {
 688                  $default= $option;
 689                  $option= array();
 690              }
 691              foreach ($key as $k) {
 692                  $option[$k]= $this->getOption($k, $options, $default);
 693              }
 694          } elseif (is_string($key) && !empty($key)) {
 695              if (is_array($options) && !empty($options) && array_key_exists($key, $options) && (!$skipEmpty || ($skipEmpty && $options[$key] !== ''))) {
 696                  $option= $options[$key];
 697              } elseif (is_array($this->config) && !empty($this->config) && array_key_exists($key, $this->config) && (!$skipEmpty || ($skipEmpty && $this->config[$key] !== ''))) {
 698                  $option= $this->config[$key];
 699              }
 700          }
 701          return $option;
 702      }
 703  
 704      /**
 705       * Sets an xPDO configuration option value.
 706       *
 707       * @param string $key The option key.
 708       * @param mixed $value A value to set for the given option key.
 709       */
 710      public function setOption($key, $value) {
 711          $this->config[$key]= $value;
 712      }
 713  
 714      /**
 715       * Call a static method from a valid package class with arguments.
 716       *
 717       * Will always search for database-specific class files first.
 718       *
 719       * @param string $class The name of a class to to get the static method from.
 720       * @param string $method The name of the method you want to call.
 721       * @param array $args An array of arguments for the method.
 722       * @param boolean $transient Indicates if the class has dbtype derivatives. Set to true if you
 723       * want to use on classes not derived from xPDOObject.
 724       * @return mixed|null The callback method's return value or null if no valid method is found.
 725       */
 726      public function call($class, $method, array $args = array(), $transient = false) {
 727          $return = null;
 728          $callback = '';
 729          if ($transient) {
 730              $className = $this->loadClass($class, '', false, true);
 731              if ($className) {
 732                  $callback = array($className, $method);
 733              }
 734          } else {
 735              $className = $this->loadClass($class);
 736              if ($className) {
 737                  $className .= '_' . $this->getOption('dbtype');
 738                  $callback = array($className, $method);
 739              }
 740          }
 741          if (!empty($callback) && is_callable($callback)) {
 742              try {
 743                  $return = call_user_func_array($callback, $args);
 744              } catch (Exception $e) {
 745                  $this->log(xPDO::LOG_LEVEL_ERROR, "An exception occurred calling {$className}::{$method}() - " . $e->getMessage());
 746              }
 747          } else {
 748              $this->log(xPDO::LOG_LEVEL_ERROR, "{$class}::{$method}() is not a valid static method.");
 749          }
 750          return $return;
 751      }
 752  
 753      /**
 754       * Creates a new instance of a specified class.
 755       *
 756       * All new objects created with this method are transient until {@link
 757       * xPDOObject::save()} is called the first time and is reflected by the
 758       * {@link xPDOObject::$_new} property.
 759       *
 760       * @param string $className Name of the class to get a new instance of.
 761       * @param array $fields An associated array of field names/values to
 762       * populate the object with.
 763       * @return object|null A new instance of the specified class, or null if a
 764       * new object could not be instantiated.
 765       */
 766      public function newObject($className, $fields= array ()) {
 767          $instance= null;
 768          if ($className= $this->loadClass($className)) {
 769              $className .=  '_' . $this->config['dbtype'];
 770              if ($instance= new $className ($this)) {
 771                  if (is_array($fields) && !empty ($fields)) {
 772                      $instance->fromArray($fields);
 773                  }
 774              }
 775          }
 776          return $instance;
 777      }
 778  
 779      /**
 780       * Finds the class responsible for loading instances of the specified class.
 781       *
 782       * @deprecated Use call() instead.
 783       * @param string $className The name of the class to find a loader for.
 784       * @param string $method Indicates the specific loader method to use,
 785       * loadCollection or loadObject (or other public static methods).
 786       * @return callable A callable loader function.
 787       */
 788      public function getObjectLoader($className, $method) {
 789          $loader = false;
 790          if (isset($this->config[xPDO::OPT_LOADER_CLASSES]) && is_array($this->config[xPDO::OPT_LOADER_CLASSES])) {
 791              if ($ancestry = $this->getAncestry($className, true)) {
 792                  if ($callbacks = array_intersect($ancestry, $this->config[xPDO::OPT_LOADER_CLASSES])) {
 793                      if ($loaderClass = reset($callbacks)) {
 794                          $loader = array($loaderClass, $method);
 795                          while (!is_callable($loader) && $loaderClass = next($callbacks)) {
 796                              $loader = array($loaderClass, $method);
 797                          }
 798                      }
 799                  }
 800              }
 801          }
 802          if (!is_callable($loader)) {
 803              $loader = array('xPDOObject', $method);
 804          }
 805          return $loader;
 806      }
 807  
 808      /**
 809       * Retrieves a single object instance by the specified criteria.
 810       *
 811       * The criteria can be a primary key value, and array of primary key values
 812       * (for multiple primary key objects) or an {@link xPDOCriteria} object. If
 813       * no $criteria parameter is specified, no class is found, or an object
 814       * cannot be located by the supplied criteria, null is returned.
 815       *
 816       * @uses xPDOObject::load()
 817       * @param string $className Name of the class to get an instance of.
 818       * @param mixed $criteria Primary key of the record or a xPDOCriteria object.
 819       * @param mixed $cacheFlag If an integer value is provided, this specifies
 820       * the time to live in the object cache; if cacheFlag === false, caching is
 821       * ignored for the object and if cacheFlag === true, the object will live in
 822       * cache indefinitely.
 823       * @return object|null An instance of the class, or null if it could not be
 824       * instantiated.
 825      */
 826      public function getObject($className, $criteria= null, $cacheFlag= true) {
 827          $instance= null;
 828          if ($criteria !== null) {
 829              $instance = $this->call($className, 'load', array(& $this, $className, $criteria, $cacheFlag));
 830          }
 831          return $instance;
 832      }
 833  
 834      /**
 835       * Retrieves a collection of xPDOObjects by the specified xPDOCriteria.
 836       *
 837       * @uses xPDOObject::loadCollection()
 838       * @param string $className Name of the class to search for instances of.
 839       * @param object|array|string $criteria An xPDOCriteria object or an array
 840       * search expression.
 841       * @param mixed $cacheFlag If an integer value is provided, this specifies
 842       * the time to live in the result set cache; if cacheFlag === false, caching
 843       * is ignored for the collection and if cacheFlag === true, the objects will
 844       * live in cache until flushed by another process.
 845       * @return array|null An array of class instances retrieved.
 846      */
 847      public function getCollection($className, $criteria= null, $cacheFlag= true) {
 848          return $this->call($className, 'loadCollection', array(& $this, $className, $criteria, $cacheFlag));
 849      }
 850  
 851      /**
 852       * Retrieves an iterable representation of a collection of xPDOObjects.
 853       *
 854       * @param string $className Name of the class to search for instances of.
 855       * @param mixed $criteria An xPDOCriteria object or representation.
 856       * @param bool $cacheFlag If an integer value is provided, this specifies
 857       * the time to live in the result set cache; if cacheFlag === false, caching
 858       * is ignored for the collection and if cacheFlag === true, the objects will
 859       * live in cache until flushed by another process.
 860       * @return xPDOIterator An iterable representation of a collection.
 861       */
 862      public function getIterator($className, $criteria= null, $cacheFlag= true) {
 863          return new xPDOIterator($this, array('class' => $className, 'criteria' => $criteria, 'cacheFlag' => $cacheFlag));
 864      }
 865  
 866      /**
 867       * Update field values across a collection of xPDOObjects.
 868       *
 869       * @param string $className Name of the class to update fields of.
 870       * @param array $set An associative array of field/value pairs representing the updates to make.
 871       * @param mixed $criteria An xPDOCriteria object or representation.
 872       * @return bool|int The number of instances affected by the update or false on failure.
 873       */
 874      public function updateCollection($className, array $set, $criteria= null) {
 875          $affected = false;
 876          if ($this->getConnection(array(xPDO::OPT_CONN_MUTABLE => true))) {
 877              $query = $this->newQuery($className);
 878              if ($query && !empty($set)) {
 879                  $query->command('UPDATE');
 880                  $query->set($set);
 881                  if (!empty($criteria)) $query->where($criteria);
 882                  if ($query->prepare()) {
 883                      $affected = $this->exec($query->toSQL());
 884                      if ($affected === false) {
 885                          $this->log(xPDO::LOG_LEVEL_ERROR, "Error updating {$className} instances using query " . $query->toSQL(), '', __METHOD__, __FILE__, __LINE__);
 886                      } else {
 887                          if ($this->getOption(xPDO::OPT_CACHE_DB)) {
 888                              $relatedClasses = array($query->getTableClass());
 889                              $related = array_merge($this->getAggregates($className), $this->getComposites($className));
 890                              foreach ($related as $relatedAlias => $relatedMeta) {
 891                                  $relatedClasses[] = $relatedMeta['class'];
 892                              }
 893                              $relatedClasses = array_unique($relatedClasses);
 894                              foreach ($relatedClasses as $relatedClass) {
 895                                  $this->cacheManager->delete($relatedClass, array(
 896                                      xPDO::OPT_CACHE_KEY => $this->getOption('cache_db_key', null, 'db'),
 897                                      xPDO::OPT_CACHE_HANDLER => $this->getOption(xPDO::OPT_CACHE_DB_HANDLER, null, $this->getOption(xPDO::OPT_CACHE_HANDLER, null, 'cache.xPDOFileCache')),
 898                                      xPDO::OPT_CACHE_FORMAT => (integer) $this->getOption('cache_db_format', null, $this->getOption(xPDO::OPT_CACHE_FORMAT, null, xPDOCacheManager::CACHE_PHP)),
 899                                      xPDO::OPT_CACHE_PREFIX => $this->getOption('cache_db_prefix', null, xPDOCacheManager::CACHE_DIR),
 900                                      'multiple_object_delete' => true
 901                                  ));
 902                              }
 903                          }
 904                          $callback = $this->getOption(xPDO::OPT_CALLBACK_ON_SAVE);
 905                          if ($callback && is_callable($callback)) {
 906                              call_user_func($callback, array('className' => $className, 'criteria' => $query, 'object' => null));
 907                          }
 908                      }
 909                  }
 910              }
 911          } else {
 912              $this->log(xPDO::LOG_LEVEL_ERROR, "Could not get connection for writing data", '', __METHOD__, __FILE__, __LINE__);
 913          }
 914          return $affected;
 915      }
 916  
 917      /**
 918       * Remove an instance of the specified className by a supplied criteria.
 919       *
 920       * @param string $className The name of the class to remove an instance of.
 921       * @param mixed $criteria Valid xPDO criteria for selecting an instance.
 922       * @return boolean True if the instance is successfully removed.
 923       */
 924      public function removeObject($className, $criteria) {
 925          $removed= false;
 926          if ($this->getConnection(array(xPDO::OPT_CONN_MUTABLE => true))) {
 927              if ($this->getCount($className, $criteria) === 1) {
 928                  if ($query= $this->newQuery($className)) {
 929                      $query->command('DELETE');
 930                      $query->where($criteria);
 931                      if ($query->prepare()) {
 932                          if ($this->exec($query->toSQL()) !== 1) {
 933                              $this->log(xPDO::LOG_LEVEL_ERROR, "xPDO->removeObject - Error deleting {$className} instance using query " . $query->toSQL());
 934                          } else {
 935                              $removed= true;
 936                              if ($this->getOption(xPDO::OPT_CACHE_DB)) {
 937                                  $this->cacheManager->delete(xPDOCacheManager::CACHE_DIR . $query->getAlias(), array('multiple_object_delete' => true));
 938                              }
 939                              $callback = $this->getOption(xPDO::OPT_CALLBACK_ON_REMOVE);
 940                              if ($callback && is_callable($callback)) {
 941                                  call_user_func($callback, array('className' => $className, 'criteria' => $query));
 942                              }
 943                          }
 944                      }
 945                  }
 946              } else {
 947                  $this->log(xPDO::LOG_LEVEL_WARN, "xPDO->removeObject - {$className} instance to remove not found!");
 948                  if ($this->getDebug() === true) $this->log(xPDO::LOG_LEVEL_DEBUG, "xPDO->removeObject - {$className} instance to remove not found using criteria " . print_r($criteria, true));
 949              }
 950          } else {
 951              $this->log(xPDO::LOG_LEVEL_ERROR, "Could not get connection for writing data", '', __METHOD__, __FILE__, __LINE__);
 952          }
 953          return $removed;
 954      }
 955  
 956      /**
 957       * Remove a collection of instances by the supplied className and criteria.
 958       *
 959       * @param string $className The name of the class to remove a collection of.
 960       * @param mixed $criteria Valid xPDO criteria for selecting a collection.
 961       * @return boolean|integer False if the remove encounters an error, otherwise an integer value
 962       * representing the number of rows that were removed.
 963       */
 964      public function removeCollection($className, $criteria) {
 965          $removed= false;
 966          if ($this->getConnection(array(xPDO::OPT_CONN_MUTABLE => true))) {
 967              if ($query= $this->newQuery($className)) {
 968                  $query->command('DELETE');
 969                  $query->where($criteria);
 970                  if ($query->prepare()) {
 971                      $removed= $this->exec($query->toSQL());
 972                      if ($removed === false) {
 973                          $this->log(xPDO::LOG_LEVEL_ERROR, "xPDO->removeCollection - Error deleting {$className} instances using query " . $query->toSQL());
 974                      } else {
 975                          if ($this->getOption(xPDO::OPT_CACHE_DB)) {
 976                              $this->cacheManager->delete(xPDOCacheManager::CACHE_DIR . $query->getAlias(), array('multiple_object_delete' => true));
 977                          }
 978                          $callback = $this->getOption(xPDO::OPT_CALLBACK_ON_REMOVE);
 979                          if ($callback && is_callable($callback)) {
 980                              call_user_func($callback, array('className' => $className, 'criteria' => $query));
 981                          }
 982                      }
 983                  } else {
 984                      $this->log(xPDO::LOG_LEVEL_ERROR, "xPDO->removeCollection - Error preparing statement to delete {$className} instances using query: {$query->toSQL()}");
 985                  }
 986              }
 987          } else {
 988              $this->log(xPDO::LOG_LEVEL_ERROR, "Could not get connection for writing data", '', __METHOD__, __FILE__, __LINE__);
 989          }
 990          return $removed;
 991      }
 992  
 993      /**
 994       * Retrieves a count of xPDOObjects by the specified xPDOCriteria.
 995       *
 996       * @param string $className Class of xPDOObject to count instances of.
 997       * @param mixed $criteria Any valid xPDOCriteria object or expression.
 998       * @return integer The number of instances found by the criteria.
 999       */
1000      public function getCount($className, $criteria = null) {
1001          $count = 0;
1002          if ($query = $this->newQuery($className, $criteria)) {
1003              $stmt = null;
1004              $expr = '*';
1005              if ($pk = $this->getPK($className)) {
1006                  if (!is_array($pk)) {
1007                      $pk = array($pk);
1008                  }
1009                  $expr = $this->getSelectColumns($className, $query->getAlias(), '', $pk);
1010              }
1011              if (isset($query->query['columns'])) {
1012                  $query->query['columns'] = array();
1013              }
1014              if (!empty($query->query['groupby']) || !empty($query->query['having'])) {
1015                  $query->select($expr);
1016                  if ($query->prepare()) {
1017                      $countQuery = new xPDOCriteria($this, "SELECT COUNT(*) FROM ({$query->toSQL(false)}) cq", $query->bindings, $query->cacheFlag);
1018                      $stmt = $countQuery->prepare();
1019                  }
1020              } else {
1021                  $query->select(array("COUNT(DISTINCT {$expr})"));
1022                  $stmt = $query->prepare();
1023              }
1024              if ($stmt && $stmt->execute()) {
1025                  $count = intval($stmt->fetchColumn());
1026              }
1027          }
1028          return $count;
1029      }
1030  
1031      /**
1032       * Retrieves an xPDOObject instance with specified related objects.
1033       *
1034       * @uses xPDO::getCollectionGraph()
1035       * @param string $className The name of the class to return an instance of.
1036       * @param string|array $graph A related object graph in array or JSON
1037       * format, e.g. array('relationAlias'=>array('subRelationAlias'=>array()))
1038       * or {"relationAlias":{"subRelationAlias":{}}}.  Note that the empty arrays
1039       * are necessary in order for the relation to be recognized.
1040       * @param mixed $criteria A valid xPDOCriteria instance or expression.
1041       * @param boolean|integer $cacheFlag Indicates if the result set should be
1042       * cached, and optionally for how many seconds.
1043       * @return object The object instance with related objects from the graph
1044       * hydrated, or null if no instance can be located by the criteria.
1045       */
1046      public function getObjectGraph($className, $graph, $criteria= null, $cacheFlag= true) {
1047          $object= null;
1048          if ($collection= $this->getCollectionGraph($className, $graph, $criteria, $cacheFlag)) {
1049              if (!count($collection) === 1) {
1050                  $this->log(xPDO::LOG_LEVEL_WARN, 'getObjectGraph criteria returned more than one instance.');
1051              }
1052              $object= reset($collection);
1053          }
1054          return $object;
1055      }
1056  
1057      /**
1058       * Retrieves a collection of xPDOObject instances with related objects.
1059       *
1060       * @uses xPDOQuery::bindGraph()
1061       * @param string $className The name of the class to return a collection of.
1062       * @param string|array $graph A related object graph in array or JSON
1063       * format, e.g. array('relationAlias'=>array('subRelationAlias'=>array()))
1064       * or {"relationAlias":{"subRelationAlias":{}}}.  Note that the empty arrays
1065       * are necessary in order for the relation to be recognized.
1066       * @param mixed $criteria A valid xPDOCriteria instance or condition string.
1067       * @param boolean $cacheFlag Indicates if the result set should be cached.
1068       * @return array An array of instances matching the criteria with related
1069       * objects from the graph hydrated.  An empty array is returned when no
1070       * matches are found.
1071       */
1072      public function getCollectionGraph($className, $graph, $criteria= null, $cacheFlag= true) {
1073          return $this->call($className, 'loadCollectionGraph', array(& $this, $className, $graph, $criteria, $cacheFlag));
1074      }
1075  
1076      /**
1077       * Execute a PDOStatement and get a single column value from the first row of the result set.
1078       *
1079       * @param PDOStatement $stmt A prepared PDOStatement object ready to be executed.
1080       * @param null|integer $column 0-indexed number of the column you wish to retrieve from the row. If
1081       * null or no value is supplied, it fetches the first column.
1082       * @return mixed The value of the specified column from the first row of the result set, or null.
1083       */
1084      public function getValue($stmt, $column= null) {
1085          $value = null;
1086          if (is_object($stmt) && $stmt instanceof PDOStatement) {
1087              $tstart = microtime(true);
1088              if ($stmt->execute()) {
1089                  $this->queryTime += microtime(true) - $tstart;
1090                  $this->executedQueries++;
1091                  $value= $stmt->fetchColumn($column);
1092                  $stmt->closeCursor();
1093              } else {
1094                  $this->queryTime += microtime(true) - $tstart;
1095                  $this->executedQueries++;
1096                  $this->log(xPDO::LOG_LEVEL_ERROR, "Error " . $stmt->errorCode() . " executing statement: \n" . print_r($stmt->errorInfo(), true), '', __METHOD__, __FILE__, __LINE__);
1097              }
1098          } else {
1099              $this->log(xPDO::LOG_LEVEL_ERROR, "No valid PDOStatement provided to getValue", '', __METHOD__, __FILE__, __LINE__);
1100          }
1101          return $value;
1102      }
1103  
1104      /**
1105       * Convert any valid criteria into an xPDOQuery instance.
1106       *
1107       * @todo Get criteria pre-defined in an {@link xPDOObject} class metadata
1108       * definition by name.
1109       *
1110       * @todo Define callback functions as an alternative to retreiving criteria
1111       * sql and/or bindings from the metadata.
1112       *
1113       * @param string $className The class to get predefined criteria for.
1114       * @param string $type The type of criteria to get (you can define any
1115       * type you want, but 'object' and 'collection' are the typical criteria
1116       * for retrieving single and multiple instances of an object).
1117       * @param boolean|integer $cacheFlag Indicates if the result is cached and
1118       * optionally for how many seconds.
1119       * @return xPDOCriteria A criteria object or null if not found.
1120       */
1121      public function getCriteria($className, $type= null, $cacheFlag= true) {
1122          return $this->newQuery($className, $type, $cacheFlag);
1123      }
1124  
1125      /**
1126       * Validate and return the type of a specified criteria variable.
1127       *
1128       * @param mixed $criteria An xPDOCriteria instance or any valid criteria variable.
1129       * @return string|null The type of valid criteria passed, or null if the criteria is not valid.
1130       */
1131      public function getCriteriaType($criteria) {
1132          $type = gettype($criteria);
1133          if ($type === 'object') {
1134              $type = get_class($criteria);
1135              if (!$criteria instanceof xPDOCriteria) {
1136                  $this->log(xPDO::LOG_LEVEL_WARN, "Invalid criteria object of class {$type} encountered.", '', __METHOD__, __FILE__, __LINE__);
1137                  $type = null;
1138              }
1139          }
1140          return $type;
1141      }
1142  
1143      /**
1144       * Add criteria when requesting a derivative class row automatically.
1145       *
1146       * This applies class_key filtering for single-table inheritance queries and may
1147       * provide a convenient location for similar features in the future.
1148       *
1149       * @param string $className A valid xPDOObject derivative table class.
1150       * @param xPDOQuery $criteria A valid xPDOQuery instance.
1151       * @return xPDOQuery The xPDOQuery instance with derivative criteria added.
1152       */
1153      public function addDerivativeCriteria($className, $criteria) {
1154          if ($criteria instanceof xPDOQuery && !isset($this->map[$className]['table'])) {
1155              if (isset($this->map[$className]['fields']['class_key']) && !empty($this->map[$className]['fields']['class_key'])) {
1156                  $criteria->where(array('class_key' => $this->map[$className]['fields']['class_key']));
1157                  if ($this->getDebug() === true) {
1158                      $this->log(xPDO::LOG_LEVEL_DEBUG, "#1: Automatically adding class_key criteria for derivative query of class {$className}");
1159                  }
1160              } else {
1161                  foreach ($this->getAncestry($className, false) as $ancestor) {
1162                      if (isset($this->map[$ancestor]['table']) && isset($this->map[$ancestor]['fields']['class_key'])) {
1163                          $criteria->where(array('class_key' => $className));
1164                          if ($this->getDebug() === true) {
1165                              $this->log(xPDO::LOG_LEVEL_DEBUG, "#2: Automatically adding class_key criteria for derivative query of class {$className} from base table class {$ancestor}");
1166                          }
1167                          break;
1168                      }
1169                  }
1170              }
1171          }
1172          return $criteria;
1173      }
1174  
1175      /**
1176       * Gets the package name from a specified class name.
1177       *
1178       * @param string $className The name of the class to lookup the package for.
1179       * @return string The package the class belongs to.
1180       */
1181      public function getPackage($className) {
1182          $package= '';
1183          if ($className= $this->loadClass($className)) {
1184              if (isset($this->map[$className]['package'])) {
1185                  $package= $this->map[$className]['package'];
1186              }
1187              if (!$package && $ancestry= $this->getAncestry($className, false)) {
1188                  foreach ($ancestry as $ancestor) {
1189                      if (isset ($this->map[$ancestor]['package']) && ($package= $this->map[$ancestor]['package'])) {
1190                          break;
1191                      }
1192                  }
1193              }
1194          }
1195          return $package;
1196      }
1197  
1198      /**
1199       * Load and return a named service class instance.
1200       *
1201       * @param string $name The variable name of the instance.
1202       * @param string $class The service class name.
1203       * @param string $path An optional root path to search for the class.
1204       * @param array $params An array of optional params to pass to the service
1205       * class constructor.
1206       * @return object|null A reference to the service class instance or null if
1207       * it could not be loaded.
1208       */
1209      public function &getService($name, $class= '', $path= '', $params= array ()) {
1210          $service= null;
1211          if (!isset ($this->services[$name]) || !is_object($this->services[$name])) {
1212              if (empty ($class) && isset ($this->config[$name . '.class'])) {
1213                  $class= $this->config[$name . '.class'];
1214              } elseif (empty ($class)) {
1215                  $class= $name;
1216              }
1217              $className= $this->loadClass($class, $path, false, true);
1218              if (!empty($className)) {
1219                  $service = new $className ($this, $params);
1220                  if ($service) {
1221                      $this->services[$name]=& $service;
1222                      $this->$name= & $this->services[$name];
1223                  }
1224              }
1225          }
1226          if (array_key_exists($name, $this->services)) {
1227              $service= & $this->services[$name];
1228          } else {
1229              if ($this->getDebug() === true) {
1230                  $this->log(xPDO::LOG_LEVEL_DEBUG, "Problem getting service {$name}, instance of class {$class}, from path {$path}, with params " . print_r($params, true));
1231              } else {
1232                  $this->log(xPDO::LOG_LEVEL_ERROR, "Problem getting service {$name}, instance of class {$class}, from path {$path}");
1233              }
1234          }
1235          return $service;
1236      }
1237  
1238      /**
1239       * Gets the actual run-time table name from a specified class name.
1240       *
1241       * @param string $className The name of the class to lookup a table name
1242       * for.
1243       * @param boolean $includeDb Qualify the table name with the database name.
1244       * @return string The table name for the class, or null if unsuccessful.
1245       */
1246      public function getTableName($className, $includeDb= false) {
1247          $table= null;
1248          if ($className= $this->loadClass($className)) {
1249              if (isset ($this->map[$className]['table'])) {
1250                  $table= $this->map[$className]['table'];
1251                  if (isset($this->map[$className]['package']) && isset($this->packages[$this->map[$className]['package']]['prefix'])) {
1252                      $table= $this->packages[$this->map[$className]['package']]['prefix'] . $table;
1253                  } else {
1254                      $table= $this->getOption(xPDO::OPT_TABLE_PREFIX, null, '') . $table;
1255                  }
1256              }
1257              if (!$table && $ancestry= $this->getAncestry($className, false)) {
1258                  foreach ($ancestry as $ancestor) {
1259                      if (isset ($this->map[$ancestor]['table']) && $table= $this->map[$ancestor]['table']) {
1260                          if (isset($this->map[$ancestor]['package']) && isset($this->packages[$this->map[$ancestor]['package']]['prefix'])) {
1261                              $table= $this->packages[$this->map[$ancestor]['package']]['prefix'] . $table;
1262                          } else {
1263                              $table= $this->getOption(xPDO::OPT_TABLE_PREFIX, null, '') . $table;
1264                          }
1265                          break;
1266                      }
1267                  }
1268              }
1269          }
1270          if ($table) {
1271              $table= $this->_getFullTableName($table, $includeDb);
1272              if ($this->getDebug() === true) $this->log(xPDO::LOG_LEVEL_DEBUG, 'Returning table name: ' . $table . ' for class: ' . $className);
1273          } else {
1274              $this->log(xPDO::LOG_LEVEL_ERROR, 'Could not get table name for class: ' . $className);
1275          }
1276          return $table;
1277      }
1278  
1279      /**
1280       * Get the class which defines the table for a specified className.
1281       *
1282       * @param string $className The name of a class to determine the table class from.
1283       * @return null|string The name of a class defining the table for the specified className; null if not found.
1284       */
1285      public function getTableClass($className) {
1286          $tableClass= null;
1287          if ($className= $this->loadClass($className)) {
1288              if (isset ($this->map[$className]['table'])) {
1289                  $tableClass= $className;
1290              }
1291              if (!$tableClass && $ancestry= $this->getAncestry($className, false)) {
1292                  foreach ($ancestry as $ancestor) {
1293                      if (isset ($this->map[$ancestor]['table'])) {
1294                          $tableClass= $ancestor;
1295                          break;
1296                      }
1297                  }
1298              }
1299          }
1300          if ($tableClass) {
1301              if ($this->getDebug() === true) {
1302                  $this->log(xPDO::LOG_LEVEL_DEBUG, 'Returning table class: ' . $tableClass . ' for class: ' . $className);
1303              }
1304          } else {
1305              $this->log(xPDO::LOG_LEVEL_ERROR, 'Could not get table class for class: ' . $className);
1306          }
1307          return $tableClass;
1308      }
1309  
1310      /**
1311       * Gets the actual run-time table metadata from a specified class name.
1312       *
1313       * @param string $className The name of the class to lookup a table name
1314       * for.
1315       * @return string The table meta data for the class, or null if
1316       * unsuccessful.
1317       */
1318      public function getTableMeta($className) {
1319          $tableMeta= null;
1320          if ($className= $this->loadClass($className)) {
1321              if (isset ($this->map[$className]['tableMeta'])) {
1322                  $tableMeta= $this->map[$className]['tableMeta'];
1323              }
1324              if (!$tableMeta && $ancestry= $this->getAncestry($className)) {
1325                  foreach ($ancestry as $ancestor) {
1326                      if (isset ($this->map[$ancestor]['tableMeta'])) {
1327                          if ($tableMeta= $this->map[$ancestor]['tableMeta']) {
1328                              break;
1329                          }
1330                      }
1331                  }
1332              }
1333          }
1334          return $tableMeta;
1335      }
1336  
1337      /**
1338       * Indicates the inheritance model for the xPDOObject class specified.
1339       *
1340       * @param string $className The class to determine the table inherit type from.
1341       * @return string single, multiple, or none
1342       */
1343      public function getInherit($className) {
1344          $inherit= false;
1345          if ($className= $this->loadClass($className)) {
1346              if (isset ($this->map[$className]['inherit'])) {
1347                  $inherit= $this->map[$className]['inherit'];
1348              }
1349              if (!$inherit && $ancestry= $this->getAncestry($className, false)) {
1350                  foreach ($ancestry as $ancestor) {
1351                      if (isset ($this->map[$ancestor]['inherit'])) {
1352                          $inherit= $this->map[$ancestor]['inherit'];
1353                          break;
1354                      }
1355                  }
1356              }
1357          }
1358          if (!empty($inherit)) {
1359              if ($this->getDebug() === true) {
1360                  $this->log(xPDO::LOG_LEVEL_DEBUG, 'Returning inherit: ' . $inherit . ' for class: ' . $className);
1361              }
1362          } else {
1363              $inherit= 'none';
1364          }
1365          return $inherit;
1366      }
1367  
1368      /**
1369       * Gets a list of fields (or columns) for an object by class name.
1370       *
1371       * This includes default values for each field and is used by the objects
1372       * themselves to build their initial attributes based on class inheritence.
1373       *
1374       * @param string $className The name of the class to lookup fields for.
1375       * @return array An array featuring field names as the array keys, and
1376       * default field values as the array values; empty array is returned if
1377       * unsuccessful.
1378       */
1379      public function getFields($className) {
1380          $fields= array ();
1381          if ($className= $this->loadClass($className)) {
1382              if ($ancestry= $this->getAncestry($className)) {
1383                  for ($i= count($ancestry) - 1; $i >= 0; $i--) {
1384                      if (isset ($this->map[$ancestry[$i]]['fields'])) {
1385                          $fields= array_merge($fields, $this->map[$ancestry[$i]]['fields']);
1386                      }
1387                  }
1388              }
1389              if ($this->getInherit($className) === 'single') {
1390                  $descendants= $this->getDescendants($className);
1391                  if ($descendants) {
1392                      foreach ($descendants as $descendant) {
1393                          $descendantClass= $this->loadClass($descendant);
1394                          if ($descendantClass && isset($this->map[$descendantClass]['fields'])) {
1395                              $fields= array_merge($fields, array_diff_key($this->map[$descendantClass]['fields'], $fields));
1396                          }
1397                      }
1398                  }
1399              }
1400          }
1401          return $fields;
1402      }
1403  
1404      /**
1405       * Gets a list of field (or column) definitions for an object by class name.
1406       *
1407       * These definitions are used by the objects themselves to build their
1408       * own meta data based on class inheritance.
1409       *
1410       * @param string $className The name of the class to lookup fields meta data
1411       * for.
1412       * @param boolean $includeExtended If true, include meta from all derivative
1413       * classes in loaded packages.
1414       * @return array An array featuring field names as the array keys, and
1415       * arrays of metadata information as the array values; empty array is
1416       * returned if unsuccessful.
1417       */
1418      public function getFieldMeta($className, $includeExtended = false) {
1419          $fieldMeta= array ();
1420          if ($className= $this->loadClass($className)) {
1421              if ($ancestry= $this->getAncestry($className)) {
1422                  for ($i= count($ancestry) - 1; $i >= 0; $i--) {
1423                      if (isset ($this->map[$ancestry[$i]]['fieldMeta'])) {
1424                          $fieldMeta= array_merge($fieldMeta, $this->map[$ancestry[$i]]['fieldMeta']);
1425                      }
1426                  }
1427              }
1428              if ($includeExtended && $this->getInherit($className) === 'single') {
1429                  $descendants= $this->getDescendants($className);
1430                  if ($descendants) {
1431                      foreach ($descendants as $descendant) {
1432                          $descendantClass= $this->loadClass($descendant);
1433                          if ($descendantClass && isset($this->map[$descendantClass]['fieldMeta'])) {
1434                              $fieldMeta= array_merge($fieldMeta, array_diff_key($this->map[$descendantClass]['fieldMeta'], $fieldMeta));
1435                          }
1436                      }
1437                  }
1438              }
1439          }
1440          return $fieldMeta;
1441      }
1442  
1443      /**
1444       * Gets a collection of field aliases for an object by class name.
1445       *
1446       * @param string $className The name of the class to lookup field aliases for.
1447       * @return array An array of field aliases with aliases as keys and actual field names as values.
1448       */
1449      public function getFieldAliases($className) {
1450          $fieldAliases= array ();
1451          if ($className= $this->loadClass($className)) {
1452              if ($ancestry= $this->getAncestry($className)) {
1453                  for ($i= count($ancestry) - 1; $i >= 0; $i--) {
1454                      if (isset ($this->map[$ancestry[$i]]['fieldAliases'])) {
1455                          $fieldAliases= array_merge($fieldAliases, $this->map[$ancestry[$i]]['fieldAliases']);
1456                      }
1457                  }
1458              }
1459              if ($this->getInherit($className) === 'single') {
1460                  $descendants= $this->getDescendants($className);
1461                  if ($descendants) {
1462                      foreach ($descendants as $descendant) {
1463                          $descendantClass= $this->loadClass($descendant);
1464                          if ($descendantClass && isset($this->map[$descendantClass]['fieldAliases'])) {
1465                              $fieldAliases= array_merge($fieldAliases, array_diff_key($this->map[$descendantClass]['fieldAliases'], $fieldAliases));
1466                          }
1467                      }
1468                  }
1469              }
1470          }
1471          return $fieldAliases;
1472      }
1473  
1474      /**
1475       * Gets a set of validation rules defined for an object by class name.
1476       *
1477       * @param string $className The name of the class to lookup validation rules
1478       * for.
1479       * @return array An array featuring field names as the array keys, and
1480       * arrays of validation rule information as the array values; empty array is
1481       * returned if unsuccessful.
1482       */
1483      public function getValidationRules($className) {
1484          $rules= array();
1485          if ($className= $this->loadClass($className)) {
1486              if ($ancestry= $this->getAncestry($className)) {
1487                  for ($i= count($ancestry) - 1; $i >= 0; $i--) {
1488                      if (isset($this->map[$ancestry[$i]]['validation']['rules'])) {
1489                          $rules= array_merge($rules, $this->map[$ancestry[$i]]['validation']['rules']);
1490                      }
1491                  }
1492              }
1493              if ($this->getInherit($className) === 'single') {
1494                  $descendants= $this->getDescendants($className);
1495                  if ($descendants) {
1496                      foreach ($descendants as $descendant) {
1497                          $descendantClass= $this->loadClass($descendant);
1498                          if ($descendantClass && isset($this->map[$descendantClass]['validation']['rules'])) {
1499                              $rules= array_merge($rules, array_diff_key($this->map[$descendantClass]['validation']['rules'], $rules));
1500                          }
1501                      }
1502                  }
1503              }
1504              if ($this->getDebug() === true) {
1505                  $this->log(xPDO::LOG_LEVEL_DEBUG, "Returning validation rules: " . print_r($rules, true));
1506              }
1507          }
1508          return $rules;
1509      }
1510  
1511      /**
1512       * Get indices defined for a table class.
1513       *
1514       * @param string $className The name of the class to lookup indices for.
1515       * @return array An array of indices and their details for the specified class.
1516       */
1517      public function getIndexMeta($className) {
1518          $indices= array();
1519          if ($className= $this->loadClass($className)) {
1520              if ($ancestry= $this->getAncestry($className)) {
1521                  for ($i= count($ancestry) -1; $i >= 0; $i--) {
1522                      if (isset($this->map[$ancestry[$i]]['indexes'])) {
1523                          $indices= array_merge($indices, $this->map[$ancestry[$i]]['indexes']);
1524                      }
1525                  }
1526                  if ($this->getInherit($className) === 'single') {
1527                      $descendants= $this->getDescendants($className);
1528                      if ($descendants) {
1529                          foreach ($descendants as $descendant) {
1530                              $descendantClass= $this->loadClass($descendant);
1531                              if ($descendantClass && isset($this->map[$descendantClass]['indexes'])) {
1532                                  $indices= array_merge($indices, array_diff_key($this->map[$descendantClass]['indexes'], $indices));
1533                              }
1534                          }
1535                      }
1536                  }
1537                  if ($this->getDebug() === true) {
1538                      $this->log(xPDO::LOG_LEVEL_DEBUG, "Returning indices: " . print_r($indices, true));
1539                  }
1540              }
1541          }
1542          return $indices;
1543      }
1544  
1545      /**
1546       * Gets the primary key field(s) for a class.
1547       *
1548       * @param string $className The name of the class to lookup the primary key
1549       * for.
1550       * @return mixed The name of the field representing a class instance primary
1551       * key, an array of key names for compound primary keys, or null if no
1552       * primary key is found or defined for the class.
1553       */
1554      public function getPK($className) {
1555          $pk= null;
1556          if (strcasecmp($className, 'xPDOObject') !== 0) {
1557              if ($actualClassName= $this->loadClass($className)) {
1558                  if (isset ($this->map[$actualClassName]['indexes'])) {
1559                      foreach ($this->map[$actualClassName]['indexes'] as $k => $v) {
1560                          if (isset ($this->map[$actualClassName]['fieldMeta'][$k]['phptype'])) {
1561                              if (isset ($v['primary']) && $v['primary'] == true) {
1562                                  $pk[$k]= $k;
1563                              }
1564                          }
1565                      }
1566                  }
1567                  if (isset ($this->map[$actualClassName]['fieldMeta'])) {
1568                      foreach ($this->map[$actualClassName]['fieldMeta'] as $k => $v) {
1569                          if (isset ($v['index']) && isset ($v['phptype']) && $v['index'] == 'pk') {
1570                              $pk[$k]= $k;
1571                          }
1572                      }
1573                  }
1574                  if ($ancestry= $this->getAncestry($actualClassName)) {
1575                      foreach ($ancestry as $ancestor) {
1576                          if ($ancestorClassName= $this->loadClass($ancestor)) {
1577                              if (isset ($this->map[$ancestorClassName]['indexes'])) {
1578                                  foreach ($this->map[$ancestorClassName]['indexes'] as $k => $v) {
1579                                      if (isset ($this->map[$ancestorClassName]['fieldMeta'][$k]['phptype'])) {
1580                                          if (isset ($v['primary']) && $v['primary'] == true) {
1581                                              $pk[$k]= $k;
1582                                          }
1583                                      }
1584                                  }
1585                              }
1586                              if (isset ($this->map[$ancestorClassName]['fieldMeta'])) {
1587                                  foreach ($this->map[$ancestorClassName]['fieldMeta'] as $k => $v) {
1588                                      if (isset ($v['index']) && isset ($v['phptype']) && $v['index'] == 'pk') {
1589                                          $pk[$k]= $k;
1590                                      }
1591                                  }
1592                              }
1593                          }
1594                      }
1595                  }
1596                  if ($pk && count($pk) === 1) {
1597                      $pk= current($pk);
1598                  }
1599              } else {
1600                  $this->log(xPDO::LOG_LEVEL_ERROR, "Could not load class {$className}");
1601              }
1602          }
1603          return $pk;
1604      }
1605  
1606      /**
1607       * Gets the type of primary key field for a class.
1608       *
1609       * @param string $className The name of the class to lookup the primary key
1610       * type for.
1611       * @param mixed $pk Optional specific PK column or columns to get type(s) for.
1612       * @return string The type of the field representing a class instance primary
1613       * key, or null if no primary key is found or defined for the class.
1614       */
1615      public function getPKType($className, $pk= false) {
1616          $pktype= null;
1617          if ($actualClassName= $this->loadClass($className)) {
1618              if (!$pk)
1619                  $pk= $this->getPK($actualClassName);
1620              if (!is_array($pk))
1621                  $pk= array($pk);
1622              $ancestry= $this->getAncestry($actualClassName, true);
1623              foreach ($pk as $_pk) {
1624                  foreach ($ancestry as $parentClass) {
1625                      if (isset ($this->map[$parentClass]['fieldMeta'][$_pk]['phptype'])) {
1626                          $pktype[$_pk]= $this->map[$parentClass]['fieldMeta'][$_pk]['phptype'];
1627                          break;
1628                      }
1629                  }
1630              }
1631              if (is_array($pktype) && count($pktype) == 1) {
1632                  $pktype= reset($pktype);
1633              }
1634              elseif (empty($pktype)) {
1635                  $pktype= null;
1636              }
1637          } else {
1638              $this->log(xPDO::LOG_LEVEL_ERROR, "Could not load class {$className}!");
1639          }
1640          return $pktype;
1641      }
1642  
1643      /**
1644       * Gets a collection of aggregate foreign key relationship definitions.
1645       *
1646       * @param string $className The fully-qualified name of the class.
1647       * @return array An array of aggregate foreign key relationship definitions.
1648       */
1649      public function getAggregates($className) {
1650          $aggregates= array ();
1651          if ($className= $this->loadClass($className)) {
1652              if ($ancestry= $this->getAncestry($className)) {
1653                  for ($i= count($ancestry) - 1; $i >= 0; $i--) {
1654                      if (isset ($this->map[$ancestry[$i]]['aggregates'])) {
1655                          $aggregates= array_merge($aggregates, $this->map[$ancestry[$i]]['aggregates']);
1656                      }
1657                  }
1658              }
1659              if ($this->getInherit($className) === 'single') {
1660                  $descendants= $this->getDescendants($className);
1661                  if ($descendants) {
1662                      foreach ($descendants as $descendant) {
1663                          $descendantClass= $this->loadClass($descendant);
1664                          if ($descendantClass && isset($this->map[$descendantClass]['aggregates'])) {
1665                              $aggregates= array_merge($aggregates, array_diff_key($this->map[$descendantClass]['aggregates'], $aggregates));
1666                          }
1667                      }
1668                  }
1669              }
1670          }
1671          return $aggregates;
1672      }
1673  
1674      /**
1675       * Gets a collection of composite foreign key relationship definitions.
1676       *
1677       * @param string $className The fully-qualified name of the class.
1678       * @return array An array of composite foreign key relationship definitions.
1679       */
1680      public function getComposites($className) {
1681          $composites= array ();
1682          if ($className= $this->loadClass($className)) {
1683              if ($ancestry= $this->getAncestry($className)) {
1684                  for ($i= count($ancestry) - 1; $i >= 0; $i--) {
1685                      if (isset ($this->map[$ancestry[$i]]['composites'])) {
1686                          $composites= array_merge($composites, $this->map[$ancestry[$i]]['composites']);
1687                      }
1688                  }
1689              }
1690              if ($this->getInherit($className) === 'single') {
1691                  $descendants= $this->getDescendants($className);
1692                  if ($descendants) {
1693                      foreach ($descendants as $descendant) {
1694                          $descendantClass= $this->loadClass($descendant);
1695                          if ($descendantClass && isset($this->map[$descendantClass]['composites'])) {
1696                              $composites= array_merge($composites, array_diff_key($this->map[$descendantClass]['composites'], $composites));
1697                          }
1698                      }
1699                  }
1700              }
1701          }
1702          return $composites;
1703      }
1704  
1705      /**
1706       * Get a complete relation graph for an xPDOObject class.
1707       *
1708       * @param string $className A fully-qualified xPDOObject class name.
1709       * @param int $depth The depth to retrieve relations for the graph, defaults to 3.
1710       * @param array &$parents An array of parent classes to avoid traversing circular dependencies.
1711       * @param array &$visited An array of already visited classes to avoid traversing circular dependencies.
1712       * @return array An xPDOObject relation graph, or an empty array if no graph can be constructed.
1713       */
1714      public function getGraph($className, $depth= 3, &$parents = array(), &$visited = array()) {
1715          $graph = array();
1716          $className = $this->loadClass($className);
1717          if ($className && $depth > 0) {
1718              $depth--;
1719              $parents = array_merge($parents, $this->getAncestry($className));
1720              $parentsNested = array_unique($parents);
1721              $visitNested = array_merge($visited, array($className));
1722              $relations = array_merge($this->getAggregates($className), $this->getComposites($className));
1723              foreach ($relations as $alias => $relation) {
1724                  if (in_array($relation['class'], $visited)) {
1725                      continue;
1726                  }
1727                  $childGraph = array();
1728                  if ($depth > 0 && !in_array($relation['class'], $parents)) {
1729                      $childGraph = $this->getGraph($relation['class'], $depth, $parentsNested, $visitNested);
1730                  }
1731                  $graph[$alias] = $childGraph;
1732              }
1733              $visited[] = $className;
1734          }
1735          return $graph;
1736      }
1737  
1738      /**
1739       * Retrieves the complete ancestry for a class.
1740       *
1741       * @param string $className The name of the class.
1742       * @param bool $includeSelf Determines if the specified class should be
1743       * included in the resulting array.
1744       * @return array An array of string class names representing the class
1745       * hierarchy, or an empty array if unsuccessful.
1746       */
1747      public function getAncestry($className, $includeSelf= true) {
1748          $ancestry= array ();
1749          if ($actualClassName= $this->loadClass($className)) {
1750              $ancestor= $actualClassName;
1751              if ($includeSelf) {
1752                  $ancestry[]= $actualClassName;
1753              }
1754              while ($ancestor= get_parent_class($ancestor)) {
1755                  $ancestry[]= $ancestor;
1756              }
1757              if ($this->getDebug() === true) {
1758                  $this->log(xPDO::LOG_LEVEL_DEBUG, "Returning ancestry for {$className}: " . print_r($ancestry, 1));
1759              }
1760          }
1761          return $ancestry;
1762      }
1763  
1764      /**
1765       * Gets select columns from a specific class for building a query.
1766       *
1767       * @uses xPDOObject::getSelectColumns()
1768       * @param string $className The name of the class to build the column list
1769       * from.
1770       * @param string $tableAlias An optional alias for the class table, to be
1771       * used in complex queries with multiple tables.
1772       * @param string $columnPrefix An optional string with which to prefix the
1773       * columns returned, to avoid name collisions in return columns.
1774       * @param array $columns An optional array of columns to include.
1775       * @param boolean $exclude If true, will exclude columns in the previous
1776       * parameter, instead of including them.
1777       * @return string A valid SQL string of column names for a SELECT statement.
1778       */
1779      public function getSelectColumns($className, $tableAlias= '', $columnPrefix= '', $columns= array (), $exclude= false) {
1780          return $this->call($className, 'getSelectColumns', array(&$this, $className, $tableAlias, $columnPrefix, $columns, $exclude));
1781      }
1782  
1783      /**
1784       * Gets an aggregate or composite relation definition from a class.
1785       *
1786       * @param string $parentClass The class from which the relation is defined.
1787       * @param string $alias The alias identifying the related class.
1788       * @return array The aggregate or composite definition details in an array
1789       * or null if no definition is found.
1790       */
1791      function getFKDefinition($parentClass, $alias) {
1792          $def= null;
1793          $parentClass= $this->loadClass($parentClass);
1794          if ($parentClass && $alias) {
1795              if ($aggregates= $this->getAggregates($parentClass)) {
1796                  if (isset ($aggregates[$alias])) {
1797                      $def= $aggregates[$alias];
1798                      $def['type']= 'aggregate';
1799                  }
1800              }
1801              if ($composites= $this->getComposites($parentClass)) {
1802                  if (isset ($composites[$alias])) {
1803                      $def= $composites[$alias];
1804                      $def['type']= 'composite';
1805                  }
1806              }
1807          }
1808          if ($def === null) {
1809              $this->log(xPDO::LOG_LEVEL_ERROR, 'No foreign key definition for parentClass: ' . $parentClass . ' using relation alias: ' . $alias);
1810          }
1811          return $def;
1812      }
1813  
1814      /**
1815       * Gets the version string of the schema the specified class was generated from.
1816       *
1817       * @param string $className The name of the class to get the model version from.
1818       * @return string The version string for the schema model the class was generated from.
1819       */
1820      public function getModelVersion($className) {
1821          $version = '1.0';
1822          $className= $this->loadClass($className);
1823          if ($className && isset($this->map[$className]['version'])) {
1824              $version= $this->map[$className]['version'];
1825          }
1826          return $version;
1827      }
1828  
1829      /**
1830       * Gets the manager class for this xPDO connection.
1831       *
1832       * The manager class can perform operations such as creating or altering
1833       * table structures, creating data containers, generating custom persistence
1834       * classes, and other advanced operations that do not need to be loaded
1835       * frequently.
1836       *
1837       * @return xPDOManager|null An xPDOManager instance for the xPDO connection, or null
1838       * if a manager class can not be instantiated.
1839       */
1840      public function getManager() {
1841          if ($this->manager === null || !$this->manager instanceof xPDOManager) {
1842              $loaded= include_once(XPDO_CORE_PATH . 'om/' . $this->config['dbtype'] . '/xpdomanager.class.php');
1843              if ($loaded) {
1844                  $managerClass = 'xPDOManager_' . $this->config['dbtype'];
1845                  $this->manager= new $managerClass ($this);
1846              }
1847              if (!$this->manager) {
1848                  $this->log(xPDO::LOG_LEVEL_ERROR, "Could not load xPDOManager class.");
1849              }
1850          }
1851          return $this->manager;
1852      }
1853  
1854      /**
1855       * Gets the driver class for this xPDO connection.
1856       *
1857       * The driver class provides baseline data and operations for a specific database driver.
1858       *
1859       * @return xPDODriver|null An xPDODriver instance for the xPDO connection, or null
1860       * if a driver class can not be instantiated.
1861       */
1862      public function getDriver() {
1863          if ($this->driver === null || !$this->driver instanceof xPDODriver) {
1864              $loaded= include_once(XPDO_CORE_PATH . 'om/' . $this->config['dbtype'] . '/xpdodriver.class.php');
1865              if ($loaded) {
1866                  $driverClass = 'xPDODriver_' . $this->config['dbtype'];
1867                  $this->driver= new $driverClass ($this);
1868              }
1869              if (!$this->driver) {
1870                  $this->log(xPDO::LOG_LEVEL_ERROR, "Could not load xPDODriver class for the {$this->config['dbtype']} PDO driver. " . print_r($this->config, true));
1871              }
1872          }
1873          return $this->driver;
1874      }
1875  
1876      /**
1877       * Gets the absolute path to the cache directory.
1878       *
1879       * @return string The full cache directory path.
1880       */
1881      public function getCachePath() {
1882          if (!$this->cachePath) {
1883              if ($this->getCacheManager()) {
1884                  $this->cachePath= $this->cacheManager->getCachePath();
1885              }
1886          }
1887          return $this->cachePath;
1888      }
1889  
1890      /**
1891       * Gets an xPDOCacheManager instance.
1892       *
1893       * This class is responsible for handling all types of caching operations for the xPDO core.
1894       *
1895       * @param string $class Optional name of a derivative xPDOCacheManager class.
1896       * @param array $options An array of options for the cache manager instance; valid options include:
1897       *  - path = Optional root path for looking up the $class.
1898       *  - ignorePkg = If false and you do not specify a path, you can look up custom xPDOCacheManager
1899       *      derivatives in declared packages.
1900       * @return xPDOCacheManager The xPDOCacheManager for this xPDO instance.
1901       */
1902      public function getCacheManager($class= 'cache.xPDOCacheManager', $options = array('path' => XPDO_CORE_PATH, 'ignorePkg' => true)) {
1903          $actualClass = $this->loadClass($class, $options['path'], $options['ignorePkg'], true);
1904          if ($this->cacheManager === null || !is_object($this->cacheManager) || !($this->cacheManager instanceof $actualClass)) {
1905              if ($this->cacheManager= new $actualClass($this, $options)) {
1906                      $this->_cacheEnabled= true;
1907              }
1908          }
1909          return $this->cacheManager;
1910      }
1911  
1912      /**
1913       * Returns the debug state for the xPDO instance.
1914       *
1915       * @return boolean The current debug state for the instance, true for on,
1916       * false for off.
1917       */
1918      public function getDebug() {
1919          return $this->_debug;
1920      }
1921  
1922      /**
1923       * Sets the debug state for the xPDO instance.
1924       *
1925       * @param boolean|integer $v The debug status, true for on, false for off, or a valid
1926       * error_reporting level for PHP.
1927       */
1928      public function setDebug($v= true) {
1929          $this->_debug= $v;
1930      }
1931  
1932      /**
1933       * Sets the logging level state for the xPDO instance.
1934       *
1935       * @param integer $level The logging level to switch to.
1936       * @return integer The previous log level.
1937       */
1938      public function setLogLevel($level= xPDO::LOG_LEVEL_FATAL) {
1939          $oldLevel = $this->logLevel;
1940          $this->logLevel= intval($level);
1941          return $oldLevel;
1942      }
1943  
1944      /**
1945       * @return integer The current log level.
1946       */
1947      public function getLogLevel() {
1948          return $this->logLevel;
1949      }
1950  
1951      /**
1952       * Sets the log target for xPDO::_log() calls.
1953       *
1954       * Valid target values include:
1955       * <ul>
1956       * <li>'ECHO': Returns output to the STDOUT.</li>
1957       * <li>'HTML': Returns output to the STDOUT with HTML formatting.</li>
1958       * <li>'FILE': Sends output to a log file.</li>
1959       * <li>An array with at least one element with key 'target' matching
1960       * one of the valid log targets listed above. For 'target' => 'FILE'
1961       * you can specify a second element with key 'options' with another
1962       * associative array with one or both of the elements 'filename' and
1963       * 'filepath'</li>
1964       * </ul>
1965       *
1966       * @param string $target An identifier indicating the target of the logging.
1967       * @return mixed The previous log target.
1968       */
1969      public function setLogTarget($target= 'ECHO') {
1970          $oldTarget = $this->logTarget;
1971          $this->logTarget= $target;
1972          return $oldTarget;
1973      }
1974  
1975      /**
1976       * @return integer The current log level.
1977       */
1978      public function getLogTarget() {
1979          return $this->logTarget;
1980      }
1981  
1982      /**
1983       * Log a message with details about where and when an event occurs.
1984       *
1985       * @param integer $level The level of the logged message.
1986       * @param string $msg The message to log.
1987       * @param string $target The logging target.
1988       * @param string $def The name of a defining structure (such as a class) to
1989       * help identify the message source.
1990       * @param string $file A filename in which the log event occured.
1991       * @param string $line A line number to help locate the source of the event
1992       * within the indicated file.
1993       */
1994      public function log($level, $msg, $target= '', $def= '', $file= '', $line= '') {
1995          $this->_log($level, $msg, $target, $def, $file, $line);
1996      }
1997  
1998      /**
1999       * Log a message as appropriate for the level and target.
2000       *
2001       * @param integer $level The level of the logged message.
2002       * @param string $msg The message to log.
2003       * @param string $target The logging target.
2004       * @param string $def The name of a defining structure (such as a class) to
2005       * help identify the log event source.
2006       * @param string $file A filename in which the log event occured.
2007       * @param string $line A line number to help locate the source of the event
2008       * within the indicated file.
2009       */
2010      protected function _log($level, $msg, $target= '', $def= '', $file= '', $line= '') {
2011          if (empty ($target)) {
2012              $target = $this->logTarget;
2013          }
2014          $targetOptions = array();
2015          if (is_array($target)) {
2016              if (isset($target['options'])) $targetOptions =& $target['options'];
2017              $target = isset($target['target']) ? $target['target'] : 'ECHO';
2018          }
2019          if (empty($file) && isset($_SERVER['SCRIPT_NAME'])) {
2020              $file= $_SERVER['SCRIPT_NAME'];
2021          }
2022          if ($level === xPDO::LOG_LEVEL_FATAL) {
2023              while (ob_get_level() && @ob_end_flush()) {}
2024              exit ('[' . strftime('%Y-%m-%d %H:%M:%S') . '] (' . $this->_getLogLevel($level) . $def . $file . $line . ') ' . $msg . "\n" . ($this->getDebug() === true ? '<pre>' . "\n" . print_r(debug_backtrace(), true) . "\n" . '</pre>' : ''));
2025          }
2026          if ($this->_debug === true || $level <= $this->logLevel) {
2027              @ob_start();
2028              if (!empty ($def)) {
2029                  $def= " in {$def}";
2030              }
2031              if (!empty ($file)) {
2032                  $file= " @ {$file}";
2033              }
2034              if (!empty ($line)) {
2035                  $line= " : {$line}";
2036              }
2037              switch ($target) {
2038                  case 'HTML' :
2039                      echo '<h5>[' . strftime('%Y-%m-%d %H:%M:%S') . '] (' . $this->_getLogLevel($level) . $def . $file . $line . ')</h5><pre>' . $msg . '</pre>' . "\n";
2040                      break;
2041                  default :
2042                      echo '[' . strftime('%Y-%m-%d %H:%M:%S') . '] (' . $this->_getLogLevel($level) . $def . $file . $line . ') ' . $msg . "\n";
2043              }
2044              $content= @ob_get_contents();
2045              @ob_end_clean();
2046              if ($target=='FILE' && $this->getCacheManager()) {
2047                  $filename = isset($targetOptions['filename']) ? $targetOptions['filename'] : 'error.log';
2048                  $filepath = isset($targetOptions['filepath']) ? $targetOptions['filepath'] : $this->getCachePath() . xPDOCacheManager::LOG_DIR;
2049                  $this->cacheManager->writeFile($filepath . $filename, $content, 'a');
2050              } elseif ($target=='ARRAY' && isset($targetOptions['var']) && is_array($targetOptions['var'])) {
2051                  $targetOptions['var'][] = $content;
2052              } else {
2053                  echo $content;
2054              }
2055          }
2056      }
2057  
2058      /**
2059       * Returns an abbreviated backtrace of debugging information.
2060       *
2061       * This function returns just the fields returned via xPDOObject::toArray()
2062       * on xPDOObject instances, and simply the classname for other objects, to
2063       * reduce the amount of unnecessary information returned.
2064       *
2065       * @return array The abbreviated backtrace.
2066       */
2067      public function getDebugBacktrace() {
2068          $backtrace= array ();
2069          foreach (debug_backtrace() as $levelKey => $levelElement) {
2070              foreach ($levelElement as $traceKey => $traceElement) {
2071                  if ($traceKey == 'object' && $traceElement instanceof xPDOObject) {
2072                      $backtrace[$levelKey][$traceKey]= $traceElement->toArray('', true);
2073                  } elseif ($traceKey == 'object') {
2074                      $backtrace[$levelKey][$traceKey]= get_class($traceElement);
2075                  } else {
2076                      $backtrace[$levelKey][$traceKey]= $traceElement;
2077                  }
2078              }
2079          }
2080          return $backtrace;
2081      }
2082  
2083      /**
2084       * Gets a logging level as a string representation.
2085       *
2086       * @param integer $level The logging level to retrieve a string for.
2087       * @return string The string representation of a valid logging level.
2088       */
2089      protected function _getLogLevel($level) {
2090          switch ($level) {
2091              case xPDO::LOG_LEVEL_DEBUG :
2092                  $levelText= 'DEBUG';
2093                  break;
2094              case xPDO::LOG_LEVEL_INFO :
2095                  $levelText= 'INFO';
2096                  break;
2097              case xPDO::LOG_LEVEL_WARN :
2098                  $levelText= 'WARN';
2099                  break;
2100              case xPDO::LOG_LEVEL_ERROR :
2101                  $levelText= 'ERROR';
2102                  break;
2103              default :
2104                  $levelText= 'FATAL';
2105          }
2106          return $levelText;
2107      }
2108  
2109      /**
2110       * Escapes the provided string using the platform-specific escape character.
2111       *
2112       * Different database engines escape string literals in SQL using different characters. For example, this is used to
2113       * escape column names that might match a reserved string for that SQL interpreter. To write database agnostic
2114       * queries with xPDO, it is highly recommend to escape any database or column names in any native SQL strings used.
2115       *
2116       * @param string $string A string to escape using the platform-specific escape characters.
2117       * @return string The string escaped with the platform-specific escape characters.
2118       */
2119      public function escape($string) {
2120          $string = trim($string, $this->_escapeCharOpen . $this->_escapeCharClose);
2121          return $this->_escapeCharOpen . $string . $this->_escapeCharClose;
2122      }
2123  
2124      /**
2125       * Use to insert a literal string into a SQL query without escaping or quoting.
2126       *
2127       * @param string $string A string to return as a literal, unescaped and unquoted.
2128       * @return string The string with any escape or quote characters trimmed.
2129       */
2130      public function literal($string) {
2131          $string = trim($string, $this->_escapeCharOpen . $this->_escapeCharClose . $this->_quoteChar);
2132          return $string;
2133      }
2134  
2135      /**
2136       * Adds the table prefix, and optionally database name, to a given table.
2137       *
2138       * @param string $baseTableName The table name as specified in the object
2139       * model.
2140       * @param boolean $includeDb Qualify the table name with the database name.
2141       * @return string The fully-qualified and quoted table name for the
2142       */
2143      private function _getFullTableName($baseTableName, $includeDb= false) {
2144          $fqn= '';
2145          if (!empty ($baseTableName)) {
2146              if ($includeDb) {
2147                  $fqn .= $this->escape($this->config['dbname']) . '.';
2148              }
2149              $fqn .= $this->escape($baseTableName);
2150          }
2151          return $fqn;
2152      }
2153  
2154      /**
2155       * Parses a DSN and returns an array of the connection details.
2156       *
2157       * @static
2158       * @param string $string The DSN to parse.
2159       * @return array An array of connection details from the DSN.
2160       * @todo Have this method handle all methods of DSN specification as handled
2161       * by latest native PDO implementation.
2162       */
2163      public static function parseDSN($string) {
2164          $result= array ();
2165          $pos= strpos($string, ':');
2166          $result['dbtype']= strtolower(substr($string, 0, $pos));
2167          $parameters= explode(';', substr($string, ($pos +1)));
2168          for ($a= 0, $b= count($parameters); $a < $b; $a++) {
2169              $tmp= explode('=', $parameters[$a]);
2170              if (count($tmp) == 2) {
2171                  $result[strtolower(trim($tmp[0]))]= trim($tmp[1]);
2172              } else {
2173                  $result['dbname']= trim($parameters[$a]);
2174              }
2175          }
2176          if (!isset($result['dbname']) && isset($result['database'])) {
2177              $result['dbname'] = $result['database'];
2178          }
2179          if (!isset($result['host']) && isset($result['server'])) {
2180              $result['host'] = $result['server'];
2181          }
2182          return $result;
2183      }
2184  
2185      /**
2186       * Retrieves a result array from the object cache.
2187       *
2188       * @param string|xPDOCriteria $signature A unique string or xPDOCriteria object
2189       * that represents the query identifying the result set.
2190       * @param string $class An optional classname the result represents.
2191       * @param array $options Various cache options.
2192       * @return array|string|null A PHP array or JSON object representing the
2193       * result set, or null if no cache representation is found.
2194       */
2195      public function fromCache($signature, $class= '', $options= array()) {
2196          $result= null;
2197          if ($this->getOption(xPDO::OPT_CACHE_DB, $options)) {
2198              if ($signature && $this->getCacheManager()) {
2199                  $sig= '';
2200                  $sigKey= array();
2201                  $sigHash= '';
2202                  $sigClass= empty($class) || !is_string($class) ? '' : $class;
2203                  if (is_object($signature)) {
2204                      if ($signature instanceof xPDOCriteria) {
2205                          if ($signature instanceof xPDOQuery) {
2206                              $signature->construct();
2207                              if (empty($sigClass)) $sigClass= $signature->getTableClass();
2208                          }
2209                          $sigKey= array ($signature->sql, $signature->bindings);
2210                      }
2211                  }
2212                  elseif (is_string($signature)) {
2213                      if ($exploded= explode('_', $signature)) {
2214                          $class= reset($exploded);
2215                          if (empty($sigClass) || $sigClass !== $class) {
2216                              $sigClass= $class;
2217                          }
2218                          if (empty($sigKey)) {
2219                              while ($key= next($exploded)) {
2220                                  $sigKey[]= $key;
2221                              }
2222                          }
2223                      }
2224                  }
2225                  if (empty($sigClass)) $sigClass= '__sqlResult';
2226                  if ($sigClass && $sigKey) {
2227                      $sigHash= md5($this->toJSON($sigKey));
2228                      $sig= implode('/', array ($sigClass, $sigHash));
2229                  }
2230                  if (is_string($sig) && !empty($sig)) {
2231                      $result= $this->cacheManager->get($sig, array(
2232                          xPDO::OPT_CACHE_KEY => $this->getOption('cache_db_key', $options, 'db'),
2233                          xPDO::OPT_CACHE_HANDLER => $this->getOption(xPDO::OPT_CACHE_DB_HANDLER, $options, $this->getOption(xPDO::OPT_CACHE_HANDLER, $options, 'cache.xPDOFileCache')),
2234                          xPDO::OPT_CACHE_FORMAT => (integer) $this->getOption('cache_db_format', null, $this->getOption(xPDO::OPT_CACHE_FORMAT, null, xPDOCacheManager::CACHE_PHP)),
2235                          'cache_prefix' => $this->getOption('cache_db_prefix', $options, xPDOCacheManager::CACHE_DIR),
2236                      ));
2237                      if ($this->getDebug() === true) {
2238                          if (!$result) {
2239                              $this->log(xPDO::LOG_LEVEL_DEBUG, 'No cache item found for class ' . $sigClass . ' with signature ' . xPDOCacheManager::CACHE_DIR . $sig);
2240                          } else {
2241                              $this->log(xPDO::LOG_LEVEL_DEBUG, 'Loaded cache item for class ' . $sigClass . ' with signature ' . xPDOCacheManager::CACHE_DIR . $sig);
2242                          }
2243                      }
2244                  }
2245              }
2246          }
2247          return $result;
2248      }
2249  
2250      /**
2251       * Places a result set in the object cache.
2252       *
2253       * @param string|xPDOCriteria $signature A unique string or xPDOCriteria object
2254       * representing the object.
2255       * @param object $object An object to place a representation of in the cache.
2256       * @param integer $lifetime An optional number of seconds the cached result
2257       * will remain valid, with 0 meaning it will remain valid until replaced or
2258       * removed.
2259       * @param array $options Various cache options.
2260       * @return boolean Indicates if the object was successfully cached.
2261       */
2262      public function toCache($signature, $object, $lifetime= 0, $options = array()) {
2263          $result= false;
2264          if ($this->getCacheManager()) {
2265              if ($this->getOption(xPDO::OPT_CACHE_DB, $options)) {
2266                  if ($lifetime === true) {
2267                      $lifetime = 0;
2268                  }
2269                  elseif (!$lifetime && $this->getOption(xPDO::OPT_CACHE_DB_EXPIRES, $options, 0)) {
2270                      $lifetime= intval($this->getOption(xPDO::OPT_CACHE_DB_EXPIRES, $options, 0));
2271                  }
2272                  $sigKey= array();
2273                  $sigClass= '';
2274                  $sigGraph= $this->getOption(xPDO::OPT_CACHE_DB_SIG_GRAPH, $options, array());
2275                  if (is_object($signature)) {
2276                      if ($signature instanceof xPDOCriteria) {
2277                          if ($signature instanceof xPDOQuery) {
2278                              $signature->construct();
2279                              if (empty($sigClass)) $sigClass = $signature->getTableClass();
2280                          }
2281                          $sigKey= array($signature->sql, $signature->bindings);
2282                      }
2283                  }
2284                  elseif (is_string($signature)) {
2285                      $exploded= explode('_', $signature);
2286                      if ($exploded && count($exploded) >= 2) {
2287                          $class= reset($exploded);
2288                          if (empty($sigClass) || $sigClass !== $class) {
2289                              $sigClass= $class;
2290                          }
2291                          if (empty($sigKey)) {
2292                              while ($key= next($exploded)) {
2293                                  $sigKey[]= $key;
2294                              }
2295                          }
2296                      }
2297                  }
2298                  if (empty($sigClass)) {
2299                      if ($object instanceof xPDOObject) {
2300                          $sigClass= $object->_class;
2301                      } else {
2302                          $sigClass= $this->getOption(xPDO::OPT_CACHE_DB_SIG_CLASS, $options, '__sqlResult');
2303                      }
2304                  }
2305                  if (empty($sigKey) && is_string($signature)) $sigKey= $signature;
2306                  if (empty($sigKey) && $object instanceof xPDOObject) $sigKey= $object->getPrimaryKey();
2307                  if ($sigClass && $sigKey) {
2308                      $sigHash= md5($this->toJSON(is_array($sigKey) ? $sigKey : array($sigKey)));
2309                      $sig= implode('/', array ($sigClass, $sigHash));
2310                      if (is_string($sig)) {
2311                          if ($this->getOption('modified', $options, false)) {
2312                              if (empty($sigGraph) && $object instanceof xPDOObject) {
2313                                  $sigGraph = array_merge(array($object->_class => array('class' => $object->_class)), $object->_aggregates, $object->_composites);
2314                              }
2315                              if (!empty($sigGraph)) {
2316                                  foreach ($sigGraph as $gAlias => $gMeta) {
2317                                      $gClass = $gMeta['class'];
2318                                      $removed= $this->cacheManager->delete($gClass, array_merge($options, array(
2319                                          xPDO::OPT_CACHE_KEY => $this->getOption('cache_db_key', $options, 'db'),
2320                                          xPDO::OPT_CACHE_HANDLER => $this->getOption(xPDO::OPT_CACHE_DB_HANDLER, $options, $this->getOption(xPDO::OPT_CACHE_HANDLER, $options, 'cache.xPDOFileCache')),
2321                                          xPDO::OPT_CACHE_FORMAT => (integer) $this->getOption('cache_db_format', $options, $this->getOption(xPDO::OPT_CACHE_FORMAT, $options, xPDOCacheManager::CACHE_PHP)),
2322                                          xPDO::OPT_CACHE_EXPIRES => (integer) $this->getOption(xPDO::OPT_CACHE_DB_EXPIRES, null, $this->getOption(xPDO::OPT_CACHE_EXPIRES, null, 0)),
2323                                          xPDO::OPT_CACHE_PREFIX => $this->getOption('cache_db_prefix', $options, xPDOCacheManager::CACHE_DIR),
2324                                          'multiple_object_delete' => true
2325                                      )));
2326                                      if ($this->getDebug() === true) {
2327                                          $this->log(xPDO::LOG_LEVEL_DEBUG, "Removing all cache objects of class {$gClass}: " . ($removed ? 'successful' : 'failed'));
2328                                      }
2329                                  }
2330                              }
2331                          }
2332                          $cacheOptions = array_merge($options, array(
2333                              xPDO::OPT_CACHE_KEY => $this->getOption('cache_db_key', $options, 'db'),
2334                              xPDO::OPT_CACHE_HANDLER => $this->getOption(xPDO::OPT_CACHE_DB_HANDLER, $options, $this->getOption(xPDO::OPT_CACHE_HANDLER, $options, 'cache.xPDOFileCache')),
2335                              xPDO::OPT_CACHE_FORMAT => (integer) $this->getOption('cache_db_format', $options, $this->getOption(xPDO::OPT_CACHE_FORMAT, $options, xPDOCacheManager::CACHE_PHP)),
2336                              xPDO::OPT_CACHE_EXPIRES => (integer) $this->getOption(xPDO::OPT_CACHE_DB_EXPIRES, null, $this->getOption(xPDO::OPT_CACHE_EXPIRES, null, 0)),
2337                              xPDO::OPT_CACHE_PREFIX => $this->getOption('cache_db_prefix', $options, xPDOCacheManager::CACHE_DIR)
2338                          ));
2339                          $result= $this->cacheManager->set($sig, $object, $lifetime, $cacheOptions);
2340                          if ($result && $object instanceof xPDOObject) {
2341                              if ($this->getDebug() === true) {
2342                                  $this->log(xPDO::LOG_LEVEL_DEBUG, "xPDO->toCache() successfully cached object with signature " . xPDOCacheManager::CACHE_DIR . $sig);
2343                              }
2344                          }
2345                          if (!$result) {
2346                              $this->log(xPDO::LOG_LEVEL_WARN, "xPDO->toCache() could not cache object with signature " . xPDOCacheManager::CACHE_DIR . $sig);
2347                          }
2348                      }
2349                  } else {
2350                      $this->log(xPDO::LOG_LEVEL_ERROR, "Object sent toCache() has an invalid signature.");
2351                  }
2352              }
2353          } else {
2354              $this->log(xPDO::LOG_LEVEL_ERROR, "Attempt to send a non-object to toCache().");
2355          }
2356          return $result;
2357      }
2358  
2359      /**
2360       * Converts a PHP array into a JSON encoded string.
2361       *
2362       * @param array $array The PHP array to convert.
2363       * @return string The JSON representation of the source array.
2364       */
2365      public function toJSON($array) {
2366          $encoded= '';
2367          if (is_array ($array)) {
2368              if (!function_exists('json_encode')) {
2369                  if (@ include_once  (XPDO_CORE_PATH . 'json/JSON.php')) {
2370                      $json = new Services_JSON();
2371                      $encoded= $json->encode($array);
2372                  }
2373              } else {
2374                  $encoded= json_encode($array);
2375              }
2376          }
2377          return $encoded;
2378      }
2379  
2380      /**
2381       * Converts a JSON source string into an equivalent PHP representation.
2382       *
2383       * @param string $src A JSON source string.
2384       * @param boolean $asArray Indicates if the result should treat objects as
2385       * associative arrays; since all JSON associative arrays are objects, the default
2386       * is true.  Set to false to have JSON objects returned as PHP objects.
2387       * @return mixed The PHP representation of the JSON source.
2388       */
2389      public function fromJSON($src, $asArray= true) {
2390          $decoded= '';
2391          if ($src) {
2392              if (!function_exists('json_decode')) {
2393                  if (@ include_once  (XPDO_CORE_PATH . 'json/JSON.php')) {
2394                      if ($asArray) {
2395                          $json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
2396                      } else {
2397                      $json = new Services_JSON();
2398                      }
2399                      $decoded= $json->decode($src);
2400                      }
2401              } else {
2402                  $decoded= json_decode($src, $asArray);
2403              }
2404          }
2405          return $decoded;
2406      }
2407  
2408      /**
2409       * @see http://php.net/manual/en/function.pdo-begintransaction.php
2410       */
2411      public function beginTransaction() {
2412          if (!$this->connect(null, array(xPDO::OPT_CONN_MUTABLE => true))) {
2413              return false;
2414          }
2415          return $this->pdo->beginTransaction();
2416      }
2417  
2418      /**
2419       * @see http://php.net/manual/en/function.pdo-commit.php
2420       */
2421      public function commit() {
2422          if (!$this->connect(null, array(xPDO::OPT_CONN_MUTABLE => true))) {
2423              return false;
2424          }
2425          return $this->pdo->commit();
2426      }
2427  
2428      /**
2429       * @see http://php.net/manual/en/function.pdo-exec.php
2430       */
2431      public function exec($query) {
2432          if (!$this->connect(null, array(xPDO::OPT_CONN_MUTABLE => true))) {
2433              return false;
2434          }
2435          $tstart= microtime(true);
2436          $return= $this->pdo->exec($query);
2437          $this->queryTime += microtime(true) - $tstart;
2438          $this->executedQueries++;
2439          return $return;
2440      }
2441  
2442      /**
2443       * @see http://php.net/manual/en/function.pdo-errorcode.php
2444       */
2445      public function errorCode() {
2446          if (!$this->connect()) {
2447              return false;
2448          }
2449          return $this->pdo->errorCode();
2450      }
2451  
2452      /**
2453       * @see http://php.net/manual/en/function.pdo-errorinfo.php
2454       */
2455      public function errorInfo() {
2456          if (!$this->connect()) {
2457              return false;
2458          }
2459          return $this->pdo->errorInfo();
2460      }
2461  
2462      /**
2463       * @see http://php.net/manual/en/function.pdo-getattribute.php
2464       */
2465      public function getAttribute($attribute) {
2466          if (!$this->connect()) {
2467              return false;
2468          }
2469          return $this->pdo->getAttribute($attribute);
2470      }
2471  
2472      /**
2473       * @see http://php.net/manual/en/function.pdo-lastinsertid.php
2474       */
2475      public function lastInsertId() {
2476          if (!$this->connect()) {
2477              return false;
2478          }
2479          return $this->pdo->lastInsertId();
2480      }
2481  
2482      /**
2483       * @see http://php.net/manual/en/function.pdo-prepare.php
2484       */
2485      public function prepare($statement, $driver_options= array ()) {
2486          if (!$this->connect()) {
2487              return false;
2488          }
2489          return $this->pdo->prepare($statement, $driver_options);
2490      }
2491  
2492      /**
2493       * @see http://php.net/manual/en/function.pdo-query.php
2494       */
2495      public function query($query) {
2496          if (!$this->connect()) {
2497              return false;
2498          }
2499          $tstart= microtime(true);
2500          $return= $this->pdo->query($query);
2501          $this->queryTime += microtime(true) - $tstart;
2502          $this->executedQueries++;
2503          return $return;
2504      }
2505  
2506      /**
2507       * @see http://php.net/manual/en/function.pdo-quote.php
2508       */
2509      public function quote($string, $parameter_type= PDO::PARAM_STR) {
2510          if (!$this->connect()) {
2511              return false;
2512          }
2513          $quoted = $this->pdo->quote($string, $parameter_type);
2514          switch ($parameter_type) {
2515              case PDO::PARAM_STR:
2516                  $quoted = trim($quoted);
2517                  break;
2518              case PDO::PARAM_INT:
2519                  $quoted = trim($quoted);
2520                  $quoted = (integer) trim($quoted, "'");
2521                  break;
2522              default:
2523                  break;
2524          }
2525          return $quoted;
2526      }
2527  
2528      /**
2529       * @see http://php.net/manual/en/function.pdo-rollback.php
2530       */
2531      public function rollBack() {
2532          if (!$this->connect(null, array(xPDO::OPT_CONN_MUTABLE => true))) {
2533              return false;
2534          }
2535          return $this->pdo->rollBack();
2536      }
2537  
2538      /**
2539       * @see http://php.net/manual/en/function.pdo-setattribute.php
2540       */
2541      public function setAttribute($attribute, $value) {
2542          if (!$this->connect()) {
2543              return false;
2544          }
2545          return $this->pdo->setAttribute($attribute, $value);
2546      }
2547  
2548  
2549      /**
2550       * Convert current microtime() result into seconds.
2551       *
2552       * @deprecated Use microtime(true) directly; this was to emulate PHP 5 behavior in PHP 4.
2553       * @return float
2554       */
2555      public function getMicroTime() {
2556         return microtime(true);
2557      }
2558  
2559      /**
2560       * Creates an new xPDOQuery for a specified xPDOObject class.
2561       *
2562       * @param string $class The class to create the xPDOQuery for.
2563       * @param mixed $criteria Any valid xPDO criteria expression.
2564       * @param boolean|integer $cacheFlag Indicates if the result should be cached
2565       * and optionally for how many seconds (if passed an integer greater than 0).
2566       * @return xPDOQuery The resulting xPDOQuery instance or false if unsuccessful.
2567       */
2568      public function newQuery($class, $criteria= null, $cacheFlag= true) {
2569          $query= false;
2570          if ($this->loadClass($this->config['dbtype'] . '.xPDOQuery', '', false, true)) {
2571              $xpdoQueryClass= 'xPDOQuery_' . $this->config['dbtype'];
2572              if (!class_exists($xpdoQueryClass, false))
2573                  include_once dirname(__FILE__) . '/om/' . $this->config['dbtype'] . '/xpdoquery.class.php';
2574              if ($query= new $xpdoQueryClass($this, $class, $criteria)) {
2575                  $query->cacheFlag= $cacheFlag;
2576              }
2577          }
2578          return $query;
2579      }
2580  
2581      /**
2582       * Splits a string on a specified character, ignoring escaped content.
2583       *
2584       * @static
2585       * @param string $char A character to split the tag content on.
2586       * @param string $str The string to operate on.
2587       * @param string $escToken A character used to surround escaped content; all
2588       * content within a pair of these tokens will be ignored by the split
2589       * operation.
2590       * @param integer $limit Limit the number of results. Default is 0 which is
2591       * no limit. Note that setting the limit to 1 will only return the content
2592       * up to the first instance of the split character and will discard the
2593       * remainder of the string.
2594       * @return array An array of results from the split operation, or an empty
2595       * array.
2596       */
2597      public static function escSplit($char, $str, $escToken = '`', $limit = 0) {
2598          $split= array();
2599          $charPos = strpos($str, $char);
2600          if ($charPos !== false) {
2601              if ($charPos === 0) {
2602                  $searchPos = 1;
2603                  $startPos = 1;
2604              } else {
2605                  $searchPos = 0;
2606                  $startPos = 0;
2607              }
2608              $escOpen = false;
2609              $strlen = strlen($str);
2610              for ($i = $startPos; $i <= $strlen; $i++) {
2611                  if ($i == $strlen) {
2612                      $tmp= trim(substr($str, $searchPos));
2613                      if (!empty($tmp)) $split[]= $tmp;
2614                      break;
2615                  }
2616                  if ($str[$i] == $escToken) {
2617                      $escOpen = $escOpen == true ? false : true;
2618                      continue;
2619                  }
2620                  if (!$escOpen && $str[$i] == $char) {
2621                      $tmp= trim(substr($str, $searchPos, $i - $searchPos));
2622                      if (!empty($tmp)) {
2623                          $split[]= $tmp;
2624                          if ($limit > 0 && count($split) >= $limit) {
2625                              break;
2626                          }
2627                      }
2628                      $searchPos = $i + 1;
2629                  }
2630              }
2631          } else {
2632              $split[]= trim($str);
2633          }
2634          return $split;
2635      }
2636  
2637      /**
2638       * Parses parameter bindings in SQL prepared statements.
2639       *
2640       * @param string $sql A SQL prepared statement to parse bindings in.
2641       * @param array $bindings An array of parameter bindings to use for the replacements.
2642       * @return string The SQL with the binding placeholders replaced.
2643       */
2644      public function parseBindings($sql, $bindings) {
2645          if (!empty($sql) && !empty($bindings)) {
2646              reset($bindings);
2647              $bound = array();
2648              while (list ($k, $param)= each($bindings)) {
2649                  if (!is_array($param)) {
2650                      $v= $param;
2651                      $type= $this->getPDOType($param);
2652                      $bindings[$k]= array(
2653                          'value' => $v,
2654                          'type' => $type
2655                      );
2656                  } else {
2657                      $v= $param['value'];
2658                      $type= $param['type'];
2659                  }
2660                  if (!$v) {
2661                      switch ($type) {
2662                          case PDO::PARAM_INT:
2663                              $v= '0';
2664                              break;
2665                          case PDO::PARAM_BOOL:
2666                              $v= '0';
2667                              break;
2668                          default:
2669                              break;
2670                      }
2671                  }
2672                  if ($type > 0) {
2673                      $v= $this->quote($v, $type);
2674                  } else {
2675                      $v= 'NULL';
2676                  }
2677                  if (!is_int($k) || substr($k, 0, 1) === ':') {
2678                      $pattern= '/' . $k . '\b/';
2679                      $bound[$pattern] = str_replace(array('\\', '$'), array('\\\\', '\$'), $v);
2680                  } else {
2681                      $pattern = '/(\?)(\b)?/';
2682                      $sql = preg_replace($pattern, ':' . $k . '$2', $sql, 1);
2683                      $bound['/:' . $k . '\b/'] = str_replace(array('\\', '$'), array('\\\\', '\$'), $v);
2684                  }
2685              }
2686              $this->log(xPDO::LOG_LEVEL_INFO, "{$sql}\n" . print_r($bound, true));
2687              if (!empty($bound)) {
2688                  $sql= preg_replace(array_keys($bound), array_values($bound), $sql);
2689              }
2690          }
2691          return $sql;
2692      }
2693  
2694      /**
2695       * Get the appropriate PDO::PARAM_ type constant from a PHP value.
2696       *
2697       * @param mixed $value Any PHP scalar or null value
2698       * @return int|null
2699       */
2700      public function getPDOType($value) {
2701          $type= null;
2702          if (is_null($value)) $type= PDO::PARAM_NULL;
2703          elseif (is_scalar($value)) {
2704              if (is_int($value)) $type= PDO::PARAM_INT;
2705              else $type= PDO::PARAM_STR;
2706          }
2707          return $type;
2708      }
2709  }
2710  
2711  /**
2712   * Encapsulates a SQL query into a PDOStatement with a set of bindings.
2713   *
2714   * @package xpdo
2715   *
2716   */
2717  class xPDOCriteria {
2718      public $sql= '';
2719      public $stmt= null;
2720      public $bindings= array ();
2721      public $cacheFlag= false;
2722  
2723      /**
2724       * The constructor for a new xPDOCriteria instance.
2725       *
2726       * The constructor optionally prepares provided SQL and/or parameter
2727       * bindings.  Setting the bindings via the constructor or with the {@link
2728       * xPDOCriteria::bind()} function allows you to make use of the data object
2729       * caching layer.
2730       *
2731       * The statement will not be prepared immediately if the cacheFlag value is
2732       * true or a positive integer, in order to allow the result to be found in
2733       * the cache before being queried from an actual database connection.
2734       *
2735       * @param xPDO &$xpdo An xPDO instance that will control this criteria.
2736       * @param string $sql The SQL statement.
2737       * @param array $bindings Bindings to bind to the criteria.
2738       * @param boolean|integer $cacheFlag Indicates if the result set from the
2739       * criteria is to be cached (true|false) or optionally a TTL in seconds.
2740       * @return xPDOCriteria
2741       */
2742      public function __construct(& $xpdo, $sql= '', $bindings= array (), $cacheFlag= false) {
2743          $this->xpdo= & $xpdo;
2744          $this->cacheFlag= $cacheFlag;
2745          if (is_string($sql) && !empty ($sql)) {
2746              $this->sql= $sql;
2747              if ($cacheFlag === false || $cacheFlag < 0) {
2748              $this->stmt= $xpdo->prepare($sql);
2749              }
2750              if (!empty ($bindings)) {
2751                  $this->bind($bindings, true, $cacheFlag);
2752              }
2753          }
2754      }
2755  
2756      /**
2757       * Binds an array of key/value pairs to the xPDOCriteria prepared statement.
2758       *
2759       * Use this method to bind parameters in a way that makes it possible to
2760       * cache results of previous executions of the criteria or compare the
2761       * criteria to other individual or collections of criteria.
2762       *
2763       * @param array $bindings Bindings to merge with any existing bindings
2764       * defined for this xPDOCriteria instance.  Bindings can be simple
2765       * associative array of key-value pairs or the value for each key can
2766       * contain elements titled value, type, and length corresponding to the
2767       * appropriate parameters in the PDOStatement::bindValue() and
2768       * PDOStatement::bindParam() functions.
2769       * @param boolean $byValue Determines if the $bindings are to be bound as
2770       * parameters (by variable reference, the default behavior) or by direct
2771       * value (if true).
2772       * @param boolean|integer $cacheFlag The cacheFlag indicates the cache state
2773       * of the xPDOCriteria object and can be absolutely off (false), absolutely
2774       * on (true), or an integer indicating the number of seconds the result will
2775       * live in the cache.
2776       */
2777      public function bind($bindings= array (), $byValue= true, $cacheFlag= false) {
2778          if (!empty ($bindings)) {
2779              $this->bindings= array_merge($this->bindings, $bindings);
2780          }
2781          if (is_object($this->stmt) && $this->stmt && !empty ($this->bindings)) {
2782              reset($this->bindings);
2783              while (list ($key, $val)= each($this->bindings)) {
2784                  if (is_array($val)) {
2785                      $type= isset ($val['type']) ? $val['type'] : PDO::PARAM_STR;
2786                      $length= isset ($val['length']) ? $val['length'] : 0;
2787                      $value= & $val['value'];
2788                  } else {
2789                      $value= & $val;
2790                      $type= PDO::PARAM_STR;
2791                      $length= 0;
2792                  }
2793                  if (is_int($key)) $key= $key + 1;
2794                  if ($byValue) {
2795                      $this->stmt->bindValue($key, $value, $type);
2796                  } else {
2797                      $this->stmt->bindParam($key, $value, $type, $length);
2798                  }
2799              }
2800          }
2801          $this->cacheFlag= $cacheFlag === null ? $this->cacheFlag : $cacheFlag;
2802      }
2803  
2804      /**
2805       * Compares to see if two xPDOCriteria instances are the same.
2806       *
2807       * @param object $obj A xPDOCriteria object to compare to this one.
2808       * @return boolean true if they are both equal is SQL and bindings, otherwise
2809       * false.
2810       */
2811      public function equals($obj) {
2812          return (is_object($obj) && $obj instanceof xPDOCriteria && $this->sql === $obj->sql && !array_diff_assoc($this->bindings, $obj->bindings));
2813      }
2814  
2815      /**
2816       * Prepares the sql and bindings of this instance into a PDOStatement.
2817       *
2818       * The {@link xPDOCriteria::$sql} attribute must be set in order to prepare
2819       * the statement. You can also pass bindings directly to this function and
2820       * they will be run through {@link xPDOCriteria::bind()} if the statement
2821       * is successfully prepared.
2822       *
2823       * If the {@link xPDOCriteria::$stmt} already exists, it is simply returned.
2824       *
2825       * @param array $bindings Bindings to merge with any existing bindings
2826       * defined for this xPDOCriteria instance.  Bindings can be simple
2827       * associative array of key-value pairs or the value for each key can
2828       * contain elements titled value, type, and length corresponding to the
2829       * appropriate parameters in the PDOStatement::bindValue() and
2830       * PDOStatement::bindParam() functions.
2831       * @param boolean $byValue Determines if the $bindings are to be bound as
2832       * parameters (by variable reference, the default behavior) or by direct
2833       * value (if true).
2834       * @param boolean|integer $cacheFlag The cacheFlag indicates the cache state
2835       * of the xPDOCriteria object and can be absolutely off (false), absolutely
2836       * on (true), or an integer indicating the number of seconds the result will
2837       * live in the cache.
2838       * @return PDOStatement The prepared statement, ready to execute.
2839       */
2840      public function prepare($bindings= array (), $byValue= true, $cacheFlag= null) {
2841          if ($this->stmt === null || !is_object($this->stmt)) {
2842              if (!empty ($this->sql) && $stmt= $this->xpdo->prepare($this->sql)) {
2843                  $this->stmt= & $stmt;
2844                  $this->bind($bindings, $byValue, $cacheFlag);
2845              }
2846          }
2847          return $this->stmt;
2848      }
2849  
2850      /**
2851       * Converts the current xPDOQuery to parsed SQL.
2852       *
2853       * @param bool $parseBindings If true, bindings are parsed locally; otherwise
2854       * they are left in place.
2855       * @return string The parsed SQL query.
2856       */
2857      public function toSQL($parseBindings = true) {
2858          $sql = $this->sql;
2859          if ($parseBindings && !empty($this->bindings)) {
2860              $sql = $this->xpdo->parseBindings($sql, $this->bindings);
2861          }
2862          return $sql;
2863      }
2864  }
2865  
2866  /**
2867   * An iteratable representation of an xPDOObject result set.
2868   *
2869   * Use an xPDOIterator to loop over large result sets and work with one instance
2870   * at a time. This greatly reduces memory usage over loading the entire collection
2871   * of objects into memory at one time. It is also slightly faster.
2872   *
2873   * @package xpdo
2874   */
2875  class xPDOIterator implements Iterator {
2876      private $xpdo = null;
2877      private $index = 0;
2878      private $current = null;
2879      /** @var null|PDOStatement */
2880      private $stmt = null;
2881      private $class = null;
2882      private $alias = null;
2883      /** @var null|int|str|array|xPDOQuery */
2884      private $criteria = null;
2885      private $criteriaType = 'xPDOQuery';
2886      private $cacheFlag = false;
2887  
2888      /**
2889       * Construct a new xPDOIterator instance (do not call directly).
2890       *
2891       * @see xPDO::getIterator()
2892       * @param xPDO &$xpdo A reference to a valid xPDO instance.
2893       * @param array $options An array of options for the iterator.
2894       * @return xPDOIterator An xPDOIterator instance.
2895       */
2896      function __construct(& $xpdo, array $options= array()) {
2897          $this->xpdo =& $xpdo;
2898          if (isset($options['class'])) {
2899              $this->class = $this->xpdo->loadClass($options['class']);
2900          }
2901          if (isset($options['alias'])) {
2902              $this->alias = $options['alias'];
2903          } else {
2904              $this->alias = $this->class;
2905          }
2906          if (isset($options['cacheFlag'])) {
2907              $this->cacheFlag = $options['cacheFlag'];
2908          }
2909          if (array_key_exists('criteria', $options) && is_object($options['criteria'])) {
2910              $this->criteria = $options['criteria'];
2911          } elseif (!empty($this->class)) {
2912              $criteria = array_key_exists('criteria', $options) ? $options['criteria'] : null;
2913              $this->criteria = $this->xpdo->getCriteria($this->class, $criteria, $this->cacheFlag);
2914          }
2915          if (!empty($this->criteria)) {
2916              $this->criteriaType = $this->xpdo->getCriteriaType($this->criteria);
2917              if ($this->criteriaType === 'xPDOQuery') {
2918                  $this->class = $this->criteria->getClass();
2919                  $this->alias = $this->criteria->getAlias();
2920              }
2921          }
2922      }
2923  
2924      public function rewind() {
2925          $this->index = 0;
2926          if (!empty($this->stmt)) {
2927              $this->stmt->closeCursor();
2928          }
2929          $this->stmt = $this->criteria->prepare();
2930          $tstart = microtime(true);
2931          if ($this->stmt && $this->stmt->execute()) {
2932              $this->xpdo->queryTime += microtime(true) - $tstart;
2933              $this->xpdo->executedQueries++;
2934              $this->fetch();
2935          } elseif ($this->stmt) {
2936              $this->xpdo->queryTime += microtime(true) - $tstart;
2937              $this->xpdo->executedQueries++;
2938          }
2939      }
2940  
2941      public function current() {
2942          return $this->current;
2943      }
2944  
2945      public function key() {
2946          return $this->index;
2947      }
2948  
2949      public function next() {
2950          $this->fetch();
2951          if (!$this->valid()) {
2952              $this->index = null;
2953          } else {
2954              $this->index++;
2955          }
2956          return $this->current();
2957      }
2958  
2959      public function valid() {
2960          return ($this->current !== null);
2961      }
2962  
2963      /**
2964       * Fetch the next row from the result set and set it as current.
2965       *
2966       * Calls the _loadInstance() method for the specified class, so it properly
2967       * inherits behavior from xPDOObject derivatives.
2968       */
2969      protected function fetch() {
2970          $row = $this->stmt->fetch(PDO::FETCH_ASSOC);
2971          if (is_array($row) && !empty($row)) {
2972              $this->current = $this->xpdo->call($this->class, '_loadInstance', array(& $this->xpdo, $this->class, $this->alias, $row));
2973          } else {
2974              $this->current = null;
2975          }
2976      }
2977  }
2978  
2979  /**
2980   * Represents a unique PDO connection managed by xPDO.
2981   *
2982   * @package xpdo
2983   */
2984  class xPDOConnection {
2985      /**
2986       * @var xPDO A reference to a valid xPDO instance.
2987       */
2988      public $xpdo = null;
2989      /**
2990       * @var array An array of configuration options for this connection.
2991       */
2992      public $config = array();
2993  
2994      /**
2995       * @var PDO The PDO object represented by the xPDOConnection instance.
2996       */
2997      public $pdo = null;
2998      /**
2999       * @var boolean Indicates if this connection can be written to.
3000       */
3001      private $_mutable = true;
3002  
3003      /**
3004       * Construct a new xPDOConnection instance.
3005       *
3006       * @param xPDO $xpdo A reference to a valid xPDO instance to attach to.
3007       * @param string $dsn A string representing the DSN connection string.
3008       * @param string $username The database username credentials.
3009       * @param string $password The database password credentials.
3010       * @param array $options An array of xPDO options for the connection.
3011       * @param array $driverOptions An array of PDO driver options for the connection.
3012       */
3013      public function __construct(xPDO &$xpdo, $dsn, $username= '', $password= '', $options= array(), $driverOptions= array()) {
3014          $this->xpdo =& $xpdo;
3015          if (is_array($this->xpdo->config)) $options= array_merge($this->xpdo->config, $options);
3016          if (!isset($options[xPDO::OPT_TABLE_PREFIX])) $options[xPDO::OPT_TABLE_PREFIX]= '';
3017          $this->config= array_merge($options, xPDO::parseDSN($dsn));
3018          $this->config['dsn']= $dsn;
3019          $this->config['username']= $username;
3020          $this->config['password']= $password;
3021          $driverOptions = is_array($driverOptions) ? $driverOptions : array();
3022          if (array_key_exists('driverOptions', $this->config) && is_array($this->config['driverOptions'])) {
3023              $driverOptions = array_merge($this->config['driverOptions'], $driverOptions);
3024          }
3025          $this->config['driverOptions']= $driverOptions;
3026          if (array_key_exists(xPDO::OPT_CONN_MUTABLE, $this->config)) {
3027              $this->_mutable= (boolean) $this->config[xPDO::OPT_CONN_MUTABLE];
3028          }
3029      }
3030  
3031      /**
3032       * Indicates if the connection can be written to, e.g. INSERT/UPDATE/DELETE.
3033       *
3034       * @return bool True if the connection can be written to.
3035       */
3036      public function isMutable() {
3037          return $this->_mutable;
3038      }
3039  
3040      /**
3041       * Actually make a connection for this instance via PDO.
3042       *
3043       * @param array $driverOptions An array of PDO driver options for the connection.
3044       * @return bool True if a successful connection is made.
3045       */
3046      public function connect($driverOptions = array()) {
3047          if ($this->pdo === null) {
3048              if (is_array($driverOptions) && !empty($driverOptions)) {
3049                  $this->config['driverOptions']= array_merge($this->config['driverOptions'], $driverOptions);
3050              }
3051              try {
3052                  $this->pdo= new PDO($this->config['dsn'], $this->config['username'], $this->config['password'], $this->config['driverOptions']);
3053              } catch (PDOException $xe) {
3054                  $this->xpdo->log(xPDO::LOG_LEVEL_ERROR, $xe->getMessage(), '', __METHOD__, __FILE__, __LINE__);
3055                  return false;
3056              } catch (Exception $e) {
3057                  $this->xpdo->log(xPDO::LOG_LEVEL_ERROR, $e->getMessage(), '', __METHOD__, __FILE__, __LINE__);
3058                  return false;
3059              }
3060  
3061              $connected= (is_object($this->pdo));
3062              if ($connected) {
3063                  $connectFile = XPDO_CORE_PATH . 'om/' . $this->config['dbtype'] . '/connect.inc.php';
3064                  if (!empty($this->config['connect_file']) && file_exists($this->config['connect_file'])) {
3065                      $connectFile = $this->config['connect_file'];
3066                  }
3067                  if (file_exists($connectFile)) include ($connectFile);
3068              }
3069              if (!$connected) {
3070                  $this->pdo= null;
3071              }
3072          }
3073          $connected= is_object($this->pdo);
3074          return $connected;
3075      }
3076  
3077      /**
3078       * Get an option set for this xPDOConnection instance.
3079       *
3080       * @param string $key The option key to get a value for.
3081       * @param array|null $options An optional array of options to consider.
3082       * @param mixed $default A default value to use if the option is not found.
3083       * @return mixed The option value.
3084       */
3085      public function getOption($key, $options = null, $default = null) {
3086          if (is_array($options)) {
3087              $options = array_merge($this->config, $options);
3088          } else {
3089              $options = $this->config;
3090          }
3091          return $this->xpdo->getOption($key, $options, $default);
3092      }
3093  }
3094  
3095  /**
3096   * A basic class for xPDO Exceptions.
3097   */
3098  class xPDOException extends Exception {}

title

Description

title

Description

title

Description

title

title

Body