ManageAttachments.php 95 KB

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