CommonComponent.php 41 KB

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