FormatHelper.php 18 KB

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