ManageAttachments.php 95 KB

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