source: trunk/i.php @ 13021

Last change on this file since 13021 was 13021, checked in by rvelices, 12 years ago

feature 2548 multisize - custom sizes restricted to those requested by theme/plugin
code refacto

File size: 12.2 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | Piwigo - a PHP based photo gallery                                    |
4// +-----------------------------------------------------------------------+
5// | Copyright(C) 2008-2012 Piwigo Team                  http://piwigo.org |
6// +-----------------------------------------------------------------------+
7// | This program is free software; you can redistribute it and/or modify  |
8// | it under the terms of the GNU General Public License as published by  |
9// | the Free Software Foundation                                          |
10// |                                                                       |
11// | This program is distributed in the hope that it will be useful, but   |
12// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
13// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
14// | General Public License for more details.                              |
15// |                                                                       |
16// | You should have received a copy of the GNU General Public License     |
17// | along with this program; if not, write to the Free Software           |
18// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
19// | USA.                                                                  |
20// +-----------------------------------------------------------------------+
21
22define('PHPWG_ROOT_PATH','./');
23
24// fast bootstrap - no db connection
25include(PHPWG_ROOT_PATH . 'include/config_default.inc.php');
26@include(PHPWG_ROOT_PATH. 'local/config/config.inc.php');
27
28defined('PWG_LOCAL_DIR') or define('PWG_LOCAL_DIR', 'local/');
29defined('PWG_DERIVATIVE_DIR') or define('PWG_DERIVATIVE_DIR', $conf['data_location'].'i/');
30
31function trigger_action() {}
32function get_extension( $filename )
33{
34  return substr( strrchr( $filename, '.' ), 1, strlen ( $filename ) );
35}
36
37function mkgetdir($dir)
38{
39  if ( !is_dir($dir) )
40  {
41    global $conf;
42    if (substr(PHP_OS, 0, 3) == 'WIN')
43    {
44      $dir = str_replace('/', DIRECTORY_SEPARATOR, $dir);
45    }
46    $umask = umask(0);
47    $mkd = @mkdir($dir, $conf['chmod_value'], true);
48    umask($umask);
49    if ($mkd==false)
50    {
51      return false;
52    }
53
54    $file = $dir.'/index.htm';
55    file_exists($file) or @file_put_contents( $file, 'Not allowed!' );
56  }
57  if ( !is_writable($dir) )
58  {
59    return false;
60  }
61  return true;
62}
63
64// end fast bootstrap
65
66function ilog()
67{
68  global $conf;
69  if (!$conf['enable_i_log']) return;
70
71  $line = date("c");
72  foreach( func_get_args() as $arg)
73  {
74    $line .= ' ';
75    if (is_array($arg))
76    {
77      $line .= implode(' ', $arg);
78    }
79    else
80    {
81      $line .= $arg;
82    }
83  }
84        $file=PHPWG_ROOT_PATH.$conf['data_location'].'tmp/i.log';
85  if (false == file_put_contents($file, $line."\n", FILE_APPEND))
86        {
87                mkgetdir(dirname($file));
88        }
89}
90
91function ierror($msg, $code)
92{
93  if ($code==301 || $code==302)
94  {
95    if (ob_get_length () !== FALSE)
96    {
97      ob_clean();
98    }
99    // default url is on html format
100    $url = html_entity_decode($msg);
101    header('Request-URI: '.$url);
102    header('Content-Location: '.$url);
103    header('Location: '.$url);
104    exit;
105  }
106  if ($code>=400)
107  {
108    $protocol = $_SERVER["SERVER_PROTOCOL"];
109    if ( ('HTTP/1.1' != $protocol) && ('HTTP/1.0' != $protocol) )
110      $protocol = 'HTTP/1.0';
111
112    header( "$protocol $code $msg", true, $code );
113  }
114  //todo improve
115  echo $msg;
116  exit;
117}
118
119function time_step( &$step )
120{
121  $tmp = $step;
122  $step = microtime(true);
123  return intval(1000*($step - $tmp));
124}
125
126function url_to_size($s)
127{
128  $pos = strpos($s, 'x');
129  if ($pos===false)
130  {
131    return array((int)$s, (int)$s);
132  }
133  return array((int)substr($s,0,$pos), (int)substr($s,$pos+1));
134}
135
136function parse_custom_params($tokens)
137{
138  if (count($tokens)<1)
139    ierror('Empty array while parsing Sizing', 400);
140
141  $crop = 0;
142  $min_size = null;
143
144  $token = array_shift($tokens);
145  if ($token[0]=='s')
146  {
147    $size = url_to_size( substr($token,1) );
148  }
149  elseif ($token[0]=='e')
150  {
151    $crop = 1;
152    $size = $min_size = url_to_size( substr($token,1) );
153  }
154  else
155  {
156    $size = url_to_size( $token );
157    if (count($tokens)<2)
158      ierror('Sizing arr', 400);
159
160    $token = array_shift($tokens);
161    $crop = char_to_fraction($token);
162
163    $token = array_shift($tokens);
164    $min_size = url_to_size( $token );
165  }
166  return new DerivativeParams( new SizingParams($size, $crop, $min_size) );
167}
168
169function parse_request()
170{
171  global $conf, $page;
172
173  if ( $conf['question_mark_in_urls']==false and
174       isset($_SERVER["PATH_INFO"]) and !empty($_SERVER["PATH_INFO"]) )
175  {
176    $req = $_SERVER["PATH_INFO"];
177    $req = str_replace('//', '/', $req);
178    $path_count = count( explode('/', $req) );
179    $page['root_path'] = PHPWG_ROOT_PATH.str_repeat('../', $path_count-1);
180  }
181  else
182  {
183    $req = $_SERVER["QUERY_STRING"];
184    if ($pos=strpos($req, '&'))
185    {
186      $req = substr($req, 0, $pos);
187    }
188    /*foreach (array_keys($_GET) as $keynum => $key)
189    {
190      $req = $key;
191      break;
192    }*/
193    $page['root_path'] = PHPWG_ROOT_PATH;
194  }
195
196  $req = ltrim($req, '/');
197  !preg_match('#[^a-zA-Z0-9/_.-]#', $req) or ierror('Invalid chars in request', 400);
198
199  $page['derivative_path'] = PHPWG_ROOT_PATH.PWG_DERIVATIVE_DIR.$req;
200
201  $pos = strrpos($req, '.');
202  $pos!== false || ierror('Missing .', 400);
203  $ext = substr($req, $pos);
204  $page['derivative_ext'] = $ext;
205  $req = substr($req, 0, $pos);
206
207  $pos = strrpos($req, '-');
208  $pos!== false || ierror('Missing -', 400);
209  $deriv = substr($req, $pos+1);
210  $req = substr($req, 0, $pos);
211
212  $deriv = explode('_', $deriv);
213  foreach (ImageStdParams::get_defined_type_map() as $type => $params)
214  {
215    if ( derivative_to_url($type) == $deriv[0])
216    {
217      $page['derivative_type'] = $type;
218      $page['derivative_params'] = $params;
219      break;
220    }
221  }
222
223  if (!isset($page['derivative_type']))
224  {
225    if (derivative_to_url(IMG_CUSTOM) == $deriv[0])
226    {
227      $page['derivative_type'] = IMG_CUSTOM;
228    }
229    else
230    {
231      ierror('Unknown parsing type', 400);
232    }
233  }
234  array_shift($deriv);
235  $page['coi'] = '';
236  if (count($deriv) && $deriv[0][0]=='c' && $deriv[0][1]=='i')
237  {
238    $page['coi'] = substr(array_shift($deriv), 2);
239    preg_match('#^[a-zA-Z]{4}$#', $page['coi']) or ierror('Invalid center of interest', 400);
240  }
241
242  if ($page['derivative_type'] == IMG_CUSTOM)
243  {
244    $params = $page['derivative_params'] = parse_custom_params($deriv);
245
246    if ($params->sizing->ideal_size[0] < 20 or $params->sizing->ideal_size[1] < 20)
247    {
248      ierror('Invalid size', 400);
249    }
250    if ($params->sizing->max_crop < 0 or $params->sizing->max_crop > 1)
251    {
252      ierror('Invalid crop', 400);
253    }
254    $greatest = ImageStdParams::get_by_type(IMG_XXLARGE);
255    if ($params->max_width() > $greatest->max_width() || $params->max_height() > $greatest->max_height())
256    {
257      ierror('Too big', 403);
258    }
259   
260    $key = array();
261    $params->add_url_tokens($key);
262    $key = implode('_', $key);
263    if (!isset(ImageStdParams::$custom[$key]))
264    {
265      ierror('Size not allowed', 403);
266    }
267  }
268
269  if (!is_file(PHPWG_ROOT_PATH.$req.$ext) and
270      is_file(PHPWG_ROOT_PATH.'../'.$req.$ext) )
271    $req = '../'.$req;
272
273  $page['src_location'] = $req.$ext;
274  $page['src_path'] = PHPWG_ROOT_PATH.$page['src_location'];
275  $page['src_url'] = $page['root_path'].$page['src_location'];
276}
277
278
279function send_derivative($expires)
280{
281  global $page;
282  $fp = fopen($page['derivative_path'], 'rb');
283
284  $fstat = fstat($fp);
285  header('Last-Modified: '.gmdate('D, d M Y H:i:s', $fstat['mtime']).' GMT');
286  if ($expires!==false)
287  {
288    header('Expires: '.gmdate('D, d M Y H:i:s', $expires).' GMT');
289  }
290  header('Content-length: '.$fstat['size']);
291  header('Connection: close');
292
293  $ctype="application/octet-stream";
294  switch (strtolower($page['derivative_ext']))
295  {
296    case ".jpe": case ".jpeg": case ".jpg": $ctype="image/jpeg"; break;
297    case ".png": $ctype="image/png"; break;
298    case ".gif": $ctype="image/gif"; break;
299  }
300  header("Content-Type: $ctype");
301
302  fpassthru($fp);
303  fclose($fp);
304}
305
306
307$page=array();
308$begin = $step = microtime(true);
309$timing=array();
310foreach( explode(',','load,rotate,crop,scale,sharpen,watermark,save,send') as $k )
311{
312  $timing[$k] = '';
313}
314
315include_once( PHPWG_ROOT_PATH .'/include/derivative_params.inc.php');
316include_once( PHPWG_ROOT_PATH .'/include/derivative_std_params.inc.php');
317
318ImageStdParams::load_from_file();
319
320
321parse_request();
322//var_export($page);
323
324$params = $page['derivative_params'];
325
326$src_mtime = @filemtime($page['src_path']);
327if ($src_mtime === false)
328{
329  ierror('Source not found', 404);
330}
331
332$need_generate = false;
333$derivative_mtime = @filemtime($page['derivative_path']);
334if ($derivative_mtime === false or
335    $derivative_mtime < $src_mtime or
336    $derivative_mtime < $params->last_mod_time)
337{
338  $need_generate = true;
339}
340
341$expires=false;
342$now = time();
343if ( isset($_GET['b']) )
344{
345  $expires = $now + 100;
346  header("Cache-control: no-store, max-age=100");
347}
348elseif ( $now > (max($src_mtime, $params->last_mod_time) + 24*3600) )
349{// somehow arbitrary - if derivative params or src didn't change for the last 24 hours, we send an expire header for several days
350  $expires = $now + 10*24*3600;
351}
352
353if (!$need_generate)
354{
355  if ( isset( $_SERVER['HTTP_IF_MODIFIED_SINCE'] )
356    and strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $derivative_mtime)
357  {// send the last mod time of the file back
358    header('Last-Modified: '.gmdate('D, d M Y H:i:s', $derivative_mtime).' GMT', true, 304);
359    header('Expires: '.gmdate('D, d M Y H:i:s', time()+10*24*3600).' GMT', true, 304);
360    exit;
361  }
362  send_derivative($expires);
363}
364
365if (!mkgetdir(dirname($page['derivative_path'])))
366{
367  ierror("dir create error", 500);
368}
369
370include_once(PHPWG_ROOT_PATH . 'admin/include/image.class.php');
371
372ignore_user_abort(true);
373set_time_limit(0);
374
375$image = new pwg_image($page['src_path']);
376$timing['load'] = time_step($step);
377
378$changes = 0;
379
380// todo rotate
381
382// Crop & scale
383$o_size = $d_size = array($image->get_width(),$image->get_height());
384$params->sizing->compute($o_size , $page['coi'], $crop_rect, $scaled_size );
385if ($crop_rect)
386{
387  $changes++;
388  $image->crop( $crop_rect->width(), $crop_rect->height(), $crop_rect->l, $crop_rect->t);
389  $timing['crop'] = time_step($step);
390}
391
392if ($scaled_size)
393{
394  $changes++;
395  $image->resize( $scaled_size[0], $scaled_size[1] );
396  $d_size = $scaled_size;
397  $timing['scale'] = time_step($step);
398}
399
400if ($params->sharpen)
401{
402  $changes += $image->sharpen( $params->sharpen );
403  $timing['sharpen'] = time_step($step);
404}
405
406if ($params->use_watermark)
407{
408  $wm = ImageStdParams::get_watermark();
409  $wm_image = new pwg_image(PHPWG_ROOT_PATH.$wm->file);
410  $wm_size = array($wm_image->get_width(),$wm_image->get_height());
411  if ($d_size[0]<$wm_size[0] or $d_size[1]<$wm_size[1])
412  {
413    $wm_scaling_params = SizingParams::classic($d_size[0], $d_size[1]);
414    $wm_scaling_params->compute($wm_size, null, $tmp, $wm_scaled_size);
415    $wm_size = $wm_scaled_size;
416    $wm_image->resize( $wm_scaled_size[0], $wm_scaled_size[1] );
417  }
418  $x = round( ($wm->xpos/100)*($d_size[0]-$wm_size[0]) );
419  $y = round( ($wm->ypos/100)*($d_size[1]-$wm_size[1]) );
420  if ($image->compose($wm_image, $x, $y, $wm->opacity))
421  {
422    $changes++;
423    if ($wm->xrepeat)
424    {
425      // todo
426      $pad = $wm_size[0] + max(30, round($wm_size[0]/4));
427      for($i=-$wm->xrepeat; $i<=$wm->xrepeat; $i++)
428      {
429        if (!$i) continue;
430        $x2 = $x + $i * $pad;
431        if ($x2>=0 && $x2+$wm_size[0]<$d_size[0])
432          if (!$image->compose($wm_image, $x2, $y, $wm->opacity))
433            break;
434      }
435    }
436  }
437  $wm_image->destroy();
438  $timing['watermark'] = time_step($step);
439}
440
441// no change required - redirect to source
442if (!$changes)
443{
444  header("X-i: No change");
445  ierror( $page['src_url'], 301);
446}
447
448if ($d_size[0]*$d_size[1] < 100000)
449{// strip metadata for small images
450  $image->strip();
451}
452$image->set_compression_quality( $params->quality );
453$image->write( $page['derivative_path'] );
454$image->destroy();
455$timing['save'] = time_step($step);
456
457send_derivative($expires);
458$timing['send'] = time_step($step);
459
460ilog('perf',
461  basename($page['src_path']), $o_size, $o_size[0]*$o_size[1],
462  basename($page['derivative_path']), $d_size, $d_size[0]*$d_size[1],
463  function_exists('memory_get_peak_usage') ? round( memory_get_peak_usage()/(1024*1024), 1) : '',
464  time_step($begin),
465  '|', $timing);
466?>
Note: See TracBrowser for help on using the repository browser.