Merge pull request #345 from asarhaddon/ada.2
[jackhill/mal.git] / php / readline.php
1 <?php
2
3 if (php_sapi_name() == "cli") {
4 $HISTORY_FILE = $_SERVER['HOME'] . "/.mal-history";
5 function mal_readline($prompt) {
6 global $HISTORY_FILE;
7 static $history_loaded = false;
8
9 // Load the history file
10 if (! $history_loaded) {
11 $history_loaded = true;
12 if (is_readable($HISTORY_FILE)) {
13 if ($file = fopen($HISTORY_FILE, "r")) {
14 while (!feof($file)) {
15 $line = fgets($file);
16 if ($line) { readline_add_history($line); }
17 }
18 fclose($file);
19 }
20 }
21 }
22
23 $line = readline($prompt);
24 if ($line === false) { return NULL; }
25 readline_add_history($line);
26
27 // Append to the history file
28 if (is_writable($HISTORY_FILE)) {
29 if ($file = fopen($HISTORY_FILE, "a")) {
30 fputs($file, $line . "\n");
31 fclose($file);
32 }
33 }
34
35 return $line;
36 }
37 } else {
38 function mal_readline($prompt) {}
39 }
40
41 ?>