<?php

  /*

      login.php

      This page authenticates the user and then sets up a session for them. [Commented]

      Changelog:
        2006-01-14 dave: Cleaned up code for v1.0 release
        2005-07-03 arne_sf: Replaced all instances of column name 'user' for
          table tbl_UserDomains with 'userid'
      
      ----

      Copyright (C) 2003  Central Manchester CLC
      Copyright (C) 2003  David Thorne (davethorne@gmail.com)

      This program 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 version 2.

      This program 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 this program; if not, write to the Free Software
      Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

  */

  require_once 'system/db.php';
  require_once 'system/lang.php';
  require_once 'system/authentication.php';
  require_once 'system/global_preferences.php';
  require_once 'system/logs.php';

  // Start session and populate it with data
  session_start();

  // Retrieve Get/Post variables
  $act = $_POST['act'];
  $user = $_POST['user'];
  $password = $_POST['password'];
  $domain = $_POST['domain'];
  $redirect = $_POST['redirect'];

  // Default action: Login
  if ($act == '') {
    $result = (auth($user, $password));
    if ($result == 0) {
      $ptitle = "Login Failed";
      include 'header.php';
      set_text_domain("login");

      print "<h1>".gettext('Access Error')."</h1>\n";
      print "<h2>".gettext('Your username or password is incorrect.')."</h2>\n";
      print "<div class=\"block\" align=\"center\"><p><a href=\"/index.php\">".gettext('Please try again.')."</a></p></div>";
      include 'footer.php';
      exit;
    }

    //build array resulting from authentication
    $user = array(
      array (
        user => "$result[0]",
        name => "$result[1]",
        email => "$result[2]",
        id => "$result[3]",
        root => "$result[4]",
        restricted => "$result[5]"
     ),
   );

    // Register session variables
    session_register('_username');
    session_register('_name');
    session_register('_email');
    session_register('_id');
    session_register('_usertype');
    session_register('_usertypesortorder');
    session_register('_restricted');
    session_register('_domain');
    session_register('_domaincss');

    // Set user associated session variables
    $_SESSION['_username'] = $user[0]['user'];
    $_SESSION['_name'] = $user[0]['name'];
    $_SESSION['_email'] = $user[0]['email'];
    $_SESSION['_id'] = $user[0]['id'];
    $_SESSION['_restricted'] = $user[0]['restricted'];

    // If this user is the root user then bypass finding the user type.
    if ($user[0][root] == 1) {

      $act = 'acceptroot';

    } else {

      // Find the default domain of this user
      ## $sql = "SELECT DISTINCT domain FROM vw_UserTypes WHERE id=$_SESSION[_id] AND defaultflag=1";
      $sql = "SELECT DISTINCT domain
              FROM tbl_UserDomains
              WHERE userid=$_SESSION[_id]
                AND defaultflag=1";
      $domains = db_recordset($sql);

      // If there is no domain set, then set the first domain found as default
      if (count($domains) == 0) {
        ## $sql = "SELECT DISTINCT domain FROM vw_UserTypes WHERE id=$_SESSION[_id]";
        $sql = "SELECT DISTINCT tbl_UserDomains.domain 
                FROM tbl_UserDomains, tbl_Users
                WHERE tbl_Users.id=$_SESSION[_id]
                  AND tbl_Users.id = tbl_UserDomains.userid";
        $domains = db_recordset($sql);

        // If there are no domains at all for this user, then throw an access error
        if (count($domains) == 0) {
          ThrowOut();
        }

        // Set the first domain to default
        db_send("UPDATE tbl_UserDomains SET defaultflag=0 WHERE userid=$_SESSION[_id]");
        db_send("UPDATE tbl_UserDomains SET defaultflag=1 WHERE userid=$_SESSION[_id] AND domain=" . $domains[0][domain]);
      }

      $domain = $domains[0][domain];
      $act = 'accept';

    }
  }

  // Accepting and setting to a domain in order to continue into the system
  if ($act == 'accept' || $act == 'acceptroot') {

    if ($act == 'acceptroot') {
      // Retrieve user type information for Root
      $sql = "SELECT type,sortorder FROM tbl_UserTypes WHERE type='Root'";
      $user = db_recordset($sql);

      // Set user type session variables
      $_SESSION['_usertype'] = $user[0][type];
      $_SESSION['_usertypesortorder'] = $user[0][sortorder];

      // If a domain has not yet been picked then choose the first one in the database
      if ($domain == '') {
        $sql = "SELECT * FROM tbl_Domains WHERE id>0 AND active=1";
        $domains = db_recordset($sql);

        $_SESSION['_domain'] = $domains[0][id];

        if ($_SESSION['_domain'] == '') {
          $dirname = dirname($_SERVER['PHP_SELF']);
          $https = 'http'.($_SERVER['HTTPS'] ? 's' : '');
          $headertext = "Location: $https://".$_SERVER['HTTP_HOST'].$dirname.(strrpos($dirname,'/') == (strlen($dirname)-1)?'':'/').'domains.php';

          header($headertext);
          exit;
        }

      } else {
        $_SESSION['_domain'] = $domain;
      }

    } else {
      // Set the domain session variables
      $_SESSION['_domain'] = $domain;

      // Retrieve user type information for Root
      ## $sql = "SELECT usertypename,usertypesortorder FROM vw_UserTypes WHERE id=$_SESSION[_id] AND domain=$domain ORDER BY usertypesortorder DESC";
      $sql = "SELECT tbl_UserTypes.type AS usertypename,tbl_UserTypes.sortorder AS usertypesortorder
              FROM tbl_UserTypes,tbl_UserSites,tbl_Sites
              WHERE tbl_UserSites.userid=$_SESSION[_id]
                AND tbl_UserSites.site=tbl_Sites.id
                AND tbl_Sites.domain=$domain
                AND tbl_UserTypes.id=tbl_UserSites.usertype
              ORDER BY usertypesortorder DESC
              LIMIT 1";
  
      $user = db_recordset($sql);

      // Set user type session variables
      $_SESSION['_usertype'] = $user[0][usertypename];
      $_SESSION['_usertypesortorder'] = $user[0][usertypesortorder];
    }

    if ($act == 'accept' || $act == 'acceptroot') {
      // Retrieve domain information
      $sql = "SELECT * FROM tbl_Domains WHERE id=$_SESSION[_domain]";
      $domains = db_recordset($sql);

      // Set the domain session variables
      $_SESSION['_domaincss'] = $domains[0][css];
      $_SESSION['_domainname'] = $domains[0][domain];

      $relative_uri = $redirect;
      if ($_SESSION['_usertype'] == 'Client') {
        $relative_uri = 'myissues.php';
      } elseif ($_SESSION['_usertype'] == 'Root') {
        $relative_uri = 'domains.php';
      } elseif ($redirect == '') {
        $relative_uri = 'unassignedissues.php';
      }

      $dirname = dirname($_SERVER['PHP_SELF']);
      $https = 'http'.($_SERVER['HTTPS'] ? 's' : '');
      $headertext = "Location: $https://".$_SERVER['HTTP_HOST'].$dirname.
        (strrpos($dirname,'/') == (strlen($dirname)-1)?'':'/').$relative_uri;

      makelog($_SESSION['_id'], $_SESSION['_domain'], 'LOGIN',
        "$_SESSION[_name] has successfully logged in.");

      header($headertext);

      $ptitle = 'Login';
      require 'header.php';
  
      set_text_domain("login");
?>

<div align="center">

   <h2><?php echo gettext('Helpdesk Management Tool')?></h2>
  <br /><br /><br /><br />

  <strong><?php echo gettext('You have successfully logged into the domain')?>:</strong><br /><br />
  <h2><?php echo $domains[0][domain]?></h2><br /><br />
  <?php echo gettext('Name')?>: <strong><?php echo $_SESSION['_name']?></strong><br /><br /><br /><br />

  <a href="<?php echo $relative_uri?>"><?php echo gettext('Continue')?>...</a>

  <br /><br /><br /><br />
  <br /><br /><br /><br />

<?php
    }
  }

  // Include
  require 'footer.php';
?>
