<?php
/*******************************************************************************
 *
 * LEIDEN OPEN VARIATION DATABASE (LOVD)
 *
 * Created     : 2006-05-04
 * Modified    : 2019-07-30
 * For LOVD    : 2.0-37
 *
 * Access      : Administrator and managers.
 * Purpose     : View, search and drop log entries.
 *
 * Copyright   : 2004-2019 Leiden University Medical Center; http://www.LUMC.nl/
 * Programmer  : Ivo F.A.C. Fokkema <I.F.A.C.Fokkema@LUMC.nl>
 * Last edited : 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_MANAGER);





if (!isset($_GET['action'])) {
    $_GET['action'] = '';
}

// Verzamelen log names.
$q = mysql_query('SELECT DISTINCT logname FROM ' . TABLE_LOGS);
$aLogs = array();
while (list($sLog) = mysql_fetch_row($q)) {
    $aLogs[] = $sLog;
}

if ($_GET['action'] == 'select') {
    // Select log file to show.
    require ROOT_PATH . 'inc-top.php';
    lovd_printHeader('setup_logs', 'LOVD Setup - System logs');

    $nTotal = count($aLogs);
    if (!$nTotal) {
        print('      No logs available' . "\n");
        require ROOT_PATH . 'inc-bot.php';
        exit;
    }

    // Standaard query, later uit te bouwen.
    $sQ = 'SELECT DISTINCT logname, COUNT(*) AS count, MIN(date) AS min, MAX(date) AS max FROM ' . TABLE_LOGS . ' GROUP BY logname ORDER BY logname';
    $q = mysql_query($sQ);
    if (!$q) {
        lovd_dbFout('Log' . ucfirst($_GET['action']), $sQ, mysql_error());
    }

    print('      <SPAN class="S11">' . $nTotal . ' log' . ($nTotal == 1? '' : 's') . '</SPAN><BR>' . "\n");

    // Array which will make up the table (header and data).
    $aTable =
             array(
                    'logname' => array('Log', '*', ''),
                    'count' => array('Entries', '60', 'align="right"'),
                    'min' => array('First log', '150', ''),
                    'max' => array('Last log', '150', ''),
                  );

    // Table.
    print('      <TABLE border="0" cellpadding="0" cellspacing="1" width="500" 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>');

    while ($zData = mysql_fetch_assoc($q)) {
        print("\n" .
              '        <TR style="cursor : pointer; cursor : hand;" onmouseover="this.className = \'hover\';" onmouseout="this.className = \'\';" onclick="window.location.href = \'' . $_SERVER['PHP_SELF'] . '?action=browse&amp;log=' . $zData['logname'] . lovd_showSID(true, true) . '\';">');

        $zData['logname'] = '<A href="' . $_SERVER['PHP_SELF'] . '?action=browse&amp;log=' . $zData['logname'] . '" class="data">' . $zData['logname'] . '</A>';

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

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





} elseif ($_GET['action'] == 'browse' && in_array($_GET['log'], $aLogs)) {
    // Browse log entries.
    require ROOT_PATH . 'inc-lib-form.php';
    require ROOT_PATH . 'inc-lib-list.php';

    // Delete, if necessary.
    if (isset($_GET['delete'])) {
        // One entry, or a whole lot?
        if (substr_count($_GET['delete'], ',')) {
            // Just one, clicked on a link.
            $aDel = explode(',', $_GET['delete']);
            $sQ = 'DELETE FROM ' . TABLE_LOGS . ' WHERE logname = "' . $_GET['log'] . '" AND date = "' . $aDel[0] . '" AND mtime = "' . $aDel[1] . '"';

            $q = mysql_query($sQ);
            if (!$q) {
                // Non-fatal.
                lovd_dbFout('LogDel', $sQ, mysql_error(), false);
            }

        } else {
            // More entries...
            $sQ = '';
            if (isset($_GET['delete_all']) && $_GET['delete_all']) {
                $sQ = 'DELETE FROM ' . TABLE_LOGS . ' WHERE logname = "' . $_GET['log'] . '"';
            } else {
                if (isset($_GET['del_days']) && is_numeric($_GET['del_days']) && $_GET['del_days'] >= 0) {
                    $sDate = date('Y-m-d H:i:s', mktime(date('H'), date('i'), date('s'), date('m'), date('d') - $_GET['del_days'], date('Y')));
                    $sQ    = 'DELETE FROM ' . TABLE_LOGS . ' WHERE logname = "' . $_GET['log'] . '" AND date < "' . $sDate . '"';
                }
            }

            if ($sQ) {
                $q = mysql_query($sQ);
                if (!$q) {
                    // Non-fatal.
                    lovd_dbFout('LogDel', $sQ, mysql_error(), false);
                }
            }
        }
    }

    list($nTotal) = mysql_fetch_row(mysql_query('SELECT COUNT(*) FROM ' . TABLE_LOGS . ' WHERE logname = "' . $_GET['log'] . '"'));
    if (!$nTotal) {
        header('Location: ' . PROTOCOL . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . lovd_showSID());
        exit;
    }

    require ROOT_PATH . 'inc-top.php';
    lovd_printHeader('setup_logs', 'LOVD Setup - System logs');
    print('      <H5>Browsing &quot;' . ucfirst($_GET['log']) . '&quot; log' . (count($aLogs) > 1? ' [<A href="' . $_SERVER['PHP_SELF'] . '?action=select">View other logs</A>]' : '') . '</H5><BR>' . "\n\n");

    // Standaard query, later uit te bouwen. MODIFIED - altijd een WHERE clause.
    $sQ = 'SELECT *, CONCAT(date, " ", mtime) AS timestamp FROM ' . TABLE_LOGS . ' WHERE logname = "' . $_GET['log'] . '"';

    // Here starts the actual building of the query.
    // SEARCH: Simple text search.
    $aSearchText = array('date' => 'date', 'event' => 'event', 'entry' => 'log');
    foreach ($aSearchText as $key => $val) {
        if (isset($_GET[$key]) && trim($_GET[$key])) {
            $a = explode(' ', trim($_GET[$key]));
            foreach ($a as $sTerm) {
                if (trim($sTerm)) {
                    $sQ .= ' AND ' . $val . ' LIKE "%' . $sTerm . '%"';
                }
            }
        }
    }

    $nResults = mysql_num_rows(mysql_query($sQ));

    // SORT: Current settings.
    // 2008-08-07; 2.0-10; Implement XSS check on order variable.
    if (isset($_GET['order']) && $_GET['order'] && $_GET['order'] == strip_tags($_GET['order'])) {
        $aOrder = explode(',', $_GET['order']);
    } else {
        $aOrder = array('', '');
    }

    // SORT: Column data.
    $aOrderList = array('date' => array('timestamp', 'DESC'), 'event' => array('event', 'ASC'));
    if (!array_key_exists($aOrder[0], $aOrderList)) {
        $aOrder[0] = 'date';
    }
    if ($aOrder[1] != 'ASC' && $aOrder[1] != 'DESC') {
        $aOrder[1] = $aOrderList[$aOrder[0]][1];
    }

    if ($nResults > 0) {
        $sQueryLimit = lovd_pagesplitInit($nResults, 50);
    } else {
        $sQueryLimit = lovd_pagesplitInit($nTotal, 50);
    }
    $sQ .= ' ORDER BY ' . $aOrderList[$aOrder[0]][0] . ' ' . $aOrder[1] . ', timestamp ' . $sQueryLimit;



    // Show form; required for sorting and searching.
    print('      <FORM action="' . $_SERVER['PHP_SELF'] . '" method="get" style="margin : 0px;">' . "\n" .
          '        <INPUT type="hidden" name="action" value="' . $_GET['action'] . '">' . "\n" .
          '        <INPUT type="hidden" name="log" value="' . $_GET['log'] . '">' . "\n" .
          '        <INPUT type="hidden" name="order" value="' . implode(',', $aOrder) . '">');



    // Table for searching and deleting the data.
    print('      <TABLE border="0" cellpadding="0" cellspacing="0" width="950">' . "\n" .
          '        <TR valign="top">' . "\n" .
          '          <TD align="left" width="50%">');

    print("\n" .
          '        <TABLE border="0" cellpadding="0" cellspacing="1" width="400" class="data">' . "\n" .
          '          <TR>' . "\n" .
          '            <TH colspan="2">Search options</TH></TR>');
    // Array which will make up the form table.
    $aForm = array(
                    array('GET', 'header', 'data', '30%', '70%'),
                    array('Date', 'text', 'date', 20),
                    array('Event', 'text', 'event', 12),
                    array('Log entry', 'text', 'entry', 30),
                    array('', 'submit', 'Search', 'search'),
                  );
    $_MODULES->processForm('SetupLogsSearch', $aForm);
    lovd_viewForm($aForm, "\n" . '          <TR>' . "\n" . '            <TH valign="top" width="{{ WIDTH }}" style="padding-top : 3px;">', '</TH>');
    print('</TABLE>');

    print("\n" .
          '          </TD>' . "\n" .
          '          <TD align="right" width="50%">');



    print("\n" .
          '        <TABLE border="0" cellpadding="0" cellspacing="1" width="400" class="data_red">' . "\n" .
          '          <TR>' . "\n" .
          '            <TH colspan="2">Delete log entries</TH></TR>');
    // Array which will make up the form table.
    $aForm = array(
                    array('GET', 'header', 'data', '60%', '40%'),
                    array('Delete entries older than', 'print', '<INPUT type="text" name="del_days" size="3" value="' . (isset($_GET['del_days'])? $_GET['del_days'] : '') . '">&nbsp;day(s)'),
                    array('Delete all entries in log', 'checkbox', 'delete_all', 0),
                    array('', 'submit', 'Delete', 'delete'),
                  );
    $_MODULES->processForm('SetupLogsDelete', $aForm);
    lovd_viewForm($aForm, "\n" . '          <TR>' . "\n" . '            <TH valign="top" width="{{ WIDTH }}" style="padding-top : 3px;">', '</TH>');
    print('</TABLE>' . "\n" .
          '        <SPAN class="S11">Please note that delete commands affect all entries in the ' . $_GET['log'] . ' log, not only the search results.</SPAN><BR>' . "\n\n");

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



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

    if (!$nResults) {
        // Gezocht, en geen resultaten.
        print('      No results have been found that match your criteria.<BR>' . "\n\n");
        require ROOT_PATH . 'inc-bot.php';
        exit;
    }

    $q = mysql_query($sQ);
    if (!$q) {
        lovd_dbFout('Log' . ucfirst($_GET['action']), $sQ, mysql_error());
    }

    $n = $nResults;
    print('      <SPAN class="S11">' . $n . ' entr' . ($n == 1? 'y' : 'ies') . '</SPAN><BR>' . "\n");

    // Array which will make up the table (header and data).
    $aTable =
             array(
                    'date' => array('Date', '130', ''),
                    'event' => array('Event', '100', ''),
                    'del' => array('&nbsp;', '14', 'valign="middle" align="center"'),
                    'log' => array('Entry', '*', ''),
                  );

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

    foreach ($aTable as $sField => $aCol) {
        print("\n" . '          <TH' . (!empty($aCol[2])? ' ' . $aCol[2] : '') . (is_numeric($aCol[1])? ' width="' . $aCol[1] . '"' : '') . (array_key_exists($sField, $aOrderList)? ' class="order' . ($aOrder[0] == $sField? 'ed' : '') . '" onclick="document.forms[0].order.value=\'' . $sField . ',' . ($aOrder[0] == $sField? ($aOrder[1] == 'ASC'? 'DESC' : 'ASC') : $aOrderList[$sField][1]) . '\';document.forms[0].submit();"' : '') . '>' .
              (array_key_exists($sField, $aOrderList)? "\n" .
                                                           '            <TABLE border="0" cellpadding="0" cellspacing="0" width="100%" class="S11">' . "\n" .
                                                           '              <TR>' . "\n" .
                                                           '                <TH>' . $aCol[0] . '</TH>' . "\n" .
                                                           '                <TD align="right"><IMG src="gfx/order_arrow_desc' . ($aOrder[0] == $sField && $aOrder[1] == 'DESC'? '_sel' : '') . '.png" alt="Descending" title="Descending" width="13" height="6"><BR><IMG src="gfx/order_arrow_asc' . ($aOrder[0] == $sField && $aOrder[1] == 'ASC'? '_sel' : '') . '.png" alt="Ascending" title="Ascending" width="13" height="6"></TD></TR></TABLE>' : $aCol[0]) . '</TH>');
    }

    print('</TR>');

    // <!-- Moved up because we need this var.
    // URL pagelink.
    $sPageLink = 'log=' . $_GET['log'] . '&amp;order=' . rawurlencode(implode(',', $aOrder));

    // SEARCH: Simple text search.
    foreach ($aSearchText as $key => $val) {
        if (isset($_GET[$key]) && $_GET[$key]) {
            // 2009-04-23; 2.0-18; Added stripslashes to allow search terms to include quotes.
            $sPageLink .= ($sPageLink? '&amp;' : '') . $key . '=' . rawurlencode(stripslashes($_GET[$key]));
        }
    }
    // --> Moved up because we need this var.

    while ($zData = mysql_fetch_assoc($q)) {
        // Modified to add 'valign' and remove the 'style' tag (disable cursor mod).
        print("\n" .
              '        <TR valign="top" onmouseover="this.className = \'hover\';" onmouseout="this.className = \'\';">');

        $zData['del'] = '<A href="' . $_SERVER['PHP_SELF'] . '?action=' . $_GET['action'] . '&amp;' . $sPageLink . (!empty($_GET['page'])? '&amp;page=' . $_GET['page'] : '') . '&amp;delete=' . rawurlencode($zData['date'] . ',' . $zData['mtime']) . '"><IMG src="gfx/mark_0.png" alt="Delete" title="Delete" width="11" height="11" border="0"></A>';
        $zData['log'] = htmlspecialchars(str_replace(array("\r\n", "\r", "\n"), '<BR>', $zData['log']));

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

    lovd_pagesplitShowNav($sPageLink);

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





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