CommonComponent.php 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451
  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. * Extract email from "name <email>" etc
  1007. *
  1008. * @deprecated
  1009. * use splitEmail instead
  1010. */
  1011. public function extractEmail($email) {
  1012. if (($pos = mb_strpos($email, '<')) !== false) {
  1013. $email = substr($email, $pos + 1);
  1014. }
  1015. if (($pos = mb_strrpos($email, '>')) !== false) {
  1016. $email = substr($email, 0, $pos);
  1017. }
  1018. return trim($email);
  1019. }
  1020. /**
  1021. * expects email to be valid!
  1022. * TODO: move to Lib
  1023. * @return array $email - pattern: array('email'=>,'name'=>)
  1024. * 2010-04-20 ms
  1025. */
  1026. public function splitEmail($email, $abortOnError = false) {
  1027. $array = array('email'=>'', 'name'=>'');
  1028. if (($pos = mb_strpos($email, '<')) !== false) {
  1029. $name = substr($email, 0, $pos);
  1030. $email = substr($email, $pos+1);
  1031. }
  1032. if (($pos = mb_strrpos($email, '>')) !== false) {
  1033. $email = substr($email, 0, $pos);
  1034. }
  1035. $email = trim($email);
  1036. if (!empty($email)) {
  1037. $array['email'] = $email;
  1038. }
  1039. if (!empty($name)) {
  1040. $array['name'] = trim($name);
  1041. }
  1042. return $array;
  1043. }
  1044. /**
  1045. * TODO: move to Lib
  1046. * @param string $email
  1047. * @param string $name (optional, will use email otherwise)
  1048. */
  1049. public function combineEmail($email, $name = null) {
  1050. if (empty($email)) {
  1051. return '';
  1052. }
  1053. if (empty($name)) {
  1054. $name = $email;
  1055. }
  1056. return $name.' <'.$email['email'].'>';
  1057. }
  1058. /**
  1059. * TODO: move to Lib
  1060. * returns type
  1061. * - username: everything till @ (xyz@abc.de => xyz)
  1062. * - hostname: whole domain (xyz@abc.de => abc.de)
  1063. * - tld: top level domain only (xyz@abc.de => de)
  1064. * - domain: if available (xyz@e.abc.de => abc)
  1065. * - subdomain: if available (xyz@e.abc.de => e)
  1066. * @param string $email: well formatted email! (containing one @ and one .)
  1067. * @param string $type (TODO: defaults to return all elements)
  1068. * @returns string or false on failure
  1069. * 2010-01-10 ms
  1070. */
  1071. public function extractEmailInfo($email, $type = null) {
  1072. //$checkpos = strrpos($email, '@');
  1073. $nameParts = explode('@', $email);
  1074. if (count($nameParts) !== 2) {
  1075. return false;
  1076. }
  1077. if ($type === 'username') {
  1078. return $nameParts[0];
  1079. } elseif ($type === 'hostname') {
  1080. return $nameParts[1];
  1081. }
  1082. $checkpos = strrpos($nameParts[1], '.');
  1083. $tld = trim(mb_substr($nameParts[1], $checkpos + 1));
  1084. if ($type === 'tld') {
  1085. return $tld;
  1086. }
  1087. $server = trim(mb_substr($nameParts[1], 0, $checkpos));
  1088. //TODO; include 3rd-Level-Label
  1089. $domain = '';
  1090. $subdomain = '';
  1091. $checkpos = strrpos($server, '.');
  1092. if ($checkpos !== false) {
  1093. $subdomain = trim(mb_substr($server, 0, $checkpos));
  1094. $domain = trim(mb_substr($server, $checkpos + 1));
  1095. }
  1096. if ($type === 'domain') {
  1097. return $domain;
  1098. }
  1099. if ($type === 'subdomain') {
  1100. return $subdomain;
  1101. }
  1102. //$hostParts = explode();
  1103. //$check = trim(mb_substr($email, $checkpos));
  1104. return '';
  1105. }
  1106. /**
  1107. * Returns searchArray (options['wildcard'] TRUE/FALSE)
  1108. * TODO: move to SearchLib etc
  1109. *
  1110. * @return ARRAY cleaned array('keyword'=>'searchphrase') or array('keyword LIKE'=>'searchphrase')
  1111. * @access public
  1112. */
  1113. public function getSearchItem($keyword = null, $searchphrase = null, $options = array()) {
  1114. if (isset($options['wildcard']) && $options['wildcard'] == true) {
  1115. if (strpos($searchphrase, '*') !== false || strpos($searchphrase, '_') !== false) {
  1116. $keyword .= ' LIKE';
  1117. $searchphrase = str_replace('*', '%', $searchphrase);
  1118. // additionally remove % ?
  1119. //$searchphrase = str_replace(array('%','_'), array('',''), $searchphrase);
  1120. }
  1121. } else {
  1122. // allow % and _ to remain in searchstring (without LIKE not problematic), * has no effect either!
  1123. }
  1124. return array($keyword => $searchphrase);
  1125. }
  1126. /**
  1127. * returns auto-generated password
  1128. * @param string $type: user, ...
  1129. * @param int $length (if no type is submitted)
  1130. * @return pwd on success, empty string otherwise
  1131. * @static
  1132. * @deprecated - use RandomLib
  1133. * 2009-12-26 ms
  1134. */
  1135. public static function pwd($type = null, $length = null) {
  1136. trigger_error('deprecated');
  1137. App::uses('RandomLib', 'Tools.Lib');
  1138. if (!empty($type) && $type === 'user') {
  1139. return RandomLib::pronounceablePwd(6);
  1140. }
  1141. if (!empty($length)) {
  1142. return RandomLib::pronounceablePwd($length);
  1143. }
  1144. return '';
  1145. }
  1146. /**
  1147. * TODO: move to Lib
  1148. * Checks if string contains @ sign
  1149. * @return true if at least one @ is in the string, false otherwise
  1150. * 2009-12-26 ms
  1151. */
  1152. public static function containsAtSign($string = null) {
  1153. if (!empty($string) && strpos($string, '@') !== false) {
  1154. return true;
  1155. }
  1156. return false;
  1157. }
  1158. /**
  1159. * @deprecated - use IpLip instead!
  1160. * IPv4/6 to slugged ip
  1161. * 192.111.111.111 => 192-111-111-111
  1162. * 4C00:0207:01E6:3152 => 4C00+0207+01E6+3152
  1163. * @return string sluggedIp
  1164. * 2010-06-19 ms
  1165. */
  1166. public function slugIp($ip) {
  1167. trigger_error('deprecated');
  1168. $ip = str_replace(array(':', '.'), array('+', '-'), $ip);
  1169. return $ip;
  1170. }
  1171. /**
  1172. * @deprecated - use IpLip instead!
  1173. * @return string ip on success, FALSE on failure
  1174. * 2010-06-19 ms
  1175. */
  1176. public function unslugIp($ip) {
  1177. trigger_error('deprecated');
  1178. $ip = str_replace(array('+', '-'), array(':', '.'), $ip);
  1179. return $ip;
  1180. }
  1181. /**
  1182. * @deprecated - use IpLip instead!
  1183. * @return string v4/v6 or FALSE on failure
  1184. */
  1185. public function ipFormat($ip) {
  1186. trigger_error('deprecated');
  1187. if (Validation::ip($ip, 'ipv4')) {
  1188. return 'ipv4';
  1189. }
  1190. if (Validation::ip($ip, 'ipv6')) {
  1191. return 'ipv6';
  1192. }
  1193. return false;
  1194. }
  1195. /**
  1196. * Get the Corresponding Message to an HTTP Error Code
  1197. * @param int $code: 100...505
  1198. * @return array $codes if code is NULL, otherwise string $code (empty string on failure)
  1199. * 2009-07-21 ms
  1200. */
  1201. public function responseCodes($code = null, $autoTranslate = false) {
  1202. //TODO: use core ones Controller::httpCodes
  1203. $responses = array(
  1204. 100 => 'Continue',
  1205. 101 => 'Switching Protocols',
  1206. 200 => 'OK',
  1207. 201 => 'Created',
  1208. 202 => 'Accepted',
  1209. 203 => 'Non-Authoritative Information',
  1210. 204 => 'No Content',
  1211. 205 => 'Reset Content',
  1212. 206 => 'Partial Content',
  1213. 300 => 'Multiple Choices',
  1214. 301 => 'Moved Permanently',
  1215. 302 => 'Found',
  1216. 303 => 'See Other',
  1217. 304 => 'Not Modified',
  1218. 305 => 'Use Proxy',
  1219. 307 => 'Temporary Redirect',
  1220. 400 => 'Bad Request',
  1221. 401 => 'Unauthorized',
  1222. 402 => 'Payment Required',
  1223. 403 => 'Forbidden',
  1224. 404 => 'Not Found',
  1225. 405 => 'Method Not Allowed',
  1226. 406 => 'Not Acceptable',
  1227. 407 => 'Proxy Authentication Required',
  1228. 408 => 'Request Time-out',
  1229. 409 => 'Conflict',
  1230. 410 => 'Gone',
  1231. 411 => 'Length Required',
  1232. 412 => 'Precondition Failed',
  1233. 413 => 'Request Entity Too Large',
  1234. 414 => 'Request-URI Too Large',
  1235. 415 => 'Unsupported Media Type',
  1236. 416 => 'Requested range not satisfiable',
  1237. 417 => 'Expectation Failed',
  1238. 500 => 'Internal Server Error',
  1239. 501 => 'Not Implemented',
  1240. 502 => 'Bad Gateway',
  1241. 503 => 'Service Unavailable',
  1242. 504 => 'Gateway Time-out',
  1243. 505 => 'HTTP Version not supported' # MOD 2009-07-21 ms: 505 added!!!
  1244. );
  1245. if ($code === null) {
  1246. if ($autoTranslate) {
  1247. foreach ($responses as $key => $value) {
  1248. $responses[$key] = __($value);
  1249. }
  1250. }
  1251. return $responses;
  1252. }
  1253. # RFC 2616 states that all unknown HTTP codes must be treated the same as the
  1254. # base code in their class.
  1255. if (!isset($responses[$code])) {
  1256. $code = floor($code / 100) * 100;
  1257. }
  1258. if (!empty($code) && array_key_exists((int)$code, $responses)) {
  1259. if ($autoTranslate) {
  1260. return __($responses[$code]);
  1261. }
  1262. return $responses[$code];
  1263. }
  1264. return '';
  1265. }
  1266. /**
  1267. * Get the Corresponding Message to an HTTP Error Code
  1268. * @param int $code: 4xx...5xx
  1269. * 2010-06-08 ms
  1270. */
  1271. public function smtpResponseCodes($code = null, $autoTranslate = false) {
  1272. # 550 5.1.1 User is unknown
  1273. # 552 5.2.2 Storage Exceeded
  1274. $responses = array(
  1275. 451 => 'Need to authenticate',
  1276. 550 => 'User Unknown',
  1277. 552 => 'Storage Exceeded',
  1278. 554 => 'Refused'
  1279. );
  1280. if (!empty($code) && array_key_exists((int)$code, $responses)) {
  1281. if ($autoTranslate) {
  1282. return __($responses[$code]);
  1283. }
  1284. return $responses[$code];
  1285. }
  1286. return '';
  1287. }
  1288. /**
  1289. * Move to Lib
  1290. * isnt this covered by core Set stuff anyway?)
  1291. *
  1292. * tryout: sorting multidim. array by field [0]..[x]; z.b. $array['Model']['name'] DESC etc.
  1293. */
  1294. public function sortArray($array, $obj, $direction = null) {
  1295. if (empty($direction) || empty($array) || empty($obj)) {
  1296. return array();
  1297. }
  1298. if ($direction === 'up') {
  1299. usort($products, array($obj, '_sortUp'));
  1300. }
  1301. if ($direction === 'down') {
  1302. usort($products, array($obj, '_sortDown'));
  1303. }
  1304. return array();
  1305. }
  1306. protected function _sortUp($x, $y) {
  1307. if ($x[1] == $y[1]) {
  1308. return 0;
  1309. } elseif ($x[1] < $y[1]) {
  1310. return 1;
  1311. }
  1312. return - 1;
  1313. }
  1314. protected function _sortDown($x, $y) {
  1315. if ($x[1] == $y[1]) {
  1316. return 0;
  1317. } elseif ($x[1] < $y[1]) {
  1318. return - 1;
  1319. }
  1320. return 1;
  1321. }
  1322. }