source: trunk/forum/download/file.php

Last change on this file was 702, checked in by george, 15 years ago
  • Upraveno: Aktualizace fóra.
File size: 18.1 KB
Line 
1<?php
2/**
3*
4* @package phpBB3
5* @version $Id$
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'] = utf8_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 file_gc();
282}
283else
284{
285 // Determine the 'presenting'-method
286 if ($download_mode == PHYSICAL_LINK)
287 {
288 // This presenting method should no longer be used
289 if (!@is_dir($phpbb_root_path . $config['upload_path']))
290 {
291 trigger_error($user->lang['PHYSICAL_DOWNLOAD_NOT_POSSIBLE']);
292 }
293
294 redirect($phpbb_root_path . $config['upload_path'] . '/' . $attachment['physical_filename']);
295 file_gc();
296 }
297 else
298 {
299 send_file_to_browser($attachment, $config['upload_path'], $display_cat);
300 file_gc();
301 }
302}
303
304
305/**
306* A simplified function to deliver avatars
307* The argument needs to be checked before calling this function.
308*/
309function send_avatar_to_browser($file, $browser)
310{
311 global $config, $phpbb_root_path;
312
313 $prefix = $config['avatar_salt'] . '_';
314 $image_dir = $config['avatar_path'];
315
316 // Adjust image_dir path (no trailing slash)
317 if (substr($image_dir, -1, 1) == '/' || substr($image_dir, -1, 1) == '\\')
318 {
319 $image_dir = substr($image_dir, 0, -1) . '/';
320 }
321 $image_dir = str_replace(array('../', '..\\', './', '.\\'), '', $image_dir);
322
323 if ($image_dir && ($image_dir[0] == '/' || $image_dir[0] == '\\'))
324 {
325 $image_dir = '';
326 }
327 $file_path = $phpbb_root_path . $image_dir . '/' . $prefix . $file;
328
329 if ((@file_exists($file_path) && @is_readable($file_path)) && !headers_sent())
330 {
331 header('Pragma: public');
332
333 $image_data = @getimagesize($file_path);
334 header('Content-Type: ' . image_type_to_mime_type($image_data[2]));
335
336 if (strpos(strtolower($browser), 'msie') !== false && strpos(strtolower($browser), 'msie 8.0') === false)
337 {
338 header('Content-Disposition: attachment; ' . header_filename($file));
339
340 if (strpos(strtolower($browser), 'msie 6.0') !== false)
341 {
342 header('Expires: -1');
343 }
344 else
345 {
346 header('Expires: ' . gmdate('D, d M Y H:i:s \G\M\T', time() + 31536000));
347 }
348 }
349 else
350 {
351 header('Content-Disposition: inline; ' . header_filename($file));
352 header('Expires: ' . gmdate('D, d M Y H:i:s \G\M\T', time() + 31536000));
353 }
354
355 $size = @filesize($file_path);
356 if ($size)
357 {
358 header("Content-Length: $size");
359 }
360
361 if (@readfile($file_path) == false)
362 {
363 $fp = @fopen($file_path, 'rb');
364
365 if ($fp !== false)
366 {
367 while (!feof($fp))
368 {
369 echo fread($fp, 8192);
370 }
371 fclose($fp);
372 }
373 }
374
375 flush();
376 }
377 else
378 {
379 header('HTTP/1.0 404 Not Found');
380 }
381}
382
383/**
384* Wraps an url into a simple html page. Used to display attachments in IE.
385* this is a workaround for now; might be moved to template system later
386* direct any complaints to 1 Microsoft Way, Redmond
387*/
388function wrap_img_in_html($src, $title)
389{
390 echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-Strict.dtd">';
391 echo '<html>';
392 echo '<head>';
393 echo '<meta http-equiv="content-type" content="text/html; charset=UTF-8" />';
394 echo '<title>' . $title . '</title>';
395 echo '</head>';
396 echo '<body>';
397 echo '<div>';
398 echo '<img src="' . $src . '" alt="' . $title . '" />';
399 echo '</div>';
400 echo '</body>';
401 echo '</html>';
402}
403
404/**
405* Send file to browser
406*/
407function send_file_to_browser($attachment, $upload_dir, $category)
408{
409 global $user, $db, $config, $phpbb_root_path;
410
411 $filename = $phpbb_root_path . $upload_dir . '/' . $attachment['physical_filename'];
412
413 if (!@file_exists($filename))
414 {
415 trigger_error($user->lang['ERROR_NO_ATTACHMENT'] . '<br /><br />' . sprintf($user->lang['FILE_NOT_FOUND_404'], $filename));
416 }
417
418 // Correct the mime type - we force application/octetstream for all files, except images
419 // Please do not change this, it is a security precaution
420 if ($category != ATTACHMENT_CATEGORY_IMAGE || strpos($attachment['mimetype'], 'image') !== 0)
421 {
422 $attachment['mimetype'] = (strpos(strtolower($user->browser), 'msie') !== false || strpos(strtolower($user->browser), 'opera') !== false) ? 'application/octetstream' : 'application/octet-stream';
423 }
424
425 if (@ob_get_length())
426 {
427 @ob_end_clean();
428 }
429
430 // Now send the File Contents to the Browser
431 $size = @filesize($filename);
432
433 // To correctly display further errors we need to make sure we are using the correct headers for both (unsetting content-length may not work)
434
435 // Check if headers already sent or not able to get the file contents.
436 if (headers_sent() || !@file_exists($filename) || !@is_readable($filename))
437 {
438 // PHP track_errors setting On?
439 if (!empty($php_errormsg))
440 {
441 trigger_error($user->lang['UNABLE_TO_DELIVER_FILE'] . '<br />' . sprintf($user->lang['TRACKED_PHP_ERROR'], $php_errormsg));
442 }
443
444 trigger_error('UNABLE_TO_DELIVER_FILE');
445 }
446
447 // Now the tricky part... let's dance
448 header('Pragma: public');
449
450 /**
451 * 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.
452 *
453 * Try X-Sendfile since it is much more server friendly - only works if the path is *not* outside of the root path...
454 * lighttpd has core support for it. An apache2 module is available at http://celebnamer.celebworld.ws/stuff/mod_xsendfile/
455 *
456 * Not really ideal, but should work fine...
457 * <code>
458 * if (strpos($upload_dir, '/') !== 0 && strpos($upload_dir, '../') === false)
459 * {
460 * header('X-Sendfile: ' . $filename);
461 * }
462 * </code>
463 */
464
465 // Send out the Headers. Do not set Content-Disposition to inline please, it is a security measure for users using the Internet Explorer.
466 $is_ie8 = (strpos(strtolower($user->browser), 'msie 8.0') !== false);
467 header('Content-Type: ' . $attachment['mimetype']);
468
469 if ($is_ie8)
470 {
471 header('X-Content-Type-Options: nosniff');
472 }
473
474 if ($category == ATTACHMENT_CATEGORY_FLASH && request_var('view', 0) === 1)
475 {
476 // 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
477 header('Content-Disposition: inline');
478 }
479 else
480 {
481 if (empty($user->browser) || (!$is_ie8 && (strpos(strtolower($user->browser), 'msie') !== false)))
482 {
483 header('Content-Disposition: attachment; ' . header_filename(htmlspecialchars_decode($attachment['real_filename'])));
484 if (empty($user->browser) || (strpos(strtolower($user->browser), 'msie 6.0') !== false))
485 {
486 header('expires: -1');
487 }
488 }
489 else
490 {
491 header('Content-Disposition: ' . ((strpos($attachment['mimetype'], 'image') === 0) ? 'inline' : 'attachment') . '; ' . header_filename(htmlspecialchars_decode($attachment['real_filename'])));
492 if ($is_ie8 && (strpos($attachment['mimetype'], 'image') !== 0))
493 {
494 header('X-Download-Options: noopen');
495 }
496 }
497 }
498
499 if ($size)
500 {
501 header("Content-Length: $size");
502 }
503
504 // Close the db connection before sending the file
505 $db->sql_close();
506
507 if (!set_modified_headers($attachment['filetime'], $user->browser))
508 {
509 // Try to deliver in chunks
510 @set_time_limit(0);
511
512 $fp = @fopen($filename, 'rb');
513
514 if ($fp !== false)
515 {
516 while (!feof($fp))
517 {
518 echo fread($fp, 8192);
519 }
520 fclose($fp);
521 }
522 else
523 {
524 @readfile($filename);
525 }
526
527 flush();
528 }
529 file_gc();
530}
531
532/**
533* Get a browser friendly UTF-8 encoded filename
534*/
535function header_filename($file)
536{
537 $user_agent = (!empty($_SERVER['HTTP_USER_AGENT'])) ? htmlspecialchars((string) $_SERVER['HTTP_USER_AGENT']) : '';
538
539 // There be dragons here.
540 // Not many follows the RFC...
541 if (strpos($user_agent, 'MSIE') !== false || strpos($user_agent, 'Safari') !== false || strpos($user_agent, 'Konqueror') !== false)
542 {
543 return "filename=" . rawurlencode($file);
544 }
545
546 // follow the RFC for extended filename for the rest
547 return "filename*=UTF-8''" . rawurlencode($file);
548}
549
550/**
551* Check if downloading item is allowed
552*/
553function download_allowed()
554{
555 global $config, $user, $db;
556
557 if (!$config['secure_downloads'])
558 {
559 return true;
560 }
561
562 $url = (!empty($_SERVER['HTTP_REFERER'])) ? trim($_SERVER['HTTP_REFERER']) : trim(getenv('HTTP_REFERER'));
563
564 if (!$url)
565 {
566 return ($config['secure_allow_empty_referer']) ? true : false;
567 }
568
569 // Split URL into domain and script part
570 $url = @parse_url($url);
571
572 if ($url === false)
573 {
574 return ($config['secure_allow_empty_referer']) ? true : false;
575 }
576
577 $hostname = $url['host'];
578 unset($url);
579
580 $allowed = ($config['secure_allow_deny']) ? false : true;
581 $iplist = array();
582
583 if (($ip_ary = @gethostbynamel($hostname)) !== false)
584 {
585 foreach ($ip_ary as $ip)
586 {
587 if ($ip)
588 {
589 $iplist[] = $ip;
590 }
591 }
592 }
593
594 // Check for own server...
595 $server_name = $user->host;
596
597 // Forcing server vars is the only way to specify/override the protocol
598 if ($config['force_server_vars'] || !$server_name)
599 {
600 $server_name = $config['server_name'];
601 }
602
603 if (preg_match('#^.*?' . preg_quote($server_name, '#') . '.*?$#i', $hostname))
604 {
605 $allowed = true;
606 }
607
608 // Get IP's and Hostnames
609 if (!$allowed)
610 {
611 $sql = 'SELECT site_ip, site_hostname, ip_exclude
612 FROM ' . SITELIST_TABLE;
613 $result = $db->sql_query($sql);
614
615 while ($row = $db->sql_fetchrow($result))
616 {
617 $site_ip = trim($row['site_ip']);
618 $site_hostname = trim($row['site_hostname']);
619
620 if ($site_ip)
621 {
622 foreach ($iplist as $ip)
623 {
624 if (preg_match('#^' . str_replace('\*', '.*?', preg_quote($site_ip, '#')) . '$#i', $ip))
625 {
626 if ($row['ip_exclude'])
627 {
628 $allowed = ($config['secure_allow_deny']) ? false : true;
629 break 2;
630 }
631 else
632 {
633 $allowed = ($config['secure_allow_deny']) ? true : false;
634 }
635 }
636 }
637 }
638
639 if ($site_hostname)
640 {
641 if (preg_match('#^' . str_replace('\*', '.*?', preg_quote($site_hostname, '#')) . '$#i', $hostname))
642 {
643 if ($row['ip_exclude'])
644 {
645 $allowed = ($config['secure_allow_deny']) ? false : true;
646 break;
647 }
648 else
649 {
650 $allowed = ($config['secure_allow_deny']) ? true : false;
651 }
652 }
653 }
654 }
655 $db->sql_freeresult($result);
656 }
657
658 return $allowed;
659}
660
661/**
662* Check if the browser has the file already and set the appropriate headers-
663* @returns false if a resend is in order.
664*/
665function set_modified_headers($stamp, $browser)
666{
667 // let's see if we have to send the file at all
668 $last_load = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? strtotime(trim($_SERVER['HTTP_IF_MODIFIED_SINCE'])) : false;
669 if ((strpos(strtolower($browser), 'msie 6.0') === false) && (strpos(strtolower($browser), 'msie 8.0') === false))
670 {
671 if ($last_load !== false && $last_load >= $stamp)
672 {
673 if (substr(strtolower(@php_sapi_name()),0,3) === 'cgi')
674 {
675 // in theory, we shouldn't need that due to php doing it. Reality offers a differing opinion, though
676 header('Status: 304 Not Modified', true, 304);
677 }
678 else
679 {
680 header('HTTP/1.0 304 Not Modified', true, 304);
681 }
682 // seems that we need those too ... browsers
683 header('Pragma: public');
684 header('Expires: ' . gmdate('D, d M Y H:i:s \G\M\T', time() + 31536000));
685 return true;
686 }
687 else
688 {
689 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $stamp) . ' GMT');
690 }
691 }
692 return false;
693}
694
695function file_gc()
696{
697 global $cache, $db;
698 if (!empty($cache))
699 {
700 $cache->unload();
701 }
702 $db->sql_close();
703 exit;
704}
705
706?>
Note: See TracBrowser for help on using the repository browser.