MyModel.php 49 KB

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