CommonComponent.php 41 KB

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