CommonComponent.php 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040
  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 void
  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 void
  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 void
  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 void
  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 void
  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 true;
  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. */
  638. public static function getGroup($multiDimArray, $key, $matching = []) {
  639. if (!is_array($multiDimArray) || empty($key)) {
  640. return '';
  641. }
  642. foreach ($multiDimArray as $group => $data) {
  643. if (array_key_exists($key, $data)) {
  644. if (!empty($matching)) {
  645. if (array_key_exists($group, $matching)) {
  646. return $matching[$group];
  647. }
  648. return '';
  649. }
  650. return $group;
  651. }
  652. }
  653. return '';
  654. }
  655. /*** DEEP FUNCTIONS ***/
  656. /**
  657. * Move to boostrap?
  658. */
  659. public function trimDeep($value) {
  660. $value = is_array($value) ? array_map([$this, 'trimDeep'], $value) : trim($value);
  661. return $value;
  662. }
  663. /**
  664. * Move to boostrap?
  665. */
  666. public function specialcharsDeep($value) {
  667. $value = is_array($value) ? array_map([$this, 'specialcharsDeep'], $value) : htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
  668. return $value;
  669. }
  670. /**
  671. * Move to boostrap?
  672. */
  673. public function deep($function, $value) {
  674. $value = is_array($value) ? array_map([$this, $function], $value) : $function($value);
  675. return $value;
  676. }
  677. /**
  678. * Takes list of items and transforms it into an array
  679. * + cleaning (trim, no empty parts, etc).
  680. * Similar to CakeText::tokenize, but with more logic.
  681. *
  682. * //TODO: 3.4. parameter as array, move to Lib
  683. *
  684. * @deprecated Will be removed in 1.0.
  685. * @param string $string containing the parts
  686. * @param string $separator (defaults to ',')
  687. * @param bool $camelize (true/false): problems with äöüß etc!
  688. * @return array Results as list
  689. */
  690. public static function parseList($string, $separator = null, $camelize = false, $capitalize = true) {
  691. if ($separator === null) {
  692. $separator = ',';
  693. }
  694. // parses the list, but leaves tokens untouched inside () brackets
  695. $stringArray = CakeText::tokenize($string, $separator);
  696. $returnArray = [];
  697. if (empty($stringArray)) {
  698. return [];
  699. }
  700. foreach ($stringArray as $t) {
  701. $t = trim($t);
  702. if (!empty($t)) {
  703. if ($camelize === true) {
  704. $t = mb_strtolower($t);
  705. $t = Inflector::camelize(Inflector::underscore($t)); // problems with non-alpha chars!
  706. } elseif ($capitalize === true) {
  707. $t = ucwords($t);
  708. }
  709. $returnArray[] = $t;
  710. }
  711. }
  712. return $returnArray;
  713. }
  714. /**
  715. * //todo move to lib!!!
  716. *
  717. * @param string $s
  718. * @return mixed
  719. * @deprecated
  720. */
  721. public static function separators($s = null, $valueOnly = false) {
  722. $separatorsValues = [SEPARATOR_COMMA => ',', SEPARATOR_SEMI => ';', SEPARATOR_SPACE => ' ', SEPARATOR_TAB => TB, SEPARATOR_NL => NL];
  723. $separators = [SEPARATOR_COMMA => '[ , ] ' . __d('tools', 'Comma'), SEPARATOR_SEMI => '[ ; ] ' . __d('tools', 'Semicolon'), SEPARATOR_SPACE => '[ &nbsp; ] ' . __d('tools', 'Space'), SEPARATOR_TAB =>
  724. '[ &nbsp;&nbsp;&nbsp;&nbsp; ] ' . __d('tools', 'Tabulator'), SEPARATOR_NL => '[ \n ] ' . __d('tools', 'New Line')];
  725. if ($s !== null) {
  726. if (array_key_exists($s, $separators)) {
  727. if ($valueOnly) {
  728. return $separatorsValues[$s];
  729. }
  730. return $separators[$s];
  731. }
  732. return '';
  733. }
  734. return $valueOnly ? $separatorsValues : $separators;
  735. }
  736. /**
  737. * Expects email to be valid!
  738. *
  739. * @return array email - pattern: array('email'=>,'name'=>)
  740. * @deprecated
  741. */
  742. public function splitEmail($email) {
  743. $array = ['email' => '', 'name' => ''];
  744. if (($pos = mb_strpos($email, '<')) !== false) {
  745. $name = substr($email, 0, $pos);
  746. $email = substr($email, $pos + 1);
  747. }
  748. if (($pos = mb_strrpos($email, '>')) !== false) {
  749. $email = substr($email, 0, $pos);
  750. }
  751. $email = trim($email);
  752. if (!empty($email)) {
  753. $array['email'] = $email;
  754. }
  755. if (!empty($name)) {
  756. $array['name'] = trim($name);
  757. }
  758. return $array;
  759. }
  760. /**
  761. * @param string $email
  762. * @param string $name (optional, will use email otherwise)
  763. * @deprecated
  764. */
  765. public function combineEmail($email, $name = null) {
  766. if (empty($email)) {
  767. return '';
  768. }
  769. if (empty($name)) {
  770. $name = $email;
  771. }
  772. return $name . ' <' . $email['email'] . '>';
  773. }
  774. /**
  775. * TODO: move to Lib
  776. * returns type
  777. * - username: everything till @ (xyz@abc.de => xyz)
  778. * - hostname: whole domain (xyz@abc.de => abc.de)
  779. * - tld: top level domain only (xyz@abc.de => de)
  780. * - domain: if available (xyz@e.abc.de => abc)
  781. * - subdomain: if available (xyz@e.abc.de => e)
  782. * @param string $email: well formatted email! (containing one @ and one .)
  783. * @param string $type (TODO: defaults to return all elements)
  784. * @return string or false on failure
  785. * @deprecated
  786. */
  787. public function extractEmailInfo($email, $type = null) {
  788. //$checkpos = strrpos($email, '@');
  789. $nameParts = Hash::filter(explode('@', $email));
  790. if (count($nameParts) !== 2) {
  791. return false;
  792. }
  793. if ($type === 'username') {
  794. return $nameParts[0];
  795. }
  796. if ($type === 'hostname') {
  797. return $nameParts[1];
  798. }
  799. $checkpos = strrpos($nameParts[1], '.');
  800. $tld = trim(mb_substr($nameParts[1], $checkpos + 1));
  801. if ($type === 'tld') {
  802. return $tld;
  803. }
  804. $server = trim(mb_substr($nameParts[1], 0, $checkpos));
  805. //TODO; include 3rd-Level-Label
  806. $domain = '';
  807. $subdomain = '';
  808. $checkpos = strrpos($server, '.');
  809. if ($checkpos !== false) {
  810. $subdomain = trim(mb_substr($server, 0, $checkpos));
  811. $domain = trim(mb_substr($server, $checkpos + 1));
  812. }
  813. if ($type === 'domain') {
  814. return $domain;
  815. }
  816. if ($type === 'subdomain') {
  817. return $subdomain;
  818. }
  819. return '';
  820. }
  821. /**
  822. * Returns searchArray (options['wildcard'] TRUE/FALSE)
  823. * TODO: move to SearchLib etc
  824. *
  825. * @param string $keyword
  826. * @param string $searchphrase
  827. * @param array $options
  828. * @return array Cleaned array('keyword'=>'searchphrase') or array('keyword LIKE'=>'searchphrase')
  829. */
  830. public function getSearchItem($keyword = null, $searchphrase = null, $options = []) {
  831. if (isset($options['wildcard']) && $options['wildcard'] == true) {
  832. if (strpos($searchphrase, '*') !== false || strpos($searchphrase, '_') !== false) {
  833. $keyword .= ' LIKE';
  834. $searchphrase = str_replace('*', '%', $searchphrase);
  835. // additionally remove % ?
  836. //$searchphrase = str_replace(array('%','_'), array('',''), $searchphrase);
  837. }
  838. } else {
  839. // allow % and _ to remain in searchstring (without LIKE not problematic), * has no effect either!
  840. }
  841. return [$keyword => $searchphrase];
  842. }
  843. /**
  844. * TODO: move to Lib
  845. * Checks if string contains @ sign
  846. *
  847. * @param string
  848. * @return true if at least one @ is in the string, false otherwise
  849. */
  850. public static function containsAtSign($string = null) {
  851. if (!empty($string) && strpos($string, '@') !== false) {
  852. return true;
  853. }
  854. return false;
  855. }
  856. /**
  857. * Get the Corresponding Message to an HTTP Error Code
  858. *
  859. * @param int $code: 100...505
  860. * @param bool $autoTranslate
  861. * @return array codes if code is NULL, otherwise string $code (empty string on failure)
  862. */
  863. public function responseCodes($code = null, $autoTranslate = false) {
  864. //TODO: use core ones Controller::httpCodes
  865. $responses = [
  866. 100 => 'Continue',
  867. 101 => 'Switching Protocols',
  868. 200 => 'OK',
  869. 201 => 'Created',
  870. 202 => 'Accepted',
  871. 203 => 'Non-Authoritative Information',
  872. 204 => 'No Content',
  873. 205 => 'Reset Content',
  874. 206 => 'Partial Content',
  875. 300 => 'Multiple Choices',
  876. 301 => 'Moved Permanently',
  877. 302 => 'Found',
  878. 303 => 'See Other',
  879. 304 => 'Not Modified',
  880. 305 => 'Use Proxy',
  881. 307 => 'Temporary Redirect',
  882. 400 => 'Bad Request',
  883. 401 => 'Unauthorized',
  884. 402 => 'Payment Required',
  885. 403 => 'Forbidden',
  886. 404 => 'Not Found',
  887. 405 => 'Method Not Allowed',
  888. 406 => 'Not Acceptable',
  889. 407 => 'Proxy Authentication Required',
  890. 408 => 'Request Time-out',
  891. 409 => 'Conflict',
  892. 410 => 'Gone',
  893. 411 => 'Length Required',
  894. 412 => 'Precondition Failed',
  895. 413 => 'Request Entity Too Large',
  896. 414 => 'Request-URI Too Large',
  897. 415 => 'Unsupported Media Type',
  898. 416 => 'Requested range not satisfiable',
  899. 417 => 'Expectation Failed',
  900. 500 => 'Internal Server Error',
  901. 501 => 'Not Implemented',
  902. 502 => 'Bad Gateway',
  903. 503 => 'Service Unavailable',
  904. 504 => 'Gateway Time-out',
  905. 505 => 'HTTP Version not supported' # MOD 2009-07-21 ms: 505 added!!!
  906. ];
  907. if ($code === null) {
  908. if ($autoTranslate) {
  909. foreach ($responses as $key => $value) {
  910. $responses[$key] = __d('tools', $value);
  911. }
  912. }
  913. return $responses;
  914. }
  915. // RFC 2616 states that all unknown HTTP codes must be treated the same as the
  916. // base code in their class.
  917. if (!isset($responses[$code])) {
  918. $code = floor($code / 100) * 100;
  919. }
  920. if (!empty($code) && array_key_exists((int)$code, $responses)) {
  921. if ($autoTranslate) {
  922. return __d('tools', $responses[$code]);
  923. }
  924. return $responses[$code];
  925. }
  926. return '';
  927. }
  928. /**
  929. * Get the Corresponding Message to an HTTP Error Code
  930. *
  931. * @param int $code: 4xx...5xx
  932. * @return string
  933. */
  934. public function smtpResponseCodes($code = null, $autoTranslate = false) {
  935. // 550 5.1.1 User is unknown
  936. // 552 5.2.2 Storage Exceeded
  937. $responses = [
  938. 451 => 'Need to authenticate',
  939. 550 => 'User Unknown',
  940. 552 => 'Storage Exceeded',
  941. 554 => 'Refused'
  942. ];
  943. if (!empty($code) && array_key_exists((int)$code, $responses)) {
  944. if ($autoTranslate) {
  945. return __d('tools', $responses[$code]);
  946. }
  947. return $responses[$code];
  948. }
  949. return '';
  950. }
  951. }