MyModel.php 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619
  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 = array('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', array(
  29. 'engine' => 'File',
  30. 'serialize' => true,
  31. 'prefix' => '',
  32. 'path' => CACHE . 'sql' . DS,
  33. 'duration' => '+1 day'
  34. ));
  35. }
  36. if (!Configure::read('Model.disablePrefixing')) {
  37. $this->prefixOrderProperty();
  38. }
  39. // Get a notice if there is an AppModel 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, array('datetime', 'timestamp', 'date', 'time'))) {
  108. $useNewDate = (isset($data['year']) || isset($data['month']) ||
  109. isset($data['day']) || isset($data['hour']) || isset($data['minute']));
  110. $dateFields = array('Y' => 'year', 'm' => 'month', 'd' => 'day', 'H' => 'hour', 'i' => 'min', 's' => 'sec');
  111. $timeFields = array('H' => 'hour', 'i' => 'min', 's' => 'sec');
  112. $date = array();
  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 (array('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 = array();
  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 = array()) {
  213. $res = array();
  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 = array()) {
  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, array($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 = array($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 = array()) {
  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. * Enables HABTM-Validation
  356. * e.g. with
  357. * 'rule' => array('multiple', array('min' => 2))
  358. *
  359. * @return bool Success
  360. */
  361. public function beforeValidate($options = array()) {
  362. foreach ($this->hasAndBelongsToMany as $k => $v) {
  363. if (isset($this->data[$k][$k])) {
  364. $this->data[$this->alias][$k] = $this->data[$k][$k];
  365. }
  366. }
  367. return parent::beforeValidate($options);
  368. }
  369. /**
  370. * @param params
  371. * - key: functioName or other key used
  372. * @return bool Success
  373. */
  374. public function deleteCache($key = null) {
  375. $key = Inflector::underscore($key);
  376. if (!empty($key)) {
  377. return Cache::delete(strtolower(Inflector::underscore($this->alias)) . '__' . $key, 'sql');
  378. }
  379. return Cache::clear(false, 'sql');
  380. }
  381. /**
  382. * Generates a SQL subquery snippet to be used in your actual query.
  383. * Your subquery snippet needs to return a single value or flat array of values.
  384. *
  385. * Example:
  386. *
  387. * $this->Model->find('first', array(
  388. * 'conditions' => array('NOT' => array('some_id' => $this->Model->subquery(...)))
  389. * ))
  390. *
  391. * Note: You might have to set `autoFields` to false in order to retrieve only the fields you request:
  392. * http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html#containablebehavior-options
  393. *
  394. * @param string $type The type of the query ('count'/'all'/'first' - first only works with some mysql versions)
  395. * @param array $options The options array
  396. * @param string $alias You can use this intead of $options['alias'] if you want
  397. * @param bool $parenthesise Add parenthesis before and after
  398. * @return string result sql snippet of the query to run
  399. * @modified Mark Scherer (cake2.x ready and improvements)
  400. * @link http://bakery.cakephp.org/articles/lucaswxp/2011/02/11/easy_and_simple_subquery_cakephp
  401. */
  402. public function subquery($type, $options = array(), $alias = null, $parenthesise = true) {
  403. if ($alias === null) {
  404. $alias = 'Sub' . $this->alias . '';
  405. }
  406. $fields = array($alias . '.id');
  407. $limit = null;
  408. switch ($type) {
  409. case 'count':
  410. $fields = array('COUNT(*)');
  411. break;
  412. case 'first':
  413. $limit = 1;
  414. break;
  415. }
  416. $dbo = $this->getDataSource();
  417. $default = array(
  418. 'fields' => $fields,
  419. 'table' => $dbo->fullTableName($this),
  420. 'alias' => $alias,
  421. 'limit' => $limit,
  422. 'offset' => null,
  423. 'joins' => array(),
  424. 'conditions' => array(),
  425. 'order' => null,
  426. 'group' => null
  427. );
  428. $params = array_merge($default, $options);
  429. $subQuery = trim($dbo->buildStatement($params, $this));
  430. if ($parenthesise) {
  431. $subQuery = '(' . $subQuery . ')';
  432. }
  433. return $subQuery;
  434. }
  435. /**
  436. * Wrapper find() to cache sql queries.
  437. *
  438. * @param array $conditions
  439. * @param array $fields
  440. * @param string $order
  441. * @param string $recursive
  442. * @return array
  443. */
  444. public function find($type = null, $query = array()) {
  445. // reset/delete
  446. if (!empty($query['reset'])) {
  447. if (!empty($query['cache'])) {
  448. if (is_array($query['cache'])) {
  449. $key = $query['cache'][0];
  450. } else {
  451. $key = $query['cache'];
  452. if ($key === true) {
  453. $backtrace = debug_backtrace();
  454. $key = $backtrace[1]['function'];
  455. }
  456. }
  457. $this->deleteCache($key);
  458. }
  459. }
  460. // custom fixes
  461. if (is_string($type)) {
  462. switch ($type) {
  463. case 'count':
  464. if (isset($query['fields'])) {
  465. unset($query['fields']);
  466. }
  467. break;
  468. default:
  469. }
  470. }
  471. // having and group clauses enhancement
  472. if (is_array($query) && !empty($query['having']) && !empty($query['group'])) {
  473. if (!is_array($query['group'])) {
  474. $query['group'] = array($query['group']);
  475. }
  476. $ds = $this->getDataSource();
  477. $having = $ds->conditions($query['having'], true, false);
  478. $query['group'][count($query['group']) - 1] .= " HAVING $having";
  479. } /* elseif (is_array($query) && !empty($query['having'])) {
  480. $ds = $this->getDataSource();
  481. $having = $ds->conditions($query['having'], true, false);
  482. $query['conditions'][] = '1=1 HAVING '.$having;
  483. }
  484. */
  485. // find
  486. if (!Configure::read('Cache.disable') && Configure::read('Cache.check') && !empty($query['cache'])) {
  487. if (is_array($query['cache'])) {
  488. $key = $query['cache'][0];
  489. $expires = DAY;
  490. if (!empty($query['cache'][1])) {
  491. $expires = $query['cache'][1];
  492. }
  493. } else {
  494. $key = $query['cache'];
  495. if ($key === true) {
  496. $backtrace = debug_backtrace();
  497. $key = $backtrace[1]['function'];
  498. }
  499. $expires = DAY;
  500. }
  501. $options = array('prefix' => strtolower(Inflector::underscore($this->alias)) . '__', );
  502. if (!empty($expires)) {
  503. $options['duration'] = $expires;
  504. }
  505. if (!Configure::read('Cache.disable')) {
  506. Cache::config('sql', $options);
  507. $key = Inflector::underscore($key);
  508. $results = Cache::read($key, 'sql');
  509. }
  510. if (!isset($results)) {
  511. $results = parent::find($type, $query);
  512. Cache::write($key, $results, 'sql');
  513. }
  514. return $results;
  515. }
  516. // Without caching
  517. return parent::find($type, $query);
  518. }
  519. /**
  520. * 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!
  521. *
  522. * @see http://bakery.cakephp.org/articles/view/add-formatted-lists-to-your-appmodel
  523. * @deprecated
  524. * added Caching
  525. */
  526. protected function _find($type, $options = array()) {
  527. $res = false;
  528. if ($res === false) {
  529. if (isset($options['cache'])) {
  530. unset($options['cache']);
  531. }
  532. if (!isset($options['recursive'])) {
  533. //$options['recursive'] = -1;
  534. }
  535. switch ($type) {
  536. // @see http://bakery.cakephp.org/deu/articles/nate/2010/10/10/quick-tipp_-_doing_ad-hoc-joins_bei_model_find
  537. case 'matches':
  538. if (!isset($options['joins'])) {
  539. $options['joins'] = array();
  540. }
  541. if (!isset($options['model']) || !isset($options['scope'])) {
  542. break;
  543. }
  544. $assoc = $this->hasAndBelongsToMany[$options['model']];
  545. $bind = "{$assoc['with']}.{$assoc['foreignKey']} = {$this->alias}.{$this->primaryKey}";
  546. $options['joins'][] = array(
  547. 'table' => $assoc['joinTable'],
  548. 'alias' => $assoc['with'],
  549. 'type' => 'inner',
  550. 'foreignKey' => false,
  551. 'conditions' => array($bind)
  552. );
  553. $bind = $options['model'] . '.' . $this->{$options['model']}->primaryKey . ' = ';
  554. $bind .= "{$assoc['with']}.{$assoc['associationForeignKey']}";
  555. $options['joins'][] = array(
  556. 'table' => $this->{$options['model']}->table,
  557. 'alias' => $options['model'],
  558. 'type' => 'inner',
  559. 'foreignKey' => false,
  560. 'conditions' => array($bind) + (array)$options['scope'],
  561. );
  562. unset($options['model'], $options['scope']);
  563. $type = 'all';
  564. break;
  565. // probably deprecated since "virtual fields" in 1.3
  566. case 'formattedlist':
  567. if (!isset($options['fields']) || count($options['fields']) < 3) {
  568. $res = parent::find('list', $options);
  569. break;
  570. }
  571. $this->recursive = -1;
  572. //setup formating
  573. $format = '';
  574. if (!isset($options['format'])) {
  575. for ($i = 0; $i < (count($options['fields']) - 1); $i++) $format .= '%s ';
  576. $format = substr($format, 0, -1);
  577. } else {
  578. $format = $options['format'];
  579. }
  580. //get data
  581. $list = parent::find('all', $options);
  582. // remove model alias from strings to only get field names
  583. $tmpPath2[] = $format;
  584. for ($i = 1; $i <= (count($options['fields']) - 1); $i++) {
  585. $field[$i] = str_replace($this->alias . '.', '', $options['fields'][$i]);
  586. $tmpPath2[] = '{n}.' . $this->alias . '.' . $field[$i];
  587. }
  588. //do the magic?? read the code...
  589. $res = Hash::combine($list, '{n}.' . $this->alias . '.' . $this->primaryKey, $tmpPath2);
  590. break;
  591. default:
  592. $res = parent::find($type, $options);
  593. }
  594. if (!empty($this->useCache)) {
  595. Cache::write($this->cacheName, $res, $this->cacheConfig);
  596. if (Configure::read('debug') > 0) {
  597. $this->log('WRITE (' . $this->cacheConfig . '): ' . $this->cacheName, 'cache');
  598. }
  599. }
  600. } else {
  601. if (Configure::read('debug') > 0) {
  602. $this->log('READ (' . $this->cacheConfig . '): ' . $this->cacheName, 'cache');
  603. }
  604. }
  605. return $res;
  606. }
  607. /**
  608. * Core-fix for multiple sort orders
  609. *
  610. * @param addiotional 'scope'=>array(field,order) - value is retrieved by (submitted) primary key
  611. * @return mixed
  612. * TODO: fix it
  613. */
  614. protected function _findNeighbors($state, $query, $results = array()) {
  615. return parent::_findNeighbors($state, $query, $results);
  616. if (isset($query['scope'])) {
  617. //TODO
  618. }
  619. return parent::find($type, $options);
  620. }
  621. /**
  622. * @param mixed $id: id only, or request array
  623. * @param array $options
  624. * - filter: open/closed/none
  625. * - field (sortField, if not id)
  626. * - reverse: sortDirection (0=normalAsc/1=reverseDesc)
  627. * - displayField: ($this->displayField, if empty)
  628. * @param array $qryOptions
  629. * - recursive (defaults to -1)
  630. * TODO: try to use core function, TRY TO ALLOW MULTIPLE SORT FIELDS
  631. * @return array
  632. */
  633. public function neighbors($id = null, $options = array(), $qryOptions = array()) {
  634. $sortField = (!empty($options['field']) ? $options['field'] : 'created');
  635. $normalDirection = (!empty($options['reverse']) ? false : true);
  636. $sortDirWord = $normalDirection ? array('ASC', 'DESC') : array('DESC', 'ASC');
  637. $sortDirSymb = $normalDirection ? array('>=', '<=') : array('<=', '>=');
  638. $displayField = (!empty($options['displayField']) ? $options['displayField'] : $this->displayField);
  639. if (is_array($id)) {
  640. $data = $id;
  641. $id = $data[$this->alias][$this->primaryKey];
  642. } elseif ($id === null) {
  643. $id = $this->id;
  644. }
  645. if (!empty($id)) {
  646. $data = $this->find('first', array('conditions' => array($this->primaryKey => $id), 'contain' => array()));
  647. }
  648. if (empty($id) || empty($data) || empty($data[$this->alias][$sortField])) {
  649. return array();
  650. } else {
  651. $field = $data[$this->alias][$sortField];
  652. }
  653. $findOptions = array('recursive' => -1);
  654. if (isset($qryOptions['recursive'])) {
  655. $findOptions['recursive'] = $qryOptions['recursive'];
  656. }
  657. if (isset($qryOptions['contain'])) {
  658. $findOptions['contain'] = $qryOptions['contain'];
  659. }
  660. $findOptions['fields'] = array($this->alias . '.' . $this->primaryKey, $this->alias . '.' . $displayField);
  661. $findOptions['conditions'][$this->alias . '.' . $this->primaryKey . ' !='] = $id;
  662. // //TODO: take out
  663. if (!empty($options['filter']) && $options['filter'] == REQUEST_STATUS_FILTER_OPEN) {
  664. $findOptions['conditions'][$this->alias . '.status <'] = REQUEST_STATUS_DECLINED;
  665. } elseif (!empty($options['filter']) && $options['filter'] == REQUEST_STATUS_FILTER_CLOSED) {
  666. $findOptions['conditions'][$this->alias . '.status >='] = REQUEST_STATUS_DECLINED;
  667. }
  668. $return = array();
  669. if (!empty($qryOptions['conditions'])) {
  670. $findOptions['conditions'] = Hash::merge($findOptions['conditions'], $qryOptions['conditions']);
  671. }
  672. $options = $findOptions;
  673. $options['conditions'] = Hash::merge($options['conditions'], array($this->alias . '.' . $sortField . ' ' . $sortDirSymb[1] => $field));
  674. $options['order'] = array($this->alias . '.' . $sortField . '' => $sortDirWord[1]);
  675. $this->id = $id;
  676. $return['prev'] = $this->find('first', $options);
  677. $options = $findOptions;
  678. $options['conditions'] = Hash::merge($options['conditions'], array($this->alias . '.' . $sortField . ' ' . $sortDirSymb[0] => $field));
  679. $options['order'] = array($this->alias . '.' . $sortField . '' => $sortDirWord[0]); // ??? why 0 instead of 1
  680. $this->id = $id;
  681. $return['next'] = $this->find('first', $options);
  682. return $return;
  683. }
  684. /**
  685. * Delete all records using an atomic query similar to updateAll().
  686. * Note: Does not need manual sanitizing/escaping, though.
  687. *
  688. * Does not do any callbacks
  689. *
  690. * @param mixed $conditions Conditions to match, true for all records
  691. * @return bool Success
  692. */
  693. public function deleteAllRaw($conditions = true) {
  694. return $this->getDataSource()->delete($this, $conditions);
  695. }
  696. /**
  697. * Overwrite invalidate to allow last => true
  698. *
  699. * @param string $field The name of the field to invalidate
  700. * @param mixed $value Name of validation rule that was not failed, or validation message to
  701. * be returned. If no validation key is provided, defaults to true.
  702. * @param bool $last If this should be the last validation check for this validation run
  703. * @return void
  704. */
  705. public function invalidate($field, $value = true, $last = false) {
  706. parent::invalidate($field, $value);
  707. if (!$last) {
  708. return;
  709. }
  710. $this->validator()->remove($field);
  711. }
  712. /**
  713. * Validates a primary or foreign key depending on the current schema data for this field
  714. * recognizes uuid (char36) and aiid (int10 unsigned) - not yet mixed (varchar36)
  715. * more useful than using numeric or notEmpty which are type specific
  716. *
  717. * @param array $data
  718. * @param array $options
  719. * - allowEmpty
  720. * @return bool Success
  721. */
  722. public function validateKey($data = array(), $options = array()) {
  723. $keys = array_keys($data);
  724. $key = array_shift($keys);
  725. $value = array_shift($data);
  726. $schema = $this->schema($key);
  727. if (!$schema) {
  728. return true;
  729. }
  730. $defaults = array(
  731. 'allowEmpty' => false,
  732. );
  733. $options += $defaults;
  734. if ($schema['type'] !== 'integer') {
  735. if ($options['allowEmpty'] && $value === '') {
  736. return true;
  737. }
  738. return Validation::uuid($value);
  739. }
  740. if ($options['allowEmpty'] && $value === 0) {
  741. return true;
  742. }
  743. return is_numeric($value) && (int)$value == $value && $value > 0;
  744. }
  745. /**
  746. * Checks if the passed enum value is valid
  747. *
  748. * @return bool Success
  749. */
  750. public function validateEnum(array $data, $enum = null, $additionalKeys = array()) {
  751. $keys = array_keys($data);
  752. $valueKey = array_shift($keys);
  753. $value = $data[$valueKey];
  754. $keys = array();
  755. if ($enum === true) {
  756. $enum = $valueKey;
  757. }
  758. if ($enum !== null) {
  759. if (!method_exists($this, $enum)) {
  760. trigger_error('Enum method \'' . $enum . '()\' not exists', E_USER_ERROR);
  761. return false;
  762. }
  763. //TODO: make static
  764. $keys = $this->{$enum}();
  765. }
  766. $keys = array_merge($additionalKeys, array_keys($keys));
  767. if (!empty($keys) && in_array($value, $keys)) {
  768. return true;
  769. }
  770. return false;
  771. }
  772. /**
  773. * Checks if the content of 2 fields are equal
  774. * Does not check on empty fields! Return TRUE even if both are empty (secure against empty in another rule)!
  775. *
  776. * @return bool Success
  777. */
  778. public function validateIdentical($data = array(), $compareWith = null, $options = array()) {
  779. if (is_array($data)) {
  780. $value = array_shift($data);
  781. } else {
  782. $value = $data;
  783. }
  784. $compareValue = $this->data[$this->alias][$compareWith];
  785. $matching = array('string' => 'string', 'int' => 'integer', 'float' => 'float', 'bool' => 'boolean');
  786. if (!empty($options['cast']) && array_key_exists($options['cast'], $matching)) {
  787. // cast values to string/int/float/bool if desired
  788. settype($compareValue, $matching[$options['cast']]);
  789. settype($value, $matching[$options['cast']]);
  790. }
  791. return ($compareValue === $value);
  792. }
  793. /**
  794. * Validate range, but in a more sane way than CORE range().
  795. * This range() validation rule is inclusive regarding the borders.
  796. *
  797. * If $lower and $upper are not set, will return true if
  798. * $check is a legal finite on this platform
  799. *
  800. * @param string $check Value to check
  801. * @param float $lower Lower limit
  802. * @param float $upper Upper limit
  803. * @return bool Success
  804. */
  805. public function validateRange($data, $lower = null, $upper = null) {
  806. foreach ($data as $key => $check) {
  807. break;
  808. }
  809. if (!is_numeric($check)) {
  810. return false;
  811. }
  812. if (isset($lower) && isset($upper)) {
  813. return ($check >= $lower && $check <= $upper);
  814. }
  815. return is_finite($check);
  816. }
  817. /**
  818. * Checks a record, if it is unique - depending on other fields in this table (transfered as array)
  819. * example in model: 'rule' => array ('validateUnique', array('belongs_to_table_id','some_id','user_id')),
  820. * if all keys (of the array transferred) match a record, return false, otherwise true
  821. *
  822. * @param array $fields Other fields to depend on
  823. * TODO: add possibity of deep nested validation (User -> Comment -> CommentCategory: UNIQUE comment_id, Comment.user_id)
  824. * @param array $options
  825. * - requireDependentFields Require all dependent fields for the validation rule to return true
  826. * @return bool Success
  827. */
  828. public function validateUnique($data, $fields = array(), $options = array()) {
  829. $id = (!empty($this->data[$this->alias][$this->primaryKey]) ? $this->data[$this->alias][$this->primaryKey] : 0);
  830. if (!$id && $this->id) {
  831. $id = $this->id;
  832. }
  833. foreach ($data as $key => $value) {
  834. $fieldName = $key;
  835. $fieldValue = $value;
  836. break;
  837. }
  838. $conditions = array(
  839. $this->alias . '.' . $fieldName => $fieldValue,
  840. $this->alias . '.id !=' => $id);
  841. $fields = (array)$fields;
  842. if (!array_key_exists('allowEmpty', $fields)) {
  843. foreach ($fields as $dependingField) {
  844. if (isset($this->data[$this->alias][$dependingField])) { // add ONLY if some content is transfered (check on that first!)
  845. $conditions[$this->alias . '.' . $dependingField] = $this->data[$this->alias][$dependingField];
  846. } elseif (isset($this->data['Validation'][$dependingField])) { // add ONLY if some content is transfered (check on that first!
  847. $conditions[$this->alias . '.' . $dependingField] = $this->data['Validation'][$dependingField];
  848. } elseif (!empty($id)) {
  849. // manual query! (only possible on edit)
  850. $res = $this->find('first', array('fields' => array($this->alias . '.' . $dependingField), 'conditions' => array($this->alias . '.id' => $id)));
  851. if (!empty($res)) {
  852. $conditions[$this->alias . '.' . $dependingField] = $res[$this->alias][$dependingField];
  853. }
  854. } else {
  855. if (!empty($options['requireDependentFields'])) {
  856. trigger_error('Required field ' . $dependingField . ' for validateUnique validation not present');
  857. return false;
  858. }
  859. return true;
  860. }
  861. }
  862. }
  863. $this->recursive = -1;
  864. if (count($conditions) > 2) {
  865. $this->recursive = 0;
  866. }
  867. $options = array('fields' => array($this->alias . '.' . $this->primaryKey), 'conditions' => $conditions);
  868. $res = $this->find('first', $options);
  869. return empty($res);
  870. }
  871. /**
  872. * Checks if a url is valid AND accessable (returns false otherwise)
  873. *
  874. * @param array/string $data: full url(!) starting with http://...
  875. * @options array
  876. * - allowEmpty TRUE/FALSE (TRUE: if empty => return TRUE)
  877. * - required TRUE/FALSE (TRUE: overrides allowEmpty)
  878. * - autoComplete (default: TRUE)
  879. * - deep (default: TRUE)
  880. * @return bool Success
  881. */
  882. public function validateUrl($data, $options = array()) {
  883. if (is_array($data)) {
  884. foreach ($data as $key => $url) {
  885. break;
  886. }
  887. } else {
  888. $url = $data;
  889. }
  890. if (empty($url)) {
  891. if (!empty($options['allowEmpty']) && empty($options['required'])) {
  892. return true;
  893. }
  894. return false;
  895. }
  896. if (!isset($options['autoComplete']) || $options['autoComplete'] !== false) {
  897. $url = $this->_autoCompleteUrl($url);
  898. if (isset($key)) {
  899. $this->data[$this->alias][$key] = $url;
  900. }
  901. }
  902. if (!isset($options['strict']) || $options['strict'] !== false) {
  903. $options['strict'] = true;
  904. }
  905. // validation
  906. if (!Validation::url($url, $options['strict']) && env('REMOTE_ADDR') && env('REMOTE_ADDR') !== '127.0.0.1') {
  907. return false;
  908. }
  909. // same domain?
  910. if (!empty($options['sameDomain']) && env('HTTP_HOST')) {
  911. $is = parse_url($url, PHP_URL_HOST);
  912. $expected = env('HTTP_HOST');
  913. if (mb_strtolower($is) !== mb_strtolower($expected)) {
  914. return false;
  915. }
  916. }
  917. if (isset($options['deep']) && $options['deep'] === false) {
  918. return true;
  919. }
  920. return $this->_validUrl($url);
  921. }
  922. /**
  923. * Prepend protocol if missing
  924. *
  925. * @param string $url
  926. * @return string Url
  927. */
  928. protected function _autoCompleteUrl($url) {
  929. if (mb_strpos($url, '/') === 0) {
  930. $url = Router::url($url, true);
  931. } elseif (mb_strpos($url, '://') === false && mb_strpos($url, 'www.') === 0) {
  932. $url = 'http://' . $url;
  933. }
  934. return $url;
  935. }
  936. /**
  937. * Checks if a url is valid
  938. *
  939. * @param string url
  940. * @return bool Success
  941. */
  942. protected function _validUrl($url) {
  943. $headers = Utility::getHeaderFromUrl($url);
  944. if ($headers === false) {
  945. return false;
  946. }
  947. $headers = implode("\n", $headers);
  948. $protocol = mb_strpos($url, 'https://') === 0 ? 'HTTP' : 'HTTP';
  949. if (!preg_match('#^' . $protocol . '/.*?\s+[(200|301|302)]+\s#i', $headers)) {
  950. return false;
  951. }
  952. if (preg_match('#^' . $protocol . '/.*?\s+[(404|999)]+\s#i', $headers)) {
  953. return false;
  954. }
  955. return true;
  956. }
  957. /**
  958. * Validation of DateTime Fields (both Date and Time together)
  959. *
  960. * @param options
  961. * - dateFormat (defaults to 'ymd')
  962. * - allowEmpty
  963. * - after/before (fieldName to validate against)
  964. * - min/max (defaults to >= 1 - at least 1 second apart)
  965. * @return bool Success
  966. */
  967. public function validateDateTime($data, $options = array()) {
  968. $format = !empty($options['dateFormat']) ? $options['dateFormat'] : 'ymd';
  969. if (is_array($data)) {
  970. $value = array_shift($data);
  971. } else {
  972. $value = $data;
  973. }
  974. $dateTime = explode(' ', trim($value), 2);
  975. $date = $dateTime[0];
  976. $time = (!empty($dateTime[1]) ? $dateTime[1] : '');
  977. if (!empty($options['allowEmpty']) && (empty($date) && empty($time) || $date == DEFAULT_DATE && $time == DEFAULT_TIME || $date == DEFAULT_DATE && empty($time))) {
  978. return true;
  979. }
  980. /*
  981. if ($this->validateDate($date, $options) && $this->validateTime($time, $options)) {
  982. return true;
  983. }
  984. */
  985. if (Validation::date($date, $format) && Validation::time($time)) {
  986. // after/before?
  987. $seconds = isset($options['min']) ? $options['min'] : 1;
  988. if (!empty($options['after']) && isset($this->data[$this->alias][$options['after']])) {
  989. if (strtotime($this->data[$this->alias][$options['after']]) > strtotime($value) - $seconds) {
  990. return false;
  991. }
  992. }
  993. if (!empty($options['before']) && isset($this->data[$this->alias][$options['before']])) {
  994. if (strtotime($this->data[$this->alias][$options['before']]) < strtotime($value) + $seconds) {
  995. return false;
  996. }
  997. }
  998. return true;
  999. }
  1000. return false;
  1001. }
  1002. /**
  1003. * Validation of Date fields (as the core one is buggy!!!)
  1004. *
  1005. * @param options
  1006. * - dateFormat (defaults to 'ymd')
  1007. * - allowEmpty
  1008. * - after/before (fieldName to validate against)
  1009. * - min (defaults to 0 - equal is OK too)
  1010. * @return bool Success
  1011. */
  1012. public function validateDate($data, $options = array()) {
  1013. $format = !empty($options['format']) ? $options['format'] : 'ymd';
  1014. if (is_array($data)) {
  1015. $value = array_shift($data);
  1016. } else {
  1017. $value = $data;
  1018. }
  1019. $dateTime = explode(' ', trim($value), 2);
  1020. $date = $dateTime[0];
  1021. if (!empty($options['allowEmpty']) && (empty($date) || $date == DEFAULT_DATE)) {
  1022. return true;
  1023. }
  1024. if (Validation::date($date, $format)) {
  1025. // after/before?
  1026. $days = !empty($options['min']) ? $options['min'] : 0;
  1027. if (!empty($options['after']) && isset($this->data[$this->alias][$options['after']])) {
  1028. if ($this->data[$this->alias][$options['after']] > date(FORMAT_DB_DATE, strtotime($date) - $days * DAY)) {
  1029. return false;
  1030. }
  1031. }
  1032. if (!empty($options['before']) && isset($this->data[$this->alias][$options['before']])) {
  1033. if ($this->data[$this->alias][$options['before']] < date(FORMAT_DB_DATE, strtotime($date) + $days * DAY)) {
  1034. return false;
  1035. }
  1036. }
  1037. return true;
  1038. }
  1039. return false;
  1040. }
  1041. /**
  1042. * Validation of Time fields
  1043. *
  1044. * @param array $options
  1045. * - timeFormat (defaults to 'hms')
  1046. * - allowEmpty
  1047. * - after/before (fieldName to validate against)
  1048. * - min/max (defaults to >= 1 - at least 1 minute apart)
  1049. * @return bool Success
  1050. */
  1051. public function validateTime($data, $options = array()) {
  1052. if (is_array($data)) {
  1053. $value = array_shift($data);
  1054. } else {
  1055. $value = $data;
  1056. }
  1057. $dateTime = explode(' ', trim($value), 2);
  1058. $value = array_pop($dateTime);
  1059. if (Validation::time($value)) {
  1060. // after/before?
  1061. if (!empty($options['after']) && isset($this->data[$this->alias][$options['after']])) {
  1062. if ($this->data[$this->alias][$options['after']] >= $value) {
  1063. return false;
  1064. }
  1065. }
  1066. if (!empty($options['before']) && isset($this->data[$this->alias][$options['before']])) {
  1067. if ($this->data[$this->alias][$options['before']] <= $value) {
  1068. return false;
  1069. }
  1070. }
  1071. return true;
  1072. }
  1073. return false;
  1074. }
  1075. /**
  1076. * Validation of Date Fields (>= minDate && <= maxDate)
  1077. *
  1078. * @param options
  1079. * - min/max (TODO!!)
  1080. */
  1081. public function validateDateRange($data, $options = array()) {
  1082. }
  1083. /**
  1084. * Validation of Time Fields (>= minTime && <= maxTime)
  1085. *
  1086. * @param options
  1087. * - min/max (TODO!!)
  1088. */
  1089. public function validateTimeRange($data, $options = array()) {
  1090. }
  1091. /**
  1092. * Model validation rule for email addresses
  1093. *
  1094. * @return bool Success
  1095. */
  1096. public function validateUndisposable($data, $proceed = false) {
  1097. $email = array_shift($data);
  1098. if (empty($email)) {
  1099. return true;
  1100. }
  1101. return $this->isUndisposableEmail($email, false, $proceed);
  1102. }
  1103. /**
  1104. * NOW: can be set to work offline only (if server is down etc)
  1105. * Checks if a email is not from a garbage hoster
  1106. *
  1107. * @param string email (necessary)
  1108. * @return bool true if valid, else false
  1109. */
  1110. public function isUndisposableEmail($email, $onlineMode = false, $proceed = false) {
  1111. if (!isset($this->UndisposableEmail)) {
  1112. App::import('Vendor', 'undisposable/undisposable');
  1113. $this->UndisposableEmail = new UndisposableEmail();
  1114. }
  1115. if (!$onlineMode) {
  1116. // crashed with white screen of death otherwise... (if foreign page is 404)
  1117. $this->UndisposableEmail->useOnlineList(false);
  1118. }
  1119. if (!class_exists('Validation')) {
  1120. App::uses('Validation', 'Utility');
  1121. }
  1122. if (!Validation::email($email)) {
  1123. return false;
  1124. }
  1125. if ($this->UndisposableEmail->isUndisposableEmail($email) === false) {
  1126. // trigger log
  1127. $this->log('Disposable Email detected: ' . h($email) . ' (IP ' . env('REMOTE_ADDR') . ')', 'undisposable');
  1128. if ($proceed === true) {
  1129. return true;
  1130. }
  1131. return false;
  1132. }
  1133. return true;
  1134. }
  1135. /**
  1136. * Is blocked email?
  1137. * //TODO: move outside of MyModel?
  1138. *
  1139. * @return bool ifNotBlacklisted
  1140. */
  1141. public function validateNotBlocked($params) {
  1142. $email = array_shift($params);
  1143. if (!isset($this->Blacklist)) {
  1144. $this->Blacklist = ClassRegistry::init('Tools.Blacklist');
  1145. }
  1146. if ($this->Blacklist->isBlacklisted(Blacklist::TYPE_EMAIL, $email)) {
  1147. return false;
  1148. }
  1149. return true;
  1150. }
  1151. /**
  1152. * Set + guaranteeFields!
  1153. * Extends the core set function (only using data!!!)
  1154. *
  1155. * @param mixed $data
  1156. * @param mixed $data2 (optional)
  1157. * @param array $requiredFields Required fields
  1158. * @param array $fieldList Whitelist / Allowed fields
  1159. * @return array
  1160. */
  1161. public function set($data, $data2 = null, $requiredFields = array(), $fieldList = array()) {
  1162. if (!empty($requiredFields)) {
  1163. $data = $this->guaranteeFields($requiredFields, $data);
  1164. }
  1165. if (!empty($fieldList)) {
  1166. $data = $this->whitelist($fieldList, $data);
  1167. }
  1168. return parent::set($data, $data2);
  1169. }
  1170. /**
  1171. * @param array $fieldList
  1172. * @param array $data (optional)
  1173. * @return array
  1174. */
  1175. public function whitelist(array $fieldList, $data = null) {
  1176. $model = $this->alias;
  1177. if ($data === null) {
  1178. $data =& $this->data;
  1179. }
  1180. if (empty($data[$model])) {
  1181. return array();
  1182. }
  1183. foreach ($data[$model] as $key => $val) {
  1184. if (!in_array($key, $fieldList)) {
  1185. unset($data[$model][$key]);
  1186. }
  1187. }
  1188. return $data;
  1189. }
  1190. /**
  1191. * Instead of whitelisting this will remove all blacklisted keys.
  1192. *
  1193. * @param array $blacklist
  1194. * - array: fields to blacklist
  1195. * - boolean TRUE: removes all foreign_keys (_id)
  1196. * note: one-dimensional
  1197. * @return array
  1198. */
  1199. public function blacklist($blacklist, $data = null) {
  1200. $model = $this->alias;
  1201. if ($data === null) {
  1202. $data =& $this->data;
  1203. }
  1204. if (empty($data[$model])) {
  1205. return array();
  1206. }
  1207. if ($blacklist === true) {
  1208. foreach ($data[$model] as $key => $value) {
  1209. if (substr($key, -3, 3) === '_id') {
  1210. unset($data[$model][$key]);
  1211. }
  1212. }
  1213. return;
  1214. }
  1215. foreach ($blacklist as $key) {
  1216. if (isset($data[$model][$key])) {
  1217. unset($data[$model][$key]);
  1218. }
  1219. }
  1220. return $data;
  1221. }
  1222. /**
  1223. * Generate a whitelist, based on the current schema and a passed blacklist.
  1224. *
  1225. * @param array $blacklist
  1226. * @return array
  1227. */
  1228. public function generateWhitelistFromBlacklist(array $blacklist) {
  1229. return array_diff(array_keys($this->schema()), $blacklist);
  1230. }
  1231. /**
  1232. * Make sure required fields exists - in order to properly validate them
  1233. *
  1234. * @param array: field1, field2 - or field1, Model2.field1 etc
  1235. * @param array: data (optional, otherwise the array with the required fields will be returned)
  1236. * @return array
  1237. */
  1238. public function guaranteeFields($requiredFields, $data = null) {
  1239. $guaranteedFields = array();
  1240. foreach ($requiredFields as $column) {
  1241. if (strpos($column, '.') !== false) {
  1242. list($model, $column) = explode('.', $column, 2);
  1243. } else {
  1244. $model = $this->alias;
  1245. }
  1246. $guaranteedFields[$model][$column] = ''; # now field exists in any case!
  1247. }
  1248. if ($data === null) {
  1249. return $guaranteedFields;
  1250. }
  1251. if (!empty($guaranteedFields)) {
  1252. $data = Hash::merge($guaranteedFields, $data);
  1253. }
  1254. return $data;
  1255. }
  1256. /**
  1257. * Make certain fields a requirement for the form to validate
  1258. * (they must only be present - can still be empty, though!)
  1259. *
  1260. * @param array $fieldList
  1261. * @param bool $allowEmpty (or NULL to not touch already set elements)
  1262. * @return void
  1263. */
  1264. public function requireFields($requiredFields, $allowEmpty = null) {
  1265. if ($allowEmpty === null) {
  1266. $setAllowEmpty = true;
  1267. } else {
  1268. $setAllowEmpty = $allowEmpty;
  1269. }
  1270. foreach ($requiredFields as $column) {
  1271. if (strpos($column, '.') !== false) {
  1272. list($model, $column) = explode('.', $column, 2);
  1273. } else {
  1274. $model = $this->alias;
  1275. }
  1276. if ($model !== $this->alias) {
  1277. continue;
  1278. }
  1279. if (empty($this->validate[$column])) {
  1280. $this->validate[$column]['notEmpty'] = array('rule' => 'notEmpty', 'required' => true, 'allowEmpty' => $setAllowEmpty, 'message' => 'valErrMandatoryField');
  1281. } else {
  1282. $keys = array_keys($this->validate[$column]);
  1283. if (!in_array('rule', $keys)) {
  1284. $key = array_shift($keys);
  1285. $this->validate[$column][$key]['required'] = true;
  1286. if (!isset($this->validate[$column][$key]['allowEmpty'])) {
  1287. $this->validate[$column][$key]['allowEmpty'] = $setAllowEmpty;
  1288. }
  1289. } else {
  1290. $keys['required'] = true;
  1291. if (!isset($keys['allowEmpty'])) {
  1292. $keys['allowEmpty'] = $setAllowEmpty;
  1293. }
  1294. $this->validate[$column] = $keys;
  1295. }
  1296. }
  1297. }
  1298. }
  1299. /**
  1300. * Shortcut method to find a specific entry via primary key.
  1301. *
  1302. * Either provide the id directly:
  1303. *
  1304. * $record = $this->Model->get($id);
  1305. *
  1306. * Or use
  1307. *
  1308. * $this->Model->id = $id;
  1309. * $record = $this->Model->get();
  1310. *
  1311. * @param mixed $id
  1312. * @param array $options Options for find(). Used to be fields array/string.
  1313. * @param array $contain Deprecated - use
  1314. * @return mixed
  1315. */
  1316. public function get($id = null, $options = array(), $contain = array()) {
  1317. if (is_array($id)) {
  1318. $column = $id[0];
  1319. $value = $id[1];
  1320. } else {
  1321. $column = $this->primaryKey;
  1322. $value = $id;
  1323. if ($value === null) {
  1324. $value = $this->id;
  1325. }
  1326. }
  1327. if (!$value) {
  1328. return array();
  1329. }
  1330. // BC
  1331. $fields = null;
  1332. if (is_string($options)) {
  1333. $fields = $options;
  1334. $options = array();
  1335. }
  1336. if (!empty($options) && !array_key_exists('fields', $options) && !array_key_exists('contain', $options)) {
  1337. $fields = $options;
  1338. $options = array();
  1339. }
  1340. if ($fields === '*') {
  1341. $fields = $this->alias . '.*';
  1342. } elseif (!empty($fields)) {
  1343. foreach ((array)$fields as $row => $field) {
  1344. if (strpos($field, '.') !== false) {
  1345. continue;
  1346. }
  1347. $fields[$row] = $this->alias . '.' . $field;
  1348. }
  1349. }
  1350. $options = array(
  1351. 'conditions' => array($this->alias . '.' . $column => $value),
  1352. ) + $options;
  1353. // BC
  1354. if (!empty($fields)) {
  1355. $options['fields'] = $fields;
  1356. }
  1357. if (!empty($contain)) {
  1358. $options['contain'] = $contain;
  1359. }
  1360. return $this->find('first', $options);
  1361. }
  1362. /**
  1363. * Get all related entries that have been used so far
  1364. *
  1365. * @param string $modelName The related model
  1366. * @param string $groupField Field to group by
  1367. * @param string $type Find type
  1368. * @param array $options
  1369. * @return array
  1370. */
  1371. public function getRelatedInUse($modelName, $groupField = null, $type = 'all', $options = array()) {
  1372. if ($groupField === null) {
  1373. $groupField = $this->belongsTo[$modelName]['foreignKey'];
  1374. }
  1375. $defaults = array(
  1376. 'contain' => array($modelName),
  1377. 'group' => $groupField,
  1378. 'order' => $this->$modelName->order ? $this->$modelName->order : array($modelName . '.' . $this->$modelName->displayField => 'ASC'),
  1379. );
  1380. if ($type === 'list') {
  1381. $defaults['fields'] = array($modelName . '.' . $this->$modelName->primaryKey, $modelName . '.' . $this->$modelName->displayField);
  1382. }
  1383. $options += $defaults;
  1384. return $this->find($type, $options);
  1385. }
  1386. /**
  1387. * Get all fields that have been used so far
  1388. *
  1389. * @param string $groupField Field to group by
  1390. * @param string $type Find type
  1391. * @param array $options
  1392. * @return array
  1393. */
  1394. public function getFieldInUse($groupField, $type = 'all', $options = array()) {
  1395. $defaults = array(
  1396. 'group' => $groupField,
  1397. 'order' => array($this->alias . '.' . $this->displayField => 'ASC'),
  1398. );
  1399. if ($type === 'list') {
  1400. $defaults['fields'] = array($this->alias . '.' . $this->primaryKey, $this->alias . '.' . $this->displayField);
  1401. }
  1402. $options += $defaults;
  1403. return $this->find($type, $options);
  1404. }
  1405. /**
  1406. * Update a row with certain fields (dont use "Model" as super-key)
  1407. *
  1408. * @param int $id
  1409. * @param array $data
  1410. * @return bool|array Success
  1411. */
  1412. public function update($id, $data, $validate = false) {
  1413. $this->id = $id;
  1414. $options = array(
  1415. 'validate' => $validate,
  1416. 'fieldList' => array_keys($data)
  1417. );
  1418. return $this->save($data, $options);
  1419. }
  1420. /**
  1421. * Toggles Field (Important/Deleted/Primary etc)
  1422. *
  1423. * @param STRING fieldName
  1424. * @param int id (cleaned!)
  1425. * @return ARRAY record: [Model][values],...
  1426. */
  1427. public function toggleField($fieldName, $id) {
  1428. $record = $this->get($id, array($this->primaryKey, $fieldName));
  1429. if (!empty($record) && !empty($fieldName) && $this->hasField($fieldName)) {
  1430. $record[$this->alias][$fieldName] = ($record[$this->alias][$fieldName] == 1 ? 0 : 1);
  1431. $this->id = $id;
  1432. $this->saveField($fieldName, $record[$this->alias][$fieldName]);
  1433. }
  1434. return $record;
  1435. }
  1436. /**
  1437. * Truncate TABLE (already validated, that table exists)
  1438. *
  1439. * @param string table [default:FALSE = current model table]
  1440. * @return bool Success
  1441. */
  1442. public function truncate($table = null) {
  1443. if (empty($table)) {
  1444. $table = $this->table;
  1445. }
  1446. $db = ConnectionManager::getDataSource($this->useDbConfig);
  1447. return $db->truncate($table);
  1448. }
  1449. /**
  1450. * Recursive Dropdown Lists
  1451. * NEEDS tree behavior, NEEDS lft, rght, parent_id (!)
  1452. * //FIXME
  1453. */
  1454. public function recursiveSelect($conditions = array(), $attachTree = false, $spacer = '-- ') {
  1455. if ($attachTree) {
  1456. $this->Behaviors->load('Tree');
  1457. }
  1458. $data = $this->generateTreeList($conditions, null, null, $spacer);
  1459. return $data;
  1460. }
  1461. /**
  1462. * From http://othy.wordpress.com/2006/06/03/generatenestedlist/
  1463. * NEEDS parent_id
  1464. * //TODO refactor for 1.2
  1465. *
  1466. * @deprecated use generateTreeList instead
  1467. */
  1468. public function generateNestedList($conditions = null, $indent = '--') {
  1469. $cats = $this->find('threaded', array('conditions' => $conditions, 'fields' => array(
  1470. $this->alias . '.' . $this->primaryKey,
  1471. $this->alias . '.' . $this->displayField,
  1472. $this->alias . '.parent_id')));
  1473. return $this->_generateNestedList($cats, $indent);
  1474. }
  1475. /**
  1476. * From http://othy.wordpress.com/2006/06/03/generatenestedlist/
  1477. *
  1478. * @deprecated use generateTreeList instead
  1479. */
  1480. public function _generateNestedList($cats, $indent = '--', $level = 0) {
  1481. static $list = array();
  1482. $c = count($cats);
  1483. for ($i = 0; $i < $c; $i++) {
  1484. $list[$cats[$i][$this->alias][$this->primaryKey]] = str_repeat($indent, $level) . $cats[$i][$this->alias][$this->displayField];
  1485. if (!empty($cats[$i]['children'])) {
  1486. $this->_generateNestedList($cats[$i]['children'], $indent, $level + 1);
  1487. }
  1488. }
  1489. return $list;
  1490. }
  1491. }