<?php
/*******************************************************************************
 *
 * LEIDEN OPEN VARIATION DATABASE (LOVD)
 *
 * Created     : 2006-05-01
 * Modified    : 2009-09-04
 * For LOVD    : 2.0-21
 *
 * Access      : Administrator and managers.
 * Purpose     : Allow managers and the database administrator to change the
 *               LOVD system settings.
 *
 * 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-init.php';
require ROOT_PATH . 'inc-lib-form.php';

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

// Require manager clearance.
lovd_requireAUTH(LEVEL_MANAGER);





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

    // Mandatory fields.
    $aCheck =
             array(
                    'email_address' => 'LOVD email address',
                  );

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

    // 2009-03-09; 2.0-17; Database URL should be an URL.
    if ($_POST['location_url'] && !lovd_matchURL($_POST['location_url'])) {
        lovd_errorAdd('Please fill in a correct URL in the \'Database URL\' field.');
    }

    // 2009-03-09; 2.0-17; Database URL is mandatory, if the option "Include in the global LOVD listing" is selected.
    if ($_POST['send_listings'] && empty($_POST['location_url'])) {
        lovd_errorAdd('Please fill in an URL in the \'Database URL\' field, if you want this LOVD installation to be included in the global LOVD listing.');
    }

    // Disease list.
    if ($_POST['disease_list']) {
        $aDiseases = explode("\r\n", $_POST['disease_list']);
        foreach ($aDiseases as $n => $sDisease) {
            if (!preg_match('/^([^=]+|[A-Z0-9 \/\()?._+-]+ *= *[^=]+)$/i', $sDisease)) {
                lovd_errorAdd('Disease #' . ($n + 1) . ' &quot;' . htmlspecialchars($sDisease) . '&quot; not understood.');
            }
        }
    }

    // Technique list.
    if ($_POST['technique_list']) {
        // Technique list.
        $aTechniques = explode("\r\n", $_POST['technique_list']);
        foreach ($aTechniques as $n => $sTechnique) {
            if (!preg_match('/^([^=]+|[A-Z0-9 ._-]+ *= *[^=]+)$/i', $sTechnique)) {
                lovd_errorAdd('Technique ' . ($n+1) . ' &quot;' . htmlspecialchars($sTechnique) . '&quot; not understood.');
            }
        }
    }

    // Email address.
    if ($_POST['email_address'] && !lovd_matchEmail($_POST['email_address'])) {
        lovd_errorAdd('Please fill in a correct email address.');
    }

    // 2008-02-28; 2.0-04; SSL check.
    if ($_POST['use_ssl'] && !SSL) {
        lovd_errorAdd('You\'ve selected to use SSL, but SSL is not currently activated for this session. To force SSL, I must be sure it\'s possible to approach LOVD through an SSL connection (use <A href="https://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . '" target="_blank">https://</A> in stead of http://).');
    }

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

        // 2009-04-22; 2.0-18; Make sure the database URL ends in a /.
        if ($_POST['location_url'] && substr($_POST['location_url'], -1) != '/') {
            $_POST['location_url'] .= '/';
        }

        // Standard fields to be used.
        $aQ = array('system_title', 'location_name', 'location_url', 'email_address', 'send_fwd', 'send_signature', 'send_stats', 'send_listings', 'use_cookies', 'use_ssl', 'my_submissions', 'search_count_entries', 'hide_nonpublic', 'api_feed_history', 'lock_curators', 'lock_submitters', 'allow_unlock');

        // Default values.
        // System title.
        if (empty($_POST['system_title'])) {
            $_POST['system_title'] = 'LOVD - Leiden Open Variation Database';
        }
        // Location name.
        if (empty($_POST['location_name'])) {
            $_POST['location_name'] = $_SERVER['HTTP_HOST'];
        }

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

        $q = mysql_query($sQ);
        if (!$q) {
            require ROOT_PATH . 'inc-top.php';
            lovd_printHeader('setup_settings', 'LOVD Setup - System settings');
            lovd_dbFout('ConfigEdit', $sQ, mysql_error());
        }

        // Update Patient/Phenotype/Disease column according to the $_POST['disease_list'].
        // Not even doing a check if the column exists - takes too much time. Just do the update. It's a HGVS column anyway.
        $sQ = 'UPDATE ' . TABLE_PATIENTS_COLS . ' SET select_options = "' . $_POST['disease_list'] . '" WHERE colid = "Patient/Phenotype/Disease"';
        $q = mysql_query($sQ);
        if (!$q) {
            require ROOT_PATH . 'inc-top.php';
            lovd_printHeader('setup_settings', 'LOVD Setup - System settings');
            lovd_dbFout('DisListEdit', $sQ, mysql_error());
        }

        // Update Patient/Detection/Technique column according to the $_POST['technique_list'].
        // Not even doing a check if the column exists - takes too much time. Just do the update. It's a HGVS column anyway.
        $sQ = 'UPDATE ' . TABLE_PATIENTS_COLS . ' SET select_options = "' . $_POST['technique_list'] . '" WHERE colid = "Patient/Detection/Technique"';
        $q = mysql_query($sQ);
        if (!$q) {
            require ROOT_PATH . 'inc-top.php';
            lovd_printHeader('setup_settings', 'LOVD Setup - System settings');
            lovd_dbFout('TechListEdit', $sQ, mysql_error());
        }

        // Write to log...
        lovd_writeLog('MySQL:Event', 'ConfigEdit', $_AUTH['username'] . ' (' . mysql_real_escape_string($_AUTH['name']) . ') successfully edited system configuration');

        // Thank the user...
        header('Refresh: 3; url=' . PROTOCOL . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . '/setup.php' . lovd_showSID());

        require ROOT_PATH . 'inc-top.php';
        lovd_printHeader('setup_settings', 'LOVD Setup - System settings');
        print('      Successfully edited the system settings!<BR>' . "\n\n");

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

    } else {
        // Errors, thus we must return to the form.
        lovd_magicUnquoteAll();
    }

} else {
    // Default values.
    $zData = $_CONF;
    foreach ($zData as $key => $val) {
        if (!isset($_POST[$key]) || !$_POST[$key]) {
            $_POST[$key] = $val;
        }
    }

    // Add lists.
    list($_POST['disease_list'])   = mysql_fetch_row(mysql_query('SELECT select_options FROM ' . TABLE_PATIENTS_COLS . ' WHERE colid = "Patient/Phenotype/Disease"'));
    list($_POST['technique_list']) = mysql_fetch_row(mysql_query('SELECT select_options FROM ' . TABLE_PATIENTS_COLS . ' WHERE colid = "Patient/Detection/Technique"'));
}



require ROOT_PATH . 'inc-top.php';
lovd_printHeader('setup_settings', 'LOVD Setup - System settings');

// 2009-03-09; 2.0-17; Include javascript for checking the database location BUT through HTTP so that the PHP code in there gets executed.
lovd_includeJS(PROTOCOL . $_SERVER['HTTP_HOST'] . lovd_cleanDirName(dirname($_SERVER['PHP_SELF']) . '/' . ROOT_PATH) . 'inc-js-database_url.php');

if (!isset($_GET['sent'])) {
    print('      To change the system settings, review the form below and press \'Update\' at the bottom of the form.<BR>' . "\n" .
          '      <BR>' . "\n\n");
}

lovd_errorPrint();

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

$aFeedHistory = array('Not available');
for ($i = 1; $i <= 12; $i ++) {
    $aFeedHistory[$i] = $i . ' month' . ($i == 1? '' : 's');
}

// Array which will make up the form table.
$aForm = array(
                array('POST', '', '', '40%', '60%'),
                array('', 'print', '<B>General system settings</B>'),
                'hr',
                array('Title of this LOVD installation', 'text', 'system_title', 50),
                array('', 'print', '<SPAN class="form_note">This will be shown on the top of every page. Default is &quot;LOVD - Leiden Open Variation Database&quot;.</SPAN>'),
                'hr',
                array('Database location (optional)', 'text', 'location_name', 50),
                array('', 'print', '<SPAN class="form_note">The database location is displayed in the public area and in emails sent by LOVD. Is commonly set to a laboratory name or a website name. If not specified, LOVD will use &quot;' . $_SERVER['HTTP_HOST'] . '&quot;.</SPAN>'),
                'hr',
                array('Database URL (optional)', 'print', '<INPUT type="text" name="location_url" size="50" id="location_url" value="' . (empty($_POST['location_url'])? '' : htmlspecialchars($_POST['location_url'])) . '">&nbsp;<SPAN id="location_url_check">(<A href="#" onclick="javascript:lovd_checkURL(); return false;">check</A>)</SPAN>'),
                array('', 'print', '<SPAN class="form_note">This is the URL with which the database can be accessed by the outside world, including "http://" or "https://". It will also be used in emails sent by LOVD. This field is mandatory if you select the "Include in the global LOVD listing" option.<BR>If you click the "check" link, LOVD will verify or try to predict the value.</SPAN>'),
                'hr',
                array('LOVD email address', 'text', 'email_address', 40),
                array('', 'print', '<SPAN class="form_note">This email address will be used to send emails from LOVD to users. We need this address to make sure that emails from LOVD arrive. Please note that although strictly spoken this email address does not need to exist, we recommend that you use a valid address.</SPAN>'),
                'hr',
                array('Forward messages to database admin', 'checkbox', 'send_fwd', 1),
                array('', 'print', '<SPAN class="form_note">This will forward messages to the database administrator about submitter registrations, submissions, and such.</SPAN>'),
                'hr',
                array('Enable \'My Submissions\'', 'checkbox', 'my_submissions', 1),
                array('', 'print', '<SPAN class="form_note">Enabling \'My Submissions\' allows submitters to gather a list of submissions they\'ve made to the database and make changes to them.</SPAN>'),
                'hr',
                array('Enable searching through hidden entries', 'checkbox', 'search_count_entries', 1),
                array('', 'print', '<SPAN class="form_note">Enabling this feature allows the public to find the number of entries in the database (including hidden entries) matching one or more search terms on a specified set of columns. This feature will only mention the number of variant entries matched, without showing them.</SPAN>'),
                'hr',
                array('List database changes in feed for how long?', 'select', 'api_feed_history', 1, $aFeedHistory, false, false, false),
                array('', 'print', '<SPAN class="form_note">LOVD includes a "newsfeed" that allows users to get a list of changes recently made in the database. Select here how many months back you want changes to appear on <A href="' . ROOT_PATH . 'api/feed.php" target="_blank">this list</A>. Set to "Not available" to disable the newsfeed.</SPAN>'),
                'hr',
                'skip',
                'skip',
                array('', 'print', '<B>Global LOVD statistics</B>'),
                array('', 'print', '<SPAN class="form_note">The following settings apply to the kind of information your LOVD install sends to the development team to gather statistics about global LOVD usage.</SPAN>'),
                'hr',
                array('Send signature', 'checkbox', 'send_signature', 1),
                array('', 'print', '<SPAN class="form_note">This sends an unique <I>anonymous</I> signature allowing us to determine the number of unique installations of LOVD.</SPAN>'),
                'hr',
                array('Send statistics', 'checkbox', 'send_stats', 1),
                array('', 'print', '<SPAN class="form_note">This sends <I>anonymous</I> statistics about the number of submitters, genes, patients and mutations in your installation of LOVD.</SPAN>'),
                'hr',
                array('Include in the global LOVD listing', 'checkbox', 'send_listings', 1),
                array('', 'print', '<SPAN class="form_note">We keep a public listing of LOVD installations, their genes and their URLs. Deselect this checkbox if you do not want to be included in this public listing.</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('Use cookies for user authentication', 'checkbox', 'use_cookies', 1),
                array('', 'print', '<SPAN class="form_note">Leaving this option set is <I>highly recommended</I>, as disabling this allows others to hijack LOVD user accounts.</SPAN>'),
                'hr',
                array('Use SSL only to access LOVD', 'checkbox', 'use_ssl', 1),
                array('', 'print', '<SPAN class="form_note">SSL is a secure protocol allowing for encryption of data sent between you and LOVD. When you will record sensitive patient information in LOVD, you <B>should</B> enable this setting, as the patient information can otherwise be \'sniffed\' off the network. If you do not record sensitive information, enabling SSL is <I>recommended</I>.</SPAN>'),
                'hr',
                array('Hide non public entries from the unique variant listing', 'checkbox', 'hide_nonpublic', 1),
                array('', 'print', '<SPAN class="form_note">If you turn this off, information on non public variants will be included in the unique variant listing. This setting does not effect the safety of the patient data.</SPAN>'),
                'hr',
                array('Lock <I>curators</I> after 3rd failed login', 'checkbox', 'lock_curators', 1),
                array('', 'print', '<SPAN class="form_note">Do you want to lock curators and managers after three failed attempts to log in using their username?<BR>(This does <I>not</I> affect the database administrator account)</SPAN>'),
                'hr',
                array('Lock <I>submitters</I> after 3rd failed login', 'checkbox', 'lock_submitters', 1),
                array('', 'print', '<SPAN class="form_note">Do you want to lock submitters after three failed attempts to log in using their username?</SPAN>'),
                'hr',
                array('Allow locked users to retrieve a new password', 'checkbox', 'allow_unlock', 1),
                array('', 'print', '<SPAN class="form_note">Do you want to enable an "I forgot my password" option that allows users who forgot their password to retrieve a new one?</SPAN>'),
                'hr',
                'skip',
                'skip',
                array('', 'print', '<B>Legend settings (optional)</B>'),
                array('', 'print', '<SPAN class="form_note">These settings are used to create a more detailed legend. Also, the lists are used to create selection lists on the submit form.</SPAN>'),
                'hr',
                array('List of possible diseases associated<BR>with mutations in the available genes', 'print', '<TEXTAREA name="disease_list" cols="73" rows="10" class="S11">' . $_POST['disease_list'] . '</TEXTAREA>'),
                array('', 'print', '<SPAN class="form_note">This is used to build a selection list with available disease phenotypes. One disease per line, format: Abbreviation = Disease name<BR>Example: &quot;DMD = Duchenne Muscular Dystrophy&quot;</SPAN>'),
                'hr',
                array('List of available detection techniques<BR>(LOVD system wide)', 'print', '<TEXTAREA name="technique_list" cols="73" rows="10" class="S11">' . $_POST['technique_list'] . '</TEXTAREA>'),
                array('', 'print', '<SPAN class="form_note">This is used to build a selection list with available detection techniques. One technique per line, format: Abbreviation = Technique name<BR>Example: &quot;DHPLC = Denaturing High-Performance Liquid Chromatography&quot;</SPAN>'),
                'hr',
                'skip',
                array('', 'submit', 'Update'),
              );
$_MODULES->processForm('SetupSettingsEdit', $aForm);
lovd_viewForm($aForm);

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

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