ManageAttachments.php 95 KB

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