CommonComponent.php 33 KB

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