2
0

ManageAttachments.php 60 KB

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