<?php
// Simple Text-File Login (SiTeFiLo).
// Copyright ©2004 by Mario A. Valdez-Ramirez
// http://www.mariovaldez.net/

// 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; either version 2 of the License, or
// (at your option) any later version.

// 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.

// You can contact Mario A. Valdez-Ramirez by email
// at mario@mariovaldez.org or paper mail at
// Olmos 809, San Nicolas, NL. 66495, Mexico.



// Set reporting level.
error_reporting(E_ALL & ~E_NOTICE);

// Set current language.
$slogin_lang = "en";

// Set name of users file.
// To disable authentication, just empty the slogin_userstxt variable.
$slogin_userstxt = "slog_users.txt";
$slogin_altuser = "slog_users.php";

// Use normal text file (easier to edit), set to 1
// or alternative php file (if fopen function is disabled), set to 0.
$slogin_canusefopen = 1;

// Use MD5 hashes, for extra security. The passwords
// in the password file need to be MD5 hashes. Also,
//using a hash will make passwords case-sensitive.
$slogin_usehashes = 0;



// Define some constants.
define ("SLOGIN_USER_PREFIX", "slog_");
define ("SLOGIN_LOG_PREFIX", "slog_");
define ("SLOGIN_LOG_SUFFIX", "_log");
define ("SLOGIN_TIMEZONE_SHIFT", 0);
define ("SLOGIN_USERS_FILE", $slogin_userstxt);
// To disable logging just empty the SLOGIN_LOG_FILE constant.
define ("SLOGIN_LOG_FILE", SLOGIN_LOG_PREFIX . fslogin_logprefix() . SLOGIN_LOG_SUFFIX . ".txt");
define ("SLOGIN_MAXLEN_USERNAME", 32);
define ("SLOGIN_MAXLEN_PASSWORD", 32);



// Define some message strings.
$slogin_text["en"]["Username"] = "Username:";
$slogin_text["en"]["Password"] = "Password:";
$slogin_text["en"]["LoginButton"] = "Enter";
$slogin_text["en"]["UserLoggedIn"] = "User logged in";
$slogin_text["en"]["LoginFailed"] = "Login failed for";
$slogin_text["en"]["WrongLogin"] = "Wrong username or password.";
$slogin_text["en"]["ReturnLogList"] = "Return to log list.";
$slogin_text["en"]["ReturnHome"] = "Return to homepage.";
$slogin_text["en"]["CantRead"] = "CRITICAL ERROR: The users file cannot be read.";
$slogin_text["en"]["CantLog"] = "Cannot create logs, cannot show logs.";
$slogin_text["en"]["NoAdmin"] = "Only the admin user can view the logs.";
$slogin_text["en"]["EnterPlain"] = "Enter the password in plain text to generate the MD5 hashed string:";
$slogin_text["en"]["GetHashed"] = "The hashed password is:";
$slogin_text["en"]["HashButton"] = "Generate";

$slogin_text["es"]["Username"] = "Nombre de usuario:";
$slogin_text["es"]["Password"] = "Contrase&ntilde;a:";
$slogin_text["es"]["LoginButton"] = "Entrar";
$slogin_text["es"]["UserLoggedIn"] = "Usuario inició sesión";
$slogin_text["es"]["LoginFailed"] = "Inicio de sesión fállido para";
$slogin_text["es"]["WrongLogin"] = "Nombre de usuario o contrase&ntilde;a incorrectos.";
$slogin_text["es"]["ReturnLogList"] = "Regresar a la lista de registros.";
$slogin_text["es"]["ReturnHome"] = "Regresar a p&aacute;gina principal.";
$slogin_text["es"]["CantRead"] = "ERROR CRITICO: No se puede leer el archivo de usuarios.";
$slogin_text["es"]["CantLog"] = "No se pueden crear registros, no se pueden mostrar registros.";
$slogin_text["es"]["NoAdmin"] = "Sólo el usuario admin puede ver los registros.";
$slogin_text["es"]["EnterPlain"] = "Introduzca la contrase&ntilde;a en texto simple para generar la cadena MD5 encriptada:";
$slogin_text["es"]["GetHashed"] = "La contrase&ntilde;a encryptada es:";
$slogin_text["es"]["HashButton"] = "Generar";



// Get environment variable.
$slogin_php_self = $_SERVER["PHP_SELF"];
if (!$slogin_php_self) {
  $slogin_php_self = $HTTP_SERVER_VARS["PHP_SELF"];
  if (!$slogin_php_self) {
    $slogin_php_self = $_ENV["PHP_SELF"];
    if (!$slogin_php_self) {
      $slogin_php_self = getenv("PHP_SELF");
    }
    else $slogin_php_self = "";
  }
}


// Include alternative user file.
if (!$slogin_canusefopen) {
  include ($slogin_altuser);
}


// Get login data from login-form or session variables.
if ($_GET["logout"]) { $slogin_logout = 1; } else { $slogin_logout = 0; }
if ($_GET["login"]) { $slogin_login = 1; } else { $slogin_login = 0; }
if ($_POST["slogin_POST_explicitauth"]) { $slogin_explicitauth = 1; } else { $slogin_explicitauth = 0; }
if ($_POST["slogin_POST_username"]) { $slogin_loginname = substr (trim (ereg_replace("[^[:alnum:]_.]", "", $_POST["slogin_POST_username"])), 0, SLOGIN_MAXLEN_USERNAME); } else { $slogin_loginname = ""; }
if ($_POST["slogin_POST_password"]) { $slogin_loginpass = substr (trim (ereg_replace("[^[:alnum:]_.]", "",$_POST["slogin_POST_password"])), 0, SLOGIN_MAXLEN_PASSWORD); } else { $slogin_loginpass = ""; }
if ($_SESSION["Username"]) { $slogin_Username = substr ($_SESSION["Username"], 0, SLOGIN_MAXLEN_USERNAME); } else { $slogin_Username = ""; }

// Authenticate.
if ($slogin_logout || $slogin_login) {
  @session_unset ();
  @session_destroy ();
  include_once ("header.inc.php");
  include_once ("slogin.inc.php");
  include_once ("footer.inc.php");
  exit;
}
else {
  if (($slogin_noauthpage != 1) || ($slogin_explicitauth)) {
    if ((!$slogin_Username) && (!$slogin_Password)) {
      if ((!$slogin_loginname) && (!$slogin_loginpass)) {
        include_once ("header.inc.php");
        include_once ("slogin.inc.php");
        include_once ("footer.inc.php");
        exit;
      }
      else {
        if (fslogin_check_user ($slogin_loginname, $slogin_loginpass)) {
          fslogin_log_user ("{$slogin_text[$slogin_lang]["UserLoggedIn"]} $slogin_loginname");
          $slogin_Username = $slogin_loginname;
          $slogin_Name = $slogin_loginpass;
          $_SESSION["Username"] = $slogin_loginname;
        }
        else {
          @session_unset ();
          @session_destroy ();
          fslogin_log_user ("{$slogin_text[$slogin_lang]["LoginFailed"]} $slogin_loginname");
          include_once ("header.inc.php");
          echo "<div align=\"center\">{$slogin_text[$slogin_lang]["WrongLogin"]}</div>";
          include_once ("slogin.inc.php");
          include_once ("footer.inc.php");
          exit;
        }
      }
    }
  }
}


function fslogin_check_user ($username, $password) {
global $slogin_canusefopen, $slogin_user, $slogin_pass, $slogin_text, $slogin_lang, $slogin_usehashes;
  if (SLOGIN_USERS_FILE) {
    if ($slogin_canusefopen) {
      if (file_exists (SLOGIN_USERS_FILE) && is_readable (SLOGIN_USERS_FILE)) {
        $slogin_ufilef = @fopen (SLOGIN_USERS_FILE, "rb");
        if ($slogin_ufilef) {
          while ($slogin_content = fgetcsv ($slogin_ufilef, 100, ",")) {
            if (strtoupper (trim ($slogin_content[0])) == strtoupper (trim ($username))) {
              if ($slogin_usehashes) {
                if (trim ($slogin_content[1]) == md5 (trim ($password))) {
                  fclose ($slogin_ufilef);
                  return ($slogin_content);
                }
              }
              else {
                if (strtoupper (trim ($slogin_content[1])) == strtoupper (trim ($password))) {
                  fclose ($slogin_ufilef);
                  return ($slogin_content);
                }
              }
            }
          }
          fclose ($slogin_ufilef);
        }
        else {
          echo "<div align=\"center\">{$slogin_text[$slogin_lang]["CantRead"]}</div>";
        }
      }
    }
    else {
      foreach ($slogin_user as $key => $user) {
        if (strtoupper (trim ($user)) == strtoupper (trim ($username))) {
          if ($slogin_usehashes) {
            if (trim ($slogin_pass[$key]) == md5 (trim ($password))) {
              $slogin_content[0] = $username;
              $slogin_content[1] = $password;
              return ($slogin_content);
            }
          }
          else {
            if (strtoupper (trim ($slogin_pass[$key])) == strtoupper (trim ($password))) {
              $slogin_content[0] = $username;
              $slogin_content[1] = $password;
              return ($slogin_content);
            }
          }
        }
      }
    }
  }
  else {
    $slogin_content[0] = "user";
    $slogin_content[1] = "user";
    return ($slogin_content);
  }
}


function fslogin_log_user ($loguserline) {
  if (SLOGIN_LOG_FILE) {
    if (!(file_exists (SLOGIN_LOG_FILE) && !is_writable (SLOGIN_LOG_FILE))) {
      $slogin_lfilef = @fopen (SLOGIN_LOG_FILE, 'a');
      if ($slogin_lfilef) {
        fwrite ($slogin_lfilef, fslogin_curdate_string() . ": " . $loguserline . "\n");
        fclose ($slogin_lfilef);
      }
    }
  }
}


function fslogin_curdate_string () {
  return (date("Y-m-d H:i:s", mktime(date("H")+SLOGIN_TIMEZONE_SHIFT,date("i"),date("s"),date("m"),date("d"),date("Y"))));
}

function fslogin_logprefix () {
  return (date("Ym", mktime(date("H")+SLOGIN_TIMEZONE_SHIFT,date("i"),date("s"),date("m"),date("d"),date("Y"))));
}



// Display logs...
function fslogin_show_logs () {
  $logs_dirhandle = opendir(".");
  $logs_sorteddir = array ();
  while (($logs_file = readdir($logs_dirhandle)) != false)
    $logs_sorteddir[count($logs_sorteddir)] = $logs_file;
  closedir($logs_dirhandle);
  sort($logs_sorteddir);
  foreach ($logs_sorteddir as $logs_file) {
    if (($logs_file != ".") && ($logs_file != "..") && (eregi (SLOGIN_LOG_SUFFIX . "\.txt$", strtolower ($logs_file))) && (eregi ("^" . SLOGIN_LOG_PREFIX, strtolower ($logs_file)))) {
      $logs_file = strtolower ($logs_file);
      $logs_file = substr ($logs_file, strlen (SLOGIN_LOG_PREFIX), strlen ($logs_file));
      $logs_file = substr ($logs_file, 0, strlen (fslogin_logprefix ()));
      echo "<p class=\"maintext\">\n";
      echo "<A href=\"$slogin_php_self?log=" . $logs_file . "\">$logs_file</a>";
      echo "</p>";
    }
  }
}


?>