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 $index = rand(0, $amount);
43 while ($quotes[$i] < $index) {
47 return $this->getRandomQuote($dir . "/" . $files[$i]);
53 Reads the number of quotes in the file.
55 function getNumberOfQuotes($file)
57 $fd = fopen($file, "rb");
58 $this->readLong($fd); // Just move over the first long. Might as well be fseek.
59 $len = $this->readLong($fd);
65 Picks quote number $index from the dat-file in $file.
67 function getExactQuote($file, $index)
69 if (is_file($file) == false) {
70 echo "Input must be a file!<br/>";
74 if (($fd = fopen($file, "rb")) == false) {
75 echo "Cannot open $file<br/>";
78 fseek($fd, 24 + 4 * $index);
80 $phys_index = $this->readLong($fd);
84 $quotefile = substr($file, 0, strlen($file) - 4);
86 if (($fd = fopen($quotefile, "rb")) == false) {
87 echo "Cannot find file $quotefile!<br/>";
90 $res = $this->getQuote($fd, $phys_index);
97 Returns a random quote from $file.
99 function getRandomQuote($file)
101 $number = $this->getNumberOfQuotes($file);
103 $index = rand(0, $number - 1);
105 return $this->getExactQuote($file, $index);
109 Reads a quote from the specified index.
111 function getQuote($fd, $index)
118 $line = fgets($fd, 1024) . "<br>";
119 } while (($line[0] != "%") && (!feof($fd)));
125 Gets indexes from the file pointed to by the filedescriptor $fd.
127 function getIndices($fd)
129 fseek($fd, 24, SEEK_SET);
132 while (feof($fd) == FALSE) {
133 $res[$i] = readLong($fd);
139 function readLong($fd)
141 $res = fread($fd, 4);
143 $l += ord($res[2]) << 8;
144 $l += ord($res[1]) << 16;
145 $l += ord($res[0]) << 24;
149 function createIndexFile($file)
151 $fd = @fopen($file, "r");
164 if ($line == "%\n") {
165 $indices[$i] = ftell($fd);
167 if ($length > $longest)
170 if ($length < $shortest)
175 $length = $length + strlen($line);
181 $fd = @fopen($file . ".dat", "w");
184 echo "<!-- createIndexFile: Could not write to file....-->";
189 $this->writeLong($fd, 2);
190 $this->writeLong($fd, count($indices));
191 $this->writeLong($fd, $longest);
192 $this->writeLong($fd, $shortest);
193 $this->writeLong($fd, 0);
194 $this->writeLong($fd, 37 << 24);
196 for ($i = 0; $i < count($indices); $i++) {
197 $this->writeLong($fd, $indices[$i]);
203 function writeLong($fd, $l)
205 fwrite($fd, chr(($l >> 24) & 255));
206 fwrite($fd, chr(($l >> 16) & 255));
207 fwrite($fd, chr(($l >> 8) & 255));
208 fwrite($fd, chr($l & 255));