MyModel.php 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408
  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->field($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. $this->id = $id;
  185. return $this->save($data, 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. $this->recursive = -1;
  431. //setup formating
  432. $format = '';
  433. if (!isset($options['format'])) {
  434. for ($i = 0; $i < (count($options['fields']) - 1); $i++) {
  435. $format .= '%s ';
  436. }
  437. $format = substr($format, 0, -1);
  438. } else {
  439. $format = $options['format'];
  440. }
  441. //get data
  442. $list = parent::find('all', $options);
  443. // remove model alias from strings to only get field names
  444. $tmpPath2[] = $format;
  445. for ($i = 1; $i <= (count($options['fields']) - 1); $i++) {
  446. $field[$i] = str_replace($this->alias . '.', '', $options['fields'][$i]);
  447. $tmpPath2[] = '{n}.' . $this->alias . '.' . $field[$i];
  448. }
  449. //do the magic?? read the code...
  450. $res = Hash::combine($list, '{n}.' . $this->alias . '.' . $this->primaryKey, $tmpPath2);
  451. break;
  452. default:
  453. $res = parent::find($type, $options);
  454. }
  455. if (!empty($this->useCache)) {
  456. Cache::write($this->cacheName, $res, $this->cacheConfig);
  457. if (Configure::read('debug') > 0) {
  458. $this->log('WRITE (' . $this->cacheConfig . '): ' . $this->cacheName, 'cache');
  459. }
  460. }
  461. } else {
  462. if (Configure::read('debug') > 0) {
  463. $this->log('READ (' . $this->cacheConfig . '): ' . $this->cacheName, 'cache');
  464. }
  465. }
  466. return $res;
  467. }
  468. /**
  469. * Core-fix for multiple sort orders
  470. *
  471. * @param addiotional 'scope'=>array(field,order) - value is retrieved by (submitted) primary key
  472. * @return mixed
  473. * TODO: fix it
  474. */
  475. protected function _findNeighbors($state, $query, $results = []) {
  476. return parent::_findNeighbors($state, $query, $results);
  477. if (isset($query['scope'])) {
  478. //TODO
  479. }
  480. return parent::find($type, $options);
  481. }
  482. /**
  483. * @param mixed $id: id only, or request array
  484. * @param array $options
  485. * - filter: open/closed/none
  486. * - field (sortField, if not id)
  487. * - reverse: sortDirection (0=normalAsc/1=reverseDesc)
  488. * - displayField: ($this->displayField, if empty)
  489. * @param array $qryOptions
  490. * - recursive (defaults to -1)
  491. * TODO: try to use core function, TRY TO ALLOW MULTIPLE SORT FIELDS
  492. * @return array
  493. */
  494. public function neighbors($id = null, $options = [], $qryOptions = []) {
  495. $sortField = (!empty($options['field']) ? $options['field'] : 'created');
  496. $normalDirection = (!empty($options['reverse']) ? false : true);
  497. $sortDirWord = $normalDirection ? ['ASC', 'DESC'] : ['DESC', 'ASC'];
  498. $sortDirSymb = $normalDirection ? ['>=', '<='] : ['<=', '>='];
  499. $displayField = (!empty($options['displayField']) ? $options['displayField'] : $this->displayField);
  500. if (is_array($id)) {
  501. $data = $id;
  502. $id = $data[$this->alias][$this->primaryKey];
  503. } elseif ($id === null) {
  504. $id = $this->id;
  505. }
  506. if (!empty($id)) {
  507. $data = $this->find('first', ['conditions' => [$this->primaryKey => $id], 'contain' => []]);
  508. }
  509. if (empty($id) || empty($data) || empty($data[$this->alias][$sortField])) {
  510. return [];
  511. } else {
  512. $field = $data[$this->alias][$sortField];
  513. }
  514. $findOptions = ['recursive' => -1];
  515. if (isset($qryOptions['recursive'])) {
  516. $findOptions['recursive'] = $qryOptions['recursive'];
  517. }
  518. if (isset($qryOptions['contain'])) {
  519. $findOptions['contain'] = $qryOptions['contain'];
  520. }
  521. $findOptions['fields'] = [$this->alias . '.' . $this->primaryKey, $this->alias . '.' . $displayField];
  522. $findOptions['conditions'][$this->alias . '.' . $this->primaryKey . ' !='] = $id;
  523. // //TODO: take out
  524. if (!empty($options['filter']) && $options['filter'] == REQUEST_STATUS_FILTER_OPEN) {
  525. $findOptions['conditions'][$this->alias . '.status <'] = REQUEST_STATUS_DECLINED;
  526. } elseif (!empty($options['filter']) && $options['filter'] == REQUEST_STATUS_FILTER_CLOSED) {
  527. $findOptions['conditions'][$this->alias . '.status >='] = REQUEST_STATUS_DECLINED;
  528. }
  529. $return = [];
  530. if (!empty($qryOptions['conditions'])) {
  531. $findOptions['conditions'] = Hash::merge($findOptions['conditions'], $qryOptions['conditions']);
  532. }
  533. $options = $findOptions;
  534. $options['conditions'] = Hash::merge($options['conditions'], [$this->alias . '.' . $sortField . ' ' . $sortDirSymb[1] => $field]);
  535. $options['order'] = [$this->alias . '.' . $sortField . '' => $sortDirWord[1]];
  536. $this->id = $id;
  537. $return['prev'] = $this->find('first', $options);
  538. $options = $findOptions;
  539. $options['conditions'] = Hash::merge($options['conditions'], [$this->alias . '.' . $sortField . ' ' . $sortDirSymb[0] => $field]);
  540. $options['order'] = [$this->alias . '.' . $sortField . '' => $sortDirWord[0]]; // ??? why 0 instead of 1
  541. $this->id = $id;
  542. $return['next'] = $this->find('first', $options);
  543. return $return;
  544. }
  545. /**
  546. * Validates a primary or foreign key depending on the current schema data for this field
  547. * recognizes uuid (char36) and aiid (int10 unsigned) - not yet mixed (varchar36)
  548. * more useful than using numeric or notEmpty which are type specific
  549. *
  550. * @param array $data
  551. * @param array $options
  552. * - allowEmpty
  553. * @return bool Success
  554. */
  555. public function validateKey($data = [], $options = []) {
  556. $keys = array_keys($data);
  557. $key = array_shift($keys);
  558. $value = array_shift($data);
  559. $schema = $this->schema($key);
  560. if (!$schema) {
  561. return true;
  562. }
  563. $defaults = [
  564. 'allowEmpty' => false,
  565. ];
  566. $options += $defaults;
  567. if ($schema['type'] !== 'integer') {
  568. if ($options['allowEmpty'] && $value === '') {
  569. return true;
  570. }
  571. return Validation::uuid($value);
  572. }
  573. if ($options['allowEmpty'] && $value === 0) {
  574. return true;
  575. }
  576. return is_numeric($value) && (int)$value == $value && $value > 0;
  577. }
  578. /**
  579. * Checks if the passed enum value is valid
  580. *
  581. * @return bool Success
  582. */
  583. public function validateEnum(array $data, $enum = null, $additionalKeys = []) {
  584. $keys = array_keys($data);
  585. $valueKey = array_shift($keys);
  586. $value = $data[$valueKey];
  587. $keys = [];
  588. if ($enum === true) {
  589. $enum = $valueKey;
  590. }
  591. if ($enum !== null) {
  592. if (!method_exists($this, $enum)) {
  593. trigger_error('Enum method \'' . $enum . '()\' not exists', E_USER_ERROR);
  594. return false;
  595. }
  596. //TODO: make static
  597. $keys = $this->{$enum}();
  598. }
  599. $keys = array_merge($additionalKeys, array_keys($keys));
  600. if (!empty($keys) && in_array($value, $keys)) {
  601. return true;
  602. }
  603. return false;
  604. }
  605. /**
  606. * Checks if the content of 2 fields are equal
  607. * Does not check on empty fields! Return TRUE even if both are empty (secure against empty in another rule)!
  608. *
  609. * @return bool Success
  610. */
  611. public function validateIdentical($data = [], $compareWith = null, $options = []) {
  612. if (is_array($data)) {
  613. $value = array_shift($data);
  614. } else {
  615. $value = $data;
  616. }
  617. $compareValue = $this->data[$this->alias][$compareWith];
  618. $matching = ['string' => 'string', 'int' => 'integer', 'float' => 'float', 'bool' => 'boolean'];
  619. if (!empty($options['cast']) && array_key_exists($options['cast'], $matching)) {
  620. // cast values to string/int/float/bool if desired
  621. settype($compareValue, $matching[$options['cast']]);
  622. settype($value, $matching[$options['cast']]);
  623. }
  624. return ($compareValue === $value);
  625. }
  626. /**
  627. * Validate range, but in a more sane way than CORE range().
  628. * This range() validation rule is inclusive regarding the borders.
  629. *
  630. * If $lower and $upper are not set, will return true if
  631. * $check is a legal finite on this platform
  632. *
  633. * @param string $check Value to check
  634. * @param float $lower Lower limit
  635. * @param float $upper Upper limit
  636. * @return bool Success
  637. */
  638. public function validateRange($data, $lower = null, $upper = null) {
  639. foreach ($data as $key => $check) {
  640. break;
  641. }
  642. if (!is_numeric($check)) {
  643. return false;
  644. }
  645. if (isset($lower) && isset($upper)) {
  646. return ($check >= $lower && $check <= $upper);
  647. }
  648. return is_finite($check);
  649. }
  650. /**
  651. * Checks a record, if it is unique - depending on other fields in this table (transfered as array)
  652. * example in model: 'rule' => array ('validateUnique', array('belongs_to_table_id','some_id','user_id')),
  653. * if all keys (of the array transferred) match a record, return false, otherwise true
  654. *
  655. * @param array $fields Other fields to depend on
  656. * TODO: add possibity of deep nested validation (User -> Comment -> CommentCategory: UNIQUE comment_id, Comment.user_id)
  657. * @param array $options
  658. * - requireDependentFields Require all dependent fields for the validation rule to return true
  659. * @return bool Success
  660. */
  661. public function validateUnique($data, $fields = [], $options = []) {
  662. $id = (!empty($this->data[$this->alias][$this->primaryKey]) ? $this->data[$this->alias][$this->primaryKey] : 0);
  663. if (!$id && $this->id) {
  664. $id = $this->id;
  665. }
  666. foreach ($data as $key => $value) {
  667. $fieldName = $key;
  668. $fieldValue = $value;
  669. break;
  670. }
  671. $conditions = [
  672. $this->alias . '.' . $fieldName => $fieldValue,
  673. $this->alias . '.id !=' => $id];
  674. $fields = (array)$fields;
  675. if (!array_key_exists('allowEmpty', $fields)) {
  676. foreach ($fields as $dependingField) {
  677. if (isset($this->data[$this->alias][$dependingField])) { // add ONLY if some content is transfered (check on that first!)
  678. $conditions[$this->alias . '.' . $dependingField] = $this->data[$this->alias][$dependingField];
  679. } elseif (isset($this->data['Validation'][$dependingField])) { // add ONLY if some content is transfered (check on that first!
  680. $conditions[$this->alias . '.' . $dependingField] = $this->data['Validation'][$dependingField];
  681. } elseif (!empty($id)) {
  682. // manual query! (only possible on edit)
  683. $res = $this->find('first', ['fields' => [$this->alias . '.' . $dependingField], 'conditions' => [$this->alias . '.id' => $id]]);
  684. if (!empty($res)) {
  685. $conditions[$this->alias . '.' . $dependingField] = $res[$this->alias][$dependingField];
  686. }
  687. } else {
  688. if (!empty($options['requireDependentFields'])) {
  689. trigger_error('Required field ' . $dependingField . ' for validateUnique validation not present');
  690. return false;
  691. }
  692. return true;
  693. }
  694. }
  695. }
  696. if (count($conditions) > 2 && !isset($options['contain']) && !isset($options['recursive'])) {
  697. $options['recursive'] = 0;
  698. }
  699. $options = ['fields' => [$this->alias . '.' . $this->primaryKey], 'conditions' => $conditions] + $options;
  700. $res = $this->find('count', $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 (!Validation::email($email)) {
  952. return false;
  953. }
  954. if ($this->UndisposableEmail->isUndisposableEmail($email) === false) {
  955. // trigger log
  956. $this->log('Disposable Email detected: ' . h($email) . ' (IP ' . env('REMOTE_ADDR') . ')', 'undisposable');
  957. if ($proceed === true) {
  958. return true;
  959. }
  960. return false;
  961. }
  962. return true;
  963. }
  964. /**
  965. * Is blocked email?
  966. * //TODO: move outside of MyModel?
  967. *
  968. * @return bool ifNotBlacklisted
  969. */
  970. public function validateNotBlocked($params) {
  971. $email = array_shift($params);
  972. if (!isset($this->Blacklist)) {
  973. $this->Blacklist = ClassRegistry::init('Tools.Blacklist');
  974. }
  975. if ($this->Blacklist->isBlacklisted(Blacklist::TYPE_EMAIL, $email)) {
  976. return false;
  977. }
  978. return true;
  979. }
  980. /**
  981. * Set + guaranteeFields!
  982. * Extends the core set function (only using data!!!)
  983. *
  984. * @param mixed $data
  985. * @param mixed $data2 (optional)
  986. * @param array $requiredFields Required fields
  987. * @param array $fieldList Whitelist / Allowed fields
  988. * @return array
  989. */
  990. public function set($data, $data2 = null, $requiredFields = [], $fieldList = []) {
  991. if (!empty($requiredFields)) {
  992. $data = $this->guaranteeFields($requiredFields, $data);
  993. }
  994. if (!empty($fieldList)) {
  995. $data = $this->whitelist($fieldList, $data);
  996. }
  997. return parent::set($data, $data2);
  998. }
  999. /**
  1000. * @param array $fieldList
  1001. * @param array $data (optional)
  1002. * @return array
  1003. */
  1004. public function whitelist(array $fieldList, $data = null) {
  1005. $model = $this->alias;
  1006. if ($data === null) {
  1007. $data =& $this->data;
  1008. }
  1009. if (empty($data[$model])) {
  1010. return [];
  1011. }
  1012. foreach ($data[$model] as $key => $val) {
  1013. if (!in_array($key, $fieldList)) {
  1014. unset($data[$model][$key]);
  1015. }
  1016. }
  1017. return $data;
  1018. }
  1019. /**
  1020. * Instead of whitelisting this will remove all blacklisted keys.
  1021. *
  1022. * @param array $blacklist
  1023. * - array: fields to blacklist
  1024. * - boolean TRUE: removes all foreign_keys (_id)
  1025. * note: one-dimensional
  1026. * @return array
  1027. */
  1028. public function blacklist($blacklist, $data = null) {
  1029. $model = $this->alias;
  1030. if ($data === null) {
  1031. $data =& $this->data;
  1032. }
  1033. if (empty($data[$model])) {
  1034. return [];
  1035. }
  1036. if ($blacklist === true) {
  1037. foreach ($data[$model] as $key => $value) {
  1038. if (substr($key, -3, 3) === '_id') {
  1039. unset($data[$model][$key]);
  1040. }
  1041. }
  1042. return;
  1043. }
  1044. foreach ($blacklist as $key) {
  1045. if (isset($data[$model][$key])) {
  1046. unset($data[$model][$key]);
  1047. }
  1048. }
  1049. return $data;
  1050. }
  1051. /**
  1052. * Generate a whitelist, based on the current schema and a passed blacklist.
  1053. *
  1054. * @param array $blacklist
  1055. * @return array
  1056. */
  1057. public function generateWhitelistFromBlacklist(array $blacklist) {
  1058. return array_diff(array_keys($this->schema()), $blacklist);
  1059. }
  1060. /**
  1061. * Make sure required fields exists - in order to properly validate them
  1062. *
  1063. * @param array: field1, field2 - or field1, Model2.field1 etc
  1064. * @param array: data (optional, otherwise the array with the required fields will be returned)
  1065. * @return array
  1066. */
  1067. public function guaranteeFields($requiredFields, $data = null) {
  1068. $guaranteedFields = [];
  1069. foreach ($requiredFields as $column) {
  1070. if (strpos($column, '.') !== false) {
  1071. list($model, $column) = explode('.', $column, 2);
  1072. } else {
  1073. $model = $this->alias;
  1074. }
  1075. $guaranteedFields[$model][$column] = ''; # now field exists in any case!
  1076. }
  1077. if ($data === null) {
  1078. return $guaranteedFields;
  1079. }
  1080. if (!empty($guaranteedFields)) {
  1081. $data = Hash::merge($guaranteedFields, $data);
  1082. }
  1083. return $data;
  1084. }
  1085. /**
  1086. * Make certain fields a requirement for the form to validate
  1087. * (they must only be present - can still be empty, though!)
  1088. *
  1089. * @param array $fieldList
  1090. * @param bool $allowEmpty (or NULL to not touch already set elements)
  1091. * @return void
  1092. */
  1093. public function requireFields($requiredFields, $allowEmpty = null) {
  1094. if ($allowEmpty === null) {
  1095. $setAllowEmpty = true;
  1096. } else {
  1097. $setAllowEmpty = $allowEmpty;
  1098. }
  1099. foreach ($requiredFields as $column) {
  1100. if (strpos($column, '.') !== false) {
  1101. list($model, $column) = explode('.', $column, 2);
  1102. } else {
  1103. $model = $this->alias;
  1104. }
  1105. if ($model !== $this->alias) {
  1106. continue;
  1107. }
  1108. if (empty($this->validate[$column])) {
  1109. $this->validate[$column]['notBlank'] = ['rule' => 'notBlank', 'required' => true, 'allowEmpty' => $setAllowEmpty, 'message' => 'valErrMandatoryField'];
  1110. } else {
  1111. $keys = array_keys($this->validate[$column]);
  1112. if (!in_array('rule', $keys)) {
  1113. $key = array_shift($keys);
  1114. $this->validate[$column][$key]['required'] = true;
  1115. if (!isset($this->validate[$column][$key]['allowEmpty'])) {
  1116. $this->validate[$column][$key]['allowEmpty'] = $setAllowEmpty;
  1117. }
  1118. } else {
  1119. $keys['required'] = true;
  1120. if (!isset($keys['allowEmpty'])) {
  1121. $keys['allowEmpty'] = $setAllowEmpty;
  1122. }
  1123. $this->validate[$column] = $keys;
  1124. }
  1125. }
  1126. }
  1127. }
  1128. /**
  1129. * Shortcut method to find a specific entry via primary key.
  1130. * Wraps ShimModel::get() for an exception free response.
  1131. *
  1132. * $record = $this->Model->get($id);
  1133. *
  1134. * @param mixed $id
  1135. * @param array $options Options for find().
  1136. * @return array
  1137. */
  1138. public function record($id, array $options = []) {
  1139. try {
  1140. return $this->get($id, $options);
  1141. } catch (RecordNotFoundException $e) {
  1142. }
  1143. return [];
  1144. }
  1145. /**
  1146. * Get all related entries that have been used so far
  1147. *
  1148. * @param string $modelName The related model
  1149. * @param string $groupField Field to group by
  1150. * @param string $type Find type
  1151. * @param array $options
  1152. * @return array
  1153. */
  1154. public function getRelatedInUse($modelName, $groupField = null, $type = 'all', $options = []) {
  1155. if ($groupField === null) {
  1156. $groupField = $this->belongsTo[$modelName]['foreignKey'];
  1157. }
  1158. $defaults = [
  1159. 'contain' => [$modelName],
  1160. 'group' => $groupField,
  1161. 'order' => $this->$modelName->order ? $this->$modelName->order : [$modelName . '.' . $this->$modelName->displayField => 'ASC'],
  1162. ];
  1163. if ($type === 'list') {
  1164. $defaults['fields'] = [$modelName . '.' . $this->$modelName->primaryKey, $modelName . '.' . $this->$modelName->displayField];
  1165. }
  1166. $options += $defaults;
  1167. return $this->find($type, $options);
  1168. }
  1169. /**
  1170. * Get all fields that have been used so far
  1171. *
  1172. * @param string $groupField Field to group by
  1173. * @param string $type Find type
  1174. * @param array $options
  1175. * @return array
  1176. */
  1177. public function getFieldInUse($groupField, $type = 'all', $options = []) {
  1178. $defaults = [
  1179. 'group' => $groupField,
  1180. 'order' => [$this->alias . '.' . $this->displayField => 'ASC'],
  1181. ];
  1182. if ($type === 'list') {
  1183. $defaults['fields'] = [$this->alias . '.' . $this->primaryKey, $this->alias . '.' . $this->displayField];
  1184. }
  1185. $options += $defaults;
  1186. return $this->find($type, $options);
  1187. }
  1188. /**
  1189. * Update a row with certain fields (dont use "Model" as super-key)
  1190. *
  1191. * @param int $id
  1192. * @param array $data
  1193. * @return bool|array Success
  1194. */
  1195. public function update($id, $data, $validate = false) {
  1196. $this->id = $id;
  1197. $options = [
  1198. 'validate' => $validate,
  1199. 'fieldList' => array_keys($data)
  1200. ];
  1201. return $this->save($data, $options);
  1202. }
  1203. /**
  1204. * Toggles Field (Important/Deleted/Primary etc)
  1205. *
  1206. * @param STRING fieldName
  1207. * @param int id (cleaned!)
  1208. * @return ARRAY record: [Model][values],...
  1209. */
  1210. public function toggleField($fieldName, $id) {
  1211. $record = $this->get($id, ['conditions' => [$this->primaryKey, $fieldName]]);
  1212. if (!empty($record) && !empty($fieldName) && $this->hasField($fieldName)) {
  1213. $record[$this->alias][$fieldName] = ($record[$this->alias][$fieldName] == 1 ? 0 : 1);
  1214. $this->id = $id;
  1215. $this->saveField($fieldName, $record[$this->alias][$fieldName]);
  1216. }
  1217. return $record;
  1218. }
  1219. /**
  1220. * Truncate TABLE (already validated, that table exists)
  1221. *
  1222. * @param string table [default:FALSE = current model table]
  1223. * @return bool Success
  1224. */
  1225. public function truncate($table = null) {
  1226. if (empty($table)) {
  1227. $table = $this->table;
  1228. }
  1229. $db = ConnectionManager::getDataSource($this->useDbConfig);
  1230. return $db->truncate($table);
  1231. }
  1232. /**
  1233. * Shim wrapper for 2.6 to allow 2.7 notBlank validation rule to work already.
  1234. * This is only there to avoid the deprecation errors in 2.6 test runs.
  1235. *
  1236. * @param array $data
  1237. * @return bool
  1238. */
  1239. public function notBlank($data) {
  1240. $value = array_shift($data);
  1241. if ((float)Configure::version() < 2.7) {
  1242. return Validation::notEmpty($value);
  1243. }
  1244. return Validation::notBlank($value);
  1245. }
  1246. /**
  1247. * Shim wrapper for 2.6 to allow 2.7 notBlank validation rule to work already.
  1248. * This is only there to avoid the deprecation errors in 2.6 test runs.
  1249. *
  1250. * @param array $data
  1251. * @return bool
  1252. */
  1253. public function notEmpty($data) {
  1254. return $this->notBlank($data);
  1255. }
  1256. /**
  1257. * Recursive Dropdown Lists
  1258. * NEEDS tree behavior, NEEDS lft, rght, parent_id (!)
  1259. * //FIXME
  1260. */
  1261. public function recursiveSelect($conditions = [], $attachTree = false, $spacer = '-- ') {
  1262. if ($attachTree) {
  1263. $this->Behaviors->load('Tree');
  1264. }
  1265. $data = $this->generateTreeList($conditions, null, null, $spacer);
  1266. return $data;
  1267. }
  1268. /**
  1269. * From http://othy.wordpress.com/2006/06/03/generatenestedlist/
  1270. * NEEDS parent_id
  1271. * //TODO refactor for 1.2
  1272. *
  1273. * @deprecated use generateTreeList instead
  1274. */
  1275. public function generateNestedList($conditions = null, $indent = '--') {
  1276. $cats = $this->find('threaded', ['conditions' => $conditions, 'fields' => [
  1277. $this->alias . '.' . $this->primaryKey,
  1278. $this->alias . '.' . $this->displayField,
  1279. $this->alias . '.parent_id']]);
  1280. return $this->_generateNestedList($cats, $indent);
  1281. }
  1282. /**
  1283. * From http://othy.wordpress.com/2006/06/03/generatenestedlist/
  1284. *
  1285. * @deprecated use generateTreeList instead
  1286. */
  1287. public function _generateNestedList($cats, $indent = '--', $level = 0) {
  1288. static $list = [];
  1289. $c = count($cats);
  1290. for ($i = 0; $i < $c; $i++) {
  1291. $list[$cats[$i][$this->alias][$this->primaryKey]] = str_repeat($indent, $level) . $cats[$i][$this->alias][$this->displayField];
  1292. if (!empty($cats[$i]['children'])) {
  1293. $this->_generateNestedList($cats[$i]['children'], $indent, $level + 1);
  1294. }
  1295. }
  1296. return $list;
  1297. }
  1298. }