add some properties
[phpbb.git] / phpBB / includes / functions_upload.php
blob142ec1537a27d5113bc520c05a7743d9d444e5dd
1 <?php
2 /**
4 * @package phpBB3
5 * @version $Id$
6 * @copyright (c) 2005 phpBB Group
7 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
9 */
11 /**
12 * @ignore
14 if (!defined('IN_PHPBB'))
16 exit;
19 /**
20 * Responsible for holding all file relevant information, as well as doing file-specific operations.
21 * The {@link fileupload fileupload class} can be used to upload several files, each of them being this object to operate further on.
22 * @package phpBB3
24 class filespec
26 var $filename = '';
27 var $realname = '';
28 var $uploadname = '';
29 var $mimetype = '';
30 var $extension = '';
31 var $filesize = 0;
32 var $width = 0;
33 var $height = 0;
34 var $image_info = array();
36 var $destination_file = '';
37 var $destination_path = '';
39 var $file_moved = false;
40 var $init_error = false;
41 var $local = false;
43 var $error = array();
45 var $upload = '';
47 /**
48 * File Class
49 * @access private
51 function __construct($upload_ary, $upload_namespace)
53 if (!isset($upload_ary))
55 $this->init_error = true;
56 return;
59 $this->filename = $upload_ary['tmp_name'];
60 $this->filesize = $upload_ary['size'];
61 $name = trim(htmlspecialchars(basename($upload_ary['name'])));
62 $this->realname = $this->uploadname = (STRIP) ? stripslashes($name) : $name;
63 $this->mimetype = $upload_ary['type'];
65 // Opera adds the name to the mime type
66 $this->mimetype = (strpos($this->mimetype, '; name') !== false) ? str_replace(strstr($this->mimetype, '; name'), '', $this->mimetype) : $this->mimetype;
68 if (!$this->mimetype)
70 $this->mimetype = 'application/octetstream';
73 $this->extension = strtolower($this->get_extension($this->realname));
75 // Try to get real filesize from temporary folder (not always working) ;)
76 $this->filesize = (@filesize($this->filename)) ? @filesize($this->filename) : $this->filesize;
78 $this->width = $this->height = 0;
79 $this->file_moved = false;
81 $this->local = (isset($upload_ary['local_mode'])) ? true : false;
82 $this->upload = $upload_namespace;
85 /**
86 * Cleans destination filename
88 * @param real|unique|unique_ext $mode real creates a realname, filtering some characters, lowering every character. Unique creates an unique filename
89 * @param string $prefix Prefix applied to filename
90 * @access public
92 function clean_filename($mode = 'unique', $prefix = '', $user_id = '')
94 if ($this->init_error)
96 return;
99 switch ($mode)
101 case 'real':
102 // Remove every extension from filename (to not let the mime bug being exposed)
103 if (strpos($this->realname, '.') !== false)
105 $this->realname = substr($this->realname, 0, strpos($this->realname, '.'));
108 // Replace any chars which may cause us problems with _
109 $bad_chars = array("'", "\\", ' ', '/', ':', '*', '?', '"', '<', '>', '|');
111 $this->realname = rawurlencode(str_replace($bad_chars, '_', strtolower($this->realname)));
112 $this->realname = preg_replace("/%(\w{2})/", '_', $this->realname);
114 $this->realname = $prefix . $this->realname . '.' . $this->extension;
115 break;
117 case 'unique':
118 $this->realname = $prefix . md5(unique_id());
119 break;
121 case 'avatar':
122 $this->extension = strtolower($this->extension);
123 $this->realname = $prefix . $user_id . '.' . $this->extension;
125 break;
127 case 'unique_ext':
128 default:
129 $this->realname = $prefix . md5(unique_id()) . '.' . $this->extension;
130 break;
135 * Get property from file object
137 function get($property)
139 if ($this->init_error || !isset($this->$property))
141 return false;
144 return $this->$property;
148 * Check if file is an image (mimetype)
150 * @return true if it is an image, false if not
152 function is_image()
154 return (strpos($this->mimetype, 'image/') !== false) ? true : false;
158 * Check if the file got correctly uploaded
160 * @return true if it is a valid upload, false if not
162 function is_uploaded()
164 if (!$this->local && !is_uploaded_file($this->filename))
166 return false;
169 if ($this->local && !file_exists($this->filename))
171 return false;
174 return true;
178 * Remove file
180 function remove()
182 if ($this->file_moved)
184 @unlink($this->destination_file);
189 * Get file extension
191 function get_extension($filename)
193 if (strpos($filename, '.') === false)
195 return '';
198 $filename = explode('.', $filename);
199 return array_pop($filename);
203 * Get mimetype. Utilize mime_content_type if the function exist.
204 * Not used at the moment...
206 function get_mimetype($filename)
208 $mimetype = '';
210 if (function_exists('mime_content_type'))
212 $mimetype = mime_content_type($filename);
215 // Some browsers choke on a mimetype of application/octet-stream
216 if (!$mimetype || $mimetype == 'application/octet-stream')
218 $mimetype = 'application/octetstream';
221 return $mimetype;
225 * Get filesize
227 function get_filesize($filename)
229 return @filesize($filename);
234 * Check the first 256 bytes for forbidden content
236 function check_content($disallowed_content)
238 if (empty($disallowed_content))
240 return true;
243 $fp = @fopen($this->filename, 'rb');
245 if ($fp !== false)
247 $ie_mime_relevant = fread($fp, 256);
248 fclose($fp);
249 foreach ($disallowed_content as $forbidden)
251 if (stripos($ie_mime_relevant, '<' . $forbidden) !== false)
253 return false;
257 return true;
261 * Move file to destination folder
262 * The phpbb_root_path variable will be applied to the destination path
264 * @param string $destination_path Destination path, for example phpbb::$config['avatar_path']
265 * @param bool $overwrite If set to true, an already existing file will be overwritten
266 * @param string $chmod Permission mask for chmodding the file after a successful move. The mode entered here is the octal permission mask.
268 * @access public
270 function move_file($destination, $overwrite = false, $skip_image_check = false, $chmod = false)
272 global $user;
274 if (sizeof($this->error))
276 return false;
279 $chmod = ($chmod === false) ? phpbb::CHMOD_READ | phpbb::CHMOD_WRITE : $chmod;
281 // We need to trust the admin in specifying valid upload directories and an attacker not being able to overwrite it...
282 $this->destination_path = PHPBB_ROOT_PATH . $destination;
284 // Check if the destination path exist...
285 if (!file_exists($this->destination_path))
287 @unlink($this->filename);
288 return false;
291 $upload_mode = (@ini_get('open_basedir') || @ini_get('safe_mode') || strtolower(@ini_get('safe_mode')) == 'on') ? 'move' : 'copy';
292 $upload_mode = ($this->local) ? 'local' : $upload_mode;
293 $this->destination_file = $this->destination_path . '/' . basename($this->realname);
295 // Check if the file already exist, else there is something wrong...
296 if (file_exists($this->destination_file) && !$overwrite)
298 @unlink($this->filename);
300 else
302 if (file_exists($this->destination_file))
304 @unlink($this->destination_file);
307 switch ($upload_mode)
309 case 'copy':
311 if (!@copy($this->filename, $this->destination_file))
313 if (!@move_uploaded_file($this->filename, $this->destination_file))
315 $this->error[] = sprintf($user->lang[$this->upload->error_prefix . 'GENERAL_UPLOAD_ERROR'], $this->destination_file);
316 return false;
320 @unlink($this->filename);
322 break;
324 case 'move':
326 if (!@move_uploaded_file($this->filename, $this->destination_file))
328 if (!@copy($this->filename, $this->destination_file))
330 $this->error[] = sprintf($user->lang[$this->upload->error_prefix . 'GENERAL_UPLOAD_ERROR'], $this->destination_file);
331 return false;
335 @unlink($this->filename);
337 break;
339 case 'local':
341 if (!@copy($this->filename, $this->destination_file))
343 $this->error[] = sprintf($user->lang[$this->upload->error_prefix . 'GENERAL_UPLOAD_ERROR'], $this->destination_file);
344 return false;
346 @unlink($this->filename);
348 break;
351 phpbb::$system->chmod($this->destination_file, $chmod);
354 // Try to get real filesize from destination folder
355 $this->filesize = (@filesize($this->destination_file)) ? @filesize($this->destination_file) : $this->filesize;
357 if ($this->is_image() && !$skip_image_check)
359 $this->width = $this->height = 0;
361 if (($this->image_info = @getimagesize($this->destination_file)) !== false)
363 $this->width = $this->image_info[0];
364 $this->height = $this->image_info[1];
366 if (!empty($this->image_info['mime']))
368 $this->mimetype = $this->image_info['mime'];
371 // Check image type
372 $types = $this->upload->image_types();
374 if (!isset($types[$this->image_info[2]]) || !in_array($this->extension, $types[$this->image_info[2]]))
376 if (!isset($types[$this->image_info[2]]))
378 $this->error[] = sprintf($user->lang['IMAGE_FILETYPE_INVALID'], $this->image_info[2], $this->mimetype);
380 else
382 $this->error[] = sprintf($user->lang['IMAGE_FILETYPE_MISMATCH'], $types[$this->image_info[2]][0], $this->extension);
386 // Make sure the dimensions match a valid image
387 if (empty($this->width) || empty($this->height))
389 $this->error[] = $user->lang['ATTACHED_IMAGE_NOT_IMAGE'];
392 else
394 $this->error[] = $user->lang['UNABLE_GET_IMAGE_SIZE'];
398 $this->file_moved = true;
399 $this->additional_checks();
400 unset($this->upload);
402 return true;
406 * Performing additional checks
408 function additional_checks()
410 global $user;
412 if (!$this->file_moved)
414 return false;
417 // Filesize is too big or it's 0 if it was larger than the maxsize in the upload form
418 if ($this->upload->max_filesize && ($this->get('filesize') > $this->upload->max_filesize || $this->filesize == 0))
420 $size_lang = ($this->upload->max_filesize >= 1048576) ? $user->lang['MIB'] : (($this->upload->max_filesize >= 1024) ? $user->lang['KIB'] : $user->lang['BYTES'] );
421 $max_filesize = get_formatted_filesize($this->upload->max_filesize, false);
423 $this->error[] = sprintf($user->lang[$this->upload->error_prefix . 'WRONG_FILESIZE'], $max_filesize, $size_lang);
425 return false;
428 if (!$this->upload->valid_dimensions($this))
430 $this->error[] = sprintf($user->lang[$this->upload->error_prefix . 'WRONG_SIZE'], $this->upload->min_width, $this->upload->min_height, $this->upload->max_width, $this->upload->max_height, $this->width, $this->height);
432 return false;
435 return true;
440 * Class for assigning error messages before a real filespec class can be assigned
442 * @package phpBB3
444 class fileerror extends filespec
446 function fileerror($error_msg)
448 $this->error[] = $error_msg;
453 * File upload class
454 * Init class (all parameters optional and able to be set/overwritten separately) - scope is global and valid for all uploads
456 * @package phpBB3
458 class fileupload
460 var $allowed_extensions = array();
461 var $disallowed_content = array();
462 var $max_filesize = 0;
463 var $min_width = 0;
464 var $min_height = 0;
465 var $max_width = 0;
466 var $max_height = 0;
467 var $error_prefix = '';
470 * Init file upload class.
472 * @param string $error_prefix Used error messages will get prefixed by this string
473 * @param array $allowed_extensions Array of allowed extensions, for example array('jpg', 'jpeg', 'gif', 'png')
474 * @param int $max_filesize Maximum filesize
475 * @param int $min_width Minimum image width (only checked for images)
476 * @param int $min_height Minimum image height (only checked for images)
477 * @param int $max_width Maximum image width (only checked for images)
478 * @param int $max_height Maximum image height (only checked for images)
481 function __construct($error_prefix = '', $allowed_extensions = false, $max_filesize = false, $min_width = false, $min_height = false, $max_width = false, $max_height = false, $disallowed_content = false)
483 $this->set_allowed_extensions($allowed_extensions);
484 $this->set_max_filesize($max_filesize);
485 $this->set_allowed_dimensions($min_width, $min_height, $max_width, $max_height);
486 $this->set_error_prefix($error_prefix);
487 $this->set_disallowed_content($disallowed_content);
491 * Reset vars
493 function reset_vars()
495 $this->max_filesize = 0;
496 $this->min_width = $this->min_height = $this->max_width = $this->max_height = 0;
497 $this->error_prefix = '';
498 $this->allowed_extensions = array();
499 $this->disallowed_content = array();
503 * Set allowed extensions
505 function set_allowed_extensions($allowed_extensions)
507 if ($allowed_extensions !== false && is_array($allowed_extensions))
509 $this->allowed_extensions = $allowed_extensions;
514 * Set allowed dimensions
516 function set_allowed_dimensions($min_width, $min_height, $max_width, $max_height)
518 $this->min_width = (int) $min_width;
519 $this->min_height = (int) $min_height;
520 $this->max_width = (int) $max_width;
521 $this->max_height = (int) $max_height;
525 * Set maximum allowed filesize
527 function set_max_filesize($max_filesize)
529 if ($max_filesize !== false && (int) $max_filesize)
531 $this->max_filesize = (int) $max_filesize;
536 * Set disallowed strings
538 function set_disallowed_content($disallowed_content)
540 if ($disallowed_content !== false && is_array($disallowed_content))
542 $this->disallowed_content = $disallowed_content;
547 * Set error prefix
549 function set_error_prefix($error_prefix)
551 $this->error_prefix = $error_prefix;
555 * Form upload method
556 * Upload file from users harddisk
558 * @param string $form_name Form name assigned to the file input field (if it is an array, the key has to be specified)
559 * @return object $file Object "filespec" is returned, all further operations can be done with this object
560 * @access public
562 function form_upload($form_name)
564 global $user;
566 unset($_FILES[$form_name]['local_mode']);
567 $file = new filespec($_FILES[$form_name], $this);
569 if ($file->init_error)
571 $file->error[] = '';
572 return $file;
575 // Error array filled?
576 if (isset($_FILES[$form_name]['error']))
578 $error = $this->assign_internal_error($_FILES[$form_name]['error']);
580 if ($error !== false)
582 $file->error[] = $error;
583 return $file;
587 // Check if empty file got uploaded (not catched by is_uploaded_file)
588 if (isset($_FILES[$form_name]['size']) && $_FILES[$form_name]['size'] == 0)
590 $file->error[] = $user->lang[$this->error_prefix . 'EMPTY_FILEUPLOAD'];
591 return $file;
594 // PHP Upload filesize exceeded
595 if ($file->get('filename') == 'none')
597 $file->error[] = (@ini_get('upload_max_filesize') == '') ? $user->lang[$this->error_prefix . 'PHP_SIZE_NA'] : sprintf($user->lang[$this->error_prefix . 'PHP_SIZE_OVERRUN'], @ini_get('upload_max_filesize'));
598 return $file;
601 // Not correctly uploaded
602 if (!$file->is_uploaded())
604 $file->error[] = $user->lang[$this->error_prefix . 'NOT_UPLOADED'];
605 return $file;
608 $this->common_checks($file);
610 return $file;
614 * Move file from another location to phpBB
616 function local_upload($source_file, $filedata = false)
618 global $user;
620 $form_name = 'local';
622 $_FILES[$form_name]['local_mode'] = true;
623 $_FILES[$form_name]['tmp_name'] = $source_file;
625 if ($filedata === false)
627 $_FILES[$form_name]['name'] = basename($source_file);
628 $_FILES[$form_name]['size'] = 0;
629 $mimetype = '';
631 if (function_exists('mime_content_type'))
633 $mimetype = mime_content_type($source_file);
636 // Some browsers choke on a mimetype of application/octet-stream
637 if (!$mimetype || $mimetype == 'application/octet-stream')
639 $mimetype = 'application/octetstream';
642 $_FILES[$form_name]['type'] = $mimetype;
644 else
646 $_FILES[$form_name]['name'] = $filedata['realname'];
647 $_FILES[$form_name]['size'] = $filedata['size'];
648 $_FILES[$form_name]['type'] = $filedata['type'];
651 $file = new filespec($_FILES[$form_name], $this);
653 if ($file->init_error)
655 $file->error[] = '';
656 return $file;
659 if (isset($_FILES[$form_name]['error']))
661 $error = $this->assign_internal_error($_FILES[$form_name]['error']);
663 if ($error !== false)
665 $file->error[] = $error;
666 return $file;
670 // PHP Upload filesize exceeded
671 if ($file->get('filename') == 'none')
673 $file->error[] = (@ini_get('upload_max_filesize') == '') ? $user->lang[$this->error_prefix . 'PHP_SIZE_NA'] : sprintf($user->lang[$this->error_prefix . 'PHP_SIZE_OVERRUN'], @ini_get('upload_max_filesize'));
674 return $file;
677 // Not correctly uploaded
678 if (!$file->is_uploaded())
680 $file->error[] = $user->lang[$this->error_prefix . 'NOT_UPLOADED'];
681 return $file;
684 $this->common_checks($file);
686 return $file;
690 * Remote upload method
691 * Uploads file from given url
693 * @param string $upload_url URL pointing to file to upload, for example http://www.foobar.com/example.gif
694 * @return object $file Object "filespec" is returned, all further operations can be done with this object
695 * @access public
697 function remote_upload($upload_url)
699 global $user;
701 $upload_ary = array();
702 $upload_ary['local_mode'] = true;
704 if (!preg_match('#^(https?://).*?\.(' . implode('|', $this->allowed_extensions) . ')$#i', $upload_url, $match))
706 $file = new fileerror($user->lang[$this->error_prefix . 'URL_INVALID']);
707 return $file;
710 if (empty($match[2]))
712 $file = new fileerror($user->lang[$this->error_prefix . 'URL_INVALID']);
713 return $file;
716 $url = parse_url($upload_url);
718 $host = $url['host'];
719 $path = $url['path'];
720 $port = (!empty($url['port'])) ? (int) $url['port'] : 80;
722 $upload_ary['type'] = 'application/octet-stream';
724 $url['path'] = explode('.', $url['path']);
725 $ext = array_pop($url['path']);
727 $url['path'] = implode('', $url['path']);
728 $upload_ary['name'] = basename($url['path']) . (($ext) ? '.' . $ext : '');
729 $filename = $url['path'];
730 $filesize = 0;
732 $errno = 0;
733 $errstr = '';
735 if (!($fsock = @fsockopen($host, $port, $errno, $errstr)))
737 $file = new fileerror($user->lang[$this->error_prefix . 'NOT_UPLOADED']);
738 return $file;
741 // Make sure $path not beginning with /
742 if (strpos($path, '/') === 0)
744 $path = substr($path, 1);
747 fputs($fsock, 'GET /' . $path . " HTTP/1.1\r\n");
748 fputs($fsock, "HOST: " . $host . "\r\n");
749 fputs($fsock, "Connection: close\r\n\r\n");
751 $get_info = false;
752 $data = '';
753 while (!@feof($fsock))
755 if ($get_info)
757 $data .= @fread($fsock, 1024);
759 else
761 $line = @fgets($fsock, 1024);
763 if ($line == "\r\n")
765 $get_info = true;
767 else
769 if (stripos($line, 'content-type: ') !== false)
771 $upload_ary['type'] = rtrim(str_replace('content-type: ', '', strtolower($line)));
773 else if (stripos($line, '404 not found') !== false)
775 $file = new fileerror($user->lang[$this->error_prefix . 'URL_NOT_FOUND']);
776 return $file;
781 @fclose($fsock);
783 if (empty($data))
785 $file = new fileerror($user->lang[$this->error_prefix . 'EMPTY_REMOTE_DATA']);
786 return $file;
789 $tmp_path = (!@ini_get('safe_mode') || strtolower(@ini_get('safe_mode')) == 'off') ? false : PHPBB_ROOT_PATH . 'cache';
790 $filename = tempnam($tmp_path, unique_id() . '-');
792 if (!($fp = @fopen($filename, 'wb')))
794 $file = new fileerror($user->lang[$this->error_prefix . 'NOT_UPLOADED']);
795 return $file;
798 $upload_ary['size'] = fwrite($fp, $data);
799 fclose($fp);
800 unset($data);
802 $upload_ary['tmp_name'] = $filename;
804 $file = new filespec($upload_ary, $this);
805 $this->common_checks($file);
807 return $file;
811 * Assign internal error
812 * @access private
814 function assign_internal_error($errorcode)
816 global $user;
818 switch ($errorcode)
820 case 1:
821 $error = (@ini_get('upload_max_filesize') == '') ? $user->lang[$this->error_prefix . 'PHP_SIZE_NA'] : sprintf($user->lang[$this->error_prefix . 'PHP_SIZE_OVERRUN'], @ini_get('upload_max_filesize'));
822 break;
824 case 2:
825 $size_lang = ($this->max_filesize >= 1048576) ? $user->lang['MIB'] : (($this->max_filesize >= 1024) ? $user->lang['KIB'] : $user->lang['BYTES']);
826 $max_filesize = get_formatted_filesize($this->max_filesize, false);
828 $error = sprintf($user->lang[$this->error_prefix . 'WRONG_FILESIZE'], $max_filesize, $size_lang);
829 break;
831 case 3:
832 $error = $user->lang[$this->error_prefix . 'PARTIAL_UPLOAD'];
833 break;
835 case 4:
836 $error = $user->lang[$this->error_prefix . 'NOT_UPLOADED'];
837 break;
839 case 6:
840 $error = 'Temporary folder could not be found. Please check your PHP installation.';
841 break;
843 default:
844 $error = false;
845 break;
848 return $error;
852 * Perform common checks
854 function common_checks(&$file)
856 global $user;
858 // Filesize is too big or it's 0 if it was larger than the maxsize in the upload form
859 if ($this->max_filesize && ($file->get('filesize') > $this->max_filesize || $file->get('filesize') == 0))
861 $size_lang = ($this->max_filesize >= 1048576) ? $user->lang['MIB'] : (($this->max_filesize >= 1024) ? $user->lang['KIB'] : $user->lang['BYTES']);
862 $max_filesize = get_formatted_filesize($this->max_filesize, false);
864 $file->error[] = sprintf($user->lang[$this->error_prefix . 'WRONG_FILESIZE'], $max_filesize, $size_lang);
867 // check Filename
868 if (preg_match("#[\\/:*?\"<>|]#i", $file->get('realname')))
870 $file->error[] = sprintf($user->lang[$this->error_prefix . 'INVALID_FILENAME'], $file->get('realname'));
873 // Invalid Extension
874 if (!$this->valid_extension($file))
876 $file->error[] = sprintf($user->lang[$this->error_prefix . 'DISALLOWED_EXTENSION'], $file->get('extension'));
879 // MIME Sniffing
880 if (!$this->valid_content($file))
882 $file->error[] = sprintf($user->lang[$this->error_prefix . 'DISALLOWED_CONTENT']);
887 * Check for allowed extension
889 function valid_extension(&$file)
891 return (in_array($file->get('extension'), $this->allowed_extensions)) ? true : false;
895 * Check for allowed dimension
897 function valid_dimensions(&$file)
899 if (!$this->max_width && !$this->max_height && !$this->min_width && !$this->min_height)
901 return true;
904 if (($file->get('width') > $this->max_width && $this->max_width) ||
905 ($file->get('height') > $this->max_height && $this->max_height) ||
906 ($file->get('width') < $this->min_width && $this->min_width) ||
907 ($file->get('height') < $this->min_height && $this->min_height))
909 return false;
912 return true;
916 * Check if form upload is valid
918 function is_valid($form_name)
920 return (isset($_FILES[$form_name]) && $_FILES[$form_name]['name'] != 'none') ? true : false;
925 * Check for allowed extension
927 function valid_content(&$file)
929 return ($file->check_content($this->disallowed_content));
933 * Return image type/extension mapping
935 function image_types()
937 return array(
938 1 => array('gif'),
939 2 => array('jpg', 'jpeg'),
940 3 => array('png'),
941 4 => array('swf'),
942 5 => array('psd'),
943 6 => array('bmp'),
944 7 => array('tif', 'tiff'),
945 8 => array('tif', 'tiff'),
946 9 => array('jpg', 'jpeg'),
947 10 => array('jpg', 'jpeg'),
948 11 => array('jpg', 'jpeg'),
949 12 => array('jpg', 'jpeg'),
950 13 => array('swc'),
951 14 => array('iff'),
952 15 => array('wbmp'),
953 16 => array('xbm'),