PageRenderTime 96ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/Vendor/pear-pear.cakephp.org/CakePHP/Cake/Model/Datasource/DboSource.php

https://bitbucket.org/daveschwan/ronin-group
PHP | 3315 lines | 2162 code | 283 blank | 870 comment | 563 complexity | 9a098476aa248d85f75552c236141195 MD5 | raw file
Possible License(s): LGPL-2.1, MPL-2.0-no-copyleft-exception, MIT, BSD-3-Clause, Apache-2.0

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

  1. <?php
  2. /**
  3. * Dbo Source
  4. *
  5. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  6. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  7. *
  8. * Licensed under The MIT License
  9. * For full copyright and license information, please see the LICENSE.txt
  10. * Redistributions of files must retain the above copyright notice.
  11. *
  12. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  13. * @link http://cakephp.org CakePHP(tm) Project
  14. * @package Cake.Model.Datasource
  15. * @since CakePHP(tm) v 0.10.0.1076
  16. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  17. */
  18. App::uses('DataSource', 'Model/Datasource');
  19. App::uses('String', 'Utility');
  20. App::uses('View', 'View');
  21. /**
  22. * DboSource
  23. *
  24. * Creates DBO-descendant objects from a given db connection configuration
  25. *
  26. * @package Cake.Model.Datasource
  27. */
  28. class DboSource extends DataSource {
  29. /**
  30. * Description string for this Database Data Source.
  31. *
  32. * @var string
  33. */
  34. public $description = "Database Data Source";
  35. /**
  36. * index definition, standard cake, primary, index, unique
  37. *
  38. * @var array
  39. */
  40. public $index = array('PRI' => 'primary', 'MUL' => 'index', 'UNI' => 'unique');
  41. /**
  42. * Database keyword used to assign aliases to identifiers.
  43. *
  44. * @var string
  45. */
  46. public $alias = 'AS ';
  47. /**
  48. * Caches result from query parsing operations. Cached results for both DboSource::name() and
  49. * DboSource::conditions() will be stored here. Method caching uses `md5()`. If you have
  50. * problems with collisions, set DboSource::$cacheMethods to false.
  51. *
  52. * @var array
  53. */
  54. public static $methodCache = array();
  55. /**
  56. * Whether or not to cache the results of DboSource::name() and DboSource::conditions()
  57. * into the memory cache. Set to false to disable the use of the memory cache.
  58. *
  59. * @var boolean
  60. */
  61. public $cacheMethods = true;
  62. /**
  63. * Flag to support nested transactions. If it is set to false, you will be able to use
  64. * the transaction methods (begin/commit/rollback), but just the global transaction will
  65. * be executed.
  66. *
  67. * @var boolean
  68. */
  69. public $useNestedTransactions = false;
  70. /**
  71. * Print full query debug info?
  72. *
  73. * @var boolean
  74. */
  75. public $fullDebug = false;
  76. /**
  77. * String to hold how many rows were affected by the last SQL operation.
  78. *
  79. * @var string
  80. */
  81. public $affected = null;
  82. /**
  83. * Number of rows in current resultset
  84. *
  85. * @var integer
  86. */
  87. public $numRows = null;
  88. /**
  89. * Time the last query took
  90. *
  91. * @var integer
  92. */
  93. public $took = null;
  94. /**
  95. * Result
  96. *
  97. * @var array
  98. */
  99. protected $_result = null;
  100. /**
  101. * Queries count.
  102. *
  103. * @var integer
  104. */
  105. protected $_queriesCnt = 0;
  106. /**
  107. * Total duration of all queries.
  108. *
  109. * @var integer
  110. */
  111. protected $_queriesTime = null;
  112. /**
  113. * Log of queries executed by this DataSource
  114. *
  115. * @var array
  116. */
  117. protected $_queriesLog = array();
  118. /**
  119. * Maximum number of items in query log
  120. *
  121. * This is to prevent query log taking over too much memory.
  122. *
  123. * @var integer Maximum number of queries in the queries log.
  124. */
  125. protected $_queriesLogMax = 200;
  126. /**
  127. * Caches serialized results of executed queries
  128. *
  129. * @var array Cache of results from executed sql queries.
  130. */
  131. protected $_queryCache = array();
  132. /**
  133. * A reference to the physical connection of this DataSource
  134. *
  135. * @var array
  136. */
  137. protected $_connection = null;
  138. /**
  139. * The DataSource configuration key name
  140. *
  141. * @var string
  142. */
  143. public $configKeyName = null;
  144. /**
  145. * The starting character that this DataSource uses for quoted identifiers.
  146. *
  147. * @var string
  148. */
  149. public $startQuote = null;
  150. /**
  151. * The ending character that this DataSource uses for quoted identifiers.
  152. *
  153. * @var string
  154. */
  155. public $endQuote = null;
  156. /**
  157. * The set of valid SQL operations usable in a WHERE statement
  158. *
  159. * @var array
  160. */
  161. protected $_sqlOps = array('like', 'ilike', 'or', 'not', 'in', 'between', 'regexp', 'similar to');
  162. /**
  163. * Indicates the level of nested transactions
  164. *
  165. * @var integer
  166. */
  167. protected $_transactionNesting = 0;
  168. /**
  169. * Default fields that are used by the DBO
  170. *
  171. * @var array
  172. */
  173. protected $_queryDefaults = array(
  174. 'conditions' => array(),
  175. 'fields' => null,
  176. 'table' => null,
  177. 'alias' => null,
  178. 'order' => null,
  179. 'limit' => null,
  180. 'joins' => array(),
  181. 'group' => null,
  182. 'offset' => null
  183. );
  184. /**
  185. * Separator string for virtualField composition
  186. *
  187. * @var string
  188. */
  189. public $virtualFieldSeparator = '__';
  190. /**
  191. * List of table engine specific parameters used on table creating
  192. *
  193. * @var array
  194. */
  195. public $tableParameters = array();
  196. /**
  197. * List of engine specific additional field parameters used on table creating
  198. *
  199. * @var array
  200. */
  201. public $fieldParameters = array();
  202. /**
  203. * Indicates whether there was a change on the cached results on the methods of this class
  204. * This will be used for storing in a more persistent cache
  205. *
  206. * @var boolean
  207. */
  208. protected $_methodCacheChange = false;
  209. /**
  210. * Constructor
  211. *
  212. * @param array $config Array of configuration information for the Datasource.
  213. * @param boolean $autoConnect Whether or not the datasource should automatically connect.
  214. * @throws MissingConnectionException when a connection cannot be made.
  215. */
  216. public function __construct($config = null, $autoConnect = true) {
  217. if (!isset($config['prefix'])) {
  218. $config['prefix'] = '';
  219. }
  220. parent::__construct($config);
  221. $this->fullDebug = Configure::read('debug') > 1;
  222. if (!$this->enabled()) {
  223. throw new MissingConnectionException(array(
  224. 'class' => get_class($this),
  225. 'message' => __d('cake_dev', 'Selected driver is not enabled'),
  226. 'enabled' => false
  227. ));
  228. }
  229. if ($autoConnect) {
  230. $this->connect();
  231. }
  232. }
  233. /**
  234. * Reconnects to database server with optional new settings
  235. *
  236. * @param array $config An array defining the new configuration settings
  237. * @return boolean True on success, false on failure
  238. */
  239. public function reconnect($config = array()) {
  240. $this->disconnect();
  241. $this->setConfig($config);
  242. $this->_sources = null;
  243. return $this->connect();
  244. }
  245. /**
  246. * Disconnects from database.
  247. *
  248. * @return boolean Always true
  249. */
  250. public function disconnect() {
  251. if ($this->_result instanceof PDOStatement) {
  252. $this->_result->closeCursor();
  253. }
  254. unset($this->_connection);
  255. $this->connected = false;
  256. return true;
  257. }
  258. /**
  259. * Get the underlying connection object.
  260. *
  261. * @return PDO
  262. */
  263. public function getConnection() {
  264. return $this->_connection;
  265. }
  266. /**
  267. * Gets the version string of the database server
  268. *
  269. * @return string The database version
  270. */
  271. public function getVersion() {
  272. return $this->_connection->getAttribute(PDO::ATTR_SERVER_VERSION);
  273. }
  274. /**
  275. * Returns a quoted and escaped string of $data for use in an SQL statement.
  276. *
  277. * @param string $data String to be prepared for use in an SQL statement
  278. * @param string $column The column datatype into which this data will be inserted.
  279. * @return string Quoted and escaped data
  280. */
  281. public function value($data, $column = null) {
  282. if (is_array($data) && !empty($data)) {
  283. return array_map(
  284. array(&$this, 'value'),
  285. $data, array_fill(0, count($data), $column)
  286. );
  287. } elseif (is_object($data) && isset($data->type, $data->value)) {
  288. if ($data->type === 'identifier') {
  289. return $this->name($data->value);
  290. } elseif ($data->type === 'expression') {
  291. return $data->value;
  292. }
  293. } elseif (in_array($data, array('{$__cakeID__$}', '{$__cakeForeignKey__$}'), true)) {
  294. return $data;
  295. }
  296. if ($data === null || (is_array($data) && empty($data))) {
  297. return 'NULL';
  298. }
  299. if (empty($column)) {
  300. $column = $this->introspectType($data);
  301. }
  302. switch ($column) {
  303. case 'binary':
  304. return $this->_connection->quote($data, PDO::PARAM_LOB);
  305. case 'boolean':
  306. return $this->_connection->quote($this->boolean($data, true), PDO::PARAM_BOOL);
  307. case 'string':
  308. case 'text':
  309. return $this->_connection->quote($data, PDO::PARAM_STR);
  310. default:
  311. if ($data === '') {
  312. return 'NULL';
  313. }
  314. if (is_float($data)) {
  315. return str_replace(',', '.', strval($data));
  316. }
  317. if ((is_int($data) || $data === '0') || (
  318. is_numeric($data) && strpos($data, ',') === false &&
  319. $data[0] != '0' && strpos($data, 'e') === false)
  320. ) {
  321. return $data;
  322. }
  323. return $this->_connection->quote($data);
  324. }
  325. }
  326. /**
  327. * Returns an object to represent a database identifier in a query. Expression objects
  328. * are not sanitized or escaped.
  329. *
  330. * @param string $identifier A SQL expression to be used as an identifier
  331. * @return stdClass An object representing a database identifier to be used in a query
  332. */
  333. public function identifier($identifier) {
  334. $obj = new stdClass();
  335. $obj->type = 'identifier';
  336. $obj->value = $identifier;
  337. return $obj;
  338. }
  339. /**
  340. * Returns an object to represent a database expression in a query. Expression objects
  341. * are not sanitized or escaped.
  342. *
  343. * @param string $expression An arbitrary SQL expression to be inserted into a query.
  344. * @return stdClass An object representing a database expression to be used in a query
  345. */
  346. public function expression($expression) {
  347. $obj = new stdClass();
  348. $obj->type = 'expression';
  349. $obj->value = $expression;
  350. return $obj;
  351. }
  352. /**
  353. * Executes given SQL statement.
  354. *
  355. * @param string $sql SQL statement
  356. * @param array $params Additional options for the query.
  357. * @return boolean
  358. */
  359. public function rawQuery($sql, $params = array()) {
  360. $this->took = $this->numRows = false;
  361. return $this->execute($sql, $params);
  362. }
  363. /**
  364. * Queries the database with given SQL statement, and obtains some metadata about the result
  365. * (rows affected, timing, any errors, number of rows in resultset). The query is also logged.
  366. * If Configure::read('debug') is set, the log is shown all the time, else it is only shown on errors.
  367. *
  368. * ### Options
  369. *
  370. * - log - Whether or not the query should be logged to the memory log.
  371. *
  372. * @param string $sql SQL statement
  373. * @param array $options
  374. * @param array $params values to be bound to the query
  375. * @return mixed Resource or object representing the result set, or false on failure
  376. */
  377. public function execute($sql, $options = array(), $params = array()) {
  378. $options += array('log' => $this->fullDebug);
  379. $t = microtime(true);
  380. $this->_result = $this->_execute($sql, $params);
  381. if ($options['log']) {
  382. $this->took = round((microtime(true) - $t) * 1000, 0);
  383. $this->numRows = $this->affected = $this->lastAffected();
  384. $this->logQuery($sql, $params);
  385. }
  386. return $this->_result;
  387. }
  388. /**
  389. * Executes given SQL statement.
  390. *
  391. * @param string $sql SQL statement
  392. * @param array $params list of params to be bound to query
  393. * @param array $prepareOptions Options to be used in the prepare statement
  394. * @return mixed PDOStatement if query executes with no problem, true as the result of a successful, false on error
  395. * query returning no rows, such as a CREATE statement, false otherwise
  396. * @throws PDOException
  397. */
  398. protected function _execute($sql, $params = array(), $prepareOptions = array()) {
  399. $sql = trim($sql);
  400. if (preg_match('/^(?:CREATE|ALTER|DROP)\s+(?:TABLE|INDEX)/i', $sql)) {
  401. $statements = array_filter(explode(';', $sql));
  402. if (count($statements) > 1) {
  403. $result = array_map(array($this, '_execute'), $statements);
  404. return array_search(false, $result) === false;
  405. }
  406. }
  407. try {
  408. $query = $this->_connection->prepare($sql, $prepareOptions);
  409. $query->setFetchMode(PDO::FETCH_LAZY);
  410. if (!$query->execute($params)) {
  411. $this->_results = $query;
  412. $query->closeCursor();
  413. return false;
  414. }
  415. if (!$query->columnCount()) {
  416. $query->closeCursor();
  417. if (!$query->rowCount()) {
  418. return true;
  419. }
  420. }
  421. return $query;
  422. } catch (PDOException $e) {
  423. if (isset($query->queryString)) {
  424. $e->queryString = $query->queryString;
  425. } else {
  426. $e->queryString = $sql;
  427. }
  428. throw $e;
  429. }
  430. }
  431. /**
  432. * Returns a formatted error message from previous database operation.
  433. *
  434. * @param PDOStatement $query the query to extract the error from if any
  435. * @return string Error message with error number
  436. */
  437. public function lastError(PDOStatement $query = null) {
  438. if ($query) {
  439. $error = $query->errorInfo();
  440. } else {
  441. $error = $this->_connection->errorInfo();
  442. }
  443. if (empty($error[2])) {
  444. return null;
  445. }
  446. return $error[1] . ': ' . $error[2];
  447. }
  448. /**
  449. * Returns number of affected rows in previous database operation. If no previous operation exists,
  450. * this returns false.
  451. *
  452. * @param mixed $source
  453. * @return integer Number of affected rows
  454. */
  455. public function lastAffected($source = null) {
  456. if ($this->hasResult()) {
  457. return $this->_result->rowCount();
  458. }
  459. return 0;
  460. }
  461. /**
  462. * Returns number of rows in previous resultset. If no previous resultset exists,
  463. * this returns false.
  464. *
  465. * @param mixed $source Not used
  466. * @return integer Number of rows in resultset
  467. */
  468. public function lastNumRows($source = null) {
  469. return $this->lastAffected();
  470. }
  471. /**
  472. * DataSource Query abstraction
  473. *
  474. * @return resource Result resource identifier.
  475. */
  476. public function query() {
  477. $args = func_get_args();
  478. $fields = null;
  479. $order = null;
  480. $limit = null;
  481. $page = null;
  482. $recursive = null;
  483. if (count($args) === 1) {
  484. return $this->fetchAll($args[0]);
  485. } elseif (count($args) > 1 && (strpos($args[0], 'findBy') === 0 || strpos($args[0], 'findAllBy') === 0)) {
  486. $params = $args[1];
  487. if (substr($args[0], 0, 6) === 'findBy') {
  488. $all = false;
  489. $field = Inflector::underscore(substr($args[0], 6));
  490. } else {
  491. $all = true;
  492. $field = Inflector::underscore(substr($args[0], 9));
  493. }
  494. $or = (strpos($field, '_or_') !== false);
  495. if ($or) {
  496. $field = explode('_or_', $field);
  497. } else {
  498. $field = explode('_and_', $field);
  499. }
  500. $off = count($field) - 1;
  501. if (isset($params[1 + $off])) {
  502. $fields = $params[1 + $off];
  503. }
  504. if (isset($params[2 + $off])) {
  505. $order = $params[2 + $off];
  506. }
  507. if (!array_key_exists(0, $params)) {
  508. return false;
  509. }
  510. $c = 0;
  511. $conditions = array();
  512. foreach ($field as $f) {
  513. $conditions[$args[2]->alias . '.' . $f] = $params[$c++];
  514. }
  515. if ($or) {
  516. $conditions = array('OR' => $conditions);
  517. }
  518. if ($all) {
  519. if (isset($params[3 + $off])) {
  520. $limit = $params[3 + $off];
  521. }
  522. if (isset($params[4 + $off])) {
  523. $page = $params[4 + $off];
  524. }
  525. if (isset($params[5 + $off])) {
  526. $recursive = $params[5 + $off];
  527. }
  528. return $args[2]->find('all', compact('conditions', 'fields', 'order', 'limit', 'page', 'recursive'));
  529. }
  530. if (isset($params[3 + $off])) {
  531. $recursive = $params[3 + $off];
  532. }
  533. return $args[2]->find('first', compact('conditions', 'fields', 'order', 'recursive'));
  534. }
  535. if (isset($args[1]) && $args[1] === true) {
  536. return $this->fetchAll($args[0], true);
  537. } elseif (isset($args[1]) && !is_array($args[1])) {
  538. return $this->fetchAll($args[0], false);
  539. } elseif (isset($args[1]) && is_array($args[1])) {
  540. if (isset($args[2])) {
  541. $cache = $args[2];
  542. } else {
  543. $cache = true;
  544. }
  545. return $this->fetchAll($args[0], $args[1], array('cache' => $cache));
  546. }
  547. }
  548. /**
  549. * Returns a row from current resultset as an array
  550. *
  551. * @param string $sql Some SQL to be executed.
  552. * @return array The fetched row as an array
  553. */
  554. public function fetchRow($sql = null) {
  555. if (is_string($sql) && strlen($sql) > 5 && !$this->execute($sql)) {
  556. return null;
  557. }
  558. if ($this->hasResult()) {
  559. $this->resultSet($this->_result);
  560. $resultRow = $this->fetchResult();
  561. if (isset($resultRow[0])) {
  562. $this->fetchVirtualField($resultRow);
  563. }
  564. return $resultRow;
  565. }
  566. return null;
  567. }
  568. /**
  569. * Returns an array of all result rows for a given SQL query.
  570. * Returns false if no rows matched.
  571. *
  572. * ### Options
  573. *
  574. * - `cache` - Returns the cached version of the query, if exists and stores the result in cache.
  575. * This is a non-persistent cache, and only lasts for a single request. This option
  576. * defaults to true. If you are directly calling this method, you can disable caching
  577. * by setting $options to `false`
  578. *
  579. * @param string $sql SQL statement
  580. * @param array|boolean $params Either parameters to be bound as values for the SQL statement,
  581. * or a boolean to control query caching.
  582. * @param array $options additional options for the query.
  583. * @return boolean|array Array of resultset rows, or false if no rows matched
  584. */
  585. public function fetchAll($sql, $params = array(), $options = array()) {
  586. if (is_string($options)) {
  587. $options = array('modelName' => $options);
  588. }
  589. if (is_bool($params)) {
  590. $options['cache'] = $params;
  591. $params = array();
  592. }
  593. $options += array('cache' => true);
  594. $cache = $options['cache'];
  595. if ($cache && ($cached = $this->getQueryCache($sql, $params)) !== false) {
  596. return $cached;
  597. }
  598. $result = $this->execute($sql, array(), $params);
  599. if ($result) {
  600. $out = array();
  601. if ($this->hasResult()) {
  602. $first = $this->fetchRow();
  603. if ($first) {
  604. $out[] = $first;
  605. }
  606. while ($item = $this->fetchResult()) {
  607. if (isset($item[0])) {
  608. $this->fetchVirtualField($item);
  609. }
  610. $out[] = $item;
  611. }
  612. }
  613. if (!is_bool($result) && $cache) {
  614. $this->_writeQueryCache($sql, $out, $params);
  615. }
  616. if (empty($out) && is_bool($this->_result)) {
  617. return $this->_result;
  618. }
  619. return $out;
  620. }
  621. return false;
  622. }
  623. /**
  624. * Fetches the next row from the current result set
  625. *
  626. * @return boolean
  627. */
  628. public function fetchResult() {
  629. return false;
  630. }
  631. /**
  632. * Modifies $result array to place virtual fields in model entry where they belongs to
  633. *
  634. * @param array $result Reference to the fetched row
  635. * @return void
  636. */
  637. public function fetchVirtualField(&$result) {
  638. if (isset($result[0]) && is_array($result[0])) {
  639. foreach ($result[0] as $field => $value) {
  640. if (strpos($field, $this->virtualFieldSeparator) === false) {
  641. continue;
  642. }
  643. list($alias, $virtual) = explode($this->virtualFieldSeparator, $field);
  644. if (!ClassRegistry::isKeySet($alias)) {
  645. return;
  646. }
  647. $model = ClassRegistry::getObject($alias);
  648. if ($model->isVirtualField($virtual)) {
  649. $result[$alias][$virtual] = $value;
  650. unset($result[0][$field]);
  651. }
  652. }
  653. if (empty($result[0])) {
  654. unset($result[0]);
  655. }
  656. }
  657. }
  658. /**
  659. * Returns a single field of the first of query results for a given SQL query, or false if empty.
  660. *
  661. * @param string $name Name of the field
  662. * @param string $sql SQL query
  663. * @return mixed Value of field read.
  664. */
  665. public function field($name, $sql) {
  666. $data = $this->fetchRow($sql);
  667. if (empty($data[$name])) {
  668. return false;
  669. }
  670. return $data[$name];
  671. }
  672. /**
  673. * Empties the method caches.
  674. * These caches are used by DboSource::name() and DboSource::conditions()
  675. *
  676. * @return void
  677. */
  678. public function flushMethodCache() {
  679. $this->_methodCacheChange = true;
  680. self::$methodCache = array();
  681. }
  682. /**
  683. * Cache a value into the methodCaches. Will respect the value of DboSource::$cacheMethods.
  684. * Will retrieve a value from the cache if $value is null.
  685. *
  686. * If caching is disabled and a write is attempted, the $value will be returned.
  687. * A read will either return the value or null.
  688. *
  689. * @param string $method Name of the method being cached.
  690. * @param string $key The key name for the cache operation.
  691. * @param mixed $value The value to cache into memory.
  692. * @return mixed Either null on failure, or the value if its set.
  693. */
  694. public function cacheMethod($method, $key, $value = null) {
  695. if ($this->cacheMethods === false) {
  696. return $value;
  697. }
  698. if (!$this->_methodCacheChange && empty(self::$methodCache)) {
  699. self::$methodCache = Cache::read('method_cache', '_cake_core_');
  700. }
  701. if ($value === null) {
  702. return (isset(self::$methodCache[$method][$key])) ? self::$methodCache[$method][$key] : null;
  703. }
  704. $this->_methodCacheChange = true;
  705. return self::$methodCache[$method][$key] = $value;
  706. }
  707. /**
  708. * Returns a quoted name of $data for use in an SQL statement.
  709. * Strips fields out of SQL functions before quoting.
  710. *
  711. * Results of this method are stored in a memory cache. This improves performance, but
  712. * because the method uses a hashing algorithm it can have collisions.
  713. * Setting DboSource::$cacheMethods to false will disable the memory cache.
  714. *
  715. * @param mixed $data Either a string with a column to quote. An array of columns to quote or an
  716. * object from DboSource::expression() or DboSource::identifier()
  717. * @return string SQL field
  718. */
  719. public function name($data) {
  720. if (is_object($data) && isset($data->type)) {
  721. return $data->value;
  722. }
  723. if ($data === '*') {
  724. return '*';
  725. }
  726. if (is_array($data)) {
  727. foreach ($data as $i => $dataItem) {
  728. $data[$i] = $this->name($dataItem);
  729. }
  730. return $data;
  731. }
  732. $cacheKey = md5($this->startQuote . $data . $this->endQuote);
  733. if ($return = $this->cacheMethod(__FUNCTION__, $cacheKey)) {
  734. return $return;
  735. }
  736. $data = trim($data);
  737. if (preg_match('/^[\w-]+(?:\.[^ \*]*)*$/', $data)) { // string, string.string
  738. if (strpos($data, '.') === false) { // string
  739. return $this->cacheMethod(__FUNCTION__, $cacheKey, $this->startQuote . $data . $this->endQuote);
  740. }
  741. $items = explode('.', $data);
  742. return $this->cacheMethod(__FUNCTION__, $cacheKey,
  743. $this->startQuote . implode($this->endQuote . '.' . $this->startQuote, $items) . $this->endQuote
  744. );
  745. }
  746. if (preg_match('/^[\w-]+\.\*$/', $data)) { // string.*
  747. return $this->cacheMethod(__FUNCTION__, $cacheKey,
  748. $this->startQuote . str_replace('.*', $this->endQuote . '.*', $data)
  749. );
  750. }
  751. if (preg_match('/^([\w-]+)\((.*)\)$/', $data, $matches)) { // Functions
  752. return $this->cacheMethod(__FUNCTION__, $cacheKey,
  753. $matches[1] . '(' . $this->name($matches[2]) . ')'
  754. );
  755. }
  756. if (
  757. preg_match('/^([\w-]+(\.[\w-]+|\(.*\))*)\s+' . preg_quote($this->alias) . '\s*([\w-]+)$/i', $data, $matches
  758. )) {
  759. return $this->cacheMethod(
  760. __FUNCTION__, $cacheKey,
  761. preg_replace(
  762. '/\s{2,}/', ' ', $this->name($matches[1]) . ' ' . $this->alias . ' ' . $this->name($matches[3])
  763. )
  764. );
  765. }
  766. if (preg_match('/^[\w-_\s]*[\w-_]+/', $data)) {
  767. return $this->cacheMethod(__FUNCTION__, $cacheKey, $this->startQuote . $data . $this->endQuote);
  768. }
  769. return $this->cacheMethod(__FUNCTION__, $cacheKey, $data);
  770. }
  771. /**
  772. * Checks if the source is connected to the database.
  773. *
  774. * @return boolean True if the database is connected, else false
  775. */
  776. public function isConnected() {
  777. return $this->connected;
  778. }
  779. /**
  780. * Checks if the result is valid
  781. *
  782. * @return boolean True if the result is valid else false
  783. */
  784. public function hasResult() {
  785. return $this->_result instanceof PDOStatement;
  786. }
  787. /**
  788. * Get the query log as an array.
  789. *
  790. * @param boolean $sorted Get the queries sorted by time taken, defaults to false.
  791. * @param boolean $clear If True the existing log will cleared.
  792. * @return array Array of queries run as an array
  793. */
  794. public function getLog($sorted = false, $clear = true) {
  795. if ($sorted) {
  796. $log = sortByKey($this->_queriesLog, 'took', 'desc', SORT_NUMERIC);
  797. } else {
  798. $log = $this->_queriesLog;
  799. }
  800. if ($clear) {
  801. $this->_queriesLog = array();
  802. }
  803. return array('log' => $log, 'count' => $this->_queriesCnt, 'time' => $this->_queriesTime);
  804. }
  805. /**
  806. * Outputs the contents of the queries log. If in a non-CLI environment the sql_log element
  807. * will be rendered and output. If in a CLI environment, a plain text log is generated.
  808. *
  809. * @param boolean $sorted Get the queries sorted by time taken, defaults to false.
  810. * @return void
  811. */
  812. public function showLog($sorted = false) {
  813. $log = $this->getLog($sorted, false);
  814. if (empty($log['log'])) {
  815. return;
  816. }
  817. if (PHP_SAPI !== 'cli') {
  818. $controller = null;
  819. $View = new View($controller, false);
  820. $View->set('sqlLogs', array($this->configKeyName => $log));
  821. echo $View->element('sql_dump', array('_forced_from_dbo_' => true));
  822. } else {
  823. foreach ($log['log'] as $k => $i) {
  824. print (($k + 1) . ". {$i['query']}\n");
  825. }
  826. }
  827. }
  828. /**
  829. * Log given SQL query.
  830. *
  831. * @param string $sql SQL statement
  832. * @param array $params Values binded to the query (prepared statements)
  833. * @return void
  834. */
  835. public function logQuery($sql, $params = array()) {
  836. $this->_queriesCnt++;
  837. $this->_queriesTime += $this->took;
  838. $this->_queriesLog[] = array(
  839. 'query' => $sql,
  840. 'params' => $params,
  841. 'affected' => $this->affected,
  842. 'numRows' => $this->numRows,
  843. 'took' => $this->took
  844. );
  845. if (count($this->_queriesLog) > $this->_queriesLogMax) {
  846. array_shift($this->_queriesLog);
  847. }
  848. }
  849. /**
  850. * Gets full table name including prefix
  851. *
  852. * @param Model|string $model Either a Model object or a string table name.
  853. * @param boolean $quote Whether you want the table name quoted.
  854. * @param boolean $schema Whether you want the schema name included.
  855. * @return string Full quoted table name
  856. */
  857. public function fullTableName($model, $quote = true, $schema = true) {
  858. if (is_object($model)) {
  859. $schemaName = $model->schemaName;
  860. $table = $model->tablePrefix . $model->table;
  861. } elseif (!empty($this->config['prefix']) && strpos($model, $this->config['prefix']) !== 0) {
  862. $table = $this->config['prefix'] . strval($model);
  863. } else {
  864. $table = strval($model);
  865. }
  866. if ($schema && !isset($schemaName)) {
  867. $schemaName = $this->getSchemaName();
  868. }
  869. if ($quote) {
  870. if ($schema && !empty($schemaName)) {
  871. if (strstr($table, '.') === false) {
  872. return $this->name($schemaName) . '.' . $this->name($table);
  873. }
  874. }
  875. return $this->name($table);
  876. }
  877. if ($schema && !empty($schemaName)) {
  878. if (strstr($table, '.') === false) {
  879. return $schemaName . '.' . $table;
  880. }
  881. }
  882. return $table;
  883. }
  884. /**
  885. * The "C" in CRUD
  886. *
  887. * Creates new records in the database.
  888. *
  889. * @param Model $model Model object that the record is for.
  890. * @param array $fields An array of field names to insert. If null, $model->data will be
  891. * used to generate field names.
  892. * @param array $values An array of values with keys matching the fields. If null, $model->data will
  893. * be used to generate values.
  894. * @return boolean Success
  895. */
  896. public function create(Model $model, $fields = null, $values = null) {
  897. $id = null;
  898. if (!$fields) {
  899. unset($fields, $values);
  900. $fields = array_keys($model->data);
  901. $values = array_values($model->data);
  902. }
  903. $count = count($fields);
  904. for ($i = 0; $i < $count; $i++) {
  905. $valueInsert[] = $this->value($values[$i], $model->getColumnType($fields[$i]));
  906. $fieldInsert[] = $this->name($fields[$i]);
  907. if ($fields[$i] == $model->primaryKey) {
  908. $id = $values[$i];
  909. }
  910. }
  911. $query = array(
  912. 'table' => $this->fullTableName($model),
  913. 'fields' => implode(', ', $fieldInsert),
  914. 'values' => implode(', ', $valueInsert)
  915. );
  916. if ($this->execute($this->renderStatement('create', $query))) {
  917. if (empty($id)) {
  918. $id = $this->lastInsertId($this->fullTableName($model, false, false), $model->primaryKey);
  919. }
  920. $model->setInsertID($id);
  921. $model->id = $id;
  922. return true;
  923. }
  924. $model->onError();
  925. return false;
  926. }
  927. /**
  928. * The "R" in CRUD
  929. *
  930. * Reads record(s) from the database.
  931. *
  932. * @param Model $model A Model object that the query is for.
  933. * @param array $queryData An array of queryData information containing keys similar to Model::find()
  934. * @param integer $recursive Number of levels of association
  935. * @return mixed boolean false on error/failure. An array of results on success.
  936. */
  937. public function read(Model $model, $queryData = array(), $recursive = null) {
  938. $queryData = $this->_scrubQueryData($queryData);
  939. $null = null;
  940. $array = array('callbacks' => $queryData['callbacks']);
  941. $linkedModels = array();
  942. $bypass = false;
  943. if ($recursive === null && isset($queryData['recursive'])) {
  944. $recursive = $queryData['recursive'];
  945. }
  946. if ($recursive !== null) {
  947. $_recursive = $model->recursive;
  948. $model->recursive = $recursive;
  949. }
  950. if (!empty($queryData['fields'])) {
  951. $bypass = true;
  952. $queryData['fields'] = $this->fields($model, null, $queryData['fields']);
  953. } else {
  954. $queryData['fields'] = $this->fields($model);
  955. }
  956. $_associations = $model->associations();
  957. if ($model->recursive == -1) {
  958. $_associations = array();
  959. } elseif ($model->recursive === 0) {
  960. unset($_associations[2], $_associations[3]);
  961. }
  962. foreach ($_associations as $type) {
  963. foreach ($model->{$type} as $assoc => $assocData) {
  964. $linkModel = $model->{$assoc};
  965. $external = isset($assocData['external']);
  966. $linkModel->getDataSource();
  967. if ($model->useDbConfig === $linkModel->useDbConfig) {
  968. if ($bypass) {
  969. $assocData['fields'] = false;
  970. }
  971. if ($this->generateAssociationQuery($model, $linkModel, $type, $assoc, $assocData, $queryData, $external, $null) === true) {
  972. $linkedModels[$type . '/' . $assoc] = true;
  973. }
  974. }
  975. }
  976. }
  977. $query = $this->generateAssociationQuery($model, null, null, null, null, $queryData, false, $null);
  978. $resultSet = $this->fetchAll($query, $model->cacheQueries);
  979. if ($resultSet === false) {
  980. $model->onError();
  981. return false;
  982. }
  983. $filtered = array();
  984. if ($queryData['callbacks'] === true || $queryData['callbacks'] === 'after') {
  985. $filtered = $this->_filterResults($resultSet, $model);
  986. }
  987. if ($model->recursive > -1) {
  988. $joined = array();
  989. if (isset($queryData['joins'][0]['alias'])) {
  990. $joined[$model->alias] = (array)Hash::extract($queryData['joins'], '{n}.alias');
  991. }
  992. foreach ($_associations as $type) {
  993. foreach ($model->{$type} as $assoc => $assocData) {
  994. $linkModel = $model->{$assoc};
  995. if (!isset($linkedModels[$type . '/' . $assoc])) {
  996. if ($model->useDbConfig === $linkModel->useDbConfig) {
  997. $db = $this;
  998. } else {
  999. $db = ConnectionManager::getDataSource($linkModel->useDbConfig);
  1000. }
  1001. } elseif ($model->recursive > 1 && ($type === 'belongsTo' || $type === 'hasOne')) {
  1002. $db = $this;
  1003. }
  1004. if (isset($db) && method_exists($db, 'queryAssociation')) {
  1005. $stack = array($assoc);
  1006. $stack['_joined'] = $joined;
  1007. $db->queryAssociation($model, $linkModel, $type, $assoc, $assocData, $array, true, $resultSet, $model->recursive - 1, $stack);
  1008. unset($db);
  1009. if ($type === 'hasMany') {
  1010. $filtered[] = $assoc;
  1011. }
  1012. }
  1013. }
  1014. }
  1015. if ($queryData['callbacks'] === true || $queryData['callbacks'] === 'after') {
  1016. $this->_filterResults($resultSet, $model, $filtered);
  1017. }
  1018. }
  1019. if ($recursive !== null) {
  1020. $model->recursive = $_recursive;
  1021. }
  1022. return $resultSet;
  1023. }
  1024. /**
  1025. * Passes association results thru afterFind filters of corresponding model
  1026. *
  1027. * @param array $results Reference of resultset to be filtered
  1028. * @param Model $model Instance of model to operate against
  1029. * @param array $filtered List of classes already filtered, to be skipped
  1030. * @return array Array of results that have been filtered through $model->afterFind
  1031. */
  1032. protected function _filterResults(&$results, Model $model, $filtered = array()) {
  1033. $current = reset($results);
  1034. if (!is_array($current)) {
  1035. return array();
  1036. }
  1037. $keys = array_diff(array_keys($current), $filtered, array($model->alias));
  1038. $filtering = array();
  1039. foreach ($keys as $className) {
  1040. if (!isset($model->{$className}) || !is_object($model->{$className})) {
  1041. continue;
  1042. }
  1043. $linkedModel = $model->{$className};
  1044. $filtering[] = $className;
  1045. foreach ($results as $key => &$result) {
  1046. $data = $linkedModel->afterFind(array(array($className => $result[$className])), false);
  1047. if (isset($data[0][$className])) {
  1048. $result[$className] = $data[0][$className];
  1049. } else {
  1050. unset($results[$key]);
  1051. }
  1052. }
  1053. }
  1054. return $filtering;
  1055. }
  1056. /**
  1057. * Queries associations. Used to fetch results on recursive models.
  1058. *
  1059. * @param Model $model Primary Model object
  1060. * @param Model $linkModel Linked model that
  1061. * @param string $type Association type, one of the model association types ie. hasMany
  1062. * @param string $association
  1063. * @param array $assocData
  1064. * @param array $queryData
  1065. * @param boolean $external Whether or not the association query is on an external datasource.
  1066. * @param array $resultSet Existing results
  1067. * @param integer $recursive Number of levels of association
  1068. * @param array $stack
  1069. * @return mixed
  1070. * @throws CakeException when results cannot be created.
  1071. */
  1072. public function queryAssociation(Model $model, &$linkModel, $type, $association, $assocData, &$queryData, $external, &$resultSet, $recursive, $stack) {
  1073. if (isset($stack['_joined'])) {
  1074. $joined = $stack['_joined'];
  1075. unset($stack['_joined']);
  1076. }
  1077. if ($query = $this->generateAssociationQuery($model, $linkModel, $type, $association, $assocData, $queryData, $external, $resultSet)) {
  1078. if (!is_array($resultSet)) {
  1079. throw new CakeException(__d('cake_dev', 'Error in Model %s', get_class($model)));
  1080. }
  1081. if ($type === 'hasMany' && empty($assocData['limit']) && !empty($assocData['foreignKey'])) {
  1082. $ins = $fetch = array();
  1083. foreach ($resultSet as &$result) {
  1084. if ($in = $this->insertQueryData('{$__cakeID__$}', $result, $association, $assocData, $model, $linkModel, $stack)) {
  1085. $ins[] = $in;
  1086. }
  1087. }
  1088. if (!empty($ins)) {
  1089. $ins = array_unique($ins);
  1090. $fetch = $this->fetchAssociated($model, $query, $ins);
  1091. }
  1092. if (!empty($fetch) && is_array($fetch)) {
  1093. if ($recursive > 0) {
  1094. foreach ($linkModel->associations() as $type1) {
  1095. foreach ($linkModel->{$type1} as $assoc1 => $assocData1) {
  1096. $deepModel = $linkModel->{$assoc1};
  1097. $tmpStack = $stack;
  1098. $tmpStack[] = $assoc1;
  1099. if ($linkModel->useDbConfig === $deepModel->useDbConfig) {
  1100. $db = $this;
  1101. } else {
  1102. $db = ConnectionManager::getDataSource($deepModel->useDbConfig);
  1103. }
  1104. $db->queryAssociation($linkModel, $deepModel, $type1, $assoc1, $assocData1, $queryData, true, $fetch, $recursive - 1, $tmpStack);
  1105. }
  1106. }
  1107. }
  1108. }
  1109. if ($queryData['callbacks'] === true || $queryData['callbacks'] === 'after') {
  1110. $this->_filterResults($fetch, $model);
  1111. }
  1112. return $this->_mergeHasMany($resultSet, $fetch, $association, $model, $linkModel);
  1113. } elseif ($type === 'hasAndBelongsToMany') {
  1114. $ins = $fetch = array();
  1115. foreach ($resultSet as &$result) {
  1116. if ($in = $this->insertQueryData('{$__cakeID__$}', $result, $association, $assocData, $model, $linkModel, $stack)) {
  1117. $ins[] = $in;
  1118. }
  1119. }
  1120. if (!empty($ins)) {
  1121. $ins = array_unique($ins);
  1122. if (count($ins) > 1) {
  1123. $query = str_replace('{$__cakeID__$}', '(' . implode(', ', $ins) . ')', $query);
  1124. $query = str_replace('= (', 'IN (', $query);
  1125. } else {
  1126. $query = str_replace('{$__cakeID__$}', $ins[0], $query);
  1127. }
  1128. $query = str_replace(' WHERE 1 = 1', '', $query);
  1129. }
  1130. $foreignKey = $model->hasAndBelongsToMany[$association]['foreignKey'];
  1131. $joinKeys = array($foreignKey, $model->hasAndBelongsToMany[$association]['associationForeignKey']);
  1132. list($with, $habtmFields) = $model->joinModel($model->hasAndBelongsToMany[$association]['with'], $joinKeys);
  1133. $habtmFieldsCount = count($habtmFields);
  1134. $q = $this->insertQueryData($query, null, $association, $assocData, $model, $linkModel, $stack);
  1135. if ($q !== false) {
  1136. $fetch = $this->fetchAll($q, $model->cacheQueries);
  1137. } else {
  1138. $fetch = null;
  1139. }
  1140. }
  1141. $modelAlias = $model->alias;
  1142. $modelPK = $model->primaryKey;
  1143. foreach ($resultSet as &$row) {
  1144. if ($type !== 'hasAndBelongsToMany') {
  1145. $q = $this->insertQueryData($query, $row, $association, $assocData, $model, $linkModel, $stack);
  1146. $fetch = null;
  1147. if ($q !== false) {
  1148. $joinedData = array();
  1149. if (($type === 'belongsTo' || $type === 'hasOne') && isset($row[$linkModel->alias], $joined[$model->alias]) && in_array($linkModel->alias, $joined[$model->alias])) {
  1150. $joinedData = Hash::filter($row[$linkModel->alias]);
  1151. if (!empty($joinedData)) {
  1152. $fetch[0] = array($linkModel->alias => $row[$linkModel->alias]);
  1153. }
  1154. } else {
  1155. $fetch = $this->fetchAll($q, $model->cacheQueries);
  1156. }
  1157. }
  1158. }
  1159. $selfJoin = $linkModel->name === $model->name;
  1160. if (!empty($fetch) && is_array($fetch)) {
  1161. if ($recursive > 0) {
  1162. foreach ($linkModel->associations() as $type1) {
  1163. foreach ($linkModel->{$type1} as $assoc1 => $assocData1) {
  1164. $deepModel = $linkModel->{$assoc1};
  1165. if ($type1 === 'belongsTo' || ($deepModel->alias === $modelAlias && $type === 'belongsTo') || ($deepModel->alias !== $modelAlias)) {
  1166. $tmpStack = $stack;
  1167. $tmpStack[] = $assoc1;
  1168. if ($linkModel->useDbConfig == $deepModel->useDbConfig) {
  1169. $db = $this;
  1170. } else {
  1171. $db = ConnectionManager::getDataSource($deepModel->useDbConfig);
  1172. }
  1173. $db->queryAssociation($linkModel, $deepModel, $type1, $assoc1, $assocData1, $queryData, true, $fetch, $recursive - 1, $tmpStack);
  1174. }
  1175. }
  1176. }
  1177. }
  1178. if ($type === 'hasAndBelongsToMany') {
  1179. $merge = array();
  1180. foreach ($fetch as $data) {
  1181. if (isset($data[$with]) && $data[$with][$foreignKey] === $row[$modelAlias][$modelPK]) {
  1182. if ($habtmFieldsCount <= 2) {
  1183. unset($data[$with]);
  1184. }
  1185. $merge[] = $data;
  1186. }
  1187. }
  1188. if (empty($merge) && !isset($row[$association])) {
  1189. $row[$association] = $merge;
  1190. } else {
  1191. $this->_mergeAssociation($row, $merge, $association, $type);
  1192. }
  1193. } else {
  1194. $this->_mergeAssociation($row, $fetch, $association, $type, $selfJoin);
  1195. }
  1196. if (isset($row[$association])) {
  1197. $row[$association] = $linkModel->afterFind($row[$association], false);
  1198. }
  1199. } else {
  1200. $tempArray[0][$association] = false;
  1201. $this->_mergeAssociation($row, $tempArray, $association, $type, $selfJoin);
  1202. }
  1203. }
  1204. }
  1205. }
  1206. /**
  1207. * A more efficient way to fetch associations.
  1208. *
  1209. * @param Model $model Primary model object
  1210. * @param string $query Association query
  1211. * @param array $ids Array of IDs of associated records
  1212. * @return array Association results
  1213. */
  1214. public function fetchAssociated(Model $model, $query, $ids) {
  1215. $query = str_replace('{$__cakeID__$}', implode(', ', $ids), $query);
  1216. if (count($ids) > 1) {
  1217. $query = str_replace('= (', 'IN (', $query);
  1218. }
  1219. return $this->fetchAll($query, $model->cacheQueries);
  1220. }
  1221. /**
  1222. * Merge the results of hasMany relations.
  1223. *
  1224. * @param array $resultSet Data to merge into
  1225. * @param array $merge Data to merge
  1226. * @param string $association Name of Model being Merged
  1227. * @param Model $model Model being merged onto
  1228. * @param Model $linkModel Model being merged
  1229. * @return void
  1230. */
  1231. protected function _mergeHasMany(&$resultSet, $merge, $association, $model, $linkModel) {
  1232. $modelAlias = $model->alias;
  1233. $modelPK = $model->primaryKey;
  1234. $modelFK = $model->hasMany[$association]['foreignKey'];
  1235. foreach ($resultSet as &$result) {
  1236. if (!isset($result[$modelAlias])) {
  1237. continue;
  1238. }
  1239. $merged = array();
  1240. foreach ($merge as $data) {
  1241. if ($result[$modelAlias][$modelPK] === $data[$association][$modelFK]) {
  1242. if (count($data) > 1) {
  1243. $data = array_merge($data[$association], $data);
  1244. unset($data[$association]);
  1245. foreach ($data as $key => $name) {
  1246. if (is_numeric($key)) {
  1247. $data[$association][] = $name;
  1248. unset($data[$key]);
  1249. }
  1250. }
  1251. $merged[] = $data;
  1252. } else {
  1253. $merged[] = $data[$association];
  1254. }
  1255. }
  1256. }
  1257. $result = Hash::mergeDiff($result, array($association => $merged));
  1258. }
  1259. }
  1260. /**
  1261. * Merge association of merge into data
  1262. *
  1263. * @param array $data
  1264. * @param array $merge
  1265. * @param string $association
  1266. * @param string $type
  1267. * @param boolean $selfJoin
  1268. * @return void
  1269. */
  1270. protected function _mergeAssociation(&$data, &$merge, $association, $type, $selfJoin = false) {
  1271. if (isset($merge[0]) && !isset($merge[0][$association])) {
  1272. $association = Inflector::pluralize($association);
  1273. }
  1274. if ($type === 'belongsTo' || $type === 'hasOne') {
  1275. if (isset($merge[$association])) {
  1276. $data[$association] = $merge[$association][0];
  1277. } else {
  1278. if (!empty($merge[0][$association])) {
  1279. foreach ($merge[0] as $assoc => $data2) {
  1280. if ($assoc !== $association) {
  1281. $merge[0][$association][$assoc] = $data2;
  1282. }
  1283. }
  1284. }
  1285. if (!isset($data[$association])) {
  1286. $data[$association] = array();
  1287. if ($merge[0][$association]) {
  1288. $data[$association] = $merge[0][$association];
  1289. }
  1290. } else {
  1291. if (is_array($merge[0][$association])) {
  1292. foreach ($data[$association] as $k => $v) {
  1293. if (!is_array($v)) {
  1294. $dataAssocTmp[$k] = $v;
  1295. }
  1296. }
  1297. foreach ($merge[0][$association] as $k => $v) {
  1298. if (!is_array($v)) {
  1299. $mergeAssocTmp[$k] = $v;
  1300. }
  1301. }
  1302. $dataKeys = array_keys($data);
  1303. $mergeKeys = array_keys($merge[0]);
  1304. if ($mergeKeys[0] === $dataKeys[0] || $mergeKeys === $dataKeys) {
  1305. $data[$association][$association] = $merge[0][$association];
  1306. } else {
  1307. $diff = Hash::diff($dataAssocTmp, $mergeAssocTmp);
  1308. $data[$association] = array_merge($merge[0][$association], $diff);
  1309. }
  1310. } elseif ($selfJoin && array_key_exists($association, $merge[0])) {
  1311. $data[$association] = array_merge($data[$association], array($association => array()));
  1312. }
  1313. }
  1314. }
  1315. } else {
  1316. if (isset($merge[0][$association]) && $merge[0][$association] === false) {
  1317. if (!isset($data[$association])) {
  1318. $data[$association] = array();
  1319. }
  1320. } else {
  1321. foreach ($merge as $row) {
  1322. $insert = array();
  1323. if (count($row) === 1) {
  1324. $insert = $row[$association];
  1325. } elseif (isset($row[$association])) {
  1326. $insert = array_merge($row[$association], $row);
  1327. unset($insert[$association]);
  1328. }
  1329. if (empty($data[$association]) || (isset($data[$association]) && !in_array($insert, $data[$association], true))) {
  1330. $data[$association][] = $insert;
  1331. }
  1332. }
  1333. }
  1334. }
  1335. }
  1336. /**
  1337. * Generates an array representing a query or part of a query from a single model or two associated models
  1338. *
  1339. * @param Model $model
  1340. * @param Model $linkModel
  1341. * @param string $type
  1342. * @param string $association
  1343. * @param array $assocData
  1344. * @param array $queryData
  1345. * @param boolean $external
  1346. * @param array $resultSet
  1347. * @return mixed
  1348. */
  1349. public function generateAssociationQuery(Model $model, $linkModel, $type, $association, $assocData, &$queryData, $external, &$resultSet) {
  1350. $queryData = $this->_scrubQueryData($queryData);
  1351. $assocData = $this->_scrubQueryData($assocData);
  1352. $modelAlias = $model->alias;
  1353. if (empty($queryData['fields'])) {
  1354. $queryData['fields'] = $this->fields($model, $modelAlias);
  1355. } elseif (!empty($model->hasMany) && $model->recursive > -1) {
  1356. $assocFields = $this->fields($model, $modelAlias, array("{$modelAlias}.{$model->primaryKey}"));
  1357. $passedFields = $queryData['fields'];
  1358. if (count($passedFields) === 1) {
  1359. if (strpos($passedFields[0], $assocFields[0]) === false && !preg_match('/^[a-z]+\(/i', $passedFields[0])) {
  1360. $queryData['fields'] = array_merge($passedFields, $assocFields);
  1361. } else {
  1362. $queryData['fields'] = $passedFields;
  1363. }
  1364. } else {
  1365. $queryData['fields'] = array_merge($passedFields, $assocFields);
  1366. }
  1367. unset($assocFields, $passedFields);
  1368. }
  1369. if ($linkModel === null) {
  1370. return $this->buildStatement(
  1371. array(
  1372. 'fields' => array_unique($queryData['fields']),
  1373. 'table' => $this->fullTableName($model),
  1374. 'alias' => $modelAlias,
  1375. 'limit' => $queryData['limit'],
  1376. 'offset' => $queryData['offset'],
  1377. 'joins' => $queryData['joins'],
  1378. 'conditions' => $queryData['conditions'],
  1379. 'order' => $queryData['order'],
  1380. 'group' => $queryData['group']
  1381. ),
  1382. $model
  1383. );
  1384. }
  1385. if ($external && !empty($assocData['finderQuery'])) {
  1386. return $assocData['finderQuery'];
  1387. }
  1388. $self = $model->name === $linkModel->name;
  1389. $fields = array();
  1390. if ($external || (in_array($type, array('hasOne', 'belongsTo')) && $assocData['fields'] !== false)) {
  1391. $fields = $this->fields($linkModel, $association, $assocData['fields']);
  1392. }
  1393. if (empty($assocData['offset']) && !empty($assocData['page'])) {
  1394. $assocData['offset'] = ($assocData['page'] - 1) * $assocData['limit'];
  1395. }
  1396. switch ($type) {
  1397. case 'hasOne':
  1398. case 'belongsTo':
  1399. $conditions = $this->_mergeConditions(
  1400. $assocData['conditions'],
  1401. $this->getConstraint($type, $model, $linkModel, $association, array_merge($assocData, compact('external', 'self')))
  1402. );
  1403. if (!$self && $external) {
  1404. foreach ($conditions as $key => $condition) {
  1405. if (is_numeric($key) && strpos($condition, $modelAlias . '.') !== false) {
  1406. unset($conditions[$key]);
  1407. }
  1408. }
  1409. }
  1410. if ($external) {
  1411. $query = array_merge($assocData, array(
  1412. 'conditions' => $conditions,
  1413. 'table' => $this->fullTableName($linkModel),
  1414. 'fields' => $fields,
  1415. 'alias' => $association,
  1416. 'group' => null
  1417. ));
  1418. } else {
  1419. $join = array(
  1420. 'table' => $linkModel,
  1421. 'alias' => $association,
  1422. 'type' => isset($assocData['type']) ? $assocData['type'] : 'LEFT',
  1423. 'conditions' => trim($this->conditions($conditions, true, false, $model))
  1424. );
  1425. $queryData['fields'] = array_merge($queryData['fields'], $fields);
  1426. if (!empty($assocData['order'])) {
  1427. $queryData['order'][] = $assocData['order'];
  1428. }
  1429. if (!in_array($join, $queryData['joins'])) {
  1430. $queryData['joins'][] = $join;
  1431. }
  1432. return true;
  1433. }
  1434. break;
  1435. case 'hasMany':
  1436. $assocData['fields'] = $this->fields($linkModel, $association, $assocData['fields']);
  1437. if (!empty($assocData['foreignKey'])) {
  1438. $assocData['fields'] = array_merge($assocData['fields'], $this->fields($linkModel, $association, array("{$association}.{$assocData['foreignKey']}")));
  1439. }
  1440. $query = array(
  1441. 'conditions' => $this->_mergeConditions($this->getConstraint('hasMany', $model, $linkModel, $association, $assocData), $assocData['conditions']),
  1442. 'fields' => array_unique($assocData['fields']),
  1443. 'table' => $this->fullTableName($linkModel),
  1444. 'alias' => $association,
  1445. 'order' => $assocData['order'],
  1446. 'limit' => $assocData['limit'],
  1447. 'offset' => $assocData['offset'],
  1448. 'group' => null
  1449. );
  1450. break;
  1451. case 'hasAndBelongsToMany':
  1452. $joinFields = array();
  1453. $joinAssoc = null;
  1454. if (isset($assocData['with']) && !empty($assocData['with'])) {
  1455. $joinKeys = array($assocData['foreignKey'], $assocData['associationForeignKey']);
  1456. list($with, $joinFields) = $model->joinModel($assocData['with'], $joinKeys);
  1457. $joinTbl = $model->{$with};
  1458. $joinAlias = $joinTbl;
  1459. if (is_array($joinFields) && !empty($joinFields)) {
  1460. $joinAssoc = $joinAlias = $model->{$with}->alias;
  1461. $joinFields = $this->fields($model->{$with}, $joinAlias, $joinFields);
  1462. } else {
  1463. $joinFields = array();
  1464. }
  1465. } else {
  1466. $joinTbl = $assocData['joinTable'];
  1467. $joinAlias = $this->fullTableName($assocData['joinTable']);
  1468. }
  1469. $query = array(
  1470. 'conditions' => $assocData['conditions'],
  1471. 'limit' => $assocData['limit'],
  1472. 'offset' => $assocData['offset'],
  1473. 'table' => $this->fullTableName($linkModel),
  1474. 'alias' => $association,
  1475. 'fields' => array_merge($this->fields($linkModel, $association, $assocData['fields']), $joinFields),
  1476. 'order' => $assocData['order'],
  1477. 'group' => null,
  1478. 'joins' => array(array(
  1479. 'table' => $joinTbl,
  1480. 'alias' => $joinAssoc,
  1481. 'conditions' => $this->getConstraint('hasAndBelongsToMany', $model, $linkModel, $joinAlias, $assocData, $association)
  1482. ))
  1483. );
  1484. break;
  1485. }
  1486. if (isset($query)) {
  1487. return $this->buildStatement($query, $model);
  1488. }
  1489. return null;
  1490. }
  1491. /**
  1492. * Returns a conditions array for the constraint between two models
  1493. *
  1494. * @param string $type Association type
  1495. * @param Model $model Model object
  1496. * @param string $linkModel
  1497. * @param string $alias
  1498. * @param array $assoc
  1499. * @param string $alias2
  1500. * @return array Conditions array defining the constraint between $model and $association
  1501. */
  1502. public function getConstraint($type, $model, $linkModel, $alias, $assoc, $alias2 = null) {
  1503. $assoc += array('external' => false, 'self' => false);
  1504. if (empty($assoc['foreignKey'])) {
  1505. return array();
  1506. }
  1507. switch (true) {
  1508. case ($assoc['external'] && $type === 'hasOne'):
  1509. return array("{$alias}.{$assoc['foreignKey']}" => '{$__cakeID__$}');
  1510. case ($assoc['external'] && $type === 'belongsTo'):
  1511. return array("{$alias}.{$linkModel->primaryKey}" => '{$__cakeForeignKey__$}');
  1512. case (!$assoc['external'] && $type === 'hasOne'):
  1513. return array("{$alias}.{$assoc['foreignKey']}" => $this->identifier("{$model->alias}.{$model->primaryKey}"));
  1514. case (!$assoc['external'] && $type === 'belongsTo'):
  1515. return array("{$model->alias}.{$assoc['foreignKey']}" => $this->identifier("{$alias}.{$linkModel->primaryKey}"));
  1516. case ($type === 'hasMany'):
  1517. return array("{$alias}.{$assoc['foreignKey']}" => array('{$__cakeID__$}'));
  1518. case ($type === 'hasAndBelongsToMany'):
  1519. return array(
  1520. array("{$alias}.{$assoc['foreignKey']}" => '{$__cakeID__$}'),
  1521. array("{$alias}.{$assoc['associationForeignKey']}" => $this->identifier("{$alias2}.{$linkModel->primaryKey}"))
  1522. );
  1523. }
  1524. return array();
  1525. }
  1526. /**
  1527. * Builds and generates a JOIN statement from an array. Handles final clean-up before conversion.
  1528. *
  1529. * @param array $join An array defining a JOIN statement in a query
  1530. * @return string An SQL JOIN statement to be used in a query
  1531. * @see DboSource::renderJoinStatement()
  1532. * @see DboSource::buildStatement()
  1533. */
  1534. public function buildJoinStatement($join) {
  1535. $data = array_merge(array(
  1536. 'type' => null,
  1537. 'alias' => null,
  1538. 'table' => 'join_table',
  1539. 'conditions' => array()
  1540. ), $join);
  1541. if (!empty($data['alias'])) {
  1542. $data['alias'] = $this->alias . $this->name($data['alias']);
  1543. }
  1544. if (!empty($data['conditions'])) {
  1545. $data['conditions'] = trim($this->conditions($data['conditions'], true, false));
  1546. }
  1547. if (!empty($data['table']) && (!is_st

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