ManageAttachments.php 65 KB

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