ManageAttachments.php 70 KB

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