PageRenderTime 83ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/Sources/ManageAttachments.php

https://github.com/smf-portal/SMF2.1
PHP | 2804 lines | 2156 code | 317 blank | 331 comment | 354 complexity | bdad0f490f02cff1e33eca646315cf8b MD5 | raw file

Large files files are truncated, but you can click here to view the full file

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

Large files files are truncated, but you can click here to view the full file