MyModel.php 47 KB

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