MyModel.php 48 KB

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