PageRenderTime 82ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/sources/admin/ManageAttachments.php

https://github.com/Arantor/Elkarte
PHP | 2433 lines | 1859 code | 283 blank | 291 comment | 310 complexity | c1292f73b09bb0efa1251e47c4fc5b5b MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-3.0

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

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

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