MyModel.php 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683
  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 o 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();
  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 other fields
  856. * TODO: add possibity of deep nested validation (User -> Comment -> CommentCategory: UNIQUE comment_id, Comment.user_id)
  857. * @return bool Success
  858. * 2010-01-30 ms
  859. */
  860. public function validateUnique($data, $fields = array(), $options = array()) {
  861. $id = (!empty($this->data[$this->alias]['id']) ? $this->data[$this->alias]['id'] : 0);
  862. if (!$id && $this->id) {
  863. $id = $this->id;
  864. }
  865. foreach ($data as $key => $value) {
  866. $fieldName = $key;
  867. $fieldValue = $value; // equals: $this->data[$this->alias][$fieldName]
  868. }
  869. $conditions = array($this->alias . '.' . $fieldName => $fieldValue, // Model.field => $this->data['Model']['field']
  870. $this->alias . '.id !=' => $id);
  871. # careful, if fields is not manually filled, the options will be the second param!!! big problem...
  872. $fields = (array)$fields;
  873. if (!array_key_exists('allowEmpty', $fields)) {
  874. foreach ((array)$fields as $dependingField) {
  875. if (isset($this->data[$this->alias][$dependingField])) { // add ONLY if some content is transfered (check on that first!)
  876. $conditions[$this->alias . '.' . $dependingField] = $this->data[$this->alias][$dependingField];
  877. } elseif (isset($this->data['Validation'][$dependingField])) { // add ONLY if some content is transfered (check on that first!
  878. $conditions[$this->alias . '.' . $dependingField] = $this->data['Validation'][$dependingField];
  879. } elseif (!empty($id)) {
  880. # manual query! (only possible on edit)
  881. $res = $this->find('first', array('fields' => array($this->alias.'.'.$dependingField), 'conditions' => array($this->alias.'.id' => $id)));
  882. if (!empty($res)) {
  883. $conditions[$this->alias . '.' . $dependingField] = $res[$this->alias][$dependingField];
  884. }
  885. }
  886. }
  887. }
  888. $this->recursive = -1;
  889. if (count($conditions) > 2) {
  890. $this->recursive = 0;
  891. }
  892. $res = $this->find('first', array('fields' => array($this->alias . '.id'), 'conditions' => $conditions));
  893. if (!empty($res)) {
  894. return false;
  895. }
  896. return true;
  897. }
  898. /**
  899. * @param array $data
  900. * @param array $options
  901. * - scope (array of other fields as scope - isUnique dependent on other fields of the table)
  902. * - batch (defaults to true, remembers previous values in order to validate batch imports)
  903. * example in model: 'rule' => array ('validateUniqueExt', array('scope'=>array('belongs_to_table_id','some_id','user_id'))),
  904. * http://groups.google.com/group/cake-php/browse_thread/thread/880ee963456739ec
  905. * //TODO: test!!!
  906. * @return bool Success
  907. * @deprecated in favor of validateUnique?
  908. * 2011-03-27 ms
  909. */
  910. public function validateUniqueExt($data, $options = array()) {
  911. foreach ($data as $key => $value) {
  912. $fieldName = $key;
  913. $fieldValue = $value;
  914. }
  915. $defaults = array('batch' => true, 'scope' => array());
  916. $options = array_merge($defaults, $options);
  917. # for batch
  918. if ($options['batch'] !== false && !empty($this->batchRecords)) {
  919. if (array_key_exists($value, $this->batchRecords[$fieldName])) {
  920. return $options['scope'] === $this->batchRecords[$fieldName][$value];
  921. }
  922. }
  923. # continue with validation
  924. if (!$this->validateUnique($data, $options['scope'])) {
  925. return false;
  926. }
  927. # for batch
  928. if ($options['batch'] !== false) {
  929. if (!isset($this->batchRecords)) {
  930. $this->batchRecords = array();
  931. }
  932. $this->batchRecords[$fieldName][$value] = $scope;
  933. }
  934. return true;
  935. }
  936. /**
  937. * Checks if a url is valid AND accessable (returns false otherwise)
  938. *
  939. * @param array/string $data: full url(!) starting with http://...
  940. * @options array
  941. * - allowEmpty TRUE/FALSE (TRUE: if empty => return TRUE)
  942. * - required TRUE/FALSE (TRUE: overrides allowEmpty)
  943. * - autoComplete (default: TRUE)
  944. * - deep (default: TRUE)
  945. * @return bool Success
  946. * 2010-10-18 ms
  947. */
  948. public function validateUrl($data, $options = array()) {
  949. if (is_array($data)) {
  950. $url = array_shift($data);
  951. } else {
  952. $url = $data;
  953. }
  954. if (empty($url)) {
  955. if (!empty($options['allowEmpty']) && empty($options['required'])) {
  956. return true;
  957. }
  958. return false;
  959. }
  960. if (!isset($options['autoComplete']) || $options['autoComplete'] !== false) {
  961. $url = $this->_autoCompleteUrl($url);
  962. }
  963. if (!isset($options['strict']) || $options['strict'] !== false) {
  964. $options['strict'] = true;
  965. }
  966. # validation
  967. if (!Validation::url($url, $options['strict']) && env('REMOTE_ADDR') !== '127.0.0.1') {
  968. return false;
  969. }
  970. # same domain?
  971. if (!empty($options['sameDomain']) && !empty($_SERVER['HTTP_HOST'])) {
  972. $is = parse_url($url, PHP_URL_HOST);
  973. $expected = $_SERVER['HTTP_HOST'];
  974. if (mb_strtolower($is) !== mb_strtolower($expected)) {
  975. return false;
  976. }
  977. }
  978. if (isset($options['deep']) && $options['deep'] === false) {
  979. return true;
  980. }
  981. return $this->_validUrl($url);
  982. }
  983. /**
  984. * prepend protocol if missing
  985. *
  986. * @param string $url
  987. * @return string Url
  988. * 2009-02-27 ms
  989. */
  990. protected function _autoCompleteUrl($url) {
  991. if (mb_strpos($url, '/') === 0) {
  992. $url = Router::url($url, true);
  993. } elseif (mb_strpos($url, '://') === false && mb_strpos($url, 'www.') === 0) {
  994. $url = 'http://' . $url;
  995. }
  996. return $url;
  997. }
  998. /**
  999. * checks if a url is valid
  1000. *
  1001. * @param string url
  1002. * @return bool Success
  1003. * 2009-02-27 ms
  1004. */
  1005. protected function _validUrl($url) {
  1006. $headers = Utility::getHeaderFromUrl($url);
  1007. if ($headers === false) {
  1008. return false;
  1009. }
  1010. $headers = implode("\n", $headers);
  1011. $protocol = mb_strpos($url, 'https://') === 0 ? 'HTTP' : 'HTTP';
  1012. return ((bool)preg_match('#^'.$protocol.'/.*\s+[(200|301|302)]+\s#i', $headers) && !(bool)preg_match('#^'.$protocol.'/.*\s+[(404|999)]+\s#i', $headers));
  1013. }
  1014. /**
  1015. * Validation of DateTime Fields (both Date and Time together)
  1016. *
  1017. * @param options
  1018. * - dateFormat (defaults to 'ymd')
  1019. * - allowEmpty
  1020. * - after/before (fieldName to validate against)
  1021. * - min/max (defaults to >= 1 - at least 1 minute apart)
  1022. * @return bool Success
  1023. * 2011-03-02 ms
  1024. */
  1025. public function validateDateTime($data, $options = array()) {
  1026. $format = !empty($options['dateFormat']) ? $options['dateFormat'] : 'ymd';
  1027. if (is_array($data)) {
  1028. $value = array_shift($data);
  1029. } else {
  1030. $value = $data;
  1031. }
  1032. $dateTime = explode(' ', trim($value), 2);
  1033. $date = $dateTime[0];
  1034. $time = (!empty($dateTime[1]) ? $dateTime[1] : '');
  1035. if (!empty($options['allowEmpty']) && (empty($date) && empty($time) || $date == DEFAULT_DATE && $time == DEFAULT_TIME || $date == DEFAULT_DATE && empty($time))) {
  1036. return true;
  1037. }
  1038. /*
  1039. if ($this->validateDate($date, $options) && $this->validateTime($time, $options)) {
  1040. return true;
  1041. }
  1042. */
  1043. if (Validation::date($date, $format) && Validation::time($time)) {
  1044. # after/before?
  1045. $minutes = isset($options['min']) ? $options['min'] : 1;
  1046. if (!empty($options['after']) && isset($this->data[$this->alias][$options['after']])) {
  1047. if (strtotime($this->data[$this->alias][$options['after']]) > strtotime($value) - $minutes) {
  1048. return false;
  1049. }
  1050. }
  1051. if (!empty($options['before']) && isset($this->data[$this->alias][$options['before']])) {
  1052. if (strtotime($this->data[$this->alias][$options['before']]) < strtotime($value) + $minutes) {
  1053. return false;
  1054. }
  1055. }
  1056. return true;
  1057. }
  1058. return false;
  1059. }
  1060. /**
  1061. * Validation of Date fields (as the core one is buggy!!!)
  1062. *
  1063. * @param options
  1064. * - dateFormat (defaults to 'ymd')
  1065. * - allowEmpty
  1066. * - after/before (fieldName to validate against)
  1067. * - min (defaults to 0 - equal is OK too)
  1068. * @return bool Success
  1069. * 2011-03-02 ms
  1070. */
  1071. public function validateDate($data, $options = array()) {
  1072. $format = !empty($options['format']) ? $options['format'] : 'ymd';
  1073. if (is_array($data)) {
  1074. $value = array_shift($data);
  1075. } else {
  1076. $value = $data;
  1077. }
  1078. $dateTime = explode(' ', trim($value), 2);
  1079. $date = $dateTime[0];
  1080. if (!empty($options['allowEmpty']) && (empty($date) || $date == DEFAULT_DATE)) {
  1081. return true;
  1082. }
  1083. if (Validation::date($date, $format)) {
  1084. # after/before?
  1085. $days = !empty($options['min']) ? $options['min'] : 0;
  1086. if (!empty($options['after']) && isset($this->data[$this->alias][$options['after']])) {
  1087. if ($this->data[$this->alias][$options['after']] > date(FORMAT_DB_DATE, strtotime($date) - $days * DAY)) {
  1088. return false;
  1089. }
  1090. }
  1091. if (!empty($options['before']) && isset($this->data[$this->alias][$options['before']])) {
  1092. if ($this->data[$this->alias][$options['before']] < date(FORMAT_DB_DATE, strtotime($date) + $days * DAY)) {
  1093. return false;
  1094. }
  1095. }
  1096. return true;
  1097. }
  1098. return false;
  1099. }
  1100. /**
  1101. * Validation of Time fields
  1102. *
  1103. * @param array $options
  1104. * - timeFormat (defaults to 'hms')
  1105. * - allowEmpty
  1106. * - after/before (fieldName to validate against)
  1107. * - min/max (defaults to >= 1 - at least 1 minute apart)
  1108. * @return bool Success
  1109. * 2011-03-02 ms
  1110. */
  1111. public function validateTime($data, $options = array()) {
  1112. if (is_array($data)) {
  1113. $value = array_shift($data);
  1114. } else {
  1115. $value = $data;
  1116. }
  1117. $dateTime = explode(' ', trim($value), 2);
  1118. $value = array_pop($dateTime);
  1119. if (Validation::time($value)) {
  1120. # after/before?
  1121. if (!empty($options['after']) && isset($this->data[$this->alias][$options['after']])) {
  1122. if ($this->data[$this->alias][$options['after']] >= $value) {
  1123. return false;
  1124. }
  1125. }
  1126. if (!empty($options['before']) && isset($this->data[$this->alias][$options['before']])) {
  1127. if ($this->data[$this->alias][$options['before']] <= $value) {
  1128. return false;
  1129. }
  1130. }
  1131. return true;
  1132. }
  1133. return false;
  1134. }
  1135. //TODO
  1136. /**
  1137. * Validation of Date Fields (>= minDate && <= maxDate)
  1138. * @param options
  1139. * - min/max (TODO!!)
  1140. * 2010-01-20 ms
  1141. */
  1142. public function validateDateRange($data, $options = array()) {
  1143. }
  1144. //TODO
  1145. /**
  1146. * Validation of Time Fields (>= minTime && <= maxTime)
  1147. * @param options
  1148. * - min/max (TODO!!)
  1149. * 2010-01-20 ms
  1150. */
  1151. public function validateTimeRange($data, $options = array()) {
  1152. }
  1153. /**
  1154. * model validation rule for email addresses
  1155. *
  1156. * @return bool Success
  1157. * 2010-01-14 ms
  1158. */
  1159. public function validateUndisposable($data, $proceed = false) {
  1160. $email = array_shift($data);
  1161. if (empty($email)) {
  1162. return true;
  1163. }
  1164. return $this->isUndisposableEmail($email, false, $proceed);
  1165. }
  1166. /**
  1167. * NOW: can be set to work offline only (if server is down etc)
  1168. * Checks if a email is not from a garbige hoster
  1169. *
  1170. * @param string email (necessary)
  1171. * @return boolean true if valid, else false
  1172. * 2009-03-09 ms
  1173. */
  1174. public function isUndisposableEmail($email, $onlineMode = false, $proceed = false) {
  1175. if (!isset($this->UndisposableEmail)) {
  1176. App::import('Vendor', 'undisposable/undisposable');
  1177. $this->UndisposableEmail = new UndisposableEmail();
  1178. }
  1179. if (!$onlineMode) {
  1180. # crashed with white screen of death otherwise... (if foreign page is 404)
  1181. $this->UndisposableEmail->useOnlineList(false);
  1182. }
  1183. if (!class_exists('Validation')) {
  1184. App::uses('Validation', 'Utility');
  1185. }
  1186. if (!Validation::email($email)) {
  1187. return false;
  1188. }
  1189. if ($this->UndisposableEmail->isUndisposableEmail($email) === false) {
  1190. # trigger log
  1191. $this->log('Disposable Email detected: ' . h($email).' (IP '.env('REMOTE_ADDR').')', 'undisposable');
  1192. if ($proceed === true) {
  1193. return true;
  1194. }
  1195. return false;
  1196. }
  1197. return true;
  1198. }
  1199. /**
  1200. * Is blocked email?
  1201. * //TODO: move outside of MyModel?
  1202. *
  1203. * @return bool $ifNotBlacklisted
  1204. * 2009-12-22 ms
  1205. */
  1206. public function validateNotBlocked($params) {
  1207. $email = array_shift($params);
  1208. if (!isset($this->Blacklist)) {
  1209. //App::uses('Blacklist', 'Tools.Model'
  1210. $this->Blacklist = ClassRegistry::init('Tools.Blacklist');
  1211. }
  1212. if ($this->Blacklist->isBlacklisted(Blacklist::TYPE_EMAIL, $email)) {
  1213. return false;
  1214. }
  1215. return true;
  1216. }
  1217. /** General Model Functions **/
  1218. /**
  1219. * CAREFUL: use LIMIT due to Starker Serverlastigkeit! or CACHE it!
  1220. *
  1221. * e.g.: 'ORDER BY ".$this->umlautsOrderFix('User.nic')." ASC'
  1222. *
  1223. * @param string variable (to be correctly ordered)
  1224. * @deprecated
  1225. */
  1226. public function umlautsOrderFix($var) {
  1227. return "REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(".$var.", 'Ä', 'Ae'), 'Ö', 'Oe'), 'Ü', 'Ue'), 'ä', 'ae'), 'ö', 'oe'), 'ü','ue'), 'ß', 'ss')";
  1228. }
  1229. /**
  1230. * set + guaranteeFields!
  1231. * Extends the core set function (only using data!!!)
  1232. *
  1233. * @param mixed $data
  1234. * @param mixed $data2 (optional)
  1235. * @param array $requiredFields Required fields
  1236. * @param array $fieldList Whitelist / Allowed fields
  1237. * @return array
  1238. * 2010-03-11 ms
  1239. */
  1240. public function set($data, $data2 = null, $requiredFields = array(), $fieldList = array()) {
  1241. if (!empty($requiredFields)) {
  1242. $data = $this->guaranteeFields($requiredFields, $data);
  1243. }
  1244. if (!empty($fieldList)) {
  1245. $data = $this->whitelist($fieldList, $data);
  1246. }
  1247. return parent::set($data, $data2);
  1248. }
  1249. /**
  1250. * @param array $fieldList
  1251. * @param array $data (optional)
  1252. * @return array
  1253. * 2011-06-01 ms
  1254. */
  1255. public function whitelist($fieldList, $data = null) {
  1256. $model = $this->alias;
  1257. if ($data === null) {
  1258. $data = $this->data;
  1259. }
  1260. foreach ($data[$model] as $key => $val) {
  1261. if (!in_array($key, $fieldList)) {
  1262. unset($data[$model][$key]);
  1263. }
  1264. }
  1265. return $data;
  1266. }
  1267. /**
  1268. * make sure required fields exists - in order to properly validate them
  1269. * @param array: field1, field2 - or field1, Model2.field1 etc
  1270. * @param array: data (optional, otherwise the array with the required fields will be returned)
  1271. * @return array
  1272. * 2010-03-11 ms
  1273. */
  1274. public function guaranteeFields($requiredFields, $data = null) {
  1275. $guaranteedFields = array();
  1276. foreach ($requiredFields as $column) {
  1277. if (strpos($column, '.') !== false) {
  1278. list($model, $column) = explode('.', $column, 2);
  1279. } else {
  1280. $model = $this->alias;
  1281. }
  1282. $guaranteedFields[$model][$column] = ''; # now field exists in any case!
  1283. }
  1284. if ($data === null) {
  1285. return $guaranteedFields;
  1286. }
  1287. if (!empty($guaranteedFields)) {
  1288. $data = Set::merge($guaranteedFields, $data);
  1289. }
  1290. return $data;
  1291. }
  1292. /**
  1293. * make certain fields a requirement for the form to validate
  1294. * (they must only be present - can still be empty, though!)
  1295. *
  1296. * @param array $fieldList
  1297. * @param bool $allowEmpty (or NULL to not touch already set elements)
  1298. * @return void
  1299. * 2012-02-20 ms
  1300. */
  1301. public function requireFields($requiredFields, $allowEmpty = null) {
  1302. if ($allowEmpty === null) {
  1303. $setAllowEmpty = true;
  1304. } else {
  1305. $setAllowEmpty = $allowEmpty;
  1306. }
  1307. foreach ($requiredFields as $column) {
  1308. if (strpos($column, '.') !== false) {
  1309. list($model, $column) = explode('.', $column, 2);
  1310. } else {
  1311. $model = $this->alias;
  1312. }
  1313. if ($model !== $this->alias) {
  1314. continue;
  1315. }
  1316. if (empty($this->validate[$column])) {
  1317. $this->validate[$column]['notEmpty'] = array('rule' => 'notEmpty', 'required' => true, 'allowEmpty' => $setAllowEmpty, 'message' => 'valErrMandatoryField');
  1318. } else {
  1319. $keys = array_keys($this->validate[$column]);
  1320. if (!in_array('rule', $keys)) {
  1321. $key = array_shift($keys);
  1322. $this->validate[$column][$key]['required'] = true;
  1323. if (!isset($this->validate[$column][$key]['allowEmpty'])) {
  1324. $this->validate[$column][$key]['allowEmpty'] = $setAllowEmpty;
  1325. }
  1326. } else {
  1327. $keys['required'] = true;
  1328. if (!isset($keys['allowEmpty'])) {
  1329. $keys['allowEmpty'] = $setAllowEmpty;
  1330. }
  1331. $this->validate[$column] = $keys;
  1332. }
  1333. }
  1334. }
  1335. }
  1336. /**
  1337. * instead of whitelisting
  1338. * @param array $blackList
  1339. * - array: fields to blacklist
  1340. * - boolean TRUE: removes all foreign_keys (_id and _key)
  1341. * note: one-dimensional
  1342. * @return array
  1343. * 2009-06-19 ms
  1344. */
  1345. public function blacklist($blackList = array()) {
  1346. if ($blackList === true) {
  1347. //TODO
  1348. }
  1349. return array_diff(array_keys($this->schema()), (array)$blackList);
  1350. }
  1351. /**
  1352. * Shortcut method to find a specific entry via primary key
  1353. *
  1354. * @param mixed $id
  1355. * @param string|array $fields
  1356. * @param array $contain
  1357. * @return mixed
  1358. * 2009-11-14 ms
  1359. */
  1360. public function get($id, $fields = array(), $contain = array()) {
  1361. if (is_array($id)) {
  1362. $column = $id[0];
  1363. $value = $id[1];
  1364. } else {
  1365. $column = 'id';
  1366. $value = $id;
  1367. }
  1368. if ($fields === '*') {
  1369. $fields = $this->alias . '.*';
  1370. } elseif (!empty($fields)) {
  1371. foreach ($fields as $row => $field) {
  1372. if (strpos($field, '.') !== false) {
  1373. continue;
  1374. }
  1375. $fields[$row] = $this->alias . '.' . $field;
  1376. }
  1377. }
  1378. $options = array(
  1379. 'conditions' => array($this->alias . '.' . $column => $value),
  1380. );
  1381. if (!empty($fields)) {
  1382. $options['fields'] = $fields;
  1383. }
  1384. if (!empty($contain)) {
  1385. $options['contain'] = $contain;
  1386. }
  1387. return $this->find('first', $options);
  1388. }
  1389. /**
  1390. * Get all related entries that have been used so far
  1391. *
  1392. * @param string $modelName The related model
  1393. * @param string $groupField Field to group by
  1394. * @param string $type Find type
  1395. * @param array $options
  1396. * @return array
  1397. */
  1398. public function getRelatedInUse($modelName, $groupField, $type = 'all', $options = array()) {
  1399. $defaults = array(
  1400. 'contain' => array($modelName),
  1401. 'group' => $groupField,
  1402. 'order' => $this->$modelName->order ? $this->$modelName->order : array($modelName . '.' . $this->$modelName->displayField => 'ASC'),
  1403. );
  1404. if ($type === 'list') {
  1405. $defaults['fields'] = array($modelName . '.' . $this->$modelName->primaryKey, $modelName . '.' . $this->$modelName->displayField);
  1406. }
  1407. $options += $defaults;
  1408. return $this->find($type, $options);
  1409. }
  1410. /**
  1411. * Get all fields that have been used so far
  1412. *
  1413. * @param string $groupField Field to group by
  1414. * @param string $type Find type
  1415. * @param array $options
  1416. * @return array
  1417. */
  1418. public function getFieldInUse($groupField, $type = 'all', $options = array()) {
  1419. $defaults = array(
  1420. 'group' => $groupField,
  1421. 'order' => array($this->alias . '.' . $this->displayField => 'ASC'),
  1422. );
  1423. if ($type === 'list') {
  1424. $defaults['fields'] = array($this->alias . '.' . $this->primaryKey, $this->alias . '.' . $this->displayField);
  1425. }
  1426. $options += $defaults;
  1427. return $this->find($type, $options);
  1428. }
  1429. /**
  1430. * Update a row with certain fields (dont use "Model" as super-key)
  1431. * @param int $id
  1432. * @param array $data
  1433. * @return bool|array Success
  1434. * 2012-11-20 ms
  1435. */
  1436. public function update($id, $data, $validate = false) {
  1437. $this->id = $id;
  1438. return $this->save($data, $validate, array_keys($data));
  1439. }
  1440. /**
  1441. * Automagic increasing of a field with e.g.:
  1442. * $this->id = ID; $this->inc('weight',3);
  1443. *
  1444. * @deprecated use atomic updateAll() instead!
  1445. * @param string fieldname
  1446. * @param int factor: defaults to 1 (could be negative as well - if field is signed and can be < 0)
  1447. */
  1448. public function inc($field, $factor = 1) {
  1449. $value = Set::extract($this->read($field), $this->alias . '.' . $field);
  1450. $value += $factor;
  1451. return $this->saveField($field, $value);
  1452. }
  1453. /**
  1454. * Toggles Field (Important/Deleted/Primary etc)
  1455. * @param STRING fieldName
  1456. * @param INT id (cleaned!)
  1457. * @return ARRAY record: [Model][values],...
  1458. * AJAX?
  1459. * 2008-11-06 ms
  1460. */
  1461. public function toggleField($fieldName, $id) {
  1462. $record = $this->get($id, array('id', $fieldName));
  1463. if (!empty($record) && !empty($fieldName) && $this->hasField($fieldName)) {
  1464. $record[$this->alias][$fieldName] = ($record[$this->alias][$fieldName] == 1 ? 0 : 1);
  1465. $this->id = $id;
  1466. $this->saveField($fieldName, $record[$this->alias][$fieldName]);
  1467. }
  1468. return $record;
  1469. }
  1470. /**
  1471. * truncate TABLE (already validated, that table exists)
  1472. * @param string table [default:FALSE = current model table]
  1473. * @return bool Success
  1474. */
  1475. public function truncate($table = null) {
  1476. if (empty($table)) {
  1477. $table = $this->table;
  1478. }
  1479. $db = ConnectionManager::getDataSource($this->useDbConfig);
  1480. return $db->truncate($table);
  1481. }
  1482. /** Deep Lists **/
  1483. /**
  1484. * recursive Dropdown Lists
  1485. * NEEDS tree behavior, NEEDS lft, rght, parent_id (!)
  1486. * //FIXME
  1487. * 2008-01-02 ms
  1488. */
  1489. public function recursiveSelect($conditions = array(), $attachTree = false, $spacer = '-- ') {
  1490. if ($attachTree) {
  1491. $this->Behaviors->load('Tree');
  1492. }
  1493. $data = $this->generateTreeList($conditions, null, null, $spacer);
  1494. return $data;
  1495. }
  1496. /**
  1497. * from http://othy.wordpress.com/2006/06/03/generatenestedlist/
  1498. * NEEDS parent_id
  1499. * //TODO refactor for 1.2
  1500. *
  1501. * @deprecated use generateTreeList instead
  1502. * 2009-08-12 ms
  1503. */
  1504. public function generateNestedList($conditions = null, $indent = '--') {
  1505. $cats = $this->find('threaded', array('conditions' => $conditions, 'fields' => array(
  1506. $this->name . '.id',
  1507. $this->name . '.name',
  1508. $this->name . '.parent_id')));
  1509. $glist = $this->_generateNestedList($cats, $indent);
  1510. return $glist;
  1511. }
  1512. /**
  1513. * from http://othy.wordpress.com/2006/06/03/generatenestedlist/
  1514. * @deprecated use generateTreeList instead
  1515. * 2009-08-12 ms
  1516. */
  1517. public function _generateNestedList($cats, $indent = '--', $level = 0) {
  1518. static $list = array();
  1519. $c = count($cats);
  1520. for ($i = 0; $i < $c; $i++) {
  1521. $list[$cats[$i][$this->alias]['id']] = str_repeat($indent, $level) . $cats[$i][$this->alias][$this->displayField];
  1522. if (!empty($cats[$i]['children'])) {
  1523. $this->_generateNestedList($cats[$i]['children'], $indent, $level + 1);
  1524. }
  1525. }
  1526. return $list;
  1527. }
  1528. }