CommonHelper.php 18 KB

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