-
Notifications
You must be signed in to change notification settings - Fork 0
/
Gallery.php
445 lines (357 loc) · 11.1 KB
/
Gallery.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
<?php
/** My Little Gallery
*
* A simple drop-in file-based HTML gallery.
*
* $Id: Gallery.php 987 2019-02-24 19:38:16Z anrdaemon $
*/
namespace AnrDaemon\MyLittleGallery;
class Gallery
implements \ArrayAccess, \Countable, \IteratorAggregate
{
const previewTemplate =
'<div><a href="%1$s" target="_blank"><img src="%2$s" alt="%3$s"/></a><p><a href="%1$s" target="_blank">%3$s</a></p></div>';
const defaultTypes = 'gif|jpeg|jpg|png|wbmp|webp';
// All paths are UTF-8! (Except those from \SplFileInfo)
protected $path; // Gallery base path
protected $prefix = array(); // Various prefixes for correct links construction
protected $params = array(); // Files list
protected $extensions = array(); // Allowed extensions
// FS encoding
protected $cs;
// Numbers formatter
protected $nf;
// Preview settings
protected $pWidth;
protected $pHeight;
protected $template;
// X-SendFile settings
protected $sfPrefix;
protected $sfHeader = 'X-SendFile';
protected function fromFileList(array $list)
{
$prev = null;
foreach($list as $fname)
{
if(is_dir($fname))
continue;
$name = iconv($this->cs, 'UTF-8', basename($fname));
$this->isSaneName($name);
$meta = getimagesize($fname);
if($meta === false || $meta[0] === 0 || $meta[1] === 0)
continue;
$this->params[$name] = new \ArrayObject([
'desc' => $name,
'path' => "{$this->path}/{$name}",
'width' => $meta[0],
'height' => $meta[1],
'mime' => $meta['mime'],
]);
if(isset($prev))
{
$this->params[$name]['prev'] = $prev;
$this->params[$prev]['next'] = $name;
}
$prev = $name;
}
return $this;
}
public static function fromListfile(\SplFileInfo $target, $charset = 'CP866', $fsEncoding = null)
{
$path = $target->getRealPath();
if(empty($path))
throw new \Exception('Can\'t use empty path.', 500);
if(is_dir($path))
throw new \Exception('Target is a directory', 500);
$self = new static($target->getPathInfo(), null, $fsEncoding);
$f = iconv($charset, 'UTF-8', file_get_contents($path));
if(preg_match_all('/^(\"?)(?P<name>[^\"]+?)\1\s+(?P<desc>.*?)\s*$/um', $f, $ta, PREG_SET_ORDER))
{
$prev = null;
foreach($ta as $a)
{
$name = basename(trim($a['name']));
$self->isSaneName($name);
$meta = getimagesize(iconv('UTF-8', $self->cs, "{$self->path}/$name"));
if($meta === false || $meta[0] === 0 || $meta[1] === 0)
continue;
$self->params[$name] = new \ArrayObject([
'desc' => $a['desc'],
'path' => "{$self->path}/{$name}",
'width' => $meta[0],
'height' => $meta[1],
'mime' => $meta['mime'],
]);
if(isset($prev))
{
$self->params[$name]['prev'] = $prev;
$self->params[$prev]['next'] = $name;
}
$prev = $name;
}
}
return $self;
}
public static function fromDirectory(\SplFileInfo $target, array $extensions = null, $fsEncoding = null)
{
if(empty($extensions))
{
$extensions = explode('|', static::defaultTypes);
}
$mask = "*.{" . implode(',', $extensions) . "}";
return static::fromCustomMask($target, $mask, $fsEncoding);
}
public static function fromCustomMask(\SplFileInfo $target, $mask, $fsEncoding = null)
{
$path = $target->getRealPath();
if(empty($path))
throw new \Exception('Can\'t use empty path.', 500);
if(!is_dir($path))
throw new \Exception('Target is not a directory', 500);
$self = new static($target, null, $fsEncoding);
return $self->fromFileList(glob("{$path}/" . iconv('UTF-8', $self->cs, $mask), GLOB_BRACE | GLOB_MARK));
}
/**
* $template($show, $preview, $description)
*/
public function showIndex($template = null)
{
if(empty($template))
{
$template = $this->template;
}
$gp = '';
foreach($this->params as $f => $d)
{
$gp .= sprintf($template, htmlspecialchars($this->prefix['view'] . rawurlencode($f)),
htmlspecialchars($this->prefix['thumbnail'] . rawurlencode($f)),
htmlspecialchars($d['desc'] . ' (' . $this->imageFileSize($f, 1024) . "\xC2\xA0kB)"));
}
return $gp;
}
public function setNumberFormatter($locale = 'en_US.UTF-8', $style = \NumberFormatter::DECIMAL, $pattern = '')
{
$this->nf = new \NumberFormatter($locale, $style, $pattern);
return $this;
}
public function allowSendFile($prefix = null, $header = null)
{
$this->sfPrefix = $prefix;
$this->sfHeader = trim($header) ?: 'X-SendFile';
return $this;
}
public function sendFile($path)
{
if(!isset($this->sfPrefix))
return false;
header_register_callback(
function()
{
/*
Accept-Ranges
Cache-Control
Content-Disposition
Content-Type
Expires
Set-Cookie
*/
header_remove('Accept-Ranges');
header_remove('Content-Type');
}
);
header("{$this->sfHeader}: {$this->sfPrefix}" . urlencode("$path"));
return true;
}
public function imageFileSize($name, $divisor = 1)
{
return $this->nf->format(ceil(filesize(iconv('UTF-8', $this->cs, "{$this->path}/$name")) / $divisor));
}
public function imagePreviewExists($name)
{
if(isset($this->params[$name]['preview']))
return !empty($this->params[$name]['preview']);
$fname = iconv('UTF-8', $this->cs, "{$this->path}/.preview/$name");
return $this->params[$name]['preview'] = file_exists($fname);
}
public function setPreviewSize($width = null, $height = null)
{
if((int)$width < 0 || (int)$height < 0)
throw new \Exception('Thumbnail dimensions can\'t be negative.', 500);
$this->pWidth = (int)$width ?: 160;
$this->pHeight = (int)$height ?: 120;
return $this;
}
public function setPrefix($name, $prefix)
{
if(!isset($this->prefix[$name]))
throw new \Exception("Unknown prefix '$name'.", 500);
$this->prefix[$name] = $prefix;
return $this;
}
public function setTemplate($template = null)
{
$this->template = empty($template)
? static::previewTemplate
: $template;
return $this;
}
public function getPrefix($name)
{
return $this->prefix[$name];
}
public function getPath($name = null, $local = null)
{
$path = $this->path;
if(isset($name))
{
$path .= $name;
}
if($local)
{
$path = iconv('UTF-8', $this->cs, $path);
}
return $path;
}
public function getUrl($prefix, $name = '')
{
return $this->prefix[$prefix] . ($prefix === 'index' ? '/' : rawurlencode($name));
}
public function thumbnailImage($name)
{
static $gdSave = array(
'image/gif' => 'imagegif',
'image/jpeg' => 'imagejpeg',
'image/png' => 'imagepng',
'image/vnd.wap.wbmp' => 'imagewbmp',
'image/webp' => 'imagewebp',
);
if(!isset($this->params[$name]))
throw new \Exception("Image '$name' is not registered in the gallery.", 404);
$path = $this->getPath("/.preview/$name", true);
if(is_file($path))
return true;
try
{
set_error_handler(function($s, $m, $f, $l, $c = null) { throw new \ErrorException($m, 0, $s, $f, $l); });
if(class_exists('Imagick'))
{
$img = new \Imagick("{$this->path}/$name");
$img->thumbnailImage($this->pWidth, $this->pHeight, true);
$img->writeImage("{$this->path}/.preview/$name");
}
elseif(function_exists('imagecreatefromstring'))
{
$src = imagecreatefromstring(file_get_contents($this->getPath("/$name", true)));
if($src === false)
throw new \Exception("The file '$name' can't be interpreted as image.", 500);
$oFactor = $this->params[$name]['width'] / $this->params[$name]['height'];
$tFactor = $this->pWidth / $this->pHeight;
if($oFactor >= $tFactor)
{
$w = $this->pWidth;
$h = min($this->pHeight, ceil($this->pWidth / $oFactor));
}
else
{
$w = min($this->pWidth, ceil($this->pHeight * $oFactor));
$h = $this->pHeight;
}
$img = imagecreatetruecolor($w, $h);
if(!imagecopyresampled($img, $src, 0, 0, 0, 0, $w, $h, $this->params[$name]['width'], $this->params[$name]['height']))
throw new \Exception("Unable to create thumbnail for '$name'.", 500);
$gdSave[$this->params[$name]['mime']]($img, $path);
}
else
throw new \ErrorException('Imagick or gd2 extension is required to create thumbnails at runtime.', 501);
restore_error_handler();
}
catch(\Exception $e)
{
restore_error_handler();
if(!is_dir(dirname($path)))
{
mkdir(dirname($path));
return false;
}
throw $e;
}
return true;
}
// FIX anti-exploit
public function isSaneName($fname)
{
$name = basename($fname);
if(preg_match('/[^!#$%&\'()+,\-.;=@\[\]^_`{}~\p{L}\d\s]/uiS', $name))
throw new \Exception("Invalid character in name '$name'.", 400);
if(!preg_match('{.+\.(' . implode('|', array_map('preg_quote', $this->extensions)) . ')$}ui', $name))
throw new \Exception('Invalid filename extension.', 400);
return true;
}
// Magic!
protected function __construct(\SplFileInfo $path, array $extensions = null, $fsEncoding = null)
{
if(version_compare(PHP_VERSION, '7.1', '<'))
{
$this->cs = trim($fsEncoding) ?: 'UTF-8';
}
else
{
ini_set('internal_encoding', 'UTF-8');
$this->cs = 'UTF-8';
}
$this->path = iconv($this->cs, 'UTF-8', realpath($path->getRealPath()));
// $path is not necessarily equals $path->getRealPath()
// Work off original $path
$this->prefix['index'] = iconv($this->cs, 'UTF-8', substr(realpath(realpath($path)), strlen(realpath(realpath($_SERVER['DOCUMENT_ROOT'])))));
$this->prefix['view'] = $this->prefix['index'] . '/?show=';
$this->prefix['thumbnail'] = $this->prefix['index'] . '/?preview=';
$this->prefix['image'] = $this->prefix['index'] . '/?view=';
$this->setNumberFormatter();
$this->setPreviewSize();
$this->setTemplate();
if(empty($extensions))
{
$this->extensions = explode('|', static::defaultTypes);
}
else
{
$masks = array();
foreach(array_map('trim', $extensions) as $ext)
{
if(empty($ext))
continue;
$masks[] = $ext;
}
if(empty($masks))
throw new \Exception('File extensions can\'t be empty strings.', 500);
$this->extensions = $masks;
}
}
// ArrayAccess
public function offsetSet($offset, $value)
{
$this->params[$offset] = $value;
}
public function offsetGet($offset)
{
return $this->params[$offset];
}
public function offsetExists($offset)
{
return isset($this->params[$offset]);
}
public function offsetUnset($offset)
{
unset($this->params[$offset]);
}
// Countable
public function count()
{
return count($this->params);
}
// IteratorAggregate
public function getIterator()
{
return new \ArrayIterator($this->params);
}
}