CommonComponent.php 44 KB

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