source: trunk/i.php @ 12865

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

feature 2548 multisize - added a page to build missing derivatives

  • browser driven, chained ws calls to retrieve urls, visual feedback of progress through slideshow
File size: 9.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
66
67function ierror($msg, $code)
68{
69  if ($code==301 || $code==302)
70  {
71    if (ob_get_length () !== FALSE)
72    {
73      ob_clean();
74    }
75    // default url is on html format
76    $url = html_entity_decode($msg);
77    header('Request-URI: '.$url);
78    header('Content-Location: '.$url);
79    header('Location: '.$url);
80    exit;
81  }
82  if ($code>=400)
83  {
84    $protocol = $_SERVER["SERVER_PROTOCOL"];
85    if ( ('HTTP/1.1' != $protocol) && ('HTTP/1.0' != $protocol) )
86      $protocol = 'HTTP/1.0';
87
88    header( "$protocol $code $msg", true, $code );
89  }
90  //todo improve
91  echo $msg;
92  exit;
93}
94
95
96function parse_request()
97{
98  global $conf, $page;
99
100  if ( $conf['question_mark_in_urls']==false and
101       isset($_SERVER["PATH_INFO"]) and !empty($_SERVER["PATH_INFO"]) )
102  {
103    $req = $_SERVER["PATH_INFO"];
104    $req = str_replace('//', '/', $req);
105    $path_count = count( explode('/', $req) );
106    $page['root_path'] = PHPWG_ROOT_PATH.str_repeat('../', $path_count-1);
107  }
108  else
109  {
110    $req = $_SERVER["QUERY_STRING"];
111    if ($pos=strpos($req, '&'))
112    {
113      $req = substr($req, 0, $pos);
114    }
115    /*foreach (array_keys($_GET) as $keynum => $key)
116    {
117      $req = $key;
118      break;
119    }*/
120    $page['root_path'] = PHPWG_ROOT_PATH;
121  }
122
123  $req = ltrim($req, '/');
124  !preg_match('#[^a-zA-Z0-9/_.-]#', $req) or ierror('Invalid chars in request', 400);
125
126  $page['derivative_path'] = PHPWG_ROOT_PATH.PWG_DERIVATIVE_DIR.$req;
127
128  $pos = strrpos($req, '.');
129  $pos!== false || ierror('Missing .', 400);
130  $ext = substr($req, $pos);
131  $page['derivative_ext'] = $ext;
132  $req = substr($req, 0, $pos);
133
134  $pos = strrpos($req, '-');
135  $pos!== false || ierror('Missing -', 400);
136  $deriv = substr($req, $pos+1);
137  $req = substr($req, 0, $pos);
138
139  $deriv = explode('_', $deriv);
140  foreach (ImageStdParams::get_defined_type_map() as $type => $params)
141  {
142    if ( derivative_to_url($type) == $deriv[0])
143    {
144      $page['derivative_type'] = $type;
145      $page['derivative_params'] = $params;
146      break;
147    }
148  }
149
150  if (!isset($page['derivative_type']))
151  {
152    if (derivative_to_url(IMG_CUSTOM) == $deriv[0])
153    {
154      $page['derivative_type'] = IMG_CUSTOM;
155    }
156    else
157    {
158      ierror('Unknown parsing type', 400);
159    }
160  }
161  array_shift($deriv);
162
163  $page['coi'] = '';
164  if (count($deriv) && $deriv[0][0]=='c' && $deriv[0][1]=='i')
165  {
166    $page['coi'] = substr(array_shift($deriv), 2);
167    preg_match('#^[a-z]{4}$#', $page['coi']) or ierror('Invalid center of interest', 400);
168  }
169
170  if ($page['derivative_type'] == IMG_CUSTOM)
171  {
172    try
173    {
174      $params = $page['derivative_params'] = DerivativeParams::from_url_tokens($deriv);
175    }
176    catch (Exception $e)
177    {
178      ierror($e->getMessage(), 400);
179    }
180    if ($params->sizing->ideal_size[0] < 20 or $params->sizing->ideal_size[1] < 20)
181    {
182      ierror('Invalid size', 400);
183    }
184    if ($params->sizing->max_crop < 0 or $params->sizing->max_crop > 1)
185    {
186      ierror('Invalid crop', 400);
187    }
188  }
189
190  if ($req[0]!='g' && $req[0]!='u')
191    $req = '../'.$req;
192
193  $page['src_location'] = $req.$ext;
194  $page['src_path'] = PHPWG_ROOT_PATH.$page['src_location'];
195  $page['src_url'] = $page['root_path'].$page['src_location'];
196}
197
198
199function send_derivative($expires)
200{
201  global $page;
202  $fp = fopen($page['derivative_path'], 'rb');
203
204  $fstat = fstat($fp);
205  header('Last-Modified: '.gmdate('D, d M Y H:i:s', $fstat['mtime']).' GMT');
206  if ($expires!==false)
207  {
208    header('Expires: '.gmdate('D, d M Y H:i:s', $expires).' GMT');
209  }
210  header('Content-length: '.$fstat['size']);
211  header('Connection: close');
212
213  $ctype="application/octet-stream";
214  switch (strtolower($page['derivative_ext']))
215  {
216    case ".jpe": case ".jpeg": case ".jpg": $ctype="image/jpeg"; break;
217    case ".png": $ctype="image/png"; break;
218    case ".gif": $ctype="image/gif"; break;
219  }
220  header("Content-Type: $ctype");
221
222  fpassthru($fp);
223  fclose($fp);
224}
225
226
227$page=array();
228
229include_once( PHPWG_ROOT_PATH .'/include/derivative_params.inc.php');
230include_once( PHPWG_ROOT_PATH .'/include/derivative_std_params.inc.php');
231
232ImageStdParams::load_from_file();
233
234
235parse_request();
236//var_export($page);
237
238$params = $page['derivative_params'];
239
240$src_mtime = @filemtime($page['src_path']);
241if ($src_mtime === false)
242{
243  ierror('Source not found', 404);
244}
245
246$need_generate = false;
247$derivative_mtime = @filemtime($page['derivative_path']);
248if ($derivative_mtime === false or
249    $derivative_mtime < $src_mtime or
250    $derivative_mtime < $params->last_mod_time)
251{
252  $need_generate = true;
253}
254
255$expires=false;
256$now = time();
257if ( isset($_GET['b']) )
258{
259  $expires = $now + 100;
260  header("Cache-control: no-store, max-age=100");
261}
262elseif ( $now > (max($src_mtime, $params->last_mod_time) + 24*3600) )
263{// somehow arbitrary - if derivative params or src didn't change for the last 24 hours, we send an expire header for several days
264  $expires = $now + 10*24*3600;
265}
266
267if (!$need_generate)
268{
269  if ( isset( $_SERVER['HTTP_IF_MODIFIED_SINCE'] )
270    and strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $derivative_mtime)
271  {// send the last mod time of the file back
272    header('Last-Modified: '.gmdate('D, d M Y H:i:s', $derivative_mtime).' GMT', true, 304);
273    header('Expires: '.gmdate('D, d M Y H:i:s', time()+10*24*3600).' GMT', true, 304);
274    exit;
275  }
276  send_derivative($expires);
277}
278
279if (!mkgetdir(dirname($page['derivative_path'])))
280{
281  ierror("dir create error", 500);
282}
283
284include_once(PHPWG_ROOT_PATH . 'admin/include/image.class.php');
285
286ignore_user_abort(true);
287set_time_limit(0);
288
289$image = new pwg_image($page['src_path']);
290
291$changes = 0;
292
293// todo rotate
294
295// Crop & scale
296$o_size = $d_size = array($image->get_width(),$image->get_height());
297$params->sizing->compute($o_size , $page['coi'], $crop_rect, $scaled_size );
298if ($crop_rect)
299{
300  $changes++;
301  $image->crop( $crop_rect->width(), $crop_rect->height(), $crop_rect->l, $crop_rect->t);
302}
303
304if ($scaled_size)
305{
306  $changes++;
307  $image->resize( $scaled_size[0], $scaled_size[1] );
308  $d_size = $scaled_size;
309}
310
311if ($params->sharpen)
312{
313  $changes += $image->sharpen( $params->sharpen );
314}
315
316if ($params->use_watermark)
317{
318  $wm = ImageStdParams::get_watermark();
319  $wm_image = new pwg_image(PHPWG_ROOT_PATH.$wm->file);
320  $wm_size = array($wm_image->get_width(),$wm_image->get_height());
321  if ($d_size[0]<$wm_size[0] or $d_size[1]<$wm_size[1])
322  {
323    $wm_scaling_params = SizingParams::classic($d_size[0], $d_size[1]);
324    $wm_scaling_params->compute($wm_size, null, $tmp, $wm_scaled_size);
325    $wm_size = $wm_scaled_size;
326    $wm_image->resize( $wm_scaled_size[0], $wm_scaled_size[1] );
327  }
328  $x = round( ($wm->xpos/100)*($d_size[0]-$wm_size[0]) );
329  $y = round( ($wm->ypos/100)*($d_size[1]-$wm_size[1]) );
330  if ($image->compose($wm_image, $x, $y, $wm->opacity))
331  {
332    $changes++;
333    if ($wm->xrepeat)
334    {
335      // todo
336      $pad = $wm_size[0] + max(30, round($wm_size[0]/4));
337      for($i=-$wm->xrepeat; $i<=$wm->xrepeat; $i++)
338      {
339        if (!$i) continue;
340        $x2 = $x + $i * $pad;
341        if ($x2>=0 && $x2+$wm_size[0]<$d_size[0])
342          if (!$image->compose($wm_image, $x2, $y, $wm->opacity))
343            break;
344      }
345    }
346  }
347  $wm_image->destroy();
348}
349
350// no change required - redirect to source
351if (!$changes)
352{
353  header("X-i: No change");
354  ierror( $page['src_url'], 301);
355}
356
357$image->set_compression_quality( $params->quality );
358$image->write( $page['derivative_path'] );
359$image->destroy();
360
361send_derivative($expires);
362?>
Note: See TracBrowser for help on using the repository browser.