plugins/SpecialUpdownload.php
changeset 1227 bdac73ed481e
parent 1175 1e2c9819ede3
child 1279 0bc945385d74
equal deleted inserted replaced
1226:de56132c008d 1227:bdac73ed481e
     1 <?php
     1 <?php
     2 /**!info**
     2 /**!info**
     3 {
     3 {
     4   "Plugin Name"  : "plugin_specialupdownload_title",
     4 	"Plugin Name"  : "plugin_specialupdownload_title",
     5   "Plugin URI"   : "http://enanocms.org/",
     5 	"Plugin URI"   : "http://enanocms.org/",
     6   "Description"  : "plugin_specialupdownload_desc",
     6 	"Description"  : "plugin_specialupdownload_desc",
     7   "Author"       : "Dan Fuhry",
     7 	"Author"       : "Dan Fuhry",
     8   "Version"      : "1.1.6",
     8 	"Version"      : "1.1.6",
     9   "Author URI"   : "http://enanocms.org/"
     9 	"Author URI"   : "http://enanocms.org/"
    10 }
    10 }
    11 **!*/
    11 **!*/
    12 
    12 
    13 /*
    13 /*
    14  * Enano - an open-source CMS capable of wiki functions, Drupal-like sidebar blocks, and everything in between
    14  * Enano - an open-source CMS capable of wiki functions, Drupal-like sidebar blocks, and everything in between
    26 
    26 
    27 // $plugins->attachHook('session_started', 'SpecialUpDownload_paths_init();');
    27 // $plugins->attachHook('session_started', 'SpecialUpDownload_paths_init();');
    28 
    28 
    29 function SpecialUpDownload_paths_init()
    29 function SpecialUpDownload_paths_init()
    30 {
    30 {
    31   register_special_page('UploadFile', 'specialpage_upload_file');
    31 	register_special_page('UploadFile', 'specialpage_upload_file');
    32   register_special_page('DownloadFile', 'specialpage_download_file');
    32 	register_special_page('DownloadFile', 'specialpage_download_file');
    33 }
    33 }
    34   
    34 	
    35 function page_Special_UploadFile()
    35 function page_Special_UploadFile()
    36 {
    36 {
    37   global $db, $session, $paths, $template, $plugins; // Common objects
    37 	global $db, $session, $paths, $template, $plugins; // Common objects
    38   global $lang;
    38 	global $lang;
    39   global $cache;
    39 	global $cache;
    40   global $mime_types;
    40 	global $mime_types;
    41   if(getConfig('enable_uploads')!='1') { die_friendly($lang->get('etc_access_denied_short'), '<p>' . $lang->get('upload_err_disabled_site') . '</p>'); }
    41 	if(getConfig('enable_uploads')!='1') { die_friendly($lang->get('etc_access_denied_short'), '<p>' . $lang->get('upload_err_disabled_site') . '</p>'); }
    42   if ( !$session->get_permissions('upload_files') )
    42 	if ( !$session->get_permissions('upload_files') )
    43   {
    43 	{
    44     die_friendly($lang->get('etc_access_denied_short'), '<p>' . $lang->get('upload_err_disabled_acl') . '</p>');
    44 		die_friendly($lang->get('etc_access_denied_short'), '<p>' . $lang->get('upload_err_disabled_acl') . '</p>');
    45   }
    45 	}
    46   if(isset($_POST['doit']))
    46 	if(isset($_POST['doit']))
    47   {
    47 	{
    48     if(isset($_FILES['data']))
    48 		if(isset($_FILES['data']))
    49     {
    49 		{
    50       $file =& $_FILES['data'];
    50 			$file =& $_FILES['data'];
    51     }
    51 		}
    52     else
    52 		else
    53     {
    53 		{
    54       $file = false;
    54 			$file = false;
    55     }
    55 		}
    56     if ( !is_array($file) )
    56 		if ( !is_array($file) )
    57     {
    57 		{
    58       die_friendly($lang->get('upload_err_title'), '<p>' . $lang->get('upload_err_cant_get_file_meta') . '</p>');
    58 			die_friendly($lang->get('upload_err_title'), '<p>' . $lang->get('upload_err_cant_get_file_meta') . '</p>');
    59     }
    59 		}
    60     if ( $file['size'] == 0 || $file['size'] > (int)getConfig('max_file_size', '256000') )
    60 		if ( $file['size'] == 0 || $file['size'] > (int)getConfig('max_file_size', '256000') )
    61     {
    61 		{
    62       die_friendly($lang->get('upload_err_title'), '<p>' . $lang->get('upload_err_too_big_or_small') . '</p>');
    62 			die_friendly($lang->get('upload_err_title'), '<p>' . $lang->get('upload_err_too_big_or_small') . '</p>');
    63     }
    63 		}
    64     
    64 		
    65     $types = fetch_allowed_extensions();
    65 		$types = fetch_allowed_extensions();
    66     $ext = strtolower(substr($file['name'], strrpos($file['name'], '.')+1, strlen($file['name'])));
    66 		$ext = strtolower(substr($file['name'], strrpos($file['name'], '.')+1, strlen($file['name'])));
    67     if ( !isset($types[$ext]) || ( isset($types[$ext]) && !$types[$ext] ) )
    67 		if ( !isset($types[$ext]) || ( isset($types[$ext]) && !$types[$ext] ) )
    68     {
    68 		{
    69       die_friendly($lang->get('upload_err_title'), '<p>' . $lang->get('upload_err_banned_ext', array('ext' => htmlspecialchars($ext))) . '</p>');
    69 			die_friendly($lang->get('upload_err_title'), '<p>' . $lang->get('upload_err_banned_ext', array('ext' => htmlspecialchars($ext))) . '</p>');
    70     }
    70 		}
    71     $type = $mime_types[$ext];
    71 		$type = $mime_types[$ext];
    72     //$type = explode(';', $type); $type = $type[0];
    72 		//$type = explode(';', $type); $type = $type[0];
    73     //if(!in_array($type, $allowed_mime_types)) die_friendly('Upload failed', '<p>The file type "'.$type.'" is not allowed.</p>');
    73 		//if(!in_array($type, $allowed_mime_types)) die_friendly('Upload failed', '<p>The file type "'.$type.'" is not allowed.</p>');
    74     if($_POST['rename'] != '')
    74 		if($_POST['rename'] != '')
    75     {
    75 		{
    76       $filename = $_POST['rename'];
    76 			$filename = $_POST['rename'];
    77     }
    77 		}
    78     else
    78 		else
    79     {
    79 		{
    80       $filename = $file['name'];
    80 			$filename = $file['name'];
    81     }
    81 		}
    82     $bad_chars = Array(':', '\\', '/', '<', '>', '|', '*', '?', '"', '#', '+');
    82 		$bad_chars = Array(':', '\\', '/', '<', '>', '|', '*', '?', '"', '#', '+');
    83     foreach($bad_chars as $ch)
    83 		foreach($bad_chars as $ch)
    84     {
    84 		{
    85       if(strstr($filename, $ch) || preg_match('/^([ ]+)$/is', $filename))
    85 			if(strstr($filename, $ch) || preg_match('/^([ ]+)$/is', $filename))
    86       {
    86 			{
    87         die_friendly($lang->get('upload_err_title'), '<p>' . $lang->get('upload_err_banned_chars') . '</p>');
    87 				die_friendly($lang->get('upload_err_title'), '<p>' . $lang->get('upload_err_banned_chars') . '</p>');
    88       }
    88 			}
    89     }
    89 		}
    90     
    90 		
    91     $ns = namespace_factory($filename, 'File');
    91 		$ns = namespace_factory($filename, 'File');
    92     $cdata = $ns->get_cdata();
    92 		$cdata = $ns->get_cdata();
    93     $is_protected = $cdata['really_protected'];
    93 		$is_protected = $cdata['really_protected'];
    94     
    94 		
    95     if ( isPage($paths->get_pathskey($filename, 'File')) && !isset ( $_POST['update'] ) )
    95 		if ( isPage($paths->get_pathskey($filename, 'File')) && !isset ( $_POST['update'] ) )
    96     {
    96 		{
    97       $upload_link = makeUrlNS('Special', 'UploadFile/'.$filename);
    97 			$upload_link = makeUrlNS('Special', 'UploadFile/'.$filename);
    98       die_friendly($lang->get('upload_err_title'), '<p>' . $lang->get('upload_err_already_exists', array('upload_link' => $upload_link)) . '</p>');
    98 			die_friendly($lang->get('upload_err_title'), '<p>' . $lang->get('upload_err_already_exists', array('upload_link' => $upload_link)) . '</p>');
    99     }
    99 		}
   100     else if ( isset($_POST['update']) && $is_protected )
   100 		else if ( isset($_POST['update']) && $is_protected )
   101     {
   101 		{
   102       die_friendly($lang->get('upload_err_title'), '<p>' . $lang->get('upload_err_replace_protected') . '</p>');
   102 			die_friendly($lang->get('upload_err_title'), '<p>' . $lang->get('upload_err_replace_protected') . '</p>');
   103     }
   103 		}
   104     
   104 		
   105     $utime = time();
   105 		$utime = time();
   106            
   106  					
   107     $filename = $db->escape(sanitize_page_id($filename));
   107 		$filename = $db->escape(sanitize_page_id($filename));
   108     $ext = substr($filename, strrpos($filename, '.'), strlen($filename));
   108 		$ext = substr($filename, strrpos($filename, '.'), strlen($filename));
   109     $flen = filesize($file['tmp_name']);
   109 		$flen = filesize($file['tmp_name']);
   110     
   110 		
   111     $perms = $session->fetch_page_acl($filename, 'File');
   111 		$perms = $session->fetch_page_acl($filename, 'File');
   112     $comments = ( isset($_POST['update']) ) ? $db->escape($_POST['comments']) : $db->escape(RenderMan::preprocess_text($_POST['comments'], false, false, true, $perms));
   112 		$comments = ( isset($_POST['update']) ) ? $db->escape($_POST['comments']) : $db->escape(RenderMan::preprocess_text($_POST['comments'], false, false, true, $perms));
   113     $chartag = sha1(microtime());
   113 		$chartag = sha1(microtime());
   114     $urln = str_replace(' ', '_', $filename);
   114 		$urln = str_replace(' ', '_', $filename);
   115     
   115 		
   116     $key = md5($filename . '_' . ( function_exists('md5_file') ? md5_file($file['tmp_name']) : file_get_contents($file['tmp_name'])));
   116 		$key = md5($filename . '_' . ( function_exists('md5_file') ? md5_file($file['tmp_name']) : file_get_contents($file['tmp_name'])));
   117     $targetname = ENANO_ROOT . '/files/' . $key . $ext;
   117 		$targetname = ENANO_ROOT . '/files/' . $key . $ext;
   118     
   118 		
   119     if(!@move_uploaded_file($file['tmp_name'], $targetname))
   119 		if(!@move_uploaded_file($file['tmp_name'], $targetname))
   120     {
   120 		{
   121       die_friendly($lang->get('upload_err_title'), '<p>' . $lang->get('upload_err_move_failed') . '</p>');
   121 			die_friendly($lang->get('upload_err_title'), '<p>' . $lang->get('upload_err_move_failed') . '</p>');
   122     }
   122 		}
   123     
   123 		
   124     if(getConfig('file_history') != '1')
   124 		if(getConfig('file_history') != '1')
   125     {
   125 		{
   126       if(!$db->sql_query('DELETE FROM  '.table_prefix.'files WHERE filename=\''.$filename.'\' LIMIT 1;')) $db->_die('The old file data could not be deleted.');
   126 			if(!$db->sql_query('DELETE FROM  '.table_prefix.'files WHERE filename=\''.$filename.'\' LIMIT 1;')) $db->_die('The old file data could not be deleted.');
   127     }
   127 		}
   128     if(!$db->sql_query('INSERT INTO '.table_prefix.'files(time_id,page_id,filename,size,mimetype,file_extension,file_key) VALUES('.$utime.', \''.$urln.'\', \''.$filename.'\', '.$flen.', \''.$type.'\', \''.$ext.'\', \''.$key.'\')')) $db->_die('The file data entry could not be inserted.');
   128 		if(!$db->sql_query('INSERT INTO '.table_prefix.'files(time_id,page_id,filename,size,mimetype,file_extension,file_key) VALUES('.$utime.', \''.$urln.'\', \''.$filename.'\', '.$flen.', \''.$type.'\', \''.$ext.'\', \''.$key.'\')')) $db->_die('The file data entry could not be inserted.');
   129     if(!isset($_POST['update']))
   129 		if(!isset($_POST['update']))
   130     {
   130 		{
   131       if(!$db->sql_query('INSERT INTO '.table_prefix.'logs(time_id,date_string,log_type,action,author,author_uid,page_id,namespace) VALUES('.$utime.', \''.enano_date(ED_DATE | ED_TIME).'\', \'page\', \'create\', \''.$session->username.'\',' . $session->user_id . ', \''.$filename.'\', \''.'File'.'\');')) $db->_die('The page log could not be updated.');
   131 			if(!$db->sql_query('INSERT INTO '.table_prefix.'logs(time_id,date_string,log_type,action,author,author_uid,page_id,namespace) VALUES('.$utime.', \''.enano_date(ED_DATE | ED_TIME).'\', \'page\', \'create\', \''.$session->username.'\',' . $session->user_id . ', \''.$filename.'\', \''.'File'.'\');')) $db->_die('The page log could not be updated.');
   132       if(!$db->sql_query('INSERT INTO '.table_prefix.'pages(name,urlname,namespace,protected,delvotes,delvote_ips) VALUES(\''.$filename.'\', \''.$urln.'\', \'File\', 0, 0, \'\')')) $db->_die('The page listing entry could not be inserted.');
   132 			if(!$db->sql_query('INSERT INTO '.table_prefix.'pages(name,urlname,namespace,protected,delvotes,delvote_ips) VALUES(\''.$filename.'\', \''.$urln.'\', \'File\', 0, 0, \'\')')) $db->_die('The page listing entry could not be inserted.');
   133       if(!$db->sql_query('INSERT INTO '.table_prefix.'page_text(page_id,namespace,page_text,char_tag) VALUES(\''.$urln.'\', \'File\', \''.$comments.'\', \''.$chartag.'\')')) $db->_die('The page text entry could not be inserted.');
   133 			if(!$db->sql_query('INSERT INTO '.table_prefix.'page_text(page_id,namespace,page_text,char_tag) VALUES(\''.$urln.'\', \'File\', \''.$comments.'\', \''.$chartag.'\')')) $db->_die('The page text entry could not be inserted.');
   134     }
   134 		}
   135     else
   135 		else
   136     {
   136 		{
   137       if(!$db->sql_query('INSERT INTO '.table_prefix.'logs(time_id,date_string,log_type,action,author,author_uid,page_id,namespace,edit_summary) VALUES('.$utime.', \''.enano_date(ED_DATE | ED_TIME).'\', \'page\', \'reupload\', \''.$session->username.'\',' . $session->user_id . ', \''.$filename.'\', \''.'File'.'\', \''.$comments.'\');')) $db->_die('The page log could not be updated.');
   137 			if(!$db->sql_query('INSERT INTO '.table_prefix.'logs(time_id,date_string,log_type,action,author,author_uid,page_id,namespace,edit_summary) VALUES('.$utime.', \''.enano_date(ED_DATE | ED_TIME).'\', \'page\', \'reupload\', \''.$session->username.'\',' . $session->user_id . ', \''.$filename.'\', \''.'File'.'\', \''.$comments.'\');')) $db->_die('The page log could not be updated.');
   138     }
   138 		}
   139     $cache->purge('page_meta');
   139 		$cache->purge('page_meta');
   140     die_friendly($lang->get('upload_success_title'), '<p>' . $lang->get('upload_success_body', array('file_link' => makeUrlNS('File', $filename))) . '</p>');
   140 		die_friendly($lang->get('upload_success_title'), '<p>' . $lang->get('upload_success_body', array('file_link' => makeUrlNS('File', $filename))) . '</p>');
   141   }
   141 	}
   142   else
   142 	else
   143   {
   143 	{
   144     $template->header();
   144 		$template->header();
   145     $fn = $paths->getParam(0);
   145 		$fn = $paths->getParam(0);
   146     if ( $fn && !$session->get_permissions('upload_new_version') )
   146 		if ( $fn && !$session->get_permissions('upload_new_version') )
   147     {
   147 		{
   148       die_friendly($lang->get('etc_access_denied_short'), '<p>' . $lang->get('upload_err_replace_denied') . '<p>');
   148 			die_friendly($lang->get('etc_access_denied_short'), '<p>' . $lang->get('upload_err_replace_denied') . '<p>');
   149     }
   149 		}
   150     ?>
   150 		?>
   151     <p><?php echo $lang->get('upload_intro'); ?></p>
   151 		<p><?php echo $lang->get('upload_intro'); ?></p>
   152     <p><?php 
   152 		<p><?php 
   153       // Get the max file size, and format it in a way that is user-friendly
   153 			// Get the max file size, and format it in a way that is user-friendly
   154       
   154 			
   155       $fs = getConfig('max_file_size', '256000');
   155 			$fs = getConfig('max_file_size', '256000');
   156       $fs = (int)$fs;
   156 			$fs = (int)$fs;
   157       if($fs >= 1048576)
   157 			if($fs >= 1048576)
   158       {
   158 			{
   159         $fs = round($fs / 1048576, 1);
   159 				$fs = round($fs / 1048576, 1);
   160         $unitized = $fs . ' ' . $lang->get('etc_unit_megabytes_short');
   160 				$unitized = $fs . ' ' . $lang->get('etc_unit_megabytes_short');
   161       }
   161 			}
   162       elseif($fs >= 1024)
   162 			elseif($fs >= 1024)
   163       {
   163 			{
   164         $fs = round($fs / 1024, 1);
   164 				$fs = round($fs / 1024, 1);
   165         $unitized = $fs . ' ' . $lang->get('etc_unit_kilobytes_short');
   165 				$unitized = $fs . ' ' . $lang->get('etc_unit_kilobytes_short');
   166       }
   166 			}
   167       
   167 			
   168       echo $lang->get('upload_max_filesize', array(
   168 			echo $lang->get('upload_max_filesize', array(
   169           'size' => $unitized
   169 					'size' => $unitized
   170         ));
   170 				));
   171     ?></p>
   171 		?></p>
   172     <form action="<?php echo makeUrl($paths->page); ?>" method="post" enctype="multipart/form-data">
   172 		<form action="<?php echo makeUrl($paths->page); ?>" method="post" enctype="multipart/form-data">
   173       <table border="0" cellspacing="1" cellpadding="4">
   173 			<table border="0" cellspacing="1" cellpadding="4">
   174         <tr><td><?php echo $lang->get('upload_field_file'); ?></td><td><input name="data" type="file" size="40" /></td></tr>
   174 				<tr><td><?php echo $lang->get('upload_field_file'); ?></td><td><input name="data" type="file" size="40" /></td></tr>
   175         <tr><td><?php echo $lang->get('upload_field_renameto'); ?></td><td><input name="rename" type="text" size="40"<?php if($fn) echo ' value="'.$fn.'" readonly="readonly"'; ?> /></td></tr>
   175 				<tr><td><?php echo $lang->get('upload_field_renameto'); ?></td><td><input name="rename" type="text" size="40"<?php if($fn) echo ' value="'.$fn.'" readonly="readonly"'; ?> /></td></tr>
   176         <?php
   176 				<?php
   177         if(!$fn) echo '<tr><td>' . $lang->get('upload_field_comments') . '</td><td><textarea name="comments" rows="20" cols="60"></textarea></td></tr>';
   177 				if(!$fn) echo '<tr><td>' . $lang->get('upload_field_comments') . '</td><td><textarea name="comments" rows="20" cols="60"></textarea></td></tr>';
   178         else echo '<tr><td>' . $lang->get('upload_field_reason') . '</td><td><input name="comments" size="50" /></td></tr>';
   178 				else echo '<tr><td>' . $lang->get('upload_field_reason') . '</td><td><input name="comments" size="50" /></td></tr>';
   179         ?>
   179 				?>
   180         <tr><td colspan="2" style="text-align: center">
   180 				<tr><td colspan="2" style="text-align: center">
   181           <?php
   181 					<?php
   182           if($fn)
   182 					if($fn)
   183             echo '<input type="hidden" name="update" value="true" />';
   183 						echo '<input type="hidden" name="update" value="true" />';
   184           ?>
   184 					?>
   185           <input type="submit" name="doit" value="<?php echo $lang->get('upload_btn_upload'); ?>" />
   185 					<input type="submit" name="doit" value="<?php echo $lang->get('upload_btn_upload'); ?>" />
   186         </td></tr>
   186 				</td></tr>
   187       </table>
   187 			</table>
   188     </form>
   188 		</form>
   189     <?php
   189 		<?php
   190     $template->footer();
   190 		$template->footer();
   191   }
   191 	}
   192 }                                                     
   192 }                                                     
   193 
   193 
   194 function page_Special_DownloadFile()
   194 function page_Special_DownloadFile()
   195 {
   195 {
   196   global $db, $session, $paths, $template, $plugins; // Common objects
   196 	global $db, $session, $paths, $template, $plugins; // Common objects
   197   global $lang;
   197 	global $lang;
   198   global $do_gzip;
   198 	global $do_gzip;
   199   $filename = $paths->getParam(0);
   199 	$filename = $paths->getParam(0);
   200   $timeid = $paths->getParam(1);
   200 	$timeid = $paths->getParam(1);
   201   if ( $timeid && ctype_digit((string)$timeid) )
   201 	if ( $timeid && ctype_digit((string)$timeid) )
   202   {
   202 	{
   203     $tid = ' AND time_id='.$timeid;
   203 		$tid = ' AND time_id='.$timeid;
   204   }
   204 	}
   205   else
   205 	else
   206   {
   206 	{
   207     $tid = '';
   207 		$tid = '';
   208   }
   208 	}
   209   $filename = $db->escape(sanitize_page_id($filename));
   209 	$filename = $db->escape(sanitize_page_id($filename));
   210   
   210 	
   211   $q = $db->sql_query('SELECT page_id,size,mimetype,time_id,file_extension,file_key FROM '.table_prefix.'files WHERE filename=\''.$filename.'\''.$tid.' ORDER BY time_id DESC;');
   211 	$q = $db->sql_query('SELECT page_id,size,mimetype,time_id,file_extension,file_key FROM '.table_prefix.'files WHERE filename=\''.$filename.'\''.$tid.' ORDER BY time_id DESC;');
   212   if ( !$q )
   212 	if ( !$q )
   213   {
   213 	{
   214     $db->_die('The file data could not be selected.');
   214 		$db->_die('The file data could not be selected.');
   215   }
   215 	}
   216   if ( $db->numrows() < 1 )
   216 	if ( $db->numrows() < 1 )
   217   {
   217 	{
   218     header('HTTP/1.1 404 Not Found');
   218 		header('HTTP/1.1 404 Not Found');
   219     die_friendly($lang->get('upload_err_not_found_title'), '<p>' . $lang->get('upload_err_not_found_body', array('filename' => htmlspecialchars($filename))) . '</p>');
   219 		die_friendly($lang->get('upload_err_not_found_title'), '<p>' . $lang->get('upload_err_not_found_body', array('filename' => htmlspecialchars($filename))) . '</p>');
   220   }
   220 	}
   221   $row = $db->fetchrow();
   221 	$row = $db->fetchrow();
   222   $db->free_result();
   222 	$db->free_result();
   223   
   223 	
   224   // Check permissions
   224 	// Check permissions
   225   $perms = $session->fetch_page_acl($row['page_id'], 'File');
   225 	$perms = $session->fetch_page_acl($row['page_id'], 'File');
   226   if ( !$perms->get_permissions('read') )
   226 	if ( !$perms->get_permissions('read') )
   227   {
   227 	{
   228     die_friendly($lang->get('etc_access_denied_short'), '<p>' . $lang->get('etc_access_denied') . '</p>');
   228 		die_friendly($lang->get('etc_access_denied_short'), '<p>' . $lang->get('etc_access_denied') . '</p>');
   229   }
   229 	}
   230   
   230 	
   231   $fname = ENANO_ROOT . '/files/' . $row['file_key'] . $row['file_extension'];
   231 	$fname = ENANO_ROOT . '/files/' . $row['file_key'] . $row['file_extension'];
   232   if ( !file_exists($fname) )
   232 	if ( !file_exists($fname) )
   233   {
   233 	{
   234     $fname = ENANO_ROOT . '/files/' . $row['file_key'] . '_' . $row['time_id'] . $row['file_extension'];
   234 		$fname = ENANO_ROOT . '/files/' . $row['file_key'] . '_' . $row['time_id'] . $row['file_extension'];
   235   }
   235 	}
   236   if ( !file_exists($fname) )
   236 	if ( !file_exists($fname) )
   237   {
   237 	{
   238     die("Uploaded file $fname not found.");
   238 		die("Uploaded file $fname not found.");
   239   }
   239 	}
   240   
   240 	
   241   if ( isset($_GET['preview']) && substr($row['mimetype'], 0, 6) == 'image/' )
   241 	if ( isset($_GET['preview']) && substr($row['mimetype'], 0, 6) == 'image/' )
   242   {
   242 	{
   243     // Determine appropriate width and height
   243 		// Determine appropriate width and height
   244     $width  = ( isset($_GET['width'])  ) ? intval($_GET['width'] ) : 320;
   244 		$width  = ( isset($_GET['width'])  ) ? intval($_GET['width'] ) : 320;
   245     $height = ( isset($_GET['height']) ) ? intval($_GET['height']) : 320;
   245 		$height = ( isset($_GET['height']) ) ? intval($_GET['height']) : 320;
   246     
   246 		
   247     // 1.1.7: allow different format output
   247 		// 1.1.7: allow different format output
   248     $extension = $row['file_extension'];
   248 		$extension = $row['file_extension'];
   249     if ( isset($_GET['fmt']) && in_array($_GET['fmt'], array('png', 'jpg')) )
   249 		if ( isset($_GET['fmt']) && in_array($_GET['fmt'], array('png', 'jpg')) )
   250       $extension = ".{$_GET['fmt']}";
   250 			$extension = ".{$_GET['fmt']}";
   251     
   251 		
   252     $cache_filename = ENANO_ROOT . "/cache/{$filename}-{$row['time_id']}-{$width}x{$height}$extension";
   252 		$cache_filename = ENANO_ROOT . "/cache/{$filename}-{$row['time_id']}-{$width}x{$height}$extension";
   253     if ( file_exists($cache_filename) )
   253 		if ( file_exists($cache_filename) )
   254     {
   254 		{
   255       $fname = $cache_filename;
   255 			$fname = $cache_filename;
   256     }
   256 		}
   257     else
   257 		else
   258     {
   258 		{
   259       $allow_scale = false;
   259 			$allow_scale = false;
   260       $orig_fname = $fname;
   260 			$orig_fname = $fname;
   261       // is caching enabled?
   261 			// is caching enabled?
   262       if ( getConfig('cache_thumbs') == '1' )
   262 			if ( getConfig('cache_thumbs') == '1' )
   263       {
   263 			{
   264         $fname = $cache_filename;
   264 				$fname = $cache_filename;
   265         if ( is_writeable(dirname($fname)) )
   265 				if ( is_writeable(dirname($fname)) )
   266         {
   266 				{
   267           $allow_scale = true;
   267 					$allow_scale = true;
   268         }
   268 				}
   269       }
   269 			}
   270       else
   270 			else
   271       {
   271 			{
   272         // Get a temporary file
   272 				// Get a temporary file
   273         // In this case, the file will not be cached and will be scaled each time it's requested
   273 				// In this case, the file will not be cached and will be scaled each time it's requested
   274         $temp_dir = sys_get_temp_dir();
   274 				$temp_dir = sys_get_temp_dir();
   275         // if tempnam() cannot use the specified directory name, it will fall back on the system default
   275 				// if tempnam() cannot use the specified directory name, it will fall back on the system default
   276         $tempname = tempnam($temp_dir, $filename);
   276 				$tempname = tempnam($temp_dir, $filename);
   277         if ( $tempname && is_writeable($tempname) )
   277 				if ( $tempname && is_writeable($tempname) )
   278         {
   278 				{
   279           $allow_scale = true;
   279 					$allow_scale = true;
   280         }
   280 				}
   281       }
   281 			}
   282       if ( $allow_scale )
   282 			if ( $allow_scale )
   283       {
   283 			{
   284         $result = scale_image($orig_fname, $fname, $width, $height);
   284 				$result = scale_image($orig_fname, $fname, $width, $height);
   285         if ( !$result )
   285 				if ( !$result )
   286           $fname = $orig_fname;
   286 					$fname = $orig_fname;
   287       }
   287 			}
   288       else
   288 			else
   289       {
   289 			{
   290         $fname = $orig_fname;
   290 				$fname = $orig_fname;
   291       }
   291 			}
   292     }
   292 		}
   293   }
   293 	}
   294   $handle = @fopen($fname, 'r');
   294 	$handle = @fopen($fname, 'r');
   295   if ( !$handle )
   295 	if ( !$handle )
   296     die('Can\'t open output file for reading');
   296 		die('Can\'t open output file for reading');
   297   
   297 	
   298   $len = filesize($fname);
   298 	$len = filesize($fname);
   299   header('Content-type: '.$row['mimetype']);
   299 	header('Content-type: '.$row['mimetype']);
   300   if ( isset($_GET['download']) )
   300 	if ( isset($_GET['download']) )
   301   {
   301 	{
   302     header('Content-disposition: attachment, filename="' . $filename . '";');
   302 		header('Content-disposition: attachment, filename="' . $filename . '";');
   303   }
   303 	}
   304   if ( !@$GLOBALS['do_gzip'] )
   304 	if ( !@$GLOBALS['do_gzip'] )
   305     header('Content-length: ' . $len);
   305 		header('Content-length: ' . $len);
   306   
   306 	
   307   header('Last-Modified: '.enano_date('r', $row['time_id']));
   307 	header('Last-Modified: '.enano_date('r', $row['time_id']));
   308   
   308 	
   309   // using this method limits RAM consumption
   309 	// using this method limits RAM consumption
   310   while ( !feof($handle) )
   310 	while ( !feof($handle) )
   311   {
   311 	{
   312     echo fread($handle, 512000);
   312 		echo fread($handle, 512000);
   313   }
   313 	}
   314   fclose($handle);
   314 	fclose($handle);
   315   
   315 	
   316   gzip_output();
   316 	gzip_output();
   317   
   317 	
   318   exit;
   318 	exit;
   319   
   319 	
   320 }
   320 }
   321 
   321 
   322 ?>
   322 ?>