<?php
/*******************************************************************************
 *
 * LEIDEN OPEN VARIATION DATABASE (LOVD)
 *
 * Created     : 2003-04-27
 * Modified    : 2008-08-05
 * For LOVD    : 2.0-10
 *
 * Access      : Administrator
 * Purpose     : Remove all traces of LOVD from the MySQL database.
 *
 * Copyright   : 2004-2009 Leiden University Medical Center; http://www.LUMC.nl/
 * Programmer  : Ing. Ivo F.A.C. Fokkema <I.F.A.C.Fokkema@LUMC.nl>
 * Last edited : Ing. Ivo F.A.C. Fokkema <I.F.A.C.Fokkema@LUMC.nl>
 *
 *
 * This file is part of LOVD.
 *
 * LOVD is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * LOVD is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with LOVD; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 *************/

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

require 'inc-top.php'; // Install dir's own top include.
print('<TABLE border="0" cellpadding="0" cellspacing="0" width="100%" style="padding : 0px 10px;">' . "\n" .
      '  <TR valign="top">' . "\n" .
      '    <TD>' . "\n");
lovd_printHeader('uninstall', 'Uninstall LOVD');

// Require DB admin clearance.
lovd_requireAUTH(LEVEL_ADMIN);

// If we've gotten this far, we apparently have/had an config, status and user
// table. This should suffice to uninstall LOVD even if we don't have a working
// installation.

// Uninstall lock set?
if (isset($_CONF['lock_uninstall']) && $_CONF['lock_uninstall']) {
    // Sorry, can't remove LOVD...
    lovd_showInfoTable('Can\'t uninstall LOVD - Uninstall lock in place.', 'warning');
    require ROOT_PATH . 'inc-bot.php';
    exit;
}





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

    if (!isset($_GET['confirm'])) {
        // Check password.
        if (md5($_POST['password']) != $_AUTH['password']) {
            lovd_errorAdd('Please enter your correct password for authorization.');
        }
    }

    if (!lovd_error()) {
        if (isset($_GET['confirm'])) {
            // Check password.
            if (md5($_POST['password']) != $_AUTH['password']) {
                lovd_errorAdd('Please enter your correct password for authorization.');
            }

            if (!lovd_error()) {
                // OK, uninstall the lot.
                print('      <PRE>' . "\n" .
                      'Uninstalling LOVD...' . "\n");

                // Firstly: uninstall the genes.
                $qGenes = mysql_query('SELECT symbol, gene FROM ' . TABLE_DBS . ' ORDER BY symbol');
                $nGenes = mysql_num_rows($qGenes);
                if ($nGenes) {
                    print('  Removing gene' . ($nGenes == 1? '' : 's') . '...' . "\n");
                    while (list($sSymbol, $sGene) = mysql_fetch_row($qGenes)) {
                        print('    Removing ' . $sSymbol . ' (' . $sGene . ')... ');
                        $b = (mysql_query('DROP TABLE IF EXISTS ' . TABLEPREFIX . '_' . $sSymbol . '_variants') && mysql_query('DROP TABLE IF EXISTS ' . TABLEPREFIX . '_' . $sSymbol . '_columns'));
                        if ($b) {
                            $b = mysql_query('DELETE FROM ' . TABLE_DBS . ' WHERE symbol = "' . $sSymbol . '"');
                        }
                        if ($b) {
                            print('OK' . "\n");
                        } else {
                            print('Failed!' . "\n");
                            print('      </PRE>' . "\n");
                            require ROOT_PATH . 'inc-bot.php';
                            exit;
                        }
                    }
                }

                // Remove tables...
                print('  Removing database tables [');
                flush();

                // There is no real reason to reverse the table, but the most
                // important tables are mentioned first in the list and I feel
                // better when removing them last.
                $aTables = array_reverse(array_values($_TABLES));
                
                foreach ($aTables as $key => $sTable) {
                    if (@mysql_query('DROP TABLE IF EXISTS ' . $sTable)) {
                        print('<GARBAGE>.</GARBAGE>');
                        if ($key + 1 == count($aTables)) {
                            print('] OK' . "\n");
                        } else {
                            flush();
                            usleep(200000);
                        }

                    } else {
                        print ('] Failed!' . "\n");
                        print('      </PRE>' . "\n");
                        require ROOT_PATH . 'inc-bot.php';
                        exit;
                    }
                }
                print('      </PRE>' . "\n");

                // All done!
                print('      LOVD successfully uninstalled. Thank you for having used LOVD!' . "\n\n");

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

        } else {
            // Show some general statistics and warn about loss of data.
            print('      <PRE>' . "\n");

            // Does any of these tables exist yet?
            print('Checking LOVD installation...' . "\n");
            $aTables = array();
            $q = mysql_query('SHOW TABLES LIKE "' . TABLEPREFIX . '\_%"');
            while ($r = mysql_fetch_row($q)) {
                if (in_array($r[0], $_TABLES)) {
                    $aTables[] = $r[0];
                }
            }
            $nTables = count($aTables);
            print('  Found ' . $nTables . '/' . count($_TABLES) . ' tables.' . "\n");

            // Real simple checkup on the status and config table.
            require 'inc-sql-tables.php';

            // Does the config and status tables look somewhat OK?
            if (count($_CONF) == (substr_count($aTableSQL['TABLE_CONFIG'], "\n") - 1)) {
                print('  Configuration seems OK.' . "\n");
            } elseif (!in_array(TABLE_CONFIG, $aTables)) {
                print('  Configuration table missing!' . "\n");
            } else {
                print('  Configuration table corrupt!' . "\n");
            }

            // Does the config and status tables look somewhat OK?
// FIXME; can this be a little more specific?!!??
            if (count($_STAT) >= (substr_count($aTableSQL['TABLE_STATUS'], "\n") - 1)) {
                print('  Status seems OK.' . "\n");
            } elseif (!in_array(TABLE_STATUS, $aTables)) {
                print('  Status table missing!' . "\n");
            } else {
                print('  Status table corrupt!' . "\n");
            }
            flush();

            // General statistics...
            print("\n");
            list($nUsers) = mysql_fetch_row(mysql_query('SELECT COUNT(*) FROM ' . TABLE_USERS));
            list($nSubs) = mysql_fetch_row(mysql_query('SELECT COUNT(*) FROM ' . TABLE_SUBS));
            $nGenes = GENE_COUNT;
            list($nPats) = mysql_fetch_row(mysql_query('SELECT COUNT(*) FROM ' . TABLE_PATIENTS));
            list($nVars) = mysql_fetch_row(mysql_query('SELECT COUNT(*) FROM ' . TABLE_PAT2VAR));
            print('  Found ' . $nUsers . ' user' . ($nUsers == 1? '' : 's') . '.' . "\n" .
                  '  Found ' . $nSubs . ' submitter' . ($nSubs == 1? '' : 's') . '.' . "\n" .
                  '  Found ' . $nGenes . ' gene' . ($nGenes == 1? '' : 's') . '.' . "\n" .
                  '  Found ' . $nPats . ' patient' . ($nPats == 1? '' : 's') . '.' . "\n" .
                  '  Found ' . $nVars . ' variant' . ($nVars == 1? '' : 's') . '.' . "\n");
            print('      </PRE>' . "\n");

            if ($nGenes || $nPats || $nVars) {
                lovd_showInfoTable('FINAL WARNING! If you did not download the variation and patient data stored in the LOVD system, everything will be lost!', 'warning');
            }

            print('      Please confirm uninstalling LOVD using your password.<BR>' . "\n" .
                  '      <BR>' . "\n\n");
        }

        lovd_errorPrint();

        print('      <FORM action="' . $_SERVER['PHP_SELF'] . '?sent&amp;confirm" method="post">' . "\n" .
              '        <TABLE border="0" cellpadding="0" cellspacing="0" width="300">' . "\n" .
              '          <TR align="right">' . "\n" .
              '            <TD width="125" style="padding-right : 5px;">Password</TD>' . "\n" .
              '            <TD width="175"><INPUT type="password" name="password" size="20"></TD></TR>' . "\n" .
              '          <TR align="right">' . "\n" .
              '            <TD width="125">&nbsp;</TD>' . "\n" .
              '            <TD width="175"><INPUT type="submit" value="Uninstall LOVD" style="font-weight : bold; font-size : 11px; width : 110px;"></TD></TR></TABLE></FORM>' . "\n\n");

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

}

if (!isset($_GET['sent'])) {
    print('      Welcome to the LOVD uninstaller. Please continue by providing your password.<BR>' . "\n" .
          '      <BR>' . "\n\n");

    lovd_showInfoTable('WARNING! If you did not download your variations, you will loose all of your data!', 'warning');
}

lovd_errorPrint();

print('      <FORM action="' . $_SERVER['PHP_SELF'] . '?sent" method="post">' . "\n" .
      '        <TABLE border="0" cellpadding="0" cellspacing="0" width="300">' . "\n" .
      '          <TR align="right">' . "\n" .
      '            <TD width="125" style="padding-right : 5px;">Password</TD>' . "\n" .
      '            <TD width="175"><INPUT type="password" name="password" size="20"></TD></TR>' . "\n" .
      '          <TR align="right">' . "\n" .
      '            <TD width="125">&nbsp;</TD>' . "\n" .
      '            <TD width="175">' . "\n" .
      '              <TABLE border="0" cellpadding="0" cellspacing="0" width="162">' . "\n" .
      '                <TR>' . "\n" .
      '                  <TD align="left"><INPUT type="button" value="&lt;&lt; Cancel" onclick="window.location.href=\'' . PROTOCOL . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['PHP_SELF']), '/') . '/' . ROOT_PATH . 'setup.php' . lovd_showSID() . '\';" style="font-weight : bold; font-size : 11px; width : 80px;"></TD>' . "\n" .
      '                  <TD align="right"><INPUT type="submit" value="Next &gt;&gt;" style="font-weight : bold; font-size : 11px; width : 70px;"></TD></TR></TABLE></TD></TR></TABLE></FORM>' . "\n\n");

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