MyHelper.php 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. <?php
  2. App::uses('Helper', 'View');
  3. App::uses('UrlCacheManager', 'Tools.Routing');
  4. /**
  5. * Helper enhancements for Cake2
  6. *
  7. * @author Mark Scherer
  8. * @license MIT
  9. * 2012-02-27 ms
  10. */
  11. class MyHelper extends Helper {
  12. public function __construct($View = null, $settings = array()) {
  13. if (class_exists('Packages')) {
  14. Packages::initialize($this, __CLASS__);
  15. }
  16. parent::__construct($View, $settings);
  17. }
  18. /**
  19. * Sets the defaults for an input tag. Will set the
  20. * name, value, and id attributes for an array of html attributes. Will also
  21. * add a 'form-error' class if the field contains validation errors.
  22. *
  23. * @param string $field The field name to initialize.
  24. * @param array $options Array of options to use while initializing an input field.
  25. * @return array Array options for the form input.
  26. */
  27. protected function _initInputField($field, $options = array()) {
  28. if ($field !== null) {
  29. $this->setEntity($field);
  30. }
  31. $options = (array)$options;
  32. $normalize = true;
  33. if (isset($options['normalize'])) {
  34. $normalize = $options['normalize'];
  35. unset($options['normalize']);
  36. }
  37. $options = $this->_name($options);
  38. $options = $this->value($options);
  39. if (!empty($options['value']) && $normalize) {
  40. $options['value'] = str_replace(array("\t", "\r\n", "\n"), ' ', $options['value']);
  41. }
  42. $options = $this->domId($options);
  43. return $options;
  44. }
  45. /**
  46. * manually
  47. */
  48. public function loadHelpers($helpers = array(), $callbacks = false) {
  49. foreach ((array)$helpers as $helper => $config) {
  50. if (is_int($helper)) {
  51. $helper = $config;
  52. $config = array();
  53. }
  54. list($plugin, $helperName) = pluginSplit($helper);
  55. if (isset($this->{$helperName})) {
  56. continue;
  57. }
  58. App::import('Helper', $helper);
  59. $helperFullName = $helperName.'Helper';
  60. $this->{$helperName} = new $helperFullName($this->_View, (array)$config);
  61. if ($callbacks) {
  62. if (method_exists($helper, 'beforeRender')) {
  63. $this->{$helperName}->beforeRender();
  64. }
  65. }
  66. }
  67. }
  68. //TODO
  69. /**
  70. * problems: what if inside plugin webroot? not easy to do...
  71. */
  72. public function imageIfExists($path, $options = array(), $default = '---') {
  73. if (startsWith($path, '/')) {
  74. /*
  75. $completePath = Router::url($path);
  76. //echo (returns(file_exists($completePath)));
  77. //die($completePath);
  78. # problem with plugin files!!! needs "webroot" added after plugin name
  79. if (!file_exists($completePath)) {
  80. return $default;
  81. }
  82. */
  83. } else {
  84. $completePath = Router::url($path);
  85. }
  86. if (!empty($completePath) && !file_exists($completePath)) {
  87. return $default;
  88. }
  89. return $this->image($path, $options);
  90. }
  91. /**
  92. * display image tag from blob content
  93. * enhancement for HtmlHelper
  94. * @param binary $content
  95. * @param array $options
  96. * @return string $html imageTag
  97. * 2010-11-22 ms
  98. */
  99. public function imageFromBlob($content, $options = array()) {
  100. $text = 'data:image/png;base64,' . base64_encode($content);
  101. $image = sprintf($this->_tags['image'], $text, $this->_parseAttributes($options, null, '', ' '));
  102. return $image;
  103. }
  104. /**
  105. * HTML Helper extension for HTML5 time
  106. * The time element represents either a time on a 24 hour clock,
  107. * or a precise date in the proleptic Gregorian calendar,
  108. * optionally with a time and a time-zone offset.
  109. *
  110. * @param $content string
  111. * @param $options array
  112. * - 'format' STRING: Use the specified TimeHelper method (or format()). FALSE: Generate the datetime. NULL: Do nothing.
  113. * - 'datetime' STRING: If 'format' is STRING use as the formatting string. FALSE: Don't generate attribute
  114. *
  115. * //TODO: fixme
  116. * 2011-07-17 ms
  117. */
  118. public function time($content, $options = array()) {
  119. if (!isset($this->tags['time'])) {
  120. $this->tags['time'] = '<time%s>%s</time>';
  121. }
  122. $options = array_merge(array(
  123. 'datetime' => '%Y-%m-%d %T',
  124. 'pubdate' => false,
  125. 'format' => '%Y-%m-%d %T',
  126. ), $options);
  127. if ($options['format'] !== null) {
  128. App::uses('TimeHelper', 'View/Helper');
  129. $TimeHelper = new TimeHelper($this->_View);
  130. }
  131. if ($options['format']) {
  132. if (method_exists($t, $options['format'])) {
  133. $content = $TimeHelper->$options['format']($content);
  134. } else {
  135. $content = $TimeHelper->i18nFormat($content, $options['format']);
  136. }
  137. $options['datetime'] = $TimeHelper->i18nFormat(strtotime($content), $options['datetime']);
  138. } elseif ($options['format'] === false && $options['datetime']) {
  139. $options['datetime'] = $TimeHelper->i18nFormat(strtotime($content), $options['datetime']);
  140. }
  141. if ($options['pubdate']) {
  142. $pubdate = true;
  143. }
  144. unset($options['format']);
  145. unset($options['pubdate']);
  146. $attributes = $this->_parseAttributes($options, array(0), ' ', '');
  147. if (isset($pubdate)) {
  148. $attributes .= ' pubdate';
  149. }
  150. return sprintf($this->tags['time'], $attributes, $content);
  151. }
  152. # for convienience function Html::defaultLink()
  153. protected $linkDefaults = null;
  154. /*
  155. # only one prefix at a time
  156. public function url($url, $full = false) {
  157. if (is_array($url)) {
  158. $url['lang'] = 'deu';
  159. }
  160. return parent::url($url, $full);
  161. }
  162. */
  163. /**
  164. * convenience function for normal links
  165. * useful for layout links and links inside elements etc
  166. * @params same as Html::link($title, $url, $options, $confirmMessage)
  167. * 2010-01-23 ms
  168. */
  169. public function defaultLink($title, $url=null, $options=array(), $confirmMessage=false) {
  170. if ($this->linkDefaults === null) {
  171. if (!class_exists('CommonComponent')) {
  172. App::import('Component', 'Tools.Common');
  173. }
  174. $this->linkDefaults = CommonComponent::defaultUrlParams();
  175. }
  176. if (!defined('PREFIX_ADMIN')) {
  177. define('PREFIX_ADMIN', 'admin');
  178. }
  179. if ($url !== null && is_array($url)) {
  180. $url = array_merge($this->linkDefaults, $url);
  181. if (!empty($url[PREFIX_ADMIN])) {
  182. $options['rel'] = 'nofollow';
  183. }
  184. } elseif (is_array($title)) {
  185. $title = array_merge($this->linkDefaults, $title);
  186. if (!empty($title[PREFIX_ADMIN])) {
  187. $options['rel'] = 'nofollow';
  188. }
  189. }
  190. //$this->log($url, '404');
  191. return $this->link($title, $url, $options, $confirmMessage);
  192. }
  193. /**
  194. * convenience function for normal urls
  195. * useful for layout urls and urls inside elements etc
  196. * @params same as Html::url($url, $full)
  197. * 2010-01-23 ms
  198. */
  199. public function defaultUrl($url = null, $full = false) {
  200. if ($this->linkDefaults === null) {
  201. if (!class_exists('CommonComponent')) {
  202. App::import('Component', 'Tools.Common');
  203. }
  204. $this->linkDefaults = CommonComponent::defaultUrlParams();
  205. }
  206. if ($url !== null && is_array($url)) {
  207. $url = array_merge($this->linkDefaults, $url);
  208. }
  209. return $this->url($url, $full);
  210. }
  211. public $urlHere = null;
  212. /**
  213. * Small Helper Function to retrieve CORRECT $this->here (as it should be) - CAKE BUG !? -> this is a fix
  214. * 2009-01-06 ms
  215. */
  216. public function here() {
  217. if (empty($this->urlHere) && isset($_GET['url'])) {
  218. $this->urlHere = $_GET['url'];
  219. if (strpos($this->urlHere, '/') !== 0) {
  220. $this->urlHere = '/'.$this->urlHere;
  221. }
  222. }
  223. return $this->urlHere;
  224. }
  225. /**
  226. * enhancement to htmlHelper which allows the crumbs protected array
  227. * to be cleared so that more than one set of crumbs can be generated in the same view.
  228. *
  229. * @return void
  230. * 2009-08-05 ms
  231. */
  232. public function resetCrumbs() {
  233. $this->_crumbs = array();
  234. }
  235. /** deprecated */
  236. /**
  237. * @deprecated
  238. */
  239. public function nl2p($text, $options = array(), $enforceMaxLength = true) {
  240. $pS = $this->Html->tag('p', null, $options);
  241. $pE = '</p>';
  242. if (!empty($text)) {
  243. // Max length auto line break, if enabled
  244. if ($enforceMaxLength) {
  245. $maxLength = null;
  246. if (isset($options['maxLength'])) {
  247. $maxLength = (int)$options['maxLength'];
  248. }
  249. $text = $this->maxLength($text, $maxLength);
  250. }
  251. // Replace double newlines with <p>
  252. $text = $pS . preg_replace('#(\r?\n) {2,}(\s+)?#u', $pE . $pS, $text) . $pE;
  253. // Replace single newlines with <br>
  254. $text = preg_replace('#\r?\n#u', BR, $text);
  255. // Add newlines to sourcecode for sourcode readability
  256. $text = preg_replace(
  257. array(
  258. '#' . $pE . '#u', // Matches $pE (like </p>)
  259. '#' . BR . '#u', // Matches $br (like <br />)
  260. ),
  261. array(
  262. $pE . "\n",
  263. BR . "\n",
  264. ),
  265. $text);
  266. }
  267. return $text;
  268. }
  269. /**
  270. * This function is responsible for setting up the Url cache before the application starts generating urls in views
  271. *
  272. * @return void
  273. */
  274. public function beforeRender($viewFile) {
  275. if (!Configure::read('UrlCache.active') || Configure::read('UrlCache.runtime.beforeRender')) {
  276. return;
  277. }
  278. # todo: maybe lazy load with HtmlHelper::url()?
  279. UrlCacheManager::init($this->_View);
  280. Configure::write('UrlCache.runtime.beforeRender', true);
  281. }
  282. /**
  283. * This method will store the current generated urls into a persistent cache for next use
  284. *
  285. * @return void
  286. */
  287. public function afterLayout($layoutFile = null) {
  288. if (!Configure::read('UrlCache.active') || Configure::read('UrlCache.runtime.afterLayout')) {
  289. return;
  290. }
  291. UrlCacheManager::finalize();
  292. Configure::write('UrlCache.runtime.afterLayout', true);
  293. }
  294. /**
  295. * Intercepts the parent url function to first look if the cache was already generated for the same params
  296. *
  297. * @param mixed $url url to generate using cakephp array syntax
  298. * @param boolean $full wheter to generate a full url or not (http scheme)
  299. * @return string
  300. * @see Helper::url()
  301. */
  302. public function url($url = null, $full = false, $escape = true) {
  303. if (Configure::read('UrlCache.active')) {
  304. if ($cachedUrl = UrlCacheManager::get($url, $full)) {
  305. return $cachedUrl;
  306. }
  307. }
  308. $routerUrl = parent::url($url, $full, $escape);
  309. if (Configure::read('UrlCache.active')) {
  310. UrlCacheManager::set($routerUrl);
  311. }
  312. return $routerUrl;
  313. }
  314. }