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

Last change on this file since 6625 was 6625, checked in by plg, 14 years ago

merge r6624 from branch 2.1 to trunk

bug 1747 fixed: some checks were added to verify the upload will fail for a
too big size or if the upload has failed for a too big size (test on
upload_max_filesize and post_max_size)

File size: 9.0 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, 6);
22add_event_handler('upload_thumbnail_resize', 'pwg_image_resize', EVENT_HANDLER_PRIORITY_NEUTRAL, 6);
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('upload_image_resize',
78      false,
79      $high_path,
80      $file_path,
81      $conf['upload_form_websize_maxwidth'],
82      $conf['upload_form_websize_maxheight'],
83      $conf['upload_form_websize_quality']
84      );
85  }
86
87  $file_infos = pwg_image_infos($file_path);
88 
89  $thumb_path = file_path_for_type($file_path, 'thumb');
90  $thumb_dir = dirname($thumb_path);
91  prepare_directory($thumb_dir);
92 
93  trigger_event('upload_thumbnail_resize',
94    false,
95    $file_path,
96    $thumb_path,
97    $conf['upload_form_thumb_maxwidth'],
98    $conf['upload_form_thumb_maxheight'],
99    $conf['upload_form_thumb_quality']
100    );
101 
102  $thumb_infos = pwg_image_infos($thumb_path);
103
104  // database registration
105  $insert = array(
106    'file' => isset($original_filename) ? $original_filename : basename($file_path),
107    'date_available' => $dbnow,
108    'tn_ext' => 'jpg',
109    'path' => preg_replace('#^'.preg_quote(PHPWG_ROOT_PATH).'#', '', $file_path),
110    'filesize' => $file_infos['filesize'],
111    'width' => $file_infos['width'],
112    'height' => $file_infos['height'],
113    'md5sum' => $md5sum,
114    );
115
116  if (isset($high_infos))
117  {
118    $insert['has_high'] = 'true';
119    $insert['high_filesize'] = $high_infos['filesize'];
120  }
121
122  if (isset($level))
123  {
124    $insert['level'] = $level;
125  }
126 
127  mass_inserts(
128    IMAGES_TABLE,
129    array_keys($insert),
130    array($insert)
131    );
132 
133  $image_id = pwg_db_insert_id();
134
135  if (isset($categories) and count($categories) > 0)
136  {
137    associate_images_to_categories(
138      array($image_id),
139      $categories
140      );
141  }
142 
143  // update metadata from the uploaded file (exif/iptc)
144  if ($conf['use_exif'] and !function_exists('read_exif_data'))
145  {
146    $conf['use_exif'] = false;
147  }
148  update_metadata(array($image_id=>$file_path));
149 
150  invalidate_user_cache();
151
152  return $image_id;
153}
154
155function prepare_directory($directory)
156{
157  if (!is_dir($directory)) {
158    if (substr(PHP_OS, 0, 3) == 'WIN')
159    {
160      $directory = str_replace('/', DIRECTORY_SEPARATOR, $directory);
161    }
162    umask(0000);
163    $recursive = true;
164    if (!@mkdir($directory, 0777, $recursive))
165    {
166      die('[prepare_directory] cannot create directory "'.$directory.'"');
167    }
168  }
169
170  if (!is_writable($directory))
171  {
172    // last chance to make the directory writable
173    @chmod($directory, 0777);
174
175    if (!is_writable($directory))
176    {
177      die('[prepare_directory] directory "'.$directory.'" has no write access');
178    }
179  }
180
181  secure_directory($directory);
182}
183
184function need_resize($image_filepath, $max_width, $max_height)
185{
186  list($width, $height) = getimagesize($image_filepath);
187 
188  if ($width > $max_width or $height > $max_height)
189  {
190    return true;
191  }
192
193  return false;
194}
195
196function pwg_image_resize($result, $source_filepath, $destination_filepath, $max_width, $max_height, $quality)
197{
198  if ($result !== false)
199  {
200    //someone hooked us - so we skip
201    return $result;
202  }
203
204  if (!function_exists('gd_info'))
205  {
206    return false;
207  }
208
209  // extension of the picture filename
210  $extension = strtolower(get_extension($source_filepath));
211
212  $source_image = null;
213  if (in_array($extension, array('jpg', 'jpeg')))
214  {
215    $source_image = imagecreatefromjpeg($source_filepath);
216  }
217  else if ($extension == 'png')
218  {
219    $source_image = imagecreatefrompng($source_filepath);
220  }
221  else
222  {
223    die('unsupported file extension');
224  }
225 
226  // width/height
227  $source_width  = imagesx($source_image); 
228  $source_height = imagesy($source_image);
229 
230  $ratio_width  = $source_width / $max_width;
231  $ratio_height = $source_height / $max_height;
232 
233  // maximal size exceeded ?
234  if ($ratio_width > 1 or $ratio_height > 1)
235  {
236    if ($ratio_width < $ratio_height)
237    { 
238      $destination_width = ceil($source_width / $ratio_height);
239      $destination_height = $max_height; 
240    }
241    else
242    { 
243      $destination_width = $max_width; 
244      $destination_height = ceil($source_height / $ratio_width);
245    }
246  }
247  else
248  {
249    // the image doesn't need any resize! We just copy it to the destination
250    copy($source_filepath, $destination_filepath);
251    return true;
252  }
253 
254  $destination_image = imagecreatetruecolor($destination_width, $destination_height);
255 
256  imagecopyresampled(
257    $destination_image,
258    $source_image,
259    0,
260    0,
261    0,
262    0,
263    $destination_width,
264    $destination_height,
265    $source_width,
266    $source_height
267    );
268 
269  $extension = strtolower(get_extension($destination_filepath));
270  if ($extension == 'png')
271  {
272    imagepng($destination_image, $destination_filepath);
273  }
274  else
275  {
276    imagejpeg($destination_image, $destination_filepath, $quality);
277  }
278  // freeing memory ressources
279  imagedestroy($source_image);
280  imagedestroy($destination_image);
281
282  // everything should be OK if we are here!
283  return true;
284}
285
286function pwg_image_infos($path)
287{
288  list($width, $height) = getimagesize($path);
289  $filesize = floor(filesize($path)/1024);
290 
291  return array(
292    'width'  => $width,
293    'height' => $height,
294    'filesize' => $filesize,
295    );
296}
297
298function is_valid_image_extension($extension)
299{
300  return in_array(strtolower($extension), array('jpg', 'jpeg', 'png'));
301}
302
303function file_upload_error_message($error_code)
304{
305  switch ($error_code) {
306    case UPLOAD_ERR_INI_SIZE:
307      return sprintf(
308        l10n('The uploaded file exceeds the upload_max_filesize directive in php.ini: %sB'),
309        get_ini_size('upload_max_filesize', false)
310        );
311    case UPLOAD_ERR_FORM_SIZE:
312      return l10n('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form');
313    case UPLOAD_ERR_PARTIAL:
314      return l10n('The uploaded file was only partially uploaded');
315    case UPLOAD_ERR_NO_FILE:
316      return l10n('No file was uploaded');
317    case UPLOAD_ERR_NO_TMP_DIR:
318      return l10n('Missing a temporary folder');
319    case UPLOAD_ERR_CANT_WRITE:
320      return l10n('Failed to write file to disk');
321    case UPLOAD_ERR_EXTENSION:
322      return l10n('File upload stopped by extension');
323    default:
324      return l10n('Unknown upload error');
325  }
326}
327
328function get_ini_size($ini_key, $in_bytes=true)
329{
330  $size = ini_get($ini_key);
331
332  if ($in_bytes)
333  {
334    $size = convert_shortand_notation_to_bytes($size);
335  }
336 
337  return $size;
338}
339
340function convert_shortand_notation_to_bytes($value)
341{
342  $suffix = substr($value, -1);
343  $multiply_by = null;
344 
345  if ('K' == $suffix)
346  {
347    $multiply_by = 1024;
348  }
349  else if ('M' == $suffix)
350  {
351    $multiply_by = 1024*1024;
352  }
353  else if ('G' == $suffix)
354  {
355    $multiply_by = 1024*1024*1024;
356  }
357 
358  if (isset($multiply_by))
359  {
360    $value = substr($value, 0, -1);
361    $value*= $multiply_by;
362  }
363
364  return $value;
365}
366
367function add_upload_error($upload_id, $error_message)
368{
369  if (!isset($_SESSION['uploads_error']))
370  {
371    $_SESSION['uploads_error'] = array();
372  }
373  if (!isset($_SESSION['uploads_error'][$upload_id]))
374  {
375    $_SESSION['uploads_error'][$upload_id] = array();
376  }
377
378  array_push($_SESSION['uploads_error'][$upload_id], $error_message);
379}
380?>
Note: See TracBrowser for help on using the repository browser.