2
0

Subs-Attachments.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849
  1. <?php
  2. /**
  3. * This file handles the uploading and creation of attachments
  4. * as well as the auto management of the attachment directories.
  5. *
  6. * Simple Machines Forum (SMF)
  7. *
  8. * @package SMF
  9. * @author Simple Machines
  10. * @copyright 2014 Simple Machines and individual contributors
  11. * @license http://www.simplemachines.org/about/smf/license.php BSD
  12. *
  13. * @version 2.1 Alpha 1
  14. */
  15. if (!defined('SMF'))
  16. die('No direct access...');
  17. /**
  18. * Check if the current directory is still valid or not.
  19. * If not creates the new directory
  20. *
  21. * @return (bool) false if any error occurred
  22. */
  23. function automanage_attachments_check_directory()
  24. {
  25. global $boarddir, $modSettings, $context;
  26. // Not pretty, but since we don't want folders created for every post. It'll do unless a better solution can be found.
  27. if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'admin')
  28. $doit = true;
  29. elseif (empty($modSettings['automanage_attachments']))
  30. return;
  31. elseif (!isset($_FILES))
  32. return;
  33. elseif (isset($_FILES['attachment']))
  34. foreach ($_FILES['attachment']['tmp_name'] as $dummy)
  35. if (!empty($dummy))
  36. {
  37. $doit = true;
  38. break;
  39. }
  40. if (!isset($doit))
  41. return;
  42. $year = date('Y');
  43. $month = date('m');
  44. $day = date('d');
  45. $rand = md5(mt_rand());
  46. $rand1 = $rand[1];
  47. $rand = $rand[0];
  48. if (!empty($modSettings['attachment_basedirectories']) && !empty($modSettings['use_subdirectories_for_attachments']))
  49. {
  50. if (!is_array($modSettings['attachment_basedirectories']))
  51. $modSettings['attachment_basedirectories'] = unserialize($modSettings['attachment_basedirectories']);
  52. $base_dir = array_search($modSettings['basedirectory_for_attachments'], $modSettings['attachment_basedirectories']);
  53. }
  54. else
  55. $base_dir = 0;
  56. if ($modSettings['automanage_attachments'] == 1)
  57. {
  58. if (!isset($modSettings['last_attachments_directory']))
  59. $modSettings['last_attachments_directory'] = array();
  60. if (!is_array($modSettings['last_attachments_directory']))
  61. $modSettings['last_attachments_directory'] = unserialize($modSettings['last_attachments_directory']);
  62. if (!isset($modSettings['last_attachments_directory'][$base_dir]))
  63. $modSettings['last_attachments_directory'][$base_dir] = 0;
  64. }
  65. $basedirectory = (!empty($modSettings['use_subdirectories_for_attachments']) ? ($modSettings['basedirectory_for_attachments']) : $boarddir);
  66. //Just to be sure: I don't want directory separators at the end
  67. $sep = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') ? '\/' : DIRECTORY_SEPARATOR;
  68. $basedirectory = rtrim($basedirectory, $sep);
  69. switch ($modSettings['automanage_attachments'])
  70. {
  71. case 1:
  72. $updir = $basedirectory . DIRECTORY_SEPARATOR . 'attachments_' . (isset($modSettings['last_attachments_directory'][$base_dir]) ? $modSettings['last_attachments_directory'][$base_dir] : 0);
  73. break;
  74. case 2:
  75. $updir = $basedirectory . DIRECTORY_SEPARATOR . $year;
  76. break;
  77. case 3:
  78. $updir = $basedirectory . DIRECTORY_SEPARATOR . $year . DIRECTORY_SEPARATOR . $month;
  79. break;
  80. case 4:
  81. $updir = $basedirectory . DIRECTORY_SEPARATOR . (empty($modSettings['use_subdirectories_for_attachments']) ? 'attachments-' : 'random_') . $rand;
  82. break;
  83. case 5:
  84. $updir = $basedirectory . DIRECTORY_SEPARATOR . (empty($modSettings['use_subdirectories_for_attachments']) ? 'attachments-' : 'random_') . $rand . DIRECTORY_SEPARATOR . $rand1;
  85. break;
  86. default :
  87. $updir = '';
  88. }
  89. if (!is_array($modSettings['attachmentUploadDir']))
  90. $modSettings['attachmentUploadDir'] = unserialize($modSettings['attachmentUploadDir']);
  91. if (!in_array($updir, $modSettings['attachmentUploadDir']) && !empty($updir))
  92. $outputCreation = automanage_attachments_create_directory($updir);
  93. elseif (in_array($updir, $modSettings['attachmentUploadDir']))
  94. $outputCreation = true;
  95. if ($outputCreation)
  96. {
  97. $modSettings['currentAttachmentUploadDir'] = array_search($updir, $modSettings['attachmentUploadDir']);
  98. $context['attach_dir'] = $modSettings['attachmentUploadDir'][$modSettings['currentAttachmentUploadDir']];
  99. updateSettings(array(
  100. 'currentAttachmentUploadDir' => $modSettings['currentAttachmentUploadDir'],
  101. ));
  102. }
  103. return $outputCreation;
  104. }
  105. /**
  106. * Creates a directory
  107. *
  108. * @param $updir: the directory to be created
  109. *
  110. * @return (bool) false on errors
  111. */
  112. function automanage_attachments_create_directory($updir)
  113. {
  114. global $modSettings, $initial_error, $context, $boarddir;
  115. $tree = get_directory_tree_elements($updir);
  116. $count = count($tree);
  117. $directory = attachments_init_dir($tree, $count);
  118. if ($directory === false)
  119. {
  120. // Maybe it's just the folder name
  121. $tree = get_directory_tree_elements($boarddir . DIRECTORY_SEPARATOR . $updir);
  122. $count = count($tree);
  123. $directory = attachments_init_dir($tree, $count);
  124. if ($directory === false)
  125. return false;
  126. }
  127. $directory .= DIRECTORY_SEPARATOR . array_shift($tree);
  128. while (!@is_dir($directory) || $count != -1)
  129. {
  130. if (!@is_dir($directory))
  131. {
  132. if (!@mkdir($directory,0755))
  133. {
  134. $context['dir_creation_error'] = 'attachments_no_create';
  135. return false;
  136. }
  137. }
  138. $directory .= DIRECTORY_SEPARATOR . array_shift($tree);
  139. $count--;
  140. }
  141. // @todo: chmod (especially with some servers) is usually bad
  142. if (!is_writable($directory))
  143. {
  144. chmod($directory, 0755);
  145. if (!is_writable($directory))
  146. {
  147. chmod($directory, 0775);
  148. if (!is_writable($directory))
  149. {
  150. chmod($directory, 0777);
  151. if (!is_writable($directory))
  152. {
  153. $context['dir_creation_error'] = 'attachments_no_write';
  154. return false;
  155. }
  156. }
  157. }
  158. }
  159. // Everything seems fine...let's create the .htaccess
  160. if (!file_exists($directory . DIRECTORY_SEPARATOR . '.htaccess'))
  161. secureDirectory($updir, true);
  162. $sep = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') ? '\/' : DIRECTORY_SEPARATOR;
  163. $updir = rtrim($updir, $sep);
  164. // Only update if it's a new directory
  165. if (!in_array($updir, $modSettings['attachmentUploadDir']))
  166. {
  167. $modSettings['currentAttachmentUploadDir'] = max(array_keys($modSettings['attachmentUploadDir'])) + 1;
  168. $modSettings['attachmentUploadDir'][$modSettings['currentAttachmentUploadDir']] = $updir;
  169. updateSettings(array(
  170. 'attachmentUploadDir' => serialize($modSettings['attachmentUploadDir']),
  171. 'currentAttachmentUploadDir' => $modSettings['currentAttachmentUploadDir'],
  172. ), true);
  173. $modSettings['attachmentUploadDir'] = unserialize($modSettings['attachmentUploadDir']);
  174. }
  175. $context['attach_dir'] = $modSettings['attachmentUploadDir'][$modSettings['currentAttachmentUploadDir']];
  176. return true;
  177. }
  178. /**
  179. * Called when a directory space limit is reached.
  180. * Creates a new directory and increments the directory suffix number.
  181. *
  182. * @return (bool) false on erros
  183. */
  184. function automanage_attachments_by_space()
  185. {
  186. global $modSettings, $boarddir, $context;
  187. if (!isset($modSettings['automanage_attachments']) || (!empty($modSettings['automanage_attachments']) && $modSettings['automanage_attachments'] != 1))
  188. return;
  189. $basedirectory = !empty($modSettings['use_subdirectories_for_attachments']) ? $modSettings['basedirectory_for_attachments'] : $boarddir;
  190. //Just to be sure: I don't want directory separators at the end
  191. $sep = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') ? '\/' : DIRECTORY_SEPARATOR;
  192. $basedirectory = rtrim($basedirectory, $sep);
  193. // Get the current base directory
  194. if (!empty($modSettings['use_subdirectories_for_attachments']) && !empty($modSettings['attachment_basedirectories']))
  195. {
  196. $base_dir = array_search($modSettings['basedirectory_for_attachments'], $modSettings['attachment_basedirectories']);
  197. $base_dir = !empty($modSettings['automanage_attachments']) ? $base_dir : 0;
  198. }
  199. else
  200. $base_dir = 0;
  201. // Get the last attachment directory for that base directory
  202. if (empty($modSettings['last_attachments_directory'][$base_dir]))
  203. $modSettings['last_attachments_directory'][$base_dir] = 0;
  204. // And increment it.
  205. $modSettings['last_attachments_directory'][$base_dir]++;
  206. $updir = $basedirectory . DIRECTORY_SEPARATOR . 'attachments_' . $modSettings['last_attachments_directory'][$base_dir];
  207. if (automanage_attachments_create_directory($updir))
  208. {
  209. $modSettings['currentAttachmentUploadDir'] = array_search($updir, $modSettings['attachmentUploadDir']);
  210. updateSettings(array(
  211. 'last_attachments_directory' => serialize($modSettings['last_attachments_directory']),
  212. 'currentAttachmentUploadDir' => $modSettings['currentAttachmentUploadDir'],
  213. ));
  214. $modSettings['last_attachments_directory'] = unserialize($modSettings['last_attachments_directory']);
  215. return true;
  216. }
  217. else
  218. return false;
  219. }
  220. /**
  221. * Split a path into a list of all directories and subdirectories
  222. *
  223. * @param $directory a path
  224. *
  225. * @return (mixed) an array of all the directories and subdirectories or false on failure
  226. */
  227. function get_directory_tree_elements ($directory)
  228. {
  229. /*
  230. In Windows server both \ and / can be used as directory separators in paths
  231. In Linux (and presumably *nix) servers \ can be part of the name
  232. So for this reasons:
  233. * in Windows we need to explode for both \ and /
  234. * while in linux should be safe to explode only for / (aka DIRECTORY_SEPARATOR)
  235. */
  236. if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN')
  237. $tree = preg_split('#[\\\/]#', $directory);
  238. else
  239. {
  240. if (substr($directory, 0, 1) != DIRECTORY_SEPARATOR)
  241. return false;
  242. $tree = explode(DIRECTORY_SEPARATOR, trim($directory,DIRECTORY_SEPARATOR));
  243. }
  244. return $tree;
  245. }
  246. /**
  247. * Return the first part of a path (i.e. c:\ or / + the first directory), used by automanage_attachments_create_directory
  248. *
  249. * @param $tree an array
  250. * @param $count the number of elements in $tree
  251. *
  252. * @return (string)
  253. */
  254. function attachments_init_dir (&$tree, &$count)
  255. {
  256. $directory = '';
  257. // If on Windows servers the first part of the path is the drive (e.g. "C:")
  258. if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN')
  259. {
  260. //Better be sure that the first part of the path is actually a drive letter...
  261. //...even if, I should check this in the admin page...isn't it?
  262. //...NHAAA Let's leave space for users' complains! :P
  263. if (preg_match('/^[a-z]:$/i',$tree[0]))
  264. $directory = array_shift($tree);
  265. else
  266. return false;
  267. $count--;
  268. }
  269. return $directory;
  270. }
  271. /**
  272. * Moves an attachment to the proper directory and set the relevant data into $_SESSION['temp_attachments']
  273. */
  274. function processAttachments()
  275. {
  276. global $context, $modSettings, $smcFunc, $txt, $user_info;
  277. // Make sure we're uploading to the right place.
  278. if (!empty($modSettings['automanage_attachments']))
  279. automanage_attachments_check_directory();
  280. if (!is_array($modSettings['attachmentUploadDir']))
  281. $modSettings['attachmentUploadDir'] = unserialize($modSettings['attachmentUploadDir']);
  282. $context['attach_dir'] = $modSettings['attachmentUploadDir'][$modSettings['currentAttachmentUploadDir']];
  283. // Is the attachments folder actualy there?
  284. if (!empty($context['dir_creation_error']))
  285. $initial_error = $context['dir_creation_error'];
  286. elseif (!is_dir($context['attach_dir']))
  287. {
  288. $initial_error = 'attach_folder_warning';
  289. log_error(sprintf($txt['attach_folder_admin_warning'], $context['attach_dir']), 'critical');
  290. }
  291. if (!isset($initial_error) && !isset($context['attachments']))
  292. {
  293. // If this isn't a new post, check the current attachments.
  294. if (isset($_REQUEST['msg']))
  295. {
  296. $request = $smcFunc['db_query']('', '
  297. SELECT COUNT(*), SUM(size)
  298. FROM {db_prefix}attachments
  299. WHERE id_msg = {int:id_msg}
  300. AND attachment_type = {int:attachment_type}',
  301. array(
  302. 'id_msg' => (int) $_REQUEST['msg'],
  303. 'attachment_type' => 0,
  304. )
  305. );
  306. list ($context['attachments']['quantity'], $context['attachments']['total_size']) = $smcFunc['db_fetch_row']($request);
  307. $smcFunc['db_free_result']($request);
  308. }
  309. else
  310. $context['attachments'] = array(
  311. 'quantity' => 0,
  312. 'total_size' => 0,
  313. );
  314. }
  315. // Hmm. There are still files in session.
  316. $ignore_temp = false;
  317. if (!empty($_SESSION['temp_attachments']['post']['files']) && count($_SESSION['temp_attachments']) > 1)
  318. {
  319. // Let's try to keep them. But...
  320. $ignore_temp = true;
  321. // If new files are being added. We can't ignore those
  322. foreach ($_FILES['attachment']['tmp_name'] as $dummy)
  323. if (!empty($dummy))
  324. {
  325. $ignore_temp = false;
  326. break;
  327. }
  328. // Need to make space for the new files. So, bye bye.
  329. if (!$ignore_temp)
  330. {
  331. foreach ($_SESSION['temp_attachments'] as $attachID => $attachment)
  332. if (strpos($attachID, 'post_tmp_' . $user_info['id']) !== false)
  333. unlink($attachment['tmp_name']);
  334. $context['we_are_history'] = $txt['error_temp_attachments_flushed'];
  335. $_SESSION['temp_attachments'] = array();
  336. }
  337. }
  338. if (!isset($_FILES['attachment']['name']))
  339. $_FILES['attachment']['tmp_name'] = array();
  340. if (!isset($_SESSION['temp_attachments']))
  341. $_SESSION['temp_attachments'] = array();
  342. // Remember where we are at. If it's anywhere at all.
  343. if (!$ignore_temp)
  344. $_SESSION['temp_attachments']['post'] = array(
  345. 'msg' => !empty($_REQUEST['msg']) ? $_REQUEST['msg'] : 0,
  346. 'last_msg' => !empty($_REQUEST['last_msg']) ? $_REQUEST['last_msg'] : 0,
  347. 'topic' => !empty($topic) ? $topic : 0,
  348. 'board' => !empty($board) ? $board : 0,
  349. );
  350. // If we have an itital error, lets just display it.
  351. if (!empty($initial_error))
  352. {
  353. $_SESSION['temp_attachments']['initial_error'] = $initial_error;
  354. // And delete the files 'cos they ain't going nowhere.
  355. foreach ($_FILES['attachment']['tmp_name'] as $n => $dummy)
  356. if (file_exists($_FILES['attachment']['tmp_name'][$n]))
  357. unlink($_FILES['attachment']['tmp_name'][$n]);
  358. $_FILES['attachment']['tmp_name'] = array();
  359. }
  360. // Loop through $_FILES['attachment'] array and move each file to the current attachments folder.
  361. foreach ($_FILES['attachment']['tmp_name'] as $n => $dummy)
  362. {
  363. if ($_FILES['attachment']['name'][$n] == '')
  364. continue;
  365. // First, let's first check for PHP upload errors.
  366. $errors = array();
  367. if (!empty($_FILES['attachment']['error'][$n]))
  368. {
  369. if ($_FILES['attachment']['error'][$n] == 2)
  370. $errors[] = array('file_too_big', array($modSettings['attachmentSizeLimit']));
  371. elseif ($_FILES['attachment']['error'][$n] == 6)
  372. log_error($_FILES['attachment']['name'][$n] . ': ' . $txt['php_upload_error_6'], 'critical');
  373. else
  374. log_error($_FILES['attachment']['name'][$n] . ': ' . $txt['php_upload_error_' . $_FILES['attachment']['error'][$n]]);
  375. if (empty($errors))
  376. $errors[] = 'attach_php_error';
  377. }
  378. // Try to move and rename the file before doing any more checks on it.
  379. $attachID = 'post_tmp_' . $user_info['id'] . '_' . md5(mt_rand());
  380. $destName = $context['attach_dir'] . '/' . $attachID;
  381. if (empty($errors))
  382. {
  383. $_SESSION['temp_attachments'][$attachID] = array(
  384. 'name' => $smcFunc['htmlspecialchars'](basename($_FILES['attachment']['name'][$n])),
  385. 'tmp_name' => $destName,
  386. 'size' => $_FILES['attachment']['size'][$n],
  387. 'type' => $_FILES['attachment']['type'][$n],
  388. 'id_folder' => $modSettings['currentAttachmentUploadDir'],
  389. 'errors' => array(),
  390. );
  391. // Move the file to the attachments folder with a temp name for now.
  392. if (@move_uploaded_file($_FILES['attachment']['tmp_name'][$n], $destName))
  393. @chmod($destName, 0644);
  394. else
  395. {
  396. $_SESSION['temp_attachments'][$attachID]['errors'][] = 'attach_timeout';
  397. if (file_exists($_FILES['attachment']['tmp_name'][$n]))
  398. unlink($_FILES['attachment']['tmp_name'][$n]);
  399. }
  400. }
  401. else
  402. {
  403. $_SESSION['temp_attachments'][$attachID] = array(
  404. 'name' => $smcFunc['htmlspecialchars'](basename($_FILES['attachment']['name'][$n])),
  405. 'tmp_name' => $destName,
  406. 'errors' => $errors,
  407. );
  408. if (file_exists($_FILES['attachment']['tmp_name'][$n]))
  409. unlink($_FILES['attachment']['tmp_name'][$n]);
  410. }
  411. // If there's no errors to this pont. We still do need to apply some addtional checks before we are finished.
  412. if (empty($_SESSION['temp_attachments'][$attachID]['errors']))
  413. attachmentChecks($attachID);
  414. }
  415. // Mod authors, finally a hook to hang an alternate attachment upload system upon
  416. // Upload to the current attachment folder with the file name $attachID or 'post_tmp_' . $user_info['id'] . '_' . md5(mt_rand())
  417. // Populate $_SESSION['temp_attachments'][$attachID] with the following:
  418. // name => The file name
  419. // tmp_name => Path to the temp file ($context['attach_dir'] . '/' . $attachID).
  420. // size => File size (required).
  421. // type => MIME type (optional if not available on upload).
  422. // id_folder => $modSettings['currentAttachmentUploadDir']
  423. // errors => An array of errors (use the index of the $txt variable for that error).
  424. // Template changes can be done using "integrate_upload_template".
  425. call_integration_hook('integrate_attachment_upload', array());
  426. }
  427. /**
  428. * Performs various checks on an uploaded file.
  429. * - Requires that $_SESSION['temp_attachments'][$attachID] be properly populated.
  430. *
  431. * @param $attachID
  432. */
  433. function attachmentChecks($attachID)
  434. {
  435. global $modSettings, $context, $sourcedir, $smcFunc;
  436. // No data or missing data .... Not necessarily needed, but in case a mod author missed something.
  437. if ( empty($_SESSION['temp_attachments'][$attachID]))
  438. $errror = '$_SESSION[\'temp_attachments\'][$attachID]';
  439. elseif (empty($attachID))
  440. $errror = '$attachID';
  441. elseif (empty($context['attachments']))
  442. $errror = '$context[\'attachments\']';
  443. elseif (empty($context['attach_dir']))
  444. $errror = '$context[\'attach_dir\']';
  445. // Let's get their attention.
  446. if (!empty($error))
  447. fatal_lang_error('attach_check_nag', 'debug', array($error));
  448. // These are the only valid image types for SMF.
  449. $validImageTypes = array(
  450. 1 => 'gif',
  451. 2 => 'jpeg',
  452. 3 => 'png',
  453. 5 => 'psd',
  454. 6 => 'bmp',
  455. 7 => 'tiff',
  456. 8 => 'tiff',
  457. 9 => 'jpeg',
  458. 14 => 'iff'
  459. );
  460. // Just in case this slipped by the first checks, we stop it here and now
  461. if ($_SESSION['temp_attachments'][$attachID]['size'] == 0)
  462. {
  463. $_SESSION['temp_attachments'][$attachID]['errors'][] = 'attach_0_byte_file';
  464. return false;
  465. }
  466. // First, the dreaded security check. Sorry folks, but this should't be avoided
  467. $size = @getimagesize($_SESSION['temp_attachments'][$attachID]['tmp_name']);
  468. if (isset($validImageTypes[$size[2]]))
  469. {
  470. require_once($sourcedir . '/Subs-Graphics.php');
  471. if (!checkImageContents($_SESSION['temp_attachments'][$attachID]['tmp_name'], !empty($modSettings['attachment_image_paranoid'])))
  472. {
  473. // It's bad. Last chance, maybe we can re-encode it?
  474. if (empty($modSettings['attachment_image_reencode']) || (!reencodeImage($_SESSION['temp_attachments'][$attachID]['tmp_name'], $size[2])))
  475. {
  476. // Nothing to do: not allowed or not successful re-encoding it.
  477. $_SESSION['temp_attachments'][$attachID]['errors'][] = 'bad_attachment';
  478. return false;
  479. }
  480. // Success! However, successes usually come for a price:
  481. // we might get a new format for our image...
  482. $old_format = $size[2];
  483. $size = @getimagesize($attachmentOptions['tmp_name']);
  484. if (!(empty($size)) && ($size[2] != $old_format))
  485. {
  486. if (isset($validImageTypes[$size[2]]))
  487. $_SESSION['temp_attachments'][$attachID]['type'] = 'image/' . $validImageTypes[$size[2]];
  488. }
  489. }
  490. }
  491. // Is there room for this sucker?
  492. if (!empty($modSettings['attachmentDirSizeLimit']) || !empty($modSettings['attachmentDirFileLimit']))
  493. {
  494. // Check the folder size and count. If it hasn't been done already.
  495. if (empty($context['dir_size']) || empty($context['dir_files']))
  496. {
  497. $request = $smcFunc['db_query']('', '
  498. SELECT COUNT(*), SUM(size)
  499. FROM {db_prefix}attachments
  500. WHERE id_folder = {int:folder_id}
  501. AND attachment_type != {int:type}',
  502. array(
  503. 'folder_id' => $modSettings['currentAttachmentUploadDir'],
  504. 'type' => 1,
  505. )
  506. );
  507. list ($context['dir_files'], $context['dir_size']) = $smcFunc['db_fetch_row']($request);
  508. $smcFunc['db_free_result']($request);
  509. }
  510. $context['dir_size'] += $_SESSION['temp_attachments'][$attachID]['size'];
  511. $context['dir_files']++;
  512. // Are we about to run out of room? Let's notify the admin then.
  513. if (empty($modSettings['attachment_full_notified']) && !empty($modSettings['attachmentDirSizeLimit']) && $modSettings['attachmentDirSizeLimit'] > 4000 && $context['dir_size'] > ($modSettings['attachmentDirSizeLimit'] - 2000) * 1024
  514. || (!empty($modSettings['attachmentDirFileLimit']) && $modSettings['attachmentDirFileLimit'] * .95 < $context['dir_files'] && $modSettings['attachmentDirFileLimit'] > 500))
  515. {
  516. require_once($sourcedir . '/Subs-Admin.php');
  517. emailAdmins('admin_attachments_full');
  518. updateSettings(array('attachment_full_notified' => 1));
  519. }
  520. // // No room left.... What to do now???
  521. if (!empty($modSettings['attachmentDirFileLimit']) && $context['dir_files'] + 2 > $modSettings['attachmentDirFileLimit']
  522. || (!empty($modSettings['attachmentDirSizeLimit']) && $context['dir_size'] > $modSettings['attachmentDirSizeLimit'] * 1024))
  523. {
  524. if (!empty($modSettings['automanage_attachments']) && $modSettings['automanage_attachments'] == 1)
  525. {
  526. // Move it to the new folder if we can.
  527. if (automanage_attachments_by_space())
  528. {
  529. rename($_SESSION['temp_attachments'][$attachID]['tmp_name'], $context['attach_dir'] . '/' . $attachID);
  530. $_SESSION['temp_attachments'][$attachID]['tmp_name'] = $context['attach_dir'] . '/' . $attachID;
  531. $_SESSION['temp_attachments'][$attachID]['id_folder'] = $modSettings['currentAttachmentUploadDir'];
  532. $context['dir_size'] = 0;
  533. $context['dir_files'] = 0;
  534. }
  535. // Or, let the user know that it ain't gonna happen.
  536. else
  537. {
  538. if (isset($context['dir_creation_error']))
  539. $_SESSION['temp_attachments'][$attachID]['errors'][] = $context['dir_creation_error'];
  540. else
  541. $_SESSION['temp_attachments'][$attachID]['errors'][] = 'ran_out_of_space';
  542. }
  543. }
  544. else
  545. $_SESSION['temp_attachments'][$attachID]['errors'][] = 'ran_out_of_space';
  546. }
  547. }
  548. // Is the file too big?
  549. $context['attachments']['total_size'] += $_SESSION['temp_attachments'][$attachID]['size'];
  550. if (!empty($modSettings['attachmentSizeLimit']) && $_SESSION['temp_attachments'][$attachID]['size'] > $modSettings['attachmentSizeLimit'] * 1024)
  551. $_SESSION['temp_attachments'][$attachID]['errors'][] = array('file_too_big', array(comma_format($modSettings['attachmentSizeLimit'], 0)));
  552. // Check the total upload size for this post...
  553. if (!empty($modSettings['attachmentPostLimit']) && $context['attachments']['total_size'] > $modSettings['attachmentPostLimit'] * 1024)
  554. $_SESSION['temp_attachments'][$attachID]['errors'][] = array('attach_max_total_file_size', array(comma_format($modSettings['attachmentPostLimit'], 0), comma_format($modSettings['attachmentPostLimit'] - (($context['attachments']['total_size'] - $_SESSION['temp_attachments'][$attachID]['size']) / 1024), 0)));
  555. // Have we reached the maximum number of files we are allowed?
  556. $context['attachments']['quantity']++;
  557. // Set a max limit if none exists
  558. if (empty($modSettings['attachmentNumPerPostLimit']) && $context['attachments']['quantity'] >= 50)
  559. $modSettings['attachmentNumPerPostLimit'] = 50;
  560. if (!empty($modSettings['attachmentNumPerPostLimit']) && $context['attachments']['quantity'] > $modSettings['attachmentNumPerPostLimit'])
  561. $_SESSION['temp_attachments'][$attachID]['errors'][] = array('attachments_limit_per_post', array($modSettings['attachmentNumPerPostLimit']));
  562. // File extension check
  563. if (!empty($modSettings['attachmentCheckExtensions']))
  564. {
  565. $allowed = explode(',', strtolower($modSettings['attachmentExtensions']));
  566. foreach ($allowed as $k => $dummy)
  567. $allowed[$k] = trim($dummy);
  568. if (!in_array(strtolower(substr(strrchr($_SESSION['temp_attachments'][$attachID]['name'], '.'), 1)), $allowed))
  569. {
  570. $allowed_extensions = strtr(strtolower($modSettings['attachmentExtensions']), array(',' => ', '));
  571. $_SESSION['temp_attachments'][$attachID]['errors'][] = array('cant_upload_type', array($allowed_extensions));
  572. }
  573. }
  574. // Undo the math if there's an error
  575. if (!empty($_SESSION['temp_attachments'][$attachID]['errors']))
  576. {
  577. if (isset($context['dir_size']))
  578. $context['dir_size'] -= $_SESSION['temp_attachments'][$attachID]['size'];
  579. if (isset($context['dir_files']))
  580. $context['dir_files']--;
  581. $context['attachments']['total_size'] -= $_SESSION['temp_attachments'][$attachID]['size'];
  582. $context['attachments']['quantity']--;
  583. return false;
  584. }
  585. return true;
  586. }
  587. /**
  588. * Create an attachment, with the given array of parameters.
  589. * - Adds any addtional or missing parameters to $attachmentOptions.
  590. * - Renames the temporary file.
  591. * - Creates a thumbnail if the file is an image and the option enabled.
  592. *
  593. * @param array $attachmentOptions
  594. */
  595. function createAttachment(&$attachmentOptions)
  596. {
  597. global $modSettings, $sourcedir, $smcFunc, $context;
  598. global $txt, $boarddir;
  599. require_once($sourcedir . '/Subs-Graphics.php');
  600. // These are the only valid image types for SMF.
  601. $validImageTypes = array(
  602. 1 => 'gif',
  603. 2 => 'jpeg',
  604. 3 => 'png',
  605. 5 => 'psd',
  606. 6 => 'bmp',
  607. 7 => 'tiff',
  608. 8 => 'tiff',
  609. 9 => 'jpeg',
  610. 14 => 'iff'
  611. );
  612. // If this is an image we need to set a few additional parameters.
  613. $size = @getimagesize($attachmentOptions['tmp_name']);
  614. list ($attachmentOptions['width'], $attachmentOptions['height']) = $size;
  615. // If it's an image get the mime type right.
  616. if (empty($attachmentOptions['mime_type']) && $attachmentOptions['width'])
  617. {
  618. // Got a proper mime type?
  619. if (!empty($size['mime']))
  620. $attachmentOptions['mime_type'] = $size['mime'];
  621. // Otherwise a valid one?
  622. elseif (isset($validImageTypes[$size[2]]))
  623. $attachmentOptions['mime_type'] = 'image/' . $validImageTypes[$size[2]];
  624. }
  625. // It is possible we might have a MIME type that isn't actually an image but still have a size.
  626. // For example, Shockwave files will be able to return size but be 'application/shockwave' or similar.
  627. if (!empty($attachmentOptions['mime_type']) && strpos($attachmentOptions['mime_type'], 'image/') !== 0)
  628. {
  629. $attachmentOptions['width'] = 0;
  630. $attachmentOptions['height'] = 0;
  631. }
  632. // Get the hash if no hash has been given yet.
  633. if (empty($attachmentOptions['file_hash']))
  634. $attachmentOptions['file_hash'] = getAttachmentFilename($attachmentOptions['name'], false, null, true);
  635. // Assuming no-one set the extension let's take a look at it.
  636. if (empty($attachmentOptions['fileext']))
  637. {
  638. $attachmentOptions['fileext'] = strtolower(strrpos($attachmentOptions['name'], '.') !== false ? substr($attachmentOptions['name'], strrpos($attachmentOptions['name'], '.') + 1) : '');
  639. if (strlen($attachmentOptions['fileext']) > 8 || '.' . $attachmentOptions['fileext'] == $attachmentOptions['name'])
  640. $attachmentOptions['fileext'] = '';
  641. }
  642. $smcFunc['db_insert']('',
  643. '{db_prefix}attachments',
  644. array(
  645. 'id_folder' => 'int', 'id_msg' => 'int', 'filename' => 'string-255', 'file_hash' => 'string-40', 'fileext' => 'string-8',
  646. 'size' => 'int', 'width' => 'int', 'height' => 'int',
  647. 'mime_type' => 'string-20', 'approved' => 'int',
  648. ),
  649. array(
  650. (int) $attachmentOptions['id_folder'], (int) $attachmentOptions['post'], $attachmentOptions['name'], $attachmentOptions['file_hash'], $attachmentOptions['fileext'],
  651. (int) $attachmentOptions['size'], (empty($attachmentOptions['width']) ? 0 : (int) $attachmentOptions['width']), (empty($attachmentOptions['height']) ? '0' : (int) $attachmentOptions['height']),
  652. (!empty($attachmentOptions['mime_type']) ? $attachmentOptions['mime_type'] : ''), (int) $attachmentOptions['approved'],
  653. ),
  654. array('id_attach')
  655. );
  656. $attachmentOptions['id'] = $smcFunc['db_insert_id']('{db_prefix}attachments', 'id_attach');
  657. // @todo Add an error here maybe?
  658. if (empty($attachmentOptions['id']))
  659. return false;
  660. // Now that we have the attach id, let's rename this sucker and finish up.
  661. $attachmentOptions['destination'] = getAttachmentFilename(basename($attachmentOptions['name']), $attachmentOptions['id'], $attachmentOptions['id_folder'], false, $attachmentOptions['file_hash']);
  662. rename($attachmentOptions['tmp_name'], $attachmentOptions['destination']);
  663. // If it's not approved then add to the approval queue.
  664. if (!$attachmentOptions['approved'])
  665. $smcFunc['db_insert']('',
  666. '{db_prefix}approval_queue',
  667. array(
  668. 'id_attach' => 'int', 'id_msg' => 'int',
  669. ),
  670. array(
  671. $attachmentOptions['id'], (int) $attachmentOptions['post'],
  672. ),
  673. array()
  674. );
  675. if (empty($modSettings['attachmentThumbnails']) || (empty($attachmentOptions['width']) && empty($attachmentOptions['height'])))
  676. return true;
  677. // Like thumbnails, do we?
  678. if (!empty($modSettings['attachmentThumbWidth']) && !empty($modSettings['attachmentThumbHeight']) && ($attachmentOptions['width'] > $modSettings['attachmentThumbWidth'] || $attachmentOptions['height'] > $modSettings['attachmentThumbHeight']))
  679. {
  680. if (createThumbnail($attachmentOptions['destination'], $modSettings['attachmentThumbWidth'], $modSettings['attachmentThumbHeight']))
  681. {
  682. // Figure out how big we actually made it.
  683. $size = @getimagesize($attachmentOptions['destination'] . '_thumb');
  684. list ($thumb_width, $thumb_height) = $size;
  685. if (!empty($size['mime']))
  686. $thumb_mime = $size['mime'];
  687. elseif (isset($validImageTypes[$size[2]]))
  688. $thumb_mime = 'image/' . $validImageTypes[$size[2]];
  689. // Lord only knows how this happened...
  690. else
  691. $thumb_mime = '';
  692. $thumb_filename = $attachmentOptions['name'] . '_thumb';
  693. $thumb_size = filesize($attachmentOptions['destination'] . '_thumb');
  694. $thumb_file_hash = getAttachmentFilename($thumb_filename, false, null, true);
  695. $thumb_path = $attachmentOptions['destination'] . '_thumb';
  696. // We should check the file size and count here since thumbs are added to the existing totals.
  697. if (!empty($modSettings['automanage_attachments']) && $modSettings['automanage_attachments'] == 1 && !empty($modSettings['attachmentDirSizeLimit']) || !empty($modSettings['attachmentDirFileLimit']))
  698. {
  699. $context['dir_size'] = isset($context['dir_size']) ? $context['dir_size'] += $thumb_size : $context['dir_size'] = 0;
  700. $context['dir_files'] = isset($context['dir_files']) ? $context['dir_files']++ : $context['dir_files'] = 0;
  701. // If the folder is full, try to create a new one and move the thumb to it.
  702. if ($context['dir_size'] > $modSettings['attachmentDirSizeLimit'] * 1024 || $context['dir_files'] + 2 > $modSettings['attachmentDirFileLimit'])
  703. {
  704. if (automanage_attachments_by_space())
  705. {
  706. rename($thumb_path, $context['attach_dir'] . '/' . $thumb_filename);
  707. $thumb_path = $context['attach_dir'] . '/' . $thumb_filename;
  708. $context['dir_size'] = 0;
  709. $context['dir_files'] = 0;
  710. }
  711. }
  712. }
  713. // If a new folder has been already created. Gotta move this thumb there then.
  714. if ($modSettings['currentAttachmentUploadDir'] != $attachmentOptions['id_folder'])
  715. {
  716. rename($thumb_path, $context['attach_dir'] . '/' . $thumb_filename);
  717. $thumb_path = $context['attach_dir'] . '/' . $thumb_filename;
  718. }
  719. // To the database we go!
  720. $smcFunc['db_insert']('',
  721. '{db_prefix}attachments',
  722. array(
  723. 'id_folder' => 'int', 'id_msg' => 'int', 'attachment_type' => 'int', 'filename' => 'string-255', 'file_hash' => 'string-40', 'fileext' => 'string-8',
  724. 'size' => 'int', 'width' => 'int', 'height' => 'int', 'mime_type' => 'string-20', 'approved' => 'int',
  725. ),
  726. array(
  727. $modSettings['currentAttachmentUploadDir'], (int) $attachmentOptions['post'], 3, $thumb_filename, $thumb_file_hash, $attachmentOptions['fileext'],
  728. $thumb_size, $thumb_width, $thumb_height, $thumb_mime, (int) $attachmentOptions['approved'],
  729. ),
  730. array('id_attach')
  731. );
  732. $attachmentOptions['thumb'] = $smcFunc['db_insert_id']('{db_prefix}attachments', 'id_attach');
  733. if (!empty($attachmentOptions['thumb']))
  734. {
  735. $smcFunc['db_query']('', '
  736. UPDATE {db_prefix}attachments
  737. SET id_thumb = {int:id_thumb}
  738. WHERE id_attach = {int:id_attach}',
  739. array(
  740. 'id_thumb' => $attachmentOptions['thumb'],
  741. 'id_attach' => $attachmentOptions['id'],
  742. )
  743. );
  744. rename($thumb_path, getAttachmentFilename($thumb_filename, $attachmentOptions['thumb'], $modSettings['currentAttachmentUploadDir'], false, $thumb_file_hash));
  745. }
  746. }
  747. }
  748. return true;
  749. }
  750. ?>