<?php
/*******************************************************************************
 *
 * LEIDEN OPEN VARIATION DATABASE (LOVD)
 *
 * Created     : 2010-06-23
 * Modified    : 2011-06-30
 * For LOVD    : 2.0-32
 *
 * Access      : Administrator and managers.
 * Purpose     : Allows adding, removing, sorting and hiding curators on a per-
 *               gene basis.
 *
 * Copyright   : 2004-2011 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';

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





if ($_GET['action'] == 'edit' && in_array($_GET['edit'], lovd_getGeneList())) {
    // Add/remove curators.

    // Require manager clearance.
    lovd_requireAUTH(LEVEL_MANAGER);

    $zData = array();
    $q = @mysql_query('SELECT userid FROM ' . TABLE_CURATES . ' WHERE symbol = "' . $_GET['edit'] . '"');
    while ($z = mysql_fetch_assoc($q)) {
        $zData[] = str_pad($z['userid'], 3, '0', STR_PAD_LEFT); // We need str_pad because TABLE_CURATES has no ZEROFILL.
    }

    // 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.');
            }
        }

        // Select at least one curator.
        if (empty($_POST['curators']) || !is_array($_POST['curators'])) {
            lovd_errorAdd('Please select at least one curator!');
        }

        // 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.');
        }

        // XSS attack prevention. Simply deny input of HTML, PHP other stuff blocked by strip_tags().
        lovd_checkXSS();

        if (!lovd_error()) {
            // Change curator?
            sort($zData);
            sort($_POST['curators']);
            if ($zData != $_POST['curators']) {
                // Something changed...
                // To facilitate proper reporting, retrieve user information for the users which have been selected, and were selected.
                $aUsers = array();
                $q = mysql_query('SELECT userid, username, name, level FROM ' . TABLE_USERS . ' WHERE userid IN (' . implode(', ', array_unique(array_merge($zData, $_POST['curators']))) . ')');
                while ($z = mysql_fetch_assoc($q)) {
                    $aUsers[$z['userid']] = $z;
                }

                // Remove as curator?
                foreach ($zData AS $nUserID) {
                    if (!in_array($nUserID, $_POST['curators']) && ($_AUTH['userid'] == $nUserID || $_AUTH['level'] > $aUsers[$nUserID]['level'])) {
                        // User will be removed...
                        $sQ = 'DELETE FROM ' . TABLE_CURATES . ' WHERE symbol = "' . $_GET['edit'] . '" AND userid = "' . $nUserID . '"';
                        $q = mysql_query($sQ);
                        if (!$q) {
                            $sError = mysql_error(); // Save the mysql_error before it disappears.
                            require ROOT_PATH . 'inc-top.php';
                            lovd_printHeader('setup_curators_manage', 'LOVD Setup - Manage gene curators');
                            lovd_dbFout('CuratorRemove', $sQ, $sError);
                        } else {
                            lovd_writeLog('MySQL:Event', 'CuratorRemove', $aUsers[$nUserID]['username'] . ' (' . mysql_real_escape_string($aUsers[$nUserID]['name']) . ') successfully removed as curator for ' . $_GET['edit']);
                        }
                    }
                }

                // Add as curator.
                foreach ($_POST['curators'] AS $nUserID) {
                    // 2011-06-30; 2.0-32; Checking user levels HERE allows somebody to remove all curators from a gene database (remove successful, addition fails).
                    // New rule: managers may add ALL curators, also other managers and the db admin.
                    //if (!in_array($nUserID, $zData) && ($_AUTH['userid'] == $nUserID || $_AUTH['level'] > $aUsers[$nUserID]['level'])) {
                    if (!in_array($nUserID, $zData)) {
                        // User has requested addition...
                        $sQ = 'INSERT INTO ' . TABLE_CURATES . ' VALUES ("' . $nUserID . '", "' . $_GET['edit'] . '", 1)';
                        $q = mysql_query($sQ);
                        if (!$q) {
                            $sError = mysql_error(); // Save the mysql_error before it disappears.
                            require ROOT_PATH . 'inc-top.php';
                            lovd_printHeader('setup_curators_manage', 'LOVD Setup - Manage gene curators');
                            lovd_dbFout('CuratorAdd', $sQ, $sError);
                        } else {
                            lovd_writeLog('MySQL:Event', 'CuratorAdd', $aUsers[$nUserID]['username'] . ' (' . mysql_real_escape_string($aUsers[$nUserID]['name']) . ') successfully added as curator for ' . $_GET['edit']);
                        }
                    }
                }
            }

            // Thank the user...
            header('Refresh: 1; url=' . PROTOCOL . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . '?action=sort&sort=' . $_GET['edit'] . lovd_showSID(true));

            require ROOT_PATH . 'inc-top.php';
            lovd_printHeader('setup_curators_manage', 'LOVD Setup - Manage gene curators');
            lovd_showInfoTable('Successfully updated the curator list of the ' . stripslashes($_GET['edit']) . ' gene database!', 'success');

            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 {
        // Load current curators.
        $_POST['curators'] = $zData;
    }



    require ROOT_PATH . 'inc-top.php';
    lovd_printHeader('setup_curators_manage', 'LOVD Setup - Manage gene curators');

    lovd_showInfoTable('Users selected as curators will receive notification emails after new submissions to this gene. Also, they will be mentioned on the gene homepage. If their user level is also "Curator", they will get write access to the gene\'s data - higher user levels already have write access regardless of whether or not they are configured as gene curators. Changes you make to other users with the same or a higher level than you, will be ignored.<BR>Whether or not a user\'s name appears on the gene homepage and how the names of multiple curators are sorted will be configured in the next screen.', 'warning');

    lovd_errorPrint();

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

    // Get user list, to select users as curators.
    $aUsers = array();
    $q = mysql_query('SELECT userid, name, level FROM ' . TABLE_USERS . ' ORDER BY level DESC, name');
    while ($z = mysql_fetch_assoc($q)) {
        $aUsers[$z['userid']] = '(' . $_SETT['user_levels'][$z['level']] . ') ' . $z['name'];
    }
    $nUsers = count($aUsers);
    $nUsersSize = ($nUsers < 5? $nUsers : 5);

    // Array which will make up the form table.
    $aForm = array(
                    array('POST', '', '', '50%', '50%'),
                    array('', 'print', '<B>Gene curators</B>'),
                    array('Select which users are this gene\'s curators', 'select', 'curators', $nUsersSize, $aUsers, false, true, true),
                    'skip',
                    array('Enter your password for authorization', 'password', 'password', 20),
                    array('', 'print', '<INPUT type="submit" value="Edit curator list">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<INPUT type="submit" value="Skip &raquo;" onclick="window.location.href=\'' . PROTOCOL . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . '?action=sort&amp;sort=' . $_GET['edit'] . lovd_showSID(true, true) . '\'; return false;">'),
                  );
    $_MODULES->processForm('SetupCuratorsEdit', $aForm);
    lovd_viewForm($aForm);

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

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





} elseif ($_GET['action'] == 'sort' && in_array($_GET['sort'], lovd_getGeneList())) {
    // Sort and hide curator names from the gene homepage.

    // Require manager clearance.
    lovd_requireAUTH(LEVEL_CURATOR);

    $zData = array();
    // Special ORDER BY statement makes sure show_order value of 0 is sent to the bottom of the list.
    $q = @mysql_query('SELECT u.userid, u.name, u2g.show_order FROM ' . TABLE_USERS . ' AS u LEFT JOIN ' . TABLE_CURATES . ' AS u2g USING(userid) WHERE u2g.symbol = "' . $_GET['sort'] . '" ORDER BY (u2g.show_order > 0) DESC, u2g.show_order, u.level DESC, u.name');
    while ($z = mysql_fetch_assoc($q)) {
        $zData[$z['userid']] = $z;
    }

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

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

        // Select at least one curator.
        if (empty($_POST['sortable']) || !is_array($_POST['sortable'])) {
            lovd_errorAdd('Please select at least one curator!');
        }

        if (!lovd_error()) {
            // Loop $zData, to see which users are not in $_POST['sortable'] (users we need to hide).
            foreach ($zData as $nID => $aUser) {
                if (!isset($_POST['sortable'][$nID])) {
                    $_POST['sortable'][$nID] = 0;
                }
            }
            // Now loop $_POST['sortable'], to store the order.
            $i = 1;
            foreach ($_POST['sortable'] as $nID => $nOrder) {
                if ($nOrder > 0) {
                    $n = $i;
                    $i ++;
                } else {
                    $n = 0;
                }
                $sQ = 'UPDATE ' . TABLE_CURATES . ' SET show_order = ' . $n . ' WHERE symbol = "' . $_GET['sort'] . '" AND userid = "' . $nID . '"';
                $q = mysql_query($sQ);
                if (!$q) {
                    $sError = mysql_error(); // Save the mysql_error before it disappears.
                    require ROOT_PATH . 'inc-top.php';
                    lovd_printHeader('setup_curators_manage', 'LOVD Setup - Manage gene curators');
                    lovd_dbFout('CuratorSort', $sQ, $sError);
                }
            }

            // Write to log...
            lovd_writeLog('MySQL:Event', 'CuratorSort', $_AUTH['username'] . ' (' . mysql_real_escape_string($_AUTH['name']) . ') successfully sorted the ' . $_GET['sort'] . ' curators list');

            // Thank the user...
            if ($_AUTH['level'] == LEVEL_CURATOR) {
                $sURL = 'config.php' . lovd_showSID();
            } else {
                $sURL = 'setup_genes.php?action=view&view=' . $_GET['sort'] . lovd_showSID(true);
            }
            header('Refresh: 3; url=' . PROTOCOL . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['PHP_SELF']), '/') . '/' . $sURL);

            require ROOT_PATH . 'inc-top.php';
            lovd_printHeader('setup_curators_manage', 'LOVD Setup - Manage gene curators');
            lovd_showInfoTable('Successfully sorted the curator list of the ' . stripslashes($_GET['sort']) . ' gene database!', 'success');

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

        } else {
            // Errors, so the whole lot returns to the form.
            lovd_magicUnquoteAll();
        }
    } else {
        // Default values.
        // Create array that defines the order of the elements, and also after submitting the form.
        $_POST['sortable'] = array();
        foreach ($zData as $nID => $aUser) {
            $_POST['sortable'][$nID] = $aUser['show_order'];
        }
    }



    require ROOT_PATH . 'inc-top.php';
    lovd_printHeader('setup_curators_manage', 'LOVD Setup - Manage gene curators');

    lovd_showInfoTable('To sort the list of curators for this gene, click and drag the <IMG src="' . ROOT_PATH . 'gfx/sort_vertical.png" alt="" width="5" height="13"> icon up or down the list. Release the mouse button in the preferred location. If you do not want a user to be shown on the list of curators on the gene homepage and on the top of the screen, deselect the checkbox on the right side of his name.', 'information');

    lovd_errorPrint();

    // Form & table.
    print('      <FORM action="' . $_SERVER['PHP_SELF'] . '?action=' . $_GET['action'] . '&amp;sort=' . $_GET['sort'] . '&amp;sent=true" method="post">' . "\n" .
          '        <UL id="sortable" class="sortable">' . "\n");
    // Sounds stupid, but because I choose to use a checkbox, I need to loop $zData to see if we lost somebody here (checkbox was not checked).
    foreach ($zData as $nID => $aUser) {
        if (!isset($_POST['sortable'][$nID])) {
            $_POST['sortable'][$nID] = 0;
        }
    }
    // Now loop the items in the order given.
    foreach ($_POST['sortable'] as $nID => $nOrder) {
        print('          <LI><TABLE width="100%"><TR><TD width="10"><IMG src="gfx/sort_vertical.png" alt="" title="Click and drag to sort" width="5" height="13" class="handle"></TD><TD>' . $zData[$nID]['name'] . '</TD><TD width="20" align="right"><INPUT type="checkbox" name="sortable[' . $nID . ']" value="1"' . ($nOrder > 0? ' checked' : '') . '></TD></TR></TABLE></LI>' . "\n");
    }
    print('        </UL>' . "\n" .
          '        <INPUT type="submit" value="Save">' . "\n" .
          '      </FORM>' . "\n\n");

?>
      <!-- Tim Taylor's ToolMan DHTML Library, see http://tool-man.org/examples/ -->
      <SCRIPT type="text/javascript" src="lib/tool-man/core.js"></SCRIPT>
      <SCRIPT type="text/javascript" src="lib/tool-man/events.js"></SCRIPT>
      <SCRIPT type="text/javascript" src="lib/tool-man/css.js"></SCRIPT>
      <SCRIPT type="text/javascript" src="lib/tool-man/coordinates.js"></SCRIPT>
      <SCRIPT type="text/javascript" src="lib/tool-man/drag.js"></SCRIPT>
      <SCRIPT type="text/javascript" src="lib/tool-man/dragsort.js"></SCRIPT>
      <SCRIPT type="text/javascript">
        <!--
          var dragsort = ToolMan.dragsort()
          dragsort.makeListSortable(document.getElementById("sortable"), setHandle)

          function setHandle(item) {
              item.toolManDragGroup.setHandle(findHandle(item))
          }

          function findHandle(item) {
              var children = item.getElementsByTagName("img")
              for (var i = 0; i < children.length; i++) {
                  var child = children[i]

                  if (child.getAttribute("class") == null) continue

                  if (child.getAttribute("class").indexOf("handle") >= 0)
                      return child
              }
              return item
          }
        //-->
      </SCRIPT>
<?php

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