CommonComponent.php 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088
  1. <?php
  2. if (!defined('CLASS_USER')) {
  3. define('CLASS_USER', 'User');
  4. }
  5. App::uses('Component', 'Controller');
  6. App::uses('Sanitize', 'Utility');
  7. App::uses('Utility', 'Tools.Utility');
  8. /**
  9. * A component included in every app to take care of common stuff.
  10. *
  11. * @author Mark Scherer
  12. * @copyright 2012 Mark Scherer
  13. * @license MIT
  14. */
  15. class CommonComponent extends Component {
  16. public $components = array('Session', 'RequestHandler');
  17. public $userModel = CLASS_USER;
  18. /**
  19. * For automatic startup
  20. * for this helper the controller has to be passed as reference
  21. *
  22. * @return void
  23. */
  24. public function initialize(Controller $Controller) {
  25. parent::initialize($Controller);
  26. $this->Controller = $Controller;
  27. }
  28. /**
  29. * For this helper the controller has to be passed as reference
  30. * for manual startup with $disableStartup = true (requires this to be called prior to any other method)
  31. *
  32. * @return void
  33. */
  34. public function startup(Controller $Controller = null) {
  35. parent::startup($Controller);
  36. // Data preparation
  37. if (!empty($this->Controller->request->data) && !Configure::read('DataPreparation.notrim')) {
  38. $this->Controller->request->data = $this->trimDeep($this->Controller->request->data);
  39. }
  40. if (!empty($this->Controller->request->query) && !Configure::read('DataPreparation.notrim')) {
  41. $this->Controller->request->query = $this->trimDeep($this->Controller->request->query);
  42. }
  43. if (!empty($this->Controller->request->params['named']) && !Configure::read('DataPreparation.notrim')) {
  44. $this->Controller->request->params['named'] = $this->trimDeep($this->Controller->request->params['named']);
  45. }
  46. if (!empty($this->Controller->request->params['pass']) && !Configure::read('DataPreparation.notrim')) {
  47. $this->Controller->request->params['pass'] = $this->trimDeep($this->Controller->request->params['pass']);
  48. }
  49. // Deprecation notices
  50. if (Configure::read('App.warnAboutNamedParams')) {
  51. if (!empty($Controller->request->params['named']) && ($referer = $Controller->request->referer(true)) && $referer !== '/') {
  52. trigger_error('Named params ' . json_encode($Controller->request->params['named']) . ' - from ' . $referer, E_USER_DEPRECATED);
  53. }
  54. }
  55. // Information gathering
  56. if (!Configure::read('App.disableMobileDetection') && ($mobile = $this->Session->read('Session.mobile')) === null) {
  57. App::uses('UserAgentLib', 'Tools.Lib');
  58. $UserAgentLib = new UserAgentLib();
  59. $mobile = (int)$UserAgentLib->isMobile();
  60. $this->Session->write('Session.mobile', $mobile);
  61. }
  62. // Auto layout switch
  63. if ($this->Controller->request->is('ajax')) {
  64. $this->Controller->layout = 'ajax';
  65. }
  66. }
  67. /**
  68. * Called after the Controller::beforeRender(), after the view class is loaded, and before the
  69. * Controller::render()
  70. *
  71. * @param object $Controller Controller with components to beforeRender
  72. * @return void
  73. */
  74. public function beforeRender(Controller $Controller) {
  75. if ($messages = $this->Session->read('Message')) {
  76. foreach ($messages as $message) {
  77. $this->flashMessage($message['message'], 'error');
  78. }
  79. $this->Session->delete('Message');
  80. }
  81. if ($this->Controller->request->is('ajax')) {
  82. $ajaxMessages = array_merge(
  83. (array)$this->Session->read('messages'),
  84. (array)Configure::read('messages')
  85. );
  86. // The header can be read with JavaScript and a custom Message can be displayed
  87. $this->Controller->response->header('X-Ajax-Flashmessage', json_encode($ajaxMessages));
  88. $this->Session->delete('messages');
  89. }
  90. // Custom options
  91. if (isset($Controller->options)) {
  92. $Controller->set('options', $Controller->options);
  93. }
  94. }
  95. /**
  96. * List all direct actions of a controller
  97. *
  98. * @return array Actions
  99. */
  100. public function listActions() {
  101. $class = Inflector::camelize($this->Controller->name) . 'Controller';
  102. $parentClassMethods = get_class_methods(get_parent_class($class));
  103. $subClassMethods = get_class_methods($class);
  104. $classMethods = array_diff($subClassMethods, $parentClassMethods);
  105. foreach ($classMethods as $key => $value) {
  106. if (substr($value, 0, 1) === '_') {
  107. unset($classMethods[$key]);
  108. }
  109. }
  110. return $classMethods;
  111. }
  112. /**
  113. * Convenience method to check on POSTED data.
  114. * Doesn't matter if it's POST or PUT.
  115. *
  116. * Note that since 2.4 you can use request->is(array('post', 'put') directly.
  117. *
  118. * @return bool If it is of type POST/PUT
  119. */
  120. public function isPosted() {
  121. return $this->Controller->request->is(array('post', 'put'));
  122. }
  123. /**
  124. * Adds a flash message.
  125. * Updates "messages" session content (to enable multiple messages of one type).
  126. *
  127. * @param string $message Message to output.
  128. * @param string $type Type ('error', 'warning', 'success', 'info' or custom class).
  129. * @return void
  130. */
  131. public function flashMessage($message, $type = null) {
  132. if (!$type) {
  133. $type = 'info';
  134. }
  135. $old = (array)$this->Session->read('messages');
  136. if (isset($old[$type]) && count($old[$type]) > 99) {
  137. array_shift($old[$type]);
  138. }
  139. $old[$type][] = $message;
  140. $this->Session->write('messages', $old);
  141. }
  142. /**
  143. * Adds a transient flash message.
  144. * These flash messages that are not saved (only available for current view),
  145. * will be merged into the session flash ones prior to output.
  146. *
  147. * @param string $message Message to output.
  148. * @param string $type Type ('error', 'warning', 'success', 'info' or custom class).
  149. * @return void
  150. */
  151. public static function transientFlashMessage($message, $type = null) {
  152. if (!$type) {
  153. $type = 'info';
  154. }
  155. $old = (array)Configure::read('messages');
  156. if (isset($old[$type]) && count($old[$type]) > 99) {
  157. array_shift($old[$type]);
  158. }
  159. $old[$type][] = $message;
  160. Configure::write('messages', $old);
  161. }
  162. /**
  163. * Add helper just in time (inside actions - only when needed)
  164. * aware of plugins
  165. * @param mixed $helpers (single string or multiple array)
  166. */
  167. public function loadHelper($helpers = array()) {
  168. $this->Controller->helpers = array_merge($this->Controller->helpers, (array)$helpers);
  169. }
  170. /**
  171. * Add lib just in time (inside actions - only when needed)
  172. * aware of plugins and config array (if passed)
  173. * ONLY works if constructor consists only of one param (settings)!
  174. * @param mixed $libs (single string or multiple array)
  175. * e.g.: array('Tools.MyLib'=>array('key'=>'value'), ...)
  176. */
  177. public function loadLib($libs = array()) {
  178. foreach ((array)$libs as $lib => $config) {
  179. if (is_int($lib)) {
  180. $lib = $config;
  181. $config = null;
  182. }
  183. list($plugin, $libName) = pluginSplit($lib);
  184. if (isset($this->Controller->{$libName})) {
  185. continue;
  186. }
  187. $package = 'Lib';
  188. if ($plugin) {
  189. $package = $plugin . '.' . $package;
  190. }
  191. App::uses($libName, $package);
  192. $this->Controller->{$libName} = new $libName($config);
  193. }
  194. }
  195. /**
  196. * Add component just in time (inside actions - only when needed)
  197. * aware of plugins and config array (if passed)
  198. * @param mixed $components (single string or multiple array)
  199. * @poaram bool $callbacks (defaults to true)
  200. */
  201. public function loadComponent($components = array(), $callbacks = true) {
  202. foreach ((array)$components as $component => $config) {
  203. if (is_int($component)) {
  204. $component = $config;
  205. $config = array();
  206. }
  207. list($plugin, $componentName) = pluginSplit($component);
  208. if (isset($this->Controller->{$componentName})) {
  209. continue;
  210. }
  211. $this->Controller->{$componentName} = $this->Controller->Components->load($component, $config);
  212. if (!$callbacks) {
  213. continue;
  214. }
  215. if (method_exists($this->Controller->{$componentName}, 'initialize')) {
  216. $this->Controller->{$componentName}->initialize($this->Controller);
  217. }
  218. if (method_exists($this->Controller->{$componentName}, 'startup')) {
  219. $this->Controller->{$componentName}->startup($this->Controller);
  220. }
  221. }
  222. }
  223. /**
  224. * Used to get the value of a passed param.
  225. *
  226. * @param mixed $var
  227. * @param mixed $default
  228. * @return mixed
  229. */
  230. public function getPassedParam($var, $default = null) {
  231. return (isset($this->Controller->request->params['pass'][$var])) ? $this->Controller->request->params['pass'][$var] : $default;
  232. }
  233. /**
  234. * Returns defaultUrlParams including configured prefixes.
  235. *
  236. * @return array Url params
  237. */
  238. public static function defaultUrlParams() {
  239. $defaults = array('plugin' => false);
  240. $prefixes = (array)Configure::read('Routing.prefixes');
  241. foreach ($prefixes as $prefix) {
  242. $defaults[$prefix] = false;
  243. }
  244. return $defaults;
  245. }
  246. /**
  247. * Returns current url (with all missing params automatically added).
  248. * Necessary for Router::url() and comparison of urls to work.
  249. *
  250. * @param bool $asString: defaults to false = array
  251. * @return mixed Url
  252. */
  253. public function currentUrl($asString = false) {
  254. if (isset($this->Controller->request->params['prefix']) && mb_strpos($this->Controller->request->params['action'], $this->Controller->request->params['prefix']) === 0) {
  255. $action = mb_substr($this->Controller->request->params['action'], mb_strlen($this->Controller->request->params['prefix']) + 1);
  256. } else {
  257. $action = $this->Controller->request->params['action'];
  258. }
  259. $url = array_merge($this->Controller->request->params['named'], $this->Controller->request->params['pass'], array('prefix' => isset($this->Controller->request->params['prefix']) ? $this->Controller->request->params['prefix'] : null,
  260. 'plugin' => $this->Controller->request->params['plugin'], 'action' => $action, 'controller' => $this->Controller->request->params['controller']));
  261. if ($asString === true) {
  262. return Router::url($url);
  263. }
  264. return $url;
  265. }
  266. /**
  267. * Tries to allow super admin access for certain urls via `Config.pwd`.
  268. * Only used in admin actions and only to prevent accidental data loss due to incorrect access.
  269. * Do not assume this to be a safe access control mechanism!
  270. *
  271. * Password can be passed as named param or query string param.
  272. *
  273. * @return bool Success
  274. */
  275. public function validAdminUrlAccess() {
  276. $pwd = Configure::read('Config.pwd');
  277. if (!$pwd) {
  278. return false;
  279. }
  280. $urlPwd = $this->getNamedParam('pwd');
  281. if (!$urlPwd) {
  282. $urlPwd = $this->getQueryParam('pwd');
  283. }
  284. if (!$urlPwd) {
  285. return false;
  286. }
  287. return $pwd === $urlPwd;
  288. }
  289. /**
  290. * Direct login for a specific user id.
  291. * Will respect full login scope (if defined in auth setup) as well as contained data and
  292. * can therefore return false if the login fails due to unmatched scope.
  293. *
  294. * @see DirectAuthentication auth adapter
  295. * @param mixed $id User id
  296. * @param array $settings Settings for DirectAuthentication
  297. * - fields
  298. * @return bool Success
  299. */
  300. public function manualLogin($id, $settings = array()) {
  301. $requestData = $this->Controller->request->data;
  302. $authData = $this->Controller->Auth->authenticate;
  303. $settings = array_merge($authData, $settings);
  304. $settings['fields'] = array('username' => 'id');
  305. $this->Controller->request->data = array($this->userModel => array('id' => $id));
  306. $this->Controller->Auth->authenticate = array('Tools.Direct' => $settings);
  307. $result = $this->Controller->Auth->login();
  308. $this->Controller->Auth->authenticate = $authData;
  309. $this->Controller->request->data = $requestData;
  310. return $result;
  311. }
  312. /**
  313. * Force login for a specific user id.
  314. * Only fails if the user does not exist or if he is already
  315. * logged in as it ignores the usual scope.
  316. *
  317. * Better than Auth->login($data) since it respects the other auth configs such as
  318. * fields, contain, recursive and userModel.
  319. *
  320. * @param mixed $id User id
  321. * @return bool Success
  322. */
  323. public function forceLogin($id) {
  324. $settings = array(
  325. 'scope' => array(),
  326. );
  327. return $this->manualLogin($id, $settings);
  328. /*
  329. if (!isset($this->User)) {
  330. $this->User = ClassRegistry::init(defined('CLASS_USER') ? CLASS_USER : $this->userModel);
  331. }
  332. $data = $this->User->get($id);
  333. if (!$data) {
  334. return false;
  335. }
  336. $data = $data[$this->userModel];
  337. return $this->Controller->Auth->login($data);
  338. */
  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. $this->Controller->redirect($this->Controller->referer($whereTo, true), $status);
  352. }
  353. $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. $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. $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 = array();
  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. $this->autoRedirect($whereTo, true, $status);
  408. }
  409. }
  410. $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. $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, array('title', 'canonical', 'description', 'keywords', 'robots', 'language', 'custom'))) {
  462. trigger_error(__('Meta Type invalid'), 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', array());
  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
  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 = array('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 = array('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
  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(array($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 = array()) {
  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(array($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(array($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(array($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
  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 = array();
  721. if (empty($stringArray)) {
  722. return array();
  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 = array(SEPARATOR_COMMA => ',', SEPARATOR_SEMI => ';', SEPARATOR_SPACE => ' ', SEPARATOR_TAB => TB, SEPARATOR_NL => NL);
  746. $separators = array(SEPARATOR_COMMA => '[ , ] ' . __('Comma'), SEPARATOR_SEMI => '[ ; ] ' . __('Semicolon'), SEPARATOR_SPACE => '[ &nbsp; ] ' . __('Space'), SEPARATOR_TAB =>
  747. '[ &nbsp;&nbsp;&nbsp;&nbsp; ] ' . __('Tabulator'), SEPARATOR_NL => '[ \n ] ' . __('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 = 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 = 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 = array()) {
  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 array($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 - 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 = array(
  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] = __($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 __($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 = array(
  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 __($responses[$code]);
  989. }
  990. return $responses[$code];
  991. }
  992. return '';
  993. }
  994. }