CommonComponent.php 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112
  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 boolean 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. * Used to get the value of a named param.
  235. * @deprecated - move to query strings instead
  236. *
  237. * @param mixed $var
  238. * @param mixed $default
  239. * @return mixed
  240. */
  241. public function getNamedParam($var, $default = null) {
  242. return (isset($this->Controller->request->params['named'][$var])) ? $this->Controller->request->params['named'][$var] : $default;
  243. }
  244. /**
  245. * Used to get the value of a get query.
  246. * @deprecated - use request->query() instead
  247. *
  248. * @param mixed $var
  249. * @param mixed $default
  250. * @return mixed
  251. */
  252. public function getQueryParam($var, $default = null) {
  253. trigger_error('deprecated - use $this->request->query()');
  254. return (isset($this->Controller->request->query[$var])) ? $this->Controller->request->query[$var] : $default;
  255. }
  256. /**
  257. * Returns defaultUrlParams including configured prefixes.
  258. *
  259. * @return array Url params
  260. */
  261. public static function defaultUrlParams() {
  262. $defaults = array('plugin' => false);
  263. $prefixes = (array)Configure::read('Routing.prefixes');
  264. foreach ($prefixes as $prefix) {
  265. $defaults[$prefix] = false;
  266. }
  267. return $defaults;
  268. }
  269. /**
  270. * Returns current url (with all missing params automatically added).
  271. * Necessary for Router::url() and comparison of urls to work.
  272. *
  273. * @param boolean $asString: defaults to false = array
  274. * @return mixed Url
  275. */
  276. public function currentUrl($asString = false) {
  277. if (isset($this->Controller->request->params['prefix']) && mb_strpos($this->Controller->request->params['action'], $this->Controller->request->params['prefix']) === 0) {
  278. $action = mb_substr($this->Controller->request->params['action'], mb_strlen($this->Controller->request->params['prefix']) + 1);
  279. } else {
  280. $action = $this->Controller->request->params['action'];
  281. }
  282. $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,
  283. 'plugin' => $this->Controller->request->params['plugin'], 'action' => $action, 'controller' => $this->Controller->request->params['controller']));
  284. if ($asString === true) {
  285. return Router::url($url);
  286. }
  287. return $url;
  288. }
  289. /**
  290. * Tries to allow super admin access for certain urls via `Config.pwd`.
  291. * Only used in admin actions and only to prevent accidental data loss due to incorrect access.
  292. * Do not assume this to be a safe access control mechanism!
  293. *
  294. * Password can be passed as named param or query string param.
  295. *
  296. * @return boolean Success
  297. */
  298. public function validAdminUrlAccess() {
  299. $pwd = Configure::read('Config.pwd');
  300. if (!$pwd) {
  301. return false;
  302. }
  303. $urlPwd = $this->getNamedParam('pwd');
  304. if (!$urlPwd) {
  305. $urlPwd = $this->getQueryParam('pwd');
  306. }
  307. if (!$urlPwd) {
  308. return false;
  309. }
  310. return $pwd === $urlPwd;
  311. }
  312. /**
  313. * Direct login for a specific user id.
  314. * Will respect full login scope (if defined in auth setup) as well as contained data and
  315. * can therefore return false if the login fails due to unmatched scope.
  316. *
  317. * @see DirectAuthentication auth adapter
  318. * @param mixed $id User id
  319. * @param array $settings Settings for DirectAuthentication
  320. * - fields
  321. * @return boolean Success
  322. */
  323. public function manualLogin($id, $settings = array()) {
  324. $requestData = $this->Controller->request->data;
  325. $authData = $this->Controller->Auth->authenticate;
  326. $settings = array_merge($authData, $settings);
  327. $settings['fields'] = array('username' => 'id');
  328. $this->Controller->request->data = array($this->userModel => array('id' => $id));
  329. $this->Controller->Auth->authenticate = array('Tools.Direct' => $settings);
  330. $result = $this->Controller->Auth->login();
  331. $this->Controller->Auth->authenticate = $authData;
  332. $this->Controller->request->data = $requestData;
  333. return $result;
  334. }
  335. /**
  336. * Force login for a specific user id.
  337. * Only fails if the user does not exist or if he is already
  338. * logged in as it ignores the usual scope.
  339. *
  340. * Better than Auth->login($data) since it respects the other auth configs such as
  341. * fields, contain, recursive and userModel.
  342. *
  343. * @param mixed $id User id
  344. * @return boolean Success
  345. */
  346. public function forceLogin($id) {
  347. $settings = array(
  348. 'scope' => array(),
  349. );
  350. return $this->manualLogin($id, $settings);
  351. /*
  352. if (!isset($this->User)) {
  353. $this->User = ClassRegistry::init(defined('CLASS_USER') ? CLASS_USER : $this->userModel);
  354. }
  355. $data = $this->User->get($id);
  356. if (!$data) {
  357. return false;
  358. }
  359. $data = $data[$this->userModel];
  360. return $this->Controller->Auth->login($data);
  361. */
  362. }
  363. /**
  364. * Smart Referer Redirect - will try to use an existing referer first
  365. * otherwise it will use the default url
  366. *
  367. * @param mixed $url
  368. * @param boolean $allowSelf if redirect to the same controller/action (url) is allowed
  369. * @param integer $status
  370. * @return void
  371. */
  372. public function autoRedirect($whereTo, $allowSelf = true, $status = null) {
  373. if ($allowSelf || $this->Controller->referer(null, true) !== '/' . $this->Controller->request->url) {
  374. $this->Controller->redirect($this->Controller->referer($whereTo, true), $status);
  375. }
  376. $this->Controller->redirect($whereTo, $status);
  377. }
  378. /**
  379. * Should be a 303, but:
  380. * 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.
  381. *
  382. * TODO: change to 303 with backwardscompatability for older browsers...
  383. *
  384. * @see http://en.wikipedia.org/wiki/Post/Redirect/Get
  385. * @param mixed $url
  386. * @param integer $status
  387. * @return void
  388. */
  389. public function postRedirect($whereTo, $status = 302) {
  390. $this->Controller->redirect($whereTo, $status);
  391. }
  392. /**
  393. * Combine auto with post
  394. * also allows whitelisting certain actions for autoRedirect (use Controller::$autoRedirectActions)
  395. * @param mixed $url
  396. * @param boolean $conditionalAutoRedirect false to skip whitelisting
  397. * @param integer $status
  398. * @return void
  399. */
  400. public function autoPostRedirect($whereTo, $conditionalAutoRedirect = true, $status = 302) {
  401. $referer = $this->Controller->referer($whereTo, true);
  402. if (!$conditionalAutoRedirect && !empty($referer)) {
  403. $this->postRedirect($referer, $status);
  404. }
  405. if (!empty($referer)) {
  406. $referer = Router::parse($referer);
  407. }
  408. if (!$conditionalAutoRedirect || empty($this->Controller->autoRedirectActions) || is_array($referer) && !empty($referer['action'])) {
  409. // Be sure that controller offset exists, otherwise you
  410. // will run into problems, if you use url rewriting.
  411. if (isset($referer['controller'])) {
  412. $refererController = Inflector::camelize($referer['controller']);
  413. }
  414. // fixme
  415. if (!isset($this->Controller->autoRedirectActions)) {
  416. $this->Controller->autoRedirectActions = array();
  417. }
  418. foreach ($this->Controller->autoRedirectActions as $action) {
  419. list($controller, $action) = pluginSplit($action);
  420. if (!empty($controller) && $refererController !== '*' && $refererController != $controller) {
  421. continue;
  422. }
  423. if (empty($controller) && $refererController != Inflector::camelize($this->Controller->request->params['controller'])) {
  424. continue;
  425. }
  426. if (!in_array($referer['action'], $this->Controller->autoRedirectActions)) {
  427. continue;
  428. }
  429. $this->autoRedirect($whereTo, true, $status);
  430. }
  431. }
  432. $this->postRedirect($whereTo, $status);
  433. }
  434. /**
  435. * Automatically add missing url parts of the current url including
  436. * - querystring (especially for 3.x then)
  437. * - named params (until 3.x when they will become deprecated)
  438. * - passed params
  439. *
  440. * @param mixed $url
  441. * @param integer $status
  442. * @param boolean $exit
  443. * @return void
  444. */
  445. public function completeRedirect($url = null, $status = null, $exit = true) {
  446. if ($url === null) {
  447. $url = $this->Controller->request->params;
  448. unset($url['named']);
  449. unset($url['pass']);
  450. unset($url['isAjax']);
  451. }
  452. if (is_array($url)) {
  453. $url += $this->Controller->request->params['named'];
  454. $url += $this->Controller->request->params['pass'];
  455. }
  456. return $this->Controller->redirect($url, $status, $exit);
  457. }
  458. /**
  459. * Only redirect to itself if cookies are on
  460. * Prevents problems with lost data
  461. * 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.
  462. *
  463. * @see http://en.wikipedia.org/wiki/Post/Redirect/Get
  464. * TODO: change to 303 with backwardscompatability for older browsers...
  465. * @param integer $status
  466. * @return void
  467. */
  468. public function prgRedirect($status = 302) {
  469. if (!empty($_COOKIE[Configure::read('Session.cookie')])) {
  470. $this->Controller->redirect('/' . $this->Controller->request->url, $status);
  471. }
  472. }
  473. /**
  474. * Handler for passing some meta data to the view
  475. * uses CommonHelper to include them in the layout
  476. *
  477. * @param type (relevance):
  478. * - title (10), description (9), robots(7), language(5), keywords (0)
  479. * - custom: abstract (1), category(1), GOOGLEBOT(0) ...
  480. * @return void
  481. */
  482. public function setMeta($type, $content, $prep = true) {
  483. if (!in_array($type, array('title', 'canonical', 'description', 'keywords', 'robots', 'language', 'custom'))) {
  484. trigger_error(__('Meta Type invalid'), E_USER_WARNING);
  485. return;
  486. }
  487. if ($type === 'canonical' && $prep) {
  488. $content = Router::url($content);
  489. }
  490. if ($type === 'canonical' && $prep) {
  491. $content = h($content);
  492. }
  493. Configure::write('Meta.' . $type, $content);
  494. }
  495. /**
  496. * Set headers to cache this request.
  497. * Opposite of Controller::disableCache()
  498. * TODO: set response class header instead
  499. *
  500. * @param integer $seconds
  501. * @return void
  502. */
  503. public function forceCache($seconds = HOUR) {
  504. $this->Controller->response->header('Cache-Control', 'public, max-age=' . $seconds);
  505. $this->Controller->response->header('Last-modified', gmdate("D, j M Y H:i:s", time()) . " GMT");
  506. $this->Controller->response->header('Expires', gmdate("D, j M Y H:i:s", time() + $seconds) . " GMT");
  507. }
  508. /**
  509. * Referrer checking (where does the user come from)
  510. * Only returns true for a valid external referrer.
  511. *
  512. * @return boolean Success
  513. */
  514. public function isForeignReferer($ref = null) {
  515. if ($ref === null) {
  516. $ref = env('HTTP_REFERER');
  517. }
  518. if (!$ref) {
  519. return false;
  520. }
  521. $base = Configure::read('App.fullBaseUrl') . '/';
  522. if (strpos($ref, $base) === 0) {
  523. return false;
  524. }
  525. return true;
  526. }
  527. /**
  528. * CommonComponent::denyAccess()
  529. *
  530. * @return void
  531. */
  532. public function denyAccess() {
  533. $ref = env('HTTP_USER_AGENT');
  534. if ($this->isForeignReferer($ref)) {
  535. if (strpos(strtolower($ref), 'http://anonymouse.org/') === 0) {
  536. $this->cakeError('error406', array());
  537. }
  538. }
  539. }
  540. /**
  541. * CommonComponent::monitorCookieProblems()
  542. *
  543. * @return void
  544. */
  545. public function monitorCookieProblems() {
  546. $ip = $this->RequestHandler->getClientIP();
  547. $host = gethostbyaddr($ip);
  548. $sessionId = session_id();
  549. if (empty($sessionId)) {
  550. $sessionId = '--';
  551. }
  552. if (empty($_REQUEST[Configure::read('Session.cookie')]) && !($res = Cache::read($ip))) {
  553. $this->log('CookieProblem:: SID: ' . $sessionId . ' | IP: ' . $ip . ' (' . $host . ') | REF: ' . $this->Controller->referer() . ' | Agent: ' . env('HTTP_USER_AGENT'), 'noscript');
  554. Cache::write($ip, 1);
  555. }
  556. }
  557. /**
  558. * //todo: move to Utility?
  559. *
  560. * @return boolean true if disabled (bots, etc), false if enabled
  561. */
  562. public static function cookiesDisabled() {
  563. if (!empty($_COOKIE) && !empty($_COOKIE[Configure::read('Session.cookie')])) {
  564. return false;
  565. }
  566. return true;
  567. }
  568. /**
  569. * Quick sql debug from controller dynamically
  570. * or statically from just about any other place in the script
  571. *
  572. * @param boolean $exit If script should exit.
  573. * @return boolean Success
  574. */
  575. public function sql($exit = true) {
  576. if (isset($this->Controller)) {
  577. $object = $this->Controller->{$this->Controller->modelClass};
  578. } else {
  579. $object = ClassRegistry::init(defined('CLASS_USER') ? CLASS_USER : $this->userModel);
  580. }
  581. $log = $object->getDataSource()->getLog(false, false);
  582. foreach ($log['log'] as $key => $value) {
  583. if (strpos($value['query'], 'SHOW ') === 0 || strpos($value['query'], 'SELECT CHARACTER_SET_NAME ') === 0) {
  584. unset($log['log'][$key]);
  585. continue;
  586. }
  587. }
  588. if ($exit) {
  589. debug($log);
  590. exit();
  591. }
  592. $log = print_r($log, true);
  593. App::uses('CakeLog', 'Log');
  594. return CakeLog::write('sql', $log);
  595. }
  596. /**
  597. * Localize
  598. *
  599. * @return boolean Success
  600. */
  601. public function localize($lang = null) {
  602. if ($lang === null) {
  603. $lang = Configure::read('Config.language');
  604. }
  605. if (empty($lang)) {
  606. return false;
  607. }
  608. if (($pos = strpos($lang, '-')) !== false) {
  609. $lang = substr($lang, 0, $pos);
  610. }
  611. if ($lang === DEFAULT_LANGUAGE) {
  612. return null;
  613. }
  614. if (!($pattern = Configure::read('LocalizationPattern.' . $lang))) {
  615. return false;
  616. }
  617. foreach ((array)$pattern as $key => $value) {
  618. Configure::write('Localization.' . $key, $value);
  619. }
  620. return true;
  621. }
  622. /**
  623. * Main controller function for consistency in controller naming
  624. *
  625. * @deprecated
  626. * @return void
  627. */
  628. public function ensureControllerConsistency() {
  629. // problems with plugins
  630. if (!empty($this->Controller->request->params['plugin'])) {
  631. return;
  632. }
  633. if (($name = strtolower(Inflector::underscore($this->Controller->name))) !== $this->Controller->request->params['controller']) {
  634. $this->Controller->log('301: ' . $this->Controller->request->params['controller'] . ' => ' . $name . ' (Ref ' . $this->Controller->referer() . ')', '301'); // log problem with controller naming
  635. if (!$this->Controller->RequestHandler->isPost()) {
  636. // underscored version is the only valid one to avoid duplicate content
  637. $url = array('controller' => $name, 'action' => $this->Controller->request->params['action']);
  638. $url = array_merge($url, $this->Controller->request->params['pass'], $this->Controller->request->params['named']);
  639. //TODO: add plugin/admin stuff which right now is supposed to work automatically
  640. $this->Controller->redirect($url, 301);
  641. }
  642. }
  643. return true;
  644. // problem with extensions (rss etc)
  645. if (empty($this->Controller->request->params['prefix']) && ($currentUrl = $this->currentUrl(true)) != $this->Controller->here) {
  646. //pr($this->Controller->here);
  647. //pr($currentUrl);
  648. $this->log('301: ' . $this->Controller->here . ' => ' . $currentUrl . ' (Referer ' . $this->Controller->referer() . ')', '301');
  649. if (!$this->Controller->RequestHandler->isPost()) {
  650. $url = array('controller' => $this->Controller->request->params['controller'], 'action' => $this->Controller->request->params['action']);
  651. $url = array_merge($url, $this->Controller->request->params['pass'], $this->Controller->request->params['named']);
  652. $this->Controller->redirect($url, 301);
  653. }
  654. }
  655. }
  656. /**
  657. * Main controller function for seo-slugs
  658. * passed titleSlug != current title => redirect to the expected one
  659. *
  660. * @deprecated
  661. * @return void
  662. */
  663. public function ensureConsistency($id, $passedTitleSlug, $currentTitle) {
  664. $expectedTitle = slug($currentTitle);
  665. if (empty($passedTitleSlug) || $expectedTitle != $passedTitleSlug) { # case sensitive!!!
  666. $ref = env('HTTP_REFERER');
  667. if (!$this->isForeignReferer($ref)) {
  668. $this->Controller->log('Internal ConsistencyProblem at \'' . $ref . '\' - [' . $passedTitleSlug . '] instead of [' . $expectedTitle . ']', 'referer');
  669. } else {
  670. $this->Controller->log('External ConsistencyProblem at \'' . $ref . '\' - [' . $passedTitleSlug . '] instead of [' . $expectedTitle . ']', 'referer');
  671. }
  672. $this->Controller->redirect(array($id, $expectedTitle), 301);
  673. }
  674. }
  675. /**
  676. * Try to detect group for a multidim array for select boxes.
  677. * Extracts the group name of the selected key.
  678. *
  679. * @param array $array
  680. * @param string $key
  681. * @param array $matching
  682. * @return string result
  683. */
  684. public static function getGroup($multiDimArray, $key, $matching = array()) {
  685. if (!is_array($multiDimArray) || empty($key)) {
  686. return '';
  687. }
  688. foreach ($multiDimArray as $group => $data) {
  689. if (array_key_exists($key, $data)) {
  690. if (!empty($matching)) {
  691. if (array_key_exists($group, $matching)) {
  692. return $matching[$group];
  693. }
  694. return '';
  695. }
  696. return $group;
  697. }
  698. }
  699. return '';
  700. }
  701. /*** DEEP FUNCTIONS ***/
  702. /**
  703. * Move to boostrap?
  704. */
  705. public function trimDeep($value) {
  706. $value = is_array($value) ? array_map(array($this, 'trimDeep'), $value) : trim($value);
  707. return $value;
  708. }
  709. /**
  710. * Move to boostrap?
  711. */
  712. public function specialcharsDeep($value) {
  713. $value = is_array($value) ? array_map(array($this, 'specialcharsDeep'), $value) : htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
  714. return $value;
  715. }
  716. /**
  717. * Move to boostrap?
  718. */
  719. public function deep($function, $value) {
  720. $value = is_array($value) ? array_map(array($this, $function), $value) : $function($value);
  721. return $value;
  722. }
  723. /**
  724. * Takes list of items and transforms it into an array
  725. * + cleaning (trim, no empty parts, etc).
  726. * Similar to String::tokenize, but with more logic.
  727. *
  728. * //TODO: 3.4. parameter as array, move to Lib
  729. *
  730. * @deprecated
  731. * @param string $string containing the parts
  732. * @param string $separator (defaults to ',')
  733. * @param boolean $camelize (true/false): problems with äöüß etc!
  734. * @return array Results as list
  735. */
  736. public function parseList($string, $separator = null, $camelize = false, $capitalize = true) {
  737. if ($separator === null) {
  738. $separator = ',';
  739. }
  740. // parses the list, but leaves tokens untouched inside () brackets
  741. $stringArray = String::tokenize($string, $separator);
  742. $returnArray = array();
  743. if (empty($stringArray)) {
  744. return array();
  745. }
  746. foreach ($stringArray as $t) {
  747. $t = trim($t);
  748. if (!empty($t)) {
  749. if ($camelize === true) {
  750. $t = mb_strtolower($t);
  751. $t = Inflector::camelize(Inflector::underscore($t)); // problems with non-alpha chars!
  752. } elseif ($capitalize === true) {
  753. $t = ucwords($t);
  754. }
  755. $returnArray[] = $t;
  756. }
  757. }
  758. return $returnArray;
  759. }
  760. /**
  761. * //todo move to lib!!!
  762. *
  763. * @param string $s
  764. * @return mixed
  765. */
  766. public static function separators($s = null, $valueOnly = false) {
  767. $separatorsValues = array(SEPARATOR_COMMA => ',', SEPARATOR_SEMI => ';', SEPARATOR_SPACE => ' ', SEPARATOR_TAB => TB, SEPARATOR_NL => NL);
  768. $separators = array(SEPARATOR_COMMA => '[ , ] ' . __('Comma'), SEPARATOR_SEMI => '[ ; ] ' . __('Semicolon'), SEPARATOR_SPACE => '[ &nbsp; ] ' . __('Space'), SEPARATOR_TAB =>
  769. '[ &nbsp;&nbsp;&nbsp;&nbsp; ] ' . __('Tabulator'), SEPARATOR_NL => '[ \n ] ' . __('New Line'));
  770. if ($s !== null) {
  771. if (array_key_exists($s, $separators)) {
  772. if ($valueOnly) {
  773. return $separatorsValues[$s];
  774. }
  775. return $separators[$s];
  776. }
  777. return '';
  778. }
  779. return $valueOnly ? $separatorsValues : $separators;
  780. }
  781. /**
  782. * Expects email to be valid!
  783. * TODO: move to Lib
  784. *
  785. * @return array email - pattern: array('email'=>,'name'=>)
  786. */
  787. public function splitEmail($email, $abortOnError = false) {
  788. $array = array('email' => '', 'name' => '');
  789. if (($pos = mb_strpos($email, '<')) !== false) {
  790. $name = substr($email, 0, $pos);
  791. $email = substr($email, $pos + 1);
  792. }
  793. if (($pos = mb_strrpos($email, '>')) !== false) {
  794. $email = substr($email, 0, $pos);
  795. }
  796. $email = trim($email);
  797. if (!empty($email)) {
  798. $array['email'] = $email;
  799. }
  800. if (!empty($name)) {
  801. $array['name'] = trim($name);
  802. }
  803. return $array;
  804. }
  805. /**
  806. * TODO: move to Lib
  807. * @param string $email
  808. * @param string $name (optional, will use email otherwise)
  809. */
  810. public function combineEmail($email, $name = null) {
  811. if (empty($email)) {
  812. return '';
  813. }
  814. if (empty($name)) {
  815. $name = $email;
  816. }
  817. return $name . ' <' . $email['email'] . '>';
  818. }
  819. /**
  820. * TODO: move to Lib
  821. * returns type
  822. * - username: everything till @ (xyz@abc.de => xyz)
  823. * - hostname: whole domain (xyz@abc.de => abc.de)
  824. * - tld: top level domain only (xyz@abc.de => de)
  825. * - domain: if available (xyz@e.abc.de => abc)
  826. * - subdomain: if available (xyz@e.abc.de => e)
  827. * @param string $email: well formatted email! (containing one @ and one .)
  828. * @param string $type (TODO: defaults to return all elements)
  829. * @return string or false on failure
  830. */
  831. public function extractEmailInfo($email, $type = null) {
  832. //$checkpos = strrpos($email, '@');
  833. $nameParts = explode('@', $email);
  834. if (count($nameParts) !== 2) {
  835. return false;
  836. }
  837. if ($type === 'username') {
  838. return $nameParts[0];
  839. }
  840. if ($type === 'hostname') {
  841. return $nameParts[1];
  842. }
  843. $checkpos = strrpos($nameParts[1], '.');
  844. $tld = trim(mb_substr($nameParts[1], $checkpos + 1));
  845. if ($type === 'tld') {
  846. return $tld;
  847. }
  848. $server = trim(mb_substr($nameParts[1], 0, $checkpos));
  849. //TODO; include 3rd-Level-Label
  850. $domain = '';
  851. $subdomain = '';
  852. $checkpos = strrpos($server, '.');
  853. if ($checkpos !== false) {
  854. $subdomain = trim(mb_substr($server, 0, $checkpos));
  855. $domain = trim(mb_substr($server, $checkpos + 1));
  856. }
  857. if ($type === 'domain') {
  858. return $domain;
  859. }
  860. if ($type === 'subdomain') {
  861. return $subdomain;
  862. }
  863. //$hostParts = explode();
  864. //$check = trim(mb_substr($email, $checkpos));
  865. return '';
  866. }
  867. /**
  868. * Returns searchArray (options['wildcard'] TRUE/FALSE)
  869. * TODO: move to SearchLib etc
  870. *
  871. * @param string $keyword
  872. * @param string $searchphrase
  873. * @param array $options
  874. * @return array Cleaned array('keyword'=>'searchphrase') or array('keyword LIKE'=>'searchphrase')
  875. */
  876. public function getSearchItem($keyword = null, $searchphrase = null, $options = array()) {
  877. if (isset($options['wildcard']) && $options['wildcard'] == true) {
  878. if (strpos($searchphrase, '*') !== false || strpos($searchphrase, '_') !== false) {
  879. $keyword .= ' LIKE';
  880. $searchphrase = str_replace('*', '%', $searchphrase);
  881. // additionally remove % ?
  882. //$searchphrase = str_replace(array('%','_'), array('',''), $searchphrase);
  883. }
  884. } else {
  885. // allow % and _ to remain in searchstring (without LIKE not problematic), * has no effect either!
  886. }
  887. return array($keyword => $searchphrase);
  888. }
  889. /**
  890. * Returns auto-generated password
  891. *
  892. * @param string $type: user, ...
  893. * @param integer $length (if no type is submitted)
  894. * @return pwd on success, empty string otherwise
  895. * @deprecated - use RandomLib
  896. */
  897. public static function pwd($type = null, $length = null) {
  898. trigger_error('deprecated');
  899. App::uses('RandomLib', 'Tools.Lib');
  900. if (!empty($type) && $type === 'user') {
  901. return RandomLib::pronounceablePwd(6);
  902. }
  903. if (!empty($length)) {
  904. return RandomLib::pronounceablePwd($length);
  905. }
  906. return '';
  907. }
  908. /**
  909. * TODO: move to Lib
  910. * Checks if string contains @ sign
  911. *
  912. * @param string
  913. * @return true if at least one @ is in the string, false otherwise
  914. */
  915. public static function containsAtSign($string = null) {
  916. if (!empty($string) && strpos($string, '@') !== false) {
  917. return true;
  918. }
  919. return false;
  920. }
  921. /**
  922. * Get the Corresponding Message to an HTTP Error Code
  923. *
  924. * @param integer $code: 100...505
  925. * @param boolean $autoTranslate
  926. * @return array codes if code is NULL, otherwise string $code (empty string on failure)
  927. */
  928. public function responseCodes($code = null, $autoTranslate = false) {
  929. //TODO: use core ones Controller::httpCodes
  930. $responses = array(
  931. 100 => 'Continue',
  932. 101 => 'Switching Protocols',
  933. 200 => 'OK',
  934. 201 => 'Created',
  935. 202 => 'Accepted',
  936. 203 => 'Non-Authoritative Information',
  937. 204 => 'No Content',
  938. 205 => 'Reset Content',
  939. 206 => 'Partial Content',
  940. 300 => 'Multiple Choices',
  941. 301 => 'Moved Permanently',
  942. 302 => 'Found',
  943. 303 => 'See Other',
  944. 304 => 'Not Modified',
  945. 305 => 'Use Proxy',
  946. 307 => 'Temporary Redirect',
  947. 400 => 'Bad Request',
  948. 401 => 'Unauthorized',
  949. 402 => 'Payment Required',
  950. 403 => 'Forbidden',
  951. 404 => 'Not Found',
  952. 405 => 'Method Not Allowed',
  953. 406 => 'Not Acceptable',
  954. 407 => 'Proxy Authentication Required',
  955. 408 => 'Request Time-out',
  956. 409 => 'Conflict',
  957. 410 => 'Gone',
  958. 411 => 'Length Required',
  959. 412 => 'Precondition Failed',
  960. 413 => 'Request Entity Too Large',
  961. 414 => 'Request-URI Too Large',
  962. 415 => 'Unsupported Media Type',
  963. 416 => 'Requested range not satisfiable',
  964. 417 => 'Expectation Failed',
  965. 500 => 'Internal Server Error',
  966. 501 => 'Not Implemented',
  967. 502 => 'Bad Gateway',
  968. 503 => 'Service Unavailable',
  969. 504 => 'Gateway Time-out',
  970. 505 => 'HTTP Version not supported' # MOD 2009-07-21 ms: 505 added!!!
  971. );
  972. if ($code === null) {
  973. if ($autoTranslate) {
  974. foreach ($responses as $key => $value) {
  975. $responses[$key] = __($value);
  976. }
  977. }
  978. return $responses;
  979. }
  980. // RFC 2616 states that all unknown HTTP codes must be treated the same as the
  981. // base code in their class.
  982. if (!isset($responses[$code])) {
  983. $code = floor($code / 100) * 100;
  984. }
  985. if (!empty($code) && array_key_exists((int)$code, $responses)) {
  986. if ($autoTranslate) {
  987. return __($responses[$code]);
  988. }
  989. return $responses[$code];
  990. }
  991. return '';
  992. }
  993. /**
  994. * Get the Corresponding Message to an HTTP Error Code
  995. *
  996. * @param integer $code: 4xx...5xx
  997. * @return string
  998. */
  999. public function smtpResponseCodes($code = null, $autoTranslate = false) {
  1000. // 550 5.1.1 User is unknown
  1001. // 552 5.2.2 Storage Exceeded
  1002. $responses = array(
  1003. 451 => 'Need to authenticate',
  1004. 550 => 'User Unknown',
  1005. 552 => 'Storage Exceeded',
  1006. 554 => 'Refused'
  1007. );
  1008. if (!empty($code) && array_key_exists((int)$code, $responses)) {
  1009. if ($autoTranslate) {
  1010. return __($responses[$code]);
  1011. }
  1012. return $responses[$code];
  1013. }
  1014. return '';
  1015. }
  1016. }