<?php
/* daCode http://www.dacode.org/
 * src/phplib/fortunes.php3
 * $Id: fortunes.php3,v 1.10 2001/07/14 20:15:23 barbier Exp $
 *
 * Will contain a fortune module
 *
 * Thanks to yog <yogi@nicolas.as> for the code
 *
 * Depends: Config
 */

Class Fortunes {
	var $config;

	Function Fortunes() {
//echo '<br>Fortunes';
	}

	Function get_random() {
		global $config;

		// Exit if file doesn't exist
		if ($config->fortunefile == '' || !file_exists($config->fortunefile)) {
			return;
		}

		// Get size for random number
		$size = filesize($config->fortunefile);
		// Open file read only
		$file = fopen($config->fortunefile, "r");
		// Generate random in $rand between 0 to size of file
		mt_srand((double)microtime()*1000000);
		$rand = mt_rand(0,$size);
		// Go forward in the file
		fseek($file,$rand);
		$pointeur = $rand + 1;
		$comp = fgetc($file);
		while ($comp != "%") {
			$pointeur++;
			$comp = fgetc($file);
			if ($pointeur == $size - 1) {
				$pointeur = -1;
				rewind($file);
				break;
			}
		}

		//  Skip % and newline
		$pos1 = $pointeur + 2;
		$pointeur++;
		$comp = fgetc($file);
		while ($comp != "%") {
			$pointeur++;
			$comp = fgetc($file);
			//   Just in case trailing % is missing
			if ($pointeur == $size - 1) {
				break;
			}
		}
		$pos2 = $pointeur;
		$length = $pos2 - $pos1;
		fseek($file,$pos1 - 1);
		if ($length < 0) {
			return;
		}

		$out=fread($file,$length);
		fclose($file);

		$out=htmlentities($out);
		$out=nl2br($out);

		return $out;
	}

}

?>
