CommonComponent.php 42 KB

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