CommonComponent.php 41 KB

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