MyModel.php 49 KB

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