<?php
if( !defined('CMS_VERSION') ) { exit; }
if( ($uid = $this->LoggedInId()) < 1 ) throw new \CmsError403Exception();

// download an image... or a file, or dump an image to stdout
// just with obfuscation so that the filename and path are not obvious.
// and with FEU protection
$params = \xt_utils::decrypt_params( $params );
$file = \xt_param::get_string( $params, 'file' );
$dl = \xt_param::get_bool( $params, 'download' );
$groups = \xt_param::get_string( $params, 'groups' );
$nocache = \xt_param::get_bool( $params, 'nocache' );

if( $groups ) {
    // convert permitted groups into gids.
    $groups = explode(',',$groups);
    $all_groups = $this->GetGroupList();
    $allowed_groups = null;
    foreach( $groups as $group_name ) {
        $group_name = trim($group_name);
        if( !$group_name ) continue;
        if( isset( $all_groups[$group_name]) ) $allowed_groups = $all_groups[$group_name];
    }

    // see if the current user is in one of these groups
    if( ! $this->MemberOfGroup( $uid, $allowed_groups ) ) throw new \CmsError403Exception();
}

if( $file ) {
    if( !is_file( $file ) ) throw new \CmsError404Exception();

    $mime_type = \xt_utils::get_mime_type( $file );
    if( ! startswith( $mime_type, 'image/') ) $dl = true;
    if( $dl ) \xt_utils::send_file_and_exit( $file );

    // its an image.
    // so just passthrough the image
    if( $nocache ) {
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Cache-Control: private',false);
    }
    header('Content-type: '.$mime_type);
    header('Content-Length: ' . filesize($file));

    $chunksize = 65535;
    $handle=fopen($file,'rb');
    $contents = '';
    do {
        $data = fread($handle,$chunksize);
        if( strlen($data) == 0 ) break;
        print($data);
    } while(true);
    fclose($handle);
}
exit();
