<?php
/*******************************************************************************
 *
 * LEIDEN OPEN VARIATION DATABASE (LOVD)
 *
 * Created     : 2006-05-08
 * Modified    : 2010-02-15
 * For LOVD    : 2.0-25
 *
 * Access      : Curators and up.
 * Purpose     : Allows managers to create new genes and edit previously added
 *               genes. Also curators can, to a certain extent, edit genes.
 *
 * Copyright   : 2004-2010 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 manager clearance.
lovd_requireAUTH(LEVEL_CURATOR);

// 2009-09-03; 2.0-21; Provide better error message than "Hack attempt", when user is using green "switch gene" icon and gets into a gene that he is denied access to.
// Needs to be curator for THIS gene.
if (!lovd_isCurator($_SESSION['currdb'])) {
    // NOTE that this does not unset certain links in the top menu. Links are available.
    require ROOT_PATH . 'inc-top.php';
    lovd_showInfoTable((GENE_COUNT? 'You are not allowed access to ' . (GENE_COUNT > 1? 'this gene database' : 'the installed gene database') . '. Please contact your manager or the administrator to grant you access.' : 'There are currently no databases installed.'), 'stop');
    require ROOT_PATH . 'inc-bot.php';
    exit;
}





if (($_GET['action'] == 'edit' && !empty($_GET['edit'])) || $_GET['action'] == 'manage') {
    // Edit gene (managers and, to some extent, curators).

    // Should we forward to the setup?
    if ($_AUTH['level'] >= LEVEL_MANAGER && $_GET['action'] == 'edit' && !empty($_GET['edit'])) {
        // Manager specifically gave gene to edit.
        $bSetup = true;
    } else {
        $bSetup = false;
        // 2009-09-11; 2.0-22; We need to "lock" the gene that's being edited, so we don't overwrite another gene's settings!
        if (empty($_GET['edit'])) {
            $_GET['edit'] = $_SESSION['currdb'];
        }
    }

    $zData = @mysql_fetch_assoc(mysql_query('SELECT * FROM ' . TABLE_DBS . ' WHERE symbol = "' . $_GET['edit'] . '"'));
    if (!$zData) {
        // Wrong ID, apparently.
        require ROOT_PATH . 'inc-top.php';
        if ($bSetup) {
            lovd_printHeader('setup_genes_manage', 'LOVD Setup - Manage configured genes');
        } else {
            lovd_printHeader('config_gene_manage', 'LOVD Configuration - Manage gene');
        }
        lovd_showInfoTable('No such ID!', 'stop');
        require ROOT_PATH . 'inc-bot.php';
        exit;
    }

    // Require form functions.
    require ROOT_PATH . 'inc-lib-form.php';

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

        // Mandatory fields.
        $aCheck =
                 array(
                        'gene' => 'Full gene name',
                        'chrom_location' => 'Chromosome location',
                        'password' => 'Enter your password for authorization',
                      );

        foreach ($aCheck as $key => $val) {
            if (empty($_POST[$key])) {
                lovd_errorAdd('Please fill in the \'' . $val . '\' field.');
            }
        }

        // 2010-01-13; 2.0-24; Added proper check on chromosome information because we need this to map to the genome!
        if (!empty($_POST['chrom_location']) && !empty($_POST['refseq_build']) && substr($_POST['refseq_build'], 0, 2) == 'hg' && !preg_match('/^([0-9]{1,2}|[XY])([pq0-9.-]+)?$/', $_POST['chrom_location'])) {
            lovd_errorAdd('Incorrect chromosome location. Chromosome locations have to start with the chromosome number or name (X,Y), possibly followed by the chromosome band location.');
        }

        // GenBank file or ID.
        if ($_POST['genbank']) {
            if (empty($_POST['genbank_uri'])) {
                lovd_errorAdd('If you wish to use a GenBank file, please fill in the "GenBank file name or ID" field. Otherwise, clear the "Has a GenBank file" field.');
            } else {
                if (basename($_POST['genbank_uri']) != $_POST['genbank_uri']) {
                    // 2008-03-06; 2.0-05; Disallow Directory Traversal Attack.
                    lovd_errorAdd('Illegal GenBank file name or ID.');
                } elseif ($_POST['genbank'] == 1 && !is_readable(ROOT_PATH . 'genbank/' . $_POST['genbank_uri'])) {
                    // 2008-09-18; 2.0-12; If a proper GenBank filename has been selected, check if it's there.
                    lovd_errorAdd('Could not find the given GenBank file in the genbank directory. Are you sure it\'s in the right location?');
                }
            }

            // 2009-11-11; 2.0-23; The c. -> g. mapping fields are mandatory if the database is using a GenBank file.
            // FIXME; maybe before these checks, check if the field is empty but $_POST['genbank_uri'] contains useful information... then copy, in stead of complain.
            if (empty($_POST['refseq_genomic'])) {
                lovd_errorAdd('Please fill in the \'NCBI accession number for the genomic reference sequence\' field.');
            } elseif (!preg_match('/^N(G|C)_[0-9]{6,9}\.[0-9]{1,2}$/', $_POST['refseq_genomic'])) {
                lovd_errorAdd('Please fill in a proper NG or NC accession number in the \'NCBI accession number for the genomic reference sequence\' field, like \'NG_012232.1\'.');
            }
            if (empty($_POST['refseq_mrna'])) {
                lovd_errorAdd('Please fill in the \'NCBI accession number for the coding DNA reference sequence\' field.');
            } elseif (!preg_match('/^NM_[0-9]{6,9}\.[0-9]{1,2}$/', $_POST['refseq_mrna'])) {
                lovd_errorAdd('Please fill in a proper NM accession number in the \'NCBI accession number for the coding DNA reference sequence\' field, like \'NM_004006.2\'.');
            }
            if (empty($_POST['refseq_build']) || !isset($_SETT['human_builds'][$_POST['refseq_build']])) {
                lovd_errorAdd('Please fill in the \'Human Build to map to (UCSC/NCBI)\' field.');
            }
        }

        // 2010-01-13; 2.0-24; When refseq is filled in, we need an URL!
        if (!empty($_POST['refseq']) && empty($_POST['refseq_url'])) {
            lovd_errorAdd('You have selected that there is a human-readable reference sequence. Please fill in the "Human-readable reference sequence location" field. Otherwise, select \'No\' for the "This gene has a human-readable reference sequence" field.');
        }

        // Disclaimer text.
        if ($_POST['disclaimer'] == 2 && empty($_POST['disclaimer_text'])) {
            lovd_errorAdd('If you wish to use an own disclaimer, please fill in the "Text for own disclaimer" field. Otherwise, select \'No\' for the "Include disclaimer" field.');
        }

        // Numeric fields.
        $aCheck =
                 array(
                        'id_entrez' => 'Entrez Gene (Locuslink) ID',
                        'id_omim_gene' => 'OMIM Gene ID',
                        'header_align' => 'Header aligned to',
                        'footer_align' => 'Footer aligned to',
                      );

        foreach ($aCheck as $key => $val) {
            if ($_POST[$key] && !is_numeric($_POST[$key])) {
                lovd_errorAdd('The \'' . $val . '\' field has to contain a numeric value.');
            }
        }

        // URLs.
        $aCheck =
                 array(
                        'url_homepage' => 'Homepage URL',
                        'refseq_url' => 'Human-readable reference sequence location',
                      );

        foreach ($aCheck as $key => $val) {
            if ($_POST[$key] && !lovd_matchURL($_POST[$key])) {
                lovd_errorAdd('The \'' . $val . '\' field does not seem to contain a correct URL.');
            }
        }

        // List of external links.
        if ($_POST['url_external']) {
            $aExternalLinks = explode("\r\n", trim($_POST['url_external']));
            foreach ($aExternalLinks as $n => $sLink) {
                if (!lovd_matchURL($sLink) && (!preg_match('/^[^<>]+ <?([^< >]+)>?$/', $sLink, $aRegs) || !lovd_matchURL($aRegs[1]))) {
                    lovd_errorAdd('External link #' . ($n + 1) . ' (' . htmlspecialchars($sLink) . ') not understood.');
                }
            }
        }

        // OMIM disease ID list.
        if ($_POST['id_omim_disease']) {
            // OMIM Disease ID's.
            $aOMIM = explode("\r\n", $_POST['id_omim_disease']);
            foreach ($aOMIM as $n => $sOMIM) {
                if (!preg_match('/^[0-9]{1,6} [^<>]+$/', $sOMIM)) {
                    lovd_errorAdd('OMIM Disease ID #' . ($n + 1) . ' (' . htmlspecialchars($sOMIM) . ') not understood.');
                }
            }
        }

        // User had to enter his/her password for authorization.
        if ($_POST['password'] && md5($_POST['password']) != $_AUTH['password']) {
            lovd_errorAdd('Please enter your correct password for authorization.');
        }

        if (!lovd_error()) {
            // Query text.
            $sQ = 'UPDATE ' . TABLE_DBS . ' SET ';

            $_POST['reference'] = $_POST['Gene/Reference'];

            // Standard fields to be used.
            // 2009-08-20; 2.0-21; added by Gerard: id_uniprot, show_genecards.
            $aQ = array('gene', 'chrom_location', 'refseq_genomic', 'refseq_mrna', 'refseq_build', 'c_position_mrna_start', 'c_position_mrna_end', 'c_position_cds_end', 'g_position_mrna_start', 'g_position_mrna_end', 'reference', 'url_homepage', 'url_external', 'allow_download', 'allow_index_wiki', 'id_entrez', 'id_omim_gene', 'id_omim_disease', 'id_uniprot', 'show_hgmd', 'show_genecards', 'show_genetests', 'note_index', 'note_listing', 'genbank', 'genbank_uri', 'refseq', 'refseq_url', 'disclaimer', 'disclaimer_text', 'header', 'header_align', 'footer', 'footer_align');

            foreach ($aQ as $key => $val) {
                $sQ .= ($key? ', ' : '') . $val . ' = "' . $_POST[$val] . '"';
            }

            $sQ .= ', edited_by = "' . $_AUTH['userid'] . '", edited_date = NOW() WHERE symbol = "' . $zData['symbol'] . '"';

            $q = mysql_query($sQ);
            if (!$q) {
                $sError = mysql_error(); // Save the mysql_error before it disappears.
                require ROOT_PATH . 'inc-top.php';
                if ($bSetup) {
                    lovd_printHeader('setup_genes_manage', 'LOVD Setup - Manage configured genes');
                } else {
                    lovd_printHeader('config_gene_manage', 'LOVD Configuration - Manage gene');
                }
                lovd_dbFout('GeneEdit', $sQ, $sError);
            }

            // Write to log...
            lovd_writeLog('MySQL:Event', 'GeneEdit', $_AUTH['username'] . ' (' . mysql_real_escape_string($_AUTH['name']) . ') successfully edited gene ' . $zData['symbol'] . ' (' . $_POST['gene'] . ')');

            // Thank the user...
            require ROOT_PATH . 'inc-top.php';
            if ($bSetup) {
                lovd_printHeader('setup_genes_manage', 'LOVD Setup - Manage configured genes');
            } else {
                lovd_printHeader('config_gene_manage', 'LOVD Configuration - Manage gene');
            }
            print('      Successfully edited gene ' . stripslashes($_POST['gene']) . '!<BR><BR>' . "\n\n");

            // 2009-12-07; 2.0-23; Reload the variant mapping, if needed.
            if ($zData['refseq_mrna'] != $_POST['refseq_mrna'] || $zData['refseq_build'] != $_POST['refseq_build']) {
                @mysql_query('UPDATE ' . TABLEPREFIX . '_' . $zData['symbol'] . '_variants SET c_position_start = NULL, c_position_start_intron = NULL, c_position_end = NULL, c_position_end_intron = NULL, g_position_start = NULL, g_position_end = NULL');
                $_SESSION['mapping']['time_complete'] = 0; // Redo mapping.
            }

            // 2009-09-23; 2.0-22; Moved the module part down and added a notification, because we don't want the user to wait without knowing what's happening.
            // 2008-09-19; 2.0-12; Reload Mutalyzer module, if present, if GenBank file has been added or changed.
            // 2010-02-15; 2.0-25; Also reload the Mutalyzer module if the genbank file does not change, but the genbank field is changed to 1!!!
            if ($_POST['genbank'] == 1 && $_MODULES->isLoaded('mutalyzer') && ($zData['genbank_uri'] != $_POST['genbank_uri'] || $zData['genbank'] != 1)) {
                print('      <B>Please wait while the Mutalyzer module is being reloaded....</B><BR>' . "\n\n");
                flush();

                // 2009-06-30; 2.0-19; Force reload of specifically this gene's genbank file by emptying the field. Otherwise the module may not resend the file.
                $aSett = $_MODULES->getSettings('mutalyzer');
                $aSett['accessionid'][$zData['symbol']] = '';
                $_MODULES->setSettings('mutalyzer', $aSett);
                // Then, reload the module.
                $_MODULES->disable('mutalyzer');
                $_MODULES->enable('mutalyzer');

                // 2009-09-23; 2.0-22; Check if there's still a gene left (we won't receive errors from the Mutalyzer module).
                $aSett = $_MODULES->getSettings('mutalyzer');
                $aFailed = array();
                foreach ($aSett['accessionid'] as $sGene => $sID) {
                    if (!$sID) {
                        // A gene that exists in this list, but does not have an ID associated to it, is proof of a failed Mutalyzer run.
                        // However, there is always the possibility that the "genbank" field is no longer "1", if it's not the current gene.
                        if ($sGene == $_GET['edit']) {
                            $aFailed[] = $sGene;
                            break;
                        } else {
                            // We need to verify something first!
                            if (mysql_fetch_row(mysql_query('SELECT symbol FROM ' . TABLE_DBS . ' WHERE symbol = "' . $sGene . '" AND genbank = 1'))) {
                                $aFailed[] = $sGene;
                                break;
                            }
                        }
                    }
                }
                $nFailed = count($aFailed);

                if ($nFailed) {
                    print('      <I>The Mutalyzer module failed reloading for ' . $nFailed . ' gene' . ($nFailed == 1? '' : 's'). '; ' . implode(', ', $aFailed) . '.</I> The Mutalyzer module will not work for th' . ($nFailed == 1? 'is gene' : 'ese genes') . ', unless you submit your GenBank files there manually and fill in the UD numbers in LOVD.<BR><BR>' . "\n\n\n\n");
                } else {
                    print('      <I>Successful!</I><BR><BR>' . "\n\n\n\n");
                }
            }

            if (empty($nFailed)) {
                // Manipulation to send users coming from the setup right back there...
                if ($bSetup) {
                    $sURL = '/setup_genes.php?action=view&view=' . $_GET['edit'];
                } else {
                    $sURL = '/config.php';
                }

                // Alternate refresh; since we can't send a HTTP header since we don't know how long it will take for the module to reload...
                print('      <SCRIPT type="text/javascript">' . "\n" .
                      '      <!--' . "\n" .
                      '        setTimeout(\'window.location.href = "' . PROTOCOL . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['PHP_SELF']), '/') . $sURL . lovd_showSID(true, true) . '"\', 5000);' . "\n" .
                      '      // -->' . "\n" .
                      '      </SCRIPT>' . "\n\n");
            }

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

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

            // Because we're sending the data back to the form, I need to unset the password fields!
            unset($_POST['password']);
        }

    } else {
        foreach ($zData as $key => $val) {
            if (!isset($_POST[$key]) || !$_POST[$key]) {
                $_POST[$key] = $val;
            }
        }
        $_POST['Gene/Reference'] = $_POST['reference'];
        $_POST['password'] = '';
    }



    require ROOT_PATH . 'inc-top.php';
    if ($bSetup) {
        lovd_printHeader('setup_genes_manage', 'LOVD Setup - Manage configured genes');
    } else {
        lovd_printHeader('config_gene_manage', 'LOVD Configuration - Manage gene');
    }

    lovd_errorPrint();

    // 2009-11-11; 2.0-23; We want to try and force people to use a proper reference sequence.
    lovd_includeJS(ROOT_PATH . 'inc-js-submit_geneform.php');

    // Table.
    // 2009-09-11; 2.0-22; We need to "lock" the gene that's being edited, so we don't overwrite another gene's settings!
    // 2009-11-11; 2.0-23; Added the JS; we want to try and force people to use a proper reference sequence.
    print('      <FORM action="' . $_SERVER['PHP_SELF'] . '?action=' . $_GET['action'] . '&amp;edit=' . $zData['symbol'] . '&amp;sent" method="post" onsubmit="return lovd_checkSubmittedForm();">' . "\n" .
          '        <INPUT type="hidden" name="c_position_mrna_start" value="' . $_POST['c_position_mrna_start'] . '">' . "\n" .
          '        <INPUT type="hidden" name="c_position_mrna_end" value="' . $_POST['c_position_mrna_end'] . '">' . "\n" .
          '        <INPUT type="hidden" name="c_position_cds_end" value="' . $_POST['c_position_cds_end'] . '">' . "\n" .
          '        <INPUT type="hidden" name="g_position_mrna_start" value="' . $_POST['g_position_mrna_start'] . '">' . "\n" .
          '        <INPUT type="hidden" name="g_position_mrna_end" value="' . $_POST['g_position_mrna_end'] . '">' . "\n" .
          '        <TABLE border="0" cellpadding="0" cellspacing="1" width="760">');

    $aHumanBuilds = array();
    foreach ($_SETT['human_builds'] as $sCode => $aBuild) {
        $aHumanBuilds[$sCode] = $sCode . ' / ' . $aBuild['ncbi_name'];
    }

    // Array which will make up the form table.
    $aForm = array(
                    array('POST', '', '', '40%', '60%'),
                    array('', 'print', '<B>General information</B>'),
                    'hr',
                    array('Full gene name', 'text', 'gene', 40),
                    'hr',
                    array('Chromosome location', 'text', 'chrom_location', 15),
                    array('', 'print', '<SPAN class="form_note">Example: Xp21.2</SPAN>'),
                    'hr',
                    'skip',
                    'skip',
                    array('', 'print', '<B>Reference sequences</B>'),
                    array('', 'print', '<SPAN class="form_note">Collecting variants requires a proper reference sequence.</SPAN>'),
                    'hr',
                    array('This gene has a GenBank file', 'select', 'genbank', 1, array(1 => 'Uploaded own GenBank file', 2 => 'NCBI GenBank record', 3 => 'Mutalyzer UD identifier'), 'No', false, false),
                    array('', 'print', '<SPAN class="form_note">Without a (genomic) reference sequence the variants in this LOVD database cannot be interpreted properly. A valid genomic GenBank file can be used to map your variants to a genomic location, as well as creating a human-readable reference sequence format and linking to the mutation check Mutalyzer module. Select this option if you have a GenBank file uploaded to the genbank directory (you can <A href="#" onclick="lovd_openWindow(\'' . ROOT_PATH . 'scripts/uploadGenBank.php' . lovd_showSID() . '\', \'ScriptsUploadGenBank\', 800, 300); return false;">do so here</A>), if you want to use a GenBank record at the NCBI or if you have uploaded your GenBank file to Mutalyzer.</SPAN>'),
                    'hr',
                    array('GenBank file name or ID', 'text', 'genbank_uri', 30),
                    array('', 'print', '<SPAN class="form_note">If you have a GenBank file uploaded to the genbank directory, fill in the filename. If you wish to use a NCBI GenBank record, fill in the GenBank accession number. If you have uploaded your GenBank file to Mutalyzer and have received a Mutalyzer UD identifier, fill in this identifier.</SPAN>'),
                    'hr',
                    'skip',
                    array('', 'print', '<SPAN class="form_note"><B>The following three fields are for the mapping of the variants to the genomic reference sequence. They are mandatory if you have a GenBank file, and highly recommended otherwise.</B></SPAN>'),
                    'hr',
                    array('NCBI accession number for the genomic reference sequence', 'text', 'refseq_genomic', 15),
                    array('', 'print', '<SPAN class="form_note">Fill in the NCBI GenBank ID of the genomic reference sequence (NG or NC accession numbers), such as "NG_012232.1" or "NC_000023.10". If you have already provided an NG or NC accession number above, please copy that value to this field. Always include the version number as well!</SPAN>'),
                    'hr',
                    array('NCBI accession number for the coding DNA reference sequence', 'text', 'refseq_mrna', 15),
                    array('', 'print', '<SPAN class="form_note">Fill in the NCBI GenBank ID of the coding DNA reference sequence (NM accession numbers), such as "NM_004006.2". If you have already provided an NM accession number above, please copy that value to this field. Always include the version number as well!</SPAN>'),
                    'hr',
                    array('Human Build to map to (UCSC/NCBI)', 'select', 'refseq_build', 1, $aHumanBuilds, false, false, false),
                    array('', 'print', '<SPAN class="form_note">We need to know which version of the Human Build we need to map to.</SPAN>'),
                    'hr',
                    'skip',
                    'skip',
                    array('', 'print', '<B>Links to information sources (optional)</B>'),
                    array('', 'print', '<SPAN class="form_note">Here you can add links that will be displayed on the gene\'s LOVD gene homepage.</SPAN>'),
                    'hr',
                    array('Homepage URL', 'text', 'url_homepage', 40),
                    array('', 'print', '<SPAN class="form_note">If you have a separate homepage about this gene, you can specify the URL here.<BR>Format: complete URL, including &quot;http://&quot;.</SPAN>'),
                    'hr',
                    array('External links', 'textarea', 'url_external', 55, 3),
                    array('', 'print', '<SPAN class="form_note">Here you can provide links to other resources on the internet that you would like to link to.<BR>One link per line, format: complete URLs or &quot;Description &lt;URL&gt;&quot;.</SPAN>'),
                    'hr',
                    array('Entrez Gene (Locuslink) ID', 'text', 'id_entrez', 10),
                    'hr',
                    array('OMIM Gene ID', 'text', 'id_omim_gene', 10),
                    'hr',
                    array('OMIM Disease IDs', 'textarea', 'id_omim_disease', 40, 3),
                    array('', 'print', '<SPAN class="form_note">One line per OMIM ID, format : &quot;OMIM_ID Disease_name&quot;.<BR>Example : &quot;310200 Duchenne Muscular Dystrophy (DMD)&quot;.</SPAN>'),
                    'hr',
                    // 2009-08-17; 2.0-21; added link to UniProtKB/Swiss-Prot.
                    array('UniProt (SwissProt/TrEMBL) ID', 'text', 'id_uniprot', 10),
                    array('', 'print', '<SPAN class="form_note">This will add a link to the UniProtKB (SwissProt/TrEMBL) database from the gene\'s homepage.</SPAN>'),
                    'hr',
                    array('Provide link to HGMD', 'checkbox', 'show_hgmd', 1),
                    array('', 'print', '<SPAN class="form_note">Do you want a link to this gene\'s entry in the Human Gene Mutation Database added to the homepage?</SPAN>'),
                    'hr',
                    // 2009-08-17; 2.0-21; added link to GeneCards
                    array('Provide link to GeneCards', 'checkbox', 'show_genecards', 1),
                    array('', 'print', '<SPAN class="form_note">Do you want a link to this gene\'s entry in the GeneCards database added to the homepage?</SPAN>'),
                    'hr',
                    array('Provide link to GeneTests', 'checkbox', 'show_genetests', 1),
                    array('', 'print', '<SPAN class="form_note">Do you want a link to this gene\'s entry in the GeneTests database added to the homepage?</SPAN>'),
                    'hr',
                    array('This gene has a human-readable reference sequence', 'select', 'refseq', 1, array('c' => 'Coding DNA', 'g' => 'Genomic'), 'No', false, false),
                    array('', 'print', '<SPAN class="form_note">Although GenBank files are the official reference sequence, they are not very readable for humans. If you have a human-readable format of your reference sequence online, please select the type here.</SPAN>'),
                    'hr',
                    array('Human-readable reference sequence location', 'text', 'refseq_url', 40),
                    array('', 'print', '<SPAN class="form_note">If you used our Reference Sequence Parser to create a human-readable reference sequence, the result is located at<BR>&quot;' . (!empty($_CONF['location_url'])? $_CONF['location_url'] : PROTOCOL . $_SERVER['HTTP_HOST'] . lovd_cleanDirName(dirname($_SERVER['PHP_SELF']) . '/' . ROOT_PATH)) . 'refseq/' . substr($zData['symbol'], 0, strpos($zData['symbol'] . '_', '_')) . '_codingDNA.html&quot;.</SPAN>'),
                    'hr',
                    'skip',
                    'skip',
                    array('', 'print', '<B>Customizations (optional)</B>'),
                    array('', 'print', '<SPAN class="form_note">You can use the following fields to customize the gene\'s LOVD gene homepage.</SPAN>'),
                    'hr',
                    array('Citation reference(s)', 'textarea', 'Gene/Reference', 30, 3),
                    /* FIXME; this is hard-coded... do this gracefully, add links if applicable and remove this if it's deactivated */
                    array('', 'print', '<SPAN class="S11">(Active custom link : <A href="#" onclick="javascript:lovd_openWindow(\'' . ROOT_PATH . 'links.php?view=1&amp;col=Gene/Reference\', \'LinkView\', \'800\', \'200\'); return false;">PubMed</A>)</SPAN>'),
                    'hr',
                    array('Include disclaimer', 'select', 'disclaimer', 1, array(1 => 'Use standard LOVD disclaimer', 2 => 'Use own disclaimer (enter below)'), 'No', false, false),
                    array('', 'print', '<SPAN class="form_note">If you want a disclaimer added to the gene\'s LOVD gene homepage, select your preferred option here.</SPAN>'),
                    'hr',
                    array('Text for own disclaimer', 'textarea', 'disclaimer_text', 55, 3),
                    array('', 'print', '<SPAN class="form_note">Only applicable if you choose to use your own disclaimer (see option above).</SPAN>'),
                    'hr',
                    array('Page header', 'textarea', 'header', 55, 3),
                    array('', 'print', '<SPAN class="form_note">Text entered here will appear above all public gene-specific pages.</SPAN>'),
                    array('Header aligned to', 'select', 'header_align', 1, $_SETT['notes_align'], false, false, false),
                    'hr',
                    array('Page footer', 'textarea', 'footer', 55, 3),
                    array('', 'print', '<SPAN class="form_note">Text entered here will appear below all public gene-specific pages.</SPAN>'),
                    array('Footer aligned to', 'select', 'footer_align', 1, $_SETT['notes_align'], false, false, false),
                    'hr',
                    array('Notes for the LOVD gene homepage', 'textarea', 'note_index', 55, 3),
                    array('', 'print', '<SPAN class="form_note">Text entered here will appear in the General Information box on the gene\'s LOVD gene homepage.</SPAN>'),
                    'hr',
                    array('Notes for the variant listings', 'textarea', 'note_listing', 55, 3),
                    array('', 'print', '<SPAN class="form_note">Text entered here will appear below the gene\'s variant listings.</SPAN>'),
                    'hr',
                    'skip',
                    'skip',
                    array('', 'print', '<B>Security settings</B>'),
                    array('', 'print', '<SPAN class="form_note">Using the following settings you can control some security settings of LOVD.</SPAN>'),
                    'hr',
                    array('Allow public to download variant entries', 'checkbox', 'allow_download', 1),
                    'hr',
                    array('Allow my public variant and patient data to be indexed by WikiProfessional', 'checkbox', 'allow_index_wiki', 1),
                    'hr',
                    'skip',
                    array('Enter your password for authorization', 'password', 'password', 20),
                    array('', 'submit', 'Edit'),
                  );
    $_MODULES->processForm('ConfigGenesEdit', $aForm);
    lovd_viewForm($aForm);

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

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





} elseif ($_GET['action'] == 'empty') {
    // Empty gene variant table.
    list($nTotalVars) = mysql_fetch_row(mysql_query('SELECT COUNT(*) FROM ' . TABLE_PAT2VAR . ' WHERE symbol = "' . $_SESSION['currdb'] . '"'));

    if (!$nTotalVars) {
        // No variants, apparently.
        require ROOT_PATH . 'inc-top.php';
        lovd_printHeader('config_gene_empty', 'LOVD Configuration - Empty gene database');
        lovd_showInfoTable('There are already no variants in this gene database!', 'stop');
        require ROOT_PATH . 'inc-bot.php';
        exit;
    }

    // Require form functions.
    require ROOT_PATH . 'inc-lib-form.php';

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

        // Mandatory fields.
        $aCheck =
                 array(
                        'password' => 'Enter your password for authorization',
                      );

        foreach ($aCheck as $key => $val) {
            if (empty($_POST[$key])) {
                lovd_errorAdd('Please fill in the \'' . $val . '\' field.');
            }
        }

        // User had to enter his/her password for authorization.
        if ($_POST['password'] && md5($_POST['password']) != $_AUTH['password']) {
            lovd_errorAdd('Please enter your correct password for authorization.');
        }

        if (!lovd_error()) {
            // Truncate TABLE_CURRDB_VARS, Drop Variant links, Remove orphaned patients from TABLE_PATIENTS.
            require ROOT_PATH . 'inc-top.php';
            lovd_printHeader('config_gene_empty', 'LOVD Configuration - Empty gene database');

            // Using transactions useless here; TRUNCATE TABLE will commit!

            // Start with the variants table.
            print('      Emptying gene database...<BR>' . "\n" .
                  '      Removing all variants ... ');

            flush();
            $sQ = 'TRUNCATE TABLE ' . TABLE_CURRDB_VARS;
            $q = mysql_query($sQ);
            if (!$q) {
                lovd_dbFout('GeneEmptyA', $sQ, mysql_error());
            }

            // Variant links.
            print('      Removing variant <-> patient links ... ');
            flush();
            $sQ = 'DELETE FROM ' . TABLE_PAT2VAR . ' WHERE symbol = "' . $_SESSION['currdb'] . '"';
            $q = mysql_query($sQ);
            if (!$q) {
                lovd_dbFout('GeneEmptyB', $sQ, mysql_error());
            }
            print('OK<BR>' . "\n");

            // Orphaned patients.
            print('      Removing obsolete patients ... ');
            flush();
            // Backwards compatible with MySQL 4.0 and earlier. These versions do not support subqueries, which would really come in handy now.
            // Fist, determine the ID's of the orphaned patients. Then construct the DELETE query.
            $aOrphaned = array();
            $qOrphaned = mysql_query('SELECT p.patientid FROM ' . TABLE_PATIENTS . ' AS p LEFT OUTER JOIN ' . TABLE_PAT2VAR . ' AS p2v USING (patientid) WHERE p2v.symbol IS NULL');
            while ($rOrphaned = mysql_fetch_row($qOrphaned)) {
                $aOrphaned[] = $rOrphaned[0];
            }
            if (count($aOrphaned)) {
                // Construct DELETE query.
                $sQ = 'DELETE FROM ' . TABLE_PATIENTS . ' WHERE patientid IN (' . implode(', ', $aOrphaned) . ')';
                $q = mysql_query($sQ);
                if (!$q) {
                    lovd_dbFout('GeneEmptyC', $sQ, mysql_error());
                }
                print('OK<BR><BR>' . "\n");
            } else {
                print('N/A<BR><BR>' . "\n");
            }

            // 2007-12-05; 2.0-02; Fixed bug #20 - Gene's "Last update" field not updated.
            lovd_setUpdatedDate($_SESSION['currdb']);

            // Write to log...
            lovd_writeLog('MySQL:Event', 'GeneEmpty', $_AUTH['username'] . ' (' . mysql_real_escape_string($_AUTH['name']) . ') successfully emptied gene ' . $_SESSION['currdb'] . ' (' . $_SETT['currdb']['gene'] . ')');

            // Thank the user...
            print('      Successfully emptied ' . $_SESSION['currdb'] . ' gene database!<BR><BR>' . "\n\n");

            // Alternate refresh; since we can't send a HTTP header...
            print('      <SCRIPT type="text/javascript">' . "\n" .
                  '      <!--' . "\n" .
                  '        setTimeout(\'window.location.href = "' . PROTOCOL . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['PHP_SELF']), '/') . '/config.php' . lovd_showSID() . '"\', 3000);' . "\n" .
                  '      // -->' . "\n" .
                  '      </SCRIPT>' . "\n\n");

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

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

            // Because we're sending the data back to the form, I need to unset the password fields!
            unset($_POST['password']);
        }
    }



    require ROOT_PATH . 'inc-top.php';
    lovd_printHeader('config_gene_empty', 'LOVD Configuration - Empty gene database');

    if (!isset($_GET['sent'])) {
        lovd_showInfoTable('Please note that this will delete all variant information for the ' . $_SESSION['currdb'] . ' database! Patients with variants only in the ' . $_SESSION['currdb'] . ' database will be deleted also! Patients with variants also in other genes, will not be deleted.', 'warning');
    }

    lovd_errorPrint();

    // Table.
    print('      <FORM action="' . $_SERVER['PHP_SELF'] . '?select_db=' . $_SESSION['currdb'] . '&amp;action=' . $_GET['action'] . '&amp;sent" method="post">' . "\n" .
          '        <TABLE border="0" cellpadding="0" cellspacing="1" width="760">');

    // Array which will make up the form table.
    $aForm = array(
                    array('POST', '', '', '50%', '50%'),
                    array('Emptying gene database', 'print', $_SESSION['currdb'] . ' (' . $_SETT['currdb']['gene'] . ')'),
                    'skip',
                    array('Enter your password for authorization', 'password', 'password', 20),
                    array('', 'submit', 'Empty gene database'),
                  );
    $_MODULES->processForm('ConfigGenesEmpty', $aForm);
    lovd_viewForm($aForm);

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

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





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