ManageAttachments.php 65 KB

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