<?php
/**
 * Front-end wrapper for downloading files that were uploaded in the CMS
 * Has support for conditional get and partial downloads. Both require HTTP/1.1,
 * but the script is backwards compatible with HTTP/1.0
 * @author Erik Hoogeboom
 * @version $Id: file.php5,v 1.8 2009-03-11 15:41:51 hoogeboom Exp $
 * @package egrip
 */

require_once("VWM/VWM.php");

// get VWM instance
$vwm = VWM::getInstance('../../vwm_config.xml');

// load CMS dataobjects ini
VWM_Controller::loadDataObjectsfiles('CMS');

require_once('CMS/CMS_File.class.php');

if ($file_id = $_REQUEST['id']) {
    $tmp_file = new CMS_File();
    $tmp_file->setid($file_id);

    $tmp_file->selectAdd('(SELECT COUNT(*) FROM cms_contentright WHERE container_id = (SELECT id FROM cms_contentcontainer WHERE content_type_id = 7 AND content_id = ' . ((int)$file_id) . ') AND righttype_id = 1 AND group_id = 0) AS public_read');

    $has_access = false;

    if ($tmp_file->find(true)) {

        if ($tmp_file->toValue('public_read') == 1) {

            $has_access = true;

        } else {

            // check if user is logged in and has rights

            /* if no action and module are set, default to RenderPage
            * and set urlparts based on request uri */
            $controller =& $vwm->getController('VWM_FrontEndController');

            $user = $controller->getContext()->getUser();

            if ($user->getid() > 0) {

                try {
                    $tmp = VWM_Controller::factory('CMS_ContentContainer');
                    $tmp->whereAdd('content_type_id = 7');
                    $tmp->whereAdd('content_id = ' . ((int)$file_id));
                    if ($tmp->find(true)) {
                        // user has access
                        $has_access = true;
                    }
                } catch (Exception $e) {
                    // This user does not have access
                }

            } else {
                // not logged in
            }

        }

        if ($has_access) {

            $filename = $tmp_file->getdata_dir().$tmp_file->getsystemfilename();

    		require_once('VWM/util/VWM_FileServer.class.php');
    		$fileServer = new VWM_FileServer($filename, null, $tmp_file->getmimetype());
    		$fileServer->setDisposition('attachment', $tmp_file->getDownloadFilename());
    		$fileServer->doServe($_SERVER);
        } else {
            header('HTTP/1.0 403 Forbidden');
            echo 'Access denied';

        }
		exit;
	}

}
?>
