MyModel.php 46 KB

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