CommonComponent.php 42 KB

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