CommonComponent.php 34 KB

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