/titania/download/file.php

https://github.com/bogtom/customisation-db · PHP · 555 lines · 409 code · 66 blank · 80 comment · 111 complexity · 10bd5407a4c76d75d43a2d10b4f1dff0 MD5 · raw file

  1. <?php
  2. /**
  3. *
  4. * @package titania
  5. * @version $Id$
  6. * @copyright (c) 2008 phpBB Customisation Database Team
  7. * @license http://opensource.org/licenses/gpl-2.0.php GNU Public License
  8. *
  9. */
  10. /**
  11. * @ignore
  12. */
  13. define('IN_TITANIA', true);
  14. if (!defined('TITANIA_ROOT')) define('TITANIA_ROOT', './../');
  15. if (!defined('PHP_EXT')) define('PHP_EXT', substr(strrchr(__FILE__, '.'), 1));
  16. require TITANIA_ROOT . 'common.' . PHP_EXT;
  17. phpbb::$user->add_lang('viewtopic');
  18. // Thank you sun.
  19. if (isset($_SERVER['CONTENT_TYPE']))
  20. {
  21. if ($_SERVER['CONTENT_TYPE'] === 'application/x-java-archive')
  22. {
  23. exit;
  24. }
  25. }
  26. else if (isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], 'Java') !== false)
  27. {
  28. exit;
  29. }
  30. $download_id = request_var('id', 0);
  31. $mode = request_var('mode', '');
  32. $thumbnail = request_var('thumb', false);
  33. if (!$download_id)
  34. {
  35. // Mostly to make moving from Ariel easier
  36. $revision_id = request_var('revision', 0);
  37. $contrib_id = request_var('contrib', 0);
  38. if ($revision_id)
  39. {
  40. $sql = 'SELECT attachment_id FROM ' . TITANIA_REVISIONS_TABLE . '
  41. WHERE revision_id = ' . $revision_id;
  42. phpbb::$db->sql_query($sql);
  43. $download_id = phpbb::$db->sql_fetchfield('attachment_id');
  44. phpbb::$db->sql_freeresult();
  45. }
  46. else if ($contrib_id)
  47. {
  48. $sql = 'SELECT attachment_id FROM ' . TITANIA_REVISIONS_TABLE . '
  49. WHERE contrib_id = ' . $contrib_id . '
  50. AND revision_status = ' . TITANIA_REVISION_APPROVED . '
  51. ORDER BY revision_id DESC';
  52. phpbb::$db->sql_query_limit($sql, 1);
  53. $download_id = phpbb::$db->sql_fetchfield('attachment_id');
  54. phpbb::$db->sql_freeresult();
  55. }
  56. if (!$download_id)
  57. {
  58. trigger_error('NO_ATTACHMENT_SELECTED');
  59. }
  60. }
  61. $sql = 'SELECT *
  62. FROM ' . TITANIA_ATTACHMENTS_TABLE . "
  63. WHERE attachment_id = $download_id";
  64. $result = phpbb::$db->sql_query_limit($sql, 1);
  65. $attachment = phpbb::$db->sql_fetchrow($result);
  66. phpbb::$db->sql_freeresult($result);
  67. if (!$attachment)
  68. {
  69. trigger_error('ERROR_NO_ATTACHMENT');
  70. }
  71. // Don't allow downloads of revisions for TITANIA_CONTRIB_DOWNLOAD_DISABLED items unless on the team or an author.
  72. if ($attachment['object_type'] == TITANIA_CONTRIB)
  73. {
  74. $sql = 'SELECT contrib_id, revision_status FROM ' . TITANIA_REVISIONS_TABLE . '
  75. WHERE attachment_id = ' . $attachment['attachment_id'];
  76. $result = phpbb::$db->sql_query($sql);
  77. $revision = phpbb::$db->sql_fetchrow($result);
  78. phpbb::$db->sql_freeresult($result);
  79. $contrib = new titania_contribution;
  80. if (!$contrib->load((int) $revision['contrib_id']))
  81. {
  82. trigger_error('NO_ATTACHMENT_SELECTED');
  83. }
  84. if ((($revision['revision_status'] != TITANIA_REVISION_APPROVED && titania::$config->require_validation && titania_types::$types[$contrib->contrib_type]->require_validation) || $contrib->contrib_status == TITANIA_CONTRIB_DOWNLOAD_DISABLED) && !$contrib->is_author && !$contrib->is_active_coauthor && !titania_types::$types[$contrib->contrib_type]->acl_get('view') && !titania_types::$types[$contrib->contrib_type]->acl_get('moderate'))
  85. {
  86. // Is it the MPV server requesting the file? If so we allow non-approved file downloads
  87. $is_mpv_server = false;
  88. foreach (titania::$config->mpv_server_list as $data)
  89. {
  90. $dns_ipv4 = dns_get_record($data['host'], DNS_A);
  91. $dns_ipv6 = dns_get_record($data['host'], DNS_AAAA);
  92. if ((isset($dns_ipv4[0]) && isset($dns_ipv4[0]['ip']) && phpbb::$user->ip == $dns_ipv4[0]['ip']) || (isset($dns_ipv6[0]) && isset($dns_ipv6[0]['ip']) && phpbb::$user->ip == $dns_ipv6[0]['ip']))
  93. {
  94. $is_mpv_server = true;
  95. break;
  96. }
  97. }
  98. if (!$is_mpv_server)
  99. {
  100. trigger_error('NO_ATTACHMENT_SELECTED');
  101. }
  102. }
  103. // Access Level
  104. if ($contrib->is_author || $contrib->is_active_coauthor)
  105. {
  106. titania::$access_level = TITANIA_ACCESS_AUTHORS;
  107. }
  108. unset($contrib);
  109. }
  110. if ($thumbnail)
  111. {
  112. $attachment['physical_filename'] = utf8_basename($attachment['attachment_directory']) . '/thumb_' . utf8_basename($attachment['physical_filename']);
  113. }
  114. else
  115. {
  116. $attachment['physical_filename'] = utf8_basename($attachment['attachment_directory']) . '/' . utf8_basename($attachment['physical_filename']);
  117. }
  118. if ($attachment['is_orphan'] && phpbb::$user->data['user_id'] != $attachment['attachment_user_id'] && !phpbb::$auth->acl_get('a_attach'))
  119. {
  120. trigger_error('ERROR_NO_ATTACHMENT');
  121. }
  122. else if (!download_allowed())
  123. {
  124. header('HTTP/1.0 403 Forbidden');
  125. trigger_error('SORRY_AUTH_VIEW_ATTACH');
  126. }
  127. else if ($attachment['attachment_access'] < titania::$access_level && $attachment['attachment_access'] == TITANIA_ACCESS_TEAMS)
  128. {
  129. header('HTTP/1.0 403 Forbidden');
  130. trigger_error('SORRY_AUTH_VIEW_ATTACH');
  131. }
  132. else if ($attachment['attachment_access'] < titania::$access_level && $attachment['attachment_access'] == TITANIA_ACCESS_AUTHORS)
  133. {
  134. // Author level check
  135. $contrib = false;
  136. switch ((int) $attachment['object_type'])
  137. {
  138. case TITANIA_FAQ :
  139. $sql = 'SELECT c.contrib_id, c.contrib_user_id
  140. FROM ' . TITANIA_CONTRIB_FAQ_TABLE . ' f, ' . TITANIA_CONTRIBS_TABLE . ' c
  141. WHERE f.faq_id = ' . $attachment['object_id'] . '
  142. AND c.contrib_id = f.contrib_id';
  143. $result = phpbb::$db->sql_query($sql);
  144. $contrib = phpbb::$db->sql_fetchrow($result);
  145. phpbb::$db->sql_freeresult($result);
  146. break;
  147. case TITANIA_SUPPORT :
  148. case TITANIA_QUEUE_DISCUSSION :
  149. $sql = 'SELECT c.contrib_id, c.contrib_user_id
  150. FROM ' . TITANIA_POSTS_TABLE . ' p, ' . TITANIA_TOPICS_TABLE . ' t, ' . TITANIA_CONTRIBS_TABLE . ' c
  151. WHERE p.post_id = ' . $attachment['object_id'] . '
  152. AND t.topic_id = p.topic_id
  153. AND c.contrib_id = t.parent_id';
  154. $result = phpbb::$db->sql_query($sql);
  155. $contrib = phpbb::$db->sql_fetchrow($result);
  156. phpbb::$db->sql_freeresult($result);
  157. break;
  158. }
  159. if ($contrib !== false)
  160. {
  161. if ($contrib['contrib_user_id'] == phpbb::$user->data['user_id'])
  162. {
  163. // Main author
  164. titania::$access_level = TITANIA_ACCESS_AUTHORS;
  165. }
  166. else
  167. {
  168. // Coauthor
  169. $sql = 'SELECT user_id FROM ' . TITANIA_CONTRIB_COAUTHORS_TABLE . '
  170. WHERE contrib_id = ' . $contrib['contrib_id'] . '
  171. AND user_id = ' . phpbb::$user->data['user_id'] . '
  172. AND active = 1';
  173. $result = phpbb::$db->sql_query($sql);
  174. if (phpbb::$db->sql_fetchrow($result))
  175. {
  176. titania::$access_level = TITANIA_ACCESS_AUTHORS;
  177. }
  178. phpbb::$db->sql_freeresult($result);
  179. }
  180. }
  181. // Still not authorised?
  182. if ($attachment['attachment_access'] < titania::$access_level)
  183. {
  184. header('HTTP/1.0 403 Forbidden');
  185. trigger_error('SORRY_AUTH_VIEW_ATTACH');
  186. }
  187. }
  188. /*
  189. * Can not currently be done with the way extensions are setup... @todo?
  190. $extensions = titania::$cache->obtain_attach_extensions();
  191. $download_mode = (int) $extensions[$attachment['extension']]['download_mode'];
  192. $attachment['physical_filename'] = utf8_basename($attachment['physical_filename']);
  193. $display_cat = $extensions[$attachment['extension']]['display_cat'];
  194. if (($display_cat == ATTACHMENT_CATEGORY_IMAGE || $display_cat == ATTACHMENT_CATEGORY_THUMB) && !$user->optionget('viewimg'))
  195. {
  196. $display_cat = ATTACHMENT_CATEGORY_NONE;
  197. }
  198. if ($display_cat == ATTACHMENT_CATEGORY_FLASH && !$user->optionget('viewflash'))
  199. {
  200. $display_cat = ATTACHMENT_CATEGORY_NONE;
  201. }
  202. */
  203. if (!$thumbnail)
  204. {
  205. // Update download count
  206. $sql = 'UPDATE ' . TITANIA_ATTACHMENTS_TABLE . '
  207. SET download_count = download_count + 1
  208. WHERE attachment_id = ' . $attachment['attachment_id'];
  209. phpbb::$db->sql_query($sql);
  210. // Update download count for the contrib object as well
  211. if ($attachment['object_type'] == TITANIA_CONTRIB)
  212. {
  213. $sql = 'UPDATE ' . TITANIA_CONTRIBS_TABLE . '
  214. SET contrib_downloads = contrib_downloads + 1
  215. WHERE contrib_id = ' . $attachment['object_id'];
  216. phpbb::$db->sql_query($sql);
  217. }
  218. }
  219. if (!$thumbnail && $mode === 'view' && (strpos($attachment['mimetype'], 'image') === 0) && ((strpos(strtolower(phpbb::$user->browser), 'msie') !== false) && (strpos(strtolower(phpbb::$user->browser), 'msie 8.0') === false)))
  220. {
  221. wrap_img_in_html(titania_url::build_url('download', array('id' => $attachment['attachment_id'])), $attachment['real_filename']);
  222. file_gc();
  223. }
  224. else
  225. {
  226. send_file_to_browser($attachment, titania::$config->upload_path);
  227. file_gc();
  228. }
  229. /**
  230. * Wraps an url into a simple html page. Used to display attachments in IE.
  231. * this is a workaround for now; might be moved to template system later
  232. * direct any complaints to 1 Microsoft Way, Redmond
  233. */
  234. function wrap_img_in_html($src, $title)
  235. {
  236. echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-Strict.dtd">';
  237. echo '<html>';
  238. echo '<head>';
  239. echo '<meta http-equiv="content-type" content="text/html; charset=UTF-8" />';
  240. echo '<title>' . $title . '</title>';
  241. echo '</head>';
  242. echo '<body>';
  243. echo '<div>';
  244. echo '<img src="' . $src . '" alt="' . $title . '" />';
  245. echo '</div>';
  246. echo '</body>';
  247. echo '</html>';
  248. }
  249. /**
  250. * Send file to browser
  251. */
  252. function send_file_to_browser($attachment, $upload_dir)
  253. {
  254. $filename = $upload_dir . $attachment['physical_filename'];
  255. if (!@file_exists($filename))
  256. {
  257. trigger_error(phpbb::$user->lang['ERROR_NO_ATTACHMENT'] . '<br /><br />' . sprintf(phpbb::$user->lang['FILE_NOT_FOUND_404'], $filename));
  258. }
  259. // Correct the mime type - we force application/octetstream for all files, except images
  260. // Please do not change this, it is a security precaution
  261. if (strpos($attachment['mimetype'], 'image') !== 0)
  262. {
  263. $attachment['mimetype'] = (strpos(strtolower(phpbb::$user->browser), 'msie') !== false || strpos(strtolower(phpbb::$user->browser), 'opera') !== false) ? 'application/octetstream' : 'application/octet-stream';
  264. }
  265. if (@ob_get_length())
  266. {
  267. @ob_end_clean();
  268. }
  269. // Now send the File Contents to the Browser
  270. $size = @filesize($filename);
  271. // To correctly display further errors we need to make sure we are using the correct headers for both (unsetting content-length may not work)
  272. // Check if headers already sent or not able to get the file contents.
  273. if (headers_sent() || !@file_exists($filename) || !@is_readable($filename))
  274. {
  275. // PHP track_errors setting On?
  276. if (!empty($php_errormsg))
  277. {
  278. trigger_error(phpbb::$user->lang['UNABLE_TO_DELIVER_FILE'] . '<br />' . sprintf(phpbb::$user->lang['TRACKED_PHP_ERROR'], $php_errormsg));
  279. }
  280. trigger_error('UNABLE_TO_DELIVER_FILE');
  281. }
  282. // Now the tricky part... let's dance
  283. header('Pragma: public');
  284. // Send out the Headers. Do not set Content-Disposition to inline please, it is a security measure for users using the Internet Explorer.
  285. $is_ie8 = (strpos(strtolower(phpbb::$user->browser), 'msie 8.0') !== false);
  286. header('Content-Type: ' . $attachment['mimetype']);
  287. if ($is_ie8)
  288. {
  289. header('X-Content-Type-Options: nosniff');
  290. }
  291. if (empty(phpbb::$user->browser) || (!$is_ie8 && (strpos(strtolower(phpbb::$user->browser), 'msie') !== false)))
  292. {
  293. header('Content-Disposition: attachment; ' . header_filename(htmlspecialchars_decode($attachment['real_filename'])));
  294. if (empty(phpbb::$user->browser) || (strpos(strtolower(phpbb::$user->browser), 'msie 6.0') !== false))
  295. {
  296. header('expires: -1');
  297. }
  298. }
  299. else
  300. {
  301. header('Content-Disposition: ' . ((strpos($attachment['mimetype'], 'image') === 0) ? 'inline' : 'attachment') . '; ' . header_filename(htmlspecialchars_decode($attachment['real_filename'])));
  302. if ($is_ie8 && (strpos($attachment['mimetype'], 'image') !== 0))
  303. {
  304. header('X-Download-Options: noopen');
  305. }
  306. }
  307. if ($size)
  308. {
  309. header("Content-Length: $size");
  310. }
  311. // Close the db connection before sending the file
  312. phpbb::$db->sql_close();
  313. if (!set_modified_headers($attachment['filetime'], phpbb::$user->browser))
  314. {
  315. // Try to deliver in chunks
  316. @set_time_limit(0);
  317. $fp = @fopen($filename, 'rb');
  318. if ($fp !== false)
  319. {
  320. while (!feof($fp))
  321. {
  322. echo fread($fp, 8192);
  323. }
  324. fclose($fp);
  325. }
  326. else
  327. {
  328. @readfile($filename);
  329. }
  330. flush();
  331. }
  332. file_gc();
  333. }
  334. /**
  335. * Get a browser friendly UTF-8 encoded filename
  336. */
  337. function header_filename($file)
  338. {
  339. $user_agent = (!empty($_SERVER['HTTP_USER_AGENT'])) ? htmlspecialchars((string) $_SERVER['HTTP_USER_AGENT']) : '';
  340. // There be dragons here.
  341. // Not many follows the RFC...
  342. if (strpos($user_agent, 'MSIE') !== false || strpos($user_agent, 'Safari') !== false || strpos($user_agent, 'Konqueror') !== false)
  343. {
  344. return "filename=" . rawurlencode($file);
  345. }
  346. // follow the RFC for extended filename for the rest
  347. return "filename*=UTF-8''" . rawurlencode($file);
  348. }
  349. /**
  350. * Check if downloading item is allowed
  351. */
  352. function download_allowed()
  353. {
  354. if (!phpbb::$config['secure_downloads'])
  355. {
  356. return true;
  357. }
  358. $url = (!empty($_SERVER['HTTP_REFERER'])) ? trim($_SERVER['HTTP_REFERER']) : trim(getenv('HTTP_REFERER'));
  359. if (!$url)
  360. {
  361. return (phpbb::$config['secure_allow_empty_referer']) ? true : false;
  362. }
  363. // Split URL into domain and script part
  364. $url = @parse_url($url);
  365. if ($url === false)
  366. {
  367. return (phpbb::$config['secure_allow_empty_referer']) ? true : false;
  368. }
  369. $hostname = $url['host'];
  370. unset($url);
  371. $allowed = (phpbb::$config['secure_allow_deny']) ? false : true;
  372. $iplist = array();
  373. if (($ip_ary = @gethostbynamel($hostname)) !== false)
  374. {
  375. foreach ($ip_ary as $ip)
  376. {
  377. if ($ip)
  378. {
  379. $iplist[] = $ip;
  380. }
  381. }
  382. }
  383. // Check for own server...
  384. $server_name = phpbb::$user->host;
  385. // Forcing server vars is the only way to specify/override the protocol
  386. if (phpbb::$config['force_server_vars'] || !$server_name)
  387. {
  388. $server_name = phpbb::$config['server_name'];
  389. }
  390. if (preg_match('#^.*?' . preg_quote($server_name, '#') . '.*?$#i', $hostname))
  391. {
  392. $allowed = true;
  393. }
  394. // Get IP's and Hostnames
  395. if (!$allowed)
  396. {
  397. $sql = 'SELECT site_ip, site_hostname, ip_exclude
  398. FROM ' . SITELIST_TABLE;
  399. $result = phpbb::$db->sql_query($sql);
  400. while ($row = phpbb::$db->sql_fetchrow($result))
  401. {
  402. $site_ip = trim($row['site_ip']);
  403. $site_hostname = trim($row['site_hostname']);
  404. if ($site_ip)
  405. {
  406. foreach ($iplist as $ip)
  407. {
  408. if (preg_match('#^' . str_replace('\*', '.*?', preg_quote($site_ip, '#')) . '$#i', $ip))
  409. {
  410. if ($row['ip_exclude'])
  411. {
  412. $allowed = (phpbb::$config['secure_allow_deny']) ? false : true;
  413. break 2;
  414. }
  415. else
  416. {
  417. $allowed = (phpbb::$config['secure_allow_deny']) ? true : false;
  418. }
  419. }
  420. }
  421. }
  422. if ($site_hostname)
  423. {
  424. if (preg_match('#^' . str_replace('\*', '.*?', preg_quote($site_hostname, '#')) . '$#i', $hostname))
  425. {
  426. if ($row['ip_exclude'])
  427. {
  428. $allowed = (phpbb::$config['secure_allow_deny']) ? false : true;
  429. break;
  430. }
  431. else
  432. {
  433. $allowed = (phpbb::$config['secure_allow_deny']) ? true : false;
  434. }
  435. }
  436. }
  437. }
  438. phpbb::$db->sql_freeresult($result);
  439. }
  440. return $allowed;
  441. }
  442. /**
  443. * Check if the browser has the file already and set the appropriate headers-
  444. * @returns false if a resend is in order.
  445. */
  446. function set_modified_headers($stamp, $browser)
  447. {
  448. // let's see if we have to send the file at all
  449. $last_load = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? strtotime(trim($_SERVER['HTTP_IF_MODIFIED_SINCE'])) : false;
  450. if ((strpos(strtolower($browser), 'msie 6.0') === false) && (strpos(strtolower($browser), 'msie 8.0') === false))
  451. {
  452. if ($last_load !== false && $last_load <= $stamp)
  453. {
  454. if (substr(strtolower(@php_sapi_name()),0,3) === 'cgi')
  455. {
  456. // in theory, we shouldn't need that due to php doing it. Reality offers a differing opinion, though
  457. header('Status: 304 Not Modified', true, 304);
  458. }
  459. else
  460. {
  461. header('HTTP/1.0 304 Not Modified', true, 304);
  462. }
  463. // seems that we need those too ... browsers
  464. header('Pragma: public');
  465. header('Expires: ' . gmdate('D, d M Y H:i:s \G\M\T', time() + 31536000));
  466. return true;
  467. }
  468. else
  469. {
  470. header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $stamp) . ' GMT');
  471. }
  472. }
  473. return false;
  474. }
  475. function file_gc()
  476. {
  477. if (!empty(phpbb::$cache))
  478. {
  479. phpbb::$cache->unload();
  480. }
  481. phpbb::$db->sql_close();
  482. exit;
  483. }
  484. ?>