MyModel.php 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407
  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. //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', 'undisposable/undisposable');
  944. $this->UndisposableEmail = new UndisposableEmail();
  945. }
  946. if (!$onlineMode) {
  947. // crashed with white screen of death otherwise... (if foreign page is 404)
  948. $this->UndisposableEmail->useOnlineList(false);
  949. }
  950. if (!Validation::email($email)) {
  951. return false;
  952. }
  953. if ($this->UndisposableEmail->isUndisposableEmail($email) === false) {
  954. // trigger log
  955. $this->log('Disposable Email detected: ' . h($email) . ' (IP ' . env('REMOTE_ADDR') . ')', 'undisposable');
  956. if ($proceed === true) {
  957. return true;
  958. }
  959. return false;
  960. }
  961. return true;
  962. }
  963. /**
  964. * Is blocked email?
  965. * //TODO: move outside of MyModel?
  966. *
  967. * @return bool ifNotBlacklisted
  968. */
  969. public function validateNotBlocked($params) {
  970. $email = array_shift($params);
  971. if (!isset($this->Blacklist)) {
  972. $this->Blacklist = ClassRegistry::init('Tools.Blacklist');
  973. }
  974. if ($this->Blacklist->isBlacklisted(Blacklist::TYPE_EMAIL, $email)) {
  975. return false;
  976. }
  977. return true;
  978. }
  979. /**
  980. * Set + guaranteeFields!
  981. * Extends the core set function (only using data!!!)
  982. *
  983. * @param mixed $data
  984. * @param mixed $data2 (optional)
  985. * @param array $requiredFields Required fields
  986. * @param array $fieldList Whitelist / Allowed fields
  987. * @return array
  988. */
  989. public function set($data, $data2 = null, $requiredFields = [], $fieldList = []) {
  990. if (!empty($requiredFields)) {
  991. $data = $this->guaranteeFields($requiredFields, $data);
  992. }
  993. if (!empty($fieldList)) {
  994. $data = $this->whitelist($fieldList, $data);
  995. }
  996. return parent::set($data, $data2);
  997. }
  998. /**
  999. * @param array $fieldList
  1000. * @param array $data (optional)
  1001. * @return array
  1002. */
  1003. public function whitelist(array $fieldList, $data = null) {
  1004. $model = $this->alias;
  1005. if ($data === null) {
  1006. $data =& $this->data;
  1007. }
  1008. if (empty($data[$model])) {
  1009. return [];
  1010. }
  1011. foreach ($data[$model] as $key => $val) {
  1012. if (!in_array($key, $fieldList)) {
  1013. unset($data[$model][$key]);
  1014. }
  1015. }
  1016. return $data;
  1017. }
  1018. /**
  1019. * Instead of whitelisting this will remove all blacklisted keys.
  1020. *
  1021. * @param array $blacklist
  1022. * - array: fields to blacklist
  1023. * - boolean TRUE: removes all foreign_keys (_id)
  1024. * note: one-dimensional
  1025. * @return array
  1026. */
  1027. public function blacklist($blacklist, $data = null) {
  1028. $model = $this->alias;
  1029. if ($data === null) {
  1030. $data =& $this->data;
  1031. }
  1032. if (empty($data[$model])) {
  1033. return [];
  1034. }
  1035. if ($blacklist === true) {
  1036. foreach ($data[$model] as $key => $value) {
  1037. if (substr($key, -3, 3) === '_id') {
  1038. unset($data[$model][$key]);
  1039. }
  1040. }
  1041. return;
  1042. }
  1043. foreach ($blacklist as $key) {
  1044. if (isset($data[$model][$key])) {
  1045. unset($data[$model][$key]);
  1046. }
  1047. }
  1048. return $data;
  1049. }
  1050. /**
  1051. * Generate a whitelist, based on the current schema and a passed blacklist.
  1052. *
  1053. * @param array $blacklist
  1054. * @return array
  1055. */
  1056. public function generateWhitelistFromBlacklist(array $blacklist) {
  1057. return array_diff(array_keys($this->schema()), $blacklist);
  1058. }
  1059. /**
  1060. * Make sure required fields exists - in order to properly validate them
  1061. *
  1062. * @param array: field1, field2 - or field1, Model2.field1 etc
  1063. * @param array: data (optional, otherwise the array with the required fields will be returned)
  1064. * @return array
  1065. */
  1066. public function guaranteeFields($requiredFields, $data = null) {
  1067. $guaranteedFields = [];
  1068. foreach ($requiredFields as $column) {
  1069. if (strpos($column, '.') !== false) {
  1070. list($model, $column) = explode('.', $column, 2);
  1071. } else {
  1072. $model = $this->alias;
  1073. }
  1074. $guaranteedFields[$model][$column] = ''; # now field exists in any case!
  1075. }
  1076. if ($data === null) {
  1077. return $guaranteedFields;
  1078. }
  1079. if (!empty($guaranteedFields)) {
  1080. $data = Hash::merge($guaranteedFields, $data);
  1081. }
  1082. return $data;
  1083. }
  1084. /**
  1085. * Make certain fields a requirement for the form to validate
  1086. * (they must only be present - can still be empty, though!)
  1087. *
  1088. * @param array $fieldList
  1089. * @param bool $allowEmpty (or NULL to not touch already set elements)
  1090. * @return void
  1091. */
  1092. public function requireFields($requiredFields, $allowEmpty = null) {
  1093. if ($allowEmpty === null) {
  1094. $setAllowEmpty = true;
  1095. } else {
  1096. $setAllowEmpty = $allowEmpty;
  1097. }
  1098. foreach ($requiredFields as $column) {
  1099. if (strpos($column, '.') !== false) {
  1100. list($model, $column) = explode('.', $column, 2);
  1101. } else {
  1102. $model = $this->alias;
  1103. }
  1104. if ($model !== $this->alias) {
  1105. continue;
  1106. }
  1107. if (empty($this->validate[$column])) {
  1108. $this->validate[$column]['notBlank'] = ['rule' => 'notBlank', 'required' => true, 'allowEmpty' => $setAllowEmpty, 'message' => 'valErrMandatoryField'];
  1109. } else {
  1110. $keys = array_keys($this->validate[$column]);
  1111. if (!in_array('rule', $keys)) {
  1112. $key = array_shift($keys);
  1113. $this->validate[$column][$key]['required'] = true;
  1114. if (!isset($this->validate[$column][$key]['allowEmpty'])) {
  1115. $this->validate[$column][$key]['allowEmpty'] = $setAllowEmpty;
  1116. }
  1117. } else {
  1118. $keys['required'] = true;
  1119. if (!isset($keys['allowEmpty'])) {
  1120. $keys['allowEmpty'] = $setAllowEmpty;
  1121. }
  1122. $this->validate[$column] = $keys;
  1123. }
  1124. }
  1125. }
  1126. }
  1127. /**
  1128. * Shortcut method to find a specific entry via primary key.
  1129. * Wraps ShimModel::get() for an exception free response.
  1130. *
  1131. * $record = $this->Model->get($id);
  1132. *
  1133. * @param mixed $id
  1134. * @param array $options Options for find().
  1135. * @return array
  1136. */
  1137. public function record($id, array $options = []) {
  1138. try {
  1139. return $this->get($id, $options);
  1140. } catch (RecordNotFoundException $e) {
  1141. }
  1142. return [];
  1143. }
  1144. /**
  1145. * Get all related entries that have been used so far
  1146. *
  1147. * @param string $modelName The related model
  1148. * @param string $groupField Field to group by
  1149. * @param string $type Find type
  1150. * @param array $options
  1151. * @return array
  1152. */
  1153. public function getRelatedInUse($modelName, $groupField = null, $type = 'all', $options = []) {
  1154. if ($groupField === null) {
  1155. $groupField = $this->belongsTo[$modelName]['foreignKey'];
  1156. }
  1157. $defaults = [
  1158. 'contain' => [$modelName],
  1159. 'group' => $groupField,
  1160. 'order' => $this->$modelName->order ? $this->$modelName->order : [$modelName . '.' . $this->$modelName->displayField => 'ASC'],
  1161. ];
  1162. if ($type === 'list') {
  1163. $defaults['fields'] = [$modelName . '.' . $this->$modelName->primaryKey, $modelName . '.' . $this->$modelName->displayField];
  1164. }
  1165. $options += $defaults;
  1166. return $this->find($type, $options);
  1167. }
  1168. /**
  1169. * Get all fields that have been used so far
  1170. *
  1171. * @param string $groupField Field to group by
  1172. * @param string $type Find type
  1173. * @param array $options
  1174. * @return array
  1175. */
  1176. public function getFieldInUse($groupField, $type = 'all', $options = []) {
  1177. $defaults = [
  1178. 'group' => $groupField,
  1179. 'order' => [$this->alias . '.' . $this->displayField => 'ASC'],
  1180. ];
  1181. if ($type === 'list') {
  1182. $defaults['fields'] = [$this->alias . '.' . $this->primaryKey, $this->alias . '.' . $this->displayField];
  1183. }
  1184. $options += $defaults;
  1185. return $this->find($type, $options);
  1186. }
  1187. /**
  1188. * Update a row with certain fields (dont use "Model" as super-key)
  1189. *
  1190. * @param int $id
  1191. * @param array $data
  1192. * @return bool|array Success
  1193. */
  1194. public function update($id, $data, $validate = false) {
  1195. $this->id = $id;
  1196. $options = [
  1197. 'validate' => $validate,
  1198. 'fieldList' => array_keys($data)
  1199. ];
  1200. return $this->save($data, $options);
  1201. }
  1202. /**
  1203. * Toggles Field (Important/Deleted/Primary etc)
  1204. *
  1205. * @param STRING fieldName
  1206. * @param int id (cleaned!)
  1207. * @return ARRAY record: [Model][values],...
  1208. */
  1209. public function toggleField($fieldName, $id) {
  1210. $record = $this->get($id, ['conditions' => [$this->primaryKey, $fieldName]]);
  1211. if (!empty($record) && !empty($fieldName) && $this->hasField($fieldName)) {
  1212. $record[$this->alias][$fieldName] = ($record[$this->alias][$fieldName] == 1 ? 0 : 1);
  1213. $this->id = $id;
  1214. $this->saveField($fieldName, $record[$this->alias][$fieldName]);
  1215. }
  1216. return $record;
  1217. }
  1218. /**
  1219. * Truncate TABLE (already validated, that table exists)
  1220. *
  1221. * @param string table [default:FALSE = current model table]
  1222. * @return bool Success
  1223. */
  1224. public function truncate($table = null) {
  1225. if (empty($table)) {
  1226. $table = $this->table;
  1227. }
  1228. $db = ConnectionManager::getDataSource($this->useDbConfig);
  1229. return $db->truncate($table);
  1230. }
  1231. /**
  1232. * Shim wrapper for 2.6 to allow 2.7 notBlank validation rule to work already.
  1233. * This is only there to avoid the deprecation errors in 2.6 test runs.
  1234. *
  1235. * @param array $data
  1236. * @return bool
  1237. */
  1238. public function notBlank($data) {
  1239. $value = array_shift($data);
  1240. if ((float)Configure::version() < 2.7) {
  1241. return Validation::notEmpty($value);
  1242. }
  1243. return Validation::notBlank($value);
  1244. }
  1245. /**
  1246. * Shim wrapper for 2.6 to allow 2.7 notBlank validation rule to work already.
  1247. * This is only there to avoid the deprecation errors in 2.6 test runs.
  1248. *
  1249. * @param array $data
  1250. * @return bool
  1251. */
  1252. public function notEmpty($data) {
  1253. return $this->notBlank($data);
  1254. }
  1255. /**
  1256. * Recursive Dropdown Lists
  1257. * NEEDS tree behavior, NEEDS lft, rght, parent_id (!)
  1258. * //FIXME
  1259. */
  1260. public function recursiveSelect($conditions = [], $attachTree = false, $spacer = '-- ') {
  1261. if ($attachTree) {
  1262. $this->Behaviors->load('Tree');
  1263. }
  1264. $data = $this->generateTreeList($conditions, null, null, $spacer);
  1265. return $data;
  1266. }
  1267. /**
  1268. * From http://othy.wordpress.com/2006/06/03/generatenestedlist/
  1269. * NEEDS parent_id
  1270. * //TODO refactor for 1.2
  1271. *
  1272. * @deprecated use generateTreeList instead
  1273. */
  1274. public function generateNestedList($conditions = null, $indent = '--') {
  1275. $cats = $this->find('threaded', ['conditions' => $conditions, 'fields' => [
  1276. $this->alias . '.' . $this->primaryKey,
  1277. $this->alias . '.' . $this->displayField,
  1278. $this->alias . '.parent_id']]);
  1279. return $this->_generateNestedList($cats, $indent);
  1280. }
  1281. /**
  1282. * From http://othy.wordpress.com/2006/06/03/generatenestedlist/
  1283. *
  1284. * @deprecated use generateTreeList instead
  1285. */
  1286. public function _generateNestedList($cats, $indent = '--', $level = 0) {
  1287. static $list = [];
  1288. $c = count($cats);
  1289. for ($i = 0; $i < $c; $i++) {
  1290. $list[$cats[$i][$this->alias][$this->primaryKey]] = str_repeat($indent, $level) . $cats[$i][$this->alias][$this->displayField];
  1291. if (!empty($cats[$i]['children'])) {
  1292. $this->_generateNestedList($cats[$i]['children'], $indent, $level + 1);
  1293. }
  1294. }
  1295. return $list;
  1296. }
  1297. }