CommonHelper.php 18 KB

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