ManageAttachments.php 94 KB

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