Browse Source

The rest of Avatar.php

Signed-off-by: Suki <[email protected]>
Suki 12 years ago
parent
commit
f7280a6993
1 changed files with 53 additions and 2 deletions
  1. 53 2
      Sources/Avatar.php

+ 53 - 2
Sources/Avatar.php

@@ -29,7 +29,7 @@ if (!defined('SMF'))
  */
  function Download()
  {
-	global
+	global $modSettings, $smcFunc, $context;
 
 	// We need a valid ID
 	if(empty($_GET['attach']) || (string)$_GET['attach'] != (string)(int)$_GET['attach'])
@@ -88,13 +88,64 @@ if (!defined('SMF'))
 
 		$file = $smcFunc['db_fetch_assoc']($result);
 
+		// Update the download counter (unless it's a thumbnail).
+		if ($file['attachment_type'] != 3)
+			$smcFunc['db_query']('attach_download_increase', '
+				UPDATE LOW_PRIORITY {db_prefix}attachments
+				SET downloads = downloads + 1
+				WHERE id_attach = {int:id_attach}',
+				array(
+					'id_attach' => $id_attach,
+				)
+		);
+
 		require($sourcedir. '/Subs.php');
 
 		// Get the file info
 		$file['filename'] = getAttachmentFilename($file['real_filename'], $id_attach, $file['id_folder'], false, $file['file_hash']);
 		$file['etag'] = '"'. function_exists('md5_file') ? md5_file($file['filename']) : md5(file_get_contents($file['filename'])). '"';
 
-	// Cache it... (Why do I randomly select a length at which to expire? Search around for RIP_JITTER :P)
+		// Cache it... (Why do I randomly select a length at which to expire? Search around for RIP_JITTER :P)
 		cache_put_data('avatar_lookup_id-'. $id_attach, $file, mt_rand(850, 900));
 	}
+
+	// No point in a nicer message, because this is supposed to be an attachment anyway...
+	if (!file_exists($file['filename']))
+	{
+		header('HTTP/1.0 404 File Not Found');
+
+		// We need to die like this *before* we send any anti-caching headers as below.
+		die('404 File Not Found');
+	}
+
+	// If it hasn't been modified since the last time this attachement was retrieved, there's no need to display it again.
+	if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']))
+	{
+		list($modified_since) = explode(';', $_SERVER['HTTP_IF_MODIFIED_SINCE']);
+		if (strtotime($modified_since) >= filemtime($file['filename']))
+		{
+			ob_end_clean();
+
+			// Answer the question - no, it hasn't been modified ;).
+			header('HTTP/1.1 304 Not Modified');
+			exit;
+		}
+	}
+
+	// Send the avatar headers.
+	header('Expires: '. gmdate('D, d M Y H:i:s', time() + 31536000). ' GMT'); # Expire in a year. Hehe.
+	header('Last-Modified: '. gmdate('D, d M Y H:i:s', filemtime($file['filename'])). ' GMT');
+	header('Accept-Ranges: bytes');
+	header('Connection: close');
+	header('ETag: '. $file['etag']);
+	header('Content-Type: '. $file['mime_type']);
+
+	// Output the file
+	$fp = fopen($file['filename'], 'rb');
+
+	while(!feof($fp))
+		echo fread($fp, 8192);
+
+	fclose($fp);
+	exit;
  }