2
0

ManageAttachments.php 96 KB

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