ups, seems i really forgot to change this. :)
[phpbb.git] / phpBB / download / file.php
blobad2abf880e81f7c3cf33a007d95265439957d56e
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 = (defined('PHPBB_ROOT_PATH')) ? 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 if (@readfile($file_path) === false)
327 $fp = @fopen($file_path, 'rb');
329 if ($fp !== false)
331 while (!feof($fp))
333 echo fread($fp, 8192);
335 fclose($fp);
339 flush();
341 else
343 header('HTTP/1.0 404 not found');
348 * Wraps an url into a simple html page. Used to display attachments in IE.
349 * this is a workaround for now; might be moved to template system later
350 * direct any complaints to 1 Microsoft Way, Redmond
352 function wrap_img_in_html($src, $title)
354 echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-Strict.dtd">';
355 echo '<html>';
356 echo '<head>';
357 echo '<meta http-equiv="content-type" content="text/html; charset=UTF-8" />';
358 echo '<title>' . $title . '</title>';
359 echo '</head>';
360 echo '<body>';
361 echo '<div>';
362 echo '<img src="' . $src . '" alt="' . $title . '" />';
363 echo '</div>';
364 echo '</body>';
365 echo '</html>';
369 * Send file to browser
371 function send_file_to_browser($attachment, $upload_dir, $category)
373 global $user, $db, $config, $phpbb_root_path;
375 $filename = $phpbb_root_path . $upload_dir . '/' . $attachment['physical_filename'];
377 if (!@file_exists($filename))
379 trigger_error($user->lang['ERROR_NO_ATTACHMENT'] . '<br /><br />' . sprintf($user->lang['FILE_NOT_FOUND_404'], $filename));
382 // Correct the mime type - we force application/octetstream for all files, except images
383 // Please do not change this, it is a security precaution
384 if ($category != ATTACHMENT_CATEGORY_IMAGE || strpos($attachment['mimetype'], 'image') !== 0)
386 $attachment['mimetype'] = (strpos(strtolower($user->browser), 'msie') !== false || strpos(strtolower($user->browser), 'opera') !== false) ? 'application/octetstream' : 'application/octet-stream';
389 if (@ob_get_length())
391 @ob_end_clean();
394 // Now send the File Contents to the Browser
395 $size = @filesize($filename);
397 // To correctly display further errors we need to make sure we are using the correct headers for both (unsetting content-length may not work)
399 // Check if headers already sent or not able to get the file contents.
400 if (headers_sent() || !@file_exists($filename) || !@is_readable($filename))
402 // PHP track_errors setting On?
403 if (!empty($php_errormsg))
405 trigger_error($user->lang['UNABLE_TO_DELIVER_FILE'] . '<br />' . sprintf($user->lang['TRACKED_PHP_ERROR'], $php_errormsg));
408 trigger_error('UNABLE_TO_DELIVER_FILE');
411 // Now the tricky part... let's dance
412 header('Pragma: public');
415 * 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.
417 * Try X-Sendfile since it is much more server friendly - only works if the path is *not* outside of the root path...
418 * lighttpd has core support for it. An apache2 module is available at http://celebnamer.celebworld.ws/stuff/mod_xsendfile/
420 * Not really ideal, but should work fine...
421 * <code>
422 * if (strpos($upload_dir, '/') !== 0 && strpos($upload_dir, '../') === false)
424 * header('X-Sendfile: ' . $filename);
426 * </code>
429 // Send out the Headers. Do not set Content-Disposition to inline please, it is a security measure for users using the Internet Explorer.
430 header('Content-Type: ' . $attachment['mimetype']);
432 if (empty($user->browser) || (strpos(strtolower($user->browser), 'msie') !== false))
434 header('Content-Disposition: attachment; ' . header_filename(htmlspecialchars_decode($attachment['real_filename'])));
435 if (empty($user->browser) || (strpos(strtolower($user->browser), 'msie 6.0') !== false))
437 header('expires: -1');
440 else
442 header('Content-Disposition: ' . ((strpos($attachment['mimetype'], 'image') === 0) ? 'inline' : 'attachment') . '; ' . header_filename(htmlspecialchars_decode($attachment['real_filename'])));
445 if ($size)
447 header("Content-Length: $size");
450 // Try to deliver in chunks
451 @set_time_limit(0);
453 $fp = @fopen($filename, 'rb');
455 if ($fp !== false)
457 while (!feof($fp))
459 echo fread($fp, 8192);
461 fclose($fp);
463 else
465 @readfile($filename);
468 flush();
469 exit;
473 * Get a browser friendly UTF-8 encoded filename
475 function header_filename($file)
477 $user_agent = (!empty($_SERVER['HTTP_USER_AGENT'])) ? htmlspecialchars((string) $_SERVER['HTTP_USER_AGENT']) : '';
479 // There be dragons here.
480 // Not many follows the RFC...
481 if (strpos($user_agent, 'MSIE') !== false || strpos($user_agent, 'Safari') !== false || strpos($user_agent, 'Konqueror') !== false)
483 return "filename=" . rawurlencode($file);
486 // follow the RFC for extended filename for the rest
487 return "filename*=UTF-8''" . rawurlencode($file);
491 * Check if downloading item is allowed
493 function download_allowed()
495 global $config, $user, $db;
497 if (!$config['secure_downloads'])
499 return true;
502 $url = (!empty($_SERVER['HTTP_REFERER'])) ? trim($_SERVER['HTTP_REFERER']) : trim(getenv('HTTP_REFERER'));
504 if (!$url)
506 return ($config['secure_allow_empty_referer']) ? true : false;
509 // Split URL into domain and script part
510 $url = @parse_url($url);
512 if ($url === false)
514 return ($config['secure_allow_empty_referer']) ? true : false;
517 $hostname = $url['host'];
518 unset($url);
520 $allowed = ($config['secure_allow_deny']) ? false : true;
521 $iplist = array();
523 if (($ip_ary = @gethostbynamel($hostname)) !== false)
525 foreach ($ip_ary as $ip)
527 if ($ip)
529 $iplist[] = $ip;
534 // Check for own server...
535 $server_name = (!empty($_SERVER['SERVER_NAME'])) ? $_SERVER['SERVER_NAME'] : getenv('SERVER_NAME');
537 // Forcing server vars is the only way to specify/override the protocol
538 if ($config['force_server_vars'] || !$server_name)
540 $server_name = $config['server_name'];
543 if (preg_match('#^.*?' . preg_quote($server_name, '#') . '.*?$#i', $hostname))
545 $allowed = true;
548 // Get IP's and Hostnames
549 if (!$allowed)
551 $sql = 'SELECT site_ip, site_hostname, ip_exclude
552 FROM ' . SITELIST_TABLE;
553 $result = $db->sql_query($sql);
555 while ($row = $db->sql_fetchrow($result))
557 $site_ip = trim($row['site_ip']);
558 $site_hostname = trim($row['site_hostname']);
560 if ($site_ip)
562 foreach ($iplist as $ip)
564 if (preg_match('#^' . str_replace('\*', '.*?', preg_quote($site_ip, '#')) . '$#i', $ip))
566 if ($row['ip_exclude'])
568 $allowed = ($config['secure_allow_deny']) ? false : true;
569 break 2;
571 else
573 $allowed = ($config['secure_allow_deny']) ? true : false;
579 if ($site_hostname)
581 if (preg_match('#^' . str_replace('\*', '.*?', preg_quote($site_hostname, '#')) . '$#i', $hostname))
583 if ($row['ip_exclude'])
585 $allowed = ($config['secure_allow_deny']) ? false : true;
586 break;
588 else
590 $allowed = ($config['secure_allow_deny']) ? true : false;
595 $db->sql_freeresult($result);
598 return $allowed;