Issues (1065)

Sources/ShowAttachments.php (13 issues)

1
<?php
2
3
/**
4
 * This file handles avatar and attachment requests. The whole point of this file is to reduce the loaded stuff to show an image.
5
 *
6
 * Simple Machines Forum (SMF)
7
 *
8
 * @package SMF
9
 * @author Simple Machines https://www.simplemachines.org
10
 * @copyright 2025 Simple Machines and individual contributors
11
 * @license https://www.simplemachines.org/about/smf/license.php BSD
12
 *
13
 * @version 2.1.5
14
 */
15
16
if (!defined('SMF'))
17
	die('No direct access...');
18
19
/**
20
 * Downloads an avatar or attachment based on $_GET['attach'], and increments the download count.
21
 * It requires the view_attachments permission.
22
 * It disables the session parser, and clears any previous output.
23
 * It depends on the attachmentUploadDir setting being correct.
24
 * It is accessed via the query string ?action=dlattach.
25
 * Views to attachments do not increase hits and are not logged in the "Who's Online" log.
26
 */
27
function showAttachment()
28
{
29
	global $smcFunc, $modSettings, $maintenance, $context, $txt, $user_info;
30
31
	// Some defaults that we need.
32
	$context['character_set'] = empty($modSettings['global_character_set']) ? (empty($txt['lang_character_set']) ? 'ISO-8859-1' : $txt['lang_character_set']) : $modSettings['global_character_set'];
33
	$context['utf8'] = $context['character_set'] === 'UTF-8';
34
35
	// An early hook to set up global vars, clean cache and other early process.
36
	call_integration_hook('integrate_pre_download_request');
37
38
	// This is done to clear any output that was made before now.
39
	ob_end_clean();
40
	header_remove('content-encoding');
41
42
	if (!empty($modSettings['enableCompressedOutput']) && !headers_sent() && ob_get_length() == 0)
43
	{
44
		if (@ini_get('zlib.output_compression') == '1' || @ini_get('output_handler') == 'ob_gzhandler')
45
			$modSettings['enableCompressedOutput'] = 0;
46
47
		else
48
			ob_start('ob_gzhandler');
49
	}
50
51
	if (empty($modSettings['enableCompressedOutput']))
52
	{
53
		ob_start();
54
		header('content-encoding: none');
55
	}
56
57
	// Better handling.
58
	$attachId = $_REQUEST['attach'] = isset($_REQUEST['attach']) ? (int) $_REQUEST['attach'] : (int) (isset($_REQUEST['id']) ? (int) $_REQUEST['id'] : 0);
59
60
	// We need a valid ID.
61
	if (empty($attachId))
62
	{
63
		send_http_status(404, 'File Not Found');
64
		die('404 File Not Found');
0 ignored issues
show
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
65
	}
66
67
	// A thumbnail has been requested? madness! madness I say!
68
	$showThumb = isset($_REQUEST['thumb']);
69
70
	// No access in strict maintenance mode.
71
	if (!empty($maintenance) && $maintenance == 2)
72
	{
73
		send_http_status(404, 'File Not Found');
74
		die('404 File Not Found');
0 ignored issues
show
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
75
	}
76
77
	// Use cache when possible.
78
	if (($cache = cache_get_data('attachment_lookup_id-' . $attachId)) != null)
79
		list ($file, $thumbFile) = $cache;
80
81
	// Get the info from the DB.
82
	if (empty($file) || empty($thumbFile) && !empty($file['id_thumb']))
83
	{
84
		// Do we have a hook wanting to use our attachment system? We use $attachRequest to prevent accidental usage of $request.
85
		$attachRequest = null;
86
		call_integration_hook('integrate_download_request', array(&$attachRequest));
87
		if (!is_null($attachRequest) && $smcFunc['db_is_resource']($attachRequest))
0 ignored issues
show
The condition is_null($attachRequest) is always true.
Loading history...
88
			$request = $attachRequest;
89
		else
90
		{
91
			// Make sure this attachment is on this board and load its info while we are at it.
92
			$request = $smcFunc['db_query']('', '
93
				SELECT
94
					{string:source} AS source,
95
					a.id_folder, a.filename, a.file_hash, a.fileext, a.id_attach,
96
					a.id_thumb, a.attachment_type, a.mime_type, a.approved, a.id_msg,
97
					m.id_board
98
				FROM {db_prefix}attachments AS a
99
					LEFT JOIN {db_prefix}messages AS m ON (m.id_msg = a.id_msg)
100
				WHERE a.id_attach = {int:attach}
101
				LIMIT 1',
102
				array(
103
					'source' => 'SMF',
104
					'attach' => $attachId,
105
				)
106
			);
107
		}
108
109
		// No attachment has been found.
110
		if ($smcFunc['db_num_rows']($request) == 0)
111
		{
112
			send_http_status(404, 'File Not Found');
113
			die('404 File Not Found');
0 ignored issues
show
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
114
		}
115
116
		$file = $smcFunc['db_fetch_assoc']($request);
117
		$smcFunc['db_free_result']($request);
118
119
		// set filePath and ETag time
120
		$file['filePath'] = getAttachmentFilename($file['filename'], $attachId, $file['id_folder'], false, $file['file_hash']);
121
		// ensure variant attachment compatibility
122
		$filePath = pathinfo($file['filePath']);
123
124
		$file['exists'] = file_exists($file['filePath']);
125
		$file['filePath'] = !$file['exists'] && isset($filePath['extension']) ? substr($file['filePath'], 0, -(strlen($filePath['extension']) + 1)) : $file['filePath'];
126
		$file['mtime'] = $file['exists'] ? filemtime($file['filePath']) : 0;
127
		$file['size'] = $file['exists'] ? filesize($file['filePath']) : 0;
128
		$file['etag'] = $file['exists'] ? sha1_file($file['filePath']) : '';
129
		$file['filename'] = un_htmlspecialchars($file['filename']);
130
131
		// now get the thumbfile!
132
		$thumbFile = array();
133
		if (!empty($file['id_thumb']))
134
		{
135
			$request = $smcFunc['db_query']('', '
136
				SELECT id_folder, filename, file_hash, fileext, id_attach, attachment_type, mime_type, approved, id_member
137
				FROM {db_prefix}attachments
138
				WHERE id_attach = {int:thumb_id}
139
				LIMIT 1',
140
				array(
141
					'thumb_id' => $file['id_thumb'],
142
				)
143
			);
144
145
			$thumbFile = $smcFunc['db_fetch_assoc']($request);
146
			$smcFunc['db_free_result']($request);
147
148
			// Got something! replace the $file var with the thumbnail info.
149
			if ($thumbFile)
150
			{
151
				$thumbFile['filePath'] = getAttachmentFilename($thumbFile['filename'], $thumbFile['id_attach'], $thumbFile['id_folder'], false, $thumbFile['file_hash']);
152
				$thumbPath = pathinfo($thumbFile['filePath']);
153
154
				// set filePath and ETag time
155
				$thumbFile['exists'] = file_exists($thumbFile['filePath']);
156
				$thumbFile['filePath'] = !$thumbFile['exists'] && isset($thumbPath['extension']) ? substr($thumbFile['filePath'], 0, -(strlen($thumbPath['extension']) + 1)) : $thumbFile['filePath'];
157
				$thumbFile['mtime'] = $thumbFile['exists'] ? filemtime($thumbFile['filePath']) : 0;
158
				$thumbFile['size'] = $thumbFile['exists'] ? filesize($thumbFile['filePath']) : 0;
159
				$thumbFile['etag'] = $thumbFile['exists'] ? sha1_file($thumbFile['filePath']) : '';
160
			}
161
		}
162
163
		// Cache it.
164
		if (!empty($file) || !empty($thumbFile))
165
			cache_put_data('attachment_lookup_id-' . $file['id_attach'], array($file, $thumbFile), mt_rand(850, 900));
166
	}
167
168
	// Can they see attachments on this board?
169
	if (!empty($file['id_msg']))
170
	{
171
		// Special case for profile exports.
172
		if (!empty($context['attachment_allow_hidden_boards']))
173
		{
174
			$boards_allowed = array(0);
175
		}
176
		// Check permissions and board access.
177
		elseif (($boards_allowed = cache_get_data('view_attachment_boards_id-' . $user_info['id'])) == null)
178
		{
179
			$boards_allowed = boardsAllowedTo('view_attachments');
180
			cache_put_data('view_attachment_boards_id-' . $user_info['id'], $boards_allowed, mt_rand(850, 900));
181
		}
182
	}
183
184
	// No access if you don't have permission to see this attachment.
185
	if
186
	(
187
		// This was from SMF or a hook didn't claim it.
188
		(
189
			empty($file['source'])
190
			|| $file['source'] == 'SMF'
191
		)
192
		&& (
193
			// No id_msg and no id_member, so we don't know where its from.
194
			// Avatars will have id_msg = 0 and id_member > 0.
195
			(
196
				empty($file['id_msg'])
197
				&& empty($file['id_member'])
198
			)
199
			// When we have a message, we need a board and that board needs to
200
			// let us view the attachment.
201
			|| (
202
				!empty($file['id_msg'])
203
				&& (
204
					empty($file['id_board'])
205
					|| ($boards_allowed !== array(0) && !in_array($file['id_board'], $boards_allowed))
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $boards_allowed does not seem to be defined for all execution paths leading up to this point.
Loading history...
206
				)
207
			)
208
		)
209
		// We are not previewing an attachment.
210
		&& !isset($_SESSION['attachments_can_preview'][$attachId])
211
	)
212
	{
213
		send_http_status(404, 'File Not Found');
214
		die('404 File Not Found');
0 ignored issues
show
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
215
	}
216
217
	// If attachment is unapproved, see if user is allowed to approve
218
	if (!$file['approved'] && $modSettings['postmod_active'] && !allowedTo('approve_posts'))
219
	{
220
		$request = $smcFunc['db_query']('', '
221
			SELECT id_member
222
			FROM {db_prefix}messages
223
			WHERE id_msg = {int:id_msg}
224
			LIMIT 1',
225
			array(
226
				'id_msg' => $file['id_msg'],
227
			)
228
		);
229
230
		$id_member = $smcFunc['db_fetch_assoc']($request)['id_member'];
231
		$smcFunc['db_free_result']($request);
232
233
		// Let users see own unapproved attachments
234
		if ($id_member != $user_info['id'])
235
		{
236
			send_http_status(403, 'Forbidden');
237
			die('403 Forbidden');
0 ignored issues
show
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
238
		}
239
	}
240
241
	// Replace the normal file with its thumbnail if it has one!
242
	if (!empty($showThumb) && !empty($thumbFile))
243
		$file = $thumbFile;
244
245
	// No point in a nicer message, because this is supposed to be an attachment anyway...
246
	if (empty($file['exists']))
247
	{
248
		send_http_status(404);
249
		header('content-type: text/plain; charset=' . (empty($context['character_set']) ? 'ISO-8859-1' : $context['character_set']));
250
251
		// We need to die like this *before* we send any anti-caching headers as below.
252
		die('File not found.');
253
	}
254
255
	// If it hasn't been modified since the last time this attachment was retrieved, there's no need to display it again.
256
	if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']))
257
	{
258
		list($modified_since) = explode(';', $_SERVER['HTTP_IF_MODIFIED_SINCE']);
259
		if (!empty($file['mtime']) && strtotime($modified_since) >= $file['mtime'])
260
		{
261
			ob_end_clean();
262
			header_remove('content-encoding');
263
264
			// Answer the question - no, it hasn't been modified ;).
265
			send_http_status(304);
266
			exit;
0 ignored issues
show
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
267
		}
268
	}
269
270
	// Check whether the ETag was sent back, and cache based on that...
271
	if (!empty($file['etag']) && !empty($_SERVER['HTTP_IF_NONE_MATCH']) && strpos($_SERVER['HTTP_IF_NONE_MATCH'], $file['etag']) !== false)
272
	{
273
		ob_end_clean();
274
		header_remove('content-encoding');
275
276
		send_http_status(304);
277
		exit;
0 ignored issues
show
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
278
	}
279
280
	// If this is a partial download, we need to determine what data range to send
281
	$range = 0;
282
	if (isset($_SERVER['HTTP_RANGE']))
283
	{
284
		list($a, $range) = explode("=", $_SERVER['HTTP_RANGE'], 2);
285
		list($range) = explode(",", $range, 2);
286
		list($range, $range_end) = explode("-", $range);
287
		$range = intval($range);
288
		$range_end = !$range_end ? $file['size'] - 1 : intval($range_end);
289
		$new_length = $range_end - $range + 1;
290
	}
291
292
	// Update the download counter (unless it's a thumbnail or resuming an incomplete download).
293
	if ($file['attachment_type'] != 3 && empty($showThumb) && empty($_REQUEST['preview']) && $range === 0 && empty($context['skip_downloads_increment']))
294
		$smcFunc['db_query']('', '
295
			UPDATE {db_prefix}attachments
296
			SET downloads = downloads + 1
297
			WHERE id_attach = {int:id_attach}',
298
			array(
299
				'id_attach' => $attachId,
300
			)
301
		);
302
303
	// Send the attachment headers.
304
	header('pragma: ');
305
306
	if (!isBrowser('gecko'))
307
		header('content-transfer-encoding: binary');
308
309
	header('expires: ' . gmdate('D, d M Y H:i:s', time() + 525600 * 60) . ' GMT');
310
	header('last-modified: ' . gmdate('D, d M Y H:i:s', $file['mtime']) . ' GMT');
311
	header('accept-ranges: bytes');
312
	header('connection: close');
313
	header('etag: "' . $file['etag'] . '"');
314
315
	// Make sure the mime type warrants an inline display.
316
	if (isset($_REQUEST['image']) && !empty($file['mime_type']) && strpos($file['mime_type'], 'image/') !== 0)
317
		unset($_REQUEST['image']);
318
319
	// Does this have a mime type?
320
	elseif (!empty($file['mime_type']) && (isset($_REQUEST['image']) || !in_array($file['fileext'], array('jpg', 'gif', 'jpeg', 'x-ms-bmp', 'png', 'psd', 'tiff', 'iff', 'webp'))))
321
		header('content-type: ' . strtr($file['mime_type'], array('image/bmp' => 'image/x-ms-bmp')));
322
323
	else
324
	{
325
		header('content-type: ' . (isBrowser('ie') || isBrowser('opera') ? 'application/octetstream' : 'application/octet-stream'));
326
		if (isset($_REQUEST['image']))
327
			unset($_REQUEST['image']);
328
	}
329
330
	// Convert the file to UTF-8, cuz most browsers dig that.
331
	$utf8name = !$context['utf8'] && function_exists('iconv') ? iconv($context['character_set'], 'UTF-8', $file['filename']) : (!$context['utf8'] && function_exists('mb_convert_encoding') ? mb_convert_encoding($file['filename'], 'UTF-8', $context['character_set']) : $file['filename']);
332
333
	if (!empty($context['prepend_attachment_id']))
334
		$utf8name = $_REQUEST['attach'] . ' - ' . $utf8name;
0 ignored issues
show
Are you sure $utf8name of type array|mixed|string can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

334
		$utf8name = $_REQUEST['attach'] . ' - ' . /** @scrutinizer ignore-type */ $utf8name;
Loading history...
335
336
	// On mobile devices, audio and video should be served inline so the browser can play them.
337
	if (isset($_REQUEST['image']) || (isBrowser('is_mobile') && (strpos($file['mime_type'], 'audio/') === 0 || strpos($file['mime_type'], 'video/') === 0)))
338
		$disposition = 'inline';
339
	else
340
		$disposition = 'attachment';
341
342
	// Different browsers like different standards...
343
	if (isBrowser('firefox'))
344
		header('content-disposition: ' . $disposition . '; filename*=UTF-8\'\'' . rawurlencode(preg_replace_callback('~&#(\d{3,8});~', 'fixchar__callback', $utf8name)));
345
346
	elseif (isBrowser('opera'))
347
		header('content-disposition: ' . $disposition . '; filename="' . preg_replace_callback('~&#(\d{3,8});~', 'fixchar__callback', $utf8name) . '"');
348
349
	elseif (isBrowser('ie'))
350
		header('content-disposition: ' . $disposition . '; filename="' . urlencode(preg_replace_callback('~&#(\d{3,8});~', 'fixchar__callback', $utf8name)) . '"');
351
352
	else
353
		header('content-disposition: ' . $disposition . '; filename="' . $utf8name . '"');
354
355
	// If this has an "image extension" - but isn't actually an image - then ensure it isn't cached cause of silly IE.
356
	if (!isset($_REQUEST['image']) && in_array($file['fileext'], array('gif', 'jpg', 'bmp', 'png', 'jpeg', 'tiff', 'webp')))
357
		header('cache-control: no-cache');
358
359
	else
360
		header('cache-control: max-age=' . (525600 * 60) . ', private');
361
362
	// Multipart and resuming support
363
	if (isset($_SERVER['HTTP_RANGE']))
364
	{
365
		send_http_status(206);
366
		header("content-length: $new_length");
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $new_length does not seem to be defined for all execution paths leading up to this point.
Loading history...
367
		header("content-range: bytes $range-$range_end/$file[size]");
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $range_end does not seem to be defined for all execution paths leading up to this point.
Loading history...
368
	}
369
	else
370
		header("content-length: " . $file['size']);
371
372
	// Allow customizations to hook in here before we send anything to modify any headers needed.  Or to change the process of how we output.
373
	call_integration_hook('integrate_download_headers');
374
375
	// Try to buy some time...
376
	@set_time_limit(600);
377
378
	// For multipart/resumable downloads, send the requested chunk(s) of the file
379
	if (isset($_SERVER['HTTP_RANGE']))
380
	{
381
		while (@ob_get_level() > 0)
382
			@ob_end_clean();
383
384
		header_remove('content-encoding');
385
386
		// 40 kilobytes is a good-ish amount
387
		$chunksize = 40 * 1024;
388
		$bytes_sent = 0;
389
390
		$fp = fopen($file['filePath'], 'rb');
391
392
		fseek($fp, $range);
393
394
		while (!feof($fp) && (!connection_aborted()) && ($bytes_sent < $new_length))
395
		{
396
			$buffer = fread($fp, $chunksize);
397
			echo($buffer);
398
			flush();
399
			$bytes_sent += strlen($buffer);
400
		}
401
		fclose($fp);
402
	}
403
404
	// Since we don't do output compression for files this large...
405
	elseif ($file['size'] > 4194304)
406
	{
407
		// Forcibly end any output buffering going on.
408
		while (@ob_get_level() > 0)
409
			@ob_end_clean();
410
411
		header_remove('content-encoding');
412
413
		$fp = fopen($file['filePath'], 'rb');
414
		while (!feof($fp))
415
		{
416
			echo fread($fp, 8192);
417
			flush();
418
		}
419
		fclose($fp);
420
	}
421
422
	// On some of the less-bright hosts, readfile() is disabled.  It's just a faster, more byte safe, version of what's in the if.
423
	elseif (@readfile($file['filePath']) === null)
424
		echo file_get_contents($file['filePath']);
425
426
	die();
0 ignored issues
show
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
427
}
428
429
?>