<?php
/**
 * uploadsvc.php
 * 2 Apr 2011
 * receive uploads from upload page widget
 */
session_start();
require_once 'util.function.php';
if(!$_SESSION['researcher_id'] || !experiment_access_permission($_SESSION['researcher_id'], $_GET['id'])) {
    exit;
}
if($_FILES['file']['error'] == UPLOAD_ERR_OK && $_FILES['file']['size']) {
    require_once 'const.inc.php';
    $filepath  = FILE_REPOSITORY_PATH . '/' . uniqid() . date('YmdHis');
    if(move_uploaded_file($_FILES['file']['tmp_name'], $filepath)) {
        require_once 'db.function.php';
        $metadata = array();
        $orig_name = strip_tags($_FILES['file']['name']);
        $zipcommands = array('zip' => 'unzip', 'tar.gz' => 'tar zxvf', 'tar.bz2' => 'tar jxvf', 'gz' => 'gunzip', 'bz2' => 'bunzip2');
        if(preg_match("/\.(zip|tar\.gz|tar\.bz2|gz|bz2)$/i", $orig_name, $matches)) {
            $zipcmd = $zipcommands[$matches[1]];
            $zipdir = FILE_REPOSITORY_PATH . '/' . uniqid() . date('YmdHis');
            mkdir($zipdir);
            rename($filepath, $zip = ("$zipdir/" . basename($filepath). ".$matches[1]"));
            chdir($zipdir);
            `$zipcmd $zip`;
            $bedfiles = explode("\n", trim(`find . -type f -print | egrep -v ".$matches[1]$"`));
            foreach($bedfiles as $b) {
                $filepath = FILE_REPOSITORY_PATH . '/' . uniqid() . date('YmdHis');
                rename($b, $filepath);
                chmod($filepath, 0600);
                if($matches[1] == 'gz' || $matches[1] == 'bz2') {
                    $b = preg_replace("/\.$matches[1]$/", '', $orig_name);
                }
                $metadata[] = process_single_bed($filepath, $_GET['id'], basename($b));
            }
            rrmdir($zipdir); // clean up
        } else {
            $metadata[] = process_single_bed($filepath, $_GET['id'], $orig_name);
        }
        print json_encode($metadata);
    }
}

function process_single_bed($filepath, $experiment_id, $orig_name) {
    $header = trim(`head -1 $filepath`);
    if(stripos($header, 'chr') === 0) {
        $header = null;
    }
    $header = strip_tags($header);
    $date = date('Y-m-d H:i:s');
    $db = getDB();
    $stat = $db->query("insert into bedfile (experiment_id, name, header, upload_date) values (?,?,?,?)", array($experiment_id, $orig_name, $header, $date));
    if(PEAR::isError($stat)) {
        file_put_contents("/tmp/dasrupload.log", print_r($stat, true));
    }
    $bedfile_id = $db->getOne("select last_insert_id()");
    $err = '';
    if(trim(`/usr/bin/wc -l $filepath`) > RAWBED_THRESHOLD) {
        $db->query("insert into rawbed (bedfile_id, filepath) values (?,?)", array($bedfile_id, $filepath));
        $filetype = 'rawbed';
    } else {
        require_once 'load_bed.function.php';
        $err = load_bed($bedfile_id, $filepath);
        if(!$err) {
            unlink($filepath);  // save space
            $filetype = 'summarybed';
        } else {
            $db->query("update bedfile set descr = ? where bedfile_id = ?", array($err, $bedfile_id));
            $db->query("insert into rawbed (bedfile_id, filepath) values (?,?)", array($bedfile_id, $filepath));
            $filetype = 'rawbed';
        }
    }
    $db->query("update bedfile set filetype = ? where bedfile_id = ?", array($filetype, $bedfile_id));
    $count = $db->getOne("select count(*) from bedfile b where b.experiment_id = ?", $_GET['id']);
    $db->query("update experiment set bedcount = ? where experiment_id = ?", array($count, $_GET['id']));
    $db->commit();
    return array('name' => $orig_name, 'header' => $header, 'upload_date' => date('n/j/y', strtotime($date)), 'id' => $bedfile_id, 'genome' => '', 'method' => '', 'descr' => (string)$err);
}

?>
