PageRenderTime 35ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 0ms

/core/xpdo/xpdo.class.php

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