$auth-> to phpbb::$acl->
[phpbb.git] / phpBB / download / file.php
blob676befc15906224af9dddb8c40dba97592ba9e98
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 if (!defined('PHPBB_ROOT_PATH')) define('PHPBB_ROOT_PATH', './../');
16 if (!defined('PHP_EXT')) define('PHP_EXT', substr(strrchr(__FILE__, '.'), 1));
17 include(PHPBB_ROOT_PATH . 'includes/core/bootstrap.' . PHP_EXT);
19 // Thank you sun.
20 if (isset($_SERVER['CONTENT_TYPE']))
22 if ($_SERVER['CONTENT_TYPE'] === 'application/x-java-archive')
24 exit;
27 else if (isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], 'Java') !== false)
29 exit;
32 if (phpbb_request::is_set('avatar', phpbb_request::GET))
34 // worst-case default
35 $browser = (!empty($_SERVER['HTTP_USER_AGENT'])) ? htmlspecialchars((string) $_SERVER['HTTP_USER_AGENT']) : 'msie 6.0';
37 phpbb::$config = phpbb_cache::obtain_config();
38 $filename = phpbb_request::variable('avatar', '', false, phpbb_request::GET);
39 $avatar_group = false;
40 $exit = false;
42 if ($filename[0] === 'g')
44 $avatar_group = true;
45 $filename = substr($filename, 1);
48 // '==' is not a bug - . as the first char is as bad as no dot at all
49 if (strpos($filename, '.') == false)
51 header('HTTP/1.0 403 forbidden');
52 $exit = true;
55 if (!$exit)
57 $ext = substr(strrchr($filename, '.'), 1);
58 $stamp = (int) substr(stristr($filename, '_'), 1);
59 $filename = (int) $filename;
60 $exit = set_modified_headers($stamp, $browser);
62 if (!$exit && !in_array($ext, array('png', 'gif', 'jpg', 'jpeg')))
64 // no way such an avatar could exist. They are not following the rules, stop the show.
65 header("HTTP/1.0 403 Forbidden");
66 $exit = true;
70 if (!$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");
77 else
79 send_avatar_to_browser(($avatar_group ? 'g' : '') . $filename . '.' . $ext, $browser);
82 file_gc();
85 // implicit else: we are not in avatar mode
86 $download_id = request_var('id', 0);
87 $mode = request_var('mode', '');
88 $thumbnail = request_var('t', false);
90 // Start session management, do not update session page.
91 phpbb::$user->session_begin(false);
92 phpbb::$acl->init(phpbb::$user->data);
93 phpbb::$user->setup('viewtopic');
95 if (!$download_id)
97 trigger_error('NO_ATTACHMENT_SELECTED');
100 if (!phpbb::$config['allow_attachments'] && !phpbb::$config['allow_pm_attach'])
102 trigger_error('ATTACHMENT_FUNCTIONALITY_DISABLED');
105 $sql = 'SELECT attach_id, in_message, post_msg_id, extension, is_orphan, poster_id, filetime
106 FROM ' . ATTACHMENTS_TABLE . "
107 WHERE attach_id = $download_id";
108 $result = $db->sql_query_limit($sql, 1);
109 $attachment = $db->sql_fetchrow($result);
110 phpbb::$db->sql_freeresult($result);
112 if (!$attachment)
114 trigger_error('ERROR_NO_ATTACHMENT');
117 if ((!$attachment['in_message'] && !phpbb::$config['allow_attachments']) || ($attachment['in_message'] && !phpbb::$config['allow_pm_attach']))
119 trigger_error('ATTACHMENT_FUNCTIONALITY_DISABLED');
122 $row = array();
124 if ($attachment['is_orphan'])
126 // We allow admins having attachment permissions to see orphan attachments...
127 $own_attachment = (phpbb::$acl->acl_get('a_attach') || $attachment['poster_id'] == phpbb::$user->data['user_id']) ? true : false;
129 if (!$own_attachment || ($attachment['in_message'] && !phpbb::$acl->acl_get('u_pm_download')) || (!$attachment['in_message'] && !phpbb::$acl->acl_get('u_download')))
131 trigger_error('ERROR_NO_ATTACHMENT');
134 // Obtain all extensions...
135 $extensions = phpbb_cache::obtain_extensions();
137 else
139 if (!$attachment['in_message'])
142 $sql = 'SELECT p.forum_id, f.forum_password, f.parent_id
143 FROM ' . POSTS_TABLE . ' p, ' . FORUMS_TABLE . ' f
144 WHERE p.post_id = ' . $attachment['post_msg_id'] . '
145 AND p.forum_id = f.forum_id';
146 $result = $db->sql_query_limit($sql, 1);
147 $row = $db->sql_fetchrow($result);
148 $db->sql_freeresult($result);
150 // Global announcement?
151 $f_download = (!$row) ? phpbb::$acl->acl_getf_global('f_download') : phpbb::$acl->acl_get('f_download', $row['forum_id']);
153 if (phpbb::$acl->acl_get('u_download') && $f_download)
155 if ($row && $row['forum_password'])
157 // Do something else ... ?
158 login_forum_box($row);
161 else
163 trigger_error('SORRY_AUTH_VIEW_ATTACH');
166 else
168 $row['forum_id'] = false;
169 if (!phpbb::$acl->acl_get('u_pm_download'))
171 header('HTTP/1.0 403 forbidden');
172 trigger_error('SORRY_AUTH_VIEW_ATTACH');
175 // Check if the attachment is within the users scope...
176 $sql = 'SELECT user_id, author_id
177 FROM ' . PRIVMSGS_TO_TABLE . '
178 WHERE msg_id = ' . $attachment['post_msg_id'];
179 $result = $db->sql_query($sql);
181 $allowed = false;
182 while ($user_row = $db->sql_fetchrow($result))
184 if (phpbb::$user->data['user_id'] == $user_row['user_id'] || phpbb::$user->data['user_id'] == $user_row['author_id'])
186 $allowed = true;
187 break;
190 $db->sql_freeresult($result);
192 if (!$allowed)
194 header('HTTP/1.0 403 forbidden');
195 trigger_error('ERROR_NO_ATTACHMENT');
199 // disallowed?
200 $extensions = array();
201 if (!extension_allowed($row['forum_id'], $attachment['extension'], $extensions))
203 trigger_error(sprintf(phpbb::$user->lang['EXTENSION_DISABLED_AFTER_POSTING'], $attachment['extension']));
207 if (!download_allowed())
209 header('HTTP/1.0 403 forbidden');
210 trigger_error(phpbb::$user->lang['LINKAGE_FORBIDDEN']);
213 $download_mode = (int) $extensions[$attachment['extension']]['download_mode'];
215 // Fetching filename here to prevent sniffing of filename
216 $sql = 'SELECT attach_id, is_orphan, in_message, post_msg_id, extension, physical_filename, real_filename, mimetype, filetime
217 FROM ' . ATTACHMENTS_TABLE . "
218 WHERE attach_id = $download_id";
219 $result = $db->sql_query_limit($sql, 1);
220 $attachment = $db->sql_fetchrow($result);
221 phpbb::$db->sql_freeresult($result);
223 if (!$attachment)
225 trigger_error('ERROR_NO_ATTACHMENT');
228 $attachment['physical_filename'] = basename($attachment['physical_filename']);
229 $display_cat = $extensions[$attachment['extension']]['display_cat'];
231 if (($display_cat == ATTACHMENT_CATEGORY_IMAGE || $display_cat == ATTACHMENT_CATEGORY_THUMB) && !phpbb::$user->optionget('viewimg'))
233 $display_cat = ATTACHMENT_CATEGORY_NONE;
236 if ($display_cat == ATTACHMENT_CATEGORY_FLASH && !phpbb::$user->optionget('viewflash'))
238 $display_cat = ATTACHMENT_CATEGORY_NONE;
241 if ($thumbnail)
243 $attachment['physical_filename'] = 'thumb_' . $attachment['physical_filename'];
245 else if (($display_cat == ATTACHMENT_CATEGORY_NONE || $display_cat == ATTACHMENT_CATEGORY_IMAGE) && !$attachment['is_orphan'])
247 // Update download count
248 $sql = 'UPDATE ' . ATTACHMENTS_TABLE . '
249 SET download_count = download_count + 1
250 WHERE attach_id = ' . $attachment['attach_id'];
251 $db->sql_query($sql);
254 if ($display_cat == ATTACHMENT_CATEGORY_IMAGE && $mode === 'view' && (strpos($attachment['mimetype'], 'image') === 0) && ((strpos(strtolower(phpbb::$user->system['browser']), 'msie') !== false) && (strpos(strtolower(phpbb::$user->system['browser']), 'msie 8.0') === false)))
256 wrap_img_in_html(append_sid('download/file', 'id=' . $attachment['attach_id']), $attachment['real_filename']);
258 else
260 // Determine the 'presenting'-method
261 if ($download_mode == PHYSICAL_LINK)
263 // This presenting method should no longer be used
264 if (!@is_dir(PHPBB_ROOT_PATH . phpbb::$config['upload_path']))
266 trigger_error(phpbb::$user->lang['PHYSICAL_DOWNLOAD_NOT_POSSIBLE']);
269 redirect(PHPBB_ROOT_PATH . phpbb::$config['upload_path'] . '/' . $attachment['physical_filename']);
270 file_gc();
272 else
274 send_file_to_browser($attachment, phpbb::$config['upload_path'], $display_cat);
275 file_gc();
281 * A simplified function to deliver avatars
282 * The argument needs to be checked before calling this function.
284 function send_avatar_to_browser($file, $browser)
286 $prefix = phpbb::$config['avatar_salt'] . '_';
287 $image_dir = phpbb::$config['avatar_path'];
289 // Adjust image_dir path (no trailing slash)
290 if (substr($image_dir, -1, 1) == '/' || substr($image_dir, -1, 1) == '\\')
292 $image_dir = substr($image_dir, 0, -1) . '/';
294 $image_dir = str_replace(array('../', '..\\', './', '.\\'), '', $image_dir);
296 if ($image_dir && ($image_dir[0] == '/' || $image_dir[0] == '\\'))
298 $image_dir = '';
300 $file_path = PHPBB_ROOT_PATH . $image_dir . '/' . $prefix . $file;
302 if ((@file_exists($file_path) && @is_readable($file_path)) && !headers_sent())
304 header('Pragma: public');
306 $image_data = @getimagesize($file_path);
307 header('Content-Type: ' . image_type_to_mime_type($image_data[2]));
309 if (strpos(strtolower($browser), 'msie') !== false && strpos(strtolower($browser), 'msie 8.0') === false)
311 header('Content-Disposition: attachment; ' . header_filename($file));
313 if (strpos(strtolower($browser), 'msie 6.0') !== false)
315 header('Expires: -1');
317 else
319 header('Expires: ' . gmdate('D, d M Y H:i:s \G\M\T', time() + 31536000));
322 else
324 header('Content-Disposition: inline; ' . header_filename($file));
325 header('Expires: ' . gmdate('D, d M Y H:i:s \G\M\T', time() + 31536000));
328 $size = @filesize($file_path);
329 if ($size)
331 header("Content-Length: $size");
334 if (@readfile($file_path) == false)
336 $fp = @fopen($file_path, 'rb');
338 if ($fp !== false)
340 while (!feof($fp))
342 echo fread($fp, 8192);
344 fclose($fp);
348 flush();
350 else
352 header('HTTP/1.0 404 not found');
357 * Wraps an url into a simple html page. Used to display attachments in IE.
358 * this is a workaround for now; might be moved to template system later
359 * direct any complaints to 1 Microsoft Way, Redmond
361 function wrap_img_in_html($src, $title)
363 echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-Strict.dtd">';
364 echo '<html>';
365 echo '<head>';
366 echo '<meta http-equiv="content-type" content="text/html; charset=UTF-8" />';
367 echo '<title>' . $title . '</title>';
368 echo '</head>';
369 echo '<body>';
370 echo '<div>';
371 echo '<img src="' . $src . '" alt="' . $title . '" />';
372 echo '</div>';
373 echo '</body>';
374 echo '</html>';
378 * Send file to browser
380 function send_file_to_browser($attachment, $upload_dir, $category)
382 $filename = PHPBB_ROOT_PATH . $upload_dir . '/' . $attachment['physical_filename'];
384 if (!@file_exists($filename))
386 trigger_error(phpbb::$user->lang['ERROR_NO_ATTACHMENT'] . '<br /><br />' . sprintf(phpbb::$user->lang['FILE_NOT_FOUND_404'], $filename));
389 // Correct the mime type - we force application/octetstream for all files, except images
390 // Please do not change this, it is a security precaution
391 if ($category != ATTACHMENT_CATEGORY_IMAGE || strpos($attachment['mimetype'], 'image') !== 0)
393 $attachment['mimetype'] = (strpos(strtolower(phpbb::$user->system['browser']), 'msie') !== false || strpos(strtolower(phpbb::$user->system['browser']), 'opera') !== false) ? 'application/octetstream' : 'application/octet-stream';
396 if (@ob_get_length())
398 @ob_end_clean();
401 // Now send the File Contents to the Browser
402 $size = @filesize($filename);
404 // To correctly display further errors we need to make sure we are using the correct headers for both (unsetting content-length may not work)
406 // Check if headers already sent or not able to get the file contents.
407 if (headers_sent() || !@file_exists($filename) || !@is_readable($filename))
409 // PHP track_errors setting On?
410 if (!empty($php_errormsg))
412 trigger_error(phpbb::$user->lang['UNABLE_TO_DELIVER_FILE'] . '<br />' . sprintf(phpbb::$user->lang['TRACKED_PHP_ERROR'], $php_errormsg));
415 trigger_error('UNABLE_TO_DELIVER_FILE');
418 // Now the tricky part... let's dance
419 header('Pragma: public');
422 * 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.
424 * Try X-Sendfile since it is much more server friendly - only works if the path is *not* outside of the root path...
425 * lighttpd has core support for it. An apache2 module is available at http://celebnamer.celebworld.ws/stuff/mod_xsendfile/
427 * Not really ideal, but should work fine...
428 * <code>
429 * if (strpos($upload_dir, '/') !== 0 && strpos($upload_dir, '../') === false)
431 * header('X-Sendfile: ' . $filename);
433 * </code>
436 // Send out the Headers. Do not set Content-Disposition to inline please, it is a security measure for users using the Internet Explorer.
437 $is_ie8 = (strpos(strtolower(phpbb::$user->system['browser']), 'msie 8.0') !== false);
438 header('Content-Type: ' . $attachment['mimetype'] . (($is_ie8) ? '; authoritative=true;' : ''));
440 if (empty(phpbb::$user->system['browser']) || (!$is_ie8 && (strpos(strtolower(phpbb::$user->system['browser']), 'msie') !== false)))
442 header('Content-Disposition: attachment; ' . header_filename(htmlspecialchars_decode($attachment['real_filename'])));
443 if (empty(phpbb::$user->system['browser']) || (strpos(strtolower(phpbb::$user->system['browser']), 'msie 6.0') !== false))
445 header('expires: -1');
448 else
450 header('Content-Disposition: ' . ((strpos($attachment['mimetype'], 'image') === 0) ? 'inline' : 'attachment') . '; ' . header_filename(htmlspecialchars_decode($attachment['real_filename'])));
451 if ($is_ie8 && (strpos($attachment['mimetype'], 'image') !== 0))
453 header('X-Download-Options: noopen');
457 if ($size)
459 header("Content-Length: $size");
462 // Close the db connection before sending the file
463 $db->sql_close();
465 if (!set_modified_headers($attachment['filetime'], phpbb::$user->system['browser']))
467 // Try to deliver in chunks
468 @set_time_limit(0);
470 $fp = @fopen($filename, 'rb');
472 if ($fp !== false)
474 while (!feof($fp))
476 echo fread($fp, 8192);
478 fclose($fp);
480 else
482 @readfile($filename);
485 flush();
487 file_gc();
491 * Get a browser friendly UTF-8 encoded filename
493 function header_filename($file)
495 $user_agent = (!empty($_SERVER['HTTP_USER_AGENT'])) ? htmlspecialchars((string) $_SERVER['HTTP_USER_AGENT']) : '';
497 // There be dragons here.
498 // Not many follows the RFC...
499 if (strpos($user_agent, 'MSIE') !== false || strpos($user_agent, 'Safari') !== false || strpos($user_agent, 'Konqueror') !== false)
501 return "filename=" . rawurlencode($file);
504 // follow the RFC for extended filename for the rest
505 return "filename*=UTF-8''" . rawurlencode($file);
509 * Check if downloading item is allowed
511 function download_allowed()
513 if (!phpbb::$config['secure_downloads'])
515 return true;
518 $url = (!empty($_SERVER['HTTP_REFERER'])) ? trim($_SERVER['HTTP_REFERER']) : trim(getenv('HTTP_REFERER'));
520 if (!$url)
522 return (phpbb::$config['secure_allow_empty_referer']) ? true : false;
525 // Split URL into domain and script part
526 $url = @parse_url($url);
528 if ($url === false)
530 return (phpbb::$config['secure_allow_empty_referer']) ? true : false;
533 $hostname = $url['host'];
534 unset($url);
536 $allowed = (phpbb::$config['secure_allow_deny']) ? false : true;
537 $iplist = array();
539 if (($ip_ary = @gethostbynamel($hostname)) !== false)
541 foreach ($ip_ary as $ip)
543 if ($ip)
545 $iplist[] = $ip;
550 // Check for own server...
551 $server_name = phpbb::$user->system['host'];
553 // Forcing server vars is the only way to specify/override the protocol
554 if (phpbb::$config['force_server_vars'] || !$server_name)
556 $server_name = phpbb::$config['server_name'];
559 if (preg_match('#^.*?' . preg_quote($server_name, '#') . '.*?$#i', $hostname))
561 $allowed = true;
564 // Get IP's and Hostnames
565 if (!$allowed)
567 $sql = 'SELECT site_ip, site_hostname, ip_exclude
568 FROM ' . SITELIST_TABLE;
569 $result = $db->sql_query($sql);
571 while ($row = $db->sql_fetchrow($result))
573 $site_ip = trim($row['site_ip']);
574 $site_hostname = trim($row['site_hostname']);
576 if ($site_ip)
578 foreach ($iplist as $ip)
580 if (preg_match('#^' . str_replace('\*', '.*?', preg_quote($site_ip, '#')) . '$#i', $ip))
582 if ($row['ip_exclude'])
584 $allowed = (phpbb::$config['secure_allow_deny']) ? false : true;
585 break 2;
587 else
589 $allowed = (phpbb::$config['secure_allow_deny']) ? true : false;
595 if ($site_hostname)
597 if (preg_match('#^' . str_replace('\*', '.*?', preg_quote($site_hostname, '#')) . '$#i', $hostname))
599 if ($row['ip_exclude'])
601 $allowed = (phpbb::$config['secure_allow_deny']) ? false : true;
602 break;
604 else
606 $allowed = (phpbb::$config['secure_allow_deny']) ? true : false;
611 $db->sql_freeresult($result);
614 return $allowed;
618 * Check if the browser has the file already and set the appropriate headers-
619 * @returns false if a resend is in order.
621 function set_modified_headers($stamp, $browser)
623 // let's see if we have to send the file at all
624 $last_load = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? strtotime(trim($_SERVER['HTTP_IF_MODIFIED_SINCE'])) : false;
625 if ((strpos(strtolower($browser), 'msie 6.0') === false) && (strpos(strtolower($browser), 'msie 8.0') === false))
627 if ($last_load !== false && $last_load <= $stamp)
629 if (@php_sapi_name() === 'CGI')
631 header('Status: 304 Not Modified', true, 304);
633 else
635 header('HTTP/1.0 304 Not Modified', true, 304);
637 // seems that we need those too ... browsers
638 header('Pragma: public');
639 header('Expires: ' . gmdate('D, d M Y H:i:s \G\M\T', time() + 31536000));
640 return true;
642 else
644 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $stamp) . ' GMT');
647 return false;
650 function file_gc()
652 if (phpbb::registered('acm'))
654 phpbb::$acm->unload();
657 if (phpbb::registered('db'))
659 phpbb::$db->sql_close();
662 exit;