MyModel.php 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411
  1. <?php
  2. App::uses('ShimModel', 'Shim.Model');
  3. App::uses('Utility', 'Tools.Utility');
  4. App::uses('Hash', 'Utility');
  5. App::uses('Validation', 'Utility');
  6. /**
  7. * Model enhancements for Cake2
  8. *
  9. * @author Mark Scherer
  10. * @license http://opensource.org/licenses/mit-license.php MIT
  11. */
  12. class MyModel extends ShimModel {
  13. /**
  14. * MyModel::__construct()
  15. *
  16. * @param int $id
  17. * @param string $table
  18. * @param string $ds
  19. */
  20. public function __construct($id = false, $table = null, $ds = null) {
  21. parent::__construct($id, $table, $ds);
  22. // enable caching
  23. if (!Configure::read('Cache.disable') && Cache::config('sql') === false) {
  24. if (!file_exists(CACHE . 'sql')) {
  25. mkdir(CACHE . 'sql', CHOWN_PUBLIC);
  26. }
  27. Cache::config('sql', [
  28. 'engine' => 'File',
  29. 'serialize' => true,
  30. 'prefix' => '',
  31. 'path' => CACHE . 'sql' . DS,
  32. 'duration' => '+1 day'
  33. ]);
  34. }
  35. // Get a notice if there is an AppModel instance instead of a real Model (in those cases usually a dev error!)
  36. if (!is_a($this, $this->name) && $this->displayField !== $this->primaryKey && $this->useDbConfig === 'default'
  37. && !Configure::read('Core.disableModelInstanceNotice')) {
  38. trigger_error('AppModel instance! Expected: ' . $this->name);
  39. }
  40. }
  41. /**
  42. * The main method for any enumeration, should be called statically
  43. * Now also supports reordering/filtering
  44. *
  45. * @link http://www.dereuromark.de/2010/06/24/static-enums-or-semihardcoded-attributes/
  46. * @param string $value or array $keys or NULL for complete array result
  47. * @param array $options (actual data)
  48. * @return mixed string/array
  49. */
  50. public static function enum($value, $options, $default = null) {
  51. if ($value !== null && !is_array($value)) {
  52. if (array_key_exists($value, $options)) {
  53. return $options[$value];
  54. }
  55. return $default;
  56. } elseif ($value !== null) {
  57. $newOptions = [];
  58. foreach ($value as $v) {
  59. $newOptions[$v] = $options[$v];
  60. }
  61. return $newOptions;
  62. }
  63. return $options;
  64. }
  65. /**
  66. * @return string Error message with error number
  67. */
  68. public function lastError() {
  69. $db = $this->getDataSource();
  70. return $db->lastError();
  71. }
  72. /**
  73. * Combine virtual fields with fields values of find()
  74. * USAGE:
  75. * $this->Model->find('all', array('fields' => $this->Model->virtualFields('full_name')));
  76. * Also adds the field to the virtualFields array of the model (for correct result)
  77. * TODO: adding of fields only temperory!
  78. *
  79. * @param array $virtualFields to include
  80. * @return array
  81. */
  82. public function virtualFields($fields = []) {
  83. $res = [];
  84. foreach ((array)$fields as $field => $sql) {
  85. if (is_int($field)) {
  86. $field = $sql;
  87. $sql = null;
  88. }
  89. $plugin = $model = null;
  90. if (($pos = strrpos($field, '.')) !== false) {
  91. $model = substr($field, 0, $pos);
  92. $field = substr($field, $pos + 1);
  93. if (($pos = strrpos($model, '.')) !== false) {
  94. list($plugin, $model) = pluginSplit($model);
  95. }
  96. }
  97. if (empty($model)) {
  98. $model = $this->alias;
  99. if ($sql === null) {
  100. $sql = $this->virtualFields[$field];
  101. } else {
  102. $this->virtualFields[$field] = $sql;
  103. }
  104. } else {
  105. if (!isset($this->$model)) {
  106. $fullModelName = ($plugin ? $plugin . '.' : '') . $model;
  107. $this->$model = ClassRegistry::init($fullModelName);
  108. }
  109. if ($sql === null) {
  110. $sql = $this->$model->virtualFields[$field];
  111. } else {
  112. $this->$model->virtualFields[$field] = $sql;
  113. }
  114. }
  115. $res[] = $sql . ' AS ' . $model . '__' . $field;
  116. }
  117. return $res;
  118. }
  119. /**
  120. * HIGHLY EXPERIMENTAL
  121. * manually escape value for updateAll() etc
  122. *
  123. * @return string
  124. */
  125. public function escapeValue($value) {
  126. if ($value === null || is_numeric($value)) {
  127. return $value;
  128. }
  129. if (is_bool($value)) {
  130. return (int)$value;
  131. }
  132. return "'" . $value . "'";
  133. }
  134. /**
  135. * HIGHLY EXPERIMENTAL
  136. *
  137. * @see http://cakephp.lighthouseapp.com/projects/42648/tickets/1799-model-should-have-escapefield-method
  138. * @return string
  139. */
  140. public function value($content) {
  141. $db = $this->getDatasource();
  142. return $db->value($content);
  143. }
  144. /**
  145. * TODO: move to behavior (Incremental)
  146. *
  147. * @param mixed id (single string)
  148. * @param options:
  149. * - step (defaults to 1)
  150. * - current (if none it will get it from db)
  151. * - reset (if true, it will be set to 0)
  152. * - field (defaults to 'count')
  153. * - modify (if true if will affect modified timestamp)
  154. * - timestampField (if provided it will be filled with NOW())
  155. * @return See Model::save()
  156. */
  157. public function up($id, $customOptions = []) {
  158. $step = 1;
  159. if (isset($customOptions['step'])) {
  160. $step = $customOptions['step'];
  161. }
  162. $field = 'count';
  163. if (isset($customOptions['field'])) {
  164. $field = $customOptions['field'];
  165. }
  166. if (isset($customOptions['reset'])) {
  167. $currentValue = $step = 0;
  168. } elseif (!isset($customOptions['current'])) {
  169. $currentValue = $this->fieldByConditions($field, [$this->alias . '.id' => $id]);
  170. if ($currentValue === false) {
  171. return false;
  172. }
  173. } else {
  174. $currentValue = $customOptions['current'];
  175. }
  176. $value = (int)$currentValue + (int)$step;
  177. $data = [$field => $value];
  178. if (empty($customOptions['modify'])) {
  179. $data['modified'] = false;
  180. }
  181. if (!empty($customOptions['timestampField'])) {
  182. $data[$customOptions['timestampField']] = date(FORMAT_DB_DATETIME);
  183. }
  184. $data[$this->primaryKey] = $id;
  185. return $this->save($data, ['validate' => false]);
  186. }
  187. /**
  188. * Return the next auto increment id from the current table
  189. * UUIDs will return false
  190. *
  191. * @return int next auto increment value or False on failure
  192. */
  193. public function getNextAutoIncrement() {
  194. $query = "SHOW TABLE STATUS WHERE name = '" . $this->tablePrefix . $this->table . "'";
  195. $result = $this->query($query);
  196. if (!isset($result[0]['TABLES']['Auto_increment'])) {
  197. return false;
  198. }
  199. return (int)$result[0]['TABLES']['Auto_increment'];
  200. }
  201. /**
  202. * Fix for non atomic queries (MyISAM etc) and saveAll to still return just the boolean result
  203. * Otherwise you would have to iterate over all result values to find out if the save was successful.
  204. *
  205. * Use Configure::read('Model.atomic') to modify atomic behavior.
  206. * Additional options:
  207. *
  208. * - returnArray: bool
  209. *
  210. * @param mixed $data
  211. * @param array $options
  212. * @return bool Success
  213. */
  214. public function saveAll($data = null, $options = []) {
  215. if (!isset($options['atomic']) && Configure::read('Model.atomic') !== null) {
  216. $options['atomic'] = (bool)Configure::read('Model.atomic');
  217. }
  218. $res = parent::saveAll($data, $options);
  219. if (is_array($res) && empty($options['returnArray'])) {
  220. $res = Utility::isValidSaveAll($res);
  221. }
  222. return $res;
  223. }
  224. /**
  225. * Enables HABTM-Validation
  226. * e.g. with
  227. * 'rule' => array('multiple', array('min' => 2))
  228. *
  229. * @return bool Success
  230. */
  231. public function beforeValidate($options = []) {
  232. foreach ($this->hasAndBelongsToMany as $k => $v) {
  233. if (isset($this->data[$k][$k])) {
  234. $this->data[$this->alias][$k] = $this->data[$k][$k];
  235. }
  236. }
  237. return parent::beforeValidate($options);
  238. }
  239. /**
  240. * @param params
  241. * - key: functioName or other key used
  242. * @return bool Success
  243. */
  244. public function deleteCache($key = null) {
  245. $key = Inflector::underscore($key);
  246. if (!empty($key)) {
  247. return Cache::delete(strtolower(Inflector::underscore($this->alias)) . '__' . $key, 'sql');
  248. }
  249. return Cache::clear(false, 'sql');
  250. }
  251. /**
  252. * Generates a SQL subquery snippet to be used in your actual query.
  253. * Your subquery snippet needs to return a single value or flat array of values.
  254. *
  255. * Example:
  256. *
  257. * $this->Model->find('first', array(
  258. * 'conditions' => array('NOT' => array('some_id' => $this->Model->subquery(...)))
  259. * ))
  260. *
  261. * Note: You might have to set `autoFields` to false in order to retrieve only the fields you request:
  262. * http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html#containablebehavior-options
  263. *
  264. * @param string $type The type of the query ('count'/'all'/'first' - first only works with some mysql versions)
  265. * @param array $options The options array
  266. * @param string $alias You can use this intead of $options['alias'] if you want
  267. * @param bool $parenthesise Add parenthesis before and after
  268. * @return string result sql snippet of the query to run
  269. * @modified Mark Scherer (cake2.x ready and improvements)
  270. * @link http://bakery.cakephp.org/articles/lucaswxp/2011/02/11/easy_and_simple_subquery_cakephp
  271. */
  272. public function subquery($type, $options = [], $alias = null, $parenthesise = true) {
  273. if ($alias === null) {
  274. $alias = 'Sub' . $this->alias . '';
  275. }
  276. $fields = [$alias . '.id'];
  277. $limit = null;
  278. switch ($type) {
  279. case 'count':
  280. $fields = ['COUNT(*)'];
  281. break;
  282. case 'first':
  283. $limit = 1;
  284. break;
  285. }
  286. $dbo = $this->getDataSource();
  287. $default = [
  288. 'fields' => $fields,
  289. 'table' => $dbo->fullTableName($this),
  290. 'alias' => $alias,
  291. 'limit' => $limit,
  292. 'offset' => null,
  293. 'joins' => [],
  294. 'conditions' => [],
  295. 'order' => null,
  296. 'group' => null
  297. ];
  298. $params = array_merge($default, $options);
  299. $subQuery = trim($dbo->buildStatement($params, $this));
  300. if ($parenthesise) {
  301. $subQuery = '(' . $subQuery . ')';
  302. }
  303. return $subQuery;
  304. }
  305. /**
  306. * Wrapper find() to cache sql queries.
  307. *
  308. * @param array $conditions
  309. * @param array $fields
  310. * @param string $order
  311. * @param string $recursive
  312. * @return array
  313. */
  314. public function find($type = null, $query = []) {
  315. // reset/delete
  316. if (!empty($query['reset'])) {
  317. if (!empty($query['cache'])) {
  318. if (is_array($query['cache'])) {
  319. $key = $query['cache'][0];
  320. } else {
  321. $key = $query['cache'];
  322. if ($key === true) {
  323. $backtrace = debug_backtrace();
  324. $key = $backtrace[1]['function'];
  325. }
  326. }
  327. $this->deleteCache($key);
  328. }
  329. }
  330. // having and group clauses enhancement
  331. if (is_array($query) && !empty($query['having']) && !empty($query['group'])) {
  332. if (!is_array($query['group'])) {
  333. $query['group'] = [$query['group']];
  334. }
  335. $ds = $this->getDataSource();
  336. $having = $ds->conditions($query['having'], true, false);
  337. $query['group'][count($query['group']) - 1] .= " HAVING $having";
  338. } /* elseif (is_array($query) && !empty($query['having'])) {
  339. $ds = $this->getDataSource();
  340. $having = $ds->conditions($query['having'], true, false);
  341. $query['conditions'][] = '1=1 HAVING '.$having;
  342. }
  343. */
  344. // find
  345. if (!Configure::read('Cache.disable') && Configure::read('Cache.check') && !empty($query['cache'])) {
  346. if (is_array($query['cache'])) {
  347. $key = $query['cache'][0];
  348. $expires = DAY;
  349. if (!empty($query['cache'][1])) {
  350. $expires = $query['cache'][1];
  351. }
  352. } else {
  353. $key = $query['cache'];
  354. if ($key === true) {
  355. $backtrace = debug_backtrace();
  356. $key = $backtrace[1]['function'];
  357. }
  358. $expires = DAY;
  359. }
  360. $options = ['prefix' => strtolower(Inflector::underscore($this->alias)) . '__', ];
  361. if (!empty($expires)) {
  362. $options['duration'] = $expires;
  363. }
  364. if (!Configure::read('Cache.disable')) {
  365. Cache::config('sql', $options);
  366. $key = Inflector::underscore($key);
  367. $results = Cache::read($key, 'sql');
  368. }
  369. if (!isset($results)) {
  370. $results = parent::find($type, $query);
  371. Cache::write($key, $results, 'sql');
  372. }
  373. return $results;
  374. }
  375. // Without caching
  376. return parent::find($type, $query);
  377. }
  378. /**
  379. * 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!
  380. *
  381. * @see http://bakery.cakephp.org/articles/view/add-formatted-lists-to-your-appmodel
  382. * @deprecated
  383. * added Caching
  384. */
  385. protected function _find($type, $options = []) {
  386. $res = false;
  387. if ($res === false) {
  388. if (isset($options['cache'])) {
  389. unset($options['cache']);
  390. }
  391. if (!isset($options['recursive'])) {
  392. //$options['recursive'] = -1;
  393. }
  394. switch ($type) {
  395. // @see http://bakery.cakephp.org/deu/articles/nate/2010/10/10/quick-tipp_-_doing_ad-hoc-joins_bei_model_find
  396. case 'matches':
  397. if (!isset($options['joins'])) {
  398. $options['joins'] = [];
  399. }
  400. if (!isset($options['model']) || !isset($options['scope'])) {
  401. break;
  402. }
  403. $assoc = $this->hasAndBelongsToMany[$options['model']];
  404. $bind = "{$assoc['with']}.{$assoc['foreignKey']} = {$this->alias}.{$this->primaryKey}";
  405. $options['joins'][] = [
  406. 'table' => $assoc['joinTable'],
  407. 'alias' => $assoc['with'],
  408. 'type' => 'inner',
  409. 'foreignKey' => false,
  410. 'conditions' => [$bind]
  411. ];
  412. $bind = $options['model'] . '.' . $this->{$options['model']}->primaryKey . ' = ';
  413. $bind .= "{$assoc['with']}.{$assoc['associationForeignKey']}";
  414. $options['joins'][] = [
  415. 'table' => $this->{$options['model']}->table,
  416. 'alias' => $options['model'],
  417. 'type' => 'inner',
  418. 'foreignKey' => false,
  419. 'conditions' => [$bind] + (array)$options['scope'],
  420. ];
  421. unset($options['model'], $options['scope']);
  422. $type = 'all';
  423. break;
  424. // probably deprecated since "virtual fields" in 1.3
  425. case 'formattedlist':
  426. if (!isset($options['fields']) || count($options['fields']) < 3) {
  427. $res = parent::find('list', $options);
  428. break;
  429. }
  430. //setup formatting
  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. if (count($conditions) > 2 && !isset($options['contain']) && !isset($options['recursive'])) {
  696. $options['recursive'] = 0;
  697. }
  698. $options = ['fields' => [$this->alias . '.' . $this->primaryKey], 'conditions' => $conditions] + $options;
  699. $res = $this->find('count', $options);
  700. return empty($res);
  701. }
  702. /**
  703. * Checks if a url is valid AND accessable (returns false otherwise)
  704. *
  705. * @param array/string $data: full url(!) starting with http://...
  706. * @options array
  707. * - allowEmpty TRUE/FALSE (TRUE: if empty => return TRUE)
  708. * - required TRUE/FALSE (TRUE: overrides allowEmpty)
  709. * - autoComplete (default: TRUE)
  710. * - deep (default: TRUE)
  711. * @return bool Success
  712. */
  713. public function validateUrl($data, $options = []) {
  714. if (is_array($data)) {
  715. foreach ($data as $key => $url) {
  716. break;
  717. }
  718. } else {
  719. $url = $data;
  720. }
  721. if (empty($url)) {
  722. if (!empty($options['allowEmpty']) && empty($options['required'])) {
  723. return true;
  724. }
  725. return false;
  726. }
  727. if (!isset($options['autoComplete']) || $options['autoComplete'] !== false) {
  728. $url = $this->_autoCompleteUrl($url);
  729. if (isset($key)) {
  730. $this->data[$this->alias][$key] = $url;
  731. }
  732. }
  733. if (!isset($options['strict']) || $options['strict'] !== false) {
  734. $options['strict'] = true;
  735. }
  736. // validation
  737. if (!Validation::url($url, $options['strict']) && env('REMOTE_ADDR') && env('REMOTE_ADDR') !== '127.0.0.1') {
  738. return false;
  739. }
  740. // same domain?
  741. if (!empty($options['sameDomain']) && env('HTTP_HOST')) {
  742. $is = parse_url($url, PHP_URL_HOST);
  743. $expected = env('HTTP_HOST');
  744. if (mb_strtolower($is) !== mb_strtolower($expected)) {
  745. return false;
  746. }
  747. }
  748. if (isset($options['deep']) && $options['deep'] === false) {
  749. return true;
  750. }
  751. return $this->_validUrl($url);
  752. }
  753. /**
  754. * Prepend protocol if missing
  755. *
  756. * @param string $url
  757. * @return string Url
  758. */
  759. protected function _autoCompleteUrl($url) {
  760. if (mb_strpos($url, '/') === 0) {
  761. $url = Router::url($url, true);
  762. } elseif (mb_strpos($url, '://') === false && mb_strpos($url, 'www.') === 0) {
  763. $url = 'http://' . $url;
  764. }
  765. return $url;
  766. }
  767. /**
  768. * Checks if a url is valid
  769. *
  770. * @param string url
  771. * @return bool Success
  772. */
  773. protected function _validUrl($url) {
  774. $headers = Utility::getHeaderFromUrl($url);
  775. if ($headers === false) {
  776. return false;
  777. }
  778. $headers = implode("\n", $headers);
  779. $protocol = mb_strpos($url, 'https://') === 0 ? 'HTTP' : 'HTTP';
  780. if (!preg_match('#^' . $protocol . '/.*?\s+[(200|301|302)]+\s#i', $headers)) {
  781. return false;
  782. }
  783. if (preg_match('#^' . $protocol . '/.*?\s+[(404|999)]+\s#i', $headers)) {
  784. return false;
  785. }
  786. return true;
  787. }
  788. /**
  789. * Validation of DateTime Fields (both Date and Time together)
  790. *
  791. * @param options
  792. * - dateFormat (defaults to 'ymd')
  793. * - allowEmpty
  794. * - after/before (fieldName to validate against)
  795. * - min/max (defaults to >= 1 - at least 1 second apart)
  796. * @return bool Success
  797. */
  798. public function validateDateTime($data, $options = []) {
  799. $format = !empty($options['dateFormat']) ? $options['dateFormat'] : 'ymd';
  800. if (is_array($data)) {
  801. $value = array_shift($data);
  802. } else {
  803. $value = $data;
  804. }
  805. $dateTime = explode(' ', trim($value), 2);
  806. $date = $dateTime[0];
  807. $time = (!empty($dateTime[1]) ? $dateTime[1] : '');
  808. if (!empty($options['allowEmpty']) && (empty($date) && empty($time) || $date == DEFAULT_DATE && $time == DEFAULT_TIME || $date == DEFAULT_DATE && empty($time))) {
  809. return true;
  810. }
  811. /*
  812. if ($this->validateDate($date, $options) && $this->validateTime($time, $options)) {
  813. return true;
  814. }
  815. */
  816. if (Validation::date($date, $format) && Validation::time($time)) {
  817. // after/before?
  818. $seconds = isset($options['min']) ? $options['min'] : 1;
  819. if (!empty($options['after']) && isset($this->data[$this->alias][$options['after']])) {
  820. if (strtotime($this->data[$this->alias][$options['after']]) > strtotime($value) - $seconds) {
  821. return false;
  822. }
  823. }
  824. if (!empty($options['before']) && isset($this->data[$this->alias][$options['before']])) {
  825. if (strtotime($this->data[$this->alias][$options['before']]) < strtotime($value) + $seconds) {
  826. return false;
  827. }
  828. }
  829. return true;
  830. }
  831. return false;
  832. }
  833. /**
  834. * Validation of Date fields (as the core one is buggy!!!)
  835. *
  836. * @param options
  837. * - dateFormat (defaults to 'ymd')
  838. * - allowEmpty
  839. * - after/before (fieldName to validate against)
  840. * - min (defaults to 0 - equal is OK too)
  841. * @return bool Success
  842. */
  843. public function validateDate($data, $options = []) {
  844. $format = !empty($options['format']) ? $options['format'] : 'ymd';
  845. if (is_array($data)) {
  846. $value = array_shift($data);
  847. } else {
  848. $value = $data;
  849. }
  850. $dateTime = explode(' ', trim($value), 2);
  851. $date = $dateTime[0];
  852. if (!empty($options['allowEmpty']) && (empty($date) || $date == DEFAULT_DATE)) {
  853. return true;
  854. }
  855. if (Validation::date($date, $format)) {
  856. // after/before?
  857. $days = !empty($options['min']) ? $options['min'] : 0;
  858. if (!empty($options['after']) && isset($this->data[$this->alias][$options['after']])) {
  859. if ($this->data[$this->alias][$options['after']] > date(FORMAT_DB_DATE, strtotime($date) - $days * DAY)) {
  860. return false;
  861. }
  862. }
  863. if (!empty($options['before']) && isset($this->data[$this->alias][$options['before']])) {
  864. if ($this->data[$this->alias][$options['before']] < date(FORMAT_DB_DATE, strtotime($date) + $days * DAY)) {
  865. return false;
  866. }
  867. }
  868. return true;
  869. }
  870. return false;
  871. }
  872. /**
  873. * Validation of Time fields
  874. *
  875. * @param array $options
  876. * - timeFormat (defaults to 'hms')
  877. * - allowEmpty
  878. * - after/before (fieldName to validate against)
  879. * - min/max (defaults to >= 1 - at least 1 minute apart)
  880. * @return bool Success
  881. */
  882. public function validateTime($data, $options = []) {
  883. if (is_array($data)) {
  884. $value = array_shift($data);
  885. } else {
  886. $value = $data;
  887. }
  888. $dateTime = explode(' ', trim($value), 2);
  889. $value = array_pop($dateTime);
  890. if (Validation::time($value)) {
  891. // after/before?
  892. if (!empty($options['after']) && isset($this->data[$this->alias][$options['after']])) {
  893. if ($this->data[$this->alias][$options['after']] >= $value) {
  894. return false;
  895. }
  896. }
  897. if (!empty($options['before']) && isset($this->data[$this->alias][$options['before']])) {
  898. if ($this->data[$this->alias][$options['before']] <= $value) {
  899. return false;
  900. }
  901. }
  902. return true;
  903. }
  904. return false;
  905. }
  906. /**
  907. * Validation of Date Fields (>= minDate && <= maxDate)
  908. *
  909. * @param options
  910. * - min/max (TODO!!)
  911. */
  912. public function validateDateRange($data, $options = []) {
  913. }
  914. /**
  915. * Validation of Time Fields (>= minTime && <= maxTime)
  916. *
  917. * @param options
  918. * - min/max (TODO!!)
  919. */
  920. public function validateTimeRange($data, $options = []) {
  921. }
  922. /**
  923. * Model validation rule for email addresses
  924. *
  925. * @return bool Success
  926. */
  927. public function validateUndisposable($data, $proceed = false) {
  928. $email = array_shift($data);
  929. if (empty($email)) {
  930. return true;
  931. }
  932. return $this->isUndisposableEmail($email, false, $proceed);
  933. }
  934. /**
  935. * NOW: can be set to work offline only (if server is down etc)
  936. * Checks if a email is not from a garbage hoster
  937. *
  938. * @param string email (necessary)
  939. * @return bool true if valid, else false
  940. */
  941. public function isUndisposableEmail($email, $onlineMode = false, $proceed = false) {
  942. if (!isset($this->UndisposableEmail)) {
  943. App::import('Vendor', 'ToolsExtra.undisposable/undisposable');
  944. if (!class_exists('UndisposableEmail')) {
  945. return true;
  946. }
  947. $this->UndisposableEmail = new UndisposableEmail();
  948. }
  949. if (!$onlineMode) {
  950. // crashed with white screen of death otherwise... (if foreign page is 404)
  951. $this->UndisposableEmail->useOnlineList(false);
  952. }
  953. if (!Validation::email($email)) {
  954. return false;
  955. }
  956. if ($this->UndisposableEmail->isUndisposableEmail($email) === false) {
  957. // trigger log
  958. $this->log('Disposable Email detected: ' . h($email) . ' (IP ' . env('REMOTE_ADDR') . ')', 'undisposable');
  959. if ($proceed === true) {
  960. return true;
  961. }
  962. return false;
  963. }
  964. return true;
  965. }
  966. /**
  967. * Is blocked email?
  968. * //TODO: move outside of MyModel?
  969. *
  970. * @return bool ifNotBlacklisted
  971. */
  972. public function validateNotBlocked($params) {
  973. $email = array_shift($params);
  974. if (!isset($this->Blacklist)) {
  975. $this->Blacklist = ClassRegistry::init('Tools.Blacklist');
  976. }
  977. if ($this->Blacklist->isBlacklisted(Blacklist::TYPE_EMAIL, $email)) {
  978. return false;
  979. }
  980. return true;
  981. }
  982. /**
  983. * Set + guaranteeFields!
  984. * Extends the core set function (only using data!!!)
  985. *
  986. * @param mixed $data
  987. * @param mixed $data2 (optional)
  988. * @param array $requiredFields Required fields
  989. * @param array $fieldList Whitelist / Allowed fields
  990. * @return array
  991. */
  992. public function set($data, $data2 = null, $requiredFields = [], $fieldList = []) {
  993. if (!empty($requiredFields)) {
  994. $data = $this->guaranteeFields($requiredFields, $data);
  995. }
  996. if (!empty($fieldList)) {
  997. $data = $this->whitelist($fieldList, $data);
  998. }
  999. return parent::set($data, $data2);
  1000. }
  1001. /**
  1002. * @param array $fieldList
  1003. * @param array $data (optional)
  1004. * @return array
  1005. */
  1006. public function whitelist(array $fieldList, $data = null) {
  1007. $model = $this->alias;
  1008. if ($data === null) {
  1009. $data =& $this->data;
  1010. }
  1011. if (empty($data[$model])) {
  1012. return [];
  1013. }
  1014. foreach ($data[$model] as $key => $val) {
  1015. if (!in_array($key, $fieldList)) {
  1016. unset($data[$model][$key]);
  1017. }
  1018. }
  1019. return $data;
  1020. }
  1021. /**
  1022. * Instead of whitelisting this will remove all blacklisted keys.
  1023. *
  1024. * @param array $blacklist
  1025. * - array: fields to blacklist
  1026. * - boolean TRUE: removes all foreign_keys (_id)
  1027. * note: one-dimensional
  1028. * @return array
  1029. */
  1030. public function blacklist($blacklist, $data = null) {
  1031. $model = $this->alias;
  1032. if ($data === null) {
  1033. $data =& $this->data;
  1034. }
  1035. if (empty($data[$model])) {
  1036. return [];
  1037. }
  1038. if ($blacklist === true) {
  1039. foreach ($data[$model] as $key => $value) {
  1040. if (substr($key, -3, 3) === '_id') {
  1041. unset($data[$model][$key]);
  1042. }
  1043. }
  1044. return;
  1045. }
  1046. foreach ($blacklist as $key) {
  1047. if (isset($data[$model][$key])) {
  1048. unset($data[$model][$key]);
  1049. }
  1050. }
  1051. return $data;
  1052. }
  1053. /**
  1054. * Generate a whitelist, based on the current schema and a passed blacklist.
  1055. *
  1056. * @param array $blacklist
  1057. * @return array
  1058. */
  1059. public function generateWhitelistFromBlacklist(array $blacklist) {
  1060. return array_diff(array_keys($this->schema()), $blacklist);
  1061. }
  1062. /**
  1063. * Make sure required fields exists - in order to properly validate them
  1064. *
  1065. * @param array: field1, field2 - or field1, Model2.field1 etc
  1066. * @param array: data (optional, otherwise the array with the required fields will be returned)
  1067. * @return array
  1068. */
  1069. public function guaranteeFields($requiredFields, $data = null) {
  1070. $guaranteedFields = [];
  1071. foreach ($requiredFields as $column) {
  1072. if (strpos($column, '.') !== false) {
  1073. list($model, $column) = explode('.', $column, 2);
  1074. } else {
  1075. $model = $this->alias;
  1076. }
  1077. $guaranteedFields[$model][$column] = ''; # now field exists in any case!
  1078. }
  1079. if ($data === null) {
  1080. return $guaranteedFields;
  1081. }
  1082. if (!empty($guaranteedFields)) {
  1083. $data = Hash::merge($guaranteedFields, $data);
  1084. }
  1085. return $data;
  1086. }
  1087. /**
  1088. * Make certain fields a requirement for the form to validate
  1089. * (they must only be present - can still be empty, though!)
  1090. *
  1091. * @param array $fieldList
  1092. * @param bool $allowEmpty (or NULL to not touch already set elements)
  1093. * @return void
  1094. */
  1095. public function requireFields($requiredFields, $allowEmpty = null) {
  1096. if ($allowEmpty === null) {
  1097. $setAllowEmpty = true;
  1098. } else {
  1099. $setAllowEmpty = $allowEmpty;
  1100. }
  1101. foreach ($requiredFields as $column) {
  1102. if (strpos($column, '.') !== false) {
  1103. list($model, $column) = explode('.', $column, 2);
  1104. } else {
  1105. $model = $this->alias;
  1106. }
  1107. if ($model !== $this->alias) {
  1108. continue;
  1109. }
  1110. if (empty($this->validate[$column])) {
  1111. $this->validate[$column]['notBlank'] = ['rule' => 'notBlank', 'required' => true, 'allowEmpty' => $setAllowEmpty, 'message' => 'valErrMandatoryField'];
  1112. } else {
  1113. $keys = array_keys($this->validate[$column]);
  1114. if (!in_array('rule', $keys)) {
  1115. $key = array_shift($keys);
  1116. $this->validate[$column][$key]['required'] = true;
  1117. if (!isset($this->validate[$column][$key]['allowEmpty'])) {
  1118. $this->validate[$column][$key]['allowEmpty'] = $setAllowEmpty;
  1119. }
  1120. } else {
  1121. $keys['required'] = true;
  1122. if (!isset($keys['allowEmpty'])) {
  1123. $keys['allowEmpty'] = $setAllowEmpty;
  1124. }
  1125. $this->validate[$column] = $keys;
  1126. }
  1127. }
  1128. }
  1129. }
  1130. /**
  1131. * Shortcut method to find a specific entry via primary key.
  1132. * Wraps ShimModel::get() for an exception free response.
  1133. *
  1134. * $record = $this->Model->get($id);
  1135. *
  1136. * @param mixed $id
  1137. * @param array $options Options for find().
  1138. * @return array
  1139. */
  1140. public function record($id, array $options = []) {
  1141. try {
  1142. return $this->get($id, $options);
  1143. } catch (RecordNotFoundException $e) {
  1144. }
  1145. return [];
  1146. }
  1147. /**
  1148. * Get all related entries that have been used so far
  1149. *
  1150. * @param string $modelName The related model
  1151. * @param string $groupField Field to group by
  1152. * @param string $type Find type
  1153. * @param array $options
  1154. * @return array
  1155. */
  1156. public function getRelatedInUse($modelName, $groupField = null, $type = 'all', $options = []) {
  1157. if ($groupField === null) {
  1158. $groupField = $this->belongsTo[$modelName]['foreignKey'];
  1159. }
  1160. $defaults = [
  1161. 'contain' => [$modelName],
  1162. 'group' => $groupField,
  1163. 'order' => $this->$modelName->order ? $this->$modelName->order : [$modelName . '.' . $this->$modelName->displayField => 'ASC'],
  1164. ];
  1165. if ($type === 'list') {
  1166. $defaults['fields'] = [$modelName . '.' . $this->$modelName->primaryKey, $modelName . '.' . $this->$modelName->displayField];
  1167. }
  1168. $options += $defaults;
  1169. return $this->find($type, $options);
  1170. }
  1171. /**
  1172. * Get all fields that have been used so far
  1173. *
  1174. * @param string $groupField Field to group by
  1175. * @param string $type Find type
  1176. * @param array $options
  1177. * @return array
  1178. */
  1179. public function getFieldInUse($groupField, $type = 'all', $options = []) {
  1180. $defaults = [
  1181. 'group' => $groupField,
  1182. 'order' => [$this->alias . '.' . $this->displayField => 'ASC'],
  1183. ];
  1184. if ($type === 'list') {
  1185. $defaults['fields'] = [$this->alias . '.' . $this->primaryKey, $this->alias . '.' . $this->displayField];
  1186. }
  1187. $options += $defaults;
  1188. return $this->find($type, $options);
  1189. }
  1190. /**
  1191. * Update a row with certain fields (dont use "Model" as super-key)
  1192. *
  1193. * @param int $id
  1194. * @param array $data
  1195. * @param bool $validate
  1196. * @return bool|array Success
  1197. */
  1198. public function update($id, $data, $validate = false) {
  1199. $options = [
  1200. 'validate' => $validate,
  1201. 'fieldList' => array_keys($data)
  1202. ];
  1203. $data[$this->primaryKey] = $id;
  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, ['fields' => [$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. $data = [$fieldName => $record[$this->alias][$fieldName]];
  1218. $this->updateAllJoinless($data, [$this->primaryKey => $id]);
  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. * Shim wrapper for 2.6 to allow 2.7 notBlank validation rule to work already.
  1237. * This is only there to avoid the deprecation errors in 2.6 test runs.
  1238. *
  1239. * @param array $data
  1240. * @return bool
  1241. */
  1242. public function notBlank($data) {
  1243. $value = array_shift($data);
  1244. if ((float)Configure::version() < 2.7) {
  1245. return Validation::notEmpty($value);
  1246. }
  1247. return Validation::notBlank($value);
  1248. }
  1249. /**
  1250. * Shim wrapper for 2.6 to allow 2.7 notBlank validation rule to work already.
  1251. * This is only there to avoid the deprecation errors in 2.6 test runs.
  1252. *
  1253. * @param array $data
  1254. * @return bool
  1255. */
  1256. public function notEmpty($data) {
  1257. return $this->notBlank($data);
  1258. }
  1259. /**
  1260. * Recursive Dropdown Lists
  1261. * NEEDS tree behavior, NEEDS lft, rght, parent_id (!)
  1262. * //FIXME
  1263. */
  1264. public function recursiveSelect($conditions = [], $attachTree = false, $spacer = '-- ') {
  1265. if ($attachTree) {
  1266. $this->Behaviors->load('Tree');
  1267. }
  1268. $data = $this->generateTreeList($conditions, null, null, $spacer);
  1269. return $data;
  1270. }
  1271. /**
  1272. * From http://othy.wordpress.com/2006/06/03/generatenestedlist/
  1273. * NEEDS parent_id
  1274. * //TODO refactor for 1.2
  1275. *
  1276. * @deprecated use generateTreeList instead
  1277. */
  1278. public function generateNestedList($conditions = null, $indent = '--') {
  1279. $cats = $this->find('threaded', ['conditions' => $conditions, 'fields' => [
  1280. $this->alias . '.' . $this->primaryKey,
  1281. $this->alias . '.' . $this->displayField,
  1282. $this->alias . '.parent_id']]);
  1283. return $this->_generateNestedList($cats, $indent);
  1284. }
  1285. /**
  1286. * From http://othy.wordpress.com/2006/06/03/generatenestedlist/
  1287. *
  1288. * @deprecated use generateTreeList instead
  1289. */
  1290. public function _generateNestedList($cats, $indent = '--', $level = 0) {
  1291. static $list = [];
  1292. $c = count($cats);
  1293. for ($i = 0; $i < $c; $i++) {
  1294. $list[$cats[$i][$this->alias][$this->primaryKey]] = str_repeat($indent, $level) . $cats[$i][$this->alias][$this->displayField];
  1295. if (!empty($cats[$i]['children'])) {
  1296. $this->_generateNestedList($cats[$i]['children'], $indent, $level + 1);
  1297. }
  1298. }
  1299. return $list;
  1300. }
  1301. }