<?php
/*******************************************************************************
 *
 * LEIDEN OPEN VARIATION DATABASE (LOVD)
 *
 * Created     : 2009-03-17
 * Modified    : 2009-07-13
 * Version     : 1.1
 * For LOVD    : 2.0-20
 *
 * Access      : Curators and up.
 * Purpose     : GenBank uploader: upload a GenBank file into the genbank
 *               directory.
 *
 * Copyright   : 2004-2009 Leiden University Medical Center; http://www.LUMC.nl/
 * Programmers : Ir. Gerard C.P. Schaafsma <G.C.P.Schaafsma@LUMC.nl>
 *               Ing. Ivo F.A.C. Fokkema <I.F.A.C.Fokkema@LUMC.nl>
 * Last edited : Ing. Ivo F.A.C. Fokkema <I.F.A.C.Fokkema@LUMC.nl>
 *
 *
 * This file is part of LOVD.
 *
 * LOVD is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * LOVD is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with LOVD; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 *************/

define('ROOT_PATH', '../');
require ROOT_PATH . 'inc-init.php';
require ROOT_PATH . 'inc-lib-form.php';

// Require curator clearance.
lovd_requireAUTH(LEVEL_CURATOR);

// Check presence or writability of the genbank directory
if (!is_dir(ROOT_PATH . 'genbank') || !is_writable(ROOT_PATH . 'genbank')) {
    require ROOT_PATH . 'inc-top-clean.php';
    print('<SPAN class="S18"><B>LOVD GenBank File Uploader</B></SPAN><BR><BR>' . "\n\n" .
          'The \'genbank\' directory does not exist or is not writable. Please make sure it exists and that it is world writable, otherwise you can\'t use the GenBank File Uploader. For more information or troubleshooting, please refer to the <A href="' . ROOT_PATH . 'docs/lovd_scripts/genbank_file_uploader.php" target="_blank">LOVD manual</A>.<BR><BR>' . "\n\n");
    require ROOT_PATH . 'inc-bot-clean.php';
    exit;
}

$nMaxSize = 10485760; // 10 MB.
$nMaxPHP = ini_get('upload_max_filesize');
$nMaxPHP = substr($nMaxPHP, 0, -1) * pow(1024, 2);
if ($nMaxPHP < $nMaxSize) {
    $nMaxSize = $nMaxPHP;
}

if (isset($_GET['sent'])) {
    lovd_errorClean();

    // No file...
    if ($_FILES['upload_file']['error'] > 0 && $_FILES['upload_file']['error'] < 4) {
        lovd_errorAdd('There was a problem with the file transfer. Please try again. The file cannot be larger than ' . round($nMaxSize/pow(1024, 2), 1) . ' MB.');

    } else if ($_FILES['upload_file']['error'] == 4 || !$_FILES['upload_file']['size']) {
        lovd_errorAdd('Please select a file to upload.');

    } else if ($_FILES['upload_file']['size'] > $nMaxSize) {
        lovd_errorAdd('The file cannot be larger than ' . round($nMaxSize/pow(1024, 2), 1) . ' MB.');

    } elseif ($_FILES['upload_file']['error']) {
        // Various errors available from 4.3.0 or later.
        lovd_errorAdd('There was an unknown problem with receiving the file properly, possibly because of the current server settings. If the problem persists, contact the database administrator.');
    }

    if (!lovd_error()) {
        $fInput = @fopen($_FILES['upload_file']['tmp_name'], 'r');
        if (!$fInput) {
            lovd_errorAdd('Cannot open file after it was received by the server.');
        }
        // Read the first line of the file to check if it is a downloaded GenBank sequence file.
        $sLine = @fgets($fInput, 4096);
        $sLine = rtrim($sLine, "\r\n");

        // Check if in the first line LOCUS is present at the first position
        if (strpos($sLine, 'LOCUS') !== 0) {
            lovd_errorAdd('This is not a proper GenBank file.');
        }

        // Verify that this gene exists.
        if (!in_array($_POST['symbol'], lovd_getGeneList())) {
            lovd_errorAdd('This gene does not exists in this LOVD installation!');
        } elseif (!lovd_isCurator($_POST['symbol'])) {
            lovd_errorAdd('You are not allowed access to this gene!');
        }
    }
    
    if (!lovd_error()) {
        // Generate LOVD gene symbol.
        $sSymbol = substr($_POST['symbol'], 0, strpos($_POST['symbol'] . '_', '_'));

        // Determine the new name of the GenBank file
        $sFileName = $sSymbol . '.gb';
        $sPath = ROOT_PATH . 'genbank/';

        if ($_POST['exists'] == 'rename') {
            // Check if the file name already exists and rename, if necessary.
            $i = 1;
            while (file_exists($sPath . $sFileName)) {
                // Try to create a new unique name.
                $i ++;
                $sFileName = $sSymbol . '_' . str_pad($i, 2, '0', STR_PAD_LEFT) . '.gb';
            }
        }

        // Move the GenBank file to the new location.
        $bMove = move_uploaded_file($_FILES['upload_file']['tmp_name'], $sPath . $sFileName);

        require ROOT_PATH . 'inc-top-clean.php';
        if ($bMove) {
            lovd_writeLog('MySQL:Event', 'GenBankUpload', $_AUTH['username'] . ' (' . mysql_real_escape_string($_AUTH['name']) . ') successfully uploaded new GenBank file: ' . $sFileName . ' (' . $_POST['symbol'] . ')');
            print('Successfully uploaded new GenBank file: ' . $sFileName . '<BR>' . "\n\n" .
                  '<A href="' . $_SERVER['PHP_SELF'] . '">Want to upload more?</A><BR>' . "\n\n");

            // 2009-07-10; 2.0-20; by Gerard added choice to go back to the Reference Sequence Parser
            print('      <SCRIPT type="text/javascript">' . "\n" .
                  '        <!--' . "\n" .
                  '        if (window.name == \'LOVD_' . preg_replace('/[^a-z0-9_]/i', '_', $_STAT['signature']) . '_ScriptsUploadGenBank\') {' . "\n" .
                  '            document.writeln(\'<A href="#" onclick="lovd_openWindow(\\\'' . ROOT_PATH . 'scripts/parseRefSeq.php' . lovd_showSID() . '\\\', \\\'ScriptsParseRefSeq\\\', 800, 500); return false;">Go to the Reference Sequence Parser</A><BR>\');' . "\n" .
                  '        } else {' . "\n" .
                  '            document.writeln(\'<A href="' . ROOT_PATH . 'scripts/parseRefSeq.php?step=1">Go back to the Reference Sequence Parser</A><BR>\');' . "\n" .
                  '        }' . "\n" .
                  '        // -->' . "\n" .
                  '      </SCRIPT>' . "\n\n");

            // Now, if this gene never had a GenBank file enabled, we will do so now.
            @mysql_query('UPDATE ' . TABLE_DBS . ' SET genbank = 1, genbank_uri = "' . mysql_real_escape_string($sFileName) . '" WHERE symbol = "' . $_POST['symbol'] . '" AND genbank = 0 AND genbank_uri = ""');

        } else {
            lovd_writeLog('MySQL:Error', 'GenBankUpload', $_AUTH['username'] . ' (' . mysql_real_escape_string($_AUTH['name']) . ') successfully uploaded new GenBank file: ' . $sFileName . ' (' . $_POST['symbol'] . ')');
            print('Failed to upload new GenBank file.<BR>' . "\n\n");
        }
        require ROOT_PATH . 'inc-bot-clean.php';
        exit;        
    }

} else {
    // Default values.
    $_POST['symbol'] = $_SESSION['currdb'];
}



require ROOT_PATH . 'inc-top-clean.php';
print('<SPAN class="S18"><B>LOVD GenBank File Uploader</B></SPAN><BR><BR>' . "\n\n");

print('      Please select the GenBank file that you wish to import.<BR>' . "\n" .
      '      <BR>' . "\n\n");

lovd_errorPrint();

print('      <FORM action="' . $_SERVER['PHP_SELF'] . '?sent" method="post" enctype="multipart/form-data">' . "\n" .
      '        <INPUT type="hidden" name="MAX_FILE_SIZE" value="' . $nMaxSize . '">' . "\n" .
      '        <TABLE border="0" cellpadding="1" cellspacing="0" width="760">' . "\n");

// Find genes we're applying this to.
if ($_AUTH['level'] == LEVEL_CURATOR) {
    $sQ = 'SELECT c.symbol, CONCAT(c.symbol, " (", g.gene, ")") AS gene FROM ' . TABLE_CURATES . ' AS c LEFT JOIN ' . TABLE_DBS . ' AS g USING (symbol) WHERE userid = "' . $_AUTH['userid'] . '" ORDER BY c.symbol';
} else {
    $sQ = 'SELECT symbol, CONCAT(symbol, " (", gene, ")") AS gene FROM ' . TABLE_DBS . ' ORDER BY symbol';
}
$qGenes = mysql_query($sQ);

$aForm = array();
$aForm[] = array('POST', '', '', '50%', '50%');
$aForm[] = array('Select the gene for which you are uploading', 'select', 'symbol', 1, $qGenes, true, false, false);
$aForm[] = array('Select the GenBank file', 'file', 'upload_file', 30);
$aForm[] = array('If a GenBank file is already uploaded', 'select', 'exists', 1, array('overwrite' => 'overwrite it', 'rename' => 'rename automatically'), false, false, false);
$aForm[] = array('', 'submit', 'Upload');
lovd_viewForm($aForm);

print('</TABLE><BR>' . "\n\n" .
      '  </FORM><BR>' . "\n\n");

require ROOT_PATH . 'inc-bot-clean.php';
?>
