ManageAttachments.php 94 KB

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