ManageAttachments.php 94 KB

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