MyModel.php 48 KB

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