PageRenderTime 64ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/src/cake/libs/model/datasources/dbo_source.php

http://github.com/mfriesen/kaching-php
PHP | 2914 lines | 2078 code | 208 blank | 628 comment | 488 complexity | f5e432aff167dbe146216e6c2dccb60f MD5 | raw file
Possible License(s): LGPL-2.1

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

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

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