MyModel.php 46 KB

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