CommonComponent.php 34 KB

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