<?/*
Copyright (C) 2003 Media Net Link, Inc. Danville, CA 94526 USA

This file is part of AthenaRMS.

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

AthenaRMS 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
*/?>
<?php
require_once 'md5.php';

class Crypt {
  function Crypt ($config='') {
    global $crypt_key;
    $this->key = $crypt_key;
    $this->iv = '00000000';

    global $error_log;
    $this->logging = isset($error_log);
    $this->errfile = $error_log;

    global $dbi;
    $this->db = &$dbi;
    $this->th = new TicketHash;
  }
  
  function encrypt ($data) {
    $e = $this->th->makeHash($data);
    if (!$e) {
	$this->error = 'Crypt::encrypt(): ' . $this->th->error;
	return;
    }
    return $e;
  }
  
  function decrypt ($data) {

    /* 
       First try the new md5 hashing method.  If that doesn't work,
       fall back to the old Mcrypt method.
    */
    $ret = $this->th->fetch($data);
    if ($ret) {
	return $ret;
    }

$this->log("Page requested: " . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] ."\n");
$this->log("Falling back to Mcrypt, trying MCRYPT_MODE_CBC.\n");

    /* Fall back to Mcrypt. */
    if ($this->key) {
      $data = $this->hex2bin($data);
      $td = mcrypt_module_open (MCRYPT_TRIPLEDES, '', MCRYPT_MODE_CBC, '');
      mcrypt_generic_init ($td, $this->key, $this->iv);
      $text = mdecrypt_generic ($td, $data);
      mcrypt_generic_deinit ($td);
      mcrypt_module_close($td);
    } else {
      $text = '';
    }

    ## swap out nulls
    $text = preg_replace ('/\0/', '', $text);

    ## is a ticket_id or ticket_id|person_id
    if (preg_match('/^\d+$/',$text) or
        preg_match('/^\d+\|\d+$/',$text)) {
$this->log("Exiting decrypt() with ticket_id or ticket_id|person_id.\n");
      return $text;
    }

    ## use old decrypt method

    if ($this->key) {
      warnings_off();
      $ret = mcrypt_cbc (MCRYPT_TripleDES, $this->key, $data, MCRYPT_DECRYPT);
      warnings_on();
    } else {
      $ret = '';
    }

    ## swap out nulls
    $ret = preg_replace ('/\0/', '', $ret);

    $this->log("Exiting decrypt() with MCRYPT_DECRYPT.\n");
    return $ret;
  }
  
  function hex2bin($data) {
    return pack('H'.strlen($data), $data); 
  } 

  function log($txt) {
    if (!$this->logging) return;
    $ts = date("[Y/m/d H:i:s]");
    error_log("$ts $txt",3,$this->errfile);
  }
}
?>
