2
0

ManageAttachments.php 94 KB

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