MyModel.php 48 KB

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