MyModel.php 49 KB

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