ManageAttachments.php 60 KB

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