CommonComponent.php 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420
  1. <?php
  2. /* just some common functions - by mark */
  3. App::uses('Component', 'Controller');
  4. App::uses('Sanitize', 'Utility');
  5. App::uses('Utility', 'Tools.Utility');
  6. /**
  7. * A component included in every app to take care of common stuff
  8. *
  9. * @author Mark Scherer
  10. * @copyright 2012 Mark Scherer
  11. * @license MIT
  12. *
  13. */
  14. class CommonComponent extends Component {
  15. public $components = array('Session', 'RequestHandler');
  16. public $userModel = 'User';
  17. public $allowedChars = array('Ä', 'Ö', 'Ü', 'ä', 'ö', 'ü', 'ß');
  18. public $removeChars = false;
  19. /**
  20. * For automatic startup
  21. * for this helper the controller has to be passed as reference
  22. *
  23. * @return void
  24. */
  25. public function initialize(Controller $Controller) {
  26. parent::initialize($Controller);
  27. $this->Controller = $Controller;
  28. }
  29. /**
  30. * For this helper the controller has to be passed as reference
  31. * for manual startup with $disableStartup = true (requires this to be called prior to any other method)
  32. *
  33. * @return void
  34. */
  35. public function startup(Controller $Controller = null) {
  36. parent::startup($Controller);
  37. // Data preparation
  38. if (!empty($this->Controller->request->data) && !Configure::read('DataPreparation.notrim')) {
  39. $this->Controller->request->data = $this->trimDeep($this->Controller->request->data);
  40. }
  41. if (!empty($this->Controller->request->query) && !Configure::read('DataPreparation.notrim')) {
  42. $this->Controller->request->query = $this->trimDeep($this->Controller->request->query);
  43. }
  44. if (!empty($this->Controller->request->params['named']) && !Configure::read('DataPreparation.notrim')) {
  45. $this->Controller->request->params['named'] = $this->trimDeep($this->Controller->request->params['named']);
  46. }
  47. if (!empty($this->Controller->request->params['pass']) && !Configure::read('DataPreparation.notrim')) {
  48. $this->Controller->request->params['pass'] = $this->trimDeep($this->Controller->request->params['pass']);
  49. }
  50. // Information gathering
  51. if (!Configure::read('App.disableMobileDetection') && ($mobile = $this->Session->read('Session.mobile')) === null) {
  52. App::uses('UserAgentLib', 'Tools.Lib');
  53. $UserAgentLib = new UserAgentLib();
  54. $mobile = (int)$UserAgentLib->isMobile();
  55. $this->Session->write('Session.mobile', $mobile);
  56. }
  57. // Auto layout switch
  58. if ($this->Controller->request->is('ajax')) {
  59. $this->Controller->layout = 'ajax';
  60. }
  61. }
  62. /**
  63. * Called after the Controller::beforeRender(), after the view class is loaded, and before the
  64. * Controller::render()
  65. *
  66. * @param object $Controller Controller with components to beforeRender
  67. * @return void
  68. */
  69. public function beforeRender(Controller $Controller) {
  70. if ($messages = $this->Session->read('Message')) {
  71. foreach ($messages as $message) {
  72. $this->flashMessage($message['message'], 'error');
  73. }
  74. $this->Session->delete('Message');
  75. }
  76. if ($this->Controller->request->is('ajax')) {
  77. $ajaxMessages = array_merge(
  78. (array)$this->Session->read('messages'),
  79. (array)Configure::read('messages')
  80. );
  81. // The header can be read with JavaScript and a custom Message can be displayed
  82. $this->Controller->response->header('X-Ajax-Flashmessage', json_encode($ajaxMessages));
  83. // AJAX debug off
  84. Configure::write('debug', 0);
  85. }
  86. // Custom options
  87. if (isset($Controller->options)) {
  88. $Controller->set('options', $Controller->options);
  89. }
  90. }
  91. /**
  92. * List all direct actions of a controller
  93. *
  94. * @return array Actions
  95. */
  96. public function listActions() {
  97. $class = Inflector::camelize($this->Controller->name) . 'Controller';
  98. $parentClassMethods = get_class_methods(get_parent_class($class));
  99. $subClassMethods = get_class_methods($class);
  100. $classMethods = array_diff($subClassMethods, $parentClassMethods);
  101. foreach ($classMethods as $key => $value) {
  102. if (substr($value, 0, 1) === '_') {
  103. unset($classMethods[$key]);
  104. }
  105. }
  106. return $classMethods;
  107. }
  108. /**
  109. * Convenience method to check on POSTED data.
  110. * Doesn't matter if it's POST or PUT.
  111. *
  112. * @return boolean isPost
  113. */
  114. public function isPosted() {
  115. return $this->Controller->request->is('post') || $this->Controller->request->is('put');
  116. }
  117. /**
  118. * Updates FlashMessage SessionContent (to enable unlimited messages of one case)
  119. *
  120. * @param string messagestring
  121. * @param string class ['error', 'warning', 'success', 'info']
  122. * @return void
  123. */
  124. public function flashMessage($messagestring, $class = null) {
  125. switch ($class) {
  126. case 'error':
  127. case 'warning':
  128. case 'success':
  129. break;
  130. default:
  131. $class = 'info';
  132. break;
  133. }
  134. $old = (array)$this->Session->read('messages');
  135. if (isset($old[$class]) && count($old[$class]) > 99) {
  136. array_shift($old[$class]);
  137. }
  138. $old[$class][] = $messagestring;
  139. $this->Session->write('messages', $old);
  140. }
  141. /**
  142. * FlashMessages that are not saved (only for current view)
  143. * will be merged into the session flash ones prior to output
  144. *
  145. * @param string messagestring
  146. * @param string class ['error', 'warning', 'success', 'info']
  147. * @return void
  148. */
  149. public static function transientFlashMessage($messagestring, $class = null) {
  150. switch ($class) {
  151. case 'error':
  152. case 'warning':
  153. case 'success':
  154. break;
  155. default:
  156. $class = 'info';
  157. break;
  158. }
  159. $old = (array)Configure::read('messages');
  160. if (isset($old[$class]) && count($old[$class]) > 99) {
  161. array_shift($old[$class]);
  162. }
  163. $old[$class][] = $messagestring;
  164. Configure::write('messages', $old);
  165. }
  166. /**
  167. * Add helper just in time (inside actions - only when needed)
  168. * aware of plugins
  169. * @param mixed $helpers (single string or multiple array)
  170. */
  171. public function loadHelper($helpers = array()) {
  172. $this->Controller->helpers = array_merge($this->Controller->helpers, (array)$helpers);
  173. }
  174. /**
  175. * Add lib just in time (inside actions - only when needed)
  176. * aware of plugins and config array (if passed)
  177. * ONLY works if constructor consists only of one param (settings)!
  178. * @param mixed $libs (single string or multiple array)
  179. * e.g.: array('Tools.MyLib'=>array('key'=>'value'), ...)
  180. */
  181. public function loadLib($libs = array()) {
  182. foreach ((array)$libs as $lib => $config) {
  183. if (is_int($lib)) {
  184. $lib = $config;
  185. $config = null;
  186. }
  187. list($plugin, $libName) = pluginSplit($lib);
  188. if (isset($this->Controller->{$libName})) {
  189. continue;
  190. }
  191. $package = 'Lib';
  192. if ($plugin) {
  193. $package = $plugin . '.' . $package;
  194. }
  195. App::uses($libName, $package);
  196. $this->Controller->{$libName} = new $libName($config);
  197. }
  198. }
  199. /**
  200. * Add component just in time (inside actions - only when needed)
  201. * aware of plugins and config array (if passed)
  202. * @param mixed $components (single string or multiple array)
  203. * @poaram bool $callbacks (defaults to true)
  204. */
  205. public function loadComponent($components = array(), $callbacks = true) {
  206. foreach ((array)$components as $component => $config) {
  207. if (is_int($component)) {
  208. $component = $config;
  209. $config = array();
  210. }
  211. list($plugin, $componentName) = pluginSplit($component);
  212. if (isset($this->Controller->{$componentName})) {
  213. continue;
  214. }
  215. $this->Controller->{$componentName} = $this->Controller->Components->load($component, $config);
  216. if (!$callbacks) {
  217. continue;
  218. }
  219. if (method_exists($this->Controller->{$componentName}, 'initialize')) {
  220. $this->Controller->{$componentName}->initialize($this->Controller);
  221. }
  222. if (method_exists($this->Controller->{$componentName}, 'startup')) {
  223. $this->Controller->{$componentName}->startup($this->Controller);
  224. }
  225. }
  226. }
  227. /**
  228. * Used to get the value of a named param
  229. * @param mixed $var
  230. * @param mixed $default
  231. * @return mixed
  232. */
  233. public function getPassedParam($var, $default = null) {
  234. return (isset($this->Controller->request->params['pass'][$var])) ? $this->Controller->request->params['pass'][$var] : $default;
  235. }
  236. /**
  237. * Used to get the value of a named param
  238. * @param mixed $var
  239. * @param mixed $default
  240. * @return mixed
  241. */
  242. public function getNamedParam($var, $default = null) {
  243. return (isset($this->Controller->request->params['named'][$var])) ? $this->Controller->request->params['named'][$var] : $default;
  244. }
  245. /**
  246. * Used to get the value of a get query
  247. * @deprecated - use request->query() instead
  248. *
  249. * @param mixed $var
  250. * @param mixed $default
  251. * @return mixed
  252. */
  253. public function getQueryParam($var, $default = null) {
  254. return (isset($this->Controller->request->query[$var])) ? $this->Controller->request->query[$var] : $default;
  255. }
  256. /**
  257. * Return 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. * Return 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. ### Controller Stuff ###
  313. /**
  314. * Direct login for a specific user id.
  315. * Will respect full login scope (if defined in auth setup) as well as contained data and
  316. * can therefore return false if the login fails due to unmatched scope.
  317. *
  318. * @see DirectAuthentication auth adapter
  319. * @param mixed $id User id
  320. * @param array $settings Settings for DirectAuthentication
  321. * - fields
  322. * @return boolean Success
  323. */
  324. public function manualLogin($id, $settings = array()) {
  325. $requestData = $this->Controller->request->data;
  326. $authData = $this->Controller->Auth->authenticate;
  327. $settings = array_merge($authData, $settings);
  328. $settings['fields'] = array('username' => 'id');
  329. $this->Controller->request->data = array($this->userModel => array('id' => $id));
  330. $this->Controller->Auth->authenticate = array('Tools.Direct' => $settings);
  331. $result = $this->Controller->Auth->login();
  332. $this->Controller->Auth->authenticate = $authData;
  333. $this->Controller->request->data = $requestData;
  334. return $result;
  335. }
  336. /**
  337. * Force login for a specific user id.
  338. * Only fails if the user does not exist or if he is already
  339. * logged in as it ignores the usual scope.
  340. *
  341. * Better than Auth->login($data) since it respects the other auth configs such as
  342. * fields, contain, recursive and userModel.
  343. *
  344. * @param mixed $id User id
  345. * @return boolean Success
  346. */
  347. public function forceLogin($id) {
  348. $settings = array(
  349. 'scope' => array(),
  350. );
  351. return $this->manualLogin($id, $settings);
  352. /*
  353. if (!isset($this->User)) {
  354. $this->User = ClassRegistry::init(defined('CLASS_USER') ? CLASS_USER : $this->userModel);
  355. }
  356. $data = $this->User->get($id);
  357. if (!$data) {
  358. return false;
  359. }
  360. $data = $data[$this->userModel];
  361. return $this->Controller->Auth->login($data);
  362. */
  363. }
  364. /**
  365. * Smart Referer Redirect - will try to use an existing referer first
  366. * otherwise it will use the default url
  367. *
  368. * @param mixed $url
  369. * @param boolean $allowSelf if redirect to the same controller/action (url) is allowed
  370. * @param integer $status
  371. * returns nothing and automatically redirects
  372. */
  373. public function autoRedirect($whereTo, $allowSelf = true, $status = null) {
  374. if ($allowSelf || $this->Controller->referer(null, true) !== '/' . $this->Controller->request->url) {
  375. $this->Controller->redirect($this->Controller->referer($whereTo, true), $status);
  376. }
  377. $this->Controller->redirect($whereTo, $status);
  378. }
  379. /**
  380. * Should be a 303, but:
  381. * 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.
  382. * @see http://en.wikipedia.org/wiki/Post/Redirect/Get
  383. * @param mixed $url
  384. * @param integer $status
  385. * TODO: change to 303 with backwardscompatability for older browsers...
  386. */
  387. public function postRedirect($whereTo, $status = 302) {
  388. $this->Controller->redirect($whereTo, $status);
  389. }
  390. /**
  391. * Combine auto with post
  392. * also allows whitelisting certain actions for autoRedirect (use Controller::$autoRedirectActions)
  393. * @param mixed $url
  394. * @param boolean $conditionalAutoRedirect false to skip whitelisting
  395. * @param integer $status
  396. */
  397. public function autoPostRedirect($whereTo, $conditionalAutoRedirect = true, $status = 302) {
  398. $referer = $this->Controller->referer($whereTo, true);
  399. if (!$conditionalAutoRedirect && !empty($referer)) {
  400. $this->postRedirect($referer, $status);
  401. }
  402. if (!empty($referer)) {
  403. $referer = Router::parse($referer);
  404. }
  405. if (!$conditionalAutoRedirect || empty($this->Controller->autoRedirectActions) || is_array($referer) && !empty($referer['action'])) {
  406. $refererController = Inflector::camelize($referer['controller']);
  407. # fixme
  408. if (!isset($this->Controller->autoRedirectActions)) {
  409. $this->Controller->autoRedirectActions = array();
  410. }
  411. foreach ($this->Controller->autoRedirectActions as $action) {
  412. list($controller, $action) = pluginSplit($action);
  413. if (!empty($controller) && $refererController !== '*' && $refererController != $controller) {
  414. continue;
  415. }
  416. if (empty($controller) && $refererController != Inflector::camelize($this->Controller->request->params['controller'])) {
  417. continue;
  418. }
  419. if (!in_array($referer['action'], $this->Controller->autoRedirectActions)) {
  420. continue;
  421. }
  422. $this->autoRedirect($whereTo, true, $status);
  423. }
  424. }
  425. $this->postRedirect($whereTo, $status);
  426. }
  427. /**
  428. * Automatically add missing url parts of the current url including
  429. * - querystring (especially for 3.x then)
  430. * - named params (until 3.x when they will become deprecated)
  431. * - passed params
  432. *
  433. * @param mixed $url
  434. * @param intger $status
  435. * @param boolean $exit
  436. * @return void
  437. */
  438. public function completeRedirect($url = null, $status = null, $exit = true) {
  439. if ($url === null) {
  440. $url = $this->Controller->request->params;
  441. unset($url['named']);
  442. unset($url['pass']);
  443. unset($url['isAjax']);
  444. }
  445. if (is_array($url)) {
  446. $url += $this->Controller->request->params['named'];
  447. $url += $this->Controller->request->params['pass'];
  448. }
  449. return $this->Controller->redirect($url, $status, $exit);
  450. }
  451. /**
  452. * Only redirect to itself if cookies are on
  453. * Prevents problems with lost data
  454. * 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.
  455. *
  456. * @see http://en.wikipedia.org/wiki/Post/Redirect/Get
  457. * TODO: change to 303 with backwardscompatability for older browsers...
  458. */
  459. public function prgRedirect($status = 302) {
  460. if (!empty($_COOKIE[Configure::read('Session.cookie')])) {
  461. $this->Controller->redirect('/' . $this->Controller->request->url, $status);
  462. }
  463. }
  464. /**
  465. * Handler for passing some meta data to the view
  466. * uses CommonHelper to include them in the layout
  467. *
  468. * @param type (relevance):
  469. * - title (10), description (9), robots(7), language(5), keywords (0)
  470. * - custom: abstract (1), category(1), GOOGLEBOT(0) ...
  471. * @return void
  472. */
  473. public function setMeta($type, $content, $prep = true) {
  474. if (!in_array($type, array('title', 'canonical', 'description', 'keywords', 'robots', 'language', 'custom'))) {
  475. trigger_error(__('Meta Type invalid'), E_USER_WARNING);
  476. return;
  477. }
  478. if ($type === 'canonical' && $prep) {
  479. $content = Router::url($content);
  480. }
  481. if ($type === 'canonical' && $prep) {
  482. $content = h($content);
  483. }
  484. Configure::write('Meta.' . $type, $content);
  485. }
  486. /*** Other helpers and debug features **/
  487. /**
  488. * Generates validation error messages for HABTM fields
  489. * ?
  490. *
  491. * @return void
  492. */
  493. protected function _habtmValidation() {
  494. $model = $this->Controller->modelClass;
  495. if (isset($this->Controller->{$model}) && isset($this->Controller->{$model}->hasAndBelongsToMany)) {
  496. foreach ($this->Controller->{$model}->hasAndBelongsToMany as $alias => $options) {
  497. if (isset($this->Controller->{$model}->validationErrors[$alias])) {
  498. $this->Controller->{$model}->{$alias}->validationErrors[$alias] = $this->Controller->{$model}->validationErrors[$alias];
  499. }
  500. }
  501. }
  502. }
  503. /**
  504. * Set headers to cache this request.
  505. * Opposite of Controller::disableCache()
  506. * TODO: set response class header instead
  507. *
  508. * @param integer $seconds
  509. * @return void
  510. */
  511. public function forceCache($seconds = HOUR) {
  512. $this->Controller->response->header('Cache-Control', 'public, max-age=' . $seconds);
  513. $this->Controller->response->header('Last-modified', gmdate("D, j M Y H:i:s", time()) . " GMT");
  514. $this->Controller->response->header('Expires', gmdate("D, j M Y H:i:s", time() + $seconds) . " GMT");
  515. }
  516. /**
  517. * Referrer checking (where does the user come from)
  518. * Only returns true for a valid external referrer.
  519. *
  520. * @return boolean Success
  521. */
  522. public function isForeignReferer($ref = null) {
  523. if ($ref === null) {
  524. $ref = env('HTTP_REFERER');
  525. }
  526. if (!$ref) {
  527. return false;
  528. }
  529. $base = Configure::read('App.fullBaseUrl') . $this->Controller->webroot;
  530. if (strpos($ref, $base) === 0) {
  531. return false;
  532. }
  533. return true;
  534. }
  535. /**
  536. * CommonComponent::denyAccess()
  537. *
  538. * @return void
  539. */
  540. public function denyAccess() {
  541. $ref = env('HTTP_USER_AGENT');
  542. if ($this->isForeignReferer($ref)) {
  543. if (eregi('http://Anonymouse.org/', $ref)) {
  544. //echo returns(Configure::read('Config.language'));
  545. $this->cakeError('error406', array());
  546. }
  547. }
  548. }
  549. /**
  550. * CommonComponent::monitorCookieProblems()
  551. *
  552. * @return void
  553. */
  554. public function monitorCookieProblems() {
  555. /*
  556. if (($language = Configure::read('Config.language')) === null) {
  557. //$this->log('CookieProblem: SID '.session_id().' | '.env('REMOTE_ADDR').' | Ref: '.env('HTTP_REFERER').' |Agent: '.env('HTTP_USER_AGENT'));
  558. }
  559. */
  560. $ip = $this->RequestHandler->getClientIP(); //env('REMOTE_ADDR');
  561. $host = gethostbyaddr($ip);
  562. $sessionId = session_id();
  563. if (empty($sessionId)) {
  564. $sessionId = '--';
  565. }
  566. if (empty($_REQUEST[Configure::read('Session.cookie')]) && !($res = Cache::read($ip))) {
  567. $this->log('CookieProblem:: SID: ' . $sessionId . ' | IP: ' . $ip . ' (' . $host . ') | REF: ' . $this->Controller->referer() . ' | Agent: ' . env('HTTP_USER_AGENT'), 'noscript');
  568. Cache::write($ip, 1);
  569. }
  570. }
  571. /**
  572. * //todo: move to Utility?
  573. *
  574. * @return boolean true if disabled (bots, etc), false if enabled
  575. */
  576. public static function cookiesDisabled() {
  577. if (!empty($_COOKIE) && !empty($_COOKIE[Configure::read('Session.cookie')])) {
  578. return false;
  579. }
  580. return true;
  581. }
  582. /**
  583. * Quick sql debug from controller dynamically
  584. * or statically from just about any other place in the script
  585. * @param boolean $die: TRUE to output and die, FALSE to log to file and continue
  586. */
  587. public function sql($die = true) {
  588. if (isset($this->Controller)) {
  589. $object = $this->Controller->{$this->Controller->modelClass};
  590. } else {
  591. $object = ClassRegistry::init(defined('CLASS_USER') ? CLASS_USER : $this->userModel);
  592. }
  593. $log = $object->getDataSource()->getLog(false, false);
  594. foreach ($log['log'] as $key => $value) {
  595. if (strpos($value['query'], 'SHOW ') === 0 || strpos($value['query'], 'SELECT CHARACTER_SET_NAME ') === 0) {
  596. unset($log['log'][$key]);
  597. continue;
  598. }
  599. }
  600. # output and die?
  601. if ($die) {
  602. debug($log);
  603. die();
  604. }
  605. # log to file then and continue
  606. $log = print_r($log, true);
  607. App::uses('CakeLog', 'Log');
  608. return CakeLog::write('sql', $log);
  609. }
  610. /**
  611. * Temporary check how often current cache fails!
  612. * TODO: move
  613. *
  614. * @return boolean Success
  615. */
  616. public function ensureCacheIsOk() {
  617. $x = Cache::read('xyz012345');
  618. if (!$x) {
  619. $x = Cache::write('xyz012345', 1);
  620. $this->log(date(FORMAT_DB_DATETIME), 'cacheprob');
  621. return false;
  622. }
  623. return true;
  624. }
  625. /**
  626. * Localize
  627. *
  628. * @return boolean Success
  629. */
  630. public function localize($lang = null) {
  631. if ($lang === null) {
  632. $lang = Configure::read('Config.language');
  633. }
  634. if (empty($lang)) {
  635. return false;
  636. }
  637. if (($pos = strpos($lang, '-')) !== false) {
  638. $lang = substr($lang, 0, $pos);
  639. }
  640. if ($lang == DEFAULT_LANGUAGE) {
  641. return null;
  642. }
  643. if (!((array)$pattern = Configure::read('LocalizationPattern.' . $lang))) {
  644. return false;
  645. }
  646. foreach ($pattern as $key => $value) {
  647. Configure::write('Localization.' . $key, $value);
  648. }
  649. return true;
  650. }
  651. /**
  652. * Bug fix for i18n
  653. * still needed?
  654. *
  655. * @return void
  656. */
  657. public function ensureDefaultLanguage() {
  658. if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
  659. //Configure::write('Config.language', DEFAULT_LANGUAGE);
  660. }
  661. }
  662. /**
  663. * Main controller function for consistency in controller naming
  664. */
  665. public function ensureControllerConsistency() {
  666. # problems with plugins
  667. if (!empty($this->Controller->request->params['plugin'])) {
  668. return;
  669. }
  670. if (($name = strtolower(Inflector::underscore($this->Controller->name))) !== $this->Controller->request->params['controller']) {
  671. $this->Controller->log('301: ' . $this->Controller->request->params['controller'] . ' => ' . $name . ' (Ref ' . $this->Controller->referer() . ')', '301'); // log problem with controller naming
  672. if (!$this->Controller->RequestHandler->isPost()) {
  673. # underscored version is the only valid one to avoid duplicate content
  674. $url = array('controller' => $name, 'action' => $this->Controller->request->params['action']);
  675. $url = array_merge($url, $this->Controller->request->params['pass'], $this->Controller->request->params['named']);
  676. //TODO: add plugin/admin stuff which right now is supposed to work automatically
  677. $this->Controller->redirect($url, 301);
  678. }
  679. }
  680. return true;
  681. # problem with extensions (rss etc)
  682. if (empty($this->Controller->request->params['prefix']) && ($currentUrl = $this->currentUrl(true)) != $this->Controller->here) {
  683. //pr($this->Controller->here);
  684. //pr($currentUrl);
  685. $this->log('301: ' . $this->Controller->here . ' => ' . $currentUrl . ' (Referer ' . $this->Controller->referer() . ')', '301');
  686. if (!$this->Controller->RequestHandler->isPost()) {
  687. $url = array('controller' => $this->Controller->request->params['controller'], 'action' => $this->Controller->request->params['action']);
  688. $url = array_merge($url, $this->Controller->request->params['pass'], $this->Controller->request->params['named']);
  689. $this->Controller->redirect($url, 301);
  690. }
  691. }
  692. }
  693. /**
  694. * Main controller function for seo-slugs
  695. * passed titleSlug != current title => redirect to the expected one
  696. */
  697. public function ensureConsistency($id, $passedTitleSlug, $currentTitle) {
  698. $expectedTitle = slug($currentTitle);
  699. if (empty($passedTitleSlug) || $expectedTitle != $passedTitleSlug) { # case sensitive!!!
  700. $ref = env('HTTP_REFERER');
  701. if (!$this->isForeignReferer($ref)) {
  702. $this->Controller->log('Internal ConsistencyProblem at \'' . $ref . '\' - [' . $passedTitleSlug . '] instead of [' . $expectedTitle . ']', 'referer');
  703. } else {
  704. $this->Controller->log('External ConsistencyProblem at \'' . $ref . '\' - [' . $passedTitleSlug . '] instead of [' . $expectedTitle . ']', 'referer');
  705. }
  706. $this->Controller->redirect(array($id, $expectedTitle), 301);
  707. }
  708. }
  709. /**
  710. * Try to detect group for a multidim array for select boxes.
  711. * Extracts the group name of the selected key.
  712. *
  713. * @param array $array
  714. * @param string $key
  715. * @param array $matching
  716. * @return string result
  717. */
  718. public static function getGroup($multiDimArray, $key, $matching = array()) {
  719. if (!is_array($multiDimArray) || empty($key)) {
  720. return '';
  721. }
  722. foreach ($multiDimArray as $group => $data) {
  723. if (array_key_exists($key, $data)) {
  724. if (!empty($matching)) {
  725. if (array_key_exists($group, $matching)) {
  726. return $matching[$group];
  727. }
  728. return '';
  729. }
  730. return $group;
  731. }
  732. }
  733. return '';
  734. }
  735. /*** DEEP FUNCTIONS ***/
  736. /**
  737. * Move to boostrap?
  738. */
  739. public function trimDeep($value) {
  740. $value = is_array($value) ? array_map(array($this, 'trimDeep'), $value) : trim($value);
  741. return $value;
  742. }
  743. /**
  744. * Move to boostrap?
  745. */
  746. public function specialcharsDeep($value) {
  747. $value = is_array($value) ? array_map(array($this, 'specialcharsDeep'), $value) : htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
  748. return $value;
  749. }
  750. /**
  751. * Move to boostrap?
  752. */
  753. public function deep($function, $value) {
  754. $value = is_array($value) ? array_map(array($this, $function), $value) : $function($value);
  755. return $value;
  756. }
  757. /**
  758. * MAIN Sanitize Array-FUNCTION
  759. * @param string $type: html, paranoid
  760. * move to boostrap?
  761. */
  762. public function sanitizeDeep($value, $type = null, $options = null) {
  763. switch ($type) {
  764. case 'html':
  765. if (isset($options['remove']) && is_bool($options['remove'])) {
  766. $this->removeChars = $options['remove'];
  767. }
  768. $value = $this->htmlDeep($value);
  769. break;
  770. case 'paranoid':
  771. default:
  772. if (isset($options['allowed']) && is_array($options['allowed'])) {
  773. $this->allowedChars = $options['allowed'];
  774. }
  775. $value = $this->paranoidDeep($value);
  776. }
  777. return $value;
  778. }
  779. /**
  780. * Removes all except A-Z,a-z,0-9 and allowedChars (allowedChars array)
  781. * move to boostrap?
  782. */
  783. public function paranoidDeep($value) {
  784. $mrClean = new Sanitize();
  785. $value = is_array($value) ? array_map(array($this, 'paranoidDeep'), $value) : $mrClean->paranoid($value, $this->allowedChars);
  786. return $value;
  787. }
  788. /**
  789. * transfers/removes all < > from text (remove TRUE/FALSE)
  790. * move to boostrap?
  791. */
  792. public function htmlDeep($value) {
  793. $mrClean = new Sanitize();
  794. $value = is_array($value) ? array_map(array($this, 'htmlDeep'), $value) : $mrClean->html($value, $this->removeChars);
  795. return $value;
  796. }
  797. /**
  798. * Takes list of items and transforms it into an array
  799. * + cleaning (trim, no empty parts, etc)
  800. *
  801. * @param string $string containing the parts
  802. * @param string $separator (defaults to ',')
  803. * @param boolean $camelize (true/false): problems with äöüß etc!
  804. * @return array results as array list
  805. * //TODO: 3.4. parameter as array, move to Lib
  806. */
  807. public function parseList($string, $separator = null, $camelize = false, $capitalize = true) {
  808. if ($separator === null) {
  809. $separator = ',';
  810. }
  811. # parses the list, but leaves tokens untouched inside () brackets
  812. $stringArray = String::tokenize($string, $separator);
  813. $returnArray = array();
  814. if (empty($stringArray)) {
  815. return array();
  816. }
  817. foreach ($stringArray as $t) {
  818. $t = trim($t);
  819. if (!empty($t)) {
  820. if ($camelize === true) {
  821. $t = mb_strtolower($t);
  822. $t = Inflector::camelize(Inflector::underscore($t)); # problems with non-alpha chars!!
  823. } elseif ($capitalize === true) {
  824. $t = ucwords($t);
  825. }
  826. $returnArray[] = $t;
  827. }
  828. }
  829. return $returnArray;
  830. }
  831. /**
  832. * //todo move to lib!!!
  833. * static
  834. */
  835. public function separators($s = null, $valueOnly = false) {
  836. $separatorsValues = array(SEPARATOR_COMMA => ',', SEPARATOR_SEMI => ';', SEPARATOR_SPACE => ' ', SEPARATOR_TAB => TB, SEPARATOR_NL => NL);
  837. $separators = array(SEPARATOR_COMMA => '[ , ] ' . __('Comma'), SEPARATOR_SEMI => '[ ; ] ' . __('Semicolon'), SEPARATOR_SPACE => '[ &nbsp; ] ' . __('Space'), SEPARATOR_TAB =>
  838. '[ &nbsp;&nbsp;&nbsp;&nbsp; ] ' . __('Tabulator'), SEPARATOR_NL => '[ \n ] ' . __('New Line'));
  839. if ($s !== null) {
  840. if (array_key_exists($s, $separators)) {
  841. if ($valueOnly) {
  842. return $separatorsValues[$s];
  843. }
  844. return $separators[$s];
  845. }
  846. return '';
  847. }
  848. return $valueOnly ? $separatorsValues : $separators;
  849. }
  850. /*** deprecated ***/
  851. /**
  852. * Add protocol prefix if necessary (and possible)
  853. */
  854. public function autoPrefixUrl($url, $prefix = null) {
  855. trigger_error('deprecated - use Utility::autoPrefixUrl()');
  856. return Utility::autoPrefixUrl($url, $prefix);
  857. }
  858. /**
  859. * Remove unnessary stuff + add http:// for external urls
  860. */
  861. public static function cleanUrl($url, $headerRedirect = false) {
  862. trigger_error('deprecated - use Utility::cleanUrl()');
  863. return Utility::cleanUrl($url, $headerRedirect);
  864. }
  865. /**
  866. */
  867. public static function getHeaderFromUrl($url) {
  868. trigger_error('deprecated - use Utility::getHeaderFromUrl()');
  869. return Utility::getHeaderFromUrl($url);
  870. }
  871. /**
  872. * Get the current ip address
  873. * @param boolean $safe
  874. * @return string ip
  875. */
  876. public static function getClientIp($safe = null) {
  877. trigger_error('deprecated - use Utility::getClientIp()');
  878. return Utility::getClientIp($safe);
  879. }
  880. /**
  881. * Get the current referer
  882. * @param boolean $full (defaults to false and leaves the url untouched)
  883. * @return string referer (local or foreign)
  884. */
  885. public static function getReferer($full = false) {
  886. trigger_error('deprecated - use Utility::getReferer()');
  887. return Utility::getReferer($full);
  888. }
  889. /**
  890. * Returns true only if all values are true
  891. * @return boolean result
  892. * maybe move to bootstrap?
  893. */
  894. public static function logicalAnd($array) {
  895. trigger_error('deprecated - use Utility::logicalAnd()');
  896. return Utility::logicalAnd($array);
  897. }
  898. /**
  899. * Returns true if at least one value is true
  900. * @return boolean result
  901. * maybe move to bootstrap?
  902. */
  903. public static function logicalOr($array) {
  904. trigger_error('deprecated - use Utility::logicalOr()');
  905. return Utility::logicalOr($array);
  906. }
  907. /**
  908. * Convenience function for automatic casting in form methods etc
  909. * @return safe value for DB query, or NULL if type was not a valid one
  910. * maybe move to bootstrap?
  911. */
  912. public static function typeCast($type = null, $value = null) {
  913. trigger_error('deprecated - use Utility::typeCast()');
  914. return Utility::typeCast($type, $value);
  915. }
  916. /**
  917. * //TODO: move somewhere else
  918. * Returns an array with chars
  919. * up = uppercase, low = lowercase
  920. * @var char type: NULL/up/down | default: NULL (= down)
  921. * @return array with the a-z
  922. *
  923. * @deprecated: USE range() instead! move to lib
  924. */
  925. public function alphaFilterSymbols($type = null) {
  926. trigger_error('deprecated');
  927. $arr = array();
  928. for ($i = 97; $i < 123; $i++) {
  929. if ($type === 'up') {
  930. $arr[] = chr($i - 32);
  931. } else {
  932. $arr[] = chr($i);
  933. }
  934. }
  935. return $arr;
  936. }
  937. /**
  938. * //TODO: move somewhere else
  939. * Assign Array to Char Array
  940. *
  941. * @var content array
  942. * @var char array
  943. * @return array: chars with content
  944. * PROTECTED NAMES (content cannot contain those): undefined
  945. */
  946. public function assignToChar($contentArray, $charArray = null) {
  947. $res = array();
  948. $res['undefined'] = array();
  949. if (empty($charArray)) {
  950. $charArray = $this->alphaFilterSymbols();
  951. }
  952. foreach ($contentArray as $content) {
  953. $done = false;
  954. # loop them trough
  955. foreach ($charArray as $char) {
  956. if (empty($res[$char])) { // throws warnings otherwise
  957. $res[$char] = array();
  958. }
  959. if (!empty($content) && strtolower(substr($content, 0, 1)) == $char) {
  960. $res[$char][] = $content;
  961. $done = true;
  962. }
  963. }
  964. # no match?
  965. if (!empty($content) && !$done) {
  966. $res['undefined'][] = $content;
  967. }
  968. }
  969. return $res;
  970. }
  971. /**
  972. * Extract email from "name <email>" etc
  973. *
  974. * @deprecated
  975. * use splitEmail instead
  976. */
  977. public function extractEmail($email) {
  978. if (($pos = mb_strpos($email, '<')) !== false) {
  979. $email = substr($email, $pos + 1);
  980. }
  981. if (($pos = mb_strrpos($email, '>')) !== false) {
  982. $email = substr($email, 0, $pos);
  983. }
  984. return trim($email);
  985. }
  986. /**
  987. * Expects email to be valid!
  988. * TODO: move to Lib
  989. * @return array email - pattern: array('email'=>,'name'=>)
  990. */
  991. public function splitEmail($email, $abortOnError = false) {
  992. $array = array('email' => '', 'name' => '');
  993. if (($pos = mb_strpos($email, '<')) !== false) {
  994. $name = substr($email, 0, $pos);
  995. $email = substr($email, $pos + 1);
  996. }
  997. if (($pos = mb_strrpos($email, '>')) !== false) {
  998. $email = substr($email, 0, $pos);
  999. }
  1000. $email = trim($email);
  1001. if (!empty($email)) {
  1002. $array['email'] = $email;
  1003. }
  1004. if (!empty($name)) {
  1005. $array['name'] = trim($name);
  1006. }
  1007. return $array;
  1008. }
  1009. /**
  1010. * TODO: move to Lib
  1011. * @param string $email
  1012. * @param string $name (optional, will use email otherwise)
  1013. */
  1014. public function combineEmail($email, $name = null) {
  1015. if (empty($email)) {
  1016. return '';
  1017. }
  1018. if (empty($name)) {
  1019. $name = $email;
  1020. }
  1021. return $name . ' <' . $email['email'] . '>';
  1022. }
  1023. /**
  1024. * TODO: move to Lib
  1025. * returns type
  1026. * - username: everything till @ (xyz@abc.de => xyz)
  1027. * - hostname: whole domain (xyz@abc.de => abc.de)
  1028. * - tld: top level domain only (xyz@abc.de => de)
  1029. * - domain: if available (xyz@e.abc.de => abc)
  1030. * - subdomain: if available (xyz@e.abc.de => e)
  1031. * @param string $email: well formatted email! (containing one @ and one .)
  1032. * @param string $type (TODO: defaults to return all elements)
  1033. * @returns string or false on failure
  1034. */
  1035. public function extractEmailInfo($email, $type = null) {
  1036. //$checkpos = strrpos($email, '@');
  1037. $nameParts = explode('@', $email);
  1038. if (count($nameParts) !== 2) {
  1039. return false;
  1040. }
  1041. if ($type === 'username') {
  1042. return $nameParts[0];
  1043. }
  1044. if ($type === 'hostname') {
  1045. return $nameParts[1];
  1046. }
  1047. $checkpos = strrpos($nameParts[1], '.');
  1048. $tld = trim(mb_substr($nameParts[1], $checkpos + 1));
  1049. if ($type === 'tld') {
  1050. return $tld;
  1051. }
  1052. $server = trim(mb_substr($nameParts[1], 0, $checkpos));
  1053. //TODO; include 3rd-Level-Label
  1054. $domain = '';
  1055. $subdomain = '';
  1056. $checkpos = strrpos($server, '.');
  1057. if ($checkpos !== false) {
  1058. $subdomain = trim(mb_substr($server, 0, $checkpos));
  1059. $domain = trim(mb_substr($server, $checkpos + 1));
  1060. }
  1061. if ($type === 'domain') {
  1062. return $domain;
  1063. }
  1064. if ($type === 'subdomain') {
  1065. return $subdomain;
  1066. }
  1067. //$hostParts = explode();
  1068. //$check = trim(mb_substr($email, $checkpos));
  1069. return '';
  1070. }
  1071. /**
  1072. * Returns searchArray (options['wildcard'] TRUE/FALSE)
  1073. * TODO: move to SearchLib etc
  1074. *
  1075. * @param string $keyword
  1076. * @param string $searchphrase
  1077. * @param array $options
  1078. * @return array Cleaned array('keyword'=>'searchphrase') or array('keyword LIKE'=>'searchphrase')
  1079. */
  1080. public function getSearchItem($keyword = null, $searchphrase = null, $options = array()) {
  1081. if (isset($options['wildcard']) && $options['wildcard'] == true) {
  1082. if (strpos($searchphrase, '*') !== false || strpos($searchphrase, '_') !== false) {
  1083. $keyword .= ' LIKE';
  1084. $searchphrase = str_replace('*', '%', $searchphrase);
  1085. // additionally remove % ?
  1086. //$searchphrase = str_replace(array('%','_'), array('',''), $searchphrase);
  1087. }
  1088. } else {
  1089. // allow % and _ to remain in searchstring (without LIKE not problematic), * has no effect either!
  1090. }
  1091. return array($keyword => $searchphrase);
  1092. }
  1093. /**
  1094. * Returns auto-generated password
  1095. *
  1096. * @param string $type: user, ...
  1097. * @param integer $length (if no type is submitted)
  1098. * @return pwd on success, empty string otherwise
  1099. * @deprecated - use RandomLib
  1100. */
  1101. public static function pwd($type = null, $length = null) {
  1102. trigger_error('deprecated');
  1103. App::uses('RandomLib', 'Tools.Lib');
  1104. if (!empty($type) && $type === 'user') {
  1105. return RandomLib::pronounceablePwd(6);
  1106. }
  1107. if (!empty($length)) {
  1108. return RandomLib::pronounceablePwd($length);
  1109. }
  1110. return '';
  1111. }
  1112. /**
  1113. * TODO: move to Lib
  1114. * Checks if string contains @ sign
  1115. *
  1116. * @param string
  1117. * @return true if at least one @ is in the string, false otherwise
  1118. */
  1119. public static function containsAtSign($string = null) {
  1120. if (!empty($string) && strpos($string, '@') !== false) {
  1121. return true;
  1122. }
  1123. return false;
  1124. }
  1125. /**
  1126. * @deprecated - use IpLip instead!
  1127. * IPv4/6 to slugged ip
  1128. * 192.111.111.111 => 192-111-111-111
  1129. * 4C00:0207:01E6:3152 => 4C00+0207+01E6+3152
  1130. * @return string sluggedIp
  1131. */
  1132. public function slugIp($ip) {
  1133. trigger_error('deprecated');
  1134. $ip = str_replace(array(':', '.'), array('+', '-'), $ip);
  1135. return $ip;
  1136. }
  1137. /**
  1138. * @deprecated - use IpLip instead!
  1139. * @return string ip on success, FALSE on failure
  1140. */
  1141. public function unslugIp($ip) {
  1142. trigger_error('deprecated');
  1143. $ip = str_replace(array('+', '-'), array(':', '.'), $ip);
  1144. return $ip;
  1145. }
  1146. /**
  1147. * @deprecated - use IpLip instead!
  1148. * @return string v4/v6 or FALSE on failure
  1149. */
  1150. public function ipFormat($ip) {
  1151. trigger_error('deprecated');
  1152. if (Validation::ip($ip, 'ipv4')) {
  1153. return 'ipv4';
  1154. }
  1155. if (Validation::ip($ip, 'ipv6')) {
  1156. return 'ipv6';
  1157. }
  1158. return false;
  1159. }
  1160. /**
  1161. * Get the Corresponding Message to an HTTP Error Code
  1162. *
  1163. * @param integer $code: 100...505
  1164. * @param boolean $autoTranslate
  1165. * @return array codes if code is NULL, otherwise string $code (empty string on failure)
  1166. */
  1167. public function responseCodes($code = null, $autoTranslate = false) {
  1168. //TODO: use core ones Controller::httpCodes
  1169. $responses = array(
  1170. 100 => 'Continue',
  1171. 101 => 'Switching Protocols',
  1172. 200 => 'OK',
  1173. 201 => 'Created',
  1174. 202 => 'Accepted',
  1175. 203 => 'Non-Authoritative Information',
  1176. 204 => 'No Content',
  1177. 205 => 'Reset Content',
  1178. 206 => 'Partial Content',
  1179. 300 => 'Multiple Choices',
  1180. 301 => 'Moved Permanently',
  1181. 302 => 'Found',
  1182. 303 => 'See Other',
  1183. 304 => 'Not Modified',
  1184. 305 => 'Use Proxy',
  1185. 307 => 'Temporary Redirect',
  1186. 400 => 'Bad Request',
  1187. 401 => 'Unauthorized',
  1188. 402 => 'Payment Required',
  1189. 403 => 'Forbidden',
  1190. 404 => 'Not Found',
  1191. 405 => 'Method Not Allowed',
  1192. 406 => 'Not Acceptable',
  1193. 407 => 'Proxy Authentication Required',
  1194. 408 => 'Request Time-out',
  1195. 409 => 'Conflict',
  1196. 410 => 'Gone',
  1197. 411 => 'Length Required',
  1198. 412 => 'Precondition Failed',
  1199. 413 => 'Request Entity Too Large',
  1200. 414 => 'Request-URI Too Large',
  1201. 415 => 'Unsupported Media Type',
  1202. 416 => 'Requested range not satisfiable',
  1203. 417 => 'Expectation Failed',
  1204. 500 => 'Internal Server Error',
  1205. 501 => 'Not Implemented',
  1206. 502 => 'Bad Gateway',
  1207. 503 => 'Service Unavailable',
  1208. 504 => 'Gateway Time-out',
  1209. 505 => 'HTTP Version not supported' # MOD 2009-07-21 ms: 505 added!!!
  1210. );
  1211. if ($code === null) {
  1212. if ($autoTranslate) {
  1213. foreach ($responses as $key => $value) {
  1214. $responses[$key] = __($value);
  1215. }
  1216. }
  1217. return $responses;
  1218. }
  1219. # RFC 2616 states that all unknown HTTP codes must be treated the same as the
  1220. # base code in their class.
  1221. if (!isset($responses[$code])) {
  1222. $code = floor($code / 100) * 100;
  1223. }
  1224. if (!empty($code) && array_key_exists((int)$code, $responses)) {
  1225. if ($autoTranslate) {
  1226. return __($responses[$code]);
  1227. }
  1228. return $responses[$code];
  1229. }
  1230. return '';
  1231. }
  1232. /**
  1233. * Get the Corresponding Message to an HTTP Error Code
  1234. *
  1235. * @param integer $code: 4xx...5xx
  1236. * @return string
  1237. */
  1238. public function smtpResponseCodes($code = null, $autoTranslate = false) {
  1239. # 550 5.1.1 User is unknown
  1240. # 552 5.2.2 Storage Exceeded
  1241. $responses = array(
  1242. 451 => 'Need to authenticate',
  1243. 550 => 'User Unknown',
  1244. 552 => 'Storage Exceeded',
  1245. 554 => 'Refused'
  1246. );
  1247. if (!empty($code) && array_key_exists((int)$code, $responses)) {
  1248. if ($autoTranslate) {
  1249. return __($responses[$code]);
  1250. }
  1251. return $responses[$code];
  1252. }
  1253. return '';
  1254. }
  1255. /**
  1256. * Move to Lib
  1257. * isnt this covered by core Set stuff anyway?)
  1258. *
  1259. * tryout: sorting multidim. array by field [0]..[x]; z.b. $array['Model']['name'] DESC etc.
  1260. *
  1261. * @return array()
  1262. * @deprecated
  1263. */
  1264. public function sortArray($array, $obj, $direction = null) {
  1265. if (empty($direction) || empty($array) || empty($obj)) {
  1266. return array();
  1267. }
  1268. if ($direction === 'up') {
  1269. usort($products, array($obj, '_sortUp'));
  1270. }
  1271. if ($direction === 'down') {
  1272. usort($products, array($obj, '_sortDown'));
  1273. }
  1274. return array();
  1275. }
  1276. protected function _sortUp($x, $y) {
  1277. if ($x[1] == $y[1]) {
  1278. return 0;
  1279. }
  1280. if ($x[1] < $y[1]) {
  1281. return 1;
  1282. }
  1283. return - 1;
  1284. }
  1285. protected function _sortDown($x, $y) {
  1286. if ($x[1] == $y[1]) {
  1287. return 0;
  1288. }
  1289. if ($x[1] < $y[1]) {
  1290. return - 1;
  1291. }
  1292. return 1;
  1293. }
  1294. }