source: trunk/i.php @ 13171

Last change on this file since 13171 was 13171, checked in by patdenice, 12 years ago

multisize: removed useless test in i.php

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