CommonComponent.php 41 KB

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