MyModel.php 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702
  1. <?php
  2. App::uses('Model', 'Model');
  3. App::uses('Utility', 'Tools.Utility');
  4. /**
  5. * Model enhancements for Cake2
  6. *
  7. * @author Mark Scherer
  8. * @license MIT
  9. * 2012-02-27 ms
  10. */
  11. class MyModel extends Model {
  12. public $recursive = -1;
  13. public $actsAs = array('Containable');
  14. /** Specific Stuff **/
  15. public function __construct($id = false, $table = null, $ds = null) {
  16. parent::__construct($id, $table, $ds);
  17. # enable caching
  18. if (!Configure::read('Cache.disable') && Cache::config('sql') === false) {
  19. if (!file_exists(CACHE . 'sql')) {
  20. mkdir(CACHE . 'sql', CHOWN_PUBLIC);
  21. }
  22. Cache::config('sql', array(
  23. 'engine' => 'File',
  24. 'serialize' => true,
  25. 'prefix' => '',
  26. 'path' => CACHE .'sql'. DS,
  27. 'duration' => '+1 day'
  28. ));
  29. }
  30. # get a notice if there is an AppModel instances instead of real Models (in those cases usually a dev error!)
  31. if (defined('HTTP_HOST') && HTTP_HOST && !is_a($this, $this->name) && $this->displayField !== 'id' && $this->useDbConfig !== 'test' && !Configure::read('Core.disableModelInstanceNotice')) {
  32. trigger_error('AppModel instance! Expected: ' . $this->name);
  33. }
  34. }
  35. /**
  36. * Deconstructs a complex data type (array or object) into a single field value.
  37. * BUGFIXED VERSION - autodetects type and allows manual override
  38. *
  39. * @param string $field The name of the field to be deconstructed
  40. * @param array|object $data An array or object to be deconstructed into a field
  41. * @return mixed The resulting data that should be assigned to a field
  42. */
  43. public function deconstruct($field, $data, $type = null) {
  44. if (!is_array($data)) {
  45. return $data;
  46. }
  47. if ($type === null) {
  48. $type = $this->getColumnType($field);
  49. }
  50. if ($type === null) {
  51. //try to autodetect
  52. if (isset($data['day']) || isset($data['month']) || isset($data['year'])) {
  53. $type = 'date';
  54. }
  55. if (isset($data['hour']) || isset($data['min']) || isset($data['sec'])) {
  56. $type .= 'time';
  57. }
  58. }
  59. if (in_array($type, array('datetime', 'timestamp', 'date', 'time'))) {
  60. $useNewDate = (isset($data['year']) || isset($data['month']) ||
  61. isset($data['day']) || isset($data['hour']) || isset($data['minute']));
  62. $dateFields = array('Y' => 'year', 'm' => 'month', 'd' => 'day', 'H' => 'hour', 'i' => 'min', 's' => 'sec');
  63. $timeFields = array('H' => 'hour', 'i' => 'min', 's' => 'sec');
  64. $date = array();
  65. if (isset($data['meridian']) && empty($data['meridian'])) {
  66. return null;
  67. }
  68. if (
  69. isset($data['hour']) &&
  70. isset($data['meridian']) &&
  71. !empty($data['hour']) &&
  72. $data['hour'] != 12 &&
  73. 'pm' == $data['meridian']
  74. ) {
  75. $data['hour'] = $data['hour'] + 12;
  76. }
  77. if (isset($data['hour']) && isset($data['meridian']) && $data['hour'] == 12 && 'am' == $data['meridian']) {
  78. $data['hour'] = '00';
  79. }
  80. if ($type === 'time') {
  81. foreach ($timeFields as $key => $val) {
  82. if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') {
  83. $data[$val] = '00';
  84. } elseif ($data[$val] !== '') {
  85. $data[$val] = sprintf('%02d', $data[$val]);
  86. }
  87. if (!empty($data[$val])) {
  88. $date[$key] = $data[$val];
  89. } else {
  90. return null;
  91. }
  92. }
  93. }
  94. if ($type === 'datetime' || $type === 'timestamp' || $type === 'date') {
  95. foreach ($dateFields as $key => $val) {
  96. if ($val === 'hour' || $val === 'min' || $val === 'sec') {
  97. if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') {
  98. $data[$val] = '00';
  99. } else {
  100. $data[$val] = sprintf('%02d', $data[$val]);
  101. }
  102. }
  103. if (!isset($data[$val]) || isset($data[$val]) && (empty($data[$val]) || $data[$val][0] === '-')) {
  104. return null;
  105. }
  106. if (isset($data[$val]) && !empty($data[$val])) {
  107. $date[$key] = $data[$val];
  108. }
  109. }
  110. }
  111. if ($useNewDate && !empty($date)) {
  112. $format = $this->getDataSource()->columns[$type]['format'];
  113. foreach (array('m', 'd', 'H', 'i', 's') as $index) {
  114. if (isset($date[$index])) {
  115. $date[$index] = sprintf('%02d', $date[$index]);
  116. }
  117. }
  118. return str_replace(array_keys($date), array_values($date), $format);
  119. }
  120. }
  121. return $data;
  122. }
  123. /**
  124. * The main method for any enumeration, should be called statically
  125. * Now also supports reordering/filtering
  126. *
  127. * @link http://www.dereuromark.de/2010/06/24/static-enums-or-semihardcoded-attributes/
  128. * @param string $value or array $keys or NULL for complete array result
  129. * @param array $options (actual data)
  130. * @return mixed string/array
  131. * static enums
  132. * 2009-11-05 ms
  133. */
  134. public static function enum($value, $options, $default = null) {
  135. if ($value !== null && !is_array($value)) {
  136. if (array_key_exists($value, $options)) {
  137. return $options[$value];
  138. }
  139. return $default;
  140. } elseif ($value !== null) {
  141. $newOptions = array();
  142. foreach ($value as $v) {
  143. $newOptions[$v] = $options[$v];
  144. }
  145. return $newOptions;
  146. }
  147. return $options;
  148. }
  149. /**
  150. * Catch database errors before it’s too late
  151. * //TODO: testing
  152. * 2010-11-04 ms
  153. */
  154. public function onError() {
  155. $err = $this->lastError();
  156. if (!empty($err)) {
  157. $this->log($err, 'sql_error');
  158. } else {
  159. $this->log('unknown error', 'sql_error');
  160. }
  161. if (!empty($this->data)) {
  162. $data = $this->data;
  163. } elseif ($this->id) {
  164. $data = 'id ' . $this->id;
  165. } else {
  166. $data = 'no data';
  167. }
  168. $data .= ' (' . env('REDIRECT_URL') . ')';
  169. $this->log($data, 'sql_error');
  170. }
  171. /**
  172. * @return string Error message with error number
  173. * 2010-11-06 ms
  174. */
  175. public function lastError() {
  176. $db = $this->getDataSource();
  177. return $db->lastError();
  178. }
  179. /**
  180. * combine virtual fields with fields values of find()
  181. * USAGE:
  182. * $this->Model->find('all', array('fields' => $this->Model->virtualFields('full_name')));
  183. * Also adds the field to the virtualFields array of the model (for correct result)
  184. * TODO: adding of fields only temperory!
  185. * @param array $virtualFields to include
  186. * 2011-10-13 ms
  187. */
  188. public function virtualFields($fields = array()) {
  189. $res = array();
  190. foreach ((array)$fields as $field => $sql) {
  191. if (is_int($field)) {
  192. $field = $sql;
  193. $sql = null;
  194. }
  195. $plugin = $model = null;
  196. if (($pos = strrpos($field, '.')) !== false) {
  197. $model = substr($field, 0, $pos);
  198. $field = substr($field, $pos+1);
  199. if (($pos = strrpos($model, '.')) !== false) {
  200. list($plugin, $model) = pluginSplit($model);
  201. }
  202. }
  203. if (empty($model)) {
  204. $model = $this->alias;
  205. if ($sql === null) {
  206. $sql = $this->virtualFields[$field];
  207. } else {
  208. $this->virtualFields[$field] = $sql;
  209. }
  210. } else {
  211. if (!isset($this->$model)) {
  212. $fullModelName = ($plugin ? $plugin.'.' : '') . $model;
  213. $this->$model = ClassRegistry::init($fullModelName);
  214. }
  215. if ($sql === null) {
  216. $sql = $this->$model->virtualFields[$field];
  217. } else {
  218. $this->$model->virtualFields[$field] = $sql;
  219. }
  220. }
  221. $res[] = $sql.' AS '.$model.'__'.$field;
  222. }
  223. return $res;
  224. }
  225. /**
  226. * HIGHLY EXPERIMENTAL
  227. * manually escape value for updateAll() etc
  228. * 2011-06-27 ms
  229. */
  230. public function escapeValue($value) {
  231. if ($value === null || is_numeric($value)) {
  232. return $value;
  233. }
  234. if (is_bool($value)) {
  235. return (int)$value;
  236. }
  237. return "'" . $value . "'";
  238. }
  239. /**
  240. * HIGHLY EXPERIMENTAL
  241. * @see http://cakephp.lighthouseapp.com/projects/42648/tickets/1799-model-should-have-escapefield-method
  242. * 2011-07-05 ms
  243. */
  244. public function value($content) {
  245. $db = $this->getDatasource();
  246. return $db->value($content);
  247. }
  248. /**
  249. * TODO: move to behavior (Incremental)
  250. * @param mixed id (single string)
  251. * @param options:
  252. * - step (defaults to 1)
  253. * - current (if none it will get it from db)
  254. * - reset (if true, it will be set to 0)
  255. * - field (defaults to 'count')
  256. * - modify (if true if will affect modified timestamp)
  257. * - timestampField (if provided it will be filled with NOW())
  258. * 2010-06-08 ms
  259. */
  260. public function up($id, $customOptions = array()) {
  261. $step = 1;
  262. if (isset($customOptions['step'])) {
  263. $step = $customOptions['step'];
  264. }
  265. $field = 'count';
  266. if (isset($customOptions['field'])) {
  267. $field = $customOptions['field'];
  268. }
  269. if (isset($customOptions['reset'])) {
  270. $currentValue = $step = 0;
  271. } elseif (!isset($customOptions['current'])) {
  272. $currentValue = $this->field($field, array($this->alias.'.id'=>$id));
  273. if ($currentValue === false) {
  274. return false;
  275. }
  276. } else {
  277. $currentValue = $customOptions['current'];
  278. }
  279. $value = (int)$currentValue + (int)$step;
  280. $data = array($field=>$value);
  281. if (empty($customOptions['modify'])) {
  282. $data['modified'] = false;
  283. }
  284. if (!empty($customOptions['timestampField'])) {
  285. $data[$customOptions['timestampField']] = date(FORMAT_DB_DATETIME);
  286. }
  287. $this->id = $id;
  288. return $this->save($data, false);
  289. }
  290. /**
  291. * return the next auto increment id from the current table
  292. * UUIDs will return false
  293. *
  294. * @return int next auto increment value or False on failure
  295. */
  296. public function getNextAutoIncrement() {
  297. $next_increment = 0;
  298. $query = "SHOW TABLE STATUS WHERE name = '" . $this->tablePrefix . $this->table . "'";
  299. $result = $this->query($query);
  300. if (!isset($result[0]['TABLES']['Auto_increment'])) {
  301. return false;
  302. }
  303. return (int)$result[0]['TABLES']['Auto_increment'];
  304. }
  305. /**
  306. * workaround for a cake bug which sets empty fields to NULL in Model::set()
  307. * we cannot use if (isset() && empty()) statements without this fix
  308. * @param array $fields (which are supposed to be present in $this->data[$this->alias])
  309. * @param bool $force (if init should be forced, otherwise only if array_key exists)
  310. * 2011-03-06 ms
  311. */
  312. public function init($fields = array(), $force = false) {
  313. foreach ($fields as $field) {
  314. if ($force || array_key_exists($field, $this->data[$this->alias])) {
  315. if (!isset($this->data[$this->alias][$field])) {
  316. $this->data[$this->alias][$field] = '';
  317. }
  318. }
  319. }
  320. }
  321. /**
  322. * Fix for non atomic queries (MyISAM etc) and saveAll to still return just the boolean result
  323. * Otherwise you would have to interate over all result values to find out if the save was successful.
  324. *
  325. * @param mixed $data
  326. * @param array $options
  327. * @return bool Success
  328. * 2012-11-10 ms
  329. */
  330. public function saveAll($data = null, $options = array()) {
  331. if (!isset($options['atomic'])) {
  332. $options['atomic'] = (bool)Configure::read('Model.atomic');
  333. }
  334. $res = parent::saveAll($data, $options);
  335. if (is_array($res)) {
  336. $res = Utility::isValidSaveAll($res);
  337. }
  338. return $res;
  339. }
  340. /**
  341. * enables HABTM-Validation
  342. * e.g. with
  343. * 'rule' => array('multiple', array('min' => 2))
  344. * 2010-01-14 ms
  345. */
  346. public function beforeValidate($options = array()) {
  347. foreach ($this->hasAndBelongsToMany as $k => $v) {
  348. if (isset($this->data[$k][$k])) {
  349. $this->data[$this->alias][$k] = $this->data[$k][$k];
  350. }
  351. }
  352. return parent::beforeValidate($options);
  353. }
  354. /**
  355. * @param params
  356. * - key: functioName or other key used
  357. * @return bool Success
  358. * 2010-12-02 ms
  359. */
  360. public function deleteCache($key) {
  361. $key = Inflector::underscore($key);
  362. if (!empty($key)) {
  363. return Cache::delete(strtolower(Inflector::underscore($this->alias)) . '__' . $key, 'sql');
  364. }
  365. return Cache::clear(false, 'sql');
  366. }
  367. /**
  368. * Generates a SQL subquery snippet to be used in your actual query.
  369. * Your subquery snippet needs to return a single value or flat array of values.
  370. *
  371. * Example:
  372. *
  373. * $this->Model->find('first', array(
  374. * 'conditions' => array('NOT' => array('some_id' => $this->Model->subquery(...)))
  375. * ))
  376. *
  377. * Note: You might have to set `autoFields` to false in order to retrieve only the fields you request:
  378. * http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html#containablebehavior-options
  379. *
  380. * @param string $type The type of the query ('count'/'all'/'first' - first only works with some mysql versions)
  381. * @param array $options The options array
  382. * @param string $alias You can use this intead of $options['alias'] if you want
  383. * @param bool $parenthesise Add parenthesis before and after
  384. * @return string $result sql snippet of the query to run
  385. * @modified Mark Scherer (cake2.x ready and improvements)
  386. * @link http://bakery.cakephp.org/articles/lucaswxp/2011/02/11/easy_and_simple_subquery_cakephp
  387. * 2011-07-05 ms
  388. */
  389. public function subquery($type, $options = array(), $alias = null, $parenthesise = true) {
  390. if ($alias === null) {
  391. $alias = 'Sub' . $this->alias . '';
  392. }
  393. $fields = array($alias . '.id');
  394. $limit = null;
  395. switch ($type) {
  396. case 'count':
  397. $fields = array('COUNT(*)');
  398. break;
  399. case 'first':
  400. $limit = 1;
  401. break;
  402. }
  403. $dbo = $this->getDataSource();
  404. $default = array(
  405. 'fields' => $fields,
  406. 'table' => $dbo->fullTableName($this),
  407. 'alias' => $alias,
  408. 'limit' => $limit,
  409. 'offset' => null,
  410. 'joins' => array(),
  411. 'conditions' => array(),
  412. 'order' => null,
  413. 'group' => null
  414. );
  415. $params = array_merge($default, $options);
  416. $subQuery = trim($dbo->buildStatement($params, $this));
  417. if ($parenthesise) {
  418. $subQuery = '(' . $subQuery . ')';
  419. }
  420. return $subQuery;
  421. }
  422. /**
  423. * Wrapper find() to cache sql queries.
  424. *
  425. * @access public
  426. * @param array $conditions
  427. * @param array $fields
  428. * @param string $order
  429. * @param string $recursive
  430. * @return array
  431. * 2010-12-02 ms
  432. */
  433. public function find($type = null, $query = array()) {
  434. # reset/delete
  435. if (!empty($query['reset'])) {
  436. if (!empty($query['cache'])) {
  437. if (is_array($query['cache'])) {
  438. $key = $query['cache'][0];
  439. } else {
  440. $key = $query['cache'];
  441. if ($key === true) {
  442. $backtrace = debug_backtrace();
  443. $key = $backtrace[1]['function'];
  444. }
  445. }
  446. $this->deleteCache($key);
  447. }
  448. }
  449. # custom fixes
  450. if (is_string($type)) {
  451. switch ($type) {
  452. case 'count':
  453. if (isset($query['fields'])) {
  454. unset($query['fields']);
  455. }
  456. break;
  457. default:
  458. }
  459. }
  460. # having and group clauses enhancement
  461. if (is_array($query) && !empty($query['having']) && !empty($query['group'])) {
  462. if (!is_array($query['group'])) {
  463. $query['group'] = array($query['group']);
  464. }
  465. $ds = $this->getDataSource();
  466. $having = $ds->conditions($query['having'], true, false);
  467. $query['group'][count($query['group']) - 1] .= " HAVING $having";
  468. } /* elseif (is_array($query) && !empty($query['having'])) {
  469. $ds = $this->getDataSource();
  470. $having = $ds->conditions($query['having'], true, false);
  471. $query['conditions'][] = '1=1 HAVING '.$having;
  472. }
  473. */
  474. # find
  475. if (!Configure::read('Cache.disable') && Configure::read('Cache.check') && !empty($query['cache'])) {
  476. if (is_array($query['cache'])) {
  477. $key = $query['cache'][0];
  478. $expires = DAY;
  479. if (!empty($query['cache'][1])) {
  480. $expires = $query['cache'][1];
  481. }
  482. } else {
  483. $key = $query['cache'];
  484. if ($key === true) {
  485. $backtrace = debug_backtrace();
  486. $key = $backtrace[1]['function'];
  487. }
  488. $expires = DAY;
  489. }
  490. $options = array('prefix' => strtolower(Inflector::underscore($this->alias)) . '__', );
  491. if (!empty($expires)) {
  492. $options['duration'] = $expires;
  493. }
  494. if (!Configure::read('Cache.disable')) {
  495. Cache::config('sql', $options);
  496. $key = Inflector::underscore($key);
  497. $results = Cache::read($key, 'sql');
  498. }
  499. if ($results === null) {
  500. $results = parent::find($type, $query);
  501. Cache::write($key, $results, 'sql');
  502. }
  503. return $results;
  504. }
  505. # Without caching
  506. return parent::find($type, $query);
  507. }
  508. /*
  509. public function _findCount($state, $query, $results = array()) {
  510. if (isset($query['fields'])) {
  511. unset($query['fields']);
  512. }
  513. pr($results);
  514. return parent::_findCount($state, $query, $results = array());
  515. }
  516. */
  517. /**
  518. * 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!
  519. * @see http://bakery.cakephp.org/articles/view/add-formatted-lists-to-your-appmodel
  520. * @deprecated
  521. * added Caching
  522. * 2009-12-27 ms
  523. */
  524. protected function _find($type, $options = array()) {
  525. $res = false; // $this->_getCachedResults($type, $options);
  526. if ($res === false) {
  527. if (isset($options['cache'])) {
  528. unset($options['cache']);
  529. }
  530. if (!isset($options['recursive'])) {
  531. //$options['recursive'] = -1;
  532. }
  533. switch ($type) {
  534. # @see http://bakery.cakephp.org/deu/articles/nate/2010/10/10/quick-tipp_-_doing_ad-hoc-joins_bei_model_find
  535. case 'matches':
  536. if (!isset($options['joins'])) {
  537. $options['joins'] = array();
  538. }
  539. if (!isset($options['model']) || !isset($options['scope'])) {
  540. break;
  541. }
  542. $assoc = $this->hasAndBelongsToMany[$options['model']];
  543. $bind = "{$assoc['with']}.{$assoc['foreignKey']} = {$this->alias}.{$this->primaryKey}";
  544. $options['joins'][] = array(
  545. 'table' => $assoc['joinTable'],
  546. 'alias' => $assoc['with'],
  547. 'type' => 'inner',
  548. 'foreignKey' => false,
  549. 'conditions'=> array($bind)
  550. );
  551. $bind = $options['model'] . '.' . $this->{$options['model']}->primaryKey . ' = ';
  552. $bind .= "{$assoc['with']}.{$assoc['associationForeignKey']}";
  553. $options['joins'][] = array(
  554. 'table' => $this->{$options['model']}->table,
  555. 'alias' => $options['model'],
  556. 'type' => 'inner',
  557. 'foreignKey' => false,
  558. 'conditions'=> array($bind) + (array)$options['scope'],
  559. );
  560. unset($options['model'], $options['scope']);
  561. $type = 'all';
  562. break;
  563. # probably deprecated since "virtual fields" in 1.3
  564. case 'formattedlist':
  565. if (!isset($options['fields']) || count($options['fields']) < 3) {
  566. $res = parent::find('list', $options);
  567. break;
  568. }
  569. $this->recursive = -1;
  570. //setup formating
  571. $format = '';
  572. if (!isset($options['format'])) {
  573. for ($i = 0; $i < (count($options['fields']) - 1); $i++) $format .= '%s ';
  574. $format = substr($format, 0, -1);
  575. } else {
  576. $format = $options['format'];
  577. }
  578. //get data
  579. $list = parent::find('all', $options);
  580. // remove model alias from strings to only get field names
  581. $tmpPath2[] = $format;
  582. for ($i = 1; $i <= (count($options['fields']) - 1); $i++) {
  583. $field[$i] = str_replace($this->alias . '.', '', $options['fields'][$i]);
  584. $tmpPath2[] = '{n}.' . $this->alias . '.' . $field[$i];
  585. }
  586. //do the magic?? read the code...
  587. $res = Set::combine($list, '{n}.' . $this->alias . '.' . $this->primaryKey, $tmpPath2);
  588. break;
  589. default:
  590. $res = parent::find($type, $options);
  591. break;
  592. }
  593. if (!empty($this->useCache)) {
  594. Cache::write($this->cacheName, $res, $this->cacheConfig);
  595. if (Configure::read('debug') > 0) {
  596. $this->log('WRITE (' . $this->cacheConfig . '): ' . $this->cacheName, 'cache');
  597. }
  598. }
  599. } else {
  600. if (Configure::read('debug') > 0) {
  601. $this->log('READ (' . $this->cacheConfig . '): ' . $this->cacheName, 'cache');
  602. }
  603. }
  604. return $res;
  605. }
  606. /*
  607. USAGE of formattetlist:
  608. $this->Model->find('formattedlist',
  609. array(
  610. 'fields'=>array(
  611. 'Model.id', // allows start with the value="" tags field
  612. 'Model.field1', // then put them in order of how you want the format to output.
  613. 'Model.field2',
  614. 'Model.field3',
  615. 'Model.field4',
  616. 'Model.field5',
  617. ),
  618. 'format'=>'%s-%s%s %s%s'
  619. )
  620. );
  621. */
  622. /**
  623. * @deprecated
  624. */
  625. public function _getCachedResults($type, $options) {
  626. $this->useCache = true;
  627. if (!is_array($options) || empty($options['cache']) || Configure::read('debug') > 0 && !(Configure::read('Debug.override'))) {
  628. $this->useCache = false;
  629. return false;
  630. }
  631. if ($options['cache'] === true) {
  632. $this->cacheName = $this->alias . '_' . sha1($type . serialize($options));
  633. } else {
  634. /*
  635. if (!isset($options['cache']['name'])) {
  636. return false;
  637. }
  638. */
  639. $this->cacheName = $this->alias . '_' . sha1($type . serialize($options));
  640. $this->cacheConfig = $options['cache'];
  641. //$this->cacheName = $this->alias . '_' . $type . '_' . $options['cache'];
  642. //$this->cacheConfig = isset($options['cache']['config']) ? $options['cache']['config'] : 'default';
  643. }
  644. $results = Cache::read($this->cacheName, $this->cacheConfig);
  645. return $results;
  646. }
  647. /*
  648. neighbor find problem:
  649. This means it will sort the results on Model.created ASC and DESC.
  650. However, in certain situations you would like to order on more than one
  651. field. For example, on a rating and a uploaddate. Requirements could look
  652. like: Get next en previous record of a certain Model based on the top
  653. rated. When the rating is equal those should be ordered on creation date.
  654. I suggest something similar to:
  655. $this->Movie->find('neighbors', array(
  656. 'scope' => array(
  657. array(
  658. 'field' => 'rating',
  659. 'order' => 'DESC',
  660. 'value' => 4.85
  661. ),
  662. array(
  663. 'field' => 'created',
  664. 'order' => 'DESC',
  665. 'value' => '2009-05-26 06:20:03'
  666. )
  667. )
  668. 'conditions' => array(
  669. 'approved' => true,
  670. 'processed' => true
  671. )
  672. */
  673. /**
  674. * core-fix for multiple sort orders
  675. * @param addiotional 'scope'=>array(field,order) - value is retrieved by (submitted) primary key
  676. * TODO: fix it
  677. * 2009-07-25 ms
  678. */
  679. protected function _findNeighbors($state, $query, $results = array()) {
  680. return parent::_findNeighbors($state, $query, $results);
  681. if (isset($query['scope'])) {
  682. //TODO
  683. }
  684. return parent::find($type, $options);
  685. }
  686. /**
  687. * @param mixed $id: id only, or request array
  688. * @param array $options
  689. * - filter: open/closed/none
  690. * - field (sortField, if not id)
  691. * - reverse: sortDirection (0=normalAsc/1=reverseDesc)
  692. * - displayField: ($this->displayField, if empty)
  693. * @param array $qryOptions
  694. * - recursive (defaults to -1)
  695. * TODO: try to use core function, TRY TO ALLOW MULTIPLE SORT FIELDS
  696. * @return array
  697. */
  698. public function neighbors($id = null, $options = array(), $qryOptions = array()) {
  699. $sortField = (!empty($options['field']) ? $options['field'] : 'created');
  700. $normalDirection = (!empty($options['reverse']) ? false : true);
  701. $sortDirWord = $normalDirection ? array('ASC', 'DESC') : array('DESC', 'ASC');
  702. $sortDirSymb = $normalDirection ? array('>=', '<=') : array('<=', '>=');
  703. $displayField = (!empty($options['displayField']) ? $options['displayField'] : $this->displayField);
  704. if (is_array($id)) {
  705. $data = $id;
  706. $id = $data[$this->alias]['id'];
  707. } elseif ($id === null) {
  708. $id = $this->id;
  709. }
  710. if (!empty($id)) {
  711. $data = $this->find('first', array('conditions' => array('id' => $id), 'contain' => array()));
  712. }
  713. if (empty($id) || empty($data) || empty($data[$this->alias][$sortField])) {
  714. return array();
  715. } else {
  716. $field = $data[$this->alias][$sortField];
  717. }
  718. $findOptions = array('recursive' => -1);
  719. if (isset($qryOptions['recursive'])) {
  720. $findOptions['recursive'] = $qryOptions['recursive'];
  721. }
  722. if (isset($qryOptions['contain'])) {
  723. $findOptions['contain'] = $qryOptions['contain'];
  724. }
  725. $findOptions['fields'] = array($this->alias . '.id', $this->alias . '.' . $displayField);
  726. $findOptions['conditions'][$this->alias . '.id !='] = $id;
  727. # //TODO: take out
  728. if (!empty($options['filter']) && $options['filter'] == REQUEST_STATUS_FILTER_OPEN) {
  729. $findOptions['conditions'][$this->alias . '.status <'] = REQUEST_STATUS_DECLINED;
  730. } elseif (!empty($options['filter']) && $options['filter'] == REQUEST_STATUS_FILTER_CLOSED) {
  731. $findOptions['conditions'][$this->alias . '.status >='] = REQUEST_STATUS_DECLINED;
  732. }
  733. $return = array();
  734. if (!empty($qryOptions['conditions'])) {
  735. $findOptions['conditions'] = Set::merge($findOptions['conditions'], $qryOptions['conditions']);
  736. }
  737. $options = $findOptions;
  738. $options['conditions'] = Set::merge($options['conditions'], array($this->alias . '.' . $sortField . ' ' . $sortDirSymb[1] => $field));
  739. $options['order'] = array($this->alias . '.' . $sortField . '' => $sortDirWord[1]);
  740. $this->id = $id;
  741. $return['prev'] = $this->find('first', $options);
  742. $options = $findOptions;
  743. $options['conditions'] = Set::merge($options['conditions'], array($this->alias . '.' . $sortField . ' ' . $sortDirSymb[0] => $field));
  744. $options['order'] = array($this->alias . '.' . $sortField . '' => $sortDirWord[0]); // ??? why 0 instead of 1
  745. $this->id = $id;
  746. $return['next'] = $this->find('first', $options);
  747. return $return;
  748. }
  749. /**
  750. * Delete all records using an atomic query similar to updateAll().
  751. * Note: Does not need manual sanitizing/escaping, though.
  752. *
  753. * Does not do any callbacks
  754. *
  755. * @param mixed $conditions Conditions to match, true for all records
  756. * @return bool Success
  757. */
  758. public function deleteAllRaw($conditions = true) {
  759. return $this->getDataSource()->delete($this, $conditions);
  760. }
  761. /** Validation Functions **/
  762. /**
  763. * Overwrite invalidate to allow last => true
  764. *
  765. * @param string $field The name of the field to invalidate
  766. * @param mixed $value Name of validation rule that was not failed, or validation message to
  767. * be returned. If no validation key is provided, defaults to true.
  768. * @param boolean $last If this should be the last validation check for this validation run
  769. * @return void
  770. */
  771. public function invalidate($field, $value = true, $last = false) {
  772. parent::invalidate($field, $value);
  773. if (!$last) {
  774. return;
  775. }
  776. $this->validator()->remove($field);
  777. }
  778. /**
  779. * validates a primary or foreign key depending on the current schema data for this field
  780. * recognizes uuid (char36) and aiid (int10 unsigned) - not yet mixed (varchar36)
  781. * more useful than using numeric or notEmpty which are type specific
  782. *
  783. * @param array $data
  784. * @param array $options
  785. * - allowEmpty
  786. * @return bool Success
  787. * 2011-06-21 ms
  788. */
  789. public function validateKey($data = array(), $options = array()) {
  790. $keys = array_keys($data);
  791. $key = array_shift($keys);
  792. $value = array_shift($data);
  793. $schema = $this->schema($key);
  794. if (!$schema) {
  795. return true;
  796. }
  797. $defaults = array(
  798. 'allowEmpty' => false,
  799. );
  800. $options = array_merge($defaults, $options);
  801. if ($schema['type'] !== 'integer') {
  802. if ($options['allowEmpty'] && $value === '') {
  803. return true;
  804. }
  805. return Validation::uuid($value);
  806. }
  807. if ($options['allowEmpty'] && $value === 0) {
  808. return true;
  809. }
  810. return is_numeric($value) && (int)$value == $value && $value > 0;
  811. }
  812. /**
  813. * checks if the passed enum value is valid
  814. *
  815. * @return bool Success
  816. * 2010-02-09 ms
  817. */
  818. public function validateEnum(array $data, $enum = null, $additionalKeys = array()) {
  819. $keys = array_keys($data);
  820. $valueKey = array_shift($keys);
  821. $value = $data[$valueKey];
  822. $keys = array();
  823. if ($enum === true) {
  824. $enum = $valueKey;
  825. }
  826. if ($enum !== null) {
  827. if (!method_exists($this, $enum)) {
  828. trigger_error('Enum method \'' . $enum . '()\' not exists', E_USER_ERROR);
  829. return false;
  830. }
  831. //TODO: make static
  832. $keys = $this->{$enum}();
  833. }
  834. $keys = array_merge($additionalKeys, array_keys($keys));
  835. if (!empty($keys) && in_array($value, $keys)) {
  836. return true;
  837. }
  838. return false;
  839. }
  840. /**
  841. * checks if the content of 2 fields are equal
  842. * Does not check on empty fields! Return TRUE even if both are empty (secure against empty in another rule)!
  843. *
  844. * @return bool Success
  845. * 2009-01-22 ms
  846. */
  847. public function validateIdentical($data = array(), $compareWith = null, $options = array()) {
  848. if (is_array($data)) {
  849. $value = array_shift($data);
  850. } else {
  851. $value = $data;
  852. }
  853. $compareValue = $this->data[$this->alias][$compareWith];
  854. $matching = array('string' => 'string', 'int' => 'integer', 'float' => 'float', 'bool' => 'boolean');
  855. if (!empty($options['cast']) && array_key_exists($options['cast'], $matching)) {
  856. # cast values to string/int/float/bool if desired
  857. settype($compareValue, $matching[$options['cast']]);
  858. settype($value, $matching[$options['cast']]);
  859. }
  860. return ($compareValue === $value);
  861. }
  862. /**
  863. * checks a record, if it is unique - depending on other fields in this table (transfered as array)
  864. * example in model: 'rule' => array ('validateUnique', array('belongs_to_table_id','some_id','user_id')),
  865. * if all keys (of the array transferred) match a record, return false, otherwise true
  866. *
  867. * @param array $fields Other fields to depend on
  868. * TODO: add possibity of deep nested validation (User -> Comment -> CommentCategory: UNIQUE comment_id, Comment.user_id)
  869. * @param array $options
  870. * - requireDependentFields Require all dependent fields for the validation rule to return true
  871. * @return bool Success
  872. * 2010-01-30 ms
  873. */
  874. public function validateUnique($data, $fields = array(), $options = array()) {
  875. $id = (!empty($this->data[$this->alias]['id']) ? $this->data[$this->alias]['id'] : 0);
  876. if (!$id && $this->id) {
  877. $id = $this->id;
  878. }
  879. foreach ($data as $key => $value) {
  880. $fieldName = $key;
  881. $fieldValue = $value;
  882. break;
  883. }
  884. $conditions = array(
  885. $this->alias . '.' . $fieldName => $fieldValue,
  886. $this->alias . '.id !=' => $id);
  887. # careful, if fields is not manually filled, the options will be the second param!!! big problem...
  888. $fields = (array)$fields;
  889. if (!array_key_exists('allowEmpty', $fields)) {
  890. foreach ($fields as $dependingField) {
  891. if (isset($this->data[$this->alias][$dependingField])) { // add ONLY if some content is transfered (check on that first!)
  892. $conditions[$this->alias . '.' . $dependingField] = $this->data[$this->alias][$dependingField];
  893. } elseif (isset($this->data['Validation'][$dependingField])) { // add ONLY if some content is transfered (check on that first!
  894. $conditions[$this->alias . '.' . $dependingField] = $this->data['Validation'][$dependingField];
  895. } elseif (!empty($id)) {
  896. # manual query! (only possible on edit)
  897. $res = $this->find('first', array('fields' => array($this->alias.'.'.$dependingField), 'conditions' => array($this->alias.'.id' => $id)));
  898. if (!empty($res)) {
  899. $conditions[$this->alias . '.' . $dependingField] = $res[$this->alias][$dependingField];
  900. }
  901. } else {
  902. if (!empty($options['requireDependentFields'])) {
  903. trigger_error('Required field ' . $dependingField . ' for validateUnique validation not present');
  904. return false;
  905. }
  906. return true;
  907. }
  908. }
  909. }
  910. $this->recursive = -1;
  911. if (count($conditions) > 2) {
  912. $this->recursive = 0;
  913. }
  914. $res = $this->find('first', array('fields' => array($this->alias . '.id'), 'conditions' => $conditions));
  915. return empty($res);
  916. }
  917. /**
  918. * @param array $data
  919. * @param array $options
  920. * - scope (array of other fields as scope - isUnique dependent on other fields of the table)
  921. * - batch (defaults to true, remembers previous values in order to validate batch imports)
  922. * example in model: 'rule' => array ('validateUniqueExt', array('scope'=>array('belongs_to_table_id','some_id','user_id'))),
  923. * http://groups.google.com/group/cake-php/browse_thread/thread/880ee963456739ec
  924. * //TODO: test!!!
  925. * @return bool Success
  926. * @deprecated in favor of validateUnique?
  927. * 2011-03-27 ms
  928. */
  929. public function validateUniqueExt($data, $options = array()) {
  930. foreach ($data as $key => $value) {
  931. $fieldName = $key;
  932. $fieldValue = $value;
  933. }
  934. $defaults = array('batch' => true, 'scope' => array());
  935. $options = array_merge($defaults, $options);
  936. # for batch
  937. if ($options['batch'] !== false && !empty($this->batchRecords)) {
  938. if (array_key_exists($value, $this->batchRecords[$fieldName])) {
  939. return $options['scope'] === $this->batchRecords[$fieldName][$value];
  940. }
  941. }
  942. # continue with validation
  943. if (!$this->validateUnique($data, $options['scope'])) {
  944. return false;
  945. }
  946. # for batch
  947. if ($options['batch'] !== false) {
  948. if (!isset($this->batchRecords)) {
  949. $this->batchRecords = array();
  950. }
  951. $this->batchRecords[$fieldName][$value] = $scope;
  952. }
  953. return true;
  954. }
  955. /**
  956. * Checks if a url is valid AND accessable (returns false otherwise)
  957. *
  958. * @param array/string $data: full url(!) starting with http://...
  959. * @options array
  960. * - allowEmpty TRUE/FALSE (TRUE: if empty => return TRUE)
  961. * - required TRUE/FALSE (TRUE: overrides allowEmpty)
  962. * - autoComplete (default: TRUE)
  963. * - deep (default: TRUE)
  964. * @return bool Success
  965. * 2010-10-18 ms
  966. */
  967. public function validateUrl($data, $options = array()) {
  968. if (is_array($data)) {
  969. $url = array_shift($data);
  970. } else {
  971. $url = $data;
  972. }
  973. if (empty($url)) {
  974. if (!empty($options['allowEmpty']) && empty($options['required'])) {
  975. return true;
  976. }
  977. return false;
  978. }
  979. if (!isset($options['autoComplete']) || $options['autoComplete'] !== false) {
  980. $url = $this->_autoCompleteUrl($url);
  981. }
  982. if (!isset($options['strict']) || $options['strict'] !== false) {
  983. $options['strict'] = true;
  984. }
  985. # validation
  986. if (!Validation::url($url, $options['strict']) && env('REMOTE_ADDR') !== '127.0.0.1') {
  987. return false;
  988. }
  989. # same domain?
  990. if (!empty($options['sameDomain']) && !empty($_SERVER['HTTP_HOST'])) {
  991. $is = parse_url($url, PHP_URL_HOST);
  992. $expected = $_SERVER['HTTP_HOST'];
  993. if (mb_strtolower($is) !== mb_strtolower($expected)) {
  994. return false;
  995. }
  996. }
  997. if (isset($options['deep']) && $options['deep'] === false) {
  998. return true;
  999. }
  1000. return $this->_validUrl($url);
  1001. }
  1002. /**
  1003. * prepend protocol if missing
  1004. *
  1005. * @param string $url
  1006. * @return string Url
  1007. * 2009-02-27 ms
  1008. */
  1009. protected function _autoCompleteUrl($url) {
  1010. if (mb_strpos($url, '/') === 0) {
  1011. $url = Router::url($url, true);
  1012. } elseif (mb_strpos($url, '://') === false && mb_strpos($url, 'www.') === 0) {
  1013. $url = 'http://' . $url;
  1014. }
  1015. return $url;
  1016. }
  1017. /**
  1018. * checks if a url is valid
  1019. *
  1020. * @param string url
  1021. * @return bool Success
  1022. * 2009-02-27 ms
  1023. */
  1024. protected function _validUrl($url) {
  1025. $headers = Utility::getHeaderFromUrl($url);
  1026. if ($headers === false) {
  1027. return false;
  1028. }
  1029. $headers = implode("\n", $headers);
  1030. $protocol = mb_strpos($url, 'https://') === 0 ? 'HTTP' : 'HTTP';
  1031. return ((bool)preg_match('#^'.$protocol.'/.*\s+[(200|301|302)]+\s#i', $headers) && !(bool)preg_match('#^'.$protocol.'/.*\s+[(404|999)]+\s#i', $headers));
  1032. }
  1033. /**
  1034. * Validation of DateTime Fields (both Date and Time together)
  1035. *
  1036. * @param options
  1037. * - dateFormat (defaults to 'ymd')
  1038. * - allowEmpty
  1039. * - after/before (fieldName to validate against)
  1040. * - min/max (defaults to >= 1 - at least 1 minute apart)
  1041. * @return bool Success
  1042. * 2011-03-02 ms
  1043. */
  1044. public function validateDateTime($data, $options = array()) {
  1045. $format = !empty($options['dateFormat']) ? $options['dateFormat'] : 'ymd';
  1046. if (is_array($data)) {
  1047. $value = array_shift($data);
  1048. } else {
  1049. $value = $data;
  1050. }
  1051. $dateTime = explode(' ', trim($value), 2);
  1052. $date = $dateTime[0];
  1053. $time = (!empty($dateTime[1]) ? $dateTime[1] : '');
  1054. if (!empty($options['allowEmpty']) && (empty($date) && empty($time) || $date == DEFAULT_DATE && $time == DEFAULT_TIME || $date == DEFAULT_DATE && empty($time))) {
  1055. return true;
  1056. }
  1057. /*
  1058. if ($this->validateDate($date, $options) && $this->validateTime($time, $options)) {
  1059. return true;
  1060. }
  1061. */
  1062. if (Validation::date($date, $format) && Validation::time($time)) {
  1063. # after/before?
  1064. $minutes = isset($options['min']) ? $options['min'] : 1;
  1065. if (!empty($options['after']) && isset($this->data[$this->alias][$options['after']])) {
  1066. if (strtotime($this->data[$this->alias][$options['after']]) > strtotime($value) - $minutes) {
  1067. return false;
  1068. }
  1069. }
  1070. if (!empty($options['before']) && isset($this->data[$this->alias][$options['before']])) {
  1071. if (strtotime($this->data[$this->alias][$options['before']]) < strtotime($value) + $minutes) {
  1072. return false;
  1073. }
  1074. }
  1075. return true;
  1076. }
  1077. return false;
  1078. }
  1079. /**
  1080. * Validation of Date fields (as the core one is buggy!!!)
  1081. *
  1082. * @param options
  1083. * - dateFormat (defaults to 'ymd')
  1084. * - allowEmpty
  1085. * - after/before (fieldName to validate against)
  1086. * - min (defaults to 0 - equal is OK too)
  1087. * @return bool Success
  1088. * 2011-03-02 ms
  1089. */
  1090. public function validateDate($data, $options = array()) {
  1091. $format = !empty($options['format']) ? $options['format'] : 'ymd';
  1092. if (is_array($data)) {
  1093. $value = array_shift($data);
  1094. } else {
  1095. $value = $data;
  1096. }
  1097. $dateTime = explode(' ', trim($value), 2);
  1098. $date = $dateTime[0];
  1099. if (!empty($options['allowEmpty']) && (empty($date) || $date == DEFAULT_DATE)) {
  1100. return true;
  1101. }
  1102. if (Validation::date($date, $format)) {
  1103. # after/before?
  1104. $days = !empty($options['min']) ? $options['min'] : 0;
  1105. if (!empty($options['after']) && isset($this->data[$this->alias][$options['after']])) {
  1106. if ($this->data[$this->alias][$options['after']] > date(FORMAT_DB_DATE, strtotime($date) - $days * DAY)) {
  1107. return false;
  1108. }
  1109. }
  1110. if (!empty($options['before']) && isset($this->data[$this->alias][$options['before']])) {
  1111. if ($this->data[$this->alias][$options['before']] < date(FORMAT_DB_DATE, strtotime($date) + $days * DAY)) {
  1112. return false;
  1113. }
  1114. }
  1115. return true;
  1116. }
  1117. return false;
  1118. }
  1119. /**
  1120. * Validation of Time fields
  1121. *
  1122. * @param array $options
  1123. * - timeFormat (defaults to 'hms')
  1124. * - allowEmpty
  1125. * - after/before (fieldName to validate against)
  1126. * - min/max (defaults to >= 1 - at least 1 minute apart)
  1127. * @return bool Success
  1128. * 2011-03-02 ms
  1129. */
  1130. public function validateTime($data, $options = array()) {
  1131. if (is_array($data)) {
  1132. $value = array_shift($data);
  1133. } else {
  1134. $value = $data;
  1135. }
  1136. $dateTime = explode(' ', trim($value), 2);
  1137. $value = array_pop($dateTime);
  1138. if (Validation::time($value)) {
  1139. # after/before?
  1140. if (!empty($options['after']) && isset($this->data[$this->alias][$options['after']])) {
  1141. if ($this->data[$this->alias][$options['after']] >= $value) {
  1142. return false;
  1143. }
  1144. }
  1145. if (!empty($options['before']) && isset($this->data[$this->alias][$options['before']])) {
  1146. if ($this->data[$this->alias][$options['before']] <= $value) {
  1147. return false;
  1148. }
  1149. }
  1150. return true;
  1151. }
  1152. return false;
  1153. }
  1154. //TODO
  1155. /**
  1156. * Validation of Date Fields (>= minDate && <= maxDate)
  1157. * @param options
  1158. * - min/max (TODO!!)
  1159. * 2010-01-20 ms
  1160. */
  1161. public function validateDateRange($data, $options = array()) {
  1162. }
  1163. //TODO
  1164. /**
  1165. * Validation of Time Fields (>= minTime && <= maxTime)
  1166. * @param options
  1167. * - min/max (TODO!!)
  1168. * 2010-01-20 ms
  1169. */
  1170. public function validateTimeRange($data, $options = array()) {
  1171. }
  1172. /**
  1173. * model validation rule for email addresses
  1174. *
  1175. * @return bool Success
  1176. * 2010-01-14 ms
  1177. */
  1178. public function validateUndisposable($data, $proceed = false) {
  1179. $email = array_shift($data);
  1180. if (empty($email)) {
  1181. return true;
  1182. }
  1183. return $this->isUndisposableEmail($email, false, $proceed);
  1184. }
  1185. /**
  1186. * NOW: can be set to work offline only (if server is down etc)
  1187. * Checks if a email is not from a garbige hoster
  1188. *
  1189. * @param string email (necessary)
  1190. * @return boolean true if valid, else false
  1191. * 2009-03-09 ms
  1192. */
  1193. public function isUndisposableEmail($email, $onlineMode = false, $proceed = false) {
  1194. if (!isset($this->UndisposableEmail)) {
  1195. App::import('Vendor', 'undisposable/undisposable');
  1196. $this->UndisposableEmail = new UndisposableEmail();
  1197. }
  1198. if (!$onlineMode) {
  1199. # crashed with white screen of death otherwise... (if foreign page is 404)
  1200. $this->UndisposableEmail->useOnlineList(false);
  1201. }
  1202. if (!class_exists('Validation')) {
  1203. App::uses('Validation', 'Utility');
  1204. }
  1205. if (!Validation::email($email)) {
  1206. return false;
  1207. }
  1208. if ($this->UndisposableEmail->isUndisposableEmail($email) === false) {
  1209. # trigger log
  1210. $this->log('Disposable Email detected: ' . h($email).' (IP '.env('REMOTE_ADDR').')', 'undisposable');
  1211. if ($proceed === true) {
  1212. return true;
  1213. }
  1214. return false;
  1215. }
  1216. return true;
  1217. }
  1218. /**
  1219. * Is blocked email?
  1220. * //TODO: move outside of MyModel?
  1221. *
  1222. * @return bool $ifNotBlacklisted
  1223. * 2009-12-22 ms
  1224. */
  1225. public function validateNotBlocked($params) {
  1226. $email = array_shift($params);
  1227. if (!isset($this->Blacklist)) {
  1228. //App::uses('Blacklist', 'Tools.Model'
  1229. $this->Blacklist = ClassRegistry::init('Tools.Blacklist');
  1230. }
  1231. if ($this->Blacklist->isBlacklisted(Blacklist::TYPE_EMAIL, $email)) {
  1232. return false;
  1233. }
  1234. return true;
  1235. }
  1236. /** General Model Functions **/
  1237. /**
  1238. * CAREFUL: use LIMIT due to Starker Serverlastigkeit! or CACHE it!
  1239. *
  1240. * e.g.: 'ORDER BY ".$this->umlautsOrderFix('User.nic')." ASC'
  1241. *
  1242. * @param string variable (to be correctly ordered)
  1243. * @deprecated
  1244. */
  1245. public function umlautsOrderFix($var) {
  1246. return "REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(".$var.", 'Ä', 'Ae'), 'Ö', 'Oe'), 'Ü', 'Ue'), 'ä', 'ae'), 'ö', 'oe'), 'ü','ue'), 'ß', 'ss')";
  1247. }
  1248. /**
  1249. * set + guaranteeFields!
  1250. * Extends the core set function (only using data!!!)
  1251. *
  1252. * @param mixed $data
  1253. * @param mixed $data2 (optional)
  1254. * @param array $requiredFields Required fields
  1255. * @param array $fieldList Whitelist / Allowed fields
  1256. * @return array
  1257. * 2010-03-11 ms
  1258. */
  1259. public function set($data, $data2 = null, $requiredFields = array(), $fieldList = array()) {
  1260. if (!empty($requiredFields)) {
  1261. $data = $this->guaranteeFields($requiredFields, $data);
  1262. }
  1263. if (!empty($fieldList)) {
  1264. $data = $this->whitelist($fieldList, $data);
  1265. }
  1266. return parent::set($data, $data2);
  1267. }
  1268. /**
  1269. * @param array $fieldList
  1270. * @param array $data (optional)
  1271. * @return array
  1272. * 2011-06-01 ms
  1273. */
  1274. public function whitelist($fieldList, $data = null) {
  1275. $model = $this->alias;
  1276. if ($data === null) {
  1277. $data = $this->data;
  1278. }
  1279. foreach ($data[$model] as $key => $val) {
  1280. if (!in_array($key, $fieldList)) {
  1281. unset($data[$model][$key]);
  1282. }
  1283. }
  1284. return $data;
  1285. }
  1286. /**
  1287. * make sure required fields exists - in order to properly validate them
  1288. * @param array: field1, field2 - or field1, Model2.field1 etc
  1289. * @param array: data (optional, otherwise the array with the required fields will be returned)
  1290. * @return array
  1291. * 2010-03-11 ms
  1292. */
  1293. public function guaranteeFields($requiredFields, $data = null) {
  1294. $guaranteedFields = array();
  1295. foreach ($requiredFields as $column) {
  1296. if (strpos($column, '.') !== false) {
  1297. list($model, $column) = explode('.', $column, 2);
  1298. } else {
  1299. $model = $this->alias;
  1300. }
  1301. $guaranteedFields[$model][$column] = ''; # now field exists in any case!
  1302. }
  1303. if ($data === null) {
  1304. return $guaranteedFields;
  1305. }
  1306. if (!empty($guaranteedFields)) {
  1307. $data = Set::merge($guaranteedFields, $data);
  1308. }
  1309. return $data;
  1310. }
  1311. /**
  1312. * make certain fields a requirement for the form to validate
  1313. * (they must only be present - can still be empty, though!)
  1314. *
  1315. * @param array $fieldList
  1316. * @param bool $allowEmpty (or NULL to not touch already set elements)
  1317. * @return void
  1318. * 2012-02-20 ms
  1319. */
  1320. public function requireFields($requiredFields, $allowEmpty = null) {
  1321. if ($allowEmpty === null) {
  1322. $setAllowEmpty = true;
  1323. } else {
  1324. $setAllowEmpty = $allowEmpty;
  1325. }
  1326. foreach ($requiredFields as $column) {
  1327. if (strpos($column, '.') !== false) {
  1328. list($model, $column) = explode('.', $column, 2);
  1329. } else {
  1330. $model = $this->alias;
  1331. }
  1332. if ($model !== $this->alias) {
  1333. continue;
  1334. }
  1335. if (empty($this->validate[$column])) {
  1336. $this->validate[$column]['notEmpty'] = array('rule' => 'notEmpty', 'required' => true, 'allowEmpty' => $setAllowEmpty, 'message' => 'valErrMandatoryField');
  1337. } else {
  1338. $keys = array_keys($this->validate[$column]);
  1339. if (!in_array('rule', $keys)) {
  1340. $key = array_shift($keys);
  1341. $this->validate[$column][$key]['required'] = true;
  1342. if (!isset($this->validate[$column][$key]['allowEmpty'])) {
  1343. $this->validate[$column][$key]['allowEmpty'] = $setAllowEmpty;
  1344. }
  1345. } else {
  1346. $keys['required'] = true;
  1347. if (!isset($keys['allowEmpty'])) {
  1348. $keys['allowEmpty'] = $setAllowEmpty;
  1349. }
  1350. $this->validate[$column] = $keys;
  1351. }
  1352. }
  1353. }
  1354. }
  1355. /**
  1356. * instead of whitelisting
  1357. * @param array $blackList
  1358. * - array: fields to blacklist
  1359. * - boolean TRUE: removes all foreign_keys (_id and _key)
  1360. * note: one-dimensional
  1361. * @return array
  1362. * 2009-06-19 ms
  1363. */
  1364. public function blacklist($blackList = array()) {
  1365. if ($blackList === true) {
  1366. //TODO
  1367. }
  1368. return array_diff(array_keys($this->schema()), (array)$blackList);
  1369. }
  1370. /**
  1371. * Shortcut method to find a specific entry via primary key
  1372. *
  1373. * @param mixed $id
  1374. * @param string|array $fields
  1375. * @param array $contain
  1376. * @return mixed
  1377. * 2009-11-14 ms
  1378. */
  1379. public function get($id, $fields = array(), $contain = array()) {
  1380. if (is_array($id)) {
  1381. $column = $id[0];
  1382. $value = $id[1];
  1383. } else {
  1384. $column = 'id';
  1385. $value = $id;
  1386. }
  1387. if ($fields === '*') {
  1388. $fields = $this->alias . '.*';
  1389. } elseif (!empty($fields)) {
  1390. foreach ($fields as $row => $field) {
  1391. if (strpos($field, '.') !== false) {
  1392. continue;
  1393. }
  1394. $fields[$row] = $this->alias . '.' . $field;
  1395. }
  1396. }
  1397. $options = array(
  1398. 'conditions' => array($this->alias . '.' . $column => $value),
  1399. );
  1400. if (!empty($fields)) {
  1401. $options['fields'] = $fields;
  1402. }
  1403. if (!empty($contain)) {
  1404. $options['contain'] = $contain;
  1405. }
  1406. return $this->find('first', $options);
  1407. }
  1408. /**
  1409. * Get all related entries that have been used so far
  1410. *
  1411. * @param string $modelName The related model
  1412. * @param string $groupField Field to group by
  1413. * @param string $type Find type
  1414. * @param array $options
  1415. * @return array
  1416. */
  1417. public function getRelatedInUse($modelName, $groupField, $type = 'all', $options = array()) {
  1418. $defaults = array(
  1419. 'contain' => array($modelName),
  1420. 'group' => $groupField,
  1421. 'order' => $this->$modelName->order ? $this->$modelName->order : array($modelName . '.' . $this->$modelName->displayField => 'ASC'),
  1422. );
  1423. if ($type === 'list') {
  1424. $defaults['fields'] = array($modelName . '.' . $this->$modelName->primaryKey, $modelName . '.' . $this->$modelName->displayField);
  1425. }
  1426. $options += $defaults;
  1427. return $this->find($type, $options);
  1428. }
  1429. /**
  1430. * Get all fields that have been used so far
  1431. *
  1432. * @param string $groupField Field to group by
  1433. * @param string $type Find type
  1434. * @param array $options
  1435. * @return array
  1436. */
  1437. public function getFieldInUse($groupField, $type = 'all', $options = array()) {
  1438. $defaults = array(
  1439. 'group' => $groupField,
  1440. 'order' => array($this->alias . '.' . $this->displayField => 'ASC'),
  1441. );
  1442. if ($type === 'list') {
  1443. $defaults['fields'] = array($this->alias . '.' . $this->primaryKey, $this->alias . '.' . $this->displayField);
  1444. }
  1445. $options += $defaults;
  1446. return $this->find($type, $options);
  1447. }
  1448. /**
  1449. * Update a row with certain fields (dont use "Model" as super-key)
  1450. * @param int $id
  1451. * @param array $data
  1452. * @return bool|array Success
  1453. * 2012-11-20 ms
  1454. */
  1455. public function update($id, $data, $validate = false) {
  1456. $this->id = $id;
  1457. return $this->save($data, $validate, array_keys($data));
  1458. }
  1459. /**
  1460. * Automagic increasing of a field with e.g.:
  1461. * $this->id = ID; $this->inc('weight',3);
  1462. *
  1463. * @deprecated use atomic updateAll() instead!
  1464. * @param string fieldname
  1465. * @param int factor: defaults to 1 (could be negative as well - if field is signed and can be < 0)
  1466. */
  1467. public function inc($field, $factor = 1) {
  1468. $value = Set::extract($this->read($field), $this->alias . '.' . $field);
  1469. $value += $factor;
  1470. return $this->saveField($field, $value);
  1471. }
  1472. /**
  1473. * Toggles Field (Important/Deleted/Primary etc)
  1474. * @param STRING fieldName
  1475. * @param INT id (cleaned!)
  1476. * @return ARRAY record: [Model][values],...
  1477. * AJAX?
  1478. * 2008-11-06 ms
  1479. */
  1480. public function toggleField($fieldName, $id) {
  1481. $record = $this->get($id, array('id', $fieldName));
  1482. if (!empty($record) && !empty($fieldName) && $this->hasField($fieldName)) {
  1483. $record[$this->alias][$fieldName] = ($record[$this->alias][$fieldName] == 1 ? 0 : 1);
  1484. $this->id = $id;
  1485. $this->saveField($fieldName, $record[$this->alias][$fieldName]);
  1486. }
  1487. return $record;
  1488. }
  1489. /**
  1490. * truncate TABLE (already validated, that table exists)
  1491. * @param string table [default:FALSE = current model table]
  1492. * @return bool Success
  1493. */
  1494. public function truncate($table = null) {
  1495. if (empty($table)) {
  1496. $table = $this->table;
  1497. }
  1498. $db = ConnectionManager::getDataSource($this->useDbConfig);
  1499. return $db->truncate($table);
  1500. }
  1501. /** Deep Lists **/
  1502. /**
  1503. * recursive Dropdown Lists
  1504. * NEEDS tree behavior, NEEDS lft, rght, parent_id (!)
  1505. * //FIXME
  1506. * 2008-01-02 ms
  1507. */
  1508. public function recursiveSelect($conditions = array(), $attachTree = false, $spacer = '-- ') {
  1509. if ($attachTree) {
  1510. $this->Behaviors->load('Tree');
  1511. }
  1512. $data = $this->generateTreeList($conditions, null, null, $spacer);
  1513. return $data;
  1514. }
  1515. /**
  1516. * from http://othy.wordpress.com/2006/06/03/generatenestedlist/
  1517. * NEEDS parent_id
  1518. * //TODO refactor for 1.2
  1519. *
  1520. * @deprecated use generateTreeList instead
  1521. * 2009-08-12 ms
  1522. */
  1523. public function generateNestedList($conditions = null, $indent = '--') {
  1524. $cats = $this->find('threaded', array('conditions' => $conditions, 'fields' => array(
  1525. $this->name . '.id',
  1526. $this->name . '.name',
  1527. $this->name . '.parent_id')));
  1528. $glist = $this->_generateNestedList($cats, $indent);
  1529. return $glist;
  1530. }
  1531. /**
  1532. * from http://othy.wordpress.com/2006/06/03/generatenestedlist/
  1533. * @deprecated use generateTreeList instead
  1534. * 2009-08-12 ms
  1535. */
  1536. public function _generateNestedList($cats, $indent = '--', $level = 0) {
  1537. static $list = array();
  1538. $c = count($cats);
  1539. for ($i = 0; $i < $c; $i++) {
  1540. $list[$cats[$i][$this->alias]['id']] = str_repeat($indent, $level) . $cats[$i][$this->alias][$this->displayField];
  1541. if (!empty($cats[$i]['children'])) {
  1542. $this->_generateNestedList($cats[$i]['children'], $indent, $level + 1);
  1543. }
  1544. }
  1545. return $list;
  1546. }
  1547. }