CommonComponent.php 33 KB

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