CommonComponent.php 31 KB

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