ManageAttachments.php 59 KB

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