ManageAttachments.php 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042
  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=attachements.
  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. 'function' => create_function('$rowData','
  353. global $txt;
  354. return comma_format($rowData[\'downloads\']);
  355. '),
  356. ),
  357. 'sort' => array(
  358. 'default' => 'a.downloads',
  359. 'reverse' => 'a.downloads DESC',
  360. ),
  361. ),
  362. 'check' => array(
  363. 'header' => array(
  364. 'value' => '<input type="checkbox" onclick="invertAll(this, this.form);" class="input_check" />',
  365. ),
  366. 'data' => array(
  367. 'sprintf' => array(
  368. 'format' => '<input type="checkbox" name="remove[%1$d]" class="input_check" />',
  369. 'params' => array(
  370. 'id_attach' => false,
  371. ),
  372. ),
  373. 'style' => 'text-align: center',
  374. ),
  375. ),
  376. ),
  377. 'form' => array(
  378. 'href' => $scripturl . '?action=admin;area=manageattachments;sa=remove' . ($context['browse_type'] === 'avatars' ? ';avatars' : ($context['browse_type'] === 'thumbs' ? ';thumbs' : '')),
  379. 'include_sort' => true,
  380. 'include_start' => true,
  381. 'hidden_fields' => array(
  382. 'type' => $context['browse_type'],
  383. ),
  384. ),
  385. 'additional_rows' => array(
  386. array(
  387. 'position' => 'below_table_data',
  388. 'value' => '<input type="submit" name="remove_submit" class="button_submit" value="' . $txt['quickmod_delete_selected'] . '" onclick="return confirm(\'' . $txt['confirm_delete_attachments'] . '\');" />',
  389. 'style' => 'text-align: right;',
  390. ),
  391. ),
  392. );
  393. // Create the list.
  394. require_once($sourcedir . '/Subs-List.php');
  395. createList($listOptions);
  396. }
  397. /**
  398. * Returns the list of attachments files (avatars or not), recorded
  399. * in the database, per the parameters received.
  400. *
  401. * @param int $start
  402. * @param int $items_per_page
  403. * @param string $sort
  404. * @param string $browse_type, can be 'avatars' or ... not. :P
  405. */
  406. function list_getFiles($start, $items_per_page, $sort, $browse_type)
  407. {
  408. global $smcFunc, $txt;
  409. // Choose a query depending on what we are viewing.
  410. if ($browse_type === 'avatars')
  411. $request = $smcFunc['db_query']('', '
  412. SELECT
  413. {string:blank_text} AS id_msg, IFNULL(mem.real_name, {string:not_applicable_text}) AS poster_name,
  414. mem.last_login AS poster_time, 0 AS id_topic, a.id_member, a.id_attach, a.filename, a.file_hash, a.attachment_type,
  415. a.size, a.width, a.height, a.downloads, {string:blank_text} AS subject, 0 AS id_board
  416. FROM {db_prefix}attachments AS a
  417. LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = a.id_member)
  418. WHERE a.id_member != {int:guest_id}
  419. ORDER BY {raw:sort}
  420. LIMIT {int:start}, {int:per_page}',
  421. array(
  422. 'guest_id' => 0,
  423. 'blank_text' => '',
  424. 'not_applicable_text' => $txt['not_applicable'],
  425. 'sort' => $sort,
  426. 'start' => $start,
  427. 'per_page' => $items_per_page,
  428. )
  429. );
  430. else
  431. $request = $smcFunc['db_query']('', '
  432. SELECT
  433. m.id_msg, IFNULL(mem.real_name, m.poster_name) AS poster_name, m.poster_time, m.id_topic, m.id_member,
  434. a.id_attach, a.filename, a.file_hash, a.attachment_type, a.size, a.width, a.height, a.downloads, mf.subject, t.id_board
  435. FROM {db_prefix}attachments AS a
  436. INNER JOIN {db_prefix}messages AS m ON (m.id_msg = a.id_msg)
  437. INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic)
  438. INNER JOIN {db_prefix}messages AS mf ON (mf.id_msg = t.id_first_msg)
  439. LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)
  440. WHERE a.attachment_type = {int:attachment_type}
  441. ORDER BY {raw:sort}
  442. LIMIT {int:start}, {int:per_page}',
  443. array(
  444. 'attachment_type' => $browse_type == 'thumbs' ? '3' : '0',
  445. 'sort' => $sort,
  446. 'start' => $start,
  447. 'per_page' => $items_per_page,
  448. )
  449. );
  450. $files = array();
  451. while ($row = $smcFunc['db_fetch_assoc']($request))
  452. $files[] = $row;
  453. $smcFunc['db_free_result']($request);
  454. return $files;
  455. }
  456. /**
  457. * Return the number of files of the specified type recorded in the database.
  458. * (the specified type being attachments or avatars).
  459. *
  460. * @param string $browse_type, can be 'avatars' or not. (in which case they're
  461. * attachments)
  462. */
  463. function list_getNumFiles($browse_type)
  464. {
  465. global $smcFunc;
  466. // Depending on the type of file, different queries are used.
  467. if ($browse_type === 'avatars')
  468. $request = $smcFunc['db_query']('', '
  469. SELECT COUNT(*)
  470. FROM {db_prefix}attachments
  471. WHERE id_member != {int:guest_id_member}',
  472. array(
  473. 'guest_id_member' => 0,
  474. )
  475. );
  476. else
  477. $request = $smcFunc['db_query']('', '
  478. SELECT COUNT(*) AS num_attach
  479. FROM {db_prefix}attachments AS a
  480. INNER JOIN {db_prefix}messages AS m ON (m.id_msg = a.id_msg)
  481. INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic)
  482. INNER JOIN {db_prefix}messages AS mf ON (mf.id_msg = t.id_first_msg)
  483. WHERE a.attachment_type = {int:attachment_type}
  484. AND a.id_member = {int:guest_id_member}',
  485. array(
  486. 'attachment_type' => $browse_type === 'thumbs' ? '3' : '0',
  487. 'guest_id_member' => 0,
  488. )
  489. );
  490. list ($num_files) = $smcFunc['db_fetch_row']($request);
  491. $smcFunc['db_free_result']($request);
  492. return $num_files;
  493. }
  494. /**
  495. * Show several file maintenance options.
  496. * Called by ?action=admin;area=manageattachments;sa=maintain.
  497. * Calculates file statistics (total file size, number of attachments,
  498. * number of avatars, attachment space available).
  499. *
  500. * @uses the 'maintain' sub template.
  501. */
  502. function MaintainFiles()
  503. {
  504. global $context, $modSettings, $txt, $smcFunc;
  505. $context['sub_template'] = 'maintenance';
  506. if (!empty($modSettings['currentAttachmentUploadDir']))
  507. $attach_dirs = unserialize($modSettings['attachmentUploadDir']);
  508. else
  509. $attach_dirs = array($modSettings['attachmentUploadDir']);
  510. // Get the number of attachments....
  511. $request = $smcFunc['db_query']('', '
  512. SELECT COUNT(*)
  513. FROM {db_prefix}attachments
  514. WHERE attachment_type = {int:attachment_type}
  515. AND id_member = {int:guest_id_member}',
  516. array(
  517. 'attachment_type' => 0,
  518. 'guest_id_member' => 0,
  519. )
  520. );
  521. list ($context['num_attachments']) = $smcFunc['db_fetch_row']($request);
  522. $smcFunc['db_free_result']($request);
  523. // Also get the avatar amount....
  524. $request = $smcFunc['db_query']('', '
  525. SELECT COUNT(*)
  526. FROM {db_prefix}attachments
  527. WHERE id_member != {int:guest_id_member}',
  528. array(
  529. 'guest_id_member' => 0,
  530. )
  531. );
  532. list ($context['num_avatars']) = $smcFunc['db_fetch_row']($request);
  533. $smcFunc['db_free_result']($request);
  534. // Check the size of all the directories.
  535. $request = $smcFunc['db_query']('', '
  536. SELECT SUM(size)
  537. FROM {db_prefix}attachments',
  538. array(
  539. )
  540. );
  541. list ($attachmentDirSize) = $smcFunc['db_fetch_row']($request);
  542. $smcFunc['db_free_result']($request);
  543. // Divide it into kilobytes.
  544. $attachmentDirSize /= 1024;
  545. // If they specified a limit only....
  546. if (!empty($modSettings['attachmentDirSizeLimit']))
  547. $context['attachment_space'] = max(round($modSettings['attachmentDirSizeLimit'] - $attachmentDirSize, 2), 0);
  548. $context['attachment_total_size'] = round($attachmentDirSize, 2);
  549. $context['attach_multiple_dirs'] = !empty($modSettings['currentAttachmentUploadDir']);
  550. }
  551. /**
  552. * Move avatars from their current location, to the custom_avatar_dir folder.
  553. * Called from the maintenance screen by ?action=admin;area=manageattachments;sa=moveAvatars.
  554. */
  555. function MoveAvatars()
  556. {
  557. global $modSettings, $smcFunc;
  558. // First make sure the custom avatar dir is writable.
  559. if (!is_writable($modSettings['custom_avatar_dir']))
  560. {
  561. // Try to fix it.
  562. @chmod($modSettings['custom_avatar_dir'], 0777);
  563. // Guess that didn't work?
  564. if (!is_writable($modSettings['custom_avatar_dir']))
  565. fatal_lang_error('attachments_no_write', 'critical');
  566. }
  567. $request = $smcFunc['db_query']('', '
  568. SELECT id_attach, id_folder, id_member, filename, file_hash
  569. FROM {db_prefix}attachments
  570. WHERE attachment_type = {int:attachment_type}
  571. AND id_member > {int:guest_id_member}',
  572. array(
  573. 'attachment_type' => 0,
  574. 'guest_id_member' => 0,
  575. )
  576. );
  577. $updatedAvatars = array();
  578. while ($row = $smcFunc['db_fetch_assoc']($request))
  579. {
  580. $filename = getAttachmentFilename($row['filename'], $row['id_attach'], $row['id_folder'], false, $row['file_hash']);
  581. if (rename($filename, $modSettings['custom_avatar_dir'] . '/' . $row['filename']))
  582. $updatedAvatars[] = $row['id_attach'];
  583. }
  584. $smcFunc['db_free_result']($request);
  585. if (!empty($updatedAvatars))
  586. $smcFunc['db_query']('', '
  587. UPDATE {db_prefix}attachments
  588. SET attachment_type = {int:attachment_type}
  589. WHERE id_attach IN ({array_int:updated_avatars})',
  590. array(
  591. 'updated_avatars' => $updatedAvatars,
  592. 'attachment_type' => 1,
  593. )
  594. );
  595. redirectexit('action=admin;area=manageattachments;sa=maintenance');
  596. }
  597. /**
  598. * Remove attachments older than a given age.
  599. * Called from the maintenance screen by
  600. * ?action=admin;area=manageattachments;sa=byAge.
  601. * It optionally adds a certain text to the messages the attachments
  602. * were removed from.
  603. * @todo refactor this silly superglobals use...
  604. */
  605. function RemoveAttachmentByAge()
  606. {
  607. global $modSettings, $smcFunc;
  608. checkSession('post', 'admin');
  609. // @todo Ignore messages in topics that are stickied?
  610. // Deleting an attachment?
  611. if ($_REQUEST['type'] != 'avatars')
  612. {
  613. // Get rid of all the old attachments.
  614. $messages = removeAttachments(array('attachment_type' => 0, 'poster_time' => (time() - 24 * 60 * 60 * $_POST['age'])), 'messages', true);
  615. // Update the messages to reflect the change.
  616. if (!empty($messages) && !empty($_POST['notice']))
  617. $smcFunc['db_query']('', '
  618. UPDATE {db_prefix}messages
  619. SET body = CONCAT(body, {string:notice})
  620. WHERE id_msg IN ({array_int:messages})',
  621. array(
  622. 'messages' => $messages,
  623. 'notice' => '<br /><br />' . $_POST['notice'],
  624. )
  625. );
  626. }
  627. else
  628. {
  629. // Remove all the old avatars.
  630. removeAttachments(array('not_id_member' => 0, 'last_login' => (time() - 24 * 60 * 60 * $_POST['age'])), 'members');
  631. }
  632. redirectexit('action=admin;area=manageattachments' . (empty($_REQUEST['avatars']) ? ';sa=maintenance' : ';avatars'));
  633. }
  634. /**
  635. * Remove attachments larger than a given size.
  636. * Called from the maintenance screen by
  637. * ?action=admin;area=manageattachments;sa=bySize.
  638. * Optionally adds a certain text to the messages the attachments were
  639. * removed from.
  640. */
  641. function RemoveAttachmentBySize()
  642. {
  643. global $modSettings, $smcFunc;
  644. checkSession('post', 'admin');
  645. // Find humungous attachments.
  646. $messages = removeAttachments(array('attachment_type' => 0, 'size' => 1024 * $_POST['size']), 'messages', true);
  647. // And make a note on the post.
  648. if (!empty($messages) && !empty($_POST['notice']))
  649. $smcFunc['db_query']('', '
  650. UPDATE {db_prefix}messages
  651. SET body = CONCAT(body, {string:notice})
  652. WHERE id_msg IN ({array_int:messages})',
  653. array(
  654. 'messages' => $messages,
  655. 'notice' => '<br /><br />' . $_POST['notice'],
  656. )
  657. );
  658. redirectexit('action=admin;area=manageattachments;sa=maintenance');
  659. }
  660. /**
  661. * Remove a selection of attachments or avatars.
  662. * Called from the browse screen as submitted form by
  663. * ?action=admin;area=manageattachments;sa=remove
  664. */
  665. function RemoveAttachment()
  666. {
  667. global $txt, $smcFunc, $language;
  668. checkSession('post');
  669. if (!empty($_POST['remove']))
  670. {
  671. $attachments = array();
  672. // There must be a quicker way to pass this safety test??
  673. foreach ($_POST['remove'] as $removeID => $dummy)
  674. $attachments[] = (int) $removeID;
  675. if ($_REQUEST['type'] == 'avatars' && !empty($attachments))
  676. removeAttachments(array('id_attach' => $attachments));
  677. else if (!empty($attachments))
  678. {
  679. $messages = removeAttachments(array('id_attach' => $attachments), 'messages', true);
  680. // And change the message to reflect this.
  681. if (!empty($messages))
  682. {
  683. loadLanguage('index', $language, true);
  684. $smcFunc['db_query']('', '
  685. UPDATE {db_prefix}messages
  686. SET body = CONCAT(body, {string:deleted_message})
  687. WHERE id_msg IN ({array_int:messages_affected})',
  688. array(
  689. 'messages_affected' => $messages,
  690. 'deleted_message' => '<br /><br />' . $txt['attachment_delete_admin'],
  691. )
  692. );
  693. loadLanguage('index', $user_info['language'], true);
  694. }
  695. }
  696. }
  697. $_GET['sort'] = isset($_GET['sort']) ? $_GET['sort'] : 'date';
  698. redirectexit('action=admin;area=manageattachments;sa=browse;' . $_REQUEST['type'] . ';sort=' . $_GET['sort'] . (isset($_GET['desc']) ? ';desc' : '') . ';start=' . $_REQUEST['start']);
  699. }
  700. /**
  701. * Removes all attachments in a single click
  702. * Called from the maintenance screen by
  703. * ?action=admin;area=manageattachments;sa=removeall.
  704. */
  705. function RemoveAllAttachments()
  706. {
  707. global $txt, $smcFunc;
  708. checkSession('get', 'admin');
  709. $messages = removeAttachments(array('attachment_type' => 0), '', true);
  710. if (!isset($_POST['notice']))
  711. $_POST['notice'] = $txt['attachment_delete_admin'];
  712. // Add the notice on the end of the changed messages.
  713. if (!empty($messages))
  714. $smcFunc['db_query']('', '
  715. UPDATE {db_prefix}messages
  716. SET body = CONCAT(body, {string:deleted_message})
  717. WHERE id_msg IN ({array_int:messages})',
  718. array(
  719. 'messages' => $messages,
  720. 'deleted_message' => '<br /><br />' . $_POST['notice'],
  721. )
  722. );
  723. redirectexit('action=admin;area=manageattachments;sa=maintenance');
  724. }
  725. /**
  726. * Removes attachments or avatars based on a given query condition.
  727. * Called by several remove avatar/attachment functions in this file.
  728. * It removes attachments based that match the $condition.
  729. * It allows query_types 'messages' and 'members', whichever is need by the
  730. * $condition parameter.
  731. * It does no permissions check.
  732. * @internal
  733. *
  734. * @param array $condition
  735. * @param string $query_type
  736. * @param bool $return_affected_messages = false
  737. * @param bool $autoThumbRemoval = true
  738. */
  739. function removeAttachments($condition, $query_type = '', $return_affected_messages = false, $autoThumbRemoval = true)
  740. {
  741. global $modSettings, $smcFunc;
  742. // @todo This might need more work!
  743. $new_condition = array();
  744. $query_parameter = array(
  745. 'thumb_attachment_type' => 3,
  746. );
  747. $do_logging = array();
  748. if (is_array($condition))
  749. {
  750. foreach ($condition as $real_type => $restriction)
  751. {
  752. // Doing a NOT?
  753. $is_not = substr($real_type, 0, 4) == 'not_';
  754. $type = $is_not ? substr($real_type, 4) : $real_type;
  755. if (in_array($type, array('id_member', 'id_attach', 'id_msg')))
  756. $new_condition[] = 'a.' . $type . ($is_not ? ' NOT' : '') . ' IN (' . (is_array($restriction) ? '{array_int:' . $real_type . '}' : '{int:' . $real_type . '}') . ')';
  757. elseif ($type == 'attachment_type')
  758. $new_condition[] = 'a.attachment_type = {int:' . $real_type . '}';
  759. elseif ($type == 'poster_time')
  760. $new_condition[] = 'm.poster_time < {int:' . $real_type . '}';
  761. elseif ($type == 'last_login')
  762. $new_condition[] = 'mem.last_login < {int:' . $real_type . '}';
  763. elseif ($type == 'size')
  764. $new_condition[] = 'a.size > {int:' . $real_type . '}';
  765. elseif ($type == 'id_topic')
  766. $new_condition[] = 'm.id_topic IN (' . (is_array($restriction) ? '{array_int:' . $real_type . '}' : '{int:' . $real_type . '}') . ')';
  767. // Add the parameter!
  768. $query_parameter[$real_type] = $restriction;
  769. if ($type == 'do_logging')
  770. $do_logging = $condition['id_attach'];
  771. }
  772. $condition = implode(' AND ', $new_condition);
  773. }
  774. // Delete it only if it exists...
  775. $msgs = array();
  776. $attach = array();
  777. $parents = array();
  778. // Get all the attachment names and id_msg's.
  779. $request = $smcFunc['db_query']('', '
  780. SELECT
  781. 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') . ',
  782. 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
  783. FROM {db_prefix}attachments AS a' .($query_type == 'members' ? '
  784. INNER JOIN {db_prefix}members AS mem ON (mem.id_member = a.id_member)' : ($query_type == 'messages' ? '
  785. INNER JOIN {db_prefix}messages AS m ON (m.id_msg = a.id_msg)' : '')) . '
  786. LEFT JOIN {db_prefix}attachments AS thumb ON (thumb.id_attach = a.id_thumb)
  787. LEFT JOIN {db_prefix}attachments AS thumb_parent ON (thumb.attachment_type = {int:thumb_attachment_type} AND thumb_parent.id_thumb = a.id_attach)
  788. WHERE ' . $condition,
  789. $query_parameter
  790. );
  791. while ($row = $smcFunc['db_fetch_assoc']($request))
  792. {
  793. // Figure out the "encrypted" filename and unlink it ;).
  794. if ($row['attachment_type'] == 1)
  795. {
  796. // if attachment_type = 1, it's... an avatar in a custom avatar directory.
  797. // wasn't it obvious? :P
  798. // @todo look again at this.
  799. @unlink($modSettings['custom_avatar_dir'] . '/' . $row['filename']);
  800. }
  801. else
  802. {
  803. $filename = getAttachmentFilename($row['filename'], $row['id_attach'], $row['id_folder'], false, $row['file_hash']);
  804. @unlink($filename);
  805. // If this was a thumb, the parent attachment should know about it.
  806. if (!empty($row['id_parent']))
  807. $parents[] = $row['id_parent'];
  808. // If this attachments has a thumb, remove it as well.
  809. if (!empty($row['id_thumb']) && $autoThumbRemoval)
  810. {
  811. $thumb_filename = getAttachmentFilename($row['thumb_filename'], $row['id_thumb'], $row['thumb_folder'], false, $row['thumb_file_hash']);
  812. @unlink($thumb_filename);
  813. $attach[] = $row['id_thumb'];
  814. }
  815. }
  816. // Make a list.
  817. if ($return_affected_messages && empty($row['attachment_type']))
  818. $msgs[] = $row['id_msg'];
  819. $attach[] = $row['id_attach'];
  820. }
  821. $smcFunc['db_free_result']($request);
  822. // Removed attachments don't have to be updated anymore.
  823. $parents = array_diff($parents, $attach);
  824. if (!empty($parents))
  825. $smcFunc['db_query']('', '
  826. UPDATE {db_prefix}attachments
  827. SET id_thumb = {int:no_thumb}
  828. WHERE id_attach IN ({array_int:parent_attachments})',
  829. array(
  830. 'parent_attachments' => $parents,
  831. 'no_thumb' => 0,
  832. )
  833. );
  834. if (!empty($do_logging))
  835. {
  836. // In order to log the attachments, we really need their message and filename
  837. $request = $smcFunc['db_query']('', '
  838. SELECT m.id_msg, a.filename
  839. FROM {db_prefix}attachments AS a
  840. INNER JOIN {db_prefix}messages AS m ON (a.id_msg = m.id_msg)
  841. WHERE a.id_attach IN ({array_int:attachments})
  842. AND a.attachment_type = {int:attachment_type}',
  843. array(
  844. 'attachments' => $do_logging,
  845. 'attachment_type' => 0,
  846. )
  847. );
  848. while ($row = $smcFunc['db_fetch_assoc']($request))
  849. logAction(
  850. 'remove_attach',
  851. array(
  852. 'message' => $row['id_msg'],
  853. 'filename' => preg_replace('~&amp;#(\\d{1,7}|x[0-9a-fA-F]{1,6});~', '&#\\1;', $smcFunc['htmlspecialchars']($row['filename'])),
  854. )
  855. );
  856. $smcFunc['db_free_result']($request);
  857. }
  858. if (!empty($attach))
  859. $smcFunc['db_query']('', '
  860. DELETE FROM {db_prefix}attachments
  861. WHERE id_attach IN ({array_int:attachment_list})',
  862. array(
  863. 'attachment_list' => $attach,
  864. )
  865. );
  866. call_integration_hook('integrate_remove_attachments', array($attach));
  867. if ($return_affected_messages)
  868. return array_unique($msgs);
  869. }
  870. /**
  871. * This function should find attachments in the database that no longer exist and clear them, and fix filesize issues.
  872. */
  873. function RepairAttachments()
  874. {
  875. global $modSettings, $context, $txt, $smcFunc;
  876. checkSession('get');
  877. // If we choose cancel, redirect right back.
  878. if (isset($_POST['cancel']))
  879. redirectexit('action=admin;area=manageattachments;sa=maintenance');
  880. // Try give us a while to sort this out...
  881. @set_time_limit(600);
  882. $_GET['step'] = empty($_GET['step']) ? 0 : (int) $_GET['step'];
  883. $_GET['substep'] = empty($_GET['substep']) ? 0 : (int) $_GET['substep'];
  884. // Don't recall the session just in case.
  885. if ($_GET['step'] == 0 && $_GET['substep'] == 0)
  886. {
  887. unset($_SESSION['attachments_to_fix'], $_SESSION['attachments_to_fix2']);
  888. // If we're actually fixing stuff - work out what.
  889. if (isset($_GET['fixErrors']))
  890. {
  891. // Nothing?
  892. if (empty($_POST['to_fix']))
  893. redirectexit('action=admin;area=manageattachments;sa=maintenance');
  894. $_SESSION['attachments_to_fix'] = array();
  895. // @todo No need to do this I think.
  896. foreach ($_POST['to_fix'] as $key => $value)
  897. $_SESSION['attachments_to_fix'][] = $value;
  898. }
  899. }
  900. // All the valid problems are here:
  901. $context['repair_errors'] = array(
  902. 'missing_thumbnail_parent' => 0,
  903. 'parent_missing_thumbnail' => 0,
  904. 'file_missing_on_disk' => 0,
  905. 'file_wrong_size' => 0,
  906. 'file_size_of_zero' => 0,
  907. 'attachment_no_msg' => 0,
  908. 'avatar_no_member' => 0,
  909. 'wrong_folder' => 0,
  910. 'files_without_attachment' => 0,
  911. );
  912. $to_fix = !empty($_SESSION['attachments_to_fix']) ? $_SESSION['attachments_to_fix'] : array();
  913. $context['repair_errors'] = isset($_SESSION['attachments_to_fix2']) ? $_SESSION['attachments_to_fix2'] : $context['repair_errors'];
  914. $fix_errors = isset($_GET['fixErrors']) ? true : false;
  915. // Get stranded thumbnails.
  916. if ($_GET['step'] <= 0)
  917. {
  918. $result = $smcFunc['db_query']('', '
  919. SELECT MAX(id_attach)
  920. FROM {db_prefix}attachments
  921. WHERE attachment_type = {int:thumbnail}',
  922. array(
  923. 'thumbnail' => 3,
  924. )
  925. );
  926. list ($thumbnails) = $smcFunc['db_fetch_row']($result);
  927. $smcFunc['db_free_result']($result);
  928. for (; $_GET['substep'] < $thumbnails; $_GET['substep'] += 500)
  929. {
  930. $to_remove = array();
  931. $result = $smcFunc['db_query']('', '
  932. SELECT thumb.id_attach, thumb.id_folder, thumb.filename, thumb.file_hash
  933. FROM {db_prefix}attachments AS thumb
  934. LEFT JOIN {db_prefix}attachments AS tparent ON (tparent.id_thumb = thumb.id_attach)
  935. WHERE thumb.id_attach BETWEEN {int:substep} AND {int:substep} + 499
  936. AND thumb.attachment_type = {int:thumbnail}
  937. AND tparent.id_attach IS NULL',
  938. array(
  939. 'thumbnail' => 3,
  940. 'substep' => $_GET['substep'],
  941. )
  942. );
  943. while ($row = $smcFunc['db_fetch_assoc']($result))
  944. {
  945. // Only do anything once... just in case
  946. if (!isset($to_remove[$row['id_attach']]))
  947. {
  948. $to_remove[$row['id_attach']] = $row['id_attach'];
  949. $context['repair_errors']['missing_thumbnail_parent']++;
  950. // If we are repairing remove the file from disk now.
  951. if ($fix_errors && in_array('missing_thumbnail_parent', $to_fix))
  952. {
  953. $filename = getAttachmentFilename($row['filename'], $row['id_attach'], $row['id_folder'], false, $row['file_hash']);
  954. @unlink($filename);
  955. }
  956. }
  957. }
  958. if ($smcFunc['db_num_rows']($result) != 0)
  959. $to_fix[] = 'missing_thumbnail_parent';
  960. $smcFunc['db_free_result']($result);
  961. // Do we need to delete what we have?
  962. if ($fix_errors && !empty($to_remove) && in_array('missing_thumbnail_parent', $to_fix))
  963. $smcFunc['db_query']('', '
  964. DELETE FROM {db_prefix}attachments
  965. WHERE id_attach IN ({array_int:to_remove})
  966. AND attachment_type = {int:attachment_type}',
  967. array(
  968. 'to_remove' => $to_remove,
  969. 'attachment_type' => 3,
  970. )
  971. );
  972. pauseAttachmentMaintenance($to_fix, $thumbnails);
  973. }
  974. $_GET['step'] = 1;
  975. $_GET['substep'] = 0;
  976. pauseAttachmentMaintenance($to_fix);
  977. }
  978. // Find parents which think they have thumbnails, but actually, don't.
  979. if ($_GET['step'] <= 1)
  980. {
  981. $result = $smcFunc['db_query']('', '
  982. SELECT MAX(id_attach)
  983. FROM {db_prefix}attachments
  984. WHERE id_thumb != {int:no_thumb}',
  985. array(
  986. 'no_thumb' => 0,
  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_update = array();
  994. $result = $smcFunc['db_query']('', '
  995. SELECT a.id_attach
  996. FROM {db_prefix}attachments AS a
  997. LEFT JOIN {db_prefix}attachments AS thumb ON (thumb.id_attach = a.id_thumb)
  998. WHERE a.id_attach BETWEEN {int:substep} AND {int:substep} + 499
  999. AND a.id_thumb != {int:no_thumb}
  1000. AND thumb.id_attach IS NULL',
  1001. array(
  1002. 'no_thumb' => 0,
  1003. 'substep' => $_GET['substep'],
  1004. )
  1005. );
  1006. while ($row = $smcFunc['db_fetch_assoc']($result))
  1007. {
  1008. $to_update[] = $row['id_attach'];
  1009. $context['repair_errors']['parent_missing_thumbnail']++;
  1010. }
  1011. if ($smcFunc['db_num_rows']($result) != 0)
  1012. $to_fix[] = 'parent_missing_thumbnail';
  1013. $smcFunc['db_free_result']($result);
  1014. // Do we need to delete what we have?
  1015. if ($fix_errors && !empty($to_update) && in_array('parent_missing_thumbnail', $to_fix))
  1016. $smcFunc['db_query']('', '
  1017. UPDATE {db_prefix}attachments
  1018. SET id_thumb = {int:no_thumb}
  1019. WHERE id_attach IN ({array_int:to_update})',
  1020. array(
  1021. 'to_update' => $to_update,
  1022. 'no_thumb' => 0,
  1023. )
  1024. );
  1025. pauseAttachmentMaintenance($to_fix, $thumbnails);
  1026. }
  1027. $_GET['step'] = 2;
  1028. $_GET['substep'] = 0;
  1029. pauseAttachmentMaintenance($to_fix);
  1030. }
  1031. // This may take forever I'm afraid, but life sucks... recount EVERY attachments!
  1032. if ($_GET['step'] <= 2)
  1033. {
  1034. $result = $smcFunc['db_query']('', '
  1035. SELECT MAX(id_attach)
  1036. FROM {db_prefix}attachments',
  1037. array(
  1038. )
  1039. );
  1040. list ($thumbnails) = $smcFunc['db_fetch_row']($result);
  1041. $smcFunc['db_free_result']($result);
  1042. for (; $_GET['substep'] < $thumbnails; $_GET['substep'] += 250)
  1043. {
  1044. $to_remove = array();
  1045. $errors_found = array();
  1046. $result = $smcFunc['db_query']('', '
  1047. SELECT id_attach, id_folder, filename, file_hash, size, attachment_type
  1048. FROM {db_prefix}attachments
  1049. WHERE id_attach BETWEEN {int:substep} AND {int:substep} + 249',
  1050. array(
  1051. 'substep' => $_GET['substep'],
  1052. )
  1053. );
  1054. while ($row = $smcFunc['db_fetch_assoc']($result))
  1055. {
  1056. // Get the filename.
  1057. if ($row['attachment_type'] == 1)
  1058. $filename = $modSettings['custom_avatar_dir'] . '/' . $row['filename'];
  1059. else
  1060. $filename = getAttachmentFilename($row['filename'], $row['id_attach'], $row['id_folder'], false, $row['file_hash']);
  1061. // File doesn't exist?
  1062. if (!file_exists($filename))
  1063. {
  1064. // If we're lucky it might just be in a different folder.
  1065. if (!empty($modSettings['currentAttachmentUploadDir']))
  1066. {
  1067. // Get the attachment name with out the folder.
  1068. $attachment_name = !empty($row['file_hash']) ? $row['id_attach'] . '_' . $row['file_hash'] : getLegacyAttachmentFilename($row['filename'], $row['id_attach'], null, true);
  1069. if (!is_array($modSettings['attachmentUploadDir']))
  1070. $modSettings['attachmentUploadDir'] = unserialize($modSettings['attachmentUploadDir']);
  1071. // Loop through the other folders.
  1072. foreach ($modSettings['attachmentUploadDir'] as $id => $dir)
  1073. if (file_exists($dir . '/' . $attachment_name))
  1074. {
  1075. $context['repair_errors']['wrong_folder']++;
  1076. $errors_found[] = 'wrong_folder';
  1077. // Are we going to fix this now?
  1078. if ($fix_errors && in_array('wrong_folder', $to_fix))
  1079. $smcFunc['db_query']('', '
  1080. UPDATE {db_prefix}attachments
  1081. SET id_folder = {int:new_folder}
  1082. WHERE id_attach = {int:id_attach}',
  1083. array(
  1084. 'new_folder' => $id,
  1085. 'id_attach' => $row['id_attach'],
  1086. )
  1087. );
  1088. continue 2;
  1089. }
  1090. }
  1091. $to_remove[] = $row['id_attach'];
  1092. $context['repair_errors']['file_missing_on_disk']++;
  1093. $errors_found[] = 'file_missing_on_disk';
  1094. }
  1095. elseif (filesize($filename) == 0)
  1096. {
  1097. $context['repair_errors']['file_size_of_zero']++;
  1098. $errors_found[] = 'file_size_of_zero';
  1099. // Fixing?
  1100. if ($fix_errors && in_array('file_size_of_zero', $to_fix))
  1101. {
  1102. $to_remove[] = $row['id_attach'];
  1103. @unlink($filename);
  1104. }
  1105. }
  1106. elseif (filesize($filename) != $row['size'])
  1107. {
  1108. $context['repair_errors']['file_wrong_size']++;
  1109. $errors_found[] = 'file_wrong_size';
  1110. // Fix it here?
  1111. if ($fix_errors && in_array('file_wrong_size', $to_fix))
  1112. {
  1113. $smcFunc['db_query']('', '
  1114. UPDATE {db_prefix}attachments
  1115. SET size = {int:filesize}
  1116. WHERE id_attach = {int:id_attach}',
  1117. array(
  1118. 'filesize' => filesize($filename),
  1119. 'id_attach' => $row['id_attach'],
  1120. )
  1121. );
  1122. }
  1123. }
  1124. }
  1125. if (in_array('file_missing_on_disk', $errors_found))
  1126. $to_fix[] = 'file_missing_on_disk';
  1127. if (in_array('file_size_of_zero', $errors_found))
  1128. $to_fix[] = 'file_size_of_zero';
  1129. if (in_array('file_wrong_size', $errors_found))
  1130. $to_fix[] = 'file_wrong_size';
  1131. if (in_array('wrong_folder', $errors_found))
  1132. $to_fix[] = 'wrong_folder';
  1133. $smcFunc['db_free_result']($result);
  1134. // Do we need to delete what we have?
  1135. if ($fix_errors && !empty($to_remove))
  1136. {
  1137. $smcFunc['db_query']('', '
  1138. DELETE FROM {db_prefix}attachments
  1139. WHERE id_attach IN ({array_int:to_remove})',
  1140. array(
  1141. 'to_remove' => $to_remove,
  1142. )
  1143. );
  1144. $smcFunc['db_query']('', '
  1145. UPDATE {db_prefix}attachments
  1146. SET id_thumb = {int:no_thumb}
  1147. WHERE id_thumb IN ({array_int:to_remove})',
  1148. array(
  1149. 'to_remove' => $to_remove,
  1150. 'no_thumb' => 0,
  1151. )
  1152. );
  1153. }
  1154. pauseAttachmentMaintenance($to_fix, $thumbnails);
  1155. }
  1156. $_GET['step'] = 3;
  1157. $_GET['substep'] = 0;
  1158. pauseAttachmentMaintenance($to_fix);
  1159. }
  1160. // Get avatars with no members associated with them.
  1161. if ($_GET['step'] <= 3)
  1162. {
  1163. $result = $smcFunc['db_query']('', '
  1164. SELECT MAX(id_attach)
  1165. FROM {db_prefix}attachments',
  1166. array(
  1167. )
  1168. );
  1169. list ($thumbnails) = $smcFunc['db_fetch_row']($result);
  1170. $smcFunc['db_free_result']($result);
  1171. for (; $_GET['substep'] < $thumbnails; $_GET['substep'] += 500)
  1172. {
  1173. $to_remove = array();
  1174. $result = $smcFunc['db_query']('', '
  1175. SELECT a.id_attach, a.id_folder, a.filename, a.file_hash, a.attachment_type
  1176. FROM {db_prefix}attachments AS a
  1177. LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = a.id_member)
  1178. WHERE a.id_attach BETWEEN {int:substep} AND {int:substep} + 499
  1179. AND a.id_member != {int:no_member}
  1180. AND a.id_msg = {int:no_msg}
  1181. AND mem.id_member IS NULL',
  1182. array(
  1183. 'no_member' => 0,
  1184. 'no_msg' => 0,
  1185. 'substep' => $_GET['substep'],
  1186. )
  1187. );
  1188. while ($row = $smcFunc['db_fetch_assoc']($result))
  1189. {
  1190. $to_remove[] = $row['id_attach'];
  1191. $context['repair_errors']['avatar_no_member']++;
  1192. // If we are repairing remove the file from disk now.
  1193. if ($fix_errors && in_array('avatar_no_member', $to_fix))
  1194. {
  1195. if ($row['attachment_type'] == 1)
  1196. $filename = $modSettings['custom_avatar_dir'] . '/' . $row['filename'];
  1197. else
  1198. $filename = getAttachmentFilename($row['filename'], $row['id_attach'], $row['id_folder'], false, $row['file_hash']);
  1199. @unlink($filename);
  1200. }
  1201. }
  1202. if ($smcFunc['db_num_rows']($result) != 0)
  1203. $to_fix[] = 'avatar_no_member';
  1204. $smcFunc['db_free_result']($result);
  1205. // Do we need to delete what we have?
  1206. if ($fix_errors && !empty($to_remove) && in_array('avatar_no_member', $to_fix))
  1207. $smcFunc['db_query']('', '
  1208. DELETE FROM {db_prefix}attachments
  1209. WHERE id_attach IN ({array_int:to_remove})
  1210. AND id_member != {int:no_member}
  1211. AND id_msg = {int:no_msg}',
  1212. array(
  1213. 'to_remove' => $to_remove,
  1214. 'no_member' => 0,
  1215. 'no_msg' => 0,
  1216. )
  1217. );
  1218. pauseAttachmentMaintenance($to_fix, $thumbnails);
  1219. }
  1220. $_GET['step'] = 4;
  1221. $_GET['substep'] = 0;
  1222. pauseAttachmentMaintenance($to_fix);
  1223. }
  1224. // What about attachments, who are missing a message :'(
  1225. if ($_GET['step'] <= 4)
  1226. {
  1227. $result = $smcFunc['db_query']('', '
  1228. SELECT MAX(id_attach)
  1229. FROM {db_prefix}attachments',
  1230. array(
  1231. )
  1232. );
  1233. list ($thumbnails) = $smcFunc['db_fetch_row']($result);
  1234. $smcFunc['db_free_result']($result);
  1235. for (; $_GET['substep'] < $thumbnails; $_GET['substep'] += 500)
  1236. {
  1237. $to_remove = array();
  1238. $result = $smcFunc['db_query']('', '
  1239. SELECT a.id_attach, a.id_folder, a.filename, a.file_hash
  1240. FROM {db_prefix}attachments AS a
  1241. LEFT JOIN {db_prefix}messages AS m ON (m.id_msg = a.id_msg)
  1242. WHERE a.id_attach BETWEEN {int:substep} AND {int:substep} + 499
  1243. AND a.id_member = {int:no_member}
  1244. AND a.id_msg != {int:no_msg}
  1245. AND m.id_msg IS NULL',
  1246. array(
  1247. 'no_member' => 0,
  1248. 'no_msg' => 0,
  1249. 'substep' => $_GET['substep'],
  1250. )
  1251. );
  1252. while ($row = $smcFunc['db_fetch_assoc']($result))
  1253. {
  1254. $to_remove[] = $row['id_attach'];
  1255. $context['repair_errors']['attachment_no_msg']++;
  1256. // If we are repairing remove the file from disk now.
  1257. if ($fix_errors && in_array('attachment_no_msg', $to_fix))
  1258. {
  1259. $filename = getAttachmentFilename($row['filename'], $row['id_attach'], $row['id_folder'], false, $row['file_hash']);
  1260. @unlink($filename);
  1261. }
  1262. }
  1263. if ($smcFunc['db_num_rows']($result) != 0)
  1264. $to_fix[] = 'attachment_no_msg';
  1265. $smcFunc['db_free_result']($result);
  1266. // Do we need to delete what we have?
  1267. if ($fix_errors && !empty($to_remove) && in_array('attachment_no_msg', $to_fix))
  1268. $smcFunc['db_query']('', '
  1269. DELETE FROM {db_prefix}attachments
  1270. WHERE id_attach IN ({array_int:to_remove})
  1271. AND id_member = {int:no_member}
  1272. AND id_msg != {int:no_msg}',
  1273. array(
  1274. 'to_remove' => $to_remove,
  1275. 'no_member' => 0,
  1276. 'no_msg' => 0,
  1277. )
  1278. );
  1279. pauseAttachmentMaintenance($to_fix, $thumbnails);
  1280. }
  1281. $_GET['step'] = 5;
  1282. $_GET['substep'] = 0;
  1283. pauseAttachmentMaintenance($to_fix);
  1284. }
  1285. // What about files who are not recorded in the database?
  1286. if ($_GET['step'] <= 5)
  1287. {
  1288. if (!empty($modSettings['currentAttachmentUploadDir']))
  1289. {
  1290. if (!is_array($modSettings['attachmentUploadDir']))
  1291. $modSettings['attachmentUploadDir'] = unserialize($modSettings['attachmentUploadDir']);
  1292. // Just use the current path for temp files.
  1293. $attach_dirs = $modSettings['attachmentUploadDir'];
  1294. }
  1295. else
  1296. {
  1297. $attach_dirs = array($modSettings['attachmentUploadDir']);
  1298. }
  1299. $current_check = 0;
  1300. $max_checks = 500;
  1301. $files_checked = empty($_GET['substep']) ? 0 : $_GET['substep'];
  1302. foreach ($attach_dirs as $attach_dir)
  1303. {
  1304. if ($dir = @opendir($attach_dir))
  1305. {
  1306. while ($file = readdir($dir))
  1307. {
  1308. if ($file == '.' || $file == '..')
  1309. continue;
  1310. if ($files_checked <= $current_check)
  1311. {
  1312. // Temporary file, get rid of it!
  1313. if (strpos($file, 'post_tmp_') !== false)
  1314. {
  1315. // Temp file is more than 5 hours old!
  1316. if (filemtime($attach_dir . '/' . $file) < time() - 18000)
  1317. @unlink($attach_dir . '/' . $file);
  1318. }
  1319. // That should be an attachment, let's check if we have it in the database
  1320. elseif (strpos($file, '_') !== false)
  1321. {
  1322. $attachID = (int) substr($file, 0, strpos($file, '_'));
  1323. if (!empty($attachID))
  1324. {
  1325. $request = $smcFunc['db_query']('', '
  1326. SELECT id_attach
  1327. FROM {db_prefix}attachments
  1328. WHERE id_attach = {int:attachment_id}
  1329. LIMIT 1',
  1330. array(
  1331. 'attachment_id' => $attachID,
  1332. )
  1333. );
  1334. if ($smcFunc['db_num_rows']($request) == 0)
  1335. {
  1336. if ($fix_errors)
  1337. {
  1338. @unlink($attach_dir . '/' . $file);
  1339. }
  1340. else
  1341. {
  1342. $context['repair_errors']['files_without_attachment']++;
  1343. $to_fix[] = 'files_without_attachment';
  1344. }
  1345. }
  1346. $smcFunc['db_free_result']($request);
  1347. }
  1348. }
  1349. }
  1350. $current_check++;
  1351. if ($current_check - $files_checked >= $max_checks)
  1352. pauseAttachmentMaintenance($to_fix);
  1353. }
  1354. closedir($dir);
  1355. }
  1356. }
  1357. $_GET['step'] = 5;
  1358. $_GET['substep'] = 0;
  1359. pauseAttachmentMaintenance($to_fix);
  1360. }
  1361. // Got here we must be doing well - just the template! :D
  1362. $context['page_title'] = $txt['repair_attachments'];
  1363. $context[$context['admin_menu_name']]['current_subsection'] = 'maintenance';
  1364. $context['sub_template'] = 'attachment_repair';
  1365. // What stage are we at?
  1366. $context['completed'] = $fix_errors ? true : false;
  1367. $context['errors_found'] = !empty($to_fix) ? true : false;
  1368. }
  1369. /**
  1370. * Function called in-between each round of attachments and avatar repairs.
  1371. * Called by repairAttachments().
  1372. * If repairAttachments() has more steps added, this function needs updated!
  1373. *
  1374. * @param array $to_fix attachments to fix
  1375. * @param int $max_substep = 0
  1376. */
  1377. function pauseAttachmentMaintenance($to_fix, $max_substep = 0)
  1378. {
  1379. global $context, $txt, $time_start;
  1380. // Try get more time...
  1381. @set_time_limit(600);
  1382. if (function_exists('apache_reset_timeout'))
  1383. @apache_reset_timeout();
  1384. // Have we already used our maximum time?
  1385. if (time() - array_sum(explode(' ', $time_start)) < 3)
  1386. return;
  1387. $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'];
  1388. $context['page_title'] = $txt['not_done_title'];
  1389. $context['continue_post_data'] = '';
  1390. $context['continue_countdown'] = '2';
  1391. $context['sub_template'] = 'not_done';
  1392. // Specific stuff to not break this template!
  1393. $context[$context['admin_menu_name']]['current_subsection'] = 'maintenance';
  1394. // Change these two if more steps are added!
  1395. if (empty($max_substep))
  1396. $context['continue_percent'] = round(($_GET['step'] * 100) / 25);
  1397. else
  1398. $context['continue_percent'] = round(($_GET['step'] * 100 + ($_GET['substep'] * 100) / $max_substep) / 25);
  1399. // Never more than 100%!
  1400. $context['continue_percent'] = min($context['continue_percent'], 100);
  1401. $_SESSION['attachments_to_fix'] = $to_fix;
  1402. $_SESSION['attachments_to_fix2'] = $context['repair_errors'];
  1403. obExit();
  1404. }
  1405. /**
  1406. * Called from a mouse click, works out what we want to do with attachments and actions it.
  1407. */
  1408. function ApproveAttach()
  1409. {
  1410. global $smcFunc;
  1411. // Security is our primary concern...
  1412. checkSession('get');
  1413. // If it approve or delete?
  1414. $is_approve = !isset($_GET['sa']) || $_GET['sa'] != 'reject' ? true : false;
  1415. $attachments = array();
  1416. // If we are approving all ID's in a message , get the ID's.
  1417. if ($_GET['sa'] == 'all' && !empty($_GET['mid']))
  1418. {
  1419. $id_msg = (int) $_GET['mid'];
  1420. $request = $smcFunc['db_query']('', '
  1421. SELECT id_attach
  1422. FROM {db_prefix}attachments
  1423. WHERE id_msg = {int:id_msg}
  1424. AND approved = {int:is_approved}
  1425. AND attachment_type = {int:attachment_type}',
  1426. array(
  1427. 'id_msg' => $id_msg,
  1428. 'is_approved' => 0,
  1429. 'attachment_type' => 0,
  1430. )
  1431. );
  1432. while ($row = $smcFunc['db_fetch_assoc']($request))
  1433. $attachments[] = $row['id_attach'];
  1434. $smcFunc['db_free_result']($request);
  1435. }
  1436. elseif (!empty($_GET['aid']))
  1437. $attachments[] = (int) $_GET['aid'];
  1438. if (empty($attachments))
  1439. fatal_lang_error('no_access', false);
  1440. // Now we have some ID's cleaned and ready to approve, but first - let's check we have permission!
  1441. $allowed_boards = boardsAllowedTo('approve_posts');
  1442. // Validate the attachments exist and are the right approval state.
  1443. $request = $smcFunc['db_query']('', '
  1444. SELECT a.id_attach, m.id_board, m.id_msg, m.id_topic
  1445. FROM {db_prefix}attachments AS a
  1446. INNER JOIN {db_prefix}messages AS m ON (m.id_msg = a.id_msg)
  1447. WHERE a.id_attach IN ({array_int:attachments})
  1448. AND a.attachment_type = {int:attachment_type}
  1449. AND a.approved = {int:is_approved}',
  1450. array(
  1451. 'attachments' => $attachments,
  1452. 'attachment_type' => 0,
  1453. 'is_approved' => 0,
  1454. )
  1455. );
  1456. $attachments = array();
  1457. while ($row = $smcFunc['db_fetch_assoc']($request))
  1458. {
  1459. // We can only add it if we can approve in this board!
  1460. if ($allowed_boards = array(0) || in_array($row['id_board'], $allowed_boards))
  1461. {
  1462. $attachments[] = $row['id_attach'];
  1463. // Also come up witht he redirection URL.
  1464. $redirect = 'topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#msg' . $row['id_msg'];
  1465. }
  1466. }
  1467. $smcFunc['db_free_result']($request);
  1468. if (empty($attachments))
  1469. fatal_lang_error('no_access', false);
  1470. // Finally, we are there. Follow through!
  1471. if ($is_approve)
  1472. {
  1473. // Checked and deemed worthy.
  1474. ApproveAttachments($attachments);
  1475. }
  1476. else
  1477. removeAttachments(array('id_attach' => $attachments, 'do_logging' => true));
  1478. // Return to the topic....
  1479. redirectexit($redirect);
  1480. }
  1481. /**
  1482. * Approve an attachment, or maybe even more - no permission check!
  1483. *
  1484. * @param array $attachments
  1485. */
  1486. function ApproveAttachments($attachments)
  1487. {
  1488. global $smcFunc;
  1489. if (empty($attachments))
  1490. return 0;
  1491. // For safety, check for thumbnails...
  1492. $request = $smcFunc['db_query']('', '
  1493. SELECT
  1494. a.id_attach, a.id_member, IFNULL(thumb.id_attach, 0) AS id_thumb
  1495. FROM {db_prefix}attachments AS a
  1496. LEFT JOIN {db_prefix}attachments AS thumb ON (thumb.id_attach = a.id_thumb)
  1497. WHERE a.id_attach IN ({array_int:attachments})
  1498. AND a.attachment_type = {int:attachment_type}',
  1499. array(
  1500. 'attachments' => $attachments,
  1501. 'attachment_type' => 0,
  1502. )
  1503. );
  1504. $attachments = array();
  1505. while ($row = $smcFunc['db_fetch_assoc']($request))
  1506. {
  1507. // Update the thumbnail too...
  1508. if (!empty($row['id_thumb']))
  1509. $attachments[] = $row['id_thumb'];
  1510. $attachments[] = $row['id_attach'];
  1511. }
  1512. $smcFunc['db_free_result']($request);
  1513. if (empty($attachments))
  1514. return 0;
  1515. // Approving an attachment is not hard - it's easy.
  1516. $smcFunc['db_query']('', '
  1517. UPDATE {db_prefix}attachments
  1518. SET approved = {int:is_approved}
  1519. WHERE id_attach IN ({array_int:attachments})',
  1520. array(
  1521. 'attachments' => $attachments,
  1522. 'is_approved' => 1,
  1523. )
  1524. );
  1525. // In order to log the attachments, we really need their message and filename
  1526. $request = $smcFunc['db_query']('', '
  1527. SELECT m.id_msg, a.filename
  1528. FROM {db_prefix}attachments AS a
  1529. INNER JOIN {db_prefix}messages AS m ON (a.id_msg = m.id_msg)
  1530. WHERE a.id_attach IN ({array_int:attachments})
  1531. AND a.attachment_type = {int:attachment_type}',
  1532. array(
  1533. 'attachments' => $attachments,
  1534. 'attachment_type' => 0,
  1535. )
  1536. );
  1537. while ($row = $smcFunc['db_fetch_assoc']($request))
  1538. logAction(
  1539. 'approve_attach',
  1540. array(
  1541. 'message' => $row['id_msg'],
  1542. 'filename' => preg_replace('~&amp;#(\\d{1,7}|x[0-9a-fA-F]{1,6});~', '&#\\1;', $smcFunc['htmlspecialchars']($row['filename'])),
  1543. )
  1544. );
  1545. $smcFunc['db_free_result']($request);
  1546. // Remove from the approval queue.
  1547. $smcFunc['db_query']('', '
  1548. DELETE FROM {db_prefix}approval_queue
  1549. WHERE id_attach IN ({array_int:attachments})',
  1550. array(
  1551. 'attachments' => $attachments,
  1552. )
  1553. );
  1554. call_integration_hook('integrate_approve_attachments', array($attachments));
  1555. }
  1556. /**
  1557. * This function lists and allows updating of multiple attachments paths.
  1558. */
  1559. function ManageAttachmentPaths()
  1560. {
  1561. global $modSettings, $scripturl, $context, $txt, $sourcedir, $smcFunc;
  1562. // Saving?
  1563. if (isset($_REQUEST['save']))
  1564. {
  1565. checkSession();
  1566. $new_dirs = array();
  1567. foreach ($_POST['dirs'] as $id => $path)
  1568. {
  1569. $id = (int) $id;
  1570. if ($id < 1)
  1571. continue;
  1572. if (empty($path))
  1573. {
  1574. // Let's not try to delete a path with files in it.
  1575. $request = $smcFunc['db_query']('', '
  1576. SELECT COUNT(id_attach) AS num_attach
  1577. FROM {db_prefix}attachments
  1578. WHERE id_folder = {int:id_folder}',
  1579. array(
  1580. 'id_folder' => (int) $id,
  1581. )
  1582. );
  1583. list ($num_attach) = $smcFunc['db_fetch_row']($request);
  1584. $smcFunc['db_free_result']($request);
  1585. // It's safe to delete.
  1586. if ($num_attach == 0)
  1587. continue;
  1588. }
  1589. $new_dirs[$id] = $path;
  1590. }
  1591. // We need to make sure the current directory is right.
  1592. $_POST['current_dir'] = (int) $_POST['current_dir'];
  1593. if (empty($_POST['current_dir']) || empty($new_dirs[$_POST['current_dir']]))
  1594. fatal_lang_error('attach_path_current_bad', false);
  1595. // Going back to just one path?
  1596. if (count($new_dirs) == 1)
  1597. {
  1598. // We might need to reset the paths. This loop will just loop through once.
  1599. foreach ($new_dirs as $id => $dir)
  1600. {
  1601. if ($id != 1)
  1602. $smcFunc['db_query']('', '
  1603. UPDATE {db_prefix}attachments
  1604. SET id_folder = {int:default_folder}
  1605. WHERE id_folder = {int:current_folder}',
  1606. array(
  1607. 'default_folder' => 1,
  1608. 'current_folder' => $id,
  1609. )
  1610. );
  1611. updateSettings(array(
  1612. 'currentAttachmentUploadDir' => 0,
  1613. 'attachmentUploadDir' => $dir,
  1614. ));
  1615. }
  1616. }
  1617. else
  1618. // Save it to the database.
  1619. updateSettings(array(
  1620. 'currentAttachmentUploadDir' => $_POST['current_dir'],
  1621. 'attachmentUploadDir' => serialize($new_dirs),
  1622. ));
  1623. }
  1624. // Are they here for the first time?
  1625. if (empty($modSettings['currentAttachmentUploadDir']))
  1626. {
  1627. $modSettings['attachmentUploadDir'] = array(
  1628. 1 => $modSettings['attachmentUploadDir']
  1629. );
  1630. $modSettings['currentAttachmentUploadDir'] = 1;
  1631. }
  1632. // Otherwise just load up their attachment paths.
  1633. else
  1634. $modSettings['attachmentUploadDir'] = unserialize($modSettings['attachmentUploadDir']);
  1635. $listOptions = array(
  1636. 'id' => 'attach_paths',
  1637. 'base_href' => $scripturl . '?action=admin;area=manageattachments;sa=attachpaths;' . $context['session_var'] . '=' . $context['session_id'],
  1638. 'title' => $txt['attach_paths'],
  1639. 'get_items' => array(
  1640. 'function' => 'list_getAttachDirs',
  1641. ),
  1642. 'columns' => array(
  1643. 'current_dir' => array(
  1644. 'header' => array(
  1645. 'value' => $txt['attach_current_dir'],
  1646. ),
  1647. 'data' => array(
  1648. 'function' => create_function('$rowData', '
  1649. return \'<input type="radio" name="current_dir" value="\' . $rowData[\'id\'] . \'" \' . ($rowData[\'current\'] ? \'checked="checked"\' : \'\') . \' class="input_radio" />\';
  1650. '),
  1651. 'style' => 'text-align: center; width: 15%;',
  1652. ),
  1653. ),
  1654. 'path' => array(
  1655. 'header' => array(
  1656. 'value' => $txt['attach_path'],
  1657. ),
  1658. 'data' => array(
  1659. 'function' => create_function('$rowData', '
  1660. return \'<input type="text" size="30" name="dirs[\' . $rowData[\'id\'] . \']" value="\' . $rowData[\'path\'] . \'" class="input_text" style="width: 100%" />\';
  1661. '),
  1662. 'style' => 'text-align: center; width: 30%;',
  1663. ),
  1664. ),
  1665. 'current_size' => array(
  1666. 'header' => array(
  1667. 'value' => $txt['attach_current_size'],
  1668. ),
  1669. 'data' => array(
  1670. 'db' => 'current_size',
  1671. 'style' => 'text-align: center; width: 15%;',
  1672. ),
  1673. ),
  1674. 'num_files' => array(
  1675. 'header' => array(
  1676. 'value' => $txt['attach_num_files'],
  1677. ),
  1678. 'data' => array(
  1679. 'db' => 'num_files',
  1680. 'style' => 'text-align: center; width: 15%;',
  1681. ),
  1682. ),
  1683. 'status' => array(
  1684. 'header' => array(
  1685. 'value' => $txt['attach_dir_status'],
  1686. ),
  1687. 'data' => array(
  1688. 'db' => 'status',
  1689. 'style' => 'text-align: center; width: 25%;',
  1690. ),
  1691. ),
  1692. ),
  1693. 'form' => array(
  1694. 'href' => $scripturl . '?action=admin;area=manageattachments;sa=attachpaths;' . $context['session_var'] . '=' . $context['session_id'],
  1695. ),
  1696. 'additional_rows' => array(
  1697. array(
  1698. 'position' => 'below_table_data',
  1699. '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" />',
  1700. 'style' => 'text-align: right;',
  1701. ),
  1702. ),
  1703. );
  1704. require_once($sourcedir . '/Subs-List.php');
  1705. createList($listOptions);
  1706. // Fix up our template.
  1707. $context[$context['admin_menu_name']]['current_subsection'] = 'attachments';
  1708. $context['page_title'] = $txt['attach_path_manage'];
  1709. $context['sub_template'] = 'attachment_paths';
  1710. }
  1711. /**
  1712. * Prepare the actual attachment directories to be displayed in the list.
  1713. */
  1714. function list_getAttachDirs()
  1715. {
  1716. global $smcFunc, $modSettings, $context, $txt;
  1717. // The dirs should already have been unserialized but just in case...
  1718. if (!is_array($modSettings['attachmentUploadDir']))
  1719. $modSettings['attachmentUploadDir'] = unserialize($modSettings['attachmentUploadDir']);
  1720. $request = $smcFunc['db_query']('', '
  1721. SELECT id_folder, COUNT(id_attach) AS num_attach
  1722. FROM {db_prefix}attachments' . (empty($modSettings['custom_avatar_enabled']) ? '' : '
  1723. WHERE attachment_type != {int:type_avatar}') . '
  1724. GROUP BY id_folder',
  1725. array(
  1726. 'type_avatar' => 1,
  1727. )
  1728. );
  1729. $expected_files = array();
  1730. while ($row = $smcFunc['db_fetch_assoc']($request))
  1731. $expected_files[$row['id_folder']] = $row['num_attach'];
  1732. $smcFunc['db_free_result']($request);
  1733. $attachdirs = array();
  1734. foreach ($modSettings['attachmentUploadDir'] as $id => $dir)
  1735. {
  1736. // If there aren't any attachments in this directory this won't exist.
  1737. if (!isset($expected_files[$id]))
  1738. $expected_files[$id] = 0;
  1739. // Check if the directory is doing okay.
  1740. list ($status, $error, $size) = attachDirStatus($dir, $expected_files[$id]);
  1741. $attachdirs[] = array(
  1742. 'id' => $id,
  1743. 'current' => $id == $modSettings['currentAttachmentUploadDir'],
  1744. 'path' => $dir,
  1745. 'current_size' => $size,
  1746. 'num_files' => $expected_files[$id],
  1747. 'status' => ($error ? '<span class="error">' : '') . sprintf($txt['attach_dir_' . $status], $context['session_id'], $context['session_var']) . ($error ? '</span>' : ''),
  1748. );
  1749. }
  1750. // Just stick a new directory on at the bottom.
  1751. if (isset($_REQUEST['new_path']))
  1752. $attachdirs[] = array(
  1753. 'id' => max(array_merge(array_keys($expected_files), array_keys($modSettings['attachmentUploadDir']))) + 1,
  1754. 'current' => false,
  1755. 'path' => '',
  1756. 'current_size' => '',
  1757. 'num_files' => '',
  1758. 'status' => '',
  1759. );
  1760. return $attachdirs;
  1761. }
  1762. /**
  1763. * Checks the status of an attachment directory and returns an array
  1764. * of the status key, if that status key signifies an error, and
  1765. * the folder size.
  1766. *
  1767. * @param string $dir
  1768. * @param int $expected_files
  1769. */
  1770. function attachDirStatus($dir, $expected_files)
  1771. {
  1772. if (!is_dir($dir))
  1773. return array('does_not_exist', true, '');
  1774. elseif (!is_writable($dir))
  1775. return array('not_writable', true, '');
  1776. // Everything is okay so far, start to scan through the directory.
  1777. $dir_size = 0;
  1778. $num_files = 0;
  1779. $dir_handle = dir($dir);
  1780. while ($file = $dir_handle->read())
  1781. {
  1782. // Now do we have a real file here?
  1783. if (in_array($file, array('.', '..', '.htaccess', 'index.php')))
  1784. continue;
  1785. $dir_size += filesize($dir . '/' . $file);
  1786. $num_files++;
  1787. }
  1788. $dir_handle->close();
  1789. $dir_size = round($dir_size / 1024, 2);
  1790. if ($num_files < $expected_files)
  1791. return array('files_missing', true, $dir_size);
  1792. // Empty?
  1793. elseif ($expected_files == 0)
  1794. return array('unused', false, $dir_size);
  1795. // All good!
  1796. else
  1797. return array('ok', false, $dir_size);
  1798. }
  1799. ?>