CommonComponent.php 41 KB

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