CommonHelper.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  1. <?php
  2. App::uses('AppHelper', 'View/Helper');
  3. App::uses('CommonComponent', 'Tools.Controller/Component');
  4. App::uses('Hash', 'Utility');
  5. /**
  6. * All site-wide necessary stuff for the view layer
  7. */
  8. class CommonHelper extends AppHelper {
  9. public $helpers = array('Session', 'Html');
  10. /**
  11. * Display all flash messages.
  12. *
  13. * TODO: export div wrapping method (for static messaging on a page)
  14. *
  15. * @param array $types Types to output. Defaults to all if none are specified.
  16. * @return string HTML
  17. */
  18. public function flash(array $types = array()) {
  19. // Get the messages from the session
  20. $messages = (array)$this->Session->read('messages');
  21. $cMessages = (array)Configure::read('messages');
  22. if (!empty($cMessages)) {
  23. $messages = (array)Hash::merge($messages, $cMessages);
  24. }
  25. $html = '';
  26. if (!empty($messages)) {
  27. $html = '<div class="flash-messages flashMessages">';
  28. if ($types) {
  29. foreach ($types as $type) {
  30. // Add a div for each message using the type as the class.
  31. foreach ($messages as $messageType => $msgs) {
  32. if ($messageType !== $type) {
  33. continue;
  34. }
  35. foreach ((array)$msgs as $msg) {
  36. $html .= $this->_message($msg, $messageType);
  37. }
  38. }
  39. }
  40. } else {
  41. foreach ($messages as $messageType => $msgs) {
  42. foreach ((array)$msgs as $msg) {
  43. $html .= $this->_message($msg, $messageType);
  44. }
  45. }
  46. }
  47. $html .= '</div>';
  48. if ($types) {
  49. foreach ($types as $type) {
  50. CakeSession::delete('messages.' . $type);
  51. Configure::delete('messages.' . $type);
  52. }
  53. } else {
  54. CakeSession::delete('messages');
  55. Configure::delete('messages');
  56. }
  57. }
  58. return $html;
  59. }
  60. /**
  61. * Outputs a single flashMessage directly.
  62. * Note that this does not use the Session.
  63. *
  64. * @param string $message String to output.
  65. * @param string $type Type (success, warning, error, info)
  66. * @param bool $escape Set to false to disable escaping.
  67. * @return string HTML
  68. */
  69. public function flashMessage($msg, $type = 'info', $escape = true) {
  70. $html = '<div class="flash-messages flashMessages">';
  71. if ($escape) {
  72. $msg = h($msg);
  73. }
  74. $html .= $this->_message($msg, $type);
  75. $html .= '</div>';
  76. return $html;
  77. }
  78. /**
  79. * Formats a message
  80. *
  81. * @param string $msg Message to output.
  82. * @param string $type Type that will be formatted to a class tag.
  83. * @return string
  84. */
  85. protected function _message($msg, $type) {
  86. if (!empty($msg)) {
  87. return '<div class="message' . (!empty($type) ? ' ' . $type : '') . '">' . $msg . '</div>';
  88. }
  89. return '';
  90. }
  91. /**
  92. * Add a message on the fly
  93. *
  94. * @param string $msg
  95. * @param string $class
  96. * @return void
  97. */
  98. public function addFlashMessage($msg, $class = null) {
  99. CommonComponent::transientFlashMessage($msg, $class);
  100. }
  101. /**
  102. * CommonHelper::transientFlashMessage()
  103. *
  104. * @param mixed $msg
  105. * @param mixed $class
  106. * @return void
  107. * @deprecated Use addFlashMessage() instead
  108. */
  109. public function transientFlashMessage($msg, $class = null) {
  110. $this->addFlashMessage($msg, $class);
  111. }
  112. /**
  113. * Escape text with some more automagic
  114. * TODO: move into TextExt?
  115. *
  116. * @param string $text
  117. * @param array $options
  118. * @return string processedText
  119. * - nl2br: true/false (defaults to true)
  120. * - escape: false prevents h() and space transformation (defaults to true)
  121. * - tabsToSpaces: int (defaults to 4)
  122. */
  123. public function esc($text, $options = array()) {
  124. if (!isset($options['escape']) || $options['escape'] !== false) {
  125. //$text = str_replace(' ', '&nbsp;', h($text));
  126. $text = h($text);
  127. // try to fix indends made out of spaces
  128. $text = explode(NL, $text);
  129. foreach ($text as $key => $t) {
  130. $i = 0;
  131. while (!empty($t[$i]) && $t[$i] === ' ') {
  132. $i++;
  133. }
  134. if ($i > 0) {
  135. $t = str_repeat('&nbsp;', $i) . substr($t, $i);
  136. $text[$key] = $t;
  137. }
  138. }
  139. $text = implode(NL, $text);
  140. $esc = true;
  141. }
  142. if (!isset($options['nl2br']) || $options['nl2br'] !== false) {
  143. $text = nl2br($text);
  144. }
  145. if (!isset($options['tabsToSpaces'])) {
  146. $options['tabsToSpaces'] = 4;
  147. }
  148. if (!empty($options['tabsToSpaces'])) {
  149. $text = str_replace(TB, str_repeat(!empty($esc) ? '&nbsp;' : ' ', $options['tabsToSpaces']), $text);
  150. }
  151. return $text;
  152. }
  153. /**
  154. * Alternates between two or more strings.
  155. *
  156. * echo CommonHelper::alternate('one', 'two'); // "one"
  157. * echo CommonHelper::alternate('one', 'two'); // "two"
  158. * echo CommonHelper::alternate('one', 'two'); // "one"
  159. *
  160. * Note that using multiple iterations of different strings may produce
  161. * unexpected results.
  162. * TODO: move to booststrap/lib!!!
  163. *
  164. * @param string strings to alternate between
  165. * @return string
  166. */
  167. public static function alternate() {
  168. static $i;
  169. if (func_num_args() === 0) {
  170. $i = 0;
  171. return '';
  172. }
  173. $args = func_get_args();
  174. return $args[($i++ % count($args))];
  175. }
  176. /**
  177. * Auto-pluralizing a word using the Inflection class
  178. * //TODO: move to lib or bootstrap
  179. *
  180. * @param string $singular The string to be pl.
  181. * @param int $count
  182. * @return string "member" or "members" OR "Mitglied"/"Mitglieder" if autoTranslate TRUE
  183. */
  184. public function asp($singular, $count, $autoTranslate = false) {
  185. if ((int)$count !== 1) {
  186. $pural = Inflector::pluralize($singular);
  187. } else {
  188. $pural = null; // No pluralization necessary
  189. }
  190. return $this->sp($singular, $pural, $count, $autoTranslate);
  191. }
  192. /**
  193. * Manual pluralizing a word using the Inflection class
  194. * //TODO: move to lib or bootstrap
  195. *
  196. * @param string $singular
  197. * @param string $plural
  198. * @param int $count
  199. * @return string result
  200. */
  201. public function sp($singular, $plural, $count, $autoTranslate = false) {
  202. if ((int)$count !== 1) {
  203. $result = $plural;
  204. } else {
  205. $result = $singular;
  206. }
  207. if ($autoTranslate) {
  208. $result = __($result);
  209. }
  210. return $result;
  211. }
  212. /**
  213. * Convenience method for clean ROBOTS allowance
  214. *
  215. * @param string $type - private/public
  216. * @return string HTML
  217. */
  218. public function metaRobots($type = null) {
  219. if ($type === null && ($meta = Configure::read('Config.robots')) !== null) {
  220. $type = $meta;
  221. }
  222. $content = array();
  223. if ($type === 'public') {
  224. $this->privatePage = false;
  225. $content['robots'] = array('index', 'follow', 'noarchive');
  226. } else {
  227. $this->privatePage = true;
  228. $content['robots'] = array('noindex', 'nofollow', 'noarchive');
  229. }
  230. $return = '<meta name="robots" content="' . implode(',', $content['robots']) . '" />';
  231. return $return;
  232. }
  233. /**
  234. * Convenience method for clean meta name tags
  235. *
  236. * @param string $name: author, date, generator, revisit-after, language
  237. * @param mixed $content: if array, it will be seperated by commas
  238. * @return string HTML Markup
  239. */
  240. public function metaName($name = null, $content = null) {
  241. if (empty($name) || empty($content)) {
  242. return '';
  243. }
  244. $content = (array)$content;
  245. $return = '<meta name="' . $name . '" content="' . implode(', ', $content) . '" />';
  246. return $return;
  247. }
  248. /**
  249. * Convenience method for meta description
  250. *
  251. * @param string $content
  252. * @param string $language (iso2: de, en-us, ...)
  253. * @param array $additionalOptions
  254. * @return string HTML Markup
  255. */
  256. public function metaDescription($content, $language = null, $options = array()) {
  257. if (!empty($language)) {
  258. $options['lang'] = mb_strtolower($language);
  259. } elseif ($language !== false) {
  260. $options['lang'] = Configure::read('Config.locale');
  261. }
  262. return $this->Html->meta('description', $content, $options);
  263. }
  264. /**
  265. * Convenience method to output meta keywords
  266. *
  267. * @param string|array $keywords
  268. * @param string $language (iso2: de, en-us, ...)
  269. * @param bool $escape
  270. * @return string HTML Markup
  271. */
  272. public function metaKeywords($keywords = null, $language = null, $escape = true) {
  273. if ($keywords === null) {
  274. $keywords = Configure::read('Config.keywords');
  275. }
  276. if (is_array($keywords)) {
  277. $keywords = implode(', ', $keywords);
  278. }
  279. if ($escape) {
  280. $keywords = h($keywords);
  281. }
  282. if (!empty($language)) {
  283. $options['lang'] = mb_strtolower($language);
  284. } elseif ($language !== false) {
  285. $options['lang'] = Configure::read('Config.locale');
  286. }
  287. return $this->Html->meta('keywords', $keywords, $options);
  288. }
  289. /**
  290. * Convenience function for "canonical" SEO links
  291. *
  292. * @param mixed $url
  293. * @param bool $full
  294. * @return string HTML Markup
  295. */
  296. public function metaCanonical($url = null, $full = false) {
  297. $canonical = $this->Html->url($url, $full);
  298. $options = array('rel' => 'canonical', 'type' => null, 'title' => null);
  299. return $this->Html->meta('canonical', $canonical, $options);
  300. }
  301. /**
  302. * Convenience method for "alternate" SEO links
  303. *
  304. * @param mixed $url
  305. * @param mixed $lang (lang(iso2) or array of langs)
  306. * lang: language (in ISO 6391-1 format) + optionally the region (in ISO 3166-1 Alpha 2 format)
  307. * - de
  308. * - de-ch
  309. * etc
  310. * @return string HTML Markup
  311. */
  312. public function metaAlternate($url, $lang, $full = false) {
  313. //$canonical = $this->Html->url($url, $full);
  314. $url = $this->Html->url($url, $full);
  315. //return $this->Html->meta('canonical', $canonical, array('rel'=>'canonical', 'type'=>null, 'title'=>null));
  316. $lang = (array)$lang;
  317. $res = array();
  318. foreach ($lang as $language => $countries) {
  319. if (is_numeric($language)) {
  320. $language = '';
  321. } else {
  322. $language .= '-';
  323. }
  324. $countries = (array)$countries;
  325. foreach ($countries as $country) {
  326. $l = $language . $country;
  327. $options = array('rel' => 'alternate', 'hreflang' => $l, 'type' => null, 'title' => null);
  328. $res[] = $this->Html->meta('alternate', $url, $options) . PHP_EOL;
  329. }
  330. }
  331. return implode('', $res);
  332. }
  333. /**
  334. * Convenience method for META Tags
  335. *
  336. * @param mixed $url
  337. * @param string $title
  338. * @return string HTML Markup
  339. */
  340. public function metaRss($url, $title = null) {
  341. $tags = array(
  342. 'meta' => '<link rel="alternate" type="application/rss+xml" title="%s" href="%s" />',
  343. );
  344. if (empty($title)) {
  345. $title = __('Subscribe to this feed');
  346. } else {
  347. $title = h($title);
  348. }
  349. return sprintf($tags['meta'], $title, $this->url($url));
  350. }
  351. /**
  352. * Convenience method for META Tags
  353. *
  354. * @param string $type
  355. * @param string $content
  356. * @return string HTML Markup
  357. */
  358. public function metaEquiv($type, $value, $escape = true) {
  359. $tags = array(
  360. 'meta' => '<meta http-equiv="%s"%s />',
  361. );
  362. if ($value === null) {
  363. return '';
  364. }
  365. if ($escape) {
  366. $value = h($value);
  367. }
  368. return sprintf($tags['meta'], $type, ' content="' . $value . '"');
  369. }
  370. /**
  371. * (example): array(x, Tools|y, Tools.Jquery|jquery/sub/z)
  372. * => x is in webroot/
  373. * => y is in plugins/tools/webroot/
  374. * => z is in plugins/tools/packages/jquery/files/jquery/sub/
  375. *
  376. * @return string HTML Markup
  377. * @deprecated Use AssetCompress plugin instead
  378. */
  379. public function css($files = array(), $options = array()) {
  380. $files = (array)$files;
  381. $pieces = array();
  382. foreach ($files as $file) {
  383. $pieces[] = 'file=' . $file;
  384. }
  385. if ($v = Configure::read('Config.layout_v')) {
  386. $pieces[] = 'v=' . $v;
  387. }
  388. $string = implode('&', $pieces);
  389. return $this->Html->css('/css.php?' . $string, $options);
  390. }
  391. /**
  392. * (example): array(x, Tools|y, Tools.Jquery|jquery/sub/z)
  393. * => x is in webroot/
  394. * => y is in plugins/tools/webroot/
  395. * => z is in plugins/tools/packages/jquery/files/jquery/sub/
  396. *
  397. * @return string HTML Markup
  398. * @deprecated Use AssetCompress plugin instead
  399. */
  400. public function script($files = array(), $options = array()) {
  401. $files = (array)$files;
  402. foreach ($files as $file) {
  403. $pieces[] = 'file=' . $file;
  404. }
  405. if ($v = Configure::read('Config.layout_v')) {
  406. $pieces[] = 'v=' . $v;
  407. }
  408. $string = implode('&', $pieces);
  409. return $this->Html->script('/js.php?' . $string, $options);
  410. }
  411. /**
  412. * Still necessary?
  413. *
  414. * @param array $fields
  415. * @return string HTML
  416. */
  417. public function displayErrors($fields = array()) {
  418. $res = '';
  419. if (!empty($this->validationErrors)) {
  420. if ($fields === null) { # catch ALL
  421. foreach ($this->validationErrors as $alias => $error) {
  422. list($alias, $fieldname) = explode('.', $error);
  423. $this->validationErrors[$alias][$fieldname];
  424. }
  425. } elseif (!empty($fields)) {
  426. foreach ($fields as $field) {
  427. list($alias, $fieldname) = explode('.', $field);
  428. if (!empty($this->validationErrors[$alias][$fieldname])) {
  429. $res .= $this->_renderError($this->validationErrors[$alias][$fieldname]);
  430. }
  431. }
  432. }
  433. }
  434. return $res;
  435. }
  436. protected function _renderError($error, $escape = true) {
  437. if ($escape !== false) {
  438. $error = h($error);
  439. }
  440. return '<div class="error-message">' . $error . '</div>';
  441. }
  442. /**
  443. * Check if session works due to allowed cookies
  444. *
  445. * @param bool Success
  446. */
  447. public function sessionCheck() {
  448. return !CommonComponent::cookiesDisabled();
  449. /*
  450. if (!empty($_COOKIE) && !empty($_COOKIE[Configure::read('Session.cookie')])) {
  451. return true;
  452. }
  453. return false;
  454. */
  455. }
  456. /**
  457. * Display warning if cookies are disallowed (and session won't work)
  458. *
  459. * @return string HTML
  460. */
  461. public function sessionCheckAlert() {
  462. if ($this->sessionCheck()) {
  463. return '';
  464. }
  465. return '<div class="cookieWarning">' . __('Please enable cookies') . '</div>';
  466. }
  467. /**
  468. * Prevents site being opened/included by others/websites inside frames
  469. *
  470. * @return string
  471. */
  472. public function framebuster() {
  473. return $this->Html->scriptBlock('
  474. if (top!=self) top.location.ref=self.location.href;
  475. ');
  476. }
  477. /**
  478. * Currenctly only alerts on IE6/IE7
  479. * options
  480. * - engine (js, jquery)
  481. * - escape
  482. * needs the id element to be a present (div) container in the layout
  483. *
  484. * @return string
  485. */
  486. public function browserAlert($id, $message, $options = array()) {
  487. $engine = 'js';
  488. if (!isset($options['escape']) || $options['escape'] !== false) {
  489. $message = h($message);
  490. }
  491. return $this->Html->scriptBlock('
  492. // Returns the version of Internet Explorer or a -1
  493. function getInternetExplorerVersion() {
  494. var rv = -1; // Return value assumes failure.
  495. if (navigator.appName === "Microsoft Internet Explorer") {
  496. var ua = navigator.userAgent;
  497. var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
  498. if (re.exec(ua) != null)
  499. rv = parseFloat( RegExp.$1 );
  500. }
  501. return rv;
  502. }
  503. if ((document.all) && (navigator.appVersion.indexOf("MSIE 7.") != -1) || typeof document.body.style.maxHeight == \'undefined\') {
  504. document.getElementById(\'' . $id . '\').innerHTML = \'' . $message . '\';
  505. }
  506. /*
  507. jQuery(document).ready(function() {
  508. if ($.browser.msie && $.browser.version.substring(0,1) < 8) {
  509. document.getElementById(\'' . $id . '\').innerHTML = \'' . $message . '\';
  510. }
  511. });
  512. */
  513. ');
  514. }
  515. /**
  516. * In noscript tags:
  517. * - link which should not be followed by bots!
  518. * - "pseudo"image which triggers log
  519. *
  520. * @return string
  521. */
  522. public function honeypot($noFollowUrl, $noscriptUrl = array()) {
  523. $res = '<div class="invisible" style="display:none"><noscript>';
  524. $res .= $this->Html->defaultLink('Email', $noFollowUrl, array('rel' => 'nofollow'));
  525. if (!empty($noscriptUrl)) {
  526. $res .= BR . $this->Html->image($this->Html->defaultUrl($noscriptUrl, true)); //$this->Html->link($noscriptUrl);
  527. }
  528. $res .= '</noscript></div>';
  529. return $res;
  530. }
  531. /**
  532. * Print js-visit-stats-link to layout
  533. * uses Piwik open source statistics framework
  534. *
  535. * @return string
  536. */
  537. public function visitStats($viewPath = null) {
  538. $res = '';
  539. if (!defined('HTTP_HOST_LIVESERVER')) {
  540. return '';
  541. }
  542. if (HTTP_HOST == HTTP_HOST_LIVESERVER && (int)Configure::read('Config.tracking') === 1) {
  543. $trackingUrl = Configure::read('Config.tracking_url');
  544. if (empty($trackingUrl)) {
  545. $trackingUrl = 'visit_stats';
  546. }
  547. $error = false;
  548. if (!empty($viewPath) && $viewPath === 'errors') {
  549. $error = true;
  550. }
  551. $res .= '
  552. <script type="text/javascript">
  553. var pkBaseURL = (("https:" == document.location.protocol) ? "https://' . HTTP_HOST . '/' . $trackingUrl . '/" : "http://' . HTTP_HOST . '/' . $trackingUrl . '/");
  554. document.write(unescape("%3Cscript src=\'" + pkBaseURL + "piwik.js\' type=\'text/javascript\'%3E%3C/script%3E"));
  555. </script>
  556. <script type="text/javascript">
  557. try {
  558. var piwikTracker = Piwik.getTracker(pkBaseURL + "piwik.php", 1);
  559. piwikTracker.trackPageView();
  560. piwikTracker.enableLinkTracking();
  561. ' . ($error ? 'piwikTracker.setDocumentTitle(\'404/URL = \'+encodeURIComponent(document.location.pathname+document.location.search) + \'/From = \' + encodeURIComponent(document.referrer));' : '') . '
  562. } catch( err ) {}
  563. </script>
  564. <noscript><p>' . $this->visitStatsImg() . '</p></noscript>
  565. ';
  566. }
  567. return $res;
  568. }
  569. /**
  570. * Non js browsers
  571. *
  572. * @return string
  573. */
  574. public function visitStatsImg($trackingUrl = null) {
  575. if (empty($trackingUrl)) {
  576. $trackingUrl = Configure::read('Config.tracking_url');
  577. }
  578. if (empty($trackingUrl)) {
  579. $trackingUrl = 'visit_stats';
  580. }
  581. return '<img src="' . Router::url('/', true) . $trackingUrl . '/piwik.php?idsite=1" style="border:0" alt=""/>';
  582. }
  583. /*** deprecated ***/
  584. /**
  585. * Checks if a role is in the current users session
  586. *
  587. * @param necessary right(s) as array - or a single one as string possible
  588. * @return array
  589. * @deprecated - use Auth class instead
  590. */
  591. public function roleNames($sessionRoles = null) {
  592. $tmp = array();
  593. if ($sessionRoles === null) {
  594. $sessionRoles = $this->Session->read('Auth.User.Role');
  595. }
  596. $roles = Cache::read('User.Role');
  597. if (empty($roles) || !is_array($roles)) {
  598. $Role = ClassRegistry::init('Role');
  599. $roles = $Role->getActive('list');
  600. Cache::write('User.Role', $roles);
  601. }
  602. if (!empty($sessionRoles)) {
  603. if (is_array($sessionRoles)) {
  604. foreach ($sessionRoles as $sessionRole) {
  605. if (!$sessionRole) {
  606. continue;
  607. }
  608. if (array_key_exists((int)$sessionRole, $roles)) {
  609. $tmp[$sessionRole] = $roles[(int)$sessionRole];
  610. }
  611. }
  612. } else {
  613. if (array_key_exists($sessionRoles, $roles)) {
  614. $tmp[$sessionRoles] = $roles[$sessionRoles];
  615. }
  616. }
  617. }
  618. return $tmp;
  619. }
  620. /**
  621. * Display Roles separated by Commas
  622. *
  623. * @deprecated - use Auth class instead
  624. */
  625. public function displayRoles($sessionRoles = null, $placeHolder = '---') {
  626. $roles = $this->roleNames($sessionRoles);
  627. if (!empty($roles)) {
  628. return implode(', ', $roles);
  629. }
  630. return $placeHolder;
  631. }
  632. /**
  633. * Takes int / array(int) and finds the role name to it
  634. *
  635. * @return array roles
  636. * @deprecated - use Auth class instead
  637. */
  638. public function roleNamesTranslated($value) {
  639. if (empty($value)) {
  640. return array();
  641. }
  642. $ret = array();
  643. $translate = (array)Configure::read('Role');
  644. if (is_array($value)) {
  645. foreach ($value as $k => $v) {
  646. $ret[$v] = __($translate[$v]);
  647. }
  648. } else {
  649. $ret[$value] = __($translate[$value]);
  650. }
  651. return $ret;
  652. }
  653. }