(no commit message)
[atutor.git] / include / lib / upload.php
1 <?php
2 /*
3 This is an upload script for SWFUpload that attempts to properly handle uploaded files
4 in a secure way.
5
6 Notes:
7         
8         SWFUpload doesn't send a MIME-TYPE. In my opinion this is ok since MIME-TYPE is no better than
9          file extension and is probably worse because it can vary from OS to OS and browser to browser (for the same file).
10          The best thing to do is content sniff the file but this can be resource intensive, is difficult, and can still be fooled or inaccurate.
11          Accepting uploads can never be 100% secure.
12          
13         You can't guarantee that SWFUpload is really the source of the upload.  A malicious user
14          will probably be uploading from a tool that sends invalid or false metadata about the file.
15          The script should properly handle this.
16          
17         The script should not over-write existing files.
18         
19         The script should strip away invalid characters from the file name or reject the file.
20         
21         The script should not allow files to be saved that could then be executed on the webserver (such as .php files).
22          To keep things simple we will use an extension whitelist for allowed file extensions.  Which files should be allowed
23          depends on your server configuration. The extension white-list is _not_ tied your SWFUpload file_types setting
24         
25         For better security uploaded files should be stored outside the webserver's document root.  Downloaded files
26          should be accessed via a download script that proxies from the file system to the webserver.  This prevents
27          users from executing malicious uploaded files.  It also gives the developer control over the outgoing mime-type,
28          access restrictions, etc.  This, however, is outside the scope of this script.
29         
30         SWFUpload sends each file as a separate POST rather than several files in a single post. This is a better
31          method in my opinions since it better handles file size limits, e.g., if post_max_size is 100 MB and I post two 60 MB files then
32          the post would fail (2x60MB = 120MB). In SWFupload each 60 MB is posted as separate post and we stay within the limits. This
33          also simplifies the upload script since we only have to handle a single file.
34         
35         The script should properly handle situations where the post was too large or the posted file is larger than
36          our defined max.  These values are not tied to your SWFUpload file_size_limit setting.
37         
38 */
39
40 // Code for Session Cookie workaround
41         if (isset($_POST["PHPSESSID"])) {
42                 session_id($_POST["PHPSESSID"]);
43         } else if (isset($_GET["PHPSESSID"])) {
44                 session_id($_GET["PHPSESSID"]);
45         }
46
47         session_start();
48
49 // Check post_max_size (http://us3.php.net/manual/en/features.file-upload.php#73762)
50         $POST_MAX_SIZE = ini_get('post_max_size');
51         $unit = strtoupper(substr($POST_MAX_SIZE, -1));
52         $multiplier = ($unit == 'M' ? 1048576 : ($unit == 'K' ? 1024 : ($unit == 'G' ? 1073741824 : 1)));
53
54         if ((int)$_SERVER['CONTENT_LENGTH'] > $multiplier*(int)$POST_MAX_SIZE && $POST_MAX_SIZE) {
55                 header("HTTP/1.1 500 Internal Server Error");
56                 echo "POST exceeded maximum allowed size.";
57                 exit(0);
58         }
59
60 // Settings
61 //      $save_path = "/home/elicochr/public_html/sos/uploads/";
62         $save_path = urldecode($_GET['path']);
63         $upload_name = "Filedata";
64         $max_file_size_in_bytes = 2147483647;                           // 2GB in bytes
65         //$extension_whitelist = array("jpg", "gif", "png");    // Allowed file extensions
66         $valid_chars_regex = '.A-Z0-9_ !@#$%^&()+={}\[\]\',~`-';                                // Characters allowed in the file name (in a Regular Expression format)
67         
68 // Other variables      
69         $MAX_FILENAME_LENGTH = 260;
70         $file_name = "";
71         $file_extension = "";
72         $uploadErrors = array(
73         0=>"There is no error, the file uploaded with success",
74         1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
75         2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
76         3=>"The uploaded file was only partially uploaded",
77         4=>"No file was uploaded",
78         6=>"Missing a temporary folder"
79         );
80
81
82 // Validate the upload
83         if (!isset($_FILES[$upload_name])) {
84                 HandleError("No upload found in \$_FILES for " . $upload_name);
85                 exit(0);
86         } else if (isset($_FILES[$upload_name]["error"]) && $_FILES[$upload_name]["error"] != 0) {
87                 HandleError($uploadErrors[$_FILES[$upload_name]["error"]]);
88                 exit(0);
89         } else if (!isset($_FILES[$upload_name]["tmp_name"]) || !@is_uploaded_file($_FILES[$upload_name]["tmp_name"])) {
90                 HandleError("Upload failed is_uploaded_file test.");
91                 exit(0);
92         } else if (!isset($_FILES[$upload_name]['name'])) {
93                 HandleError("File has no name.");
94                 exit(0);
95         }
96         
97 // Validate the file size (Warning: the largest files supported by this code is 2GB)
98         $file_size = @filesize($_FILES[$upload_name]["tmp_name"]);
99         if (!$file_size || $file_size > $max_file_size_in_bytes) {
100                 HandleError("File exceeds the maximum allowed size");
101                 exit(0);
102         }
103         
104         if ($file_size <= 0) {
105                 HandleError("File size outside allowed lower bound");
106                 exit(0);
107         }
108
109
110 // Validate file name (for our purposes we'll just remove invalid characters)
111         $file_name = preg_replace('/[^'.$valid_chars_regex.']|\.+$/i', "", basename($_FILES[$upload_name]['name']));
112         if (strlen($file_name) == 0 || strlen($file_name) > $MAX_FILENAME_LENGTH) {
113                 HandleError("Invalid file name");
114                 exit(0);
115         }
116
117
118 // Validate that we won't over-write an existing file
119         if (file_exists($save_path . $file_name)) {
120                 HandleError("File with this name already exists");
121                 exit(0);
122         }
123
124 // Validate file extension
125 /*      $path_info = pathinfo($_FILES[$upload_name]['name']);
126         $file_extension = $path_info["extension"];
127         $is_valid_extension = false;
128         foreach ($extension_whitelist as $extension) {
129                 if ($file_extension == $extension) {
130                         $is_valid_extension = true;
131                         break;
132                 }
133         }
134         if (!$is_valid_extension) {
135                 HandleError("Invalid file extension");
136                 exit(0);
137         }*/
138
139 // Validate file contents (extension and mime-type can't be trusted)
140         /*
141                 Validating the file contents is OS and web server configuration dependant.  Also, it may not be reliable.
142                 See the comments on this page: http://us2.php.net/fileinfo
143                 
144                 Also see http://72.14.253.104/search?q=cache:3YGZfcnKDrYJ:www.scanit.be/uploads/php-file-upload.pdf+php+file+command&hl=en&ct=clnk&cd=8&gl=us&client=firefox-a
145                  which describes how a PHP script can be embedded within a GIF image file.
146                 
147                 Therefore, no sample code will be provided here.  Research the issue, decide how much security is
148                  needed, and implement a solution that meets the needs.
149         */
150
151
152 // Process the file
153         /*
154                 At this point we are ready to process the valid file. This sample code shows how to save the file. Other tasks
155                  could be done such as creating an entry in a database or generating a thumbnail.
156                  
157                 Depending on your server OS and needs you may need to set the Security Permissions on the file after it has
158                 been saved.
159         */
160         if (!@move_uploaded_file($_FILES[$upload_name]["tmp_name"], $save_path.$file_name)) {
161                 HandleError("File could not be saved.");
162                 exit(0);
163         }
164
165 // Return output to the browser (only supported by SWFUpload for Flash Player 9)
166
167         echo "File Received";
168         exit(0);
169
170
171 /* Handles the error output.  This function was written for SWFUpload for Flash Player 8 which
172 cannot return data to the server, so it just returns a 500 error. For Flash Player 9 you will
173 want to change this to return the server data you want to indicate an error and then use SWFUpload's
174 uploadSuccess to check the server_data for your error indicator. */
175 function HandleError($message) {
176         header("HTTP/1.1 500 Internal Server Error");
177         echo $message;
178 }
179 ?>