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

Revision 8219, 13.1 KB checked in by plg, 9 years ago (diff)

feature 2076 added: automatically use ImageMagick (imagick) instead of GD if
Imagick extension is available. ImageMagick does not strip EXIF/IPTC metadata
from "web size" version of the photo.

We force remove EXIF/IPTC from the thumbnails to save space and bandwith.

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