showAttachment()   F
last analyzed

Complexity

Conditions 99

Size

Total Lines 399
Code Lines 191

Duplication

Lines 0
Ratio 0 %

Importance

Changes 6
Bugs 0 Features 0
Metric Value
cc 99
eloc 191
c 6
b 0
f 0
nop 0
dl 0
loc 399
rs 3.3333

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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 2022 Simple Machines and individual contributors
11
 * @license https://www.simplemachines.org/about/smf/license.php BSD
12
 *
13
 * @version 2.1.2
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
Best Practice introduced by
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
Best Practice introduced by
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
introduced by
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
Best Practice introduced by
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'] = '"' . sha1_file($file['filePath']) . '"';
129
130
		// now get the thumbfile!
131
		$thumbFile = array();
132
		if (!empty($file['id_thumb']))
133
		{
134
			$request = $smcFunc['db_query']('', '
135
				SELECT id_folder, filename, file_hash, fileext, id_attach, attachment_type, mime_type, approved, id_member
136
				FROM {db_prefix}attachments
137
				WHERE id_attach = {int:thumb_id}
138
				LIMIT 1',
139
				array(
140
					'thumb_id' => $file['id_thumb'],
141
				)
142
			);
143
144
			$thumbFile = $smcFunc['db_fetch_assoc']($request);
145
			$smcFunc['db_free_result']($request);
146
147
			// Got something! replace the $file var with the thumbnail info.
148
			if ($thumbFile)
149
			{
150
				$thumbFile['filePath'] = getAttachmentFilename($thumbFile['filename'], $thumbFile['id_attach'], $thumbFile['id_folder'], false, $thumbFile['file_hash']);
151
				$thumbPath = pathinfo($thumbFile['filePath']);
152
153
				// set filePath and ETag time
154
				$thumbFile['exists'] = file_exists($thumbFile['filePath']);
155
				$thumbFile['filePath'] = !$thumbFile['exists'] && isset($thumbPath['extension']) ? substr($thumbFile['filePath'], 0, -(strlen($thumbPath['extension']) + 1)) : $thumbFile['filePath'];
156
				$thumbFile['mtime'] = $thumbFile['exists'] ? filemtime($thumbFile['filePath']) : 0;
157
				$thumbFile['size'] = $thumbFile['exists'] ? filesize($thumbFile['filePath']) : 0;
158
				$thumbFile['etag'] = '"' . sha1_file($thumbFile['filePath']) . '"';
159
			}
160
		}
161
162
		// Cache it.
163
		if (!empty($file) || !empty($thumbFile))
164
			cache_put_data('attachment_lookup_id-' . $file['id_attach'], array($file, $thumbFile), mt_rand(850, 900));
165
	}
166
167
	// Can they see attachments on this board?
168
	if (!empty($file['id_msg']))
169
	{
170
		// Special case for profile exports.
171
		if (!empty($context['attachment_allow_hidden_boards']))
172
		{
173
			$boards_allowed = array(0);
174
		}
175
		// Check permissions and board access.
176
		elseif (($boards_allowed = cache_get_data('view_attachment_boards_id-' . $user_info['id'])) == null)
177
		{
178
			$boards_allowed = boardsAllowedTo('view_attachments');
179
			cache_put_data('view_attachment_boards_id-' . $user_info['id'], $boards_allowed, mt_rand(850, 900));
180
		}
181
	}
182
183
	// No access if you don't have permission to see this attachment.
184
	if
185
	(
186
		// This was from SMF or a hook didn't claim it.
187
		(
188
			empty($file['source'])
189
			|| $file['source'] == 'SMF'
190
		)
191
		&& (
192
			// No id_msg and no id_member, so we don't know where its from.
193
			// Avatars will have id_msg = 0 and id_member > 0.
194
			(
195
				empty($file['id_msg'])
196
				&& empty($file['id_member'])
197
			)
198
			// When we have a message, we need a board and that board needs to
199
			// let us view the attachment.
200
			|| (
201
				!empty($file['id_msg'])
202
				&& (
203
					empty($file['id_board'])
204
					|| ($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...
205
				)
206
			)
207
		)
208
		// We are not previewing an attachment.
209
		&& !isset($_SESSION['attachments_can_preview'][$attachId])
210
	)
211
	{
212
		send_http_status(404, 'File Not Found');
213
		die('404 File Not Found');
0 ignored issues
show
Best Practice introduced by
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...
214
	}
215
216
	// If attachment is unapproved, see if user is allowed to approve
217
	if (!$file['approved'] && $modSettings['postmod_active'] && !allowedTo('approve_posts'))
218
	{
219
		$request = $smcFunc['db_query']('', '
220
			SELECT id_member
221
			FROM {db_prefix}messages
222
			WHERE id_msg = {int:id_msg}
223
			LIMIT 1',
224
			array(
225
				'id_msg' => $file['id_msg'],
226
			)
227
		);
228
229
		$id_member = $smcFunc['db_fetch_assoc']($request)['id_member'];
230
		$smcFunc['db_free_result']($request);
231
232
		// Let users see own unapproved attachments
233
		if ($id_member != $user_info['id'])
234
		{
235
			send_http_status(403, 'Forbidden');
236
			die('403 Forbidden');
0 ignored issues
show
Best Practice introduced by
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...
237
		}
238
	}
239
240
	// Replace the normal file with its thumbnail if it has one!
241
	if (!empty($showThumb) && !empty($thumbFile))
242
		$file = $thumbFile;
243
244
	// No point in a nicer message, because this is supposed to be an attachment anyway...
245
	if (empty($file['exists']))
246
	{
247
		send_http_status(404);
248
		header('content-type: text/plain; charset=' . (empty($context['character_set']) ? 'ISO-8859-1' : $context['character_set']));
249
250
		// We need to die like this *before* we send any anti-caching headers as below.
251
		die('File not found.');
252
	}
253
254
	// If it hasn't been modified since the last time this attachment was retrieved, there's no need to display it again.
255
	if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']))
256
	{
257
		list($modified_since) = explode(';', $_SERVER['HTTP_IF_MODIFIED_SINCE']);
258
		if (!empty($file['mtime']) && strtotime($modified_since) >= $file['mtime'])
259
		{
260
			ob_end_clean();
261
			header_remove('content-encoding');
262
263
			// Answer the question - no, it hasn't been modified ;).
264
			send_http_status(304);
265
			exit;
0 ignored issues
show
Best Practice introduced by
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...
266
		}
267
	}
268
269
	// Check whether the ETag was sent back, and cache based on that...
270
	if (!empty($file['etag']) && !empty($_SERVER['HTTP_IF_NONE_MATCH']) && strpos($_SERVER['HTTP_IF_NONE_MATCH'], $file['etag']) !== false)
271
	{
272
		ob_end_clean();
273
		header_remove('content-encoding');
274
275
		send_http_status(304);
276
		exit;
0 ignored issues
show
Best Practice introduced by
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...
277
	}
278
279
	// If this is a partial download, we need to determine what data range to send
280
	$range = 0;
281
	if (isset($_SERVER['HTTP_RANGE']))
282
	{
283
		list($a, $range) = explode("=", $_SERVER['HTTP_RANGE'], 2);
284
		list($range) = explode(",", $range, 2);
285
		list($range, $range_end) = explode("-", $range);
286
		$range = intval($range);
287
		$range_end = !$range_end ? $file['size'] - 1 : intval($range_end);
288
		$new_length = $range_end - $range + 1;
289
	}
290
291
	// Update the download counter (unless it's a thumbnail or resuming an incomplete download).
292
	if ($file['attachment_type'] != 3 && empty($showThumb) && $range === 0 && empty($context['skip_downloads_increment']))
293
		$smcFunc['db_query']('', '
294
			UPDATE {db_prefix}attachments
295
			SET downloads = downloads + 1
296
			WHERE id_attach = {int:id_attach}',
297
			array(
298
				'id_attach' => $attachId,
299
			)
300
		);
301
302
	// Send the attachment headers.
303
	header('pragma: ');
304
305
	if (!isBrowser('gecko'))
306
		header('content-transfer-encoding: binary');
307
308
	header('expires: ' . gmdate('D, d M Y H:i:s', time() + 525600 * 60) . ' GMT');
309
	header('last-modified: ' . gmdate('D, d M Y H:i:s', $file['mtime']) . ' GMT');
310
	header('accept-ranges: bytes');
311
	header('connection: close');
312
	header('etag: ' . $file['etag']);
313
314
	// Make sure the mime type warrants an inline display.
315
	if (isset($_REQUEST['image']) && !empty($file['mime_type']) && strpos($file['mime_type'], 'image/') !== 0)
316
		unset($_REQUEST['image']);
317
318
	// Does this have a mime type?
319
	elseif (!empty($file['mime_type']) && (isset($_REQUEST['image']) || !in_array($file['fileext'], array('jpg', 'gif', 'jpeg', 'x-ms-bmp', 'png', 'psd', 'tiff', 'iff'))))
320
		header('content-type: ' . strtr($file['mime_type'], array('image/bmp' => 'image/x-ms-bmp')));
321
322
	else
323
	{
324
		header('content-type: ' . (isBrowser('ie') || isBrowser('opera') ? 'application/octetstream' : 'application/octet-stream'));
325
		if (isset($_REQUEST['image']))
326
			unset($_REQUEST['image']);
327
	}
328
329
	// Convert the file to UTF-8, cuz most browsers dig that.
330
	$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']);
331
332
	if (!empty($context['prepend_attachment_id']))
333
		$utf8name = $_REQUEST['attach'] . ' - ' . $utf8name;
0 ignored issues
show
Bug introduced by
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

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