<?php
/*******************************************************************************
 *
 * LEIDEN OPEN VARIATION DATABASE (LOVD)
 *
 * Created     : 2006-10-12
 * Modified    : 2009-06-12
 * For LOVD    : 2.0-19
 *
 * Access      : Submitters and up.
 * Purpose     : Submit new variant and patient data.
 *
 * Copyright   : 2004-2009 Leiden University Medical Center; http://www.LUMC.nl/
 * Programmers : Ing. Ivo F.A.C. Fokkema <I.F.A.C.Fokkema@LUMC.nl>
 *               Ir. Gerard C.P. Schaafsma <G.C.P.Schaafsma@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';

if (HAS_AUTH) {
    // If authorized, check for updates.
    require ROOT_PATH . 'inc-upgrade.php';
}

// Require valid user.
lovd_requireAUTH();





if ($_GET['action'] == 'submit') {
    // View all / search variants in this gene.

    // Require form functions.
    require ROOT_PATH . 'inc-lib-form.php';
    require ROOT_PATH . 'inc-top.php';
    lovd_printHeader('submit', 'Submit new sequence variant');

    // Step 1: Require gene.
    if (!GENE_COUNT) {
        // No gene? No submission, then.
        lovd_showInfoTable('There are no configured genes yet.', 'stop');
        require ROOT_PATH . 'inc-bot.php';
        exit;

    } else {
        // 2008-08-06; 2.0-10; Prevent any type of attack through $_GET['gene'] and $_POST['gene'] by verifying it exists.
        if (!empty($_GET['gene']) && !in_array($_GET['gene'], lovd_getGeneList())) {
            unset($_GET['gene']);
        }
        if (!empty($_POST['gene']) && !in_array($_POST['gene'], lovd_getGeneList())) {
            unset($_POST['gene']);
        }
    }

    // 2007-08-17; 2.0-beta-07; We want to click a link, and add the patient info right away. So we need $_POST['patientid'].
    if (!empty($_GET['add_pat']) && empty($_GET['add']) && empty($_POST['patientid']) && empty($_SESSION['submit_pat'])) {
        $_POST['patientid'] = $_GET['add_pat'];
        $_GET['add'] = 'pat';
    }

    // Delete entries?
    if (!empty($_GET['delete']) && !empty($_GET['gene']) && preg_match('/^(pat|var)([0-9]{1,})?$/', $_GET['delete'], $aRegs)) {
        list(, $sList) = $aRegs;
        if ($sList == 'var') {
            $nDel = (int) $aRegs[2];
        }
        if ($sList == 'var' && isset($nDel) && !empty($_SESSION['submit_muts'][$_GET['gene']][$nDel])) {
            unset($_SESSION['submit_muts'][$_GET['gene']][$nDel]);
        } elseif ($sList == 'pat' && !empty($_SESSION['submit_pat'])) {
            unset($_SESSION['submit_pat']);
            unset($_SESSION['submit_patid']);
        }

        $_POST['gene'] = $_GET['gene'];
    }

    if (empty($_POST['gene'])) {
        // Select gene?

        if (GENE_COUNT == 1) {
            // Never mind, we've only got one.
            list($_POST['gene']) = lovd_getGeneList();

        } else {
            $_POST['gene'] = $_SESSION['currdb'];

            // Table.
            print('      <FORM action="' . $_SERVER['PHP_SELF'] . '?action=' . $_GET['action'] . (!empty($_GET['add'])? '&amp;add=' . $_GET['add'] : '') . '" method="post">' . "\n" .
                  (!empty($_POST['patientid'])? '        <INPUT type="hidden" name="patientid" value="' . $_POST['patientid'] . '">' . "\n" : '') .
                  '        <TABLE border="0" cellpadding="0" cellspacing="1" width="600">');

            // Get gene list.
            $qGenes = mysql_query('SELECT symbol, CONCAT(symbol, " (", gene, ")") FROM ' . TABLE_DBS . ' ORDER BY symbol');

            $aForm = array(
                            array('POST', '', '', '40%', '60%'),
                            array('Submit new sequence variation for:', 'select', 'gene', 1, $qGenes, false, false, false),
                            'skip',
                            array('', 'submit', 'Select gene database'),
                          );
            $_MODULES->processForm('SubmitGeneSelect', $aForm);
            lovd_viewForm($aForm);
            print('</TABLE></FORM>' . "\n\n");

            require ROOT_PATH . 'inc-bot.php';
            exit;
        }
    }





    // Whether or not a user can submit non-public data.
    if (lovd_isCurator($_POST['gene'])) {
        define('IS_CURATOR', true);
    } else {
        define('IS_CURATOR', false);
    }

    // Set some vars.
    require ROOT_PATH . 'class/currdb.php';
    $_CURRDB = new CurrDB(true, $_POST['gene']);
    $_CURRDB->hideCols('public_form', IS_CURATOR);

    if (!isset($_SESSION['submit_muts']) || !is_array($_SESSION['submit_muts'])) {
        $_SESSION['submit_muts'] = array($_POST['gene'] => array());
    } elseif (!isset($_SESSION['submit_muts'][$_POST['gene']]) || !is_array($_SESSION['submit_muts'][$_POST['gene']])) {
        $_SESSION['submit_muts'][$_POST['gene']] = array();
    }

    if (!isset($_SESSION['submit_pat']) || !is_array($_SESSION['submit_pat'])) {
        $_SESSION['submit_pat'] = array();
    }
    if (!isset($_GET['add'])) {
        $_GET['add'] = '';
    }





    // Step 2: Add variant data.
    if ($_GET['add'] == 'var') {
        // Add variant data.

        // 2007-08-30; 2.0-beta-08; Added option to add a variant to the
        // submission process, which is already in the database.
        if (!empty($_POST['variant_name'])) {
            // Variant name sent; we're importing everything (well, this is just the first one we happen to find).
            $zData = mysql_fetch_assoc(mysql_query('SELECT v.* FROM ' . TABLEPREFIX . '_' . $_POST['gene'] . '_variants AS v WHERE v.`' . $_CURRDB->getMutationCol() . '` = "' . $_POST['variant_name'] . '"'));

            if (!$zData) {
                // Wrong ID, apparently.
                lovd_showInfoTable('Could not find this variant in the system!', 'stop');
                print('      <FORM action="' . $_SERVER['PHP_SELF'] . '?action=' . $_GET['action'] . '" method="post">' . "\n" .
                      '        <INPUT type="hidden" name="gene" value="' . $_POST['gene'] . '">' . "\n" .
                      '        <INPUT type="submit" value="Continue &raquo;">' . "\n" .
                      '      </FORM>' . "\n\n" .
                      '      <SCRIPT type="text/javascript">' . "\n" .
                      '        <!--' . "\n" .
                      '        setTimeout("document.forms[0].submit()", 3000);' . "\n" .
                      '        // -->' . "\n" .
                      '      </SCRIPT>' . "\n\n");

                require ROOT_PATH . 'inc-bot.php';
                exit;
            }

            // We will not mark this as being taken from the database... at the
            // end, LOVD checks if the variant exists already anyway.

            // Load data into $_POST.
            $aCols = $_CURRDB->getColList('Variant');
            foreach ($aCols as $sCol) {
                $_POST[$sCol] = $zData[$sCol];
            }
            $_CURRDB->transformSelectValues($_POST, true);
        }

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

            // 2008-04-24; 2.0-06; Check Variant/DBID field to make sure it's consistent with the variant.
            // Submitters don't see this DBID column. Possibly, this LOVD has been configured to hide it anyway. So:
            $_CURRDBtmp = new CurrDB(true, $_POST['gene']);
            if ($_CURRDBtmp->colExists('Variant/DBID')) {
                $sMutationCol = $_CURRDB->getMutationCol();
                if (!empty($_POST[$sMutationCol])) {
                    // 2008-05-19; 2.0-07; Some modifications here to apply new function that checks if
                    // the given ID matches the given variant and predict the ID only when left empty.
                    if (empty($_POST['Variant/DBID'])) {
                        // Submitters who don't have this field AND curators who left this field open.
                        $sIDGenerated = lovd_fetchDBID($_POST['gene'], $_POST[$sMutationCol], $sMutationCol);
                        // 2008-10-13; 2.0-13; If this ID is a new ID, and this ID also exists in the submission for a different variant, increment by one.
                        list($n) = @mysql_fetch_row(mysql_query('SELECT COUNT(*) FROM `' . TABLEPREFIX . '_' . mysql_real_escape_string($_POST['gene']) . '_variants` WHERE `Variant/DBID` LIKE "' . $sIDGenerated . '%"'));
                        if (!$n) {
                            // This is a new ID, make sure it does not exist in this submission for a different variant.
                            while (true) {
                                foreach ($_SESSION['submit_muts'][$_POST['gene']] as $aSession) {
                                    if (substr($aSession['Variant/DBID'], 0, strlen($sIDGenerated)) == $sIDGenerated && str_replace(array('(', ')', '?'), '', $_POST[$sMutationCol]) != str_replace(array('(', ')', '?'), '', $aSession[$sMutationCol])) {
                                        // Exists already and this is not the same variant!
                                        $sIDGenerated ++; // I know this looks weird, but it works.
                                        continue 2;
                                    }
                                }
                                break;
                            }
                        }
                        $_POST['Variant/DBID'] = $sIDGenerated;
                    } else {
                        // 2008-10-13; 2.0-13; The DBID check allowed invalid DBID values if the DBID field contained more than just the ID.
                        $sSymb = substr($_POST['gene'], 0, strpos($_POST['gene'] . '_', '_'));
                        $sDBID = substr($_POST['Variant/DBID'], 0, strlen($sSymb) + 6);
                        if (!lovd_checkDBID($_POST['gene'], $_POST[$sMutationCol], $sMutationCol, $sDBID)) {
                            lovd_errorAdd('The given variant ID "' . strip_tags($sDBID) . '" does not match the variant "' . strip_tags($_POST[$sMutationCol]) . '".');
                        } elseif (count($_SESSION['submit_muts'][$_POST['gene']])) {
                            // 2008-10-13; 2.0-13; Check given ID against submission, also.
                            foreach ($_SESSION['submit_muts'][$_POST['gene']] as $aSession) {
                                if (substr($aSession['Variant/DBID'], 0, strlen($sDBID)) == $sDBID && str_replace(array('(', ')', '?'), '', $_POST[$sMutationCol]) != str_replace(array('(', ')', '?'), '', $aSession[$sMutationCol])) {
                                    // Exists already and this is not the same variant!
                                    lovd_errorAdd('The given variant ID "' . strip_tags($sDBID) . '" does not match the variant "' . strip_tags($_POST[$sMutationCol]) . '".');
                                }
                            }
                        }
                    }
                }
            }
            unset($_CURRDBtmp);

            // Mandatory fields.
            $_CURRDB->checkMandatory('Variant');

            // Field lengths.
            $_CURRDB->checkInputLength();

            // Field types.
            $_CURRDB->checkInputType();

            // Regular expressions.
            $_CURRDB->checkInputRegExp();

            // 2006-12-07; 2.0-alpha-02
            // XSS attack prevention. Simply deny input of HTML, PHP other stuff blocked by strip_tags().
            lovd_checkXSS();

            // 2008-10-10; 2.0-13; Deny this entry, if the exact combination is already present in the database, or the submission. Otherwise, an SQL error would show up.
            // Step 1: Check current submission for the same variant.
            if (!lovd_error() && count($_SESSION['submit_muts'][$_POST['gene']])) {
                // Check submission for other variant that is actually equal.
                $aCols = $_CURRDB->getColList('Variant');
                // Compare session array.
                foreach ($_SESSION['submit_muts'][$_POST['gene']] as $aSession) {
                    $bEqual = true;
                    foreach ($aCols as $sCol) {
                        if (!isset($_POST[$sCol])) {
                            // Multiple select list without selected value.
                            $_POST[$sCol] = '';
                        }
                        if (is_array($_POST[$sCol])) {
                            // Multiple select list.
                            if (implode(';', $_POST[$sCol]) != $aSession[$sCol]) {
                                $bEqual = false;
                            }
                        } elseif ($_POST[$sCol] != $aSession[$sCol]) {
                            $bEqual = false;
                        }
                    }
                    if ($bEqual && $_POST['allele'] == $aSession['allele']) {
                        // This is bad... we should not allow this!
                        lovd_errorAdd('An entry in your submission exactly like this already exists! Are you sure you don\'t want a different value for the \'Variant allele\' field?');
                    }
                }
            }

            // Step 2: Check database for the same variant, only if an existing patient has been selected.
            if (!lovd_error() && !empty($_SESSION['submit_patid'])) {
                // Determine if mutation already exists in database. If so, check allele value and throw error if necessary.
                $aCols = $_CURRDB->getColList('Variant');
                $sQ = 'SELECT variantid FROM ' . TABLEPREFIX . '_' . $_POST['gene'] . '_variants WHERE ';
                foreach ($aCols as $key => $sCol) {
                    if (!isset($_POST[$sCol])) {
                        // Multiple select list without selected value.
                        $_POST[$sCol] = '';
                    }
                    if (is_array($_POST[$sCol])) {
                        // Multiple select list.
                        $sQ .= (!$key? '' : ' AND ') . '`' . $sCol . '` = "' . implode(';', $_POST[$sCol]) . '"';
                    } else {
                        $sQ .= (!$key? '' : ' AND ') . '`' . $sCol . '` = "' . $_POST[$sCol] . '"';
                    }
                }

                // Store IDs that match.
                $aIDs = array();
                $qIDs = mysql_query($sQ);
                while (list($nID) = mysql_fetch_row($qIDs)) {
                    $aIDs[] = $nID;
                }

                // Now, find if these ID's exist with the same patient and the same allele data. If so, throw a warning.
                list($n) = mysql_fetch_row(mysql_query('SELECT COUNT(*) FROM ' . TABLE_PAT2VAR . ' WHERE symbol = "' . $_POST['gene'] . '" AND (variantid = "' . implode('" OR variantid = "', $aIDs) . '") AND allele = "' . $_POST['allele'] . '"'));
                if ($n) {
                    // This is bad... we should not allow this!
                    lovd_errorAdd('An entry in the database exactly like this already exists! Are you sure you don\'t want a different value for the \'Variant allele\' field?');
                }
            }

            if (!lovd_error()) {
                // Insert into $_SESSION and return to the submission overview page.
                $aCols = $_CURRDB->getColList('Variant');

                // 2008-04-24; 2.0-06; Include auto generated Variant/DBID field for submitters.
                if (array_search('Variant/DBID', $aCols) === false && !empty($_POST['Variant/DBID'])) {
                    // Variant/DBID was hidden, but value is filled in.
                    $aCols[] = 'Variant/DBID';
                }

                while (true) {
                    // Loop to process possible homozygous mutation ($_POST['allele'] == 3).

                    // Build session array.
                    $aSession = array('allele' => ($_POST['allele'] == 3? 10 : $_POST['allele']));
                    foreach ($aCols as $sCol) {
                        // 2007-12-21; 2.0-02; Reset to empty value to prevent notices + warnings about non-existent indexes.
                        if (!isset($_POST[$sCol])) {
                            // Multiple select list without selected value.
                            $_POST[$sCol] = '';
                        }
                        // 2007-12-21; 2.0-02; Multiple select lists need to be stored properly, such as is done in the patient data processing.
                        if (is_array($_POST[$sCol])) {
                            $_POST[$sCol] = implode(';', $_POST[$sCol]);
                        }
                        $aSession[$sCol] = $_POST[$sCol];
                    }

                    // Define variant status.
                    if (IS_CURATOR) {
                        $aSession['status'] = $_POST['status'];
                    } else {
                        $aSession['status'] = STATUS_NEW;
                    }

                    // Variant pathogenicity.
                    if (HAS_AUTH) {
                        // Curator and up.
                        $aSession['pathogenic'] = $_POST['pathogenic_reported'] . $_POST['pathogenic_concluded'];
                    } else {
                        // Submitter...
                        if (!array_key_exists($_POST['pathogenic_reported'], $_SETT['var_pathogenic'])) {
                            $aSession['pathogenic'] = 55;
                        } else {
                            $aSession['pathogenic'] = $_POST['pathogenic_reported'] . '5';
                        }
                    }

                    // The check if variant already exists is done when finalizing.
                    $_SESSION['submit_muts'][$_POST['gene']][] = $aSession;

                    // End loop, or continue?
                    if ($_POST['allele'] == 3) {
                        $_POST['allele'] = 20;
                    } else {
                        break;
                    }
                }

                // Thank the user...
                print('      Successfully added variant data to your submission!<BR><BR>' . "\n\n");

                print('      <FORM action="' . $_SERVER['PHP_SELF'] . '?action=' . $_GET['action'] . '" method="post">' . "\n" .
                      '        <INPUT type="hidden" name="gene" value="' . $_POST['gene'] . '">' . "\n" .
                      '        <INPUT type="submit" value="Continue &raquo;">' . "\n" .
                      '      </FORM>' . "\n\n" .
                      '      <SCRIPT type="text/javascript">' . "\n" .
                      '        <!--' . "\n" .
                      '        setTimeout("document.forms[0].submit()", ' . (empty($_POST['variantid'])? 1000 : 0) . ');' . "\n" .
                      '        // -->' . "\n" .
                      '      </SCRIPT>' . "\n\n");

                require ROOT_PATH . 'inc-bot.php';
                exit;

            } else {
                // Errors, so the whole lot returns to the form.
                lovd_magicUnquoteAll();
            }

        } else {
            // Default values.
            $_POST['pathogenic_reported'] = 5;
            $_POST['pathogenic_concluded'] = 5;

            // 2009-02-16; 2.0-16; Introducing default values.
            if (empty($_POST['variant_name'])) {
                // But only for NEW variants!
                $_CURRDB->initDefaultValues('Variant');
            }
        }



        if (!isset($_GET['sent'])) {
            print('      To add sequence variant data to your submission, please fill out the form below.<BR>' . "\n" .
                  '      <BR>' . "\n\n");
        }

        lovd_showInfoTable('All fields, unless specified otherwise, are required to be filled in.', 'information');

        lovd_errorPrint();

        // Table.
        print('      <FORM action="' . $_SERVER['PHP_SELF'] . '?action=' . $_GET['action'] . '&amp;add=' . $_GET['add'] . '&amp;sent=true" method="post">' . "\n" .
              '        <INPUT type="hidden" name="gene" value="' . $_POST['gene'] . '">' . "\n" .
              '        <TABLE border="0" cellpadding="0" cellspacing="1" width="950">');

        // Array which will make up the form table.
        $aForm = array_merge(
                             array(
                                    array('POST', '', '', '40%', '60%'),
                                    array('', 'print', '<B>Add sequence variant data to the ' . $_POST['gene'] . ' database</B>'),
                                    array('Variant allele', 'select', 'allele', 1, $_SETT['var_allele'], false, false, false),
                                  ),
                             $_CURRDB->buildFormTable('Variant'));
        // 2007-12-06; 2.0-02; Ooops... submitters never had the option to report the pathogenicity.
        $aForm = array_merge($aForm,
                             array(
                                    'skip',
                                    array('Pathogenicity (reported)', 'select', 'pathogenic_reported', 1, $_SETT['var_pathogenic'], false, false, false),
                                  ));

        if (IS_CURATOR) {
            // Authorized user logged in; provide status control.
            $aForm = array_merge($aForm,
                                 array(
                                        array('Pathogenicity (concluded)', 'select', 'pathogenic_concluded', 1, $_SETT['var_pathogenic'], false, false, false),
                                        array('Variant status', 'select', 'status', 1, $_SETT['var_status'], false, false, false),
                                      ));
        }

        $aForm = array_merge($aForm,
                             array(
                                    'skip',
                                    // 2007-08-08; 2.0-beta-07; Added "cancel" button.
//                                    array('', 'submit', 'Add variant data'),
                                    array('', 'print', '<INPUT type="submit" value="Add variant data">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<INPUT type="submit" value="Cancel" onclick="document.forms[1].submit(); return false;" style="border : 1px solid #FF4422;">'),
                                  ));

        $_MODULES->processForm('SubmitVariantData', $aForm);
        lovd_viewForm($aForm);

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

        print('      <FORM action="' . $_SERVER['PHP_SELF'] . '?action=' . $_GET['action'] . '" method="post">' . "\n" .
              '        <INPUT type="hidden" name="gene" value="' . $_POST['gene'] . '">' . "\n" .
              '      </FORM>' . "\n\n");

        require ROOT_PATH . 'inc-bot.php';
        exit;
    }





    // Step 3: Add patient data.
    if ($_GET['add'] == 'pat' && empty($_SESSION['submit_pat'])) {
        // Add patient data.

        // 2007-08-09; 2.0-beta-07; Added option for curators and up (and submitters
        // owning the patient) to submit variants to an existing patient.
        if (!empty($_POST['patientid'])) {
            // Patient ID sent; we're importing everything.
            $zData = @mysql_fetch_assoc(mysql_query('SELECT p.* FROM ' . TABLE_PATIENTS . ' AS p WHERE p.patientid = "' . $_POST['patientid'] . '"'));

            if (!$zData || (!HAS_AUTH && $zData['submitterid'] != $_SUBS['submitterid'])) {
                // Wrong ID, apparently.
                if (!$zData) {
                    lovd_showInfoTable('Could not find this patient in the system!', 'stop');
                } else {
                    // This is a submitter, and he/she does not own this patient.
                    // The issue is, the system can't even store who added the variants if we would allow this.
                    lovd_showInfoTable('This patient has not been submitted by you!', 'stop');
                }
                print('      <FORM action="' . $_SERVER['PHP_SELF'] . '?action=' . $_GET['action'] . '" method="post">' . "\n" .
                      '        <INPUT type="hidden" name="gene" value="' . $_POST['gene'] . '">' . "\n" .
                      '        <INPUT type="submit" value="Continue &raquo;">' . "\n" .
                      '      </FORM>' . "\n\n" .
                      '      <SCRIPT type="text/javascript">' . "\n" .
                      '        <!--' . "\n" .
                      '        setTimeout("document.forms[0].submit()", 3000);' . "\n" .
                      '        // -->' . "\n" .
                      '      </SCRIPT>' . "\n\n");

                require ROOT_PATH . 'inc-bot.php';
                exit;
            }

            // $zData comes from the database, and is therefore not quoted.
            lovd_magicQuote($zData);

            // Mark as being taken from the database.
            $_SESSION['submit_patid'] = $zData['patientid'];
            // Load data into $_POST.
            $aCols = $_CURRDB->getColList('Patient');
            // 2008-10-02; 2.0-13; SubmitterID is now sent by patient form.
            $aCols[] = 'submitterid';
            foreach ($aCols as $sCol) {
                $_POST[$sCol] = $zData[$sCol];
            }
            $_CURRDB->transformSelectValues($_POST, true);
            // Make it look like the form has been sent. This has a downside; if a check returns
            // an error, the user gets the form back, and has to make changes, which will not be
            // put in the database, but will appear in the confirmation email.
            $_GET['sent'] = '';
        }

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

            // Mandatory fields.
            $_CURRDB->checkMandatory('Patient');

            // Field lengths.
            $_CURRDB->checkInputLength();

            // Field types.
            $_CURRDB->checkInputType();

            // Regular expressions.
            $_CURRDB->checkInputRegExp();

            // 2006-12-07; 2.0-alpha-02
            // XSS attack prevention. Simply deny input of HTML, PHP other stuff blocked by strip_tags().
            lovd_checkXSS();

            if (!lovd_error()) {
                // Insert into $_SESSION and return to the submission overview page.
                $aCols = $_CURRDB->getColList('Patient');
                // 2008-10-02; 2.0-13; SubmitterID is now sent by patient form.
                $aCols[] = 'submitterid';
                if (!HAS_AUTH) {
                    $_POST['submitterid'] = $_AUTH['submitterid'];
                }

                // Build session array.
                $aSession = array();
                foreach ($aCols as $sCol) {
                    // 2007-12-21; 2.0-02; Reset to empty value to prevent notices + warnings about non-existent indexes.
                    if (!isset($_POST[$sCol])) {
                        // Multiple select list without selected value.
                        $_POST[$sCol] = '';
                    }
                    if (is_array($_POST[$sCol])) {
                        $_POST[$sCol] = implode(';', $_POST[$sCol]);
                    }
                    $aSession[$sCol] = $_POST[$sCol];
                }
                $_SESSION['submit_pat'] = $aSession;

                // Thank the user...
                print('      Successfully added patient data to your submission!<BR><BR>' . "\n\n");
                
                print('      <FORM action="' . $_SERVER['PHP_SELF'] . '?action=' . $_GET['action'] . '" method="post">' . "\n" .
                      '        <INPUT type="hidden" name="gene" value="' . $_POST['gene'] . '">' . "\n" .
                      '        <INPUT type="submit" value="Continue &raquo;">' . "\n" .
                      '      </FORM>' . "\n\n" .
                      '      <SCRIPT type="text/javascript">' . "\n" .
                      '        <!--' . "\n" .
                      '        setTimeout("document.forms[0].submit()", ' . (empty($_POST['patientid'])? 1000 : 0) . ');' . "\n" .
                      '        // -->' . "\n" .
                      '      </SCRIPT>' . "\n\n");

                require ROOT_PATH . 'inc-bot.php';
                exit;

            } else {
                // Errors, so the whole lot returns to the form.
                lovd_magicUnquoteAll();
            }

        } else {
            // Default values.

            // 2009-02-16; 2.0-16; Introducing default values.
            if (empty($_POST['patientid'])) {
                // But only for NEW patients!
                $_CURRDB->initDefaultValues('Patient');
            }
        }



        if (!isset($_GET['sent'])) {
            print('      To add patient data to your submission, please fill out the form below.<BR>' . "\n" .
                  '      <BR>' . "\n\n");
        }

        lovd_showInfoTable('All fields, unless specified otherwise, are required to be filled in.', 'information');

        lovd_errorPrint();

        // Table.
        print('      <FORM action="' . $_SERVER['PHP_SELF'] . '?action=' . $_GET['action'] . '&amp;add=' . $_GET['add'] . '&amp;sent=true" method="post">' . "\n" .
              '        <INPUT type="hidden" name="gene" value="' . $_POST['gene'] . '">' . "\n" .
              '        <TABLE border="0" cellpadding="0" cellspacing="1" width="950">');

        // Array which will make up the form table.
        $aForm = array_merge(
                             array(
                                    array('POST', '', '', '40%', '60%'),
                                    array('', 'print', '<B>Add patient data to the ' . $_POST['gene'] . ' database</B>'),
                                  ),
                             $_CURRDB->buildFormTable('Patient'));

        // 2008-10-02; 2.0-13; Allow curator to set submitter.
        if (IS_CURATOR) {
            $qSubmitters = mysql_query('SELECT s.submitterid, CONCAT(c.country, " / ", s.city, " - ", s.firstname, " ", s.lastname, " (#", s.submitterid, ")") AS name FROM ' . TABLE_SUBS . ' AS s LEFT JOIN ' . TABLE_COUNTRIES . ' AS c ON (s.country = c.code) WHERE s.deleted = 0 ORDER BY name');
            $aForm = array_merge($aForm,
                                 array(
                                        'skip',
                                        array('Submitter', 'select', 'submitterid', 1, $qSubmitters, '-- None --', false, false),
                                      ));
        }

        $aForm = array_merge($aForm,
                             array(
                                    'skip',
                                    // 2007-08-08; 2.0-beta-07; Added "cancel" button.
//                                    array('', 'submit', 'Add patient data'),
                                    array('', 'print', '<INPUT type="submit" value="Add patient data">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<INPUT type="submit" value="Cancel" onclick="document.forms[1].submit(); return false;" style="border : 1px solid #FF4422;">'),
                                  ));
        $_MODULES->processForm('SubmitPatientData', $aForm);
        lovd_viewForm($aForm);

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

        print('      <FORM action="' . $_SERVER['PHP_SELF'] . '?action=' . $_GET['action'] . '" method="post">' . "\n" .
              '        <INPUT type="hidden" name="gene" value="' . $_POST['gene'] . '">' . "\n" .
              '      </FORM>' . "\n\n");

        require ROOT_PATH . 'inc-bot.php';
        exit;
    }





    // Step 4: Show options / overview.
    require ROOT_PATH . 'inc-lib-list.php';
    lovd_showInfoTable('Please note that your submission is only stored <I>after</I> you click the button "Finalize submission".', 'warning');
    print('      In order to complete your submission, please review your options below.' . (!IS_CURATOR? ' On submission, your data will be collected and stored in the database. You will immediately receive a confirmation email and the curator(s) of the specified gene will be notified that a new submission has taken place. Your submission will appear online when the curator agrees with your findings.' : '') . '<BR><BR>' . "\n\n");



    // Do we have some mutation data already?
    print('      <HR>' . "\n" .
          '      <B>Sequence variant data</B><BR>' . "\n");
    if (!count($_SESSION['submit_muts'][$_POST['gene']])) {
        $nMuts = 0;
        print('      You haven\'t provided any sequence variant data yet.<BR><BR>' . "\n");

    } else {
        // Show mutation list.
        $nMuts = count($_SESSION['submit_muts'][$_POST['gene']]);
        print('      <SPAN class="S11">' . $nMuts . ' entr' . ($nMuts == 1? 'y' : 'ies') . '</SPAN><BR>' . "\n");

        // Array which will make up the table (header and data).
        $aTable = $_CURRDB->buildTable('list');

        // Remove columns not for variants.
        $aCols = $_CURRDB->getColList('Variant');
        foreach ($aTable as $sCol => $aCol) {
            if (!in_array($sCol, $aCols)) {
                unset($aTable[$sCol]);
            }
        }

        // Add columns.
        $aTable = array_merge(
                 array(
                        'pathogenic_' => array('Path.', 40),
                        'allele' => array('Allele', '120'),
                      ),
                 $aTable,
                 array(
                        'status' => array('Status', '60'),
                        'del' => array('&nbsp;', '14', 'valign="middle" align="center"'),
                      ));

        // Total width.
        $nTotalWidth = 2;
        foreach ($aTable as $aCol) {
            $nTotalWidth += $aCol[1] + 8;
        }

        // Stretch table up, to respect column widths.
        print('      <IMG src="' . ROOT_PATH . 'gfx/trans.png" alt="" width="' . $nTotalWidth . '" height="1"><BR>' . "\n\n");

        // Table.
        print('      <TABLE border="0" cellpadding="0" cellspacing="1" class="data">' . "\n" .
              '        <TR>');

        foreach ($aTable as $sField => $aCol) {
            print("\n" . '          <TH' . (!empty($aCol[2])? ' ' . $aCol[2] : '') . (is_numeric($aCol[1])? ' width="' . $aCol[1] . '"' : '') . '>' . $aCol[0] . '</TH>');
        }
        print('</TR>');

        foreach ($_SESSION['submit_muts'][$_POST['gene']] as $nVar => $zData) {
            print("\n" .
                  '        <TR valign="top" onmouseover="this.className = \'hover\';" onmouseout="this.className = \'\';">');

            // $zData is taken from a form, and is therefore still quoted.
            lovd_magicUnquote($zData);

            $zData['pathogenic_'] = $_SETT['var_pathogenic_short'][$zData['pathogenic']];
            $zData['allele']      = $_SETT['var_allele'][$zData['allele']];
            $nVar                 = str_pad($nVar, 2, '0', STR_PAD_LEFT);
            $zData['del']         = '<A href="' . $_SERVER['PHP_SELF'] . '?action=' . $_GET['action'] . '&amp;gene=' . $_POST['gene'] . '&amp;delete=var' . $nVar . '" onclick="if (!confirm(\'Are you sure to remove this data from your submission?\')) { return false; } return true;"><IMG src="gfx/mark_0.png" alt="Delete" title="Delete" width="11" height="11" border="0"></A>';
            $zData['status']      = $_SETT['var_status'][$zData['status']];

            // Parse and build Custom Links.
            lovd_buildLinks($zData);

            // Transform select lists' values.
            $_CURRDB->transformSelectValues($zData);

            foreach ($aTable as $sField => $aCol) {
                print("\n" . '          <TD' . (!empty($aCol[2])? ' ' . $aCol[2] : '') . (is_numeric($aCol[1])? ' width="' . $aCol[1] . '"' : '') . '>' . (!$zData[$sField]? '-' : $zData[$sField]) . '</TD>');
            }
            print('</TR>');
        }
        print('</TABLE><BR>' . "\n");
    }

    print('      <FORM action="' . $_SERVER['PHP_SELF'] . '?action=' . $_GET['action'] . '&amp;add=var" method="post">' . "\n" .
          '        <INPUT type="hidden" name="gene" value="' . $_POST['gene'] . '">' . "\n" .
          '        <INPUT type="hidden" name="variant_name" value="">' . "\n" .
          '        <INPUT type="submit" value="Add' . (count($_SESSION['submit_muts'][$_POST['gene']])? ' more' : '') . ' variant data &raquo;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<INPUT type="submit" value="Using an existing variant &raquo;" onclick="lovd_openWindow(\'' . $_SERVER['PHP_SELF'] . '?action=search_var&amp;gene=' . $_POST['gene'] . lovd_showSID(true, true) . '\', \'SearchVar\', 400, 175); return false;">' . "\n" .
          '      </FORM>' . "\n" .
          '      <HR> ' . "\n" .
          '      <BR><BR>' . "\n\n");



    // Do we have some patient data already?
    print('      <HR>' . "\n" .
          '      <B>Patient data</B><BR>' . "\n");
    if (empty($_SESSION['submit_pat'])) {
        $nPat = 0;
        print('      You haven\'t provided any patient data yet.<BR><BR>' . "\n");

        print('      <FORM action="' . $_SERVER['PHP_SELF'] . '?action=' . $_GET['action'] . '&amp;add=pat" method="post">' . "\n" .
              '        <INPUT type="hidden" name="gene" value="' . $_POST['gene'] . '">' . "\n" .
              '        <INPUT type="hidden" name="patientid" value="">' . "\n" .
              '        <INPUT type="submit" value="Add new patient data &raquo;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<INPUT type="submit" value="Using an existing patient &raquo;" onclick="var patid = window.prompt(\'Please insert the internal Patient ID reference number\', \'\'); if (patid) { document.forms[1].patientid.value = patid; } else { return false; }">' . "\n" .
              '      </FORM>' . "\n");

    } else {
        // Show patient data list.
        $nPat = count($_SESSION['submit_pat']);

        // Array which will make up the table (header and data).
        $aTable = $_CURRDB->buildTable('list');

        // Remove columns not for variants.
        $aCols = $_CURRDB->getColList('Patient');
        foreach ($aTable as $sCol => $aCol) {
            if (!in_array($sCol, $aCols)) {
                unset($aTable[$sCol]);
            }
        }

        // Add Del column.
        $aTable['del'] = array('&nbsp;', '14', 'valign="middle" align="center"');

        // Total width.
        $nTotalWidth = 2;
        foreach ($aTable as $aCol) {
            $nTotalWidth += $aCol[1] + 8;
        }

        // Stretch table up, to respect column widths.
        print('      <IMG src="' . ROOT_PATH . 'gfx/trans.png" alt="" width="' . $nTotalWidth . '" height="1"><BR>' . "\n\n");

        // Table.
        print('      <TABLE border="0" cellpadding="0" cellspacing="1" class="data">' . "\n" .
              '        <TR>');

        foreach ($aTable as $sField => $aCol) {
            print("\n" . '          <TH' . (!empty($aCol[2])? ' ' . $aCol[2] : '') . (is_numeric($aCol[1])? ' width="' . $aCol[1] . '"' : '') . '>' . $aCol[0] . '</TH>');
        }
        print('</TR>');

        $zData = $_SESSION['submit_pat'];
        print("\n" .
              '        <TR valign="top" onmouseover="this.className = \'hover\';" onmouseout="this.className = \'\';">');

        // $zData is taken from a form, and is therefore still quoted.
        lovd_magicUnquote($zData);

        $zData['del'] = '<A href="' . $_SERVER['PHP_SELF'] . '?action=' . $_GET['action'] . '&amp;gene=' . $_POST['gene'] . '&amp;delete=pat" onclick="if (!confirm(\'Are you sure to remove this data from your submission?\')) { return false; } return true;"><IMG src="gfx/mark_0.png" alt="Delete" title="Delete" width="11" height="11" border="0"></A>';

        // Parse and build Custom Links.
        lovd_buildLinks($zData);

        // Transform select lists' values.
        $_CURRDB->transformSelectValues($zData);

        // 2008-10-02; 2.0-13; Allow curator to set submitter.
        if ($_CURRDB->colExists('Patient/Reference') && $zData['submitterid']) {
            list($sReference) = mysql_fetch_row(mysql_query('SELECT reference FROM ' . TABLE_SUBS . ' WHERE submitterid = "' . $zData['submitterid'] . '"'));
            if ($sReference) {
                $zData['Patient/Reference'] .= (!empty($zData['Patient/Reference'])? ', ' : '') . '<A href="#" onclick="lovd_openWindow(\'' . ROOT_PATH . 'submitters.php?action=view&amp;view=' . $zData['submitterid'] . lovd_showSID(true, true) . '\', \'SubmitterView\', 400, 175, event.screenX - 50, event.screenY - 50); return false;">' . $sReference . '</A>';
            }
        }

        foreach ($aTable as $sField => $aCol) {
            print("\n" . '          <TD' . (!empty($aCol[2])? ' ' . $aCol[2] : '') . (is_numeric($aCol[1])? ' width="' . $aCol[1] . '"' : '') . '>' . (!$zData[$sField]? '-' : $zData[$sField]) . '</TD>');
        }
        print('</TR>');
        print('</TABLE><BR>' . "\n");
    }

    print('      <HR> ' . "\n" .
          '      <BR><BR>' . "\n\n");



    // Finalize submission.
    // 2009-06-09; 2.0-19; If finalize button is clicked before both variant and patient data are submitted you will get an error message.
    print('      <FORM action="' . $_SERVER['PHP_SELF'] . '?action=finalize" method="post">' . "\n" .
          '        <INPUT type="hidden" name="gene" value="' . $_POST['gene'] . '">' . "\n" .
          '        <INPUT type="submit" value="Finalize submission" style="font-weight : bold;');
    if (!($nMuts && $nPat)) {
        if ($nMuts && !$nPat) {
            $sMessage = 'You have not provided any patient data yet';
        } elseif (!$nMuts && $nPat) {
            $sMessage = 'You have not provided any variant data yet';
        } else {
            $sMessage = 'You have not provided any variant or patient data yet';
        }
        print(' color : #AAAAAA;" onclick="alert(\'' . $sMessage . '\'); return false;"');
    }
    print('">' . "\n" .
          '      </FORM>' . "\n");

    require ROOT_PATH . 'inc-bot.php';
    exit;





} elseif ($_GET['action'] == 'finalize' && !empty($_POST['gene']) && in_array($_POST['gene'], lovd_getGeneList()) && !empty($_SESSION['submit_muts'][$_POST['gene']]) && !empty($_SESSION['submit_pat'])) {
    // Put all the stuff in the database.

    // Require form functions - just for lovd_sort() and lovd_wrapText();
    require ROOT_PATH . 'inc-lib-form.php';

    // Finalize submission; put in database and mail people.
    require ROOT_PATH . 'inc-top.php';
    require ROOT_PATH . 'class/currdb.php';
    $_CURRDB = new CurrDB(true, $_POST['gene']);
    $_CURRDB->hideCols('public_form', lovd_isCurator($_POST['gene']));
    lovd_printHeader('submit', 'Submit new sequence variant');

    // If using transactional tables; begin transaction.
    if ($_INI['database']['engine'] == 'InnoDB') {
        // FIXME; It's better to use 'START TRANSACTION', but that's only available from 4.0.11.
        //   This works from the introduction of InnoDB in 3.23.
        @mysql_query('BEGIN WORK');
    }



    // Step 1: Add patient to database.
    if (empty($_SESSION['submit_patid'])) {
        $sQ = 'INSERT INTO ' . TABLE_PATIENTS . ' (';
        $aColsToCopy = $_CURRDB->getColList('Patient');
        // 2008-10-02; 2.0-13; SubmitterID is now sent by patient form.
        $aColsToCopy[] = 'submitterid';
        $aCol = array();
        foreach ($aColsToCopy as $sCol) {
            if (isset($_SESSION['submit_pat'][$sCol])) {
                $sQ .= (substr($sQ, -1) == '('? '' : ', ') . '`' . $sCol . '`';
                $aCol[] = $_SESSION['submit_pat'][$sCol];
            }
        }
        $sQ .= ', created_by, created_date) VALUES (';

        // FIXME; reference should include the submitter stuff, as indicated by him.
        foreach ($aCol as $key => $val) {
            $sQ .= ($key? ', ' : '') . '"' . $val . '"';
        }
        // 2008-10-02; 2.0-13; SubmitterID is now sent by patient form.
        // "0" (created_by) means submitter; "ID" means user.
        $sQ .= ', "' . (HAS_AUTH? $_AUTH['userid'] : '0') . '", NOW())';

        $q = mysql_query($sQ);
        if (!$q) {
            lovd_dbFout('SubmitNew_A', $sQ, mysql_error());
        }
    
        // Remember patient id.
        $nPatientID = str_pad(mysql_insert_id(), 7, '0', STR_PAD_LEFT);

    } else {
        // Patient ID was stored, therefore we're not inserting into the database.
        $nPatientID = $_SESSION['submit_patid'];
    }



    // Step 2: Add variants + links to database.
    $aColsToCopy = $_CURRDB->getColList('Variant');
    $aVariantIDs = array();
    // 2008-10-09; 2.0-13; Use this separate array because we don't want to loose existing variants when things to wrong.
    $aVariantsAdded = array();
    $nMinStatus  = STATUS_NEW; // Determine the min status for the submission email.

    $sMutationCol = $_CURRDB->getMutationCol();
    if ($sMutationCol && in_array($sMutationCol, array('Variant/DNA', 'Variant/RNA'))) {
        // Find mutation column, include sort column in list.
        $aColsToCopy[] = 'sort';
    }

    foreach ($_SESSION['submit_muts'][$_POST['gene']] as $nMut => $aMut) {
        // Determine sort code if sort column is in the list.
        if (in_array('sort', $aColsToCopy)) {
            // 2009-06-12; 2.0-19; Added exon column for better search results.
            // A bit crude; we're not checking if Variant/Exon exists, we just suppress a possible notice.
            $aMut['sort'] = @lovd_sort($aMut[$sMutationCol], $aMut['Variant/Exon']);
        }

        // 2008-04-24; 2.0-06; Include auto generated Variant/DBID field for submitters.
        if (array_search('Variant/DBID', $aColsToCopy) === false && !empty($aMut['Variant/DBID'])) {
            // Variant/DBID was hidden, but value is filled in.
            $aColsToCopy[] = 'Variant/DBID';
        }

        // Determine if mutation already exists in database. If so, insert link only.
        $sQ = 'SELECT variantid FROM ' . TABLEPREFIX . '_' . $_POST['gene'] . '_variants WHERE ';
        foreach ($aColsToCopy as $key => $sCol) {
            if (isset($aMut[$sCol])) {
                $sQ .= (!$key? '' : ' AND ') . '`' . $sCol . '` = "' . $aMut[$sCol] . '"';
            }
        }
        $sQ .= ' ORDER BY variantid LIMIT 1';
        list($nVariantID) = @mysql_fetch_row(mysql_query($sQ));
        if (!$nVariantID) {
            // Not found!
            $sQ = 'INSERT INTO ' . TABLEPREFIX . '_' . $_POST['gene'] . '_variants (';
            $nMut = str_pad($nMut + 1, 2, '0', STR_PAD_LEFT); // 01, 02, 03, 04 ...
            $aCol = array();
            foreach ($aColsToCopy as $sCol) {
                if (isset($aMut[$sCol])) {
                    $sQ .= (substr($sQ, -1) == '('? '' : ', ') . '`' . $sCol . '`';
                    $aCol[] = $aMut[$sCol];
                }
            }
            $sQ .= ') VALUES (';

            foreach ($aCol as $key => $val) {
                $sQ .= ($key? ', ' : '') . '"' . $val . '"';
            }
            $sQ .= ')';

            $q = mysql_query($sQ);
            if (!$q) {
                // Save the mysql_error before it disappears.
                $sError = mysql_error();

                if ($_INI['database']['engine'] == 'InnoDB') {
                    @mysql_query('ROLLBACK');
                } else {
                    if (empty($_SESSION['submit_patid'])) {
                        @mysql_query('DELETE FROM ' . TABLE_PATIENTS . ' WHERE patientid = "' . $nPatientID . '"');
                    }
                    // 2008-10-09; 2.0-13; Use this separate array because we don't want to loose existing variants when things to wrong.
                    if (count($aVariantsAdded)) {
                        @mysql_query('DELETE FROM ' . TABLEPREFIX . '_' . $_POST['gene'] . '_variants WHERE variantid = "' . implode('" OR variantid = "', $aVariantsAdded) . '"');
                    }
                    // 2008-10-09; 2.0-13; Nor do we want to loose the Pat2Var values...
                    if (empty($_SESSION['submit_patid'])) {
                        @mysql_query('DELETE FROM ' . TABLE_PAT2VAR . ' WHERE patientid = "' . $nPatientID . '"');
                    }
                }
                lovd_dbFout('SubmitNew_B' . $nMut, $sQ, $sError);
            }

            // Remember variant id.
            $nVariantID = str_pad(mysql_insert_id(), 7, '0', STR_PAD_LEFT);
            $aVariantsAdded[] = $nVariantID;
        }



        // Store variant id.
        $aVariantIDs[] = $nVariantID;

        // FIXME; 0 (created_by) means, not a user. How do we do this with submitters?
        $sQ = 'INSERT INTO ' . TABLE_PAT2VAR . ' VALUES ("' . $nPatientID . '", "' . $aMut['allele'] . '", "' . $_POST['gene'] . '", "' . $nVariantID . '", "' . $aMut['pathogenic'] . '", "' . $aMut['status'] . '", "' . (HAS_AUTH? $_AUTH['userid'] : 0) . '", NOW(), NULL, NULL)';
        $q = mysql_query($sQ);
        if (!$q) {
            // Save the mysql_error before it disappears.
            $sError = mysql_error();

            if ($_INI['database']['engine'] == 'InnoDB') {
                @mysql_query('ROLLBACK');
            } else {
                if (empty($_SESSION['submit_patid'])) {
                    @mysql_query('DELETE FROM ' . TABLE_PATIENTS . ' WHERE patientid = "' . $nPatientID . '"');
                }
                // 2008-10-09; 2.0-13; Use this separate array because we don't want to loose existing variants when things to wrong.
                if (count($aVariantsAdded)) {
                    @mysql_query('DELETE FROM ' . TABLEPREFIX . '_' . $_POST['gene'] . '_variants WHERE variantid = "' . implode('" OR variantid = "', $aVariantsAdded) . '"');
                }
                // 2008-10-09; 2.0-13; Nor do we want to loose the Pat2Var values...
                if (empty($_SESSION['submit_patid'])) {
                    @mysql_query('DELETE FROM ' . TABLE_PAT2VAR . ' WHERE patientid = "' . $nPatientID . '"');
                }
            }
            lovd_dbFout('SubmitNew_C' . $nMut, $sQ, $sError);
        }

        // Store status, so we can see if curator even needs to publish anything from this submission.
        if ($nMinStatus > $aMut['status']) {
            $nMinStatus = $aMut['status'];
        }
    }

    // If we don't do this, we haven't got anything in the DB... duh!
    if ($_INI['database']['engine'] == 'InnoDB') {
        // Could this actually fail?!!??
        @mysql_query('COMMIT');
    }

    // 2007-12-05; 2.0-02; Fixed bug #20 - Gene's "Last update" field not updated.
    if (lovd_isCurator($_POST['gene'])) {
        // We assume here that curators and up will probably submit entries as public and therefore 'change' the way the database looks like for the public.
        lovd_setUpdatedDate($_POST['gene']);
    }

    // Submission completed successfully!
    // Write to log...
    lovd_writeLog('MySQL:Event', 'SubmitNew', $_AUTH['username'] . ' (' . mysql_real_escape_string($_AUTH['name']) . ') successfully created new submission for ' . $_POST['gene'] . ' (Patient #' . $nPatientID . '; Mutation' . (count($aVariantIDs) == 1? '' : 's') . ' #' . implode(', #', $aVariantIDs) . ')');



    // Step 3: Mail curators and submitter.
    // Grab email adresses of addressees, to prevent double emails.
    $aEmails = array();

    // Find me the curator of this gene...
    $qCurators = mysql_query('SELECT u.name, u.email FROM ' . TABLE_CURATES . ' AS c, ' . TABLE_USERS . ' AS u WHERE c.userid = u.userid AND c.symbol = "' . $_POST['gene'] . '" ORDER BY u.level DESC, u.name');
    $nCurators = mysql_num_rows($qCurators);
    $sCurators = '';
    while ($r = mysql_fetch_row($qCurators)) {
        // If email hasn't been added before, add it.
        if (!in_array($r[1], $aEmails)) {
            // 2009-02-27; 2.0-16; Sending emails on Windows requires removal of names from the email addresses.
            $sCurators .= ($sCurators? ', ' : '') . (ON_WINDOWS? '' : '"' . $r[0] . '" ') . '<' . $r[1] . '>';
            $aEmails[] = $r[1];
        }
    }

    // 2009-02-27; 2.0-16; Sending emails on Windows requires removal of names from the email addresses.
    $sSubmitter = (ON_WINDOWS? '' : '"' . $_AUTH['name'] . '" ') . '<' . str_replace(array("\r\n", "\r", "\n"), '>, <', trim($_AUTH['email'])) . '>';

    $sBody = 'LOVD ' . $_SETT['system']['version'] . ' @ ' . $_CONF['location_name'] . ' for ' . $_POST['gene'] . "\n" .
             'To Curator' . ($nCurators == 1? ' ' : 's') . '  : ' . str_replace('"', '', $sCurators) . "\n" .
             'CC Submitter : ' . str_replace('"', '', $sSubmitter) . "\n\n" .
             'Dear Curator' . ($nCurators == 1? '' : 's') . ',' . "\n\n" .
             $_AUTH['name'] . ' has submitted an addition to the ' . $_POST['gene'] . ' database.' . "\n" .
             ($nMinStatus <  STATUS_MARKED? 'This submission won\'t be viewable to the public until you as curator agree with the additions. ' : '') .
             'Below is a copy of the submission.' . "\n\n";
    // 2009-04-06; 2.0-17; Add the location of the new entry, so that the curator can just click the link.
    if ($_CONF['location_url']) {
        $sBody .= 'To view the new entry, click this link (you may need to log in first):' . "\n" .
                  $_CONF['location_url'] . 'variants.php?select_db=' . $_POST['gene'] . '&action=view&view=' . $nPatientID . "\n\n";
    }
    $sBody .= 'Regards,' . "\n" .
              '    LOVD system at ' . $_CONF['location_name'] . "\n\n";

    // Submitter information.
    $sBody .= str_repeat('-', 80) . "\n" .
              '  SUBMITTER DETAILS' . "\n" .
              str_repeat('-', 80) . "\n";

    // Array containing the fields.
    $aMail =
             array(
                    'submitterid' => 'Submitter ID',
                    'userid' => 'User ID',
                    'name' => 'Name',
                    'institute' => 'Institute',
                    'department' => 'Department',
                    'address' => 'Address',
                    'city' => 'City',
                    'country_' => 'Country',
                    'email' => 'Email address',
                    'telephone' => 'Telephone',
                  );

    // Remove unnecessary columns.
    if (HAS_AUTH) {
        unset($aMail['submitterid'], $aMail['department'], $aMail['address'], $aMail['city'], $aMail['country_'], $aMail['telephone']);
    } else {
        unset($aMail['userid']);
    }

    // Fetching country name.
    if (!HAS_AUTH) {
        list($_AUTH['country_']) = mysql_fetch_row(mysql_query('SELECT country FROM ' . TABLE_COUNTRIES . ' WHERE code = "' . $_AUTH['country'] . '"'));
    }

    // Padding to...
    $lPad = 0;
    foreach ($aMail as $val) {
        $l = strlen($val);
        if ($l > $lPad) {
            $lPad = $l;
        }
    }

    foreach ($aMail as $key => $val) {
        $sBody .= str_pad($val, $lPad) . ' : ' . str_replace("\n", "\n" . str_repeat(' ', $lPad + 3), lovd_wrapText($_AUTH[$key], 80 - $lPad - 3)) . "\n";
    }
    $sBody .= str_repeat('-', 80) . "\n\n";

    // Variant information.
    $sBody .= str_repeat('-', 80) . "\n" .
              '  VARIANT DETAILS' . "\n" .
              str_repeat('-', 80) . "\n";

    // Array containing the fields.
    $aMail = $_CURRDB->buildTable('detail');

    // Remove columns not for variants.
    $aCols = $_CURRDB->getColList('Variant');
    foreach ($aMail as $sCol => $aCol) {
        if (!in_array($sCol, $aCols)) {
            unset($aMail[$sCol]);
        }
    }

    // Add columns.
    $aMail = array_merge(
             array(
                    'pathogenic' => 'Pathogenic',
                    'allele' => 'Allele',
                  ),
             $aMail,
             array(
                    'status' => 'Status',
                  ));

    // Padding to...
    $lPad = 0;
    foreach ($aMail as $val) {
        $l = strlen($val);
        if ($l > $lPad) {
            $lPad = $l;
        }
    }

    // Loop the variant data.
    foreach ($_SESSION['submit_muts'][$_POST['gene']] as $nVar => $zData) {
        // Good practice when mailing and printing.
        lovd_magicUnquote($zData);

        $zData['pathogenic'] = $_SETT['var_pathogenic'][$zData['pathogenic']{0}] . (HAS_AUTH? ' (reported) / ' . $_SETT['var_pathogenic'][$zData['pathogenic']{1}] . ' (concluded)' : '');
        $zData['allele']     = $_SETT['var_allele'][$zData['allele']];
        $zData['status']     = $_SETT['var_status'][$zData['status']];

        // Transform select lists' values.
        $_CURRDB->transformSelectValues($zData);

        foreach ($aMail as $key => $val) {
            $sBody .= str_pad($val, $lPad) . ' : ' . str_replace("\n", "\n" . str_repeat(' ', $lPad + 3), lovd_wrapText($zData[$key], 80 - $lPad - 3)) . "\n";
        }
        $sBody .= str_repeat('-', 80) . "\n";
    }
    $sBody .= "\n";

    // Patient information.
    $sBody .= str_repeat('-', 80) . "\n" .
              '  PATIENT DETAILS' . (empty($_SESSION['submit_patid'])? '' : ' (Addition to existing patient)') . "\n" .
              str_repeat('-', 80) . "\n";

    // Array containing the fields.
    $aMail = $_CURRDB->buildTable('detail');

    // Remove columns not for variants.
    $aCols = $_CURRDB->getColList('Patient');
    foreach ($aMail as $sCol => $aCol) {
        if (!in_array($sCol, $aCols)) {
            unset($aMail[$sCol]);
        }
    }

    // Padding to...
    $lPad = 0;
    foreach ($aMail as $val) {
        $l = strlen($val);
        if ($l > $lPad) {
            $lPad = $l;
        }
    }

    // Loop the variant data.
    $zData = $_SESSION['submit_pat'];

    // Good practice when mailing and printing.
    lovd_magicUnquote($zData);

    // Transform select lists' values.
    $_CURRDB->transformSelectValues($zData);

    foreach ($aMail as $key => $val) {
        $sBody .= str_pad($val, $lPad) . ' : ' . str_replace("\n", "\n" . str_repeat(' ', $lPad + 3), lovd_wrapText($zData[$key], 80 - $lPad - 3)) . "\n";
    }
    $sBody .= str_repeat('-', 80) . "\n";

    // Set proper subject.
    $sSubject = 'LOVD submission (' . $_POST['gene'] . ')';

    // Send mail.
    $bMail = @mail($sCurators,
                   $sSubject,
                   lovd_wrapText($sBody),
                   $_SETT['headers'] .
                   (HAS_AUTH && in_array($_AUTH['email'], $aEmails)? '' : $sEol . 'Cc: ' . $sSubmitter));
    if (HAS_AUTH) {
        $aEmails[] = $_AUTH['email'];
    }



    // Step 4: Possibly, mail the database admin if he's not the submitter or the curator(s).
    if ($bMail) {
        if ($_CONF['send_fwd'] && !in_array($_SETT['admin']['email'], $aEmails)) {
            // Sent mail to curator(s), send copy to database administrator.
            $sBody = 'Dear ' . $_SETT['admin']['name'] . ",\n\n" .
                     'As requested, a copy of the message I\'ve just sent.' . "\n\n" .
                     str_repeat('-', 30) . ' Forwarded  Message ' . str_repeat('-', 30) . "\n\n" .
                     rtrim($sBody) . "\n\n" .
                     str_repeat('-', 27) . ' End of Forwarded Message ' . str_repeat('-', 27) . "\n";

            // Send mail.
            // 2009-02-27; 2.0-16; Sending emails on Windows requires removal of names from the email addresses.
            $bMail = @mail((ON_WINDOWS? '' : '"' . $_SETT['admin']['name'] . '" ') . '<' . $_SETT['admin']['email'] . '>',
                           'Fw: ' . $sSubject,
                           lovd_wrapText($sBody),
                           $_SETT['headers']);

            if (!$bMail) {
                // Couldn't sent confirmation to admin...
                lovd_writeLog('MySQL:Error', 'EmailNotify', $_SERVER['PHP_SELF'] . ' returned SubmitNewNotifyAdmin error for submitter ' . $_AUTH['username'] . ' (' . mysql_real_escape_string($_AUTH['name']) . ')');
            }
        }

        // Thank the user...
        print('      Thank you, ' . $_AUTH['name'] . '. Your submission was successful!<BR>' . "\n" .
              '      The curator' . ($nCurators == 1? '' : 's') . ' of the ' . $_POST['gene'] . ' database ha' . ($nCurators == 1? 's' : 've') . ' been sent an email containing your submission. A copy has been sent to you.<BR><BR>' . "\n\n");

    } else {
        // Couldn't sent confirmation...
        lovd_writeLog('MySQL:Error', 'EmailNotify', $_SERVER['PHP_SELF'] . ' returned SubmitNewNotify error for submitter ' . $_AUTH['username'] . ' (' . mysql_real_escape_string($_AUTH['name']) . ')');

        print('      Thank you, ' . $_AUTH['name'] . '. Your submission was successful!<BR>' . "\n" .
              '      <B>Due to an unknown error, no email regarding the submission could be sent to the curator' . ($nCurators == 1? '' : 's') . ' of the ' . $_POST['gene'] . ' database. Your submission has successfully been added to the database.</B><BR><BR>' . "\n\n");
    }

    // 2009-06-11; 2.0-19; Authorized users: jump back to the patient.
    if (HAS_AUTH) {
        print('      <SCRIPT type="text/javascript">' . "\n" .
              '        <!--' . "\n" .
              '        setTimeout("window.location.href = \'' . PROTOCOL . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['PHP_SELF'])) . '/variants.php' . '?select_db=' . $_POST['gene'] . '&action=view&view=' . $nPatientID . '\'", ' . ($bMail? 2000 : 5000) . ');' . "\n" .
              '        // -->' . "\n" .
              '      </SCRIPT>' . "\n\n");
    }

    // Now that we're done, we must clean the $_SESSION vars.
    $_SESSION['submit_pat'] = array();
    unset($_SESSION['submit_patid']);
    $_SESSION['submit_muts'][$_POST['gene']] = array();

    require ROOT_PATH . 'inc-bot.php';
    exit;





} elseif ($_GET['action'] == 'search_var' && !empty($_GET['gene']) && in_array($_GET['gene'], lovd_getGeneList())) {
    // Search for mutation, and send it's ID to the form so that the data can be loaded.

    require ROOT_PATH . 'inc-top-clean.php';

    // Fetch mutation names.
    require ROOT_PATH . 'class/currdb.php';
    $_CURRDB = new CurrDB(true, $_GET['gene']);
    $sMutationCol = $_CURRDB->getMutationCol();
    $aMuts = array();
    // In case this doesn't run: big deal! It's just a service to the user, that's all.
    $qMuts = @mysql_query('SELECT DISTINCT `' . $sMutationCol . '` FROM ' . TABLEPREFIX . '_' . $_GET['gene'] . '_variants ORDER BY ' . ($_CURRDB->colExists('Variant/Exon')? '`Variant/Exon`, ' : '') . 'sort');
    while ($r = @mysql_fetch_row($qMuts)) {
        $aMuts[] = $r[0];
    }
    $sMuts = '["' . implode('",' . "\n" . '                "', $aMuts) . '"];';

    // Show form and all.
    lovd_includeJS('inc-js-autocomplete.js');

    print("\n" .
          '      <TABLE border="0" cellpadding="0" cellspacing="0" width="100%"><TR><TD>' . "\n" .
          '      Please insert the mutation name below.<BR><BR>' . "\n\n" .
          '      <FORM action="' . $_SERVER['PHP_SELF'] . '?action=' . $_GET['action'] . '&amp;gene=' . $_GET['gene'] . '" method="post" onsubmit="opener.document.forms[0][\'variant_name\'].value = this[\'variant_name\'].value; opener.document.forms[0].submit(); self.close();">' . "\n" .
          '        <INPUT type="text" name="variant_name" size="30" value="" id="variant_name"><BR>' . "\n" .
          '        <INPUT type="submit" value="Cancel" onclick="self.close(); return false;" style="border : 1px solid #FF4422;">' . "\n" .
          '        <INPUT type="submit" value="Review variant data &raquo;">' . "\n" .
          '      </FORM>' . "\n");
    print('      </TD></TR></TABLE>' . "\n\n");

    // 2007-12-14; 2.0-02; Fixing feature non-functional in IE.
    // Normally, we would just print it out here, but that doesn't work in IE. So we're going to dump it in inc-bot-clean.php.
    $sBotClean = '      <SCRIPT type="text/javascript">' . "\n" .
                 '        <!--' . "\n" .
                 '        data = ' . $sMuts . "\n\n" .
                 '        AutoComplete_Create("variant_name", data, 5);' . "\n" .
                 '        // -->' . "\n" .
                 '      </SCRIPT>' . "\n\n";

    require ROOT_PATH . 'inc-bot-clean.php';
    exit;





} else {
    // Default action:
    header('Location: ' . PROTOCOL . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . '?action=submit' . lovd_showSID(true));
    exit;
}
?>