FormatHelper.php 16 KB

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