CommonComponent.php 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155
  1. <?php
  2. App::uses('Component', 'Controller');
  3. App::uses('Sanitize', 'Utility');
  4. App::uses('Utility', 'Tools.Utility');
  5. /**
  6. * A component included in every app to take care of common stuff.
  7. *
  8. * @author Mark Scherer
  9. * @copyright 2012 Mark Scherer
  10. * @license MIT
  11. */
  12. class CommonComponent extends Component {
  13. public $components = array('Session', 'RequestHandler');
  14. public $userModel = 'User';
  15. /**
  16. * For automatic startup
  17. * for this helper the controller has to be passed as reference
  18. *
  19. * @return void
  20. */
  21. public function initialize(Controller $Controller) {
  22. parent::initialize($Controller);
  23. $this->Controller = $Controller;
  24. }
  25. /**
  26. * For this helper the controller has to be passed as reference
  27. * for manual startup with $disableStartup = true (requires this to be called prior to any other method)
  28. *
  29. * @return void
  30. */
  31. public function startup(Controller $Controller = null) {
  32. parent::startup($Controller);
  33. // Data preparation
  34. if (!empty($this->Controller->request->data) && !Configure::read('DataPreparation.notrim')) {
  35. $this->Controller->request->data = $this->trimDeep($this->Controller->request->data);
  36. }
  37. if (!empty($this->Controller->request->query) && !Configure::read('DataPreparation.notrim')) {
  38. $this->Controller->request->query = $this->trimDeep($this->Controller->request->query);
  39. }
  40. if (!empty($this->Controller->request->params['named']) && !Configure::read('DataPreparation.notrim')) {
  41. $this->Controller->request->params['named'] = $this->trimDeep($this->Controller->request->params['named']);
  42. }
  43. if (!empty($this->Controller->request->params['pass']) && !Configure::read('DataPreparation.notrim')) {
  44. $this->Controller->request->params['pass'] = $this->trimDeep($this->Controller->request->params['pass']);
  45. }
  46. // Deprecation notices
  47. if (Configure::read('App.warnAboutNamedParams')) {
  48. if (!empty($Controller->request->params['named']) && ($referer = $Controller->request->referer(true)) && $referer !== '/') {
  49. trigger_error('Named params ' . json_encode($Controller->request->params['named']) . ' - from ' . $referer, E_USER_DEPRECATED);
  50. }
  51. }
  52. // Information gathering
  53. if (!Configure::read('App.disableMobileDetection') && ($mobile = $this->Session->read('Session.mobile')) === null) {
  54. App::uses('UserAgentLib', 'Tools.Lib');
  55. $UserAgentLib = new UserAgentLib();
  56. $mobile = (int)$UserAgentLib->isMobile();
  57. $this->Session->write('Session.mobile', $mobile);
  58. }
  59. // Auto layout switch
  60. if ($this->Controller->request->is('ajax')) {
  61. $this->Controller->layout = 'ajax';
  62. }
  63. }
  64. /**
  65. * Called after the Controller::beforeRender(), after the view class is loaded, and before the
  66. * Controller::render()
  67. *
  68. * @param object $Controller Controller with components to beforeRender
  69. * @return void
  70. */
  71. public function beforeRender(Controller $Controller) {
  72. if ($messages = $this->Session->read('Message')) {
  73. foreach ($messages as $message) {
  74. $this->flashMessage($message['message'], 'error');
  75. }
  76. $this->Session->delete('Message');
  77. }
  78. if ($this->Controller->request->is('ajax')) {
  79. $ajaxMessages = array_merge(
  80. (array)$this->Session->read('messages'),
  81. (array)Configure::read('messages')
  82. );
  83. // The header can be read with JavaScript and a custom Message can be displayed
  84. $this->Controller->response->header('X-Ajax-Flashmessage', json_encode($ajaxMessages));
  85. $this->Session->delete('messages');
  86. }
  87. // Custom options
  88. if (isset($Controller->options)) {
  89. $Controller->set('options', $Controller->options);
  90. }
  91. }
  92. /**
  93. * List all direct actions of a controller
  94. *
  95. * @return array Actions
  96. */
  97. public function listActions() {
  98. $class = Inflector::camelize($this->Controller->name) . 'Controller';
  99. $parentClassMethods = get_class_methods(get_parent_class($class));
  100. $subClassMethods = get_class_methods($class);
  101. $classMethods = array_diff($subClassMethods, $parentClassMethods);
  102. foreach ($classMethods as $key => $value) {
  103. if (substr($value, 0, 1) === '_') {
  104. unset($classMethods[$key]);
  105. }
  106. }
  107. return $classMethods;
  108. }
  109. /**
  110. * Convenience method to check on POSTED data.
  111. * Doesn't matter if it's POST or PUT.
  112. *
  113. * Note that since 2.4 you can use request->is(array('post', 'put') directly.
  114. *
  115. * @return boolean If it is of type POST/PUT
  116. */
  117. public function isPosted() {
  118. return $this->Controller->request->is(array('post', 'put'));
  119. }
  120. /**
  121. * Updates FlashMessage SessionContent (to enable unlimited messages of one case)
  122. *
  123. * @param string messagestring
  124. * @param string class ['error', 'warning', 'success', 'info']
  125. * @return void
  126. */
  127. public function flashMessage($messagestring, $class = null) {
  128. switch ($class) {
  129. case 'error':
  130. case 'warning':
  131. case 'success':
  132. break;
  133. default:
  134. $class = 'info';
  135. break;
  136. }
  137. $old = (array)$this->Session->read('messages');
  138. if (isset($old[$class]) && count($old[$class]) > 99) {
  139. array_shift($old[$class]);
  140. }
  141. $old[$class][] = $messagestring;
  142. $this->Session->write('messages', $old);
  143. }
  144. /**
  145. * FlashMessages that are not saved (only for current view)
  146. * will be merged into the session flash ones prior to output
  147. *
  148. * @param string messagestring
  149. * @param string class ['error', 'warning', 'success', 'info']
  150. * @return void
  151. */
  152. public static function transientFlashMessage($messagestring, $class = null) {
  153. switch ($class) {
  154. case 'error':
  155. case 'warning':
  156. case 'success':
  157. break;
  158. default:
  159. $class = 'info';
  160. break;
  161. }
  162. $old = (array)Configure::read('messages');
  163. if (isset($old[$class]) && count($old[$class]) > 99) {
  164. array_shift($old[$class]);
  165. }
  166. $old[$class][] = $messagestring;
  167. Configure::write('messages', $old);
  168. }
  169. /**
  170. * Add helper just in time (inside actions - only when needed)
  171. * aware of plugins
  172. * @param mixed $helpers (single string or multiple array)
  173. */
  174. public function loadHelper($helpers = array()) {
  175. $this->Controller->helpers = array_merge($this->Controller->helpers, (array)$helpers);
  176. }
  177. /**
  178. * Add lib just in time (inside actions - only when needed)
  179. * aware of plugins and config array (if passed)
  180. * ONLY works if constructor consists only of one param (settings)!
  181. * @param mixed $libs (single string or multiple array)
  182. * e.g.: array('Tools.MyLib'=>array('key'=>'value'), ...)
  183. */
  184. public function loadLib($libs = array()) {
  185. foreach ((array)$libs as $lib => $config) {
  186. if (is_int($lib)) {
  187. $lib = $config;
  188. $config = null;
  189. }
  190. list($plugin, $libName) = pluginSplit($lib);
  191. if (isset($this->Controller->{$libName})) {
  192. continue;
  193. }
  194. $package = 'Lib';
  195. if ($plugin) {
  196. $package = $plugin . '.' . $package;
  197. }
  198. App::uses($libName, $package);
  199. $this->Controller->{$libName} = new $libName($config);
  200. }
  201. }
  202. /**
  203. * Add component just in time (inside actions - only when needed)
  204. * aware of plugins and config array (if passed)
  205. * @param mixed $components (single string or multiple array)
  206. * @poaram bool $callbacks (defaults to true)
  207. */
  208. public function loadComponent($components = array(), $callbacks = true) {
  209. foreach ((array)$components as $component => $config) {
  210. if (is_int($component)) {
  211. $component = $config;
  212. $config = array();
  213. }
  214. list($plugin, $componentName) = pluginSplit($component);
  215. if (isset($this->Controller->{$componentName})) {
  216. continue;
  217. }
  218. $this->Controller->{$componentName} = $this->Controller->Components->load($component, $config);
  219. if (!$callbacks) {
  220. continue;
  221. }
  222. if (method_exists($this->Controller->{$componentName}, 'initialize')) {
  223. $this->Controller->{$componentName}->initialize($this->Controller);
  224. }
  225. if (method_exists($this->Controller->{$componentName}, 'startup')) {
  226. $this->Controller->{$componentName}->startup($this->Controller);
  227. }
  228. }
  229. }
  230. /**
  231. * Used to get the value of a passed param.
  232. *
  233. * @param mixed $var
  234. * @param mixed $default
  235. * @return mixed
  236. */
  237. public function getPassedParam($var, $default = null) {
  238. return (isset($this->Controller->request->params['pass'][$var])) ? $this->Controller->request->params['pass'][$var] : $default;
  239. }
  240. /**
  241. * Used to get the value of a named param.
  242. * @deprecated - move to query strings instead
  243. *
  244. * @param mixed $var
  245. * @param mixed $default
  246. * @return mixed
  247. */
  248. public function getNamedParam($var, $default = null) {
  249. return (isset($this->Controller->request->params['named'][$var])) ? $this->Controller->request->params['named'][$var] : $default;
  250. }
  251. /**
  252. * Used to get the value of a get query.
  253. * @deprecated - use request->query() instead
  254. *
  255. * @param mixed $var
  256. * @param mixed $default
  257. * @return mixed
  258. */
  259. public function getQueryParam($var, $default = null) {
  260. trigger_error('deprecated - use $this->request->query()');
  261. return (isset($this->Controller->request->query[$var])) ? $this->Controller->request->query[$var] : $default;
  262. }
  263. /**
  264. * Returns defaultUrlParams including configured prefixes.
  265. *
  266. * @return array Url params
  267. */
  268. public static function defaultUrlParams() {
  269. $defaults = array('plugin' => false);
  270. $prefixes = (array)Configure::read('Routing.prefixes');
  271. foreach ($prefixes as $prefix) {
  272. $defaults[$prefix] = false;
  273. }
  274. return $defaults;
  275. }
  276. /**
  277. * Returns current url (with all missing params automatically added).
  278. * Necessary for Router::url() and comparison of urls to work.
  279. *
  280. * @param boolean $asString: defaults to false = array
  281. * @return mixed Url
  282. */
  283. public function currentUrl($asString = false) {
  284. if (isset($this->Controller->request->params['prefix']) && mb_strpos($this->Controller->request->params['action'], $this->Controller->request->params['prefix']) === 0) {
  285. $action = mb_substr($this->Controller->request->params['action'], mb_strlen($this->Controller->request->params['prefix']) + 1);
  286. } else {
  287. $action = $this->Controller->request->params['action'];
  288. }
  289. $url = array_merge($this->Controller->request->params['named'], $this->Controller->request->params['pass'], array('prefix' => isset($this->Controller->request->params['prefix']) ? $this->Controller->request->params['prefix'] : null,
  290. 'plugin' => $this->Controller->request->params['plugin'], 'action' => $action, 'controller' => $this->Controller->request->params['controller']));
  291. if ($asString === true) {
  292. return Router::url($url);
  293. }
  294. return $url;
  295. }
  296. /**
  297. * Tries to allow super admin access for certain urls via `Config.pwd`.
  298. * Only used in admin actions and only to prevent accidental data loss due to incorrect access.
  299. * Do not assume this to be a safe access control mechanism!
  300. *
  301. * Password can be passed as named param or query string param.
  302. *
  303. * @return boolean Success
  304. */
  305. public function validAdminUrlAccess() {
  306. $pwd = Configure::read('Config.pwd');
  307. if (!$pwd) {
  308. return false;
  309. }
  310. $urlPwd = $this->getNamedParam('pwd');
  311. if (!$urlPwd) {
  312. $urlPwd = $this->getQueryParam('pwd');
  313. }
  314. if (!$urlPwd) {
  315. return false;
  316. }
  317. return $pwd === $urlPwd;
  318. }
  319. /**
  320. * Direct login for a specific user id.
  321. * Will respect full login scope (if defined in auth setup) as well as contained data and
  322. * can therefore return false if the login fails due to unmatched scope.
  323. *
  324. * @see DirectAuthentication auth adapter
  325. * @param mixed $id User id
  326. * @param array $settings Settings for DirectAuthentication
  327. * - fields
  328. * @return boolean Success
  329. */
  330. public function manualLogin($id, $settings = array()) {
  331. $requestData = $this->Controller->request->data;
  332. $authData = $this->Controller->Auth->authenticate;
  333. $settings = array_merge($authData, $settings);
  334. $settings['fields'] = array('username' => 'id');
  335. $this->Controller->request->data = array($this->userModel => array('id' => $id));
  336. $this->Controller->Auth->authenticate = array('Tools.Direct' => $settings);
  337. $result = $this->Controller->Auth->login();
  338. $this->Controller->Auth->authenticate = $authData;
  339. $this->Controller->request->data = $requestData;
  340. return $result;
  341. }
  342. /**
  343. * Force login for a specific user id.
  344. * Only fails if the user does not exist or if he is already
  345. * logged in as it ignores the usual scope.
  346. *
  347. * Better than Auth->login($data) since it respects the other auth configs such as
  348. * fields, contain, recursive and userModel.
  349. *
  350. * @param mixed $id User id
  351. * @return boolean Success
  352. */
  353. public function forceLogin($id) {
  354. $settings = array(
  355. 'scope' => array(),
  356. );
  357. return $this->manualLogin($id, $settings);
  358. /*
  359. if (!isset($this->User)) {
  360. $this->User = ClassRegistry::init(defined('CLASS_USER') ? CLASS_USER : $this->userModel);
  361. }
  362. $data = $this->User->get($id);
  363. if (!$data) {
  364. return false;
  365. }
  366. $data = $data[$this->userModel];
  367. return $this->Controller->Auth->login($data);
  368. */
  369. }
  370. /**
  371. * Smart Referer Redirect - will try to use an existing referer first
  372. * otherwise it will use the default url
  373. *
  374. * @param mixed $url
  375. * @param boolean $allowSelf if redirect to the same controller/action (url) is allowed
  376. * @param integer $status
  377. * @return void
  378. */
  379. public function autoRedirect($whereTo, $allowSelf = true, $status = null) {
  380. if ($allowSelf || $this->Controller->referer(null, true) !== '/' . $this->Controller->request->url) {
  381. $this->Controller->redirect($this->Controller->referer($whereTo, true), $status);
  382. }
  383. $this->Controller->redirect($whereTo, $status);
  384. }
  385. /**
  386. * Should be a 303, but:
  387. * Note: Many pre-HTTP/1.1 user agents do not understand the 303 status. When interoperability with such clients is a concern, the 302 status code may be used instead, since most user agents react to a 302 response as described here for 303.
  388. *
  389. * TODO: change to 303 with backwardscompatability for older browsers...
  390. *
  391. * @see http://en.wikipedia.org/wiki/Post/Redirect/Get
  392. * @param mixed $url
  393. * @param integer $status
  394. * @return void
  395. */
  396. public function postRedirect($whereTo, $status = 302) {
  397. $this->Controller->redirect($whereTo, $status);
  398. }
  399. /**
  400. * Combine auto with post
  401. * also allows whitelisting certain actions for autoRedirect (use Controller::$autoRedirectActions)
  402. * @param mixed $url
  403. * @param boolean $conditionalAutoRedirect false to skip whitelisting
  404. * @param integer $status
  405. * @return void
  406. */
  407. public function autoPostRedirect($whereTo, $conditionalAutoRedirect = true, $status = 302) {
  408. $referer = $this->Controller->referer($whereTo, true);
  409. if (!$conditionalAutoRedirect && !empty($referer)) {
  410. $this->postRedirect($referer, $status);
  411. }
  412. if (!empty($referer)) {
  413. $referer = Router::parse($referer);
  414. }
  415. if (!$conditionalAutoRedirect || empty($this->Controller->autoRedirectActions) || is_array($referer) && !empty($referer['action'])) {
  416. $refererController = Inflector::camelize($referer['controller']);
  417. // fixme
  418. if (!isset($this->Controller->autoRedirectActions)) {
  419. $this->Controller->autoRedirectActions = array();
  420. }
  421. foreach ($this->Controller->autoRedirectActions as $action) {
  422. list($controller, $action) = pluginSplit($action);
  423. if (!empty($controller) && $refererController !== '*' && $refererController != $controller) {
  424. continue;
  425. }
  426. if (empty($controller) && $refererController != Inflector::camelize($this->Controller->request->params['controller'])) {
  427. continue;
  428. }
  429. if (!in_array($referer['action'], $this->Controller->autoRedirectActions)) {
  430. continue;
  431. }
  432. $this->autoRedirect($whereTo, true, $status);
  433. }
  434. }
  435. $this->postRedirect($whereTo, $status);
  436. }
  437. /**
  438. * Automatically add missing url parts of the current url including
  439. * - querystring (especially for 3.x then)
  440. * - named params (until 3.x when they will become deprecated)
  441. * - passed params
  442. *
  443. * @param mixed $url
  444. * @param integer $status
  445. * @param boolean $exit
  446. * @return void
  447. */
  448. public function completeRedirect($url = null, $status = null, $exit = true) {
  449. if ($url === null) {
  450. $url = $this->Controller->request->params;
  451. unset($url['named']);
  452. unset($url['pass']);
  453. unset($url['isAjax']);
  454. }
  455. if (is_array($url)) {
  456. $url += $this->Controller->request->params['named'];
  457. $url += $this->Controller->request->params['pass'];
  458. }
  459. return $this->Controller->redirect($url, $status, $exit);
  460. }
  461. /**
  462. * Only redirect to itself if cookies are on
  463. * Prevents problems with lost data
  464. * Note: Many pre-HTTP/1.1 user agents do not understand the 303 status. When interoperability with such clients is a concern, the 302 status code may be used instead, since most user agents react to a 302 response as described here for 303.
  465. *
  466. * @see http://en.wikipedia.org/wiki/Post/Redirect/Get
  467. * TODO: change to 303 with backwardscompatability for older browsers...
  468. * @param integer $status
  469. * @return void
  470. */
  471. public function prgRedirect($status = 302) {
  472. if (!empty($_COOKIE[Configure::read('Session.cookie')])) {
  473. $this->Controller->redirect('/' . $this->Controller->request->url, $status);
  474. }
  475. }
  476. /**
  477. * Handler for passing some meta data to the view
  478. * uses CommonHelper to include them in the layout
  479. *
  480. * @param type (relevance):
  481. * - title (10), description (9), robots(7), language(5), keywords (0)
  482. * - custom: abstract (1), category(1), GOOGLEBOT(0) ...
  483. * @return void
  484. */
  485. public function setMeta($type, $content, $prep = true) {
  486. if (!in_array($type, array('title', 'canonical', 'description', 'keywords', 'robots', 'language', 'custom'))) {
  487. trigger_error(__('Meta Type invalid'), E_USER_WARNING);
  488. return;
  489. }
  490. if ($type === 'canonical' && $prep) {
  491. $content = Router::url($content);
  492. }
  493. if ($type === 'canonical' && $prep) {
  494. $content = h($content);
  495. }
  496. Configure::write('Meta.' . $type, $content);
  497. }
  498. /**
  499. * Set headers to cache this request.
  500. * Opposite of Controller::disableCache()
  501. * TODO: set response class header instead
  502. *
  503. * @param integer $seconds
  504. * @return void
  505. */
  506. public function forceCache($seconds = HOUR) {
  507. $this->Controller->response->header('Cache-Control', 'public, max-age=' . $seconds);
  508. $this->Controller->response->header('Last-modified', gmdate("D, j M Y H:i:s", time()) . " GMT");
  509. $this->Controller->response->header('Expires', gmdate("D, j M Y H:i:s", time() + $seconds) . " GMT");
  510. }
  511. /**
  512. * Referrer checking (where does the user come from)
  513. * Only returns true for a valid external referrer.
  514. *
  515. * @return boolean Success
  516. */
  517. public function isForeignReferer($ref = null) {
  518. if ($ref === null) {
  519. $ref = env('HTTP_REFERER');
  520. }
  521. if (!$ref) {
  522. return false;
  523. }
  524. $base = Configure::read('App.fullBaseUrl') . '/';
  525. if (strpos($ref, $base) === 0) {
  526. return false;
  527. }
  528. return true;
  529. }
  530. /**
  531. * CommonComponent::denyAccess()
  532. *
  533. * @return void
  534. */
  535. public function denyAccess() {
  536. $ref = env('HTTP_USER_AGENT');
  537. if ($this->isForeignReferer($ref)) {
  538. if (strpos(strtolower($ref), 'http://anonymouse.org/') === 0) {
  539. $this->cakeError('error406', array());
  540. }
  541. }
  542. }
  543. /**
  544. * CommonComponent::monitorCookieProblems()
  545. *
  546. * @return void
  547. */
  548. public function monitorCookieProblems() {
  549. $ip = $this->RequestHandler->getClientIP();
  550. $host = gethostbyaddr($ip);
  551. $sessionId = session_id();
  552. if (empty($sessionId)) {
  553. $sessionId = '--';
  554. }
  555. if (empty($_REQUEST[Configure::read('Session.cookie')]) && !($res = Cache::read($ip))) {
  556. $this->log('CookieProblem:: SID: ' . $sessionId . ' | IP: ' . $ip . ' (' . $host . ') | REF: ' . $this->Controller->referer() . ' | Agent: ' . env('HTTP_USER_AGENT'), 'noscript');
  557. Cache::write($ip, 1);
  558. }
  559. }
  560. /**
  561. * //todo: move to Utility?
  562. *
  563. * @return boolean true if disabled (bots, etc), false if enabled
  564. */
  565. public static function cookiesDisabled() {
  566. if (!empty($_COOKIE) && !empty($_COOKIE[Configure::read('Session.cookie')])) {
  567. return false;
  568. }
  569. return true;
  570. }
  571. /**
  572. * Quick sql debug from controller dynamically
  573. * or statically from just about any other place in the script
  574. *
  575. * @param boolean $exit If script should exit.
  576. * @return boolean Success
  577. */
  578. public function sql($exit = true) {
  579. if (isset($this->Controller)) {
  580. $object = $this->Controller->{$this->Controller->modelClass};
  581. } else {
  582. $object = ClassRegistry::init(defined('CLASS_USER') ? CLASS_USER : $this->userModel);
  583. }
  584. $log = $object->getDataSource()->getLog(false, false);
  585. foreach ($log['log'] as $key => $value) {
  586. if (strpos($value['query'], 'SHOW ') === 0 || strpos($value['query'], 'SELECT CHARACTER_SET_NAME ') === 0) {
  587. unset($log['log'][$key]);
  588. continue;
  589. }
  590. }
  591. if ($exit) {
  592. debug($log);
  593. exit();
  594. }
  595. $log = print_r($log, true);
  596. App::uses('CakeLog', 'Log');
  597. return CakeLog::write('sql', $log);
  598. }
  599. /**
  600. * Localize
  601. *
  602. * @return boolean Success
  603. */
  604. public function localize($lang = null) {
  605. if ($lang === null) {
  606. $lang = Configure::read('Config.language');
  607. }
  608. if (empty($lang)) {
  609. return false;
  610. }
  611. if (($pos = strpos($lang, '-')) !== false) {
  612. $lang = substr($lang, 0, $pos);
  613. }
  614. if ($lang === DEFAULT_LANGUAGE) {
  615. return null;
  616. }
  617. if (!($pattern = Configure::read('LocalizationPattern.' . $lang))) {
  618. return false;
  619. }
  620. foreach ((array)$pattern as $key => $value) {
  621. Configure::write('Localization.' . $key, $value);
  622. }
  623. return true;
  624. }
  625. /**
  626. * Main controller function for consistency in controller naming
  627. *
  628. * @deprecated
  629. * @return void
  630. */
  631. public function ensureControllerConsistency() {
  632. // problems with plugins
  633. if (!empty($this->Controller->request->params['plugin'])) {
  634. return;
  635. }
  636. if (($name = strtolower(Inflector::underscore($this->Controller->name))) !== $this->Controller->request->params['controller']) {
  637. $this->Controller->log('301: ' . $this->Controller->request->params['controller'] . ' => ' . $name . ' (Ref ' . $this->Controller->referer() . ')', '301'); // log problem with controller naming
  638. if (!$this->Controller->RequestHandler->isPost()) {
  639. // underscored version is the only valid one to avoid duplicate content
  640. $url = array('controller' => $name, 'action' => $this->Controller->request->params['action']);
  641. $url = array_merge($url, $this->Controller->request->params['pass'], $this->Controller->request->params['named']);
  642. //TODO: add plugin/admin stuff which right now is supposed to work automatically
  643. $this->Controller->redirect($url, 301);
  644. }
  645. }
  646. return true;
  647. // problem with extensions (rss etc)
  648. if (empty($this->Controller->request->params['prefix']) && ($currentUrl = $this->currentUrl(true)) != $this->Controller->here) {
  649. //pr($this->Controller->here);
  650. //pr($currentUrl);
  651. $this->log('301: ' . $this->Controller->here . ' => ' . $currentUrl . ' (Referer ' . $this->Controller->referer() . ')', '301');
  652. if (!$this->Controller->RequestHandler->isPost()) {
  653. $url = array('controller' => $this->Controller->request->params['controller'], 'action' => $this->Controller->request->params['action']);
  654. $url = array_merge($url, $this->Controller->request->params['pass'], $this->Controller->request->params['named']);
  655. $this->Controller->redirect($url, 301);
  656. }
  657. }
  658. }
  659. /**
  660. * Main controller function for seo-slugs
  661. * passed titleSlug != current title => redirect to the expected one
  662. *
  663. * @deprecated
  664. * @return void
  665. */
  666. public function ensureConsistency($id, $passedTitleSlug, $currentTitle) {
  667. $expectedTitle = slug($currentTitle);
  668. if (empty($passedTitleSlug) || $expectedTitle != $passedTitleSlug) { # case sensitive!!!
  669. $ref = env('HTTP_REFERER');
  670. if (!$this->isForeignReferer($ref)) {
  671. $this->Controller->log('Internal ConsistencyProblem at \'' . $ref . '\' - [' . $passedTitleSlug . '] instead of [' . $expectedTitle . ']', 'referer');
  672. } else {
  673. $this->Controller->log('External ConsistencyProblem at \'' . $ref . '\' - [' . $passedTitleSlug . '] instead of [' . $expectedTitle . ']', 'referer');
  674. }
  675. $this->Controller->redirect(array($id, $expectedTitle), 301);
  676. }
  677. }
  678. /**
  679. * Try to detect group for a multidim array for select boxes.
  680. * Extracts the group name of the selected key.
  681. *
  682. * @param array $array
  683. * @param string $key
  684. * @param array $matching
  685. * @return string result
  686. */
  687. public static function getGroup($multiDimArray, $key, $matching = array()) {
  688. if (!is_array($multiDimArray) || empty($key)) {
  689. return '';
  690. }
  691. foreach ($multiDimArray as $group => $data) {
  692. if (array_key_exists($key, $data)) {
  693. if (!empty($matching)) {
  694. if (array_key_exists($group, $matching)) {
  695. return $matching[$group];
  696. }
  697. return '';
  698. }
  699. return $group;
  700. }
  701. }
  702. return '';
  703. }
  704. /*** DEEP FUNCTIONS ***/
  705. /**
  706. * Move to boostrap?
  707. */
  708. public function trimDeep($value) {
  709. $value = is_array($value) ? array_map(array($this, 'trimDeep'), $value) : trim($value);
  710. return $value;
  711. }
  712. /**
  713. * Move to boostrap?
  714. */
  715. public function specialcharsDeep($value) {
  716. $value = is_array($value) ? array_map(array($this, 'specialcharsDeep'), $value) : htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
  717. return $value;
  718. }
  719. /**
  720. * Move to boostrap?
  721. */
  722. public function deep($function, $value) {
  723. $value = is_array($value) ? array_map(array($this, $function), $value) : $function($value);
  724. return $value;
  725. }
  726. /**
  727. * Takes list of items and transforms it into an array
  728. * + cleaning (trim, no empty parts, etc).
  729. * Similar to String::tokenize, but with more logic.
  730. *
  731. * //TODO: 3.4. parameter as array, move to Lib
  732. *
  733. * @deprecated
  734. * @param string $string containing the parts
  735. * @param string $separator (defaults to ',')
  736. * @param boolean $camelize (true/false): problems with äöüß etc!
  737. * @return array Results as list
  738. */
  739. public function parseList($string, $separator = null, $camelize = false, $capitalize = true) {
  740. if ($separator === null) {
  741. $separator = ',';
  742. }
  743. // parses the list, but leaves tokens untouched inside () brackets
  744. $stringArray = String::tokenize($string, $separator);
  745. $returnArray = array();
  746. if (empty($stringArray)) {
  747. return array();
  748. }
  749. foreach ($stringArray as $t) {
  750. $t = trim($t);
  751. if (!empty($t)) {
  752. if ($camelize === true) {
  753. $t = mb_strtolower($t);
  754. $t = Inflector::camelize(Inflector::underscore($t)); // problems with non-alpha chars!
  755. } elseif ($capitalize === true) {
  756. $t = ucwords($t);
  757. }
  758. $returnArray[] = $t;
  759. }
  760. }
  761. return $returnArray;
  762. }
  763. /**
  764. * //todo move to lib!!!
  765. *
  766. * @param string $s
  767. * @return mixed
  768. */
  769. public static function separators($s = null, $valueOnly = false) {
  770. $separatorsValues = array(SEPARATOR_COMMA => ',', SEPARATOR_SEMI => ';', SEPARATOR_SPACE => ' ', SEPARATOR_TAB => TB, SEPARATOR_NL => NL);
  771. $separators = array(SEPARATOR_COMMA => '[ , ] ' . __('Comma'), SEPARATOR_SEMI => '[ ; ] ' . __('Semicolon'), SEPARATOR_SPACE => '[ &nbsp; ] ' . __('Space'), SEPARATOR_TAB =>
  772. '[ &nbsp;&nbsp;&nbsp;&nbsp; ] ' . __('Tabulator'), SEPARATOR_NL => '[ \n ] ' . __('New Line'));
  773. if ($s !== null) {
  774. if (array_key_exists($s, $separators)) {
  775. if ($valueOnly) {
  776. return $separatorsValues[$s];
  777. }
  778. return $separators[$s];
  779. }
  780. return '';
  781. }
  782. return $valueOnly ? $separatorsValues : $separators;
  783. }
  784. /**
  785. * //TODO: move somewhere else
  786. * Assign Array to Char Array
  787. *
  788. * PROTECTED NAMES (content cannot contain those): undefined
  789. *
  790. * @var content array
  791. * @var char array
  792. * @return array: chars with content
  793. */
  794. public function assignToChar($contentArray, $charArray = null) {
  795. $res = array();
  796. $res['undefined'] = array();
  797. if (empty($charArray)) {
  798. $charArray = $this->alphaFilterSymbols();
  799. }
  800. foreach ($contentArray as $content) {
  801. $done = false;
  802. // loop them trough
  803. foreach ($charArray as $char) {
  804. if (empty($res[$char])) { // throws warnings otherwise
  805. $res[$char] = array();
  806. }
  807. if (!empty($content) && strtolower(substr($content, 0, 1)) == $char) {
  808. $res[$char][] = $content;
  809. $done = true;
  810. }
  811. }
  812. // no match?
  813. if (!empty($content) && !$done) {
  814. $res['undefined'][] = $content;
  815. }
  816. }
  817. return $res;
  818. }
  819. /**
  820. * Expects email to be valid!
  821. * TODO: move to Lib
  822. * @return array email - pattern: array('email'=>,'name'=>)
  823. */
  824. public function splitEmail($email, $abortOnError = false) {
  825. $array = array('email' => '', 'name' => '');
  826. if (($pos = mb_strpos($email, '<')) !== false) {
  827. $name = substr($email, 0, $pos);
  828. $email = substr($email, $pos + 1);
  829. }
  830. if (($pos = mb_strrpos($email, '>')) !== false) {
  831. $email = substr($email, 0, $pos);
  832. }
  833. $email = trim($email);
  834. if (!empty($email)) {
  835. $array['email'] = $email;
  836. }
  837. if (!empty($name)) {
  838. $array['name'] = trim($name);
  839. }
  840. return $array;
  841. }
  842. /**
  843. * TODO: move to Lib
  844. * @param string $email
  845. * @param string $name (optional, will use email otherwise)
  846. */
  847. public function combineEmail($email, $name = null) {
  848. if (empty($email)) {
  849. return '';
  850. }
  851. if (empty($name)) {
  852. $name = $email;
  853. }
  854. return $name . ' <' . $email['email'] . '>';
  855. }
  856. /**
  857. * TODO: move to Lib
  858. * returns type
  859. * - username: everything till @ (xyz@abc.de => xyz)
  860. * - hostname: whole domain (xyz@abc.de => abc.de)
  861. * - tld: top level domain only (xyz@abc.de => de)
  862. * - domain: if available (xyz@e.abc.de => abc)
  863. * - subdomain: if available (xyz@e.abc.de => e)
  864. * @param string $email: well formatted email! (containing one @ and one .)
  865. * @param string $type (TODO: defaults to return all elements)
  866. * @return string or false on failure
  867. */
  868. public function extractEmailInfo($email, $type = null) {
  869. //$checkpos = strrpos($email, '@');
  870. $nameParts = explode('@', $email);
  871. if (count($nameParts) !== 2) {
  872. return false;
  873. }
  874. if ($type === 'username') {
  875. return $nameParts[0];
  876. }
  877. if ($type === 'hostname') {
  878. return $nameParts[1];
  879. }
  880. $checkpos = strrpos($nameParts[1], '.');
  881. $tld = trim(mb_substr($nameParts[1], $checkpos + 1));
  882. if ($type === 'tld') {
  883. return $tld;
  884. }
  885. $server = trim(mb_substr($nameParts[1], 0, $checkpos));
  886. //TODO; include 3rd-Level-Label
  887. $domain = '';
  888. $subdomain = '';
  889. $checkpos = strrpos($server, '.');
  890. if ($checkpos !== false) {
  891. $subdomain = trim(mb_substr($server, 0, $checkpos));
  892. $domain = trim(mb_substr($server, $checkpos + 1));
  893. }
  894. if ($type === 'domain') {
  895. return $domain;
  896. }
  897. if ($type === 'subdomain') {
  898. return $subdomain;
  899. }
  900. //$hostParts = explode();
  901. //$check = trim(mb_substr($email, $checkpos));
  902. return '';
  903. }
  904. /**
  905. * Returns searchArray (options['wildcard'] TRUE/FALSE)
  906. * TODO: move to SearchLib etc
  907. *
  908. * @param string $keyword
  909. * @param string $searchphrase
  910. * @param array $options
  911. * @return array Cleaned array('keyword'=>'searchphrase') or array('keyword LIKE'=>'searchphrase')
  912. */
  913. public function getSearchItem($keyword = null, $searchphrase = null, $options = array()) {
  914. if (isset($options['wildcard']) && $options['wildcard'] == true) {
  915. if (strpos($searchphrase, '*') !== false || strpos($searchphrase, '_') !== false) {
  916. $keyword .= ' LIKE';
  917. $searchphrase = str_replace('*', '%', $searchphrase);
  918. // additionally remove % ?
  919. //$searchphrase = str_replace(array('%','_'), array('',''), $searchphrase);
  920. }
  921. } else {
  922. // allow % and _ to remain in searchstring (without LIKE not problematic), * has no effect either!
  923. }
  924. return array($keyword => $searchphrase);
  925. }
  926. /**
  927. * Returns auto-generated password
  928. *
  929. * @param string $type: user, ...
  930. * @param integer $length (if no type is submitted)
  931. * @return pwd on success, empty string otherwise
  932. * @deprecated - use RandomLib
  933. */
  934. public static function pwd($type = null, $length = null) {
  935. trigger_error('deprecated');
  936. App::uses('RandomLib', 'Tools.Lib');
  937. if (!empty($type) && $type === 'user') {
  938. return RandomLib::pronounceablePwd(6);
  939. }
  940. if (!empty($length)) {
  941. return RandomLib::pronounceablePwd($length);
  942. }
  943. return '';
  944. }
  945. /**
  946. * TODO: move to Lib
  947. * Checks if string contains @ sign
  948. *
  949. * @param string
  950. * @return true if at least one @ is in the string, false otherwise
  951. */
  952. public static function containsAtSign($string = null) {
  953. if (!empty($string) && strpos($string, '@') !== false) {
  954. return true;
  955. }
  956. return false;
  957. }
  958. /**
  959. * Get the Corresponding Message to an HTTP Error Code
  960. *
  961. * @param integer $code: 100...505
  962. * @param boolean $autoTranslate
  963. * @return array codes if code is NULL, otherwise string $code (empty string on failure)
  964. */
  965. public function responseCodes($code = null, $autoTranslate = false) {
  966. //TODO: use core ones Controller::httpCodes
  967. $responses = array(
  968. 100 => 'Continue',
  969. 101 => 'Switching Protocols',
  970. 200 => 'OK',
  971. 201 => 'Created',
  972. 202 => 'Accepted',
  973. 203 => 'Non-Authoritative Information',
  974. 204 => 'No Content',
  975. 205 => 'Reset Content',
  976. 206 => 'Partial Content',
  977. 300 => 'Multiple Choices',
  978. 301 => 'Moved Permanently',
  979. 302 => 'Found',
  980. 303 => 'See Other',
  981. 304 => 'Not Modified',
  982. 305 => 'Use Proxy',
  983. 307 => 'Temporary Redirect',
  984. 400 => 'Bad Request',
  985. 401 => 'Unauthorized',
  986. 402 => 'Payment Required',
  987. 403 => 'Forbidden',
  988. 404 => 'Not Found',
  989. 405 => 'Method Not Allowed',
  990. 406 => 'Not Acceptable',
  991. 407 => 'Proxy Authentication Required',
  992. 408 => 'Request Time-out',
  993. 409 => 'Conflict',
  994. 410 => 'Gone',
  995. 411 => 'Length Required',
  996. 412 => 'Precondition Failed',
  997. 413 => 'Request Entity Too Large',
  998. 414 => 'Request-URI Too Large',
  999. 415 => 'Unsupported Media Type',
  1000. 416 => 'Requested range not satisfiable',
  1001. 417 => 'Expectation Failed',
  1002. 500 => 'Internal Server Error',
  1003. 501 => 'Not Implemented',
  1004. 502 => 'Bad Gateway',
  1005. 503 => 'Service Unavailable',
  1006. 504 => 'Gateway Time-out',
  1007. 505 => 'HTTP Version not supported' # MOD 2009-07-21 ms: 505 added!!!
  1008. );
  1009. if ($code === null) {
  1010. if ($autoTranslate) {
  1011. foreach ($responses as $key => $value) {
  1012. $responses[$key] = __($value);
  1013. }
  1014. }
  1015. return $responses;
  1016. }
  1017. // RFC 2616 states that all unknown HTTP codes must be treated the same as the
  1018. // base code in their class.
  1019. if (!isset($responses[$code])) {
  1020. $code = floor($code / 100) * 100;
  1021. }
  1022. if (!empty($code) && array_key_exists((int)$code, $responses)) {
  1023. if ($autoTranslate) {
  1024. return __($responses[$code]);
  1025. }
  1026. return $responses[$code];
  1027. }
  1028. return '';
  1029. }
  1030. /**
  1031. * Get the Corresponding Message to an HTTP Error Code
  1032. *
  1033. * @param integer $code: 4xx...5xx
  1034. * @return string
  1035. */
  1036. public function smtpResponseCodes($code = null, $autoTranslate = false) {
  1037. // 550 5.1.1 User is unknown
  1038. // 552 5.2.2 Storage Exceeded
  1039. $responses = array(
  1040. 451 => 'Need to authenticate',
  1041. 550 => 'User Unknown',
  1042. 552 => 'Storage Exceeded',
  1043. 554 => 'Refused'
  1044. );
  1045. if (!empty($code) && array_key_exists((int)$code, $responses)) {
  1046. if ($autoTranslate) {
  1047. return __($responses[$code]);
  1048. }
  1049. return $responses[$code];
  1050. }
  1051. return '';
  1052. }
  1053. }