source: trunk/i.php @ 13465

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

Multisize
Load thumbnails with ajax.

File size: 14.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
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
323  if (isset($_GET['ajaxload']) and $_GET['ajaxload'] == 'true')
324  {
325    include_once(PHPWG_ROOT_PATH.'include/functions_cookie.inc.php');
326    include_once(PHPWG_ROOT_PATH.'include/functions_url.inc.php');
327
328    $response = new json_response();
329    $response->url = embellish_url(get_absolute_root_url().$page['derivative_path']);
330    echo json_encode($response);
331    return;
332  }
333  $fp = fopen($page['derivative_path'], 'rb');
334
335  $fstat = fstat($fp);
336  header('Last-Modified: '.gmdate('D, d M Y H:i:s', $fstat['mtime']).' GMT');
337  if ($expires!==false)
338  {
339    header('Expires: '.gmdate('D, d M Y H:i:s', $expires).' GMT');
340  }
341  header('Content-length: '.$fstat['size']);
342  header('Connection: close');
343
344  $ctype="application/octet-stream";
345  switch (strtolower($page['derivative_ext']))
346  {
347    case ".jpe": case ".jpeg": case ".jpg": $ctype="image/jpeg"; break;
348    case ".png": $ctype="image/png"; break;
349    case ".gif": $ctype="image/gif"; break;
350  }
351  header("Content-Type: $ctype");
352
353  fpassthru($fp);
354  fclose($fp);
355}
356
357class json_response
358{
359  var $url;
360}
361
362$page=array();
363$begin = $step = microtime(true);
364$timing=array();
365foreach( explode(',','load,rotate,crop,scale,sharpen,watermark,save,send') as $k )
366{
367  $timing[$k] = '';
368}
369
370include_once( PHPWG_ROOT_PATH .'/include/derivative_params.inc.php');
371include_once( PHPWG_ROOT_PATH .'/include/derivative_std_params.inc.php');
372
373ImageStdParams::load_from_file();
374
375
376parse_request();
377//var_export($page);
378
379$params = $page['derivative_params'];
380
381$src_mtime = @filemtime($page['src_path']);
382if ($src_mtime === false)
383{
384  ierror('Source not found', 404);
385}
386
387$need_generate = false;
388$derivative_mtime = @filemtime($page['derivative_path']);
389if ($derivative_mtime === false or
390    $derivative_mtime < $src_mtime or
391    $derivative_mtime < $params->last_mod_time)
392{
393  $need_generate = true;
394}
395
396$expires=false;
397$now = time();
398if ( isset($_GET['b']) )
399{
400  $expires = $now + 100;
401  header("Cache-control: no-store, max-age=100");
402}
403elseif ( $now > (max($src_mtime, $params->last_mod_time) + 24*3600) )
404{// somehow arbitrary - if derivative params or src didn't change for the last 24 hours, we send an expire header for several days
405  $expires = $now + 10*24*3600;
406}
407
408if (!$need_generate)
409{
410  if ( isset( $_SERVER['HTTP_IF_MODIFIED_SINCE'] )
411    and strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $derivative_mtime)
412  {// send the last mod time of the file back
413    header('Last-Modified: '.gmdate('D, d M Y H:i:s', $derivative_mtime).' GMT', true, 304);
414    header('Expires: '.gmdate('D, d M Y H:i:s', time()+10*24*3600).' GMT', true, 304);
415    exit;
416  }
417  send_derivative($expires);
418  exit;
419}
420
421$page['coi'] = null;
422if (strpos($page['src_location'], '/pwg_representative/')===false
423    && strpos($page['src_location'], 'themes/')===false
424    && strpos($page['src_location'], 'plugins/')===false)
425{
426  @include(PHPWG_ROOT_PATH.PWG_LOCAL_DIR .'config/database.inc.php');
427  include(PHPWG_ROOT_PATH .'include/dblayer/functions_'.$conf['dblayer'].'.inc.php');
428  try
429  {
430    $pwg_db_link = pwg_db_connect($conf['db_host'], $conf['db_user'],
431                                  $conf['db_password'], $conf['db_base']);
432    $query = 'SELECT coi, width, height FROM '.$prefixeTable.'images WHERE path=\''.$page['src_location'].'\'';
433    if ( ($row=pwg_db_fetch_assoc(pwg_query($query))) )
434    {
435      if (isset($row['width']))
436      {
437        $page['original_size'] = array($row['width'],$row['height']);
438      }
439      $page['coi'] = $row['coi'];
440    }
441    mysql_close($pwg_db_link);
442    if (!$row)
443    {
444      ierror('Db file path not found', 404);
445    }
446  }
447  catch (Exception $e)
448  {
449    ilog("db error", $e->getMessage());
450  }
451}
452
453try_switch_source($params, $src_mtime);
454
455if (!mkgetdir(dirname($page['derivative_path'])))
456{
457  ierror("dir create error", 500);
458}
459
460include_once(PHPWG_ROOT_PATH . 'admin/include/image.class.php');
461
462ignore_user_abort(true);
463set_time_limit(0);
464
465$image = new pwg_image($page['src_path']);
466$timing['load'] = time_step($step);
467
468$changes = 0;
469
470// todo rotate
471
472// Crop & scale
473$o_size = $d_size = array($image->get_width(),$image->get_height());
474$params->sizing->compute($o_size , $page['coi'], $crop_rect, $scaled_size );
475if ($crop_rect)
476{
477  $changes++;
478  $image->crop( $crop_rect->width(), $crop_rect->height(), $crop_rect->l, $crop_rect->t);
479  $timing['crop'] = time_step($step);
480}
481
482if ($scaled_size)
483{
484  $changes++;
485  $image->resize( $scaled_size[0], $scaled_size[1] );
486  $d_size = $scaled_size;
487  $timing['scale'] = time_step($step);
488}
489
490if ($params->sharpen)
491{
492  $changes += $image->sharpen( $params->sharpen );
493  $timing['sharpen'] = time_step($step);
494}
495
496if ($params->use_watermark)
497{
498  $wm = ImageStdParams::get_watermark();
499  $wm_image = new pwg_image(PHPWG_ROOT_PATH.$wm->file);
500  $wm_size = array($wm_image->get_width(),$wm_image->get_height());
501  if ($d_size[0]<$wm_size[0] or $d_size[1]<$wm_size[1])
502  {
503    $wm_scaling_params = SizingParams::classic($d_size[0], $d_size[1]);
504    $wm_scaling_params->compute($wm_size, null, $tmp, $wm_scaled_size);
505    $wm_size = $wm_scaled_size;
506    $wm_image->resize( $wm_scaled_size[0], $wm_scaled_size[1] );
507  }
508  $x = round( ($wm->xpos/100)*($d_size[0]-$wm_size[0]) );
509  $y = round( ($wm->ypos/100)*($d_size[1]-$wm_size[1]) );
510  if ($image->compose($wm_image, $x, $y, $wm->opacity))
511  {
512    $changes++;
513    if ($wm->xrepeat)
514    {
515      // todo
516      $pad = $wm_size[0] + max(30, round($wm_size[0]/4));
517      for($i=-$wm->xrepeat; $i<=$wm->xrepeat; $i++)
518      {
519        if (!$i) continue;
520        $x2 = $x + $i * $pad;
521        if ($x2>=0 && $x2+$wm_size[0]<$d_size[0])
522          if (!$image->compose($wm_image, $x2, $y, $wm->opacity))
523            break;
524      }
525    }
526  }
527  $wm_image->destroy();
528  $timing['watermark'] = time_step($step);
529}
530
531// no change required - redirect to source
532if (!$changes)
533{
534  header("X-i: No change");
535  ierror( $page['src_url'], 301);
536}
537
538if ($d_size[0]*$d_size[1] < 256000)
539{// strip metadata for small images
540  $image->strip();
541}
542$image->set_compression_quality( $params->quality );
543$image->write( $page['derivative_path'] );
544$image->destroy();
545$timing['save'] = time_step($step);
546
547send_derivative($expires);
548$timing['send'] = time_step($step);
549
550ilog('perf',
551  basename($page['src_path']), $o_size, $o_size[0]*$o_size[1],
552  basename($page['derivative_path']), $d_size, $d_size[0]*$d_size[1],
553  function_exists('memory_get_peak_usage') ? round( memory_get_peak_usage()/(1024*1024), 1) : '',
554  time_step($begin),
555  '|', $timing);
556?>
Note: See TracBrowser for help on using the repository browser.