source: trunk/i.php @ 15384

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

multi size:

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