PageRenderTime 38ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/app_controller.php

https://github.com/felixding/LonelyThinker
PHP | 423 lines | 200 code | 67 blank | 156 comment | 37 complexity | 52ed92419008dca25d1bf7bcf52660a4 MD5 | raw file
Possible License(s): GPL-2.0
  1. <?php
  2. /* SVN FILE: $Id: app_controller.php 41 2009-08-04 13:12:50Z $ */
  3. /**
  4. * Short description for file.
  5. *
  6. * Long description for file
  7. *
  8. * PHP versions 5
  9. *
  10. * Licensed under The BSD License
  11. * Redistributions of files must retain the above copyright notice.
  12. *
  13. * @filesource
  14. * @copyright Copyright 2007-2009, Felix Ding (http://dingyu.me)
  15. * @link http://lonelythinker.org Project LonelyThinker
  16. * @package LonelyThinker
  17. * @author $LastChangedBy: $
  18. * @version $Revision: 41 $
  19. * @modifiedby $LastChangedBy: $
  20. * @lastmodified $Date: 2009-08-04 21:12:50 +0800 (Tue, 04 Aug 2009) $
  21. * @license http://www.opensource.org/licenses/bsd-license.php The BSD License
  22. */
  23. class AppController extends Controller
  24. {
  25. var $components = array('othAuth', 'VisitorSense', 'RequestHandler', 'Security');
  26. var $helpers = array('Html', 'Form', 'Javascript', 'othAuth', 'Widget', 'Paginator', 'Text', 'Asset');
  27. var $othAuthRestrictions = array('add','edit','delete');
  28. var $uses = array('Setting');
  29. /**
  30. * callbacks
  31. */
  32. public function beforeFilter()
  33. {
  34. //user auth
  35. $auth_conf = array(
  36. 'mode' => 'oth',
  37. 'login_page' => '/users/login',
  38. 'logout_page' => '/users/logout',
  39. 'access_page' => '/posts/add',
  40. 'hashkey' => 'MySEcEeTHaSHKeYz1',
  41. 'noaccess_page' => '/users/noaccess',
  42. 'strict_gid_check' => false
  43. );
  44. $this->othAuth->controller = &$this;
  45. $this->othAuth->init($auth_conf);
  46. $this->othAuth->check();
  47. //make settings below are loaded only once
  48. //if(!Configure::read('LT.initialized'))
  49. //{
  50. //load config
  51. $this->Setting->get();
  52. //launch VisitorSense
  53. $this->othAuth->controller = &$this;
  54. $this->VisitorSense->init();
  55. $this->VisitorSense->launch();
  56. Configure::write('LT.initialized', true);
  57. //}
  58. //security blackhole
  59. //$this->Security->blackHoleCallback = 'denied';
  60. //admin specific settings
  61. if($this->othAuth->sessionValid())
  62. {
  63. //layout
  64. $this->layout = 'admin';
  65. }
  66. }
  67. public function beforeRender()
  68. {
  69. //render enums
  70. //$this->renderEnums();
  71. //set the referrer, many features need it
  72. $this->set('referrer', Router::url($this->referer(), true));
  73. //page title seperator
  74. Configure::write('pageTitleSeperator', ' - ');
  75. //don't mess up ajax
  76. if($this->RequestHandler->isAjax()) Configure::write('debug', 0);
  77. }
  78. /**
  79. * blackhole for CSRF or other attacks
  80. *
  81. * I don't want to waste time in designing a nice view for those attackers
  82. */
  83. public function denied()
  84. {
  85. die('Access denied!');
  86. }
  87. /**
  88. * throws the invalid fields
  89. *
  90. * @return Boolean true if the data validates
  91. * @date 2009-04-21
  92. */
  93. public function validates()
  94. {
  95. if(!$this->{$this->modelClass}->validates())
  96. {
  97. //$this->{$this->modelClass}->invalidFields = $this->{$this->modelClass}->invalidFields();
  98. $this->set('invalidFields', $this->{$this->modelClass}->invalidFields());
  99. return false;
  100. }
  101. return true;
  102. }
  103. /*
  104. * public function for adding an item
  105. *
  106. * @date 2009-04-23
  107. */
  108. public function add()
  109. {
  110. if(!empty($this->data))
  111. {
  112. if($this->{$this->modelClass}->save($this->data))
  113. {
  114. $this->redirect('/'.Inflector::pluralize(Inflector::underscore($this->modelClass)).'/');
  115. }
  116. else
  117. {
  118. $this->set(Inflector::pluralize(Inflector::underscore($this->modelClass)), $this->data);
  119. }
  120. if($this->RequestHandler->isAjax()) $this->renderView('saved');
  121. }
  122. }
  123. /*
  124. * public function for editing an item model
  125. *
  126. * @date 2009-04-23
  127. */
  128. public function edit($id = null)
  129. {
  130. //does the post exist?
  131. if(!empty($this->data)) $this->{$this->modelClass}->id = $this->data[$this->modelClass]['id'];
  132. else $this->{$this->modelClass}->id = $id;
  133. if(!$item = $this->{$this->modelClass}->read()) $this->cakeError('error404');
  134. if(!empty($this->data))
  135. {
  136. $item = $this->data;
  137. if($this->{$this->modelClass}->save($this->data))
  138. {
  139. $this->redirect('/'.Inflector::pluralize(Inflector::underscore($this->modelClass)));
  140. return true;
  141. }
  142. }
  143. $this->set(lcfirst($this->modelClass), $item);
  144. $this->render('add');
  145. }
  146. /**
  147. * public function for showing the model's index page
  148. *
  149. * @date 2009-04-23
  150. */
  151. public function index()
  152. {
  153. $this->{$this->modelClass}->recursive = -1;
  154. $data = $this->paginate($this->modelClass);
  155. $this->set(Inflector::pluralize(lcfirst($this->modelClass)) , $data);
  156. }
  157. /**
  158. * public function for deleting an item
  159. *
  160. * @date 2009-02-22
  161. */
  162. public function delete()
  163. {
  164. //if submitted?
  165. if(!empty($this->data))
  166. {
  167. $this->{$this->modelClass}->id = $this->data[$this->modelClass]['id'];
  168. if(!$this->{$this->modelClass}->hasAny(array('id'=>$this->{$this->modelClass}->id)))
  169. {
  170. $this->renderError('error404');
  171. return;
  172. }
  173. $this->{$this->modelClass}->del($this->{$this->modelClass}->id);
  174. $this->renderView('deleted', '/generic/delete/');
  175. return;
  176. }
  177. $this->renderView('delete', '/generic/delete/');
  178. }
  179. /**
  180. * get cache's key
  181. *
  182. * @param $key the unique key for each cache file
  183. * @todo check if a file with same name exists
  184. * @date 2009-03-13
  185. */
  186. private function getCacheKey($key)
  187. {
  188. if(empty($key)) return false;
  189. //get file name
  190. $filename = ereg_replace('[/-]', '_', $this->here).'_'.$key;
  191. $filename = substr($filename, 1, strlen($filename));
  192. //return the filename/key
  193. return $filename;
  194. }
  195. /**
  196. * cache model data
  197. *
  198. * @param $data the data to cache
  199. * @param $key the unique key for each cache file
  200. * @todo check if a file with same name exists
  201. * @date 2009-03-13
  202. */
  203. public function writeCache($key, $data)
  204. {
  205. if(empty($key) || empty($data)) return false;
  206. //get file name
  207. $filename = $this->getCacheKey($key);
  208. Cache::write($filename, $data);
  209. //return the filename/key
  210. return $filename;
  211. }
  212. /**
  213. * read cache model data
  214. *
  215. * @param $key the unique key for each cache file
  216. * @todo check if a file with same name exists
  217. * @date 2009-03-13
  218. */
  219. public function readCache($key)
  220. {
  221. if(empty($key)) return false;
  222. //get file name
  223. $filename = $this->getCacheKey($key);
  224. //return the data
  225. return Cache::read($filename);
  226. }
  227. /**
  228. * render the given view for either non-ajax request or ajax request
  229. *
  230. * @param $template String the name of the template
  231. * @date 2009-03-06
  232. */
  233. public function renderView($template = null, $path = null)
  234. {
  235. if(!$template) return false;
  236. $path = isset($path) ? $path : $this->params['action'] . '/';
  237. if($this->RequestHandler->isAjax()) $this->render($path.'json/'.$template, 'ajax');
  238. else $this->render($path.'html/'.$template);
  239. }
  240. /**
  241. * render an error view for either non-ajax request or ajax request
  242. *
  243. * @param $template String the name of the template
  244. * @date 2009-03-06
  245. */
  246. public function renderError($template = null)
  247. {
  248. if(!$template) return false;
  249. if($this->RequestHandler->isAjax()) $this->render('/errors/json/'.$template, 'ajax');
  250. else $this->cakeError($template);
  251. }
  252. /**
  253. * temp function for displaying enum in scaffolding
  254. *
  255. * @date 2009-1-27
  256. */
  257. public function renderEnums()
  258. {
  259. foreach($this->modelNames as $model)
  260. {
  261. foreach($this->$model->_schema as $var => $field)
  262. {
  263. if(strpos($field['type'], 'enum') === false) continue;
  264. preg_match_all("/\'([^\']+)\'/", $field['type'], $strEnum);
  265. if(is_array($strEnum[1]))
  266. {
  267. $varName = Inflector::camelize(Inflector::pluralize($var));
  268. $varName[0] = strtolower($varName[0]);
  269. $this->set($varName, array_combine($strEnum[1], $strEnum[1]));
  270. }
  271. }
  272. }
  273. }
  274. /**
  275. * get ENUM fields
  276. *
  277. * @date 2009-02-22
  278. */
  279. public function getEnumFields($fieldName = 'field')
  280. {
  281. //get blacklist fields
  282. preg_match_all("/\'([^\']+)\'/", $this->{$this->modelClass}->_schema[$fieldName]['type'], $strEnum);
  283. if(is_array($strEnum[1])) return array_combine($strEnum[1], $strEnum[1]);
  284. }
  285. /**
  286. * Write the time point into session which indicates when the user requests the page, this is for dealing with Ajax comment
  287. *
  288. * @param $id Int Post id
  289. * @date 2009-1-24
  290. */
  291. public function setTimePoint($id = null)
  292. {
  293. if(!$id) return false;
  294. $this->Session->write('TimePoint.'.$id, time());
  295. }
  296. /**
  297. * Get the time point when the user requested the page
  298. *
  299. * @date 2009-1-21
  300. */
  301. function getTimePoint($id = null)
  302. {
  303. if(!$id) return false;
  304. return $this->Session->read('TimePoint.'.$id);
  305. }
  306. }
  307. /* Works out the time since the entry post, takes a an argument in unix time (seconds) */
  308. function time_since($original) {
  309. // array of time period chunks
  310. $chunks = array(
  311. array(60 * 60 * 24 * 365 , __('year', true)),
  312. array(60 * 60 * 24 * 30 , __('month', true)),
  313. array(60 * 60 * 24 * 7, __('week', true)),
  314. array(60 * 60 * 24 , __('day', true)),
  315. array(60 * 60 , __('hour', true)),
  316. array(60 , __('minute', true)),
  317. );
  318. $today = time(); /* Current unix time */
  319. $since = $today - $original;
  320. // $j saves performing the count function each time around the loop
  321. for ($i = 0, $j = count($chunks); $i < $j; $i++) {
  322. $seconds = $chunks[$i][0];
  323. $name = $chunks[$i][1];
  324. // finding the biggest chunk (if the chunk fits, break)
  325. if (($count = floor($since / $seconds)) != 0) {
  326. // DEBUG print "<!-- It's $name -->\n";
  327. break;
  328. }
  329. }
  330. //$print = ($count == 1) ? '1 '.$name : "$count {$name}s";
  331. $name = ($name == __('month', true)) ? __('monthes', true) : $name;
  332. $print = ($count == 1) ? '1'.$name : "$count$name";
  333. if ($i + 1 < $j) {
  334. // now getting the second item
  335. $seconds2 = $chunks[$i + 1][0];
  336. $name2 = $chunks[$i + 1][1];
  337. // add second item if it's greater than 0
  338. if (($count2 = floor(($since - ($seconds * $count)) / $seconds2)) != 0) {
  339. $print .= ($count2 == 1) ? ', 1'.$name2 : ", $count2 $name2";
  340. }
  341. }
  342. return $print . __('ago', true);
  343. }
  344. /**
  345. * home-cooked lcfirst()
  346. *
  347. * @date 2009-04-27
  348. function lcfirst($string = null)
  349. {
  350. if(!$string) return null;
  351. //dont't know how to do it with RegEx, :p
  352. return preg_replace('/(^[A-Z])/', strtolower(substr($string, 0, 1)), $string);
  353. }*/
  354. ?>