CommonHelper.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  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. *
  195. * I18n will be done using default domain.
  196. *
  197. * @param string $singular
  198. * @param string $plural
  199. * @param int $count
  200. * @return string result
  201. */
  202. public function sp($singular, $plural, $count, $autoTranslate = false) {
  203. if ((int)$count !== 1) {
  204. $result = $plural;
  205. } else {
  206. $result = $singular;
  207. }
  208. if ($autoTranslate) {
  209. $result = __($result);
  210. }
  211. return $result;
  212. }
  213. /**
  214. * Convenience method for clean ROBOTS allowance
  215. *
  216. * @param string $type - private/public
  217. * @return string HTML
  218. */
  219. public function metaRobots($type = null) {
  220. if ($type === null && ($meta = Configure::read('Config.robots')) !== null) {
  221. $type = $meta;
  222. }
  223. $content = array();
  224. if ($type === 'public') {
  225. $this->privatePage = false;
  226. $content['robots'] = array('index', 'follow', 'noarchive');
  227. } else {
  228. $this->privatePage = true;
  229. $content['robots'] = array('noindex', 'nofollow', 'noarchive');
  230. }
  231. $return = '<meta name="robots" content="' . implode(',', $content['robots']) . '" />';
  232. return $return;
  233. }
  234. /**
  235. * Convenience method for clean meta name tags
  236. *
  237. * @param string $name: author, date, generator, revisit-after, language
  238. * @param mixed $content: if array, it will be seperated by commas
  239. * @return string HTML Markup
  240. */
  241. public function metaName($name = null, $content = null) {
  242. if (empty($name) || empty($content)) {
  243. return '';
  244. }
  245. $content = (array)$content;
  246. $return = '<meta name="' . $name . '" content="' . implode(', ', $content) . '" />';
  247. return $return;
  248. }
  249. /**
  250. * Convenience method for meta description
  251. *
  252. * @param string $content
  253. * @param string $language (iso2: de, en-us, ...)
  254. * @param array $additionalOptions
  255. * @return string HTML Markup
  256. */
  257. public function metaDescription($content, $language = null, $options = array()) {
  258. if (!empty($language)) {
  259. $options['lang'] = mb_strtolower($language);
  260. } elseif ($language !== false) {
  261. $options['lang'] = Configure::read('Config.locale');
  262. }
  263. return $this->Html->meta('description', $content, $options);
  264. }
  265. /**
  266. * Convenience method to output meta keywords
  267. *
  268. * @param string|array $keywords
  269. * @param string $language (iso2: de, en-us, ...)
  270. * @param bool $escape
  271. * @return string HTML Markup
  272. */
  273. public function metaKeywords($keywords = null, $language = null, $escape = true) {
  274. if ($keywords === null) {
  275. $keywords = Configure::read('Config.keywords');
  276. }
  277. if (is_array($keywords)) {
  278. $keywords = implode(', ', $keywords);
  279. }
  280. if ($escape) {
  281. $keywords = h($keywords);
  282. }
  283. if (!empty($language)) {
  284. $options['lang'] = mb_strtolower($language);
  285. } elseif ($language !== false) {
  286. $options['lang'] = Configure::read('Config.locale');
  287. }
  288. return $this->Html->meta('keywords', $keywords, $options);
  289. }
  290. /**
  291. * Convenience function for "canonical" SEO links
  292. *
  293. * @param mixed $url
  294. * @param bool $full
  295. * @return string HTML Markup
  296. */
  297. public function metaCanonical($url = null, $full = false) {
  298. $canonical = $this->Html->url($url, $full);
  299. $options = array('rel' => 'canonical', 'type' => null, 'title' => null);
  300. return $this->Html->meta('canonical', $canonical, $options);
  301. }
  302. /**
  303. * Convenience method for "alternate" SEO links
  304. *
  305. * @param mixed $url
  306. * @param mixed $lang (lang(iso2) or array of langs)
  307. * lang: language (in ISO 6391-1 format) + optionally the region (in ISO 3166-1 Alpha 2 format)
  308. * - de
  309. * - de-ch
  310. * etc
  311. * @return string HTML Markup
  312. */
  313. public function metaAlternate($url, $lang, $full = false) {
  314. //$canonical = $this->Html->url($url, $full);
  315. $url = $this->Html->url($url, $full);
  316. //return $this->Html->meta('canonical', $canonical, array('rel'=>'canonical', 'type'=>null, 'title'=>null));
  317. $lang = (array)$lang;
  318. $res = array();
  319. foreach ($lang as $language => $countries) {
  320. if (is_numeric($language)) {
  321. $language = '';
  322. } else {
  323. $language .= '-';
  324. }
  325. $countries = (array)$countries;
  326. foreach ($countries as $country) {
  327. $l = $language . $country;
  328. $options = array('rel' => 'alternate', 'hreflang' => $l, 'type' => null, 'title' => null);
  329. $res[] = $this->Html->meta('alternate', $url, $options) . PHP_EOL;
  330. }
  331. }
  332. return implode('', $res);
  333. }
  334. /**
  335. * Convenience method for META Tags
  336. *
  337. * @param mixed $url
  338. * @param string $title
  339. * @return string HTML Markup
  340. */
  341. public function metaRss($url, $title = null) {
  342. $tags = array(
  343. 'meta' => '<link rel="alternate" type="application/rss+xml" title="%s" href="%s" />',
  344. );
  345. if (empty($title)) {
  346. $title = __d('tools', 'Subscribe to this feed');
  347. } else {
  348. $title = h($title);
  349. }
  350. return sprintf($tags['meta'], $title, $this->url($url));
  351. }
  352. /**
  353. * Convenience method for META Tags
  354. *
  355. * @param string $type
  356. * @param string $content
  357. * @return string HTML Markup
  358. */
  359. public function metaEquiv($type, $value, $escape = true) {
  360. $tags = array(
  361. 'meta' => '<meta http-equiv="%s"%s />',
  362. );
  363. if ($value === null) {
  364. return '';
  365. }
  366. if ($escape) {
  367. $value = h($value);
  368. }
  369. return sprintf($tags['meta'], $type, ' content="' . $value . '"');
  370. }
  371. /**
  372. * (example): array(x, Tools|y, Tools.Jquery|jquery/sub/z)
  373. * => x is in webroot/
  374. * => y is in plugins/tools/webroot/
  375. * => z is in plugins/tools/packages/jquery/files/jquery/sub/
  376. *
  377. * @return string HTML Markup
  378. * @deprecated Use AssetCompress plugin instead
  379. */
  380. public function css($files = array(), $options = array()) {
  381. $files = (array)$files;
  382. $pieces = array();
  383. foreach ($files as $file) {
  384. $pieces[] = 'file=' . $file;
  385. }
  386. if ($v = Configure::read('Config.layout_v')) {
  387. $pieces[] = 'v=' . $v;
  388. }
  389. $string = implode('&', $pieces);
  390. return $this->Html->css('/css.php?' . $string, $options);
  391. }
  392. /**
  393. * (example): array(x, Tools|y, Tools.Jquery|jquery/sub/z)
  394. * => x is in webroot/
  395. * => y is in plugins/tools/webroot/
  396. * => z is in plugins/tools/packages/jquery/files/jquery/sub/
  397. *
  398. * @return string HTML Markup
  399. * @deprecated Use AssetCompress plugin instead
  400. */
  401. public function script($files = array(), $options = array()) {
  402. $files = (array)$files;
  403. foreach ($files as $file) {
  404. $pieces[] = 'file=' . $file;
  405. }
  406. if ($v = Configure::read('Config.layout_v')) {
  407. $pieces[] = 'v=' . $v;
  408. }
  409. $string = implode('&', $pieces);
  410. return $this->Html->script('/js.php?' . $string, $options);
  411. }
  412. /**
  413. * Still necessary?
  414. *
  415. * @param array $fields
  416. * @return string HTML
  417. */
  418. public function displayErrors($fields = array()) {
  419. $res = '';
  420. if (!empty($this->validationErrors)) {
  421. if ($fields === null) { # catch ALL
  422. foreach ($this->validationErrors as $alias => $error) {
  423. list($alias, $fieldname) = explode('.', $error);
  424. $this->validationErrors[$alias][$fieldname];
  425. }
  426. } elseif (!empty($fields)) {
  427. foreach ($fields as $field) {
  428. list($alias, $fieldname) = explode('.', $field);
  429. if (!empty($this->validationErrors[$alias][$fieldname])) {
  430. $res .= $this->_renderError($this->validationErrors[$alias][$fieldname]);
  431. }
  432. }
  433. }
  434. }
  435. return $res;
  436. }
  437. protected function _renderError($error, $escape = true) {
  438. if ($escape !== false) {
  439. $error = h($error);
  440. }
  441. return '<div class="error-message">' . $error . '</div>';
  442. }
  443. /**
  444. * Check if session works due to allowed cookies
  445. *
  446. * @param bool Success
  447. */
  448. public function sessionCheck() {
  449. return !CommonComponent::cookiesDisabled();
  450. /*
  451. if (!empty($_COOKIE) && !empty($_COOKIE[Configure::read('Session.cookie')])) {
  452. return true;
  453. }
  454. return false;
  455. */
  456. }
  457. /**
  458. * Display warning if cookies are disallowed (and session won't work)
  459. *
  460. * @return string HTML
  461. */
  462. public function sessionCheckAlert() {
  463. if ($this->sessionCheck()) {
  464. return '';
  465. }
  466. return '<div class="cookieWarning">' . __d('tools', 'Please enable cookies') . '</div>';
  467. }
  468. /**
  469. * Prevents site being opened/included by others/websites inside frames
  470. *
  471. * @return string
  472. */
  473. public function framebuster() {
  474. return $this->Html->scriptBlock('
  475. if (top!=self) top.location.ref=self.location.href;
  476. ');
  477. }
  478. /**
  479. * Currenctly only alerts on IE6/IE7
  480. * options
  481. * - engine (js, jquery)
  482. * - escape
  483. * needs the id element to be a present (div) container in the layout
  484. *
  485. * @return string
  486. */
  487. public function browserAlert($id, $message, $options = array()) {
  488. $engine = 'js';
  489. if (!isset($options['escape']) || $options['escape'] !== false) {
  490. $message = h($message);
  491. }
  492. return $this->Html->scriptBlock('
  493. // Returns the version of Internet Explorer or a -1
  494. function getInternetExplorerVersion() {
  495. var rv = -1; // Return value assumes failure.
  496. if (navigator.appName === "Microsoft Internet Explorer") {
  497. var ua = navigator.userAgent;
  498. var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
  499. if (re.exec(ua) != null)
  500. rv = parseFloat( RegExp.$1 );
  501. }
  502. return rv;
  503. }
  504. if ((document.all) && (navigator.appVersion.indexOf("MSIE 7.") != -1) || typeof document.body.style.maxHeight == \'undefined\') {
  505. document.getElementById(\'' . $id . '\').innerHTML = \'' . $message . '\';
  506. }
  507. /*
  508. jQuery(document).ready(function() {
  509. if ($.browser.msie && $.browser.version.substring(0,1) < 8) {
  510. document.getElementById(\'' . $id . '\').innerHTML = \'' . $message . '\';
  511. }
  512. });
  513. */
  514. ');
  515. }
  516. /**
  517. * In noscript tags:
  518. * - link which should not be followed by bots!
  519. * - "pseudo"image which triggers log
  520. *
  521. * @return string
  522. */
  523. public function honeypot($noFollowUrl, $noscriptUrl = array()) {
  524. $res = '<div class="invisible" style="display:none"><noscript>';
  525. $res .= $this->Html->defaultLink('Email', $noFollowUrl, array('rel' => 'nofollow'));
  526. if (!empty($noscriptUrl)) {
  527. $res .= BR . $this->Html->image($this->Html->defaultUrl($noscriptUrl, true)); //$this->Html->link($noscriptUrl);
  528. }
  529. $res .= '</noscript></div>';
  530. return $res;
  531. }
  532. /**
  533. * Print js-visit-stats-link to layout
  534. * uses Piwik open source statistics framework
  535. *
  536. * @return string
  537. */
  538. public function visitStats($viewPath = null) {
  539. $res = '';
  540. if (!defined('HTTP_HOST_LIVESERVER')) {
  541. return '';
  542. }
  543. if (HTTP_HOST == HTTP_HOST_LIVESERVER && (int)Configure::read('Config.tracking') === 1) {
  544. $trackingUrl = Configure::read('Config.tracking_url');
  545. if (empty($trackingUrl)) {
  546. $trackingUrl = 'visit_stats';
  547. }
  548. $error = false;
  549. if (!empty($viewPath) && $viewPath === 'errors') {
  550. $error = true;
  551. }
  552. $res .= '
  553. <script type="text/javascript">
  554. var pkBaseURL = (("https:" == document.location.protocol) ? "https://' . HTTP_HOST . '/' . $trackingUrl . '/" : "http://' . HTTP_HOST . '/' . $trackingUrl . '/");
  555. document.write(unescape("%3Cscript src=\'" + pkBaseURL + "piwik.js\' type=\'text/javascript\'%3E%3C/script%3E"));
  556. </script>
  557. <script type="text/javascript">
  558. try {
  559. var piwikTracker = Piwik.getTracker(pkBaseURL + "piwik.php", 1);
  560. piwikTracker.trackPageView();
  561. piwikTracker.enableLinkTracking();
  562. ' . ($error ? 'piwikTracker.setDocumentTitle(\'404/URL = \'+encodeURIComponent(document.location.pathname+document.location.search) + \'/From = \' + encodeURIComponent(document.referrer));' : '') . '
  563. } catch( err ) {}
  564. </script>
  565. <noscript><p>' . $this->visitStatsImg() . '</p></noscript>
  566. ';
  567. }
  568. return $res;
  569. }
  570. /**
  571. * Non js browsers
  572. *
  573. * @return string
  574. */
  575. public function visitStatsImg($trackingUrl = null) {
  576. if (empty($trackingUrl)) {
  577. $trackingUrl = Configure::read('Config.tracking_url');
  578. }
  579. if (empty($trackingUrl)) {
  580. $trackingUrl = 'visit_stats';
  581. }
  582. return '<img src="' . Router::url('/', true) . $trackingUrl . '/piwik.php?idsite=1" style="border:0" alt=""/>';
  583. }
  584. /*** deprecated ***/
  585. /**
  586. * Checks if a role is in the current users session
  587. *
  588. * @param necessary right(s) as array - or a single one as string possible
  589. * @return array
  590. * @deprecated - use Auth class instead
  591. */
  592. public function roleNames($sessionRoles = null) {
  593. $tmp = array();
  594. if ($sessionRoles === null) {
  595. $sessionRoles = $this->Session->read('Auth.User.Role');
  596. }
  597. $roles = Cache::read('User.Role');
  598. if (empty($roles) || !is_array($roles)) {
  599. $Role = ClassRegistry::init('Role');
  600. $roles = $Role->getActive('list');
  601. Cache::write('User.Role', $roles);
  602. }
  603. if (!empty($sessionRoles)) {
  604. if (is_array($sessionRoles)) {
  605. foreach ($sessionRoles as $sessionRole) {
  606. if (!$sessionRole) {
  607. continue;
  608. }
  609. if (array_key_exists((int)$sessionRole, $roles)) {
  610. $tmp[$sessionRole] = $roles[(int)$sessionRole];
  611. }
  612. }
  613. } else {
  614. if (array_key_exists($sessionRoles, $roles)) {
  615. $tmp[$sessionRoles] = $roles[$sessionRoles];
  616. }
  617. }
  618. }
  619. return $tmp;
  620. }
  621. /**
  622. * Display Roles separated by Commas
  623. *
  624. * @deprecated - use Auth class instead
  625. */
  626. public function displayRoles($sessionRoles = null, $placeHolder = '---') {
  627. $roles = $this->roleNames($sessionRoles);
  628. if (!empty($roles)) {
  629. return implode(', ', $roles);
  630. }
  631. return $placeHolder;
  632. }
  633. /**
  634. * Takes int / array(int) and finds the role name to it
  635. *
  636. * @return array roles
  637. * @deprecated - use Auth class instead
  638. */
  639. public function roleNamesTranslated($value) {
  640. if (empty($value)) {
  641. return array();
  642. }
  643. $ret = array();
  644. $translate = (array)Configure::read('Role');
  645. if (is_array($value)) {
  646. foreach ($value as $k => $v) {
  647. $ret[$v] = __d('tools', $translate[$v]);
  648. }
  649. } else {
  650. $ret[$value] = __d('tools', $translate[$value]);
  651. }
  652. return $ret;
  653. }
  654. }