ManageAttachments.php 61 KB

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