Ik wil graag weten of dit goed genoeg zou zijn voor in de scriptlib. Het bestaat uit wat scripts die ik nog had liggen bij elkaar gestopt. Natuurlijk moeten er nog voorbeelden bij etc. maar ik zou graag wat commentaar hebben van jullie voordat ik het erop zet. Verder zijn er inderdaad dingen die misschien nu niet van pas komen (zoals de 'DBAL' als je het al zo kan noemen), maar dat komt dus omdat ik het uit een bestaand systeem gehaald heb.

Dat doet me eraan denken dat ik nog even de regexen moet checken, of die goed werken... Doe ik morgen wel, nu geen tijd meer ;)

<?PHP
if ( ! session_id () )
session_start ();
session_regenerate_id ();

class DatabaseHandler
{

private $_socket;

private $_result;

public $num_rows;

public $affected_rows;

public $insert_id;

public function __construct ( $host, $user, $pass, $db )
{
$this->_socket = new MySQLi ( $host, $user, $pass, $db );
if ( mysqli_connect_error () )
{
throw new DatabaseException ( 'MySQL connection error [' . $this->_socket->connect_errno . ']: "' . $this->_socket->connect_error . '"' );
}
}

public function runQuery ( $query )
{
$this->_result = $this->_socket->query ( $query );
if ( $this->_socket->error != '' )
{
throw new DatabaseException ( 'MySQL connection error [' . $this->_socket->errno . ']: "' . $this->_socket->error . '"' );
return false;
}
else
{
if ( ! is_bool ( $this->_result ) )
$this->num_rows = $this->_result->num_rows;
$this->affected_rows = $this->_socket->affected_rows;
$this->insert_id = $this->_socket->insert_id;
return true;
}
}

public function fetch_assoc ()
{
if ( ! ( $this->_result instanceof MySQLi_Result ) )
{
throw new DatabaseException ( 'Not a valid result in DatbaseHandler::$result' );
}
else
{
$this->_result->data_seek ( 0 );
return $this->_result->fetch_all ( MYSQLI_ASSOC );
}
}

public function fetch_single_assoc ( $row = 0 )
{
if ( $row != 0 )
$this->_result->data_seek ( $row );
return $this->_result->fetch_assoc ();
}

public function real_escape_string ( $data )
{
return $this->_socket->real_escape_string ( $data );
}

public function real_escape_array ( $data )
{
foreach ( $data as &$string )
$string = $this->_socket->real_escape_string ( $string );
return $data;
}

public function getError ()
{
return $this->_socket->error;
}
}

class DatabaseException extends Exception
{}

class Logger
{

private static $_instance;

private $_file = 'php/errors.log';

private $_fp;

private function __construct ()
{
$this->_fp = fopen ( $this->_file, 'a' );
}

public static function getInstance ()
{
if ( ! isset ( self::$_instance ) )
self::$_instance = new self ();
return self::$_instance;
}

private function _write ( $str )
{
return fwrite ( $this->_fp, $str );
}

public function addException ( Exception $e )
{
$data = 'Errormessage: ' . $e->getMessage () . ', in: ' . $e->getFile () . ' on line: ' . $e->getLine () . PHP_EOL . 'Stack trace:' . PHP_EOL . $e->getTrace () . PHP_EOL . PHP_EOL . PHP_EOL;
return $this->_write ( $data );
}

public function addString ( $string )
{
return $this->_write ( $string . PHP_EOL . PHP_EOL . PHP_EOL );
}
}

class User
{

protected $_fingerprint;

protected $_ip;

protected $_id;

protected $_auth_level;

protected $_email;

protected $_db;

public function __construct ( $id, $auth_level, $email )
{
$this->_id = intval ( $id );
$this->_auth_level = intval ( $auth_level );
$this->_email = $email;
$this->_fingerprint = md5 ( $_SERVER["HTTP_USER_AGENT"] . $_SERVER["REMOTE_ADDR"] . $_SERVER["REMOTE_PORT"] );
}

public function setDatabaseHandler ( DatabaseHandler $db )
{
$this->_db = $db;
}

public function validate ()
{
if ( $this->_fingerprint != md5 ( $_SERVER["HTTP_USER_AGENT"] . $_SERVER["REMOTE_ADDR"] . $_SERVER["REMOTE_PORT"] ) )
{
$this->_id = 0;
$this->_auth_level = 0;
return false;
}
else
{
return true;
}
}

public function register ( $username, $pass1, $pass2, $email, $auth_level )
{
if ( ! ( $this->_db instanceof DatabaseHandler ) )
{
throw new Exception ( 'No database given to User-object' );
}
else
{
$username = $this->_db->real_escape_string ( $username );
$email = $this->_db->real_escape_string ( $email );
$auth_level = intval ( $auth_level );
if ( ! preg_match ( '/^[a-zA-Z][a-zA-Z\_\.\-]{2,}$/is', $username ) )
{
return - 1;
}
elseif ( $pass1 !== $pass2 )
{
return - 2;
}
elseif ( ! preg_match ( '/^[^@]@[^@].[a-zA-Z.]{2,5}$/is', $email ) )
{
return - 3;
}
else
{
if ( ! $this->_db->runQuery ( "SELECT id FROM users WHERE username='" . $username . "'" ) )
{
throw new Exception ( 'Couldn\'t get the userdata for username validation' );
}
elseif ( $this->_db->num_rows == 1 )
{
return - 4;
}
else
{
$password = sha1 ( $password );
if ( $this->_db->runQuery ( "INSERT INTO users(username,password,email,authlevel) VALUES('" . $username . "','" . $password . "','" . $email . "'," . $auth_level . ")" ) )
{
$this->_id = $this->_db->insert_id;
$this->_email = $email;
$this->_auth_level = $auth_level;
Authentication::getInstance ()->setCurrentUser ( $this );
return true;
}
else
{
return false;
}
}
}
}
}

public function updateEmail ( $email )
{
if ( ! ( $this->_db instanceof DatabaseHandler ) )
{
throw new Exception ( 'No database given to User-object' );
}
else
{
$email = $this->_db->real_escape_array ( $email );
if ( ! preg_match ( '/^[^@]@[^@].[a-zA-Z\.]{2,3}$/is' ) )
{
return - 1;
}
else
{
if ( ! $this->_db->runQuery ( "UPDATE users SET email='" . $_POST['email'] . "' WHERE id=" . $this->_id ) )
{
throw new Exception ( 'Couldn\'t update the userdata' );
}
else
{
if ( $this->_db->affected_rows == 1 )
{
$this->_email = $email;
Authentication::getInstance ()->setCurrentUser ( $this );
return true;
}
else
{
return false;
}
}
}
}
}

public function updatePass ( $pass1, $pass2 )
{
if ( ! ( $this->_db instanceof DatabaseHandler ) )
{
throw new Exception ( 'No database given to User-object' );
}
else
{
if ( $pass1 !== $pass2 )
{
return - 1;
}
else
{
$password = sha1 ( $pass1 );
if ( ! $this->_db->runQuery ( "UPDATE users SET password='" . $password . "' WHERE id=" . $this->_id ) )
{
throw new Exception ( 'Couldn\'t update the userdata' );
}
else
{
return $this->_db->affected_rows;
}
}
}
}

public function updateAuthLevel ( $auth_level, $id )
{
if ( ! ( $this->_db instanceof DatabaseHandler ) )
{
throw new Exception ( 'No database given to User-object' );
}
else
{
$id = intval ( $id );
$auth_level = intval ( $auth_level );
if ( ! $this->_db->runQuery ( "UPDATE users SET authlevel='" . $auth_level . "' WHERE id=" . $id ) )
{
throw new Exception ( 'Couldn\'t update the userdata' );
}
else
{
if ( $id == $this->_id )
{
if ( $this->_db->affected_rows == 1 )
{
$this->_auth_level = $auth_level;
Authentication::getInstance ()->setCurrentUser ( $this );
return true;
}
else
{
return false;
}
}
else
{
return $this->_db->affected_rows;
}
}
}
}

public function getAuthLevel ()
{
return $this->_auth_level;
}

public function getID ()
{
return $this->_id;
}

public function unsetDatabaseHandler ()
{
$this->_db = null;
}
}

class Authentication
{

private static $_instance;

private $_db;

private $_user;

public static function getInstance ()
{
if ( empty ( self::$_instance ) )
self::$_instance = new self ();
return self::$_instance;
}

private function __construct ()
{
$this->_loadUserData ();
}

public function setDatabaseHandler ( DatabaseHandler $db )
{
$this->_db = $db;
}

public function login ( $username, $password )
{
if ( ! ( $this->_db instanceof DatabaseHandler ) )
{
throw new Exception ( 'No database given to Authentication-object' );
}
else
{
$username = $this->_db->real_escape_string ( $username );
$password = sha1 ( $password );
if ( $this->_db->runQuery ( "SELECT id, authlevel, email FROM users WHERE username='" . $username . " AND password='" . $password . "'" ) )
{
if ( $this->_db->num_rows == 1 )
{
$data = $this->_db->fetch_single_assoc ();
$this->_user = new User ( $data['id'], $data['auth_level'], $data['email'] );
$this->_saveUserData ();
return true;
}
else
{
return false;
}
}
else
{
throw new Exception ( 'Couldn\'t get data from Users in Authentication::login()' );
}
}
}

public function logout ()
{
$this->_removeUserData ();
}

public function setCurrentUser ( User $user )
{
$this->_user = $user;
$this->_user->unsetDatabaseHandler ();
$this->_saveUserData ();
}

public function getCurrentUser ()
{
return $this->_user;
}

private function _saveUserData ()
{
$_SESSION['userdata'] = serialize ( $this->_user );
}

private function _loadUserData ()
{
if ( ! empty ( $_SESSION['userdata'] ) )
{
$user = unserialize ( (string) $_SESSION['userdata'] );
if ( ! $user->validate () )
{
$this->_user = new User ( 0, 0 );
}
}
$this->_user = $user;
}

private function _removeUserData ()
{
$_SESSION['userdata'] = serialize ( new User ( 0, 0 ) );
}
}
?>
Ik zou bij DatabaseHandler::__construct() of de inloggegegevens, of het MySQLi object meegeven ipv daar constanten voor te gebruiken.

Bij fetch_assoc() kan je mysqli_result::fetch_all() gebruiken.

Bij fetch_single_assoc() kan je het volgende doen:
<?php
if($row != 0) $this->result->data_seek ( $row );
?>

Wees consistent met de underscore prefix bij private/protected vars.

Maak Logger::__construct($fileName).

Waarom een UserException? Gebruik exception waar je wat aan hebt...

Scheid User en UserHandler in
- User (een gewone gebruiker, dus email hierin, ook registratie)
- Authenication (login, authorisatie, getCurrentUser() )
- Evt kan je nog een aparte Authorization class maken (die beheert wat gebruikers wel en niet mogen)

Verder netjes
Ik heb even een paar updates gedaan, maar zit nu op school. Ga die Authorization-class nog maken, maar ik moet even kijken wanneer ik nog tijd heb. Wat Pim voor de rest heeft gezegd heb ik al aangepast, iemand anders nog opmerkingen?

PS: omdat ik niet weer 300+ regels code ga plaatsen, heb ik de beginpost aangepast; zie die dus voor wat het nu is.

Reageren