6 * @copyright (c) 2005 phpBB Group
7 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
14 define('IN_PHPBB', true);
15 $phpbb_root_path = (defined('PHPBB_ROOT_PATH')) ? PHPBB_ROOT_PATH : './../';
16 $phpEx = substr(strrchr(__FILE__, '.'), 1);
20 if (isset($_SERVER['CONTENT_TYPE']))
22 if ($_SERVER['CONTENT_TYPE'] === 'application/x-java-archive')
27 else if (isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], 'Java') !== false)
32 if (isset($_GET['avatar']))
34 require($phpbb_root_path . 'includes/startup.' . $phpEx);
35 require($phpbb_root_path . 'config.' . $phpEx);
37 if (!defined('PHPBB_INSTALLED') || empty($dbms) || empty($acm_type))
42 require($phpbb_root_path . 'includes/acm/acm_' . $acm_type . '.' . $phpEx);
43 require($phpbb_root_path . 'includes/cache.' . $phpEx);
44 require($phpbb_root_path . 'includes/db/' . $dbms . '.' . $phpEx);
45 require($phpbb_root_path . 'includes/constants.' . $phpEx);
46 require($phpbb_root_path . 'includes/functions.' . $phpEx);
52 if (!@$db->sql_connect($dbhost, $dbuser, $dbpasswd, $dbname, $dbport, false, false))
59 $browser = (!empty($_SERVER['HTTP_USER_AGENT'])) ? htmlspecialchars((string) $_SERVER['HTTP_USER_AGENT']) : 'msie 6.0';
61 $config = $cache->obtain_config();
62 $filename = request_var('avatar', '');
63 $avatar_group = false;
66 if (isset($filename[0]) && $filename[0] === 'g')
69 $filename = substr($filename, 1);
72 // '==' is not a bug - . as the first char is as bad as no dot at all
73 if (strpos($filename, '.') == false)
75 send_status_line(403, 'Forbidden');
81 $ext = substr(strrchr($filename, '.'), 1);
82 $stamp = (int) substr(stristr($filename, '_'), 1);
83 $filename = (int) $filename;
84 $exit = set_modified_headers($stamp, $browser);
86 if (!$exit && !in_array($ext, array('png', 'gif', 'jpg', 'jpeg')))
88 // no way such an avatar could exist. They are not following the rules, stop the show.
89 send_status_line(403, 'Forbidden');
98 // no way such an avatar could exist. They are not following the rules, stop the show.
99 send_status_line(403, 'Forbidden');
103 send_avatar_to_browser(($avatar_group ? 'g' : '') . $filename . '.' . $ext, $browser);
109 // implicit else: we are not in avatar mode
110 include($phpbb_root_path . 'common.' . $phpEx);
112 $download_id = request_var('id', 0);
113 $mode = request_var('mode', '');
114 $thumbnail = request_var('t', false);
116 // Start session management, do not update session page.
117 $user->session_begin(false);
118 $auth->acl($user->data);
119 $user->setup('viewtopic');
123 send_status_line(404, 'Not Found');
124 trigger_error('NO_ATTACHMENT_SELECTED');
127 if (!$config['allow_attachments'] && !$config['allow_pm_attach'])
129 send_status_line(404, 'Not Found');
130 trigger_error('ATTACHMENT_FUNCTIONALITY_DISABLED');
133 $sql = 'SELECT attach_id, in_message, post_msg_id, extension, is_orphan, poster_id, filetime
134 FROM ' . ATTACHMENTS_TABLE . "
135 WHERE attach_id = $download_id";
136 $result = $db->sql_query_limit($sql, 1);
137 $attachment = $db->sql_fetchrow($result);
138 $db->sql_freeresult($result);
142 send_status_line(404, 'Not Found');
143 trigger_error('ERROR_NO_ATTACHMENT');
146 if ((!$attachment['in_message'] && !$config['allow_attachments']) || ($attachment['in_message'] && !$config['allow_pm_attach']))
148 send_status_line(404, 'Not Found');
149 trigger_error('ATTACHMENT_FUNCTIONALITY_DISABLED');
154 if ($attachment['is_orphan'])
156 // We allow admins having attachment permissions to see orphan attachments...
157 $own_attachment = ($auth->acl_get('a_attach') || $attachment['poster_id'] == $user->data['user_id']) ? true : false;
159 if (!$own_attachment || ($attachment['in_message'] && !$auth->acl_get('u_pm_download')) || (!$attachment['in_message'] && !$auth->acl_get('u_download')))
161 send_status_line(404, 'Not Found');
162 trigger_error('ERROR_NO_ATTACHMENT');
165 // Obtain all extensions...
166 $extensions = $cache->obtain_attach_extensions(true);
170 if (!$attachment['in_message'])
173 $sql = 'SELECT p.forum_id, f.forum_password, f.parent_id
174 FROM ' . POSTS_TABLE . ' p, ' . FORUMS_TABLE . ' f
175 WHERE p.post_id = ' . $attachment['post_msg_id'] . '
176 AND p.forum_id = f.forum_id';
177 $result = $db->sql_query_limit($sql, 1);
178 $row = $db->sql_fetchrow($result);
179 $db->sql_freeresult($result);
181 // Global announcement?
182 $f_download = (!$row) ? $auth->acl_getf_global('f_download') : $auth->acl_get('f_download', $row['forum_id']);
184 if ($auth->acl_get('u_download') && $f_download)
186 if ($row && $row['forum_password'])
188 // Do something else ... ?
189 login_forum_box($row);
194 send_status_line(403, 'Forbidden');
195 trigger_error('SORRY_AUTH_VIEW_ATTACH');
200 $row['forum_id'] = false;
201 if (!$auth->acl_get('u_pm_download'))
203 send_status_line(403, 'Forbidden');
204 trigger_error('SORRY_AUTH_VIEW_ATTACH');
207 // Check if the attachment is within the users scope...
208 $sql = 'SELECT user_id, author_id
209 FROM ' . PRIVMSGS_TO_TABLE . '
210 WHERE msg_id = ' . $attachment['post_msg_id'];
211 $result = $db->sql_query($sql);
214 while ($user_row = $db->sql_fetchrow($result))
216 if ($user->data['user_id'] == $user_row['user_id'] || $user->data['user_id'] == $user_row['author_id'])
222 $db->sql_freeresult($result);
226 send_status_line(403, 'Forbidden');
227 trigger_error('ERROR_NO_ATTACHMENT');
232 $extensions = array();
233 if (!extension_allowed($row['forum_id'], $attachment['extension'], $extensions))
235 send_status_line(404, 'Forbidden');
236 trigger_error(sprintf($user->lang['EXTENSION_DISABLED_AFTER_POSTING'], $attachment['extension']));
240 if (!download_allowed())
242 send_status_line(403, 'Forbidden');
243 trigger_error($user->lang['LINKAGE_FORBIDDEN']);
246 $download_mode = (int) $extensions[$attachment['extension']]['download_mode'];
248 // Fetching filename here to prevent sniffing of filename
249 $sql = 'SELECT attach_id, is_orphan, in_message, post_msg_id, extension, physical_filename, real_filename, mimetype, filetime
250 FROM ' . ATTACHMENTS_TABLE . "
251 WHERE attach_id = $download_id";
252 $result = $db->sql_query_limit($sql, 1);
253 $attachment = $db->sql_fetchrow($result);
254 $db->sql_freeresult($result);
258 send_status_line(404, 'Not Found');
259 trigger_error('ERROR_NO_ATTACHMENT');
262 $attachment['physical_filename'] = utf8_basename($attachment['physical_filename']);
263 $display_cat = $extensions[$attachment['extension']]['display_cat'];
265 if (($display_cat == ATTACHMENT_CATEGORY_IMAGE || $display_cat == ATTACHMENT_CATEGORY_THUMB) && !$user->optionget('viewimg'))
267 $display_cat = ATTACHMENT_CATEGORY_NONE;
270 if ($display_cat == ATTACHMENT_CATEGORY_FLASH && !$user->optionget('viewflash'))
272 $display_cat = ATTACHMENT_CATEGORY_NONE;
277 $attachment['physical_filename'] = 'thumb_' . $attachment['physical_filename'];
279 else if (($display_cat == ATTACHMENT_CATEGORY_NONE/* || $display_cat == ATTACHMENT_CATEGORY_IMAGE*/) && !$attachment['is_orphan'])
281 // Update download count
282 $sql = 'UPDATE ' . ATTACHMENTS_TABLE . '
283 SET download_count = download_count + 1
284 WHERE attach_id = ' . $attachment['attach_id'];
285 $db->sql_query($sql);
288 if ($display_cat == ATTACHMENT_CATEGORY_IMAGE && $mode === 'view' && (strpos($attachment['mimetype'], 'image') === 0) && ((strpos(strtolower($user->browser), 'msie') !== false) && (strpos(strtolower($user->browser), 'msie 8.0') === false)))
290 wrap_img_in_html(append_sid($phpbb_root_path . 'download/file.' . $phpEx, 'id=' . $attachment['attach_id']), $attachment['real_filename']);
295 // Determine the 'presenting'-method
296 if ($download_mode == PHYSICAL_LINK)
298 // This presenting method should no longer be used
299 if (!@is_dir($phpbb_root_path . $config['upload_path']))
301 send_status_line(500, 'Internal Server Error');
302 trigger_error($user->lang['PHYSICAL_DOWNLOAD_NOT_POSSIBLE']);
305 redirect($phpbb_root_path . $config['upload_path'] . '/' . $attachment['physical_filename']);
310 send_file_to_browser($attachment, $config['upload_path'], $display_cat);
317 * A simplified function to deliver avatars
318 * The argument needs to be checked before calling this function.
320 function send_avatar_to_browser($file, $browser)
322 global $config, $phpbb_root_path;
324 $prefix = $config['avatar_salt'] . '_';
325 $image_dir = $config['avatar_path'];
327 // Adjust image_dir path (no trailing slash)
328 if (substr($image_dir, -1, 1) == '/' || substr($image_dir, -1, 1) == '\\')
330 $image_dir = substr($image_dir, 0, -1) . '/';
332 $image_dir = str_replace(array('../', '..\\', './', '.\\'), '', $image_dir);
334 if ($image_dir && ($image_dir[0] == '/' || $image_dir[0] == '\\'))
338 $file_path = $phpbb_root_path . $image_dir . '/' . $prefix . $file;
340 if ((@file_exists($file_path) && @is_readable($file_path)) && !headers_sent())
342 header('Pragma: public');
344 $image_data = @getimagesize($file_path);
345 header('Content-Type: ' . image_type_to_mime_type($image_data[2]));
347 if (strpos(strtolower($browser), 'msie') !== false && strpos(strtolower($browser), 'msie 8.0') === false)
349 header('Content-Disposition: attachment; ' . header_filename($file));
351 if (strpos(strtolower($browser), 'msie 6.0') !== false)
353 header('Expires: -1');
357 header('Expires: ' . gmdate('D, d M Y H:i:s \G\M\T', time() + 31536000));
362 header('Content-Disposition: inline; ' . header_filename($file));
363 header('Expires: ' . gmdate('D, d M Y H:i:s \G\M\T', time() + 31536000));
366 $size = @filesize($file_path);
369 header("Content-Length: $size");
372 if (@readfile($file_path) == false)
374 $fp = @fopen($file_path, 'rb');
380 echo fread($fp, 8192);
390 send_status_line(404, 'Not Found');
395 * Wraps an url into a simple html page. Used to display attachments in IE.
396 * this is a workaround for now; might be moved to template system later
397 * direct any complaints to 1 Microsoft Way, Redmond
399 function wrap_img_in_html($src, $title)
401 echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-Strict.dtd">';
404 echo '<meta http-equiv="content-type" content="text/html; charset=UTF-8" />';
405 echo '<title>' . $title . '</title>';
409 echo '<img src="' . $src . '" alt="' . $title . '" />';
416 * Send file to browser
418 function send_file_to_browser($attachment, $upload_dir, $category)
420 global $user, $db, $config, $phpbb_root_path;
422 $filename = $phpbb_root_path . $upload_dir . '/' . $attachment['physical_filename'];
424 if (!@file_exists($filename))
426 send_status_line(404, 'Not Found');
427 trigger_error($user->lang['ERROR_NO_ATTACHMENT'] . '<br /><br />' . sprintf($user->lang['FILE_NOT_FOUND_404'], $filename));
430 // Correct the mime type - we force application/octetstream for all files, except images
431 // Please do not change this, it is a security precaution
432 if ($category != ATTACHMENT_CATEGORY_IMAGE || strpos($attachment['mimetype'], 'image') !== 0)
434 $attachment['mimetype'] = (strpos(strtolower($user->browser), 'msie') !== false || strpos(strtolower($user->browser), 'opera') !== false) ? 'application/octetstream' : 'application/octet-stream';
437 if (@ob_get_length())
442 // Now send the File Contents to the Browser
443 $size = @filesize($filename);
445 // To correctly display further errors we need to make sure we are using the correct headers for both (unsetting content-length may not work)
447 // Check if headers already sent or not able to get the file contents.
448 if (headers_sent() || !@file_exists($filename) || !@is_readable($filename))
450 // PHP track_errors setting On?
451 if (!empty($php_errormsg))
453 send_status_line(500, 'Internal Server Error');
454 trigger_error($user->lang['UNABLE_TO_DELIVER_FILE'] . '<br />' . sprintf($user->lang['TRACKED_PHP_ERROR'], $php_errormsg));
457 send_status_line(500, 'Internal Server Error');
458 trigger_error('UNABLE_TO_DELIVER_FILE');
461 // Now the tricky part... let's dance
462 header('Pragma: public');
465 * 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.
467 * Try X-Sendfile since it is much more server friendly - only works if the path is *not* outside of the root path...
468 * lighttpd has core support for it. An apache2 module is available at http://celebnamer.celebworld.ws/stuff/mod_xsendfile/
470 * Not really ideal, but should work fine...
472 * if (strpos($upload_dir, '/') !== 0 && strpos($upload_dir, '../') === false)
474 * header('X-Sendfile: ' . $filename);
479 // Send out the Headers. Do not set Content-Disposition to inline please, it is a security measure for users using the Internet Explorer.
480 $is_ie8 = (strpos(strtolower($user->browser), 'msie 8.0') !== false);
481 header('Content-Type: ' . $attachment['mimetype']);
485 header('X-Content-Type-Options: nosniff');
488 if ($category == ATTACHMENT_CATEGORY_FLASH && request_var('view', 0) === 1)
490 // We use content-disposition: inline for flash files and view=1 to let it correctly play with flash player 10 - any other disposition will fail to play inline
491 header('Content-Disposition: inline');
495 if (empty($user->browser) || (!$is_ie8 && (strpos(strtolower($user->browser), 'msie') !== false)))
497 header('Content-Disposition: attachment; ' . header_filename(htmlspecialchars_decode($attachment['real_filename'])));
498 if (empty($user->browser) || (strpos(strtolower($user->browser), 'msie 6.0') !== false))
500 header('expires: -1');
505 header('Content-Disposition: ' . ((strpos($attachment['mimetype'], 'image') === 0) ? 'inline' : 'attachment') . '; ' . header_filename(htmlspecialchars_decode($attachment['real_filename'])));
506 if ($is_ie8 && (strpos($attachment['mimetype'], 'image') !== 0))
508 header('X-Download-Options: noopen');
515 header("Content-Length: $size");
518 // Close the db connection before sending the file
521 if (!set_modified_headers($attachment['filetime'], $user->browser))
523 // Try to deliver in chunks
526 $fp = @fopen($filename, 'rb');
532 echo fread($fp, 8192);
538 @readfile($filename);
547 * Get a browser friendly UTF-8 encoded filename
549 function header_filename($file)
551 $user_agent = (!empty($_SERVER['HTTP_USER_AGENT'])) ? htmlspecialchars((string) $_SERVER['HTTP_USER_AGENT']) : '';
553 // There be dragons here.
554 // Not many follows the RFC...
555 if (strpos($user_agent, 'MSIE') !== false || strpos($user_agent, 'Safari') !== false || strpos($user_agent, 'Konqueror') !== false)
557 return "filename=" . rawurlencode($file);
560 // follow the RFC for extended filename for the rest
561 return "filename*=UTF-8''" . rawurlencode($file);
565 * Check if downloading item is allowed
567 function download_allowed()
569 global $config, $user, $db;
571 if (!$config['secure_downloads'])
576 $url = (!empty($_SERVER['HTTP_REFERER'])) ? trim($_SERVER['HTTP_REFERER']) : trim(getenv('HTTP_REFERER'));
580 return ($config['secure_allow_empty_referer']) ? true : false;
583 // Split URL into domain and script part
584 $url = @parse_url($url);
588 return ($config['secure_allow_empty_referer']) ? true : false;
591 $hostname = $url['host'];
594 $allowed = ($config['secure_allow_deny']) ? false : true;
597 if (($ip_ary = @gethostbynamel($hostname)) !== false)
599 foreach ($ip_ary as $ip)
608 // Check for own server...
609 $server_name = $user->host;
611 // Forcing server vars is the only way to specify/override the protocol
612 if ($config['force_server_vars'] || !$server_name)
614 $server_name = $config['server_name'];
617 if (preg_match('#^.*?' . preg_quote($server_name, '#') . '.*?$#i', $hostname))
622 // Get IP's and Hostnames
625 $sql = 'SELECT site_ip, site_hostname, ip_exclude
626 FROM ' . SITELIST_TABLE;
627 $result = $db->sql_query($sql);
629 while ($row = $db->sql_fetchrow($result))
631 $site_ip = trim($row['site_ip']);
632 $site_hostname = trim($row['site_hostname']);
636 foreach ($iplist as $ip)
638 if (preg_match('#^' . str_replace('\*', '.*?', preg_quote($site_ip, '#')) . '$#i', $ip))
640 if ($row['ip_exclude'])
642 $allowed = ($config['secure_allow_deny']) ? false : true;
647 $allowed = ($config['secure_allow_deny']) ? true : false;
655 if (preg_match('#^' . str_replace('\*', '.*?', preg_quote($site_hostname, '#')) . '$#i', $hostname))
657 if ($row['ip_exclude'])
659 $allowed = ($config['secure_allow_deny']) ? false : true;
664 $allowed = ($config['secure_allow_deny']) ? true : false;
669 $db->sql_freeresult($result);
676 * Check if the browser has the file already and set the appropriate headers-
677 * @returns false if a resend is in order.
679 function set_modified_headers($stamp, $browser)
681 // let's see if we have to send the file at all
682 $last_load = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? strtotime(trim($_SERVER['HTTP_IF_MODIFIED_SINCE'])) : false;
683 if ((strpos(strtolower($browser), 'msie 6.0') === false) && (strpos(strtolower($browser), 'msie 8.0') === false))
685 if ($last_load !== false && $last_load >= $stamp)
687 send_status_line(304, 'Not Modified');
688 // seems that we need those too ... browsers
689 header('Pragma: public');
690 header('Expires: ' . gmdate('D, d M Y H:i:s \G\M\T', time() + 31536000));
695 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $stamp) . ' GMT');