Passed
Push — release-2.1 ( 0c2197...207d2d )
by Jeremy
05:47
created

ManageAttachments.php ➔ BrowseFiles()   F

Complexity

Conditions 26
Paths > 20000

Size

Total Lines 205

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 26
nc 20480
nop 0
dl 0
loc 205
rs 0
c 0
b 0
f 0

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 doing the job of attachments and avatars maintenance and management.
5
 * @todo refactor as controller-model
6
 *
7
 * Simple Machines Forum (SMF)
8
 *
9
 * @package SMF
10
 * @author Simple Machines http://www.simplemachines.org
11
 * @copyright 2018 Simple Machines and individual contributors
12
 * @license http://www.simplemachines.org/about/smf/license.php BSD
13
 *
14
 * @version 2.1 Beta 4
15
 */
16
17
if (!defined('SMF'))
18
	die('No direct access...');
19
20
/**
21
 * The main 'Attachments and Avatars' management function.
22
 * This function is the entry point for index.php?action=admin;area=manageattachments
23
 * and it calls a function based on the sub-action.
24
 * It requires the manage_attachments permission.
25
 *
26
 * @uses ManageAttachments template.
27
 * @uses Admin language file.
28
 * @uses template layer 'manage_files' for showing the tab bar.
29
 *
30
 */
31
function ManageAttachments()
32
{
33
	global $txt, $context;
34
35
	// You have to be able to moderate the forum to do this.
36
	isAllowedTo('manage_attachments');
37
38
	// Setup the template stuff we'll probably need.
39
	loadTemplate('ManageAttachments');
40
41
	// If they want to delete attachment(s), delete them. (otherwise fall through..)
42
	$subActions = array(
43
		'attachments' => 'ManageAttachmentSettings',
44
		'attachpaths' => 'ManageAttachmentPaths',
45
		'avatars' => 'ManageAvatarSettings',
46
		'browse' => 'BrowseFiles',
47
		'byAge' => 'RemoveAttachmentByAge',
48
		'bySize' => 'RemoveAttachmentBySize',
49
		'maintenance' => 'MaintainFiles',
50
		'repair' => 'RepairAttachments',
51
		'remove' => 'RemoveAttachment',
52
		'removeall' => 'RemoveAllAttachments',
53
		'transfer' => 'TransferAttachments',
54
	);
55
56
	// This uses admin tabs - as it should!
57
	$context[$context['admin_menu_name']]['tab_data'] = array(
58
		'title' => $txt['attachments_avatars'],
59
		'help' => 'manage_files',
60
		'description' => $txt['attachments_desc'],
61
	);
62
63
	call_integration_hook('integrate_manage_attachments', array(&$subActions));
64
65
	// Pick the correct sub-action.
66
	if (isset($_REQUEST['sa']) && isset($subActions[$_REQUEST['sa']]))
67
		$context['sub_action'] = $_REQUEST['sa'];
68
	else
69
		$context['sub_action'] = 'browse';
70
71
	// Default page title is good.
72
	$context['page_title'] = $txt['attachments_avatars'];
73
74
	// Finally fall through to what we are doing.
75
	call_helper($subActions[$context['sub_action']]);
76
}
77
78
/**
79
 * Allows to show/change attachment settings.
80
 * This is the default sub-action of the 'Attachments and Avatars' center.
81
 * Called by index.php?action=admin;area=manageattachments;sa=attachments.
82
 *
83
 * @param bool $return_config Whether to return the array of config variables (used for admin search)
84
 * @return void|array If $return_config is true, simply returns the config_vars array, otherwise returns nothing
85
 * @uses 'attachments' sub template.
86
 */
87
88
function ManageAttachmentSettings($return_config = false)
89
{
90
	global $smcFunc, $txt, $modSettings, $scripturl, $context, $sourcedir, $boarddir;
91
92
	require_once($sourcedir . '/Subs-Attachments.php');
93
94
	$context['attachmentUploadDir'] = $modSettings['attachmentUploadDir'][$modSettings['currentAttachmentUploadDir']];
95
96
	// If not set, show a default path for the base directory
97
	if (!isset($_GET['save']) && empty($modSettings['basedirectory_for_attachments']))
98
		if (is_dir($modSettings['attachmentUploadDir'][1]))
99
			$modSettings['basedirectory_for_attachments'] = $modSettings['attachmentUploadDir'][1];
100
101
	else
102
		$modSettings['basedirectory_for_attachments'] = $context['attachmentUploadDir'];
103
104
	$context['valid_upload_dir'] = is_dir($context['attachmentUploadDir']) && is_writable($context['attachmentUploadDir']);
105
106
	if (!empty($modSettings['automanage_attachments']))
107
		$context['valid_basedirectory'] = !empty($modSettings['basedirectory_for_attachments']) && is_writable($modSettings['basedirectory_for_attachments']);
108
109
	else
110
		$context['valid_basedirectory'] = true;
111
112
	// A bit of razzle dazzle with the $txt strings. :)
113
	$txt['attachment_path'] = $context['attachmentUploadDir'];
114
	$txt['basedirectory_for_attachments_path'] = isset($modSettings['basedirectory_for_attachments']) ? $modSettings['basedirectory_for_attachments'] : '';
115
	$txt['use_subdirectories_for_attachments_note'] = empty($modSettings['attachment_basedirectories']) || empty($modSettings['use_subdirectories_for_attachments']) ? $txt['use_subdirectories_for_attachments_note'] : '';
116
	$txt['attachmentUploadDir_multiple_configure'] = '<a href="' . $scripturl . '?action=admin;area=manageattachments;sa=attachpaths">[' . $txt['attachmentUploadDir_multiple_configure'] . ']</a>';
117
	$txt['attach_current_dir'] = empty($modSettings['automanage_attachments']) ? $txt['attach_current_dir'] : $txt['attach_last_dir'];
118
	$txt['attach_current_dir_warning'] = $txt['attach_current_dir'] . $txt['attach_current_dir_warning'];
119
	$txt['basedirectory_for_attachments_warning'] = $txt['basedirectory_for_attachments_current'] . $txt['basedirectory_for_attachments_warning'];
120
121
	// Perform a test to see if the GD module or ImageMagick are installed.
122
	$testImg = get_extension_funcs('gd') || class_exists('Imagick') || get_extension_funcs('MagickWand');
123
124
	// See if we can find if the server is set up to support the attachment limits
125
	$post_max_size = ini_get('post_max_size');
126
	$upload_max_filesize = ini_get('upload_max_filesize');
127
	$testPM = !empty($post_max_size) ? (memoryReturnBytes($post_max_size) >= (isset($modSettings['attachmentPostLimit']) ? $modSettings['attachmentPostLimit'] * 1024 : 0)) : true;
128
	$testUM = !empty($upload_max_filesize) ? (memoryReturnBytes($upload_max_filesize) >= (isset($modSettings['attachmentSizeLimit']) ? $modSettings['attachmentSizeLimit'] * 1024 : 0)) : true;
129
130
	$config_vars = array(
131
		array('title', 'attachment_manager_settings'),
132
			// Are attachments enabled?
133
			array('select', 'attachmentEnable', array($txt['attachmentEnable_deactivate'], $txt['attachmentEnable_enable_all'], $txt['attachmentEnable_disable_new'])),
134
		'',
135
			// Directory and size limits.
136
			array('select', 'automanage_attachments', array(0 => $txt['attachments_normal'], 1 => $txt['attachments_auto_space'], 2 => $txt['attachments_auto_years'], 3 => $txt['attachments_auto_months'], 4 => $txt['attachments_auto_16'])),
137
			array('check', 'use_subdirectories_for_attachments', 'subtext' => $txt['use_subdirectories_for_attachments_note']),
138
			(empty($modSettings['attachment_basedirectories']) ? array('text', 'basedirectory_for_attachments', 40,) : array('var_message', 'basedirectory_for_attachments', 'message' => 'basedirectory_for_attachments_path', 'invalid' => empty($context['valid_basedirectory']), 'text_label' => (!empty($context['valid_basedirectory']) ? $txt['basedirectory_for_attachments_current'] : $txt['basedirectory_for_attachments_warning']))),
139
			empty($modSettings['attachment_basedirectories']) && $modSettings['currentAttachmentUploadDir'] == 1 && count($modSettings['attachmentUploadDir']) == 1 ? array('json', 'attachmentUploadDir', 'subtext' => $txt['attachmentUploadDir_multiple_configure'], 40, 'invalid' => !$context['valid_upload_dir'], 'disabled' => true) : array('var_message', 'attach_current_directory', 'subtext' => $txt['attachmentUploadDir_multiple_configure'], 'message' => 'attachment_path', 'invalid' => empty($context['valid_upload_dir']), 'text_label' => (!empty($context['valid_upload_dir']) ? $txt['attach_current_dir'] : $txt['attach_current_dir_warning'])),
140
			array('int', 'attachmentDirFileLimit', 'subtext' => $txt['zero_for_no_limit'], 6),
141
			array('int', 'attachmentDirSizeLimit', 'subtext' => $txt['zero_for_no_limit'], 6, 'postinput' => $txt['kilobyte']),
142
			array('check', 'dont_show_attach_under_post', 'subtext' => $txt['dont_show_attach_under_post_sub']),
143
		'',
144
			// Posting limits
145
			array('int', 'attachmentPostLimit', 'subtext' => $txt['zero_for_no_limit'], 6, 'postinput' => $txt['kilobyte']),
146
			array('warning', empty($testPM) ? 'attachment_postsize_warning' : ''),
147
			array('int', 'attachmentSizeLimit', 'subtext' => $txt['zero_for_no_limit'], 6, 'postinput' => $txt['kilobyte']),
148
			array('warning', empty($testUM) ? 'attachment_filesize_warning' : ''),
149
			array('int', 'attachmentNumPerPostLimit', 'subtext' => $txt['zero_for_no_limit'], 6),
150
			// Security Items
151
		array('title', 'attachment_security_settings'),
152
			// Extension checks etc.
153
			array('check', 'attachmentCheckExtensions'),
154
			array('text', 'attachmentExtensions', 40),
155
		'',
156
			// Image checks.
157
			array('warning', empty($testImg) ? 'attachment_img_enc_warning' : ''),
158
			array('check', 'attachment_image_reencode'),
159
		'',
160
			array('warning', 'attachment_image_paranoid_warning'),
161
			array('check', 'attachment_image_paranoid'),
162
			// Thumbnail settings.
163
		array('title', 'attachment_thumbnail_settings'),
164
			array('check', 'attachmentShowImages'),
165
			array('check', 'attachmentThumbnails'),
166
			array('check', 'attachment_thumb_png'),
167
			array('check', 'attachment_thumb_memory'),
168
			array('warning', 'attachment_thumb_memory_note'),
169
			array('text', 'attachmentThumbWidth', 6),
170
			array('text', 'attachmentThumbHeight', 6),
171
		'',
172
			array('int', 'max_image_width', 'subtext' => $txt['zero_for_no_limit']),
173
			array('int', 'max_image_height', 'subtext' => $txt['zero_for_no_limit']),
174
	);
175
176
	$context['settings_post_javascript'] = '
177
	var storing_type = document.getElementById(\'automanage_attachments\');
178
	var base_dir = document.getElementById(\'use_subdirectories_for_attachments\');
179
180
	createEventListener(storing_type)
181
	storing_type.addEventListener("change", toggleSubDir, false);
182
	createEventListener(base_dir)
183
	base_dir.addEventListener("change", toggleSubDir, false);
184
	toggleSubDir();';
185
186
	call_integration_hook('integrate_modify_attachment_settings', array(&$config_vars));
187
188
	if ($return_config)
189
		return $config_vars;
190
191
	// These are very likely to come in handy! (i.e. without them we're doomed!)
192
	require_once($sourcedir . '/ManagePermissions.php');
193
	require_once($sourcedir . '/ManageServer.php');
194
195
	// Saving settings?
196
	if (isset($_GET['save']))
197
	{
198
		checkSession();
199
200
		if (isset($_POST['attachmentUploadDir']))
201
			unset($_POST['attachmentUploadDir']);
202
203
		if (!empty($_POST['use_subdirectories_for_attachments']))
204
		{
205
			if (isset($_POST['use_subdirectories_for_attachments']) && empty($_POST['basedirectory_for_attachments']))
206
				$_POST['basedirectory_for_attachments'] = (!empty($modSettings['basedirectory_for_attachments']) ? ($modSettings['basedirectory_for_attachments']) : $boarddir);
207
208
			if (!empty($_POST['use_subdirectories_for_attachments']) && !empty($modSettings['attachment_basedirectories']))
209
			{
210
				if (!is_array($modSettings['attachment_basedirectories']))
211
					$modSettings['attachment_basedirectories'] = $smcFunc['json_decode']($modSettings['attachment_basedirectories'], true);
212
			}
213
			else
214
				$modSettings['attachment_basedirectories'] = array();
215
216
			if (!empty($_POST['use_subdirectories_for_attachments']) && !empty($_POST['basedirectory_for_attachments']) && !in_array($_POST['basedirectory_for_attachments'], $modSettings['attachment_basedirectories']))
217
			{
218
				$currentAttachmentUploadDir = $modSettings['currentAttachmentUploadDir'];
219
220
				if (!in_array($_POST['basedirectory_for_attachments'], $modSettings['attachmentUploadDir']))
221
				{
222
					if (!automanage_attachments_create_directory($_POST['basedirectory_for_attachments']))
223
						$_POST['basedirectory_for_attachments'] = $modSettings['basedirectory_for_attachments'];
224
				}
225
226
				if (!in_array($_POST['basedirectory_for_attachments'], $modSettings['attachment_basedirectories']))
227
				{
228
					$modSettings['attachment_basedirectories'][$modSettings['currentAttachmentUploadDir']] = $_POST['basedirectory_for_attachments'];
229
					updateSettings(array(
230
						'attachment_basedirectories' => $smcFunc['json_encode']($modSettings['attachment_basedirectories']),
231
						'currentAttachmentUploadDir' => $currentAttachmentUploadDir,
232
					));
233
234
					$_POST['use_subdirectories_for_attachments'] = 1;
235
					$_POST['attachmentUploadDir'] = $smcFunc['json_encode']($modSettings['attachmentUploadDir']);
236
				}
237
			}
238
		}
239
240
		call_integration_hook('integrate_save_attachment_settings');
241
242
		saveDBSettings($config_vars);
243
		$_SESSION['adm-save'] = true;
244
		redirectexit('action=admin;area=manageattachments;sa=attachments');
245
	}
246
247
	$context['post_url'] = $scripturl . '?action=admin;area=manageattachments;save;sa=attachments';
248
	prepareDBSettingContext($config_vars);
249
250
	$context['sub_template'] = 'show_settings';
251
}
252
253
/**
254
 * This allows to show/change avatar settings.
255
 * Called by index.php?action=admin;area=manageattachments;sa=avatars.
256
 * Show/set permissions for permissions: 'profile_server_avatar',
257
 * 	'profile_upload_avatar' and 'profile_remote_avatar'.
258
 *
259
 * @param bool $return_config Whether to return the config_vars array (used for admin search)
260
 * @return void|array Returns the config_vars array if $return_config is true, otherwise returns nothing
261
 * @uses 'avatars' sub template.
262
 */
263
function ManageAvatarSettings($return_config = false)
264
{
265
	global $txt, $context, $modSettings, $sourcedir, $scripturl;
266
	global $boarddir, $boardurl;
267
268
	// Perform a test to see if the GD module or ImageMagick are installed.
269
	$testImg = get_extension_funcs('gd') || class_exists('Imagick');
270
271
	$context['valid_avatar_dir'] = is_dir($modSettings['avatar_directory']);
272
	$context['valid_custom_avatar_dir'] = !empty($modSettings['custom_avatar_dir']) && is_dir($modSettings['custom_avatar_dir']) && is_writable($modSettings['custom_avatar_dir']);
273
274
	$config_vars = array(
275
		// Server stored avatars!
276
		array('title', 'avatar_server_stored'),
277
			array('warning', empty($testImg) ? 'avatar_img_enc_warning' : ''),
278
			array('permissions', 'profile_server_avatar', 0, $txt['avatar_server_stored_groups']),
279
			array('warning', !$context['valid_avatar_dir'] ? 'avatar_directory_wrong' : ''),
280
			array('text', 'avatar_directory', 40, 'invalid' => !$context['valid_avatar_dir']),
281
			array('text', 'avatar_url', 40),
282
		// External avatars?
283
		array('title', 'avatar_external'),
284
			array('permissions', 'profile_remote_avatar', 0, $txt['avatar_external_url_groups']),
285
			array('check', 'avatar_download_external', 0, 'onchange' => 'fUpdateStatus();'),
286
			array('text', 'avatar_max_width_external', 'subtext' => $txt['zero_for_no_limit'], 6),
287
			array('text', 'avatar_max_height_external', 'subtext' => $txt['zero_for_no_limit'], 6),
288
			array('select', 'avatar_action_too_large',
289
				array(
290
					'option_refuse' => $txt['option_refuse'],
291
					'option_css_resize' => $txt['option_css_resize'],
292
					'option_download_and_resize' => $txt['option_download_and_resize'],
293
				),
294
			),
295
		// Uploadable avatars?
296
		array('title', 'avatar_upload'),
297
			array('permissions', 'profile_upload_avatar', 0, $txt['avatar_upload_groups']),
298
			array('text', 'avatar_max_width_upload', 'subtext' => $txt['zero_for_no_limit'], 6),
299
			array('text', 'avatar_max_height_upload', 'subtext' => $txt['zero_for_no_limit'], 6),
300
			array('check', 'avatar_resize_upload', 'subtext' => $txt['avatar_resize_upload_note']),
301
			array('check', 'avatar_download_png'),
302
			array('check', 'avatar_reencode'),
303
		'',
304
			array('warning', 'avatar_paranoid_warning'),
305
			array('check', 'avatar_paranoid'),
306
		'',
307
			array('warning', !$context['valid_custom_avatar_dir'] ? 'custom_avatar_dir_wrong' : ''),
308
			array('text', 'custom_avatar_dir', 40, 'subtext' => $txt['custom_avatar_dir_desc'], 'invalid' => !$context['valid_custom_avatar_dir']),
309
			array('text', 'custom_avatar_url', 40),
310
		// Grvatars?
311
		array('title', 'gravatar_settings'),
312
			array('check', 'gravatarEnabled'),
313
			array('check', 'gravatarOverride'),
314
			array('check', 'gravatarAllowExtraEmail'),
315
		'',
316
			array('select', 'gravatarMaxRating',
317
				array(
318
					'G' => $txt['gravatar_maxG'],
319
					'PG' => $txt['gravatar_maxPG'],
320
					'R' => $txt['gravatar_maxR'],
321
					'X' => $txt['gravatar_maxX'],
322
				),
323
			),
324
			array('select', 'gravatarDefault',
325
				array(
326
					'mm' => $txt['gravatar_mm'],
327
					'identicon' => $txt['gravatar_identicon'],
328
					'monsterid' => $txt['gravatar_monsterid'],
329
					'wavatar' => $txt['gravatar_wavatar'],
330
					'retro' => $txt['gravatar_retro'],
331
					'blank' => $txt['gravatar_blank'],
332
				),
333
			),
334
	);
335
336
	call_integration_hook('integrate_modify_avatar_settings', array(&$config_vars));
337
338
	if ($return_config)
339
		return $config_vars;
340
341
	// We need this file for the settings template.
342
	require_once($sourcedir . '/ManageServer.php');
343
344
	// Saving avatar settings?
345
	if (isset($_GET['save']))
346
	{
347
		checkSession();
348
349
		// These settings cannot be left empty!
350
		if (empty($_POST['custom_avatar_dir']))
351
			$_POST['custom_avatar_dir'] = $boarddir . '/custom_avatar';
352
353
		if (empty($_POST['custom_avatar_url']))
354
			$_POST['custom_avatar_url'] = $boardurl . '/custom_avatar';
355
356
		if (empty($_POST['avatar_directory']))
357
			$_POST['avatar_directory'] = $boarddir . '/avatars';
358
359
		if (empty($_POST['avatar_url']))
360
			$_POST['avatar_url'] = $boardurl . '/avatars';
361
362
		call_integration_hook('integrate_save_avatar_settings');
363
364
		saveDBSettings($config_vars);
365
		$_SESSION['adm-save'] = true;
366
		redirectexit('action=admin;area=manageattachments;sa=avatars');
367
	}
368
369
	// Attempt to figure out if the admin is trying to break things.
370
	$context['settings_save_onclick'] = 'return (document.getElementById(\'custom_avatar_dir\').value == \'\' || document.getElementById(\'custom_avatar_url\').value == \'\') ? confirm(\'' . $txt['custom_avatar_check_empty'] . '\') : true;';
371
372
	// We need this for the in-line permissions
373
	createToken('admin-mp');
374
375
	// Prepare the context.
376
	$context['post_url'] = $scripturl . '?action=admin;area=manageattachments;save;sa=avatars';
377
	prepareDBSettingContext($config_vars);
378
379
	// Add a layer for the javascript.
380
	$context['template_layers'][] = 'avatar_settings';
381
	$context['sub_template'] = 'show_settings';
382
}
383
384
/**
385
 * Show a list of attachment or avatar files.
386
 * Called by ?action=admin;area=manageattachments;sa=browse for attachments
387
 *  and ?action=admin;area=manageattachments;sa=browse;avatars for avatars.
388
 * Allows sorting by name, date, size and member.
389
 * Paginates results.
390
 */
391
function BrowseFiles()
392
{
393
	global $context, $txt, $scripturl, $modSettings;
394
	global $smcFunc, $sourcedir, $settings;
395
396
	// Attachments or avatars?
397
	$context['browse_type'] = isset($_REQUEST['avatars']) ? 'avatars' : (isset($_REQUEST['thumbs']) ? 'thumbs' : 'attachments');
398
399
	$titles = array(
400
		'attachments' => array('?action=admin;area=manageattachments;sa=browse', $txt['attachment_manager_attachments']),
401
		'avatars' => array('?action=admin;area=manageattachments;sa=browse;avatars', $txt['attachment_manager_avatars']),
402
		'thumbs' => array('?action=admin;area=manageattachments;sa=browse;thumbs', $txt['attachment_manager_thumbs']),
403
	);
404
405
	$list_title = $txt['attachment_manager_browse_files'] . ': ';
406
	foreach ($titles as $browse_type => $details)
407
	{
408
		if ($browse_type != 'attachments')
409
			$list_title .= ' | ';
410
411
		if ($context['browse_type'] == $browse_type)
412
			$list_title .= '<img src="' . $settings['images_url'] . '/selected.png" alt="&gt;"> ';
413
414
		$list_title .= '<a href="' . $scripturl . $details[0] . '">' . $details[1] . '</a>';
415
	}
416
417
	// Set the options for the list component.
418
	$listOptions = array(
419
		'id' => 'file_list',
420
		'title' => $list_title,
421
		'items_per_page' => $modSettings['defaultMaxListItems'],
422
		'base_href' => $scripturl . '?action=admin;area=manageattachments;sa=browse' . ($context['browse_type'] === 'avatars' ? ';avatars' : ($context['browse_type'] === 'thumbs' ? ';thumbs' : '')),
423
		'default_sort_col' => 'name',
424
		'no_items_label' => $txt['attachment_manager_' . ($context['browse_type'] === 'avatars' ? 'avatars' : ($context['browse_type'] === 'thumbs' ? 'thumbs' : 'attachments')) . '_no_entries'],
425
		'get_items' => array(
426
			'function' => 'list_getFiles',
427
			'params' => array(
428
				$context['browse_type'],
429
			),
430
		),
431
		'get_count' => array(
432
			'function' => 'list_getNumFiles',
433
			'params' => array(
434
				$context['browse_type'],
435
			),
436
		),
437
		'columns' => array(
438
			'name' => array(
439
				'header' => array(
440
					'value' => $txt['attachment_name'],
441
				),
442
				'data' => array(
443
					'function' => function($rowData) use ($modSettings, $context, $scripturl, $smcFunc)
444
					{
445
						$link = '<a href="';
446
447
						// In case of a custom avatar URL attachments have a fixed directory.
448
						if ($rowData['attachment_type'] == 1)
449
							$link .= sprintf('%1$s/%2$s', $modSettings['custom_avatar_url'], $rowData['filename']);
450
451
						// By default avatars are downloaded almost as attachments.
452
						elseif ($context['browse_type'] == 'avatars')
453
							$link .= sprintf('%1$s?action=dlattach;type=avatar;attach=%2$d', $scripturl, $rowData['id_attach']);
454
455
						// Normal attachments are always linked to a topic ID.
456
						else
457
							$link .= sprintf('%1$s?action=dlattach;topic=%2$d.0;attach=%3$d', $scripturl, $rowData['id_topic'], $rowData['id_attach']);
458
459
						$link .= '"';
460
461
						// Show a popup on click if it's a picture and we know its dimensions.
462
						if (!empty($rowData['width']) && !empty($rowData['height']))
463
							$link .= sprintf(' onclick="return reqWin(this.href' . ($rowData['attachment_type'] == 1 ? '' : ' + \';image\'') . ', %1$d, %2$d, true);"', $rowData['width'] + 20, $rowData['height'] + 20);
464
465
						$link .= sprintf('>%1$s</a>', preg_replace('~&amp;#(\\\\d{1,7}|x[0-9a-fA-F]{1,6});~', '&#\\\\1;', $smcFunc['htmlspecialchars']($rowData['filename'])));
466
467
						// Show the dimensions.
468
						if (!empty($rowData['width']) && !empty($rowData['height']))
469
							$link .= sprintf(' <span class="smalltext">%1$dx%2$d</span>', $rowData['width'], $rowData['height']);
470
471
						return $link;
472
					},
473
				),
474
				'sort' => array(
475
					'default' => 'a.filename',
476
					'reverse' => 'a.filename DESC',
477
				),
478
			),
479
			'filesize' => array(
480
				'header' => array(
481
					'value' => $txt['attachment_file_size'],
482
				),
483
				'data' => array(
484
					'function' => function($rowData) use ($txt)
485
					{
486
						return sprintf('%1$s%2$s', round($rowData['size'] / 1024, 2), $txt['kilobyte']);
487
					},
488
				),
489
				'sort' => array(
490
					'default' => 'a.size',
491
					'reverse' => 'a.size DESC',
492
				),
493
			),
494
			'member' => array(
495
				'header' => array(
496
					'value' => $context['browse_type'] == 'avatars' ? $txt['attachment_manager_member'] : $txt['posted_by'],
497
				),
498
				'data' => array(
499
					'function' => function($rowData) use ($scripturl, $smcFunc)
500
					{
501
						// In case of an attachment, return the poster of the attachment.
502
						if (empty($rowData['id_member']))
503
							return $smcFunc['htmlspecialchars']($rowData['poster_name']);
504
505
						// Otherwise it must be an avatar, return the link to the owner of it.
506
						else
507
							return sprintf('<a href="%1$s?action=profile;u=%2$d">%3$s</a>', $scripturl, $rowData['id_member'], $rowData['poster_name']);
508
					},
509
				),
510
				'sort' => array(
511
					'default' => 'mem.real_name',
512
					'reverse' => 'mem.real_name DESC',
513
				),
514
			),
515
			'date' => array(
516
				'header' => array(
517
					'value' => $context['browse_type'] == 'avatars' ? $txt['attachment_manager_last_active'] : $txt['date'],
518
				),
519
				'data' => array(
520
					'function' => function($rowData) use ($txt, $context, $scripturl)
521
					{
522
						// The date the message containing the attachment was posted or the owner of the avatar was active.
523
						$date = empty($rowData['poster_time']) ? $txt['never'] : timeformat($rowData['poster_time']);
524
525
						// Add a link to the topic in case of an attachment.
526
						if ($context['browse_type'] !== 'avatars')
527
							$date .= sprintf('<br>%1$s <a href="%2$s?topic=%3$d.msg%4$d#msg%4$d">%5$s</a>', $txt['in'], $scripturl, $rowData['id_topic'], $rowData['id_msg'], $rowData['subject']);
528
529
						return $date;
530
					},
531
				),
532
				'sort' => array(
533
					'default' => $context['browse_type'] === 'avatars' ? 'mem.last_login' : 'm.id_msg',
534
					'reverse' => $context['browse_type'] === 'avatars' ? 'mem.last_login DESC' : 'm.id_msg DESC',
535
				),
536
			),
537
			'downloads' => array(
538
				'header' => array(
539
					'value' => $txt['downloads'],
540
				),
541
				'data' => array(
542
					'db' => 'downloads',
543
					'comma_format' => true,
544
				),
545
				'sort' => array(
546
					'default' => 'a.downloads',
547
					'reverse' => 'a.downloads DESC',
548
				),
549
			),
550
			'check' => array(
551
				'header' => array(
552
					'value' => '<input type="checkbox" onclick="invertAll(this, this.form);">',
553
					'class' => 'centercol',
554
				),
555
				'data' => array(
556
					'sprintf' => array(
557
						'format' => '<input type="checkbox" name="remove[%1$d]">',
558
						'params' => array(
559
							'id_attach' => false,
560
						),
561
					),
562
					'class' => 'centercol',
563
				),
564
			),
565
		),
566
		'form' => array(
567
			'href' => $scripturl . '?action=admin;area=manageattachments;sa=remove' . ($context['browse_type'] === 'avatars' ? ';avatars' : ($context['browse_type'] === 'thumbs' ? ';thumbs' : '')),
568
			'include_sort' => true,
569
			'include_start' => true,
570
			'hidden_fields' => array(
571
				'type' => $context['browse_type'],
572
			),
573
		),
574
		'additional_rows' => array(
575
			array(
576
				'position' => 'above_table_headers',
577
				'value' => '<input type="submit" name="remove_submit" class="button you_sure" value="' . $txt['quickmod_delete_selected'] . '" data-confirm="' . $txt['confirm_delete_attachments'] . '">',
578
			),
579
			array(
580
				'position' => 'below_table_data',
581
				'value' => '<input type="submit" name="remove_submit" class="button you_sure" value="' . $txt['quickmod_delete_selected'] . '" data-confirm="' . $txt['confirm_delete_attachments'] . '">',
582
			),
583
		),
584
	);
585
586
	// Does a hook want to display their attachments better?
587
	call_integration_hook('integrate_attachments_browse', array(&$listOptions, &$titles, &$list_title));
588
589
	// Create the list.
590
	require_once($sourcedir . '/Subs-List.php');
591
	createList($listOptions);
592
593
	$context['sub_template'] = 'show_list';
594
	$context['default_list'] = 'file_list';
595
}
596
597
/**
598
 * Returns the list of attachments files (avatars or not), recorded
599
 * in the database, per the parameters received.
600
 *
601
 * @param int $start The item to start with
602
 * @param int $items_per_page How many items to show per page
603
 * @param string $sort A string indicating how to sort results
604
 * @param string $browse_type can be one of 'avatars' or ... not. :P
605
 * @return array An array of file info
606
 */
607
function list_getFiles($start, $items_per_page, $sort, $browse_type)
608
{
609
	global $smcFunc, $txt;
610
611
	// Choose a query depending on what we are viewing.
612
	if ($browse_type === 'avatars')
613
		$request = $smcFunc['db_query']('', '
614
			SELECT
615
				{string:blank_text} AS id_msg, COALESCE(mem.real_name, {string:not_applicable_text}) AS poster_name,
616
				mem.last_login AS poster_time, 0 AS id_topic, a.id_member, a.id_attach, a.filename, a.file_hash, a.attachment_type,
617
				a.size, a.width, a.height, a.downloads, {string:blank_text} AS subject, 0 AS id_board
618
			FROM {db_prefix}attachments AS a
619
				LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = a.id_member)
620
			WHERE a.id_member != {int:guest_id}
621
			ORDER BY {raw:sort}
622
			LIMIT {int:start}, {int:per_page}',
623
			array(
624
				'guest_id' => 0,
625
				'blank_text' => '',
626
				'not_applicable_text' => $txt['not_applicable'],
627
				'sort' => $sort,
628
				'start' => $start,
629
				'per_page' => $items_per_page,
630
			)
631
		);
632
	else
633
		$request = $smcFunc['db_query']('', '
634
			SELECT
635
				m.id_msg, COALESCE(mem.real_name, m.poster_name) AS poster_name, m.poster_time, m.id_topic, m.id_member,
636
				a.id_attach, a.filename, a.file_hash, a.attachment_type, a.size, a.width, a.height, a.downloads, mf.subject, t.id_board
637
			FROM {db_prefix}attachments AS a
638
				INNER JOIN {db_prefix}messages AS m ON (m.id_msg = a.id_msg)
639
				INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic)
640
				INNER JOIN {db_prefix}messages AS mf ON (mf.id_msg = t.id_first_msg)
641
				LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)
642
			WHERE a.attachment_type = {int:attachment_type}
643
			ORDER BY {raw:sort}
644
			LIMIT {int:start}, {int:per_page}',
645
			array(
646
				'attachment_type' => $browse_type == 'thumbs' ? '3' : '0',
647
				'sort' => $sort,
648
				'start' => $start,
649
				'per_page' => $items_per_page,
650
			)
651
		);
652
	$files = array();
653
	while ($row = $smcFunc['db_fetch_assoc']($request))
654
		$files[] = $row;
655
	$smcFunc['db_free_result']($request);
656
657
	return $files;
658
}
659
660
/**
661
 * Return the number of files of the specified type recorded in the database.
662
 * (the specified type being attachments or avatars).
663
 *
664
 * @param string $browse_type can be one of 'avatars' or not. (in which case they're attachments)
665
 * @return int The number of files
666
 */
667
function list_getNumFiles($browse_type)
668
{
669
	global $smcFunc;
670
671
	// Depending on the type of file, different queries are used.
672
	if ($browse_type === 'avatars')
673
		$request = $smcFunc['db_query']('', '
674
		SELECT COUNT(*)
675
		FROM {db_prefix}attachments
676
		WHERE id_member != {int:guest_id_member}',
677
		array(
678
			'guest_id_member' => 0,
679
		)
680
	);
681
	else
682
		$request = $smcFunc['db_query']('', '
683
			SELECT COUNT(*) AS num_attach
684
			FROM {db_prefix}attachments AS a
685
				INNER JOIN {db_prefix}messages AS m ON (m.id_msg = a.id_msg)
686
				INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic)
687
				INNER JOIN {db_prefix}messages AS mf ON (mf.id_msg = t.id_first_msg)
688
			WHERE a.attachment_type = {int:attachment_type}
689
				AND a.id_member = {int:guest_id_member}',
690
			array(
691
				'attachment_type' => $browse_type === 'thumbs' ? '3' : '0',
692
				'guest_id_member' => 0,
693
			)
694
		);
695
696
	list ($num_files) = $smcFunc['db_fetch_row']($request);
697
	$smcFunc['db_free_result']($request);
698
699
	return $num_files;
700
}
701
702
/**
703
 * Show several file maintenance options.
704
 * Called by ?action=admin;area=manageattachments;sa=maintain.
705
 * Calculates file statistics (total file size, number of attachments,
706
 * number of avatars, attachment space available).
707
 *
708
 * @uses the 'maintain' sub template.
709
 */
710
function MaintainFiles()
711
{
712
	global $context, $modSettings, $smcFunc;
713
714
	$context['sub_template'] = 'maintenance';
715
716
	$attach_dirs = $smcFunc['json_decode']($modSettings['attachmentUploadDir'], true);
717
718
	// Get the number of attachments....
719
	$request = $smcFunc['db_query']('', '
720
		SELECT COUNT(*)
721
		FROM {db_prefix}attachments
722
		WHERE attachment_type = {int:attachment_type}
723
			AND id_member = {int:guest_id_member}',
724
		array(
725
			'attachment_type' => 0,
726
			'guest_id_member' => 0,
727
		)
728
	);
729
	list ($context['num_attachments']) = $smcFunc['db_fetch_row']($request);
730
	$smcFunc['db_free_result']($request);
731
	$context['num_attachments'] = comma_format($context['num_attachments'], 0);
732
733
	// Also get the avatar amount....
734
	$request = $smcFunc['db_query']('', '
735
		SELECT COUNT(*)
736
		FROM {db_prefix}attachments
737
		WHERE id_member != {int:guest_id_member}',
738
		array(
739
			'guest_id_member' => 0,
740
		)
741
	);
742
	list ($context['num_avatars']) = $smcFunc['db_fetch_row']($request);
743
	$smcFunc['db_free_result']($request);
744
	$context['num_avatars'] = comma_format($context['num_avatars'], 0);
745
746
	// Check the size of all the directories.
747
	$request = $smcFunc['db_query']('', '
748
		SELECT SUM(size)
749
		FROM {db_prefix}attachments
750
		WHERE attachment_type != {int:type}',
751
		array(
752
			'type' => 1,
753
		)
754
	);
755
	list ($attachmentDirSize) = $smcFunc['db_fetch_row']($request);
756
	$smcFunc['db_free_result']($request);
757
758
	// Divide it into kilobytes.
759
	$attachmentDirSize /= 1024;
760
	$context['attachment_total_size'] = comma_format($attachmentDirSize, 2);
761
762
	$request = $smcFunc['db_query']('', '
763
		SELECT COUNT(*), SUM(size)
764
		FROM {db_prefix}attachments
765
		WHERE id_folder = {int:folder_id}
766
			AND attachment_type != {int:type}',
767
		array(
768
			'folder_id' => $modSettings['currentAttachmentUploadDir'],
769
			'type' => 1,
770
		)
771
	);
772
	list ($current_dir_files, $current_dir_size) = $smcFunc['db_fetch_row']($request);
773
	$smcFunc['db_free_result']($request);
774
	$current_dir_size /= 1024;
775
776
	// If they specified a limit only....
777
	if (!empty($modSettings['attachmentDirSizeLimit']))
778
		$context['attachment_space'] = comma_format(max($modSettings['attachmentDirSizeLimit'] - $current_dir_size, 0), 2);
779
	$context['attachment_current_size'] = comma_format($current_dir_size, 2);
780
781
	if (!empty($modSettings['attachmentDirFileLimit']))
782
		$context['attachment_files'] = comma_format(max($modSettings['attachmentDirFileLimit'] - $current_dir_files, 0), 0);
783
	$context['attachment_current_files'] = comma_format($current_dir_files, 0);
784
785
	$context['attach_multiple_dirs'] = count($attach_dirs) > 1 ? true : false;
786
	$context['attach_dirs'] = $attach_dirs;
787
	$context['base_dirs'] = !empty($modSettings['attachment_basedirectories']) ? $smcFunc['json_decode']($modSettings['attachment_basedirectories'], true) : array();
788
	$context['checked'] = isset($_SESSION['checked']) ? $_SESSION['checked'] : true;
789
	if (!empty($_SESSION['results']))
790
	{
791
		$context['results'] = implode('<br>', $_SESSION['results']);
792
		unset($_SESSION['results']);
793
	}
794
}
795
796
/**
797
 * Remove attachments older than a given age.
798
 * Called from the maintenance screen by
799
 *   ?action=admin;area=manageattachments;sa=byAge.
800
 * It optionally adds a certain text to the messages the attachments
801
 *  were removed from.
802
 *  @todo refactor this silly superglobals use...
803
 */
804
function RemoveAttachmentByAge()
805
{
806
	global $smcFunc;
807
808
	checkSession('post', 'admin');
809
810
	// @todo Ignore messages in topics that are stickied?
811
812
	// Deleting an attachment?
813
	if ($_REQUEST['type'] != 'avatars')
814
	{
815
		// Get rid of all the old attachments.
816
		$messages = removeAttachments(array('attachment_type' => 0, 'poster_time' => (time() - 24 * 60 * 60 * $_POST['age'])), 'messages', true);
817
818
		// Update the messages to reflect the change.
819
		if (!empty($messages) && !empty($_POST['notice']))
820
			$smcFunc['db_query']('', '
821
				UPDATE {db_prefix}messages
822
				SET body = CONCAT(body, {string:notice})
823
				WHERE id_msg IN ({array_int:messages})',
824
				array(
825
					'messages' => $messages,
826
					'notice' => '<br><br>' . $_POST['notice'],
827
				)
828
			);
829
	}
830
	else
831
	{
832
		// Remove all the old avatars.
833
		removeAttachments(array('not_id_member' => 0, 'last_login' => (time() - 24 * 60 * 60 * $_POST['age'])), 'members');
834
	}
835
	redirectexit('action=admin;area=manageattachments' . (empty($_REQUEST['avatars']) ? ';sa=maintenance' : ';avatars'));
836
}
837
838
/**
839
 * Remove attachments larger than a given size.
840
 * Called from the maintenance screen by
841
 *  ?action=admin;area=manageattachments;sa=bySize.
842
 * Optionally adds a certain text to the messages the attachments were
843
 * 	removed from.
844
 */
845
function RemoveAttachmentBySize()
846
{
847
	global $smcFunc;
848
849
	checkSession('post', 'admin');
850
851
	// Find humungous attachments.
852
	$messages = removeAttachments(array('attachment_type' => 0, 'size' => 1024 * $_POST['size']), 'messages', true);
853
854
	// And make a note on the post.
855
	if (!empty($messages) && !empty($_POST['notice']))
856
		$smcFunc['db_query']('', '
857
			UPDATE {db_prefix}messages
858
			SET body = CONCAT(body, {string:notice})
859
			WHERE id_msg IN ({array_int:messages})',
860
			array(
861
				'messages' => $messages,
862
				'notice' => '<br><br>' . $_POST['notice'],
863
			)
864
		);
865
866
	redirectexit('action=admin;area=manageattachments;sa=maintenance');
867
}
868
869
/**
870
 * Remove a selection of attachments or avatars.
871
 * Called from the browse screen as submitted form by
872
 *  ?action=admin;area=manageattachments;sa=remove
873
 */
874
function RemoveAttachment()
875
{
876
	global $txt, $smcFunc, $language, $user_info;
877
878
	checkSession();
879
880
	if (!empty($_POST['remove']))
881
	{
882
		$attachments = array();
883
		// There must be a quicker way to pass this safety test??
884
		foreach ($_POST['remove'] as $removeID => $dummy)
885
			$attachments[] = (int) $removeID;
886
887
		// If the attachments are from a 3rd party, let them remove it. Hooks should remove their ids from the array.
888
		$filesRemoved = false;
889
		call_integration_hook('integrate_attachment_remove', array(&$filesRemoved, $attachments));
890
891
		if ($_REQUEST['type'] == 'avatars' && !empty($attachments))
892
			removeAttachments(array('id_attach' => $attachments));
893
		else if (!empty($attachments))
894
		{
895
			$messages = removeAttachments(array('id_attach' => $attachments), 'messages', true);
896
897
			// And change the message to reflect this.
898
			if (!empty($messages))
899
			{
900
				loadLanguage('index', $language, true);
901
				$smcFunc['db_query']('', '
902
					UPDATE {db_prefix}messages
903
					SET body = CONCAT(body, {string:deleted_message})
904
					WHERE id_msg IN ({array_int:messages_affected})',
905
					array(
906
						'messages_affected' => $messages,
907
						'deleted_message' => '<br><br>' . $txt['attachment_delete_admin'],
908
					)
909
				);
910
				loadLanguage('index', $user_info['language'], true);
911
			}
912
		}
913
	}
914
915
	$_GET['sort'] = isset($_GET['sort']) ? $_GET['sort'] : 'date';
916
	redirectexit('action=admin;area=manageattachments;sa=browse;' . $_REQUEST['type'] . ';sort=' . $_GET['sort'] . (isset($_GET['desc']) ? ';desc' : '') . ';start=' . $_REQUEST['start']);
917
}
918
919
/**
920
 * Removes all attachments in a single click
921
 * Called from the maintenance screen by
922
 *  ?action=admin;area=manageattachments;sa=removeall.
923
 */
924
function RemoveAllAttachments()
925
{
926
	global $txt, $smcFunc;
927
928
	checkSession('get', 'admin');
929
930
	$messages = removeAttachments(array('attachment_type' => 0), '', true);
931
932
	if (!isset($_POST['notice']))
933
		$_POST['notice'] = $txt['attachment_delete_admin'];
934
935
	// Add the notice on the end of the changed messages.
936
	if (!empty($messages))
937
		$smcFunc['db_query']('', '
938
			UPDATE {db_prefix}messages
939
			SET body = CONCAT(body, {string:deleted_message})
940
			WHERE id_msg IN ({array_int:messages})',
941
			array(
942
				'messages' => $messages,
943
				'deleted_message' => '<br><br>' . $_POST['notice'],
944
			)
945
		);
946
947
	redirectexit('action=admin;area=manageattachments;sa=maintenance');
948
}
949
950
/**
951
 * Removes attachments or avatars based on a given query condition.
952
 * Called by several remove avatar/attachment functions in this file.
953
 * It removes attachments based that match the $condition.
954
 * It allows query_types 'messages' and 'members', whichever is need by the
955
 * $condition parameter.
956
 * It does no permissions check.
957
 * @internal
958
 *
959
 * @param array $condition An array of conditions
960
 * @param string $query_type The query type. Can be 'messages' or 'members'
961
 * @param bool $return_affected_messages Whether to return an array with the IDs of affected messages
962
 * @param bool $autoThumbRemoval Whether to automatically remove any thumbnails associated with the removed files
963
 * @return void|int[] Returns an array containing IDs of affected messages if $return_affected_messages is true
964
 */
965
function removeAttachments($condition, $query_type = '', $return_affected_messages = false, $autoThumbRemoval = true)
966
{
967
	global $modSettings, $smcFunc;
968
969
	// @todo This might need more work!
970
	$new_condition = array();
971
	$query_parameter = array(
972
		'thumb_attachment_type' => 3,
973
	);
974
	$do_logging = array();
975
976
	if (is_array($condition))
0 ignored issues
show
introduced by
The condition is_array($condition) is always true.
Loading history...
977
	{
978
		foreach ($condition as $real_type => $restriction)
979
		{
980
			// Doing a NOT?
981
			$is_not = substr($real_type, 0, 4) == 'not_';
982
			$type = $is_not ? substr($real_type, 4) : $real_type;
983
984
			if (in_array($type, array('id_member', 'id_attach', 'id_msg')))
985
				$new_condition[] = 'a.' . $type . ($is_not ? ' NOT' : '') . ' IN (' . (is_array($restriction) ? '{array_int:' . $real_type . '}' : '{int:' . $real_type . '}') . ')';
986
			elseif ($type == 'attachment_type')
987
				$new_condition[] = 'a.attachment_type = {int:' . $real_type . '}';
988
			elseif ($type == 'poster_time')
989
				$new_condition[] = 'm.poster_time < {int:' . $real_type . '}';
990
			elseif ($type == 'last_login')
991
				$new_condition[] = 'mem.last_login < {int:' . $real_type . '}';
992
			elseif ($type == 'size')
993
				$new_condition[] = 'a.size > {int:' . $real_type . '}';
994
			elseif ($type == 'id_topic')
995
				$new_condition[] = 'm.id_topic IN (' . (is_array($restriction) ? '{array_int:' . $real_type . '}' : '{int:' . $real_type . '}') . ')';
996
997
			// Add the parameter!
998
			$query_parameter[$real_type] = $restriction;
999
1000
			if ($type == 'do_logging')
1001
				$do_logging = $condition['id_attach'];
1002
		}
1003
		$condition = implode(' AND ', $new_condition);
1004
	}
1005
1006
	// Delete it only if it exists...
1007
	$msgs = array();
1008
	$attach = array();
1009
	$parents = array();
1010
1011
	// Get all the attachment names and id_msg's.
1012
	$request = $smcFunc['db_query']('', '
1013
		SELECT
1014
			a.id_folder, a.filename, a.file_hash, a.attachment_type, a.id_attach, a.id_member' . ($query_type == 'messages' ? ', m.id_msg' : ', a.id_msg') . ',
1015
			thumb.id_folder AS thumb_folder, COALESCE(thumb.id_attach, 0) AS id_thumb, thumb.filename AS thumb_filename, thumb.file_hash AS thumb_file_hash, thumb_parent.id_attach AS id_parent
1016
		FROM {db_prefix}attachments AS a' .($query_type == 'members' ? '
1017
			INNER JOIN {db_prefix}members AS mem ON (mem.id_member = a.id_member)' : ($query_type == 'messages' ? '
1018
			INNER JOIN {db_prefix}messages AS m ON (m.id_msg = a.id_msg)' : '')) . '
1019
			LEFT JOIN {db_prefix}attachments AS thumb ON (thumb.id_attach = a.id_thumb)
1020
			LEFT JOIN {db_prefix}attachments AS thumb_parent ON (thumb.attachment_type = {int:thumb_attachment_type} AND thumb_parent.id_thumb = a.id_attach)
1021
		WHERE ' . $condition,
1022
		$query_parameter
1023
	);
1024
	while ($row = $smcFunc['db_fetch_assoc']($request))
1025
	{
1026
		// Figure out the "encrypted" filename and unlink it ;).
1027
		if ($row['attachment_type'] == 1)
1028
		{
1029
			// if attachment_type = 1, it's... an avatar in a custom avatar directory.
1030
			// wasn't it obvious? :P
1031
			// @todo look again at this.
1032
			@unlink($modSettings['custom_avatar_dir'] . '/' . $row['filename']);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for unlink(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

1032
			/** @scrutinizer ignore-unhandled */ @unlink($modSettings['custom_avatar_dir'] . '/' . $row['filename']);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1033
		}
1034
		else
1035
		{
1036
			$filename = getAttachmentFilename($row['filename'], $row['id_attach'], $row['id_folder'], false, $row['file_hash']);
1037
			@unlink($filename);
1038
1039
			// If this was a thumb, the parent attachment should know about it.
1040
			if (!empty($row['id_parent']))
1041
				$parents[] = $row['id_parent'];
1042
1043
			// If this attachments has a thumb, remove it as well.
1044
			if (!empty($row['id_thumb']) && $autoThumbRemoval)
1045
			{
1046
				$thumb_filename = getAttachmentFilename($row['thumb_filename'], $row['id_thumb'], $row['thumb_folder'], false, $row['thumb_file_hash']);
1047
				@unlink($thumb_filename);
1048
				$attach[] = $row['id_thumb'];
1049
			}
1050
		}
1051
1052
		// Make a list.
1053
		if ($return_affected_messages && empty($row['attachment_type']))
1054
			$msgs[] = $row['id_msg'];
1055
1056
		$attach[] = $row['id_attach'];
1057
	}
1058
	$smcFunc['db_free_result']($request);
1059
1060
	// Removed attachments don't have to be updated anymore.
1061
	$parents = array_diff($parents, $attach);
1062
	if (!empty($parents))
1063
		$smcFunc['db_query']('', '
1064
			UPDATE {db_prefix}attachments
1065
			SET id_thumb = {int:no_thumb}
1066
			WHERE id_attach IN ({array_int:parent_attachments})',
1067
			array(
1068
				'parent_attachments' => $parents,
1069
				'no_thumb' => 0,
1070
			)
1071
		);
1072
1073
	if (!empty($do_logging))
1074
	{
1075
		// In order to log the attachments, we really need their message and filename
1076
		$request = $smcFunc['db_query']('', '
1077
			SELECT m.id_msg, a.filename
1078
			FROM {db_prefix}attachments AS a
1079
				INNER JOIN {db_prefix}messages AS m ON (a.id_msg = m.id_msg)
1080
			WHERE a.id_attach IN ({array_int:attachments})
1081
				AND a.attachment_type = {int:attachment_type}',
1082
			array(
1083
				'attachments' => $do_logging,
1084
				'attachment_type' => 0,
1085
			)
1086
		);
1087
1088
		while ($row = $smcFunc['db_fetch_assoc']($request))
1089
			logAction(
1090
				'remove_attach',
1091
				array(
1092
					'message' => $row['id_msg'],
1093
					'filename' => preg_replace('~&amp;#(\\d{1,7}|x[0-9a-fA-F]{1,6});~', '&#\\1;', $smcFunc['htmlspecialchars']($row['filename'])),
1094
				)
1095
			);
1096
		$smcFunc['db_free_result']($request);
1097
	}
1098
1099
	if (!empty($attach))
1100
		$smcFunc['db_query']('', '
1101
			DELETE FROM {db_prefix}attachments
1102
			WHERE id_attach IN ({array_int:attachment_list})',
1103
			array(
1104
				'attachment_list' => $attach,
1105
			)
1106
		);
1107
1108
	call_integration_hook('integrate_remove_attachments', array($attach));
1109
1110
	if ($return_affected_messages)
1111
		return array_unique($msgs);
1112
}
1113
1114
/**
1115
 * This function should find attachments in the database that no longer exist and clear them, and fix filesize issues.
1116
 */
1117
function RepairAttachments()
1118
{
1119
	global $modSettings, $context, $txt, $smcFunc;
1120
1121
	checkSession('get');
1122
1123
	// If we choose cancel, redirect right back.
1124
	if (isset($_POST['cancel']))
1125
		redirectexit('action=admin;area=manageattachments;sa=maintenance');
1126
1127
	// Try give us a while to sort this out...
1128
	@set_time_limit(600);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for set_time_limit(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

1128
	/** @scrutinizer ignore-unhandled */ @set_time_limit(600);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1129
1130
	$_GET['step'] = empty($_GET['step']) ? 0 : (int) $_GET['step'];
1131
	$context['starting_substep'] = $_GET['substep'] = empty($_GET['substep']) ? 0 : (int) $_GET['substep'];
1132
1133
	// Don't recall the session just in case.
1134
	if ($_GET['step'] == 0 && $_GET['substep'] == 0)
1135
	{
1136
		unset($_SESSION['attachments_to_fix'], $_SESSION['attachments_to_fix2']);
1137
1138
		// If we're actually fixing stuff - work out what.
1139
		if (isset($_GET['fixErrors']))
1140
		{
1141
			// Nothing?
1142
			if (empty($_POST['to_fix']))
1143
				redirectexit('action=admin;area=manageattachments;sa=maintenance');
1144
1145
			$_SESSION['attachments_to_fix'] = array();
1146
			// @todo No need to do this I think.
1147
			foreach ($_POST['to_fix'] as $value)
1148
				$_SESSION['attachments_to_fix'][] = $value;
1149
		}
1150
	}
1151
1152
	// All the valid problems are here:
1153
	$context['repair_errors'] = array(
1154
		'missing_thumbnail_parent' => 0,
1155
		'parent_missing_thumbnail' => 0,
1156
		'file_missing_on_disk' => 0,
1157
		'file_wrong_size' => 0,
1158
		'file_size_of_zero' => 0,
1159
		'attachment_no_msg' => 0,
1160
		'avatar_no_member' => 0,
1161
		'wrong_folder' => 0,
1162
		'files_without_attachment' => 0,
1163
	);
1164
1165
	$to_fix = !empty($_SESSION['attachments_to_fix']) ? $_SESSION['attachments_to_fix'] : array();
1166
	$context['repair_errors'] = isset($_SESSION['attachments_to_fix2']) ? $_SESSION['attachments_to_fix2'] : $context['repair_errors'];
1167
	$fix_errors = isset($_GET['fixErrors']) ? true : false;
1168
1169
	// Get stranded thumbnails.
1170
	if ($_GET['step'] <= 0)
1171
	{
1172
		$result = $smcFunc['db_query']('', '
1173
			SELECT MAX(id_attach)
1174
			FROM {db_prefix}attachments
1175
			WHERE attachment_type = {int:thumbnail}',
1176
			array(
1177
				'thumbnail' => 3,
1178
			)
1179
		);
1180
		list ($thumbnails) = $smcFunc['db_fetch_row']($result);
1181
		$smcFunc['db_free_result']($result);
1182
1183
		for (; $_GET['substep'] < $thumbnails; $_GET['substep'] += 500)
1184
		{
1185
			$to_remove = array();
1186
1187
			$result = $smcFunc['db_query']('', '
1188
				SELECT thumb.id_attach, thumb.id_folder, thumb.filename, thumb.file_hash
1189
				FROM {db_prefix}attachments AS thumb
1190
					LEFT JOIN {db_prefix}attachments AS tparent ON (tparent.id_thumb = thumb.id_attach)
1191
				WHERE thumb.id_attach BETWEEN {int:substep} AND {int:substep} + 499
1192
					AND thumb.attachment_type = {int:thumbnail}
1193
					AND tparent.id_attach IS NULL',
1194
				array(
1195
					'thumbnail' => 3,
1196
					'substep' => $_GET['substep'],
1197
				)
1198
			);
1199
			while ($row = $smcFunc['db_fetch_assoc']($result))
1200
			{
1201
				// Only do anything once... just in case
1202
				if (!isset($to_remove[$row['id_attach']]))
1203
				{
1204
					$to_remove[$row['id_attach']] = $row['id_attach'];
1205
					$context['repair_errors']['missing_thumbnail_parent']++;
1206
1207
					// If we are repairing remove the file from disk now.
1208
					if ($fix_errors && in_array('missing_thumbnail_parent', $to_fix))
1209
					{
1210
						$filename = getAttachmentFilename($row['filename'], $row['id_attach'], $row['id_folder'], false, $row['file_hash']);
1211
						@unlink($filename);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for unlink(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

1211
						/** @scrutinizer ignore-unhandled */ @unlink($filename);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1212
					}
1213
				}
1214
			}
1215
			if ($smcFunc['db_num_rows']($result) != 0)
1216
				$to_fix[] = 'missing_thumbnail_parent';
1217
			$smcFunc['db_free_result']($result);
1218
1219
			// Do we need to delete what we have?
1220
			if ($fix_errors && !empty($to_remove) && in_array('missing_thumbnail_parent', $to_fix))
1221
				$smcFunc['db_query']('', '
1222
					DELETE FROM {db_prefix}attachments
1223
					WHERE id_attach IN ({array_int:to_remove})
1224
						AND attachment_type = {int:attachment_type}',
1225
					array(
1226
						'to_remove' => $to_remove,
1227
						'attachment_type' => 3,
1228
					)
1229
				);
1230
1231
			pauseAttachmentMaintenance($to_fix, $thumbnails);
1232
		}
1233
1234
		$_GET['step'] = 1;
1235
		$_GET['substep'] = 0;
1236
		pauseAttachmentMaintenance($to_fix);
1237
	}
1238
1239
	// Find parents which think they have thumbnails, but actually, don't.
1240
	if ($_GET['step'] <= 1)
1241
	{
1242
		$result = $smcFunc['db_query']('', '
1243
			SELECT MAX(id_attach)
1244
			FROM {db_prefix}attachments
1245
			WHERE id_thumb != {int:no_thumb}',
1246
			array(
1247
				'no_thumb' => 0,
1248
			)
1249
		);
1250
		list ($thumbnails) = $smcFunc['db_fetch_row']($result);
1251
		$smcFunc['db_free_result']($result);
1252
1253
		for (; $_GET['substep'] < $thumbnails; $_GET['substep'] += 500)
1254
		{
1255
			$to_update = array();
1256
1257
			$result = $smcFunc['db_query']('', '
1258
				SELECT a.id_attach
1259
				FROM {db_prefix}attachments AS a
1260
					LEFT JOIN {db_prefix}attachments AS thumb ON (thumb.id_attach = a.id_thumb)
1261
				WHERE a.id_attach BETWEEN {int:substep} AND {int:substep} + 499
1262
					AND a.id_thumb != {int:no_thumb}
1263
					AND thumb.id_attach IS NULL',
1264
				array(
1265
					'no_thumb' => 0,
1266
					'substep' => $_GET['substep'],
1267
				)
1268
			);
1269
			while ($row = $smcFunc['db_fetch_assoc']($result))
1270
			{
1271
				$to_update[] = $row['id_attach'];
1272
				$context['repair_errors']['parent_missing_thumbnail']++;
1273
			}
1274
			if ($smcFunc['db_num_rows']($result) != 0)
1275
				$to_fix[] = 'parent_missing_thumbnail';
1276
			$smcFunc['db_free_result']($result);
1277
1278
			// Do we need to delete what we have?
1279
			if ($fix_errors && !empty($to_update) && in_array('parent_missing_thumbnail', $to_fix))
1280
				$smcFunc['db_query']('', '
1281
					UPDATE {db_prefix}attachments
1282
					SET id_thumb = {int:no_thumb}
1283
					WHERE id_attach IN ({array_int:to_update})',
1284
					array(
1285
						'to_update' => $to_update,
1286
						'no_thumb' => 0,
1287
					)
1288
				);
1289
1290
			pauseAttachmentMaintenance($to_fix, $thumbnails);
1291
		}
1292
1293
		$_GET['step'] = 2;
1294
		$_GET['substep'] = 0;
1295
		pauseAttachmentMaintenance($to_fix);
1296
	}
1297
1298
	// This may take forever I'm afraid, but life sucks... recount EVERY attachments!
1299
	if ($_GET['step'] <= 2)
1300
	{
1301
		$result = $smcFunc['db_query']('', '
1302
			SELECT MAX(id_attach)
1303
			FROM {db_prefix}attachments',
1304
			array(
1305
			)
1306
		);
1307
		list ($thumbnails) = $smcFunc['db_fetch_row']($result);
1308
		$smcFunc['db_free_result']($result);
1309
1310
		for (; $_GET['substep'] < $thumbnails; $_GET['substep'] += 250)
1311
		{
1312
			$to_remove = array();
1313
			$errors_found = array();
1314
1315
			$result = $smcFunc['db_query']('', '
1316
				SELECT id_attach, id_folder, filename, file_hash, size, attachment_type
1317
				FROM {db_prefix}attachments
1318
				WHERE id_attach BETWEEN {int:substep} AND {int:substep} + 249',
1319
				array(
1320
					'substep' => $_GET['substep'],
1321
				)
1322
			);
1323
			while ($row = $smcFunc['db_fetch_assoc']($result))
1324
			{
1325
				// Get the filename.
1326
				if ($row['attachment_type'] == 1)
1327
					$filename = $modSettings['custom_avatar_dir'] . '/' . $row['filename'];
1328
				else
1329
					$filename = getAttachmentFilename($row['filename'], $row['id_attach'], $row['id_folder'], false, $row['file_hash']);
1330
1331
				// File doesn't exist?
1332
				if (!file_exists($filename))
1333
				{
1334
					// If we're lucky it might just be in a different folder.
1335
					if (!empty($modSettings['currentAttachmentUploadDir']))
1336
					{
1337
						// Get the attachment name with out the folder.
1338
						$attachment_name = $row['id_attach'] . '_' . $row['file_hash'] . '.dat';
1339
1340
						// Loop through the other folders.
1341
						foreach ($modSettings['attachmentUploadDir'] as $id => $dir)
1342
							if (file_exists($dir . '/' . $attachment_name))
1343
							{
1344
								$context['repair_errors']['wrong_folder']++;
1345
								$errors_found[] = 'wrong_folder';
1346
1347
								// Are we going to fix this now?
1348
								if ($fix_errors && in_array('wrong_folder', $to_fix))
1349
									$smcFunc['db_query']('', '
1350
										UPDATE {db_prefix}attachments
1351
										SET id_folder = {int:new_folder}
1352
										WHERE id_attach = {int:id_attach}',
1353
										array(
1354
											'new_folder' => $id,
1355
											'id_attach' => $row['id_attach'],
1356
										)
1357
									);
1358
1359
								continue 2;
1360
							}
1361
					}
1362
1363
					$to_remove[] = $row['id_attach'];
1364
					$context['repair_errors']['file_missing_on_disk']++;
1365
					$errors_found[] = 'file_missing_on_disk';
1366
				}
1367
				elseif (filesize($filename) == 0)
1368
				{
1369
					$context['repair_errors']['file_size_of_zero']++;
1370
					$errors_found[] = 'file_size_of_zero';
1371
1372
					// Fixing?
1373
					if ($fix_errors && in_array('file_size_of_zero', $to_fix))
1374
					{
1375
						$to_remove[] = $row['id_attach'];
1376
						@unlink($filename);
1377
					}
1378
				}
1379
				elseif (filesize($filename) != $row['size'])
1380
				{
1381
					$context['repair_errors']['file_wrong_size']++;
1382
					$errors_found[] = 'file_wrong_size';
1383
1384
					// Fix it here?
1385
					if ($fix_errors && in_array('file_wrong_size', $to_fix))
1386
					{
1387
						$smcFunc['db_query']('', '
1388
							UPDATE {db_prefix}attachments
1389
							SET size = {int:filesize}
1390
							WHERE id_attach = {int:id_attach}',
1391
							array(
1392
								'filesize' => filesize($filename),
1393
								'id_attach' => $row['id_attach'],
1394
							)
1395
						);
1396
					}
1397
				}
1398
			}
1399
1400
			if (in_array('file_missing_on_disk', $errors_found))
1401
				$to_fix[] = 'file_missing_on_disk';
1402
			if (in_array('file_size_of_zero', $errors_found))
1403
				$to_fix[] = 'file_size_of_zero';
1404
			if (in_array('file_wrong_size', $errors_found))
1405
				$to_fix[] = 'file_wrong_size';
1406
			if (in_array('wrong_folder', $errors_found))
1407
				$to_fix[] = 'wrong_folder';
1408
			$smcFunc['db_free_result']($result);
1409
1410
			// Do we need to delete what we have?
1411
			if ($fix_errors && !empty($to_remove))
1412
			{
1413
				$smcFunc['db_query']('', '
1414
					DELETE FROM {db_prefix}attachments
1415
					WHERE id_attach IN ({array_int:to_remove})',
1416
					array(
1417
						'to_remove' => $to_remove,
1418
					)
1419
				);
1420
				$smcFunc['db_query']('', '
1421
					UPDATE {db_prefix}attachments
1422
					SET id_thumb = {int:no_thumb}
1423
					WHERE id_thumb IN ({array_int:to_remove})',
1424
					array(
1425
						'to_remove' => $to_remove,
1426
						'no_thumb' => 0,
1427
					)
1428
				);
1429
			}
1430
1431
			pauseAttachmentMaintenance($to_fix, $thumbnails);
1432
		}
1433
1434
		$_GET['step'] = 3;
1435
		$_GET['substep'] = 0;
1436
		pauseAttachmentMaintenance($to_fix);
1437
	}
1438
1439
	// Get avatars with no members associated with them.
1440
	if ($_GET['step'] <= 3)
1441
	{
1442
		$result = $smcFunc['db_query']('', '
1443
			SELECT MAX(id_attach)
1444
			FROM {db_prefix}attachments',
1445
			array(
1446
			)
1447
		);
1448
		list ($thumbnails) = $smcFunc['db_fetch_row']($result);
1449
		$smcFunc['db_free_result']($result);
1450
1451
		for (; $_GET['substep'] < $thumbnails; $_GET['substep'] += 500)
1452
		{
1453
			$to_remove = array();
1454
1455
			$result = $smcFunc['db_query']('', '
1456
				SELECT a.id_attach, a.id_folder, a.filename, a.file_hash, a.attachment_type
1457
				FROM {db_prefix}attachments AS a
1458
					LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = a.id_member)
1459
				WHERE a.id_attach BETWEEN {int:substep} AND {int:substep} + 499
1460
					AND a.id_member != {int:no_member}
1461
					AND a.id_msg = {int:no_msg}
1462
					AND mem.id_member IS NULL',
1463
				array(
1464
					'no_member' => 0,
1465
					'no_msg' => 0,
1466
					'substep' => $_GET['substep'],
1467
				)
1468
			);
1469
			while ($row = $smcFunc['db_fetch_assoc']($result))
1470
			{
1471
				$to_remove[] = $row['id_attach'];
1472
				$context['repair_errors']['avatar_no_member']++;
1473
1474
				// If we are repairing remove the file from disk now.
1475
				if ($fix_errors && in_array('avatar_no_member', $to_fix))
1476
				{
1477
					if ($row['attachment_type'] == 1)
1478
						$filename = $modSettings['custom_avatar_dir'] . '/' . $row['filename'];
1479
					else
1480
						$filename = getAttachmentFilename($row['filename'], $row['id_attach'], $row['id_folder'], false, $row['file_hash']);
1481
					@unlink($filename);
1482
				}
1483
			}
1484
			if ($smcFunc['db_num_rows']($result) != 0)
1485
				$to_fix[] = 'avatar_no_member';
1486
			$smcFunc['db_free_result']($result);
1487
1488
			// Do we need to delete what we have?
1489
			if ($fix_errors && !empty($to_remove) && in_array('avatar_no_member', $to_fix))
1490
				$smcFunc['db_query']('', '
1491
					DELETE FROM {db_prefix}attachments
1492
					WHERE id_attach IN ({array_int:to_remove})
1493
						AND id_member != {int:no_member}
1494
						AND id_msg = {int:no_msg}',
1495
					array(
1496
						'to_remove' => $to_remove,
1497
						'no_member' => 0,
1498
						'no_msg' => 0,
1499
					)
1500
				);
1501
1502
			pauseAttachmentMaintenance($to_fix, $thumbnails);
1503
		}
1504
1505
		$_GET['step'] = 4;
1506
		$_GET['substep'] = 0;
1507
		pauseAttachmentMaintenance($to_fix);
1508
	}
1509
1510
	// What about attachments, who are missing a message :'(
1511
	if ($_GET['step'] <= 4)
1512
	{
1513
		$result = $smcFunc['db_query']('', '
1514
			SELECT MAX(id_attach)
1515
			FROM {db_prefix}attachments',
1516
			array(
1517
			)
1518
		);
1519
		list ($thumbnails) = $smcFunc['db_fetch_row']($result);
1520
		$smcFunc['db_free_result']($result);
1521
1522
		for (; $_GET['substep'] < $thumbnails; $_GET['substep'] += 500)
1523
		{
1524
			$to_remove = array();
1525
			$ignore_ids = array(0);
1526
1527
			// returns an array of ints of id_attach's that should not be deleted
1528
			call_integration_hook('integrate_repair_attachments_nomsg', array(&$ignore_ids, $_GET['substep'], $_GET['substep'] + 500));
1529
1530
			$result = $smcFunc['db_query']('', '
1531
				SELECT a.id_attach, a.id_folder, a.filename, a.file_hash
1532
				FROM {db_prefix}attachments AS a
1533
					LEFT JOIN {db_prefix}messages AS m ON (m.id_msg = a.id_msg)
1534
				WHERE a.id_attach BETWEEN {int:substep} AND {int:substep} + 499
1535
					AND a.id_member = {int:no_member}
1536
					AND (a.id_msg = {int:no_msg} OR m.id_msg IS NULL)
1537
					AND a.id_attach NOT IN ({array_int:ignore_ids})
1538
					AND a.attachment_type IN ({array_int:attach_thumb})',
1539
				array(
1540
					'no_member' => 0,
1541
					'no_msg' => 0,
1542
					'substep' => $_GET['substep'],
1543
					'ignore_ids' => $ignore_ids,
1544
					'attach_thumb' => array(0,3),
1545
				)
1546
			);
1547
1548
			while ($row = $smcFunc['db_fetch_assoc']($result))
1549
			{
1550
				$to_remove[] = $row['id_attach'];
1551
				$context['repair_errors']['attachment_no_msg']++;
1552
1553
				// If we are repairing remove the file from disk now.
1554
				if ($fix_errors && in_array('attachment_no_msg', $to_fix))
1555
				{
1556
					$filename = getAttachmentFilename($row['filename'], $row['id_attach'], $row['id_folder'], false, $row['file_hash']);
1557
					@unlink($filename);
1558
				}
1559
			}
1560
			if ($smcFunc['db_num_rows']($result) != 0)
1561
				$to_fix[] = 'attachment_no_msg';
1562
			$smcFunc['db_free_result']($result);
1563
1564
			// Do we need to delete what we have?
1565
			if ($fix_errors && !empty($to_remove) && in_array('attachment_no_msg', $to_fix))
1566
				$smcFunc['db_query']('', '
1567
					DELETE FROM {db_prefix}attachments
1568
					WHERE id_attach IN ({array_int:to_remove})
1569
						AND id_member = {int:no_member}
1570
						AND attachment_type IN ({array_int:attach_thumb})',
1571
					array(
1572
						'to_remove' => $to_remove,
1573
						'no_member' => 0,
1574
						'attach_thumb' => array(0,3),
1575
					)
1576
				);
1577
1578
			pauseAttachmentMaintenance($to_fix, $thumbnails);
1579
		}
1580
1581
		$_GET['step'] = 5;
1582
		$_GET['substep'] = 0;
1583
		pauseAttachmentMaintenance($to_fix);
1584
	}
1585
1586
	// What about files who are not recorded in the database?
1587
	if ($_GET['step'] <= 5)
1588
	{
1589
		$attach_dirs = $modSettings['attachmentUploadDir'];
1590
1591
		$current_check = 0;
1592
		$max_checks = 500;
1593
		$files_checked = empty($_GET['substep']) ? 0 : $_GET['substep'];
1594
		foreach ($attach_dirs as $attach_dir)
1595
		{
1596
			if ($dir = @opendir($attach_dir))
1597
			{
1598
				while ($file = readdir($dir))
1599
				{
1600
					if (in_array($file, array('.', '..', '.htaccess', 'index.php')))
1601
						continue;
1602
1603
					if ($files_checked <= $current_check)
1604
					{
1605
						// Temporary file, get rid of it!
1606
						if (strpos($file, 'post_tmp_') !== false)
1607
						{
1608
							// Temp file is more than 5 hours old!
1609
							if (filemtime($attach_dir . '/' . $file) < time() - 18000)
1610
								@unlink($attach_dir . '/' . $file);
1611
						}
1612
						// That should be an attachment, let's check if we have it in the database
1613
						elseif (strpos($file, '_') !== false)
1614
						{
1615
							$attachID = (int) substr($file, 0, strpos($file, '_'));
1616
							if (!empty($attachID))
1617
							{
1618
								$request = $smcFunc['db_query']('', '
1619
									SELECT  id_attach
1620
									FROM {db_prefix}attachments
1621
									WHERE id_attach = {int:attachment_id}
1622
									LIMIT 1',
1623
									array(
1624
										'attachment_id' => $attachID,
1625
									)
1626
								);
1627
								if ($smcFunc['db_num_rows']($request) == 0)
1628
								{
1629
									if ($fix_errors && in_array('files_without_attachment', $to_fix))
1630
									{
1631
										@unlink($attach_dir . '/' . $file);
1632
									}
1633
									else
1634
									{
1635
										$context['repair_errors']['files_without_attachment']++;
1636
										$to_fix[] = 'files_without_attachment';
1637
									}
1638
								}
1639
								$smcFunc['db_free_result']($request);
1640
							}
1641
						}
1642
						else
1643
						{
1644
							if ($fix_errors && in_array('files_without_attachment', $to_fix))
1645
							{
1646
								@unlink($attach_dir . '/' . $file);
1647
							}
1648
							else
1649
							{
1650
								$context['repair_errors']['files_without_attachment']++;
1651
								$to_fix[] = 'files_without_attachment';
1652
							}
1653
						}
1654
					}
1655
					$current_check++;
1656
					$_GET['substep'] = $current_check;
1657
					if ($current_check - $files_checked >= $max_checks)
1658
						pauseAttachmentMaintenance($to_fix);
1659
				}
1660
				closedir($dir);
1661
			}
1662
		}
1663
1664
		$_GET['step'] = 5;
1665
		$_GET['substep'] = 0;
1666
		pauseAttachmentMaintenance($to_fix);
1667
	}
1668
1669
	// Got here we must be doing well - just the template! :D
1670
	$context['page_title'] = $txt['repair_attachments'];
1671
	$context[$context['admin_menu_name']]['current_subsection'] = 'maintenance';
1672
	$context['sub_template'] = 'attachment_repair';
1673
1674
	// What stage are we at?
1675
	$context['completed'] = $fix_errors ? true : false;
1676
	$context['errors_found'] = !empty($to_fix) ? true : false;
1677
1678
}
1679
1680
/**
1681
 * Function called in-between each round of attachments and avatar repairs.
1682
 * Called by repairAttachments().
1683
 * If repairAttachments() has more steps added, this function needs updated!
1684
 *
1685
 * @param array $to_fix IDs of attachments to fix
1686
 * @param int $max_substep The maximum substep to reach before pausing
1687
 */
1688
function pauseAttachmentMaintenance($to_fix, $max_substep = 0)
1689
{
1690
	global $context, $txt, $time_start;
1691
1692
	// Try get more time...
1693
	@set_time_limit(600);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for set_time_limit(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

1693
	/** @scrutinizer ignore-unhandled */ @set_time_limit(600);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1694
	if (function_exists('apache_reset_timeout'))
1695
		@apache_reset_timeout();
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for apache_reset_timeout(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

1695
		/** @scrutinizer ignore-unhandled */ @apache_reset_timeout();

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1696
1697
	// Have we already used our maximum time?
1698
	if ((time() - $time_start) < 3 || $context['starting_substep'] == $_GET['substep'])
1699
		return;
1700
1701
	$context['continue_get_data'] = '?action=admin;area=manageattachments;sa=repair' . (isset($_GET['fixErrors']) ? ';fixErrors' : '') . ';step=' . $_GET['step'] . ';substep=' . $_GET['substep'] . ';' . $context['session_var'] . '=' . $context['session_id'];
1702
	$context['page_title'] = $txt['not_done_title'];
1703
	$context['continue_post_data'] = '';
1704
	$context['continue_countdown'] = '2';
1705
	$context['sub_template'] = 'not_done';
1706
1707
	// Specific stuff to not break this template!
1708
	$context[$context['admin_menu_name']]['current_subsection'] = 'maintenance';
1709
1710
	// Change these two if more steps are added!
1711
	if (empty($max_substep))
1712
		$context['continue_percent'] = round(($_GET['step'] * 100) / 25);
1713
	else
1714
		$context['continue_percent'] = round(($_GET['step'] * 100 + ($_GET['substep'] * 100) / $max_substep) / 25);
1715
1716
	// Never more than 100%!
1717
	$context['continue_percent'] = min($context['continue_percent'], 100);
1718
1719
	$_SESSION['attachments_to_fix'] = $to_fix;
1720
	$_SESSION['attachments_to_fix2'] = $context['repair_errors'];
1721
1722
	obExit();
1723
}
1724
1725
/**
1726
 * Called from a mouse click, works out what we want to do with attachments and actions it.
1727
 */
1728
function ApproveAttach()
1729
{
1730
	global $smcFunc;
1731
1732
	// Security is our primary concern...
1733
	checkSession('get');
1734
1735
	// If it approve or delete?
1736
	$is_approve = !isset($_GET['sa']) || $_GET['sa'] != 'reject' ? true : false;
1737
1738
	$attachments = array();
1739
	// If we are approving all ID's in a message , get the ID's.
1740
	if ($_GET['sa'] == 'all' && !empty($_GET['mid']))
1741
	{
1742
		$id_msg = (int) $_GET['mid'];
1743
1744
		$request = $smcFunc['db_query']('', '
1745
			SELECT id_attach
1746
			FROM {db_prefix}attachments
1747
			WHERE id_msg = {int:id_msg}
1748
				AND approved = {int:is_approved}
1749
				AND attachment_type = {int:attachment_type}',
1750
			array(
1751
				'id_msg' => $id_msg,
1752
				'is_approved' => 0,
1753
				'attachment_type' => 0,
1754
			)
1755
		);
1756
		while ($row = $smcFunc['db_fetch_assoc']($request))
1757
			$attachments[] = $row['id_attach'];
1758
		$smcFunc['db_free_result']($request);
1759
	}
1760
	elseif (!empty($_GET['aid']))
1761
		$attachments[] = (int) $_GET['aid'];
1762
1763
	if (empty($attachments))
1764
		fatal_lang_error('no_access', false);
1765
1766
	// Now we have some ID's cleaned and ready to approve, but first - let's check we have permission!
1767
	$allowed_boards = boardsAllowedTo('approve_posts');
1768
1769
	// Validate the attachments exist and are the right approval state.
1770
	$request = $smcFunc['db_query']('', '
1771
		SELECT a.id_attach, m.id_board, m.id_msg, m.id_topic
1772
		FROM {db_prefix}attachments AS a
1773
			INNER JOIN {db_prefix}messages AS m ON (m.id_msg = a.id_msg)
1774
		WHERE a.id_attach IN ({array_int:attachments})
1775
			AND a.attachment_type = {int:attachment_type}
1776
			AND a.approved = {int:is_approved}',
1777
		array(
1778
			'attachments' => $attachments,
1779
			'attachment_type' => 0,
1780
			'is_approved' => 0,
1781
		)
1782
	);
1783
	$attachments = array();
1784
	while ($row = $smcFunc['db_fetch_assoc']($request))
1785
	{
1786
		// We can only add it if we can approve in this board!
1787
		if ($allowed_boards = array(0) || in_array($row['id_board'], $allowed_boards))
0 ignored issues
show
Comprehensibility introduced by
Consider adding parentheses for clarity. Current Interpretation: $allowed_boards = (array...rd'], $allowed_boards)), Probably Intended Meaning: ($allowed_boards = array...ard'], $allowed_boards)
Loading history...
1788
		{
1789
			$attachments[] = $row['id_attach'];
1790
1791
			// Also come up with the redirection URL.
1792
			$redirect = 'topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#msg' . $row['id_msg'];
1793
		}
1794
	}
1795
	$smcFunc['db_free_result']($request);
1796
1797
	if (empty($attachments))
1798
		fatal_lang_error('no_access', false);
1799
1800
	// Finally, we are there. Follow through!
1801
	if ($is_approve)
1802
	{
1803
		// Checked and deemed worthy.
1804
		ApproveAttachments($attachments);
1805
	}
1806
	else
1807
		removeAttachments(array('id_attach' => $attachments, 'do_logging' => true));
1808
1809
	// Return to the topic....
1810
	redirectexit($redirect);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $redirect does not seem to be defined for all execution paths leading up to this point.
Loading history...
1811
}
1812
1813
/**
1814
 * Approve an attachment, or maybe even more - no permission check!
1815
 *
1816
 * @param array $attachments The IDs of the attachments to approve
1817
 * @return void|int Returns 0 if the operation failed, otherwise returns nothing
1818
 */
1819
function ApproveAttachments($attachments)
1820
{
1821
	global $smcFunc;
1822
1823
	if (empty($attachments))
1824
		return 0;
1825
1826
	// For safety, check for thumbnails...
1827
	$request = $smcFunc['db_query']('', '
1828
		SELECT
1829
			a.id_attach, a.id_member, COALESCE(thumb.id_attach, 0) AS id_thumb
1830
		FROM {db_prefix}attachments AS a
1831
			LEFT JOIN {db_prefix}attachments AS thumb ON (thumb.id_attach = a.id_thumb)
1832
		WHERE a.id_attach IN ({array_int:attachments})
1833
			AND a.attachment_type = {int:attachment_type}',
1834
		array(
1835
			'attachments' => $attachments,
1836
			'attachment_type' => 0,
1837
		)
1838
	);
1839
	$attachments = array();
1840
	while ($row = $smcFunc['db_fetch_assoc']($request))
1841
	{
1842
		// Update the thumbnail too...
1843
		if (!empty($row['id_thumb']))
1844
			$attachments[] = $row['id_thumb'];
1845
1846
		$attachments[] = $row['id_attach'];
1847
	}
1848
	$smcFunc['db_free_result']($request);
1849
1850
	if (empty($attachments))
1851
		return 0;
1852
1853
	// Approving an attachment is not hard - it's easy.
1854
	$smcFunc['db_query']('', '
1855
		UPDATE {db_prefix}attachments
1856
		SET approved = {int:is_approved}
1857
		WHERE id_attach IN ({array_int:attachments})',
1858
		array(
1859
			'attachments' => $attachments,
1860
			'is_approved' => 1,
1861
		)
1862
	);
1863
1864
	// In order to log the attachments, we really need their message and filename
1865
	$request = $smcFunc['db_query']('', '
1866
		SELECT m.id_msg, a.filename
1867
		FROM {db_prefix}attachments AS a
1868
			INNER JOIN {db_prefix}messages AS m ON (a.id_msg = m.id_msg)
1869
		WHERE a.id_attach IN ({array_int:attachments})
1870
			AND a.attachment_type = {int:attachment_type}',
1871
		array(
1872
			'attachments' => $attachments,
1873
			'attachment_type' => 0,
1874
		)
1875
	);
1876
1877
	while ($row = $smcFunc['db_fetch_assoc']($request))
1878
		logAction(
1879
			'approve_attach',
1880
			array(
1881
				'message' => $row['id_msg'],
1882
				'filename' => preg_replace('~&amp;#(\\d{1,7}|x[0-9a-fA-F]{1,6});~', '&#\\1;', $smcFunc['htmlspecialchars']($row['filename'])),
1883
			)
1884
		);
1885
	$smcFunc['db_free_result']($request);
1886
1887
	// Remove from the approval queue.
1888
	$smcFunc['db_query']('', '
1889
		DELETE FROM {db_prefix}approval_queue
1890
		WHERE id_attach IN ({array_int:attachments})',
1891
		array(
1892
			'attachments' => $attachments,
1893
		)
1894
	);
1895
1896
	call_integration_hook('integrate_approve_attachments', array($attachments));
1897
}
1898
1899
/**
1900
 * This function lists and allows updating of multiple attachments paths.
1901
 */
1902
function ManageAttachmentPaths()
1903
{
1904
	global $modSettings, $scripturl, $context, $txt, $sourcedir, $boarddir, $smcFunc, $settings;
1905
1906
	// Since this needs to be done eventually.
1907
	if (!isset($modSettings['attachment_basedirectories']))
1908
		$modSettings['attachment_basedirectories'] = array();
1909
1910
	elseif (!is_array($modSettings['attachment_basedirectories']))
1911
		$modSettings['attachment_basedirectories'] = $smcFunc['json_decode']($modSettings['attachment_basedirectories'], true);
1912
1913
	$errors = array();
1914
1915
	// Saving?
1916
	if (isset($_REQUEST['save']))
1917
	{
1918
		checkSession();
1919
1920
		$_POST['current_dir'] = (int) $_POST['current_dir'];
1921
		$new_dirs = array();
1922
		foreach ($_POST['dirs'] as $id => $path)
1923
		{
1924
			$error = '';
1925
			$id = (int) $id;
1926
			if ($id < 1)
1927
				continue;
1928
1929
			// Sorry, these dirs are NOT valid
1930
			$invalid_dirs = array($boarddir, $settings['default_theme_dir'], $sourcedir);
1931
			if (in_array($path, $invalid_dirs))
1932
			{
1933
				$errors[] = $path . ': ' . $txt['attach_dir_invalid'];
1934
				continue;
1935
			}
1936
1937
			// Hmm, a new path maybe?
1938
			// Don't allow empty paths
1939
			if (!array_key_exists($id, $modSettings['attachmentUploadDir']) && !empty($path))
1940
			{
1941
				// or is it?
1942
				if (in_array($path, $modSettings['attachmentUploadDir']) || in_array($boarddir . DIRECTORY_SEPARATOR . $path, $modSettings['attachmentUploadDir']))
1943
				{
1944
						$errors[] = $path . ': ' . $txt['attach_dir_duplicate_msg'];
1945
						continue;
1946
				}
1947
				elseif (empty($path))
1948
				{
1949
					// Ignore this and set $id to one less
1950
					continue;
1951
				}
1952
1953
				// OK, so let's try to create it then.
1954
				require_once($sourcedir . '/Subs-Attachments.php');
1955
				if (automanage_attachments_create_directory($path))
1956
					$_POST['current_dir'] = $modSettings['currentAttachmentUploadDir'];
1957
				else
1958
					$errors[] = $path . ': ' . $txt[$context['dir_creation_error']];
1959
			}
1960
1961
			// Changing a directory name?
1962
			if (!empty($modSettings['attachmentUploadDir'][$id]) && !empty($path) && $path != $modSettings['attachmentUploadDir'][$id])
1963
			{
1964
				if ($path != $modSettings['attachmentUploadDir'][$id] && !is_dir($path))
1965
				{
1966
					if (!@rename($modSettings['attachmentUploadDir'][$id], $path))
1967
					{
1968
						$errors[] = $path . ': ' . $txt['attach_dir_no_rename'];
1969
						$path = $modSettings['attachmentUploadDir'][$id];
1970
					}
1971
				}
1972
				else
1973
				{
1974
					$errors[] = $path . ': ' . $txt['attach_dir_exists_msg'];
1975
					$path = $modSettings['attachmentUploadDir'][$id];
1976
				}
1977
1978
				// Update the base directory path
1979
				if (!empty($modSettings['attachment_basedirectories']) && array_key_exists($id, $modSettings['attachment_basedirectories']))
1980
				{
1981
					$base = $modSettings['basedirectory_for_attachments'] == $modSettings['attachmentUploadDir'][$id] ? $path : $modSettings['basedirectory_for_attachments'];
1982
1983
					$modSettings['attachment_basedirectories'][$id] = $path;
1984
					updateSettings(array(
1985
						'attachment_basedirectories' => $smcFunc['json_encode']($modSettings['attachment_basedirectories']),
1986
						'basedirectory_for_attachments' => $base,
1987
					));
1988
					$modSettings['attachment_basedirectories'] = $smcFunc['json_decode']($modSettings['attachment_basedirectories'], true);
1989
				}
1990
			}
1991
1992
			if (empty($path))
1993
			{
1994
				$path = $modSettings['attachmentUploadDir'][$id];
1995
1996
				// It's not a good idea to delete the current directory.
1997
				if ($id == (!empty($_POST['current_dir']) ? $_POST['current_dir'] : $modSettings['currentAttachmentUploadDir']))
1998
					$errors[] = $path . ': ' . $txt['attach_dir_is_current'];
1999
				// Or the current base directory
2000
				elseif (!empty($modSettings['basedirectory_for_attachments']) && $modSettings['basedirectory_for_attachments'] == $modSettings['attachmentUploadDir'][$id])
2001
					$errors[] = $path . ': ' . $txt['attach_dir_is_current_bd'];
2002
				else
2003
				{
2004
					// Let's not try to delete a path with files in it.
2005
					$request = $smcFunc['db_query']('', '
2006
						SELECT COUNT(id_attach) AS num_attach
2007
						FROM {db_prefix}attachments
2008
						WHERE id_folder = {int:id_folder}',
2009
						array(
2010
							'id_folder' => (int) $id,
2011
						)
2012
					);
2013
2014
					list ($num_attach) = $smcFunc['db_fetch_row']($request);
2015
					$smcFunc['db_free_result']($request);
2016
2017
					// A check to see if it's a used base dir.
2018
					if (!empty($modSettings['attachment_basedirectories']))
2019
					{
2020
						// Count any sub-folders.
2021
						foreach ($modSettings['attachmentUploadDir'] as $sub)
2022
							if (strpos($sub, $path . DIRECTORY_SEPARATOR) !== false)
2023
								$num_attach++;
2024
					}
2025
2026
					// It's safe to delete. So try to delete the folder also
2027
					if ($num_attach == 0)
2028
					{
2029
						if (is_dir($path))
2030
							$doit = true;
2031
						elseif (is_dir($boarddir . DIRECTORY_SEPARATOR . $path))
2032
						{
2033
							$doit = true;
2034
							$path = $boarddir . DIRECTORY_SEPARATOR . $path;
2035
						}
2036
2037
						if (isset($doit) && realpath($path) != realpath($boarddir))
2038
						{
2039
							unlink($path . '/.htaccess');
2040
							unlink($path . '/index.php');
2041
							if (!@rmdir($path))
2042
								$error = $path . ': ' . $txt['attach_dir_no_delete'];
2043
						}
2044
2045
						// Remove it from the base directory list.
2046
						if (empty($error) && !empty($modSettings['attachment_basedirectories']))
2047
						{
2048
							unset($modSettings['attachment_basedirectories'][$id]);
2049
							updateSettings(array('attachment_basedirectories' => $smcFunc['json_encode']($modSettings['attachment_basedirectories'])));
2050
							$modSettings['attachment_basedirectories'] = $smcFunc['json_decode']($modSettings['attachment_basedirectories'], true);
2051
						}
2052
					}
2053
					else
2054
						$error = $path . ': ' . $txt['attach_dir_no_remove'];
2055
2056
					if (empty($error))
2057
						continue;
2058
					else
2059
						$errors[] = $error;
2060
				}
2061
			}
2062
2063
			$new_dirs[$id] = $path;
2064
		}
2065
2066
		// We need to make sure the current directory is right.
2067
		if (empty($_POST['current_dir']) && !empty($modSettings['currentAttachmentUploadDir']))
2068
			$_POST['current_dir'] = $modSettings['currentAttachmentUploadDir'];
2069
2070
		// Find the current directory if there's no value carried,
2071
		if (empty($_POST['current_dir']) || empty($new_dirs[$_POST['current_dir']]))
2072
		{
2073
			if (array_key_exists($modSettings['currentAttachmentUploadDir'], $modSettings['attachmentUploadDir']))
2074
				$_POST['current_dir'] = $modSettings['currentAttachmentUploadDir'];
2075
			else
2076
				$_POST['current_dir'] = max(array_keys($modSettings['attachmentUploadDir']));
2077
		}
2078
2079
		// If the user wishes to go back, update the last_dir array
2080
		if ($_POST['current_dir'] != $modSettings['currentAttachmentUploadDir'] && !empty($modSettings['last_attachments_directory']) && (isset($modSettings['last_attachments_directory'][$_POST['current_dir']]) || isset($modSettings['last_attachments_directory'][0])))
2081
		{
2082
			if (!is_array($modSettings['last_attachments_directory']))
2083
				$modSettings['last_attachments_directory'] = $smcFunc['json_decode']($modSettings['last_attachments_directory'], true);
2084
			$num = substr(strrchr($modSettings['attachmentUploadDir'][$_POST['current_dir']], '_'), 1);
2085
2086
			if (is_numeric($num))
2087
			{
2088
				// Need to find the base folder.
2089
				$bid = -1;
2090
				$use_subdirectories_for_attachments = 0;
2091
				if (!empty($modSettings['attachment_basedirectories']))
2092
					foreach ($modSettings['attachment_basedirectories'] as $bid => $base)
2093
						if (strpos($modSettings['attachmentUploadDir'][$_POST['current_dir']], $base . DIRECTORY_SEPARATOR) !== false)
2094
						{
2095
							$use_subdirectories_for_attachments = 1;
2096
							break;
2097
						}
2098
2099
				if ($use_subdirectories_for_attachments == 0 && strpos($modSettings['attachmentUploadDir'][$_POST['current_dir']], $boarddir . DIRECTORY_SEPARATOR) !== false)
2100
					$bid = 0;
2101
2102
				$modSettings['last_attachments_directory'][$bid] = (int) $num;
2103
				$modSettings['basedirectory_for_attachments'] = !empty($modSettings['basedirectory_for_attachments']) ? $modSettings['basedirectory_for_attachments'] : '';
2104
				$modSettings['use_subdirectories_for_attachments'] = !empty($modSettings['use_subdirectories_for_attachments']) ? $modSettings['use_subdirectories_for_attachments'] : 0;
2105
				updateSettings(array(
2106
					'last_attachments_directory' => $smcFunc['json_encode']($modSettings['last_attachments_directory']),
2107
					'basedirectory_for_attachments' => $bid == 0 ? $modSettings['basedirectory_for_attachments'] : $modSettings['attachment_basedirectories'][$bid],
2108
					'use_subdirectories_for_attachments' => $use_subdirectories_for_attachments,
2109
				));
2110
			}
2111
		}
2112
2113
		// Going back to just one path?
2114
		if (count($new_dirs) == 1)
2115
		{
2116
			// We might need to reset the paths. This loop will just loop through once.
2117
			foreach ($new_dirs as $id => $dir)
2118
			{
2119
				if ($id != 1)
2120
					$smcFunc['db_query']('', '
2121
						UPDATE {db_prefix}attachments
2122
						SET id_folder = {int:default_folder}
2123
						WHERE id_folder = {int:current_folder}',
2124
						array(
2125
							'default_folder' => 1,
2126
							'current_folder' => $id,
2127
						)
2128
					);
2129
2130
				$update = array(
2131
					'currentAttachmentUploadDir' => 1,
2132
					'attachmentUploadDir' => $smcFunc['json_encode'](array(1 => $dir)),
2133
				);
2134
			}
2135
		}
2136
		else
2137
		{
2138
			// Save it to the database.
2139
			$update = array(
2140
				'currentAttachmentUploadDir' => $_POST['current_dir'],
2141
				'attachmentUploadDir' => $smcFunc['json_encode']($new_dirs),
2142
			);
2143
		}
2144
2145
		if (!empty($update))
2146
			updateSettings($update);
2147
2148
		if (!empty($errors))
2149
			$_SESSION['errors']['dir'] = $errors;
2150
2151
		redirectexit('action=admin;area=manageattachments;sa=attachpaths;' . $context['session_var'] . '=' . $context['session_id']);
2152
	}
2153
2154
	// Saving a base directory?
2155
	if (isset($_REQUEST['save2']))
2156
	{
2157
		checkSession();
2158
2159
		// Changing the current base directory?
2160
		$_POST['current_base_dir'] = isset($_POST['current_base_dir']) ? (int) $_POST['current_base_dir'] : 1;
2161
		if (empty($_POST['new_base_dir']) && !empty($_POST['current_base_dir']))
2162
		{
2163
			if ($modSettings['basedirectory_for_attachments'] != $modSettings['attachmentUploadDir'][$_POST['current_base_dir']])
2164
				$update = (array(
2165
					'basedirectory_for_attachments' => $modSettings['attachmentUploadDir'][$_POST['current_base_dir']],
2166
				));
2167
		}
2168
2169
		if (isset($_POST['base_dir']))
2170
		{
2171
			foreach ($_POST['base_dir'] as $id => $dir)
2172
			{
2173
				if (!empty($dir) && $dir != $modSettings['attachmentUploadDir'][$id])
2174
				{
2175
					if (@rename($modSettings['attachmentUploadDir'][$id], $dir))
2176
					{
2177
						$modSettings['attachmentUploadDir'][$id] = $dir;
2178
						$modSettings['attachment_basedirectories'][$id] = $dir;
2179
						$update = (array(
2180
							'attachmentUploadDir' => $smcFunc['json_encode']($modSettings['attachmentUploadDir']),
2181
							'attachment_basedirectories' => $smcFunc['json_encode']($modSettings['attachment_basedirectories']),
2182
							'basedirectory_for_attachments' => $modSettings['attachmentUploadDir'][$_POST['current_base_dir']],
2183
						));
2184
					}
2185
				}
2186
2187
				if (empty($dir))
2188
				{
2189
					if ($id == $_POST['current_base_dir'])
2190
					{
2191
						$errors[] = $modSettings['attachmentUploadDir'][$id] . ': ' . $txt['attach_dir_is_current'];
2192
						continue;
2193
					}
2194
2195
					unset($modSettings['attachment_basedirectories'][$id]);
2196
					$update = (array(
2197
						'attachment_basedirectories' => $smcFunc['json_encode']($modSettings['attachment_basedirectories']),
2198
						'basedirectory_for_attachments' => $modSettings['attachmentUploadDir'][$_POST['current_base_dir']],
2199
					));
2200
				}
2201
			}
2202
		}
2203
2204
		// Or adding a new one?
2205
		if (!empty($_POST['new_base_dir']))
2206
		{
2207
			require_once($sourcedir . '/Subs-Attachments.php');
2208
			$_POST['new_base_dir'] = $smcFunc['htmlspecialchars']($_POST['new_base_dir'], ENT_QUOTES);
2209
2210
			$current_dir = $modSettings['currentAttachmentUploadDir'];
2211
2212
			if (!in_array($_POST['new_base_dir'], $modSettings['attachmentUploadDir']))
2213
			{
2214
				if (!automanage_attachments_create_directory($_POST['new_base_dir']))
2215
					$errors[] = $_POST['new_base_dir'] . ': ' . $txt['attach_dir_base_no_create'];
2216
			}
2217
2218
			$modSettings['currentAttachmentUploadDir'] = array_search($_POST['new_base_dir'], $modSettings['attachmentUploadDir']);
2219
			if (!in_array($_POST['new_base_dir'], $modSettings['attachment_basedirectories']))
2220
				$modSettings['attachment_basedirectories'][$modSettings['currentAttachmentUploadDir']] = $_POST['new_base_dir'];
2221
			ksort($modSettings['attachment_basedirectories']);
2222
2223
			$update = (array(
2224
				'attachment_basedirectories' => $smcFunc['json_encode']($modSettings['attachment_basedirectories']),
2225
				'basedirectory_for_attachments' => $_POST['new_base_dir'],
2226
				'currentAttachmentUploadDir' => $current_dir,
2227
			));
2228
		}
2229
2230
		if (!empty($errors))
2231
			$_SESSION['errors']['base'] = $errors;
2232
2233
		if (!empty($update))
2234
			updateSettings($update);
2235
2236
		redirectexit('action=admin;area=manageattachments;sa=attachpaths;' . $context['session_var'] . '=' . $context['session_id']);
2237
	}
2238
2239
	if (isset($_SESSION['errors']))
2240
	{
2241
		if (is_array($_SESSION['errors']))
2242
		{
2243
			$errors = array();
2244
			if (!empty($_SESSION['errors']['dir']))
2245
				foreach ($_SESSION['errors']['dir'] as $error)
2246
					$errors['dir'][] = $smcFunc['htmlspecialchars']($error, ENT_QUOTES);
2247
2248
			if (!empty($_SESSION['errors']['base']))
2249
				foreach ($_SESSION['errors']['base'] as $error)
2250
					$errors['base'][] = $smcFunc['htmlspecialchars']($error, ENT_QUOTES);
2251
		}
2252
		unset($_SESSION['errors']);
2253
	}
2254
2255
	$listOptions = array(
2256
		'id' => 'attach_paths',
2257
		'base_href' => $scripturl . '?action=admin;area=manageattachments;sa=attachpaths;' . $context['session_var'] . '=' . $context['session_id'],
2258
		'title' => $txt['attach_paths'],
2259
		'get_items' => array(
2260
			'function' => 'list_getAttachDirs',
2261
		),
2262
		'columns' => array(
2263
			'current_dir' => array(
2264
				'header' => array(
2265
					'value' => $txt['attach_current'],
2266
					'class' => 'centercol',
2267
				),
2268
				'data' => array(
2269
					'function' => function($rowData)
2270
					{
2271
						return '<input type="radio" name="current_dir" value="' . $rowData['id'] . '"' . ($rowData['current'] ? ' checked' : '') . (!empty($rowData['disable_current']) ? ' disabled' : '') . '>';
2272
					},
2273
					'style' => 'width: 10%;',
2274
					'class' => 'centercol',
2275
				),
2276
			),
2277
			'path' => array(
2278
				'header' => array(
2279
					'value' => $txt['attach_path'],
2280
				),
2281
				'data' => array(
2282
					'function' => function($rowData)
2283
					{
2284
						return '<input type="hidden" name="dirs[' . $rowData['id'] . ']" value="' . $rowData['path'] . '"><input type="text" size="40" name="dirs[' . $rowData['id'] . ']" value="' . $rowData['path'] . '"' . (!empty($rowData['disable_base_dir']) ? ' disabled' : '') . ' style="width: 100%">';
2285
					},
2286
					'style' => 'width: 40%;',
2287
				),
2288
			),
2289
			'current_size' => array(
2290
				'header' => array(
2291
					'value' => $txt['attach_current_size'],
2292
				),
2293
				'data' => array(
2294
					'db' => 'current_size',
2295
					'style' => 'width: 15%;',
2296
				),
2297
			),
2298
			'num_files' => array(
2299
				'header' => array(
2300
					'value' => $txt['attach_num_files'],
2301
				),
2302
				'data' => array(
2303
					'db' => 'num_files',
2304
					'style' => 'width: 15%;',
2305
				),
2306
			),
2307
			'status' => array(
2308
				'header' => array(
2309
					'value' => $txt['attach_dir_status'],
2310
					'class' => 'centercol',
2311
				),
2312
				'data' => array(
2313
					'db' => 'status',
2314
					'style' => 'width: 25%;',
2315
					'class' => 'centercol',
2316
				),
2317
			),
2318
		),
2319
		'form' => array(
2320
			'href' => $scripturl . '?action=admin;area=manageattachments;sa=attachpaths;' . $context['session_var'] . '=' . $context['session_id'],
2321
		),
2322
		'additional_rows' => array(
2323
			array(
2324
				'position' => 'below_table_data',
2325
				'value' => '
2326
				<input type="hidden" name="' . $context['session_var'] . '" value="' . $context['session_id'] . '">
2327
				<input type="submit" name="save" value="' . $txt['save'] . '" class="button">
2328
				<input type="submit" name="new_path" value="' . $txt['attach_add_path'] . '" class="button">',
2329
			),
2330
			empty($errors['dir']) ? array(
2331
				'position' => 'top_of_list',
2332
				'value' => $txt['attach_dir_desc'],
2333
				'class' => 'information'
2334
			) : array(
2335
				'position' => 'top_of_list',
2336
				'value' => $txt['attach_dir_save_problem'] . '<br>' . implode('<br>', $errors['dir']),
2337
				'style' => 'padding-left: 35px;',
2338
				'class' => 'noticebox',
2339
			),
2340
		),
2341
	);
2342
	require_once($sourcedir . '/Subs-List.php');
2343
	createList($listOptions);
2344
2345
	if (!empty($modSettings['attachment_basedirectories']))
2346
	{
2347
		$listOptions2 = array(
2348
			'id' => 'base_paths',
2349
			'base_href' => $scripturl . '?action=admin;area=manageattachments;sa=attachpaths;' . $context['session_var'] . '=' . $context['session_id'],
2350
			'title' => $txt['attach_base_paths'],
2351
			'get_items' => array(
2352
				'function' => 'list_getBaseDirs',
2353
			),
2354
			'columns' => array(
2355
				'current_dir' => array(
2356
					'header' => array(
2357
						'value' => $txt['attach_current'],
2358
						'class' => 'centercol',
2359
					),
2360
					'data' => array(
2361
						'function' => function($rowData)
2362
						{
2363
							return '<input type="radio" name="current_base_dir" value="' . $rowData['id'] . '"' . ($rowData['current'] ? ' checked' : '') . '>';
2364
						},
2365
						'style' => 'width: 10%;',
2366
						'class' => 'centercol',
2367
					),
2368
				),
2369
				'path' => array(
2370
					'header' => array(
2371
						'value' => $txt['attach_path'],
2372
					),
2373
					'data' => array(
2374
						'db' => 'path',
2375
						'style' => 'width: 45%;',
2376
					),
2377
				),
2378
				'num_dirs' => array(
2379
					'header' => array(
2380
						'value' => $txt['attach_num_dirs'],
2381
					),
2382
					'data' => array(
2383
						'db' => 'num_dirs',
2384
						'style' => 'width: 15%;',
2385
					),
2386
				),
2387
				'status' => array(
2388
					'header' => array(
2389
						'value' => $txt['attach_dir_status'],
2390
					),
2391
					'data' => array(
2392
						'db' => 'status',
2393
						'style' => 'width: 15%;',
2394
						'class' => 'centercol',
2395
					),
2396
				),
2397
			),
2398
			'form' => array(
2399
				'href' => $scripturl . '?action=admin;area=manageattachments;sa=attachpaths;' . $context['session_var'] . '=' . $context['session_id'],
2400
			),
2401
			'additional_rows' => array(
2402
				array(
2403
					'position' => 'below_table_data',
2404
					'value' => '<input type="hidden" name="' . $context['session_var'] . '" value="' . $context['session_id'] . '"><input type="submit" name="save2" value="' . $txt['save'] . '" class="button">
2405
					<input type="submit" name="new_base_path" value="' . $txt['attach_add_path'] . '" class="button">',
2406
				),
2407
				empty($errors['base']) ? array(
2408
					'position' => 'top_of_list',
2409
					'value' => $txt['attach_dir_base_desc'],
2410
					'style' => 'padding: 5px 10px;',
2411
					'class' => 'windowbg smalltext'
2412
				) : array(
2413
					'position' => 'top_of_list',
2414
					'value' => $txt['attach_dir_save_problem'] . '<br>' . implode('<br>', $errors['base']),
2415
					'style' => 'padding-left: 35px',
2416
					'class' => 'noticebox',
2417
				),
2418
			),
2419
		);
2420
		createList($listOptions2);
2421
	}
2422
2423
	// Fix up our template.
2424
	$context[$context['admin_menu_name']]['current_subsection'] = 'attachpaths';
2425
	$context['page_title'] = $txt['attach_path_manage'];
2426
	$context['sub_template'] = 'attachment_paths';
2427
}
2428
2429
/**
2430
 * Prepare the actual attachment directories to be displayed in the list.
2431
 * @return array An array of information about the attachment directories
2432
 */
2433
function list_getAttachDirs()
2434
{
2435
	global $smcFunc, $modSettings, $context, $txt;
2436
2437
	$request = $smcFunc['db_query']('', '
2438
		SELECT id_folder, COUNT(id_attach) AS num_attach, SUM(size) AS size_attach
2439
		FROM {db_prefix}attachments
2440
		WHERE attachment_type != {int:type}
2441
		GROUP BY id_folder',
2442
		array(
2443
			'type' => 1,
2444
		)
2445
	);
2446
2447
	$expected_files = array();
2448
	$expected_size = array();
2449
	while ($row = $smcFunc['db_fetch_assoc']($request))
2450
	{
2451
		$expected_files[$row['id_folder']] = $row['num_attach'];
2452
		$expected_size[$row['id_folder']] = $row['size_attach'];
2453
	}
2454
	$smcFunc['db_free_result']($request);
2455
2456
	$attachdirs = array();
2457
	foreach ($modSettings['attachmentUploadDir'] as $id => $dir)
2458
	{
2459
		// If there aren't any attachments in this directory this won't exist.
2460
		if (!isset($expected_files[$id]))
2461
			$expected_files[$id] = 0;
2462
2463
		// Check if the directory is doing okay.
2464
		list ($status, $error, $files) = attachDirStatus($dir, $expected_files[$id]);
2465
2466
		// If it is one, let's show that it's a base directory.
2467
		$sub_dirs = 0;
2468
		$is_base_dir = false;
2469
		if (!empty($modSettings['attachment_basedirectories']))
2470
		{
2471
			$is_base_dir = in_array($dir, $modSettings['attachment_basedirectories']);
2472
2473
			// Count any sub-folders.
2474
			foreach ($modSettings['attachmentUploadDir'] as $sid => $sub)
2475
				if (strpos($sub, $dir . DIRECTORY_SEPARATOR) !== false)
2476
				{
2477
					$expected_files[$id]++;
2478
					$sub_dirs++;
2479
				}
2480
		}
2481
2482
		$attachdirs[] = array(
2483
			'id' => $id,
2484
			'current' => $id == $modSettings['currentAttachmentUploadDir'],
2485
			'disable_current' => isset($modSettings['automanage_attachments']) && $modSettings['automanage_attachments'] > 1,
2486
			'disable_base_dir' =>  $is_base_dir && $sub_dirs > 0 && !empty($files) && empty($error) && empty($save_errors),
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $save_errors seems to never exist and therefore empty should always be true.
Loading history...
2487
			'path' => $dir,
2488
			'current_size' => !empty($expected_size[$id]) ? comma_format($expected_size[$id] / 1024, 0) : 0,
2489
			'num_files' => comma_format($expected_files[$id] - $sub_dirs, 0) . ($sub_dirs > 0 ? ' (' . $sub_dirs . ')' : ''),
2490
			'status' => ($is_base_dir ? $txt['attach_dir_basedir'] . '<br>' : '') . ($error ? '<div class="error">' : '') . sprintf($txt['attach_dir_' . $status], $context['session_id'], $context['session_var']) . ($error ? '</div>' : ''),
2491
		);
2492
	}
2493
2494
	// Just stick a new directory on at the bottom.
2495
	if (isset($_REQUEST['new_path']))
2496
		$attachdirs[] = array(
2497
			'id' => max(array_merge(array_keys($expected_files), array_keys($modSettings['attachmentUploadDir']))) + 1,
2498
			'current' => false,
2499
			'path' => '',
2500
			'current_size' => '',
2501
			'num_files' => '',
2502
			'status' => '',
2503
		);
2504
2505
	return $attachdirs;
2506
}
2507
2508
/**
2509
 * Prepare the base directories to be displayed in a list.
2510
 * @return void|array Returns nothing if there are no base directories, otherwise returns an array of info about the directories
2511
 */
2512
function list_getBaseDirs()
2513
{
2514
	global $modSettings, $txt;
2515
2516
	if (empty($modSettings['attachment_basedirectories']))
2517
		return;
2518
2519
	$basedirs = array();
2520
	// Get a list of the base directories.
2521
	foreach ($modSettings['attachment_basedirectories'] as $id => $dir)
2522
	{
2523
		// Loop through the attach directory array to count any sub-directories
2524
		$expected_dirs = 0;
2525
		foreach ($modSettings['attachmentUploadDir'] as $sid => $sub)
2526
			if (strpos($sub, $dir . DIRECTORY_SEPARATOR) !== false)
2527
				$expected_dirs++;
2528
2529
		if (!is_dir($dir))
2530
			$status = 'does_not_exist';
2531
		elseif (!is_writeable($dir))
2532
			$status = 'not_writable';
2533
		else
2534
			$status = 'ok';
2535
2536
		$basedirs[] = array(
2537
			'id' => $id,
2538
			'current' => $dir == $modSettings['basedirectory_for_attachments'],
2539
			'path' => $expected_dirs > 0 ? $dir : ('<input type="text" name="base_dir[' . $id . ']" value="' . $dir . '" size="40">'),
2540
			'num_dirs' => $expected_dirs,
2541
			'status' => $status == 'ok' ? $txt['attach_dir_ok'] : ('<span class="error">' . $txt['attach_dir_' . $status] . '</span>'),
2542
		);
2543
	}
2544
2545
	if (isset($_REQUEST['new_base_path']))
2546
		$basedirs[] = array(
2547
			'id' => '',
2548
			'current' => false,
2549
			'path' => '<input type="text" name="new_base_dir" value="" size="40">',
2550
			'num_dirs' => '',
2551
			'status' => '',
2552
		);
2553
2554
	return $basedirs;
2555
}
2556
2557
/**
2558
 * Checks the status of an attachment directory and returns an array
2559
 *  of the status key, if that status key signifies an error, and
2560
 *  the file count.
2561
 *
2562
 * @param string $dir The directory to check
2563
 * @param int $expected_files How many files should be in that directory
2564
 * @return array An array containing the status of the directory, whether the number of files was what we expected and how many were in the directory
2565
 */
2566
function attachDirStatus($dir, $expected_files)
2567
{
2568
	if (!is_dir($dir))
2569
		return array('does_not_exist', true, '');
2570
	elseif (!is_writable($dir))
2571
		return array('not_writable', true, '');
2572
2573
	// Everything is okay so far, start to scan through the directory.
2574
	$num_files = 0;
2575
	$dir_handle = dir($dir);
2576
	while ($file = $dir_handle->read())
2577
	{
2578
		// Now do we have a real file here?
2579
		if (in_array($file, array('.', '..', '.htaccess', 'index.php')))
2580
			continue;
2581
2582
		$num_files++;
2583
	}
2584
	$dir_handle->close();
2585
2586
	if ($num_files < $expected_files)
2587
		return array('files_missing', true, $num_files);
2588
	// Empty?
2589
	elseif ($expected_files == 0)
2590
		return array('unused', false, $num_files);
2591
	// All good!
2592
	else
2593
		return array('ok', false, $num_files);
2594
}
2595
2596
/**
2597
 * Maintance function to move attachments from one directory to another
2598
 */
2599
function TransferAttachments()
2600
{
2601
	global $modSettings, $smcFunc, $sourcedir, $txt, $boarddir;
2602
2603
	checkSession();
2604
2605
	$modSettings['attachmentUploadDir'] = $smcFunc['json_decode']($modSettings['attachmentUploadDir'], true);
2606
	if (!empty($modSettings['attachment_basedirectories']))
2607
		$modSettings['attachment_basedirectories'] = $smcFunc['json_decode']($modSettings['attachment_basedirectories'], true);
2608
	else
2609
		$modSettings['basedirectory_for_attachments'] = array();
2610
2611
	$_POST['from'] = (int) $_POST['from'];
2612
	$_POST['auto'] = !empty($_POST['auto']) ? (int) $_POST['auto'] : 0;
2613
	$_POST['to'] = (int) $_POST['to'];
2614
	$start = !empty($_POST['empty_it']) ? 0 : $modSettings['attachmentDirFileLimit'];
2615
	$_SESSION['checked'] = !empty($_POST['empty_it']) ? true : false;
2616
	$limit = 501;
2617
	$results = array();
2618
	$dir_files = 0;
2619
	$current_progress = 0;
2620
	$total_moved = 0;
2621
	$total_not_moved = 0;
2622
2623
	if (empty($_POST['from']) || (empty($_POST['auto']) && empty($_POST['to'])))
2624
		$results[] = $txt['attachment_transfer_no_dir'];
2625
2626
	if ($_POST['from'] == $_POST['to'])
2627
		$results[] = $txt['attachment_transfer_same_dir'];
2628
2629
	if (empty($results))
2630
	{
2631
		// Get the total file count for the progess bar.
2632
		$request = $smcFunc['db_query']('', '
2633
			SELECT COUNT(*)
2634
			FROM {db_prefix}attachments
2635
			WHERE id_folder = {int:folder_id}
2636
				AND attachment_type != {int:attachment_type}',
2637
			array(
2638
				'folder_id' => $_POST['from'],
2639
				'attachment_type' => 1,
2640
			)
2641
		);
2642
		list ($total_progress) = $smcFunc['db_fetch_row']($request);
2643
		$smcFunc['db_free_result']($request);
2644
		$total_progress -= $start;
2645
2646
		if ($total_progress < 1)
2647
			$results[] = $txt['attachment_transfer_no_find'];
2648
	}
2649
2650
	if (empty($results))
2651
	{
2652
		// Where are they going?
2653
		if (!empty($_POST['auto']))
2654
		{
2655
			require_once($sourcedir . '/Subs-Attachments.php');
2656
2657
			$modSettings['automanage_attachments'] = 1;
2658
			$modSettings['use_subdirectories_for_attachments'] = $_POST['auto'] == -1 ? 0 : 1;
2659
			$modSettings['basedirectory_for_attachments'] = $_POST['auto'] > 0 ? $modSettings['attachmentUploadDir'][$_POST['auto']] : $modSettings['basedirectory_for_attachments'];
2660
2661
			automanage_attachments_check_directory();
2662
			$new_dir = $modSettings['currentAttachmentUploadDir'];
2663
		}
2664
		else
2665
			$new_dir = $_POST['to'];
2666
2667
		$modSettings['currentAttachmentUploadDir'] = $new_dir;
2668
2669
		$break = false;
2670
		while ($break == false)
2671
		{
2672
			@set_time_limit(300);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for set_time_limit(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

2672
			/** @scrutinizer ignore-unhandled */ @set_time_limit(300);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2673
			if (function_exists('apache_reset_timeout'))
2674
				@apache_reset_timeout();
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for apache_reset_timeout(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

2674
				/** @scrutinizer ignore-unhandled */ @apache_reset_timeout();

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2675
2676
			// If limits are set, get the file count and size for the destination folder
2677
			if ($dir_files <= 0 && (!empty($modSettings['attachmentDirSizeLimit']) || !empty($modSettings['attachmentDirFileLimit'])))
2678
			{
2679
				$request = $smcFunc['db_query']('', '
2680
					SELECT COUNT(*), SUM(size)
2681
					FROM {db_prefix}attachments
2682
					WHERE id_folder = {int:folder_id}
2683
						AND attachment_type != {int:attachment_type}',
2684
					array(
2685
						'folder_id' => $new_dir,
2686
						'attachment_type' => 1,
2687
					)
2688
				);
2689
				list ($dir_files, $dir_size) = $smcFunc['db_fetch_row']($request);
2690
				$smcFunc['db_free_result']($request);
2691
			}
2692
2693
			// Find some attachments to move
2694
			$request = $smcFunc['db_query']('', '
2695
				SELECT id_attach, filename, id_folder, file_hash, size
2696
				FROM {db_prefix}attachments
2697
				WHERE id_folder = {int:folder}
2698
					AND attachment_type != {int:attachment_type}
2699
				LIMIT {int:start}, {int:limit}',
2700
				array(
2701
					'folder' => $_POST['from'],
2702
					'attachment_type' => 1,
2703
					'start' => $start,
2704
					'limit' => $limit,
2705
				)
2706
			);
2707
2708
			if ($smcFunc['db_num_rows']($request) === 0)
2709
			{
2710
				if (empty($current_progress))
2711
					$results[] = $txt['attachment_transfer_no_find'];
2712
				break;
2713
			}
2714
2715
			if ($smcFunc['db_num_rows']($request) < $limit)
2716
				$break = true;
2717
2718
			// Move them
2719
			$moved = array();
2720
			while ($row = $smcFunc['db_fetch_assoc']($request))
2721
			{
2722
				$source = getAttachmentFilename($row['filename'], $row['id_attach'], $row['id_folder'], false, $row['file_hash']);
2723
				$dest = $modSettings['attachmentUploadDir'][$new_dir] . '/' . basename($source);
2724
2725
				// Size and file count check
2726
				if (!empty($modSettings['attachmentDirSizeLimit']) || !empty($modSettings['attachmentDirFileLimit']))
2727
				{
2728
					$dir_files++;
2729
					$dir_size += !empty($row['size']) ? $row['size'] : filesize($source);
2730
2731
					// If we've reached a limit. Do something.
2732
					if (!empty($modSettings['attachmentDirSizeLimit']) && $dir_size > $modSettings['attachmentDirSizeLimit'] * 1024 || (!empty($modSettings['attachmentDirFileLimit']) && $dir_files > $modSettings['attachmentDirFileLimit']))
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: (! empty($modSettings['a...ttachmentDirFileLimit'], Probably Intended Meaning: ! empty($modSettings['at...tachmentDirFileLimit'])
Loading history...
2733
					{
2734
						if (!empty($_POST['auto']))
2735
						{
2736
							// Since we're in auto mode. Create a new folder and reset the counters.
2737
							automanage_attachments_by_space();
2738
2739
							$results[] = sprintf($txt['attachments_transferred'], $total_moved, $modSettings['attachmentUploadDir'][$new_dir]);
2740
							if (!empty($total_not_moved))
2741
								$results[] = sprintf($txt['attachments_not_transferred'], $total_not_moved);
2742
2743
							$dir_files = 0;
2744
							$total_moved = 0;
2745
							$total_not_moved = 0;
2746
2747
							$break = false;
2748
							break;
2749
						}
2750
						else
2751
						{
2752
							// Hmm, not in auto. Time to bail out then...
2753
							$results[] = $txt['attachment_transfer_no_room'];
2754
							$break = true;
2755
							break;
2756
						}
2757
					}
2758
				}
2759
2760
				if (@rename($source, $dest))
2761
				{
2762
					$total_moved++;
2763
					$current_progress++;
2764
					$moved[] = $row['id_attach'];
2765
				}
2766
				else
2767
					$total_not_moved++;
2768
			}
2769
			$smcFunc['db_free_result']($request);
2770
2771
			if (!empty($moved))
2772
			{
2773
				// Update the database
2774
				$smcFunc['db_query']('', '
2775
					UPDATE {db_prefix}attachments
2776
					SET id_folder = {int:new}
2777
					WHERE id_attach IN ({array_int:attachments})',
2778
					array(
2779
						'attachments' => $moved,
2780
						'new' => $new_dir,
2781
					)
2782
				);
2783
			}
2784
2785
			$new_dir = $modSettings['currentAttachmentUploadDir'];
2786
2787
			// Create the progress bar.
2788
			if (!$break)
2789
			{
2790
				$percent_done = min(round($current_progress / $total_progress * 100, 0), 100);
2791
				$prog_bar = '
2792
					<div class="progress_bar">
2793
						<div class="bar" style="width: ' . $percent_done . '%;"></div>
2794
						<span>' . $percent_done . '%</span>
2795
					</div>';
2796
				// Write it to a file so it can be displayed
2797
				$fp = fopen($boarddir . '/progress.php', "w");
2798
				fwrite($fp, $prog_bar);
2799
				fclose($fp);
2800
				usleep(500000);
2801
			}
2802
		}
2803
2804
		$results[] = sprintf($txt['attachments_transferred'], $total_moved, $modSettings['attachmentUploadDir'][$new_dir]);
2805
		if (!empty($total_not_moved))
2806
			$results[] = sprintf($txt['attachments_not_transferred'], $total_not_moved);
2807
	}
2808
2809
	$_SESSION['results'] = $results;
2810
	if (file_exists($boarddir . '/progress.php'))
2811
		unlink($boarddir . '/progress.php');
2812
2813
	redirectexit('action=admin;area=manageattachments;sa=maintenance#transfer');
2814
}
2815
2816
?>