PageRenderTime 152ms CodeModel.GetById 27ms 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

Large files files are truncated, but you can click here to view the full file

  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. $

Large files files are truncated, but you can click here to view the full file