we included a check for getimagesize() existance... now we again can suppress notices...
[phpbb.git] / phpBB / download.php
blobc24ea81425e33ae88250633e7c72d50bb776b43c
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 define('IN_PHPBB', true);
15 $phpbb_root_path = './';
16 $phpEx = substr(strrchr(__FILE__, '.'), 1);
18 if (isset($_GET['avatar']))
20 require($phpbb_root_path . 'config.' . $phpEx);
21 require($phpbb_root_path . 'includes/acm/acm_' . $acm_type . '.' . $phpEx);
22 require($phpbb_root_path . 'includes/cache.' . $phpEx);
23 require($phpbb_root_path . 'includes/db/' . $dbms . '.' . $phpEx);
24 require($phpbb_root_path . 'includes/constants.' . $phpEx);
26 $db = new $sql_db();
27 $cache = new cache();
29 // Connect to DB
30 if (!@$db->sql_connect($dbhost, $dbuser, $dbpasswd, $dbname, $dbport, false, false))
32 exit;
34 unset($dbpasswd);
36 $config = $cache->obtain_config();
37 $filename = $_GET['avatar'];
38 $avatar_group = false;
39 if ($filename[0] === 'g')
41 $avatar_group = true;
42 $filename = substr($filename, 1);
45 // '==' is not a bug - . as the first char is as bad as no dot at all
46 if (strpos($filename, '.') == false)
48 header('HTTP/1.0 403 forbidden');
49 if (!empty($cache))
51 $cache->unload();
53 $db->sql_close();
54 exit;
57 $ext = substr(strrchr($filename, '.'), 1);
58 $filename = intval($filename);
60 if (!in_array($ext, array('png', 'gif', 'jpg', 'jpeg')))
62 // no way such an avatar could exist. They are not following the rules, stop the show.
63 header("HTTP/1.0 403 forbidden");
64 if (!empty($cache))
66 $cache->unload();
68 $db->sql_close();
69 exit;
72 if (!$filename)
74 // no way such an avatar could exist. They are not following the rules, stop the show.
75 header("HTTP/1.0 403 forbidden");
76 if (!empty($cache))
78 $cache->unload();
80 $db->sql_close();
81 exit;
84 send_avatar_to_browser(($avatar_group ? 'g' : '') . $filename . '.' . $ext);
86 if (!empty($cache))
88 $cache->unload();
90 $db->sql_close();
91 exit;
94 // implicit else: we are not in avatar mode
95 include($phpbb_root_path . 'common.' . $phpEx);
97 $download_id = request_var('id', 0);
98 $mode = request_var('mode', '');
99 $thumbnail = request_var('t', false);
101 // Start session management, do not update session page.
102 $user->session_begin(false);
103 $auth->acl($user->data);
104 $user->setup('viewtopic');
106 if (!$download_id)
108 trigger_error('NO_ATTACHMENT_SELECTED');
111 if (!$config['allow_attachments'] && !$config['allow_pm_attach'])
113 trigger_error('ATTACHMENT_FUNCTIONALITY_DISABLED');
116 $sql = 'SELECT attach_id, in_message, post_msg_id, extension, is_orphan, poster_id
117 FROM ' . ATTACHMENTS_TABLE . "
118 WHERE attach_id = $download_id";
119 $result = $db->sql_query_limit($sql, 1);
120 $attachment = $db->sql_fetchrow($result);
121 $db->sql_freeresult($result);
123 if (!$attachment)
125 trigger_error('ERROR_NO_ATTACHMENT');
128 if ((!$attachment['in_message'] && !$config['allow_attachments']) || ($attachment['in_message'] && !$config['allow_pm_attach']))
130 trigger_error('ATTACHMENT_FUNCTIONALITY_DISABLED');
133 $row = array();
135 if ($attachment['is_orphan'])
137 // We allow admins having attachment permissions to see orphan attachments...
138 $own_attachment = ($auth->acl_get('a_attach') || $attachment['poster_id'] == $user->data['user_id']) ? true : false;
140 if (!$own_attachment || ($attachment['in_message'] && !$auth->acl_get('u_pm_download')) || (!$attachment['in_message'] && !$auth->acl_get('u_download')))
142 trigger_error('ERROR_NO_ATTACHMENT');
145 // Obtain all extensions...
146 $extensions = $cache->obtain_attach_extensions(true);
148 else
150 if (!$attachment['in_message'])
153 $sql = 'SELECT p.forum_id, f.forum_password, f.parent_id
154 FROM ' . POSTS_TABLE . ' p, ' . FORUMS_TABLE . ' f
155 WHERE p.post_id = ' . $attachment['post_msg_id'] . '
156 AND p.forum_id = f.forum_id';
157 $result = $db->sql_query_limit($sql, 1);
158 $row = $db->sql_fetchrow($result);
159 $db->sql_freeresult($result);
161 // Global announcement?
162 $f_download = (!$row) ? $auth->acl_getf_global('f_download') : $auth->acl_get('f_download', $row['forum_id']);
164 if ($auth->acl_get('u_download') && $f_download)
166 if ($row && $row['forum_password'])
168 // Do something else ... ?
169 login_forum_box($row);
172 else
174 trigger_error('SORRY_AUTH_VIEW_ATTACH');
177 else
179 $row['forum_id'] = false;
180 if (!$auth->acl_get('u_pm_download'))
182 trigger_error('SORRY_AUTH_VIEW_ATTACH');
186 // disallowed?
187 $extensions = array();
188 if (!extension_allowed($row['forum_id'], $attachment['extension'], $extensions))
190 trigger_error(sprintf($user->lang['EXTENSION_DISABLED_AFTER_POSTING'], $attachment['extension']));
194 if (!download_allowed())
196 trigger_error($user->lang['LINKAGE_FORBIDDEN']);
199 $download_mode = (int) $extensions[$attachment['extension']]['download_mode'];
201 // Fetching filename here to prevent sniffing of filename
202 $sql = 'SELECT attach_id, is_orphan, in_message, post_msg_id, extension, physical_filename, real_filename, mimetype
203 FROM ' . ATTACHMENTS_TABLE . "
204 WHERE attach_id = $download_id";
205 $result = $db->sql_query_limit($sql, 1);
206 $attachment = $db->sql_fetchrow($result);
207 $db->sql_freeresult($result);
209 if (!$attachment)
211 trigger_error('ERROR_NO_ATTACHMENT');
214 $attachment['physical_filename'] = basename($attachment['physical_filename']);
215 $display_cat = $extensions[$attachment['extension']]['display_cat'];
217 if (($display_cat == ATTACHMENT_CATEGORY_IMAGE || $display_cat == ATTACHMENT_CATEGORY_THUMB) && !$user->optionget('viewimg'))
219 $display_cat = ATTACHMENT_CATEGORY_NONE;
222 if ($display_cat == ATTACHMENT_CATEGORY_FLASH && !$user->optionget('viewflash'))
224 $display_cat = ATTACHMENT_CATEGORY_NONE;
227 if ($thumbnail)
229 $attachment['physical_filename'] = 'thumb_' . $attachment['physical_filename'];
231 else if (($display_cat == ATTACHMENT_CATEGORY_NONE || $display_cat == ATTACHMENT_CATEGORY_IMAGE) && !$attachment['is_orphan'])
233 // Update download count
234 $sql = 'UPDATE ' . ATTACHMENTS_TABLE . '
235 SET download_count = download_count + 1
236 WHERE attach_id = ' . $attachment['attach_id'];
237 $db->sql_query($sql);
240 if ($display_cat == ATTACHMENT_CATEGORY_IMAGE && $mode === 'view' && (strpos($attachment['mimetype'], 'image') === 0) && strpos(strtolower($user->browser), 'msie') !== false)
242 wrap_img_in_html(append_sid('./download.' . $phpEx, 'id=' . $attachment['attach_id']), $attachment['real_filename']);
244 else
246 // Determine the 'presenting'-method
247 if ($download_mode == PHYSICAL_LINK)
249 // This presenting method should no longer be used
250 if (!@is_dir($phpbb_root_path . $config['upload_path']))
252 trigger_error($user->lang['PHYSICAL_DOWNLOAD_NOT_POSSIBLE']);
255 redirect($phpbb_root_path . $config['upload_path'] . '/' . $attachment['physical_filename']);
256 exit;
258 else
260 send_file_to_browser($attachment, $config['upload_path'], $display_cat);
261 exit;
267 * A simplified function to deliver avatars
268 * The argument needs to be checked before calling this function.
270 function send_avatar_to_browser($file)
272 global $config, $phpbb_root_path;
274 $prefix = $config['avatar_salt'] . '_';
275 $image_dir = $config['avatar_path'];
277 // worst-case default
278 $browser = (!empty($_SERVER['HTTP_USER_AGENT'])) ? htmlspecialchars((string) $_SERVER['HTTP_USER_AGENT']) : 'msie 6.0';
280 // Adjust image_dir path (no trailing slash)
281 if (substr($image_dir, -1, 1) == '/' || substr($image_dir, -1, 1) == '\\')
283 $image_dir = substr($image_dir, 0, -1) . '/';
285 $image_dir = str_replace(array('../', '..\\', './', '.\\'), '', $image_dir);
287 if ($image_dir && ($image_dir[0] == '/' || $image_dir[0] == '\\'))
289 $image_dir = '';
291 $file_path = $phpbb_root_path . $image_dir . '/' . $prefix . $file;
293 if ((@file_exists($file_path) && @is_readable($file_path)) || headers_sent())
295 header('Pragma: public');
297 $image_data = @getimagesize($file_path);
298 header('Content-Type: ' . image_type_to_mime_type($image_data[2]));
300 if (strpos(strtolower($browser), 'msie') !== false)
302 header('Content-Disposition: attachment; ' . header_filename($file));
304 if (strpos(strtolower($browser), 'msie 6.0') !== false)
306 header('Expires: -1');
308 else
310 header('Expires: ' . gmdate('D, d M Y H:i:s \G\M\T', time() + 31536000));
313 else
315 header('Content-Disposition: inline; ' . header_filename($file));
316 header('Expires: ' . gmdate('D, d M Y H:i:s \G\M\T', time() + 31536000));
319 $size = @filesize($file_path);
320 if ($size)
322 header("Content-Length: $size");
325 readfile($file_path);
326 flush();
328 else
330 header('HTTP/1.0 404 not found');
335 * Wraps an url into a simple html page. Used to display attachments in IE.
336 * this is a workaround for now; might be moved to template system later
337 * direct any complaints to 1 Microsoft Way, Redmond
339 function wrap_img_in_html($src, $title)
341 echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-Strict.dtd">';
342 echo '<html>';
343 echo '<head>';
344 echo '<meta http-equiv="content-type" content="text/html; charset=UTF-8" />';
345 echo '<title>' . $title . '</title>';
346 echo '</head>';
347 echo '<body>';
348 echo '<div>';
349 echo '<img src="' . $src . '" alt="' . $title . '" />';
350 echo '</div>';
351 echo '</body>';
352 echo '</html>';
356 * Send file to browser
358 function send_file_to_browser($attachment, $upload_dir, $category)
360 global $user, $db, $config, $phpbb_root_path;
362 $filename = $phpbb_root_path . $upload_dir . '/' . $attachment['physical_filename'];
364 if (!@file_exists($filename))
366 trigger_error($user->lang['ERROR_NO_ATTACHMENT'] . '<br /><br />' . sprintf($user->lang['FILE_NOT_FOUND_404'], $filename));
369 // Correct the mime type - we force application/octetstream for all files, except images
370 // Please do not change this, it is a security precaution
371 if ($category != ATTACHMENT_CATEGORY_IMAGE || strpos($attachment['mimetype'], 'image') !== 0)
373 $attachment['mimetype'] = (strpos(strtolower($user->browser), 'msie') !== false || strpos(strtolower($user->browser), 'opera') !== false) ? 'application/octetstream' : 'application/octet-stream';
376 if (@ob_get_length())
378 @ob_end_clean();
381 // Now send the File Contents to the Browser
382 $size = @filesize($filename);
384 // To correctly display further errors we need to make sure we are using the correct headers for both (unsetting content-length may not work)
386 // Check if headers already sent or not able to get the file contents.
387 if (headers_sent() || !@file_exists($filename) || !@is_readable($filename))
389 // PHP track_errors setting On?
390 if (!empty($php_errormsg))
392 trigger_error($user->lang['UNABLE_TO_DELIVER_FILE'] . '<br />' . sprintf($user->lang['TRACKED_PHP_ERROR'], $php_errormsg));
395 trigger_error('UNABLE_TO_DELIVER_FILE');
398 // Now the tricky part... let's dance
399 header('Pragma: public');
402 * Commented out X-Sendfile support. To not expose the physical filename within the header if xsendfile is absent we need to look into methods of checking it's status.
404 * Try X-Sendfile since it is much more server friendly - only works if the path is *not* outside of the root path...
405 * lighttpd has core support for it. An apache2 module is available at http://celebnamer.celebworld.ws/stuff/mod_xsendfile/
407 * Not really ideal, but should work fine...
408 * <code>
409 * if (strpos($upload_dir, '/') !== 0 && strpos($upload_dir, '../') === false)
411 * header('X-Sendfile: ' . $filename);
413 * </code>
416 // Send out the Headers. Do not set Content-Disposition to inline please, it is a security measure for users using the Internet Explorer.
417 header('Content-Type: ' . $attachment['mimetype']);
419 if (empty($user->browser) || (strpos(strtolower($user->browser), 'msie') !== false))
421 header('Content-Disposition: attachment; ' . header_filename(htmlspecialchars_decode($attachment['real_filename'])));
422 if (empty($user->browser) || (strpos(strtolower($user->browser), 'msie 6.0') !== false))
424 header('expires: -1');
427 else
429 header('Content-Disposition: ' . ((strpos($attachment['mimetype'], 'image') === 0) ? 'inline' : 'attachment') . '; ' . header_filename(htmlspecialchars_decode($attachment['real_filename'])));
432 if ($size)
434 header("Content-Length: $size");
437 // Try to deliver in chunks
438 @set_time_limit(0);
440 $fp = @fopen($filename, 'rb');
442 if ($fp !== false)
444 while (!feof($fp))
446 echo fread($fp, 8192);
448 fclose($fp);
451 flush();
452 exit;
456 * Get a browser friendly UTF-8 encoded filename
458 function header_filename($file)
460 $user_agent = (!empty($_SERVER['HTTP_USER_AGENT'])) ? htmlspecialchars((string) $_SERVER['HTTP_USER_AGENT']) : '';
462 // There be dragons here.
463 // Not many follows the RFC...
464 if (strpos($user_agent, 'MSIE') !== false || strpos($user_agent, 'Safari') !== false || strpos($user_agent, 'Konqueror') !== false)
466 return "filename=" . rawurlencode($file);
469 // follow the RFC for extended filename for the rest
470 return "filename*=UTF-8''" . rawurlencode($file);
474 * Check if downloading item is allowed
476 function download_allowed()
478 global $config, $user, $db;
480 if (!$config['secure_downloads'])
482 return true;
485 $url = (!empty($_SERVER['HTTP_REFERER'])) ? trim($_SERVER['HTTP_REFERER']) : trim(getenv('HTTP_REFERER'));
487 if (!$url)
489 return ($config['secure_allow_empty_referer']) ? true : false;
492 // Split URL into domain and script part
493 $url = @parse_url($url);
495 if ($url === false)
497 return ($config['secure_allow_empty_referer']) ? true : false;
500 $hostname = $url['host'];
501 unset($url);
503 $allowed = ($config['secure_allow_deny']) ? false : true;
504 $iplist = array();
506 if (($ip_ary = @gethostbynamel($hostname)) !== false)
508 foreach ($ip_ary as $ip)
510 if ($ip)
512 $iplist[] = $ip;
517 // Check for own server...
518 $server_name = (!empty($_SERVER['SERVER_NAME'])) ? $_SERVER['SERVER_NAME'] : getenv('SERVER_NAME');
520 // Forcing server vars is the only way to specify/override the protocol
521 if ($config['force_server_vars'] || !$server_name)
523 $server_name = $config['server_name'];
526 if (preg_match('#^.*?' . preg_quote($server_name, '#') . '.*?$#i', $hostname))
528 $allowed = true;
531 // Get IP's and Hostnames
532 if (!$allowed)
534 $sql = 'SELECT site_ip, site_hostname, ip_exclude
535 FROM ' . SITELIST_TABLE;
536 $result = $db->sql_query($sql);
538 while ($row = $db->sql_fetchrow($result))
540 $site_ip = trim($row['site_ip']);
541 $site_hostname = trim($row['site_hostname']);
543 if ($site_ip)
545 foreach ($iplist as $ip)
547 if (preg_match('#^' . str_replace('*', '.*?', preg_quote($site_ip, '#')) . '$#i', $ip))
549 if ($row['ip_exclude'])
551 $allowed = ($config['secure_allow_deny']) ? false : true;
552 break 2;
554 else
556 $allowed = ($config['secure_allow_deny']) ? true : false;
562 if ($site_hostname)
564 if (preg_match('#^' . str_replace('*', '.*?', preg_quote($site_hostname, '#')) . '$#i', $hostname))
566 if ($row['ip_exclude'])
568 $allowed = ($config['secure_allow_deny']) ? false : true;
569 break;
571 else
573 $allowed = ($config['secure_allow_deny']) ? true : false;
578 $db->sql_freeresult($result);
581 return $allowed;