CommonComponent.php 33 KB

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