MyModel.php 46 KB

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