CommonComponent.php 33 KB

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