<?php

SDV($LinkFunctions['Attach:'], 'NewLinkUpload');
$HandleActions['getfile'] = "HandleGetFile";


function NewLinkUpload($pagename, $imap, $path, $title, $txt, $fmt=NULL) {
  global $FmtV, $UploadFileFmt, $LinkUploadCreateFmt, $UploadUrlFmt,
    $UploadPrefixFmt;
  
  global $PageUrl;
   
  $upname = MakeUploadName($pagename, $path);
  $filepath = FmtPageName("$UploadFileFmt/$upname", $pagename);
  $FmtV['$LinkUpload'] = 
    FmtPageName("\$PageUrl?action=upload&amp;upname=$upname", $pagename);
  $FmtV['$LinkText'] = $txt;
  
  if (!file_exists($filepath)){ 
    return FmtPageName($LinkUploadCreateFmt, $pagename);
  }
 
  $path = FmtPageName("\$PageUrl?action=getfile&amp;filename=$upname", $pagename);
 
  return LinkIMap($pagename, $imap, $path, $title, $txt, $fmt);
}


//  This will handle the attach command in the following forms
//  Attach: filename.txt
//  Attach: groupname/filename.txt
//  
//  $pagename in the form of $group.$name
function HandleGetFile($pagename){
	
//	$outputstring = "\n";
	
	
	// Get the associated file name and group for this attach
	
	$getFileGroup = null;
	$getFileName = null;
	
	$givenFileName = $_REQUEST['filename'];
	$seperatorPosn = strpos($givenFileName, "/");
	
	if ($seperatorPosn == FALSE){
		$seperatorPosn = strpos($pagename, ".");
		$getFileGroup = substr($pagename, 0, $seperatorPosn);
		$getFileName = $givenFileName;
	}else{
		$getFileGroup = substr($givenFileName, 0, $seperatorPosn);
		$getFileName = substr($givenFileName, $seperatorPosn + 1);
	}
	
	if (AuthenticatedAsRole("$getFileGroup.GroupAttributes", "read") == FALSE){
		return;  //Do nothing, invalid access	
	}
	
//	$outputstring .= "getFileGroup:  $getFileGroup  getFileName:  $getFileName  \n";
	
	
	//$UploadExts
	$getFileExtenstion = substr($getFileName, 
			strpos($getFileName, ".") + 1, strlen($getFileName));
	global $UploadExts, $UploadDir;
//	$outputstring .= "getFileExtenstion:  $getFileExtenstion\n";
//	$outputstring .= 'Content-type: ' . $UploadExts[$getFileExtenstion] . "\n";
	Header('Content-type: ' . $UploadExts[$getFileExtenstion]);
	
	$outputstring .= "$UploadDir/$getFileGroup/$getFileName\n";
	@readfile("$UploadDir/$getFileGroup/$getFileName");
	
//	$fp = fopen("log.txt", "a");
//	//$outputstring = "\n";
//	$outputstring .= "pagename:  $pagename  ";
//	$outputstring .= 'n:  ' . $_REQUEST['n'] . "  ";
//	$outputstring .= 'action:  ' . $_REQUEST['action'] . "  ";
//	$outputstring .= 'filename:  ' . $_REQUEST['filename'] . "  ";
//	$outputstring .= 'action:  ' . implode("  ", $_REQUEST);
//	$outputstring .= "\n";
//	fwrite($fp, $outputstring);
//	fclose($fp);
	
}
?>