MyModel.php 48 KB

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