source: trunk/admin/include/functions_upload.inc.php @ 8227

Last change on this file since 8227 was 8227, checked in by plg, 13 years ago

feature 2077 added: when ImageMagick is active, ability to remove or resize
the high definition version of the photo.

File size: 13.9 KB
Line 
1<?php
2// TODO
3// * check md5sum (already exists?)
4
5include_once(PHPWG_ROOT_PATH.'include/common.inc.php');
6include_once(PHPWG_ROOT_PATH.'include/ws_functions.inc.php');
7include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
8
9// Here is the plan
10//
11// 1) move uploaded file to upload/2010/01/22/20100122003814-449ada00.jpg
12//
13// 2) if taller than max_height or wider than max_width, move to pwg_high
14//    + web sized creation
15//
16// 3) thumbnail creation from web sized
17//
18// 4) register in database
19
20// add default event handler for image and thumbnail resize
21add_event_handler('upload_image_resize', 'pwg_image_resize', EVENT_HANDLER_PRIORITY_NEUTRAL, 7);
22add_event_handler('upload_thumbnail_resize', 'pwg_image_resize', EVENT_HANDLER_PRIORITY_NEUTRAL, 7);
23
24function add_uploaded_file($source_filepath, $original_filename=null, $categories=null, $level=null)
25{
26  global $conf;
27
28  // current date
29  list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();'));
30  list($year, $month, $day) = preg_split('/[^\d]/', $dbnow, 4);
31 
32  // upload directory hierarchy
33  $upload_dir = sprintf(
34    PHPWG_ROOT_PATH.$conf['upload_dir'].'/%s/%s/%s',
35    $year,
36    $month,
37    $day
38    );
39
40  // compute file path
41  $md5sum = md5_file($source_filepath);
42  $date_string = preg_replace('/[^\d]/', '', $dbnow);
43  $random_string = substr($md5sum, 0, 8);
44  $filename_wo_ext = $date_string.'-'.$random_string;
45  $file_path = $upload_dir.'/'.$filename_wo_ext.'.';
46
47  list($width, $height, $type) = getimagesize($source_filepath);
48  if (IMAGETYPE_PNG == $type)
49  {
50    $file_path.= 'png';
51  }
52  else
53  {
54    $file_path.= 'jpg';
55  }
56
57  prepare_directory($upload_dir);
58  if (is_uploaded_file($source_filepath))
59  {
60    move_uploaded_file($source_filepath, $file_path);
61  }
62  else
63  {
64    copy($source_filepath, $file_path);
65  }
66
67  if ($conf['upload_form_websize_resize']
68      and need_resize($file_path, $conf['upload_form_websize_maxwidth'], $conf['upload_form_websize_maxheight']))
69  {
70    $high_path = file_path_for_type($file_path, 'high');
71    $high_dir = dirname($high_path);
72    prepare_directory($high_dir);
73   
74    rename($file_path, $high_path);
75    $high_infos = pwg_image_infos($high_path);
76   
77    trigger_event(
78      'upload_image_resize',
79      false,
80      $high_path,
81      $file_path,
82      $conf['upload_form_websize_maxwidth'],
83      $conf['upload_form_websize_maxheight'],
84      $conf['upload_form_websize_quality'],
85      false
86      );
87
88    if (is_imagick())
89    {
90      if ($conf['upload_form_hd_keep'])
91      {
92        $need_resize = need_resize($high_path, $conf['upload_form_hd_maxwidth'], $conf['upload_form_hd_maxheight']);
93       
94        if ($conf['upload_form_hd_resize'] and $need_resize)
95        {
96          pwg_image_resize(
97            false,
98            $high_path,
99            $high_path,
100            $conf['upload_form_hd_maxwidth'],
101            $conf['upload_form_hd_maxheight'],
102            $conf['upload_form_hd_quality'],
103            false
104            );
105          $high_infos = pwg_image_infos($high_path);
106        }
107      }
108      else
109      {
110        unlink($high_path);
111        $high_infos = null;
112      }
113    }
114  }
115
116  $file_infos = pwg_image_infos($file_path);
117 
118  $thumb_path = file_path_for_type($file_path, 'thumb');
119  $thumb_dir = dirname($thumb_path);
120  prepare_directory($thumb_dir);
121 
122  trigger_event(
123    'upload_thumbnail_resize',
124    false,
125    $file_path,
126    $thumb_path,
127    $conf['upload_form_thumb_maxwidth'],
128    $conf['upload_form_thumb_maxheight'],
129    $conf['upload_form_thumb_quality'],
130    true
131    );
132 
133  $thumb_infos = pwg_image_infos($thumb_path);
134
135  // database registration
136  $insert = array(
137    'file' => pwg_db_real_escape_string(isset($original_filename) ? $original_filename : basename($file_path)),
138    'date_available' => $dbnow,
139    'tn_ext' => 'jpg',
140    'path' => preg_replace('#^'.preg_quote(PHPWG_ROOT_PATH).'#', '', $file_path),
141    'filesize' => $file_infos['filesize'],
142    'width' => $file_infos['width'],
143    'height' => $file_infos['height'],
144    'md5sum' => $md5sum,
145    );
146
147  if (isset($high_infos))
148  {
149    $insert['has_high'] = 'true';
150    $insert['high_filesize'] = $high_infos['filesize'];
151  }
152
153  if (isset($level))
154  {
155    $insert['level'] = $level;
156  }
157 
158  mass_inserts(
159    IMAGES_TABLE,
160    array_keys($insert),
161    array($insert)
162    );
163 
164  $image_id = pwg_db_insert_id(IMAGES_TABLE);
165
166  if (isset($categories) and count($categories) > 0)
167  {
168    associate_images_to_categories(
169      array($image_id),
170      $categories
171      );
172  }
173 
174  // update metadata from the uploaded file (exif/iptc)
175  if ($conf['use_exif'] and !function_exists('read_exif_data'))
176  {
177    $conf['use_exif'] = false;
178  }
179  update_metadata(array($image_id=>$file_path));
180 
181  invalidate_user_cache();
182
183  return $image_id;
184}
185
186function prepare_directory($directory)
187{
188  if (!is_dir($directory)) {
189    if (substr(PHP_OS, 0, 3) == 'WIN')
190    {
191      $directory = str_replace('/', DIRECTORY_SEPARATOR, $directory);
192    }
193    umask(0000);
194    $recursive = true;
195    if (!@mkdir($directory, 0777, $recursive))
196    {
197      die('[prepare_directory] cannot create directory "'.$directory.'"');
198    }
199  }
200
201  if (!is_writable($directory))
202  {
203    // last chance to make the directory writable
204    @chmod($directory, 0777);
205
206    if (!is_writable($directory))
207    {
208      die('[prepare_directory] directory "'.$directory.'" has no write access');
209    }
210  }
211
212  secure_directory($directory);
213}
214
215function need_resize($image_filepath, $max_width, $max_height)
216{
217  // TODO : the resize check should take the orientation into account. If a
218  // rotation must be applied to the resized photo, then we should test
219  // invert width and height.
220  list($width, $height) = getimagesize($image_filepath);
221 
222  if ($width > $max_width or $height > $max_height)
223  {
224    return true;
225  }
226
227  return false;
228}
229
230function get_resize_dimensions($width, $height, $max_width, $max_height, $rotation=null)
231{
232  $rotate_for_dimensions = false;
233  if (isset($rotation) and in_array(abs($rotation), array(90, 270)))
234  {
235    $rotate_for_dimensions = true;
236  }
237
238  if ($rotate_for_dimensions)
239  {
240    list($width, $height) = array($height, $width);
241  }
242 
243  $ratio_width  = $width / $max_width;
244  $ratio_height = $height / $max_height;
245 
246  // maximal size exceeded ?
247  if ($ratio_width > 1 or $ratio_height > 1)
248  {
249    if ($ratio_width < $ratio_height)
250    { 
251      $destination_width = ceil($width / $ratio_height);
252      $destination_height = $max_height;
253    }
254    else
255    { 
256      $destination_width = $max_width; 
257      $destination_height = ceil($height / $ratio_width);
258    }
259  }
260
261  if ($rotate_for_dimensions)
262  {
263    list($destination_width, $destination_height) = array($destination_height, $destination_width);
264  }
265 
266  return array(
267    'width' => $destination_width,
268    'height'=> $destination_height,
269    );
270}
271
272function pwg_image_resize($result, $source_filepath, $destination_filepath, $max_width, $max_height, $quality, $strip_metadata=false)
273{
274  if ($result !== false)
275  {
276    //someone hooked us - so we skip
277    return $result;
278  }
279
280  if (is_imagick())
281  {
282    return pwg_image_resize_im($source_filepath, $destination_filepath, $max_width, $max_height, $quality, $strip_metadata);
283  }
284  else
285  {
286    return pwg_image_resize_gd($source_filepath, $destination_filepath, $max_width, $max_height, $quality);
287  }
288}
289
290function pwg_image_resize_gd($source_filepath, $destination_filepath, $max_width, $max_height, $quality)
291{
292  if (!function_exists('gd_info'))
293  {
294    return false;
295  }
296
297  // extension of the picture filename
298  $extension = strtolower(get_extension($source_filepath));
299
300  $source_image = null;
301  if (in_array($extension, array('jpg', 'jpeg')))
302  {
303    $source_image = imagecreatefromjpeg($source_filepath);
304  }
305  else if ($extension == 'png')
306  {
307    $source_image = imagecreatefrompng($source_filepath);
308  }
309  else
310  {
311    die('unsupported file extension');
312  }
313
314  $rotation = null;
315  if (function_exists('imagerotate'))
316  {
317    $rotation = get_rotation_angle($source_filepath);
318  }
319 
320  // width/height
321  $source_width  = imagesx($source_image); 
322  $source_height = imagesy($source_image);
323 
324  $resize_dimensions = get_resize_dimensions($source_width, $source_height, $max_width, $max_height, $rotation);
325
326  // testing on height is useless in theory: if width is unchanged, there
327  // should be no resize, because width/height ratio is not modified.
328  if ($resize_dimensions['width'] == $source_width and $resize_dimensions['height'] == $source_height)
329  {
330    // the image doesn't need any resize! We just copy it to the destination
331    copy($source_filepath, $destination_filepath);
332    return true;
333  }
334 
335  $destination_image = imagecreatetruecolor($resize_dimensions['width'], $resize_dimensions['height']);
336 
337  imagecopyresampled(
338    $destination_image,
339    $source_image,
340    0,
341    0,
342    0,
343    0,
344    $resize_dimensions['width'],
345    $resize_dimensions['height'],
346    $source_width,
347    $source_height
348    );
349
350  // rotation occurs only on resized photo to avoid useless memory use
351  if (isset($rotation))
352  {
353    $destination_image = imagerotate($destination_image, $rotation, 0);
354  }
355 
356  $extension = strtolower(get_extension($destination_filepath));
357  if ($extension == 'png')
358  {
359    imagepng($destination_image, $destination_filepath);
360  }
361  else
362  {
363    imagejpeg($destination_image, $destination_filepath, $quality);
364  }
365  // freeing memory ressources
366  imagedestroy($source_image);
367  imagedestroy($destination_image);
368
369  // everything should be OK if we are here!
370  return true;
371}
372
373function pwg_image_resize_im($source_filepath, $destination_filepath, $max_width, $max_height, $quality, $strip_metadata=false)
374{
375  // extension of the picture filename
376  $extension = strtolower(get_extension($source_filepath));
377  if (!in_array($extension, array('jpg', 'jpeg', 'png')))
378  {
379    die('[Imagick] unsupported file extension');
380  }
381
382  $image = new Imagick($source_filepath);
383
384  $rotation = null;
385  if (function_exists('imagerotate'))
386  {
387    $rotation = get_rotation_angle($source_filepath);
388  }
389 
390  // width/height
391  $source_width  = $image->getImageWidth();
392  $source_height = $image->getImageHeight();
393 
394  $resize_dimensions = get_resize_dimensions($source_width, $source_height, $max_width, $max_height, $rotation);
395
396  // testing on height is useless in theory: if width is unchanged, there
397  // should be no resize, because width/height ratio is not modified.
398  if ($resize_dimensions['width'] == $source_width and $resize_dimensions['height'] == $source_height)
399  {
400    // the image doesn't need any resize! We just copy it to the destination
401    copy($source_filepath, $destination_filepath);
402    return true;
403  }
404
405  $image->setImageCompressionQuality($quality);
406  $image->setInterlaceScheme(Imagick::INTERLACE_LINE);
407 
408  if ($strip_metadata)
409  {
410    // we save a few kilobytes. For example a thumbnail with metadata
411    // weights 25KB, without metadata 7KB.
412    $image->stripImage();
413  }
414 
415  $image->resizeImage($resize_dimensions['width'], $resize_dimensions['height'], Imagick::FILTER_LANCZOS, 0.9);
416
417  if (isset($rotation))
418  {
419    $image->rotateImage(new ImagickPixel(), -$rotation);
420    $image->setImageOrientation(Imagick::ORIENTATION_TOPLEFT);
421  }
422
423  $image->writeImage($destination_filepath);
424  $image->destroy();
425
426  // everything should be OK if we are here!
427  return true;
428}
429
430function get_rotation_angle($source_filepath)
431{
432  $rotation = null;
433 
434  $exif = exif_read_data($source_filepath);
435 
436  if (isset($exif['Orientation']) and preg_match('/^\s*(\d)/', $exif['Orientation'], $matches))
437  {
438    $orientation = $matches[1];
439    if (in_array($orientation, array(3, 4)))
440    {
441      $rotation = 180;
442    }
443    elseif (in_array($orientation, array(5, 6)))
444    {
445      $rotation = 270;
446    }
447    elseif (in_array($orientation, array(7, 8)))
448    {
449      $rotation = 90;
450    }
451  }
452
453  return $rotation;
454}
455
456function pwg_image_infos($path)
457{
458  list($width, $height) = getimagesize($path);
459  $filesize = floor(filesize($path)/1024);
460 
461  return array(
462    'width'  => $width,
463    'height' => $height,
464    'filesize' => $filesize,
465    );
466}
467
468function is_valid_image_extension($extension)
469{
470  return in_array(strtolower($extension), array('jpg', 'jpeg', 'png'));
471}
472
473function file_upload_error_message($error_code)
474{
475  switch ($error_code) {
476    case UPLOAD_ERR_INI_SIZE:
477      return sprintf(
478        l10n('The uploaded file exceeds the upload_max_filesize directive in php.ini: %sB'),
479        get_ini_size('upload_max_filesize', false)
480        );
481    case UPLOAD_ERR_FORM_SIZE:
482      return l10n('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form');
483    case UPLOAD_ERR_PARTIAL:
484      return l10n('The uploaded file was only partially uploaded');
485    case UPLOAD_ERR_NO_FILE:
486      return l10n('No file was uploaded');
487    case UPLOAD_ERR_NO_TMP_DIR:
488      return l10n('Missing a temporary folder');
489    case UPLOAD_ERR_CANT_WRITE:
490      return l10n('Failed to write file to disk');
491    case UPLOAD_ERR_EXTENSION:
492      return l10n('File upload stopped by extension');
493    default:
494      return l10n('Unknown upload error');
495  }
496}
497
498function get_ini_size($ini_key, $in_bytes=true)
499{
500  $size = ini_get($ini_key);
501
502  if ($in_bytes)
503  {
504    $size = convert_shortand_notation_to_bytes($size);
505  }
506 
507  return $size;
508}
509
510function convert_shortand_notation_to_bytes($value)
511{
512  $suffix = substr($value, -1);
513  $multiply_by = null;
514 
515  if ('K' == $suffix)
516  {
517    $multiply_by = 1024;
518  }
519  else if ('M' == $suffix)
520  {
521    $multiply_by = 1024*1024;
522  }
523  else if ('G' == $suffix)
524  {
525    $multiply_by = 1024*1024*1024;
526  }
527 
528  if (isset($multiply_by))
529  {
530    $value = substr($value, 0, -1);
531    $value*= $multiply_by;
532  }
533
534  return $value;
535}
536
537function add_upload_error($upload_id, $error_message)
538{
539  if (!isset($_SESSION['uploads_error']))
540  {
541    $_SESSION['uploads_error'] = array();
542  }
543  if (!isset($_SESSION['uploads_error'][$upload_id]))
544  {
545    $_SESSION['uploads_error'][$upload_id] = array();
546  }
547
548  array_push($_SESSION['uploads_error'][$upload_id], $error_message);
549}
550
551function is_imagick()
552{
553  if (extension_loaded('imagick'))
554  {
555    return true;
556  }
557
558  return false;
559}
560?>
Note: See TracBrowser for help on using the repository browser.