ManageAttachments.php 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896
  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 $return_config
  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))
  620. $smcFunc['db_query']('', '
  621. UPDATE {db_prefix}messages
  622. SET body = CONCAT(body, ' . (!empty($_POST['notice']) ? '{string:notice}' : '') . ')
  623. WHERE id_msg IN ({array_int:messages})',
  624. array(
  625. 'messages' => $messages,
  626. 'notice' => empty($_POST['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))
  652. $smcFunc['db_query']('', '
  653. UPDATE {db_prefix}messages
  654. SET body = CONCAT(body, ' . (!empty($_POST['notice']) ? '{string:notice}' : '') . ')
  655. WHERE id_msg IN ({array_int:messages})',
  656. array(
  657. 'messages' => $messages,
  658. 'notice' => empty($_POST['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. *
  732. * @param array $condition
  733. * @param string $query_type
  734. * @param bool $return_affected_messages = false
  735. * @param bool $autoThumbRemoval = true
  736. */
  737. function removeAttachments($condition, $query_type = '', $return_affected_messages = false, $autoThumbRemoval = true)
  738. {
  739. global $modSettings, $smcFunc;
  740. //!!! This might need more work!
  741. $new_condition = array();
  742. $query_parameter = array(
  743. 'thumb_attachment_type' => 3,
  744. );
  745. if (is_array($condition))
  746. {
  747. foreach ($condition as $real_type => $restriction)
  748. {
  749. // Doing a NOT?
  750. $is_not = substr($real_type, 0, 4) == 'not_';
  751. $type = $is_not ? substr($real_type, 4) : $real_type;
  752. if (in_array($type, array('id_member', 'id_attach', 'id_msg')))
  753. $new_condition[] = 'a.' . $type . ($is_not ? ' NOT' : '') . ' IN (' . (is_array($restriction) ? '{array_int:' . $real_type . '}' : '{int:' . $real_type . '}') . ')';
  754. elseif ($type == 'attachment_type')
  755. $new_condition[] = 'a.attachment_type = {int:' . $real_type . '}';
  756. elseif ($type == 'poster_time')
  757. $new_condition[] = 'm.poster_time < {int:' . $real_type . '}';
  758. elseif ($type == 'last_login')
  759. $new_condition[] = 'mem.last_login < {int:' . $real_type . '}';
  760. elseif ($type == 'size')
  761. $new_condition[] = 'a.size > {int:' . $real_type . '}';
  762. elseif ($type == 'id_topic')
  763. $new_condition[] = 'm.id_topic IN (' . (is_array($restriction) ? '{array_int:' . $real_type . '}' : '{int:' . $real_type . '}') . ')';
  764. // Add the parameter!
  765. $query_parameter[$real_type] = $restriction;
  766. }
  767. $condition = implode(' AND ', $new_condition);
  768. }
  769. // Delete it only if it exists...
  770. $msgs = array();
  771. $attach = array();
  772. $parents = array();
  773. // Get all the attachment names and id_msg's.
  774. $request = $smcFunc['db_query']('', '
  775. SELECT
  776. 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') . ',
  777. 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
  778. FROM {db_prefix}attachments AS a' .($query_type == 'members' ? '
  779. INNER JOIN {db_prefix}members AS mem ON (mem.id_member = a.id_member)' : ($query_type == 'messages' ? '
  780. INNER JOIN {db_prefix}messages AS m ON (m.id_msg = a.id_msg)' : '')) . '
  781. LEFT JOIN {db_prefix}attachments AS thumb ON (thumb.id_attach = a.id_thumb)
  782. LEFT JOIN {db_prefix}attachments AS thumb_parent ON (thumb.attachment_type = {int:thumb_attachment_type} AND thumb_parent.id_thumb = a.id_attach)
  783. WHERE ' . $condition,
  784. $query_parameter
  785. );
  786. while ($row = $smcFunc['db_fetch_assoc']($request))
  787. {
  788. // Figure out the "encrypted" filename and unlink it ;).
  789. if ($row['attachment_type'] == 1)
  790. @unlink($modSettings['custom_avatar_dir'] . '/' . $row['filename']);
  791. else
  792. {
  793. $filename = getAttachmentFilename($row['filename'], $row['id_attach'], $row['id_folder'], false, $row['file_hash']);
  794. @unlink($filename);
  795. // If this was a thumb, the parent attachment should know about it.
  796. if (!empty($row['id_parent']))
  797. $parents[] = $row['id_parent'];
  798. // If this attachments has a thumb, remove it as well.
  799. if (!empty($row['id_thumb']) && $autoThumbRemoval)
  800. {
  801. $thumb_filename = getAttachmentFilename($row['thumb_filename'], $row['id_thumb'], $row['thumb_folder'], false, $row['thumb_file_hash']);
  802. @unlink($thumb_filename);
  803. $attach[] = $row['id_thumb'];
  804. }
  805. }
  806. // Make a list.
  807. if ($return_affected_messages && empty($row['attachment_type']))
  808. $msgs[] = $row['id_msg'];
  809. $attach[] = $row['id_attach'];
  810. }
  811. $smcFunc['db_free_result']($request);
  812. // Removed attachments don't have to be updated anymore.
  813. $parents = array_diff($parents, $attach);
  814. if (!empty($parents))
  815. $smcFunc['db_query']('', '
  816. UPDATE {db_prefix}attachments
  817. SET id_thumb = {int:no_thumb}
  818. WHERE id_attach IN ({array_int:parent_attachments})',
  819. array(
  820. 'parent_attachments' => $parents,
  821. 'no_thumb' => 0,
  822. )
  823. );
  824. if (!empty($attach))
  825. $smcFunc['db_query']('', '
  826. DELETE FROM {db_prefix}attachments
  827. WHERE id_attach IN ({array_int:attachment_list})',
  828. array(
  829. 'attachment_list' => $attach,
  830. )
  831. );
  832. if ($return_affected_messages)
  833. return array_unique($msgs);
  834. }
  835. /**
  836. * This function should find attachments in the database that no longer exist and clear them, and fix filesize issues.
  837. */
  838. function RepairAttachments()
  839. {
  840. global $modSettings, $context, $txt, $smcFunc;
  841. checkSession('get');
  842. // If we choose cancel, redirect right back.
  843. if (isset($_POST['cancel']))
  844. redirectexit('action=admin;area=manageattachments;sa=maintenance');
  845. // Try give us a while to sort this out...
  846. @set_time_limit(600);
  847. $_GET['step'] = empty($_GET['step']) ? 0 : (int) $_GET['step'];
  848. $_GET['substep'] = empty($_GET['substep']) ? 0 : (int) $_GET['substep'];
  849. // Don't recall the session just in case.
  850. if ($_GET['step'] == 0 && $_GET['substep'] == 0)
  851. {
  852. unset($_SESSION['attachments_to_fix'], $_SESSION['attachments_to_fix2']);
  853. // If we're actually fixing stuff - work out what.
  854. if (isset($_GET['fixErrors']))
  855. {
  856. // Nothing?
  857. if (empty($_POST['to_fix']))
  858. redirectexit('action=admin;area=manageattachments;sa=maintenance');
  859. $_SESSION['attachments_to_fix'] = array();
  860. /**
  861. * @todo No need to do this I think.
  862. */
  863. foreach ($_POST['to_fix'] as $key => $value)
  864. $_SESSION['attachments_to_fix'][] = $value;
  865. }
  866. }
  867. // All the valid problems are here:
  868. $context['repair_errors'] = array(
  869. 'missing_thumbnail_parent' => 0,
  870. 'parent_missing_thumbnail' => 0,
  871. 'file_missing_on_disk' => 0,
  872. 'file_wrong_size' => 0,
  873. 'file_size_of_zero' => 0,
  874. 'attachment_no_msg' => 0,
  875. 'avatar_no_member' => 0,
  876. 'wrong_folder' => 0,
  877. );
  878. $to_fix = !empty($_SESSION['attachments_to_fix']) ? $_SESSION['attachments_to_fix'] : array();
  879. $context['repair_errors'] = isset($_SESSION['attachments_to_fix2']) ? $_SESSION['attachments_to_fix2'] : $context['repair_errors'];
  880. $fix_errors = isset($_GET['fixErrors']) ? true : false;
  881. // Get stranded thumbnails.
  882. if ($_GET['step'] <= 0)
  883. {
  884. $result = $smcFunc['db_query']('', '
  885. SELECT MAX(id_attach)
  886. FROM {db_prefix}attachments
  887. WHERE attachment_type = {int:thumbnail}',
  888. array(
  889. 'thumbnail' => 3,
  890. )
  891. );
  892. list ($thumbnails) = $smcFunc['db_fetch_row']($result);
  893. $smcFunc['db_free_result']($result);
  894. for (; $_GET['substep'] < $thumbnails; $_GET['substep'] += 500)
  895. {
  896. $to_remove = array();
  897. $result = $smcFunc['db_query']('', '
  898. SELECT thumb.id_attach, thumb.id_folder, thumb.filename, thumb.file_hash
  899. FROM {db_prefix}attachments AS thumb
  900. LEFT JOIN {db_prefix}attachments AS tparent ON (tparent.id_thumb = thumb.id_attach)
  901. WHERE thumb.id_attach BETWEEN {int:substep} AND {int:substep} + 499
  902. AND thumb.attachment_type = {int:thumbnail}
  903. AND tparent.id_attach IS NULL',
  904. array(
  905. 'thumbnail' => 3,
  906. 'substep' => $_GET['substep'],
  907. )
  908. );
  909. while ($row = $smcFunc['db_fetch_assoc']($result))
  910. {
  911. // Only do anything once... just in case
  912. if (!isset($to_remove[$row['id_attach']]))
  913. {
  914. $to_remove[$row['id_attach']] = $row['id_attach'];
  915. $context['repair_errors']['missing_thumbnail_parent']++;
  916. // If we are repairing remove the file from disk now.
  917. if ($fix_errors && in_array('missing_thumbnail_parent', $to_fix))
  918. {
  919. $filename = getAttachmentFilename($row['filename'], $row['id_attach'], $row['id_folder'], false, $row['file_hash']);
  920. @unlink($filename);
  921. }
  922. }
  923. }
  924. if ($smcFunc['db_num_rows']($result) != 0)
  925. $to_fix[] = 'missing_thumbnail_parent';
  926. $smcFunc['db_free_result']($result);
  927. // Do we need to delete what we have?
  928. if ($fix_errors && !empty($to_remove) && in_array('missing_thumbnail_parent', $to_fix))
  929. $smcFunc['db_query']('', '
  930. DELETE FROM {db_prefix}attachments
  931. WHERE id_attach IN ({array_int:to_remove})
  932. AND attachment_type = {int:attachment_type}',
  933. array(
  934. 'to_remove' => $to_remove,
  935. 'attachment_type' => 3,
  936. )
  937. );
  938. pauseAttachmentMaintenance($to_fix, $thumbnails);
  939. }
  940. $_GET['step'] = 1;
  941. $_GET['substep'] = 0;
  942. pauseAttachmentMaintenance($to_fix);
  943. }
  944. // Find parents which think they have thumbnails, but actually, don't.
  945. if ($_GET['step'] <= 1)
  946. {
  947. $result = $smcFunc['db_query']('', '
  948. SELECT MAX(id_attach)
  949. FROM {db_prefix}attachments
  950. WHERE id_thumb != {int:no_thumb}',
  951. array(
  952. 'no_thumb' => 0,
  953. )
  954. );
  955. list ($thumbnails) = $smcFunc['db_fetch_row']($result);
  956. $smcFunc['db_free_result']($result);
  957. for (; $_GET['substep'] < $thumbnails; $_GET['substep'] += 500)
  958. {
  959. $to_update = array();
  960. $result = $smcFunc['db_query']('', '
  961. SELECT a.id_attach
  962. FROM {db_prefix}attachments AS a
  963. LEFT JOIN {db_prefix}attachments AS thumb ON (thumb.id_attach = a.id_thumb)
  964. WHERE a.id_attach BETWEEN {int:substep} AND {int:substep} + 499
  965. AND a.id_thumb != {int:no_thumb}
  966. AND thumb.id_attach IS NULL',
  967. array(
  968. 'no_thumb' => 0,
  969. 'substep' => $_GET['substep'],
  970. )
  971. );
  972. while ($row = $smcFunc['db_fetch_assoc']($result))
  973. {
  974. $to_update[] = $row['id_attach'];
  975. $context['repair_errors']['parent_missing_thumbnail']++;
  976. }
  977. if ($smcFunc['db_num_rows']($result) != 0)
  978. $to_fix[] = 'parent_missing_thumbnail';
  979. $smcFunc['db_free_result']($result);
  980. // Do we need to delete what we have?
  981. if ($fix_errors && !empty($to_update) && in_array('parent_missing_thumbnail', $to_fix))
  982. $smcFunc['db_query']('', '
  983. UPDATE {db_prefix}attachments
  984. SET id_thumb = {int:no_thumb}
  985. WHERE id_attach IN ({array_int:to_update})',
  986. array(
  987. 'to_update' => $to_update,
  988. 'no_thumb' => 0,
  989. )
  990. );
  991. pauseAttachmentMaintenance($to_fix, $thumbnails);
  992. }
  993. $_GET['step'] = 2;
  994. $_GET['substep'] = 0;
  995. pauseAttachmentMaintenance($to_fix);
  996. }
  997. // This may take forever I'm afraid, but life sucks... recount EVERY attachments!
  998. if ($_GET['step'] <= 2)
  999. {
  1000. $result = $smcFunc['db_query']('', '
  1001. SELECT MAX(id_attach)
  1002. FROM {db_prefix}attachments',
  1003. array(
  1004. )
  1005. );
  1006. list ($thumbnails) = $smcFunc['db_fetch_row']($result);
  1007. $smcFunc['db_free_result']($result);
  1008. for (; $_GET['substep'] < $thumbnails; $_GET['substep'] += 250)
  1009. {
  1010. $to_remove = array();
  1011. $errors_found = array();
  1012. $result = $smcFunc['db_query']('', '
  1013. SELECT id_attach, id_folder, filename, file_hash, size, attachment_type
  1014. FROM {db_prefix}attachments
  1015. WHERE id_attach BETWEEN {int:substep} AND {int:substep} + 249',
  1016. array(
  1017. 'substep' => $_GET['substep'],
  1018. )
  1019. );
  1020. while ($row = $smcFunc['db_fetch_assoc']($result))
  1021. {
  1022. // Get the filename.
  1023. if ($row['attachment_type'] == 1)
  1024. $filename = $modSettings['custom_avatar_dir'] . '/' . $row['filename'];
  1025. else
  1026. $filename = getAttachmentFilename($row['filename'], $row['id_attach'], $row['id_folder'], false, $row['file_hash']);
  1027. // File doesn't exist?
  1028. if (!file_exists($filename))
  1029. {
  1030. // If we're lucky it might just be in a different folder.
  1031. if (!empty($modSettings['currentAttachmentUploadDir']))
  1032. {
  1033. // Get the attachment name with out the folder.
  1034. $attachment_name = !empty($row['file_hash']) ? $row['id_attach'] . '_' . $row['file_hash'] : getLegacyAttachmentFilename($row['filename'], $row['id_attach'], null, true);
  1035. if (!is_array($modSettings['attachmentUploadDir']))
  1036. $modSettings['attachmentUploadDir'] = unserialize($modSettings['attachmentUploadDir']);
  1037. // Loop through the other folders.
  1038. foreach ($modSettings['attachmentUploadDir'] as $id => $dir)
  1039. if (file_exists($dir . '/' . $attachment_name))
  1040. {
  1041. $context['repair_errors']['wrong_folder']++;
  1042. $errors_found[] = 'wrong_folder';
  1043. // Are we going to fix this now?
  1044. if ($fix_errors && in_array('wrong_folder', $to_fix))
  1045. $smcFunc['db_query']('', '
  1046. UPDATE {db_prefix}attachments
  1047. SET id_folder = {int:new_folder}
  1048. WHERE id_attach = {int:id_attach}',
  1049. array(
  1050. 'new_folder' => $id,
  1051. 'id_attach' => $row['id_attach'],
  1052. )
  1053. );
  1054. continue 2;
  1055. }
  1056. }
  1057. $to_remove[] = $row['id_attach'];
  1058. $context['repair_errors']['file_missing_on_disk']++;
  1059. $errors_found[] = 'file_missing_on_disk';
  1060. }
  1061. elseif (filesize($filename) == 0)
  1062. {
  1063. $context['repair_errors']['file_size_of_zero']++;
  1064. $errors_found[] = 'file_size_of_zero';
  1065. // Fixing?
  1066. if ($fix_errors && in_array('file_size_of_zero', $to_fix))
  1067. {
  1068. $to_remove[] = $row['id_attach'];
  1069. @unlink($filename);
  1070. }
  1071. }
  1072. elseif (filesize($filename) != $row['size'])
  1073. {
  1074. $context['repair_errors']['file_wrong_size']++;
  1075. $errors_found[] = 'file_wrong_size';
  1076. // Fix it here?
  1077. if ($fix_errors && in_array('file_wrong_size', $to_fix))
  1078. {
  1079. $smcFunc['db_query']('', '
  1080. UPDATE {db_prefix}attachments
  1081. SET size = {int:filesize}
  1082. WHERE id_attach = {int:id_attach}',
  1083. array(
  1084. 'filesize' => filesize($filename),
  1085. 'id_attach' => $row['id_attach'],
  1086. )
  1087. );
  1088. }
  1089. }
  1090. }
  1091. if (in_array('file_missing_on_disk', $errors_found))
  1092. $to_fix[] = 'file_missing_on_disk';
  1093. if (in_array('file_size_of_zero', $errors_found))
  1094. $to_fix[] = 'file_size_of_zero';
  1095. if (in_array('file_wrong_size', $errors_found))
  1096. $to_fix[] = 'file_wrong_size';
  1097. if (in_array('wrong_folder', $errors_found))
  1098. $to_fix[] = 'wrong_folder';
  1099. $smcFunc['db_free_result']($result);
  1100. // Do we need to delete what we have?
  1101. if ($fix_errors && !empty($to_remove))
  1102. {
  1103. $smcFunc['db_query']('', '
  1104. DELETE FROM {db_prefix}attachments
  1105. WHERE id_attach IN ({array_int:to_remove})',
  1106. array(
  1107. 'to_remove' => $to_remove,
  1108. )
  1109. );
  1110. $smcFunc['db_query']('', '
  1111. UPDATE {db_prefix}attachments
  1112. SET id_thumb = {int:no_thumb}
  1113. WHERE id_thumb IN ({array_int:to_remove})',
  1114. array(
  1115. 'to_remove' => $to_remove,
  1116. 'no_thumb' => 0,
  1117. )
  1118. );
  1119. }
  1120. pauseAttachmentMaintenance($to_fix, $thumbnails);
  1121. }
  1122. $_GET['step'] = 3;
  1123. $_GET['substep'] = 0;
  1124. pauseAttachmentMaintenance($to_fix);
  1125. }
  1126. // Get avatars with no members associated with them.
  1127. if ($_GET['step'] <= 3)
  1128. {
  1129. $result = $smcFunc['db_query']('', '
  1130. SELECT MAX(id_attach)
  1131. FROM {db_prefix}attachments',
  1132. array(
  1133. )
  1134. );
  1135. list ($thumbnails) = $smcFunc['db_fetch_row']($result);
  1136. $smcFunc['db_free_result']($result);
  1137. for (; $_GET['substep'] < $thumbnails; $_GET['substep'] += 500)
  1138. {
  1139. $to_remove = array();
  1140. $result = $smcFunc['db_query']('', '
  1141. SELECT a.id_attach, a.id_folder, a.filename, a.file_hash, a.attachment_type
  1142. FROM {db_prefix}attachments AS a
  1143. LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = a.id_member)
  1144. WHERE a.id_attach BETWEEN {int:substep} AND {int:substep} + 499
  1145. AND a.id_member != {int:no_member}
  1146. AND a.id_msg = {int:no_msg}
  1147. AND mem.id_member IS NULL',
  1148. array(
  1149. 'no_member' => 0,
  1150. 'no_msg' => 0,
  1151. 'substep' => $_GET['substep'],
  1152. )
  1153. );
  1154. while ($row = $smcFunc['db_fetch_assoc']($result))
  1155. {
  1156. $to_remove[] = $row['id_attach'];
  1157. $context['repair_errors']['avatar_no_member']++;
  1158. // If we are repairing remove the file from disk now.
  1159. if ($fix_errors && in_array('avatar_no_member', $to_fix))
  1160. {
  1161. if ($row['attachment_type'] == 1)
  1162. $filename = $modSettings['custom_avatar_dir'] . '/' . $row['filename'];
  1163. else
  1164. $filename = getAttachmentFilename($row['filename'], $row['id_attach'], $row['id_folder'], false, $row['file_hash']);
  1165. @unlink($filename);
  1166. }
  1167. }
  1168. if ($smcFunc['db_num_rows']($result) != 0)
  1169. $to_fix[] = 'avatar_no_member';
  1170. $smcFunc['db_free_result']($result);
  1171. // Do we need to delete what we have?
  1172. if ($fix_errors && !empty($to_remove) && in_array('avatar_no_member', $to_fix))
  1173. $smcFunc['db_query']('', '
  1174. DELETE FROM {db_prefix}attachments
  1175. WHERE id_attach IN ({array_int:to_remove})
  1176. AND id_member != {int:no_member}
  1177. AND id_msg = {int:no_msg}',
  1178. array(
  1179. 'to_remove' => $to_remove,
  1180. 'no_member' => 0,
  1181. 'no_msg' => 0,
  1182. )
  1183. );
  1184. pauseAttachmentMaintenance($to_fix, $thumbnails);
  1185. }
  1186. $_GET['step'] = 4;
  1187. $_GET['substep'] = 0;
  1188. pauseAttachmentMaintenance($to_fix);
  1189. }
  1190. // What about attachments, who are missing a message :'(
  1191. if ($_GET['step'] <= 4)
  1192. {
  1193. $result = $smcFunc['db_query']('', '
  1194. SELECT MAX(id_attach)
  1195. FROM {db_prefix}attachments',
  1196. array(
  1197. )
  1198. );
  1199. list ($thumbnails) = $smcFunc['db_fetch_row']($result);
  1200. $smcFunc['db_free_result']($result);
  1201. for (; $_GET['substep'] < $thumbnails; $_GET['substep'] += 500)
  1202. {
  1203. $to_remove = array();
  1204. $result = $smcFunc['db_query']('', '
  1205. SELECT a.id_attach, a.id_folder, a.filename, a.file_hash
  1206. FROM {db_prefix}attachments AS a
  1207. LEFT JOIN {db_prefix}messages AS m ON (m.id_msg = a.id_msg)
  1208. WHERE a.id_attach BETWEEN {int:substep} AND {int:substep} + 499
  1209. AND a.id_member = {int:no_member}
  1210. AND a.id_msg != {int:no_msg}
  1211. AND m.id_msg IS NULL',
  1212. array(
  1213. 'no_member' => 0,
  1214. 'no_msg' => 0,
  1215. 'substep' => $_GET['substep'],
  1216. )
  1217. );
  1218. while ($row = $smcFunc['db_fetch_assoc']($result))
  1219. {
  1220. $to_remove[] = $row['id_attach'];
  1221. $context['repair_errors']['attachment_no_msg']++;
  1222. // If we are repairing remove the file from disk now.
  1223. if ($fix_errors && in_array('attachment_no_msg', $to_fix))
  1224. {
  1225. $filename = getAttachmentFilename($row['filename'], $row['id_attach'], $row['id_folder'], false, $row['file_hash']);
  1226. @unlink($filename);
  1227. }
  1228. }
  1229. if ($smcFunc['db_num_rows']($result) != 0)
  1230. $to_fix[] = 'attachment_no_msg';
  1231. $smcFunc['db_free_result']($result);
  1232. // Do we need to delete what we have?
  1233. if ($fix_errors && !empty($to_remove) && in_array('attachment_no_msg', $to_fix))
  1234. $smcFunc['db_query']('', '
  1235. DELETE FROM {db_prefix}attachments
  1236. WHERE id_attach IN ({array_int:to_remove})
  1237. AND id_member = {int:no_member}
  1238. AND id_msg != {int:no_msg}',
  1239. array(
  1240. 'to_remove' => $to_remove,
  1241. 'no_member' => 0,
  1242. 'no_msg' => 0,
  1243. )
  1244. );
  1245. pauseAttachmentMaintenance($to_fix, $thumbnails);
  1246. }
  1247. $_GET['step'] = 5;
  1248. $_GET['substep'] = 0;
  1249. pauseAttachmentMaintenance($to_fix);
  1250. }
  1251. // Got here we must be doing well - just the template! :D
  1252. $context['page_title'] = $txt['repair_attachments'];
  1253. $context[$context['admin_menu_name']]['current_subsection'] = 'maintenance';
  1254. $context['sub_template'] = 'attachment_repair';
  1255. // What stage are we at?
  1256. $context['completed'] = $fix_errors ? true : false;
  1257. $context['errors_found'] = !empty($to_fix) ? true : false;
  1258. }
  1259. /**
  1260. * Function called in-between each round of attachments and avatar repairs.
  1261. * Called by repairAttachments().
  1262. * If repairAttachments() has more steps added, this function needs updated!
  1263. *
  1264. * @param array $to_fix attachments to fix
  1265. * @param int $max_substep = 0
  1266. */
  1267. function pauseAttachmentMaintenance($to_fix, $max_substep = 0)
  1268. {
  1269. global $context, $txt, $time_start;
  1270. // Try get more time...
  1271. @set_time_limit(600);
  1272. if (function_exists('apache_reset_timeout'))
  1273. @apache_reset_timeout();
  1274. // Have we already used our maximum time?
  1275. if (time() - array_sum(explode(' ', $time_start)) < 3)
  1276. return;
  1277. $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'];
  1278. $context['page_title'] = $txt['not_done_title'];
  1279. $context['continue_post_data'] = '';
  1280. $context['continue_countdown'] = '2';
  1281. $context['sub_template'] = 'not_done';
  1282. // Specific stuff to not break this template!
  1283. $context[$context['admin_menu_name']]['current_subsection'] = 'maintenance';
  1284. // Change these two if more steps are added!
  1285. if (empty($max_substep))
  1286. $context['continue_percent'] = round(($_GET['step'] * 100) / 25);
  1287. else
  1288. $context['continue_percent'] = round(($_GET['step'] * 100 + ($_GET['substep'] * 100) / $max_substep) / 25);
  1289. // Never more than 100%!
  1290. $context['continue_percent'] = min($context['continue_percent'], 100);
  1291. $_SESSION['attachments_to_fix'] = $to_fix;
  1292. $_SESSION['attachments_to_fix2'] = $context['repair_errors'];
  1293. obExit();
  1294. }
  1295. /**
  1296. * Called from a mouse click, works out what we want to do with attachments and actions it.
  1297. */
  1298. function ApproveAttach()
  1299. {
  1300. global $smcFunc;
  1301. // Security is our primary concern...
  1302. checkSession('get');
  1303. // If it approve or delete?
  1304. $is_approve = !isset($_GET['sa']) || $_GET['sa'] != 'reject' ? true : false;
  1305. $attachments = array();
  1306. // If we are approving all ID's in a message , get the ID's.
  1307. if ($_GET['sa'] == 'all' && !empty($_GET['mid']))
  1308. {
  1309. $id_msg = (int) $_GET['mid'];
  1310. $request = $smcFunc['db_query']('', '
  1311. SELECT id_attach
  1312. FROM {db_prefix}attachments
  1313. WHERE id_msg = {int:id_msg}
  1314. AND approved = {int:is_approved}
  1315. AND attachment_type = {int:attachment_type}',
  1316. array(
  1317. 'id_msg' => $id_msg,
  1318. 'is_approved' => 0,
  1319. 'attachment_type' => 0,
  1320. )
  1321. );
  1322. while ($row = $smcFunc['db_fetch_assoc']($request))
  1323. $attachments[] = $row['id_attach'];
  1324. $smcFunc['db_free_result']($request);
  1325. }
  1326. elseif (!empty($_GET['aid']))
  1327. $attachments[] = (int) $_GET['aid'];
  1328. if (empty($attachments))
  1329. fatal_lang_error('no_access', false);
  1330. // Now we have some ID's cleaned and ready to approve, but first - let's check we have permission!
  1331. $allowed_boards = boardsAllowedTo('approve_posts');
  1332. // Validate the attachments exist and are the right approval state.
  1333. $request = $smcFunc['db_query']('', '
  1334. SELECT a.id_attach, m.id_board, m.id_msg, m.id_topic
  1335. FROM {db_prefix}attachments AS a
  1336. INNER JOIN {db_prefix}messages AS m ON (m.id_msg = a.id_msg)
  1337. WHERE a.id_attach IN ({array_int:attachments})
  1338. AND a.attachment_type = {int:attachment_type}
  1339. AND a.approved = {int:is_approved}',
  1340. array(
  1341. 'attachments' => $attachments,
  1342. 'attachment_type' => 0,
  1343. 'is_approved' => 0,
  1344. )
  1345. );
  1346. $attachments = array();
  1347. while ($row = $smcFunc['db_fetch_assoc']($request))
  1348. {
  1349. // We can only add it if we can approve in this board!
  1350. if ($allowed_boards = array(0) || in_array($row['id_board'], $allowed_boards))
  1351. {
  1352. $attachments[] = $row['id_attach'];
  1353. // Also come up witht he redirection URL.
  1354. $redirect = 'topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#msg' . $row['id_msg'];
  1355. }
  1356. }
  1357. $smcFunc['db_free_result']($request);
  1358. if (empty($attachments))
  1359. fatal_lang_error('no_access', false);
  1360. // Finally, we are there. Follow through!
  1361. if ($is_approve)
  1362. {
  1363. // Checked and deemed worthy.
  1364. ApproveAttachments($attachments);
  1365. }
  1366. else
  1367. removeAttachments(array('id_attach' => $attachments));
  1368. // Return to the topic....
  1369. redirectexit($redirect);
  1370. }
  1371. /**
  1372. * Approve an attachment, or maybe even more - no permission check!
  1373. *
  1374. * @param array $attachments
  1375. */
  1376. function ApproveAttachments($attachments)
  1377. {
  1378. global $smcFunc;
  1379. if (empty($attachments))
  1380. return 0;
  1381. // For safety, check for thumbnails...
  1382. $request = $smcFunc['db_query']('', '
  1383. SELECT
  1384. a.id_attach, a.id_member, IFNULL(thumb.id_attach, 0) AS id_thumb
  1385. FROM {db_prefix}attachments AS a
  1386. LEFT JOIN {db_prefix}attachments AS thumb ON (thumb.id_attach = a.id_thumb)
  1387. WHERE a.id_attach IN ({array_int:attachments})
  1388. AND a.attachment_type = {int:attachment_type}',
  1389. array(
  1390. 'attachments' => $attachments,
  1391. 'attachment_type' => 0,
  1392. )
  1393. );
  1394. $attachments = array();
  1395. while ($row = $smcFunc['db_fetch_assoc']($request))
  1396. {
  1397. // Update the thumbnail too...
  1398. if (!empty($row['id_thumb']))
  1399. $attachments[] = $row['id_thumb'];
  1400. $attachments[] = $row['id_attach'];
  1401. }
  1402. $smcFunc['db_free_result']($request);
  1403. // Approving an attachment is not hard - it's easy.
  1404. $smcFunc['db_query']('', '
  1405. UPDATE {db_prefix}attachments
  1406. SET approved = {int:is_approved}
  1407. WHERE id_attach IN ({array_int:attachments})',
  1408. array(
  1409. 'attachments' => $attachments,
  1410. 'is_approved' => 1,
  1411. )
  1412. );
  1413. // Remove from the approval queue.
  1414. $smcFunc['db_query']('', '
  1415. DELETE FROM {db_prefix}approval_queue
  1416. WHERE id_attach IN ({array_int:attachments})',
  1417. array(
  1418. 'attachments' => $attachments,
  1419. )
  1420. );
  1421. call_integration_hook('integrate_approve_attachments', array($attachments));
  1422. }
  1423. /**
  1424. * This function lists and allows updating of multiple attachments paths.
  1425. */
  1426. function ManageAttachmentPaths()
  1427. {
  1428. global $modSettings, $scripturl, $context, $txt, $sourcedir, $smcFunc;
  1429. // Saving?
  1430. if (isset($_REQUEST['save']))
  1431. {
  1432. checkSession();
  1433. $new_dirs = array();
  1434. foreach ($_POST['dirs'] as $id => $path)
  1435. {
  1436. $id = (int) $id;
  1437. if ($id < 1)
  1438. continue;
  1439. if (empty($path))
  1440. {
  1441. // Let's not try to delete a path with files in it.
  1442. $request = $smcFunc['db_query']('', '
  1443. SELECT COUNT(id_attach) AS num_attach
  1444. FROM {db_prefix}attachments
  1445. WHERE id_folder = {int:id_folder}',
  1446. array(
  1447. 'id_folder' => (int) $id,
  1448. )
  1449. );
  1450. list ($num_attach) = $smcFunc['db_fetch_row']($request);
  1451. $smcFunc['db_free_result']($request);
  1452. // It's safe to delete.
  1453. if ($num_attach == 0)
  1454. continue;
  1455. }
  1456. $new_dirs[$id] = $path;
  1457. }
  1458. // We need to make sure the current directory is right.
  1459. $_POST['current_dir'] = (int) $_POST['current_dir'];
  1460. if (empty($_POST['current_dir']) || empty($new_dirs[$_POST['current_dir']]))
  1461. fatal_lang_error('attach_path_current_bad', false);
  1462. // Going back to just one path?
  1463. if (count($new_dirs) == 1)
  1464. {
  1465. // We might need to reset the paths. This loop will just loop through once.
  1466. foreach ($new_dirs as $id => $dir)
  1467. {
  1468. if ($id != 1)
  1469. $smcFunc['db_query']('', '
  1470. UPDATE {db_prefix}attachments
  1471. SET id_folder = {int:default_folder}
  1472. WHERE id_folder = {int:current_folder}',
  1473. array(
  1474. 'default_folder' => 1,
  1475. 'current_folder' => $id,
  1476. )
  1477. );
  1478. updateSettings(array(
  1479. 'currentAttachmentUploadDir' => 0,
  1480. 'attachmentUploadDir' => $dir,
  1481. ));
  1482. }
  1483. }
  1484. else
  1485. // Save it to the database.
  1486. updateSettings(array(
  1487. 'currentAttachmentUploadDir' => $_POST['current_dir'],
  1488. 'attachmentUploadDir' => serialize($new_dirs),
  1489. ));
  1490. }
  1491. // Are they here for the first time?
  1492. if (empty($modSettings['currentAttachmentUploadDir']))
  1493. {
  1494. $modSettings['attachmentUploadDir'] = array(
  1495. 1 => $modSettings['attachmentUploadDir']
  1496. );
  1497. $modSettings['currentAttachmentUploadDir'] = 1;
  1498. }
  1499. // Otherwise just load up their attachment paths.
  1500. else
  1501. $modSettings['attachmentUploadDir'] = unserialize($modSettings['attachmentUploadDir']);
  1502. $listOptions = array(
  1503. 'id' => 'attach_paths',
  1504. 'base_href' => $scripturl . '?action=admin;area=manageattachments;sa=attachpaths;' . $context['session_var'] . '=' . $context['session_id'],
  1505. 'title' => $txt['attach_paths'],
  1506. 'get_items' => array(
  1507. 'function' => 'list_getAttachDirs',
  1508. ),
  1509. 'columns' => array(
  1510. 'current_dir' => array(
  1511. 'header' => array(
  1512. 'value' => $txt['attach_current_dir'],
  1513. ),
  1514. 'data' => array(
  1515. 'function' => create_function('$rowData', '
  1516. return \'<input type="radio" name="current_dir" value="\' . $rowData[\'id\'] . \'" \' . ($rowData[\'current\'] ? \'checked="checked"\' : \'\') . \' class="input_radio" />\';
  1517. '),
  1518. 'style' => 'text-align: center; width: 15%;',
  1519. ),
  1520. ),
  1521. 'path' => array(
  1522. 'header' => array(
  1523. 'value' => $txt['attach_path'],
  1524. ),
  1525. 'data' => array(
  1526. 'function' => create_function('$rowData', '
  1527. return \'<input type="text" size="30" name="dirs[\' . $rowData[\'id\'] . \']" value="\' . $rowData[\'path\'] . \'" class="input_text" style="width: 100%" />\';
  1528. '),
  1529. 'style' => 'text-align: center; width: 30%;',
  1530. ),
  1531. ),
  1532. 'current_size' => array(
  1533. 'header' => array(
  1534. 'value' => $txt['attach_current_size'],
  1535. ),
  1536. 'data' => array(
  1537. 'db' => 'current_size',
  1538. 'style' => 'text-align: center; width: 15%;',
  1539. ),
  1540. ),
  1541. 'num_files' => array(
  1542. 'header' => array(
  1543. 'value' => $txt['attach_num_files'],
  1544. ),
  1545. 'data' => array(
  1546. 'db' => 'num_files',
  1547. 'style' => 'text-align: center; width: 15%;',
  1548. ),
  1549. ),
  1550. 'status' => array(
  1551. 'header' => array(
  1552. 'value' => $txt['attach_dir_status'],
  1553. ),
  1554. 'data' => array(
  1555. 'db' => 'status',
  1556. 'style' => 'text-align: center; width: 25%;',
  1557. ),
  1558. ),
  1559. ),
  1560. 'form' => array(
  1561. 'href' => $scripturl . '?action=admin;area=manageattachments;sa=attachpaths;' . $context['session_var'] . '=' . $context['session_id'],
  1562. ),
  1563. 'additional_rows' => array(
  1564. array(
  1565. 'position' => 'below_table_data',
  1566. '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" />',
  1567. 'style' => 'text-align: right;',
  1568. ),
  1569. ),
  1570. );
  1571. require_once($sourcedir . '/Subs-List.php');
  1572. createList($listOptions);
  1573. // Fix up our template.
  1574. $context[$context['admin_menu_name']]['current_subsection'] = 'attachments';
  1575. $context['page_title'] = $txt['attach_path_manage'];
  1576. $context['sub_template'] = 'attachment_paths';
  1577. }
  1578. /**
  1579. * Prepare the actual attachment directories to be displayed in the list.
  1580. */
  1581. function list_getAttachDirs()
  1582. {
  1583. global $smcFunc, $modSettings, $context, $txt;
  1584. // The dirs should already have been unserialized but just in case...
  1585. if (!is_array($modSettings['attachmentUploadDir']))
  1586. $modSettings['attachmentUploadDir'] = unserialize($modSettings['attachmentUploadDir']);
  1587. $request = $smcFunc['db_query']('', '
  1588. SELECT id_folder, COUNT(id_attach) AS num_attach
  1589. FROM {db_prefix}attachments' . (empty($modSettings['custom_avatar_enabled']) ? '' : '
  1590. WHERE attachment_type != {int:type_avatar}') . '
  1591. GROUP BY id_folder',
  1592. array(
  1593. 'type_avatar' => 1,
  1594. )
  1595. );
  1596. $expected_files = array();
  1597. while ($row = $smcFunc['db_fetch_assoc']($request))
  1598. $expected_files[$row['id_folder']] = $row['num_attach'];
  1599. $smcFunc['db_free_result']($request);
  1600. $attachdirs = array();
  1601. foreach ($modSettings['attachmentUploadDir'] as $id => $dir)
  1602. {
  1603. // If there aren't any attachments in this directory this won't exist.
  1604. if (!isset($expected_files[$id]))
  1605. $expected_files[$id] = 0;
  1606. // Check if the directory is doing okay.
  1607. list ($status, $error, $size) = attachDirStatus($dir, $expected_files[$id]);
  1608. $attachdirs[] = array(
  1609. 'id' => $id,
  1610. 'current' => $id == $modSettings['currentAttachmentUploadDir'],
  1611. 'path' => $dir,
  1612. 'current_size' => $size,
  1613. 'num_files' => $expected_files[$id],
  1614. 'status' => ($error ? '<span class="error">' : '') . sprintf($txt['attach_dir_' . $status], $context['session_id'], $context['session_var']) . ($error ? '</span>' : ''),
  1615. );
  1616. }
  1617. // Just stick a new directory on at the bottom.
  1618. if (isset($_REQUEST['new_path']))
  1619. $attachdirs[] = array(
  1620. 'id' => max(array_merge(array_keys($expected_files), array_keys($modSettings['attachmentUploadDir']))) + 1,
  1621. 'current' => false,
  1622. 'path' => '',
  1623. 'current_size' => '',
  1624. 'num_files' => '',
  1625. 'status' => '',
  1626. );
  1627. return $attachdirs;
  1628. }
  1629. /**
  1630. * Checks the status of an attachment directory and returns an array
  1631. * of the status key, if that status key signifies an error, and
  1632. * the folder size.
  1633. *
  1634. * @param string $dir
  1635. * @param int $expected_files
  1636. */
  1637. function attachDirStatus($dir, $expected_files)
  1638. {
  1639. if (!is_dir($dir))
  1640. return array('does_not_exist', true, '');
  1641. elseif (!is_writable($dir))
  1642. return array('not_writable', true, '');
  1643. // Everything is okay so far, start to scan through the directory.
  1644. $dir_size = 0;
  1645. $num_files = 0;
  1646. $dir_handle = dir($dir);
  1647. while ($file = $dir_handle->read())
  1648. {
  1649. // Now do we have a real file here?
  1650. if (in_array($file, array('.', '..', '.htaccess', 'index.php')))
  1651. continue;
  1652. $dir_size += filesize($dir . '/' . $file);
  1653. $num_files++;
  1654. }
  1655. $dir_handle->close();
  1656. $dir_size = round($dir_size / 1024, 2);
  1657. if ($num_files < $expected_files)
  1658. return array('files_missing', true, $dir_size);
  1659. // Empty?
  1660. elseif ($expected_files == 0)
  1661. return array('unused', false, $dir_size);
  1662. // All good!
  1663. else
  1664. return array('ok', false, $dir_size);
  1665. }
  1666. ?>