MyModel.php 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383
  1. <?php
  2. App::uses('ShimModel', 'Shim.Model');
  3. App::uses('Utility', 'Tools.Utility');
  4. App::uses('Hash', 'Utility');
  5. /**
  6. * Model enhancements for Cake2
  7. *
  8. * @author Mark Scherer
  9. * @license http://opensource.org/licenses/mit-license.php MIT
  10. */
  11. class MyModel extends ShimModel {
  12. /**
  13. * MyModel::__construct()
  14. *
  15. * @param int $id
  16. * @param string $table
  17. * @param string $ds
  18. */
  19. public function __construct($id = false, $table = null, $ds = null) {
  20. parent::__construct($id, $table, $ds);
  21. // enable caching
  22. if (!Configure::read('Cache.disable') && Cache::config('sql') === false) {
  23. if (!file_exists(CACHE . 'sql')) {
  24. mkdir(CACHE . 'sql', CHOWN_PUBLIC);
  25. }
  26. Cache::config('sql', [
  27. 'engine' => 'File',
  28. 'serialize' => true,
  29. 'prefix' => '',
  30. 'path' => CACHE . 'sql' . DS,
  31. 'duration' => '+1 day'
  32. ]);
  33. }
  34. // Get a notice if there is an AppModel instance instead of a real Model (in those cases usually a dev error!)
  35. if (!is_a($this, $this->name) && $this->displayField !== $this->primaryKey && $this->useDbConfig === 'default'
  36. && !Configure::read('Core.disableModelInstanceNotice')) {
  37. trigger_error('AppModel instance! Expected: ' . $this->name);
  38. }
  39. }
  40. /**
  41. * The main method for any enumeration, should be called statically
  42. * Now also supports reordering/filtering
  43. *
  44. * @link http://www.dereuromark.de/2010/06/24/static-enums-or-semihardcoded-attributes/
  45. * @param string $value or array $keys or NULL for complete array result
  46. * @param array $options (actual data)
  47. * @return mixed string/array
  48. */
  49. public static function enum($value, $options, $default = null) {
  50. if ($value !== null && !is_array($value)) {
  51. if (array_key_exists($value, $options)) {
  52. return $options[$value];
  53. }
  54. return $default;
  55. } elseif ($value !== null) {
  56. $newOptions = [];
  57. foreach ($value as $v) {
  58. $newOptions[$v] = $options[$v];
  59. }
  60. return $newOptions;
  61. }
  62. return $options;
  63. }
  64. /**
  65. * @return string Error message with error number
  66. */
  67. public function lastError() {
  68. $db = $this->getDataSource();
  69. return $db->lastError();
  70. }
  71. /**
  72. * Combine virtual fields with fields values of find()
  73. * USAGE:
  74. * $this->Model->find('all', array('fields' => $this->Model->virtualFields('full_name')));
  75. * Also adds the field to the virtualFields array of the model (for correct result)
  76. * TODO: adding of fields only temperory!
  77. *
  78. * @param array $virtualFields to include
  79. * @return array
  80. */
  81. public function virtualFields($fields = []) {
  82. $res = [];
  83. foreach ((array)$fields as $field => $sql) {
  84. if (is_int($field)) {
  85. $field = $sql;
  86. $sql = null;
  87. }
  88. $plugin = $model = null;
  89. if (($pos = strrpos($field, '.')) !== false) {
  90. $model = substr($field, 0, $pos);
  91. $field = substr($field, $pos + 1);
  92. if (($pos = strrpos($model, '.')) !== false) {
  93. list($plugin, $model) = pluginSplit($model);
  94. }
  95. }
  96. if (empty($model)) {
  97. $model = $this->alias;
  98. if ($sql === null) {
  99. $sql = $this->virtualFields[$field];
  100. } else {
  101. $this->virtualFields[$field] = $sql;
  102. }
  103. } else {
  104. if (!isset($this->$model)) {
  105. $fullModelName = ($plugin ? $plugin . '.' : '') . $model;
  106. $this->$model = ClassRegistry::init($fullModelName);
  107. }
  108. if ($sql === null) {
  109. $sql = $this->$model->virtualFields[$field];
  110. } else {
  111. $this->$model->virtualFields[$field] = $sql;
  112. }
  113. }
  114. $res[] = $sql . ' AS ' . $model . '__' . $field;
  115. }
  116. return $res;
  117. }
  118. /**
  119. * HIGHLY EXPERIMENTAL
  120. * manually escape value for updateAll() etc
  121. *
  122. * @return string
  123. */
  124. public function escapeValue($value) {
  125. if ($value === null || is_numeric($value)) {
  126. return $value;
  127. }
  128. if (is_bool($value)) {
  129. return (int)$value;
  130. }
  131. return "'" . $value . "'";
  132. }
  133. /**
  134. * HIGHLY EXPERIMENTAL
  135. *
  136. * @see http://cakephp.lighthouseapp.com/projects/42648/tickets/1799-model-should-have-escapefield-method
  137. * @return string
  138. */
  139. public function value($content) {
  140. $db = $this->getDatasource();
  141. return $db->value($content);
  142. }
  143. /**
  144. * TODO: move to behavior (Incremental)
  145. *
  146. * @param mixed id (single string)
  147. * @param options:
  148. * - step (defaults to 1)
  149. * - current (if none it will get it from db)
  150. * - reset (if true, it will be set to 0)
  151. * - field (defaults to 'count')
  152. * - modify (if true if will affect modified timestamp)
  153. * - timestampField (if provided it will be filled with NOW())
  154. * @return See Model::save()
  155. */
  156. public function up($id, $customOptions = []) {
  157. $step = 1;
  158. if (isset($customOptions['step'])) {
  159. $step = $customOptions['step'];
  160. }
  161. $field = 'count';
  162. if (isset($customOptions['field'])) {
  163. $field = $customOptions['field'];
  164. }
  165. if (isset($customOptions['reset'])) {
  166. $currentValue = $step = 0;
  167. } elseif (!isset($customOptions['current'])) {
  168. $currentValue = $this->field($field, [$this->alias . '.id' => $id]);
  169. if ($currentValue === false) {
  170. return false;
  171. }
  172. } else {
  173. $currentValue = $customOptions['current'];
  174. }
  175. $value = (int)$currentValue + (int)$step;
  176. $data = [$field => $value];
  177. if (empty($customOptions['modify'])) {
  178. $data['modified'] = false;
  179. }
  180. if (!empty($customOptions['timestampField'])) {
  181. $data[$customOptions['timestampField']] = date(FORMAT_DB_DATETIME);
  182. }
  183. $this->id = $id;
  184. return $this->save($data, false);
  185. }
  186. /**
  187. * Return the next auto increment id from the current table
  188. * UUIDs will return false
  189. *
  190. * @return int next auto increment value or False on failure
  191. */
  192. public function getNextAutoIncrement() {
  193. $query = "SHOW TABLE STATUS WHERE name = '" . $this->tablePrefix . $this->table . "'";
  194. $result = $this->query($query);
  195. if (!isset($result[0]['TABLES']['Auto_increment'])) {
  196. return false;
  197. }
  198. return (int)$result[0]['TABLES']['Auto_increment'];
  199. }
  200. /**
  201. * Fix for non atomic queries (MyISAM etc) and saveAll to still return just the boolean result
  202. * Otherwise you would have to iterate over all result values to find out if the save was successful.
  203. *
  204. * Use Configure::read('Model.atomic') to modify atomic behavior.
  205. * Additional options:
  206. *
  207. * - returnArray: bool
  208. *
  209. * @param mixed $data
  210. * @param array $options
  211. * @return bool Success
  212. */
  213. public function saveAll($data = null, $options = []) {
  214. if (!isset($options['atomic']) && Configure::read('Model.atomic') !== null) {
  215. $options['atomic'] = (bool)Configure::read('Model.atomic');
  216. }
  217. $res = parent::saveAll($data, $options);
  218. if (is_array($res) && empty($options['returnArray'])) {
  219. $res = Utility::isValidSaveAll($res);
  220. }
  221. return $res;
  222. }
  223. /**
  224. * Enables HABTM-Validation
  225. * e.g. with
  226. * 'rule' => array('multiple', array('min' => 2))
  227. *
  228. * @return bool Success
  229. */
  230. public function beforeValidate($options = []) {
  231. foreach ($this->hasAndBelongsToMany as $k => $v) {
  232. if (isset($this->data[$k][$k])) {
  233. $this->data[$this->alias][$k] = $this->data[$k][$k];
  234. }
  235. }
  236. return parent::beforeValidate($options);
  237. }
  238. /**
  239. * @param params
  240. * - key: functioName or other key used
  241. * @return bool Success
  242. */
  243. public function deleteCache($key = null) {
  244. $key = Inflector::underscore($key);
  245. if (!empty($key)) {
  246. return Cache::delete(strtolower(Inflector::underscore($this->alias)) . '__' . $key, 'sql');
  247. }
  248. return Cache::clear(false, 'sql');
  249. }
  250. /**
  251. * Generates a SQL subquery snippet to be used in your actual query.
  252. * Your subquery snippet needs to return a single value or flat array of values.
  253. *
  254. * Example:
  255. *
  256. * $this->Model->find('first', array(
  257. * 'conditions' => array('NOT' => array('some_id' => $this->Model->subquery(...)))
  258. * ))
  259. *
  260. * Note: You might have to set `autoFields` to false in order to retrieve only the fields you request:
  261. * http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html#containablebehavior-options
  262. *
  263. * @param string $type The type of the query ('count'/'all'/'first' - first only works with some mysql versions)
  264. * @param array $options The options array
  265. * @param string $alias You can use this intead of $options['alias'] if you want
  266. * @param bool $parenthesise Add parenthesis before and after
  267. * @return string result sql snippet of the query to run
  268. * @modified Mark Scherer (cake2.x ready and improvements)
  269. * @link http://bakery.cakephp.org/articles/lucaswxp/2011/02/11/easy_and_simple_subquery_cakephp
  270. */
  271. public function subquery($type, $options = [], $alias = null, $parenthesise = true) {
  272. if ($alias === null) {
  273. $alias = 'Sub' . $this->alias . '';
  274. }
  275. $fields = [$alias . '.id'];
  276. $limit = null;
  277. switch ($type) {
  278. case 'count':
  279. $fields = ['COUNT(*)'];
  280. break;
  281. case 'first':
  282. $limit = 1;
  283. break;
  284. }
  285. $dbo = $this->getDataSource();
  286. $default = [
  287. 'fields' => $fields,
  288. 'table' => $dbo->fullTableName($this),
  289. 'alias' => $alias,
  290. 'limit' => $limit,
  291. 'offset' => null,
  292. 'joins' => [],
  293. 'conditions' => [],
  294. 'order' => null,
  295. 'group' => null
  296. ];
  297. $params = array_merge($default, $options);
  298. $subQuery = trim($dbo->buildStatement($params, $this));
  299. if ($parenthesise) {
  300. $subQuery = '(' . $subQuery . ')';
  301. }
  302. return $subQuery;
  303. }
  304. /**
  305. * Wrapper find() to cache sql queries.
  306. *
  307. * @param array $conditions
  308. * @param array $fields
  309. * @param string $order
  310. * @param string $recursive
  311. * @return array
  312. */
  313. public function find($type = null, $query = []) {
  314. // reset/delete
  315. if (!empty($query['reset'])) {
  316. if (!empty($query['cache'])) {
  317. if (is_array($query['cache'])) {
  318. $key = $query['cache'][0];
  319. } else {
  320. $key = $query['cache'];
  321. if ($key === true) {
  322. $backtrace = debug_backtrace();
  323. $key = $backtrace[1]['function'];
  324. }
  325. }
  326. $this->deleteCache($key);
  327. }
  328. }
  329. // having and group clauses enhancement
  330. if (is_array($query) && !empty($query['having']) && !empty($query['group'])) {
  331. if (!is_array($query['group'])) {
  332. $query['group'] = [$query['group']];
  333. }
  334. $ds = $this->getDataSource();
  335. $having = $ds->conditions($query['having'], true, false);
  336. $query['group'][count($query['group']) - 1] .= " HAVING $having";
  337. } /* elseif (is_array($query) && !empty($query['having'])) {
  338. $ds = $this->getDataSource();
  339. $having = $ds->conditions($query['having'], true, false);
  340. $query['conditions'][] = '1=1 HAVING '.$having;
  341. }
  342. */
  343. // find
  344. if (!Configure::read('Cache.disable') && Configure::read('Cache.check') && !empty($query['cache'])) {
  345. if (is_array($query['cache'])) {
  346. $key = $query['cache'][0];
  347. $expires = DAY;
  348. if (!empty($query['cache'][1])) {
  349. $expires = $query['cache'][1];
  350. }
  351. } else {
  352. $key = $query['cache'];
  353. if ($key === true) {
  354. $backtrace = debug_backtrace();
  355. $key = $backtrace[1]['function'];
  356. }
  357. $expires = DAY;
  358. }
  359. $options = ['prefix' => strtolower(Inflector::underscore($this->alias)) . '__', ];
  360. if (!empty($expires)) {
  361. $options['duration'] = $expires;
  362. }
  363. if (!Configure::read('Cache.disable')) {
  364. Cache::config('sql', $options);
  365. $key = Inflector::underscore($key);
  366. $results = Cache::read($key, 'sql');
  367. }
  368. if (!isset($results)) {
  369. $results = parent::find($type, $query);
  370. Cache::write($key, $results, 'sql');
  371. }
  372. return $results;
  373. }
  374. // Without caching
  375. return parent::find($type, $query);
  376. }
  377. /**
  378. * This code will add formatted list functionallity to find you can easy replace the $this->Model->find('list'); with $this->Model->find('formattedlist', array('fields' => array('Model.id', 'Model.field1', 'Model.field2', 'Model.field3'), 'format' => '%s-%s %s')); and get option tag output of: Model.field1-Model.field2 Model.field3. Even better part is being able to setup your own format for the output!
  379. *
  380. * @see http://bakery.cakephp.org/articles/view/add-formatted-lists-to-your-appmodel
  381. * @deprecated
  382. * added Caching
  383. */
  384. protected function _find($type, $options = []) {
  385. $res = false;
  386. if ($res === false) {
  387. if (isset($options['cache'])) {
  388. unset($options['cache']);
  389. }
  390. if (!isset($options['recursive'])) {
  391. //$options['recursive'] = -1;
  392. }
  393. switch ($type) {
  394. // @see http://bakery.cakephp.org/deu/articles/nate/2010/10/10/quick-tipp_-_doing_ad-hoc-joins_bei_model_find
  395. case 'matches':
  396. if (!isset($options['joins'])) {
  397. $options['joins'] = [];
  398. }
  399. if (!isset($options['model']) || !isset($options['scope'])) {
  400. break;
  401. }
  402. $assoc = $this->hasAndBelongsToMany[$options['model']];
  403. $bind = "{$assoc['with']}.{$assoc['foreignKey']} = {$this->alias}.{$this->primaryKey}";
  404. $options['joins'][] = [
  405. 'table' => $assoc['joinTable'],
  406. 'alias' => $assoc['with'],
  407. 'type' => 'inner',
  408. 'foreignKey' => false,
  409. 'conditions' => [$bind]
  410. ];
  411. $bind = $options['model'] . '.' . $this->{$options['model']}->primaryKey . ' = ';
  412. $bind .= "{$assoc['with']}.{$assoc['associationForeignKey']}";
  413. $options['joins'][] = [
  414. 'table' => $this->{$options['model']}->table,
  415. 'alias' => $options['model'],
  416. 'type' => 'inner',
  417. 'foreignKey' => false,
  418. 'conditions' => [$bind] + (array)$options['scope'],
  419. ];
  420. unset($options['model'], $options['scope']);
  421. $type = 'all';
  422. break;
  423. // probably deprecated since "virtual fields" in 1.3
  424. case 'formattedlist':
  425. if (!isset($options['fields']) || count($options['fields']) < 3) {
  426. $res = parent::find('list', $options);
  427. break;
  428. }
  429. $this->recursive = -1;
  430. //setup formating
  431. $format = '';
  432. if (!isset($options['format'])) {
  433. for ($i = 0; $i < (count($options['fields']) - 1); $i++) {
  434. $format .= '%s ';
  435. }
  436. $format = substr($format, 0, -1);
  437. } else {
  438. $format = $options['format'];
  439. }
  440. //get data
  441. $list = parent::find('all', $options);
  442. // remove model alias from strings to only get field names
  443. $tmpPath2[] = $format;
  444. for ($i = 1; $i <= (count($options['fields']) - 1); $i++) {
  445. $field[$i] = str_replace($this->alias . '.', '', $options['fields'][$i]);
  446. $tmpPath2[] = '{n}.' . $this->alias . '.' . $field[$i];
  447. }
  448. //do the magic?? read the code...
  449. $res = Hash::combine($list, '{n}.' . $this->alias . '.' . $this->primaryKey, $tmpPath2);
  450. break;
  451. default:
  452. $res = parent::find($type, $options);
  453. }
  454. if (!empty($this->useCache)) {
  455. Cache::write($this->cacheName, $res, $this->cacheConfig);
  456. if (Configure::read('debug') > 0) {
  457. $this->log('WRITE (' . $this->cacheConfig . '): ' . $this->cacheName, 'cache');
  458. }
  459. }
  460. } else {
  461. if (Configure::read('debug') > 0) {
  462. $this->log('READ (' . $this->cacheConfig . '): ' . $this->cacheName, 'cache');
  463. }
  464. }
  465. return $res;
  466. }
  467. /**
  468. * Core-fix for multiple sort orders
  469. *
  470. * @param addiotional 'scope'=>array(field,order) - value is retrieved by (submitted) primary key
  471. * @return mixed
  472. * TODO: fix it
  473. */
  474. protected function _findNeighbors($state, $query, $results = []) {
  475. return parent::_findNeighbors($state, $query, $results);
  476. if (isset($query['scope'])) {
  477. //TODO
  478. }
  479. return parent::find($type, $options);
  480. }
  481. /**
  482. * @param mixed $id: id only, or request array
  483. * @param array $options
  484. * - filter: open/closed/none
  485. * - field (sortField, if not id)
  486. * - reverse: sortDirection (0=normalAsc/1=reverseDesc)
  487. * - displayField: ($this->displayField, if empty)
  488. * @param array $qryOptions
  489. * - recursive (defaults to -1)
  490. * TODO: try to use core function, TRY TO ALLOW MULTIPLE SORT FIELDS
  491. * @return array
  492. */
  493. public function neighbors($id = null, $options = [], $qryOptions = []) {
  494. $sortField = (!empty($options['field']) ? $options['field'] : 'created');
  495. $normalDirection = (!empty($options['reverse']) ? false : true);
  496. $sortDirWord = $normalDirection ? ['ASC', 'DESC'] : ['DESC', 'ASC'];
  497. $sortDirSymb = $normalDirection ? ['>=', '<='] : ['<=', '>='];
  498. $displayField = (!empty($options['displayField']) ? $options['displayField'] : $this->displayField);
  499. if (is_array($id)) {
  500. $data = $id;
  501. $id = $data[$this->alias][$this->primaryKey];
  502. } elseif ($id === null) {
  503. $id = $this->id;
  504. }
  505. if (!empty($id)) {
  506. $data = $this->find('first', ['conditions' => [$this->primaryKey => $id], 'contain' => []]);
  507. }
  508. if (empty($id) || empty($data) || empty($data[$this->alias][$sortField])) {
  509. return [];
  510. } else {
  511. $field = $data[$this->alias][$sortField];
  512. }
  513. $findOptions = ['recursive' => -1];
  514. if (isset($qryOptions['recursive'])) {
  515. $findOptions['recursive'] = $qryOptions['recursive'];
  516. }
  517. if (isset($qryOptions['contain'])) {
  518. $findOptions['contain'] = $qryOptions['contain'];
  519. }
  520. $findOptions['fields'] = [$this->alias . '.' . $this->primaryKey, $this->alias . '.' . $displayField];
  521. $findOptions['conditions'][$this->alias . '.' . $this->primaryKey . ' !='] = $id;
  522. // //TODO: take out
  523. if (!empty($options['filter']) && $options['filter'] == REQUEST_STATUS_FILTER_OPEN) {
  524. $findOptions['conditions'][$this->alias . '.status <'] = REQUEST_STATUS_DECLINED;
  525. } elseif (!empty($options['filter']) && $options['filter'] == REQUEST_STATUS_FILTER_CLOSED) {
  526. $findOptions['conditions'][$this->alias . '.status >='] = REQUEST_STATUS_DECLINED;
  527. }
  528. $return = [];
  529. if (!empty($qryOptions['conditions'])) {
  530. $findOptions['conditions'] = Hash::merge($findOptions['conditions'], $qryOptions['conditions']);
  531. }
  532. $options = $findOptions;
  533. $options['conditions'] = Hash::merge($options['conditions'], [$this->alias . '.' . $sortField . ' ' . $sortDirSymb[1] => $field]);
  534. $options['order'] = [$this->alias . '.' . $sortField . '' => $sortDirWord[1]];
  535. $this->id = $id;
  536. $return['prev'] = $this->find('first', $options);
  537. $options = $findOptions;
  538. $options['conditions'] = Hash::merge($options['conditions'], [$this->alias . '.' . $sortField . ' ' . $sortDirSymb[0] => $field]);
  539. $options['order'] = [$this->alias . '.' . $sortField . '' => $sortDirWord[0]]; // ??? why 0 instead of 1
  540. $this->id = $id;
  541. $return['next'] = $this->find('first', $options);
  542. return $return;
  543. }
  544. /**
  545. * Validates a primary or foreign key depending on the current schema data for this field
  546. * recognizes uuid (char36) and aiid (int10 unsigned) - not yet mixed (varchar36)
  547. * more useful than using numeric or notEmpty which are type specific
  548. *
  549. * @param array $data
  550. * @param array $options
  551. * - allowEmpty
  552. * @return bool Success
  553. */
  554. public function validateKey($data = [], $options = []) {
  555. $keys = array_keys($data);
  556. $key = array_shift($keys);
  557. $value = array_shift($data);
  558. $schema = $this->schema($key);
  559. if (!$schema) {
  560. return true;
  561. }
  562. $defaults = [
  563. 'allowEmpty' => false,
  564. ];
  565. $options += $defaults;
  566. if ($schema['type'] !== 'integer') {
  567. if ($options['allowEmpty'] && $value === '') {
  568. return true;
  569. }
  570. return Validation::uuid($value);
  571. }
  572. if ($options['allowEmpty'] && $value === 0) {
  573. return true;
  574. }
  575. return is_numeric($value) && (int)$value == $value && $value > 0;
  576. }
  577. /**
  578. * Checks if the passed enum value is valid
  579. *
  580. * @return bool Success
  581. */
  582. public function validateEnum(array $data, $enum = null, $additionalKeys = []) {
  583. $keys = array_keys($data);
  584. $valueKey = array_shift($keys);
  585. $value = $data[$valueKey];
  586. $keys = [];
  587. if ($enum === true) {
  588. $enum = $valueKey;
  589. }
  590. if ($enum !== null) {
  591. if (!method_exists($this, $enum)) {
  592. trigger_error('Enum method \'' . $enum . '()\' not exists', E_USER_ERROR);
  593. return false;
  594. }
  595. //TODO: make static
  596. $keys = $this->{$enum}();
  597. }
  598. $keys = array_merge($additionalKeys, array_keys($keys));
  599. if (!empty($keys) && in_array($value, $keys)) {
  600. return true;
  601. }
  602. return false;
  603. }
  604. /**
  605. * Checks if the content of 2 fields are equal
  606. * Does not check on empty fields! Return TRUE even if both are empty (secure against empty in another rule)!
  607. *
  608. * @return bool Success
  609. */
  610. public function validateIdentical($data = [], $compareWith = null, $options = []) {
  611. if (is_array($data)) {
  612. $value = array_shift($data);
  613. } else {
  614. $value = $data;
  615. }
  616. $compareValue = $this->data[$this->alias][$compareWith];
  617. $matching = ['string' => 'string', 'int' => 'integer', 'float' => 'float', 'bool' => 'boolean'];
  618. if (!empty($options['cast']) && array_key_exists($options['cast'], $matching)) {
  619. // cast values to string/int/float/bool if desired
  620. settype($compareValue, $matching[$options['cast']]);
  621. settype($value, $matching[$options['cast']]);
  622. }
  623. return ($compareValue === $value);
  624. }
  625. /**
  626. * Validate range, but in a more sane way than CORE range().
  627. * This range() validation rule is inclusive regarding the borders.
  628. *
  629. * If $lower and $upper are not set, will return true if
  630. * $check is a legal finite on this platform
  631. *
  632. * @param string $check Value to check
  633. * @param float $lower Lower limit
  634. * @param float $upper Upper limit
  635. * @return bool Success
  636. */
  637. public function validateRange($data, $lower = null, $upper = null) {
  638. foreach ($data as $key => $check) {
  639. break;
  640. }
  641. if (!is_numeric($check)) {
  642. return false;
  643. }
  644. if (isset($lower) && isset($upper)) {
  645. return ($check >= $lower && $check <= $upper);
  646. }
  647. return is_finite($check);
  648. }
  649. /**
  650. * Checks a record, if it is unique - depending on other fields in this table (transfered as array)
  651. * example in model: 'rule' => array ('validateUnique', array('belongs_to_table_id','some_id','user_id')),
  652. * if all keys (of the array transferred) match a record, return false, otherwise true
  653. *
  654. * @param array $fields Other fields to depend on
  655. * TODO: add possibity of deep nested validation (User -> Comment -> CommentCategory: UNIQUE comment_id, Comment.user_id)
  656. * @param array $options
  657. * - requireDependentFields Require all dependent fields for the validation rule to return true
  658. * @return bool Success
  659. */
  660. public function validateUnique($data, $fields = [], $options = []) {
  661. $id = (!empty($this->data[$this->alias][$this->primaryKey]) ? $this->data[$this->alias][$this->primaryKey] : 0);
  662. if (!$id && $this->id) {
  663. $id = $this->id;
  664. }
  665. foreach ($data as $key => $value) {
  666. $fieldName = $key;
  667. $fieldValue = $value;
  668. break;
  669. }
  670. $conditions = [
  671. $this->alias . '.' . $fieldName => $fieldValue,
  672. $this->alias . '.id !=' => $id];
  673. $fields = (array)$fields;
  674. if (!array_key_exists('allowEmpty', $fields)) {
  675. foreach ($fields as $dependingField) {
  676. if (isset($this->data[$this->alias][$dependingField])) { // add ONLY if some content is transfered (check on that first!)
  677. $conditions[$this->alias . '.' . $dependingField] = $this->data[$this->alias][$dependingField];
  678. } elseif (isset($this->data['Validation'][$dependingField])) { // add ONLY if some content is transfered (check on that first!
  679. $conditions[$this->alias . '.' . $dependingField] = $this->data['Validation'][$dependingField];
  680. } elseif (!empty($id)) {
  681. // manual query! (only possible on edit)
  682. $res = $this->find('first', ['fields' => [$this->alias . '.' . $dependingField], 'conditions' => [$this->alias . '.id' => $id]]);
  683. if (!empty($res)) {
  684. $conditions[$this->alias . '.' . $dependingField] = $res[$this->alias][$dependingField];
  685. }
  686. } else {
  687. if (!empty($options['requireDependentFields'])) {
  688. trigger_error('Required field ' . $dependingField . ' for validateUnique validation not present');
  689. return false;
  690. }
  691. return true;
  692. }
  693. }
  694. }
  695. $this->recursive = -1;
  696. if (count($conditions) > 2) {
  697. $this->recursive = 0;
  698. }
  699. $options = ['fields' => [$this->alias . '.' . $this->primaryKey], 'conditions' => $conditions];
  700. $res = $this->find('first', $options);
  701. return empty($res);
  702. }
  703. /**
  704. * Checks if a url is valid AND accessable (returns false otherwise)
  705. *
  706. * @param array/string $data: full url(!) starting with http://...
  707. * @options array
  708. * - allowEmpty TRUE/FALSE (TRUE: if empty => return TRUE)
  709. * - required TRUE/FALSE (TRUE: overrides allowEmpty)
  710. * - autoComplete (default: TRUE)
  711. * - deep (default: TRUE)
  712. * @return bool Success
  713. */
  714. public function validateUrl($data, $options = []) {
  715. if (is_array($data)) {
  716. foreach ($data as $key => $url) {
  717. break;
  718. }
  719. } else {
  720. $url = $data;
  721. }
  722. if (empty($url)) {
  723. if (!empty($options['allowEmpty']) && empty($options['required'])) {
  724. return true;
  725. }
  726. return false;
  727. }
  728. if (!isset($options['autoComplete']) || $options['autoComplete'] !== false) {
  729. $url = $this->_autoCompleteUrl($url);
  730. if (isset($key)) {
  731. $this->data[$this->alias][$key] = $url;
  732. }
  733. }
  734. if (!isset($options['strict']) || $options['strict'] !== false) {
  735. $options['strict'] = true;
  736. }
  737. // validation
  738. if (!Validation::url($url, $options['strict']) && env('REMOTE_ADDR') && env('REMOTE_ADDR') !== '127.0.0.1') {
  739. return false;
  740. }
  741. // same domain?
  742. if (!empty($options['sameDomain']) && env('HTTP_HOST')) {
  743. $is = parse_url($url, PHP_URL_HOST);
  744. $expected = env('HTTP_HOST');
  745. if (mb_strtolower($is) !== mb_strtolower($expected)) {
  746. return false;
  747. }
  748. }
  749. if (isset($options['deep']) && $options['deep'] === false) {
  750. return true;
  751. }
  752. return $this->_validUrl($url);
  753. }
  754. /**
  755. * Prepend protocol if missing
  756. *
  757. * @param string $url
  758. * @return string Url
  759. */
  760. protected function _autoCompleteUrl($url) {
  761. if (mb_strpos($url, '/') === 0) {
  762. $url = Router::url($url, true);
  763. } elseif (mb_strpos($url, '://') === false && mb_strpos($url, 'www.') === 0) {
  764. $url = 'http://' . $url;
  765. }
  766. return $url;
  767. }
  768. /**
  769. * Checks if a url is valid
  770. *
  771. * @param string url
  772. * @return bool Success
  773. */
  774. protected function _validUrl($url) {
  775. $headers = Utility::getHeaderFromUrl($url);
  776. if ($headers === false) {
  777. return false;
  778. }
  779. $headers = implode("\n", $headers);
  780. $protocol = mb_strpos($url, 'https://') === 0 ? 'HTTP' : 'HTTP';
  781. if (!preg_match('#^' . $protocol . '/.*?\s+[(200|301|302)]+\s#i', $headers)) {
  782. return false;
  783. }
  784. if (preg_match('#^' . $protocol . '/.*?\s+[(404|999)]+\s#i', $headers)) {
  785. return false;
  786. }
  787. return true;
  788. }
  789. /**
  790. * Validation of DateTime Fields (both Date and Time together)
  791. *
  792. * @param options
  793. * - dateFormat (defaults to 'ymd')
  794. * - allowEmpty
  795. * - after/before (fieldName to validate against)
  796. * - min/max (defaults to >= 1 - at least 1 second apart)
  797. * @return bool Success
  798. */
  799. public function validateDateTime($data, $options = []) {
  800. $format = !empty($options['dateFormat']) ? $options['dateFormat'] : 'ymd';
  801. if (is_array($data)) {
  802. $value = array_shift($data);
  803. } else {
  804. $value = $data;
  805. }
  806. $dateTime = explode(' ', trim($value), 2);
  807. $date = $dateTime[0];
  808. $time = (!empty($dateTime[1]) ? $dateTime[1] : '');
  809. if (!empty($options['allowEmpty']) && (empty($date) && empty($time) || $date == DEFAULT_DATE && $time == DEFAULT_TIME || $date == DEFAULT_DATE && empty($time))) {
  810. return true;
  811. }
  812. /*
  813. if ($this->validateDate($date, $options) && $this->validateTime($time, $options)) {
  814. return true;
  815. }
  816. */
  817. if (Validation::date($date, $format) && Validation::time($time)) {
  818. // after/before?
  819. $seconds = isset($options['min']) ? $options['min'] : 1;
  820. if (!empty($options['after']) && isset($this->data[$this->alias][$options['after']])) {
  821. if (strtotime($this->data[$this->alias][$options['after']]) > strtotime($value) - $seconds) {
  822. return false;
  823. }
  824. }
  825. if (!empty($options['before']) && isset($this->data[$this->alias][$options['before']])) {
  826. if (strtotime($this->data[$this->alias][$options['before']]) < strtotime($value) + $seconds) {
  827. return false;
  828. }
  829. }
  830. return true;
  831. }
  832. return false;
  833. }
  834. /**
  835. * Validation of Date fields (as the core one is buggy!!!)
  836. *
  837. * @param options
  838. * - dateFormat (defaults to 'ymd')
  839. * - allowEmpty
  840. * - after/before (fieldName to validate against)
  841. * - min (defaults to 0 - equal is OK too)
  842. * @return bool Success
  843. */
  844. public function validateDate($data, $options = []) {
  845. $format = !empty($options['format']) ? $options['format'] : 'ymd';
  846. if (is_array($data)) {
  847. $value = array_shift($data);
  848. } else {
  849. $value = $data;
  850. }
  851. $dateTime = explode(' ', trim($value), 2);
  852. $date = $dateTime[0];
  853. if (!empty($options['allowEmpty']) && (empty($date) || $date == DEFAULT_DATE)) {
  854. return true;
  855. }
  856. if (Validation::date($date, $format)) {
  857. // after/before?
  858. $days = !empty($options['min']) ? $options['min'] : 0;
  859. if (!empty($options['after']) && isset($this->data[$this->alias][$options['after']])) {
  860. if ($this->data[$this->alias][$options['after']] > date(FORMAT_DB_DATE, strtotime($date) - $days * DAY)) {
  861. return false;
  862. }
  863. }
  864. if (!empty($options['before']) && isset($this->data[$this->alias][$options['before']])) {
  865. if ($this->data[$this->alias][$options['before']] < date(FORMAT_DB_DATE, strtotime($date) + $days * DAY)) {
  866. return false;
  867. }
  868. }
  869. return true;
  870. }
  871. return false;
  872. }
  873. /**
  874. * Validation of Time fields
  875. *
  876. * @param array $options
  877. * - timeFormat (defaults to 'hms')
  878. * - allowEmpty
  879. * - after/before (fieldName to validate against)
  880. * - min/max (defaults to >= 1 - at least 1 minute apart)
  881. * @return bool Success
  882. */
  883. public function validateTime($data, $options = []) {
  884. if (is_array($data)) {
  885. $value = array_shift($data);
  886. } else {
  887. $value = $data;
  888. }
  889. $dateTime = explode(' ', trim($value), 2);
  890. $value = array_pop($dateTime);
  891. if (Validation::time($value)) {
  892. // after/before?
  893. if (!empty($options['after']) && isset($this->data[$this->alias][$options['after']])) {
  894. if ($this->data[$this->alias][$options['after']] >= $value) {
  895. return false;
  896. }
  897. }
  898. if (!empty($options['before']) && isset($this->data[$this->alias][$options['before']])) {
  899. if ($this->data[$this->alias][$options['before']] <= $value) {
  900. return false;
  901. }
  902. }
  903. return true;
  904. }
  905. return false;
  906. }
  907. /**
  908. * Validation of Date Fields (>= minDate && <= maxDate)
  909. *
  910. * @param options
  911. * - min/max (TODO!!)
  912. */
  913. public function validateDateRange($data, $options = []) {
  914. }
  915. /**
  916. * Validation of Time Fields (>= minTime && <= maxTime)
  917. *
  918. * @param options
  919. * - min/max (TODO!!)
  920. */
  921. public function validateTimeRange($data, $options = []) {
  922. }
  923. /**
  924. * Model validation rule for email addresses
  925. *
  926. * @return bool Success
  927. */
  928. public function validateUndisposable($data, $proceed = false) {
  929. $email = array_shift($data);
  930. if (empty($email)) {
  931. return true;
  932. }
  933. return $this->isUndisposableEmail($email, false, $proceed);
  934. }
  935. /**
  936. * NOW: can be set to work offline only (if server is down etc)
  937. * Checks if a email is not from a garbage hoster
  938. *
  939. * @param string email (necessary)
  940. * @return bool true if valid, else false
  941. */
  942. public function isUndisposableEmail($email, $onlineMode = false, $proceed = false) {
  943. if (!isset($this->UndisposableEmail)) {
  944. App::import('Vendor', 'undisposable/undisposable');
  945. $this->UndisposableEmail = new UndisposableEmail();
  946. }
  947. if (!$onlineMode) {
  948. // crashed with white screen of death otherwise... (if foreign page is 404)
  949. $this->UndisposableEmail->useOnlineList(false);
  950. }
  951. if (!class_exists('Validation')) {
  952. App::uses('Validation', 'Utility');
  953. }
  954. if (!Validation::email($email)) {
  955. return false;
  956. }
  957. if ($this->UndisposableEmail->isUndisposableEmail($email) === false) {
  958. // trigger log
  959. $this->log('Disposable Email detected: ' . h($email) . ' (IP ' . env('REMOTE_ADDR') . ')', 'undisposable');
  960. if ($proceed === true) {
  961. return true;
  962. }
  963. return false;
  964. }
  965. return true;
  966. }
  967. /**
  968. * Is blocked email?
  969. * //TODO: move outside of MyModel?
  970. *
  971. * @return bool ifNotBlacklisted
  972. */
  973. public function validateNotBlocked($params) {
  974. $email = array_shift($params);
  975. if (!isset($this->Blacklist)) {
  976. $this->Blacklist = ClassRegistry::init('Tools.Blacklist');
  977. }
  978. if ($this->Blacklist->isBlacklisted(Blacklist::TYPE_EMAIL, $email)) {
  979. return false;
  980. }
  981. return true;
  982. }
  983. /**
  984. * Set + guaranteeFields!
  985. * Extends the core set function (only using data!!!)
  986. *
  987. * @param mixed $data
  988. * @param mixed $data2 (optional)
  989. * @param array $requiredFields Required fields
  990. * @param array $fieldList Whitelist / Allowed fields
  991. * @return array
  992. */
  993. public function set($data, $data2 = null, $requiredFields = [], $fieldList = []) {
  994. if (!empty($requiredFields)) {
  995. $data = $this->guaranteeFields($requiredFields, $data);
  996. }
  997. if (!empty($fieldList)) {
  998. $data = $this->whitelist($fieldList, $data);
  999. }
  1000. return parent::set($data, $data2);
  1001. }
  1002. /**
  1003. * @param array $fieldList
  1004. * @param array $data (optional)
  1005. * @return array
  1006. */
  1007. public function whitelist(array $fieldList, $data = null) {
  1008. $model = $this->alias;
  1009. if ($data === null) {
  1010. $data =& $this->data;
  1011. }
  1012. if (empty($data[$model])) {
  1013. return [];
  1014. }
  1015. foreach ($data[$model] as $key => $val) {
  1016. if (!in_array($key, $fieldList)) {
  1017. unset($data[$model][$key]);
  1018. }
  1019. }
  1020. return $data;
  1021. }
  1022. /**
  1023. * Instead of whitelisting this will remove all blacklisted keys.
  1024. *
  1025. * @param array $blacklist
  1026. * - array: fields to blacklist
  1027. * - boolean TRUE: removes all foreign_keys (_id)
  1028. * note: one-dimensional
  1029. * @return array
  1030. */
  1031. public function blacklist($blacklist, $data = null) {
  1032. $model = $this->alias;
  1033. if ($data === null) {
  1034. $data =& $this->data;
  1035. }
  1036. if (empty($data[$model])) {
  1037. return [];
  1038. }
  1039. if ($blacklist === true) {
  1040. foreach ($data[$model] as $key => $value) {
  1041. if (substr($key, -3, 3) === '_id') {
  1042. unset($data[$model][$key]);
  1043. }
  1044. }
  1045. return;
  1046. }
  1047. foreach ($blacklist as $key) {
  1048. if (isset($data[$model][$key])) {
  1049. unset($data[$model][$key]);
  1050. }
  1051. }
  1052. return $data;
  1053. }
  1054. /**
  1055. * Generate a whitelist, based on the current schema and a passed blacklist.
  1056. *
  1057. * @param array $blacklist
  1058. * @return array
  1059. */
  1060. public function generateWhitelistFromBlacklist(array $blacklist) {
  1061. return array_diff(array_keys($this->schema()), $blacklist);
  1062. }
  1063. /**
  1064. * Make sure required fields exists - in order to properly validate them
  1065. *
  1066. * @param array: field1, field2 - or field1, Model2.field1 etc
  1067. * @param array: data (optional, otherwise the array with the required fields will be returned)
  1068. * @return array
  1069. */
  1070. public function guaranteeFields($requiredFields, $data = null) {
  1071. $guaranteedFields = [];
  1072. foreach ($requiredFields as $column) {
  1073. if (strpos($column, '.') !== false) {
  1074. list($model, $column) = explode('.', $column, 2);
  1075. } else {
  1076. $model = $this->alias;
  1077. }
  1078. $guaranteedFields[$model][$column] = ''; # now field exists in any case!
  1079. }
  1080. if ($data === null) {
  1081. return $guaranteedFields;
  1082. }
  1083. if (!empty($guaranteedFields)) {
  1084. $data = Hash::merge($guaranteedFields, $data);
  1085. }
  1086. return $data;
  1087. }
  1088. /**
  1089. * Make certain fields a requirement for the form to validate
  1090. * (they must only be present - can still be empty, though!)
  1091. *
  1092. * @param array $fieldList
  1093. * @param bool $allowEmpty (or NULL to not touch already set elements)
  1094. * @return void
  1095. */
  1096. public function requireFields($requiredFields, $allowEmpty = null) {
  1097. if ($allowEmpty === null) {
  1098. $setAllowEmpty = true;
  1099. } else {
  1100. $setAllowEmpty = $allowEmpty;
  1101. }
  1102. foreach ($requiredFields as $column) {
  1103. if (strpos($column, '.') !== false) {
  1104. list($model, $column) = explode('.', $column, 2);
  1105. } else {
  1106. $model = $this->alias;
  1107. }
  1108. if ($model !== $this->alias) {
  1109. continue;
  1110. }
  1111. if (empty($this->validate[$column])) {
  1112. $this->validate[$column]['notEmpty'] = ['rule' => 'notEmpty', 'required' => true, 'allowEmpty' => $setAllowEmpty, 'message' => 'valErrMandatoryField'];
  1113. } else {
  1114. $keys = array_keys($this->validate[$column]);
  1115. if (!in_array('rule', $keys)) {
  1116. $key = array_shift($keys);
  1117. $this->validate[$column][$key]['required'] = true;
  1118. if (!isset($this->validate[$column][$key]['allowEmpty'])) {
  1119. $this->validate[$column][$key]['allowEmpty'] = $setAllowEmpty;
  1120. }
  1121. } else {
  1122. $keys['required'] = true;
  1123. if (!isset($keys['allowEmpty'])) {
  1124. $keys['allowEmpty'] = $setAllowEmpty;
  1125. }
  1126. $this->validate[$column] = $keys;
  1127. }
  1128. }
  1129. }
  1130. }
  1131. /**
  1132. * Shortcut method to find a specific entry via primary key.
  1133. * Wraps ShimModel::get() for an exception free response.
  1134. *
  1135. * $record = $this->Model->get($id);
  1136. *
  1137. * @param mixed $id
  1138. * @param array $options Options for find().
  1139. * @return array
  1140. */
  1141. public function record($id, array $options = []) {
  1142. try {
  1143. return $this->get($id, $options);
  1144. } catch (RecordNotFoundException $e) {
  1145. }
  1146. return array();
  1147. }
  1148. /**
  1149. * Get all related entries that have been used so far
  1150. *
  1151. * @param string $modelName The related model
  1152. * @param string $groupField Field to group by
  1153. * @param string $type Find type
  1154. * @param array $options
  1155. * @return array
  1156. */
  1157. public function getRelatedInUse($modelName, $groupField = null, $type = 'all', $options = []) {
  1158. if ($groupField === null) {
  1159. $groupField = $this->belongsTo[$modelName]['foreignKey'];
  1160. }
  1161. $defaults = [
  1162. 'contain' => [$modelName],
  1163. 'group' => $groupField,
  1164. 'order' => $this->$modelName->order ? $this->$modelName->order : [$modelName . '.' . $this->$modelName->displayField => 'ASC'],
  1165. ];
  1166. if ($type === 'list') {
  1167. $defaults['fields'] = [$modelName . '.' . $this->$modelName->primaryKey, $modelName . '.' . $this->$modelName->displayField];
  1168. }
  1169. $options += $defaults;
  1170. return $this->find($type, $options);
  1171. }
  1172. /**
  1173. * Get all fields that have been used so far
  1174. *
  1175. * @param string $groupField Field to group by
  1176. * @param string $type Find type
  1177. * @param array $options
  1178. * @return array
  1179. */
  1180. public function getFieldInUse($groupField, $type = 'all', $options = []) {
  1181. $defaults = [
  1182. 'group' => $groupField,
  1183. 'order' => [$this->alias . '.' . $this->displayField => 'ASC'],
  1184. ];
  1185. if ($type === 'list') {
  1186. $defaults['fields'] = [$this->alias . '.' . $this->primaryKey, $this->alias . '.' . $this->displayField];
  1187. }
  1188. $options += $defaults;
  1189. return $this->find($type, $options);
  1190. }
  1191. /**
  1192. * Update a row with certain fields (dont use "Model" as super-key)
  1193. *
  1194. * @param int $id
  1195. * @param array $data
  1196. * @return bool|array Success
  1197. */
  1198. public function update($id, $data, $validate = false) {
  1199. $this->id = $id;
  1200. $options = [
  1201. 'validate' => $validate,
  1202. 'fieldList' => array_keys($data)
  1203. ];
  1204. return $this->save($data, $options);
  1205. }
  1206. /**
  1207. * Toggles Field (Important/Deleted/Primary etc)
  1208. *
  1209. * @param STRING fieldName
  1210. * @param int id (cleaned!)
  1211. * @return ARRAY record: [Model][values],...
  1212. */
  1213. public function toggleField($fieldName, $id) {
  1214. $record = $this->get($id, ['conditions' => [$this->primaryKey, $fieldName]]);
  1215. if (!empty($record) && !empty($fieldName) && $this->hasField($fieldName)) {
  1216. $record[$this->alias][$fieldName] = ($record[$this->alias][$fieldName] == 1 ? 0 : 1);
  1217. $this->id = $id;
  1218. $this->saveField($fieldName, $record[$this->alias][$fieldName]);
  1219. }
  1220. return $record;
  1221. }
  1222. /**
  1223. * Truncate TABLE (already validated, that table exists)
  1224. *
  1225. * @param string table [default:FALSE = current model table]
  1226. * @return bool Success
  1227. */
  1228. public function truncate($table = null) {
  1229. if (empty($table)) {
  1230. $table = $this->table;
  1231. }
  1232. $db = ConnectionManager::getDataSource($this->useDbConfig);
  1233. return $db->truncate($table);
  1234. }
  1235. /**
  1236. * Recursive Dropdown Lists
  1237. * NEEDS tree behavior, NEEDS lft, rght, parent_id (!)
  1238. * //FIXME
  1239. */
  1240. public function recursiveSelect($conditions = [], $attachTree = false, $spacer = '-- ') {
  1241. if ($attachTree) {
  1242. $this->Behaviors->load('Tree');
  1243. }
  1244. $data = $this->generateTreeList($conditions, null, null, $spacer);
  1245. return $data;
  1246. }
  1247. /**
  1248. * From http://othy.wordpress.com/2006/06/03/generatenestedlist/
  1249. * NEEDS parent_id
  1250. * //TODO refactor for 1.2
  1251. *
  1252. * @deprecated use generateTreeList instead
  1253. */
  1254. public function generateNestedList($conditions = null, $indent = '--') {
  1255. $cats = $this->find('threaded', ['conditions' => $conditions, 'fields' => [
  1256. $this->alias . '.' . $this->primaryKey,
  1257. $this->alias . '.' . $this->displayField,
  1258. $this->alias . '.parent_id']]);
  1259. return $this->_generateNestedList($cats, $indent);
  1260. }
  1261. /**
  1262. * From http://othy.wordpress.com/2006/06/03/generatenestedlist/
  1263. *
  1264. * @deprecated use generateTreeList instead
  1265. */
  1266. public function _generateNestedList($cats, $indent = '--', $level = 0) {
  1267. static $list = [];
  1268. $c = count($cats);
  1269. for ($i = 0; $i < $c; $i++) {
  1270. $list[$cats[$i][$this->alias][$this->primaryKey]] = str_repeat($indent, $level) . $cats[$i][$this->alias][$this->displayField];
  1271. if (!empty($cats[$i]['children'])) {
  1272. $this->_generateNestedList($cats[$i]['children'], $indent, $level + 1);
  1273. }
  1274. }
  1275. return $list;
  1276. }
  1277. }