2
0

ManageAttachments.php 94 KB

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