comparison forum/Sources/ManageAttachments.php @ 76:e3e11437ecea website

Add forum code
author Chris Cannam
date Sun, 07 Jul 2013 11:25:48 +0200
parents
children
comparison
equal deleted inserted replaced
75:72f59aa7e503 76:e3e11437ecea
1 <?php
2
3 /**
4 * Simple Machines Forum (SMF)
5 *
6 * @package SMF
7 * @author Simple Machines http://www.simplemachines.org
8 * @copyright 2011 Simple Machines
9 * @license http://www.simplemachines.org/about/smf/license.php BSD
10 *
11 * @version 2.0
12 */
13
14 if (!defined('SMF'))
15 die('Hacking attempt...');
16
17 /* /!!!
18
19 void ManageAttachments()
20 - main 'Attachments and Avatars' center function.
21 - entry point for index.php?action=admin;area=manageattachments.
22 - requires the manage_attachments permission.
23 - load the ManageAttachments template.
24 - uses the Admin language file.
25 - uses the template layer 'manage_files' for showing the tab bar.
26 - calls a function based on the sub-action.
27
28 void ManageAttachmentSettings()
29 - show/change attachment settings.
30 - default sub action for the 'Attachments and Avatars' center.
31 - uses the 'attachments' sub template.
32 - called by index.php?action=admin;area=manageattachments;sa=attachements.
33
34 void ManageAvatarSettings()
35 - show/change avatar settings.
36 - called by index.php?action=admin;area=manageattachments;sa=avatars.
37 - uses the 'avatars' sub template.
38 - show/set permissions for permissions: 'profile_server_avatar',
39 'profile_upload_avatar' and 'profile_remote_avatar'.
40
41 void BrowseFiles()
42 - show a list of attachment or avatar files.
43 - called by ?action=admin;area=manageattachments;sa=browse for attachments and
44 ?action=admin;area=manageattachments;sa=browse;avatars for avatars.
45 - uses the 'browse' sub template
46 - allows sorting by name, date, size and member.
47 - paginates results.
48
49 void MaintainFiles()
50 - show several file maintenance options.
51 - called by ?action=admin;area=manageattachments;sa=maintain.
52 - uses the 'maintain' sub template.
53 - calculates file statistics (total file size, number of attachments,
54 number of avatars, attachment space available).
55
56 void MoveAvatars()
57 - move avatars from or to the attachment directory.
58 - called from the maintenance screen by
59 ?action=admin;area=manageattachments;sa=moveAvatars.
60
61 void RemoveAttachmentByAge()
62 - remove attachments older than a given age.
63 - called from the maintenance screen by
64 ?action=admin;area=manageattachments;sa=byAge.
65 - optionally adds a certain text to the messages the attachments were
66 removed from.
67
68 void RemoveAttachmentBySize()
69 - remove attachments larger than a given size.
70 - called from the maintenance screen by
71 ?action=admin;area=manageattachments;sa=bySize.
72 - optionally adds a certain text to the messages the attachments were
73 removed from.
74
75 void RemoveAttachment()
76 - remove a selection of attachments or avatars.
77 - called from the browse screen as submitted form by
78 ?action=admin;area=manageattachments;sa=remove
79
80 void RemoveAllAttachments()
81 - removes all attachments in a single click
82 - called from the maintenance screen by
83 ?action=admin;area=manageattachments;sa=removeall.
84
85 array removeAttachments(array condition, string query_type = '', bool return_affected_messages = false, bool autoThumbRemoval = true)
86 - removes attachments or avatars based on a given query condition.
87 - called by several remove avatar/attachment functions in this file.
88 - removes attachments based that match the $condition.
89 - allows query_types 'messages' and 'members', whichever is need by the
90 $condition parameter.
91
92 void RepairAttachments()
93 // !!!
94
95 void PauseAttachmentMaintenance()
96 // !!!
97
98 void ApproveAttach()
99 // !!!
100
101 void ApproveAttachments()
102 // !!!
103 */
104
105 // The main attachment management function.
106 function ManageAttachments()
107 {
108 global $txt, $modSettings, $scripturl, $context, $options;
109
110 // You have to be able to moderate the forum to do this.
111 isAllowedTo('manage_attachments');
112
113 // Setup the template stuff we'll probably need.
114 loadTemplate('ManageAttachments');
115
116 // If they want to delete attachment(s), delete them. (otherwise fall through..)
117 $subActions = array(
118 'attachments' => 'ManageAttachmentSettings',
119 'attachpaths' => 'ManageAttachmentPaths',
120 'avatars' => 'ManageAvatarSettings',
121 'browse' => 'BrowseFiles',
122 'byAge' => 'RemoveAttachmentByAge',
123 'bySize' => 'RemoveAttachmentBySize',
124 'maintenance' => 'MaintainFiles',
125 'moveAvatars' => 'MoveAvatars',
126 'repair' => 'RepairAttachments',
127 'remove' => 'RemoveAttachment',
128 'removeall' => 'RemoveAllAttachments'
129 );
130
131 // Pick the correct sub-action.
132 if (isset($_REQUEST['sa']) && isset($subActions[$_REQUEST['sa']]))
133 $context['sub_action'] = $_REQUEST['sa'];
134 else
135 $context['sub_action'] = 'browse';
136
137 // Default page title is good.
138 $context['page_title'] = $txt['attachments_avatars'];
139
140 // This uses admin tabs - as it should!
141 $context[$context['admin_menu_name']]['tab_data'] = array(
142 'title' => $txt['attachments_avatars'],
143 'help' => 'manage_files',
144 'description' => $txt['attachments_desc'],
145 );
146
147 // Finally fall through to what we are doing.
148 $subActions[$context['sub_action']]();
149 }
150
151 function ManageAttachmentSettings($return_config = false)
152 {
153 global $txt, $modSettings, $scripturl, $context, $options, $sourcedir;
154
155 $context['valid_upload_dir'] = is_dir($modSettings['attachmentUploadDir']) && is_writable($modSettings['attachmentUploadDir']);
156
157 // Perform a test to see if the GD module is installed.
158 $testGD = get_extension_funcs('gd');
159
160 $config_vars = array(
161 array('title', 'attachment_manager_settings'),
162 // Are attachments enabled?
163 array('select', 'attachmentEnable', array($txt['attachmentEnable_deactivate'], $txt['attachmentEnable_enable_all'], $txt['attachmentEnable_disable_new'])),
164 '',
165 // Extension checks etc.
166 array('check', 'attachmentCheckExtensions'),
167 array('text', 'attachmentExtensions', 40),
168 array('check', 'attachmentRecodeLineEndings'),
169 '',
170 // Directory and size limits.
171 empty($modSettings['currentAttachmentUploadDir']) ? array('text', 'attachmentUploadDir', 40, 'invalid' => !$context['valid_upload_dir']) : array('var_message', 'attachmentUploadDir_multiple', 'message' => 'attachmentUploadDir_multiple_configure'),
172 array('text', 'attachmentDirSizeLimit', 6, 'postinput' => $txt['kilobyte']),
173 array('text', 'attachmentPostLimit', 6, 'postinput' => $txt['kilobyte']),
174 array('text', 'attachmentSizeLimit', 6, 'postinput' => $txt['kilobyte']),
175 array('text', 'attachmentNumPerPostLimit', 6),
176 '',
177 // Image settings.
178 array('warning', empty($testGD) ? 'attachment_gd_warning' : ''),
179 array('check', 'attachment_image_reencode'),
180 '',
181 array('warning', 'attachment_image_paranoid_warning'),
182 array('check', 'attachment_image_paranoid'),
183 '',
184 // Thumbnail settings.
185 array('check', 'attachmentShowImages'),
186 array('check', 'attachmentThumbnails'),
187 array('check', 'attachment_thumb_png'),
188 array('text', 'attachmentThumbWidth', 6),
189 array('text', 'attachmentThumbHeight', 6),
190 );
191
192 if ($return_config)
193 return $config_vars;
194
195 // These are very likely to come in handy! (i.e. without them we're doomed!)
196 require_once($sourcedir . '/ManagePermissions.php');
197 require_once($sourcedir . '/ManageServer.php');
198
199 // Saving settings?
200 if (isset($_GET['save']))
201 {
202 checkSession();
203
204 saveDBSettings($config_vars);
205 redirectexit('action=admin;area=manageattachments;sa=attachments');
206 }
207
208 $context['post_url'] = $scripturl . '?action=admin;area=manageattachments;save;sa=attachments';
209 prepareDBSettingContext($config_vars);
210
211 $context['sub_template'] = 'show_settings';
212 }
213
214 function ManageAvatarSettings($return_config = false)
215 {
216 global $txt, $context, $modSettings, $sourcedir, $scripturl;
217
218 // Perform a test to see if the GD module is installed.
219 $testGD = get_extension_funcs('gd');
220
221 $context['valid_avatar_dir'] = is_dir($modSettings['avatar_directory']);
222 $context['valid_custom_avatar_dir'] = empty($modSettings['custom_avatar_enabled']) || (!empty($modSettings['custom_avatar_dir']) && is_dir($modSettings['custom_avatar_dir']) && is_writable($modSettings['custom_avatar_dir']));
223
224 $config_vars = array(
225 // Server stored avatars!
226 array('title', 'avatar_server_stored'),
227 array('warning', empty($testGD) ? 'avatar_gd_warning' : ''),
228 array('permissions', 'profile_server_avatar', 0, $txt['avatar_server_stored_groups']),
229 array('text', 'avatar_directory', 40, 'invalid' => !$context['valid_avatar_dir']),
230 array('text', 'avatar_url', 40),
231 // External avatars?
232 array('title', 'avatar_external'),
233 array('permissions', 'profile_remote_avatar', 0, $txt['avatar_external_url_groups']),
234 array('check', 'avatar_download_external', 0, 'onchange' => 'fUpdateStatus();'),
235 array('text', 'avatar_max_width_external', 6),
236 array('text', 'avatar_max_height_external', 6),
237 array('select', 'avatar_action_too_large',
238 array(
239 'option_refuse' => $txt['option_refuse'],
240 'option_html_resize' => $txt['option_html_resize'],
241 'option_js_resize' => $txt['option_js_resize'],
242 'option_download_and_resize' => $txt['option_download_and_resize'],
243 ),
244 ),
245 // Uploadable avatars?
246 array('title', 'avatar_upload'),
247 array('permissions', 'profile_upload_avatar', 0, $txt['avatar_upload_groups']),
248 array('text', 'avatar_max_width_upload', 6),
249 array('text', 'avatar_max_height_upload', 6),
250 array('check', 'avatar_resize_upload', 'subtext' => $txt['avatar_resize_upload_note']),
251 array('check', 'avatar_reencode'),
252 '',
253 array('warning', 'avatar_paranoid_warning'),
254 array('check', 'avatar_paranoid'),
255 '',
256 array('check', 'avatar_download_png'),
257 array('select', 'custom_avatar_enabled', array($txt['option_attachment_dir'], $txt['option_specified_dir']), 'onchange' => 'fUpdateStatus();'),
258 array('text', 'custom_avatar_dir', 40, 'subtext' => $txt['custom_avatar_dir_desc'], 'invalid' => !$context['valid_custom_avatar_dir']),
259 array('text', 'custom_avatar_url', 40),
260 );
261
262 if ($return_config)
263 return $config_vars;
264
265 // We need these files for the inline permission settings, and the settings template.
266 require_once($sourcedir . '/ManagePermissions.php');
267 require_once($sourcedir . '/ManageServer.php');
268
269 // Saving avatar settings?
270 if (isset($_GET['save']))
271 {
272 checkSession();
273
274 // Just incase the admin forgot to set both custom avatar values, we disable it to prevent errors.
275 if (isset($_POST['custom_avatar_enabled']) && $_POST['custom_avatar_enabled'] == 1 && (empty($_POST['custom_avatar_dir']) || empty($_POST['custom_avatar_url'])))
276 $_POST['custom_avatar_enabled'] = 0;
277
278 saveDBSettings($config_vars);
279 redirectexit('action=admin;area=manageattachments;sa=avatars');
280 }
281
282 // Attempt to figure out if the admin is trying to break things.
283 $context['settings_save_onclick'] = 'return document.getElementById(\'custom_avatar_enabled\').value == 1 && (document.getElementById(\'custom_avatar_dir\').value == \'\' || document.getElementById(\'custom_avatar_url\').value == \'\') ? confirm(\'' . $txt['custom_avatar_check_empty'] . '\') : true;';
284
285 // Prepare the context.
286 $context['post_url'] = $scripturl . '?action=admin;area=manageattachments;save;sa=avatars';
287 prepareDBSettingContext($config_vars);
288
289 // Add a layer for the javascript.
290 $context['template_layers'][] = 'avatar_settings';
291 $context['sub_template'] = 'show_settings';
292 }
293
294 function BrowseFiles()
295 {
296 global $context, $txt, $scripturl, $options, $modSettings;
297 global $smcFunc, $sourcedir;
298
299 $context['sub_template'] = 'browse';
300
301 // Attachments or avatars?
302 $context['browse_type'] = isset($_REQUEST['avatars']) ? 'avatars' : (isset($_REQUEST['thumbs']) ? 'thumbs' : 'attachments');
303
304 // Set the options for the list component.
305 $listOptions = array(
306 'id' => 'file_list',
307 'title' => $txt['attachment_manager_' . ($context['browse_type'] === 'avatars' ? 'avatars' : ( $context['browse_type'] === 'thumbs' ? 'thumbs' : 'attachments'))],
308 'items_per_page' => $modSettings['defaultMaxMessages'],
309 'base_href' => $scripturl . '?action=admin;area=manageattachments;sa=browse' . ($context['browse_type'] === 'avatars' ? ';avatars' : ($context['browse_type'] === 'thumbs' ? ';thumbs' : '')),
310 'default_sort_col' => 'name',
311 'no_items_label' => $txt['attachment_manager_' . ($context['browse_type'] === 'avatars' ? 'avatars' : ( $context['browse_type'] === 'thumbs' ? 'thumbs' : 'attachments')) . '_no_entries'],
312 'get_items' => array(
313 'function' => 'list_getFiles',
314 'params' => array(
315 $context['browse_type'],
316 ),
317 ),
318 'get_count' => array(
319 'function' => 'list_getNumFiles',
320 'params' => array(
321 $context['browse_type'],
322 ),
323 ),
324 'columns' => array(
325 'name' => array(
326 'header' => array(
327 'value' => $txt['attachment_name'],
328 ),
329 'data' => array(
330 'function' => create_function('$rowData', '
331 global $modSettings, $context, $scripturl;
332
333 $link = \'<a href="\';
334
335 // In case of a custom avatar URL attachments have a fixed directory.
336 if ($rowData[\'attachment_type\'] == 1)
337 $link .= sprintf(\'%1$s/%2$s\', $modSettings[\'custom_avatar_url\'], $rowData[\'filename\']);
338
339 // By default avatars are downloaded almost as attachments.
340 elseif ($context[\'browse_type\'] == \'avatars\')
341 $link .= sprintf(\'%1$s?action=dlattach;type=avatar;attach=%2$d\', $scripturl, $rowData[\'id_attach\']);
342
343 // Normal attachments are always linked to a topic ID.
344 else
345 $link .= sprintf(\'%1$s?action=dlattach;topic=%2$d.0;attach=%3$d\', $scripturl, $rowData[\'id_topic\'], $rowData[\'id_attach\']);
346
347 $link .= \'"\';
348
349 // Show a popup on click if it\'s a picture and we know its dimensions.
350 if (!empty($rowData[\'width\']) && !empty($rowData[\'height\']))
351 $link .= sprintf(\' onclick="return reqWin(this.href\' . ($rowData[\'attachment_type\'] == 1 ? \'\' : \' + \\\';image\\\'\') . \', %1$d, %2$d, true);"\', $rowData[\'width\'] + 20, $rowData[\'height\'] + 20);
352
353 $link .= sprintf(\'>%1$s</a>\', preg_replace(\'~&amp;#(\\\\d{1,7}|x[0-9a-fA-F]{1,6});~\', \'&#\\\\1;\', htmlspecialchars($rowData[\'filename\'])));
354
355 // Show the dimensions.
356 if (!empty($rowData[\'width\']) && !empty($rowData[\'height\']))
357 $link .= sprintf(\' <span class="smalltext">%1$dx%2$d</span>\', $rowData[\'width\'], $rowData[\'height\']);
358
359 return $link;
360 '),
361 ),
362 'sort' => array(
363 'default' => 'a.filename',
364 'reverse' => 'a.filename DESC',
365 ),
366 ),
367 'filesize' => array(
368 'header' => array(
369 'value' => $txt['attachment_file_size'],
370 ),
371 'data' => array(
372 'function' => create_function('$rowData','
373 global $txt;
374
375 return sprintf(\'%1$s%2$s\', round($rowData[\'size\'] / 1024, 2), $txt[\'kilobyte\']);
376 '),
377 'class' => 'windowbg',
378 ),
379 'sort' => array(
380 'default' => 'a.size',
381 'reverse' => 'a.size DESC',
382 ),
383 ),
384 'member' => array(
385 'header' => array(
386 'value' => $context['browse_type'] == 'avatars' ? $txt['attachment_manager_member'] : $txt['posted_by'],
387 ),
388 'data' => array(
389 'function' => create_function('$rowData', '
390 global $scripturl;
391
392 // In case of an attachment, return the poster of the attachment.
393 if (empty($rowData[\'id_member\']))
394 return htmlspecialchars($rowData[\'poster_name\']);
395
396 // Otherwise it must be an avatar, return the link to the owner of it.
397 else
398 return sprintf(\'<a href="%1$s?action=profile;u=%2$d">%3$s</a>\', $scripturl, $rowData[\'id_member\'], $rowData[\'poster_name\']);
399 '),
400 ),
401 'sort' => array(
402 'default' => 'mem.real_name',
403 'reverse' => 'mem.real_name DESC',
404 ),
405 ),
406 'date' => array(
407 'header' => array(
408 'value' => $context['browse_type'] == 'avatars' ? $txt['attachment_manager_last_active'] : $txt['date'],
409 ),
410 'data' => array(
411 'function' => create_function('$rowData', '
412 global $txt, $context, $scripturl;
413
414 // The date the message containing the attachment was posted or the owner of the avatar was active.
415 $date = empty($rowData[\'poster_time\']) ? $txt[\'never\'] : timeformat($rowData[\'poster_time\']);
416
417 // Add a link to the topic in case of an attachment.
418 if ($context[\'browse_type\'] !== \'avatars\')
419 $date .= sprintf(\'<br />%1$s <a href="%2$s?topic=%3$d.0.msg%4$d#msg%4$d">%5$s</a>\', $txt[\'in\'], $scripturl, $rowData[\'id_topic\'], $rowData[\'id_msg\'], $rowData[\'subject\']);
420
421 return $date;
422 '),
423 'class' => 'windowbg',
424 ),
425 'sort' => array(
426 'default' => $context['browse_type'] === 'avatars' ? 'mem.last_login' : 'm.id_msg',
427 'reverse' => $context['browse_type'] === 'avatars' ? 'mem.last_login DESC' : 'm.id_msg DESC',
428 ),
429 ),
430 'downloads' => array(
431 'header' => array(
432 'value' => $txt['downloads'],
433 ),
434 'data' => array(
435 'function' => create_function('$rowData','
436 global $txt;
437
438 return comma_format($rowData[\'downloads\']);
439 '),
440 'class' => 'windowbg',
441 ),
442 'sort' => array(
443 'default' => 'a.downloads',
444 'reverse' => 'a.downloads DESC',
445 ),
446 ),
447 'check' => array(
448 'header' => array(
449 'value' => '<input type="checkbox" onclick="invertAll(this, this.form);" class="input_check" />',
450 ),
451 'data' => array(
452 'sprintf' => array(
453 'format' => '<input type="checkbox" name="remove[%1$d]" class="input_check" />',
454 'params' => array(
455 'id_attach' => false,
456 ),
457 ),
458 'style' => 'text-align: center',
459 ),
460 ),
461 ),
462 'form' => array(
463 'href' => $scripturl . '?action=admin;area=manageattachments;sa=remove' . ($context['browse_type'] === 'avatars' ? ';avatars' : ($context['browse_type'] === 'thumbs' ? ';thumbs' : '')),
464 'include_sort' => true,
465 'include_start' => true,
466 'hidden_fields' => array(
467 'type' => $context['browse_type'],
468 ),
469 ),
470 'additional_rows' => array(
471 array(
472 'position' => 'below_table_data',
473 'value' => '<input type="submit" name="remove_submit" class="button_submit" value="' . $txt['quickmod_delete_selected'] . '" onclick="return confirm(\'' . $txt['confirm_delete_attachments'] . '\');" />',
474 'style' => 'text-align: right;',
475 ),
476 ),
477 );
478
479 // Create the list.
480 require_once($sourcedir . '/Subs-List.php');
481 createList($listOptions);
482 }
483
484 function list_getFiles($start, $items_per_page, $sort, $browse_type)
485 {
486 global $smcFunc, $txt;
487
488 // Choose a query depending on what we are viewing.
489 if ($browse_type === 'avatars')
490 $request = $smcFunc['db_query']('', '
491 SELECT
492 {string:blank_text} AS id_msg, IFNULL(mem.real_name, {string:not_applicable_text}) AS poster_name,
493 mem.last_login AS poster_time, 0 AS id_topic, a.id_member, a.id_attach, a.filename, a.file_hash, a.attachment_type,
494 a.size, a.width, a.height, a.downloads, {string:blank_text} AS subject, 0 AS id_board
495 FROM {db_prefix}attachments AS a
496 LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = a.id_member)
497 WHERE a.id_member != {int:guest_id}
498 ORDER BY {raw:sort}
499 LIMIT {int:start}, {int:per_page}',
500 array(
501 'guest_id' => 0,
502 'blank_text' => '',
503 'not_applicable_text' => $txt['not_applicable'],
504 'sort' => $sort,
505 'start' => $start,
506 'per_page' => $items_per_page,
507 )
508 );
509 else
510 $request = $smcFunc['db_query']('', '
511 SELECT
512 m.id_msg, IFNULL(mem.real_name, m.poster_name) AS poster_name, m.poster_time, m.id_topic, m.id_member,
513 a.id_attach, a.filename, a.file_hash, a.attachment_type, a.size, a.width, a.height, a.downloads, mf.subject, t.id_board
514 FROM {db_prefix}attachments AS a
515 INNER JOIN {db_prefix}messages AS m ON (m.id_msg = a.id_msg)
516 INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic)
517 INNER JOIN {db_prefix}messages AS mf ON (mf.id_msg = t.id_first_msg)
518 LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)
519 WHERE a.attachment_type = {int:attachment_type}
520 ORDER BY {raw:sort}
521 LIMIT {int:start}, {int:per_page}',
522 array(
523 'attachment_type' => $browse_type == 'thumbs' ? '3' : '0',
524 'sort' => $sort,
525 'start' => $start,
526 'per_page' => $items_per_page,
527 )
528 );
529 $files = array();
530 while ($row = $smcFunc['db_fetch_assoc']($request))
531 $files[] = $row;
532 $smcFunc['db_free_result']($request);
533
534 return $files;
535 }
536
537 function list_getNumFiles($browse_type)
538 {
539 global $smcFunc;
540
541 // Depending on the type of file, different queries are used.
542 if ($browse_type === 'avatars')
543 $request = $smcFunc['db_query']('', '
544 SELECT COUNT(*)
545 FROM {db_prefix}attachments
546 WHERE id_member != {int:guest_id_member}',
547 array(
548 'guest_id_member' => 0,
549 )
550 );
551 else
552 $request = $smcFunc['db_query']('', '
553 SELECT COUNT(*) AS num_attach
554 FROM {db_prefix}attachments AS a
555 INNER JOIN {db_prefix}messages AS m ON (m.id_msg = a.id_msg)
556 INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic)
557 INNER JOIN {db_prefix}messages AS mf ON (mf.id_msg = t.id_first_msg)
558 WHERE a.attachment_type = {int:attachment_type}
559 AND a.id_member = {int:guest_id_member}',
560 array(
561 'attachment_type' => $browse_type === 'thumbs' ? '3' : '0',
562 'guest_id_member' => 0,
563 )
564 );
565
566 list ($num_files) = $smcFunc['db_fetch_row']($request);
567 $smcFunc['db_free_result']($request);
568
569 return $num_files;
570 }
571
572 function MaintainFiles()
573 {
574 global $context, $modSettings, $txt, $smcFunc;
575
576 $context['sub_template'] = 'maintenance';
577
578 if (!empty($modSettings['currentAttachmentUploadDir']))
579 $attach_dirs = unserialize($modSettings['attachmentUploadDir']);
580 else
581 $attach_dirs = array($modSettings['attachmentUploadDir']);
582
583 // Get the number of attachments....
584 $request = $smcFunc['db_query']('', '
585 SELECT COUNT(*)
586 FROM {db_prefix}attachments
587 WHERE attachment_type = {int:attachment_type}
588 AND id_member = {int:guest_id_member}',
589 array(
590 'attachment_type' => 0,
591 'guest_id_member' => 0,
592 )
593 );
594 list ($context['num_attachments']) = $smcFunc['db_fetch_row']($request);
595 $smcFunc['db_free_result']($request);
596
597 // Also get the avatar amount....
598 $request = $smcFunc['db_query']('', '
599 SELECT COUNT(*)
600 FROM {db_prefix}attachments
601 WHERE id_member != {int:guest_id_member}',
602 array(
603 'guest_id_member' => 0,
604 )
605 );
606 list ($context['num_avatars']) = $smcFunc['db_fetch_row']($request);
607 $smcFunc['db_free_result']($request);
608
609 // Find out how big the directory is. We have to loop through all our attachment paths in case there's an old temp file in one of them.
610 $attachmentDirSize = 0;
611 foreach ($attach_dirs as $id => $attach_dir)
612 {
613 $dir = @opendir($attach_dir) or fatal_lang_error('cant_access_upload_path', 'critical');
614 while ($file = readdir($dir))
615 {
616 if ($file == '.' || $file == '..')
617 continue;
618
619 if (preg_match('~^post_tmp_\d+_\d+$~', $file) != 0)
620 {
621 // Temp file is more than 5 hours old!
622 if (filemtime($attach_dir . '/' . $file) < time() - 18000)
623 @unlink($attach_dir . '/' . $file);
624 continue;
625 }
626
627 // We're only counting the size of the current attachment directory.
628 if (empty($modSettings['currentAttachmentUploadDir']) || $modSettings['currentAttachmentUploadDir'] == $id)
629 $attachmentDirSize += filesize($attach_dir . '/' . $file);
630 }
631 closedir($dir);
632 }
633 // Divide it into kilobytes.
634 $attachmentDirSize /= 1024;
635
636 // If they specified a limit only....
637 if (!empty($modSettings['attachmentDirSizeLimit']))
638 $context['attachment_space'] = max(round($modSettings['attachmentDirSizeLimit'] - $attachmentDirSize, 2), 0);
639 $context['attachment_total_size'] = round($attachmentDirSize, 2);
640
641 $context['attach_multiple_dirs'] = !empty($modSettings['currentAttachmentUploadDir']);
642 }
643
644 // !!! Not implemented yet.
645 function MoveAvatars()
646 {
647 global $modSettings, $smcFunc;
648
649 // First make sure the custom avatar dir is writable.
650 if (!is_writable($modSettings['custom_avatar_dir']))
651 {
652 // Try to fix it.
653 @chmod($modSettings['custom_avatar_dir'], 0777);
654
655 // Guess that didn't work?
656 if (!is_writable($modSettings['custom_avatar_dir']))
657 fatal_lang_error('attachments_no_write', 'critical');
658 }
659
660 $request = $smcFunc['db_query']('', '
661 SELECT id_attach, id_folder, id_member, filename, file_hash
662 FROM {db_prefix}attachments
663 WHERE attachment_type = {int:attachment_type}
664 AND id_member > {int:guest_id_member}',
665 array(
666 'attachment_type' => 0,
667 'guest_id_member' => 0,
668 )
669 );
670 $updatedAvatars = array();
671 while ($row = $smcFunc['db_fetch_assoc']($request))
672 {
673 $filename = getAttachmentFilename($row['filename'], $row['id_attach'], $row['id_folder'], false, $row['file_hash']);
674
675 if (rename($filename, $modSettings['custom_avatar_dir'] . '/' . $row['filename']))
676 $updatedAvatars[] = $row['id_attach'];
677 }
678 $smcFunc['db_free_result']($request);
679
680 if (!empty($updatedAvatars))
681 $smcFunc['db_query']('', '
682 UPDATE {db_prefix}attachments
683 SET attachment_type = {int:attachment_type}
684 WHERE id_attach IN ({array_int:updated_avatars})',
685 array(
686 'updated_avatars' => $updatedAvatars,
687 'attachment_type' => 1,
688 )
689 );
690
691 redirectexit('action=admin;area=manageattachments;sa=maintenance');
692 }
693
694 function RemoveAttachmentByAge()
695 {
696 global $modSettings, $smcFunc;
697
698 checkSession('post', 'admin');
699
700 // !!! Ignore messages in topics that are stickied?
701
702 // Deleting an attachment?
703 if ($_REQUEST['type'] != 'avatars')
704 {
705 // Get all the old attachments.
706 $messages = removeAttachments(array('attachment_type' => 0, 'poster_time' => (time() - 24 * 60 * 60 * $_POST['age'])), 'messages', true);
707
708 // Update the messages to reflect the change.
709 if (!empty($messages))
710 $smcFunc['db_query']('', '
711 UPDATE {db_prefix}messages
712 SET body = CONCAT(body, ' . (!empty($_POST['notice']) ? '{string:notice}' : '') . ')
713 WHERE id_msg IN ({array_int:messages})',
714 array(
715 'messages' => $messages,
716 'notice' => empty($_POST['notice']) ? '' : '<br /><br />' . $_POST['notice'],
717 )
718 );
719 }
720 else
721 {
722 // Remove all the old avatars.
723 removeAttachments(array('not_id_member' => 0, 'last_login' => (time() - 24 * 60 * 60 * $_POST['age'])), 'members');
724 }
725 redirectexit('action=admin;area=manageattachments' . (empty($_REQUEST['avatars']) ? ';sa=maintenance' : ';avatars'));
726 }
727
728 function RemoveAttachmentBySize()
729 {
730 global $modSettings, $smcFunc;
731
732 checkSession('post', 'admin');
733
734 // Find humungous attachments.
735 $messages = removeAttachments(array('attachment_type' => 0, 'size' => 1024 * $_POST['size']), 'messages', true);
736
737 // And make a note on the post.
738 if (!empty($messages))
739 $smcFunc['db_query']('', '
740 UPDATE {db_prefix}messages
741 SET body = CONCAT(body, ' . (!empty($_POST['notice']) ? '{string:notice}' : '') . ')
742 WHERE id_msg IN ({array_int:messages})',
743 array(
744 'messages' => $messages,
745 'notice' => empty($_POST['notice']) ? '' : '<br /><br />' . $_POST['notice'],
746 )
747 );
748
749 redirectexit('action=admin;area=manageattachments;sa=maintenance');
750 }
751
752 function RemoveAttachment()
753 {
754 global $modSettings, $txt, $smcFunc;
755
756 checkSession('post');
757
758 if (!empty($_POST['remove']))
759 {
760 $attachments = array();
761 // There must be a quicker way to pass this safety test??
762 foreach ($_POST['remove'] as $removeID => $dummy)
763 $attachments[] = (int) $removeID;
764
765 if ($_REQUEST['type'] == 'avatars' && !empty($attachments))
766 removeAttachments(array('id_attach' => $attachments));
767 else if (!empty($attachments))
768 {
769 $messages = removeAttachments(array('id_attach' => $attachments), 'messages', true);
770
771 // And change the message to reflect this.
772 if (!empty($messages))
773 $smcFunc['db_query']('', '
774 UPDATE {db_prefix}messages
775 SET body = CONCAT(body, {string:deleted_message})
776 WHERE id_msg IN ({array_int:messages_affected})',
777 array(
778 'messages_affected' => $messages,
779 'deleted_message' => '<br /><br />' . $txt['attachment_delete_admin'],
780 )
781 );
782 }
783 }
784
785 $_GET['sort'] = isset($_GET['sort']) ? $_GET['sort'] : 'date';
786 redirectexit('action=admin;area=manageattachments;sa=browse;' . $_REQUEST['type'] . ';sort=' . $_GET['sort'] . (isset($_GET['desc']) ? ';desc' : '') . ';start=' . $_REQUEST['start']);
787 }
788
789 // !!! Not implemented (yet?)
790 function RemoveAllAttachments()
791 {
792 global $txt, $smcFunc;
793
794 checkSession('get', 'admin');
795
796 $messages = removeAttachments(array('attachment_type' => 0), '', true);
797
798 if (!isset($_POST['notice']))
799 $_POST['notice'] = $txt['attachment_delete_admin'];
800
801 // Add the notice on the end of the changed messages.
802 if (!empty($messages))
803 $smcFunc['db_query']('', '
804 UPDATE {db_prefix}messages
805 SET body = CONCAT(body, {string:deleted_message})
806 WHERE id_msg IN ({array_int:messages})',
807 array(
808 'messages' => $messages,
809 'deleted_message' => '<br /><br />' . $_POST['notice'],
810 )
811 );
812
813 redirectexit('action=admin;area=manageattachments;sa=maintenance');
814 }
815
816 // Removes attachments - allowed query_types: '', 'messages', 'members'
817 function removeAttachments($condition, $query_type = '', $return_affected_messages = false, $autoThumbRemoval = true)
818 {
819 global $modSettings, $smcFunc;
820
821 //!!! This might need more work!
822 $new_condition = array();
823 $query_parameter = array(
824 'thumb_attachment_type' => 3,
825 );
826
827 if (is_array($condition))
828 {
829 foreach ($condition as $real_type => $restriction)
830 {
831 // Doing a NOT?
832 $is_not = substr($real_type, 0, 4) == 'not_';
833 $type = $is_not ? substr($real_type, 4) : $real_type;
834
835 if (in_array($type, array('id_member', 'id_attach', 'id_msg')))
836 $new_condition[] = 'a.' . $type . ($is_not ? ' NOT' : '') . ' IN (' . (is_array($restriction) ? '{array_int:' . $real_type . '}' : '{int:' . $real_type . '}') . ')';
837 elseif ($type == 'attachment_type')
838 $new_condition[] = 'a.attachment_type = {int:' . $real_type . '}';
839 elseif ($type == 'poster_time')
840 $new_condition[] = 'm.poster_time < {int:' . $real_type . '}';
841 elseif ($type == 'last_login')
842 $new_condition[] = 'mem.last_login < {int:' . $real_type . '}';
843 elseif ($type == 'size')
844 $new_condition[] = 'a.size > {int:' . $real_type . '}';
845 elseif ($type == 'id_topic')
846 $new_condition[] = 'm.id_topic IN (' . (is_array($restriction) ? '{array_int:' . $real_type . '}' : '{int:' . $real_type . '}') . ')';
847
848 // Add the parameter!
849 $query_parameter[$real_type] = $restriction;
850 }
851 $condition = implode(' AND ', $new_condition);
852 }
853
854 // Delete it only if it exists...
855 $msgs = array();
856 $attach = array();
857 $parents = array();
858
859 // Get all the attachment names and id_msg's.
860 $request = $smcFunc['db_query']('', '
861 SELECT
862 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') . ',
863 thumb.id_folder AS thumb_folder, IFNULL(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
864 FROM {db_prefix}attachments AS a' .($query_type == 'members' ? '
865 INNER JOIN {db_prefix}members AS mem ON (mem.id_member = a.id_member)' : ($query_type == 'messages' ? '
866 INNER JOIN {db_prefix}messages AS m ON (m.id_msg = a.id_msg)' : '')) . '
867 LEFT JOIN {db_prefix}attachments AS thumb ON (thumb.id_attach = a.id_thumb)
868 LEFT JOIN {db_prefix}attachments AS thumb_parent ON (thumb.attachment_type = {int:thumb_attachment_type} AND thumb_parent.id_thumb = a.id_attach)
869 WHERE ' . $condition,
870 $query_parameter
871 );
872 while ($row = $smcFunc['db_fetch_assoc']($request))
873 {
874 // Figure out the "encrypted" filename and unlink it ;).
875 if ($row['attachment_type'] == 1)
876 @unlink($modSettings['custom_avatar_dir'] . '/' . $row['filename']);
877 else
878 {
879 $filename = getAttachmentFilename($row['filename'], $row['id_attach'], $row['id_folder'], false, $row['file_hash']);
880 @unlink($filename);
881
882 // If this was a thumb, the parent attachment should know about it.
883 if (!empty($row['id_parent']))
884 $parents[] = $row['id_parent'];
885
886 // If this attachments has a thumb, remove it as well.
887 if (!empty($row['id_thumb']) && $autoThumbRemoval)
888 {
889 $thumb_filename = getAttachmentFilename($row['thumb_filename'], $row['id_thumb'], $row['thumb_folder'], false, $row['thumb_file_hash']);
890 @unlink($thumb_filename);
891 $attach[] = $row['id_thumb'];
892 }
893 }
894
895 // Make a list.
896 if ($return_affected_messages && empty($row['attachment_type']))
897 $msgs[] = $row['id_msg'];
898 $attach[] = $row['id_attach'];
899 }
900 $smcFunc['db_free_result']($request);
901
902 // Removed attachments don't have to be updated anymore.
903 $parents = array_diff($parents, $attach);
904 if (!empty($parents))
905 $smcFunc['db_query']('', '
906 UPDATE {db_prefix}attachments
907 SET id_thumb = {int:no_thumb}
908 WHERE id_attach IN ({array_int:parent_attachments})',
909 array(
910 'parent_attachments' => $parents,
911 'no_thumb' => 0,
912 )
913 );
914
915 if (!empty($attach))
916 $smcFunc['db_query']('', '
917 DELETE FROM {db_prefix}attachments
918 WHERE id_attach IN ({array_int:attachment_list})',
919 array(
920 'attachment_list' => $attach,
921 )
922 );
923
924 if ($return_affected_messages)
925 return array_unique($msgs);
926 }
927
928 // This function should find attachments in the database that no longer exist and clear them, and fix filesize issues.
929 function RepairAttachments()
930 {
931 global $modSettings, $context, $txt, $smcFunc;
932
933 checkSession('get');
934
935 // If we choose cancel, redirect right back.
936 if (isset($_POST['cancel']))
937 redirectexit('action=admin;area=manageattachments;sa=maintenance');
938
939 // Try give us a while to sort this out...
940 @set_time_limit(600);
941
942 $_GET['step'] = empty($_GET['step']) ? 0 : (int) $_GET['step'];
943 $_GET['substep'] = empty($_GET['substep']) ? 0 : (int) $_GET['substep'];
944
945 // Don't recall the session just in case.
946 if ($_GET['step'] == 0 && $_GET['substep'] == 0)
947 {
948 unset($_SESSION['attachments_to_fix'], $_SESSION['attachments_to_fix2']);
949
950 // If we're actually fixing stuff - work out what.
951 if (isset($_GET['fixErrors']))
952 {
953 // Nothing?
954 if (empty($_POST['to_fix']))
955 redirectexit('action=admin;area=manageattachments;sa=maintenance');
956
957 $_SESSION['attachments_to_fix'] = array();
958 //!!! No need to do this I think.
959 foreach ($_POST['to_fix'] as $key => $value)
960 $_SESSION['attachments_to_fix'][] = $value;
961 }
962 }
963
964 // All the valid problems are here:
965 $context['repair_errors'] = array(
966 'missing_thumbnail_parent' => 0,
967 'parent_missing_thumbnail' => 0,
968 'file_missing_on_disk' => 0,
969 'file_wrong_size' => 0,
970 'file_size_of_zero' => 0,
971 'attachment_no_msg' => 0,
972 'avatar_no_member' => 0,
973 'wrong_folder' => 0,
974 );
975
976 $to_fix = !empty($_SESSION['attachments_to_fix']) ? $_SESSION['attachments_to_fix'] : array();
977 $context['repair_errors'] = isset($_SESSION['attachments_to_fix2']) ? $_SESSION['attachments_to_fix2'] : $context['repair_errors'];
978 $fix_errors = isset($_GET['fixErrors']) ? true : false;
979
980 // Get stranded thumbnails.
981 if ($_GET['step'] <= 0)
982 {
983 $result = $smcFunc['db_query']('', '
984 SELECT MAX(id_attach)
985 FROM {db_prefix}attachments
986 WHERE attachment_type = {int:thumbnail}',
987 array(
988 'thumbnail' => 3,
989 )
990 );
991 list ($thumbnails) = $smcFunc['db_fetch_row']($result);
992 $smcFunc['db_free_result']($result);
993
994 for (; $_GET['substep'] < $thumbnails; $_GET['substep'] += 500)
995 {
996 $to_remove = array();
997
998 $result = $smcFunc['db_query']('', '
999 SELECT thumb.id_attach, thumb.id_folder, thumb.filename, thumb.file_hash
1000 FROM {db_prefix}attachments AS thumb
1001 LEFT JOIN {db_prefix}attachments AS tparent ON (tparent.id_thumb = thumb.id_attach)
1002 WHERE thumb.id_attach BETWEEN {int:substep} AND {int:substep} + 499
1003 AND thumb.attachment_type = {int:thumbnail}
1004 AND tparent.id_attach IS NULL',
1005 array(
1006 'thumbnail' => 3,
1007 'substep' => $_GET['substep'],
1008 )
1009 );
1010 while ($row = $smcFunc['db_fetch_assoc']($result))
1011 {
1012 // Only do anything once... just in case
1013 if (!isset($to_remove[$row['id_attach']]))
1014 {
1015 $to_remove[$row['id_attach']] = $row['id_attach'];
1016 $context['repair_errors']['missing_thumbnail_parent']++;
1017
1018 // If we are repairing remove the file from disk now.
1019 if ($fix_errors && in_array('missing_thumbnail_parent', $to_fix))
1020 {
1021 $filename = getAttachmentFilename($row['filename'], $row['id_attach'], $row['id_folder'], false, $row['file_hash']);
1022 @unlink($filename);
1023 }
1024 }
1025 }
1026 if ($smcFunc['db_num_rows']($result) != 0)
1027 $to_fix[] = 'missing_thumbnail_parent';
1028 $smcFunc['db_free_result']($result);
1029
1030 // Do we need to delete what we have?
1031 if ($fix_errors && !empty($to_remove) && in_array('missing_thumbnail_parent', $to_fix))
1032 $smcFunc['db_query']('', '
1033 DELETE FROM {db_prefix}attachments
1034 WHERE id_attach IN ({array_int:to_remove})
1035 AND attachment_type = {int:attachment_type}',
1036 array(
1037 'to_remove' => $to_remove,
1038 'attachment_type' => 3,
1039 )
1040 );
1041
1042 pauseAttachmentMaintenance($to_fix, $thumbnails);
1043 }
1044
1045 $_GET['step'] = 1;
1046 $_GET['substep'] = 0;
1047 pauseAttachmentMaintenance($to_fix);
1048 }
1049
1050 // Find parents which think they have thumbnails, but actually, don't.
1051 if ($_GET['step'] <= 1)
1052 {
1053 $result = $smcFunc['db_query']('', '
1054 SELECT MAX(id_attach)
1055 FROM {db_prefix}attachments
1056 WHERE id_thumb != {int:no_thumb}',
1057 array(
1058 'no_thumb' => 0,
1059 )
1060 );
1061 list ($thumbnails) = $smcFunc['db_fetch_row']($result);
1062 $smcFunc['db_free_result']($result);
1063
1064 for (; $_GET['substep'] < $thumbnails; $_GET['substep'] += 500)
1065 {
1066 $to_update = array();
1067
1068 $result = $smcFunc['db_query']('', '
1069 SELECT a.id_attach
1070 FROM {db_prefix}attachments AS a
1071 LEFT JOIN {db_prefix}attachments AS thumb ON (thumb.id_attach = a.id_thumb)
1072 WHERE a.id_attach BETWEEN {int:substep} AND {int:substep} + 499
1073 AND a.id_thumb != {int:no_thumb}
1074 AND thumb.id_attach IS NULL',
1075 array(
1076 'no_thumb' => 0,
1077 'substep' => $_GET['substep'],
1078 )
1079 );
1080 while ($row = $smcFunc['db_fetch_assoc']($result))
1081 {
1082 $to_update[] = $row['id_attach'];
1083 $context['repair_errors']['parent_missing_thumbnail']++;
1084 }
1085 if ($smcFunc['db_num_rows']($result) != 0)
1086 $to_fix[] = 'parent_missing_thumbnail';
1087 $smcFunc['db_free_result']($result);
1088
1089 // Do we need to delete what we have?
1090 if ($fix_errors && !empty($to_update) && in_array('parent_missing_thumbnail', $to_fix))
1091 $smcFunc['db_query']('', '
1092 UPDATE {db_prefix}attachments
1093 SET id_thumb = {int:no_thumb}
1094 WHERE id_attach IN ({array_int:to_update})',
1095 array(
1096 'to_update' => $to_update,
1097 'no_thumb' => 0,
1098 )
1099 );
1100
1101 pauseAttachmentMaintenance($to_fix, $thumbnails);
1102 }
1103
1104 $_GET['step'] = 2;
1105 $_GET['substep'] = 0;
1106 pauseAttachmentMaintenance($to_fix);
1107 }
1108
1109 // This may take forever I'm afraid, but life sucks... recount EVERY attachments!
1110 if ($_GET['step'] <= 2)
1111 {
1112 $result = $smcFunc['db_query']('', '
1113 SELECT MAX(id_attach)
1114 FROM {db_prefix}attachments',
1115 array(
1116 )
1117 );
1118 list ($thumbnails) = $smcFunc['db_fetch_row']($result);
1119 $smcFunc['db_free_result']($result);
1120
1121 for (; $_GET['substep'] < $thumbnails; $_GET['substep'] += 250)
1122 {
1123 $to_remove = array();
1124 $errors_found = array();
1125
1126 $result = $smcFunc['db_query']('', '
1127 SELECT id_attach, id_folder, filename, file_hash, size, attachment_type
1128 FROM {db_prefix}attachments
1129 WHERE id_attach BETWEEN {int:substep} AND {int:substep} + 249',
1130 array(
1131 'substep' => $_GET['substep'],
1132 )
1133 );
1134 while ($row = $smcFunc['db_fetch_assoc']($result))
1135 {
1136 // Get the filename.
1137 if ($row['attachment_type'] == 1)
1138 $filename = $modSettings['custom_avatar_dir'] . '/' . $row['filename'];
1139 else
1140 $filename = getAttachmentFilename($row['filename'], $row['id_attach'], $row['id_folder'], false, $row['file_hash']);
1141
1142 // File doesn't exist?
1143 if (!file_exists($filename))
1144 {
1145 // If we're lucky it might just be in a different folder.
1146 if (!empty($modSettings['currentAttachmentUploadDir']))
1147 {
1148 // Get the attachment name with out the folder.
1149 $attachment_name = !empty($row['file_hash']) ? $row['id_attach'] . '_' . $row['file_hash'] : getLegacyAttachmentFilename($row['filename'], $row['id_attach'], null, true);
1150
1151 if (!is_array($modSettings['attachmentUploadDir']))
1152 $modSettings['attachmentUploadDir'] = unserialize($modSettings['attachmentUploadDir']);
1153
1154 // Loop through the other folders.
1155 foreach ($modSettings['attachmentUploadDir'] as $id => $dir)
1156 if (file_exists($dir . '/' . $attachment_name))
1157 {
1158 $context['repair_errors']['wrong_folder']++;
1159 $errors_found[] = 'wrong_folder';
1160
1161 // Are we going to fix this now?
1162 if ($fix_errors && in_array('wrong_folder', $to_fix))
1163 $smcFunc['db_query']('', '
1164 UPDATE {db_prefix}attachments
1165 SET id_folder = {int:new_folder}
1166 WHERE id_attach = {int:id_attach}',
1167 array(
1168 'new_folder' => $id,
1169 'id_attach' => $row['id_attach'],
1170 )
1171 );
1172
1173 continue 2;
1174 }
1175 }
1176
1177 $to_remove[] = $row['id_attach'];
1178 $context['repair_errors']['file_missing_on_disk']++;
1179 $errors_found[] = 'file_missing_on_disk';
1180 }
1181 elseif (filesize($filename) == 0)
1182 {
1183 $context['repair_errors']['file_size_of_zero']++;
1184 $errors_found[] = 'file_size_of_zero';
1185
1186 // Fixing?
1187 if ($fix_errors && in_array('file_size_of_zero', $to_fix))
1188 {
1189 $to_remove[] = $row['id_attach'];
1190 @unlink($filename);
1191 }
1192 }
1193 elseif (filesize($filename) != $row['size'])
1194 {
1195 $context['repair_errors']['file_wrong_size']++;
1196 $errors_found[] = 'file_wrong_size';
1197
1198 // Fix it here?
1199 if ($fix_errors && in_array('file_wrong_size', $to_fix))
1200 {
1201 $smcFunc['db_query']('', '
1202 UPDATE {db_prefix}attachments
1203 SET size = {int:filesize}
1204 WHERE id_attach = {int:id_attach}',
1205 array(
1206 'filesize' => filesize($filename),
1207 'id_attach' => $row['id_attach'],
1208 )
1209 );
1210 }
1211 }
1212 }
1213
1214 if (in_array('file_missing_on_disk', $errors_found))
1215 $to_fix[] = 'file_missing_on_disk';
1216 if (in_array('file_size_of_zero', $errors_found))
1217 $to_fix[] = 'file_size_of_zero';
1218 if (in_array('file_wrong_size', $errors_found))
1219 $to_fix[] = 'file_wrong_size';
1220 if (in_array('wrong_folder', $errors_found))
1221 $to_fix[] = 'wrong_folder';
1222 $smcFunc['db_free_result']($result);
1223
1224 // Do we need to delete what we have?
1225 if ($fix_errors && !empty($to_remove))
1226 {
1227 $smcFunc['db_query']('', '
1228 DELETE FROM {db_prefix}attachments
1229 WHERE id_attach IN ({array_int:to_remove})',
1230 array(
1231 'to_remove' => $to_remove,
1232 )
1233 );
1234 $smcFunc['db_query']('', '
1235 UPDATE {db_prefix}attachments
1236 SET id_thumb = {int:no_thumb}
1237 WHERE id_thumb IN ({array_int:to_remove})',
1238 array(
1239 'to_remove' => $to_remove,
1240 'no_thumb' => 0,
1241 )
1242 );
1243 }
1244
1245 pauseAttachmentMaintenance($to_fix, $thumbnails);
1246 }
1247
1248 $_GET['step'] = 3;
1249 $_GET['substep'] = 0;
1250 pauseAttachmentMaintenance($to_fix);
1251 }
1252
1253 // Get avatars with no members associated with them.
1254 if ($_GET['step'] <= 3)
1255 {
1256 $result = $smcFunc['db_query']('', '
1257 SELECT MAX(id_attach)
1258 FROM {db_prefix}attachments',
1259 array(
1260 )
1261 );
1262 list ($thumbnails) = $smcFunc['db_fetch_row']($result);
1263 $smcFunc['db_free_result']($result);
1264
1265 for (; $_GET['substep'] < $thumbnails; $_GET['substep'] += 500)
1266 {
1267 $to_remove = array();
1268
1269 $result = $smcFunc['db_query']('', '
1270 SELECT a.id_attach, a.id_folder, a.filename, a.file_hash, a.attachment_type
1271 FROM {db_prefix}attachments AS a
1272 LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = a.id_member)
1273 WHERE a.id_attach BETWEEN {int:substep} AND {int:substep} + 499
1274 AND a.id_member != {int:no_member}
1275 AND a.id_msg = {int:no_msg}
1276 AND mem.id_member IS NULL',
1277 array(
1278 'no_member' => 0,
1279 'no_msg' => 0,
1280 'substep' => $_GET['substep'],
1281 )
1282 );
1283 while ($row = $smcFunc['db_fetch_assoc']($result))
1284 {
1285 $to_remove[] = $row['id_attach'];
1286 $context['repair_errors']['avatar_no_member']++;
1287
1288 // If we are repairing remove the file from disk now.
1289 if ($fix_errors && in_array('avatar_no_member', $to_fix))
1290 {
1291 if ($row['attachment_type'] == 1)
1292 $filename = $modSettings['custom_avatar_dir'] . '/' . $row['filename'];
1293 else
1294 $filename = getAttachmentFilename($row['filename'], $row['id_attach'], $row['id_folder'], false, $row['file_hash']);
1295 @unlink($filename);
1296 }
1297 }
1298 if ($smcFunc['db_num_rows']($result) != 0)
1299 $to_fix[] = 'avatar_no_member';
1300 $smcFunc['db_free_result']($result);
1301
1302 // Do we need to delete what we have?
1303 if ($fix_errors && !empty($to_remove) && in_array('avatar_no_member', $to_fix))
1304 $smcFunc['db_query']('', '
1305 DELETE FROM {db_prefix}attachments
1306 WHERE id_attach IN ({array_int:to_remove})
1307 AND id_member != {int:no_member}
1308 AND id_msg = {int:no_msg}',
1309 array(
1310 'to_remove' => $to_remove,
1311 'no_member' => 0,
1312 'no_msg' => 0,
1313 )
1314 );
1315
1316 pauseAttachmentMaintenance($to_fix, $thumbnails);
1317 }
1318
1319 $_GET['step'] = 4;
1320 $_GET['substep'] = 0;
1321 pauseAttachmentMaintenance($to_fix);
1322 }
1323
1324 // What about attachments, who are missing a message :'(
1325 if ($_GET['step'] <= 4)
1326 {
1327 $result = $smcFunc['db_query']('', '
1328 SELECT MAX(id_attach)
1329 FROM {db_prefix}attachments',
1330 array(
1331 )
1332 );
1333 list ($thumbnails) = $smcFunc['db_fetch_row']($result);
1334 $smcFunc['db_free_result']($result);
1335
1336 for (; $_GET['substep'] < $thumbnails; $_GET['substep'] += 500)
1337 {
1338 $to_remove = array();
1339
1340 $result = $smcFunc['db_query']('', '
1341 SELECT a.id_attach, a.id_folder, a.filename, a.file_hash
1342 FROM {db_prefix}attachments AS a
1343 LEFT JOIN {db_prefix}messages AS m ON (m.id_msg = a.id_msg)
1344 WHERE a.id_attach BETWEEN {int:substep} AND {int:substep} + 499
1345 AND a.id_member = {int:no_member}
1346 AND a.id_msg != {int:no_msg}
1347 AND m.id_msg IS NULL',
1348 array(
1349 'no_member' => 0,
1350 'no_msg' => 0,
1351 'substep' => $_GET['substep'],
1352 )
1353 );
1354 while ($row = $smcFunc['db_fetch_assoc']($result))
1355 {
1356 $to_remove[] = $row['id_attach'];
1357 $context['repair_errors']['attachment_no_msg']++;
1358
1359 // If we are repairing remove the file from disk now.
1360 if ($fix_errors && in_array('attachment_no_msg', $to_fix))
1361 {
1362 $filename = getAttachmentFilename($row['filename'], $row['id_attach'], $row['id_folder'], false, $row['file_hash']);
1363 @unlink($filename);
1364 }
1365 }
1366 if ($smcFunc['db_num_rows']($result) != 0)
1367 $to_fix[] = 'attachment_no_msg';
1368 $smcFunc['db_free_result']($result);
1369
1370 // Do we need to delete what we have?
1371 if ($fix_errors && !empty($to_remove) && in_array('attachment_no_msg', $to_fix))
1372 $smcFunc['db_query']('', '
1373 DELETE FROM {db_prefix}attachments
1374 WHERE id_attach IN ({array_int:to_remove})
1375 AND id_member = {int:no_member}
1376 AND id_msg != {int:no_msg}',
1377 array(
1378 'to_remove' => $to_remove,
1379 'no_member' => 0,
1380 'no_msg' => 0,
1381 )
1382 );
1383
1384 pauseAttachmentMaintenance($to_fix, $thumbnails);
1385 }
1386
1387 $_GET['step'] = 5;
1388 $_GET['substep'] = 0;
1389 pauseAttachmentMaintenance($to_fix);
1390 }
1391
1392 // Got here we must be doing well - just the template! :D
1393 $context['page_title'] = $txt['repair_attachments'];
1394 $context[$context['admin_menu_name']]['current_subsection'] = 'maintenance';
1395 $context['sub_template'] = 'attachment_repair';
1396
1397 // What stage are we at?
1398 $context['completed'] = $fix_errors ? true : false;
1399 $context['errors_found'] = !empty($to_fix) ? true : false;
1400
1401 }
1402
1403 function pauseAttachmentMaintenance($to_fix, $max_substep = 0)
1404 {
1405 global $context, $txt, $time_start;
1406
1407 // Try get more time...
1408 @set_time_limit(600);
1409 if (function_exists('apache_reset_timeout'))
1410 @apache_reset_timeout();
1411
1412 // Have we already used our maximum time?
1413 if (time() - array_sum(explode(' ', $time_start)) < 3)
1414 return;
1415
1416 $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'];
1417 $context['page_title'] = $txt['not_done_title'];
1418 $context['continue_post_data'] = '';
1419 $context['continue_countdown'] = '2';
1420 $context['sub_template'] = 'not_done';
1421
1422 // Specific stuff to not break this template!
1423 $context[$context['admin_menu_name']]['current_subsection'] = 'maintenance';
1424
1425 // Change these two if more steps are added!
1426 if (empty($max_substep))
1427 $context['continue_percent'] = round(($_GET['step'] * 100) / 25);
1428 else
1429 $context['continue_percent'] = round(($_GET['step'] * 100 + ($_GET['substep'] * 100) / $max_substep) / 25);
1430
1431 // Never more than 100%!
1432 $context['continue_percent'] = min($context['continue_percent'], 100);
1433
1434 $_SESSION['attachments_to_fix'] = $to_fix;
1435 $_SESSION['attachments_to_fix2'] = $context['repair_errors'];
1436
1437 obExit();
1438 }
1439
1440 // Called from a mouse click, works out what we want to do with attachments and actions it.
1441 function ApproveAttach()
1442 {
1443 global $smcFunc;
1444
1445 // Security is our primary concern...
1446 checkSession('get');
1447
1448 // If it approve or delete?
1449 $is_approve = !isset($_GET['sa']) || $_GET['sa'] != 'reject' ? true : false;
1450
1451 $attachments = array();
1452 // If we are approving all ID's in a message , get the ID's.
1453 if ($_GET['sa'] == 'all' && !empty($_GET['mid']))
1454 {
1455 $id_msg = (int) $_GET['mid'];
1456
1457 $request = $smcFunc['db_query']('', '
1458 SELECT id_attach
1459 FROM {db_prefix}attachments
1460 WHERE id_msg = {int:id_msg}
1461 AND approved = {int:is_approved}
1462 AND attachment_type = {int:attachment_type}',
1463 array(
1464 'id_msg' => $id_msg,
1465 'is_approved' => 0,
1466 'attachment_type' => 0,
1467 )
1468 );
1469 while ($row = $smcFunc['db_fetch_assoc']($request))
1470 $attachments[] = $row['id_attach'];
1471 $smcFunc['db_free_result']($request);
1472 }
1473 elseif (!empty($_GET['aid']))
1474 $attachments[] = (int) $_GET['aid'];
1475
1476 if (empty($attachments))
1477 fatal_lang_error('no_access', false);
1478
1479 // Now we have some ID's cleaned and ready to approve, but first - let's check we have permission!
1480 $allowed_boards = boardsAllowedTo('approve_posts');
1481
1482 // Validate the attachments exist and are the right approval state.
1483 $request = $smcFunc['db_query']('', '
1484 SELECT a.id_attach, m.id_board, m.id_msg, m.id_topic
1485 FROM {db_prefix}attachments AS a
1486 INNER JOIN {db_prefix}messages AS m ON (m.id_msg = a.id_msg)
1487 WHERE a.id_attach IN ({array_int:attachments})
1488 AND a.attachment_type = {int:attachment_type}
1489 AND a.approved = {int:is_approved}',
1490 array(
1491 'attachments' => $attachments,
1492 'attachment_type' => 0,
1493 'is_approved' => 0,
1494 )
1495 );
1496 $attachments = array();
1497 while ($row = $smcFunc['db_fetch_assoc']($request))
1498 {
1499 // We can only add it if we can approve in this board!
1500 if ($allowed_boards = array(0) || in_array($row['id_board'], $allowed_boards))
1501 {
1502 $attachments[] = $row['id_attach'];
1503
1504 // Also come up witht he redirection URL.
1505 $redirect = 'topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#msg' . $row['id_msg'];
1506 }
1507 }
1508 $smcFunc['db_free_result']($request);
1509
1510 if (empty($attachments))
1511 fatal_lang_error('no_access', false);
1512
1513 // Finally, we are there. Follow through!
1514 if ($is_approve)
1515 ApproveAttachments($attachments);
1516 else
1517 removeAttachments(array('id_attach' => $attachments));
1518
1519 // Return to the topic....
1520 redirectexit($redirect);
1521 }
1522
1523 // Approve an attachment, or maybe even more - no permission check!
1524 function ApproveAttachments($attachments)
1525 {
1526 global $smcFunc;
1527
1528 if (empty($attachments))
1529 return 0;
1530
1531 // For safety, check for thumbnails...
1532 $request = $smcFunc['db_query']('', '
1533 SELECT
1534 a.id_attach, a.id_member, IFNULL(thumb.id_attach, 0) AS id_thumb
1535 FROM {db_prefix}attachments AS a
1536 LEFT JOIN {db_prefix}attachments AS thumb ON (thumb.id_attach = a.id_thumb)
1537 WHERE a.id_attach IN ({array_int:attachments})
1538 AND a.attachment_type = {int:attachment_type}',
1539 array(
1540 'attachments' => $attachments,
1541 'attachment_type' => 0,
1542 )
1543 );
1544 $attachments = array();
1545 while ($row = $smcFunc['db_fetch_assoc']($request))
1546 {
1547 // Update the thumbnail too...
1548 if (!empty($row['id_thumb']))
1549 $attachments[] = $row['id_thumb'];
1550
1551 $attachments[] = $row['id_attach'];
1552 }
1553 $smcFunc['db_free_result']($request);
1554
1555 // Approving an attachment is not hard - it's easy.
1556 $smcFunc['db_query']('', '
1557 UPDATE {db_prefix}attachments
1558 SET approved = {int:is_approved}
1559 WHERE id_attach IN ({array_int:attachments})',
1560 array(
1561 'attachments' => $attachments,
1562 'is_approved' => 1,
1563 )
1564 );
1565
1566 // Remove from the approval queue.
1567 $smcFunc['db_query']('', '
1568 DELETE FROM {db_prefix}approval_queue
1569 WHERE id_attach IN ({array_int:attachments})',
1570 array(
1571 'attachments' => $attachments,
1572 )
1573 );
1574 }
1575
1576 function ManageAttachmentPaths()
1577 {
1578 global $modSettings, $scripturl, $context, $txt, $sourcedir, $smcFunc;
1579
1580 // Saving?
1581 if (isset($_REQUEST['save']))
1582 {
1583 checkSession();
1584
1585 $new_dirs = array();
1586 foreach ($_POST['dirs'] as $id => $path)
1587 {
1588 $id = (int) $id;
1589 if ($id < 1)
1590 continue;
1591
1592 if (empty($path))
1593 {
1594 // Let's not try to delete a path with files in it.
1595 $request = $smcFunc['db_query']('', '
1596 SELECT COUNT(id_attach) AS num_attach
1597 FROM {db_prefix}attachments
1598 WHERE id_folder = {int:id_folder}',
1599 array(
1600 'id_folder' => (int) $id,
1601 )
1602 );
1603
1604 list ($num_attach) = $smcFunc['db_fetch_row']($request);
1605 $smcFunc['db_free_result']($request);
1606
1607 // It's safe to delete.
1608 if ($num_attach == 0)
1609 continue;
1610 }
1611
1612 $new_dirs[$id] = $path;
1613 }
1614
1615 // We need to make sure the current directory is right.
1616 $_POST['current_dir'] = (int) $_POST['current_dir'];
1617 if (empty($_POST['current_dir']) || empty($new_dirs[$_POST['current_dir']]))
1618 fatal_lang_error('attach_path_current_bad', false);
1619
1620 // Going back to just one path?
1621 if (count($new_dirs) == 1)
1622 {
1623 // We might need to reset the paths. This loop will just loop through once.
1624 foreach ($new_dirs as $id => $dir)
1625 {
1626 if ($id != 1)
1627 $smcFunc['db_query']('', '
1628 UPDATE {db_prefix}attachments
1629 SET id_folder = {int:default_folder}
1630 WHERE id_folder = {int:current_folder}',
1631 array(
1632 'default_folder' => 1,
1633 'current_folder' => $id,
1634 )
1635 );
1636
1637 updateSettings(array(
1638 'currentAttachmentUploadDir' => 0,
1639 'attachmentUploadDir' => $dir,
1640 ));
1641 }
1642 }
1643 else
1644 // Save it to the database.
1645 updateSettings(array(
1646 'currentAttachmentUploadDir' => $_POST['current_dir'],
1647 'attachmentUploadDir' => serialize($new_dirs),
1648 ));
1649 }
1650
1651 // Are they here for the first time?
1652 if (empty($modSettings['currentAttachmentUploadDir']))
1653 {
1654 $modSettings['attachmentUploadDir'] = array(
1655 1 => $modSettings['attachmentUploadDir']
1656 );
1657 $modSettings['currentAttachmentUploadDir'] = 1;
1658 }
1659 // Otherwise just load up their attachment paths.
1660 else
1661 $modSettings['attachmentUploadDir'] = unserialize($modSettings['attachmentUploadDir']);
1662
1663 $listOptions = array(
1664 'id' => 'attach_paths',
1665 'base_href' => $scripturl . '?action=admin;area=manageattachments;sa=attachpaths;' . $context['session_var'] . '=' . $context['session_id'],
1666 'title' => $txt['attach_paths'],
1667 'get_items' => array(
1668 'function' => 'list_getAttachDirs',
1669 ),
1670 'columns' => array(
1671 'current_dir' => array(
1672 'header' => array(
1673 'value' => $txt['attach_current_dir'],
1674 ),
1675 'data' => array(
1676 'function' => create_function('$rowData', '
1677 return \'<input type="radio" name="current_dir" value="\' . $rowData[\'id\'] . \'" \' . ($rowData[\'current\'] ? \'checked="checked"\' : \'\') . \' class="input_radio" />\';
1678 '),
1679 'style' => 'text-align: center; width: 15%;',
1680 ),
1681 ),
1682 'path' => array(
1683 'header' => array(
1684 'value' => $txt['attach_path'],
1685 ),
1686 'data' => array(
1687 'function' => create_function('$rowData', '
1688 return \'<input type="text" size="30" name="dirs[\' . $rowData[\'id\'] . \']" value="\' . $rowData[\'path\'] . \'" class="input_text" style="width: 100%" />\';
1689 '),
1690 'style' => 'text-align: center; width: 30%;',
1691 ),
1692 ),
1693 'current_size' => array(
1694 'header' => array(
1695 'value' => $txt['attach_current_size'],
1696 ),
1697 'data' => array(
1698 'db' => 'current_size',
1699 'style' => 'text-align: center; width: 15%;',
1700 ),
1701 ),
1702 'num_files' => array(
1703 'header' => array(
1704 'value' => $txt['attach_num_files'],
1705 ),
1706 'data' => array(
1707 'db' => 'num_files',
1708 'style' => 'text-align: center; width: 15%;',
1709 ),
1710 ),
1711 'status' => array(
1712 'header' => array(
1713 'value' => $txt['attach_dir_status'],
1714 ),
1715 'data' => array(
1716 'db' => 'status',
1717 'style' => 'text-align: center; width: 25%;',
1718 ),
1719 ),
1720 ),
1721 'form' => array(
1722 'href' => $scripturl . '?action=admin;area=manageattachments;sa=attachpaths;' . $context['session_var'] . '=' . $context['session_id'],
1723 ),
1724 'additional_rows' => array(
1725 array(
1726 'position' => 'below_table_data',
1727 'value' => '<input type="hidden" name="' . $context['session_var'] . '" value="' . $context['session_id'] . '" /><input type="submit" name="new_path" value="' . $txt['attach_add_path'] . '" class="button_submit" />&nbsp;<input type="submit" name="save" value="' . $txt['save'] . '" class="button_submit" />',
1728 'style' => 'text-align: right;',
1729 ),
1730 ),
1731 );
1732
1733 require_once($sourcedir . '/Subs-List.php');
1734 createList($listOptions);
1735
1736 // Fix up our template.
1737 $context[$context['admin_menu_name']]['current_subsection'] = 'attachments';
1738 $context['page_title'] = $txt['attach_path_manage'];
1739 $context['sub_template'] = 'attachment_paths';
1740 }
1741
1742 // Prepare the actual attachment directories to be displayed in the list.
1743 function list_getAttachDirs()
1744 {
1745 global $smcFunc, $modSettings, $context, $txt;
1746
1747 // The dirs should already have been unserialized but just in case...
1748 if (!is_array($modSettings['attachmentUploadDir']))
1749 $modSettings['attachmentUploadDir'] = unserialize($modSettings['attachmentUploadDir']);
1750
1751 $request = $smcFunc['db_query']('', '
1752 SELECT id_folder, COUNT(id_attach) AS num_attach
1753 FROM {db_prefix}attachments' . (empty($modSettings['custom_avatar_enabled']) ? '' : '
1754 WHERE attachment_type != {int:type_avatar}') . '
1755 GROUP BY id_folder',
1756 array(
1757 'type_avatar' => 1,
1758 )
1759 );
1760
1761 $expected_files = array();
1762 while ($row = $smcFunc['db_fetch_assoc']($request))
1763 $expected_files[$row['id_folder']] = $row['num_attach'];
1764 $smcFunc['db_free_result']($request);
1765
1766 $attachdirs = array();
1767 foreach ($modSettings['attachmentUploadDir'] as $id => $dir)
1768 {
1769 // If there aren't any attachments in this directory this won't exist.
1770 if (!isset($expected_files[$id]))
1771 $expected_files[$id] = 0;
1772
1773 // Check if the directory is doing okay.
1774 list ($status, $error, $size) = attachDirStatus($dir, $expected_files[$id]);
1775
1776 $attachdirs[] = array(
1777 'id' => $id,
1778 'current' => $id == $modSettings['currentAttachmentUploadDir'],
1779 'path' => $dir,
1780 'current_size' => $size,
1781 'num_files' => $expected_files[$id],
1782 'status' => ($error ? '<span class="error">' : '') . sprintf($txt['attach_dir_' . $status], $context['session_id'], $context['session_var']) . ($error ? '</span>' : ''),
1783 );
1784 }
1785
1786 // Just stick a new directory on at the bottom.
1787 if (isset($_REQUEST['new_path']))
1788 $attachdirs[] = array(
1789 'id' => max(array_merge(array_keys($expected_files), array_keys($modSettings['attachmentUploadDir']))) + 1,
1790 'current' => false,
1791 'path' => '',
1792 'current_size' => '',
1793 'num_files' => '',
1794 'status' => '',
1795 );
1796
1797 return $attachdirs;
1798 }
1799
1800 // Checks the status of an attachment directory and returns an array of the status key, if that status key signifies an error, and the folder size.
1801 function attachDirStatus($dir, $expected_files)
1802 {
1803 if (!is_dir($dir))
1804 return array('does_not_exist', true, '');
1805 elseif (!is_writable($dir))
1806 return array('not_writable', true, '');
1807
1808 // Everything is okay so far, start to scan through the directory.
1809 $dir_size = 0;
1810 $num_files = 0;
1811 $dir_handle = dir($dir);
1812 while ($file = $dir_handle->read())
1813 {
1814 // Now do we have a real file here?
1815 if (in_array($file, array('.', '..', '.htaccess', 'index.php')))
1816 continue;
1817
1818 $dir_size += filesize($dir . '/' . $file);
1819 $num_files++;
1820 }
1821 $dir_handle->close();
1822
1823 $dir_size = round($dir_size / 1024, 2);
1824
1825 if ($num_files < $expected_files)
1826 return array('files_missing', true, $dir_size);
1827 // Empty?
1828 elseif ($expected_files == 0)
1829 return array('unused', false, $dir_size);
1830 // All good!
1831 else
1832 return array('ok', false, $dir_size);
1833 }
1834
1835 ?>