2 // PHP Fortune - Made by henrik@aasted.org. HP: http://www.aasted.org
7 Quotes from any of the fortune-files in the dir.
9 Quotes from the specific file.
11 Written by Henrik Aasted Sorensen, henrik@aasted.org
12 Read more at http://www.aasted.org/quote
17 function quoteFromDir($dir)
24 if ($handle = opendir($dir)) {
25 while (false !== ($file = readdir($handle))) {
27 if (strpos($file, ".dat") != false) {
29 if (substr($file, $len - 4) == ".dat") {
30 $number = $this->getNumberOfQuotes($dir . "/" . $file);
32 $quotes[$index] = $amount;
33 $files[$index] = $file;
39 srand((double)microtime() * 1000000);
40 $index = rand(0, $amount);
44 while ($quotes[$i] < $index) {
48 return $this->getRandomQuote($dir . "/" . $files[$i]);
54 Reads the number of quotes in the file.
56 function getNumberOfQuotes($file)
58 $fd = fopen($file, "rb");
59 $this->readLong($fd); // Just move over the first long. Might as well be fseek.
60 $len = $this->readLong($fd);
66 Picks quote number $index from the dat-file in $file.
68 function getExactQuote($file, $index)
70 if (is_file($file) == false) {
71 echo "Input must be a file!<br/>";
75 if (($fd = fopen($file, "rb")) == false) {
76 echo "Cannot open $file<br/>";
79 fseek($fd, 24 + 4 * $index);
81 $phys_index = $this->readLong($fd);
85 $quotefile = substr($file, 0, strlen($file) - 4);
87 if (($fd = fopen($quotefile, "rb")) == false) {
88 echo "Cannot find file $quotefile!<br/>";
91 $res = $this->getQuote($fd, $phys_index);
98 Returns a random quote from $file.
100 function getRandomQuote($file)
102 $number = $this->getNumberOfQuotes($file);
104 $index = rand(0, $number - 1);
106 return $this->getExactQuote($file, $index);
110 Reads a quote from the specified index.
112 function getQuote($fd, $index)
119 $line = fgets($fd, 1024) . "<br>";
120 } while (($line[0] != "%") && (!feof($fd)));
126 Gets indexes from the file pointed to by the filedescriptor $fd.
128 function getIndices($fd)
130 fseek($fd, 24, SEEK_SET);
133 while (feof($fd) == FALSE) {
134 $res[$i] = readLong($fd);
140 function readLong($fd)
142 $res = fread($fd, 4);
144 $l += ord($res[2]) << 8;
145 $l += ord($res[1]) << 16;
146 $l += ord($res[0]) << 24;
150 function createIndexFile($file)
152 $fd = @fopen($file, "r");
165 if ($line == "%\n") {
166 $indices[$i] = ftell($fd);
168 if ($length > $longest)
171 if ($length < $shortest)
176 $length = $length + strlen($line);
182 $fd = @fopen($file . ".dat", "w");
185 echo "<!-- createIndexFile: Could not write to file....-->";
190 $this->writeLong($fd, 2);
191 $this->writeLong($fd, count($indices));
192 $this->writeLong($fd, $longest);
193 $this->writeLong($fd, $shortest);
194 $this->writeLong($fd, 0);
195 $this->writeLong($fd, 37 << 24);
197 for ($i = 0; $i < count($indices); $i++) {
198 $this->writeLong($fd, $indices[$i]);
204 function writeLong($fd, $l)
206 fwrite($fd, chr(($l >> 24) & 255));
207 fwrite($fd, chr(($l >> 16) & 255));
208 fwrite($fd, chr(($l >> 8) & 255));
209 fwrite($fd, chr($l & 255));