CommonComponent.php 33 KB

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