<?php
/*
 *	phpBookLoan Database Frontend
 *
 *	Version 1.0
 *
 *	Copyright(C) 2000 Christian W. Conkle <christian@conkle.org>
 *
 *	#ifdef LAWYER
 *
 *	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 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.
 *
 *	#endif
 *
 *	This is the frontend to a very plain loan database.  This doesn't do 
 *	anything particularly fancy- it doesn't even store a due date.  It was
 *	made for my own	personal use- if it's useful to you also, please use it.
 *
 *	The purpose of this program is to keep track of books that have been
 *	lent- so  the user can easily look them up and hound the people about
 *	the wronged books. >:)
 *
 *	It uses MySQL for a backend, although that could easily be changed.  The
 *	table should look like this:
 *
 *	+----------+------------------+------+-----+---------+----------------+
 *	| Field    | Type             | Null | Key | Default | Extra          |
 *	+----------+------------------+------+-----+---------+----------------+
 *	| ID       | int(10) unsigned |      | PRI | 0       | auto_increment |
 *	| title    | varchar(40)      | YES  |     | NULL    |                |
 *	| author   | varchar(40)      | YES  |     | NULL    |                |
 *	| borrower | varchar(20)      | YES  |     | NULL    |                |
 *	| loandate | date             | YES  |     | NULL    |                |
 *	+----------+------------------+------+-----+---------+----------------+
 *
 *	If you like, that can be accomplished with (names changed, of course):
 *
 *	CREATE TABLE $db.$table (ID int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
 *		title VARCHAR(40),
 *		author VARCHAR(40),
 *		borrower VARCHAR(20),
 *		loandate DATE,
 *		PRIMARY KEY(ID));
 *
 *	The fields can be in any order, and of course you can modify, add to, 
 *	remove from, and improve it to your heart's content.
 *
 *	Functions to do several helpful things- for instance, to make a list of
 *	selections for the user based on SELECT UNIQUE, can be found in the code
 *	to my CD Database frontend, on which this is based.
 *	Don't come crying to me for support- this is very simple.  This is, in
 *	fact, only my second project in either PHP or MySQL- the CD database was
 *	my first. :)  If you don't like my coding style... bugger off. ;)
 *	
 */
	$title = 'The Dusty Bookshelf';
	$db = 'books';
	$table = 'loaned';
	$server = 'mysql:3306';
	$user = 'librarian';
	$password = 'bookworm';	

	$link = mysql_pconnect($server, $user, $password) or die ("Connect failed, dying.");
	
	$me = end(explode("/", $HTTP_SERVER_VARS["PHP_SELF"]));
	
	//Functions
	
	function lend_book()
	{
		global $db;
		global $table;
		global $link;
		global $HTTP_POST_VARS;
		
		$title = addslashes($HTTP_POST_VARS['title']);
		$author = addslashes($HTTP_POST_VARS['author']);
		$borrower = addslashes($HTTP_POST_VARS['borrower']);
		
		mysql_query("INSERT INTO $db.$table VALUES ( NULL , \"$title\" , \"$author\" , \"$borrower\", NOW() );", $link);
		return;
	}
	
	function return_book()
	{
		global $db;
		global $table;
		global $link;
		global $HTTP_POST_VARS;
		
		foreach ($HTTP_POST_VARS['ids'] as $id)
			mysql_query("DELETE FROM $db.$table WHERE ID = \"$id\";", $link);
		return;
	}
	
	function require_login() // pop up ye olde authorisation[sic] dialog box
	{
		header('WWW-Authenticate: Basic realm="phpBookLoan"');
		header('HTTP/1.0 401 Unauthorized');
		echo 'Authorization Required.';
		exit;
	}
	
	function check_auth_pair() // Checks an auth pair against $db.users.  Returns 1 if login is bad
	{
		// Check login against the password database
		global $link;
		global $db;
		global $HTTP_SERVER_VARS;
		
		$username = $HTTP_SERVER_VARS['PHP_AUTH_USER'];
		$password = $HTTP_SERVER_VARS['PHP_AUTH_PW'];
		/*
		 * The following lines basically check whether a user/password pair exists.
		 * First, we query the database for entries that match the auth info.
		 * Then, we get the number of rows- if it's 0, there are no rows- the login is invalid.
		 * We return the opposite of this.
		 */
		$result = mysql_query ("SELECT * FROM $db.users WHERE name=\"$username\" AND password=PASSWORD(\"$password\");", $link);
		return !mysql_num_rows($result);
		
	}
	
	function do_auth() // Handles the whole authorization process.
	{
		global $link;
		global $HTTP_SERVER_VARS;
		
		if (empty($HTTP_SERVER_VARS['PHP_AUTH_USER']))
			require_login();
		if (check_auth_pair())  // If the login info aint right
			require_login();  // This kills the script.
		return 0;
	}
	
	// End functions.  Here starts the (small) main code.
	
	do_auth(); // It's my choice to require authorization to view the table, too.  This was not the initial design; you might want to move this call two lines down.
	
	if(!empty($HTTP_POST_VARS)) // We are handling a submission
	{
		if($HTTP_POST_VARS["whichform"] == "return") // We are returning a book
			return_book();
		elseif($HTTP_POST_VARS["whichform"] == "lend") // <F2>We are lending a book
			lend_book();
		else
			die ("What?");
	}

?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> 
<html>
<head>
	<title><? echo $title; ?> - Loaned Books Database</title>
</head>
<body bgcolor="#FFFFFF" text="#000000">
<h2 align="CENTER">
	Loaned Books Database
</h2>
<form method=POST action=<? echo $me; ?>>
<input type=hidden name=whichform value=return> <!--For convinience-->
<table border width="90%" align="center">	
	<tr align="CENTER">
		<th><a href="<?echo $me?>?sortby=title">Title</a></th>
		<th><a href="<?echo $me?>?sortby=author">Author</a></th>
		<th><a href="<?echo $me?>?sortby=borrower">Borrower</a></th>
		<th><a href="<?echo $me?>?sortby=loandate">Loan Date</a></th>
		<th><a href="<?echo $me?>?sortby=days">Days Ago Loaned</a></th>
		<th>Return</th>
	</tr>	
<?php
	if(!empty($HTTP_GET_VARS['sortby']))
		$sortby = addslashes($HTTP_GET_VARS['sortby']);
	else
		$sortby = 'borrower';
	$result = mysql_query ("SELECT *, (TO_DAYS(NOW()) - TO_DAYS(loandate)) AS days FROM $db.$table ORDER BY $sortby;", $link) or die ("Query failed, dying.");
	while($row = mysql_fetch_object ($result)) {
		echo "	<tr align=\"CENTER\">\n";
		echo "		<td>", $row->title, "</td>\n";
		echo "		<td>", $row->author, "</td>\n";
		echo "		<td>", $row->borrower, "</td>\n";
		echo "		<td>", $row->loandate, "</td>\n";
		echo "		<td>", $row->days, "</td>\n";
		echo "		<td><input type=checkbox name=\"ids[]\" value=", $row->ID, "></td>\n";
		echo "	</tr>\n";
	}
	mysql_free_result($result);
?>
</table>
<br>
<input type=submit value="Return Checked Books">
</form>  <!-- End of the modify form -->
<form method=POST action=<? echo $me; ?>>
<input type=hidden name=whichform value=lend>
<table border align="CENTER">
	<tr>
		<th colspan=4>Loan New Book</th>
		
	</tr>
	<tr>
		<th>Title</th>
		<th>Author</th>
		<th>Borrower</th>
		<td rowspan=3>
			<input type=submit value="Add item">
		</td>
	<tr>
		<td><input type=text size=30 maxlength=40 name=title></td>
		<td><input type=text size=30 maxlength=40 name=author></td>
		<td><input type=text size=15 maxlength=20 name=borrower></td>
	</tr>
</table>
</form>
			
<p>
 <a href="http://validator.w3.org/check/referer"><img border=0
    src="http://validator.w3.org/images/vh40"
    alt="Valid HTML 4.0!" height=31 width=88></a>
</p>
</body>
</html>
