ManageAttachments.php 95 KB

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