CommonComponent.php 41 KB

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