CommonComponent.php 41 KB

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