ManageAttachments.php 62 KB

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