ManageAttachments.php 60 KB

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