ManageAttachments.php 65 KB

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