MyModel.php 49 KB

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