PageRenderTime 63ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/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
  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('attachment_no_msg', $to_fix))
  1189. $smcFunc['db_query']('', '
  1190. DELETE FROM {db_prefix}attachments
  1191. WHERE id_attach IN ({array_int:to_remove})
  1192. AND id_member = {int:no_member}
  1193. AND id_msg != {int:no_msg}',
  1194. array(
  1195. 'to_remove' => $to_remove,
  1196. 'no_member' => 0,
  1197. 'no_msg' => 0,
  1198. )
  1199. );
  1200. pauseAttachmentMaintenance($to_fix, $thumbnails);
  1201. }
  1202. $_GET['step'] = 5;
  1203. $_GET['substep'] = 0;
  1204. pauseAttachmentMaintenance($to_fix);
  1205. }
  1206. // What about files who are not recorded in the database?
  1207. if ($_GET['step'] <= 5)
  1208. {
  1209. // Just use the current path for temp files.
  1210. if (!is_array($modSettings['attachmentUploadDir']))
  1211. $modSettings['attachmentUploadDir'] = unserialize($modSettings['attachmentUploadDir']);
  1212. $attach_dirs = $modSettings['attachmentUploadDir'];
  1213. $current_check = 0;
  1214. $max_checks = 500;
  1215. $files_checked = empty($_GET['substep']) ? 0 : $_GET['substep'];
  1216. foreach ($attach_dirs as $attach_dir)
  1217. {
  1218. if ($dir = @opendir($attach_dir))
  1219. {
  1220. while ($file = readdir($dir))
  1221. {
  1222. if ($file == '.' || $file == '..')
  1223. continue;
  1224. if ($files_checked <= $current_check)
  1225. {
  1226. // Temporary file, get rid of it!
  1227. if (strpos($file, 'post_tmp_') !== false)
  1228. {
  1229. // Temp file is more than 5 hours old!
  1230. if (filemtime($attach_dir . '/' . $file) < time() - 18000)
  1231. @unlink($attach_dir . '/' . $file);
  1232. }
  1233. // That should be an attachment, let's check if we have it in the database
  1234. elseif (strpos($file, '_') !== false)
  1235. {
  1236. $attachID = (int) substr($file, 0, strpos($file, '_'));
  1237. if (!empty($attachID))
  1238. {
  1239. $request = $smcFunc['db_query']('', '
  1240. SELECT id_attach
  1241. FROM {db_prefix}attachments
  1242. WHERE id_attach = {int:attachment_id}
  1243. LIMIT 1',
  1244. array(
  1245. 'attachment_id' => $attachID,
  1246. )
  1247. );
  1248. if ($smcFunc['db_num_rows']($request) == 0)
  1249. {
  1250. if ($fix_errors && in_array('files_without_attachment', $to_fix))
  1251. {
  1252. @unlink($attach_dir . '/' . $file);
  1253. }
  1254. else
  1255. {
  1256. $context['repair_errors']['files_without_attachment']++;
  1257. $to_fix[] = 'files_without_attachment';
  1258. }
  1259. }
  1260. $smcFunc['db_free_result']($request);
  1261. }
  1262. }
  1263. elseif ($file != 'index.php')
  1264. {
  1265. if ($fix_errors && in_array('files_without_attachment', $to_fix))
  1266. {
  1267. @unlink($attach_dir . '/' . $file);
  1268. }
  1269. else
  1270. {
  1271. $context['repair_errors']['files_without_attachment']++;
  1272. $to_fix[] = 'files_without_attachment';
  1273. }
  1274. }
  1275. }
  1276. $current_check++;
  1277. $_GET['substep'] = $current_check;
  1278. if ($current_check - $files_checked >= $max_checks)
  1279. pauseAttachmentMaintenance($to_fix);
  1280. }
  1281. closedir($dir);
  1282. }
  1283. }
  1284. $_GET['step'] = 5;
  1285. $_GET['substep'] = 0;
  1286. pauseAttachmentMaintenance($to_fix);
  1287. }
  1288. // Got here we must be doing well - just the template! :D
  1289. $context['page_title'] = $txt['repair_attachments'];
  1290. $context[$context['admin_menu_name']]['current_subsection'] = 'maintenance';
  1291. $context['sub_template'] = 'attachment_repair';
  1292. // What stage are we at?
  1293. $context['completed'] = $fix_errors ? true : false;
  1294. $context['errors_found'] = !empty($to_fix) ? true : false;
  1295. }
  1296. /**
  1297. * Function called in-between each round of attachments and avatar repairs.
  1298. * Called by repairAttachments().
  1299. * If repairAttachments() has more steps added, this function needs updated!
  1300. *
  1301. * @param array $to_fix attachments to fix
  1302. * @param int $max_substep = 0
  1303. */
  1304. function pauseAttachmentMaintenance($to_fix, $max_substep = 0)
  1305. {
  1306. global $context, $txt, $time_start;
  1307. // Try get more time...
  1308. @set_time_limit(600);
  1309. if (function_exists('apache_reset_timeout'))
  1310. @apache_reset_timeout();
  1311. // Have we already used our maximum time?
  1312. if (time() - array_sum(explode(' ', $time_start)) < 3 || $context['starting_substep'] == $_GET['substep'])
  1313. return;
  1314. $context['continue_get_data'] = '?action=admin;area=manageattachments;sa=repair' . (isset($_GET['fixErrors']) ? ';fixErrors' : '') . ';step=' . $_GET['step'] . ';substep=' . $_GET['substep'] . ';' . $context['session_var'] . '=' . $context['session_id'];
  1315. $context['page_title'] = $txt['not_done_title'];
  1316. $context['continue_post_data'] = '';
  1317. $context['continue_countdown'] = '2';
  1318. $context['sub_template'] = 'not_done';
  1319. // Specific stuff to not break this template!
  1320. $context[$context['admin_menu_name']]['current_subsection'] = 'maintenance';
  1321. // Change these two if more steps are added!
  1322. if (empty($max_substep))
  1323. $context['continue_percent'] = round(($_GET['step'] * 100) / 25);
  1324. else
  1325. $context['continue_percent'] = round(($_GET['step'] * 100 + ($_GET['substep'] * 100) / $max_substep) / 25);
  1326. // Never more than 100%!
  1327. $context['continue_percent'] = min($context['continue_percent'], 100);
  1328. $_SESSION['attachments_to_fix'] = $to_fix;
  1329. $_SESSION['attachments_to_fix2'] = $context['repair_errors'];
  1330. obExit();
  1331. }
  1332. /**
  1333. * This function lists and allows updating of multiple attachments paths.
  1334. */
  1335. function action_attachpaths()
  1336. {
  1337. global $modSettings, $scripturl, $context, $txt, $smcFunc;
  1338. // Since this needs to be done eventually.
  1339. if (!is_array($modSettings['attachmentUploadDir']))
  1340. $modSettings['attachmentUploadDir'] = unserialize($modSettings['attachmentUploadDir']);
  1341. if (!isset($modSettings['attachment_basedirectories']))
  1342. $modSettings['attachment_basedirectories'] = array();
  1343. elseif (!is_array($modSettings['attachment_basedirectories']))
  1344. $modSettings['attachment_basedirectories'] = unserialize($modSettings['attachment_basedirectories']);
  1345. $errors = array();
  1346. // Saving?
  1347. if (isset($_REQUEST['save']))
  1348. {
  1349. checkSession();
  1350. $_POST['current_dir'] = isset($_POST['current_dir']) ? (int) $_POST['current_dir'] : 0;
  1351. $new_dirs = array();
  1352. foreach ($_POST['dirs'] as $id => $path)
  1353. {
  1354. $error = '';
  1355. $id = (int) $id;
  1356. if ($id < 1)
  1357. continue;
  1358. // Hmm, a new path maybe?
  1359. if (!array_key_exists($id, $modSettings['attachmentUploadDir']))
  1360. {
  1361. // or is it?
  1362. if (in_array($path, $modSettings['attachmentUploadDir']) || in_array(BOARDDIR . DIRECTORY_SEPARATOR . $path, $modSettings['attachmentUploadDir']))
  1363. {
  1364. $errors[] = $path . ': ' . $txt['attach_dir_duplicate_msg'];
  1365. continue;
  1366. }
  1367. // OK, so let's try to create it then.
  1368. require_once(SUBSDIR . '/Attachments.subs.php');
  1369. if (automanage_attachments_create_directory($path))
  1370. $_POST['current_dir'] = $modSettings['currentAttachmentUploadDir'];
  1371. else
  1372. $errors[] = $path . ': ' . $txt[$context['dir_creation_error']];
  1373. }
  1374. // Changing a directory name?
  1375. if (!empty($modSettings['attachmentUploadDir'][$id]) && !empty($path) && $path != $modSettings['attachmentUploadDir'][$id])
  1376. {
  1377. if ($path != $modSettings['attachmentUploadDir'][$id] && !is_dir($path))
  1378. {
  1379. if (!@rename($modSettings['attachmentUploadDir'][$id], $path))
  1380. {
  1381. $errors[] = $path . ': ' . $txt['attach_dir_no_rename'];
  1382. $path = $modSettings['attachmentUploadDir'][$id];
  1383. }
  1384. }
  1385. else
  1386. {
  1387. $errors[] = $path . ': ' . $txt['attach_dir_exists_msg'];
  1388. $path = $modSettings['attachmentUploadDir'][$id];
  1389. }
  1390. // Update the base directory path
  1391. if (!empty($modSettings['attachment_basedirectories']) && array_key_exists($id, $modSettings['attachment_basedirectories']))
  1392. {
  1393. $base = $modSettings['basedirectory_for_attachments'] == $modSettings['attachmentUploadDir'][$id] ? $path : $modSettings['basedirectory_for_attachments'];
  1394. $modSettings['attachment_basedirectories'][$id] = $path;
  1395. updateSettings(array(
  1396. 'attachment_basedirectories' => serialize($modSettings['attachment_basedirectories']),
  1397. 'basedirectory_for_attachments' => $base,
  1398. ));
  1399. $modSettings['attachment_basedirectories'] = unserialize($modSettings['attachment_basedirectories']);
  1400. }
  1401. }
  1402. if (empty($path))
  1403. {
  1404. $path = $modSettings['attachmentUploadDir'][$id];
  1405. // It's not a good idea to delete the current directory.
  1406. if ($id == (!empty($_POST['current_dir']) ? $_POST['current_dir'] : $modSettings['currentAttachmentUploadDir']))
  1407. $errors[] = $path . ': ' . $txt['attach_dir_is_current'];
  1408. // Or the current base directory
  1409. elseif (!empty($modSettings['basedirectory_for_attachments']) && $modSettings['basedirectory_for_attachments'] == $modSettings['attachmentUploadDir'][$id])
  1410. $errors[] = $path . ': ' . $txt['attach_dir_is_current_bd'];
  1411. else
  1412. {
  1413. // Let's not try to delete a path with files in it.
  1414. $request = $smcFunc['db_query']('', '
  1415. SELECT COUNT(id_attach) AS num_attach
  1416. FROM {db_prefix}attachments
  1417. WHERE id_folder = {int:id_folder}',
  1418. array(
  1419. 'id_folder' => (int) $id,
  1420. )
  1421. );
  1422. list ($num_attach) = $smcFunc['db_fetch_row']($request);
  1423. $smcFunc['db_free_result']($request);
  1424. // A check to see if it's a used base dir.
  1425. if (!empty($modSettings['attachment_basedirectories']))
  1426. {
  1427. // Count any sub-folders.
  1428. foreach ($modSettings['attachmentUploadDir'] as $sub)
  1429. if (strpos($sub, $path . DIRECTORY_SEPARATOR) !== false)
  1430. $num_attach++;
  1431. }
  1432. // It's safe to delete. So try to delete the folder also
  1433. if ($num_attach == 0)
  1434. {
  1435. if (is_dir($path))
  1436. $doit = true;
  1437. elseif (is_dir(BOARDDIR . DIRECTORY_SEPARATOR . $path))
  1438. {
  1439. $doit = true;
  1440. $path = BOARDDIR . DIRECTORY_SEPARATOR . $path;
  1441. }
  1442. if (isset($doit))
  1443. {
  1444. unlink($path . '/.htaccess');
  1445. unlink($path . '/index.php');
  1446. if (!@rmdir($path))
  1447. $error = $path . ': ' . $txt['attach_dir_no_delete'];
  1448. }
  1449. // Remove it from the base directory list.
  1450. if (empty($error) && !empty($modSettings['attachment_basedirectories']))
  1451. {
  1452. unset($modSettings['attachment_basedirectories'][$id]);
  1453. updateSettings(array('attachment_basedirectories' => serialize($modSettings['attachment_basedirectories'])));
  1454. $modSettings['attachment_basedirectories'] = unserialize($modSettings['attachment_basedirectories']);
  1455. }
  1456. }
  1457. else
  1458. $error = $path . ': ' . $txt['attach_dir_no_remove'];
  1459. if (empty($error))
  1460. continue;
  1461. else
  1462. $errors[] = $error;
  1463. }
  1464. }
  1465. $new_dirs[$id] = $path;
  1466. }
  1467. // We need to make sure the current directory is right.
  1468. if (empty($_POST['current_dir']) && !empty($modSettings['currentAttachmentUploadDir']))
  1469. $_POST['current_dir'] = $modSettings['currentAttachmentUploadDir'];
  1470. // Find the current directory if there's no value carried,
  1471. if (empty($_POST['current_dir']) || empty($new_dirs[$_POST['current_dir']]))
  1472. {
  1473. if (array_key_exists($modSettings['currentAttachmentUploadDir'], $modSettings['attachmentUploadDir']))
  1474. $_POST['current_dir'] = $modSettings['currentAttachmentUploadDir'];
  1475. else
  1476. $_POST['current_dir'] = max(array_keys($modSettings['attachmentUploadDir']));
  1477. }
  1478. // If the user wishes to go back, update the last_dir array
  1479. if ($_POST['current_dir'] != $modSettings['currentAttachmentUploadDir']&& !empty($modSettings['last_attachments_directory']) && (isset($modSettings['last_attachments_directory'][$_POST['current_dir']]) || isset($modSettings['last_attachments_directory'][0])))
  1480. {
  1481. if (!is_array($modSettings['last_attachments_directory']))
  1482. $modSettings['last_attachments_directory'] = unserialize($modSettings['last_attachments_directory']);
  1483. $num = substr(strrchr($modSettings['attachmentUploadDir'][$_POST['current_dir']], '_'), 1);
  1484. if (is_numeric($num))
  1485. {
  1486. // Need to find the base folder.
  1487. $bid = -1;
  1488. $use_subdirectories_for_attachments = 0;
  1489. if (!empty($modSettings['attachment_basedirectories']))
  1490. foreach ($modSettings['attachment_basedirectories'] as $bid => $base)
  1491. if (strpos($modSettings['attachmentUploadDir'][$_POST['current_dir']], $base . DIRECTORY_SEPARATOR) !==false)
  1492. {
  1493. $use_subdirectories_for_attachments = 1;
  1494. break;
  1495. }
  1496. if ($use_subdirectories_for_attachments == 0 && strpos($modSettings['attachmentUploadDir'][$_POST['current_dir']], BOARDDIR . DIRECTORY_SEPARATOR) !== false)
  1497. $bid = 0;
  1498. $modSettings['last_attachments_directory'][$bid] = (int) $num;
  1499. $modSettings['basedirectory_for_attachments'] = !empty($modSettings['basedirectory_for_attachments']) ? $modSettings['basedirectory_for_attachments'] : '';
  1500. $modSettings['use_subdirectories_for_attachments'] = !empty($modSettings['use_subdirectories_for_attachments']) ? $modSettings['use_subdirectories_for_attachments'] : 0;
  1501. updateSettings(array(
  1502. 'last_attachments_directory' => serialize($modSettings['last_attachments_directory']),
  1503. 'basedirectory_for_attachments' => $bid == 0 ? $modSettings['basedirectory_for_attachments'] : $modSettings['attachment_basedirectories'][$bid],
  1504. 'use_subdirectories_for_attachments' => $use_subdirectories_for_attachments,
  1505. ));
  1506. }
  1507. }
  1508. // Going back to just one path?
  1509. if (count($new_dirs) == 1)
  1510. {
  1511. // We might need to reset the paths. This loop will just loop through once.
  1512. foreach ($new_dirs as $id => $dir)
  1513. {
  1514. if ($id != 1)
  1515. $smcFunc['db_query']('', '
  1516. UPDATE {db_prefix}attachments
  1517. SET id_folder = {int:default_folder}
  1518. WHERE id_folder = {int:current_folder}',
  1519. array(
  1520. 'default_folder' => 1,
  1521. 'current_folder' => $id,
  1522. )
  1523. );
  1524. $update = array(
  1525. 'currentAttachmentUploadDir' => 1,
  1526. 'attachmentUploadDir' => serialize(array(1 => $dir)),
  1527. );
  1528. }
  1529. }
  1530. else
  1531. {
  1532. // Save it to the database.
  1533. $update = array(
  1534. 'currentAttachmentUploadDir' => $_POST['current_dir'],
  1535. 'attachmentUploadDir' => serialize($new_dirs),
  1536. );
  1537. }
  1538. if (!empty($update))
  1539. updateSettings($update);
  1540. if (!empty($errors))
  1541. $_SESSION['errors']['dir'] = $errors;
  1542. redirectexit('action=admin;area=manageattachments;sa=attachpaths;' . $context['session_var'] . '=' . $context['session_id']);
  1543. }
  1544. // Saving a base directory?
  1545. if (isset($_REQUEST['save2']))
  1546. {
  1547. checkSession();
  1548. // Changing the current base directory?
  1549. $_POST['current_base_dir'] = (int) $_POST['current_base_dir'];
  1550. if (empty($_POST['new_base_dir']) && !empty($_POST['current_base_dir']))
  1551. {
  1552. if ($modSettings['basedirectory_for_attachments'] != $modSettings['attachmentUploadDir'][$_POST['current_base_dir']])
  1553. $update = (array(
  1554. 'basedirectory_for_attachments' => $modSettings['attachmentUploadDir'][$_POST['current_base_dir']],
  1555. ));
  1556. //$modSettings['attachmentUploadDir'] = serialize($modSettings['attachmentUploadDir']);
  1557. }
  1558. If (isset($_POST['base_dir']))
  1559. {
  1560. foreach ($_POST['base_dir'] as $id => $dir)
  1561. {
  1562. if (!empty($dir) && $dir != $modSettings['attachmentUploadDir'][$id])
  1563. {
  1564. if (@rename($modSettings['attachmentUploadDir'][$id], $dir))
  1565. {
  1566. $modSettings['attachmentUploadDir'][$id] = $dir;
  1567. $modSettings['attachment_basedirectories'][$id] = $dir;
  1568. $update = (array(
  1569. 'attachmentUploadDir' => serialize($modSettings['attachmentUploadDir']),
  1570. 'attachment_basedirectories' => serialize($modSettings['attachment_basedirectories']),
  1571. 'basedirectory_for_attachments' => $modSettings['attachmentUploadDir'][$_POST['current_base_dir']],
  1572. ));
  1573. }
  1574. }
  1575. if (empty($dir))
  1576. {
  1577. if ($id == $_POST['current_base_dir'])
  1578. {
  1579. $errors[] = $modSettings['attachmentUploadDir'][$id] . ': ' . $txt['attach_dir_is_current'];
  1580. continue;
  1581. }
  1582. unset($modSettings['attachment_basedirectories'][$id]);
  1583. $update = (array(
  1584. 'attachment_basedirectories' => serialize($modSettings['attachment_basedirectories']),
  1585. 'basedirectory_for_attachments' => $modSettings['attachmentUploadDir'][$_POST['current_base_dir']],
  1586. ));
  1587. }
  1588. }
  1589. }
  1590. // Or adding a new one?
  1591. if (!empty($_POST['new_base_dir']))
  1592. {
  1593. require_once(SUBSDIR . '/Attachments.subs.php');
  1594. $_POST['new_base_dir'] = htmlspecialchars($_POST['new_base_dir'], ENT_QUOTES);
  1595. $current_dir = $modSettings['currentAttachmentUploadDir'];
  1596. if (!in_array($_POST['new_base_dir'], $modSettings['attachmentUploadDir']))
  1597. {
  1598. if (!automanage_attachments_create_directory($_POST['new_base_dir']))
  1599. $errors[] = $_POST['new_base_dir'] . ': ' . $txt['attach_dir_base_no_create'];
  1600. }
  1601. $modSettings['currentAttachmentUploadDir'] = array_search($_POST['new_base_dir'], $modSettings['attachmentUploadDir']);
  1602. if (!in_array($_POST['new_base_dir'], $modSettings['attachment_basedirectories']))
  1603. $modSettings['attachment_basedirectories'][$modSettings['currentAttachmentUploadDir']] = $_POST['new_base_dir'];
  1604. ksort($modSettings['attachment_basedirectories']);
  1605. $update = (array(
  1606. 'attachment_basedirectories' => serialize($modSettings['attachment_basedirectories']),
  1607. 'basedirectory_for_attachments' => $_POST['new_base_dir'],
  1608. 'currentAttachmentUploadDir' => $current_dir,
  1609. ));
  1610. }
  1611. if (!empty($errors))
  1612. $_SESSION['errors']['base'] = $errors;
  1613. if (!empty($update))
  1614. updateSettings($update);
  1615. redirectexit('action=admin;area=manageattachments;sa=attachpaths;' . $context['session_var'] . '=' . $context['session_id']);
  1616. }
  1617. if (isset($_SESSION['errors']))
  1618. {
  1619. if (is_array($_SESSION['errors']))
  1620. {
  1621. $errors = array();
  1622. if (!empty($_SESSION['errors']['dir']))
  1623. foreach ($_SESSION['errors']['dir'] as $error)
  1624. $errors['dir'][] = $smcFunc['htmlspecialchars']($error, ENT_QUOTES);
  1625. if (!empty($_SESSION['errors']['base']))
  1626. foreach ($_SESSION['errors']['base'] as $error)
  1627. $errors['base'][] = $smcFunc['htmlspecialchars']($error, ENT_QUOTES);
  1628. }
  1629. unset($_SESSION['errors']);
  1630. }
  1631. $listOptions = array(
  1632. 'id' => 'attach_paths',
  1633. 'base_href' => $scripturl . '?action=admin;area=manageattachments;sa=attachpaths;' . $context['session_var'] . '=' . $context['session_id'],
  1634. 'title' => $txt['attach_paths'],
  1635. 'get_items' => array(
  1636. 'function' => 'list_getAttachDirs',
  1637. ),
  1638. 'columns' => array(
  1639. 'current_dir' => array(
  1640. 'header' => array(
  1641. 'value' => $txt['attach_current'],
  1642. 'class' => 'centercol',
  1643. ),
  1644. 'data' => array(
  1645. 'function' => create_function('$rowData', '
  1646. return \'<input type="radio" name="current_dir" value="\' . $rowData[\'id\'] . \'" \' . ($rowData[\'current\'] ? \' checked="checked"\' : \'\') . (!empty($rowData[\'disable_current\']) ? \' disabled="disabled"\' : \'\') . \' class="input_radio" />\';
  1647. '),
  1648. 'style' => 'width: 10%;',
  1649. 'class' => 'centercol',
  1650. ),
  1651. ),
  1652. 'path' => array(
  1653. 'header' => array(
  1654. 'value' => $txt['attach_path'],
  1655. ),
  1656. 'data' => array(
  1657. 'function' => create_function('$rowData', '
  1658. return \'<input type="hidden" name="dirs[\' . $rowData[\'id\'] . \']" value="\' . $rowData[\'path\'] . \'" /><input type="text" size="40" name="dirs[\' . $rowData[\'id\'] . \']" value="\' . $rowData[\'path\'] . \'"\' . (!empty($rowData[\'disable_base_dir\']) ? \' disabled="disabled"\' : \'\') . \' class="input_text" style="width: 100%" />\';
  1659. '),
  1660. 'style' => 'width: 40%;',
  1661. ),
  1662. ),
  1663. 'current_size' => array(
  1664. 'header' => array(
  1665. 'value' => $txt['attach_current_size'],
  1666. ),
  1667. 'data' => array(
  1668. 'db' => 'current_size',
  1669. 'style' => 'width: 15%;',
  1670. ),
  1671. ),
  1672. 'num_files' => array(
  1673. 'header' => array(
  1674. 'value' => $txt['attach_num_files'],
  1675. ),
  1676. 'data' => array(
  1677. 'db' => 'num_files',
  1678. 'style' => 'width: 15%;',
  1679. ),
  1680. ),
  1681. 'status' => array(
  1682. 'header' => array(
  1683. 'value' => $txt['attach_dir_status'],
  1684. 'class' => 'centercol',
  1685. ),
  1686. 'data' => array(
  1687. 'db' => 'status',
  1688. 'style' => 'width: 25%;',
  1689. 'class' => 'centercol',
  1690. ),
  1691. ),
  1692. ),
  1693. 'form' => array(
  1694. 'href' => $scripturl . '?action=admin;area=manageattachments;sa=attachpaths;' . $context['session_var'] . '=' . $context['session_id'],
  1695. ),
  1696. 'additional_rows' => array(
  1697. array(
  1698. 'position' => 'below_table_data',
  1699. 'value' => '
  1700. <input type="hidden" name="' . $context['session_var'] . '" value="' . $context['session_id'] . '" />
  1701. <input type="submit" name="save" value="' . $txt['save'] . '" class="button_submit" />
  1702. <input type="submit" name="new_path" value="' . $txt['attach_add_path'] . '" class="button_submit" />',
  1703. ),
  1704. empty($errors['dir']) ? array(
  1705. 'position' => 'top_of_list',
  1706. 'value' => $txt['attach_dir_desc'],
  1707. 'style' => 'padding: 5px 10px;',
  1708. 'class' => 'windowbg2 smalltext'
  1709. ) : array(
  1710. 'position' => 'top_of_list',
  1711. 'value' => $txt['attach_dir_save_problem'] . '<br />' . implode('<br />', $errors['dir']),
  1712. 'style' => 'padding-left: 35px;',
  1713. 'class' => 'noticebox',
  1714. ),
  1715. ),
  1716. );
  1717. require_once(SUBSDIR . '/List.subs.php');
  1718. createList($listOptions);
  1719. if (!empty($modSettings['attachment_basedirectories']))
  1720. {
  1721. $listOptions2 = array(
  1722. 'id' => 'base_paths',
  1723. 'base_href' => $scripturl . '?action=admin;area=manageattachments;sa=attachpaths;' . $context['session_var'] . '=' . $context['session_id'],
  1724. 'title' => $txt['attach_base_paths'],
  1725. 'get_items' => array(
  1726. 'function' => 'list_getBaseDirs',
  1727. ),
  1728. 'columns' => array(
  1729. 'current_dir' => array(
  1730. 'header' => array(
  1731. 'value' => $txt['attach_current'],
  1732. 'class' => 'centercol',
  1733. ),
  1734. 'data' => array(
  1735. 'function' => create_function('$rowData', '
  1736. return \'<input type="radio" name="current_base_dir" value="\' . $rowData[\'id\'] . \'" \' . ($rowData[\'current\'] ? \' checked="checked"\' : \'\') . \' class="input_radio" />\';
  1737. '),
  1738. 'style' => 'width: 10%;',
  1739. 'class' => 'centercol',
  1740. ),
  1741. ),
  1742. 'path' => array(
  1743. 'header' => array(
  1744. 'value' => $txt['attach_path'],
  1745. ),
  1746. 'data' => array(
  1747. 'db' => 'path',
  1748. 'style' => 'width: 45%;',
  1749. ),
  1750. ),
  1751. 'num_dirs' => array(
  1752. 'header' => array(
  1753. 'value' => $txt['attach_num_dirs'],
  1754. ),
  1755. 'data' => array(
  1756. 'db' => 'num_dirs',
  1757. 'style' => 'width: 15%;',
  1758. ),
  1759. ),
  1760. 'status' => array(
  1761. 'header' => array(
  1762. 'value' => $txt['attach_dir_status'],
  1763. ),
  1764. 'data' => array(
  1765. 'db' => 'status',
  1766. 'style' => 'width: 15%;',
  1767. 'class' => 'centercol',
  1768. ),
  1769. ),
  1770. ),
  1771. 'form' => array(
  1772. 'href' => $scripturl . '?action=admin;area=manageattachments;sa=attachpaths;' . $context['session_var'] . '=' . $context['session_id'],
  1773. ),
  1774. 'additional_rows' => array(
  1775. array(
  1776. 'position' => 'below_table_data',
  1777. 'value' => '<input type="hidden" name="' . $context['session_var'] . '" value="' . $context['session_id'] . '" /><input type="submit" name="save2" value="' . $txt['save'] . '" class="button_submit" />
  1778. <input type="submit" name="new_base_path" value="' . $txt['attach_add_path'] . '" class="button_submit" />',
  1779. ),
  1780. empty($errors['base']) ? array(
  1781. 'position' => 'top_of_list',
  1782. 'value' => $txt['attach_dir_base_desc'],
  1783. 'style' => 'padding: 5px 10px;',
  1784. 'class' => 'windowbg2 smalltext'
  1785. ) : array(
  1786. 'position' => 'top_of_list',
  1787. 'value' => $txt['attach_dir_save_problem'] . '<br />' . implode('<br />', $errors['base']),
  1788. 'style' => 'padding-left: 35px',
  1789. 'class' => 'noticebox',
  1790. ),
  1791. ),
  1792. );
  1793. createList($listOptions2);
  1794. }
  1795. // Fix up our template.
  1796. $context[$context['admin_menu_name']]['current_subsection'] = 'attachpaths';
  1797. $context['page_title'] = $txt['attach_path_manage'];
  1798. $context['sub_template'] = 'attachment_paths';
  1799. }
  1800. /**
  1801. * Prepare the actual attachment directories to be displayed in the list.
  1802. */
  1803. function list_getAttachDirs()
  1804. {
  1805. global $smcFunc, $modSettings, $context, $txt;
  1806. $request = $smcFunc['db_query']('', '
  1807. SELECT id_folder, COUNT(id_attach) AS num_attach, SUM(size) AS size_attach
  1808. FROM {db_prefix}attachments
  1809. WHERE attachment_type != {int:type}
  1810. GROUP BY id_folder',
  1811. array(
  1812. 'type' => 1,
  1813. )
  1814. );
  1815. $expected_files = array();
  1816. $expected_size = array();
  1817. while ($row = $smcFunc['db_fetch_assoc']($request))
  1818. {
  1819. $expected_files[$row['id_folder']] = $row['num_attach'];
  1820. $expected_size[$row['id_folder']] = $row['size_attach'];
  1821. }
  1822. $smcFunc['db_free_result']($request);
  1823. $attachdirs = array();
  1824. foreach ($modSettings['attachmentUploadDir'] as $id => $dir)
  1825. {
  1826. // If there aren't any attachments in this directory this won't exist.
  1827. if (!isset($expected_files[$id]))
  1828. $expected_files[$id] = 0;
  1829. // Check if the directory is doing okay.
  1830. list ($status, $error, $files) = attachDirStatus($dir, $expected_files[$id]);
  1831. // If it is one, let's show that it's a base directory.
  1832. $sub_dirs = 0;
  1833. $is_base_dir = false;
  1834. if (!empty($modSettings['attachment_basedirectories']))
  1835. {
  1836. $is_base_dir = in_array($dir, $modSettings['attachment_basedirectories']);
  1837. // Count any sub-folders.
  1838. foreach ($modSettings['attachmentUploadDir'] as $sid => $sub)
  1839. if (strpos($sub, $dir . DIRECTORY_SEPARATOR) !== false)
  1840. {
  1841. $expected_files[$id]++;
  1842. $sub_dirs++;
  1843. }
  1844. }
  1845. $attachdirs[] = array(
  1846. 'id' => $id,
  1847. 'current' => $id == $modSettings['currentAttachmentUploadDir'],
  1848. 'disable_current' => isset($modSettings['automanage_attachments']) && $modSettings['automanage_attachments'] > 1,
  1849. 'disable_base_dir' => $is_base_dir && $sub_dirs > 0 && !empty($files) && empty($error) && empty($save_errors),
  1850. 'path' => $dir,
  1851. 'current_size' => !empty($expected_size[$id]) ? comma_format($expected_size[$id] / 1024, 0) : 0,
  1852. 'num_files' => comma_format($expected_files[$id] - $sub_dirs, 0) . ($sub_dirs > 0 ? ' (' . $sub_dirs . ')' : ''),
  1853. 'status' => ($is_base_dir ? $txt['attach_dir_basedir'] . '<br />' : '') . ($error ? '<div class="error">' : '') . sprintf($txt['attach_dir_' . $status], $context['session_id'], $context['session_var']) . ($error ? '</div>' : ''),
  1854. );
  1855. }
  1856. // Just stick a new directory on at the bottom.
  1857. if (isset($_REQUEST['new_path']))
  1858. $attachdirs[] = array(
  1859. 'id' => max(array_merge(array_keys($expected_files), array_keys($modSettings['attachmentUploadDir']))) + 1,
  1860. 'current' => false,
  1861. 'path' => '',
  1862. 'current_size' => '',
  1863. 'num_files' => '',
  1864. 'status' => '',
  1865. );
  1866. return $attachdirs;
  1867. }
  1868. /**
  1869. * Prepare the base directories to be displayed in a list.
  1870. */
  1871. function list_getBaseDirs()
  1872. {
  1873. global $modSettings, $context, $txt;
  1874. if (empty($modSettings['attachment_basedirectories']))
  1875. return;
  1876. $basedirs = array();
  1877. // Get a list of the base directories.
  1878. foreach ($modSettings['attachment_basedirectories'] as $id => $dir)
  1879. {
  1880. // Loop through the attach directory array to count any sub-directories
  1881. $expected_dirs = 0;
  1882. foreach ($modSettings['attachmentUploadDir'] as $sid => $sub)
  1883. if (strpos($sub, $dir . DIRECTORY_SEPARATOR) !== false)
  1884. $expected_dirs++;
  1885. if (!is_dir($dir))
  1886. $status = 'does_not_exist';
  1887. elseif (!is_writeable($dir))
  1888. $status = 'not_writable';
  1889. else
  1890. $status = 'ok';
  1891. $basedirs[] = array(
  1892. 'id' => $id,
  1893. 'current' => $dir == $modSettings['basedirectory_for_attachments'],
  1894. 'path' => $expected_dirs > 0 ? $dir : ('<input type="text" name="base_dir[' . $id . ']" value="' . $dir . '" size="40" />'),
  1895. 'num_dirs' => $expected_dirs,
  1896. 'status' => $status == 'ok' ? $txt['attach_dir_ok'] : ('<span class="error">' . $txt['attach_dir_' . $status] . '</span>'),
  1897. );
  1898. }
  1899. if (isset($_REQUEST['new_base_path']))
  1900. $basedirs[] = array(
  1901. 'id' => '',
  1902. 'current' => false,
  1903. 'path' => '<input type="text" name="new_base_dir" value="" size="40" />',
  1904. 'num_dirs' => '',
  1905. 'status' => '',
  1906. );
  1907. return $basedirs;
  1908. }
  1909. /**
  1910. * Checks the status of an attachment directory and returns an array
  1911. * of the status key, if that status key signifies an error, and
  1912. * the file count.
  1913. *
  1914. * @param string $dir
  1915. * @param int $expected_files
  1916. */
  1917. function attachDirStatus($dir, $expected_files)
  1918. {
  1919. global $context;
  1920. if (!is_dir($dir))
  1921. return array('does_not_exist', true, '');
  1922. elseif (!is_writable($dir))
  1923. return array('not_writable', true, '');
  1924. // Everything is okay so far, start to scan through the directory.
  1925. $num_files = 0;
  1926. $dir_handle = dir($dir);
  1927. while ($file = $dir_handle->read())
  1928. {
  1929. // Now do we have a real file here?
  1930. if (in_array($file, array('.', '..', '.htaccess', 'index.php')))
  1931. continue;
  1932. $num_files++;
  1933. }
  1934. $dir_handle->close();
  1935. if ($num_files < $expected_files)
  1936. return array('files_missing', true, $num_files);
  1937. // Empty?
  1938. elseif ($expected_files == 0)
  1939. return array('unused', false, $num_files);
  1940. // All good!
  1941. else
  1942. return array('ok', false, $num_files);
  1943. }
  1944. /**
  1945. * Maintance function to move attachments from one directory to another
  1946. */
  1947. function action_transfer()
  1948. {
  1949. global $modSettings, $context, $smcFunc, $txt;
  1950. checkSession();
  1951. $modSettings['attachmentUploadDir'] = unserialize($modSettings['attachmentUploadDir']);
  1952. if (!empty($modSettings['attachment_basedirectories']))
  1953. $modSettings['attachment_basedirectories'] = unserialize($modSettings['attachment_basedirectories']);
  1954. else
  1955. $modSettings['basedirectory_for_attachments'] = array();
  1956. $_POST['from'] = (int) $_POST['from'];
  1957. $_POST['auto'] = !empty($_POST['auto']) ? (int) $_POST['auto'] : 0;
  1958. $_POST['to'] = (int) $_POST['to'];
  1959. $start = !empty($_POST['empty_it']) ? 0 : $modSettings['attachmentDirFileLimit'];
  1960. $_SESSION['checked'] = !empty($_POST['empty_it']) ? true : false;
  1961. $limit = 501;
  1962. $results = array();
  1963. $dir_files = 0;
  1964. $current_progress = 0;
  1965. $total_moved = 0;
  1966. $total_not_moved = 0;
  1967. if (empty($_POST['from']) || (empty($_POST['auto']) && empty($_POST['to'])))
  1968. $results[] = $txt['attachment_transfer_no_dir'];
  1969. if ($_POST['from'] == $_POST['to'])
  1970. $results[] = $txt['attachment_transfer_same_dir'];
  1971. if (empty($results))
  1972. {
  1973. // Get the total file count for the progess bar.
  1974. $request = $smcFunc['db_query']('', '
  1975. SELECT COUNT(*)
  1976. FROM {db_prefix}attachments
  1977. WHERE id_folder = {int:folder_id}
  1978. AND attachment_type != {int:attachment_type}',
  1979. array(
  1980. 'folder_id' => $_POST['from'],
  1981. 'attachment_type' => 1,
  1982. )
  1983. );
  1984. list ($total_progress) = $smcFunc['db_fetch_row']($request);
  1985. $smcFunc['db_free_result']($request);
  1986. $total_progress -= $start;
  1987. if ($total_progress < 1)
  1988. $results[] = $txt['attachment_transfer_no_find'];
  1989. }
  1990. if (empty($results))
  1991. {
  1992. // Where are they going?
  1993. if (!empty($_POST['auto']))
  1994. {
  1995. require_once(SUBSDIR . '/Attachments.subs.php');
  1996. $modSettings['automanage_attachments'] = 1;
  1997. $modSettings['use_subdirectories_for_attachments'] = $_POST['auto'] == -1 ? 0 : 1;
  1998. $modSettings['basedirectory_for_attachments'] = $_POST['auto'] > 0 ? $modSettings['attachmentUploadDir'][$_POST['auto']] : $modSettings['basedirectory_for_attachments'];
  1999. automanage_attachments_check_directory();
  2000. $new_dir = $modSettings['currentAttachmentUploadDir'];
  2001. }
  2002. else
  2003. $new_dir = $_POST['to'];
  2004. $modSettings['currentAttachmentUploadDir'] = $new_dir;
  2005. $break = false;
  2006. while ($break == false)
  2007. {
  2008. @set_time_limit(300);
  2009. if (function_exists('apache_reset_timeout'))
  2010. @apache_reset_timeout();
  2011. // If limts are set, get the file count and size for the destination folder
  2012. if ($dir_files <= 0 && (!empty($modSettings['attachmentDirSizeLimit']) || !empty($modSettings['attachmentDirFileLimit'])))
  2013. {
  2014. $request = $smcFunc['db_query']('', '
  2015. SELECT COUNT(*), SUM(size)
  2016. FROM {db_prefix}attachments
  2017. WHERE id_folder = {int:folder_id}
  2018. AND attachment_type != {int:attachment_type}',
  2019. array(
  2020. 'folder_id' => $new_dir,
  2021. 'attachment_type' => 1,
  2022. )
  2023. );
  2024. list ($dir_files, $dir_size) = $smcFunc['db_fetch_row']($request);
  2025. $smcFunc['db_free_result']($request);
  2026. }
  2027. // Find some attachments to move
  2028. $request = $smcFunc['db_query']('', '
  2029. SELECT id_attach, filename, id_folder, file_hash, size
  2030. FROM {db_prefix}attachments
  2031. WHERE id_folder = {int:folder}
  2032. AND attachment_type != {int:attachment_type}
  2033. LIMIT {int:start}, {int:limit}',
  2034. array(
  2035. 'folder' => $_POST['from'],
  2036. 'attachment_type' => 1,
  2037. 'start' => $start,
  2038. 'limit' => $limit,
  2039. )
  2040. );
  2041. if ($smcFunc['db_num_rows']($request) === 0)
  2042. {
  2043. if (empty($current_progress))
  2044. $results[] = $txt['attachment_transfer_no_find'];
  2045. break;
  2046. }
  2047. if ($smcFunc['db_num_rows']($request) < $limit)
  2048. $break = true;
  2049. // Move them
  2050. $moved = array();
  2051. while ($row = $smcFunc['db_fetch_assoc']($request))
  2052. {
  2053. // Size and file count check
  2054. if (!empty($modSettings['attachmentDirSizeLimit']) || !empty($modSettings['attachmentDirFileLimit']))
  2055. {
  2056. $dir_files++;
  2057. $dir_size += !empty($row['size']) ? $row['size'] : filesize($source);
  2058. // If we've reached a limit. Do something.
  2059. if (!empty($modSettings['attachmentDirSizeLimit']) && $dir_size > $modSettings['attachmentDirSizeLimit'] * 1024 || (!empty($modSettings['attachmentDirFileLimit']) && $dir_files > $modSettings['attachmentDirFileLimit']))
  2060. {
  2061. if (!empty($_POST['auto']))
  2062. {
  2063. // Since we're in auto mode. Create a new folder and reset the counters.
  2064. automanage_attachments_by_space();
  2065. $results[] = sprintf($txt['attachments_transfered'], $total_moved, $modSettings['attachmentUploadDir'][$new_dir]);
  2066. if (!empty($total_not_moved))
  2067. $results[] = sprintf($txt['attachments_not_transfered'], $total_not_moved);
  2068. $dir_files = 0;
  2069. $total_moved = 0;
  2070. $total_not_moved = 0;
  2071. $break = false;
  2072. break;
  2073. }
  2074. else
  2075. {
  2076. // Hmm, not in auto. Time to bail out then...
  2077. $results[] = $txt['attachment_transfer_no_room'];
  2078. $break = true;
  2079. break;
  2080. }
  2081. }
  2082. }
  2083. $source = getAttachmentFilename($row['filename'], $row['id_attach'], $row['id_folder'], false, $row['file_hash']);
  2084. $dest = $modSettings['attachmentUploadDir'][$new_dir] . '/' . basename($source);
  2085. if (@rename($source, $dest))
  2086. {
  2087. $total_moved++;
  2088. $current_progress++;
  2089. $moved[] = $row['id_attach'];
  2090. }
  2091. else
  2092. $total_not_moved++;
  2093. }
  2094. $smcFunc['db_free_result']($request);
  2095. if (!empty($moved))
  2096. {
  2097. // Update the database
  2098. $smcFunc['db_query']('', '
  2099. UPDATE {db_prefix}attachments
  2100. SET id_folder = {int:new}
  2101. WHERE id_attach IN ({array_int:attachments})',
  2102. array(
  2103. 'attachments' => $moved,
  2104. 'new' => $new_dir,
  2105. )
  2106. );
  2107. }
  2108. $moved = array();
  2109. $new_dir = $modSettings['currentAttachmentUploadDir'];
  2110. // Create the progress bar.
  2111. if (!$break)
  2112. {
  2113. $percent_done = min(round($current_progress / $total_progress * 100, 0), 100);
  2114. $prog_bar = '
  2115. <div class="progress_bar">
  2116. <div class="full_bar">' . $percent_done . '%</div>
  2117. <div class="green_percent" style="width: ' . $percent_done . '%;">&nbsp;</div>
  2118. </div>';
  2119. // Write it to a file so it can be displayed
  2120. $fp = fopen(BOARDDIR . '/progress.php', "w");
  2121. fwrite($fp, $prog_bar);
  2122. fclose($fp);
  2123. usleep(500000);
  2124. }
  2125. }
  2126. $results[] = sprintf($txt['attachments_transfered'], $total_moved, $modSettings['attachmentUploadDir'][$new_dir]);
  2127. if (!empty($total_not_moved))
  2128. $results[] = sprintf($txt['attachments_not_transfered'], $total_not_moved);
  2129. }
  2130. $_SESSION['results'] = $results;
  2131. if (file_exists(BOARDDIR . '/progress.php'))
  2132. unlink(BOARDDIR . '/progress.php');
  2133. redirectexit('action=admin;area=manageattachments;sa=maintenance#transfer');
  2134. }