forked from Piwigo/Piwigo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
i.php
622 lines (544 loc) · 16.8 KB
/
i.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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
<?php
// +-----------------------------------------------------------------------+
// | This file is part of Piwigo. |
// | |
// | For copyright and license information, please view the COPYING.txt |
// | file that was distributed with this source code. |
// +-----------------------------------------------------------------------+
define('PHPWG_ROOT_PATH','./');
// fast bootstrap - no db connection
include(PHPWG_ROOT_PATH . 'include/config_default.inc.php');
@include(PHPWG_ROOT_PATH. 'local/config/config.inc.php');
defined('PWG_LOCAL_DIR') or define('PWG_LOCAL_DIR', 'local/');
defined('PWG_DERIVATIVE_DIR') or define('PWG_DERIVATIVE_DIR', $conf['data_location'].'i/');
@include(PHPWG_ROOT_PATH.PWG_LOCAL_DIR .'config/database.inc.php');
include(PHPWG_ROOT_PATH . 'include/Logger.class.php');
$logger = new Logger(array(
'directory' => PHPWG_ROOT_PATH . $conf['data_location'] . $conf['log_dir'],
'severity' => $conf['log_level'],
// we use an hashed filename to prevent direct file access, and we salt with
// the db_password instead of secret_key because the log must be usable in i.php
// (secret_key is in the database)
'filename' => 'log_' . date('Y-m-d') . '_' . sha1(date('Y-m-d') . $conf['db_password']) . '.txt',
));
function trigger_notify() {}
function get_extension( $filename )
{
return substr( strrchr( $filename, '.' ), 1, strlen ( $filename ) );
}
function mkgetdir($dir)
{
if ( !is_dir($dir) )
{
global $conf;
if (substr(PHP_OS, 0, 3) == 'WIN')
{
$dir = str_replace('/', DIRECTORY_SEPARATOR, $dir);
}
$umask = umask(0);
$mkd = @mkdir($dir, $conf['chmod_value'], true);
umask($umask);
if ($mkd==false && !is_dir($dir) /* retest existence because of potential concurrent i.php with slow file systems*/)
{
return false;
}
$file = $dir.'/index.htm';
file_exists($file) or @file_put_contents( $file, 'Not allowed!' );
}
if ( !is_writable($dir) )
{
return false;
}
return true;
}
// end fast bootstrap
function ierror($msg, $code)
{
global $logger;
if ($code==301 || $code==302)
{
if (ob_get_length () !== FALSE)
{
ob_clean();
}
// default url is on html format
$url = html_entity_decode($msg);
$logger->debug($code . ' ' . $url, 'i.php', array(
'url' => $_SERVER['REQUEST_URI'],
));
header('Request-URI: '.$url);
header('Content-Location: '.$url);
header('Location: '.$url);
exit;
}
if ($code>=400)
{
$protocol = $_SERVER["SERVER_PROTOCOL"];
if ( ('HTTP/1.1' != $protocol) && ('HTTP/1.0' != $protocol) )
$protocol = 'HTTP/1.0';
header( "$protocol $code $msg", true, $code );
}
//todo improve
echo $msg;
$logger->error($code . ' ' . $msg, 'i.php', array(
'url' => $_SERVER['REQUEST_URI'],
));
exit;
}
function time_step( &$step )
{
$tmp = $step;
$step = microtime(true);
return intval(1000*($step - $tmp));
}
function url_to_size($s)
{
$pos = strpos($s, 'x');
if ($pos===false)
{
return array((int)$s, (int)$s);
}
return array((int)substr($s,0,$pos), (int)substr($s,$pos+1));
}
function parse_custom_params($tokens)
{
if (count($tokens)<1)
ierror('Empty array while parsing Sizing', 400);
$crop = 0;
$min_size = null;
$token = array_shift($tokens);
if ($token[0]=='s')
{
$size = url_to_size( substr($token,1) );
}
elseif ($token[0]=='e')
{
$crop = 1;
$size = $min_size = url_to_size( substr($token,1) );
}
else
{
$size = url_to_size( $token );
if (count($tokens)<2)
ierror('Sizing arr', 400);
$token = array_shift($tokens);
$crop = char_to_fraction($token);
$token = array_shift($tokens);
$min_size = url_to_size( $token );
}
return new DerivativeParams( new SizingParams($size, $crop, $min_size) );
}
function parse_request()
{
global $conf, $page;
if ( $conf['question_mark_in_urls']==false and
isset($_SERVER["PATH_INFO"]) and !empty($_SERVER["PATH_INFO"]) )
{
$req = $_SERVER["PATH_INFO"];
$req = str_replace('//', '/', $req);
$path_count = count( explode('/', $req) );
$page['root_path'] = PHPWG_ROOT_PATH.str_repeat('../', $path_count-1);
}
else
{
$req = $_SERVER["QUERY_STRING"];
if ($pos=strpos($req, '&'))
{
$req = substr($req, 0, $pos);
}
$req = rawurldecode($req);
/*foreach (array_keys($_GET) as $keynum => $key)
{
$req = $key;
break;
}*/
$page['root_path'] = PHPWG_ROOT_PATH;
}
$req = ltrim($req, '/');
foreach (preg_split('#/+#', $req) as $token)
{
preg_match($conf['sync_chars_regex'], $token) or ierror('Invalid chars in request', 400);
}
$page['derivative_path'] = PHPWG_ROOT_PATH.PWG_DERIVATIVE_DIR.$req;
$pos = strrpos($req, '.');
$pos!== false || ierror('Missing .', 400);
$ext = substr($req, $pos);
$page['derivative_ext'] = $ext;
$req = substr($req, 0, $pos);
$pos = strrpos($req, '-');
$pos!== false || ierror('Missing -', 400);
$deriv = substr($req, $pos+1);
$req = substr($req, 0, $pos);
$deriv = explode('_', $deriv);
foreach (ImageStdParams::get_defined_type_map() as $type => $params)
{
if ( derivative_to_url($type) == $deriv[0])
{
$page['derivative_type'] = $type;
$page['derivative_params'] = $params;
break;
}
}
if (!isset($page['derivative_type']))
{
if (derivative_to_url(IMG_CUSTOM) == $deriv[0])
{
$page['derivative_type'] = IMG_CUSTOM;
}
else
{
ierror('Unknown parsing type', 400);
}
}
array_shift($deriv);
if ($page['derivative_type'] == IMG_CUSTOM)
{
$params = $page['derivative_params'] = parse_custom_params($deriv);
ImageStdParams::apply_global($params);
if ($params->sizing->ideal_size[0] < 20 or $params->sizing->ideal_size[1] < 20)
{
ierror('Invalid size', 400);
}
if ($params->sizing->max_crop < 0 or $params->sizing->max_crop > 1)
{
ierror('Invalid crop', 400);
}
$greatest = ImageStdParams::get_by_type(IMG_XXLARGE);
$key = array();
$params->add_url_tokens($key);
$key = implode('_', $key);
if (!isset(ImageStdParams::$custom[$key]))
{
ierror('Size not allowed', 403);
}
}
if (is_file(PHPWG_ROOT_PATH.$req.$ext))
{
$req = './'.$req; // will be used to match #iamges.path
}
elseif (is_file(PHPWG_ROOT_PATH.'../'.$req.$ext))
{
$req = '../'.$req;
}
$page['src_location'] = $req.$ext;
$page['src_path'] = PHPWG_ROOT_PATH.$page['src_location'];
$page['src_url'] = $page['root_path'].$page['src_location'];
}
function try_switch_source(DerivativeParams $params, $original_mtime)
{
global $page;
if (!isset($page['original_size']))
return false;
$original_size = $page['original_size'];
if ($page['rotation_angle']==90 || $page['rotation_angle']==270)
{
$tmp = $original_size[0];
$original_size[0] = $original_size[1];
$original_size[1] = $tmp;
}
$dsize = $params->compute_final_size($original_size);
$use_watermark = $params->use_watermark;
if ($use_watermark)
{
$use_watermark = $params->will_watermark($dsize);
}
$candidates = array();
foreach(ImageStdParams::get_defined_type_map() as $candidate)
{
if ($candidate->type == $params->type)
continue;
if ($candidate->use_watermark != $use_watermark)
continue;
if ($candidate->max_width() < $params->max_width() || $candidate->max_height() < $params->max_height())
continue;
$candidate_size = $candidate->compute_final_size($original_size);
if ($dsize != $params->compute_final_size($candidate_size))
continue;
if ($params->sizing->max_crop==0)
{
if ($candidate->sizing->max_crop!=0)
continue;
}
else
{
if ($use_watermark && $candidate->use_watermark)
continue; //a square that requires watermark should not be generated from a larger derivative with watermark, because if the watermark is not centered on the large image, it will be cropped.
if ($candidate->sizing->max_crop!=0)
continue; // this could be optimized
if ($candidate_size[0] < $params->sizing->min_size[0] || $candidate_size[1] < $params->sizing->min_size[1] )
continue;
}
$candidates[] = $candidate;
}
foreach( array_reverse($candidates) as $candidate)
{
$candidate_path = $page['derivative_path'];
$candidate_path = str_replace( '-'.derivative_to_url($params->type), '-'.derivative_to_url($candidate->type), $candidate_path);
$candidate_mtime = @filemtime($candidate_path);
if ($candidate_mtime === false
|| $candidate_mtime < $original_mtime
|| $candidate_mtime < $candidate->last_mod_time)
continue;
$params->use_watermark = false;
$params->sharpen = min(1, $params->sharpen);
$page['src_path'] = $candidate_path;
$page['src_url'] = $page['root_path'] . substr($candidate_path, strlen(PHPWG_ROOT_PATH));
$page['rotation_angle'] = 0;
return true;
}
return false;
}
function send_derivative($expires)
{
global $page;
if (isset($_GET['ajaxload']) and $_GET['ajaxload'] == 'true')
{
include_once(PHPWG_ROOT_PATH.'include/functions_cookie.inc.php');
include_once(PHPWG_ROOT_PATH.'include/functions_url.inc.php');
echo json_encode( array( 'url'=>embellish_url(get_absolute_root_url().$page['derivative_path']) ) );
return;
}
$fp = fopen($page['derivative_path'], 'rb');
$fstat = fstat($fp);
header('Last-Modified: '.gmdate('D, d M Y H:i:s', $fstat['mtime']).' GMT');
if ($expires!==false)
{
header('Expires: '.gmdate('D, d M Y H:i:s', $expires).' GMT');
}
header('Content-length: '.$fstat['size']);
header('Connection: close');
$ctype="application/octet-stream";
switch (strtolower($page['derivative_ext']))
{
case ".jpe": case ".jpeg": case ".jpg": $ctype="image/jpeg"; break;
case ".png": $ctype="image/png"; break;
case ".gif": $ctype="image/gif"; break;
}
header("Content-Type: $ctype");
fpassthru($fp);
fclose($fp);
}
$page=array();
$begin = $step = microtime(true);
$timing=array();
foreach( explode(',','load,rotate,crop,scale,sharpen,watermark,save,send') as $k )
{
$timing[$k] = '';
}
include_once(PHPWG_ROOT_PATH .'include/dblayer/functions_'.$conf['dblayer'].'.inc.php');
include_once( PHPWG_ROOT_PATH .'/include/derivative_params.inc.php');
include_once( PHPWG_ROOT_PATH .'/include/derivative_std_params.inc.php');
try
{
pwg_db_connect($conf['db_host'], $conf['db_user'],
$conf['db_password'], $conf['db_base']);
}
catch (Exception $e)
{
$logger->error($e->getMessage(), 'i.php');
}
pwg_db_check_charset();
list($conf['derivatives']) = pwg_db_fetch_row(pwg_query('SELECT value FROM '.$prefixeTable.'config WHERE param=\'derivatives\''));
ImageStdParams::load_from_db();
parse_request();
//var_export($page);
$params = $page['derivative_params'];
$src_mtime = @filemtime($page['src_path']);
if ($src_mtime === false)
{
ierror('Source not found', 404);
}
$need_generate = false;
$derivative_mtime = @filemtime($page['derivative_path']);
if ($derivative_mtime === false or
$derivative_mtime < $src_mtime or
$derivative_mtime < $params->last_mod_time)
{
$need_generate = true;
}
$expires=false;
$now = time();
if ( isset($_GET['b']) )
{
$expires = $now + 100;
header("Cache-control: no-store, max-age=100");
}
elseif ( $now > (max($src_mtime, $params->last_mod_time) + 24*3600) )
{// somehow arbitrary - if derivative params or src didn't change for the last 24 hours, we send an expire header for several days
$expires = $now + 10*24*3600;
}
if (!$need_generate)
{
if ( isset( $_SERVER['HTTP_IF_MODIFIED_SINCE'] )
and strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $derivative_mtime)
{// send the last mod time of the file back
header('Last-Modified: '.gmdate('D, d M Y H:i:s', $derivative_mtime).' GMT', true, 304);
header('Expires: '.gmdate('D, d M Y H:i:s', time()+10*24*3600).' GMT', true, 304);
exit;
}
send_derivative($expires);
exit;
}
include_once(PHPWG_ROOT_PATH . 'admin/include/image.class.php');
$page['coi'] = null;
if (strpos($page['src_location'], '/pwg_representative/')===false
&& strpos($page['src_location'], 'themes/')===false
&& strpos($page['src_location'], 'plugins/')===false)
{
try
{
$query = '
SELECT *
FROM '.$prefixeTable.'images
WHERE path=\''.addslashes($page['src_location']).'\'
;';
if ( ($row=pwg_db_fetch_assoc(pwg_query($query))) )
{
if (isset($row['width']))
{
$page['original_size'] = array($row['width'],$row['height']);
}
$page['coi'] = $row['coi'];
if (!isset($row['rotation']))
{
$page['rotation_angle'] = pwg_image::get_rotation_angle($page['src_path']);
single_update(
$prefixeTable.'images',
array('rotation' => pwg_image::get_rotation_code_from_angle($page['rotation_angle'])),
array('id' => $row['id'])
);
}
else
{
$page['rotation_angle'] = pwg_image::get_rotation_angle_from_code($row['rotation']);
}
}
if (!$row)
{
ierror('Db file path not found', 404);
}
}
catch (Exception $e)
{
$logger->error($e->getMessage(), 'i.php');
}
}
else
{
$page['rotation_angle'] = 0;
}
pwg_db_close();
if (!try_switch_source($params, $src_mtime) && $params->type==IMG_CUSTOM)
{
$sharpen = 0;
foreach (ImageStdParams::get_defined_type_map() as $std_params)
{
$sharpen += $std_params->sharpen;
}
$params->sharpen = round($sharpen / count(ImageStdParams::get_defined_type_map()) );
}
if (!mkgetdir(dirname($page['derivative_path'])))
{
ierror("dir create error", 500);
}
ignore_user_abort(true);
@set_time_limit(0);
$image = new pwg_image($page['src_path']);
$timing['load'] = time_step($step);
$changes = 0;
// rotate
if (0 != $page['rotation_angle'])
{
$image->rotate($page['rotation_angle']);
$changes++;
$timing['rotate'] = time_step($step);
}
// Crop & scale
$o_size = $d_size = array($image->get_width(),$image->get_height());
$params->sizing->compute($o_size , $page['coi'], $crop_rect, $scaled_size );
if ($crop_rect)
{
$changes++;
$image->crop( $crop_rect->width(), $crop_rect->height(), $crop_rect->l, $crop_rect->t);
$timing['crop'] = time_step($step);
}
if ($scaled_size)
{
$changes++;
$image->resize( $scaled_size[0], $scaled_size[1] );
$d_size = $scaled_size;
$timing['scale'] = time_step($step);
}
if ($params->sharpen)
{
$changes += $image->sharpen( $params->sharpen );
$timing['sharpen'] = time_step($step);
}
if ($params->will_watermark($d_size))
{
$wm = ImageStdParams::get_watermark();
$wm_image = new pwg_image(PHPWG_ROOT_PATH.$wm->file);
$wm_size = array($wm_image->get_width(),$wm_image->get_height());
if ($d_size[0]<$wm_size[0] or $d_size[1]<$wm_size[1])
{
$wm_scaling_params = SizingParams::classic($d_size[0], $d_size[1]);
$wm_scaling_params->compute($wm_size, null, $tmp, $wm_scaled_size);
$wm_size = $wm_scaled_size;
$wm_image->resize( $wm_scaled_size[0], $wm_scaled_size[1] );
}
$x = round( ($wm->xpos/100)*($d_size[0]-$wm_size[0]) );
$y = round( ($wm->ypos/100)*($d_size[1]-$wm_size[1]) );
if ($image->compose($wm_image, $x, $y, $wm->opacity))
{
$changes++;
if ($wm->xrepeat || $wm->yrepeat)
{
$xpad = $wm_size[0] + max(30, round($wm_size[0]/4));
$ypad = $wm_size[1] + max(30, round($wm_size[1]/4));
for($i=-$wm->xrepeat; $i<=$wm->xrepeat; $i++)
{
for($j=-$wm->yrepeat; $j<=$wm->yrepeat; $j++)
{
if (!$i && !$j) continue;
$x2 = $x + $i * $xpad;
$y2 = $y + $j * $ypad;
if ($x2>=0 && $x2+$wm_size[0]<$d_size[0] &&
$y2>=0 && $y2+$wm_size[1]<$d_size[1] )
if (!$image->compose($wm_image, $x2, $y2, $wm->opacity))
break;
}
}
}
}
$wm_image->destroy();
$timing['watermark'] = time_step($step);
}
// no change required - redirect to source
if (!$changes)
{
header("X-i: No change");
ierror( $page['src_url'], 301);
}
if ($d_size[0]*$d_size[1] < $conf['derivatives_strip_metadata_threshold'])
{// strip metadata for small images
$image->strip();
}
$image->set_compression_quality( ImageStdParams::$quality );
$image->write( $page['derivative_path'] );
$image->destroy();
@chmod($page['derivative_path'], 0644);
$timing['save'] = time_step($step);
send_derivative($expires);
$timing['send'] = time_step($step);
$timing['total'] = time_step($begin);
if ($logger->severity() >= Logger::DEBUG)
{
$logger->debug('', 'i.php', array(
'src_path' => basename($page['src_path']),
'derivative_path' => basename($page['derivative_path']),
'o_size' => $o_size[0] . ' ' . $o_size[1] . ' ' . ($o_size[0]*$o_size[1]),
'd_size' => $d_size[0] . ' ' . $d_size[1] . ' ' . ($d_size[0]*$d_size[1]),
'mem_usage' => function_exists('memory_get_peak_usage') ? round( memory_get_peak_usage()/(1024*1024), 1) : '',
'timing' => $timing,
));
}