CommonHelper.php 18 KB

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