CommonComponent.php 33 KB

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