PageRenderTime 61ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 0ms

/titania/download/file.php

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