Passed
Push — release-2.1 ( 0bab99...d0ada2 )
by John
04:29 queued 13s
created

prepareAttachsByMsg()   B

Complexity

Conditions 10
Paths 16

Size

Total Lines 42
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 26
nc 16
nop 1
dl 0
loc 42
rs 7.6666
c 0
b 0
f 0

How to fix   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 the uploading and creation of attachments
5
 * as well as the auto management of the attachment directories.
6
 *
7
 * Simple Machines Forum (SMF)
8
 *
9
 * @package SMF
10
 * @author Simple Machines https://www.simplemachines.org
11
 * @copyright 2020 Simple Machines and individual contributors
12
 * @license https://www.simplemachines.org/about/smf/license.php BSD
13
 *
14
 * @version 2.1 RC3
15
 */
16
17
if (!defined('SMF'))
18
	die('No direct access...');
19
20
/**
21
 * Check if the current directory is still valid or not.
22
 * If not creates the new directory
23
 *
24
 * @return void|bool False if any error occurred
25
 */
26
function automanage_attachments_check_directory()
27
{
28
	global $smcFunc, $boarddir, $modSettings, $context;
29
30
	// Not pretty, but since we don't want folders created for every post. It'll do unless a better solution can be found.
31
	if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'admin')
32
		$doit = true;
33
	elseif (empty($modSettings['automanage_attachments']))
34
		return;
35
	elseif (!isset($_FILES))
36
		return;
37
	elseif (isset($_FILES['attachment']))
38
		foreach ($_FILES['attachment']['tmp_name'] as $dummy)
39
			if (!empty($dummy))
40
			{
41
				$doit = true;
42
				break;
43
			}
44
45
	if (!isset($doit))
46
		return;
47
48
	$year = date('Y');
49
	$month = date('m');
50
51
	$rand = md5(mt_rand());
52
	$rand1 = $rand[1];
53
	$rand = $rand[0];
54
55
	if (!empty($modSettings['attachment_basedirectories']) && !empty($modSettings['use_subdirectories_for_attachments']))
56
	{
57
		if (!is_array($modSettings['attachment_basedirectories']))
58
			$modSettings['attachment_basedirectories'] = $smcFunc['json_decode']($modSettings['attachment_basedirectories'], true);
59
		$base_dir = array_search($modSettings['basedirectory_for_attachments'], $modSettings['attachment_basedirectories']);
60
	}
61
	else
62
		$base_dir = 0;
63
64
	if ($modSettings['automanage_attachments'] == 1)
65
	{
66
		if (!isset($modSettings['last_attachments_directory']))
67
			$modSettings['last_attachments_directory'] = array();
68
		if (!is_array($modSettings['last_attachments_directory']))
69
			$modSettings['last_attachments_directory'] = $smcFunc['json_decode']($modSettings['last_attachments_directory'], true);
70
		if (!isset($modSettings['last_attachments_directory'][$base_dir]))
71
			$modSettings['last_attachments_directory'][$base_dir] = 0;
72
	}
73
74
	$basedirectory = (!empty($modSettings['use_subdirectories_for_attachments']) ? ($modSettings['basedirectory_for_attachments']) : $boarddir);
75
	//Just to be sure: I don't want directory separators at the end
76
	$sep = (DIRECTORY_SEPARATOR === '\\') ? '\/' : DIRECTORY_SEPARATOR;
77
	$basedirectory = rtrim($basedirectory, $sep);
78
79
	switch ($modSettings['automanage_attachments'])
80
	{
81
		case 1:
82
			$updir = $basedirectory . DIRECTORY_SEPARATOR . 'attachments_' . (isset($modSettings['last_attachments_directory'][$base_dir]) ? $modSettings['last_attachments_directory'][$base_dir] : 0);
83
			break;
84
		case 2:
85
			$updir = $basedirectory . DIRECTORY_SEPARATOR . $year;
86
			break;
87
		case 3:
88
			$updir = $basedirectory . DIRECTORY_SEPARATOR . $year . DIRECTORY_SEPARATOR . $month;
89
			break;
90
		case 4:
91
			$updir = $basedirectory . DIRECTORY_SEPARATOR . (empty($modSettings['use_subdirectories_for_attachments']) ? 'attachments-' : 'random_') . $rand;
92
			break;
93
		case 5:
94
			$updir = $basedirectory . DIRECTORY_SEPARATOR . (empty($modSettings['use_subdirectories_for_attachments']) ? 'attachments-' : 'random_') . $rand . DIRECTORY_SEPARATOR . $rand1;
95
			break;
96
		default :
97
			$updir = '';
98
	}
99
100
	if (!is_array($modSettings['attachmentUploadDir']))
101
		$modSettings['attachmentUploadDir'] = $smcFunc['json_decode']($modSettings['attachmentUploadDir'], true);
102
	if (!in_array($updir, $modSettings['attachmentUploadDir']) && !empty($updir))
103
		$outputCreation = automanage_attachments_create_directory($updir);
104
	elseif (in_array($updir, $modSettings['attachmentUploadDir']))
105
		$outputCreation = true;
106
107
	if ($outputCreation)
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $outputCreation does not seem to be defined for all execution paths leading up to this point.
Loading history...
108
	{
109
		$modSettings['currentAttachmentUploadDir'] = array_search($updir, $modSettings['attachmentUploadDir']);
110
		$context['attach_dir'] = $modSettings['attachmentUploadDir'][$modSettings['currentAttachmentUploadDir']];
111
112
		updateSettings(array(
113
			'currentAttachmentUploadDir' => $modSettings['currentAttachmentUploadDir'],
114
		));
115
	}
116
117
	return $outputCreation;
118
}
119
120
/**
121
 * Creates a directory
122
 *
123
 * @param string $updir The directory to be created
124
 *
125
 * @return bool False on errors
126
 */
127
function automanage_attachments_create_directory($updir)
128
{
129
	global $smcFunc, $modSettings, $context, $boarddir;
130
131
	$tree = get_directory_tree_elements($updir);
132
	$count = count($tree);
133
134
	$directory = attachments_init_dir($tree, $count);
135
	if ($directory === false)
136
	{
137
		// Maybe it's just the folder name
138
		$tree = get_directory_tree_elements($boarddir . DIRECTORY_SEPARATOR . $updir);
139
		$count = count($tree);
140
141
		$directory = attachments_init_dir($tree, $count);
142
		if ($directory === false)
143
			return false;
144
	}
145
146
	$directory .= DIRECTORY_SEPARATOR . array_shift($tree);
147
148
	while (!@is_dir($directory) || $count != -1)
149
	{
150
		if (!@is_dir($directory))
151
		{
152
			if (!@mkdir($directory, 0755))
153
			{
154
				$context['dir_creation_error'] = 'attachments_no_create';
155
				return false;
156
			}
157
		}
158
159
		$directory .= DIRECTORY_SEPARATOR . array_shift($tree);
160
		$count--;
161
	}
162
163
	// Check if the dir is writable.
164
	if (!smf_chmod($directory))
165
	{
166
		$context['dir_creation_error'] = 'attachments_no_write';
167
		return false;
168
	}
169
170
	// Everything seems fine...let's create the .htaccess
171
	if (!file_exists($directory . DIRECTORY_SEPARATOR . '.htaccess'))
172
		secureDirectory($updir, true);
173
174
	$sep = (DIRECTORY_SEPARATOR === '\\') ? '\/' : DIRECTORY_SEPARATOR;
175
	$updir = rtrim($updir, $sep);
176
177
	// Only update if it's a new directory
178
	if (!in_array($updir, $modSettings['attachmentUploadDir']))
179
	{
180
		$modSettings['currentAttachmentUploadDir'] = max(array_keys($modSettings['attachmentUploadDir'])) + 1;
181
		$modSettings['attachmentUploadDir'][$modSettings['currentAttachmentUploadDir']] = $updir;
182
183
		updateSettings(array(
184
			'attachmentUploadDir' => $smcFunc['json_encode']($modSettings['attachmentUploadDir']),
185
			'currentAttachmentUploadDir' => $modSettings['currentAttachmentUploadDir'],
186
		), true);
187
		$modSettings['attachmentUploadDir'] = $smcFunc['json_decode']($modSettings['attachmentUploadDir'], true);
188
	}
189
190
	$context['attach_dir'] = $modSettings['attachmentUploadDir'][$modSettings['currentAttachmentUploadDir']];
191
	return true;
192
}
193
194
/**
195
 * Called when a directory space limit is reached.
196
 * Creates a new directory and increments the directory suffix number.
197
 *
198
 * @return void|bool False on errors, true if successful, nothing if auto-management of attachments is disabled
199
 */
200
function automanage_attachments_by_space()
201
{
202
	global $smcFunc, $modSettings, $boarddir;
203
204
	if (!isset($modSettings['automanage_attachments']) || (!empty($modSettings['automanage_attachments']) && $modSettings['automanage_attachments'] != 1))
205
		return;
206
207
	$basedirectory = !empty($modSettings['use_subdirectories_for_attachments']) ? $modSettings['basedirectory_for_attachments'] : $boarddir;
208
	// Just to be sure: I don't want directory separators at the end
209
	$sep = (DIRECTORY_SEPARATOR === '\\') ? '\/' : DIRECTORY_SEPARATOR;
210
	$basedirectory = rtrim($basedirectory, $sep);
211
212
	// Get the current base directory
213
	if (!empty($modSettings['use_subdirectories_for_attachments']) && !empty($modSettings['attachment_basedirectories']))
214
	{
215
		$base_dir = array_search($modSettings['basedirectory_for_attachments'], $modSettings['attachment_basedirectories']);
216
		$base_dir = !empty($modSettings['automanage_attachments']) ? $base_dir : 0;
217
	}
218
	else
219
		$base_dir = 0;
220
221
	// Get the last attachment directory for that base directory
222
	if (empty($modSettings['last_attachments_directory'][$base_dir]))
223
		$modSettings['last_attachments_directory'][$base_dir] = 0;
224
	// And increment it.
225
	$modSettings['last_attachments_directory'][$base_dir]++;
226
227
	$updir = $basedirectory . DIRECTORY_SEPARATOR . 'attachments_' . $modSettings['last_attachments_directory'][$base_dir];
228
	if (automanage_attachments_create_directory($updir))
229
	{
230
		$modSettings['currentAttachmentUploadDir'] = array_search($updir, $modSettings['attachmentUploadDir']);
231
		updateSettings(array(
232
			'last_attachments_directory' => $smcFunc['json_encode']($modSettings['last_attachments_directory']),
233
			'currentAttachmentUploadDir' => $modSettings['currentAttachmentUploadDir'],
234
		));
235
		$modSettings['last_attachments_directory'] = $smcFunc['json_decode']($modSettings['last_attachments_directory'], true);
236
237
		return true;
238
	}
239
	else
240
		return false;
241
}
242
243
/**
244
 * Split a path into a list of all directories and subdirectories
245
 *
246
 * @param string $directory A path
247
 *
248
 * @return array|bool An array of all the directories and subdirectories or false on failure
249
 */
250
function get_directory_tree_elements($directory)
251
{
252
	/*
253
		In Windows server both \ and / can be used as directory separators in paths
254
		In Linux (and presumably *nix) servers \ can be part of the name
255
		So for this reasons:
256
			* in Windows we need to explode for both \ and /
257
			* while in linux should be safe to explode only for / (aka DIRECTORY_SEPARATOR)
258
	*/
259
	if (DIRECTORY_SEPARATOR === '\\')
260
		$tree = preg_split('#[\\\/]#', $directory);
261
	else
262
	{
263
		if (substr($directory, 0, 1) != DIRECTORY_SEPARATOR)
264
			return false;
265
266
		$tree = explode(DIRECTORY_SEPARATOR, trim($directory, DIRECTORY_SEPARATOR));
267
	}
268
	return $tree;
269
}
270
271
/**
272
 * Return the first part of a path (i.e. c:\ or / + the first directory), used by automanage_attachments_create_directory
273
 *
274
 * @param array $tree An array
275
 * @param int $count The number of elements in $tree
276
 *
277
 * @return string|bool The first part of the path or false on error
278
 */
279
function attachments_init_dir(&$tree, &$count)
280
{
281
	$directory = '';
282
	// If on Windows servers the first part of the path is the drive (e.g. "C:")
283
	if (DIRECTORY_SEPARATOR === '\\')
284
	{
285
		//Better be sure that the first part of the path is actually a drive letter...
286
		//...even if, I should check this in the admin page...isn't it?
287
		//...NHAAA Let's leave space for users' complains! :P
288
		if (preg_match('/^[a-z]:$/i', $tree[0]))
289
			$directory = array_shift($tree);
290
		else
291
			return false;
292
293
		$count--;
294
	}
295
	return $directory;
296
}
297
298
/**
299
 * Moves an attachment to the proper directory and set the relevant data into $_SESSION['temp_attachments']
300
 */
301
function processAttachments()
302
{
303
	global $context, $modSettings, $smcFunc, $txt, $user_info;
304
305
	// Make sure we're uploading to the right place.
306
	if (!empty($modSettings['automanage_attachments']))
307
		automanage_attachments_check_directory();
308
309
	if (!is_array($modSettings['attachmentUploadDir']))
310
		$modSettings['attachmentUploadDir'] = $smcFunc['json_decode']($modSettings['attachmentUploadDir'], true);
311
312
	$context['attach_dir'] = $modSettings['attachmentUploadDir'][$modSettings['currentAttachmentUploadDir']];
313
314
	// Is the attachments folder actualy there?
315
	if (!empty($context['dir_creation_error']))
316
		$initial_error = $context['dir_creation_error'];
317
	elseif (!is_dir($context['attach_dir']))
318
	{
319
		$initial_error = 'attach_folder_warning';
320
		log_error(sprintf($txt['attach_folder_admin_warning'], $context['attach_dir']), 'critical');
321
	}
322
323
	if (!isset($initial_error) && !isset($context['attachments']))
324
	{
325
		// If this isn't a new post, check the current attachments.
326
		if (isset($_REQUEST['msg']))
327
		{
328
			$request = $smcFunc['db_query']('', '
329
				SELECT COUNT(*), SUM(size)
330
				FROM {db_prefix}attachments
331
				WHERE id_msg = {int:id_msg}
332
					AND attachment_type = {int:attachment_type}',
333
				array(
334
					'id_msg' => (int) $_REQUEST['msg'],
335
					'attachment_type' => 0,
336
				)
337
			);
338
			list ($context['attachments']['quantity'], $context['attachments']['total_size']) = $smcFunc['db_fetch_row']($request);
339
			$smcFunc['db_free_result']($request);
340
		}
341
		else
342
			$context['attachments'] = array(
343
				'quantity' => 0,
344
				'total_size' => 0,
345
			);
346
	}
347
348
	// Hmm. There are still files in session.
349
	$ignore_temp = false;
350
	if (!empty($_SESSION['temp_attachments']['post']['files']) && count($_SESSION['temp_attachments']) > 1)
351
	{
352
		// Let's try to keep them. But...
353
		$ignore_temp = true;
354
		// If new files are being added. We can't ignore those
355
		foreach ($_FILES['attachment']['tmp_name'] as $dummy)
356
			if (!empty($dummy))
357
			{
358
				$ignore_temp = false;
359
				break;
360
			}
361
362
		// Need to make space for the new files. So, bye bye.
363
		if (!$ignore_temp)
364
		{
365
			foreach ($_SESSION['temp_attachments'] as $attachID => $attachment)
366
				if (strpos($attachID, 'post_tmp_' . $user_info['id']) !== false)
367
					unlink($attachment['tmp_name']);
368
369
			$context['we_are_history'] = $txt['error_temp_attachments_flushed'];
370
			$_SESSION['temp_attachments'] = array();
371
		}
372
	}
373
374
	if (!isset($_FILES['attachment']['name']))
375
		$_FILES['attachment']['tmp_name'] = array();
376
377
	if (!isset($_SESSION['temp_attachments']))
378
		$_SESSION['temp_attachments'] = array();
379
380
	// Remember where we are at. If it's anywhere at all.
381
	if (!$ignore_temp)
382
		$_SESSION['temp_attachments']['post'] = array(
383
			'msg' => !empty($_REQUEST['msg']) ? $_REQUEST['msg'] : 0,
384
			'last_msg' => !empty($_REQUEST['last_msg']) ? $_REQUEST['last_msg'] : 0,
385
			'topic' => !empty($topic) ? $topic : 0,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $topic seems to never exist and therefore empty should always be true.
Loading history...
386
			'board' => !empty($board) ? $board : 0,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $board seems to never exist and therefore empty should always be true.
Loading history...
387
		);
388
389
	// If we have an initial error, lets just display it.
390
	if (!empty($initial_error))
391
	{
392
		$_SESSION['temp_attachments']['initial_error'] = $initial_error;
393
394
		// And delete the files 'cos they ain't going nowhere.
395
		foreach ($_FILES['attachment']['tmp_name'] as $n => $dummy)
396
			if (file_exists($_FILES['attachment']['tmp_name'][$n]))
397
				unlink($_FILES['attachment']['tmp_name'][$n]);
398
399
		$_FILES['attachment']['tmp_name'] = array();
400
	}
401
402
	// Loop through $_FILES['attachment'] array and move each file to the current attachments folder.
403
	foreach ($_FILES['attachment']['tmp_name'] as $n => $dummy)
404
	{
405
		if ($_FILES['attachment']['name'][$n] == '')
406
			continue;
407
408
		// First, let's first check for PHP upload errors.
409
		$errors = array();
410
		if (!empty($_FILES['attachment']['error'][$n]))
411
		{
412
			if ($_FILES['attachment']['error'][$n] == 2)
413
				$errors[] = array('file_too_big', array($modSettings['attachmentSizeLimit']));
414
			elseif ($_FILES['attachment']['error'][$n] == 6)
415
				log_error($_FILES['attachment']['name'][$n] . ': ' . $txt['php_upload_error_6'], 'critical');
416
			else
417
				log_error($_FILES['attachment']['name'][$n] . ': ' . $txt['php_upload_error_' . $_FILES['attachment']['error'][$n]]);
418
			if (empty($errors))
419
				$errors[] = 'attach_php_error';
420
		}
421
422
		// Try to move and rename the file before doing any more checks on it.
423
		$attachID = 'post_tmp_' . $user_info['id'] . '_' . md5(mt_rand());
424
		$destName = $context['attach_dir'] . '/' . $attachID;
425
		if (empty($errors))
426
		{
427
			// The reported MIME type of the attachment might not be reliable.
428
			$detected_mime_type = get_mime_type($_FILES['attachment']['tmp_name'][$n], true);
0 ignored issues
show
Bug introduced by
true of type true is incompatible with the type string expected by parameter $is_path of get_mime_type(). ( Ignorable by Annotation )

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

428
			$detected_mime_type = get_mime_type($_FILES['attachment']['tmp_name'][$n], /** @scrutinizer ignore-type */ true);
Loading history...
429
			if ($detected_mime_type !== false)
430
				$_FILES['attachment']['type'][$n] = $detected_mime_type;
431
432
			$_SESSION['temp_attachments'][$attachID] = array(
433
				'name' => $smcFunc['htmlspecialchars'](basename($_FILES['attachment']['name'][$n])),
434
				'tmp_name' => $destName,
435
				'size' => $_FILES['attachment']['size'][$n],
436
				'type' => $_FILES['attachment']['type'][$n],
437
				'id_folder' => $modSettings['currentAttachmentUploadDir'],
438
				'errors' => array(),
439
			);
440
441
			// Move the file to the attachments folder with a temp name for now.
442
			if (@move_uploaded_file($_FILES['attachment']['tmp_name'][$n], $destName))
443
				smf_chmod($destName, 0644);
444
			else
445
			{
446
				$_SESSION['temp_attachments'][$attachID]['errors'][] = 'attach_timeout';
447
				if (file_exists($_FILES['attachment']['tmp_name'][$n]))
448
					unlink($_FILES['attachment']['tmp_name'][$n]);
449
			}
450
		}
451
		else
452
		{
453
			$_SESSION['temp_attachments'][$attachID] = array(
454
				'name' => $smcFunc['htmlspecialchars'](basename($_FILES['attachment']['name'][$n])),
455
				'tmp_name' => $destName,
456
				'errors' => $errors,
457
			);
458
459
			if (file_exists($_FILES['attachment']['tmp_name'][$n]))
460
				unlink($_FILES['attachment']['tmp_name'][$n]);
461
		}
462
		// If there's no errors to this point. We still do need to apply some additional checks before we are finished.
463
		if (empty($_SESSION['temp_attachments'][$attachID]['errors']))
464
			attachmentChecks($attachID);
0 ignored issues
show
Bug introduced by
$attachID of type string is incompatible with the type integer expected by parameter $attachID of attachmentChecks(). ( Ignorable by Annotation )

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

464
			attachmentChecks(/** @scrutinizer ignore-type */ $attachID);
Loading history...
465
	}
466
	// Mod authors, finally a hook to hang an alternate attachment upload system upon
467
	// Upload to the current attachment folder with the file name $attachID or 'post_tmp_' . $user_info['id'] . '_' . md5(mt_rand())
468
	// Populate $_SESSION['temp_attachments'][$attachID] with the following:
469
	//   name => The file name
470
	//   tmp_name => Path to the temp file ($context['attach_dir'] . '/' . $attachID).
471
	//   size => File size (required).
472
	//   type => MIME type (optional if not available on upload).
473
	//   id_folder => $modSettings['currentAttachmentUploadDir']
474
	//   errors => An array of errors (use the index of the $txt variable for that error).
475
	// Template changes can be done using "integrate_upload_template".
476
	call_integration_hook('integrate_attachment_upload', array());
477
}
478
479
/**
480
 * Performs various checks on an uploaded file.
481
 * - Requires that $_SESSION['temp_attachments'][$attachID] be properly populated.
482
 *
483
 * @param int $attachID The ID of the attachment
484
 * @return bool Whether the attachment is OK
485
 */
486
function attachmentChecks($attachID)
487
{
488
	global $modSettings, $context, $sourcedir, $smcFunc;
489
490
	// No data or missing data .... Not necessarily needed, but in case a mod author missed something.
491
	if (empty($_SESSION['temp_attachments'][$attachID]))
492
		$error = '$_SESSION[\'temp_attachments\'][$attachID]';
493
494
	elseif (empty($attachID))
495
		$error = '$attachID';
496
497
	elseif (empty($context['attachments']))
498
		$error = '$context[\'attachments\']';
499
500
	elseif (empty($context['attach_dir']))
501
		$error = '$context[\'attach_dir\']';
502
503
	// Let's get their attention.
504
	if (!empty($error))
505
		fatal_lang_error('attach_check_nag', 'debug', array($error));
506
507
	// Just in case this slipped by the first checks, we stop it here and now
508
	if ($_SESSION['temp_attachments'][$attachID]['size'] == 0)
509
	{
510
		$_SESSION['temp_attachments'][$attachID]['errors'][] = 'attach_0_byte_file';
511
		return false;
512
	}
513
514
	// First, the dreaded security check. Sorry folks, but this shouldn't be avoided.
515
	$size = @getimagesize($_SESSION['temp_attachments'][$attachID]['tmp_name']);
516
	if (is_array($size) && isset($size[2], $context['valid_image_types'][$size[2]]))
517
	{
518
		require_once($sourcedir . '/Subs-Graphics.php');
519
		if (!checkImageContents($_SESSION['temp_attachments'][$attachID]['tmp_name'], !empty($modSettings['attachment_image_paranoid'])))
520
		{
521
			// It's bad. Last chance, maybe we can re-encode it?
522
			if (empty($modSettings['attachment_image_reencode']) || (!reencodeImage($_SESSION['temp_attachments'][$attachID]['tmp_name'], $size[2])))
523
			{
524
				// Nothing to do: not allowed or not successful re-encoding it.
525
				$_SESSION['temp_attachments'][$attachID]['errors'][] = 'bad_attachment';
526
				return false;
527
			}
528
			// Success! However, successes usually come for a price:
529
			// we might get a new format for our image...
530
			$old_format = $size[2];
531
			$size = @getimagesize($_SESSION['temp_attachments'][$attachID]['tmp_name']);
532
			if (!(empty($size)) && ($size[2] != $old_format))
533
				$_SESSION['temp_attachments'][$attachID]['type'] = 'image/' . $context['valid_image_types'][$size[2]];
534
		}
535
	}
536
537
	// Is there room for this sucker?
538
	if (!empty($modSettings['attachmentDirSizeLimit']) || !empty($modSettings['attachmentDirFileLimit']))
539
	{
540
		// Check the folder size and count. If it hasn't been done already.
541
		if (empty($context['dir_size']) || empty($context['dir_files']))
542
		{
543
			$request = $smcFunc['db_query']('', '
544
				SELECT COUNT(*), SUM(size)
545
				FROM {db_prefix}attachments
546
				WHERE id_folder = {int:folder_id}
547
					AND attachment_type != {int:type}',
548
				array(
549
					'folder_id' => $modSettings['currentAttachmentUploadDir'],
550
					'type' => 1,
551
				)
552
			);
553
			list ($context['dir_files'], $context['dir_size']) = $smcFunc['db_fetch_row']($request);
554
			$smcFunc['db_free_result']($request);
555
		}
556
		$context['dir_size'] += $_SESSION['temp_attachments'][$attachID]['size'];
557
		$context['dir_files']++;
558
559
		// Are we about to run out of room? Let's notify the admin then.
560
		if (empty($modSettings['attachment_full_notified']) && !empty($modSettings['attachmentDirSizeLimit']) && $modSettings['attachmentDirSizeLimit'] > 4000 && $context['dir_size'] > ($modSettings['attachmentDirSizeLimit'] - 2000) * 1024
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: (empty($modSettings['att...entDirFileLimit'] > 500, Probably Intended Meaning: empty($modSettings['atta...ntDirFileLimit'] > 500)
Loading history...
561
			|| (!empty($modSettings['attachmentDirFileLimit']) && $modSettings['attachmentDirFileLimit'] * .95 < $context['dir_files'] && $modSettings['attachmentDirFileLimit'] > 500))
562
		{
563
			require_once($sourcedir . '/Subs-Admin.php');
564
			emailAdmins('admin_attachments_full');
565
			updateSettings(array('attachment_full_notified' => 1));
566
		}
567
568
		// // No room left.... What to do now???
569
		if (!empty($modSettings['attachmentDirFileLimit']) && $context['dir_files'] > $modSettings['attachmentDirFileLimit']
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: (! empty($modSettings['a...ntDirSizeLimit'] * 1024, Probably Intended Meaning: ! empty($modSettings['at...tDirSizeLimit'] * 1024)
Loading history...
570
			|| (!empty($modSettings['attachmentDirSizeLimit']) && $context['dir_size'] > $modSettings['attachmentDirSizeLimit'] * 1024))
571
		{
572
			if (!empty($modSettings['automanage_attachments']) && $modSettings['automanage_attachments'] == 1)
573
			{
574
				// Move it to the new folder if we can.
575
				if (automanage_attachments_by_space())
576
				{
577
					rename($_SESSION['temp_attachments'][$attachID]['tmp_name'], $context['attach_dir'] . '/' . $attachID);
578
					$_SESSION['temp_attachments'][$attachID]['tmp_name'] = $context['attach_dir'] . '/' . $attachID;
579
					$_SESSION['temp_attachments'][$attachID]['id_folder'] = $modSettings['currentAttachmentUploadDir'];
580
					$context['dir_size'] = 0;
581
					$context['dir_files'] = 0;
582
				}
583
				// Or, let the user know that it ain't gonna happen.
584
				else
585
				{
586
					if (isset($context['dir_creation_error']))
587
						$_SESSION['temp_attachments'][$attachID]['errors'][] = $context['dir_creation_error'];
588
					else
589
						$_SESSION['temp_attachments'][$attachID]['errors'][] = 'ran_out_of_space';
590
				}
591
			}
592
			else
593
				$_SESSION['temp_attachments'][$attachID]['errors'][] = 'ran_out_of_space';
594
		}
595
	}
596
597
	// Is the file too big?
598
	$context['attachments']['total_size'] += $_SESSION['temp_attachments'][$attachID]['size'];
599
	if (!empty($modSettings['attachmentSizeLimit']) && $_SESSION['temp_attachments'][$attachID]['size'] > $modSettings['attachmentSizeLimit'] * 1024)
600
		$_SESSION['temp_attachments'][$attachID]['errors'][] = array('file_too_big', array(comma_format($modSettings['attachmentSizeLimit'], 0)));
601
602
	// Check the total upload size for this post...
603
	if (!empty($modSettings['attachmentPostLimit']) && $context['attachments']['total_size'] > $modSettings['attachmentPostLimit'] * 1024)
604
		$_SESSION['temp_attachments'][$attachID]['errors'][] = array('attach_max_total_file_size', array(comma_format($modSettings['attachmentPostLimit'], 0), comma_format($modSettings['attachmentPostLimit'] - (($context['attachments']['total_size'] - $_SESSION['temp_attachments'][$attachID]['size']) / 1024), 0)));
605
606
	// Have we reached the maximum number of files we are allowed?
607
	$context['attachments']['quantity']++;
608
609
	// Set a max limit if none exists
610
	if (empty($modSettings['attachmentNumPerPostLimit']) && $context['attachments']['quantity'] >= 50)
611
		$modSettings['attachmentNumPerPostLimit'] = 50;
612
613
	if (!empty($modSettings['attachmentNumPerPostLimit']) && $context['attachments']['quantity'] > $modSettings['attachmentNumPerPostLimit'])
614
		$_SESSION['temp_attachments'][$attachID]['errors'][] = array('attachments_limit_per_post', array($modSettings['attachmentNumPerPostLimit']));
615
616
	// File extension check
617
	if (!empty($modSettings['attachmentCheckExtensions']))
618
	{
619
		$allowed = explode(',', strtolower($modSettings['attachmentExtensions']));
620
		foreach ($allowed as $k => $dummy)
621
			$allowed[$k] = trim($dummy);
622
623
		if (!in_array(strtolower(substr(strrchr($_SESSION['temp_attachments'][$attachID]['name'], '.'), 1)), $allowed))
624
		{
625
			$allowed_extensions = strtr(strtolower($modSettings['attachmentExtensions']), array(',' => ', '));
626
			$_SESSION['temp_attachments'][$attachID]['errors'][] = array('cant_upload_type', array($allowed_extensions));
627
		}
628
	}
629
630
	// Undo the math if there's an error
631
	if (!empty($_SESSION['temp_attachments'][$attachID]['errors']))
632
	{
633
		if (isset($context['dir_size']))
634
			$context['dir_size'] -= $_SESSION['temp_attachments'][$attachID]['size'];
635
		if (isset($context['dir_files']))
636
			$context['dir_files']--;
637
		$context['attachments']['total_size'] -= $_SESSION['temp_attachments'][$attachID]['size'];
638
		$context['attachments']['quantity']--;
639
		return false;
640
	}
641
642
	return true;
643
}
644
645
/**
646
 * Create an attachment, with the given array of parameters.
647
 * - Adds any additional or missing parameters to $attachmentOptions.
648
 * - Renames the temporary file.
649
 * - Creates a thumbnail if the file is an image and the option enabled.
650
 *
651
 * @param array $attachmentOptions An array of attachment options
652
 * @return bool Whether the attachment was created successfully
653
 */
654
function createAttachment(&$attachmentOptions)
655
{
656
	global $modSettings, $sourcedir, $smcFunc, $context, $txt;
657
658
	require_once($sourcedir . '/Subs-Graphics.php');
659
660
	// If this is an image we need to set a few additional parameters.
661
	$size = @getimagesize($attachmentOptions['tmp_name']);
662
	list ($attachmentOptions['width'], $attachmentOptions['height']) = $size;
663
664
	// If it's an image get the mime type right.
665
	if (empty($attachmentOptions['mime_type']) && $attachmentOptions['width'])
666
	{
667
		// Got a proper mime type?
668
		if (!empty($size['mime']))
669
			$attachmentOptions['mime_type'] = $size['mime'];
670
671
		// Otherwise a valid one?
672
		elseif (isset($context['valid_image_types'][$size[2]]))
673
			$attachmentOptions['mime_type'] = 'image/' . $context['valid_image_types'][$size[2]];
674
	}
675
676
	// It is possible we might have a MIME type that isn't actually an image but still have a size.
677
	// For example, Shockwave files will be able to return size but be 'application/shockwave' or similar.
678
	if (!empty($attachmentOptions['mime_type']) && strpos($attachmentOptions['mime_type'], 'image/') !== 0)
679
	{
680
		$attachmentOptions['width'] = 0;
681
		$attachmentOptions['height'] = 0;
682
	}
683
684
	// Get the hash if no hash has been given yet.
685
	if (empty($attachmentOptions['file_hash']))
686
		$attachmentOptions['file_hash'] = getAttachmentFilename($attachmentOptions['name'], false, null, true);
0 ignored issues
show
Bug introduced by
false of type false is incompatible with the type integer expected by parameter $attachment_id of getAttachmentFilename(). ( Ignorable by Annotation )

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

686
		$attachmentOptions['file_hash'] = getAttachmentFilename($attachmentOptions['name'], /** @scrutinizer ignore-type */ false, null, true);
Loading history...
687
688
	// Assuming no-one set the extension let's take a look at it.
689
	if (empty($attachmentOptions['fileext']))
690
	{
691
		$attachmentOptions['fileext'] = strtolower(strrpos($attachmentOptions['name'], '.') !== false ? substr($attachmentOptions['name'], strrpos($attachmentOptions['name'], '.') + 1) : '');
692
		if (strlen($attachmentOptions['fileext']) > 8 || '.' . $attachmentOptions['fileext'] == $attachmentOptions['name'])
693
			$attachmentOptions['fileext'] = '';
694
	}
695
696
	// This defines which options to use for which columns in the insert query.
697
	// Mods using the hook can add columns and even change the properties of existing columns,
698
	// but if they delete one of these columns, it will be reset to the default defined here.
699
	$attachmentStandardInserts = $attachmentInserts = array(
700
		// Format: 'column' => array('type', 'option')
701
		'id_folder' => array('int', 'id_folder'),
702
		'id_msg' => array('int', 'post'),
703
		'filename' => array('string-255', 'name'),
704
		'file_hash' => array('string-40', 'file_hash'),
705
		'fileext' => array('string-8', 'fileext'),
706
		'size' => array('int', 'size'),
707
		'width' => array('int', 'width'),
708
		'height' => array('int', 'height'),
709
		'mime_type' => array('string-20', 'mime_type'),
710
		'approved' => array('int', 'approved'),
711
	);
712
713
	// Last chance to change stuff!
714
	call_integration_hook('integrate_createAttachment', array(&$attachmentOptions, &$attachmentInserts));
715
716
	// Make sure the folder is valid...
717
	$tmp = is_array($modSettings['attachmentUploadDir']) ? $modSettings['attachmentUploadDir'] : $smcFunc['json_decode']($modSettings['attachmentUploadDir'], true);
718
	$folders = array_keys($tmp);
719
	if (empty($attachmentOptions['id_folder']) || !in_array($attachmentOptions['id_folder'], $folders))
720
		$attachmentOptions['id_folder'] = $modSettings['currentAttachmentUploadDir'];
721
722
	// Make sure all required columns are present, in case a mod screwed up.
723
	foreach ($attachmentStandardInserts as $column => $insert_info)
724
		if (!isset($attachmentInserts[$column]))
725
			$attachmentInserts[$column] = $insert_info;
726
727
	// Set up the columns and values to insert, in the correct order.
728
	$attachmentColumns = array();
729
	$attachmentValues = array();
730
	foreach ($attachmentInserts as $column => $insert_info)
731
	{
732
		$attachmentColumns[$column] = $insert_info[0];
733
734
		if (!empty($insert_info[0]) && $insert_info[0] == 'int')
735
			$attachmentValues[] = (int) $attachmentOptions[$insert_info[1]];
736
		else
737
			$attachmentValues[] = $attachmentOptions[$insert_info[1]];
738
	}
739
740
	// Create the attachment in the database.
741
	$attachmentOptions['id'] = $smcFunc['db_insert']('',
742
		'{db_prefix}attachments',
743
		$attachmentColumns,
744
		$attachmentValues,
745
		array('id_attach'),
746
		1
747
	);
748
749
	// Attachment couldn't be created.
750
	if (empty($attachmentOptions['id']))
751
	{
752
		loadLanguage('Errors');
753
		log_error($txt['attachment_not_created'], 'general');
754
		return false;
755
	}
756
757
	// Now that we have the attach id, let's rename this sucker and finish up.
758
	$attachmentOptions['destination'] = getAttachmentFilename(basename($attachmentOptions['name']), $attachmentOptions['id'], $attachmentOptions['id_folder'], false, $attachmentOptions['file_hash']);
759
	rename($attachmentOptions['tmp_name'], $attachmentOptions['destination']);
760
761
	// If it's not approved then add to the approval queue.
762
	if (!$attachmentOptions['approved'])
763
	{
764
		$smcFunc['db_insert']('',
765
			'{db_prefix}approval_queue',
766
			array(
767
				'id_attach' => 'int', 'id_msg' => 'int',
768
			),
769
			array(
770
				$attachmentOptions['id'], (int) $attachmentOptions['post'],
771
			),
772
			array()
773
		);
774
775
		// Queue background notification task.
776
		$smcFunc['db_insert'](
777
			'insert',
778
			'{db_prefix}background_tasks',
779
			array(
780
				'task_file' => 'string',
781
				'task_class' => 'string',
782
				'task_data' => 'string',
783
				'claimed_time' => 'int'
784
			),
785
			array(
786
					'$sourcedir/tasks/CreateAttachment-Notify.php',
787
					'CreateAttachment_Notify_Background',
788
					$smcFunc['json_encode'](
789
						array(
790
							'id' => $attachmentOptions['id'],
791
						)
792
					),
793
				0
794
			),
795
			array(
796
				'id_task'
797
			)
798
		);
799
	}
800
801
	if (empty($modSettings['attachmentThumbnails']) || (empty($attachmentOptions['width']) && empty($attachmentOptions['height'])))
802
		return true;
803
804
	// Like thumbnails, do we?
805
	if (!empty($modSettings['attachmentThumbWidth']) && !empty($modSettings['attachmentThumbHeight']) && ($attachmentOptions['width'] > $modSettings['attachmentThumbWidth'] || $attachmentOptions['height'] > $modSettings['attachmentThumbHeight']))
806
	{
807
		if (createThumbnail($attachmentOptions['destination'], $modSettings['attachmentThumbWidth'], $modSettings['attachmentThumbHeight']))
808
		{
809
			// Figure out how big we actually made it.
810
			$size = @getimagesize($attachmentOptions['destination'] . '_thumb');
811
			list ($thumb_width, $thumb_height) = $size;
812
813
			if (!empty($size['mime']))
814
				$thumb_mime = $size['mime'];
815
			elseif (isset($context['valid_image_types'][$size[2]]))
816
				$thumb_mime = 'image/' . $context['valid_image_types'][$size[2]];
817
			// Lord only knows how this happened...
818
			else
819
				$thumb_mime = '';
820
821
			$thumb_filename = $attachmentOptions['name'] . '_thumb';
822
			$thumb_size = filesize($attachmentOptions['destination'] . '_thumb');
823
			$thumb_file_hash = getAttachmentFilename($thumb_filename, false, null, true);
824
			$thumb_path = $attachmentOptions['destination'] . '_thumb';
825
826
			// We should check the file size and count here since thumbs are added to the existing totals.
827
			if (!empty($modSettings['automanage_attachments']) && $modSettings['automanage_attachments'] == 1 && !empty($modSettings['attachmentDirSizeLimit']) || !empty($modSettings['attachmentDirFileLimit']))
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: (! empty($modSettings['a...tachmentDirFileLimit']), Probably Intended Meaning: ! empty($modSettings['au...achmentDirFileLimit']))
Loading history...
828
			{
829
				$context['dir_size'] = isset($context['dir_size']) ? $context['dir_size'] += $thumb_size : $context['dir_size'] = 0;
830
				$context['dir_files'] = isset($context['dir_files']) ? $context['dir_files']++ : $context['dir_files'] = 0;
831
832
				// If the folder is full, try to create a new one and move the thumb to it.
833
				if ($context['dir_size'] > $modSettings['attachmentDirSizeLimit'] * 1024 || $context['dir_files'] + 2 > $modSettings['attachmentDirFileLimit'])
834
				{
835
					if (automanage_attachments_by_space())
836
					{
837
						rename($thumb_path, $context['attach_dir'] . '/' . $thumb_filename);
838
						$thumb_path = $context['attach_dir'] . '/' . $thumb_filename;
839
						$context['dir_size'] = 0;
840
						$context['dir_files'] = 0;
841
					}
842
				}
843
			}
844
			// If a new folder has been already created. Gotta move this thumb there then.
845
			if ($modSettings['currentAttachmentUploadDir'] != $attachmentOptions['id_folder'])
846
			{
847
				rename($thumb_path, $context['attach_dir'] . '/' . $thumb_filename);
848
				$thumb_path = $context['attach_dir'] . '/' . $thumb_filename;
849
			}
850
851
			// To the database we go!
852
			$attachmentOptions['thumb'] = $smcFunc['db_insert']('',
853
				'{db_prefix}attachments',
854
				array(
855
					'id_folder' => 'int', 'id_msg' => 'int', 'attachment_type' => 'int', 'filename' => 'string-255', 'file_hash' => 'string-40', 'fileext' => 'string-8',
856
					'size' => 'int', 'width' => 'int', 'height' => 'int', 'mime_type' => 'string-20', 'approved' => 'int',
857
				),
858
				array(
859
					$modSettings['currentAttachmentUploadDir'], (int) $attachmentOptions['post'], 3, $thumb_filename, $thumb_file_hash, $attachmentOptions['fileext'],
860
					$thumb_size, $thumb_width, $thumb_height, $thumb_mime, (int) $attachmentOptions['approved'],
861
				),
862
				array('id_attach'),
863
				1
864
			);
865
866
			if (!empty($attachmentOptions['thumb']))
867
			{
868
				$smcFunc['db_query']('', '
869
					UPDATE {db_prefix}attachments
870
					SET id_thumb = {int:id_thumb}
871
					WHERE id_attach = {int:id_attach}',
872
					array(
873
						'id_thumb' => $attachmentOptions['thumb'],
874
						'id_attach' => $attachmentOptions['id'],
875
					)
876
				);
877
878
				rename($thumb_path, getAttachmentFilename($thumb_filename, $attachmentOptions['thumb'], $modSettings['currentAttachmentUploadDir'], false, $thumb_file_hash));
879
			}
880
		}
881
	}
882
883
	return true;
884
}
885
886
/**
887
 * Assigns the given attachments to the given message ID.
888
 *
889
 * @param $attachIDs array of attachment IDs to assign.
890
 * @param $msgID integer the message ID.
891
 *
892
 * @return boolean false on error or missing params.
893
 */
894
function assignAttachments($attachIDs = array(), $msgID = 0)
895
{
896
	global $smcFunc;
897
898
	// Oh, come on!
899
	if (empty($attachIDs) || empty($msgID))
900
		return false;
901
902
	// "I see what is right and approve, but I do what is wrong."
903
	call_integration_hook('integrate_assign_attachments', array(&$attachIDs, &$msgID));
904
905
	// One last check
906
	if (empty($attachIDs))
907
		return false;
908
909
	// Perform.
910
	$smcFunc['db_query']('', '
911
		UPDATE {db_prefix}attachments
912
		SET id_msg = {int:id_msg}
913
		WHERE id_attach IN ({array_int:attach_ids})',
914
		array(
915
			'id_msg' => $msgID,
916
			'attach_ids' => $attachIDs,
917
		)
918
	);
919
920
	return true;
921
}
922
923
/**
924
 * Gets an attach ID and tries to load all its info.
925
 *
926
 * @param int $attachID the attachment ID to load info from.
927
 *
928
 * @return mixed If succesful, it will return an array of loaded data. String, most likely a $txt key if there was some error.
929
 */
930
function parseAttachBBC($attachID = 0)
931
{
932
	global $board, $modSettings, $context, $scripturl, $smcFunc, $user_info;
933
	static $view_attachment_boards;
934
935
	if (!isset($view_attachment_boards))
936
		$view_attachment_boards = boardsAllowedTo('view_attachments');
937
938
	// Meh...
939
	if (empty($attachID))
940
		return 'attachments_no_data_loaded';
941
942
	// Make it easy.
943
	$msgID = !empty($_REQUEST['msg']) ? (int) $_REQUEST['msg'] : 0;
944
945
	// Perhaps someone else wants to do the honors? Yes, this also includes dealing with previews ;)
946
	$externalParse = call_integration_hook('integrate_pre_parseAttachBBC', array($attachID, $msgID));
947
948
	// "I am innocent of the blood of this just person: see ye to it."
949
	if (!empty($externalParse) && (is_string($externalParse) || is_array($externalParse)))
950
		return $externalParse;
951
952
	// Are attachments enabled?
953
	if (empty($modSettings['attachmentEnable']))
954
		return 'attachments_not_enable';
955
956
	$check_board_perms = !isset($_SESSION['attachments_can_preview'][$attachID]) && $view_attachment_boards !== array(0);
957
958
	// There is always the chance someone else has already done our dirty work...
959
	// If so, all pertinent checks were already done. Hopefully...
960
	if (!empty($context['current_attachments']) && !empty($context['current_attachments'][$attachID]))
961
		return $context['current_attachments'][$attachID];
962
963
	// Can the user view attachments on this board?
964
	if ($check_board_perms && !empty($board) && !in_array($board, $view_attachment_boards))
965
		return 'attachments_not_allowed_to_see';
966
967
	// Get the message info associated with this particular attach ID.
968
	$attachInfo = getAttachMsgInfo($attachID);
969
970
	// There is always the chance this attachment no longer exists or isn't associated to a message anymore...
971
	if (empty($attachInfo) || empty($attachInfo['msg']) && empty($context['preview_message']))
972
		return 'attachments_no_msg_associated';
973
974
	// Can the user view attachments on the board that holds the attachment's original post?
975
	// (This matters when one post quotes another on a different board.)
976
	if ($check_board_perms && !in_array($attachInfo['board'], $view_attachment_boards))
977
		return 'attachments_not_allowed_to_see';
978
979
	if (empty($context['loaded_attachments'][$attachInfo['msg']]))
980
		prepareAttachsByMsg(array($attachInfo['msg']));
981
982
	if (isset($context['loaded_attachments'][$attachInfo['msg']][$attachID]))
983
		$attachContext = $context['loaded_attachments'][$attachInfo['msg']][$attachID];
984
985
	// In case the user manually typed the thumbnail's ID into the BBC
986
	elseif (!empty($context['loaded_attachments'][$attachInfo['msg']]))
987
	{
988
		foreach ($context['loaded_attachments'][$attachInfo['msg']] as $foundAttachID => $foundAttach)
989
		{
990
			if ($foundAttach['id_thumb'] == $attachID)
991
			{
992
				$attachContext = $context['loaded_attachments'][$attachInfo['msg']][$foundAttachID];
993
				$attachID = $foundAttachID;
994
				break;
995
			}
996
		}
997
	}
998
999
	// Load this particular attach's context.
1000
	if (!empty($attachContext))
1001
	{
1002
		// Skip unapproved attachment, unless they belong to the user or the user can approve them.
1003
		if (!$context['loaded_attachments'][$attachInfo['msg']][$attachID]['approved'] &&
1004
			$modSettings['postmod_active'] && !allowedTo('approve_posts') &&
1005
			$context['loaded_attachments'][$attachInfo['msg']][$attachID]['id_member'] != $user_info['id'])
1006
		{
1007
			unset($context['loaded_attachments'][$attachInfo['msg']][$attachID]);
1008
			return 'attachments_unapproved';
1009
		}
1010
		$attachLoaded = loadAttachmentContext($attachContext['id_msg'], $context['loaded_attachments']);
1011
	}
1012
	else
1013
		return 'attachments_no_data_loaded';
1014
1015
	if (empty($attachLoaded))
1016
		return 'attachments_no_data_loaded';
1017
1018
	else
1019
		$attachContext = $attachLoaded[$attachID];
1020
1021
	// It's theoretically possible that prepareAttachsByMsg() changed the board id, so check again.
1022
	if ($check_board_perms && !in_array($attachContext['board'], $view_attachment_boards))
1023
		return 'attachments_not_allowed_to_see';
1024
1025
	// Previewing much? No msg ID has been set yet.
1026
	if (!empty($context['preview_message']))
1027
	{
1028
		$attachContext['href'] = $scripturl . '?action=dlattach;attach=' . $attachID . ';type=preview';
1029
1030
		$attachContext['link'] = '<a href="' . $scripturl . '?action=dlattach;attach=' . $attachID . ';type=preview' . (empty($attachContext['is_image']) ? ';file' : '') . '" class="bbc_link">' . $smcFunc['htmlspecialchars']($attachContext['name']) . '</a>';
1031
1032
		// Fix the thumbnail too, if the image has one.
1033
		if (!empty($attachContext['thumbnail']) && !empty($attachContext['thumbnail']['has_thumb']))
1034
			$attachContext['thumbnail']['href'] = $scripturl . '?action=dlattach;attach=' . $attachContext['thumbnail']['id'] . ';image;type=preview';
1035
	}
1036
1037
	// You may or may not want to show this under the post.
1038
	if (!empty($modSettings['dont_show_attach_under_post']) && !isset($context['show_attach_under_post'][$attachID]))
1039
		$context['show_attach_under_post'][$attachID] = $attachID;
1040
1041
	// Last minute changes?
1042
	call_integration_hook('integrate_post_parseAttachBBC', array(&$attachContext));
1043
1044
	// Don't do any logic with the loaded data, leave it to whoever called this function.
1045
	return $attachContext;
1046
}
1047
1048
/**
1049
 * Gets raw info directly from the attachments table.
1050
 *
1051
 * @param array $attachIDs An array of attachments IDs.
1052
 *
1053
 * @return array.
0 ignored issues
show
Documentation Bug introduced by
The doc comment array. at position 0 could not be parsed: Unknown type name 'array.' at position 0 in array..
Loading history...
1054
 */
1055
function getRawAttachInfo($attachIDs)
1056
{
1057
	global $smcFunc, $modSettings;
1058
1059
	if (empty($attachIDs))
1060
		return array();
1061
1062
	$return = array();
1063
1064
	$request = $smcFunc['db_query']('', '
1065
		SELECT a.id_attach, a.id_msg, a.id_member, a.size, a.mime_type, a.id_folder, a.filename' . (empty($modSettings['attachmentShowImages']) || empty($modSettings['attachmentThumbnails']) ? '' : ',
1066
			COALESCE(thumb.id_attach, 0) AS id_thumb, thumb.width AS thumb_width, thumb.height AS thumb_height') . '
1067
		FROM {db_prefix}attachments AS a' . (empty($modSettings['attachmentShowImages']) || empty($modSettings['attachmentThumbnails']) ? '' : '
1068
			LEFT JOIN {db_prefix}attachments AS thumb ON (thumb.id_attach = a.id_thumb)') . '
1069
		WHERE a.id_attach IN ({array_int:attach_ids})
1070
		LIMIT 1',
1071
		array(
1072
			'attach_ids' => (array) $attachIDs,
1073
		)
1074
	);
1075
1076
	if ($smcFunc['db_num_rows']($request) != 1)
1077
		return array();
1078
1079
	while ($row = $smcFunc['db_fetch_assoc']($request))
1080
		$return[$row['id_attach']] = array(
1081
			'name' => $smcFunc['htmlspecialchars']($row['filename']),
1082
			'size' => $row['size'],
1083
			'attachID' => $row['id_attach'],
1084
			'unchecked' => false,
1085
			'approved' => 1,
1086
			'mime_type' => $row['mime_type'],
1087
			'thumb' => $row['id_thumb'],
1088
		);
1089
	$smcFunc['db_free_result']($request);
1090
1091
	return $return;
1092
}
1093
1094
/**
1095
 * Gets all needed message data associated with an attach ID
1096
 *
1097
 * @param int $attachID the attachment ID to load info from.
1098
 *
1099
 * @return array.
0 ignored issues
show
Documentation Bug introduced by
The doc comment array. at position 0 could not be parsed: Unknown type name 'array.' at position 0 in array..
Loading history...
1100
 */
1101
function getAttachMsgInfo($attachID)
1102
{
1103
	global $smcFunc, $context;
1104
1105
	if (empty($attachID))
1106
		return array();
1107
1108
	if (!isset($context['loaded_attachments']))
1109
		$context['loaded_attachments'] = array();
1110
1111
	foreach ($context['loaded_attachments'] as $msgRows)
1112
	{
1113
		if (empty($msgRows[$attachID]))
1114
			continue;
1115
1116
		$row = array(
1117
			'msg' => $msgRows[$attachID]['id_msg'],
1118
			'topic' => $msgRows[$attachID]['topic'],
1119
			'board' => $msgRows[$attachID]['board'],
1120
		);
1121
1122
		return $row;
1123
	}
1124
1125
	$request = $smcFunc['db_query']('', '
1126
		SELECT a.id_msg AS msg, m.id_topic AS topic, m.id_board AS board
1127
		FROM {db_prefix}attachments AS a
1128
			LEFT JOIN {db_prefix}messages AS m ON (m.id_msg = a.id_msg)
1129
		WHERE id_attach = {int:id_attach}
1130
		LIMIT 1',
1131
		array(
1132
			'id_attach' => (int) $attachID,
1133
		)
1134
	);
1135
1136
	if ($smcFunc['db_num_rows']($request) != 1)
1137
		return array();
1138
1139
	$row = $smcFunc['db_fetch_assoc']($request);
1140
	$smcFunc['db_free_result']($request);
1141
1142
	return $row;
1143
}
1144
1145
/**
1146
 * This loads an attachment's contextual data including, most importantly, its size if it is an image.
1147
 * It requires the view_attachments permission to calculate image size.
1148
 * It attempts to keep the "aspect ratio" of the posted image in line, even if it has to be resized by
1149
 * the max_image_width and max_image_height settings.
1150
 *
1151
 * @param int $id_msg ID of the post to load attachments for
1152
 * @param array $attachments  An array of already loaded attachments. This function no longer depends on having $topic declared, thus, you need to load the actual topic ID for each attachment.
1153
 * @return array An array of attachment info
1154
 */
1155
function loadAttachmentContext($id_msg, $attachments)
1156
{
1157
	global $modSettings, $txt, $scripturl, $sourcedir, $smcFunc, $context;
1158
1159
	if (empty($attachments) || empty($attachments[$id_msg]))
1160
		return array();
1161
1162
	// Set up the attachment info - based on code by Meriadoc.
1163
	$attachmentData = array();
1164
	$have_unapproved = false;
1165
	if (isset($attachments[$id_msg]) && !empty($modSettings['attachmentEnable']))
1166
	{
1167
		foreach ($attachments[$id_msg] as $i => $attachment)
1168
		{
1169
			$attachmentData[$i] = array(
1170
				'id' => $attachment['id_attach'],
1171
				'name' => preg_replace('~&amp;#(\\d{1,7}|x[0-9a-fA-F]{1,6});~', '&#\\1;', $smcFunc['htmlspecialchars']($attachment['filename'])),
1172
				'downloads' => $attachment['downloads'],
1173
				'size' => ($attachment['filesize'] < 1024000) ? round($attachment['filesize'] / 1024, 2) . ' ' . $txt['kilobyte'] : round($attachment['filesize'] / 1024 / 1024, 2) . ' ' . $txt['megabyte'],
1174
				'byte_size' => $attachment['filesize'],
1175
				'href' => $scripturl . '?action=dlattach;topic=' . $attachment['topic'] . '.0;attach=' . $attachment['id_attach'],
1176
				'link' => '<a href="' . $scripturl . '?action=dlattach;topic=' . $attachment['topic'] . '.0;attach=' . $attachment['id_attach'] . '" class="bbc_link">' . $smcFunc['htmlspecialchars']($attachment['filename']) . '</a>',
1177
				'is_image' => !empty($attachment['width']) && !empty($attachment['height']) && !empty($modSettings['attachmentShowImages']),
1178
				'is_approved' => $attachment['approved'],
1179
				'topic' => $attachment['topic'],
1180
				'board' => $attachment['board'],
1181
				'mime_type' => $attachment['mime_type'],
1182
			);
1183
1184
			// If something is unapproved we'll note it so we can sort them.
1185
			if (!$attachment['approved'])
1186
				$have_unapproved = true;
1187
1188
			if (!$attachmentData[$i]['is_image'])
1189
				continue;
1190
1191
			$attachmentData[$i]['real_width'] = $attachment['width'];
1192
			$attachmentData[$i]['width'] = $attachment['width'];
1193
			$attachmentData[$i]['real_height'] = $attachment['height'];
1194
			$attachmentData[$i]['height'] = $attachment['height'];
1195
1196
			// Let's see, do we want thumbs?
1197
			if (!empty($modSettings['attachmentThumbnails']) && !empty($modSettings['attachmentThumbWidth']) && !empty($modSettings['attachmentThumbHeight']) && ($attachment['width'] > $modSettings['attachmentThumbWidth'] || $attachment['height'] > $modSettings['attachmentThumbHeight']) && strlen($attachment['filename']) < 249)
1198
			{
1199
				// A proper thumb doesn't exist yet? Create one!
1200
				if (empty($attachment['id_thumb']) || $attachment['thumb_width'] > $modSettings['attachmentThumbWidth'] || $attachment['thumb_height'] > $modSettings['attachmentThumbHeight'] || ($attachment['thumb_width'] < $modSettings['attachmentThumbWidth'] && $attachment['thumb_height'] < $modSettings['attachmentThumbHeight']))
1201
				{
1202
					$filename = getAttachmentFilename($attachment['filename'], $attachment['id_attach'], $attachment['id_folder']);
1203
1204
					require_once($sourcedir . '/Subs-Graphics.php');
1205
					if (createThumbnail($filename, $modSettings['attachmentThumbWidth'], $modSettings['attachmentThumbHeight']))
1206
					{
1207
						// So what folder are we putting this image in?
1208
						if (!empty($modSettings['currentAttachmentUploadDir']))
1209
						{
1210
							if (!is_array($modSettings['attachmentUploadDir']))
1211
								$modSettings['attachmentUploadDir'] = $smcFunc['json_decode']($modSettings['attachmentUploadDir'], true);
1212
							$id_folder_thumb = $modSettings['currentAttachmentUploadDir'];
1213
						}
1214
						else
1215
						{
1216
							$id_folder_thumb = 1;
1217
						}
1218
1219
						// Calculate the size of the created thumbnail.
1220
						$size = @getimagesize($filename . '_thumb');
1221
						list ($attachment['thumb_width'], $attachment['thumb_height']) = $size;
1222
						$thumb_size = filesize($filename . '_thumb');
1223
1224
						// What about the extension?
1225
						$thumb_ext = isset($context['valid_image_types'][$size[2]]) ? $context['valid_image_types'][$size[2]] : '';
1226
1227
						// Figure out the mime type.
1228
						if (!empty($size['mime']))
1229
							$thumb_mime = $size['mime'];
1230
						else
1231
							$thumb_mime = 'image/' . $thumb_ext;
1232
1233
						$thumb_filename = $attachment['filename'] . '_thumb';
1234
						$thumb_hash = getAttachmentFilename($thumb_filename, false, null, true);
0 ignored issues
show
Bug introduced by
false of type false is incompatible with the type integer expected by parameter $attachment_id of getAttachmentFilename(). ( Ignorable by Annotation )

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

1234
						$thumb_hash = getAttachmentFilename($thumb_filename, /** @scrutinizer ignore-type */ false, null, true);
Loading history...
1235
						$old_id_thumb = $attachment['id_thumb'];
1236
1237
						// Add this beauty to the database.
1238
						$attachment['id_thumb'] = $smcFunc['db_insert']('',
1239
							'{db_prefix}attachments',
1240
							array('id_folder' => 'int', 'id_msg' => 'int', 'attachment_type' => 'int', 'filename' => 'string', 'file_hash' => 'string', 'size' => 'int', 'width' => 'int', 'height' => 'int', 'fileext' => 'string', 'mime_type' => 'string'),
1241
							array($id_folder_thumb, $id_msg, 3, $thumb_filename, $thumb_hash, (int) $thumb_size, (int) $attachment['thumb_width'], (int) $attachment['thumb_height'], $thumb_ext, $thumb_mime),
1242
							array('id_attach'),
1243
							1
1244
						);
1245
1246
						if (!empty($attachment['id_thumb']))
1247
						{
1248
							$smcFunc['db_query']('', '
1249
								UPDATE {db_prefix}attachments
1250
								SET id_thumb = {int:id_thumb}
1251
								WHERE id_attach = {int:id_attach}',
1252
								array(
1253
									'id_thumb' => $attachment['id_thumb'],
1254
									'id_attach' => $attachment['id_attach'],
1255
								)
1256
							);
1257
1258
							$thumb_realname = getAttachmentFilename($thumb_filename, $attachment['id_thumb'], $id_folder_thumb, false, $thumb_hash);
1259
							rename($filename . '_thumb', $thumb_realname);
1260
1261
							// Do we need to remove an old thumbnail?
1262
							if (!empty($old_id_thumb))
1263
							{
1264
								require_once($sourcedir . '/ManageAttachments.php');
1265
								removeAttachments(array('id_attach' => $old_id_thumb), '', false, false);
1266
							}
1267
						}
1268
					}
1269
				}
1270
1271
				// Only adjust dimensions on successful thumbnail creation.
1272
				if (!empty($attachment['thumb_width']) && !empty($attachment['thumb_height']))
1273
				{
1274
					$attachmentData[$i]['width'] = $attachment['thumb_width'];
1275
					$attachmentData[$i]['height'] = $attachment['thumb_height'];
1276
				}
1277
			}
1278
1279
			if (!empty($attachment['id_thumb']))
1280
				$attachmentData[$i]['thumbnail'] = array(
1281
					'id' => $attachment['id_thumb'],
1282
					'href' => $scripturl . '?action=dlattach;topic=' . $attachment['topic'] . '.0;attach=' . $attachment['id_thumb'] . ';image',
1283
				);
1284
			$attachmentData[$i]['thumbnail']['has_thumb'] = !empty($attachment['id_thumb']);
1285
1286
			// If thumbnails are disabled, check the maximum size of the image.
1287
			if (!$attachmentData[$i]['thumbnail']['has_thumb'] && ((!empty($modSettings['max_image_width']) && $attachment['width'] > $modSettings['max_image_width']) || (!empty($modSettings['max_image_height']) && $attachment['height'] > $modSettings['max_image_height'])))
1288
			{
1289
				if (!empty($modSettings['max_image_width']) && (empty($modSettings['max_image_height']) || $attachment['height'] * $modSettings['max_image_width'] / $attachment['width'] <= $modSettings['max_image_height']))
1290
				{
1291
					$attachmentData[$i]['width'] = $modSettings['max_image_width'];
1292
					$attachmentData[$i]['height'] = floor($attachment['height'] * $modSettings['max_image_width'] / $attachment['width']);
1293
				}
1294
				elseif (!empty($modSettings['max_image_width']))
1295
				{
1296
					$attachmentData[$i]['width'] = floor($attachment['width'] * $modSettings['max_image_height'] / $attachment['height']);
1297
					$attachmentData[$i]['height'] = $modSettings['max_image_height'];
1298
				}
1299
			}
1300
			elseif ($attachmentData[$i]['thumbnail']['has_thumb'])
1301
			{
1302
				// If the image is too large to show inline, make it a popup.
1303
				if (((!empty($modSettings['max_image_width']) && $attachmentData[$i]['real_width'] > $modSettings['max_image_width']) || (!empty($modSettings['max_image_height']) && $attachmentData[$i]['real_height'] > $modSettings['max_image_height'])))
1304
					$attachmentData[$i]['thumbnail']['javascript'] = 'return reqWin(\'' . $attachmentData[$i]['href'] . ';image\', ' . ($attachment['width'] + 20) . ', ' . ($attachment['height'] + 20) . ', true);';
1305
				else
1306
					$attachmentData[$i]['thumbnail']['javascript'] = 'return expandThumb(' . $attachment['id_attach'] . ');';
1307
			}
1308
1309
			if (!$attachmentData[$i]['thumbnail']['has_thumb'])
1310
				$attachmentData[$i]['downloads']++;
1311
		}
1312
	}
1313
1314
	// Do we need to instigate a sort?
1315
	if ($have_unapproved)
1316
		uasort($attachmentData, function($a, $b)
1317
		{
1318
			if ($a['is_approved'] == $b['is_approved'])
1319
				return 0;
1320
1321
			return $a['is_approved'] > $b['is_approved'] ? -1 : 1;
1322
		});
1323
1324
	return $attachmentData;
1325
}
1326
1327
/**
1328
 * prepare the Attachment api for all messages
1329
 *
1330
 * @param int array $msgIDs the message ID to load info from.
1331
 *
1332
 * @return void.
0 ignored issues
show
Documentation Bug introduced by
The doc comment void. at position 0 could not be parsed: Unknown type name 'void.' at position 0 in void..
Loading history...
1333
 */
1334
function prepareAttachsByMsg($msgIDs)
1335
{
1336
	global $context, $modSettings, $smcFunc;
1337
1338
	if (empty($context['loaded_attachments']))
1339
		$context['loaded_attachments'] = array();
1340
	// Remove all $msgIDs that we already processed
1341
	else
1342
		$msgIDs = array_diff($msgIDs, array_keys($context['loaded_attachments']), array(0));
1343
1344
	if (!empty($context['preview_message']))
1345
		$msgIDs[] = 0;
1346
1347
	if (!empty($msgIDs))
1348
	{
1349
		$request = $smcFunc['db_query']('', '
1350
			SELECT
1351
				a.id_attach, a.id_folder, a.id_msg, a.filename, a.file_hash, COALESCE(a.size, 0) AS filesize, a.downloads, a.approved, m.id_topic AS topic, m.id_board AS board, m.id_member, a.mime_type,
1352
				a.width, a.height' . (empty($modSettings['attachmentShowImages']) || empty($modSettings['attachmentThumbnails']) ? '' : ',
1353
				COALESCE(thumb.id_attach, 0) AS id_thumb, thumb.width AS thumb_width, thumb.height AS thumb_height') . '
1354
			FROM {db_prefix}attachments AS a' . (empty($modSettings['attachmentShowImages']) || empty($modSettings['attachmentThumbnails']) ? '' : '
1355
				LEFT JOIN {db_prefix}attachments AS thumb ON (thumb.id_attach = a.id_thumb)') . '
1356
				LEFT JOIN {db_prefix}messages AS m ON (m.id_msg = a.id_msg)
1357
			WHERE a.attachment_type = {int:attachment_type}
1358
				AND a.id_msg IN ({array_int:message_id})',
1359
			array(
1360
				'message_id' => $msgIDs,
1361
				'attachment_type' => 0,
1362
			)
1363
		);
1364
		$rows = $smcFunc['db_fetch_all']($request);
1365
		$smcFunc['db_free_result']($request);
1366
1367
		foreach ($rows as $row)
1368
		{
1369
			if (empty($context['loaded_attachments'][$row['id_msg']]))
1370
				$context['loaded_attachments'][$row['id_msg']] = array();
1371
1372
			$context['loaded_attachments'][$row['id_msg']][$row['id_attach']] = $row;
1373
1374
			// This is better than sorting it with the query...
1375
			ksort($context['loaded_attachments'][$row['id_msg']]);
1376
		}
1377
	}
1378
}
1379
1380
?>