ManageAttachments.php 82 KB

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