Utils.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. <?php
  2. namespace Grav\Common;
  3. use DateTime;
  4. use DateTimeZone;
  5. use Grav\Common\Helpers\Truncator;
  6. use RocketTheme\Toolbox\Event\Event;
  7. /**
  8. * Misc utilities.
  9. *
  10. * @package Grav\Common
  11. */
  12. abstract class Utils
  13. {
  14. use GravTrait;
  15. /**
  16. * @param string $haystack
  17. * @param string $needle
  18. *
  19. * @return bool
  20. */
  21. public static function startsWith($haystack, $needle)
  22. {
  23. if (is_array($needle)) {
  24. $status = false;
  25. foreach ($needle as $each_needle) {
  26. $status = $status || ($each_needle === '' || strpos($haystack, $each_needle) === 0);
  27. if ($status) {
  28. return $status;
  29. }
  30. }
  31. return $status;
  32. }
  33. return $needle === '' || strpos($haystack, $needle) === 0;
  34. }
  35. /**
  36. * @param string $haystack
  37. * @param string $needle
  38. *
  39. * @return bool
  40. */
  41. public static function endsWith($haystack, $needle)
  42. {
  43. if (is_array($needle)) {
  44. $status = false;
  45. foreach ($needle as $each_needle) {
  46. $status = $status || ($each_needle === '' || substr($haystack, -strlen($each_needle)) === $each_needle);
  47. if ($status) {
  48. return $status;
  49. }
  50. }
  51. return $status;
  52. }
  53. return $needle === '' || substr($haystack, -strlen($needle)) === $needle;
  54. }
  55. /**
  56. * @param string $haystack
  57. * @param string $needle
  58. *
  59. * @return bool
  60. */
  61. public static function contains($haystack, $needle)
  62. {
  63. return $needle === '' || strpos($haystack, $needle) !== false;
  64. }
  65. /**
  66. * Returns the substring of a string up to a specified needle. if not found, return the whole haytack
  67. *
  68. * @param $haystack
  69. * @param $needle
  70. * @return string
  71. */
  72. public static function substrToString($haystack, $needle)
  73. {
  74. if (static::contains($haystack, $needle)) {
  75. return substr($haystack, 0, strpos($haystack,$needle));
  76. }
  77. return $haystack;
  78. }
  79. /**
  80. * Merge two objects into one.
  81. *
  82. * @param object $obj1
  83. * @param object $obj2
  84. *
  85. * @return object
  86. */
  87. public static function mergeObjects($obj1, $obj2)
  88. {
  89. return (object)array_merge((array)$obj1, (array)$obj2);
  90. }
  91. public static function dateFormats()
  92. {
  93. $now = new DateTime();
  94. $date_formats = [
  95. 'd-m-Y H:i' => 'd-m-Y H:i (e.g. '.$now->format('d-m-Y H:i').')',
  96. 'Y-m-d H:i' => 'Y-m-d H:i (e.g. '.$now->format('Y-m-d H:i').')',
  97. 'm/d/Y h:i a' => 'm/d/Y h:i (e.g. '.$now->format('m/d/Y h:i a').')',
  98. 'H:i d-m-Y' => 'H:i d-m-Y (e.g. '.$now->format('H:i d-m-Y').')',
  99. 'h:i a m/d/Y' => 'h:i a m/d/Y (e.g. '.$now->format('h:i a m/d/Y').')',
  100. ];
  101. $default_format = self::getGrav()['config']->get('system.pages.dateformat.default');
  102. if ($default_format) {
  103. $date_formats = array_merge([$default_format => $default_format.' (e.g. '.$now->format($default_format).')'], $date_formats);
  104. }
  105. return $date_formats;
  106. }
  107. /**
  108. * Truncate text by number of characters but can cut off words.
  109. *
  110. * @param string $string
  111. * @param int $limit Max number of characters.
  112. * @param bool $up_to_break truncate up to breakpoint after char count
  113. * @param string $break Break point.
  114. * @param string $pad Appended padding to the end of the string.
  115. * @return string
  116. */
  117. public static function truncate($string, $limit = 150, $up_to_break = false, $break = " ", $pad = "&hellip;")
  118. {
  119. // return with no change if string is shorter than $limit
  120. if (mb_strlen($string) <= $limit) {
  121. return $string;
  122. }
  123. // is $break present between $limit and the end of the string?
  124. if ($up_to_break && false !== ($breakpoint = mb_strpos($string, $break, $limit))) {
  125. if ($breakpoint < mb_strlen($string) - 1) {
  126. $string = mb_substr($string, 0, $breakpoint) . $break;
  127. }
  128. } else {
  129. $string = mb_substr($string, 0, $limit) . $pad;
  130. }
  131. return $string;
  132. }
  133. /**
  134. * Truncate text by number of characters in a "word-safe" manor.
  135. *
  136. * @param $string
  137. * @param int $limit
  138. * @return string
  139. */
  140. public static function safeTruncate($string, $limit = 150)
  141. {
  142. return static::truncate($string, $limit, true);
  143. }
  144. /**
  145. * Truncate HTML by number of characters. not "word-safe"!
  146. *
  147. * @param string $text
  148. * @param int $length
  149. *
  150. * @return string
  151. */
  152. public static function truncateHtml($text, $length = 100)
  153. {
  154. return Truncator::truncate($text, $length, array('length_in_chars' => true));
  155. }
  156. /**
  157. * Truncate HTML by number of characters in a "word-safe" manor.
  158. *
  159. * @param string $text
  160. * @param int $length
  161. *
  162. * @return string
  163. */
  164. public static function safeTruncateHtml($text, $length = 100)
  165. {
  166. return Truncator::truncate($text, $length, array('length_in_chars' => true, 'word_safe' => true));
  167. }
  168. /**
  169. * Generate a random string of a given length
  170. *
  171. * @param int $length
  172. *
  173. * @return string
  174. */
  175. public static function generateRandomString($length = 5)
  176. {
  177. return substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);
  178. }
  179. /**
  180. * Provides the ability to download a file to the browser
  181. *
  182. * @param $file the full path to the file to be downloaded
  183. * @param bool $force_download as opposed to letting browser choose if to download or render
  184. */
  185. public static function download($file, $force_download = true)
  186. {
  187. if (file_exists($file)) {
  188. // fire download event
  189. self::getGrav()->fireEvent('onBeforeDownload', new Event(['file' => $file]));
  190. $file_parts = pathinfo($file);
  191. $filesize = filesize($file);
  192. // check if this function is available, if so use it to stop any timeouts
  193. if (function_exists('set_time_limit')) {
  194. set_time_limit(0);
  195. }
  196. ignore_user_abort(false);
  197. if ($force_download) {
  198. header('Content-Description: File Transfer');
  199. header('Content-Type: application/octet-stream');
  200. header('Content-Disposition: attachment; filename=' . $file_parts['basename']);
  201. header('Content-Transfer-Encoding: binary');
  202. header('Expires: 0');
  203. header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  204. header('Pragma: public');
  205. } else {
  206. header("Content-Type: " . Utils::getMimeType($file_parts['extension']));
  207. }
  208. header('Content-Length: ' . $filesize);
  209. // 8kb chunks for now
  210. $chunk = 8 * 1024;
  211. $fh = fopen($file, "rb");
  212. if ($fh === false) {
  213. return;
  214. }
  215. // Repeat reading until EOF
  216. while (!feof($fh)) {
  217. echo fread($fh, $chunk);
  218. ob_flush(); // flush output
  219. flush();
  220. }
  221. exit;
  222. }
  223. }
  224. /**
  225. * Return the mimetype based on filename
  226. *
  227. * @param $extension Extension of file (eg .txt)
  228. *
  229. * @return string
  230. */
  231. public static function getMimeType($extension)
  232. {
  233. $extension = strtolower($extension);
  234. $config = self::getGrav()['config']->get('media');
  235. if (isset($config[$extension])) {
  236. return $config[$extension]['mime'];
  237. }
  238. return 'application/octet-stream';
  239. }
  240. /**
  241. * Normalize path by processing relative `.` and `..` syntax and merging path
  242. *
  243. * @param $path
  244. *
  245. * @return string
  246. */
  247. public static function normalizePath($path)
  248. {
  249. $root = ($path[0] === '/') ? '/' : '';
  250. $segments = explode('/', trim($path, '/'));
  251. $ret = array();
  252. foreach ($segments as $segment) {
  253. if (($segment == '.') || empty($segment)) {
  254. continue;
  255. }
  256. if ($segment == '..') {
  257. array_pop($ret);
  258. } else {
  259. array_push($ret, $segment);
  260. }
  261. }
  262. return $root . implode('/', $ret);
  263. }
  264. public static function timezones()
  265. {
  266. $timezones = \DateTimeZone::listIdentifiers(\DateTimeZone::ALL);
  267. $offsets = [];
  268. $testDate = new \DateTime;
  269. foreach ($timezones as $zone) {
  270. $tz = new \DateTimeZone($zone);
  271. $offsets[$zone] = $tz->getOffset($testDate);
  272. }
  273. asort($offsets);
  274. $timezone_list = array();
  275. foreach ($offsets as $timezone => $offset) {
  276. $offset_prefix = $offset < 0 ? '-' : '+';
  277. $offset_formatted = gmdate('H:i', abs($offset));
  278. $pretty_offset = "UTC${offset_prefix}${offset_formatted}";
  279. $timezone_list[$timezone] = "(${pretty_offset}) $timezone";
  280. }
  281. return $timezone_list;
  282. }
  283. public static function arrayFilterRecursive(Array $source, $fn)
  284. {
  285. $result = array();
  286. foreach ($source as $key => $value)
  287. {
  288. if (is_array($value))
  289. {
  290. $result[$key] = static::arrayFilterRecursive($value, $fn);
  291. continue;
  292. }
  293. if ($fn($key, $value))
  294. {
  295. $result[$key] = $value; // KEEP
  296. continue;
  297. }
  298. }
  299. return $result;
  300. }
  301. public static function pathPrefixedByLangCode($string)
  302. {
  303. $languages_enabled = self::getGrav()['config']->get('system.languages.supported', []);
  304. if ($string[0] == '/' && $string[3] == '/' && in_array(substr($string, 1, 2), $languages_enabled)) {
  305. return true;
  306. }
  307. return false;
  308. }
  309. public static function date2timestamp($date)
  310. {
  311. $config = self::getGrav()['config'];
  312. $default_dateformat = $config->get('system.pages.dateformat.default');
  313. // try to use DateTime and default format
  314. if ($default_dateformat) {
  315. $datetime = DateTime::createFromFormat($default_dateformat, $date);
  316. } else {
  317. $datetime = new DateTime($date);
  318. }
  319. // fallback to strtotime if DateTime approach failed
  320. if ($datetime !== false) {
  321. return $datetime->getTimestamp();
  322. } else {
  323. return strtotime($date);
  324. }
  325. }
  326. /**
  327. * Checks if a value is positive
  328. *
  329. * @param string $value
  330. *
  331. * @return boolean
  332. */
  333. public static function isPositive($value) {
  334. return in_array($value, [true, 1, '1', 'yes', 'on', 'true'], true);
  335. }
  336. }