CommonComponent.php 33 KB

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