MyModel.php 49 KB

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