-
Notifications
You must be signed in to change notification settings - Fork 4
/
randomfile.php
81 lines (64 loc) · 2.29 KB
/
randomfile.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php
use Sunlight\Extend;
use Sunlight\Hcm;
use Sunlight\Image\ImageFormat;
use Sunlight\Image\ImageService;
use Sunlight\Image\ImageTransformer;
use Sunlight\Router;
return function ($dir = '', $type = 'text', $limit = 1, $thumbnail_size = '') {
Hcm::normalizePathArgument($dir, false);
Hcm::normalizeArgument($type, 'string');
Hcm::normalizeArgument($limit, 'int');
Hcm::normalizeArgument($thumbnail_size, 'string');
if ($dir === null) {
return '';
}
$result = '';
$handle = opendir($dir);
switch ($type) {
case 'image':
$extension_filter = function ($ext) { return ImageFormat::isValidFormat($ext); };
$resize_opts = ImageTransformer::parseResizeOptions($thumbnail_size);
break;
case 'text':
default:
$extension_filter = function ($ext) { return $ext === 'txt' || $ext === 'htm' || $ext === 'html'; };
break;
}
$items = [];
while (($item = readdir($handle)) !== false) {
$ext = strtolower(pathinfo($item, PATHINFO_EXTENSION));
if (is_dir($dir . $item) || $item == '.' || $item == '..' || !$extension_filter($ext)) {
continue;
}
$items[] = $item;
}
if (count($items) != 0) {
if ($limit > count($items)) {
$limit = count($items);
}
$randitems = array_rand($items, $limit);
if (!is_array($randitems)) {
$randitems = [$randitems];
}
foreach ($randitems as $item) {
$item = $items[$item];
switch ($type) {
case 'image':
$thumb = ImageService::getThumbnail('hcm.randomfile', $dir . $item, $resize_opts);
$result .= '<a href="' . _e(Router::file($dir . $item)) . '"'
. ' target="_blank"'
. Extend::buffer('image.lightbox', ['group' => 'hcm_rnd_' . Hcm::$uid])
. '>'
. '<img src="' . _e(Router::file($thumb)) . '" alt="' . _e($item) . '">'
. "</a>\n";
break;
default:
$result .= file_get_contents($dir . $item);
break;
}
}
}
closedir($handle);
return $result;
};