CommonHelper.php 18 KB

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