CommonComponent.php 41 KB

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