PageRenderTime 69ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/src/Backend/Core/Engine/DataGridFunctions.php

http://github.com/forkcms/forkcms
PHP | 330 lines | 163 code | 47 blank | 120 comment | 22 complexity | e382a862284dc86db091faa2d44bddc8 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, MIT, AGPL-3.0, LGPL-2.1, BSD-3-Clause
  1. <?php
  2. namespace Backend\Core\Engine;
  3. use Backend\Core\Engine\Model as BackendModel;
  4. use Backend\Core\Language\Language as BackendLanguage;
  5. use SpoonDate;
  6. use SpoonFilter;
  7. /**
  8. * A set of commonly used functions that will be applied on rows or columns
  9. */
  10. class DataGridFunctions
  11. {
  12. protected static $dataGridUsers = [];
  13. /**
  14. * Formats plain text as HTML, links will be detected, paragraphs will be inserted
  15. *
  16. * @param string $var The data to cleanup.
  17. *
  18. * @return string
  19. */
  20. public static function cleanupPlainText(string $var): string
  21. {
  22. // detect links
  23. $var = SpoonFilter::replaceURLsWithAnchors($var);
  24. // replace newlines
  25. $var = str_replace("\r", '', $var);
  26. $var = preg_replace('/(?<!.)(\r\n|\r|\n){3,}$/m', '', $var);
  27. // replace br's into p's
  28. $var = '<p>' . str_replace("\n", '</p><p>', $var) . '</p>';
  29. // cleanup
  30. $var = str_replace("\n", '', $var);
  31. $var = str_replace('<p></p>', '', $var);
  32. return $var;
  33. }
  34. /**
  35. * Format a number as a float
  36. *
  37. * @param float $number The number to format.
  38. * @param int $decimals The number of decimals.
  39. *
  40. * @return string
  41. */
  42. public static function formatFloat(float $number, int $decimals = 2): string
  43. {
  44. return number_format($number, $decimals, '.', ' ');
  45. }
  46. /**
  47. * Format a date according the users' settings
  48. *
  49. * @param int $timestamp The UNIX-timestamp to format as a human readable date.
  50. *
  51. * @return string
  52. */
  53. public static function getDate(int $timestamp): string
  54. {
  55. // if invalid timestamp return an empty string
  56. if ($timestamp <= 0) {
  57. return '';
  58. }
  59. // get user setting for long dates
  60. $format = Authentication::getUser()->getSetting('date_format');
  61. // format the date according the user his settings
  62. return SpoonDate::getDate($format, $timestamp, BackendLanguage::getInterfaceLanguage());
  63. }
  64. /**
  65. * Format a date as a long representation according the users' settings
  66. *
  67. * @param int $timestamp The UNIX-timestamp to format as a human readable date.
  68. *
  69. * @return string
  70. */
  71. public static function getLongDate(int $timestamp): string
  72. {
  73. // if invalid timestamp return an empty string
  74. if ($timestamp <= 0) {
  75. return '';
  76. }
  77. // get user setting for long dates
  78. $format = Authentication::getUser()->getSetting('datetime_format');
  79. // format the date according the user his settings
  80. return SpoonDate::getDate($format, $timestamp, BackendLanguage::getInterfaceLanguage());
  81. }
  82. /**
  83. * Format a time according the users' settings
  84. *
  85. * @param int $timestamp The UNIX-timestamp to format as a human readable time.
  86. *
  87. * @return string
  88. */
  89. public static function getTime(int $timestamp): string
  90. {
  91. // if invalid timestamp return an empty string
  92. if ($timestamp <= 0) {
  93. return '';
  94. }
  95. // get user setting for long dates
  96. $format = Authentication::getUser()->getSetting('time_format');
  97. // format the date according the user his settings
  98. return SpoonDate::getDate($format, $timestamp, BackendLanguage::getInterfaceLanguage());
  99. }
  100. /**
  101. * Get time ago as a string for use in a datagrid
  102. *
  103. * @param int $timestamp The UNIX-timestamp to convert in a time-ago-string.
  104. *
  105. * @return string
  106. */
  107. public static function getTimeAgo(int $timestamp): string
  108. {
  109. // get user setting for long dates
  110. $format = Authentication::getUser()->getSetting('datetime_format');
  111. // get the time ago as a string
  112. $timeAgo = SpoonDate::getTimeAgo($timestamp, BackendLanguage::getInterfaceLanguage(), $format);
  113. return '<time tabindex="0" data-toggle="tooltip" datetime="'
  114. . SpoonDate::getDate('Y-m-d H:i:s', $timestamp)
  115. . '" title="' . SpoonDate::getDate($format, $timestamp, BackendLanguage::getInterfaceLanguage())
  116. . '">' . $timeAgo . '</time>';
  117. }
  118. /**
  119. * Get the HTML for a user to use in a datagrid
  120. *
  121. * @param int $id The Id of the user.
  122. *
  123. * @return string
  124. */
  125. public static function getUser(int $id): string
  126. {
  127. // nothing in cache
  128. if (!isset(self::$dataGridUsers[$id])) {
  129. // create user instance
  130. $user = new User($id);
  131. // get settings
  132. $avatar = $user->getSetting('avatar', 'no-avatar.gif');
  133. $nickname = $user->getSetting('nickname');
  134. $allowed = Authentication::isAllowedAction('Edit', 'Users');
  135. // build html
  136. $html = '<div class="fork-data-grid-avatar">' . "\n";
  137. if ($allowed) {
  138. $html .= ' <a href="' .
  139. BackendModel::createUrlForAction(
  140. 'Edit',
  141. 'Users'
  142. ) . '&amp;id=' . $id . '">' . "\n";
  143. }
  144. $html .= ' <img class="img-circle" src="' . FRONTEND_FILES_URL . '/Users/avatars/32x32/' .
  145. $avatar . '" width="24" height="24" alt="' . $nickname . '" />' . "\n";
  146. $html .= '<span>' . $nickname . '</span>';
  147. if ($allowed) {
  148. $html .= '</a>' . "\n";
  149. }
  150. $html .= ' </div>';
  151. self::$dataGridUsers[$id] = $html;
  152. }
  153. return self::$dataGridUsers[$id];
  154. }
  155. /**
  156. * This will grey out certain rows from common columns. These columns are:
  157. *
  158. * 'visible', 'hidden', 'active', 'published'
  159. *
  160. * @param string $type The type of column. This is given since some columns can have different meanings than others.
  161. * @param string|bool $value
  162. * @param array $attributes
  163. *
  164. * @return array
  165. */
  166. public static function greyOut(string $type, $value, array $attributes = []): array
  167. {
  168. $grayedOutClass = 'fork-data-grid-grayed-out grayedOut';
  169. $greyOut = false;
  170. switch ($type) {
  171. case 'visible':
  172. case 'active':
  173. case 'published':
  174. if (!$value) {
  175. $greyOut = true;
  176. }
  177. break;
  178. case 'status':
  179. if ($value === 'hidden') {
  180. $greyOut = true;
  181. }
  182. break;
  183. case 'hidden':
  184. if ($value) {
  185. $greyOut = true;
  186. }
  187. break;
  188. }
  189. // add the grayedOut class to any existing attributes
  190. if ($greyOut) {
  191. if (array_key_exists('class', $attributes)) {
  192. $attributes['class'] .= ' ' . $grayedOutClass;
  193. } else {
  194. $attributes['class'] = $grayedOutClass;
  195. }
  196. }
  197. return $attributes;
  198. }
  199. /**
  200. * Returns an image tag
  201. *
  202. * @param string $path The path to the image.
  203. * @param string $image The filename of the image.
  204. * @param string $title The title (will be used as alt).
  205. * @param string $url The url
  206. * @param int $width The width for the <img element
  207. * @param int $height The height for the <img element
  208. * @param string $filter The LiipImagineBundle filter
  209. *
  210. * @return string
  211. */
  212. public static function showImage(
  213. string $path,
  214. string $image,
  215. string $title = '',
  216. string $url = null,
  217. int $width = null,
  218. int $height = null,
  219. string $filter = null
  220. ): string {
  221. if ($width === 0 || $height === 0) {
  222. throw new \Exception('An image must not have a width or height equal to 0, because the image will not be visible.');
  223. }
  224. $imagePath = $path . '/' . $image;
  225. if ($filter !== null) {
  226. $imagePath = BackendModel::get('liip_imagine.cache.manager.public')->getBrowserPath($imagePath, $filter);
  227. }
  228. $html = '<img src="' . $imagePath . '" alt="' . $title . '"';
  229. if ($width !== null) {
  230. $html .= ' width="' . $width . '"';
  231. }
  232. if ($height !== null) {
  233. $html .= ' height="' . $height . '"';
  234. }
  235. $html .= ' />';
  236. if ($url !== null) {
  237. $html = '<a href="' . $url . '" title="' . $title . '">' . $html . '</a>';
  238. }
  239. return $html;
  240. }
  241. /**
  242. * Truncate a string
  243. *
  244. * @param string $string The string to truncate.
  245. * @param int $length The maximum length for the string.
  246. * @param bool $useHellip Should a hellip be appended?
  247. *
  248. * @return string
  249. */
  250. public static function truncate(string $string, int $length, bool $useHellip = true): string
  251. {
  252. // remove special chars
  253. $string = htmlspecialchars_decode($string);
  254. // less characters
  255. if (mb_strlen($string) <= $length) {
  256. return SpoonFilter::htmlspecialchars($string);
  257. }
  258. // more characters
  259. // hellip is seen as 1 char, so remove it from length
  260. if ($useHellip) {
  261. --$length;
  262. }
  263. // get the amount of requested characters
  264. $string = mb_substr($string, 0, $length);
  265. // add hellip
  266. if ($useHellip) {
  267. $string .= '…';
  268. }
  269. return SpoonFilter::htmlspecialchars($string);
  270. }
  271. /**
  272. * This is an alias for the template modifier since it can also be used here and people didn't find it.
  273. *
  274. * @param string|bool $status
  275. * @param bool $reverse show the opposite of the status
  276. *
  277. * @return string
  278. */
  279. public static function showBool($status, bool $reverse = false): string
  280. {
  281. return TemplateModifiers::showBool($status, $reverse);
  282. }
  283. }