FormatHelper.php 16 KB

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