FormatHelper.php 18 KB

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