ManageAttachments.php 95 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818
  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 2013 Simple Machines and individual contributors
  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('No direct access...');
  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. 'transfer' => 'TransferAttachments',
  49. );
  50. call_integration_hook('integrate_manage_attachments', array(&$subActions));
  51. // Pick the correct sub-action.
  52. if (isset($_REQUEST['sa']) && isset($subActions[$_REQUEST['sa']]))
  53. $context['sub_action'] = $_REQUEST['sa'];
  54. else
  55. $context['sub_action'] = 'browse';
  56. // Default page title is good.
  57. $context['page_title'] = $txt['attachments_avatars'];
  58. // This uses admin tabs - as it should!
  59. $context[$context['admin_menu_name']]['tab_data'] = array(
  60. 'title' => $txt['attachments_avatars'],
  61. 'help' => 'manage_files',
  62. 'description' => $txt['attachments_desc'],
  63. );
  64. // Finally fall through to what we are doing.
  65. $subActions[$context['sub_action']]();
  66. }
  67. /**
  68. * Allows to show/change attachment settings.
  69. * This is the default sub-action of the 'Attachments and Avatars' center.
  70. * Called by index.php?action=admin;area=manageattachments;sa=attachments.
  71. *
  72. * @param bool $return_config = false
  73. * @uses 'attachments' sub template.
  74. */
  75. function ManageAttachmentSettings($return_config = false)
  76. {
  77. global $txt, $modSettings, $scripturl, $context, $options, $sourcedir, $boarddir;
  78. require_once($sourcedir . '/Subs-Attachments.php');
  79. // Get the current attachment directory.
  80. $modSettings['attachmentUploadDir'] = unserialize($modSettings['attachmentUploadDir']);
  81. $context['attachmentUploadDir'] = $modSettings['attachmentUploadDir'][$modSettings['currentAttachmentUploadDir']];
  82. // First time here?
  83. if (empty($modSettings['attachment_basedirectories']) && $modSettings['currentAttachmentUploadDir'] == 1 && count($modSettings['attachmentUploadDir']) == 1)
  84. $modSettings['attachmentUploadDir'] = $modSettings['attachmentUploadDir'][1];
  85. // If not set, show a default path for the base directory
  86. if (!isset($_GET['save']) && empty($modSettings['basedirectory_for_attachments']))
  87. if (is_dir($modSettings['attachmentUploadDir'][1]))
  88. $modSettings['basedirectory_for_attachments'] = $modSettings['attachmentUploadDir'][1];
  89. else
  90. $modSettings['basedirectory_for_attachments'] = $context['attachmentUploadDir'];
  91. $context['valid_upload_dir'] = is_dir($context['attachmentUploadDir']) && is_writable($context['attachmentUploadDir']);
  92. if (!empty($modSettings['automanage_attachments']))
  93. $context['valid_basedirectory'] = !empty($modSettings['basedirectory_for_attachments']) && is_writable($modSettings['basedirectory_for_attachments']);
  94. else
  95. $context['valid_basedirectory'] = true;
  96. // A bit of razzle dazzle with the $txt strings. :)
  97. $txt['attachment_path'] = $context['attachmentUploadDir'];
  98. $txt['basedirectory_for_attachments_path']= isset($modSettings['basedirectory_for_attachments']) ? $modSettings['basedirectory_for_attachments'] : '';
  99. $txt['use_subdirectories_for_attachments_note'] = empty($modSettings['attachment_basedirectories']) || empty($modSettings['use_subdirectories_for_attachments']) ? $txt['use_subdirectories_for_attachments_note'] : '';
  100. $txt['attachmentUploadDir_multiple_configure'] = '<a href="' . $scripturl . '?action=admin;area=manageattachments;sa=attachpaths">[' . $txt['attachmentUploadDir_multiple_configure'] . ']</a>';
  101. $txt['attach_current_dir'] = empty($modSettings['automanage_attachments']) ? $txt['attach_current_dir'] : $txt['attach_last_dir'];
  102. $txt['attach_current_dir_warning'] = $txt['attach_current_dir'] . $txt['attach_current_dir_warning'];
  103. $txt['basedirectory_for_attachments_warning'] = $txt['basedirectory_for_attachments_current'] . $txt['basedirectory_for_attachments_warning'];
  104. // Perform a test to see if the GD module or ImageMagick are installed.
  105. $testImg = get_extension_funcs('gd') || class_exists('Imagick');
  106. // See if we can find if the server is set up to support the attacment limits
  107. $post_max_size = ini_get('post_max_size');
  108. $upload_max_filesize = ini_get('upload_max_filesize');
  109. $testPM = !empty($post_max_size) ? (memoryReturnBytes($post_max_size) >= (isset($modSettings['attachmentPostLimit']) ? $modSettings['attachmentPostLimit'] * 1024 : 0)) : true;
  110. $testUM = !empty($upload_max_filesize) ? (memoryReturnBytes($upload_max_filesize) >= (isset($modSettings['attachmentSizeLimit']) ? $modSettings['attachmentSizeLimit'] * 1024 : 0)) : true;
  111. $config_vars = array(
  112. array('title', 'attachment_manager_settings'),
  113. // Are attachments enabled?
  114. array('select', 'attachmentEnable', array($txt['attachmentEnable_deactivate'], $txt['attachmentEnable_enable_all'], $txt['attachmentEnable_disable_new'])),
  115. '',
  116. // Directory and size limits.
  117. 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'])),
  118. array('check', 'use_subdirectories_for_attachments', 'subtext' => $txt['use_subdirectories_for_attachments_note']),
  119. (empty($modSettings['attachment_basedirectories']) ? array('text', 'basedirectory_for_attachments', 40,) : array('var_message', 'basedirectory_for_attachments', 'message' => 'basedirectory_for_attachments_path', 'invalid' => empty($context['valid_basedirectory']), 'text_label' => (!empty($context['valid_basedirectory']) ? $txt['basedirectory_for_attachments_current'] : $txt['basedirectory_for_attachments_warning']))),
  120. empty($modSettings['attachment_basedirectories']) && $modSettings['currentAttachmentUploadDir'] == 1 && count($modSettings['attachmentUploadDir']) == 1 ? array('text', 'attachmentUploadDir', 'subtext' => $txt['attachmentUploadDir_multiple_configure'], 40, 'invalid' => !$context['valid_upload_dir']) : array('var_message', 'attach_current_directory', 'subtext' => $txt['attachmentUploadDir_multiple_configure'], 'message' => 'attachment_path', 'invalid' => empty($context['valid_upload_dir']), 'text_label' => (!empty($context['valid_upload_dir']) ? $txt['attach_current_dir'] : $txt['attach_current_dir_warning'])),
  121. array('int', 'attachmentDirFileLimit', 'subtext' => $txt['zero_for_no_limit'], 6),
  122. array('int', 'attachmentDirSizeLimit', 'subtext' => $txt['zero_for_no_limit'], 6, 'postinput' => $txt['kilobyte']),
  123. '',
  124. // Posting limits
  125. array('int', 'attachmentPostLimit', 'subtext' => $txt['zero_for_no_limit'], 6, 'postinput' => $txt['kilobyte']),
  126. array('warning', empty($testPM) ? 'attachment_postsize_warning' : ''),
  127. array('int', 'attachmentSizeLimit', 'subtext' => $txt['zero_for_no_limit'], 6, 'postinput' => $txt['kilobyte']),
  128. array('warning', empty($testUM) ? 'attachment_filesize_warning' : ''),
  129. array('int', 'attachmentNumPerPostLimit', 'subtext' => $txt['zero_for_no_limit'], 6),
  130. // Security Items
  131. array('title', 'attachment_security_settings'),
  132. // Extension checks etc.
  133. array('check', 'attachmentCheckExtensions'),
  134. array('text', 'attachmentExtensions', 40),
  135. '',
  136. // Image checks.
  137. array('warning', empty($testImg) ? 'attachment_img_enc_warning' : ''),
  138. array('check', 'attachment_image_reencode'),
  139. '',
  140. array('warning', 'attachment_image_paranoid_warning'),
  141. array('check', 'attachment_image_paranoid'),
  142. // Thumbnail settings.
  143. array('title', 'attachment_thumbnail_settings'),
  144. array('check', 'attachmentShowImages'),
  145. array('check', 'attachmentThumbnails'),
  146. array('check', 'attachment_thumb_png'),
  147. array('check', 'attachment_thumb_memory'),
  148. array('warning', 'attachment_thumb_memory_note'),
  149. array('text', 'attachmentThumbWidth', 6),
  150. array('text', 'attachmentThumbHeight', 6),
  151. '',
  152. array('int', 'max_image_width', 'subtext' => $txt['zero_for_no_limit']),
  153. array('int', 'max_image_height', 'subtext' => $txt['zero_for_no_limit']),
  154. );
  155. $context['settings_post_javascript'] = '
  156. var storing_type = document.getElementById(\'automanage_attachments\');
  157. var base_dir = document.getElementById(\'use_subdirectories_for_attachments\');
  158. createEventListener(storing_type)
  159. storing_type.addEventListener("change", toggleSubDir, false);
  160. createEventListener(base_dir)
  161. base_dir.addEventListener("change", toggleSubDir, false);
  162. toggleSubDir();';
  163. call_integration_hook('integrate_modify_attachment_settings', array(&$config_vars));
  164. if ($return_config)
  165. return $config_vars;
  166. // These are very likely to come in handy! (i.e. without them we're doomed!)
  167. require_once($sourcedir . '/ManagePermissions.php');
  168. require_once($sourcedir . '/ManageServer.php');
  169. // Saving settings?
  170. if (isset($_GET['save']))
  171. {
  172. checkSession();
  173. if (isset($_POST['attachmentUploadDir']))
  174. {
  175. if (!empty($_POST['attachmentUploadDir']) && $modSettings['attachmentUploadDir'] != $_POST['attachmentUploadDir'])
  176. rename($modSettings['attachmentUploadDir'], $_POST['attachmentUploadDir']);
  177. $modSettings['attachmentUploadDir'] = array(1 => $_POST['attachmentUploadDir']);
  178. $_POST['attachmentUploadDir'] = serialize($modSettings['attachmentUploadDir']);
  179. }
  180. if (!empty($_POST['use_subdirectories_for_attachments']))
  181. {
  182. if (isset($_POST['use_subdirectories_for_attachments']) && empty($_POST['basedirectory_for_attachments']))
  183. $_POST['basedirectory_for_attachments'] = (!empty($modSettings['basedirectory_for_attachments']) ? ($modSettings['basedirectory_for_attachments']) : $boarddir);
  184. if (!empty($_POST['use_subdirectories_for_attachments']) && !empty($modSettings['attachment_basedirectories']))
  185. {
  186. if (!is_array($modSettings['attachment_basedirectories']))
  187. $modSettings['attachment_basedirectories'] = unserialize($modSettings['attachment_basedirectories']);
  188. }
  189. else
  190. $modSettings['attachment_basedirectories'] = array();
  191. if (!empty($_POST['use_subdirectories_for_attachments']) && !empty($_POST['basedirectory_for_attachments']) && !in_array($_POST['basedirectory_for_attachments'], $modSettings['attachment_basedirectories']))
  192. {
  193. $currentAttachmentUploadDir = $modSettings['currentAttachmentUploadDir'];
  194. if (!in_array($_POST['basedirectory_for_attachments'], $modSettings['attachmentUploadDir']))
  195. {
  196. if (!automanage_attachments_create_directory($_POST['basedirectory_for_attachments']))
  197. $_POST['basedirectory_for_attachments'] = $modSettings['basedirectory_for_attachments'];
  198. }
  199. if (!in_array($_POST['basedirectory_for_attachments'], $modSettings['attachment_basedirectories']))
  200. {
  201. $modSettings['attachment_basedirectories'][$modSettings['currentAttachmentUploadDir']] = $_POST['basedirectory_for_attachments'];
  202. updateSettings(array(
  203. 'attachment_basedirectories' => serialize($modSettings['attachment_basedirectories']),
  204. 'currentAttachmentUploadDir' => $currentAttachmentUploadDir,
  205. ));
  206. $_POST['use_subdirectories_for_attachments'] = 1;
  207. $_POST['attachmentUploadDir'] = serialize($modSettings['attachmentUploadDir']);
  208. }
  209. }
  210. }
  211. call_integration_hook('integrate_save_attachment_settings');
  212. saveDBSettings($config_vars);
  213. redirectexit('action=admin;area=manageattachments;sa=attachments');
  214. }
  215. $context['post_url'] = $scripturl . '?action=admin;area=manageattachments;save;sa=attachments';
  216. prepareDBSettingContext($config_vars);
  217. $context['sub_template'] = 'show_settings';
  218. }
  219. /**
  220. * This allows to show/change avatar settings.
  221. * Called by index.php?action=admin;area=manageattachments;sa=avatars.
  222. * Show/set permissions for permissions: 'profile_server_avatar',
  223. * 'profile_upload_avatar' and 'profile_remote_avatar'.
  224. *
  225. * @param bool $return_config = false
  226. * @uses 'avatars' sub template.
  227. */
  228. function ManageAvatarSettings($return_config = false)
  229. {
  230. global $txt, $context, $modSettings, $sourcedir, $scripturl;
  231. // Perform a test to see if the GD module or ImageMagick are installed.
  232. $testImg = get_extension_funcs('gd') || class_exists('Imagick');
  233. $context['valid_avatar_dir'] = is_dir($modSettings['avatar_directory']);
  234. $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']));
  235. $config_vars = array(
  236. // Server stored avatars!
  237. array('title', 'avatar_server_stored'),
  238. array('warning', empty($testImg) ? 'avatar_img_enc_warning' : ''),
  239. array('permissions', 'profile_server_avatar', 0, $txt['avatar_server_stored_groups']),
  240. array('text', 'avatar_directory', 40, 'invalid' => !$context['valid_avatar_dir']),
  241. array('text', 'avatar_url', 40),
  242. // External avatars?
  243. array('title', 'avatar_external'),
  244. array('permissions', 'profile_remote_avatar', 0, $txt['avatar_external_url_groups']),
  245. array('check', 'avatar_download_external', 0, 'onchange' => 'fUpdateStatus();'),
  246. array('text', 'avatar_max_width_external', 'subtext' => $txt['zero_for_no_limit'], 6),
  247. array('text', 'avatar_max_height_external', 'subtext' => $txt['zero_for_no_limit'], 6),
  248. array('select', 'avatar_action_too_large',
  249. array(
  250. 'option_refuse' => $txt['option_refuse'],
  251. 'option_html_resize' => $txt['option_html_resize'],
  252. 'option_js_resize' => $txt['option_js_resize'],
  253. 'option_download_and_resize' => $txt['option_download_and_resize'],
  254. ),
  255. ),
  256. // Uploadable avatars?
  257. array('title', 'avatar_upload'),
  258. array('permissions', 'profile_upload_avatar', 0, $txt['avatar_upload_groups']),
  259. array('text', 'avatar_max_width_upload', 'subtext' => $txt['zero_for_no_limit'], 6),
  260. array('text', 'avatar_max_height_upload', 'subtext' => $txt['zero_for_no_limit'], 6),
  261. array('check', 'avatar_resize_upload', 'subtext' => $txt['avatar_resize_upload_note']),
  262. array('check', 'avatar_reencode'),
  263. '',
  264. array('warning', 'avatar_paranoid_warning'),
  265. array('check', 'avatar_paranoid'),
  266. '',
  267. array('check', 'avatar_download_png'),
  268. array('select', 'custom_avatar_enabled', array($txt['option_attachment_dir'], $txt['option_specified_dir']), 'onchange' => 'fUpdateStatus();'),
  269. array('text', 'custom_avatar_dir', 40, 'subtext' => $txt['custom_avatar_dir_desc'], 'invalid' => !$context['valid_custom_avatar_dir']),
  270. array('text', 'custom_avatar_url', 40),
  271. );
  272. call_integration_hook('integrate_modify_avatar_settings', array(&$config_vars));
  273. if ($return_config)
  274. return $config_vars;
  275. // We need this file for the settings template.
  276. require_once($sourcedir . '/ManageServer.php');
  277. // Saving avatar settings?
  278. if (isset($_GET['save']))
  279. {
  280. checkSession();
  281. // Just incase the admin forgot to set both custom avatar values, we disable it to prevent errors.
  282. if (isset($_POST['custom_avatar_enabled']) && $_POST['custom_avatar_enabled'] == 1 && (empty($_POST['custom_avatar_dir']) || empty($_POST['custom_avatar_url'])))
  283. $_POST['custom_avatar_enabled'] = 0;
  284. call_integration_hook('integrate_save_avatar_settings');
  285. saveDBSettings($config_vars);
  286. redirectexit('action=admin;area=manageattachments;sa=avatars');
  287. }
  288. // Attempt to figure out if the admin is trying to break things.
  289. $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;';
  290. // We need this for the in-line permissions
  291. createToken('admin-mp');
  292. // Prepare the context.
  293. $context['post_url'] = $scripturl . '?action=admin;area=manageattachments;save;sa=avatars';
  294. prepareDBSettingContext($config_vars);
  295. // Add a layer for the javascript.
  296. $context['template_layers'][] = 'avatar_settings';
  297. $context['sub_template'] = 'show_settings';
  298. }
  299. /**
  300. * Show a list of attachment or avatar files.
  301. * Called by ?action=admin;area=manageattachments;sa=browse for attachments
  302. * and ?action=admin;area=manageattachments;sa=browse;avatars for avatars.
  303. * Allows sorting by name, date, size and member.
  304. * Paginates results.
  305. */
  306. function BrowseFiles()
  307. {
  308. global $context, $txt, $scripturl, $options, $modSettings;
  309. global $smcFunc, $sourcedir, $settings;
  310. // Attachments or avatars?
  311. $context['browse_type'] = isset($_REQUEST['avatars']) ? 'avatars' : (isset($_REQUEST['thumbs']) ? 'thumbs' : 'attachments');
  312. $titles = array(
  313. 'attachments' => array('?action=admin;area=manageattachments;sa=browse', $txt['attachment_manager_attachments']),
  314. 'avatars' => array('?action=admin;area=manageattachments;sa=browse;avatars', $txt['attachment_manager_avatars']),
  315. 'thumbs' => array('?action=admin;area=manageattachments;sa=browse;thumbs', $txt['attachment_manager_thumbs']),
  316. );
  317. $list_title = $txt['attachment_manager_browse_files'] . ': ';
  318. foreach ($titles as $browse_type => $details)
  319. {
  320. if ($browse_type != 'attachments')
  321. $list_title .= ' | ';
  322. if ($context['browse_type'] == $browse_type)
  323. $list_title .= '<img src="' . $settings['images_url'] . '/selected.png" alt="&gt;" /> ';
  324. $list_title .= '<a href="' . $scripturl . $details[0] . '">' . $details[1] . '</a>';
  325. }
  326. // Set the options for the list component.
  327. $listOptions = array(
  328. 'id' => 'file_list',
  329. 'title' => $list_title,
  330. 'items_per_page' => $modSettings['defaultMaxMessages'],
  331. 'base_href' => $scripturl . '?action=admin;area=manageattachments;sa=browse' . ($context['browse_type'] === 'avatars' ? ';avatars' : ($context['browse_type'] === 'thumbs' ? ';thumbs' : '')),
  332. 'default_sort_col' => 'name',
  333. 'no_items_label' => $txt['attachment_manager_' . ($context['browse_type'] === 'avatars' ? 'avatars' : ( $context['browse_type'] === 'thumbs' ? 'thumbs' : 'attachments')) . '_no_entries'],
  334. 'get_items' => array(
  335. 'function' => 'list_getFiles',
  336. 'params' => array(
  337. $context['browse_type'],
  338. ),
  339. ),
  340. 'get_count' => array(
  341. 'function' => 'list_getNumFiles',
  342. 'params' => array(
  343. $context['browse_type'],
  344. ),
  345. ),
  346. 'columns' => array(
  347. 'name' => array(
  348. 'header' => array(
  349. 'value' => $txt['attachment_name'],
  350. ),
  351. 'data' => array(
  352. 'function' => create_function('$rowData', '
  353. global $modSettings, $context, $scripturl;
  354. $link = \'<a href="\';
  355. // In case of a custom avatar URL attachments have a fixed directory.
  356. if ($rowData[\'attachment_type\'] == 1)
  357. $link .= sprintf(\'%1$s/%2$s\', $modSettings[\'custom_avatar_url\'], $rowData[\'filename\']);
  358. // By default avatars are downloaded almost as attachments.
  359. elseif ($context[\'browse_type\'] == \'avatars\')
  360. $link .= sprintf(\'%1$s?action=dlattach;type=avatar;attach=%2$d\', $scripturl, $rowData[\'id_attach\']);
  361. // Normal attachments are always linked to a topic ID.
  362. else
  363. $link .= sprintf(\'%1$s?action=dlattach;topic=%2$d.0;attach=%3$d\', $scripturl, $rowData[\'id_topic\'], $rowData[\'id_attach\']);
  364. $link .= \'"\';
  365. // Show a popup on click if it\'s a picture and we know its dimensions.
  366. if (!empty($rowData[\'width\']) && !empty($rowData[\'height\']))
  367. $link .= sprintf(\' onclick="return reqWin(this.href\' . ($rowData[\'attachment_type\'] == 1 ? \'\' : \' + \\\';image\\\'\') . \', %1$d, %2$d, true);"\', $rowData[\'width\'] + 20, $rowData[\'height\'] + 20);
  368. $link .= sprintf(\'>%1$s</a>\', preg_replace(\'~&amp;#(\\\\d{1,7}|x[0-9a-fA-F]{1,6});~\', \'&#\\\\1;\', htmlspecialchars($rowData[\'filename\'])));
  369. // Show the dimensions.
  370. if (!empty($rowData[\'width\']) && !empty($rowData[\'height\']))
  371. $link .= sprintf(\' <span class="smalltext">%1$dx%2$d</span>\', $rowData[\'width\'], $rowData[\'height\']);
  372. return $link;
  373. '),
  374. ),
  375. 'sort' => array(
  376. 'default' => 'a.filename',
  377. 'reverse' => 'a.filename DESC',
  378. ),
  379. ),
  380. 'filesize' => array(
  381. 'header' => array(
  382. 'value' => $txt['attachment_file_size'],
  383. ),
  384. 'data' => array(
  385. 'function' => create_function('$rowData','
  386. global $txt;
  387. return sprintf(\'%1$s%2$s\', round($rowData[\'size\'] / 1024, 2), $txt[\'kilobyte\']);
  388. '),
  389. ),
  390. 'sort' => array(
  391. 'default' => 'a.size',
  392. 'reverse' => 'a.size DESC',
  393. ),
  394. ),
  395. 'member' => array(
  396. 'header' => array(
  397. 'value' => $context['browse_type'] == 'avatars' ? $txt['attachment_manager_member'] : $txt['posted_by'],
  398. ),
  399. 'data' => array(
  400. 'function' => create_function('$rowData', '
  401. global $scripturl;
  402. // In case of an attachment, return the poster of the attachment.
  403. if (empty($rowData[\'id_member\']))
  404. return htmlspecialchars($rowData[\'poster_name\']);
  405. // Otherwise it must be an avatar, return the link to the owner of it.
  406. else
  407. return sprintf(\'<a href="%1$s?action=profile;u=%2$d">%3$s</a>\', $scripturl, $rowData[\'id_member\'], $rowData[\'poster_name\']);
  408. '),
  409. ),
  410. 'sort' => array(
  411. 'default' => 'mem.real_name',
  412. 'reverse' => 'mem.real_name DESC',
  413. ),
  414. ),
  415. 'date' => array(
  416. 'header' => array(
  417. 'value' => $context['browse_type'] == 'avatars' ? $txt['attachment_manager_last_active'] : $txt['date'],
  418. ),
  419. 'data' => array(
  420. 'function' => create_function('$rowData', '
  421. global $txt, $context, $scripturl;
  422. // The date the message containing the attachment was posted or the owner of the avatar was active.
  423. $date = empty($rowData[\'poster_time\']) ? $txt[\'never\'] : timeformat($rowData[\'poster_time\']);
  424. // Add a link to the topic in case of an attachment.
  425. if ($context[\'browse_type\'] !== \'avatars\')
  426. $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\']);
  427. return $date;
  428. '),
  429. ),
  430. 'sort' => array(
  431. 'default' => $context['browse_type'] === 'avatars' ? 'mem.last_login' : 'm.id_msg',
  432. 'reverse' => $context['browse_type'] === 'avatars' ? 'mem.last_login DESC' : 'm.id_msg DESC',
  433. ),
  434. ),
  435. 'downloads' => array(
  436. 'header' => array(
  437. 'value' => $txt['downloads'],
  438. ),
  439. 'data' => array(
  440. 'db' => 'downloads',
  441. 'comma_format' => true,
  442. ),
  443. 'sort' => array(
  444. 'default' => 'a.downloads',
  445. 'reverse' => 'a.downloads DESC',
  446. ),
  447. ),
  448. 'check' => array(
  449. 'header' => array(
  450. 'value' => '<input type="checkbox" onclick="invertAll(this, this.form);" class="input_check" />',
  451. 'class' => 'centercol',
  452. ),
  453. 'data' => array(
  454. 'sprintf' => array(
  455. 'format' => '<input type="checkbox" name="remove[%1$d]" class="input_check" />',
  456. 'params' => array(
  457. 'id_attach' => false,
  458. ),
  459. ),
  460. 'class' => 'centercol',
  461. ),
  462. ),
  463. ),
  464. 'form' => array(
  465. 'href' => $scripturl . '?action=admin;area=manageattachments;sa=remove' . ($context['browse_type'] === 'avatars' ? ';avatars' : ($context['browse_type'] === 'thumbs' ? ';thumbs' : '')),
  466. 'include_sort' => true,
  467. 'include_start' => true,
  468. 'hidden_fields' => array(
  469. 'type' => $context['browse_type'],
  470. ),
  471. ),
  472. 'additional_rows' => array(
  473. array(
  474. 'position' => 'below_table_data',
  475. 'value' => '<input type="submit" name="remove_submit" class="button_submit" value="' . $txt['quickmod_delete_selected'] . '" onclick="return confirm(\'' . $txt['confirm_delete_attachments'] . '\');" />',
  476. ),
  477. ),
  478. );
  479. // Create the list.
  480. require_once($sourcedir . '/Subs-List.php');
  481. createList($listOptions);
  482. $context['sub_template'] = 'show_list';
  483. $context['default_list'] = 'file_list';
  484. }
  485. /**
  486. * Returns the list of attachments files (avatars or not), recorded
  487. * in the database, per the parameters received.
  488. *
  489. * @param int $start
  490. * @param int $items_per_page
  491. * @param string $sort
  492. * @param string $browse_type can be one of 'avatars' or ... not. :P
  493. */
  494. function list_getFiles($start, $items_per_page, $sort, $browse_type)
  495. {
  496. global $smcFunc, $txt;
  497. // Choose a query depending on what we are viewing.
  498. if ($browse_type === 'avatars')
  499. $request = $smcFunc['db_query']('', '
  500. SELECT
  501. {string:blank_text} AS id_msg, IFNULL(mem.real_name, {string:not_applicable_text}) AS poster_name,
  502. mem.last_login AS poster_time, 0 AS id_topic, a.id_member, a.id_attach, a.filename, a.file_hash, a.attachment_type,
  503. a.size, a.width, a.height, a.downloads, {string:blank_text} AS subject, 0 AS id_board
  504. FROM {db_prefix}attachments AS a
  505. LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = a.id_member)
  506. WHERE a.id_member != {int:guest_id}
  507. ORDER BY {raw:sort}
  508. LIMIT {int:start}, {int:per_page}',
  509. array(
  510. 'guest_id' => 0,
  511. 'blank_text' => '',
  512. 'not_applicable_text' => $txt['not_applicable'],
  513. 'sort' => $sort,
  514. 'start' => $start,
  515. 'per_page' => $items_per_page,
  516. )
  517. );
  518. else
  519. $request = $smcFunc['db_query']('', '
  520. SELECT
  521. m.id_msg, IFNULL(mem.real_name, m.poster_name) AS poster_name, m.poster_time, m.id_topic, m.id_member,
  522. a.id_attach, a.filename, a.file_hash, a.attachment_type, a.size, a.width, a.height, a.downloads, mf.subject, t.id_board
  523. FROM {db_prefix}attachments AS a
  524. INNER JOIN {db_prefix}messages AS m ON (m.id_msg = a.id_msg)
  525. INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic)
  526. INNER JOIN {db_prefix}messages AS mf ON (mf.id_msg = t.id_first_msg)
  527. LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)
  528. WHERE a.attachment_type = {int:attachment_type}
  529. ORDER BY {raw:sort}
  530. LIMIT {int:start}, {int:per_page}',
  531. array(
  532. 'attachment_type' => $browse_type == 'thumbs' ? '3' : '0',
  533. 'sort' => $sort,
  534. 'start' => $start,
  535. 'per_page' => $items_per_page,
  536. )
  537. );
  538. $files = array();
  539. while ($row = $smcFunc['db_fetch_assoc']($request))
  540. $files[] = $row;
  541. $smcFunc['db_free_result']($request);
  542. return $files;
  543. }
  544. /**
  545. * Return the number of files of the specified type recorded in the database.
  546. * (the specified type being attachments or avatars).
  547. *
  548. * @param string $browse_type can be one of 'avatars' or not. (in which case they're attachments)
  549. */
  550. function list_getNumFiles($browse_type)
  551. {
  552. global $smcFunc;
  553. // Depending on the type of file, different queries are used.
  554. if ($browse_type === 'avatars')
  555. $request = $smcFunc['db_query']('', '
  556. SELECT COUNT(*)
  557. FROM {db_prefix}attachments
  558. WHERE id_member != {int:guest_id_member}',
  559. array(
  560. 'guest_id_member' => 0,
  561. )
  562. );
  563. else
  564. $request = $smcFunc['db_query']('', '
  565. SELECT COUNT(*) AS num_attach
  566. FROM {db_prefix}attachments AS a
  567. INNER JOIN {db_prefix}messages AS m ON (m.id_msg = a.id_msg)
  568. INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic)
  569. INNER JOIN {db_prefix}messages AS mf ON (mf.id_msg = t.id_first_msg)
  570. WHERE a.attachment_type = {int:attachment_type}
  571. AND a.id_member = {int:guest_id_member}',
  572. array(
  573. 'attachment_type' => $browse_type === 'thumbs' ? '3' : '0',
  574. 'guest_id_member' => 0,
  575. )
  576. );
  577. list ($num_files) = $smcFunc['db_fetch_row']($request);
  578. $smcFunc['db_free_result']($request);
  579. return $num_files;
  580. }
  581. /**
  582. * Show several file maintenance options.
  583. * Called by ?action=admin;area=manageattachments;sa=maintain.
  584. * Calculates file statistics (total file size, number of attachments,
  585. * number of avatars, attachment space available).
  586. *
  587. * @uses the 'maintain' sub template.
  588. */
  589. function MaintainFiles()
  590. {
  591. global $context, $modSettings, $txt, $smcFunc;
  592. $context['sub_template'] = 'maintenance';
  593. if (!empty($modSettings['currentAttachmentUploadDir']))
  594. $attach_dirs = unserialize($modSettings['attachmentUploadDir']);
  595. else
  596. $attach_dirs = array($modSettings['attachmentUploadDir']);
  597. // Get the number of attachments....
  598. $request = $smcFunc['db_query']('', '
  599. SELECT COUNT(*)
  600. FROM {db_prefix}attachments
  601. WHERE attachment_type = {int:attachment_type}
  602. AND id_member = {int:guest_id_member}',
  603. array(
  604. 'attachment_type' => 0,
  605. 'guest_id_member' => 0,
  606. )
  607. );
  608. list ($context['num_attachments']) = $smcFunc['db_fetch_row']($request);
  609. $smcFunc['db_free_result']($request);
  610. $context['num_attachments'] = comma_format($context['num_attachments'], 0);
  611. // Also get the avatar amount....
  612. $request = $smcFunc['db_query']('', '
  613. SELECT COUNT(*)
  614. FROM {db_prefix}attachments
  615. WHERE id_member != {int:guest_id_member}',
  616. array(
  617. 'guest_id_member' => 0,
  618. )
  619. );
  620. list ($context['num_avatars']) = $smcFunc['db_fetch_row']($request);
  621. $smcFunc['db_free_result']($request);
  622. $context['num_avatars'] = comma_format($context['num_avatars'], 0);
  623. // Check the size of all the directories.
  624. $request = $smcFunc['db_query']('', '
  625. SELECT SUM(size)
  626. FROM {db_prefix}attachments
  627. WHERE attachment_type != {int:type}',
  628. array(
  629. 'type' => 1,
  630. )
  631. );
  632. list ($attachmentDirSize) = $smcFunc['db_fetch_row']($request);
  633. $smcFunc['db_free_result']($request);
  634. // Divide it into kilobytes.
  635. $attachmentDirSize /= 1024;
  636. $context['attachment_total_size'] = comma_format($attachmentDirSize, 2);
  637. $request = $smcFunc['db_query']('', '
  638. SELECT COUNT(*), SUM(size)
  639. FROM {db_prefix}attachments
  640. WHERE id_folder = {int:folder_id}
  641. AND attachment_type != {int:type}',
  642. array(
  643. 'folder_id' => $modSettings['currentAttachmentUploadDir'],
  644. 'type' => 1,
  645. )
  646. );
  647. list ($current_dir_files, $current_dir_size) = $smcFunc['db_fetch_row']($request);
  648. $smcFunc['db_free_result']($request);
  649. $current_dir_size /= 1024;
  650. // If they specified a limit only....
  651. if (!empty($modSettings['attachmentDirSizeLimit']))
  652. $context['attachment_space'] = comma_format(max($modSettings['attachmentDirSizeLimit'] - $current_dir_size, 0), 2);
  653. $context['attachment_current_size'] = comma_format($current_dir_size, 2);
  654. if (!empty($modSettings['attachmentDirFileLimit']))
  655. $context['attachment_files'] = comma_format(max($modSettings['attachmentDirFileLimit'] - $current_dir_files, 0), 0);
  656. $context['attachment_current_files'] = comma_format($current_dir_files, 0);
  657. $context['attach_multiple_dirs'] = count($attach_dirs) > 1 ? true : false;
  658. $context['attach_dirs'] = $attach_dirs;
  659. $context['base_dirs'] = !empty($modSettings['attachment_basedirectories']) ? unserialize($modSettings['attachment_basedirectories']) : array();
  660. $context['checked'] = isset($_SESSION['checked']) ? $_SESSION['checked'] : true;
  661. if (!empty($_SESSION['results']))
  662. {
  663. $context['results'] = implode('<br />', $_SESSION['results']);
  664. unset($_SESSION['results']);
  665. }
  666. }
  667. /**
  668. * Move avatars from their current location, to the custom_avatar_dir folder.
  669. * Called from the maintenance screen by ?action=admin;area=manageattachments;sa=moveAvatars.
  670. */
  671. function MoveAvatars()
  672. {
  673. global $modSettings, $smcFunc;
  674. // First make sure the custom avatar dir is writable.
  675. if (!is_writable($modSettings['custom_avatar_dir']))
  676. {
  677. // Try to fix it.
  678. @chmod($modSettings['custom_avatar_dir'], 0777);
  679. // Guess that didn't work?
  680. if (!is_writable($modSettings['custom_avatar_dir']))
  681. fatal_lang_error('attachments_no_write', 'critical');
  682. }
  683. $request = $smcFunc['db_query']('', '
  684. SELECT id_attach, id_folder, id_member, filename, file_hash
  685. FROM {db_prefix}attachments
  686. WHERE attachment_type = {int:attachment_type}
  687. AND id_member > {int:guest_id_member}',
  688. array(
  689. 'attachment_type' => 0,
  690. 'guest_id_member' => 0,
  691. )
  692. );
  693. $updatedAvatars = array();
  694. while ($row = $smcFunc['db_fetch_assoc']($request))
  695. {
  696. $filename = getAttachmentFilename($row['filename'], $row['id_attach'], $row['id_folder'], false, $row['file_hash']);
  697. if (rename($filename, $modSettings['custom_avatar_dir'] . '/' . $row['filename']))
  698. $updatedAvatars[] = $row['id_attach'];
  699. }
  700. $smcFunc['db_free_result']($request);
  701. if (!empty($updatedAvatars))
  702. $smcFunc['db_query']('', '
  703. UPDATE {db_prefix}attachments
  704. SET attachment_type = {int:attachment_type}
  705. WHERE id_attach IN ({array_int:updated_avatars})',
  706. array(
  707. 'updated_avatars' => $updatedAvatars,
  708. 'attachment_type' => 1,
  709. )
  710. );
  711. redirectexit('action=admin;area=manageattachments;sa=maintenance');
  712. }
  713. /**
  714. * Remove attachments older than a given age.
  715. * Called from the maintenance screen by
  716. * ?action=admin;area=manageattachments;sa=byAge.
  717. * It optionally adds a certain text to the messages the attachments
  718. * were removed from.
  719. * @todo refactor this silly superglobals use...
  720. */
  721. function RemoveAttachmentByAge()
  722. {
  723. global $modSettings, $smcFunc;
  724. checkSession('post', 'admin');
  725. // @todo Ignore messages in topics that are stickied?
  726. // Deleting an attachment?
  727. if ($_REQUEST['type'] != 'avatars')
  728. {
  729. // Get rid of all the old attachments.
  730. $messages = removeAttachments(array('attachment_type' => 0, 'poster_time' => (time() - 24 * 60 * 60 * $_POST['age'])), 'messages', true);
  731. // Update the messages to reflect the change.
  732. if (!empty($messages) && !empty($_POST['notice']))
  733. $smcFunc['db_query']('', '
  734. UPDATE {db_prefix}messages
  735. SET body = CONCAT(body, {string:notice})
  736. WHERE id_msg IN ({array_int:messages})',
  737. array(
  738. 'messages' => $messages,
  739. 'notice' => '<br /><br />' . $_POST['notice'],
  740. )
  741. );
  742. }
  743. else
  744. {
  745. // Remove all the old avatars.
  746. removeAttachments(array('not_id_member' => 0, 'last_login' => (time() - 24 * 60 * 60 * $_POST['age'])), 'members');
  747. }
  748. redirectexit('action=admin;area=manageattachments' . (empty($_REQUEST['avatars']) ? ';sa=maintenance' : ';avatars'));
  749. }
  750. /**
  751. * Remove attachments larger than a given size.
  752. * Called from the maintenance screen by
  753. * ?action=admin;area=manageattachments;sa=bySize.
  754. * Optionally adds a certain text to the messages the attachments were
  755. * removed from.
  756. */
  757. function RemoveAttachmentBySize()
  758. {
  759. global $modSettings, $smcFunc;
  760. checkSession('post', 'admin');
  761. // Find humungous attachments.
  762. $messages = removeAttachments(array('attachment_type' => 0, 'size' => 1024 * $_POST['size']), 'messages', true);
  763. // And make a note on the post.
  764. if (!empty($messages) && !empty($_POST['notice']))
  765. $smcFunc['db_query']('', '
  766. UPDATE {db_prefix}messages
  767. SET body = CONCAT(body, {string:notice})
  768. WHERE id_msg IN ({array_int:messages})',
  769. array(
  770. 'messages' => $messages,
  771. 'notice' => '<br /><br />' . $_POST['notice'],
  772. )
  773. );
  774. redirectexit('action=admin;area=manageattachments;sa=maintenance');
  775. }
  776. /**
  777. * Remove a selection of attachments or avatars.
  778. * Called from the browse screen as submitted form by
  779. * ?action=admin;area=manageattachments;sa=remove
  780. */
  781. function RemoveAttachment()
  782. {
  783. global $txt, $smcFunc, $language;
  784. checkSession('post');
  785. if (!empty($_POST['remove']))
  786. {
  787. $attachments = array();
  788. // There must be a quicker way to pass this safety test??
  789. foreach ($_POST['remove'] as $removeID => $dummy)
  790. $attachments[] = (int) $removeID;
  791. if ($_REQUEST['type'] == 'avatars' && !empty($attachments))
  792. removeAttachments(array('id_attach' => $attachments));
  793. else if (!empty($attachments))
  794. {
  795. $messages = removeAttachments(array('id_attach' => $attachments), 'messages', true);
  796. // And change the message to reflect this.
  797. if (!empty($messages))
  798. {
  799. loadLanguage('index', $language, true);
  800. $smcFunc['db_query']('', '
  801. UPDATE {db_prefix}messages
  802. SET body = CONCAT(body, {string:deleted_message})
  803. WHERE id_msg IN ({array_int:messages_affected})',
  804. array(
  805. 'messages_affected' => $messages,
  806. 'deleted_message' => '<br /><br />' . $txt['attachment_delete_admin'],
  807. )
  808. );
  809. loadLanguage('index', $user_info['language'], true);
  810. }
  811. }
  812. }
  813. $_GET['sort'] = isset($_GET['sort']) ? $_GET['sort'] : 'date';
  814. redirectexit('action=admin;area=manageattachments;sa=browse;' . $_REQUEST['type'] . ';sort=' . $_GET['sort'] . (isset($_GET['desc']) ? ';desc' : '') . ';start=' . $_REQUEST['start']);
  815. }
  816. /**
  817. * Removes all attachments in a single click
  818. * Called from the maintenance screen by
  819. * ?action=admin;area=manageattachments;sa=removeall.
  820. */
  821. function RemoveAllAttachments()
  822. {
  823. global $txt, $smcFunc;
  824. checkSession('get', 'admin');
  825. $messages = removeAttachments(array('attachment_type' => 0), '', true);
  826. if (!isset($_POST['notice']))
  827. $_POST['notice'] = $txt['attachment_delete_admin'];
  828. // Add the notice on the end of the changed messages.
  829. if (!empty($messages))
  830. $smcFunc['db_query']('', '
  831. UPDATE {db_prefix}messages
  832. SET body = CONCAT(body, {string:deleted_message})
  833. WHERE id_msg IN ({array_int:messages})',
  834. array(
  835. 'messages' => $messages,
  836. 'deleted_message' => '<br /><br />' . $_POST['notice'],
  837. )
  838. );
  839. redirectexit('action=admin;area=manageattachments;sa=maintenance');
  840. }
  841. /**
  842. * Removes attachments or avatars based on a given query condition.
  843. * Called by several remove avatar/attachment functions in this file.
  844. * It removes attachments based that match the $condition.
  845. * It allows query_types 'messages' and 'members', whichever is need by the
  846. * $condition parameter.
  847. * It does no permissions check.
  848. * @internal
  849. *
  850. * @param array $condition
  851. * @param string $query_type
  852. * @param bool $return_affected_messages = false
  853. * @param bool $autoThumbRemoval = true
  854. */
  855. function removeAttachments($condition, $query_type = '', $return_affected_messages = false, $autoThumbRemoval = true)
  856. {
  857. global $modSettings, $smcFunc;
  858. // @todo This might need more work!
  859. $new_condition = array();
  860. $query_parameter = array(
  861. 'thumb_attachment_type' => 3,
  862. );
  863. $do_logging = array();
  864. if (is_array($condition))
  865. {
  866. foreach ($condition as $real_type => $restriction)
  867. {
  868. // Doing a NOT?
  869. $is_not = substr($real_type, 0, 4) == 'not_';
  870. $type = $is_not ? substr($real_type, 4) : $real_type;
  871. if (in_array($type, array('id_member', 'id_attach', 'id_msg')))
  872. $new_condition[] = 'a.' . $type . ($is_not ? ' NOT' : '') . ' IN (' . (is_array($restriction) ? '{array_int:' . $real_type . '}' : '{int:' . $real_type . '}') . ')';
  873. elseif ($type == 'attachment_type')
  874. $new_condition[] = 'a.attachment_type = {int:' . $real_type . '}';
  875. elseif ($type == 'poster_time')
  876. $new_condition[] = 'm.poster_time < {int:' . $real_type . '}';
  877. elseif ($type == 'last_login')
  878. $new_condition[] = 'mem.last_login < {int:' . $real_type . '}';
  879. elseif ($type == 'size')
  880. $new_condition[] = 'a.size > {int:' . $real_type . '}';
  881. elseif ($type == 'id_topic')
  882. $new_condition[] = 'm.id_topic IN (' . (is_array($restriction) ? '{array_int:' . $real_type . '}' : '{int:' . $real_type . '}') . ')';
  883. // Add the parameter!
  884. $query_parameter[$real_type] = $restriction;
  885. if ($type == 'do_logging')
  886. $do_logging = $condition['id_attach'];
  887. }
  888. $condition = implode(' AND ', $new_condition);
  889. }
  890. // Delete it only if it exists...
  891. $msgs = array();
  892. $attach = array();
  893. $parents = array();
  894. // Get all the attachment names and id_msg's.
  895. $request = $smcFunc['db_query']('', '
  896. SELECT
  897. 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') . ',
  898. 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
  899. FROM {db_prefix}attachments AS a' .($query_type == 'members' ? '
  900. INNER JOIN {db_prefix}members AS mem ON (mem.id_member = a.id_member)' : ($query_type == 'messages' ? '
  901. INNER JOIN {db_prefix}messages AS m ON (m.id_msg = a.id_msg)' : '')) . '
  902. LEFT JOIN {db_prefix}attachments AS thumb ON (thumb.id_attach = a.id_thumb)
  903. LEFT JOIN {db_prefix}attachments AS thumb_parent ON (thumb.attachment_type = {int:thumb_attachment_type} AND thumb_parent.id_thumb = a.id_attach)
  904. WHERE ' . $condition,
  905. $query_parameter
  906. );
  907. while ($row = $smcFunc['db_fetch_assoc']($request))
  908. {
  909. // Figure out the "encrypted" filename and unlink it ;).
  910. if ($row['attachment_type'] == 1)
  911. {
  912. // if attachment_type = 1, it's... an avatar in a custom avatar directory.
  913. // wasn't it obvious? :P
  914. // @todo look again at this.
  915. @unlink($modSettings['custom_avatar_dir'] . '/' . $row['filename']);
  916. }
  917. else
  918. {
  919. $filename = getAttachmentFilename($row['filename'], $row['id_attach'], $row['id_folder'], false, $row['file_hash']);
  920. @unlink($filename);
  921. // If this was a thumb, the parent attachment should know about it.
  922. if (!empty($row['id_parent']))
  923. $parents[] = $row['id_parent'];
  924. // If this attachments has a thumb, remove it as well.
  925. if (!empty($row['id_thumb']) && $autoThumbRemoval)
  926. {
  927. $thumb_filename = getAttachmentFilename($row['thumb_filename'], $row['id_thumb'], $row['thumb_folder'], false, $row['thumb_file_hash']);
  928. @unlink($thumb_filename);
  929. $attach[] = $row['id_thumb'];
  930. }
  931. }
  932. // Make a list.
  933. if ($return_affected_messages && empty($row['attachment_type']))
  934. $msgs[] = $row['id_msg'];
  935. $attach[] = $row['id_attach'];
  936. }
  937. $smcFunc['db_free_result']($request);
  938. // Removed attachments don't have to be updated anymore.
  939. $parents = array_diff($parents, $attach);
  940. if (!empty($parents))
  941. $smcFunc['db_query']('', '
  942. UPDATE {db_prefix}attachments
  943. SET id_thumb = {int:no_thumb}
  944. WHERE id_attach IN ({array_int:parent_attachments})',
  945. array(
  946. 'parent_attachments' => $parents,
  947. 'no_thumb' => 0,
  948. )
  949. );
  950. if (!empty($do_logging))
  951. {
  952. // In order to log the attachments, we really need their message and filename
  953. $request = $smcFunc['db_query']('', '
  954. SELECT m.id_msg, a.filename
  955. FROM {db_prefix}attachments AS a
  956. INNER JOIN {db_prefix}messages AS m ON (a.id_msg = m.id_msg)
  957. WHERE a.id_attach IN ({array_int:attachments})
  958. AND a.attachment_type = {int:attachment_type}',
  959. array(
  960. 'attachments' => $do_logging,
  961. 'attachment_type' => 0,
  962. )
  963. );
  964. while ($row = $smcFunc['db_fetch_assoc']($request))
  965. logAction(
  966. 'remove_attach',
  967. array(
  968. 'message' => $row['id_msg'],
  969. 'filename' => preg_replace('~&amp;#(\\d{1,7}|x[0-9a-fA-F]{1,6});~', '&#\\1;', $smcFunc['htmlspecialchars']($row['filename'])),
  970. )
  971. );
  972. $smcFunc['db_free_result']($request);
  973. }
  974. if (!empty($attach))
  975. $smcFunc['db_query']('', '
  976. DELETE FROM {db_prefix}attachments
  977. WHERE id_attach IN ({array_int:attachment_list})',
  978. array(
  979. 'attachment_list' => $attach,
  980. )
  981. );
  982. call_integration_hook('integrate_remove_attachments', array($attach));
  983. if ($return_affected_messages)
  984. return array_unique($msgs);
  985. }
  986. /**
  987. * This function should find attachments in the database that no longer exist and clear them, and fix filesize issues.
  988. */
  989. function RepairAttachments()
  990. {
  991. global $modSettings, $context, $txt, $smcFunc;
  992. checkSession('get');
  993. // If we choose cancel, redirect right back.
  994. if (isset($_POST['cancel']))
  995. redirectexit('action=admin;area=manageattachments;sa=maintenance');
  996. // Try give us a while to sort this out...
  997. @set_time_limit(600);
  998. $_GET['step'] = empty($_GET['step']) ? 0 : (int) $_GET['step'];
  999. $context['starting_substep'] = $_GET['substep'] = empty($_GET['substep']) ? 0 : (int) $_GET['substep'];
  1000. // Don't recall the session just in case.
  1001. if ($_GET['step'] == 0 && $_GET['substep'] == 0)
  1002. {
  1003. unset($_SESSION['attachments_to_fix'], $_SESSION['attachments_to_fix2']);
  1004. // If we're actually fixing stuff - work out what.
  1005. if (isset($_GET['fixErrors']))
  1006. {
  1007. // Nothing?
  1008. if (empty($_POST['to_fix']))
  1009. redirectexit('action=admin;area=manageattachments;sa=maintenance');
  1010. $_SESSION['attachments_to_fix'] = array();
  1011. // @todo No need to do this I think.
  1012. foreach ($_POST['to_fix'] as $key => $value)
  1013. $_SESSION['attachments_to_fix'][] = $value;
  1014. }
  1015. }
  1016. // All the valid problems are here:
  1017. $context['repair_errors'] = array(
  1018. 'missing_thumbnail_parent' => 0,
  1019. 'parent_missing_thumbnail' => 0,
  1020. 'file_missing_on_disk' => 0,
  1021. 'file_wrong_size' => 0,
  1022. 'file_size_of_zero' => 0,
  1023. 'attachment_no_msg' => 0,
  1024. 'avatar_no_member' => 0,
  1025. 'wrong_folder' => 0,
  1026. 'files_without_attachment' => 0,
  1027. );
  1028. $to_fix = !empty($_SESSION['attachments_to_fix']) ? $_SESSION['attachments_to_fix'] : array();
  1029. $context['repair_errors'] = isset($_SESSION['attachments_to_fix2']) ? $_SESSION['attachments_to_fix2'] : $context['repair_errors'];
  1030. $fix_errors = isset($_GET['fixErrors']) ? true : false;
  1031. // Get stranded thumbnails.
  1032. if ($_GET['step'] <= 0)
  1033. {
  1034. $result = $smcFunc['db_query']('', '
  1035. SELECT MAX(id_attach)
  1036. FROM {db_prefix}attachments
  1037. WHERE attachment_type = {int:thumbnail}',
  1038. array(
  1039. 'thumbnail' => 3,
  1040. )
  1041. );
  1042. list ($thumbnails) = $smcFunc['db_fetch_row']($result);
  1043. $smcFunc['db_free_result']($result);
  1044. for (; $_GET['substep'] < $thumbnails; $_GET['substep'] += 500)
  1045. {
  1046. $to_remove = array();
  1047. $result = $smcFunc['db_query']('', '
  1048. SELECT thumb.id_attach, thumb.id_folder, thumb.filename, thumb.file_hash
  1049. FROM {db_prefix}attachments AS thumb
  1050. LEFT JOIN {db_prefix}attachments AS tparent ON (tparent.id_thumb = thumb.id_attach)
  1051. WHERE thumb.id_attach BETWEEN {int:substep} AND {int:substep} + 499
  1052. AND thumb.attachment_type = {int:thumbnail}
  1053. AND tparent.id_attach IS NULL',
  1054. array(
  1055. 'thumbnail' => 3,
  1056. 'substep' => $_GET['substep'],
  1057. )
  1058. );
  1059. while ($row = $smcFunc['db_fetch_assoc']($result))
  1060. {
  1061. // Only do anything once... just in case
  1062. if (!isset($to_remove[$row['id_attach']]))
  1063. {
  1064. $to_remove[$row['id_attach']] = $row['id_attach'];
  1065. $context['repair_errors']['missing_thumbnail_parent']++;
  1066. // If we are repairing remove the file from disk now.
  1067. if ($fix_errors && in_array('missing_thumbnail_parent', $to_fix))
  1068. {
  1069. $filename = getAttachmentFilename($row['filename'], $row['id_attach'], $row['id_folder'], false, $row['file_hash']);
  1070. @unlink($filename);
  1071. }
  1072. }
  1073. }
  1074. if ($smcFunc['db_num_rows']($result) != 0)
  1075. $to_fix[] = 'missing_thumbnail_parent';
  1076. $smcFunc['db_free_result']($result);
  1077. // Do we need to delete what we have?
  1078. if ($fix_errors && !empty($to_remove) && in_array('missing_thumbnail_parent', $to_fix))
  1079. $smcFunc['db_query']('', '
  1080. DELETE FROM {db_prefix}attachments
  1081. WHERE id_attach IN ({array_int:to_remove})
  1082. AND attachment_type = {int:attachment_type}',
  1083. array(
  1084. 'to_remove' => $to_remove,
  1085. 'attachment_type' => 3,
  1086. )
  1087. );
  1088. pauseAttachmentMaintenance($to_fix, $thumbnails);
  1089. }
  1090. $_GET['step'] = 1;
  1091. $_GET['substep'] = 0;
  1092. pauseAttachmentMaintenance($to_fix);
  1093. }
  1094. // Find parents which think they have thumbnails, but actually, don't.
  1095. if ($_GET['step'] <= 1)
  1096. {
  1097. $result = $smcFunc['db_query']('', '
  1098. SELECT MAX(id_attach)
  1099. FROM {db_prefix}attachments
  1100. WHERE id_thumb != {int:no_thumb}',
  1101. array(
  1102. 'no_thumb' => 0,
  1103. )
  1104. );
  1105. list ($thumbnails) = $smcFunc['db_fetch_row']($result);
  1106. $smcFunc['db_free_result']($result);
  1107. for (; $_GET['substep'] < $thumbnails; $_GET['substep'] += 500)
  1108. {
  1109. $to_update = array();
  1110. $result = $smcFunc['db_query']('', '
  1111. SELECT a.id_attach
  1112. FROM {db_prefix}attachments AS a
  1113. LEFT JOIN {db_prefix}attachments AS thumb ON (thumb.id_attach = a.id_thumb)
  1114. WHERE a.id_attach BETWEEN {int:substep} AND {int:substep} + 499
  1115. AND a.id_thumb != {int:no_thumb}
  1116. AND thumb.id_attach IS NULL',
  1117. array(
  1118. 'no_thumb' => 0,
  1119. 'substep' => $_GET['substep'],
  1120. )
  1121. );
  1122. while ($row = $smcFunc['db_fetch_assoc']($result))
  1123. {
  1124. $to_update[] = $row['id_attach'];
  1125. $context['repair_errors']['parent_missing_thumbnail']++;
  1126. }
  1127. if ($smcFunc['db_num_rows']($result) != 0)
  1128. $to_fix[] = 'parent_missing_thumbnail';
  1129. $smcFunc['db_free_result']($result);
  1130. // Do we need to delete what we have?
  1131. if ($fix_errors && !empty($to_update) && in_array('parent_missing_thumbnail', $to_fix))
  1132. $smcFunc['db_query']('', '
  1133. UPDATE {db_prefix}attachments
  1134. SET id_thumb = {int:no_thumb}
  1135. WHERE id_attach IN ({array_int:to_update})',
  1136. array(
  1137. 'to_update' => $to_update,
  1138. 'no_thumb' => 0,
  1139. )
  1140. );
  1141. pauseAttachmentMaintenance($to_fix, $thumbnails);
  1142. }
  1143. $_GET['step'] = 2;
  1144. $_GET['substep'] = 0;
  1145. pauseAttachmentMaintenance($to_fix);
  1146. }
  1147. // This may take forever I'm afraid, but life sucks... recount EVERY attachments!
  1148. if ($_GET['step'] <= 2)
  1149. {
  1150. $result = $smcFunc['db_query']('', '
  1151. SELECT MAX(id_attach)
  1152. FROM {db_prefix}attachments',
  1153. array(
  1154. )
  1155. );
  1156. list ($thumbnails) = $smcFunc['db_fetch_row']($result);
  1157. $smcFunc['db_free_result']($result);
  1158. for (; $_GET['substep'] < $thumbnails; $_GET['substep'] += 250)
  1159. {
  1160. $to_remove = array();
  1161. $errors_found = array();
  1162. $result = $smcFunc['db_query']('', '
  1163. SELECT id_attach, id_folder, filename, file_hash, size, attachment_type
  1164. FROM {db_prefix}attachments
  1165. WHERE id_attach BETWEEN {int:substep} AND {int:substep} + 249',
  1166. array(
  1167. 'substep' => $_GET['substep'],
  1168. )
  1169. );
  1170. while ($row = $smcFunc['db_fetch_assoc']($result))
  1171. {
  1172. // Get the filename.
  1173. if ($row['attachment_type'] == 1)
  1174. $filename = $modSettings['custom_avatar_dir'] . '/' . $row['filename'];
  1175. else
  1176. $filename = getAttachmentFilename($row['filename'], $row['id_attach'], $row['id_folder'], false, $row['file_hash']);
  1177. // File doesn't exist?
  1178. if (!file_exists($filename))
  1179. {
  1180. // If we're lucky it might just be in a different folder.
  1181. if (!empty($modSettings['currentAttachmentUploadDir']))
  1182. {
  1183. // Get the attachment name with out the folder.
  1184. $attachment_name = !empty($row['file_hash']) ? $row['id_attach'] . '_' . $row['file_hash'] : getLegacyAttachmentFilename($row['filename'], $row['id_attach'], null, true);
  1185. if (!is_array($modSettings['attachmentUploadDir']))
  1186. $modSettings['attachmentUploadDir'] = unserialize($modSettings['attachmentUploadDir']);
  1187. // Loop through the other folders.
  1188. foreach ($modSettings['attachmentUploadDir'] as $id => $dir)
  1189. if (file_exists($dir . '/' . $attachment_name))
  1190. {
  1191. $context['repair_errors']['wrong_folder']++;
  1192. $errors_found[] = 'wrong_folder';
  1193. // Are we going to fix this now?
  1194. if ($fix_errors && in_array('wrong_folder', $to_fix))
  1195. $smcFunc['db_query']('', '
  1196. UPDATE {db_prefix}attachments
  1197. SET id_folder = {int:new_folder}
  1198. WHERE id_attach = {int:id_attach}',
  1199. array(
  1200. 'new_folder' => $id,
  1201. 'id_attach' => $row['id_attach'],
  1202. )
  1203. );
  1204. continue 2;
  1205. }
  1206. }
  1207. $to_remove[] = $row['id_attach'];
  1208. $context['repair_errors']['file_missing_on_disk']++;
  1209. $errors_found[] = 'file_missing_on_disk';
  1210. }
  1211. elseif (filesize($filename) == 0)
  1212. {
  1213. $context['repair_errors']['file_size_of_zero']++;
  1214. $errors_found[] = 'file_size_of_zero';
  1215. // Fixing?
  1216. if ($fix_errors && in_array('file_size_of_zero', $to_fix))
  1217. {
  1218. $to_remove[] = $row['id_attach'];
  1219. @unlink($filename);
  1220. }
  1221. }
  1222. elseif (filesize($filename) != $row['size'])
  1223. {
  1224. $context['repair_errors']['file_wrong_size']++;
  1225. $errors_found[] = 'file_wrong_size';
  1226. // Fix it here?
  1227. if ($fix_errors && in_array('file_wrong_size', $to_fix))
  1228. {
  1229. $smcFunc['db_query']('', '
  1230. UPDATE {db_prefix}attachments
  1231. SET size = {int:filesize}
  1232. WHERE id_attach = {int:id_attach}',
  1233. array(
  1234. 'filesize' => filesize($filename),
  1235. 'id_attach' => $row['id_attach'],
  1236. )
  1237. );
  1238. }
  1239. }
  1240. }
  1241. if (in_array('file_missing_on_disk', $errors_found))
  1242. $to_fix[] = 'file_missing_on_disk';
  1243. if (in_array('file_size_of_zero', $errors_found))
  1244. $to_fix[] = 'file_size_of_zero';
  1245. if (in_array('file_wrong_size', $errors_found))
  1246. $to_fix[] = 'file_wrong_size';
  1247. if (in_array('wrong_folder', $errors_found))
  1248. $to_fix[] = 'wrong_folder';
  1249. $smcFunc['db_free_result']($result);
  1250. // Do we need to delete what we have?
  1251. if ($fix_errors && !empty($to_remove))
  1252. {
  1253. $smcFunc['db_query']('', '
  1254. DELETE FROM {db_prefix}attachments
  1255. WHERE id_attach IN ({array_int:to_remove})',
  1256. array(
  1257. 'to_remove' => $to_remove,
  1258. )
  1259. );
  1260. $smcFunc['db_query']('', '
  1261. UPDATE {db_prefix}attachments
  1262. SET id_thumb = {int:no_thumb}
  1263. WHERE id_thumb IN ({array_int:to_remove})',
  1264. array(
  1265. 'to_remove' => $to_remove,
  1266. 'no_thumb' => 0,
  1267. )
  1268. );
  1269. }
  1270. pauseAttachmentMaintenance($to_fix, $thumbnails);
  1271. }
  1272. $_GET['step'] = 3;
  1273. $_GET['substep'] = 0;
  1274. pauseAttachmentMaintenance($to_fix);
  1275. }
  1276. // Get avatars with no members associated with them.
  1277. if ($_GET['step'] <= 3)
  1278. {
  1279. $result = $smcFunc['db_query']('', '
  1280. SELECT MAX(id_attach)
  1281. FROM {db_prefix}attachments',
  1282. array(
  1283. )
  1284. );
  1285. list ($thumbnails) = $smcFunc['db_fetch_row']($result);
  1286. $smcFunc['db_free_result']($result);
  1287. for (; $_GET['substep'] < $thumbnails; $_GET['substep'] += 500)
  1288. {
  1289. $to_remove = array();
  1290. $result = $smcFunc['db_query']('', '
  1291. SELECT a.id_attach, a.id_folder, a.filename, a.file_hash, a.attachment_type
  1292. FROM {db_prefix}attachments AS a
  1293. LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = a.id_member)
  1294. WHERE a.id_attach BETWEEN {int:substep} AND {int:substep} + 499
  1295. AND a.id_member != {int:no_member}
  1296. AND a.id_msg = {int:no_msg}
  1297. AND mem.id_member IS NULL',
  1298. array(
  1299. 'no_member' => 0,
  1300. 'no_msg' => 0,
  1301. 'substep' => $_GET['substep'],
  1302. )
  1303. );
  1304. while ($row = $smcFunc['db_fetch_assoc']($result))
  1305. {
  1306. $to_remove[] = $row['id_attach'];
  1307. $context['repair_errors']['avatar_no_member']++;
  1308. // If we are repairing remove the file from disk now.
  1309. if ($fix_errors && in_array('avatar_no_member', $to_fix))
  1310. {
  1311. if ($row['attachment_type'] == 1)
  1312. $filename = $modSettings['custom_avatar_dir'] . '/' . $row['filename'];
  1313. else
  1314. $filename = getAttachmentFilename($row['filename'], $row['id_attach'], $row['id_folder'], false, $row['file_hash']);
  1315. @unlink($filename);
  1316. }
  1317. }
  1318. if ($smcFunc['db_num_rows']($result) != 0)
  1319. $to_fix[] = 'avatar_no_member';
  1320. $smcFunc['db_free_result']($result);
  1321. // Do we need to delete what we have?
  1322. if ($fix_errors && !empty($to_remove) && in_array('avatar_no_member', $to_fix))
  1323. $smcFunc['db_query']('', '
  1324. DELETE FROM {db_prefix}attachments
  1325. WHERE id_attach IN ({array_int:to_remove})
  1326. AND id_member != {int:no_member}
  1327. AND id_msg = {int:no_msg}',
  1328. array(
  1329. 'to_remove' => $to_remove,
  1330. 'no_member' => 0,
  1331. 'no_msg' => 0,
  1332. )
  1333. );
  1334. pauseAttachmentMaintenance($to_fix, $thumbnails);
  1335. }
  1336. $_GET['step'] = 4;
  1337. $_GET['substep'] = 0;
  1338. pauseAttachmentMaintenance($to_fix);
  1339. }
  1340. // What about attachments, who are missing a message :'(
  1341. if ($_GET['step'] <= 4)
  1342. {
  1343. $result = $smcFunc['db_query']('', '
  1344. SELECT MAX(id_attach)
  1345. FROM {db_prefix}attachments',
  1346. array(
  1347. )
  1348. );
  1349. list ($thumbnails) = $smcFunc['db_fetch_row']($result);
  1350. $smcFunc['db_free_result']($result);
  1351. for (; $_GET['substep'] < $thumbnails; $_GET['substep'] += 500)
  1352. {
  1353. $to_remove = array();
  1354. $result = $smcFunc['db_query']('', '
  1355. SELECT a.id_attach, a.id_folder, a.filename, a.file_hash
  1356. FROM {db_prefix}attachments AS a
  1357. LEFT JOIN {db_prefix}messages AS m ON (m.id_msg = a.id_msg)
  1358. WHERE a.id_attach BETWEEN {int:substep} AND {int:substep} + 499
  1359. AND a.id_member = {int:no_member}
  1360. AND a.id_msg != {int:no_msg}
  1361. AND m.id_msg IS NULL',
  1362. array(
  1363. 'no_member' => 0,
  1364. 'no_msg' => 0,
  1365. 'substep' => $_GET['substep'],
  1366. )
  1367. );
  1368. while ($row = $smcFunc['db_fetch_assoc']($result))
  1369. {
  1370. $to_remove[] = $row['id_attach'];
  1371. $context['repair_errors']['attachment_no_msg']++;
  1372. // If we are repairing remove the file from disk now.
  1373. if ($fix_errors && in_array('attachment_no_msg', $to_fix))
  1374. {
  1375. $filename = getAttachmentFilename($row['filename'], $row['id_attach'], $row['id_folder'], false, $row['file_hash']);
  1376. @unlink($filename);
  1377. }
  1378. }
  1379. if ($smcFunc['db_num_rows']($result) != 0)
  1380. $to_fix[] = 'attachment_no_msg';
  1381. $smcFunc['db_free_result']($result);
  1382. // Do we need to delete what we have?
  1383. if ($fix_errors && !empty($to_remove) && in_array('attachment_no_msg', $to_fix))
  1384. $smcFunc['db_query']('', '
  1385. DELETE FROM {db_prefix}attachments
  1386. WHERE id_attach IN ({array_int:to_remove})
  1387. AND id_member = {int:no_member}
  1388. AND id_msg != {int:no_msg}',
  1389. array(
  1390. 'to_remove' => $to_remove,
  1391. 'no_member' => 0,
  1392. 'no_msg' => 0,
  1393. )
  1394. );
  1395. pauseAttachmentMaintenance($to_fix, $thumbnails);
  1396. }
  1397. $_GET['step'] = 5;
  1398. $_GET['substep'] = 0;
  1399. pauseAttachmentMaintenance($to_fix);
  1400. }
  1401. // What about files who are not recorded in the database?
  1402. if ($_GET['step'] <= 5)
  1403. {
  1404. // Just use the current path for temp files.
  1405. if (!is_array($modSettings['attachmentUploadDir']))
  1406. $modSettings['attachmentUploadDir'] = unserialize($modSettings['attachmentUploadDir']);
  1407. $attach_dirs = $modSettings['attachmentUploadDir'];
  1408. $current_check = 0;
  1409. $max_checks = 500;
  1410. $files_checked = empty($_GET['substep']) ? 0 : $_GET['substep'];
  1411. foreach ($attach_dirs as $attach_dir)
  1412. {
  1413. if ($dir = @opendir($attach_dir))
  1414. {
  1415. while ($file = readdir($dir))
  1416. {
  1417. if ($file == '.' || $file == '..')
  1418. continue;
  1419. if ($files_checked <= $current_check)
  1420. {
  1421. // Temporary file, get rid of it!
  1422. if (strpos($file, 'post_tmp_') !== false)
  1423. {
  1424. // Temp file is more than 5 hours old!
  1425. if (filemtime($attach_dir . '/' . $file) < time() - 18000)
  1426. @unlink($attach_dir . '/' . $file);
  1427. }
  1428. // That should be an attachment, let's check if we have it in the database
  1429. elseif (strpos($file, '_') !== false)
  1430. {
  1431. $attachID = (int) substr($file, 0, strpos($file, '_'));
  1432. if (!empty($attachID))
  1433. {
  1434. $request = $smcFunc['db_query']('', '
  1435. SELECT id_attach
  1436. FROM {db_prefix}attachments
  1437. WHERE id_attach = {int:attachment_id}
  1438. LIMIT 1',
  1439. array(
  1440. 'attachment_id' => $attachID,
  1441. )
  1442. );
  1443. if ($smcFunc['db_num_rows']($request) == 0)
  1444. {
  1445. if ($fix_errors && in_array('files_without_attachment', $to_fix))
  1446. {
  1447. @unlink($attach_dir . '/' . $file);
  1448. }
  1449. else
  1450. {
  1451. $context['repair_errors']['files_without_attachment']++;
  1452. $to_fix[] = 'files_without_attachment';
  1453. }
  1454. }
  1455. $smcFunc['db_free_result']($request);
  1456. }
  1457. }
  1458. elseif ($file != 'index.php')
  1459. {
  1460. if ($fix_errors && in_array('files_without_attachment', $to_fix))
  1461. {
  1462. @unlink($attach_dir . '/' . $file);
  1463. }
  1464. else
  1465. {
  1466. $context['repair_errors']['files_without_attachment']++;
  1467. $to_fix[] = 'files_without_attachment';
  1468. }
  1469. }
  1470. }
  1471. $current_check++;
  1472. $_GET['substep'] = $current_check;
  1473. if ($current_check - $files_checked >= $max_checks)
  1474. pauseAttachmentMaintenance($to_fix);
  1475. }
  1476. closedir($dir);
  1477. }
  1478. }
  1479. $_GET['step'] = 5;
  1480. $_GET['substep'] = 0;
  1481. pauseAttachmentMaintenance($to_fix);
  1482. }
  1483. // Got here we must be doing well - just the template! :D
  1484. $context['page_title'] = $txt['repair_attachments'];
  1485. $context[$context['admin_menu_name']]['current_subsection'] = 'maintenance';
  1486. $context['sub_template'] = 'attachment_repair';
  1487. // What stage are we at?
  1488. $context['completed'] = $fix_errors ? true : false;
  1489. $context['errors_found'] = !empty($to_fix) ? true : false;
  1490. }
  1491. /**
  1492. * Function called in-between each round of attachments and avatar repairs.
  1493. * Called by repairAttachments().
  1494. * If repairAttachments() has more steps added, this function needs updated!
  1495. *
  1496. * @param array $to_fix attachments to fix
  1497. * @param int $max_substep = 0
  1498. */
  1499. function pauseAttachmentMaintenance($to_fix, $max_substep = 0)
  1500. {
  1501. global $context, $txt, $time_start;
  1502. // Try get more time...
  1503. @set_time_limit(600);
  1504. if (function_exists('apache_reset_timeout'))
  1505. @apache_reset_timeout();
  1506. // Have we already used our maximum time?
  1507. if (time() - array_sum(explode(' ', $time_start)) < 3 || $context['starting_substep'] == $_GET['substep'])
  1508. return;
  1509. $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'];
  1510. $context['page_title'] = $txt['not_done_title'];
  1511. $context['continue_post_data'] = '';
  1512. $context['continue_countdown'] = '2';
  1513. $context['sub_template'] = 'not_done';
  1514. // Specific stuff to not break this template!
  1515. $context[$context['admin_menu_name']]['current_subsection'] = 'maintenance';
  1516. // Change these two if more steps are added!
  1517. if (empty($max_substep))
  1518. $context['continue_percent'] = round(($_GET['step'] * 100) / 25);
  1519. else
  1520. $context['continue_percent'] = round(($_GET['step'] * 100 + ($_GET['substep'] * 100) / $max_substep) / 25);
  1521. // Never more than 100%!
  1522. $context['continue_percent'] = min($context['continue_percent'], 100);
  1523. $_SESSION['attachments_to_fix'] = $to_fix;
  1524. $_SESSION['attachments_to_fix2'] = $context['repair_errors'];
  1525. obExit();
  1526. }
  1527. /**
  1528. * Called from a mouse click, works out what we want to do with attachments and actions it.
  1529. */
  1530. function ApproveAttach()
  1531. {
  1532. global $smcFunc;
  1533. // Security is our primary concern...
  1534. checkSession('get');
  1535. // If it approve or delete?
  1536. $is_approve = !isset($_GET['sa']) || $_GET['sa'] != 'reject' ? true : false;
  1537. $attachments = array();
  1538. // If we are approving all ID's in a message , get the ID's.
  1539. if ($_GET['sa'] == 'all' && !empty($_GET['mid']))
  1540. {
  1541. $id_msg = (int) $_GET['mid'];
  1542. $request = $smcFunc['db_query']('', '
  1543. SELECT id_attach
  1544. FROM {db_prefix}attachments
  1545. WHERE id_msg = {int:id_msg}
  1546. AND approved = {int:is_approved}
  1547. AND attachment_type = {int:attachment_type}',
  1548. array(
  1549. 'id_msg' => $id_msg,
  1550. 'is_approved' => 0,
  1551. 'attachment_type' => 0,
  1552. )
  1553. );
  1554. while ($row = $smcFunc['db_fetch_assoc']($request))
  1555. $attachments[] = $row['id_attach'];
  1556. $smcFunc['db_free_result']($request);
  1557. }
  1558. elseif (!empty($_GET['aid']))
  1559. $attachments[] = (int) $_GET['aid'];
  1560. if (empty($attachments))
  1561. fatal_lang_error('no_access', false);
  1562. // Now we have some ID's cleaned and ready to approve, but first - let's check we have permission!
  1563. $allowed_boards = boardsAllowedTo('approve_posts');
  1564. // Validate the attachments exist and are the right approval state.
  1565. $request = $smcFunc['db_query']('', '
  1566. SELECT a.id_attach, m.id_board, m.id_msg, m.id_topic
  1567. FROM {db_prefix}attachments AS a
  1568. INNER JOIN {db_prefix}messages AS m ON (m.id_msg = a.id_msg)
  1569. WHERE a.id_attach IN ({array_int:attachments})
  1570. AND a.attachment_type = {int:attachment_type}
  1571. AND a.approved = {int:is_approved}',
  1572. array(
  1573. 'attachments' => $attachments,
  1574. 'attachment_type' => 0,
  1575. 'is_approved' => 0,
  1576. )
  1577. );
  1578. $attachments = array();
  1579. while ($row = $smcFunc['db_fetch_assoc']($request))
  1580. {
  1581. // We can only add it if we can approve in this board!
  1582. if ($allowed_boards = array(0) || in_array($row['id_board'], $allowed_boards))
  1583. {
  1584. $attachments[] = $row['id_attach'];
  1585. // Also come up witht he redirection URL.
  1586. $redirect = 'topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#msg' . $row['id_msg'];
  1587. }
  1588. }
  1589. $smcFunc['db_free_result']($request);
  1590. if (empty($attachments))
  1591. fatal_lang_error('no_access', false);
  1592. // Finally, we are there. Follow through!
  1593. if ($is_approve)
  1594. {
  1595. // Checked and deemed worthy.
  1596. ApproveAttachments($attachments);
  1597. }
  1598. else
  1599. removeAttachments(array('id_attach' => $attachments, 'do_logging' => true));
  1600. // Return to the topic....
  1601. redirectexit($redirect);
  1602. }
  1603. /**
  1604. * Approve an attachment, or maybe even more - no permission check!
  1605. *
  1606. * @param array $attachments
  1607. */
  1608. function ApproveAttachments($attachments)
  1609. {
  1610. global $smcFunc;
  1611. if (empty($attachments))
  1612. return 0;
  1613. // For safety, check for thumbnails...
  1614. $request = $smcFunc['db_query']('', '
  1615. SELECT
  1616. a.id_attach, a.id_member, IFNULL(thumb.id_attach, 0) AS id_thumb
  1617. FROM {db_prefix}attachments AS a
  1618. LEFT JOIN {db_prefix}attachments AS thumb ON (thumb.id_attach = a.id_thumb)
  1619. WHERE a.id_attach IN ({array_int:attachments})
  1620. AND a.attachment_type = {int:attachment_type}',
  1621. array(
  1622. 'attachments' => $attachments,
  1623. 'attachment_type' => 0,
  1624. )
  1625. );
  1626. $attachments = array();
  1627. while ($row = $smcFunc['db_fetch_assoc']($request))
  1628. {
  1629. // Update the thumbnail too...
  1630. if (!empty($row['id_thumb']))
  1631. $attachments[] = $row['id_thumb'];
  1632. $attachments[] = $row['id_attach'];
  1633. }
  1634. $smcFunc['db_free_result']($request);
  1635. if (empty($attachments))
  1636. return 0;
  1637. // Approving an attachment is not hard - it's easy.
  1638. $smcFunc['db_query']('', '
  1639. UPDATE {db_prefix}attachments
  1640. SET approved = {int:is_approved}
  1641. WHERE id_attach IN ({array_int:attachments})',
  1642. array(
  1643. 'attachments' => $attachments,
  1644. 'is_approved' => 1,
  1645. )
  1646. );
  1647. // In order to log the attachments, we really need their message and filename
  1648. $request = $smcFunc['db_query']('', '
  1649. SELECT m.id_msg, a.filename
  1650. FROM {db_prefix}attachments AS a
  1651. INNER JOIN {db_prefix}messages AS m ON (a.id_msg = m.id_msg)
  1652. WHERE a.id_attach IN ({array_int:attachments})
  1653. AND a.attachment_type = {int:attachment_type}',
  1654. array(
  1655. 'attachments' => $attachments,
  1656. 'attachment_type' => 0,
  1657. )
  1658. );
  1659. while ($row = $smcFunc['db_fetch_assoc']($request))
  1660. logAction(
  1661. 'approve_attach',
  1662. array(
  1663. 'message' => $row['id_msg'],
  1664. 'filename' => preg_replace('~&amp;#(\\d{1,7}|x[0-9a-fA-F]{1,6});~', '&#\\1;', $smcFunc['htmlspecialchars']($row['filename'])),
  1665. )
  1666. );
  1667. $smcFunc['db_free_result']($request);
  1668. // Remove from the approval queue.
  1669. $smcFunc['db_query']('', '
  1670. DELETE FROM {db_prefix}approval_queue
  1671. WHERE id_attach IN ({array_int:attachments})',
  1672. array(
  1673. 'attachments' => $attachments,
  1674. )
  1675. );
  1676. call_integration_hook('integrate_approve_attachments', array($attachments));
  1677. }
  1678. /**
  1679. * This function lists and allows updating of multiple attachments paths.
  1680. */
  1681. function ManageAttachmentPaths()
  1682. {
  1683. global $modSettings, $scripturl, $context, $txt, $sourcedir, $boarddir, $smcFunc;
  1684. // Since this needs to be done eventually.
  1685. if (!is_array($modSettings['attachmentUploadDir']))
  1686. $modSettings['attachmentUploadDir'] = unserialize($modSettings['attachmentUploadDir']);
  1687. if (!isset($modSettings['attachment_basedirectories']))
  1688. $modSettings['attachment_basedirectories'] = array();
  1689. elseif (!is_array($modSettings['attachment_basedirectories']))
  1690. $modSettings['attachment_basedirectories'] = unserialize($modSettings['attachment_basedirectories']);
  1691. $errors = array();
  1692. // Saving?
  1693. if (isset($_REQUEST['save']))
  1694. {
  1695. checkSession();
  1696. $_POST['current_dir'] = (int) $_POST['current_dir'];
  1697. $new_dirs = array();
  1698. foreach ($_POST['dirs'] as $id => $path)
  1699. {
  1700. $error = '';
  1701. $id = (int) $id;
  1702. if ($id < 1)
  1703. continue;
  1704. // Hmm, a new path maybe?
  1705. if (!array_key_exists($id, $modSettings['attachmentUploadDir']))
  1706. {
  1707. // or is it?
  1708. if (in_array($path, $modSettings['attachmentUploadDir']) || in_array($boarddir . DIRECTORY_SEPARATOR . $path, $modSettings['attachmentUploadDir']))
  1709. {
  1710. $errors[] = $path . ': ' . $txt['attach_dir_duplicate_msg'];
  1711. continue;
  1712. }
  1713. // OK, so let's try to create it then.
  1714. require_once($sourcedir . '/Subs-Attachments.php');
  1715. if (automanage_attachments_create_directory($path))
  1716. $_POST['current_dir'] = $modSettings['currentAttachmentUploadDir'];
  1717. else
  1718. $errors[] = $path . ': ' . $txt[$context['dir_creation_error']];
  1719. }
  1720. // Changing a directory name?
  1721. if (!empty($modSettings['attachmentUploadDir'][$id]) && !empty($path) && $path != $modSettings['attachmentUploadDir'][$id])
  1722. {
  1723. if ($path != $modSettings['attachmentUploadDir'][$id] && !is_dir($path))
  1724. {
  1725. if (!@rename($modSettings['attachmentUploadDir'][$id], $path))
  1726. {
  1727. $errors[] = $path . ': ' . $txt['attach_dir_no_rename'];
  1728. $path = $modSettings['attachmentUploadDir'][$id];
  1729. }
  1730. }
  1731. else
  1732. {
  1733. $errors[] = $path . ': ' . $txt['attach_dir_exists_msg'];
  1734. $path = $modSettings['attachmentUploadDir'][$id];
  1735. }
  1736. // Update the base directory path
  1737. if (!empty($modSettings['attachment_basedirectories']) && array_key_exists($id, $modSettings['attachment_basedirectories']))
  1738. {
  1739. $base = $modSettings['basedirectory_for_attachments'] == $modSettings['attachmentUploadDir'][$id] ? $path : $modSettings['basedirectory_for_attachments'];
  1740. $modSettings['attachment_basedirectories'][$id] = $path;
  1741. updateSettings(array(
  1742. 'attachment_basedirectories' => serialize($modSettings['attachment_basedirectories']),
  1743. 'basedirectory_for_attachments' => $base,
  1744. ));
  1745. $modSettings['attachment_basedirectories'] = unserialize($modSettings['attachment_basedirectories']);
  1746. }
  1747. }
  1748. if (empty($path))
  1749. {
  1750. $path = $modSettings['attachmentUploadDir'][$id];
  1751. // It's not a good idea to delete the current directory.
  1752. if ($id == (!empty($_POST['current_dir']) ? $_POST['current_dir'] : $modSettings['currentAttachmentUploadDir']))
  1753. $errors[] = $path . ': ' . $txt['attach_dir_is_current'];
  1754. // Or the current base directory
  1755. elseif (!empty($modSettings['basedirectory_for_attachments']) && $modSettings['basedirectory_for_attachments'] == $modSettings['attachmentUploadDir'][$id])
  1756. $errors[] = $path . ': ' . $txt['attach_dir_is_current_bd'];
  1757. else
  1758. {
  1759. // Let's not try to delete a path with files in it.
  1760. $request = $smcFunc['db_query']('', '
  1761. SELECT COUNT(id_attach) AS num_attach
  1762. FROM {db_prefix}attachments
  1763. WHERE id_folder = {int:id_folder}',
  1764. array(
  1765. 'id_folder' => (int) $id,
  1766. )
  1767. );
  1768. list ($num_attach) = $smcFunc['db_fetch_row']($request);
  1769. $smcFunc['db_free_result']($request);
  1770. // A check to see if it's a used base dir.
  1771. if (!empty($modSettings['attachment_basedirectories']))
  1772. {
  1773. // Count any sub-folders.
  1774. foreach ($modSettings['attachmentUploadDir'] as $sub)
  1775. if (strpos($sub, $path . DIRECTORY_SEPARATOR) !== false)
  1776. $num_attach++;
  1777. }
  1778. // It's safe to delete. So try to delete the folder also
  1779. if ($num_attach == 0)
  1780. {
  1781. if (is_dir($path))
  1782. $doit = true;
  1783. elseif (is_dir($boarddir . DIRECTORY_SEPARATOR . $path))
  1784. {
  1785. $doit = true;
  1786. $path = $boarddir . DIRECTORY_SEPARATOR . $path;
  1787. }
  1788. if (isset($doit))
  1789. {
  1790. unlink($path . '/.htaccess');
  1791. unlink($path . '/index.php');
  1792. if (!@rmdir($path))
  1793. $error = $path . ': ' . $txt['attach_dir_no_delete'];
  1794. }
  1795. // Remove it from the base directory list.
  1796. if (empty($error) && !empty($modSettings['attachment_basedirectories']))
  1797. {
  1798. unset($modSettings['attachment_basedirectories'][$id]);
  1799. updateSettings(array('attachment_basedirectories' => serialize($modSettings['attachment_basedirectories'])));
  1800. $modSettings['attachment_basedirectories'] = unserialize($modSettings['attachment_basedirectories']);
  1801. }
  1802. }
  1803. else
  1804. $error = $path . ': ' . $txt['attach_dir_no_remove'];
  1805. if (empty($error))
  1806. continue;
  1807. else
  1808. $errors[] = $error;
  1809. }
  1810. }
  1811. $new_dirs[$id] = $path;
  1812. }
  1813. // We need to make sure the current directory is right.
  1814. if (empty($_POST['current_dir']) && !empty($modSettings['currentAttachmentUploadDir']))
  1815. $_POST['current_dir'] = $modSettings['currentAttachmentUploadDir'];
  1816. // Find the current directory if there's no value carried,
  1817. if (empty($_POST['current_dir']) || empty($new_dirs[$_POST['current_dir']]))
  1818. {
  1819. if (array_key_exists($modSettings['currentAttachmentUploadDir'], $modSettings['attachmentUploadDir']))
  1820. $_POST['current_dir'] = $modSettings['currentAttachmentUploadDir'];
  1821. else
  1822. $_POST['current_dir'] = max(array_keys($modSettings['attachmentUploadDir']));
  1823. }
  1824. // If the user wishes to go back, update the last_dir array
  1825. if ($_POST['current_dir'] != $modSettings['currentAttachmentUploadDir']&& !empty($modSettings['last_attachments_directory']) && (isset($modSettings['last_attachments_directory'][$_POST['current_dir']]) || isset($modSettings['last_attachments_directory'][0])))
  1826. {
  1827. if (!is_array($modSettings['last_attachments_directory']))
  1828. $modSettings['last_attachments_directory'] = unserialize($modSettings['last_attachments_directory']);
  1829. $num = substr(strrchr($modSettings['attachmentUploadDir'][$_POST['current_dir']], '_'), 1);
  1830. if (is_numeric($num))
  1831. {
  1832. // Need to find the base folder.
  1833. $bid = -1;
  1834. $use_subdirectories_for_attachments = 0;
  1835. if (!empty($modSettings['attachment_basedirectories']))
  1836. foreach ($modSettings['attachment_basedirectories'] as $bid => $base)
  1837. if (strpos($modSettings['attachmentUploadDir'][$_POST['current_dir']], $base . DIRECTORY_SEPARATOR) !==false)
  1838. {
  1839. $use_subdirectories_for_attachments = 1;
  1840. break;
  1841. }
  1842. if ($use_subdirectories_for_attachments == 0 && strpos($modSettings['attachmentUploadDir'][$_POST['current_dir']], $boarddir . DIRECTORY_SEPARATOR) !== false)
  1843. $bid = 0;
  1844. $modSettings['last_attachments_directory'][$bid] = (int) $num;
  1845. $modSettings['basedirectory_for_attachments'] = !empty($modSettings['basedirectory_for_attachments']) ? $modSettings['basedirectory_for_attachments'] : '';
  1846. $modSettings['use_subdirectories_for_attachments'] = !empty($modSettings['use_subdirectories_for_attachments']) ? $modSettings['use_subdirectories_for_attachments'] : 0;
  1847. updateSettings(array(
  1848. 'last_attachments_directory' => serialize($modSettings['last_attachments_directory']),
  1849. 'basedirectory_for_attachments' => $bid == 0 ? $modSettings['basedirectory_for_attachments'] : $modSettings['attachment_basedirectories'][$bid],
  1850. 'use_subdirectories_for_attachments' => $use_subdirectories_for_attachments,
  1851. ));
  1852. }
  1853. }
  1854. // Going back to just one path?
  1855. if (count($new_dirs) == 1)
  1856. {
  1857. // We might need to reset the paths. This loop will just loop through once.
  1858. foreach ($new_dirs as $id => $dir)
  1859. {
  1860. if ($id != 1)
  1861. $smcFunc['db_query']('', '
  1862. UPDATE {db_prefix}attachments
  1863. SET id_folder = {int:default_folder}
  1864. WHERE id_folder = {int:current_folder}',
  1865. array(
  1866. 'default_folder' => 1,
  1867. 'current_folder' => $id,
  1868. )
  1869. );
  1870. $update = array(
  1871. 'currentAttachmentUploadDir' => 1,
  1872. 'attachmentUploadDir' => serialize(array(1 => $dir)),
  1873. );
  1874. }
  1875. }
  1876. else
  1877. {
  1878. // Save it to the database.
  1879. $update = array(
  1880. 'currentAttachmentUploadDir' => $_POST['current_dir'],
  1881. 'attachmentUploadDir' => serialize($new_dirs),
  1882. );
  1883. }
  1884. if (!empty($update))
  1885. updateSettings($update);
  1886. if (!empty($errors))
  1887. $_SESSION['errors']['dir'] = $errors;
  1888. redirectexit('action=admin;area=manageattachments;sa=attachpaths;' . $context['session_var'] . '=' . $context['session_id']);
  1889. }
  1890. // Saving a base directory?
  1891. if (isset($_REQUEST['save2']))
  1892. {
  1893. checkSession();
  1894. // Changing the current base directory?
  1895. $_POST['current_base_dir'] = (int) $_POST['current_base_dir'];
  1896. if (empty($_POST['new_base_dir']) && !empty($_POST['current_base_dir']))
  1897. {
  1898. if ($modSettings['basedirectory_for_attachments'] != $modSettings['attachmentUploadDir'][$_POST['current_base_dir']])
  1899. $update = (array(
  1900. 'basedirectory_for_attachments' => $modSettings['attachmentUploadDir'][$_POST['current_base_dir']],
  1901. ));
  1902. //$modSettings['attachmentUploadDir'] = serialize($modSettings['attachmentUploadDir']);
  1903. }
  1904. If (isset($_POST['base_dir']))
  1905. {
  1906. foreach ($_POST['base_dir'] as $id => $dir)
  1907. {
  1908. if (!empty($dir) && $dir != $modSettings['attachmentUploadDir'][$id])
  1909. {
  1910. if (@rename($modSettings['attachmentUploadDir'][$id], $dir))
  1911. {
  1912. $modSettings['attachmentUploadDir'][$id] = $dir;
  1913. $modSettings['attachment_basedirectories'][$id] = $dir;
  1914. $update = (array(
  1915. 'attachmentUploadDir' => serialize($modSettings['attachmentUploadDir']),
  1916. 'attachment_basedirectories' => serialize($modSettings['attachment_basedirectories']),
  1917. 'basedirectory_for_attachments' => $modSettings['attachmentUploadDir'][$_POST['current_base_dir']],
  1918. ));
  1919. }
  1920. }
  1921. if (empty($dir))
  1922. {
  1923. if ($id == $_POST['current_base_dir'])
  1924. {
  1925. $errors[] = $modSettings['attachmentUploadDir'][$id] . ': ' . $txt['attach_dir_is_current'];
  1926. continue;
  1927. }
  1928. unset($modSettings['attachment_basedirectories'][$id]);
  1929. $update = (array(
  1930. 'attachment_basedirectories' => serialize($modSettings['attachment_basedirectories']),
  1931. 'basedirectory_for_attachments' => $modSettings['attachmentUploadDir'][$_POST['current_base_dir']],
  1932. ));
  1933. }
  1934. }
  1935. }
  1936. // Or adding a new one?
  1937. if (!empty($_POST['new_base_dir']))
  1938. {
  1939. require_once($sourcedir . '/Subs-Attachments.php');
  1940. $_POST['new_base_dir'] = htmlspecialchars($_POST['new_base_dir'], ENT_QUOTES);
  1941. $current_dir = $modSettings['currentAttachmentUploadDir'];
  1942. if (!in_array($_POST['new_base_dir'], $modSettings['attachmentUploadDir']))
  1943. {
  1944. if (!automanage_attachments_create_directory($_POST['new_base_dir']))
  1945. $errors[] = $_POST['new_base_dir'] . ': ' . $txt['attach_dir_base_no_create'];
  1946. }
  1947. $modSettings['currentAttachmentUploadDir'] = array_search($_POST['new_base_dir'], $modSettings['attachmentUploadDir']);
  1948. if (!in_array($_POST['new_base_dir'], $modSettings['attachment_basedirectories']))
  1949. $modSettings['attachment_basedirectories'][$modSettings['currentAttachmentUploadDir']] = $_POST['new_base_dir'];
  1950. ksort($modSettings['attachment_basedirectories']);
  1951. $update = (array(
  1952. 'attachment_basedirectories' => serialize($modSettings['attachment_basedirectories']),
  1953. 'basedirectory_for_attachments' => $_POST['new_base_dir'],
  1954. 'currentAttachmentUploadDir' => $current_dir,
  1955. ));
  1956. }
  1957. if (!empty($errors))
  1958. $_SESSION['errors']['base'] = $errors;
  1959. if (!empty($update))
  1960. updateSettings($update);
  1961. redirectexit('action=admin;area=manageattachments;sa=attachpaths;' . $context['session_var'] . '=' . $context['session_id']);
  1962. }
  1963. if (isset($_SESSION['errors']))
  1964. {
  1965. if (is_array($_SESSION['errors']))
  1966. {
  1967. $errors = array();
  1968. if (!empty($_SESSION['errors']['dir']))
  1969. foreach ($_SESSION['errors']['dir'] as $error)
  1970. $errors['dir'][] = $smcFunc['htmlspecialchars']($error, ENT_QUOTES);
  1971. if (!empty($_SESSION['errors']['base']))
  1972. foreach ($_SESSION['errors']['base'] as $error)
  1973. $errors['base'][] = $smcFunc['htmlspecialchars']($error, ENT_QUOTES);
  1974. }
  1975. unset($_SESSION['errors']);
  1976. }
  1977. $listOptions = array(
  1978. 'id' => 'attach_paths',
  1979. 'base_href' => $scripturl . '?action=admin;area=manageattachments;sa=attachpaths;' . $context['session_var'] . '=' . $context['session_id'],
  1980. 'title' => $txt['attach_paths'],
  1981. 'get_items' => array(
  1982. 'function' => 'list_getAttachDirs',
  1983. ),
  1984. 'columns' => array(
  1985. 'current_dir' => array(
  1986. 'header' => array(
  1987. 'value' => $txt['attach_current'],
  1988. 'class' => 'centercol',
  1989. ),
  1990. 'data' => array(
  1991. 'function' => create_function('$rowData', '
  1992. return \'<input type="radio" name="current_dir" value="\' . $rowData[\'id\'] . \'" \' . ($rowData[\'current\'] ? \' checked="checked"\' : \'\') . (!empty($rowData[\'disable_current\']) ? \' disabled="disabled"\' : \'\') . \' class="input_radio" />\';
  1993. '),
  1994. 'style' => 'width: 10%;',
  1995. 'class' => 'centercol',
  1996. ),
  1997. ),
  1998. 'path' => array(
  1999. 'header' => array(
  2000. 'value' => $txt['attach_path'],
  2001. ),
  2002. 'data' => array(
  2003. 'function' => create_function('$rowData', '
  2004. return \'<input type="hidden" name="dirs[\' . $rowData[\'id\'] . \']" value="\' . $rowData[\'path\'] . \'" /><input type="text" size="40" name="dirs[\' . $rowData[\'id\'] . \']" value="\' . $rowData[\'path\'] . \'"\' . (!empty($rowData[\'disable_base_dir\']) ? \' disabled="disabled"\' : \'\') . \' class="input_text" style="width: 100%" />\';
  2005. '),
  2006. 'style' => 'width: 40%;',
  2007. ),
  2008. ),
  2009. 'current_size' => array(
  2010. 'header' => array(
  2011. 'value' => $txt['attach_current_size'],
  2012. ),
  2013. 'data' => array(
  2014. 'db' => 'current_size',
  2015. 'style' => 'width: 15%;',
  2016. ),
  2017. ),
  2018. 'num_files' => array(
  2019. 'header' => array(
  2020. 'value' => $txt['attach_num_files'],
  2021. ),
  2022. 'data' => array(
  2023. 'db' => 'num_files',
  2024. 'style' => 'width: 15%;',
  2025. ),
  2026. ),
  2027. 'status' => array(
  2028. 'header' => array(
  2029. 'value' => $txt['attach_dir_status'],
  2030. 'class' => 'centercol',
  2031. ),
  2032. 'data' => array(
  2033. 'db' => 'status',
  2034. 'style' => 'width: 25%;',
  2035. 'class' => 'centercol',
  2036. ),
  2037. ),
  2038. ),
  2039. 'form' => array(
  2040. 'href' => $scripturl . '?action=admin;area=manageattachments;sa=attachpaths;' . $context['session_var'] . '=' . $context['session_id'],
  2041. ),
  2042. 'additional_rows' => array(
  2043. array(
  2044. 'position' => 'below_table_data',
  2045. 'value' => '
  2046. <input type="hidden" name="' . $context['session_var'] . '" value="' . $context['session_id'] . '" />
  2047. <input type="submit" name="save" value="' . $txt['save'] . '" class="button_submit" />
  2048. <input type="submit" name="new_path" value="' . $txt['attach_add_path'] . '" class="button_submit" />',
  2049. ),
  2050. empty($errors['dir']) ? array(
  2051. 'position' => 'top_of_list',
  2052. 'value' => $txt['attach_dir_desc'],
  2053. 'style' => 'padding: 5px 10px;',
  2054. 'class' => 'windowbg2 smalltext'
  2055. ) : array(
  2056. 'position' => 'top_of_list',
  2057. 'value' => $txt['attach_dir_save_problem'] . '<br />' . implode('<br />', $errors['dir']),
  2058. 'style' => 'padding-left: 35px;',
  2059. 'class' => 'noticebox',
  2060. ),
  2061. ),
  2062. );
  2063. require_once($sourcedir . '/Subs-List.php');
  2064. createList($listOptions);
  2065. if (!empty($modSettings['attachment_basedirectories']))
  2066. {
  2067. $listOptions2 = array(
  2068. 'id' => 'base_paths',
  2069. 'base_href' => $scripturl . '?action=admin;area=manageattachments;sa=attachpaths;' . $context['session_var'] . '=' . $context['session_id'],
  2070. 'title' => $txt['attach_base_paths'],
  2071. 'get_items' => array(
  2072. 'function' => 'list_getBaseDirs',
  2073. ),
  2074. 'columns' => array(
  2075. 'current_dir' => array(
  2076. 'header' => array(
  2077. 'value' => $txt['attach_current'],
  2078. 'class' => 'centercol',
  2079. ),
  2080. 'data' => array(
  2081. 'function' => create_function('$rowData', '
  2082. return \'<input type="radio" name="current_base_dir" value="\' . $rowData[\'id\'] . \'" \' . ($rowData[\'current\'] ? \' checked="checked"\' : \'\') . \' class="input_radio" />\';
  2083. '),
  2084. 'style' => 'width: 10%;',
  2085. 'class' => 'centercol',
  2086. ),
  2087. ),
  2088. 'path' => array(
  2089. 'header' => array(
  2090. 'value' => $txt['attach_path'],
  2091. ),
  2092. 'data' => array(
  2093. 'db' => 'path',
  2094. 'style' => 'width: 45%;',
  2095. ),
  2096. ),
  2097. 'num_dirs' => array(
  2098. 'header' => array(
  2099. 'value' => $txt['attach_num_dirs'],
  2100. ),
  2101. 'data' => array(
  2102. 'db' => 'num_dirs',
  2103. 'style' => 'width: 15%;',
  2104. ),
  2105. ),
  2106. 'status' => array(
  2107. 'header' => array(
  2108. 'value' => $txt['attach_dir_status'],
  2109. ),
  2110. 'data' => array(
  2111. 'db' => 'status',
  2112. 'style' => 'width: 15%;',
  2113. 'class' => 'centercol',
  2114. ),
  2115. ),
  2116. ),
  2117. 'form' => array(
  2118. 'href' => $scripturl . '?action=admin;area=manageattachments;sa=attachpaths;' . $context['session_var'] . '=' . $context['session_id'],
  2119. ),
  2120. 'additional_rows' => array(
  2121. array(
  2122. 'position' => 'below_table_data',
  2123. 'value' => '<input type="hidden" name="' . $context['session_var'] . '" value="' . $context['session_id'] . '" /><input type="submit" name="save2" value="' . $txt['save'] . '" class="button_submit" />
  2124. <input type="submit" name="new_base_path" value="' . $txt['attach_add_path'] . '" class="button_submit" />',
  2125. ),
  2126. empty($errors['base']) ? array(
  2127. 'position' => 'top_of_list',
  2128. 'value' => $txt['attach_dir_base_desc'],
  2129. 'style' => 'padding: 5px 10px;',
  2130. 'class' => 'windowbg2 smalltext'
  2131. ) : array(
  2132. 'position' => 'top_of_list',
  2133. 'value' => $txt['attach_dir_save_problem'] . '<br />' . implode('<br />', $errors['base']),
  2134. 'style' => 'padding-left: 35px',
  2135. 'class' => 'noticebox',
  2136. ),
  2137. ),
  2138. );
  2139. createList($listOptions2);
  2140. }
  2141. // Fix up our template.
  2142. $context[$context['admin_menu_name']]['current_subsection'] = 'attachpaths';
  2143. $context['page_title'] = $txt['attach_path_manage'];
  2144. $context['sub_template'] = 'attachment_paths';
  2145. }
  2146. /**
  2147. * Prepare the actual attachment directories to be displayed in the list.
  2148. */
  2149. function list_getAttachDirs()
  2150. {
  2151. global $smcFunc, $modSettings, $context, $txt;
  2152. $request = $smcFunc['db_query']('', '
  2153. SELECT id_folder, COUNT(id_attach) AS num_attach, SUM(size) AS size_attach
  2154. FROM {db_prefix}attachments
  2155. WHERE attachment_type != {int:type}
  2156. GROUP BY id_folder',
  2157. array(
  2158. 'type' => 1,
  2159. )
  2160. );
  2161. $expected_files = array();
  2162. $expected_size = array();
  2163. while ($row = $smcFunc['db_fetch_assoc']($request))
  2164. {
  2165. $expected_files[$row['id_folder']] = $row['num_attach'];
  2166. $expected_size[$row['id_folder']] = $row['size_attach'];
  2167. }
  2168. $smcFunc['db_free_result']($request);
  2169. $attachdirs = array();
  2170. foreach ($modSettings['attachmentUploadDir'] as $id => $dir)
  2171. {
  2172. // If there aren't any attachments in this directory this won't exist.
  2173. if (!isset($expected_files[$id]))
  2174. $expected_files[$id] = 0;
  2175. // Check if the directory is doing okay.
  2176. list ($status, $error, $files) = attachDirStatus($dir, $expected_files[$id]);
  2177. // If it is one, let's show that it's a base directory.
  2178. $sub_dirs = 0;
  2179. $is_base_dir = false;
  2180. if (!empty($modSettings['attachment_basedirectories']))
  2181. {
  2182. $is_base_dir = in_array($dir, $modSettings['attachment_basedirectories']);
  2183. // Count any sub-folders.
  2184. foreach ($modSettings['attachmentUploadDir'] as $sid => $sub)
  2185. if (strpos($sub, $dir . DIRECTORY_SEPARATOR) !== false)
  2186. {
  2187. $expected_files[$id]++;
  2188. $sub_dirs++;
  2189. }
  2190. }
  2191. $attachdirs[] = array(
  2192. 'id' => $id,
  2193. 'current' => $id == $modSettings['currentAttachmentUploadDir'],
  2194. 'disable_current' => isset($modSettings['automanage_attachments']) && $modSettings['automanage_attachments'] > 1,
  2195. 'disable_base_dir' => $is_base_dir && $sub_dirs > 0 && !empty($files) && empty($error) && empty($save_errors),
  2196. 'path' => $dir,
  2197. 'current_size' => !empty($expected_size[$id]) ? comma_format($expected_size[$id] / 1024, 0) : 0,
  2198. 'num_files' => comma_format($expected_files[$id] - $sub_dirs, 0) . ($sub_dirs > 0 ? ' (' . $sub_dirs . ')' : ''),
  2199. 'status' => ($is_base_dir ? $txt['attach_dir_basedir'] . '<br />' : '') . ($error ? '<div class="error">' : '') . sprintf($txt['attach_dir_' . $status], $context['session_id'], $context['session_var']) . ($error ? '</div>' : ''),
  2200. );
  2201. }
  2202. // Just stick a new directory on at the bottom.
  2203. if (isset($_REQUEST['new_path']))
  2204. $attachdirs[] = array(
  2205. 'id' => max(array_merge(array_keys($expected_files), array_keys($modSettings['attachmentUploadDir']))) + 1,
  2206. 'current' => false,
  2207. 'path' => '',
  2208. 'current_size' => '',
  2209. 'num_files' => '',
  2210. 'status' => '',
  2211. );
  2212. return $attachdirs;
  2213. }
  2214. /**
  2215. * Prepare the base directories to be displayed in a list.
  2216. */
  2217. function list_getBaseDirs()
  2218. {
  2219. global $modSettings, $context, $txt;
  2220. if (empty($modSettings['attachment_basedirectories']))
  2221. return;
  2222. $basedirs = array();
  2223. // Get a list of the base directories.
  2224. foreach ($modSettings['attachment_basedirectories'] as $id => $dir)
  2225. {
  2226. // Loop through the attach directory array to count any sub-directories
  2227. $expected_dirs = 0;
  2228. foreach ($modSettings['attachmentUploadDir'] as $sid => $sub)
  2229. if (strpos($sub, $dir . DIRECTORY_SEPARATOR) !== false)
  2230. $expected_dirs++;
  2231. if (!is_dir($dir))
  2232. $status = 'does_not_exist';
  2233. elseif (!is_writeable($dir))
  2234. $status = 'not_writable';
  2235. else
  2236. $status = 'ok';
  2237. $basedirs[] = array(
  2238. 'id' => $id,
  2239. 'current' => $dir == $modSettings['basedirectory_for_attachments'],
  2240. 'path' => $expected_dirs > 0 ? $dir : ('<input type="text" name="base_dir[' . $id . ']" value="' . $dir . '" size="40" />'),
  2241. 'num_dirs' => $expected_dirs,
  2242. 'status' => $status == 'ok' ? $txt['attach_dir_ok'] : ('<span class="error">' . $txt['attach_dir_' . $status] . '</span>'),
  2243. );
  2244. }
  2245. if (isset($_REQUEST['new_base_path']))
  2246. $basedirs[] = array(
  2247. 'id' => '',
  2248. 'current' => false,
  2249. 'path' => '<input type="text" name="new_base_dir" value="" size="40" />',
  2250. 'num_dirs' => '',
  2251. 'status' => '',
  2252. );
  2253. return $basedirs;
  2254. }
  2255. /**
  2256. * Checks the status of an attachment directory and returns an array
  2257. * of the status key, if that status key signifies an error, and
  2258. * the file count.
  2259. *
  2260. * @param string $dir
  2261. * @param int $expected_files
  2262. */
  2263. function attachDirStatus($dir, $expected_files)
  2264. {
  2265. global $sourcedir, $context;
  2266. if (!is_dir($dir))
  2267. return array('does_not_exist', true, '');
  2268. elseif (!is_writable($dir))
  2269. return array('not_writable', true, '');
  2270. // Everything is okay so far, start to scan through the directory.
  2271. $num_files = 0;
  2272. $dir_handle = dir($dir);
  2273. while ($file = $dir_handle->read())
  2274. {
  2275. // Now do we have a real file here?
  2276. if (in_array($file, array('.', '..', '.htaccess', 'index.php')))
  2277. continue;
  2278. $num_files++;
  2279. }
  2280. $dir_handle->close();
  2281. if ($num_files < $expected_files)
  2282. return array('files_missing', true, $num_files);
  2283. // Empty?
  2284. elseif ($expected_files == 0)
  2285. return array('unused', false, $num_files);
  2286. // All good!
  2287. else
  2288. return array('ok', false, $num_files);
  2289. }
  2290. /**
  2291. * Maintance function to move attachments from one directory to another
  2292. */
  2293. function TransferAttachments()
  2294. {
  2295. global $modSettings, $context, $smcFunc, $sourcedir, $txt, $boarddir;
  2296. checkSession();
  2297. $modSettings['attachmentUploadDir'] = unserialize($modSettings['attachmentUploadDir']);
  2298. if (!empty($modSettings['attachment_basedirectories']))
  2299. $modSettings['attachment_basedirectories'] = unserialize($modSettings['attachment_basedirectories']);
  2300. else
  2301. $modSettings['basedirectory_for_attachments'] = array();
  2302. $_POST['from'] = (int) $_POST['from'];
  2303. $_POST['auto'] = !empty($_POST['auto']) ? (int) $_POST['auto'] : 0;
  2304. $_POST['to'] = (int) $_POST['to'];
  2305. $start = !empty($_POST['empty_it']) ? 0 : $modSettings['attachmentDirFileLimit'];
  2306. $_SESSION['checked'] = !empty($_POST['empty_it']) ? true : false;
  2307. $limit = 501;
  2308. $results = array();
  2309. $dir_files = 0;
  2310. $current_progress = 0;
  2311. $total_moved = 0;
  2312. $total_not_moved = 0;
  2313. if (empty($_POST['from']) || (empty($_POST['auto']) && empty($_POST['to'])))
  2314. $results[] = $txt['attachment_transfer_no_dir'];
  2315. if ($_POST['from'] == $_POST['to'])
  2316. $results[] = $txt['attachment_transfer_same_dir'];
  2317. if (empty($results))
  2318. {
  2319. // Get the total file count for the progess bar.
  2320. $request = $smcFunc['db_query']('', '
  2321. SELECT COUNT(*)
  2322. FROM {db_prefix}attachments
  2323. WHERE id_folder = {int:folder_id}
  2324. AND attachment_type != {int:attachment_type}',
  2325. array(
  2326. 'folder_id' => $_POST['from'],
  2327. 'attachment_type' => 1,
  2328. )
  2329. );
  2330. list ($total_progress) = $smcFunc['db_fetch_row']($request);
  2331. $smcFunc['db_free_result']($request);
  2332. $total_progress -= $start;
  2333. if ($total_progress < 1)
  2334. $results[] = $txt['attachment_transfer_no_find'];
  2335. }
  2336. if (empty($results))
  2337. {
  2338. // Where are they going?
  2339. if (!empty($_POST['auto']))
  2340. {
  2341. require_once($sourcedir . '/Subs-Attachments.php');
  2342. $modSettings['automanage_attachments'] = 1;
  2343. $modSettings['use_subdirectories_for_attachments'] = $_POST['auto'] == -1 ? 0 : 1;
  2344. $modSettings['basedirectory_for_attachments'] = $_POST['auto'] > 0 ? $modSettings['attachmentUploadDir'][$_POST['auto']] : $modSettings['basedirectory_for_attachments'];
  2345. automanage_attachments_check_directory();
  2346. $new_dir = $modSettings['currentAttachmentUploadDir'];
  2347. }
  2348. else
  2349. $new_dir = $_POST['to'];
  2350. $modSettings['currentAttachmentUploadDir'] = $new_dir;
  2351. $break = false;
  2352. while ($break == false)
  2353. {
  2354. @set_time_limit(300);
  2355. if (function_exists('apache_reset_timeout'))
  2356. @apache_reset_timeout();
  2357. // If limts are set, get the file count and size for the destination folder
  2358. if ($dir_files <= 0 && (!empty($modSettings['attachmentDirSizeLimit']) || !empty($modSettings['attachmentDirFileLimit'])))
  2359. {
  2360. $request = $smcFunc['db_query']('', '
  2361. SELECT COUNT(*), SUM(size)
  2362. FROM {db_prefix}attachments
  2363. WHERE id_folder = {int:folder_id}
  2364. AND attachment_type != {int:attachment_type}',
  2365. array(
  2366. 'folder_id' => $new_dir,
  2367. 'attachment_type' => 1,
  2368. )
  2369. );
  2370. list ($dir_files, $dir_size) = $smcFunc['db_fetch_row']($request);
  2371. $smcFunc['db_free_result']($request);
  2372. }
  2373. // Find some attachments to move
  2374. $request = $smcFunc['db_query']('', '
  2375. SELECT id_attach, filename, id_folder, file_hash, size
  2376. FROM {db_prefix}attachments
  2377. WHERE id_folder = {int:folder}
  2378. AND attachment_type != {int:attachment_type}
  2379. LIMIT {int:start}, {int:limit}',
  2380. array(
  2381. 'folder' => $_POST['from'],
  2382. 'attachment_type' => 1,
  2383. 'start' => $start,
  2384. 'limit' => $limit,
  2385. )
  2386. );
  2387. if ($smcFunc['db_num_rows']($request) === 0)
  2388. {
  2389. if (empty($current_progress))
  2390. $results[] = $txt['attachment_transfer_no_find'];
  2391. break;
  2392. }
  2393. if ($smcFunc['db_num_rows']($request) < $limit)
  2394. $break = true;
  2395. // Move them
  2396. $moved = array();
  2397. while ($row = $smcFunc['db_fetch_assoc']($request))
  2398. {
  2399. // Size and file count check
  2400. if (!empty($modSettings['attachmentDirSizeLimit']) || !empty($modSettings['attachmentDirFileLimit']))
  2401. {
  2402. $dir_files++;
  2403. $dir_size += !empty($row['size']) ? $row['size'] : filesize($source);
  2404. // If we've reached a limit. Do something.
  2405. if (!empty($modSettings['attachmentDirSizeLimit']) && $dir_size > $modSettings['attachmentDirSizeLimit'] * 1024 || (!empty($modSettings['attachmentDirFileLimit']) && $dir_files > $modSettings['attachmentDirFileLimit']))
  2406. {
  2407. if (!empty($_POST['auto']))
  2408. {
  2409. // Since we're in auto mode. Create a new folder and reset the counters.
  2410. automanage_attachments_by_space();
  2411. $results[] = sprintf($txt['attachments_transfered'], $total_moved, $modSettings['attachmentUploadDir'][$new_dir]);
  2412. if (!empty($total_not_moved))
  2413. $results[] = sprintf($txt['attachments_not_transfered'], $total_not_moved);
  2414. $dir_files = 0;
  2415. $total_moved = 0;
  2416. $total_not_moved = 0;
  2417. $break = false;
  2418. break;
  2419. }
  2420. else
  2421. {
  2422. // Hmm, not in auto. Time to bail out then...
  2423. $results[] = $txt['attachment_transfer_no_room'];
  2424. $break = true;
  2425. break;
  2426. }
  2427. }
  2428. }
  2429. $source = getAttachmentFilename($row['filename'], $row['id_attach'], $row['id_folder'], false, $row['file_hash']);
  2430. $dest = $modSettings['attachmentUploadDir'][$new_dir] . '/' . basename($source);
  2431. if (@rename($source, $dest))
  2432. {
  2433. $total_moved++;
  2434. $current_progress++;
  2435. $moved[] = $row['id_attach'];
  2436. }
  2437. else
  2438. $total_not_moved++;
  2439. }
  2440. $smcFunc['db_free_result']($request);
  2441. if (!empty($moved))
  2442. {
  2443. // Update the database
  2444. $smcFunc['db_query']('', '
  2445. UPDATE {db_prefix}attachments
  2446. SET id_folder = {int:new}
  2447. WHERE id_attach IN ({array_int:attachments})',
  2448. array(
  2449. 'attachments' => $moved,
  2450. 'new' => $new_dir,
  2451. )
  2452. );
  2453. }
  2454. $moved = array();
  2455. $new_dir = $modSettings['currentAttachmentUploadDir'];
  2456. // Create the progress bar.
  2457. if (!$break)
  2458. {
  2459. $percent_done = min(round($current_progress / $total_progress * 100, 0), 100);
  2460. $prog_bar = '
  2461. <div class="progress_bar">
  2462. <div class="full_bar">' . $percent_done . '%</div>
  2463. <div class="green_percent" style="width: ' . $percent_done . '%;">&nbsp;</div>
  2464. </div>';
  2465. // Write it to a file so it can be displayed
  2466. $fp = fopen($boarddir . '/progress.php', "w");
  2467. fwrite($fp, $prog_bar);
  2468. fclose($fp);
  2469. usleep(500000);
  2470. }
  2471. }
  2472. $results[] = sprintf($txt['attachments_transfered'], $total_moved, $modSettings['attachmentUploadDir'][$new_dir]);
  2473. if (!empty($total_not_moved))
  2474. $results[] = sprintf($txt['attachments_not_transfered'], $total_not_moved);
  2475. }
  2476. $_SESSION['results'] = $results;
  2477. if (file_exists($boarddir . '/progress.php'))
  2478. unlink($boarddir . '/progress.php');
  2479. redirectexit('action=admin;area=manageattachments;sa=maintenance#transfer');
  2480. }
  2481. ?>