6 * @copyright (c) 2005 phpBB Group
7 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
14 if (!defined('IN_PHPBB'))
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.
34 var $image_info = array();
36 var $destination_file = '';
37 var $destination_path = '';
39 var $file_moved = false;
40 var $init_error = false;
51 function filespec($upload_ary, $upload_namespace)
53 if (!isset($upload_ary))
55 $this->init_error = true;
59 $this->filename = $upload_ary['tmp_name'];
60 $this->filesize = $upload_ary['size'];
61 $name = (STRIP) ? stripslashes($upload_ary['name']) : $upload_ary['name'];
62 $name = trim(utf8_htmlspecialchars(utf8_basename($name)));
63 $this->realname = $this->uploadname = $name;
64 $this->mimetype = $upload_ary['type'];
66 // Opera adds the name to the mime type
67 $this->mimetype = (strpos($this->mimetype, '; name') !== false) ? str_replace(strstr($this->mimetype, '; name'), '', $this->mimetype) : $this->mimetype;
71 $this->mimetype = 'application/octetstream';
74 $this->extension = strtolower($this->get_extension($this->realname));
76 // Try to get real filesize from temporary folder (not always working) ;)
77 $this->filesize = (@filesize($this->filename)) ? @filesize($this->filename) : $this->filesize;
79 $this->width = $this->height = 0;
80 $this->file_moved = false;
82 $this->local = (isset($upload_ary['local_mode'])) ? true : false;
83 $this->upload = $upload_namespace;
87 * Cleans destination filename
89 * @param real|unique|unique_ext $mode real creates a realname, filtering some characters, lowering every character. Unique creates an unique filename
90 * @param string $prefix Prefix applied to filename
93 function clean_filename($mode = 'unique', $prefix = '', $user_id = '')
95 if ($this->init_error)
103 // Remove every extension from filename (to not let the mime bug being exposed)
104 if (strpos($this->realname, '.') !== false)
106 $this->realname = substr($this->realname, 0, strpos($this->realname, '.'));
109 // Replace any chars which may cause us problems with _
110 $bad_chars = array("'", "\\", ' ', '/', ':', '*', '?', '"', '<', '>', '|');
112 $this->realname = rawurlencode(str_replace($bad_chars, '_', strtolower($this->realname)));
113 $this->realname = preg_replace("/%(\w{2})/", '_', $this->realname);
115 $this->realname = $prefix . $this->realname . '.' . $this->extension;
119 $this->realname = $prefix . md5(unique_id());
123 $this->extension = strtolower($this->extension);
124 $this->realname = $prefix . $user_id . '.' . $this->extension;
130 $this->realname = $prefix . md5(unique_id()) . '.' . $this->extension;
136 * Get property from file object
138 function get($property)
140 if ($this->init_error || !isset($this->$property))
145 return $this->$property;
149 * Check if file is an image (mimetype)
151 * @return true if it is an image, false if not
155 return (strpos($this->mimetype, 'image/') !== false) ? true : false;
159 * Check if the file got correctly uploaded
161 * @return true if it is a valid upload, false if not
163 function is_uploaded()
165 if (!$this->local && !is_uploaded_file($this->filename))
170 if ($this->local && !file_exists($this->filename))
183 if ($this->file_moved)
185 @unlink($this->destination_file);
192 function get_extension($filename)
194 if (strpos($filename, '.') === false)
199 $filename = explode('.', $filename);
200 return array_pop($filename);
204 * Get mimetype. Utilize mime_content_type if the function exist.
205 * Not used at the moment...
207 function get_mimetype($filename)
211 if (function_exists('mime_content_type'))
213 $mimetype = mime_content_type($filename);
216 // Some browsers choke on a mimetype of application/octet-stream
217 if (!$mimetype || $mimetype == 'application/octet-stream')
219 $mimetype = 'application/octetstream';
228 function get_filesize($filename)
230 return @filesize($filename);
235 * Check the first 256 bytes for forbidden content
237 function check_content($disallowed_content)
239 if (empty($disallowed_content))
244 $fp = @fopen($this->filename, 'rb');
248 $ie_mime_relevant = fread($fp, 256);
250 foreach ($disallowed_content as $forbidden)
252 if (stripos($ie_mime_relevant, '<' . $forbidden) !== false)
262 * Move file to destination folder
263 * The phpbb_root_path variable will be applied to the destination path
265 * @param string $destination_path Destination path, for example $config['avatar_path']
266 * @param bool $overwrite If set to true, an already existing file will be overwritten
267 * @param string $chmod Permission mask for chmodding the file after a successful move. The mode entered here reflects the mode defined by {@link phpbb_chmod()}
271 function move_file($destination, $overwrite = false, $skip_image_check = false, $chmod = false)
273 global $user, $phpbb_root_path;
275 if (sizeof($this->error))
280 $chmod = ($chmod === false) ? CHMOD_READ | CHMOD_WRITE : $chmod;
282 // We need to trust the admin in specifying valid upload directories and an attacker not being able to overwrite it...
283 $this->destination_path = $phpbb_root_path . $destination;
285 // Check if the destination path exist...
286 if (!file_exists($this->destination_path))
288 @unlink($this->filename);
292 $upload_mode = (@ini_get('open_basedir') || @ini_get('safe_mode') || strtolower(@ini_get('safe_mode')) == 'on') ? 'move' : 'copy';
293 $upload_mode = ($this->local) ? 'local' : $upload_mode;
294 $this->destination_file = $this->destination_path . '/' . utf8_basename($this->realname);
296 // Check if the file already exist, else there is something wrong...
297 if (file_exists($this->destination_file) && !$overwrite)
299 @unlink($this->filename);
303 if (file_exists($this->destination_file))
305 @unlink($this->destination_file);
308 switch ($upload_mode)
312 if (!@copy($this->filename, $this->destination_file))
314 if (!@move_uploaded_file($this->filename, $this->destination_file))
316 $this->error[] = sprintf($user->lang[$this->upload->error_prefix . 'GENERAL_UPLOAD_ERROR'], $this->destination_file);
324 if (!@move_uploaded_file($this->filename, $this->destination_file))
326 if (!@copy($this->filename, $this->destination_file))
328 $this->error[] = sprintf($user->lang[$this->upload->error_prefix . 'GENERAL_UPLOAD_ERROR'], $this->destination_file);
336 if (!@copy($this->filename, $this->destination_file))
338 $this->error[] = sprintf($user->lang[$this->upload->error_prefix . 'GENERAL_UPLOAD_ERROR'], $this->destination_file);
344 // Remove temporary filename
345 @unlink($this->filename);
347 if (sizeof($this->error))
352 phpbb_chmod($this->destination_file, $chmod);
355 // Try to get real filesize from destination folder
356 $this->filesize = (@filesize($this->destination_file)) ? @filesize($this->destination_file) : $this->filesize;
358 if ($this->is_image() && !$skip_image_check)
360 $this->width = $this->height = 0;
362 if (($this->image_info = @getimagesize($this->destination_file)) !== false)
364 $this->width = $this->image_info[0];
365 $this->height = $this->image_info[1];
367 if (!empty($this->image_info['mime']))
369 $this->mimetype = $this->image_info['mime'];
373 $types = $this->upload->image_types();
375 if (!isset($types[$this->image_info[2]]) || !in_array($this->extension, $types[$this->image_info[2]]))
377 if (!isset($types[$this->image_info[2]]))
379 $this->error[] = sprintf($user->lang['IMAGE_FILETYPE_INVALID'], $this->image_info[2], $this->mimetype);
383 $this->error[] = sprintf($user->lang['IMAGE_FILETYPE_MISMATCH'], $types[$this->image_info[2]][0], $this->extension);
387 // Make sure the dimensions match a valid image
388 if (empty($this->width) || empty($this->height))
390 $this->error[] = $user->lang['ATTACHED_IMAGE_NOT_IMAGE'];
395 $this->error[] = $user->lang['UNABLE_GET_IMAGE_SIZE'];
399 $this->file_moved = true;
400 $this->additional_checks();
401 unset($this->upload);
407 * Performing additional checks
409 function additional_checks()
413 if (!$this->file_moved)
418 // Filesize is too big or it's 0 if it was larger than the maxsize in the upload form
419 if ($this->upload->max_filesize && ($this->get('filesize') > $this->upload->max_filesize || $this->filesize == 0))
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['value'], $max_filesize['unit']);
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);
440 * Class for assigning error messages before a real filespec class can be assigned
444 class fileerror extends filespec
446 function fileerror($error_msg)
448 $this->error[] = $error_msg;
454 * Init class (all parameters optional and able to be set/overwritten separately) - scope is global and valid for all uploads
460 var $allowed_extensions = array();
461 var $disallowed_content = array('body', 'head', 'html', 'img', 'plaintext', 'a href', 'pre', 'script', 'table', 'title');
462 var $max_filesize = 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 fileupload($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);
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 = array_diff($disallowed_content, array(''));
549 function set_error_prefix($error_prefix)
551 $this->error_prefix = $error_prefix;
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
562 function form_upload($form_name)
566 unset($_FILES[$form_name]['local_mode']);
567 $file = new filespec($_FILES[$form_name], $this);
569 if ($file->init_error)
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;
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'];
594 // PHP Upload filesize exceeded
595 if ($file->get('filename') == 'none')
597 $max_filesize = @ini_get('upload_max_filesize');
600 if (!empty($max_filesize))
602 $unit = strtolower(substr($max_filesize, -1, 1));
603 $max_filesize = (int) $max_filesize;
605 $unit = ($unit == 'k') ? 'KB' : (($unit == 'g') ? 'GB' : 'MB');
608 $file->error[] = (empty($max_filesize)) ? $user->lang[$this->error_prefix . 'PHP_SIZE_NA'] : sprintf($user->lang[$this->error_prefix . 'PHP_SIZE_OVERRUN'], $max_filesize, $user->lang[$unit]);
612 // Not correctly uploaded
613 if (!$file->is_uploaded())
615 $file->error[] = $user->lang[$this->error_prefix . 'NOT_UPLOADED'];
619 $this->common_checks($file);
625 * Move file from another location to phpBB
627 function local_upload($source_file, $filedata = false)
631 $form_name = 'local';
633 $_FILES[$form_name]['local_mode'] = true;
634 $_FILES[$form_name]['tmp_name'] = $source_file;
636 if ($filedata === false)
638 $_FILES[$form_name]['name'] = utf8_basename($source_file);
639 $_FILES[$form_name]['size'] = 0;
642 if (function_exists('mime_content_type'))
644 $mimetype = mime_content_type($source_file);
647 // Some browsers choke on a mimetype of application/octet-stream
648 if (!$mimetype || $mimetype == 'application/octet-stream')
650 $mimetype = 'application/octetstream';
653 $_FILES[$form_name]['type'] = $mimetype;
657 $_FILES[$form_name]['name'] = $filedata['realname'];
658 $_FILES[$form_name]['size'] = $filedata['size'];
659 $_FILES[$form_name]['type'] = $filedata['type'];
662 $file = new filespec($_FILES[$form_name], $this);
664 if ($file->init_error)
670 if (isset($_FILES[$form_name]['error']))
672 $error = $this->assign_internal_error($_FILES[$form_name]['error']);
674 if ($error !== false)
676 $file->error[] = $error;
681 // PHP Upload filesize exceeded
682 if ($file->get('filename') == 'none')
684 $max_filesize = @ini_get('upload_max_filesize');
687 if (!empty($max_filesize))
689 $unit = strtolower(substr($max_filesize, -1, 1));
690 $max_filesize = (int) $max_filesize;
692 $unit = ($unit == 'k') ? 'KB' : (($unit == 'g') ? 'GB' : 'MB');
695 $file->error[] = (empty($max_filesize)) ? $user->lang[$this->error_prefix . 'PHP_SIZE_NA'] : sprintf($user->lang[$this->error_prefix . 'PHP_SIZE_OVERRUN'], $max_filesize, $user->lang[$unit]);
699 // Not correctly uploaded
700 if (!$file->is_uploaded())
702 $file->error[] = $user->lang[$this->error_prefix . 'NOT_UPLOADED'];
706 $this->common_checks($file);
712 * Remote upload method
713 * Uploads file from given url
715 * @param string $upload_url URL pointing to file to upload, for example http://www.foobar.com/example.gif
716 * @return object $file Object "filespec" is returned, all further operations can be done with this object
719 function remote_upload($upload_url)
721 global $user, $phpbb_root_path;
723 $upload_ary = array();
724 $upload_ary['local_mode'] = true;
726 if (!preg_match('#^(https?://).*?\.(' . implode('|', $this->allowed_extensions) . ')$#i', $upload_url, $match))
728 $file = new fileerror($user->lang[$this->error_prefix . 'URL_INVALID']);
732 if (empty($match[2]))
734 $file = new fileerror($user->lang[$this->error_prefix . 'URL_INVALID']);
738 $url = parse_url($upload_url);
740 $host = $url['host'];
741 $path = $url['path'];
742 $port = (!empty($url['port'])) ? (int) $url['port'] : 80;
744 $upload_ary['type'] = 'application/octet-stream';
746 $url['path'] = explode('.', $url['path']);
747 $ext = array_pop($url['path']);
749 $url['path'] = implode('', $url['path']);
750 $upload_ary['name'] = utf8_basename($url['path']) . (($ext) ? '.' . $ext : '');
751 $filename = $url['path'];
757 if (!($fsock = @fsockopen($host, $port, $errno, $errstr)))
759 $file = new fileerror($user->lang[$this->error_prefix . 'NOT_UPLOADED']);
763 // Make sure $path not beginning with /
764 if (strpos($path, '/') === 0)
766 $path = substr($path, 1);
769 fputs($fsock, 'GET /' . $path . " HTTP/1.1\r\n");
770 fputs($fsock, "HOST: " . $host . "\r\n");
771 fputs($fsock, "Connection: close\r\n\r\n");
775 while (!@feof($fsock))
779 $block = @fread($fsock, 1024);
780 $filesize += strlen($block);
782 if ($this->max_filesize && $filesize > $this->max_filesize)
784 $max_filesize = get_formatted_filesize($this->max_filesize, false);
786 $file = new fileerror(sprintf($user->lang[$this->error_prefix . 'WRONG_FILESIZE'], $max_filesize['value'], $max_filesize['unit']));
794 $line = @fgets($fsock, 1024);
802 if (stripos($line, 'content-type: ') !== false)
804 $upload_ary['type'] = rtrim(str_replace('content-type: ', '', strtolower($line)));
806 else if ($this->max_filesize && stripos($line, 'content-length: ') !== false)
808 $length = (int) str_replace('content-length: ', '', strtolower($line));
810 if ($length && $length > $this->max_filesize)
812 $max_filesize = get_formatted_filesize($this->max_filesize, false);
814 $file = new fileerror(sprintf($user->lang[$this->error_prefix . 'WRONG_FILESIZE'], $max_filesize['value'], $max_filesize['unit']));
818 else if (stripos($line, '404 not found') !== false)
820 $file = new fileerror($user->lang[$this->error_prefix . 'URL_NOT_FOUND']);
830 $file = new fileerror($user->lang[$this->error_prefix . 'EMPTY_REMOTE_DATA']);
834 $tmp_path = (!@ini_get('safe_mode') || strtolower(@ini_get('safe_mode')) == 'off') ? false : $phpbb_root_path . 'cache';
835 $filename = tempnam($tmp_path, unique_id() . '-');
837 if (!($fp = @fopen($filename, 'wb')))
839 $file = new fileerror($user->lang[$this->error_prefix . 'NOT_UPLOADED']);
843 $upload_ary['size'] = fwrite($fp, $data);
847 $upload_ary['tmp_name'] = $filename;
849 $file = new filespec($upload_ary, $this);
850 $this->common_checks($file);
856 * Assign internal error
859 function assign_internal_error($errorcode)
866 $max_filesize = @ini_get('upload_max_filesize');
869 if (!empty($max_filesize))
871 $unit = strtolower(substr($max_filesize, -1, 1));
872 $max_filesize = (int) $max_filesize;
874 $unit = ($unit == 'k') ? 'KB' : (($unit == 'g') ? 'GB' : 'MB');
877 $error = (empty($max_filesize)) ? $user->lang[$this->error_prefix . 'PHP_SIZE_NA'] : sprintf($user->lang[$this->error_prefix . 'PHP_SIZE_OVERRUN'], $max_filesize, $user->lang[$unit]);
881 $max_filesize = get_formatted_filesize($this->max_filesize, false);
883 $error = sprintf($user->lang[$this->error_prefix . 'WRONG_FILESIZE'], $max_filesize['value'], $max_filesize['unit']);
887 $error = $user->lang[$this->error_prefix . 'PARTIAL_UPLOAD'];
891 $error = $user->lang[$this->error_prefix . 'NOT_UPLOADED'];
895 $error = 'Temporary folder could not be found. Please check your PHP installation.';
907 * Perform common checks
909 function common_checks(&$file)
913 // Filesize is too big or it's 0 if it was larger than the maxsize in the upload form
914 if ($this->max_filesize && ($file->get('filesize') > $this->max_filesize || $file->get('filesize') == 0))
916 $max_filesize = get_formatted_filesize($this->max_filesize, false);
918 $file->error[] = sprintf($user->lang[$this->error_prefix . 'WRONG_FILESIZE'], $max_filesize['value'], $max_filesize['unit']);
922 if (preg_match("#[\\/:*?\"<>|]#i", $file->get('realname')))
924 $file->error[] = sprintf($user->lang[$this->error_prefix . 'INVALID_FILENAME'], $file->get('realname'));
928 if (!$this->valid_extension($file))
930 $file->error[] = sprintf($user->lang[$this->error_prefix . 'DISALLOWED_EXTENSION'], $file->get('extension'));
934 if (!$this->valid_content($file))
936 $file->error[] = sprintf($user->lang[$this->error_prefix . 'DISALLOWED_CONTENT']);
941 * Check for allowed extension
943 function valid_extension(&$file)
945 return (in_array($file->get('extension'), $this->allowed_extensions)) ? true : false;
949 * Check for allowed dimension
951 function valid_dimensions(&$file)
953 if (!$this->max_width && !$this->max_height && !$this->min_width && !$this->min_height)
958 if (($file->get('width') > $this->max_width && $this->max_width) ||
959 ($file->get('height') > $this->max_height && $this->max_height) ||
960 ($file->get('width') < $this->min_width && $this->min_width) ||
961 ($file->get('height') < $this->min_height && $this->min_height))
970 * Check if form upload is valid
972 function is_valid($form_name)
974 return (isset($_FILES[$form_name]) && $_FILES[$form_name]['name'] != 'none') ? true : false;
979 * Check for allowed extension
981 function valid_content(&$file)
983 return ($file->check_content($this->disallowed_content));
987 * Return image type/extension mapping
989 function image_types()
993 2 => array('jpg', 'jpeg'),
998 7 => array('tif', 'tiff'),
999 8 => array('tif', 'tiff'),
1000 9 => array('jpg', 'jpeg'),
1001 10 => array('jpg', 'jpeg'),
1002 11 => array('jpg', 'jpeg'),
1003 12 => array('jpg', 'jpeg'),
1006 15 => array('wbmp'),