PageRenderTime 62ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/modx/core/xpdo/om/xpdoobject.class.php

https://bitbucket.org/argnist/mohana
PHP | 2192 lines | 1449 code | 76 blank | 667 comment | 528 complexity | 5596bac0e53ac49189027212d5efcc41 MD5 | raw file
Possible License(s): BSD-3-Clause, AGPL-1.0, LGPL-2.1, GPL-2.0, GPL-3.0, LGPL-2.0
  1. <?php
  2. /*
  3. * Copyright 2010-2011 by MODX, LLC.
  4. *
  5. * This file is part of xPDO.
  6. *
  7. * xPDO is free software; you can redistribute it and/or modify it under the
  8. * terms of the GNU General Public License as published by the Free Software
  9. * Foundation; either version 2 of the License, or (at your option) any later
  10. * version.
  11. *
  12. * xPDO is distributed in the hope that it will be useful, but WITHOUT ANY
  13. * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  14. * A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License along with
  17. * xPDO; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
  18. * Suite 330, Boston, MA 02111-1307 USA
  19. */
  20. /**
  21. * The base persistent xPDO object classes.
  22. *
  23. * This file contains the base persistent object classes, which your user-
  24. * defined classes will extend when implementing an xPDO object model.
  25. *
  26. * @package xpdo
  27. * @subpackage om
  28. */
  29. /**
  30. * The base persistent xPDO object class.
  31. *
  32. * This is the basis for the entire xPDO object model, and can also be used by a
  33. * class generator {@link xPDOGenerator}, ultimately allowing custom classes to
  34. * be user-defined in a web interface and framework-generated at runtime.
  35. *
  36. * @abstract This is an abstract class, and is not represented by an actual
  37. * table; it simply defines the member variables and functions needed for object
  38. * persistence. All xPDOObject derivatives must define both a PHP 4 style
  39. * constructor which calls a PHP 5 style __construct() method with the same
  40. * parameters. This is necessary to allow instantiation of further derived
  41. * classes without knowing the name of the class ahead of time in PHP 4. Note
  42. * that this does not meet E_STRICT compliance in PHP 5, but is the only sane
  43. * way to achieve consistency between the PHP 4 and 5 inheritence models.
  44. *
  45. * @package xpdo
  46. * @subpackage om
  47. */
  48. class xPDOObject {
  49. /**
  50. * A convenience reference to the xPDO object.
  51. * @var xPDO
  52. * @access public
  53. */
  54. public $xpdo= null;
  55. /**
  56. * Name of the data source container the object belongs to.
  57. * @var string
  58. * @access public
  59. */
  60. public $container= null;
  61. /**
  62. * Names of the fields in the data table, fully-qualified with a table name.
  63. *
  64. * NOTE: For use in table joins to qualify fields with the same name.
  65. *
  66. * @var array
  67. * @access public
  68. */
  69. public $fieldNames= null;
  70. /**
  71. * The actual class name of an instance.
  72. * @var string
  73. */
  74. public $_class= null;
  75. /**
  76. * The package the class is a part of.
  77. * @var string
  78. */
  79. public $_package= null;
  80. /**
  81. * An alias for this instance of the class.
  82. * @var string
  83. */
  84. public $_alias= null;
  85. /**
  86. * The primary key field (or an array of primary key fields) for this object.
  87. * @var string|array
  88. * @access public
  89. */
  90. public $_pk= null;
  91. /**
  92. * The php native type of the primary key field.
  93. *
  94. * NOTE: Will be an array if multiple primary keys are specified for the object.
  95. *
  96. * @var string|array
  97. * @access public
  98. */
  99. public $_pktype= null;
  100. /**
  101. * Name of the actual table representing this class.
  102. * @var string
  103. * @access public
  104. */
  105. public $_table= null;
  106. /**
  107. * An array of meta data for the table.
  108. * @var string
  109. * @access public
  110. */
  111. public $_tableMeta= null;
  112. /**
  113. * An array of field names that have been modified.
  114. * @var array
  115. * @access public
  116. */
  117. public $_dirty= array ();
  118. /**
  119. * An array of field names that have not been loaded from the source.
  120. * @var array
  121. * @access public
  122. */
  123. public $_lazy= array ();
  124. /**
  125. * An array of key-value pairs representing the fields of the instance.
  126. * @var array
  127. * @access public
  128. */
  129. public $_fields= array ();
  130. /**
  131. * An array of metadata definitions for each field in the class.
  132. * @var array
  133. * @access public
  134. */
  135. public $_fieldMeta= array ();
  136. /**
  137. * An array of aggregate foreign key relationships for the class.
  138. * @var array
  139. * @access public
  140. */
  141. public $_aggregates= array ();
  142. /**
  143. * An array of composite foreign key relationships for the class.
  144. * @var array
  145. * @access public
  146. */
  147. public $_composites= array ();
  148. /**
  149. * An array of object instances related to this object instance.
  150. * @var array
  151. * @access public
  152. */
  153. public $_relatedObjects= array ();
  154. /**
  155. * A validator object responsible for this object instance.
  156. * @var xPDOValidator
  157. * @access public
  158. */
  159. public $_validator = null;
  160. /**
  161. * An array of validation rules for this object instance.
  162. * @var array
  163. * @access public
  164. */
  165. public $_validationRules = array();
  166. /**
  167. * An array of field names that have been already validated.
  168. * @var array
  169. * @access public
  170. */
  171. public $_validated= array ();
  172. /**
  173. * Indicates if the validation map has been loaded.
  174. * @var boolean
  175. * @access public
  176. */
  177. public $_validationLoaded= false;
  178. /**
  179. * Indicates if the instance is transient (and thus new).
  180. * @var boolean
  181. * @access public
  182. */
  183. public $_new= true;
  184. /**
  185. * Indicates the cacheability of the instance.
  186. * @var boolean
  187. */
  188. public $_cacheFlag= true;
  189. /**
  190. * A collection of various options that can be used on the instance.
  191. * @var array
  192. */
  193. public $_options= array();
  194. /**
  195. * Responsible for loading a result set from the database.
  196. *
  197. * @static
  198. * @param xPDO &$xpdo A valid xPDO instance.
  199. * @param string $className Name of the class.
  200. * @param xPDOCriteria $criteria A valid xPDOCriteria instance.
  201. * @return PDOStatement A reference to a PDOStatement representing the
  202. * result set.
  203. */
  204. public static function & _loadRows(& $xpdo, $className, $criteria) {
  205. $rows= null;
  206. if ($criteria->prepare()) {
  207. if ($xpdo->getDebug() === true) $xpdo->log(xPDO::LOG_LEVEL_DEBUG, "Attempting to execute query using PDO statement object: " . print_r($criteria->sql, true) . print_r($criteria->bindings, true));
  208. $tstart= $xpdo->getMicroTime();
  209. if (!$criteria->stmt->execute()) {
  210. $tend= $xpdo->getMicroTime();
  211. $totaltime= $tend - $tstart;
  212. $xpdo->queryTime= $xpdo->queryTime + $totaltime;
  213. $xpdo->executedQueries= $xpdo->executedQueries + 1;
  214. $errorInfo= $criteria->stmt->errorInfo();
  215. $xpdo->log(xPDO::LOG_LEVEL_ERROR, 'Error ' . $criteria->stmt->errorCode() . " executing statement: \n" . print_r($errorInfo, true));
  216. if (($errorInfo[1] == '1146' || $errorInfo[1] == '1') && $xpdo->getOption(xPDO::OPT_AUTO_CREATE_TABLES)) {
  217. if ($xpdo->getManager() && $xpdo->manager->createObjectContainer($className)) {
  218. $tstart= $xpdo->getMicroTime();
  219. if (!$criteria->stmt->execute()) {
  220. $xpdo->log(xPDO::LOG_LEVEL_ERROR, "Error " . $criteria->stmt->errorCode() . " executing statement: \n" . print_r($criteria->stmt->errorInfo(), true));
  221. }
  222. $tend= $xpdo->getMicroTime();
  223. $totaltime= $tend - $tstart;
  224. $xpdo->queryTime= $xpdo->queryTime + $totaltime;
  225. $xpdo->executedQueries= $xpdo->executedQueries + 1;
  226. } else {
  227. $xpdo->log(xPDO::LOG_LEVEL_ERROR, "Error " . $xpdo->errorCode() . " attempting to create object container for class {$className}:\n" . print_r($xpdo->errorInfo(), true));
  228. }
  229. }
  230. }
  231. $rows= & $criteria->stmt;
  232. } else {
  233. $errorInfo = $xpdo->errorInfo();
  234. $xpdo->log(xPDO::LOG_LEVEL_ERROR, "Error preparing statement for query: {$criteria->sql} - " . print_r($errorInfo, true));
  235. if (($errorInfo[1] == '1146' || $errorInfo[1] == '1') && $xpdo->getOption(xPDO::OPT_AUTO_CREATE_TABLES)) {
  236. if ($xpdo->getManager() && $xpdo->manager->createObjectContainer($className)) {
  237. if (!$criteria->prepare()) {
  238. $xpdo->log(xPDO::LOG_LEVEL_ERROR, "Error preparing statement for query: {$criteria->sql} - " . print_r($errorInfo, true));
  239. } else {
  240. $tstart= $xpdo->getMicroTime();
  241. if (!$criteria->stmt->execute()) {
  242. $xpdo->log(xPDO::LOG_LEVEL_ERROR, "Error " . $criteria->stmt->errorCode() . " executing statement: \n" . print_r($criteria->stmt->errorInfo(), true));
  243. }
  244. $tend= $xpdo->getMicroTime();
  245. $totaltime= $tend - $tstart;
  246. $xpdo->queryTime= $xpdo->queryTime + $totaltime;
  247. $xpdo->executedQueries= $xpdo->executedQueries + 1;
  248. }
  249. } else {
  250. $xpdo->log(xPDO::LOG_LEVEL_ERROR, "Error " . $xpdo->errorCode() . " attempting to create object container for class {$className}:\n" . print_r($xpdo->errorInfo(), true));
  251. }
  252. }
  253. }
  254. return $rows;
  255. }
  256. /**
  257. * Loads an instance from an associative array.
  258. *
  259. * @static
  260. * @param xPDO &$xpdo A valid xPDO instance.
  261. * @param string $className Name of the class.
  262. * @param xPDOQuery|string $criteria A valid xPDOQuery instance or relation alias.
  263. * @param array $row The associative array containing the instance data.
  264. * @return xPDOObject A new xPDOObject derivative representing a data row.
  265. */
  266. public static function _loadInstance(& $xpdo, $className, $criteria, $row) {
  267. $rowPrefix= '';
  268. if (is_object($criteria) && $criteria instanceof xPDOQuery) {
  269. $alias = $criteria->getAlias();
  270. $actualClass = $criteria->getClass();
  271. } elseif (is_string($criteria) && !empty($criteria)) {
  272. $alias = $criteria;
  273. $actualClass = $className;
  274. } else {
  275. $alias = $className;
  276. $actualClass= $className;
  277. }
  278. if (isset($row["{$className}_class_key"])) {
  279. $actualClass= $row["{$className}_class_key"];
  280. $rowPrefix= $className . '_';
  281. }
  282. elseif (isset ($row["{$alias}_class_key"])) {
  283. $actualClass= $row["{$alias}_class_key"];
  284. $rowPrefix= $alias . '_';
  285. }
  286. elseif (isset ($row['class_key'])) {
  287. $actualClass= $row['class_key'];
  288. }
  289. $instance= $xpdo->newObject($actualClass);
  290. if (is_object($instance) && $instance instanceof xPDOObject) {
  291. if (strpos(strtolower(key($row)), strtolower($alias . '_')) === 0) {
  292. $rowPrefix= $alias . '_';
  293. }
  294. elseif (strpos(strtolower(key($row)), strtolower($className . '_')) === 0) {
  295. $rowPrefix= $className . '_';
  296. }
  297. else {
  298. $pk = $xpdo->getPK($actualClass);
  299. if (is_array($pk)) $pk = reset($pk);
  300. if (isset($row["{$alias}_{$pk}"])) {
  301. $rowPrefix= $alias . '_';
  302. }
  303. elseif ($actualClass !== $className && $actualClass !== $alias && isset($row["{$actualClass}_{$pk}"])) {
  304. $rowPrefix= $actualClass . '_';
  305. }
  306. elseif ($className !== $alias && isset($row["{$className}_{$pk}"])) {
  307. $rowPrefix= $className . '_';
  308. }
  309. }
  310. if (!$instance instanceof $className) {
  311. $xpdo->log(xPDO::LOG_LEVEL_ERROR, "Instantiated a derived class {$actualClass} that is not a subclass of the requested class {$className}");
  312. }
  313. $instance->_lazy= $actualClass !== $className ? array_keys($xpdo->getFields($className)) : array_keys($instance->_fields);
  314. $instance->fromArray($row, $rowPrefix, true, true);
  315. $instance->_dirty= array ();
  316. $instance->_new= false;
  317. }
  318. return $instance;
  319. }
  320. /**
  321. * Responsible for loading an instance into a collection.
  322. *
  323. * @static
  324. * @param xPDO &$xpdo A valid xPDO instance.
  325. * @param array &$objCollection The collection to load the instance into.
  326. * @param string $className Name of the class.
  327. * @param mixed $criteria A valid primary key, criteria array, or xPDOCriteria instance.
  328. * @param boolean|integer $cacheFlag Indicates if the objects should be cached and
  329. * optionally, by specifying an integer value, for how many seconds.
  330. */
  331. public static function _loadCollectionInstance(xPDO & $xpdo, array & $objCollection, $className, $criteria, $row, $fromCache, $cacheFlag=true) {
  332. $loaded = false;
  333. if ($obj= xPDOObject :: _loadInstance($xpdo, $className, $criteria, $row)) {
  334. if (($cacheKey= $obj->getPrimaryKey()) && !$obj->isLazy()) {
  335. if (is_array($cacheKey)) {
  336. $pkval= implode('-', $cacheKey);
  337. } else {
  338. $pkval= $cacheKey;
  339. }
  340. if ($xpdo->getOption(xPDO::OPT_CACHE_DB_COLLECTIONS, array(), 1) == 2 && $xpdo->_cacheEnabled && $cacheFlag) {
  341. if (!$fromCache) {
  342. $pkCriteria = $xpdo->newQuery($className, $cacheKey, $cacheFlag);
  343. $xpdo->toCache($pkCriteria, $obj, $cacheFlag);
  344. } else {
  345. $obj->_cacheFlag= true;
  346. }
  347. }
  348. $objCollection[$pkval]= $obj;
  349. $loaded = true;
  350. } else {
  351. $objCollection[]= $obj;
  352. $loaded = true;
  353. }
  354. }
  355. return $loaded;
  356. }
  357. /**
  358. * Load an instance of an xPDOObject or derivative class.
  359. *
  360. * @static
  361. * @param xPDO &$xpdo A valid xPDO instance.
  362. * @param string $className Name of the class.
  363. * @param mixed $criteria A valid primary key, criteria array, or
  364. * xPDOCriteria instance.
  365. * @param boolean|integer $cacheFlag Indicates if the objects should be
  366. * cached and optionally, by specifying an integer value, for how many
  367. * seconds.
  368. * @return object|null An instance of the requested class, or null if it
  369. * could not be instantiated.
  370. */
  371. public static function load(xPDO & $xpdo, $className, $criteria, $cacheFlag= true) {
  372. $instance= null;
  373. $fromCache= false;
  374. if ($className= $xpdo->loadClass($className)) {
  375. if (!is_object($criteria)) {
  376. $criteria= $xpdo->getCriteria($className, $criteria, $cacheFlag);
  377. }
  378. if (is_object($criteria)) {
  379. $criteria = $xpdo->addDerivativeCriteria($className, $criteria);
  380. $row= null;
  381. if ($xpdo->_cacheEnabled && $criteria->cacheFlag && $cacheFlag) {
  382. $row= $xpdo->fromCache($criteria, $className);
  383. }
  384. if ($row === null || !is_array($row)) {
  385. if ($rows= xPDOObject :: _loadRows($xpdo, $className, $criteria)) {
  386. $row= $rows->fetch(PDO::FETCH_ASSOC);
  387. $rows->closeCursor();
  388. }
  389. } else {
  390. $fromCache= true;
  391. }
  392. if (!is_array($row)) {
  393. if ($xpdo->getDebug() === true) $xpdo->log(xPDO::LOG_LEVEL_DEBUG, "Fetched empty result set from statement: " . print_r($criteria->sql, true) . " with bindings: " . print_r($criteria->bindings, true));
  394. } else {
  395. $instance= xPDOObject :: _loadInstance($xpdo, $className, $criteria, $row);
  396. if (is_object($instance)) {
  397. if (!$fromCache && $cacheFlag && $xpdo->_cacheEnabled) {
  398. $xpdo->toCache($criteria, $instance, $cacheFlag);
  399. if ($xpdo->getOption(xPDO::OPT_CACHE_DB_OBJECTS_BY_PK) && ($cacheKey= $instance->getPrimaryKey()) && !$instance->isLazy()) {
  400. $pkCriteria = $xpdo->newQuery($className, $cacheKey, $cacheFlag);
  401. $xpdo->toCache($pkCriteria, $instance, $cacheFlag);
  402. }
  403. }
  404. if ($xpdo->getDebug() === true) $xpdo->log(xPDO::LOG_LEVEL_DEBUG, "Loaded object instance: " . print_r($instance->toArray('', true), true));
  405. }
  406. }
  407. } else {
  408. $xpdo->log(xPDO::LOG_LEVEL_ERROR, 'No valid statement could be found in or generated from the given criteria.');
  409. }
  410. } else {
  411. $xpdo->log(xPDO::LOG_LEVEL_ERROR, 'Invalid class specified: ' . $className);
  412. }
  413. return $instance;
  414. }
  415. /**
  416. * Load a collection of xPDOObject instances.
  417. *
  418. * @static
  419. * @param xPDO &$xpdo A valid xPDO instance.
  420. * @param string $className Name of the class.
  421. * @param mixed $criteria A valid primary key, criteria array, or xPDOCriteria instance.
  422. * @param boolean|integer $cacheFlag Indicates if the objects should be
  423. * cached and optionally, by specifying an integer value, for how many
  424. * seconds.
  425. * @return array An array of xPDOObject instances or an empty array if no instances are loaded.
  426. */
  427. public static function loadCollection(xPDO & $xpdo, $className, $criteria= null, $cacheFlag= true) {
  428. $objCollection= array ();
  429. $fromCache = false;
  430. if (!$className= $xpdo->loadClass($className)) return $objCollection;
  431. $rows= false;
  432. $fromCache= false;
  433. $collectionCaching = (integer) $xpdo->getOption(xPDO::OPT_CACHE_DB_COLLECTIONS, array(), 1);
  434. if (!is_object($criteria)) {
  435. $criteria= $xpdo->getCriteria($className, $criteria, $cacheFlag);
  436. }
  437. if (is_object($criteria)) {
  438. $criteria = $xpdo->addDerivativeCriteria($className, $criteria);
  439. }
  440. if ($collectionCaching > 0 && $xpdo->_cacheEnabled && $cacheFlag) {
  441. $rows= $xpdo->fromCache($criteria);
  442. $fromCache = (is_array($rows) && !empty($rows));
  443. }
  444. if (!$fromCache && is_object($criteria)) {
  445. $rows= xPDOObject :: _loadRows($xpdo, $className, $criteria);
  446. }
  447. if (is_array ($rows)) {
  448. foreach ($rows as $row) {
  449. xPDOObject :: _loadCollectionInstance($xpdo, $objCollection, $className, $criteria, $row, $fromCache, $cacheFlag);
  450. }
  451. } elseif (is_object($rows)) {
  452. $cacheRows = array();
  453. while ($row = $rows->fetch(PDO::FETCH_ASSOC)) {
  454. xPDOObject :: _loadCollectionInstance($xpdo, $objCollection, $className, $criteria, $row, $fromCache, $cacheFlag);
  455. if ($collectionCaching > 0 && $xpdo->_cacheEnabled && $cacheFlag && !$fromCache) $cacheRows[] = $row;
  456. }
  457. if ($collectionCaching > 0 && $xpdo->_cacheEnabled && $cacheFlag && !$fromCache) $rows =& $cacheRows;
  458. }
  459. if (!$fromCache && $xpdo->_cacheEnabled && $collectionCaching > 0 && $cacheFlag && !empty($rows)) {
  460. $xpdo->toCache($criteria, $rows, $cacheFlag);
  461. }
  462. return $objCollection;
  463. }
  464. /**
  465. * Load a collection of xPDOObject instances and a graph of related objects.
  466. *
  467. * @static
  468. * @param xPDO &$xpdo A valid xPDO instance.
  469. * @param string $className Name of the class.
  470. * @param string|array $graph A related object graph in array or JSON
  471. * format, e.g. array('relationAlias'=>array('subRelationAlias'=>array()))
  472. * or {"relationAlias":{"subRelationAlias":{}}}. Note that the empty arrays
  473. * are necessary in order for the relation to be recognized.
  474. * @param mixed $criteria A valid primary key, criteria array, or xPDOCriteria instance.
  475. * @param boolean|integer $cacheFlag Indicates if the objects should be
  476. * cached and optionally, by specifying an integer value, for how many
  477. * seconds.
  478. * @return array An array of xPDOObject instances or an empty array if no instances are loaded.
  479. */
  480. public static function loadCollectionGraph(xPDO & $xpdo, $className, $graph, $criteria, $cacheFlag) {
  481. $objCollection = array();
  482. if ($query= $xpdo->newQuery($className, $criteria, $cacheFlag)) {
  483. $query = $xpdo->addDerivativeCriteria($className, $query);
  484. $query->bindGraph($graph);
  485. $rows = array();
  486. $fromCache = false;
  487. $collectionCaching = (integer) $xpdo->getOption(xPDO::OPT_CACHE_DB_COLLECTIONS, array(), 1);
  488. if ($collectionCaching > 0 && $xpdo->_cacheEnabled && $cacheFlag) {
  489. $rows= $xpdo->fromCache($query);
  490. $fromCache = !empty($rows);
  491. }
  492. if (!$fromCache) {
  493. $stmt= $query->prepare();
  494. if ($stmt && $stmt->execute()) {
  495. $objCollection= $query->hydrateGraph($stmt, $cacheFlag);
  496. }
  497. } elseif (!empty($rows)) {
  498. $objCollection= $query->hydrateGraph($rows, $cacheFlag);
  499. }
  500. }
  501. return $objCollection;
  502. }
  503. /**
  504. * Get a set of column names from an xPDOObject for use in SQL queries.
  505. *
  506. * @static
  507. * @param xPDO &$xpdo A reference to an initialized xPDO instance.
  508. * @param string $className The class name to get columns from.
  509. * @param string $tableAlias An optional alias for the table in the query.
  510. * @param string $columnPrefix An optional prefix to prepend to each column name.
  511. * @param array $columns An optional array of field names to include or exclude
  512. * (include is default behavior).
  513. * @param boolean $exclude Determines if any specified columns should be included
  514. * or excluded from the set of results.
  515. * @return string A comma-delimited list of the field names for use in a SELECT clause.
  516. */
  517. public static function getSelectColumns(xPDO & $xpdo, $className, $tableAlias= '', $columnPrefix= '', $columns= array (), $exclude= false) {
  518. $columnarray= array ();
  519. $aColumns= $xpdo->getFields($className);
  520. if ($aColumns) {
  521. if (!empty ($tableAlias)) {
  522. $tableAlias= $xpdo->escape($tableAlias);
  523. $tableAlias.= '.';
  524. }
  525. foreach (array_keys($aColumns) as $k) {
  526. if ($exclude && in_array($k, $columns)) {
  527. continue;
  528. }
  529. elseif (empty ($columns)) {
  530. $columnarray[$k]= "{$tableAlias}" . $xpdo->escape($k);
  531. }
  532. elseif ($exclude || in_array($k, $columns)) {
  533. $columnarray[$k]= "{$tableAlias}" . $xpdo->escape($k);
  534. } else {
  535. continue;
  536. }
  537. if (!empty ($columnPrefix)) {
  538. $columnarray[$k]= $columnarray[$k] . " AS " . $xpdo->escape("{$columnPrefix}{$k}");
  539. }
  540. }
  541. }
  542. return implode(', ', $columnarray);
  543. }
  544. /**
  545. * Constructor
  546. *
  547. * Do not call the constructor directly; see {@link xPDO::newObject()}.
  548. *
  549. * All derivatives of xPDOObject must redeclare this method, and must call
  550. * the parent method explicitly before any additional logic is executed, e.g.
  551. *
  552. * <code>
  553. * public function __construct(xPDO & $xpdo) {
  554. * parent :: __construct($xpdo);
  555. * // Any additional constructor tasks here
  556. * }
  557. * </code>
  558. *
  559. * @access public
  560. * @param xPDO &$xpdo A reference to a valid xPDO instance.
  561. * @return xPDOObject
  562. */
  563. public function __construct(xPDO & $xpdo) {
  564. $this->xpdo= & $xpdo;
  565. $this->container= $xpdo->config['dbname'];
  566. $this->_class= get_class($this);
  567. $pos= strrpos($this->_class, '_');
  568. if ($pos !== false && substr($this->_class, $pos + 1) == $xpdo->config['dbtype']) {
  569. $this->_class= substr($this->_class, 0, $pos);
  570. }
  571. $this->_package= $xpdo->getPackage($this->_class);
  572. $this->_alias= $this->_class;
  573. $this->_table= $xpdo->getTableName($this->_class);
  574. $this->_tableMeta= $xpdo->getTableMeta($this->_class);
  575. $this->_fields= $xpdo->getFields($this->_class);
  576. $this->_fieldMeta= $xpdo->getFieldMeta($this->_class);
  577. $this->_aggregates= $xpdo->getAggregates($this->_class);
  578. $this->_composites= $xpdo->getComposites($this->_class);
  579. $classVars= array ();
  580. if ($relatedObjs= array_merge($this->_aggregates, $this->_composites)) {
  581. if ($this->getOption(xPDO::OPT_HYDRATE_RELATED_OBJECTS)) $classVars= get_object_vars($this);
  582. foreach ($relatedObjs as $aAlias => $aMeta) {
  583. if (!array_key_exists($aAlias, $this->_relatedObjects)) {
  584. if ($aMeta['cardinality'] == 'many') {
  585. $this->_relatedObjects[$aAlias]= array ();
  586. }
  587. else {
  588. $this->_relatedObjects[$aAlias]= null;
  589. }
  590. }
  591. if ($this->getOption(xPDO::OPT_HYDRATE_RELATED_OBJECTS) && !array_key_exists($aAlias, $classVars)) {
  592. $this->$aAlias= & $this->_relatedObjects[$aAlias];
  593. $classVars[$aAlias]= 1;
  594. }
  595. }
  596. }
  597. if ($this->getOption(xPDO::OPT_HYDRATE_FIELDS)) {
  598. if (!$this->getOption(xPDO::OPT_HYDRATE_RELATED_OBJECTS)) $classVars= get_object_vars($this);
  599. foreach ($this->_fields as $fldKey => $fldVal) {
  600. if (!array_key_exists($fldKey, $classVars)) {
  601. $this->$fldKey= & $this->_fields[$fldKey];
  602. }
  603. }
  604. }
  605. $this->setDirty();
  606. }
  607. /**
  608. * Get an option value for this instance.
  609. *
  610. * @param string $key The option key to retrieve a value for.
  611. * @param array|null $options An optional array to search for a value in first.
  612. * @param mixed $default A default value to return if no value is found; null is the default.
  613. * @return mixed The value of the option or the provided default if it is not set.
  614. */
  615. public function getOption($key, $options = null, $default = null) {
  616. if (is_array($options) && array_key_exists($key, $options)) {
  617. $value= $options[$key];
  618. } elseif (array_key_exists($key, $this->_options)) {
  619. $value= $this->_options[$key];
  620. } else {
  621. $value= $this->xpdo->getOption($key, null, $default);
  622. }
  623. return $value;
  624. }
  625. /**
  626. * Set an option value for this instance.
  627. *
  628. * @param string $key The option key to set a value for.
  629. * @param mixed $value A value to assign to the option.
  630. */
  631. public function setOption($key, $value) {
  632. $this->_options[$key]= $value;
  633. }
  634. /**
  635. * Set a field value by the field key or name.
  636. *
  637. * @todo Define and implement field validation.
  638. *
  639. * @param string $k The field key or name.
  640. * @param mixed $v The value to set the field to.
  641. * @param string|callable $vType A string indicating the format of the
  642. * provided value parameter, or a callable function that should be used to
  643. * set the field value, overriding the default behavior.
  644. * @return boolean Determines whether the value was set successfully and was
  645. * determined to be dirty (i.e. different from the previous value).
  646. */
  647. public function set($k, $v= null, $vType= '') {
  648. $set= false;
  649. $callback= '';
  650. $callable= !empty($vType) && is_callable($vType, false, $callback) ? true : false;
  651. $oldValue= null;
  652. if (is_string($k) && !empty($k)) {
  653. if (array_key_exists($k, $this->_fieldMeta)) {
  654. $oldValue= $this->_fields[$k];
  655. if (isset ($this->_fieldMeta[$k]['index']) && $this->_fieldMeta[$k]['index'] === 'pk' && isset ($this->_fieldMeta[$k]['generated'])) {
  656. if (!$this->_fieldMeta[$k]['generated'] === 'callback') {
  657. return false;
  658. }
  659. }
  660. if ($callable && $callback) {
  661. $set = $callback($k, $v, $this);
  662. } else {
  663. if (is_string($v) && $this->getOption(xPDO::OPT_ON_SET_STRIPSLASHES)) {
  664. $v= stripslashes($v);
  665. }
  666. if ($oldValue !== $v) {
  667. //type validation
  668. $phptype= $this->_fieldMeta[$k]['phptype'];
  669. $dbtype= $this->_fieldMeta[$k]['dbtype'];
  670. $allowNull= isset($this->_fieldMeta[$k]['null']) ? (boolean) $this->_fieldMeta[$k]['null'] : true;
  671. if ($v === null) {
  672. if ($allowNull) {
  673. $this->_fields[$k]= null;
  674. $set= true;
  675. } else {
  676. $this->xpdo->log(xPDO::LOG_LEVEL_ERROR, "{$this->_class}: Attempt to set NOT NULL field {$k} to NULL");
  677. }
  678. }
  679. else {
  680. switch ($phptype) {
  681. case 'timestamp' :
  682. case 'datetime' :
  683. $ts= false;
  684. if (preg_match('/int/i', $dbtype)) {
  685. if (strtolower($vType) == 'integer' || is_int($v) || $v == '0') {
  686. $ts= (integer) $v;
  687. } else {
  688. $ts= strtotime($v);
  689. }
  690. if ($ts === false) {
  691. $ts= 0;
  692. }
  693. $this->_fields[$k]= $ts;
  694. $set= true;
  695. } else {
  696. if ($vType == 'utc' || in_array($v, $this->xpdo->driver->_currentTimestamps) || $v === '0000-00-00 00:00:00') {
  697. $this->_fields[$k]= (string) $v;
  698. $set= true;
  699. } else {
  700. if (strtolower($vType) == 'integer' || is_int($v)) {
  701. $ts= intval($v);
  702. } elseif (is_string($v) && !empty($v)) {
  703. $ts= strtotime($v);
  704. }
  705. if ($ts !== false) {
  706. $this->_fields[$k]= strftime('%Y-%m-%d %H:%M:%S', $ts);
  707. $set= true;
  708. }
  709. }
  710. }
  711. break;
  712. case 'date' :
  713. if (preg_match('/int/i', $dbtype)) {
  714. if (strtolower($vType) == 'integer' || is_int($v) || $v == '0') {
  715. $ts= (integer) $v;
  716. } else {
  717. $ts= strtotime($v);
  718. }
  719. if ($ts === false) {
  720. $ts= 0;
  721. }
  722. $this->_fields[$k]= $ts;
  723. $set= true;
  724. } else {
  725. if ($vType == 'utc' || in_array($v, $this->xpdo->driver->_currentDates) || $v === '0000-00-00') {
  726. $this->_fields[$k]= $v;
  727. $set= true;
  728. } else {
  729. if (strtolower($vType) == 'integer' || is_int($v)) {
  730. $ts= intval($v);
  731. } elseif (is_string($v) && !empty($v)) {
  732. $ts= strtotime($v);
  733. }
  734. $ts= strtotime($v);
  735. if ($ts !== false) {
  736. $this->_fields[$k]= strftime('%Y-%m-%d', $ts);
  737. $set= true;
  738. }
  739. }
  740. }
  741. break;
  742. case 'boolean' :
  743. $this->_fields[$k]= intval($v);
  744. $set= true;
  745. break;
  746. case 'integer' :
  747. $this->_fields[$k]= intval($v);
  748. $set= true;
  749. break;
  750. case 'array' :
  751. if (is_object($v) && $v instanceof xPDOObject) {
  752. $v = $v->toArray();
  753. }
  754. if (is_array($v)) {
  755. $this->_fields[$k]= serialize($v);
  756. $set= true;
  757. }
  758. break;
  759. case 'json' :
  760. if (is_object($v) && $v instanceof xPDOObject) {
  761. $v = $v->toArray();
  762. }
  763. if (is_string($v)) {
  764. $v= $this->xpdo->fromJSON($v, true);
  765. }
  766. if (is_array($v)) {
  767. $this->_fields[$k]= $this->xpdo->toJSON($v);
  768. $set= true;
  769. }
  770. break;
  771. default :
  772. $this->_fields[$k]= $v;
  773. $set= true;
  774. }
  775. }
  776. }
  777. }
  778. } elseif ($this->getOption(xPDO::OPT_HYDRATE_ADHOC_FIELDS)) {
  779. $oldValue= isset($this->_fields[$k]) ? $this->_fields[$k] : null;
  780. if ($callable) {
  781. $set = $callback($k, $v, $this);
  782. } else {
  783. $this->_fields[$k]= $v;
  784. $set= true;
  785. }
  786. }
  787. if ($set && $oldValue !== $this->_fields[$k]) {
  788. $this->setDirty($k);
  789. } else {
  790. $set= false;
  791. }
  792. if ($set && $this->getOption(xPDO::OPT_HYDRATE_FIELDS) && !isset ($this->$k)) {
  793. $this->$k= & $this->_fields[$k];
  794. }
  795. } else {
  796. $this->xpdo->log(xPDO::LOG_LEVEL_ERROR, 'xPDOObject - Called set() with an invalid field name: ' . print_r($k, 1));
  797. }
  798. return $set;
  799. }
  800. /**
  801. * Get a field value (or a set of values) by the field key(s) or name(s).
  802. *
  803. * Warning: do not use the $format parameter if retrieving multiple values of
  804. * different types, as the format string will be applied to all types, most
  805. * likely with unpredicatable results. Optionally, you can supply an associate
  806. * array of format strings with the field key as the key for the format array.
  807. *
  808. * @param string|array $k A string (or an array of strings) representing the field
  809. * key or name.
  810. * @param string|array $format An optional variable (or an array of variables) to
  811. * format the return value(s).
  812. * @param mixed $formatTemplate An additional optional variable that can be used in
  813. * formatting the return value(s).
  814. * @return mixed The value(s) of the field(s) requested.
  815. */
  816. public function get($k, $format = null, $formatTemplate= null) {
  817. $value= null;
  818. if (is_array($k)) {
  819. if ($this->isLazy()) {
  820. $this->_loadFieldData($k);
  821. }
  822. foreach ($k as $key) {
  823. if (array_key_exists($key, $this->_fields)) {
  824. if (is_array($format) && isset ($format[$key])) {
  825. $formatTpl= null;
  826. if (is_array ($formatTemplate) && isset ($formatTemplate[$key])) {
  827. $formatTpl= $formatTemplate[$key];
  828. }
  829. $value[$key]= $this->get($key, $format[$key], $formatTpl);
  830. } elseif (!empty ($format) && is_string($format)) {
  831. $value[$key]= $this->get($key, $format, $formatTemplate);
  832. } else {
  833. $value[$key]= $this->get($key);
  834. }
  835. }
  836. }
  837. } elseif (is_string($k) && !empty($k)) {
  838. if (array_key_exists($k, $this->_fields)) {
  839. if ($this->isLazy($k)) {
  840. $this->_loadFieldData($k);
  841. }
  842. $dbType= $this->_getDataType($k);
  843. $fieldType= $this->_getPHPType($k);
  844. $value= $this->_fields[$k];
  845. if ($value !== null) {
  846. switch ($fieldType) {
  847. case 'boolean' :
  848. $value= (boolean) $value;
  849. break;
  850. case 'integer' :
  851. $value= intval($value);
  852. if (is_string($format) && !empty ($format)) {
  853. if (strpos($format, 're:') === 0) {
  854. if (!empty ($formatTemplate) && is_string($formatTemplate)) {
  855. $value= preg_replace(substr($format, 3), $formatTemplate, $value);
  856. }
  857. } else {
  858. $value= sprintf($format, $value);
  859. }
  860. }
  861. break;
  862. case 'float' :
  863. $value= (float) $value;
  864. if (is_string($format) && !empty ($format)) {
  865. if (strpos($format, 're:') === 0) {
  866. if (!empty ($formatTemplate) && is_string($formatTemplate)) {
  867. $value= preg_replace(substr($format, 3), $formatTemplate, $value);
  868. }
  869. } else {
  870. $value= sprintf($format, $value);
  871. }
  872. }
  873. break;
  874. case 'timestamp' :
  875. case 'datetime' :
  876. if (preg_match('/int/i', $dbType)) {
  877. $ts= intval($value);
  878. } elseif (in_array($value, $this->xpdo->driver->_currentTimestamps)) {
  879. $ts= time();
  880. } else {
  881. $ts= strtotime($value);
  882. }
  883. if ($ts !== false && !empty($value)) {
  884. if (is_string($format) && !empty ($format)) {
  885. if (strpos($format, 're:') === 0) {
  886. $value= date('Y-m-d H:M:S', $ts);
  887. if (!empty ($formatTemplate) && is_string($formatTemplate)) {
  888. $value= preg_replace(substr($format, 3), $formatTemplate, $value);
  889. }
  890. } elseif (strpos($format, '%') === false) {
  891. $value= date($format, $ts);
  892. } else {
  893. $value= strftime($format, $ts);
  894. }
  895. } else {
  896. $value= strftime('%Y-%m-%d %H:%M:%S', $ts);
  897. }
  898. }
  899. break;
  900. case 'date' :
  901. if (preg_match('/int/i', $dbType)) {
  902. $ts= intval($value);
  903. } elseif (in_array($value, $this->xpdo->driver->_currentDates)) {
  904. $ts= time();
  905. } else {
  906. $ts= strtotime($value);
  907. }
  908. if ($ts !== false && !empty($value)) {
  909. if (is_string($format) && !empty ($format)) {
  910. if (strpos($format, 're:') === 0) {
  911. $value= strftime('%Y-%m-%d', $ts);
  912. if (!empty ($formatTemplate) && is_string($formatTemplate)) {
  913. $value= preg_replace(substr($format, 3), $formatTemplate, $value);
  914. }
  915. } elseif (strpos($format, '%') === false) {
  916. $value= date($format, $ts);
  917. } elseif ($ts !== false) {
  918. $value= strftime($format, $ts);
  919. }
  920. } else {
  921. $value= strftime('%Y-%m-%d', $ts);
  922. }
  923. }
  924. break;
  925. case 'array' :
  926. if (is_string($value)) {
  927. $value= unserialize($value);
  928. }
  929. break;
  930. case 'json' :
  931. if (is_string($value) && strlen($value) > 1) {
  932. $value= $this->xpdo->fromJSON($value, true);
  933. }
  934. break;
  935. default :
  936. if (is_string($format) && !empty ($format)) {
  937. if (strpos($format, 're:') === 0) {
  938. if (!empty ($formatTemplate) && is_string($formatTemplate)) {
  939. $value= preg_replace(substr($format, 3), $formatTemplate, $value);
  940. }
  941. } else {
  942. $value= sprintf($format, $value);
  943. }
  944. }
  945. break;
  946. }
  947. }
  948. }
  949. }
  950. return $value;
  951. }
  952. /**
  953. * Gets an object related to this instance by a foreign key relationship.
  954. *
  955. * Use this for 1:? (one:zero-or-one) or 1:1 relationships, which you can
  956. * distinguish by setting the nullability of the field representing the
  957. * foreign key.
  958. *
  959. * For all 1:* relationships for this instance, see {@link getMany()}.
  960. *
  961. * @see xPDOObject::getMany()
  962. * @see xPDOObject::addOne()
  963. * @see xPDOObject::addMany()
  964. *
  965. * @param string $alias Alias of the foreign class representing the related
  966. * object.
  967. * @param object $criteria xPDOCriteria object to get the related objects
  968. * @param boolean|integer $cacheFlag Indicates if the object should be
  969. * cached and optionally, by specifying an integer value, for how many
  970. * seconds.
  971. * @return xPDOObject|null The related object or null if no instance exists.
  972. */
  973. public function & getOne($alias, $criteria= null, $cacheFlag= true) {
  974. $object= null;
  975. if ($fkdef= $this->getFKDefinition($alias)) {
  976. $k= $fkdef['local'];
  977. $fk= $fkdef['foreign'];
  978. if (isset ($this->_relatedObjects[$alias])) {
  979. if (is_object($this->_relatedObjects[$alias])) {
  980. $object= & $this->_relatedObjects[$alias];
  981. return $object;
  982. }
  983. }
  984. if ($criteria === null) {
  985. $criteria= array ($fk => $this->get($k));
  986. }
  987. if ($object= $this->xpdo->getObject($fkdef['class'], $criteria, $cacheFlag)) {
  988. $this->_relatedObjects[$alias]= $object;
  989. }
  990. } else {
  991. $this->xpdo->log(xPDO::LOG_LEVEL_WARN, "Could not getOne: foreign key definition for alias {$alias} not found.");
  992. }
  993. return $object;
  994. }
  995. /**
  996. * Gets a collection of objects related by aggregate or composite relations.
  997. *
  998. * @see xPDOObject::getOne()
  999. * @see xPDOObject::addOne()
  1000. * @see xPDOObject::addMany()
  1001. *
  1002. * @param string $alias Alias of the foreign class representing the related
  1003. * object.
  1004. * @param object $criteria xPDOCriteria object to get the related objects
  1005. * @param boolean|integer $cacheFlag Indicates if the objects should be
  1006. * cached and optionally, by specifying an integer value, for how many
  1007. * seconds.
  1008. * @return array A collection of related objects or an empty array.
  1009. */
  1010. public function & getMany($alias, $criteria= null, $cacheFlag= true) {
  1011. $collection= $this->_getRelatedObjectsByFK($alias, $criteria, $cacheFlag);
  1012. return $collection;
  1013. }
  1014. /**
  1015. * Adds an object related to this instance by a foreign key relationship.
  1016. *
  1017. * @see xPDOObject::getOne()
  1018. * @see xPDOObject::getMany()
  1019. * @see xPDOObject::addMany()
  1020. *
  1021. * @param mixed &$obj A single object to be related to this instance.
  1022. * @param string $alias The relation alias of the related object (only
  1023. * required if more than one relation exists to the same foreign class).
  1024. * @return boolean True if the related object was added to this object.
  1025. */
  1026. public function addOne(& $obj, $alias= '') {
  1027. $added= false;
  1028. if (is_object($obj)) {
  1029. if (empty ($alias)) {
  1030. if ($obj->_alias == $obj->_class) {
  1031. $aliases = $this->_getAliases($obj->_class, 1);
  1032. if (!empty($aliases)) {
  1033. $obj->_alias = reset($aliases);
  1034. }
  1035. }
  1036. $alias= $obj->_alias;
  1037. }
  1038. $fkMeta= $this->getFKDefinition($alias);
  1039. if ($fkMeta && $fkMeta['cardinality'] === 'one') {
  1040. $obj->_alias= $alias;
  1041. $fk= $fkMeta['foreign'];
  1042. $key= $fkMeta['local'];
  1043. $owner= isset ($fkMeta['owner']) ? $fkMeta['owner'] : 'local';
  1044. $kval= $this->get($key);
  1045. $fkval= $obj->get($fk);
  1046. if ($owner == 'local') {
  1047. $obj->set($fk, $kval);
  1048. }
  1049. else {
  1050. $this->set($key, $fkval);
  1051. }
  1052. $this->_relatedObjects[$obj->_alias]= $obj;
  1053. $this->setDirty($key);
  1054. $added= true;
  1055. } else {
  1056. $this->xpdo->log(xPDO::LOG_LEVEL_WARN, "Foreign key definition for class {$obj->class}, alias {$obj->_alias} not found, or cardinality is not 'one'.");
  1057. }
  1058. } else {
  1059. $this->xpdo->log(xPDO::LOG_LEVEL_WARN, "Attempt to add a non-object to a relation with alias ({$alias})");
  1060. }
  1061. if (!$added) {
  1062. $this->xpdo->log(xPDO::LOG_LEVEL_WARN, "Could not add related object! " . (is_object($obj) ? print_r($obj->toArray(), true) : ''));
  1063. }
  1064. return $added;
  1065. }
  1066. /**
  1067. * Adds an object or collection of objects related to this class.
  1068. *
  1069. * This method adds an object or collection of objects in a one-to-
  1070. * many foreign key relationship with this object to the internal list of
  1071. * related objects. By adding these related objects, you can cascade
  1072. * {@link xPDOObject::save()}, {@link xPDOObject::remove()}, and other
  1073. * operations based on the type of relationships defined.
  1074. *
  1075. * @see xPDOObject::addOne()
  1076. * @see xPDOObject::getOne()
  1077. * @see xPDOObject::getMany()
  1078. *
  1079. * @param mixed &$obj A single object or collection of objects to be related
  1080. * to this instance via the intersection class.
  1081. * @param string $alias An optional alias, required only for instances where
  1082. * you have more than one relation defined to the same class.
  1083. * @return boolean Indicates if the addMany was successful.
  1084. */
  1085. public function addMany(& $obj, $alias= '') {
  1086. $added= false;
  1087. if (!is_array($obj)) {
  1088. if (is_object($obj)) {
  1089. if (empty ($alias)) {
  1090. if ($obj->_alias == $obj->_class) {
  1091. $aliases = $this->_getAliases($obj->_class, 1);
  1092. if (!empty($aliases)) {
  1093. $obj->_alias = reset($aliases);
  1094. }
  1095. }
  1096. $alias= $obj->_alias;
  1097. }
  1098. if ($fkMeta= $this->getFKDefinition($alias)) {
  1099. $obj->_alias= $alias;
  1100. if ($fkMeta['cardinality'] === 'many') {
  1101. if ($obj->_new) {
  1102. $objpk= '__new' . (isset ($this->_relatedObjects[$alias]) ? count($this->_relatedObjects[$alias]) : 0);
  1103. } else {
  1104. $objpk= $obj->getPrimaryKey();
  1105. if (is_array($objpk)) {
  1106. $objpk= implode('-', $objpk);
  1107. }
  1108. }
  1109. $this->_relatedObjects[$alias][$objpk]= $obj;
  1110. if ($this->xpdo->getDebug() === true) $this->xpdo->log(xPDO::LOG_LEVEL_DEBUG, 'Added related object with alias: ' . $alias . ' and pk: ' . $objpk . "\n" . print_r($obj->toArray('', true), true));
  1111. $added= true;
  1112. }
  1113. }
  1114. }
  1115. } else {
  1116. foreach ($obj as $o) {
  1117. $added= $this->addMany($o, $alias);
  1118. }
  1119. }
  1120. return $added;
  1121. }
  1122. /**
  1123. * Persist new or changed objects to the database container.
  1124. *
  1125. * Inserts or updates the database record representing this object and any
  1126. * new or changed related object records. Both aggregate and composite
  1127. * related objects will be saved as appropriate, before or following the
  1128. * save operation on the controlling instance.
  1129. *
  1130. * @param boolean|integer $cacheFlag Indicates if the saved object(s) should
  1131. * be cached and optionally, by specifying an integer value, for how many
  1132. * seconds before expiring. Overrides the cacheFlag for the object(s).
  1133. * @return boolean Returns true on success, false on failure.
  1134. */
  1135. public function save($cacheFlag= null) {
  1136. if ($this->isLazy()) {
  1137. $this->xpdo->log(xPDO::LOG_LEVEL_ERROR, 'Attempt to save lazy object: ' . print_r($this->toArray('', true), 1));
  1138. return false;
  1139. }
  1140. $result= true;
  1141. $sql= '';
  1142. $pk= $this->getPrimaryKey();
  1143. $pkn= $this->getPK();
  1144. $pkGenerated= false;
  1145. if ($this->isNew()) {
  1146. $this->setDirty();
  1147. }
  1148. if ($this->getOption(xPDO::OPT_VALIDATE_ON_SAVE)) {
  1149. if (!$this->validate()) {
  1150. return false;
  1151. }
  1152. }
  1153. $this->_saveRelatedObjects();
  1154. if (!empty ($this->_dirty)) {
  1155. $cols= array ();
  1156. $bindings= array ();
  1157. $updateSql= array ();
  1158. foreach (array_keys($this->_dirty) as $_k) {
  1159. if (!array_key_exists($_k, $this->_fieldMeta)) {
  1160. continue;
  1161. }
  1162. if (isset($this->_fieldMeta[$_k]['generated'])) {
  1163. if (!$this->_new || !isset($this->_fields[$_k]) || empty($this->_fields[$_k])) {
  1164. $pkGenerated= true;
  1165. continue;
  1166. }
  1167. }
  1168. if ($this->_fieldMeta[$_k]['phptype'] === 'password') {
  1169. $this->_fields[$_k]= $this->encode($this->_fields[$_k], 'password');
  1170. }
  1171. $fieldType= PDO::PARAM_STR;
  1172. $fieldValue= $this->_fields[$_k];
  1173. if (in_array($this->_fieldMeta[$_k]['phptype'], array ('datetime', 'timestamp')) && !empty($this->_fieldMeta[$_k]['attributes']) && $this->_fieldMeta[$_k]['attributes'] == 'ON UPDATE CURRENT_TIMESTAMP') {
  1174. $this->_fields[$_k]= strftime('%Y-%m-%d %H:%M:%S');
  1175. continue;
  1176. }
  1177. elseif ($fieldValue === null || $fieldValue === 'NULL') {
  1178. if ($this->_new) continue;
  1179. $fieldType= PDO::PARAM_NULL;
  1180. $fieldValue= null;
  1181. }
  1182. elseif (in_array($this->_fieldMeta[$_k]['phptype'], array ('timestamp', 'datetime')) && in_array($fieldValue, $this->xpdo->driver->_currentTimestamps, true)) {
  1183. $this->_fields[$_k]= strftime('%Y-%m-%d %H:%M:%S');
  1184. continue;
  1185. }
  1186. elseif (in_array($this->_fieldMeta[$_k]['phptype'], array ('date')) && in_array($fieldValue, $this->xpdo->driver->_currentDates, true)) {
  1187. $this->_fields[$_k]= strftime('%Y-%m-%d');
  1188. continue;
  1189. }
  1190. elseif ($this->_fieldMeta[$_k]['phptype'] == 'timestamp' && preg_match('/int/i', $this->_fieldMeta[$_k]['dbtype'])) {
  1191. $fieldType= PDO::PARAM_INT;
  1192. }
  1193. elseif (!in_array($this->_fieldMeta[$_k]['phptype'], array ('string','password','datetime','timestamp','date','time','array','json'))) {
  1194. $fieldType= PDO::PARAM_INT;
  1195. }
  1196. if ($this->_new) {
  1197. $cols[$_k]= $this->xpdo->escape($_k);
  1198. $bindings[":{$_k}"]['value']= $fieldValue;
  1199. $bindings[":{$_k}"]['type']= $fieldType;
  1200. } else {
  1201. $bindings[":{$_k}"]['value']= $fieldValue;
  1202. $bindings[":{$_k}"]['type']= $fieldType;
  1203. $updateSql[]= $this->xpdo->escape($_k) . " = :{$_k}";
  1204. }
  1205. }
  1206. if ($this->_new) {
  1207. $sql= "INSERT INTO {$this->_table} (" . implode(', ', array_values($cols)) . ") VALUES (" . implode(', ', array_keys($bindings)) . ")";
  1208. } else {
  1209. if ($pk && $pkn) {
  1210. if (is_array($pkn)) {
  1211. $iteration= 0;
  1212. $where= '';
  1213. foreach ($pkn as $k => $v) {
  1214. $vt= PDO::PARAM_INT;
  1215. if ($this->_fieldMeta[$k]['phptype'] == 'string') {
  1216. $vt= PDO::PARAM_STR;
  1217. }
  1218. if ($iteration) {
  1219. $where .= " AND ";
  1220. }
  1221. $where .= $this->xpdo->escape($k) . " = :{$k}";
  1222. $bindings[":{$k}"]['value']= $this->_fields[$k];
  1223. $bindings[":{$k}"]['type']= $vt;
  1224. $iteration++;
  1225. }
  1226. } else {
  1227. $pkn= $this->getPK();
  1228. $pkt= PDO::PARAM_INT;
  1229. if ($this->_fieldMeta[$pkn]['phptype'] == 'string') {
  1230. $pkt= PDO::PARAM_STR;
  1231. }
  1232. $bindings[":{$pkn}"]['value']= $pk;
  1233. $bindings[":{$pkn}"]['type']= $pkt;
  1234. $where= $this->xpdo->escape($pkn) . ' = :' . $pkn;
  1235. }
  1236. if (!empty ($updateSql)) {
  1237. $sql= "UPDATE {$this->_table} SET " . implode(',', $updateSql) . " WHERE {$where}";
  1238. }
  1239. }
  1240. }
  1241. if (!empty ($sql) && $criteria= new xPDOCriteria($this->xpdo, $sql)) {
  1242. if ($criteria->prepare()) {
  1243. if (!empty ($bindings)) {
  1244. $criteria->bind($bindings, true, false);
  1245. }
  1246. if ($this->xpdo->getDebug() === true) $this->xpdo->log(xPDO::LOG_LEVEL_DEBUG, "Executing SQL:\n{$sql}\nwith bindings:\n" . print_r($bindings, true));
  1247. if (!$result= $criteria->stmt->execute()) {
  1248. $errorInfo= $criteria->stmt->errorInfo();
  1249. $this->xpdo->log(xPDO::LOG_LEVEL_ERROR, "Error " . $criteria->stmt->errorCode() . " executing statement:\n" . $criteria->toSQL() . "\n" . print_r($errorInfo, true));
  1250. if (($errorInfo[1] == '1146' || $errorInfo[1] == '1') && $this->getOption(xPDO::OPT_AUTO_CREATE_TABLES)) {
  1251. if ($this->xpdo->getManager() && $this->xpdo->manager->createObjectContainer($this->_class) === true) {
  1252. if (!$result= $criteria->stmt->execute()) {
  1253. $this->xpdo->log(xPDO::LOG_LEVEL_ERROR, "Error " . $criteria->stmt->errorCode() . " executing statement:\n{$sql}\n");
  1254. }
  1255. } else {
  1256. $this->xpdo->log(xPDO::LOG_LEVEL_ERROR, "Error " . $this->xpdo->errorCode() . " attempting to create object container for class {$this->_class}:\n" . print_r($this->xpdo->errorInfo(), true));
  1257. }
  1258. }
  1259. }
  1260. } else {
  1261. $result= false;
  1262. }
  1263. if ($result) {
  1264. if ($pkn && !$pk) {
  1265. if ($pkGenerated) {
  1266. $this->_fields[$this->getPK()]= $this->xpdo->lastInsertId();
  1267. }
  1268. $pk= $this->getPrimaryKey();
  1269. }
  1270. if ($pk || !$this->getPK()) {
  1271. $this->_dirty= array();
  1272. $this->_validated= array();
  1273. $this->_new= false;
  1274. }
  1275. $callback = $this->getOption(xPDO::OPT_CALLBACK_ON_SAVE);
  1276. if ($callback && is_callable($callback)) {
  1277. call_user_func($callback, array('className' => $this->_class, 'criteria' => $criteria, 'object' => $this));
  1278. }
  1279. if ($this->xpdo->_cacheEnabled && $pk && ($cacheFlag || ($cacheFlag === null && $this->_cacheFlag))) {
  1280. $cacheKey= is_array($pk) ? implode('_', $pk) : $pk;
  1281. if (is_bool($cacheFlag)) {
  1282. $expires= 0;
  1283. } else {
  1284. $expires= intval($cacheFlag);
  1285. }
  1286. $this->xpdo->toCache($this->xpdo->getTableClass($this->_class) . '_' . $cacheKey, $this, $expires, array('modified' => true));
  1287. }
  1288. }
  1289. }
  1290. }
  1291. $this->_saveRelatedObjects();
  1292. if ($result) {
  1293. $this->_dirty= array ();
  1294. $this->_validated= array ();
  1295. }
  1296. return $result;
  1297. }
  1298. /**
  1299. * Searches for any related objects with pending changes to save.
  1300. *
  1301. * @access protected
  1302. * @uses xPDOObject::_saveRelatedObject()
  1303. * @return integer The number of related objects processed.
  1304. */
  1305. protected function _saveRelatedObjects() {
  1306. $saved= 0;
  1307. if (!empty ($this->_relatedObjects)) {
  1308. foreach ($this->_relatedObjects as $alias => $ro) {
  1309. $objects= array ();
  1310. if (is_object($ro)) {
  1311. $primaryKey= $ro->_new ? '__new' : $ro->getPrimaryKey();
  1312. if (is_array($primaryKey)) $primaryKey= implode('-', $primaryKey);
  1313. $objects[$primaryKey]= & $ro;
  1314. $cardinality= 'one';
  1315. }
  1316. elseif (is_array($ro)) {
  1317. $objects= $ro;
  1318. $cardinality= 'many';
  1319. }
  1320. if (!empty($objects)) {
  1321. foreach ($objects as $pk => $obj) {
  1322. if ($fkMeta= $this->getFKDefinition($alias)) {
  1323. if ($this->_saveRelatedObject($obj, $fkMeta)) {
  1324. if ($cardinality == 'many') {
  1325. $newPk= $obj->getPrimaryKey();
  1326. if (is_array($newPk)) $newPk= implode('-', $newPk);
  1327. if ($pk != $newPk) {
  1328. $this->_relatedObjects[$alias][$newPk]= $obj;
  1329. unset($this->_relatedObjects[$alias][$pk]);
  1330. }
  1331. }
  1332. $saved++;
  1333. }
  1334. }
  1335. }
  1336. }
  1337. }
  1338. }
  1339. return $saved;
  1340. }
  1341. /**
  1342. * Save a related object with pending changes.
  1343. *
  1344. * This function is also responsible for setting foreign keys when new
  1345. * related objects are being saved, as well as local keys when the host
  1346. * object is new and needs the foreign key.
  1347. *
  1348. * @access protected
  1349. * @param xPDOObject &$obj A reference to the related object.
  1350. * @param array $fkMeta The meta data representing the relation.
  1351. * @return boolean True if a related object was dirty and saved successfully.
  1352. */
  1353. protected function _saveRelatedObject(& $obj, $fkMeta) {
  1354. $saved= false;
  1355. $local= $fkMeta['local'];
  1356. $foreign= $fkMeta['foreign'];
  1357. $cardinality= $fkMeta['cardinality'];
  1358. $owner= isset ($fkMeta['owner']) ? $fkMeta['owner'] : '';
  1359. if (!$owner) {
  1360. $owner= $cardinality === 'many' ? 'foreign' : 'local';
  1361. }
  1362. if ($owner === 'local' && $fk= $this->get($local)) {
  1363. $obj->set($foreign, $fk);
  1364. $saved= $obj->save();
  1365. } elseif ($owner === 'foreign') {
  1366. if ($obj->isNew() || !empty($obj->_dirty)) {
  1367. $saved= $obj->save();
  1368. }
  1369. $fk= $obj->get($foreign);
  1370. if ($fk) {
  1371. $this->set($local, $fk);
  1372. }
  1373. }
  1374. if ($this->xpdo->getDebug() === true) $this->xpdo->log(xPDO::LOG_LEVEL_DEBUG , ($saved ? 'Successfully saved' : 'Could not save') . " related object\nMain object: " . print_r($this->toArray('', true), true) . "\nRelated Object: " . print_r($obj->toArray('', true), true));
  1375. return $saved;
  1376. }
  1377. /**
  1378. * Remove the persistent instance of an object permanently.
  1379. *
  1380. * Deletes the persistent object isntance stored in the database when
  1381. * called, including any dependent objects defined by composite foreign key
  1382. * relationships.
  1383. *
  1384. * @todo Implement some way to reassign ownership of related composite
  1385. * objects when remove is called, perhaps by passing another object
  1386. * instance as an optional parameter, or creating a separate method.
  1387. *
  1388. * @param array $ancestors Keeps track of classes which have already been
  1389. * removed to prevent loop with circular references.
  1390. * @return boolean Returns true on success, false on failure.
  1391. */
  1392. public function remove(array $ancestors= array ()) {
  1393. $result= false;
  1394. if ($pk= $this->getPrimaryKey()) {
  1395. if (!empty ($this->_composites)) {
  1396. $current= array ($this->_class, $this->_alias);
  1397. foreach ($this->_composites as $compositeAlias => $composite) {
  1398. if (in_array($compositeAlias, $ancestors) || in_array($composite['class'], $ancestors)) {
  1399. continue;
  1400. }
  1401. if ($composite['cardinality'] === 'many') {
  1402. if ($many= $this->getMany($compositeAlias)) {
  1403. foreach ($many as $one) {
  1404. $ancestors[]= $compositeAlias;
  1405. $newAncestors= $ancestors + $current;
  1406. if (!$one->remove($newAncestors)) {
  1407. $this->xpdo->log(xPDO::LOG_LEVEL_ERROR, "Error removing dependent object: " . print_r($one->toArray('', true), true));
  1408. }
  1409. }
  1410. unset($many);
  1411. }
  1412. }
  1413. elseif ($one= $this->getOne($compositeAlias)) {
  1414. $ancestors[]= $compositeAlias;
  1415. $newAncestors= $ancestors + $current;
  1416. if (!$one->remove($newAncestors)) {
  1417. $this->xpdo->log(xPDO::LOG_LEVEL_ERROR, "Error removing dependent object: " . print_r($one->toArray('', true), true));
  1418. }
  1419. unset($one);
  1420. }
  1421. }
  1422. }
  1423. $delete= $this->xpdo->newQuery($this->_class);
  1424. $delete->command('DELETE');
  1425. $delete->where($pk);
  1426. // $delete->limit(1);
  1427. $stmt= $delete->prepare();
  1428. if (is_object($stmt)) {
  1429. if (!$result= $stmt->execute()) {
  1430. $this->xpdo->log(xPDO::LOG_LEVEL_ERROR, 'Could not delete from ' . $this->_table . '; primary key specified was ' . print_r($pk, true) . "\n" . print_r($stmt->errorInfo(), true));
  1431. } else {
  1432. $callback = $this->getOption(xPDO::OPT_CALLBACK_ON_REMOVE);
  1433. if ($callback && is_callable($callback)) {
  1434. call_user_func($callback, array('className' => $this->_class, 'criteria' => $delete, 'object' => $this));
  1435. }
  1436. if ($this->xpdo->_cacheEnabled) {
  1437. $cacheKey= is_array($pk) ? implode('_', $pk) : $pk;
  1438. $this->xpdo->toCache($this->xpdo->getTableClass($this->_class) . '_' . $cacheKey, null, 0, array('modified' => true));
  1439. }
  1440. $this->xpdo->log(xPDO::LOG_LEVEL_INFO, "Removed {$this->_class} instance with primary key " . print_r($pk, true));
  1441. }
  1442. } else {
  1443. $this->xpdo->log(xPDO::LOG_LEVEL_ERROR, 'Could not build criteria to delete from ' . $this->_table . '; primary key specified was ' . print_r($pk, true));
  1444. }
  1445. }
  1446. return $result;
  1447. }
  1448. /**
  1449. * Gets the value (or values) of the primary key field(s) for the object.
  1450. *
  1451. * @param boolean $validateCompound If any of the keys in a compound primary key are empty
  1452. * or null, and the default value is not allowed to be null, do not return an array, instead
  1453. * return null; the default is true
  1454. * @return mixed The string (or an array) representing the value(s) of the
  1455. * primary key field(s) for this instance.
  1456. */
  1457. public function getPrimaryKey($validateCompound= true) {
  1458. $value= null;
  1459. if ($pk= $this->getPK()) {
  1460. if (is_array($pk)) {
  1461. foreach ($pk as $k) {
  1462. $_pk= $this->get($k);
  1463. if (($_pk && strtolower($_pk) !== 'null') || !$validateCompound) {
  1464. $value[]= $_pk;
  1465. } else {
  1466. if (isset ($this->_fieldMeta[$k]['default'])) {
  1467. $value[]= $this->_fieldMeta[$k]['default'];
  1468. $this->_fields[$k]= $this->_fieldMeta[$k]['default'];
  1469. }
  1470. elseif (isset ($this->_fieldMeta[$k]['null']) && $this->_fieldMeta[$k]['null']) {
  1471. $value[]= null;
  1472. }
  1473. else {
  1474. $value= null;
  1475. break;
  1476. }
  1477. }
  1478. }
  1479. } else {
  1480. $value= $this->get($pk);
  1481. }
  1482. }
  1483. if (!$value && $this->xpdo->getDebug() === true) {
  1484. $this->xpdo->log(xPDO::LOG_LEVEL_DEBUG, "No primary key value found for pk definition: " . print_r($this->getPK(), true));
  1485. }
  1486. return $value;
  1487. }
  1488. /**
  1489. * Gets the name (or names) of the primary key field(s) for the object.
  1490. *
  1491. * @return mixed The string (or an array of strings) representing the name(s)
  1492. * of the primary key field(s) for this instance.
  1493. */
  1494. public function getPK() {
  1495. if ($this->_pk === null) {
  1496. $this->_pk= $this->xpdo->getPK($this->_class);
  1497. }
  1498. return $this->_pk;
  1499. }
  1500. /**
  1501. * Gets the type of the primary key field for the object.
  1502. *
  1503. * @return string The type of the primary key field for this instance.
  1504. */
  1505. public function getPKType() {
  1506. if ($this->_pktype === null) {
  1507. if ($this->_pk === null) {
  1508. $this->getPK();
  1509. }
  1510. $this->_pktype= $this->xpdo->getPKType($this->_class);
  1511. }
  1512. return $this->_pktype;
  1513. }
  1514. /**
  1515. * Get the name of a class related by foreign key to a specified field key.
  1516. *
  1517. * This is generally used to lookup classes involved in one-to-one
  1518. * relationships with the current object.
  1519. *
  1520. * @param string $k The field name or key to lookup a related class for.
  1521. */
  1522. public function getFKClass($k) {
  1523. $fkclass= null;
  1524. if (is_string($k)) {
  1525. if (!empty ($this->_aggregates)) {
  1526. foreach ($this->_aggregates as $aggregateAlias => $aggregate) {
  1527. if ($aggregate['local'] === $k) {
  1528. $fkclass= $aggregate['class'];
  1529. break;
  1530. }
  1531. }
  1532. }
  1533. if (!$fkclass && !empty ($this->_composites)) {
  1534. foreach ($this->_composites as $compositeAlias => $composite) {
  1535. if ($composite['local'] === $k) {
  1536. $fkclass= $composite['class'];
  1537. break;
  1538. }
  1539. }
  1540. }
  1541. $fkclass= $this->xpdo->loadClass($fkclass);
  1542. }
  1543. if ($this->xpdo->getDebug() === true) $this->xpdo->log(xPDO::LOG_LEVEL_DEBUG, "Returning foreign key class {$fkclass} for column {$k}");
  1544. return $fkclass;
  1545. }
  1546. /**
  1547. * Get a foreign key definition for a specific classname.
  1548. *
  1549. * This is generally used to lookup classes in a one-to-many relationship
  1550. * with the current object.
  1551. *
  1552. * @param string $alias Alias of the related class to lookup a foreign key
  1553. * definition from.
  1554. * @return array A foreign key definition.
  1555. */
  1556. public function getFKDefinition($alias) {
  1557. return $this->xpdo->getFKDefinition($this->_class, $alias);
  1558. }
  1559. /**
  1560. * Gets a field name as represented in the database container.
  1561. *
  1562. * This gets the name of the field, fully-qualified by either the object
  1563. * table name or a specified alias, and properly quoted.
  1564. *
  1565. * @param string $k The simple name of the field.
  1566. * @param string $alias An optional alias for the table in a specific query.
  1567. * @return string The name of the field, qualified with the table name or an
  1568. * optional table alias.
  1569. */
  1570. public function getFieldName($k, $alias= null) {
  1571. if ($this->fieldNames === null) {
  1572. $this->_initFields();
  1573. }
  1574. $name= null;
  1575. if (is_string($k) && isset ($this->fieldNames[$k])) {
  1576. $name= $this->fieldNames[$k];
  1577. }
  1578. if ($name !== null && $alias !== null) {
  1579. $name= str_replace("{$this->_table}.", "{$alias}.", $name);
  1580. }
  1581. return $name;
  1582. }
  1583. /**
  1584. * Copies the object fields and corresponding values to an associative array.
  1585. *
  1586. * @param string $keyPrefix An optional prefix to prepend to the field values.
  1587. * @param boolean $rawValues An optional flag indicating if you want the raw values instead of
  1588. * those returned by the {@link xPDOObject::get()} function.
  1589. * @param boolean $excludeLazy An option flag indicating if you want to exclude lazy fields from
  1590. * the resulting array; the default behavior is to include them which means the object will
  1591. * query the database for the lazy fields before providing the value.
  1592. * @return array An array representation of the object fields/values.
  1593. */
  1594. public function toArray($keyPrefix= '', $rawValues= false, $excludeLazy= false) {
  1595. $objarray= null;
  1596. if (is_array($this->_fields)) {
  1597. $keys= array_keys($this->_fields);
  1598. if (!$excludeLazy && $this->isLazy()) {
  1599. $this->_loadFieldData($this->_lazy);
  1600. }
  1601. foreach ($keys as $key) {
  1602. if (!$excludeLazy || !$this->isLazy($key)) {
  1603. $objarray[$keyPrefix . $key]= $rawValues ? $this->_fields[$key] : $this->get($key);
  1604. }
  1605. }
  1606. }
  1607. return $objarray;
  1608. }
  1609. /**
  1610. * Sets object fields from an associative array of key => value pairs.
  1611. *
  1612. * @param array $fldarray An associative array of key => values.
  1613. * @param string $keyPrefix Specify an optional prefix to strip from all array
  1614. * keys in fldarray.
  1615. * @param boolean $setPrimaryKeys Optional param to set generated primary keys.
  1616. * @param boolean $rawValues Optional way to set values without calling the
  1617. * {@link xPDOObject::set()} method.
  1618. * @param boolean $adhocValues Optional way to set adhoc values so that all the values of
  1619. * fldarray become object vars.
  1620. */
  1621. public function fromArray($fldarray, $keyPrefix= '', $setPrimaryKeys= false, $rawValues= false, $adhocValues= false) {
  1622. if (is_array($fldarray)) {
  1623. $pkSet= false;
  1624. $generatedKey= false;
  1625. reset($fldarray);
  1626. while (list ($key, $val)= each($fldarray)) {
  1627. if (!empty ($keyPrefix)) {
  1628. $prefixPos= strpos($key, $keyPrefix);
  1629. if ($prefixPos === 0) {
  1630. $key= substr($key, strlen($keyPrefix));
  1631. } else {
  1632. continue;
  1633. }
  1634. if ($this->xpdo->getDebug() === true) $this->xpdo->log(xPDO::LOG_LEVEL_DEBUG, "Stripped prefix {$keyPrefix} to produce key {$key}");
  1635. }
  1636. if (isset ($this->_fieldMeta[$key]['index']) && $this->_fieldMeta[$key]['index'] == 'pk') {
  1637. if ($setPrimaryKeys) {
  1638. if (isset ($this->_fieldMeta[$key]['generated'])) {
  1639. $generatedKey= true;
  1640. }
  1641. if ($this->_new) {
  1642. if ($rawValues || $generatedKey) {
  1643. $this->_setRaw($key, $val);
  1644. } else {
  1645. $this->set($key, $val);
  1646. }
  1647. $pkSet= true;
  1648. }
  1649. }
  1650. }
  1651. elseif (isset ($this->_fieldMeta[$key])) {
  1652. if ($rawValues) {
  1653. $this->_setRaw($key, $val);
  1654. } else {
  1655. $this->set($key, $val);
  1656. }
  1657. }
  1658. elseif ($adhocValues || $this->getOption(xPDO::OPT_HYDRATE_ADHOC_FIELDS)) {
  1659. if ($rawValues) {
  1660. $this->_setRaw($key, $val);
  1661. if (!isset ($this->$key)) {
  1662. if ($this->getOption(xPDO::OPT_HYDRATE_RELATED_OBJECTS) && is_object($val) || $this->getOption(xPDO::OPT_HYDRATE_FIELDS) && !is_object($val)) {
  1663. $this->$key= & $this->_fields[$key];
  1664. }
  1665. }
  1666. } else {
  1667. $this->set($key, $val);
  1668. }
  1669. }
  1670. if ($this->isLazy($key)) {
  1671. $this->_lazy = array_diff($this->_lazy, array($key));
  1672. }
  1673. }
  1674. }
  1675. }
  1676. /**
  1677. * Add a validation rule to an object field for this instance.
  1678. *
  1679. * @param string $field The field key to apply the rule to.
  1680. * @param string $name A name to identify the rule.
  1681. * @param string $type The type of rule.
  1682. * @param string $rule The rule definition.
  1683. * @param array $parameters Any input parameters for the rule.
  1684. */
  1685. public function addValidationRule($field, $name, $type, $rule, array $parameters= array()) {
  1686. if (!$this->_validationLoaded) $this->_loadValidation();
  1687. if (!isset($this->_validationRules[$field])) $this->_validationRules[$field]= array();
  1688. $this->_validationRules[$field][$name]= array(
  1689. 'type' => $type,
  1690. 'rule' => $rule,
  1691. 'parameters' => array()
  1692. );
  1693. foreach ($parameters as $paramKey => $paramValue) {
  1694. $this->_validationRules[$field][$name]['parameters'][$paramKey]= $paramValue;
  1695. }
  1696. }
  1697. /**
  1698. * Remove one or more validation rules from this instance.
  1699. *
  1700. * @param string $field An optional field name to remove rules from. If not
  1701. * specified or null, all rules from all columns will be removed.
  1702. * @param array $rules An optional array of rule names to remove if a single
  1703. * field is specified. If $field is null, this parameter is ignored.
  1704. */
  1705. public function removeValidationRules($field = null, array $rules = array()) {
  1706. if (!$this->_validationLoaded) $this->_loadValidation();
  1707. if (empty($rules) && is_string($field)) {
  1708. unset($this->_validationRules[$field]);
  1709. } elseif (empty($rules) && is_null($field)) {
  1710. $this->_validationRules = array();
  1711. } elseif (is_array($rules) && !empty($rules) && is_string($field)) {
  1712. foreach ($rules as $name) {
  1713. unset($this->_validationRules[$field][$name]);
  1714. }
  1715. }
  1716. }
  1717. /**
  1718. * Get the xPDOValidator class configured for this instance.
  1719. *
  1720. * @return string|boolean The xPDOValidator instance or false if it could
  1721. * not be loaded.
  1722. */
  1723. public function getValidator() {
  1724. if (!is_object($this->_validator)) {
  1725. $validatorClass = $this->xpdo->loadClass('validation.xPDOValidator', XPDO_CORE_PATH, true, true);
  1726. if ($derivedClass = $this->getOption(xPDO::OPT_VALIDATOR_CLASS, null, '')) {
  1727. if ($derivedClass = $this->xpdo->loadClass($derivedClass, '', false, true)) {
  1728. $validatorClass = $derivedClass;
  1729. }
  1730. }
  1731. if ($validatorClass) {
  1732. $this->_validator= new $validatorClass($this);
  1733. }
  1734. }
  1735. return $this->_validator;
  1736. }
  1737. /**
  1738. * Used to load validation from the object map.
  1739. *
  1740. * @access public
  1741. * @param boolean $reload Indicates if the schema validation rules should be
  1742. * reloaded.
  1743. */
  1744. public function _loadValidation($reload= false) {
  1745. if (!$this->_validationLoaded || $reload == true) {
  1746. $validation= $this->xpdo->getValidationRules($this->_class);
  1747. $this->_validationLoaded= true;
  1748. foreach ($validation as $column => $rules) {
  1749. foreach ($rules as $name => $rule) {
  1750. $parameters = array_diff($rule, array($rule['type'], $rule['rule']));
  1751. $this->addValidationRule($column, $name, $rule['type'], $rule['rule'], $parameters);
  1752. }
  1753. }
  1754. }
  1755. }
  1756. /**
  1757. * Validate the field values using an xPDOValidator.
  1758. *
  1759. * @param array $options An array of options to pass to the validator.
  1760. * @return boolean True if validation was successful.
  1761. */
  1762. public function validate(array $options = array()) {
  1763. $validated= false;
  1764. if ($validator= $this->getValidator()) {
  1765. $validated= $this->_validator->validate($options);
  1766. if ($this->xpdo->getDebug() === true) {
  1767. $this->xpdo->log(xPDO::LOG_LEVEL_DEBUG, "Validator class executed, result = " . print_r($validated, true));
  1768. }
  1769. } else {
  1770. if ($this->xpdo->getDebug() === true) {
  1771. $this->xpdo->log(xPDO::LOG_LEVEL_DEBUG, "No validator found for {$this->_class} instance.");
  1772. }
  1773. $validated= true;
  1774. }
  1775. return $validated;
  1776. }
  1777. /**
  1778. * Indicates if the object or specified field has been validated.
  1779. *
  1780. * @param string $key Optional key to check for specific validation.
  1781. * @return boolean True if the object or specified field has been fully
  1782. * validated successfully.
  1783. */
  1784. public function isValidated($key= '') {
  1785. $validated = false;
  1786. $unvalidated = array_diff($this->_dirty, $this->_validated);
  1787. if (empty($key)) {
  1788. $validated = (count($unvalidated) > 0);
  1789. } else {
  1790. $validated = !in_array($key, $unvalidated);
  1791. }
  1792. return $validated;
  1793. }
  1794. /**
  1795. * Indicates if the object or specified field is lazy.
  1796. *
  1797. * @param string $key Optional key to check for laziness.
  1798. * @return boolean True if the field specified or if any field is lazy if no
  1799. * field is specified.
  1800. */
  1801. public function isLazy($key= '') {
  1802. $lazy = false;
  1803. if (empty($key)) {
  1804. $lazy = (count($this->_lazy) > 0);
  1805. } else {
  1806. $lazy = in_array($key, $this->_lazy);
  1807. }
  1808. return $lazy;
  1809. }
  1810. /**
  1811. * Gets related objects by a foreign key and specified criteria.
  1812. *
  1813. * @access protected
  1814. * @param string $alias The alias representing the relationship.
  1815. * @param mixed An optional xPDO criteria expression.
  1816. * @param boolean|integer Indicates if the saved object(s) should
  1817. * be cached and optionally, by specifying an integer value, for how many
  1818. * seconds before expiring. Overrides the cacheFlag for the object.
  1819. * @return array A collection of objects matching the criteria.
  1820. */
  1821. protected function & _getRelatedObjectsByFK($alias, $criteria= null, $cacheFlag= true) {
  1822. $collection= array ();
  1823. if (isset($this->_relatedObjects[$alias]) && (is_object($this->_relatedObjects[$alias]) || (is_array($this->_relatedObjects[$alias]) && !empty ($this->_relatedObjects[$alias])))) {
  1824. $collection= & $this->_relatedObjects[$alias];
  1825. } else {
  1826. $fkMeta= $this->getFKDefinition($alias);
  1827. if ($fkMeta) {
  1828. if ($criteria === null) {
  1829. $criteria= array($fkMeta['foreign'] => $this->get($fkMeta['local']));
  1830. } else {
  1831. $criteria= $this->xpdo->newQuery($fkMeta['class'], $criteria);
  1832. $criteria->andCondition(array("{$criteria->getAlias()}.{$fkMeta['foreign']}" => $this->get($fkMeta['local'])));
  1833. }
  1834. if ($collection= $this->xpdo->getCollection($fkMeta['class'], $criteria, $cacheFlag)) {
  1835. $this->_relatedObjects[$alias]= array_merge($this->_relatedObjects[$alias], $collection);
  1836. }
  1837. }
  1838. }
  1839. if ($this->xpdo->getDebug() === true) {
  1840. $this->xpdo->log(xPDO::LOG_LEVEL_DEBUG, "_getRelatedObjectsByFK :: {$alias} :: " . (is_object($criteria) ? print_r($criteria->sql, true)."\n".print_r($criteria->bindings, true) : 'no criteria'));
  1841. }
  1842. return $collection;
  1843. }
  1844. /**
  1845. * Initializes the field names with the qualified table name.
  1846. *
  1847. * Once this is called, you can lookup the qualified name by the field name
  1848. * itself in {@link xPDOObject::$fieldNames}.
  1849. *
  1850. * @access protected
  1851. */
  1852. protected function _initFields() {
  1853. reset($this->_fieldMeta);
  1854. while (list ($k, $v)= each($this->_fieldMeta)) {
  1855. $this->fieldNames[$k]= $this->xpdo->escape($this->_table) . '.' . $this->xpdo->escape($k);
  1856. }
  1857. }
  1858. /**
  1859. * Returns a JSON representation of the object.
  1860. *
  1861. * @param string $keyPrefix An optional prefix to prepend to the field keys.
  1862. * @param boolean $rawValues An optional flag indicating if the field values
  1863. * should be returned raw or via {@link xPDOObject::get()}.
  1864. * @return string A JSON string representing the object.
  1865. */
  1866. public function toJSON($keyPrefix= '', $rawValues= false) {
  1867. $json= '';
  1868. $array= $this->toArray($keyPrefix, $rawValues);
  1869. if ($array) {
  1870. $json= $this->xpdo->toJSON($array);
  1871. }
  1872. return $json;
  1873. }
  1874. /**
  1875. * Sets the object fields from a JSON object string.
  1876. *
  1877. * @param string $jsonSource A JSON object string.
  1878. * @param string $keyPrefix An optional prefix to strip from the keys.
  1879. * @param boolean $setPrimaryKeys Indicates if primary key fields should be set.
  1880. * @param boolean $rawValues Indicates if values should be set raw or via
  1881. * {@link xPDOObject::set()}.
  1882. * @param boolean $adhocValues Indicates if ad hoc fields should be added to the
  1883. * xPDOObject from the source object.
  1884. */
  1885. public function fromJSON($jsonSource, $keyPrefix= '', $setPrimaryKeys= false, $rawValues= false, $adhocValues= false) {
  1886. $array= $this->xpdo->fromJSON($jsonSource, true);
  1887. if ($array) {
  1888. $this->fromArray($array, $keyPrefix, $setPrimaryKeys, $rawValues, $adhocValues);
  1889. } else {
  1890. $this->xpdo->log(xPDO::LOG_LEVEL_ERROR, 'xPDOObject::fromJSON() -- Could not convert jsonSource to a PHP array.');
  1891. }
  1892. }
  1893. /**
  1894. * Encodes a string using the specified algorithm.
  1895. *
  1896. * NOTE: This implementation currently only implements md5. To implement additional
  1897. * algorithms, override this function in your xPDOObject derivative classes.
  1898. *
  1899. * @param string $source The string source to encode.
  1900. * @param string $type The type of encoding algorithm to apply, md5 by default.
  1901. * @return string The encoded string.
  1902. */
  1903. public function encode($source, $type= 'md5') {
  1904. if (!is_string($source) || empty ($source)) {
  1905. $this->xpdo->log(xPDO::LOG_LEVEL_ERROR, 'xPDOObject::encode() -- Attempt to encode source data that is not a string (or is empty); encoding skipped.');
  1906. return $source;
  1907. }
  1908. switch ($type) {
  1909. case 'password':
  1910. case 'md5':
  1911. $encoded= md5($source);
  1912. break;
  1913. default :
  1914. $encoded= $source;
  1915. $this->xpdo->log(xPDO::LOG_LEVEL_ERROR, "xPDOObject::encode() -- Attempt to encode source data using an unsupported encoding algorithm ({$type}).");
  1916. break;
  1917. }
  1918. return $encoded;
  1919. }
  1920. /**
  1921. * Indicates if an object field has been modified (or never saved).
  1922. *
  1923. * @access public
  1924. * @param string $key The field name to check.
  1925. * @return boolean True if the field exists and either has been modified or the object is new.
  1926. */
  1927. public function isDirty($key) {
  1928. $dirty= false;
  1929. if (array_key_exists($key, $this->_fields)) {
  1930. if (array_key_exists($key, $this->_dirty) || $this->_new) {
  1931. $dirty= true;
  1932. }
  1933. } else {
  1934. $this->xpdo->log(xPDO::LOG_LEVEL_ERROR, "xPDOObject::isDirty() -- Attempt to check if an unknown field ({$key}) has been modified.");
  1935. }
  1936. return $dirty;
  1937. }
  1938. /**
  1939. * Add the field to a collection of field keys that have been modified.
  1940. *
  1941. * This function also clears any validation flag associated with the field.
  1942. *
  1943. * @param string $key The key of the field to set dirty.
  1944. */
  1945. public function setDirty($key= '') {
  1946. if (empty($key)) {
  1947. foreach (array_keys($this->_fields) as $fIdx => $fieldKey) {
  1948. $this->setDirty($fieldKey);
  1949. }
  1950. }
  1951. elseif (array_key_exists($key, $this->_fields)) {
  1952. $this->_dirty[$key]= $key;
  1953. if (isset($this->_validated[$key])) unset($this->_validated[$key]);
  1954. }
  1955. }
  1956. /**
  1957. * Indicates if the instance is new, and has not yet been persisted.
  1958. *
  1959. * @return boolean True if the object has not been saved or was loaded from
  1960. * the database.
  1961. */
  1962. public function isNew() {
  1963. return (boolean) $this->_new;
  1964. }
  1965. /**
  1966. * Gets the database data type for the specified field.
  1967. *
  1968. * @access protected
  1969. * @param string $key The field name to get the data type for.
  1970. * @return string The DB data type of the field.
  1971. */
  1972. protected function _getDataType($key) {
  1973. $type= 'text';
  1974. if (isset ($this->_fieldMeta[$key]['dbtype'])) {
  1975. $type= strtolower($this->_fieldMeta[$key]['dbtype']);
  1976. } elseif ($this->xpdo->getDebug() === true) {
  1977. $this->xpdo->log(xPDO::LOG_LEVEL_DEBUG, "xPDOObject::_getDataType() -- No data type specified for field ({$key}), using `text`.");
  1978. }
  1979. return $type;
  1980. }
  1981. /**
  1982. * Gets the php data type for the specified field.
  1983. *
  1984. * @access protected
  1985. * @param string $key The field name to get the data type for.
  1986. * @return string The PHP data type of the field.
  1987. */
  1988. protected function _getPHPType($key) {
  1989. $type= 'string';
  1990. if (isset ($this->_fieldMeta[$key]['phptype'])) {
  1991. $type= strtolower($this->_fieldMeta[$key]['phptype']);
  1992. } elseif ($this->xpdo->getDebug() === true) {
  1993. $this->xpdo->log(xPDO::LOG_LEVEL_DEBUG, "xPDOObject::_getPHPType() -- No PHP type specified for field ({$key}), using `string`.");
  1994. }
  1995. return $type;
  1996. }
  1997. /**
  1998. * Load persistent data from the source for the field(s) indicated.
  1999. *
  2000. * @access protected
  2001. * @param string|array $fields A field name or array of field names to load
  2002. * from the data source.
  2003. */
  2004. protected function _loadFieldData($fields) {
  2005. if (!is_array($fields)) $fields= array($fields);
  2006. else $fields= array_values($fields);
  2007. $criteria= $this->xpdo->newQuery($this->_class, $this->getPrimaryKey());
  2008. $criteria->select($fields);
  2009. if ($rows= xPDOObject :: _loadRows($this->xpdo, $this->_class, $criteria)) {
  2010. $row= reset($rows);
  2011. $this->fromArray($row, '', false, true);
  2012. $this->_lazy= array_diff($this->_lazy, $fields);
  2013. }
  2014. }
  2015. /**
  2016. * Set a raw value on a field converted to the appropriate type.
  2017. *
  2018. * @access protected
  2019. * @param string $key The key identifying the field to set.
  2020. * @param mixed $val The value to set.
  2021. * @return boolean Returns true if the value was set, false otherwise.
  2022. */
  2023. protected function _setRaw($key, $val) {
  2024. $set = false;
  2025. if ($val === null) {
  2026. $this->_fields[$key] = null;
  2027. $set = true;
  2028. } else {
  2029. $phptype = $this->_getPHPType($key);
  2030. $dbtype = $this->_getDataType($key);
  2031. switch ($phptype) {
  2032. case 'int':
  2033. case 'integer':
  2034. case 'boolean':
  2035. $this->_fields[$key] = (integer) $val;
  2036. $set = true;
  2037. break;
  2038. case 'float':
  2039. $this->_fields[$key] = (float) $val;
  2040. $set = true;
  2041. break;
  2042. case 'array':
  2043. if (is_array($val)) {
  2044. $this->_fields[$key]= serialize($val);
  2045. $set = true;
  2046. } elseif (is_string($val)) {
  2047. $this->_fields[$key]= $val;
  2048. $set = true;
  2049. } elseif (is_object($val) && $val instanceof xPDOObject) {
  2050. $this->_fields[$key]= serialize($val->toArray());
  2051. $set = true;
  2052. }
  2053. break;
  2054. case 'json':
  2055. if (!is_string($val)) {
  2056. $v = $val;
  2057. if (is_array($v)) {
  2058. $this->_fields[$key] = $this->xpdo->toJSON($v);
  2059. $set = true;
  2060. } elseif (is_object($v) && $v instanceof xPDOObject) {
  2061. $this->_fields[$key] = $this->xpdo->toJSON($v->toArray());
  2062. $set = true;
  2063. }
  2064. } else {
  2065. $this->_fields[$key]= $val;
  2066. $set = true;
  2067. }
  2068. break;
  2069. case 'date':
  2070. case 'datetime':
  2071. case 'timestamp':
  2072. if (preg_match('/int/i', $dbtype)) {
  2073. $this->_fields[$key] = (integer) $val;
  2074. $set = true;
  2075. break;
  2076. }
  2077. default:
  2078. $this->_fields[$key] = $val;
  2079. $set = true;
  2080. }
  2081. }
  2082. if ($set) $this->setDirty($key);
  2083. return $set;
  2084. }
  2085. /**
  2086. * Find aliases for any defined object relations of the specified class.
  2087. *
  2088. * @access protected
  2089. * @param string $class The name of the class to find aliases from.
  2090. * @param int $limit An optional limit on the number of aliases to return;
  2091. * default is 0, i.e. no limit.
  2092. * @return array An array of aliases or an empty array if none are found.
  2093. */
  2094. protected function _getAliases($class, $limit = 0) {
  2095. $aliases = array();
  2096. $limit = intval($limit);
  2097. $array = array('aggregates' => $this->_aggregates, 'composites' => $this->_composites);
  2098. foreach ($array as $relType => $relations) {
  2099. foreach ($relations as $alias => $def) {
  2100. if (isset($def['class']) && $def['class'] == $class) {
  2101. $aliases[] = $alias;
  2102. if ($limit > 0 && count($aliases) > $limit) break;
  2103. }
  2104. }
  2105. }
  2106. return $aliases;
  2107. }
  2108. }
  2109. /**
  2110. * Extend to define a class with a native integer primary key field named id.
  2111. *
  2112. * @see xpdo/om/mysql/xpdosimpleobject.map.inc.php
  2113. * @package xpdo
  2114. * @subpackage om
  2115. */
  2116. class xPDOSimpleObject extends xPDOObject {}