FormatHelper.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  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. $attributes += [
  337. 'data-placement' => 'bottom',
  338. 'data-toggle' => 'tooltip'
  339. ];
  340. $formatOptions = $attributes + [
  341. 'escape' => $options['escape'],
  342. ];
  343. $options['attributes'] = $this->template->formatAttributes($formatOptions);
  344. return $this->template->format('icon', $options);
  345. }
  346. /**
  347. * Displays yes/no symbol.
  348. *
  349. * @param int|bool $value Value
  350. * @param array $options
  351. * - on (defaults to 1/true)
  352. * - onTitle
  353. * - offTitle
  354. * @param array $attributes
  355. * - title, ...
  356. * @return string HTML icon Yes/No
  357. */
  358. public function yesNo($value, array $options = [], array $attributes = []) {
  359. $defaults = [
  360. 'on' => 1,
  361. 'onTitle' => __d('tools', 'Yes'),
  362. 'offTitle' => __d('tools', 'No'),
  363. ];
  364. $options += $defaults;
  365. if ($value == $options['on']) {
  366. $icon = 'yes';
  367. $value = 'on';
  368. } else {
  369. $icon = 'no';
  370. $value = 'off';
  371. }
  372. $attributes += ['title' => $options[$value . 'Title']];
  373. return $this->icon($icon, $options, $attributes);
  374. }
  375. /**
  376. * Gets URL of a png img of a website (16x16 pixel).
  377. *
  378. * @param string $domain
  379. * @return string
  380. */
  381. public function siteIconUrl($domain) {
  382. if (strpos($domain, 'http') === 0) {
  383. // Strip protocol
  384. $pieces = parse_url($domain);
  385. $domain = $pieces['host'];
  386. }
  387. return 'http://www.google.com/s2/favicons?domain=' . $domain;
  388. }
  389. /**
  390. * Display a png img of a website (16x16 pixel)
  391. * if not available, will return a fallback image (a globe)
  392. *
  393. * @param string $domain (preferably without protocol, e.g. "www.site.com")
  394. * @param array $options
  395. * @return string
  396. */
  397. public function siteIcon($domain, array $options = []) {
  398. $url = $this->siteIconUrl($domain);
  399. $options['width'] = 16;
  400. $options['height'] = 16;
  401. if (!isset($options['alt'])) {
  402. $options['alt'] = $domain;
  403. }
  404. if (!isset($options['title'])) {
  405. $options['title'] = $domain;
  406. }
  407. return $this->Html->image($url, $options);
  408. }
  409. /**
  410. * Display a disabled link tag
  411. *
  412. * @param string $text
  413. * @param array $options
  414. * @return string
  415. */
  416. public function disabledLink($text, array $options = []) {
  417. $defaults = ['class' => 'disabledLink', 'title' => __d('tools', 'notAvailable')];
  418. $options += $defaults;
  419. return $this->Html->tag('span', $text, $options);
  420. }
  421. /**
  422. * Generates a pagination count: #1 etc for each pagination record
  423. * respects order (ASC/DESC)
  424. *
  425. * @param array $paginator
  426. * @param int $count (current post count on this page)
  427. * @param string|null $dir (ASC/DESC)
  428. * @return int
  429. * @deprecated
  430. */
  431. public function absolutePaginateCount(array $paginator, $count, $dir = null) {
  432. if ($dir === null) {
  433. $dir = 'ASC';
  434. }
  435. $currentPage = $paginator['page'];
  436. $pageCount = $paginator['pageCount'];
  437. $totalCount = $paginator['count'];
  438. $limit = $paginator['limit'];
  439. $step = isset($paginator['step']) ? $paginator['step'] : 1;
  440. if ($dir === 'DESC') {
  441. $currentCount = $count + ($pageCount - $currentPage) * $limit * $step;
  442. if ($currentPage != $pageCount && $pageCount > 1) {
  443. $currentCount -= $pageCount * $limit * $step - $totalCount;
  444. }
  445. } else {
  446. $currentCount = $count + ($currentPage - 1) * $limit * $step;
  447. }
  448. return $currentCount;
  449. }
  450. /**
  451. * Fixes utf8 problems of native php str_pad function
  452. * //TODO: move to textext helper? Also note there is Text::wrap() now.
  453. *
  454. * @param string $input
  455. * @param int $padLength
  456. * @param string $padString
  457. * @param mixed $padType
  458. * @return string input
  459. */
  460. public function pad($input, $padLength, $padString, $padType = STR_PAD_RIGHT) {
  461. $length = mb_strlen($input);
  462. if ($padLength - $length > 0) {
  463. switch ($padType) {
  464. case STR_PAD_LEFT:
  465. $input = str_repeat($padString, $padLength - $length) . $input;
  466. break;
  467. case STR_PAD_RIGHT:
  468. $input .= str_repeat($padString, $padLength - $length);
  469. break;
  470. }
  471. }
  472. return $input;
  473. }
  474. /**
  475. * Returns red colored if not ok
  476. *
  477. * @param string $value
  478. * @param mixed $ok Boolish value
  479. * @return string Value in HTML tags
  480. */
  481. public function warning($value, $ok = false) {
  482. if (!$ok) {
  483. return $this->ok($value, false);
  484. }
  485. return $value;
  486. }
  487. /**
  488. * Returns green on ok, red otherwise
  489. *
  490. * @todo Remove inline css and make classes better: green=>ok red=>not-ok
  491. * Maybe use templating
  492. *
  493. * @param mixed $content Output
  494. * @param bool $ok Boolish value
  495. * @param array $attributes
  496. * @return string Value nicely formatted/colored
  497. */
  498. public function ok($content, $ok = false, array $attributes = []) {
  499. if ($ok) {
  500. $type = 'yes';
  501. $color = 'green';
  502. } else {
  503. $type = 'no';
  504. $color = 'red';
  505. }
  506. $options = [
  507. 'type' => $type,
  508. 'color' => $color
  509. ];
  510. $options['content'] = $content;
  511. $options['attributes'] = $this->template->formatAttributes($attributes);
  512. return $this->template->format('ok', $options);
  513. }
  514. /**
  515. * Useful for displaying tabbed (code) content when the default of 8 spaces
  516. * inside <pre> is too much. This converts it to spaces for better output.
  517. *
  518. * Inspired by the tab2space function found at:
  519. *
  520. * @see http://aidan.dotgeek.org/lib/?file=function.tab2space.php
  521. * @param string $text
  522. * @param int $spaces
  523. * @return string
  524. */
  525. public function tab2space($text, $spaces = 4) {
  526. $spaces = str_repeat(' ', $spaces);
  527. $text = preg_split("/\r\n|\r|\n/", trim($text));
  528. $wordLengths = [];
  529. $wArray = [];
  530. // Store word lengths
  531. foreach ($text as $line) {
  532. $words = preg_split("/(\t+)/", $line, -1, PREG_SPLIT_DELIM_CAPTURE);
  533. foreach (array_keys($words) as $i) {
  534. $strlen = strlen($words[$i]);
  535. $add = isset($wordLengths[$i]) && ($wordLengths[$i] < $strlen);
  536. if ($add || !isset($wordLengths[$i])) {
  537. $wordLengths[$i] = $strlen;
  538. }
  539. }
  540. $wArray[] = $words;
  541. }
  542. $text = '';
  543. // Apply padding when appropriate and rebuild the string
  544. foreach (array_keys($wArray) as $i) {
  545. foreach (array_keys($wArray[$i]) as $ii) {
  546. if (preg_match("/^\t+$/", $wArray[$i][$ii])) {
  547. $wArray[$i][$ii] = str_pad($wArray[$i][$ii], $wordLengths[$ii], "\t");
  548. } else {
  549. $wArray[$i][$ii] = str_pad($wArray[$i][$ii], $wordLengths[$ii]);
  550. }
  551. }
  552. $text .= str_replace("\t", $spaces, implode('', $wArray[$i])) . "\n";
  553. }
  554. return $text;
  555. }
  556. /**
  557. * Translate a result array into a HTML table
  558. *
  559. * @todo Move to Text Helper etc.
  560. *
  561. * Options:
  562. * - recursive: Recursively generate tables for multi-dimensional arrays
  563. * - heading: Display the first as heading row (th)
  564. * - escape: Defaults to true
  565. * - null: Null value
  566. *
  567. * @author Aidan Lister <aidan@php.net>
  568. * @version 1.3.2
  569. * @link http://aidanlister.com/2004/04/converting-arrays-to-human-readable-tables/
  570. * @param array $array The result (numericaly keyed, associative inner) array.
  571. * @param array $options
  572. * @param array $attributes For the table
  573. * @return string
  574. */
  575. public function array2table(array $array, array $options = [], array $attributes = []) {
  576. $defaults = [
  577. 'null' => '&nbsp;',
  578. 'recursive' => false,
  579. 'heading' => true,
  580. 'escape' => true
  581. ];
  582. $options += $defaults;
  583. // Sanity check
  584. if (empty($array)) {
  585. return '';
  586. }
  587. if (!isset($array[0]) || !is_array($array[0])) {
  588. $array = [$array];
  589. }
  590. $attributes += [
  591. 'class' => 'table'
  592. ];
  593. $attributes = $this->template->formatAttributes($attributes);
  594. // Start the table
  595. $table = "<table$attributes>\n";
  596. if ($options['heading']) {
  597. // The header
  598. $table .= "\t<tr>";
  599. // Take the keys from the first row as the headings
  600. foreach (array_keys($array[0]) as $heading) {
  601. $table .= '<th>' . ($options['escape'] ? h($heading) : $heading) . '</th>';
  602. }
  603. $table .= "</tr>\n";
  604. }
  605. // The body
  606. foreach ($array as $row) {
  607. $table .= "\t<tr>";
  608. foreach ($row as $cell) {
  609. $table .= '<td>';
  610. // Cast objects
  611. if (is_object($cell)) {
  612. $cell = (array)$cell;
  613. }
  614. if ($options['recursive'] && is_array($cell) && !empty($cell)) {
  615. // Recursive mode
  616. $table .= "\n" . static::array2table($cell, $options) . "\n";
  617. } else {
  618. $table .= (!is_array($cell) && strlen($cell) > 0) ? ($options['escape'] ? h(
  619. $cell
  620. ) : $cell) : $options['null'];
  621. }
  622. $table .= '</td>';
  623. }
  624. $table .= "</tr>\n";
  625. }
  626. $table .= '</table>';
  627. return $table;
  628. }
  629. /**
  630. * @param string $string
  631. *
  632. * @return string
  633. * @throws \RuntimeException
  634. */
  635. public function slug($string) {
  636. if ($this->_config['slugger']) {
  637. $callable = $this->_config['slugger'];
  638. if (!is_callable($callable)) {
  639. throw new RuntimeException('Invalid callable passed as slugger.');
  640. }
  641. return $callable($string);
  642. }
  643. return ShimInflector::slug($string);
  644. }
  645. }