MyModel.php 41 KB

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