CommonComponent.php 42 KB

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