2
0

ManageAttachments.php 79 KB

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