CommonComponent.php 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468
  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. Configure::write('Meta.'.$type, $content);
  505. }
  506. /*** Other helpers and debug features **/
  507. /**
  508. * Generates validation error messages for HABTM fields
  509. * ?
  510. *
  511. * @author Dean
  512. * @return void
  513. */
  514. protected function _habtmValidation() {
  515. $model = $this->Controller->modelClass;
  516. if (isset($this->Controller->{$model}) && isset($this->Controller->{$model}->hasAndBelongsToMany)) {
  517. foreach ($this->Controller->{$model}->hasAndBelongsToMany as $alias => $options) {
  518. if (isset($this->Controller->{$model}->validationErrors[$alias])) {
  519. $this->Controller->{$model}->{$alias}->validationErrors[$alias] = $this->Controller->{$model}->validationErrors[$alias];
  520. }
  521. }
  522. }
  523. }
  524. /**
  525. * Set headers to cache this request.
  526. * Opposite of Controller::disableCache()
  527. * TODO: set response class header instead
  528. *
  529. * @param int $seconds
  530. * @return void
  531. * 2009-12-26 ms
  532. */
  533. public function forceCache($seconds = HOUR) {
  534. header('Cache-Control: public, max-age=' . $seconds);
  535. header('Last-modified: ' . gmdate("D, j M Y H:i:s", time()) . " GMT");
  536. header('Expires: ' . gmdate("D, j M Y H:i:s", time() + $seconds) . " GMT");
  537. }
  538. /**
  539. * Referrer checking (where does the user come from)
  540. * Only returns true for a valid external referrer.
  541. *
  542. * @return boolean Success
  543. * 2009-12-19 ms
  544. */
  545. public function isForeignReferer($ref = null) {
  546. if ($ref === null) {
  547. $ref = env('HTTP_REFERER');
  548. }
  549. if (!$ref) {
  550. return false;
  551. }
  552. $base = FULL_BASE_URL . $this->Controller->webroot;
  553. if (strpos($ref, $base) === 0) {
  554. return false;
  555. }
  556. return true;
  557. }
  558. /**
  559. * CommonComponent::denyAccess()
  560. *
  561. * @return void
  562. */
  563. public function denyAccess() {
  564. $ref = env('HTTP_USER_AGENT');
  565. if ($this->isForeignReferer($ref)) {
  566. if (eregi('http://Anonymouse.org/', $ref)) {
  567. //echo returns(Configure::read('Config.language'));
  568. $this->cakeError('error406', array());
  569. }
  570. }
  571. }
  572. /**
  573. * CommonComponent::monitorCookieProblems()
  574. *
  575. * @return void
  576. */
  577. public function monitorCookieProblems() {
  578. /*
  579. if (($language = Configure::read('Config.language')) === null) {
  580. //$this->log('CookieProblem: SID '.session_id().' | '.env('REMOTE_ADDR').' | Ref: '.env('HTTP_REFERER').' |Agent: '.env('HTTP_USER_AGENT'));
  581. }
  582. */
  583. $ip = $this->RequestHandler->getClientIP(); //env('REMOTE_ADDR');
  584. $host = gethostbyaddr($ip);
  585. $sessionId = session_id();
  586. if (empty($sessionId)) {
  587. $sessionId = '--';
  588. }
  589. if (empty($_REQUEST[Configure::read('Session.cookie')]) && !($res = Cache::read($ip))) {
  590. $this->log('CookieProblem:: SID: '.$sessionId.' | IP: '.$ip.' ('.$host.') | REF: '.$this->Controller->referer().' | Agent: '.env('HTTP_USER_AGENT'), 'noscript');
  591. Cache::write($ip, 1);
  592. }
  593. }
  594. /**
  595. * //todo: move to Utility?
  596. *
  597. * @return boolean true if disabled (bots, etc), false if enabled
  598. * 2010-11-20 ms
  599. */
  600. public static function cookiesDisabled() {
  601. if (!empty($_COOKIE) && !empty($_COOKIE[Configure::read('Session.cookie')])) {
  602. return false;
  603. }
  604. return true;
  605. }
  606. /**
  607. * quick sql debug from controller dynamically
  608. * or statically from just about any other place in the script
  609. * @param bool $die: TRUE to output and die, FALSE to log to file and continue
  610. * 2011-06-30 ms
  611. */
  612. public function sql($die = true) {
  613. if (isset($this->Controller)) {
  614. $object = $this->Controller->{$this->Controller->modelClass};
  615. } else {
  616. $object = ClassRegistry::init(defined('CLASS_USER') ? CLASS_USER : $this->userModel);
  617. }
  618. $log = $object->getDataSource()->getLog(false, false);
  619. foreach ($log['log'] as $key => $value) {
  620. if (strpos($value['query'], 'SHOW ') === 0 || strpos($value['query'], 'SELECT CHARACTER_SET_NAME ') === 0) {
  621. unset($log['log'][$key]);
  622. continue;
  623. }
  624. }
  625. # output and die?
  626. if ($die) {
  627. debug($log);
  628. die();
  629. }
  630. # log to file then and continue
  631. $log = print_r($log, true);
  632. App::uses('CakeLog', 'Log');
  633. return CakeLog::write('sql', $log);
  634. }
  635. /**
  636. * Temporary check how often current cache fails!
  637. * TODO: move
  638. *
  639. * @return boolean Success
  640. * 2010-05-07 ms
  641. */
  642. public function ensureCacheIsOk() {
  643. $x = Cache::read('xyz012345');
  644. if (!$x) {
  645. $x = Cache::write('xyz012345', 1);
  646. $this->log(date(FORMAT_DB_DATETIME), 'cacheprob');
  647. return false;
  648. }
  649. return true;
  650. }
  651. /**
  652. * Localize
  653. *
  654. * @return boolean Success
  655. * 2010-04-29 ms
  656. */
  657. public function localize($lang = null) {
  658. if ($lang === null) {
  659. $lang = Configure::read('Config.language');
  660. }
  661. if (empty($lang)) {
  662. return false;
  663. }
  664. if (($pos = strpos($lang, '-')) !== false) {
  665. $lang = substr($lang, 0, $pos);
  666. }
  667. if ($lang == DEFAULT_LANGUAGE) {
  668. return null;
  669. }
  670. if (!((array)$pattern = Configure::read('LocalizationPattern.'.$lang))) {
  671. return false;
  672. }
  673. foreach ($pattern as $key => $value) {
  674. Configure::write('Localization.'.$key, $value);
  675. }
  676. return true;
  677. }
  678. /**
  679. * bug fix for i18n
  680. * still needed?
  681. *
  682. * @return void
  683. * 2010-01-01 ms
  684. */
  685. public function ensureDefaultLanguage() {
  686. if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
  687. //Configure::write('Config.language', DEFAULT_LANGUAGE);
  688. }
  689. }
  690. /**
  691. * main controller function for consistency in controller naming
  692. * 2009-12-19 ms
  693. */
  694. public function ensureControllerConsistency() {
  695. # problems with plugins
  696. if (!empty($this->Controller->request->params['plugin'])) {
  697. return;
  698. }
  699. if (($name = strtolower(Inflector::underscore($this->Controller->name))) !== $this->Controller->request->params['controller']) {
  700. $this->Controller->log('301: '.$this->Controller->request->params['controller'].' => '.$name.' (Ref '.$this->Controller->referer().')', '301'); // log problem with controller naming
  701. if (!$this->Controller->RequestHandler->isPost()) {
  702. # underscored version is the only valid one to avoid duplicate content
  703. $url = array('controller' => $name, 'action' => $this->Controller->request->params['action']);
  704. $url = array_merge($url, $this->Controller->request->params['pass'], $this->Controller->request->params['named']);
  705. //TODO: add plugin/admin stuff which right now is supposed to work automatically
  706. $this->Controller->redirect($url, 301);
  707. }
  708. }
  709. return true;
  710. # problem with extensions (rss etc)
  711. if (empty($this->Controller->request->params['prefix']) && ($currentUrl = $this->currentUrl(true)) != $this->Controller->here) {
  712. //pr($this->Controller->here);
  713. //pr($currentUrl);
  714. $this->log('301: '.$this->Controller->here.' => '.$currentUrl.' (Referer '.$this->Controller->referer().')', '301');
  715. if (!$this->Controller->RequestHandler->isPost()) {
  716. $url = array('controller' => $this->Controller->request->params['controller'], 'action' => $this->Controller->request->params['action']);
  717. $url = array_merge($url, $this->Controller->request->params['pass'], $this->Controller->request->params['named']);
  718. $this->Controller->redirect($url, 301);
  719. }
  720. }
  721. }
  722. /**
  723. * main controller function for seo-slugs
  724. * passed titleSlug != current title => redirect to the expected one
  725. * 2009-07-31 ms
  726. */
  727. public function ensureConsistency($id, $passedTitleSlug, $currentTitle) {
  728. $expectedTitle = slug($currentTitle);
  729. if (empty($passedTitleSlug) || $expectedTitle != $passedTitleSlug) { # case sensitive!!!
  730. $ref = env('HTTP_REFERER');
  731. if (!$this->isForeignReferer($ref)) {
  732. $this->Controller->log('Internal ConsistencyProblem at \''.$ref.'\' - ['.$passedTitleSlug.'] instead of ['.$expectedTitle.']', 'referer');
  733. } else {
  734. $this->Controller->log('External ConsistencyProblem at \''.$ref.'\' - ['.$passedTitleSlug.'] instead of ['.$expectedTitle.']', 'referer');
  735. }
  736. $this->Controller->redirect(array($id, $expectedTitle), 301);
  737. }
  738. }
  739. /**
  740. * Try to detect group for a multidim array for select boxes.
  741. * Extracts the group name of the selected key.
  742. *
  743. * @param array $array
  744. * @param string $key
  745. * @param array $matching
  746. * @return string $result
  747. * 2011-03-12 ms
  748. */
  749. public static function getGroup($multiDimArray, $key, $matching = array()) {
  750. if (!is_array($multiDimArray) || empty($key)) {
  751. return '';
  752. }
  753. foreach ($multiDimArray as $group => $data) {
  754. if (array_key_exists($key, $data)) {
  755. if (!empty($matching)) {
  756. if (array_key_exists($group, $matching)) {
  757. return $matching[$group];
  758. }
  759. return '';
  760. }
  761. return $group;
  762. }
  763. }
  764. return '';
  765. }
  766. /*** DEEP FUNCTIONS ***/
  767. /**
  768. * move to boostrap?
  769. * 2009-07-07 ms
  770. */
  771. public function trimDeep($value) {
  772. $value = is_array($value) ? array_map(array($this, 'trimDeep'), $value) : trim($value);
  773. return $value;
  774. }
  775. /**
  776. * move to boostrap?
  777. * 2009-07-07 ms
  778. */
  779. public function specialcharsDeep($value) {
  780. $value = is_array($value) ? array_map(array($this, 'specialcharsDeep'), $value) : htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
  781. return $value;
  782. }
  783. /**
  784. * move to boostrap?
  785. * 2009-07-07 ms
  786. */
  787. public function deep($function, $value) {
  788. $value = is_array($value) ? array_map(array($this, $function), $value) : $function($value);
  789. return $value;
  790. }
  791. /**
  792. * MAIN Sanitize Array-FUNCTION
  793. * @param string $type: html, paranoid
  794. * move to boostrap?
  795. * 2008-11-06 ms
  796. */
  797. public function sanitizeDeep($value, $type = null, $options = null) {
  798. switch ($type) {
  799. case 'html':
  800. if (isset($options['remove']) && is_bool($options['remove'])) {
  801. $this->removeChars = $options['remove'];
  802. }
  803. $value = $this->htmlDeep($value);
  804. break;
  805. case 'paranoid':
  806. default:
  807. if (isset($options['allowed']) && is_array($options['allowed'])) {
  808. $this->allowedChars = $options['allowed'];
  809. }
  810. $value = $this->paranoidDeep($value);
  811. }
  812. return $value;
  813. }
  814. /**
  815. * removes all except A-Z,a-z,0-9 and allowedChars (allowedChars array)
  816. * move to boostrap?
  817. * 2009-07-07 ms
  818. */
  819. public function paranoidDeep($value) {
  820. $mrClean = new Sanitize();
  821. $value = is_array($value) ? array_map(array($this, 'paranoidDeep'), $value) : $mrClean->paranoid($value, $this->allowedChars);
  822. return $value;
  823. }
  824. /**
  825. * transfers/removes all < > from text (remove TRUE/FALSE)
  826. * move to boostrap?
  827. * 2009-07-07 ms
  828. */
  829. public function htmlDeep($value) {
  830. $mrClean = new Sanitize();
  831. $value = is_array($value) ? array_map(array($this, 'htmlDeep'), $value) : $mrClean->html($value, $this->removeChars);
  832. return $value;
  833. }
  834. /**
  835. * Takes list of items and transforms it into an array
  836. * + cleaning (trim, no empty parts, etc)
  837. *
  838. * @param string $string containing the parts
  839. * @param string $separator (defaults to ',')
  840. * @param boolean $camelize (true/false): problems with äöüß etc!
  841. * @return array $results as array list
  842. * //TODO: 3.4. parameter as array, move to Lib
  843. * 2009-08-13 ms
  844. */
  845. public function parseList($string, $separator = null, $camelize = false, $capitalize = true) {
  846. if ($separator === null) {
  847. $separator = ',';
  848. }
  849. # parses the list, but leaves tokens untouched inside () brackets
  850. $stringArray = String::tokenize($string, $separator);
  851. $returnArray = array();
  852. if (empty($stringArray)) {
  853. return array();
  854. }
  855. foreach ($stringArray as $t) {
  856. $t = trim($t);
  857. if (!empty($t)) {
  858. if ($camelize === true) {
  859. $t = mb_strtolower($t);
  860. $t = Inflector::camelize(Inflector::underscore($t)); # problems with non-alpha chars!!
  861. } elseif ($capitalize === true) {
  862. $t = ucwords($t);
  863. }
  864. $returnArray[] = $t;
  865. }
  866. }
  867. return $returnArray;
  868. }
  869. /**
  870. * //todo move to lib!!!
  871. * static
  872. * 2009-12-21 ms
  873. */
  874. public function separators($s = null, $valueOnly = false) {
  875. $separatorsValues = array(SEPARATOR_COMMA => ',', SEPARATOR_SEMI => ';', SEPARATOR_SPACE => ' ', SEPARATOR_TAB => TB, SEPARATOR_NL => NL);
  876. $separators = array(SEPARATOR_COMMA => '[ , ] '.__('Comma'), SEPARATOR_SEMI => '[ ; ] '.__('Semicolon'), SEPARATOR_SPACE => '[ &nbsp; ] '.__('Space'), SEPARATOR_TAB =>
  877. '[ &nbsp;&nbsp;&nbsp;&nbsp; ] '.__('Tabulator'), SEPARATOR_NL => '[ \n ] '.__('New Line'));
  878. if ($s !== null) {
  879. if (array_key_exists($s, $separators)) {
  880. if ($valueOnly) {
  881. return $separatorsValues[$s];
  882. }
  883. return $separators[$s];
  884. }
  885. return '';
  886. }
  887. return $valueOnly ? $separatorsValues : $separators;
  888. }
  889. /*** deprecated ***/
  890. /**
  891. * add protocol prefix if necessary (and possible)
  892. * 2010-06-02 ms
  893. */
  894. public function autoPrefixUrl($url, $prefix = null) {
  895. trigger_error('deprecated - use Utility::autoPrefixUrl()');
  896. return Utility::autoPrefixUrl($url, $prefix);
  897. }
  898. /**
  899. * remove unnessary stuff + add http:// for external urls
  900. * 2009-12-22 ms
  901. */
  902. public static function cleanUrl($url, $headerRedirect = false) {
  903. trigger_error('deprecated - use Utility::cleanUrl()');
  904. return Utility::cleanUrl($url, $headerRedirect);
  905. }
  906. /**
  907. * 2009-12-26 ms
  908. */
  909. public static function getHeaderFromUrl($url) {
  910. trigger_error('deprecated - use Utility::getHeaderFromUrl()');
  911. return Utility::getHeaderFromUrl($url);
  912. }
  913. /**
  914. * get the current ip address
  915. * @param bool $safe
  916. * @return string $ip
  917. * 2011-11-02 ms
  918. */
  919. public static function getClientIp($safe = null) {
  920. trigger_error('deprecated - use Utility::getClientIp()');
  921. return Utility::getClientIp($safe);
  922. }
  923. /**
  924. * get the current referer
  925. * @param bool $full (defaults to false and leaves the url untouched)
  926. * @return string $referer (local or foreign)
  927. * 2011-11-02 ms
  928. */
  929. public static function getReferer($full = false) {
  930. trigger_error('deprecated - use Utility::getReferer()');
  931. return Utility::getReferer($full);
  932. }
  933. /**
  934. * returns true only if all values are true
  935. * @return bool $result
  936. * maybe move to bootstrap?
  937. * 2011-11-02 ms
  938. */
  939. public static function logicalAnd($array) {
  940. trigger_error('deprecated - use Utility::logicalAnd()');
  941. return Utility::logicalAnd($array);
  942. }
  943. /**
  944. * returns true if at least one value is true
  945. * @return bool $result
  946. * maybe move to bootstrap?
  947. * 2011-11-02 ms
  948. */
  949. public static function logicalOr($array) {
  950. trigger_error('deprecated - use Utility::logicalOr()');
  951. return Utility::logicalOr($array);
  952. }
  953. /**
  954. * Convenience function for automatic casting in form methods etc
  955. * @return safe value for DB query, or NULL if type was not a valid one
  956. * maybe move to bootstrap?
  957. * 2008-12-12 ms
  958. */
  959. public static function typeCast($type = null, $value = null) {
  960. trigger_error('deprecated - use Utility::typeCast()');
  961. return Utility::typeCast($type, $value);
  962. }
  963. /**
  964. * //TODO: move somewhere else
  965. * Returns an array with chars
  966. * up = uppercase, low = lowercase
  967. * @var char type: NULL/up/down | default: NULL (= down)
  968. * @return array with the a-z
  969. *
  970. * @deprecated: USE range() instead! move to lib
  971. */
  972. public function alphaFilterSymbols($type = null) {
  973. trigger_error('deprecated');
  974. $arr = array();
  975. for ($i = 97; $i < 123; $i++) {
  976. if ($type === 'up') {
  977. $arr[] = chr($i - 32);
  978. } else {
  979. $arr[] = chr($i);
  980. }
  981. }
  982. return $arr;
  983. }
  984. /**
  985. * //TODO: move somewhere else
  986. * Assign Array to Char Array
  987. *
  988. * @var content array
  989. * @var char array
  990. * @return array: chars with content
  991. * PROTECTED NAMES (content cannot contain those): undefined
  992. * 2009-12-26 ms
  993. */
  994. public function assignToChar($content_array, $char_array = null) {
  995. $res = array();
  996. $res['undefined'] = array();
  997. if (empty($char_array)) {
  998. $char_array = $this->alphaFilterSymbols();
  999. }
  1000. foreach ($content_array as $content) {
  1001. $done = false;
  1002. # loop them trough
  1003. foreach ($char_array as $char) {
  1004. if (empty($res[$char])) { // throws warnings otherwise
  1005. $res[$char] = array();
  1006. }
  1007. if (!empty($content) && strtolower(substr($content, 0, 1)) == $char) {
  1008. $res[$char][] = $content;
  1009. $done = true;
  1010. }
  1011. }
  1012. # no match?
  1013. if (!empty($content) && !$done) {
  1014. $res['undefined'][] = $content;
  1015. }
  1016. }
  1017. return $res;
  1018. }
  1019. /**
  1020. * Extract email from "name <email>" etc
  1021. *
  1022. * @deprecated
  1023. * use splitEmail instead
  1024. */
  1025. public function extractEmail($email) {
  1026. if (($pos = mb_strpos($email, '<')) !== false) {
  1027. $email = substr($email, $pos + 1);
  1028. }
  1029. if (($pos = mb_strrpos($email, '>')) !== false) {
  1030. $email = substr($email, 0, $pos);
  1031. }
  1032. return trim($email);
  1033. }
  1034. /**
  1035. * expects email to be valid!
  1036. * TODO: move to Lib
  1037. * @return array $email - pattern: array('email'=>,'name'=>)
  1038. * 2010-04-20 ms
  1039. */
  1040. public function splitEmail($email, $abortOnError = false) {
  1041. $array = array('email'=>'', 'name'=>'');
  1042. if (($pos = mb_strpos($email, '<')) !== false) {
  1043. $name = substr($email, 0, $pos);
  1044. $email = substr($email, $pos+1);
  1045. }
  1046. if (($pos = mb_strrpos($email, '>')) !== false) {
  1047. $email = substr($email, 0, $pos);
  1048. }
  1049. $email = trim($email);
  1050. if (!empty($email)) {
  1051. $array['email'] = $email;
  1052. }
  1053. if (!empty($name)) {
  1054. $array['name'] = trim($name);
  1055. }
  1056. return $array;
  1057. }
  1058. /**
  1059. * TODO: move to Lib
  1060. * @param string $email
  1061. * @param string $name (optional, will use email otherwise)
  1062. */
  1063. public function combineEmail($email, $name = null) {
  1064. if (empty($email)) {
  1065. return '';
  1066. }
  1067. if (empty($name)) {
  1068. $name = $email;
  1069. }
  1070. return $name.' <'.$email['email'].'>';
  1071. }
  1072. /**
  1073. * TODO: move to Lib
  1074. * returns type
  1075. * - username: everything till @ (xyz@abc.de => xyz)
  1076. * - hostname: whole domain (xyz@abc.de => abc.de)
  1077. * - tld: top level domain only (xyz@abc.de => de)
  1078. * - domain: if available (xyz@e.abc.de => abc)
  1079. * - subdomain: if available (xyz@e.abc.de => e)
  1080. * @param string $email: well formatted email! (containing one @ and one .)
  1081. * @param string $type (TODO: defaults to return all elements)
  1082. * @returns string or false on failure
  1083. * 2010-01-10 ms
  1084. */
  1085. public function extractEmailInfo($email, $type = null) {
  1086. //$checkpos = strrpos($email, '@');
  1087. $nameParts = explode('@', $email);
  1088. if (count($nameParts) !== 2) {
  1089. return false;
  1090. }
  1091. if ($type === 'username') {
  1092. return $nameParts[0];
  1093. }
  1094. if ($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. }
  1324. if ($x[1] < $y[1]) {
  1325. return 1;
  1326. }
  1327. return - 1;
  1328. }
  1329. protected function _sortDown($x, $y) {
  1330. if ($x[1] == $y[1]) {
  1331. return 0;
  1332. }
  1333. if ($x[1] < $y[1]) {
  1334. return - 1;
  1335. }
  1336. return 1;
  1337. }
  1338. }