CommonComponent.php 41 KB

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