ManageAttachments.php 62 KB

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