CommonComponent.php 41 KB

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