ManageAttachments.php 60 KB

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