ManageAttachments.php 94 KB

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