source: forum/download/file.php@ 400

Last change on this file since 400 was 400, checked in by george, 16 years ago
  • Přidáno: Nové forum phpBB 3.
File size: 17.7 KB
Line 
1<?php
2/**
3*
4* @package phpBB3
5* @version $Id: file.php 8792 2008-08-28 13:10:05Z Kellanved $
6* @copyright (c) 2005 phpBB Group
7* @license http://opensource.org/licenses/gpl-license.php GNU Public License
8*
9*/
10
11/**
12* @ignore
13*/
14define('IN_PHPBB', true);
15$phpbb_root_path = (defined('PHPBB_ROOT_PATH')) ? PHPBB_ROOT_PATH : './../';
16$phpEx = substr(strrchr(__FILE__, '.'), 1);
17
18
19// Thank you sun.
20if (isset($_SERVER['CONTENT_TYPE']))
21{
22 if ($_SERVER['CONTENT_TYPE'] === 'application/x-java-archive')
23 {
24 exit;
25 }
26}
27else if (isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], 'Java') !== false)
28{
29 exit;
30}
31
32if (isset($_GET['avatar']))
33{
34 require($phpbb_root_path . 'config.' . $phpEx);
35
36 if (!defined('PHPBB_INSTALLED') || empty($dbms) || empty($acm_type))
37 {
38 exit;
39 }
40
41 require($phpbb_root_path . 'includes/acm/acm_' . $acm_type . '.' . $phpEx);
42 require($phpbb_root_path . 'includes/cache.' . $phpEx);
43 require($phpbb_root_path . 'includes/db/' . $dbms . '.' . $phpEx);
44 require($phpbb_root_path . 'includes/constants.' . $phpEx);
45
46 $db = new $sql_db();
47 $cache = new cache();
48
49 // Connect to DB
50 if (!@$db->sql_connect($dbhost, $dbuser, $dbpasswd, $dbname, $dbport, false, false))
51 {
52 exit;
53 }
54 unset($dbpasswd);
55
56 // worst-case default
57 $browser = (!empty($_SERVER['HTTP_USER_AGENT'])) ? htmlspecialchars((string) $_SERVER['HTTP_USER_AGENT']) : 'msie 6.0';
58
59 $config = $cache->obtain_config();
60 $filename = $_GET['avatar'];
61 $avatar_group = false;
62 $exit = false;
63
64 if ($filename[0] === 'g')
65 {
66 $avatar_group = true;
67 $filename = substr($filename, 1);
68 }
69
70 // '==' is not a bug - . as the first char is as bad as no dot at all
71 if (strpos($filename, '.') == false)
72 {
73 header('HTTP/1.0 403 Forbidden');
74 $exit = true;
75 }
76
77 if (!$exit)
78 {
79 $ext = substr(strrchr($filename, '.'), 1);
80 $stamp = (int) substr(stristr($filename, '_'), 1);
81 $filename = (int) $filename;
82 $exit = set_modified_headers($stamp, $browser);
83 }
84 if (!$exit && !in_array($ext, array('png', 'gif', 'jpg', 'jpeg')))
85 {
86 // no way such an avatar could exist. They are not following the rules, stop the show.
87 header("HTTP/1.0 403 Forbidden");
88 $exit = true;
89 }
90
91
92 if (!$exit)
93 {
94 if (!$filename)
95 {
96 // no way such an avatar could exist. They are not following the rules, stop the show.
97 header("HTTP/1.0 403 Forbidden");
98 }
99 else
100 {
101 send_avatar_to_browser(($avatar_group ? 'g' : '') . $filename . '.' . $ext, $browser);
102 }
103 }
104 file_gc();
105}
106
107// implicit else: we are not in avatar mode
108include($phpbb_root_path . 'common.' . $phpEx);
109
110$download_id = request_var('id', 0);
111$mode = request_var('mode', '');
112$thumbnail = request_var('t', false);
113
114// Start session management, do not update session page.
115$user->session_begin(false);
116$auth->acl($user->data);
117$user->setup('viewtopic');
118
119if (!$download_id)
120{
121 trigger_error('NO_ATTACHMENT_SELECTED');
122}
123
124if (!$config['allow_attachments'] && !$config['allow_pm_attach'])
125{
126 trigger_error('ATTACHMENT_FUNCTIONALITY_DISABLED');
127}
128
129$sql = 'SELECT attach_id, in_message, post_msg_id, extension, is_orphan, poster_id, filetime
130 FROM ' . ATTACHMENTS_TABLE . "
131 WHERE attach_id = $download_id";
132$result = $db->sql_query_limit($sql, 1);
133$attachment = $db->sql_fetchrow($result);
134$db->sql_freeresult($result);
135
136if (!$attachment)
137{
138 trigger_error('ERROR_NO_ATTACHMENT');
139}
140
141if ((!$attachment['in_message'] && !$config['allow_attachments']) || ($attachment['in_message'] && !$config['allow_pm_attach']))
142{
143 trigger_error('ATTACHMENT_FUNCTIONALITY_DISABLED');
144}
145
146$row = array();
147
148if ($attachment['is_orphan'])
149{
150 // We allow admins having attachment permissions to see orphan attachments...
151 $own_attachment = ($auth->acl_get('a_attach') || $attachment['poster_id'] == $user->data['user_id']) ? true : false;
152
153 if (!$own_attachment || ($attachment['in_message'] && !$auth->acl_get('u_pm_download')) || (!$attachment['in_message'] && !$auth->acl_get('u_download')))
154 {
155 trigger_error('ERROR_NO_ATTACHMENT');
156 }
157
158 // Obtain all extensions...
159 $extensions = $cache->obtain_attach_extensions(true);
160}
161else
162{
163 if (!$attachment['in_message'])
164 {
165 //
166 $sql = 'SELECT p.forum_id, f.forum_password, f.parent_id
167 FROM ' . POSTS_TABLE . ' p, ' . FORUMS_TABLE . ' f
168 WHERE p.post_id = ' . $attachment['post_msg_id'] . '
169 AND p.forum_id = f.forum_id';
170 $result = $db->sql_query_limit($sql, 1);
171 $row = $db->sql_fetchrow($result);
172 $db->sql_freeresult($result);
173
174 // Global announcement?
175 $f_download = (!$row) ? $auth->acl_getf_global('f_download') : $auth->acl_get('f_download', $row['forum_id']);
176
177 if ($auth->acl_get('u_download') && $f_download)
178 {
179 if ($row && $row['forum_password'])
180 {
181 // Do something else ... ?
182 login_forum_box($row);
183 }
184 }
185 else
186 {
187 trigger_error('SORRY_AUTH_VIEW_ATTACH');
188 }
189 }
190 else
191 {
192 $row['forum_id'] = false;
193 if (!$auth->acl_get('u_pm_download'))
194 {
195 header('HTTP/1.0 403 Forbidden');
196 trigger_error('SORRY_AUTH_VIEW_ATTACH');
197 }
198
199 // Check if the attachment is within the users scope...
200 $sql = 'SELECT user_id, author_id
201 FROM ' . PRIVMSGS_TO_TABLE . '
202 WHERE msg_id = ' . $attachment['post_msg_id'];
203 $result = $db->sql_query($sql);
204
205 $allowed = false;
206 while ($user_row = $db->sql_fetchrow($result))
207 {
208 if ($user->data['user_id'] == $user_row['user_id'] || $user->data['user_id'] == $user_row['author_id'])
209 {
210 $allowed = true;
211 break;
212 }
213 }
214 $db->sql_freeresult($result);
215
216 if (!$allowed)
217 {
218 header('HTTP/1.0 403 Forbidden');
219 trigger_error('ERROR_NO_ATTACHMENT');
220 }
221 }
222
223 // disallowed?
224 $extensions = array();
225 if (!extension_allowed($row['forum_id'], $attachment['extension'], $extensions))
226 {
227 trigger_error(sprintf($user->lang['EXTENSION_DISABLED_AFTER_POSTING'], $attachment['extension']));
228 }
229}
230
231if (!download_allowed())
232{
233 header('HTTP/1.0 403 Forbidden');
234 trigger_error($user->lang['LINKAGE_FORBIDDEN']);
235}
236
237$download_mode = (int) $extensions[$attachment['extension']]['download_mode'];
238
239// Fetching filename here to prevent sniffing of filename
240$sql = 'SELECT attach_id, is_orphan, in_message, post_msg_id, extension, physical_filename, real_filename, mimetype, filetime
241 FROM ' . ATTACHMENTS_TABLE . "
242 WHERE attach_id = $download_id";
243$result = $db->sql_query_limit($sql, 1);
244$attachment = $db->sql_fetchrow($result);
245$db->sql_freeresult($result);
246
247if (!$attachment)
248{
249 trigger_error('ERROR_NO_ATTACHMENT');
250}
251
252$attachment['physical_filename'] = basename($attachment['physical_filename']);
253$display_cat = $extensions[$attachment['extension']]['display_cat'];
254
255if (($display_cat == ATTACHMENT_CATEGORY_IMAGE || $display_cat == ATTACHMENT_CATEGORY_THUMB) && !$user->optionget('viewimg'))
256{
257 $display_cat = ATTACHMENT_CATEGORY_NONE;
258}
259
260if ($display_cat == ATTACHMENT_CATEGORY_FLASH && !$user->optionget('viewflash'))
261{
262 $display_cat = ATTACHMENT_CATEGORY_NONE;
263}
264
265if ($thumbnail)
266{
267 $attachment['physical_filename'] = 'thumb_' . $attachment['physical_filename'];
268}
269else if (($display_cat == ATTACHMENT_CATEGORY_NONE || $display_cat == ATTACHMENT_CATEGORY_IMAGE) && !$attachment['is_orphan'])
270{
271 // Update download count
272 $sql = 'UPDATE ' . ATTACHMENTS_TABLE . '
273 SET download_count = download_count + 1
274 WHERE attach_id = ' . $attachment['attach_id'];
275 $db->sql_query($sql);
276}
277
278if ($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)))
279{
280 wrap_img_in_html(append_sid($phpbb_root_path . 'download/file.' . $phpEx, 'id=' . $attachment['attach_id']), $attachment['real_filename']);
281}
282else
283{
284 // Determine the 'presenting'-method
285 if ($download_mode == PHYSICAL_LINK)
286 {
287 // This presenting method should no longer be used
288 if (!@is_dir($phpbb_root_path . $config['upload_path']))
289 {
290 trigger_error($user->lang['PHYSICAL_DOWNLOAD_NOT_POSSIBLE']);
291 }
292
293 redirect($phpbb_root_path . $config['upload_path'] . '/' . $attachment['physical_filename']);
294 file_gc();
295 }
296 else
297 {
298 send_file_to_browser($attachment, $config['upload_path'], $display_cat);
299 file_gc();
300 }
301}
302
303
304/**
305* A simplified function to deliver avatars
306* The argument needs to be checked before calling this function.
307*/
308function send_avatar_to_browser($file, $browser)
309{
310 global $config, $phpbb_root_path;
311
312 $prefix = $config['avatar_salt'] . '_';
313 $image_dir = $config['avatar_path'];
314
315 // Adjust image_dir path (no trailing slash)
316 if (substr($image_dir, -1, 1) == '/' || substr($image_dir, -1, 1) == '\\')
317 {
318 $image_dir = substr($image_dir, 0, -1) . '/';
319 }
320 $image_dir = str_replace(array('../', '..\\', './', '.\\'), '', $image_dir);
321
322 if ($image_dir && ($image_dir[0] == '/' || $image_dir[0] == '\\'))
323 {
324 $image_dir = '';
325 }
326 $file_path = $phpbb_root_path . $image_dir . '/' . $prefix . $file;
327
328 if ((@file_exists($file_path) && @is_readable($file_path)) && !headers_sent())
329 {
330 header('Pragma: public');
331
332 $image_data = @getimagesize($file_path);
333 header('Content-Type: ' . image_type_to_mime_type($image_data[2]));
334
335 if (strpos(strtolower($browser), 'msie') !== false && strpos(strtolower($browser), 'msie 8.0') === false)
336 {
337 header('Content-Disposition: attachment; ' . header_filename($file));
338
339 if (strpos(strtolower($browser), 'msie 6.0') !== false)
340 {
341 header('Expires: -1');
342 }
343 else
344 {
345 header('Expires: ' . gmdate('D, d M Y H:i:s \G\M\T', time() + 31536000));
346 }
347 }
348 else
349 {
350 header('Content-Disposition: inline; ' . header_filename($file));
351 header('Expires: ' . gmdate('D, d M Y H:i:s \G\M\T', time() + 31536000));
352 }
353
354 $size = @filesize($file_path);
355 if ($size)
356 {
357 header("Content-Length: $size");
358 }
359
360 if (@readfile($file_path) == false)
361 {
362 $fp = @fopen($file_path, 'rb');
363
364 if ($fp !== false)
365 {
366 while (!feof($fp))
367 {
368 echo fread($fp, 8192);
369 }
370 fclose($fp);
371 }
372 }
373
374 flush();
375 }
376 else
377 {
378 header('HTTP/1.0 404 not found');
379 }
380}
381
382/**
383* Wraps an url into a simple html page. Used to display attachments in IE.
384* this is a workaround for now; might be moved to template system later
385* direct any complaints to 1 Microsoft Way, Redmond
386*/
387function wrap_img_in_html($src, $title)
388{
389 echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-Strict.dtd">';
390 echo '<html>';
391 echo '<head>';
392 echo '<meta http-equiv="content-type" content="text/html; charset=UTF-8" />';
393 echo '<title>' . $title . '</title>';
394 echo '</head>';
395 echo '<body>';
396 echo '<div>';
397 echo '<img src="' . $src . '" alt="' . $title . '" />';
398 echo '</div>';
399 echo '</body>';
400 echo '</html>';
401}
402
403/**
404* Send file to browser
405*/
406function send_file_to_browser($attachment, $upload_dir, $category)
407{
408 global $user, $db, $config, $phpbb_root_path;
409
410 $filename = $phpbb_root_path . $upload_dir . '/' . $attachment['physical_filename'];
411
412 if (!@file_exists($filename))
413 {
414 trigger_error($user->lang['ERROR_NO_ATTACHMENT'] . '<br /><br />' . sprintf($user->lang['FILE_NOT_FOUND_404'], $filename));
415 }
416
417 // Correct the mime type - we force application/octetstream for all files, except images
418 // Please do not change this, it is a security precaution
419 if ($category != ATTACHMENT_CATEGORY_IMAGE || strpos($attachment['mimetype'], 'image') !== 0)
420 {
421 $attachment['mimetype'] = (strpos(strtolower($user->browser), 'msie') !== false || strpos(strtolower($user->browser), 'opera') !== false) ? 'application/octetstream' : 'application/octet-stream';
422 }
423
424 if (@ob_get_length())
425 {
426 @ob_end_clean();
427 }
428
429 // Now send the File Contents to the Browser
430 $size = @filesize($filename);
431
432 // To correctly display further errors we need to make sure we are using the correct headers for both (unsetting content-length may not work)
433
434 // Check if headers already sent or not able to get the file contents.
435 if (headers_sent() || !@file_exists($filename) || !@is_readable($filename))
436 {
437 // PHP track_errors setting On?
438 if (!empty($php_errormsg))
439 {
440 trigger_error($user->lang['UNABLE_TO_DELIVER_FILE'] . '<br />' . sprintf($user->lang['TRACKED_PHP_ERROR'], $php_errormsg));
441 }
442
443 trigger_error('UNABLE_TO_DELIVER_FILE');
444 }
445
446 // Now the tricky part... let's dance
447 header('Pragma: public');
448
449 /**
450 * 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.
451 *
452 * Try X-Sendfile since it is much more server friendly - only works if the path is *not* outside of the root path...
453 * lighttpd has core support for it. An apache2 module is available at http://celebnamer.celebworld.ws/stuff/mod_xsendfile/
454 *
455 * Not really ideal, but should work fine...
456 * <code>
457 * if (strpos($upload_dir, '/') !== 0 && strpos($upload_dir, '../') === false)
458 * {
459 * header('X-Sendfile: ' . $filename);
460 * }
461 * </code>
462 */
463
464 // Send out the Headers. Do not set Content-Disposition to inline please, it is a security measure for users using the Internet Explorer.
465 $is_ie8 = (strpos(strtolower($user->browser), 'msie 8.0') !== false);
466 header('Content-Type: ' . $attachment['mimetype'] . (($is_ie8) ? '; authoritative=true;' : ''));
467
468 if (empty($user->browser) || (!$is_ie8 && (strpos(strtolower($user->browser), 'msie') !== false)))
469 {
470 header('Content-Disposition: attachment; ' . header_filename(htmlspecialchars_decode($attachment['real_filename'])));
471 if (empty($user->browser) || (strpos(strtolower($user->browser), 'msie 6.0') !== false))
472 {
473 header('expires: -1');
474 }
475 }
476 else
477 {
478 header('Content-Disposition: ' . ((strpos($attachment['mimetype'], 'image') === 0) ? 'inline' : 'attachment') . '; ' . header_filename(htmlspecialchars_decode($attachment['real_filename'])));
479 if ($is_ie8 && (strpos($attachment['mimetype'], 'image') !== 0))
480 {
481 header('X-Download-Options: noopen');
482 }
483 }
484
485 if ($size)
486 {
487 header("Content-Length: $size");
488 }
489
490 // Close the db connection before sending the file
491 $db->sql_close();
492
493 if (!set_modified_headers($attachment['filetime'], $user->browser))
494 {
495 // Try to deliver in chunks
496 @set_time_limit(0);
497
498 $fp = @fopen($filename, 'rb');
499
500 if ($fp !== false)
501 {
502 while (!feof($fp))
503 {
504 echo fread($fp, 8192);
505 }
506 fclose($fp);
507 }
508 else
509 {
510 @readfile($filename);
511 }
512
513 flush();
514 }
515 file_gc();
516}
517
518/**
519* Get a browser friendly UTF-8 encoded filename
520*/
521function header_filename($file)
522{
523 $user_agent = (!empty($_SERVER['HTTP_USER_AGENT'])) ? htmlspecialchars((string) $_SERVER['HTTP_USER_AGENT']) : '';
524
525 // There be dragons here.
526 // Not many follows the RFC...
527 if (strpos($user_agent, 'MSIE') !== false || strpos($user_agent, 'Safari') !== false || strpos($user_agent, 'Konqueror') !== false)
528 {
529 return "filename=" . rawurlencode($file);
530 }
531
532 // follow the RFC for extended filename for the rest
533 return "filename*=UTF-8''" . rawurlencode($file);
534}
535
536/**
537* Check if downloading item is allowed
538*/
539function download_allowed()
540{
541 global $config, $user, $db;
542
543 if (!$config['secure_downloads'])
544 {
545 return true;
546 }
547
548 $url = (!empty($_SERVER['HTTP_REFERER'])) ? trim($_SERVER['HTTP_REFERER']) : trim(getenv('HTTP_REFERER'));
549
550 if (!$url)
551 {
552 return ($config['secure_allow_empty_referer']) ? true : false;
553 }
554
555 // Split URL into domain and script part
556 $url = @parse_url($url);
557
558 if ($url === false)
559 {
560 return ($config['secure_allow_empty_referer']) ? true : false;
561 }
562
563 $hostname = $url['host'];
564 unset($url);
565
566 $allowed = ($config['secure_allow_deny']) ? false : true;
567 $iplist = array();
568
569 if (($ip_ary = @gethostbynamel($hostname)) !== false)
570 {
571 foreach ($ip_ary as $ip)
572 {
573 if ($ip)
574 {
575 $iplist[] = $ip;
576 }
577 }
578 }
579
580 // Check for own server...
581 $server_name = $user->host;
582
583 // Forcing server vars is the only way to specify/override the protocol
584 if ($config['force_server_vars'] || !$server_name)
585 {
586 $server_name = $config['server_name'];
587 }
588
589 if (preg_match('#^.*?' . preg_quote($server_name, '#') . '.*?$#i', $hostname))
590 {
591 $allowed = true;
592 }
593
594 // Get IP's and Hostnames
595 if (!$allowed)
596 {
597 $sql = 'SELECT site_ip, site_hostname, ip_exclude
598 FROM ' . SITELIST_TABLE;
599 $result = $db->sql_query($sql);
600
601 while ($row = $db->sql_fetchrow($result))
602 {
603 $site_ip = trim($row['site_ip']);
604 $site_hostname = trim($row['site_hostname']);
605
606 if ($site_ip)
607 {
608 foreach ($iplist as $ip)
609 {
610 if (preg_match('#^' . str_replace('\*', '.*?', preg_quote($site_ip, '#')) . '$#i', $ip))
611 {
612 if ($row['ip_exclude'])
613 {
614 $allowed = ($config['secure_allow_deny']) ? false : true;
615 break 2;
616 }
617 else
618 {
619 $allowed = ($config['secure_allow_deny']) ? true : false;
620 }
621 }
622 }
623 }
624
625 if ($site_hostname)
626 {
627 if (preg_match('#^' . str_replace('\*', '.*?', preg_quote($site_hostname, '#')) . '$#i', $hostname))
628 {
629 if ($row['ip_exclude'])
630 {
631 $allowed = ($config['secure_allow_deny']) ? false : true;
632 break;
633 }
634 else
635 {
636 $allowed = ($config['secure_allow_deny']) ? true : false;
637 }
638 }
639 }
640 }
641 $db->sql_freeresult($result);
642 }
643
644 return $allowed;
645}
646
647/**
648* Check if the browser has the file already and set the appropriate headers-
649* @returns false if a resend is in order.
650*/
651function set_modified_headers($stamp, $browser)
652{
653 // let's see if we have to send the file at all
654 $last_load = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? strtotime(trim($_SERVER['HTTP_IF_MODIFIED_SINCE'])) : false;
655 if ((strpos(strtolower($browser), 'msie 6.0') === false) && (strpos(strtolower($browser), 'msie 8.0') === false))
656 {
657 if ($last_load !== false && $last_load <= $stamp)
658 {
659 if (@php_sapi_name() === 'CGI')
660 {
661 header('Status: 304 Not Modified', true, 304);
662 }
663 else
664 {
665 header('HTTP/1.0 304 Not Modified', true, 304);
666 }
667 // seems that we need those too ... browsers
668 header('Pragma: public');
669 header('Expires: ' . gmdate('D, d M Y H:i:s \G\M\T', time() + 31536000));
670 return true;
671 }
672 else
673 {
674 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $stamp) . ' GMT');
675 }
676 }
677 return false;
678}
679
680function file_gc()
681{
682 global $cache, $db;
683 if (!empty($cache))
684 {
685 $cache->unload();
686 }
687 $db->sql_close();
688 exit;
689}
690
691?>
Note: See TracBrowser for help on using the repository browser.