source: trunk/i.php @ 13088

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

multisize - added the coi (still to affine the admin ui + language)
multisize - derivatives can be revuild from a larger derviative instead of the original

File size: 14.7 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
236  if ($page['derivative_type'] == IMG_CUSTOM)
237  {
238    $params = $page['derivative_params'] = parse_custom_params($deriv);
239
240    if ($params->sizing->ideal_size[0] < 20 or $params->sizing->ideal_size[1] < 20)
241    {
242      ierror('Invalid size', 400);
243    }
244    if ($params->sizing->max_crop < 0 or $params->sizing->max_crop > 1)
245    {
246      ierror('Invalid crop', 400);
247    }
248    $greatest = ImageStdParams::get_by_type(IMG_XXLARGE);
249    if ($params->max_width() > $greatest->max_width() || $params->max_height() > $greatest->max_height())
250    {
251      ierror('Too big', 403);
252    }
253
254    $key = array();
255    $params->add_url_tokens($key);
256    $key = implode('_', $key);
257    if (!isset(ImageStdParams::$custom[$key]))
258    {
259      ierror('Size not allowed', 403);
260    }
261  }
262
263  if (is_file(PHPWG_ROOT_PATH.$req.$ext))
264  {
265    $req = './'.$req; // will be used to match #iamges.path
266  }
267  elseif (is_file(PHPWG_ROOT_PATH.'../'.$req.$ext))
268  {
269    $req = '../'.$req;
270  }
271
272  $page['src_location'] = $req.$ext;
273  $page['src_path'] = PHPWG_ROOT_PATH.$page['src_location'];
274  $page['src_url'] = $page['root_path'].$page['src_location'];
275}
276
277function try_switch_source(DerivativeParams $params, $original_mtime)
278{
279  global $page;
280  $candidates = array();
281  foreach(ImageStdParams::get_defined_type_map() as $candidate)
282  {
283    if ($candidate->type == $params->type)
284      continue;
285    if ($candidate->use_watermark != $params->use_watermark)
286      continue;
287    if ($candidate->max_width() < $params->max_width() || $candidate->max_height() < $params->max_height())
288      continue;
289    if ($params->sizing->max_crop==0)
290    {
291      if ($candidate->sizing->max_crop!=0)
292        continue;
293    }
294    else
295    {
296      if ($candidate->sizing->max_crop!=0)
297        continue; // this could be optimized
298      if (!isset($page['original_size']))
299        continue;
300      $candidate_size = $candidate->compute_final_size($page['original_size']);
301      if ($candidate_size[0] < $params->sizing->min_size[0] || $candidate_size[1] < $params->sizing->min_size[1] )
302        continue;
303    }
304    $candidates[] = $candidate;
305  }
306
307  foreach( array_reverse($candidates) as $candidate)
308  {
309    $candidate_path = $page['derivative_path'];
310    $candidate_path = str_replace( '-'.derivative_to_url($params->type), '-'.derivative_to_url($candidate->type), $candidate_path);
311    $candidate_mtime = @filemtime($candidate_path);
312    if ($candidate_mtime === false
313      || $candidate_mtime < $original_mtime
314      || $candidate_mtime < $candidate->last_mod_time)
315      continue;
316    $params->use_watermark = false;
317    $params->sharpen = min(1, $params->sharpen);
318    $page['src_path'] = $candidate_path;
319    $page['src_url'] = $page['root_path'] . substr($candidate_path, strlen(PHPWG_ROOT_PATH));
320  }
321}
322
323function send_derivative($expires)
324{
325  global $page;
326  $fp = fopen($page['derivative_path'], 'rb');
327
328  $fstat = fstat($fp);
329  header('Last-Modified: '.gmdate('D, d M Y H:i:s', $fstat['mtime']).' GMT');
330  if ($expires!==false)
331  {
332    header('Expires: '.gmdate('D, d M Y H:i:s', $expires).' GMT');
333  }
334  header('Content-length: '.$fstat['size']);
335  header('Connection: close');
336
337  $ctype="application/octet-stream";
338  switch (strtolower($page['derivative_ext']))
339  {
340    case ".jpe": case ".jpeg": case ".jpg": $ctype="image/jpeg"; break;
341    case ".png": $ctype="image/png"; break;
342    case ".gif": $ctype="image/gif"; break;
343  }
344  header("Content-Type: $ctype");
345
346  fpassthru($fp);
347  fclose($fp);
348}
349
350
351$page=array();
352$begin = $step = microtime(true);
353$timing=array();
354foreach( explode(',','load,rotate,crop,scale,sharpen,watermark,save,send') as $k )
355{
356  $timing[$k] = '';
357}
358
359include_once( PHPWG_ROOT_PATH .'/include/derivative_params.inc.php');
360include_once( PHPWG_ROOT_PATH .'/include/derivative_std_params.inc.php');
361
362ImageStdParams::load_from_file();
363
364
365parse_request();
366//var_export($page);
367
368$params = $page['derivative_params'];
369
370$src_mtime = @filemtime($page['src_path']);
371if ($src_mtime === false)
372{
373  ierror('Source not found', 404);
374}
375
376$need_generate = false;
377$derivative_mtime = @filemtime($page['derivative_path']);
378if ($derivative_mtime === false or
379    $derivative_mtime < $src_mtime or
380    $derivative_mtime < $params->last_mod_time)
381{
382  $need_generate = true;
383}
384
385$expires=false;
386$now = time();
387if ( isset($_GET['b']) )
388{
389  $expires = $now + 100;
390  header("Cache-control: no-store, max-age=100");
391}
392elseif ( $now > (max($src_mtime, $params->last_mod_time) + 24*3600) )
393{// somehow arbitrary - if derivative params or src didn't change for the last 24 hours, we send an expire header for several days
394  $expires = $now + 10*24*3600;
395}
396
397if (!$need_generate)
398{
399  if ( isset( $_SERVER['HTTP_IF_MODIFIED_SINCE'] )
400    and strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $derivative_mtime)
401  {// send the last mod time of the file back
402    header('Last-Modified: '.gmdate('D, d M Y H:i:s', $derivative_mtime).' GMT', true, 304);
403    header('Expires: '.gmdate('D, d M Y H:i:s', time()+10*24*3600).' GMT', true, 304);
404    exit;
405  }
406  send_derivative($expires);
407}
408
409$page['coi'] = null;
410if (strpos($page['src_location'], '/pwg_representative/')===false
411    && strpos($page['src_location'], 'themes/')===false
412    && strpos($page['src_location'], 'plugins/')===false)
413{
414  @include(PHPWG_ROOT_PATH.PWG_LOCAL_DIR .'config/database.inc.php');
415  include(PHPWG_ROOT_PATH .'include/dblayer/functions_'.$conf['dblayer'].'.inc.php');
416  try
417  {
418    $pwg_db_link = pwg_db_connect($conf['db_host'], $conf['db_user'],
419                                  $conf['db_password'], $conf['db_base']);
420    $query = 'SELECT coi, width, height FROM '.$prefixeTable.'images WHERE path=\''.$page['src_location'].'\'';
421    if ( ($row=pwg_db_fetch_assoc(pwg_query($query))) )
422    {
423      if (isset($row['width']))
424      {
425        $page['original_size'] = array($row['width'],$row['height']);
426      }
427      $page['coi'] = $row['coi'];
428    }
429    mysql_close($pwg_db_link);
430    if (!$row)
431    {
432      ierror('Db file path not found', 404);
433    }
434  }
435  catch (Exception $e)
436  {
437    ilog("db error", $e->getMessage());
438  }
439}
440
441try_switch_source($params, $src_mtime);
442
443if (!mkgetdir(dirname($page['derivative_path'])))
444{
445  ierror("dir create error", 500);
446}
447
448include_once(PHPWG_ROOT_PATH . 'admin/include/image.class.php');
449
450ignore_user_abort(true);
451set_time_limit(0);
452
453$image = new pwg_image($page['src_path']);
454$timing['load'] = time_step($step);
455
456$changes = 0;
457
458// todo rotate
459
460// Crop & scale
461$o_size = $d_size = array($image->get_width(),$image->get_height());
462$params->sizing->compute($o_size , $page['coi'], $crop_rect, $scaled_size );
463if ($crop_rect)
464{
465  $changes++;
466  $image->crop( $crop_rect->width(), $crop_rect->height(), $crop_rect->l, $crop_rect->t);
467  $timing['crop'] = time_step($step);
468}
469
470if ($scaled_size)
471{
472  $changes++;
473  $image->resize( $scaled_size[0], $scaled_size[1] );
474  $d_size = $scaled_size;
475  $timing['scale'] = time_step($step);
476}
477
478if ($params->sharpen)
479{
480  $changes += $image->sharpen( $params->sharpen );
481  $timing['sharpen'] = time_step($step);
482}
483
484if ($params->use_watermark)
485{
486  $wm = ImageStdParams::get_watermark();
487  $wm_image = new pwg_image(PHPWG_ROOT_PATH.$wm->file);
488  $wm_size = array($wm_image->get_width(),$wm_image->get_height());
489  if ($d_size[0]<$wm_size[0] or $d_size[1]<$wm_size[1])
490  {
491    $wm_scaling_params = SizingParams::classic($d_size[0], $d_size[1]);
492    $wm_scaling_params->compute($wm_size, null, $tmp, $wm_scaled_size);
493    $wm_size = $wm_scaled_size;
494    $wm_image->resize( $wm_scaled_size[0], $wm_scaled_size[1] );
495  }
496  $x = round( ($wm->xpos/100)*($d_size[0]-$wm_size[0]) );
497  $y = round( ($wm->ypos/100)*($d_size[1]-$wm_size[1]) );
498  if ($image->compose($wm_image, $x, $y, $wm->opacity))
499  {
500    $changes++;
501    if ($wm->xrepeat)
502    {
503      // todo
504      $pad = $wm_size[0] + max(30, round($wm_size[0]/4));
505      for($i=-$wm->xrepeat; $i<=$wm->xrepeat; $i++)
506      {
507        if (!$i) continue;
508        $x2 = $x + $i * $pad;
509        if ($x2>=0 && $x2+$wm_size[0]<$d_size[0])
510          if (!$image->compose($wm_image, $x2, $y, $wm->opacity))
511            break;
512      }
513    }
514  }
515  $wm_image->destroy();
516  $timing['watermark'] = time_step($step);
517}
518
519// no change required - redirect to source
520if (!$changes)
521{
522  header("X-i: No change");
523  ierror( $page['src_url'], 301);
524}
525
526if ($d_size[0]*$d_size[1] < 100000)
527{// strip metadata for small images
528  $image->strip();
529}
530$image->set_compression_quality( $params->quality );
531$image->write( $page['derivative_path'] );
532$image->destroy();
533$timing['save'] = time_step($step);
534
535send_derivative($expires);
536$timing['send'] = time_step($step);
537
538ilog('perf',
539  basename($page['src_path']), $o_size, $o_size[0]*$o_size[1],
540  basename($page['derivative_path']), $d_size, $d_size[0]*$d_size[1],
541  function_exists('memory_get_peak_usage') ? round( memory_get_peak_usage()/(1024*1024), 1) : '',
542  time_step($begin),
543  '|', $timing);
544?>
Note: See TracBrowser for help on using the repository browser.