<?php

// wcf imports
require_once(WCF_DIR.'lib/page/AbstractPage.class.php');
require_once(WCF_DIR.'lib/data/downloadDB/DownloadDBDataEditor.class.php');

/**
 * Download Database Datei Download
 *
 * @author		Robert "Tatzelwurm" Hempel
 * @copyright	2007/2008 INSIDE das Hrspiel
 * @license 	GNU LGPL http://www.gnu.org/licenses/lgpl.txt
 * @package		de.inside.wcf.DownloadDatabase
 */

class DownloadDBFileDownloadPage extends AbstractPage {
	
	public $dataID;
	private $fileName;
	private $fileType;
	private $link;
	
	public function readParameters() {
		parent :: readParameters();
		if (isset($_REQUEST['dataID'])) $this->dataID = intval($_REQUEST['dataID']);
		if (!$this->dataID){
			require_once(WCF_DIR.'lib/system/exception/NamedUserException.class.php');
			throw new NamedUserException(WCF::getLanguage()->get('wcf.dldb.wrongid'));
			exit;
		}
		WCF::getCache()->addResource('dldbData',
			WCF_DIR.'cache/cache.dldbData.php',
			WCF_DIR.'lib/system/cache/CacheBuilderDLDBData.class.php');
	}

	public function show() {
		$this->readDaten();
		// Anzahl der Downloads erhöhen
		$sql = "UPDATE wcf".WCF_N."_dldb_data
				SET downloads = downloads + 1
				WHERE `dataID` = ".$this->dataID;
		$row = WCF::getDB()->registerShutdownUpdate($sql);
		// reset cache
		WCF::getCache()->clear(WCF_DIR.'cache/', 'cache.dldbData.php');
		if (!$this->fileType) {
			if (FileUtil::isURL($this->link)) {
				HeaderUtil::redirect($this->link,false);
				exit;
			} else {
				$link = FileUtil::getRealPath(RELATIVE_WCF_DIR.$this->link);
				$type = 'application/unknown';
			}
		} else {
			$dataset = new downloadDBDataEditor($this->dataID);
			$link = FileUtil::getRealPath(RELATIVE_WCF_DIR.$dataset->getURL());
			$type = $this->fileType;
		}
		// Set Download Infos
		@ header('Content-Description: File Transfer');
		@ header('Content-Type: '. $type);
		@ header('Content-disposition: attachment; filename="' . $this->fileName . '"');
		@ header('Content-Length: ' . filesize($link));
		@ header('Pragma: no-cache');
		@ header('Expires: 0');
		// Start Download
		@readfile($link);
	}
	
	protected function readDaten() {
		// Cache lesen
		$data = WCF::getCache()->get('dldbData');
		foreach ($data as $daten) {
			if ($daten['dataID'] == $this->dataID) {
				$this->fileType = $daten['mimeType'];
				$this->fileName = $daten['fileName'];
				$this->link		= $daten['link'];
				// Kontrolle der Zugangsberechtigung;
				$IDs = explode(',',$daten['groupcheck']);
				$daten['canViewCat'] = false;
				foreach ($IDs as $gruppe) {
					if (in_array($gruppe, WCF::getUser()->getGroupIDs())) { 
						$daten['canViewCat'] = true;
					}
				}
				if ($daten['canViewCat'] != true){
					require_once(WCF_DIR.'lib/system/exception/PermissionDeniedException.class.php');
					throw new PermissionDeniedException();
				}
			}
		}
	}
}
?>