ManageAttachments.php 60 KB

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