ManageAttachments.php 62 KB

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