source: trunk/i.php @ 17230

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

bug 2712: Custom sized derivatives are never sharpened

File size: 16.9 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
31@include(PHPWG_ROOT_PATH.PWG_LOCAL_DIR .'config/database.inc.php');
32
33
34function trigger_action() {}
35function get_extension( $filename )
36{
37  return substr( strrchr( $filename, '.' ), 1, strlen ( $filename ) );
38}
39
40function mkgetdir($dir)
41{
42  if ( !is_dir($dir) )
43  {
44    global $conf;
45    if (substr(PHP_OS, 0, 3) == 'WIN')
46    {
47      $dir = str_replace('/', DIRECTORY_SEPARATOR, $dir);
48    }
49    $umask = umask(0);
50    $mkd = @mkdir($dir, $conf['chmod_value'], true);
51    umask($umask);
52    if ($mkd==false)
53    {
54      return false;
55    }
56
57    $file = $dir.'/index.htm';
58    file_exists($file) or @file_put_contents( $file, 'Not allowed!' );
59  }
60  if ( !is_writable($dir) )
61  {
62    return false;
63  }
64  return true;
65}
66
67// end fast bootstrap
68
69function ilog()
70{
71  global $conf;
72  if (!$conf['enable_i_log']) return;
73
74  $line = date("c");
75  foreach( func_get_args() as $arg)
76  {
77    $line .= ' ';
78    if (is_array($arg))
79    {
80      $line .= implode(' ', $arg);
81    }
82    else
83    {
84      $line .= $arg;
85    }
86  }
87        $file=PHPWG_ROOT_PATH.$conf['data_location'].'tmp/i.log';
88  if (false == file_put_contents($file, $line."\n", FILE_APPEND))
89        {
90                mkgetdir(dirname($file));
91        }
92}
93
94function ierror($msg, $code)
95{
96  if ($code==301 || $code==302)
97  {
98    if (ob_get_length () !== FALSE)
99    {
100      ob_clean();
101    }
102    // default url is on html format
103    $url = html_entity_decode($msg);
104    header('Request-URI: '.$url);
105    header('Content-Location: '.$url);
106    header('Location: '.$url);
107    ilog('WARN', $code, $url, $_SERVER['REQUEST_URI']);
108    exit;
109  }
110  if ($code>=400)
111  {
112    $protocol = $_SERVER["SERVER_PROTOCOL"];
113    if ( ('HTTP/1.1' != $protocol) && ('HTTP/1.0' != $protocol) )
114      $protocol = 'HTTP/1.0';
115
116    header( "$protocol $code $msg", true, $code );
117  }
118  //todo improve
119  echo $msg;
120  ilog('ERROR', $code, $msg, $_SERVER['REQUEST_URI']);
121  exit;
122}
123
124function time_step( &$step )
125{
126  $tmp = $step;
127  $step = microtime(true);
128  return intval(1000*($step - $tmp));
129}
130
131function url_to_size($s)
132{
133  $pos = strpos($s, 'x');
134  if ($pos===false)
135  {
136    return array((int)$s, (int)$s);
137  }
138  return array((int)substr($s,0,$pos), (int)substr($s,$pos+1));
139}
140
141function parse_custom_params($tokens)
142{
143  if (count($tokens)<1)
144    ierror('Empty array while parsing Sizing', 400);
145
146  $crop = 0;
147  $min_size = null;
148
149  $token = array_shift($tokens);
150  if ($token[0]=='s')
151  {
152    $size = url_to_size( substr($token,1) );
153  }
154  elseif ($token[0]=='e')
155  {
156    $crop = 1;
157    $size = $min_size = url_to_size( substr($token,1) );
158  }
159  else
160  {
161    $size = url_to_size( $token );
162    if (count($tokens)<2)
163      ierror('Sizing arr', 400);
164
165    $token = array_shift($tokens);
166    $crop = char_to_fraction($token);
167
168    $token = array_shift($tokens);
169    $min_size = url_to_size( $token );
170  }
171  return new DerivativeParams( new SizingParams($size, $crop, $min_size) );
172}
173
174function parse_request()
175{
176  global $conf, $page;
177
178  if ( $conf['question_mark_in_urls']==false and
179       isset($_SERVER["PATH_INFO"]) and !empty($_SERVER["PATH_INFO"]) )
180  {
181    $req = $_SERVER["PATH_INFO"];
182    $req = str_replace('//', '/', $req);
183    $path_count = count( explode('/', $req) );
184    $page['root_path'] = PHPWG_ROOT_PATH.str_repeat('../', $path_count-1);
185  }
186  else
187  {
188    $req = $_SERVER["QUERY_STRING"];
189    if ($pos=strpos($req, '&'))
190    {
191      $req = substr($req, 0, $pos);
192    }
193    /*foreach (array_keys($_GET) as $keynum => $key)
194    {
195      $req = $key;
196      break;
197    }*/
198    $page['root_path'] = PHPWG_ROOT_PATH;
199  }
200
201  $req = ltrim($req, '/');
202
203  foreach (preg_split('#/+#', $req) as $token)
204  {
205    preg_match($conf['sync_chars_regex'], $token) or ierror('Invalid chars in request', 400);
206  }
207
208  $page['derivative_path'] = PHPWG_ROOT_PATH.PWG_DERIVATIVE_DIR.$req;
209
210  $pos = strrpos($req, '.');
211  $pos!== false || ierror('Missing .', 400);
212  $ext = substr($req, $pos);
213  $page['derivative_ext'] = $ext;
214  $req = substr($req, 0, $pos);
215
216  $pos = strrpos($req, '-');
217  $pos!== false || ierror('Missing -', 400);
218  $deriv = substr($req, $pos+1);
219  $req = substr($req, 0, $pos);
220
221  $deriv = explode('_', $deriv);
222  foreach (ImageStdParams::get_defined_type_map() as $type => $params)
223  {
224    if ( derivative_to_url($type) == $deriv[0])
225    {
226      $page['derivative_type'] = $type;
227      $page['derivative_params'] = $params;
228      break;
229    }
230  }
231
232  if (!isset($page['derivative_type']))
233  {
234    if (derivative_to_url(IMG_CUSTOM) == $deriv[0])
235    {
236      $page['derivative_type'] = IMG_CUSTOM;
237    }
238    else
239    {
240      ierror('Unknown parsing type', 400);
241    }
242  }
243  array_shift($deriv);
244
245  if ($page['derivative_type'] == IMG_CUSTOM)
246  {
247    $params = $page['derivative_params'] = parse_custom_params($deriv);
248    ImageStdParams::apply_global($params);
249
250    if ($params->sizing->ideal_size[0] < 20 or $params->sizing->ideal_size[1] < 20)
251    {
252      ierror('Invalid size', 400);
253    }
254    if ($params->sizing->max_crop < 0 or $params->sizing->max_crop > 1)
255    {
256      ierror('Invalid crop', 400);
257    }
258    $greatest = ImageStdParams::get_by_type(IMG_XXLARGE);
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))
270  {
271    $req = './'.$req; // will be used to match #iamges.path
272  }
273  elseif (is_file(PHPWG_ROOT_PATH.'../'.$req.$ext))
274  {
275    $req = '../'.$req;
276  }
277
278  $page['src_location'] = $req.$ext;
279  $page['src_path'] = PHPWG_ROOT_PATH.$page['src_location'];
280  $page['src_url'] = $page['root_path'].$page['src_location'];
281}
282
283function try_switch_source(DerivativeParams $params, $original_mtime)
284{
285  global $page;
286  $original_size = null;
287  if (isset($page['original_size']))
288  {
289    $original_size = $page['original_size'];
290    if ($page['rotation_angle']==90 || $page['rotation_angle']==270)
291    {
292      $tmp = $original_size[0];
293      $original_size[0] = $original_size[1];
294      $original_size[1] = $tmp;
295    }
296  }
297
298  $use_watermark = $params->use_watermark;
299  if ($use_watermark)
300  {
301    if (!isset($original_size))
302      return false; // cannot really know if a watermark is required
303    $dsize = $params->compute_final_size($original_size);
304    $use_watermark = $params->will_watermark($dsize);
305    ilog($use_watermark, $dsize);
306  }
307
308  $candidates = array();
309  foreach(ImageStdParams::get_defined_type_map() as $candidate)
310  {
311    if ($candidate->type == $params->type)
312      continue;
313    if ($candidate->use_watermark != $use_watermark)
314      continue;
315    if ($candidate->max_width() < $params->max_width() || $candidate->max_height() < $params->max_height())
316      continue;
317    if ($params->sizing->max_crop==0)
318    {
319      if ($candidate->sizing->max_crop!=0)
320        continue;
321    }
322    else
323    {
324      if ($candidate->sizing->max_crop!=0)
325        continue; // this could be optimized
326      if (!isset($original_size))
327        continue;
328      $candidate_size = $candidate->compute_final_size($original_size);
329      if ($candidate_size[0] < $params->sizing->min_size[0] || $candidate_size[1] < $params->sizing->min_size[1] )
330        continue;
331    }
332    $candidates[] = $candidate;
333  }
334
335  foreach( array_reverse($candidates) as $candidate)
336  {
337    $candidate_path = $page['derivative_path'];
338    $candidate_path = str_replace( '-'.derivative_to_url($params->type), '-'.derivative_to_url($candidate->type), $candidate_path);
339    $candidate_mtime = @filemtime($candidate_path);
340    if ($candidate_mtime === false
341      || $candidate_mtime < $original_mtime
342      || $candidate_mtime < $candidate->last_mod_time)
343      continue;
344    $params->use_watermark = false;
345    $params->sharpen = min(1, $params->sharpen);
346    $page['src_path'] = $candidate_path;
347    $page['src_url'] = $page['root_path'] . substr($candidate_path, strlen(PHPWG_ROOT_PATH));
348    $page['rotation_angle'] = 0;
349                return true;
350  }
351        return false;
352}
353
354function send_derivative($expires)
355{
356  global $page;
357
358  if (isset($_GET['ajaxload']) and $_GET['ajaxload'] == 'true')
359  {
360    include_once(PHPWG_ROOT_PATH.'include/functions_cookie.inc.php');
361    include_once(PHPWG_ROOT_PATH.'include/functions_url.inc.php');
362
363    $response = new json_response();
364    $response->url = embellish_url(get_absolute_root_url().$page['derivative_path']);
365    echo json_encode($response);
366    return;
367  }
368  $fp = fopen($page['derivative_path'], 'rb');
369
370  $fstat = fstat($fp);
371  header('Last-Modified: '.gmdate('D, d M Y H:i:s', $fstat['mtime']).' GMT');
372  if ($expires!==false)
373  {
374    header('Expires: '.gmdate('D, d M Y H:i:s', $expires).' GMT');
375  }
376  header('Content-length: '.$fstat['size']);
377  header('Connection: close');
378
379  $ctype="application/octet-stream";
380  switch (strtolower($page['derivative_ext']))
381  {
382    case ".jpe": case ".jpeg": case ".jpg": $ctype="image/jpeg"; break;
383    case ".png": $ctype="image/png"; break;
384    case ".gif": $ctype="image/gif"; break;
385  }
386  header("Content-Type: $ctype");
387
388  fpassthru($fp);
389  fclose($fp);
390}
391
392class json_response
393{
394  var $url;
395}
396
397$page=array();
398$begin = $step = microtime(true);
399$timing=array();
400foreach( explode(',','load,rotate,crop,scale,sharpen,watermark,save,send') as $k )
401{
402  $timing[$k] = '';
403}
404
405include_once(PHPWG_ROOT_PATH .'include/dblayer/functions_'.$conf['dblayer'].'.inc.php');
406include_once( PHPWG_ROOT_PATH .'/include/derivative_params.inc.php');
407include_once( PHPWG_ROOT_PATH .'/include/derivative_std_params.inc.php');
408
409try
410{
411  $pwg_db_link = pwg_db_connect($conf['db_host'], $conf['db_user'],
412                                $conf['db_password'], $conf['db_base']);
413}
414catch (Exception $e)
415{
416  ilog("db error", $e->getMessage());
417}
418list($conf['derivatives']) = pwg_db_fetch_row(pwg_query('SELECT value FROM '.$prefixeTable.'config WHERE param=\'derivatives\''));
419ImageStdParams::load_from_db();
420
421
422parse_request();
423//var_export($page);
424
425$params = $page['derivative_params'];
426
427$src_mtime = @filemtime($page['src_path']);
428if ($src_mtime === false)
429{
430  ierror('Source not found', 404);
431}
432
433$need_generate = false;
434$derivative_mtime = @filemtime($page['derivative_path']);
435if ($derivative_mtime === false or
436    $derivative_mtime < $src_mtime or
437    $derivative_mtime < $params->last_mod_time)
438{
439  $need_generate = true;
440}
441
442$expires=false;
443$now = time();
444if ( isset($_GET['b']) )
445{
446  $expires = $now + 100;
447  header("Cache-control: no-store, max-age=100");
448}
449elseif ( $now > (max($src_mtime, $params->last_mod_time) + 24*3600) )
450{// somehow arbitrary - if derivative params or src didn't change for the last 24 hours, we send an expire header for several days
451  $expires = $now + 10*24*3600;
452}
453
454if (!$need_generate)
455{
456  if ( isset( $_SERVER['HTTP_IF_MODIFIED_SINCE'] )
457    and strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $derivative_mtime)
458  {// send the last mod time of the file back
459    header('Last-Modified: '.gmdate('D, d M Y H:i:s', $derivative_mtime).' GMT', true, 304);
460    header('Expires: '.gmdate('D, d M Y H:i:s', time()+10*24*3600).' GMT', true, 304);
461    exit;
462  }
463  send_derivative($expires);
464  exit;
465}
466
467include_once(PHPWG_ROOT_PATH . 'admin/include/image.class.php');
468$page['coi'] = null;
469if (strpos($page['src_location'], '/pwg_representative/')===false
470    && strpos($page['src_location'], 'themes/')===false
471    && strpos($page['src_location'], 'plugins/')===false)
472{
473  try
474  {
475    $query = '
476SELECT *
477  FROM '.$prefixeTable.'images
478  WHERE path=\''.$page['src_location'].'\'
479;';
480
481    if ( ($row=pwg_db_fetch_assoc(pwg_query($query))) )
482    {
483      if (isset($row['width']))
484      {
485        $page['original_size'] = array($row['width'],$row['height']);
486      }
487      $page['coi'] = $row['coi'];
488
489      if (!isset($row['rotation']))
490      {
491        $page['rotation_angle'] = pwg_image::get_rotation_angle($page['src_path']);
492
493        single_update(
494          $prefixeTable.'images',
495          array('rotation' => pwg_image::get_rotation_code_from_angle($page['rotation_angle'])),
496          array('id' => $row['id'])
497          );
498      }
499      else
500      {
501        $page['rotation_angle'] = pwg_image::get_rotation_angle_from_code($row['rotation']);
502      }
503    }
504    if (!$row)
505    {
506      ierror('Db file path not found', 404);
507    }
508  }
509  catch (Exception $e)
510  {
511    ilog("db error", $e->getMessage());
512  }
513}
514else
515{
516  $page['rotation_angle'] = 0;
517}
518mysql_close($pwg_db_link);
519
520if (!try_switch_source($params, $src_mtime) && $params->type==IMG_CUSTOM)
521{
522        $sharpen = 0;
523        foreach (ImageStdParams::get_defined_type_map() as $std_params)
524        {
525                $sharpen += $std_params->sharpen;
526        }
527        $params->sharpen = round($sharpen / count(ImageStdParams::get_defined_type_map()) );
528}
529
530if (!mkgetdir(dirname($page['derivative_path'])))
531{
532  ierror("dir create error", 500);
533}
534
535ignore_user_abort(true);
536@set_time_limit(0);
537
538$image = new pwg_image($page['src_path']);
539$timing['load'] = time_step($step);
540
541$changes = 0;
542
543// rotate
544if (0 != $page['rotation_angle'])
545{
546  $image->rotate($page['rotation_angle']);
547  $changes++;
548  $timing['rotate'] = time_step($step);
549}
550
551// Crop & scale
552$o_size = $d_size = array($image->get_width(),$image->get_height());
553$params->sizing->compute($o_size , $page['coi'], $crop_rect, $scaled_size );
554if ($crop_rect)
555{
556  $changes++;
557  $image->crop( $crop_rect->width(), $crop_rect->height(), $crop_rect->l, $crop_rect->t);
558  $timing['crop'] = time_step($step);
559}
560
561if ($scaled_size)
562{
563  $changes++;
564  $image->resize( $scaled_size[0], $scaled_size[1] );
565  $d_size = $scaled_size;
566  $timing['scale'] = time_step($step);
567}
568
569if ($params->sharpen)
570{
571  $changes += $image->sharpen( $params->sharpen );
572  $timing['sharpen'] = time_step($step);
573}
574
575if ($params->will_watermark($d_size))
576{
577  $wm = ImageStdParams::get_watermark();
578  $wm_image = new pwg_image(PHPWG_ROOT_PATH.$wm->file);
579  $wm_size = array($wm_image->get_width(),$wm_image->get_height());
580  if ($d_size[0]<$wm_size[0] or $d_size[1]<$wm_size[1])
581  {
582    $wm_scaling_params = SizingParams::classic($d_size[0], $d_size[1]);
583    $wm_scaling_params->compute($wm_size, null, $tmp, $wm_scaled_size);
584    $wm_size = $wm_scaled_size;
585    $wm_image->resize( $wm_scaled_size[0], $wm_scaled_size[1] );
586  }
587  $x = round( ($wm->xpos/100)*($d_size[0]-$wm_size[0]) );
588  $y = round( ($wm->ypos/100)*($d_size[1]-$wm_size[1]) );
589  if ($image->compose($wm_image, $x, $y, $wm->opacity))
590  {
591    $changes++;
592    if ($wm->xrepeat)
593    {
594      // todo
595      $pad = $wm_size[0] + max(30, round($wm_size[0]/4));
596      for($i=-$wm->xrepeat; $i<=$wm->xrepeat; $i++)
597      {
598        if (!$i) continue;
599        $x2 = $x + $i * $pad;
600        if ($x2>=0 && $x2+$wm_size[0]<$d_size[0])
601          if (!$image->compose($wm_image, $x2, $y, $wm->opacity))
602            break;
603      }
604    }
605  }
606  $wm_image->destroy();
607  $timing['watermark'] = time_step($step);
608}
609
610// no change required - redirect to source
611if (!$changes)
612{
613  header("X-i: No change");
614  ierror( $page['src_url'], 301);
615}
616
617if ($d_size[0]*$d_size[1] < 256000)
618{// strip metadata for small images
619  $image->strip();
620}
621
622$image->set_compression_quality( ImageStdParams::$quality );
623$image->write( $page['derivative_path'] );
624$image->destroy();
625$timing['save'] = time_step($step);
626
627send_derivative($expires);
628$timing['send'] = time_step($step);
629
630ilog('perf',
631  basename($page['src_path']), $o_size, $o_size[0]*$o_size[1],
632  basename($page['derivative_path']), $d_size, $d_size[0]*$d_size[1],
633  function_exists('memory_get_peak_usage') ? round( memory_get_peak_usage()/(1024*1024), 1) : '',
634  time_step($begin),
635  '|', $timing);
636?>
Note: See TracBrowser for help on using the repository browser.