MyModel.php 46 KB

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