ManageAttachments.php 82 KB

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