source: trunk/i.php @ 12829

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

feature 2541 multisize

  • admin GUI for choosing derivative parameters + persistence
File size: 8.2 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    /*foreach (array_keys($_GET) as $keynum => $key)
112    {
113      $req = $key;
114      break;
115    }*/
116    $page['root_path'] = PHPWG_ROOT_PATH;
117  }
118
119  $req = ltrim($req, '/');
120  !preg_match('#[^a-zA-Z0-9/_.-]#', $req) or ierror('Invalid chars in request', 400);
121
122  $page['derivative_path'] = PHPWG_ROOT_PATH.PWG_DERIVATIVE_DIR.$req;
123
124  $pos = strrpos($req, '.');
125  $pos!== false || ierror('Missing .', 400);
126  $ext = substr($req, $pos);
127  $page['derivative_ext'] = $ext;
128  $req = substr($req, 0, $pos);
129
130  $pos = strrpos($req, '-');
131  $pos!== false || ierror('Missing -', 400);
132  $deriv = substr($req, $pos+1);
133  $req = substr($req, 0, $pos);
134
135  $deriv = explode('_', $deriv);
136  foreach (ImageStdParams::get_defined_type_map() as $type => $params)
137  {
138    if ( derivative_to_url($type) == $deriv[0])
139    {
140      $page['derivative_type'] = $type;
141      $page['derivative_params'] = $params;
142      break;
143    }
144  }
145
146  if (!isset($page['derivative_type']))
147  {
148    if (derivative_to_url(IMG_CUSTOM) == $deriv[0])
149    {
150      $page['derivative_type'] = IMG_CUSTOM;
151    }
152    else
153    {
154      ierror('Unknown parsing type', 400);
155    }
156  }
157  array_shift($deriv);
158
159  $page['coi'] = '';
160  if (count($deriv) && $deriv[0][0]=='c' && $deriv[0][1]=='i')
161  {
162    $page['coi'] = substr(array_shift($deriv), 2);
163    preg_match('#^[a-z]{4}$#', $page['coi']) or ierror('Invalid center of interest', 400);
164  }
165
166  if ($page['derivative_type'] == IMG_CUSTOM)
167  {
168    try
169    {
170      $page['derivative_params'] = DerivativeParams::from_url_tokens($deriv);
171    }
172    catch (Exception $e)
173    {
174      ierror($e->getMessage(), 400);
175    }
176  }
177
178  if ($req[0]!='g' && $req[0]!='u')
179    $req = '../'.$req;
180
181  $page['src_location'] = $req.$ext;
182  $page['src_path'] = PHPWG_ROOT_PATH.$page['src_location'];
183  $page['src_url'] = $page['root_path'].$page['src_location'];
184}
185
186
187function send_derivative($expires)
188{
189  global $page;
190  $fp = fopen($page['derivative_path'], 'rb');
191
192  $fstat = fstat($fp);
193  header('Last-Modified: '.gmdate('D, d M Y H:i:s', $fstat['mtime']).' GMT');
194  if ($expires!==false)
195  {
196    header('Expires: '.gmdate('D, d M Y H:i:s', $expires).' GMT');
197  }
198  header('Content-length: '.$fstat['size']);
199  header('Connection: close');
200
201  $ctype="application/octet-stream";
202  switch (strtolower($page['derivative_ext']))
203  {
204    case ".jpe": case ".jpeg": case ".jpg": $ctype="image/jpeg"; break;
205    case ".png": $ctype="image/png"; break;
206    case ".gif": $ctype="image/gif"; break;
207  }
208  header("Content-Type: $ctype");
209
210  fpassthru($fp);
211  fclose($fp);
212}
213
214
215$page=array();
216
217include_once( PHPWG_ROOT_PATH .'/include/derivative_params.inc.php');
218include_once( PHPWG_ROOT_PATH .'/include/derivative_std_params.inc.php');
219
220ImageStdParams::load_from_file();
221
222
223parse_request();
224//var_export($page);
225
226$params = $page['derivative_params'];
227if ($params->sizing->ideal_size[0] < 20 or $params->sizing->ideal_size[1] < 20)
228{
229  ierror('Invalid size', 400);
230}
231if ($params->sizing->max_crop < 0 or $params->sizing->max_crop > 1)
232{
233  ierror('Invalid crop', 400);
234}
235
236$src_mtime = @filemtime($page['src_path']);
237if ($src_mtime === false)
238{
239  ierror('Source not found', 404);
240}
241
242$need_generate = false;
243$derivative_mtime = @filemtime($page['derivative_path']);
244if ($derivative_mtime === false or
245    $derivative_mtime < $src_mtime or
246    $derivative_mtime < $params->last_mod_time)
247{
248  $need_generate = true;
249}
250
251$expires=false;
252$now = time();
253if ( $now > (max($src_mtime, $params->last_mod_time) + 24*3600) )
254{// somehow arbitrary - if derivative params or src didn't change for the last 24 hours, we send an expire header for several days
255  $expires = $now + 10*24*3600;
256}
257
258if (!$need_generate)
259{
260  if ( isset( $_SERVER['HTTP_IF_MODIFIED_SINCE'] )
261    and strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $derivative_mtime)
262  {// send the last mod time of the file back
263    header('Last-Modified: '.gmdate('D, d M Y H:i:s', $derivative_mtime).' GMT', true, 304);
264    header('Expires: '.gmdate('D, d M Y H:i:s', time()+10*24*3600).' GMT', true, 304);
265    exit;
266  }
267  send_derivative($expires);
268}
269
270
271include_once(PHPWG_ROOT_PATH . 'admin/include/image.class.php');
272$image = new pwg_image($page['src_path']);
273
274if (!mkgetdir(dirname($page['derivative_path'])))
275{
276  ierror("dir create error", 500);
277}
278
279$changes = 0;
280
281// todo rotate
282
283// Crop & scale
284$params->sizing->compute( array($image->get_width(),$image->get_height()), $page['coi'], $crop_rect, $scale_width );
285if ($crop_rect)
286{
287  $changes++;
288  $image->crop( $crop_rect->width(), $crop_rect->height(), $crop_rect->l, $crop_rect->t);
289}
290
291if ($scale_width)
292{
293  $changes++;
294  $image->resize( $scale_width[0], $scale_width[1] );
295}
296
297// no change required - redirect to source
298if (!$changes)
299{
300  header("X-i: No change");
301  ierror( $page['src_url'], 301);
302}
303
304$image->write( $page['derivative_path'] );
305$image->destroy();
306
307send_derivative($expires);
308?>
Note: See TracBrowser for help on using the repository browser.