FormatHelper.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  1. <?php
  2. namespace Tools\View\Helper;
  3. use Cake\Core\Configure;
  4. use Cake\Utility\Inflector;
  5. use Cake\View\Helper;
  6. use Cake\View\StringTemplate;
  7. use Cake\View\View;
  8. /**
  9. * Format helper with basic html snippets
  10. *
  11. * TODO: make snippets more "css and background image" (instead of inline img links)
  12. *
  13. * @author Mark Scherer
  14. * @license MIT
  15. * @property \Cake\View\Helper\HtmlHelper $Html
  16. */
  17. class FormatHelper extends Helper {
  18. /**
  19. * Other helpers used by FormHelper
  20. *
  21. * @var array
  22. */
  23. public $helpers = ['Html'];
  24. /**
  25. * @var \Cake\View\StringTemplate
  26. */
  27. public $template;
  28. /**
  29. * @var array
  30. */
  31. protected $_defaultIcons = [
  32. 'yes' => 'fa fa-check',
  33. 'no' => 'fa fa-times',
  34. 'view' => 'fa fa-eye',
  35. 'edit' => 'fa fa-pencil',
  36. 'add' => 'fa fa-plus',
  37. 'delete' => 'fa fa-trash',
  38. 'prev' => 'fa fa-prev',
  39. 'next' => 'fa fa-next',
  40. 'pro' => 'fa fa-thumbs-up',
  41. 'contra' => 'fa fa-thumbs-down',
  42. 'male' => 'fa fa-mars',
  43. 'female' => 'fa fa-venus',
  44. 'config' => 'fa fa-cogs'
  45. //'genderless' => 'fa fa-genderless'
  46. ];
  47. /**
  48. * @var array
  49. */
  50. protected $_defaults = [
  51. 'fontIcons' => null,
  52. 'iconNamespace' => 'fa', // Used to be icon,
  53. 'autoPrefix' => true, // For custom icons "prev" becomes "fa-prev" when iconNamespace is "fa"
  54. 'templates' => [
  55. 'icon' => '<i class="{{class}}"{{attributes}}></i>',
  56. 'ok' => '<span class="ok-{{type}}" style="color:{{color}}"{{attributes}}>{{content}}</span>'
  57. ]
  58. ];
  59. /**
  60. * FormatHelper constructor.
  61. *
  62. * @param \Cake\View\View $View
  63. * @param array $config
  64. */
  65. public function __construct(View $View, array $config = []) {
  66. $defaults = (array)Configure::read('Format') + $this->_defaults;
  67. $config += $defaults;
  68. $config['fontIcons'] = (array)$config['fontIcons'] + $this->_defaultIcons;
  69. $this->template = new StringTemplate($config['templates']);
  70. parent::__construct($View, $config);
  71. }
  72. /**
  73. * jqueryAccess: {id}Pro, {id}Contra
  74. *
  75. * @param mixed $value Boolish value
  76. * @param array $options
  77. * @param array $attributes
  78. * @return string
  79. */
  80. public function thumbs($value, array $options = [], array $attributes = []) {
  81. $icon = !empty($value) ? 'pro' : 'contra';
  82. return $this->icon($icon, $options, $attributes);
  83. }
  84. /**
  85. * Display neighbor quicklinks
  86. *
  87. * @param array $neighbors (containing prev and next)
  88. * @param string $field : just field or Model.field syntax
  89. * @param array $options :
  90. * - name: title name: next{Record} (if none is provided, "record" is used - not translated!)
  91. * - slug: true/false (defaults to false)
  92. * - titleField: field or Model.field
  93. * @return string
  94. */
  95. public function neighbors(array $neighbors, $field, array $options = []) {
  96. $alias = null;
  97. if (mb_strpos($field, '.') !== false) {
  98. $fieldArray = explode('.', $field, 2);
  99. $alias = $fieldArray[0];
  100. $field = $fieldArray[1];
  101. }
  102. if (empty($alias)) {
  103. if (!empty($neighbors['prev'])) {
  104. $modelNames = array_keys($neighbors['prev']);
  105. $alias = $modelNames[0];
  106. } elseif (!empty($neighbors['next'])) {
  107. $modelNames = array_keys($neighbors['next']);
  108. $alias = $modelNames[0];
  109. }
  110. }
  111. if (empty($field)) {
  112. }
  113. $name = 'Record'; // Translation further down!
  114. if (!empty($options['name'])) {
  115. $name = ucfirst($options['name']);
  116. }
  117. $prevSlug = $nextSlug = null;
  118. if (!empty($options['slug'])) {
  119. if (!empty($neighbors['prev'])) {
  120. $prevSlug = Inflector::slug($neighbors['prev'][$alias][$field], '-');
  121. }
  122. if (!empty($neighbors['next'])) {
  123. $nextSlug = Inflector::slug($neighbors['next'][$alias][$field], '-');
  124. }
  125. }
  126. $titleAlias = $alias;
  127. $titleField = $field;
  128. if (!empty($options['titleField'])) {
  129. if (mb_strpos($options['titleField'], '.') !== false) {
  130. $fieldArray = explode('.', $options['titleField'], 2);
  131. $titleAlias = $fieldArray[0];
  132. $titleField = $fieldArray[1];
  133. } else {
  134. $titleField = $options['titleField'];
  135. }
  136. }
  137. if (!isset($options['escape']) || $options['escape'] === false) {
  138. $titleField = h($titleField);
  139. }
  140. $ret = '<div class="next-prev-navi nextPrevNavi">';
  141. if (!empty($neighbors['prev'])) {
  142. $url = [$neighbors['prev'][$alias]['id'], $prevSlug];
  143. if (!empty($options['url'])) {
  144. $url += $options['url'];
  145. }
  146. // ICON_PREV, false
  147. $ret .= $this->Html->link(
  148. $this->icon('prev') . '&nbsp;' . __d('tools', 'prev' . $name),
  149. $url,
  150. ['escape' => false, 'title' => $neighbors['prev'][$titleAlias][$titleField]]
  151. );
  152. } else {
  153. //ICON_PREV_DISABLED, __d('tools', 'noPrev' . $name)) . '&nbsp;' . __d('tools', 'prev' . $name
  154. $ret .= $this->icon('prev');
  155. }
  156. $ret .= '&nbsp;&nbsp;';
  157. if (!empty($neighbors['next'])) {
  158. $url = [$neighbors['next'][$alias]['id'], $prevSlug];
  159. if (!empty($options['url'])) {
  160. $url += $options['url'];
  161. }
  162. // ICON_NEXT, false
  163. $ret .= $this->Html->link(
  164. $this->icon('next') . '&nbsp;' . __d('tools', 'next' . $name),
  165. $url,
  166. ['escape' => false, 'title' => $neighbors['next'][$titleAlias][$titleField]]
  167. );
  168. } else {
  169. // ICON_NEXT_DISABLED, __d('tools', 'noNext' . $name)
  170. $ret .= $this->icon('next') . '&nbsp;' . __d('tools', 'next' . $name);
  171. }
  172. $ret .= '</div>';
  173. return $ret;
  174. }
  175. const GENDER_FEMALE = 2;
  176. const GENDER_MALE = 1;
  177. /**
  178. * Displays gender icon
  179. *
  180. * @param mixed $value
  181. * @return string
  182. */
  183. public function genderIcon($value) {
  184. $value = (int)$value;
  185. if ($value == static::GENDER_FEMALE) {
  186. $icon = $this->icon('female');
  187. } elseif ($value == static::GENDER_MALE) {
  188. $icon = $this->icon('male');
  189. } else {
  190. $icon = $this->icon('genderless', [], ['title' => 'Unknown']);
  191. }
  192. return $icon;
  193. }
  194. /**
  195. * Display a font icon (fast and resource-efficient).
  196. * Uses http://fontawesome.io/icons/
  197. *
  198. * Options:
  199. * - size (int|string: 1...5 or large)
  200. * - rotate (integer: 90, 270, ...)
  201. * - spin (booelan: true/false)
  202. * - extra (array: muted, light, dark, border)
  203. * - pull (string: left, right)
  204. *
  205. * @param string|array $icon
  206. * @param array $options
  207. * @param array $attributes
  208. * @return string
  209. */
  210. public function fontIcon($icon, array $options = [], array $attributes = []) {
  211. $defaults = [
  212. 'namespace' => $this->_config['iconNamespace']
  213. ];
  214. $options += $defaults;
  215. $icon = (array)$icon;
  216. $class = [$options['namespace']];
  217. foreach ($icon as $i) {
  218. $class[] = $options['namespace'] . '-' . $i;
  219. }
  220. if (!empty($options['extra'])) {
  221. foreach ($options['extra'] as $i) {
  222. $class[] = $options['namespace'] . '-' . $i;
  223. }
  224. }
  225. if (!empty($options['size'])) {
  226. $class[] = $options['namespace'] . '-' . ($options['size'] === 'large' ? 'large' : $options['size'] . 'x');
  227. }
  228. if (!empty($options['pull'])) {
  229. $class[] = 'pull-' . $options['pull'];
  230. }
  231. if (!empty($options['rotate'])) {
  232. $class[] = $options['namespace'] . '-rotate-' . (int)$options['rotate'];
  233. }
  234. if (!empty($options['spin'])) {
  235. $class[] = $options['namespace'] . '-spin';
  236. }
  237. return '<i class="' . implode(' ', $class) . '"></i>';
  238. }
  239. /**
  240. * Icons using the default namespace
  241. *
  242. * @param string $icon (constant or filename)
  243. * @param array $options :
  244. * - translate, title, ...
  245. * @param array $attributes :
  246. * - class, ...
  247. * @return string
  248. */
  249. public function icon($icon, array $options = [], array $attributes = []) {
  250. $defaults = [
  251. 'translate' => true,
  252. ];
  253. $options += $defaults;
  254. if (!isset($attributes['title'])) {
  255. if (isset($options['title'])) {
  256. $attributes['title'] = $options['title'];
  257. } else {
  258. $attributes['title'] = Inflector::humanize($icon);
  259. }
  260. }
  261. return $this->_fontIcon($icon, $options, $attributes);
  262. }
  263. /**
  264. * Img Icons
  265. *
  266. * @param string $icon (constant or filename)
  267. * @param array $options :
  268. * - translate, title, ...
  269. * @param array $attributes :
  270. * - class, ...
  271. * @return string
  272. */
  273. public function cIcon($icon, array $options = [], array $attributes = []) {
  274. return $this->_customIcon($icon, $options, $attributes);
  275. }
  276. /**
  277. * Deprecated img icons, font icons should be used instead, but sometimes
  278. * we still need a custom img icon.
  279. *
  280. * @param string $icon (constant or filename)
  281. * @param array $options :
  282. * - translate, title, ...
  283. * @param array $attributes :
  284. * - class, ...
  285. * @return string
  286. */
  287. protected function _customIcon($icon, array $options = [], array $attributes = []) {
  288. $translate = isset($options['translate']) ? $options['translate'] : true;
  289. $type = pathinfo($icon, PATHINFO_FILENAME);
  290. $title = isset($t) ? $t : ucfirst($type);
  291. $alt = (isset($a) ? $a : Inflector::slug($title));
  292. if ($translate !== false) {
  293. $title = __($title);
  294. $alt = __($alt);
  295. }
  296. $alt = '[' . $alt . ']';
  297. $defaults = ['title' => $title, 'alt' => $alt, 'class' => 'icon'];
  298. $options = $attributes + $options;
  299. $options += $defaults;
  300. if (substr($icon, 0, 1) !== '/') {
  301. $icon = 'icons/' . $icon;
  302. }
  303. return $this->Html->image($icon, $options);
  304. }
  305. /**
  306. * Renders a font icon.
  307. *
  308. * @param string $type
  309. * @param array $options
  310. * @param array $attributes
  311. * @return string
  312. */
  313. protected function _fontIcon($type, $options, $attributes) {
  314. $iconClass = $type;
  315. if ($this->_config['autoPrefix'] && $this->_config['iconNamespace']) {
  316. $iconClass = $this->_config['iconNamespace'] . '-' . $iconClass;
  317. }
  318. if ($this->_config['iconNamespace']) {
  319. $iconClass = $this->_config['iconNamespace'] . ' ' . $iconClass;
  320. }
  321. if (isset($this->_config['fontIcons'][$type])) {
  322. $iconClass = $this->_config['fontIcons'][$type];
  323. }
  324. $defaults = [
  325. 'class' => 'icon icon-' . $type . ' ' . $iconClass
  326. ];
  327. $options += $defaults;
  328. if (!isset($attributes['title'])) {
  329. $attributes['title'] = ucfirst($type);
  330. if (!isset($options['translate']) || $options['translate'] !== false) {
  331. $attributes['title'] = __($attributes['title']);
  332. }
  333. }
  334. $attributes += [
  335. 'data-placement' => 'bottom',
  336. 'data-toggle' => 'tooltip'
  337. ];
  338. $options['attributes'] = $this->template->formatAttributes($attributes);
  339. return $this->template->format('icon', $options);
  340. }
  341. /**
  342. * Displays yes/no symbol.
  343. *
  344. * @param int|bool $value Value
  345. * @param array $options
  346. * - on (defaults to 1/true)
  347. * - onTitle
  348. * - offTitle
  349. * @param array $attributes
  350. * - title, ...
  351. * @return string HTML icon Yes/No
  352. */
  353. public function yesNo($value, array $options = [], array $attributes = []) {
  354. $defaults = [
  355. 'on' => 1,
  356. 'onTitle' => __d('tools', 'Yes'),
  357. 'offTitle' => __d('tools', 'No'),
  358. ];
  359. $options += $defaults;
  360. if ($value == $options['on']) {
  361. $icon = 'yes';
  362. $value = 'on';
  363. } else {
  364. $icon = 'no';
  365. $value = 'off';
  366. }
  367. $attributes += ['title' => $options[$value . 'Title']];
  368. return $this->icon($icon, $options, $attributes);
  369. }
  370. /**
  371. * Gets URL of a png img of a website (16x16 pixel).
  372. *
  373. * @param string $domain
  374. * @return string
  375. */
  376. public function siteIconUrl($domain) {
  377. if (strpos($domain, 'http') === 0) {
  378. // Strip protocol
  379. $pieces = parse_url($domain);
  380. $domain = $pieces['host'];
  381. }
  382. return 'http://www.google.com/s2/favicons?domain=' . $domain;
  383. }
  384. /**
  385. * Display a png img of a website (16x16 pixel)
  386. * if not available, will return a fallback image (a globe)
  387. *
  388. * @param string $domain (preferably without protocol, e.g. "www.site.com")
  389. * @param array $options
  390. * @return string
  391. */
  392. public function siteIcon($domain, array $options = []) {
  393. $url = $this->siteIconUrl($domain);
  394. $options['width'] = 16;
  395. $options['height'] = 16;
  396. if (!isset($options['alt'])) {
  397. $options['alt'] = $domain;
  398. }
  399. if (!isset($options['title'])) {
  400. $options['title'] = $domain;
  401. }
  402. return $this->Html->image($url, $options);
  403. }
  404. /**
  405. * Display a disabled link tag
  406. *
  407. * @param string $text
  408. * @param array $options
  409. * @return string
  410. */
  411. public function disabledLink($text, array $options = []) {
  412. $defaults = ['class' => 'disabledLink', 'title' => __d('tools', 'notAvailable')];
  413. $options += $defaults;
  414. return $this->Html->tag('span', $text, $options);
  415. }
  416. /**
  417. * Generates a pagination count: #1 etc for each pagination record
  418. * respects order (ASC/DESC)
  419. *
  420. * @param array $paginator
  421. * @param int $count (current post count on this page)
  422. * @param string|null $dir (ASC/DESC)
  423. * @return int
  424. * @deprecated
  425. */
  426. public function absolutePaginateCount(array $paginator, $count, $dir = null) {
  427. if ($dir === null) {
  428. $dir = 'ASC';
  429. }
  430. $currentPage = $paginator['page'];
  431. $pageCount = $paginator['pageCount'];
  432. $totalCount = $paginator['count'];
  433. $limit = $paginator['limit'];
  434. $step = isset($paginator['step']) ? $paginator['step'] : 1;
  435. if ($dir === 'DESC') {
  436. $currentCount = $count + ($pageCount - $currentPage) * $limit * $step;
  437. if ($currentPage != $pageCount && $pageCount > 1) {
  438. $currentCount -= $pageCount * $limit * $step - $totalCount;
  439. }
  440. } else {
  441. $currentCount = $count + ($currentPage - 1) * $limit * $step;
  442. }
  443. return $currentCount;
  444. }
  445. /**
  446. * Fixes utf8 problems of native php str_pad function
  447. * //TODO: move to textext helper? Also note there is Text::wrap() now.
  448. *
  449. * @param string $input
  450. * @param int $padLength
  451. * @param string $padString
  452. * @param mixed $padType
  453. * @return string input
  454. */
  455. public function pad($input, $padLength, $padString, $padType = STR_PAD_RIGHT) {
  456. $length = mb_strlen($input);
  457. if ($padLength - $length > 0) {
  458. switch ($padType) {
  459. case STR_PAD_LEFT:
  460. $input = str_repeat($padString, $padLength - $length) . $input;
  461. break;
  462. case STR_PAD_RIGHT:
  463. $input .= str_repeat($padString, $padLength - $length);
  464. break;
  465. }
  466. }
  467. return $input;
  468. }
  469. /**
  470. * Returns red colored if not ok
  471. *
  472. * @param string $value
  473. * @param mixed $ok Boolish value
  474. * @return string Value in HTML tags
  475. */
  476. public function warning($value, $ok = false) {
  477. if (!$ok) {
  478. return $this->ok($value, false);
  479. }
  480. return $value;
  481. }
  482. /**
  483. * Returns green on ok, red otherwise
  484. *
  485. * @todo Remove inline css and make classes better: green=>ok red=>not-ok
  486. * Maybe use templating
  487. *
  488. * @param mixed $content Output
  489. * @param bool $ok Boolish value
  490. * @param array $attributes
  491. * @return string Value nicely formatted/colored
  492. */
  493. public function ok($content, $ok = false, array $attributes = []) {
  494. if ($ok) {
  495. $type = 'yes';
  496. $color = 'green';
  497. } else {
  498. $type = 'no';
  499. $color = 'red';
  500. }
  501. $options = [
  502. 'type' => $type,
  503. 'color' => $color
  504. ];
  505. $options['content'] = $content;
  506. $options['attributes'] = $this->template->formatAttributes($attributes);
  507. return $this->template->format('ok', $options);
  508. }
  509. /**
  510. * Useful for displaying tabbed (code) content when the default of 8 spaces
  511. * inside <pre> is too much. This converts it to spaces for better output.
  512. *
  513. * Inspired by the tab2space function found at:
  514. *
  515. * @see http://aidan.dotgeek.org/lib/?file=function.tab2space.php
  516. * @param string $text
  517. * @param int $spaces
  518. * @return string
  519. */
  520. public function tab2space($text, $spaces = 4) {
  521. $spaces = str_repeat(' ', $spaces);
  522. $text = preg_split("/\r\n|\r|\n/", trim($text));
  523. $wordLengths = [];
  524. $wArray = [];
  525. // Store word lengths
  526. foreach ($text as $line) {
  527. $words = preg_split("/(\t+)/", $line, -1, PREG_SPLIT_DELIM_CAPTURE);
  528. foreach (array_keys($words) as $i) {
  529. $strlen = strlen($words[$i]);
  530. $add = isset($wordLengths[$i]) && ($wordLengths[$i] < $strlen);
  531. if ($add || !isset($wordLengths[$i])) {
  532. $wordLengths[$i] = $strlen;
  533. }
  534. }
  535. $wArray[] = $words;
  536. }
  537. $text = '';
  538. // Apply padding when appropriate and rebuild the string
  539. foreach (array_keys($wArray) as $i) {
  540. foreach (array_keys($wArray[$i]) as $ii) {
  541. if (preg_match("/^\t+$/", $wArray[$i][$ii])) {
  542. $wArray[$i][$ii] = str_pad($wArray[$i][$ii], $wordLengths[$ii], "\t");
  543. } else {
  544. $wArray[$i][$ii] = str_pad($wArray[$i][$ii], $wordLengths[$ii]);
  545. }
  546. }
  547. $text .= str_replace("\t", $spaces, implode('', $wArray[$i])) . "\n";
  548. }
  549. return $text;
  550. }
  551. /**
  552. * Translate a result array into a HTML table
  553. *
  554. * @todo Move to Text Helper etc.
  555. *
  556. * Options:
  557. * - recursive: Recursively generate tables for multi-dimensional arrays
  558. * - heading: Display the first as heading row (th)
  559. * - escape: Defaults to true
  560. * - null: Null value
  561. *
  562. * @author Aidan Lister <aidan@php.net>
  563. * @version 1.3.2
  564. * @link http://aidanlister.com/2004/04/converting-arrays-to-human-readable-tables/
  565. * @param array $array The result (numericaly keyed, associative inner) array.
  566. * @param array $options
  567. * @param array $attributes For the table
  568. * @return string
  569. */
  570. public function array2table(array $array, array $options = [], array $attributes = []) {
  571. $defaults = [
  572. 'null' => '&nbsp;',
  573. 'recursive' => false,
  574. 'heading' => true,
  575. 'escape' => true
  576. ];
  577. $options += $defaults;
  578. // Sanity check
  579. if (empty($array)) {
  580. return '';
  581. }
  582. if (!isset($array[0]) || !is_array($array[0])) {
  583. $array = [$array];
  584. }
  585. $attributes += [
  586. 'class' => 'table'
  587. ];
  588. $attributes = $this->template->formatAttributes($attributes);
  589. // Start the table
  590. $table = "<table$attributes>\n";
  591. if ($options['heading']) {
  592. // The header
  593. $table .= "\t<tr>";
  594. // Take the keys from the first row as the headings
  595. foreach (array_keys($array[0]) as $heading) {
  596. $table .= '<th>' . ($options['escape'] ? h($heading) : $heading) . '</th>';
  597. }
  598. $table .= "</tr>\n";
  599. }
  600. // The body
  601. foreach ($array as $row) {
  602. $table .= "\t<tr>";
  603. foreach ($row as $cell) {
  604. $table .= '<td>';
  605. // Cast objects
  606. if (is_object($cell)) {
  607. $cell = (array)$cell;
  608. }
  609. if ($options['recursive'] && is_array($cell) && !empty($cell)) {
  610. // Recursive mode
  611. $table .= "\n" . static::array2table($cell, $options) . "\n";
  612. } else {
  613. $table .= (!is_array($cell) && strlen($cell) > 0) ? ($options['escape'] ? h(
  614. $cell
  615. ) : $cell) : $options['null'];
  616. }
  617. $table .= '</td>';
  618. }
  619. $table .= "</tr>\n";
  620. }
  621. $table .= '</table>';
  622. return $table;
  623. }
  624. }