<?php

include 'php/classes/CaptchasDotNet.php';
include "php/classes/page.php";
$page = new Page;

$page->attr('title','The International Jairus Society : Guestbook');
$page->content('guestbook.php');

# produces a captcha for the guestbook form
# create the captcha object to display one and validate one if a post
# is being added
$captcha = new CaptchasDotNet('bramey', 'vgcR8s11vH8bQZIsPISiiCCu3buXgCVkV4AOdRmV',
                                'site/data/captchas','1800',
                                'abcdefghkmnopqrstuvwxyz','6','200','80');

# gets the guestbook data for this language
$file_name = "site/data/guestbook_".$page->attr('lang').".xml";
$file = file_get_contents($file_name);
$xml = new SimpleXMLElement($file);

# if we should add an entry to the list
if(isset($_POST['cmd']) && $_POST['cmd'] == 'add')
{
	# check that captcha worked
	# Check the random string to be valid and return an error message otherwise.
	if(!$captcha->validate($_POST['captcha_random']))
		$page->addError('You cannot use the same captcha image twice, please try again.');
	# Check, that the right CAPTCHA password has been entered and
	# return an error message otherwise.
	elseif (!$captcha->verify($_POST['captcha_password']))
		$page->addError('You entered the wrong text from the image, please try again.');
	# else, we are OK and can add the message
	else
	{
		# add the message to the xml
		$last_id = $xml->entry[count($xml->entry) - 1]['id'];
		$new_entry = $xml->addChild('entry');
		$new_entry->addAttribute('id',$last_id + 1);
		$new_entry->addChild('date',date("n/j/Y"));
		$new_entry->addChild('name',htmlentities($_POST['name']));
		$new_entry->addChild('message',htmlentities($_POST['message']));
		
		$page->addMessage('Entry successfully added!');
		
		# update the guestbook file
		file_put_contents($file_name,$xml->asXML());
	}
}

# the page to display of guestbook entries
$per_page = 7;
$gb_page = isset($_GET['page']) ? $_GET['page'] : 1;
# we start at the back of the list since the latest entries
# are last in the file
$start_at = (count($xml->entry) - 1) - (($gb_page - 1) * $per_page);
$stop_at = (($start_at - $per_page) < 0) ? 0 : $start_at - $per_page + 1;

# get the entries for this page and determine if
# there should be a link to newer and/or older posts
$entries = $xml->entry;
$older = $stop_at != 0 ? $gb_page + 1 : 0;
$newer = $xml->entry[$start_at + 1] ? $gb_page - 1 : 0;

$page->data('captcha',$captcha);
$page->data('guestbook',$entries);
$page->data('older',$older);
$page->data('newer',$newer);
$page->data('start_at',$start_at);
$page->data('stop_at',$stop_at);
$page->process();

?>