MyModel.php 49 KB

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