]> jfr.im git - irc/unrealircd/unrealircd-webpanel.git/blame - Classes/class-upgrade.php
=]
[irc/unrealircd/unrealircd-webpanel.git] / Classes / class-upgrade.php
CommitLineData
840c8c3e
VP
1<?php
2
3class Upgrade
4{
5 public $web_dir;
1ff0282b 6 private $temp_dir;
8fed0ffb 7 private static $temp_extracted_dir;
840c8c3e
VP
8 public static $upgrade_available;
9 public static $last_check;
10 public $error;
11 public static $latest_version;
12 function __construct()
13 {
14 global $config;
15 read_config_db();
16 if (!get_config('upgrade'))
17 {
18 $config['upgrade'] =[];
19 write_config('upgrade');
20 }
21
22 $tok = split(__DIR__, '/');
23 unset($tok[count($tok) - 1]);
24 $this->web_dir = implode('/',$tok).'/';
840c8c3e 25
1ff0282b 26 /** prepare the temp directory */
24432aab
VP
27 $temp_dir = $this->web_dir."panel_upgrade";
28 $temp_dir .= ($temp_dir[strlen($temp_dir) - 1] != '/') ? "/" : "";
8fed0ffb
VP
29 if (file_exists($temp_dir)) {
30 deleteDirectoryContents($temp_dir);
31 rmdir($temp_dir);
32 }
1ff0282b
VP
33 $mkdir = mkdir($temp_dir, 0755, true);
34
35 $this->temp_dir = $mkdir ? $temp_dir : NULL;
36 $this->error = $mkdir ? NULL : "Could not create directory: $temp_dir";
840c8c3e 37 Upgrade::$upgrade_available = false;
840c8c3e
VP
38 if ($this->error)
39 error_log($this->error);
840c8c3e
VP
40 }
41
42 /** Checks for a new upgrade */
43 function checkForNew()
44 {
45 global $config;
46 read_config_db();
24432aab
VP
47 $last_check = &$config['upgrade']['last_check'];
48 if (isset($last_check) && time() - $last_check < 300) // only check every 15 mins
49 {
50 error_log("Skipping upgrade check, checked ".time() - $last_check." seconds ago");
1ff0282b 51 return false;
24432aab
VP
52 }
53 error_log(time()." - ".$last_check." = ".time()-$last_check);
54 $apiUrl = "https://api.github.com/repos/unrealircd/unrealircd-webpanel/releases";
55 $response = file_get_contents($apiUrl, false, stream_context_create(
56 ["http" => ["method" => "GET", "header" => "User-agent: UnrealIRCd Webpanel"]]
57 ));
58
840c8c3e
VP
59 if ($response === false)
60 {
61 $this->error = "Couldn't check github.";
62 return false;
63 }
64 $data = json_decode($response, true);
65 $latest = $data[count($data) - 1];
66 $config['upgrade']['latest_version'] = $latest['tag_name'];
24432aab 67 $last_check = time();
840c8c3e
VP
68 $config['upgrade']['download_link'] = $latest['zipball_url'];
69 write_config('upgrade');
70 Upgrade::$upgrade_available = (float)$latest['tag_name'] > WEBPANEL_VERSION ? true : false;
71 }
72
73 function downloadUpgradeZip()
74 {
75 $ch = curl_init(get_config('upgrade::download_link'));
24432aab 76 $fp = fopen($this->temp_dir."unrealircd-webpanel-upgrade.zip", 'w+');
840c8c3e
VP
77
78 curl_setopt($ch, CURLOPT_FILE, $fp);
79 curl_setopt($ch, CURLOPT_TIMEOUT, 60);
80 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
81 curl_setopt($ch, CURLOPT_HTTPHEADER, [
82 'User-Agent: UnrealIRCd Webpanel',
83 ]);
84 $success = curl_exec($ch);
1ff0282b
VP
85 $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
86
24432aab 87 if ($code == "403" || $code == "404")
1ff0282b
VP
88 {
89 $this->error ="Unable to download";
90 }
840c8c3e
VP
91 curl_close($ch);
92 fclose($fp);
93
94 return $success;
95 }
1ff0282b
VP
96 function extractZip() {
97 $zip = new ZipArchive;
24432aab 98 if ($zip->open($this->temp_dir."unrealircd-webpanel-upgrade.zip") === true)
1ff0282b 99 {
24432aab 100 $zip->extractTo("$this->temp_dir");
1ff0282b 101 $zip->close();
8fed0ffb
VP
102 self::$temp_extracted_dir = findOnlyDirectory($this->temp_dir);
103 error_log(self::$temp_extracted_dir);
1ff0282b
VP
104 return true;
105 } else {
106 return false;
107 }
840c8c3e 108 }
1ff0282b 109 function cleanupOldFiles()
8fed0ffb
VP
110 {
111 foreach ($this->compareAndGetFilesToDelete() as $file)
9d686725
VP
112 {
113 unlink("$this->web_dir$file");
114 error_log("Deleting: $file");
115 }
8fed0ffb
VP
116 }
117 function compareAndGetFilesToDelete() : array
1ff0282b
VP
118 {
119 $currentFiles = $this->listFiles($this->web_dir);
8fed0ffb 120 $updateFiles = $this->listFiles(self::$temp_extracted_dir);
1ff0282b 121 $filesToDelete = array_diff($currentFiles, $updateFiles);
8fed0ffb 122 $filesToActuallyDelete = [];
24432aab 123 error_log("Comparing... Files to delete:");
1ff0282b
VP
124 foreach ($filesToDelete as $file)
125 {
8fed0ffb
VP
126 // skip the relevant directories
127 if (str_starts_with($file, "panel_upgrade/")
128 || str_starts_with($file, "vendor/")
129 || str_starts_with($file, "config/")
130 || str_starts_with($file, "data/")
131 || str_starts_with($file, "plugins/"))
132 continue;
133 $filesToActuallyDelete[] = $file;
1ff0282b 134 }
8fed0ffb 135 return $filesToActuallyDelete;
840c8c3e 136 }
1ff0282b
VP
137
138 function extractToWebdir()
139 {
140 $zip = new ZipArchive;
24432aab 141 if ($zip->open($this->temp_dir."unrealircd-webpanel-upgrade.zip") === true)
1ff0282b 142 {
9d686725 143 $extracted = $zip->extractTo($this->web_dir);
1ff0282b
VP
144 $zip->close();
145 if (!$extracted)
146 {
147 error_log("Cannot extract to web directory. Permission denied.");
148 return false;
149 }
1ff0282b 150 return true;
840c8c3e 151 } else {
091cbfa1 152 error_log("Cannot open zip at $this->temp_dir");
1ff0282b
VP
153 return false;
154 }
155 }
24432aab
VP
156
157 /**
158 * Cleans up the extracted update files
159 * @return void
160 */
161 function cleanupDownloadFiles()
162 {
8fed0ffb
VP
163 $ex_dir = self::$temp_extracted_dir ?? findOnlyDirectory($this->temp_dir);
164 deleteDirectoryContents($ex_dir);
165 rmdir($ex_dir);
24432aab
VP
166 }
167
1ff0282b
VP
168 function listFiles($dir) {
169 $files = [];
170 $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
171 foreach ($iterator as $file)
172 {
173 if ($file->isFile())
174 {
24432aab
VP
175 $f = substr($file->getPathname(), strlen($dir));
176 if ($f[0] == "/") $f = substr($f,1);
24432aab
VP
177
178 $files[] = $f;
1ff0282b 179 }
840c8c3e 180 }
1ff0282b 181 return $files;
840c8c3e 182 }
840c8c3e 183}
24432aab
VP
184
185
186function findOnlyDirectory($topDir) {
187 // Ensure the directory exists and is indeed a directory
188 if (!is_dir($topDir)) {
189 die("The specified path is not a directory.");
190 }
191
192 // Open the directory
193 $dirHandle = opendir($topDir);
194 if ($dirHandle === false) {
195 die("Unable to open directory.");
196 }
197
198 $directories = [];
199
200 // Read through the directory contents
201 while (($entry = readdir($dirHandle)) !== false) {
202 $fullPath = $topDir . DIRECTORY_SEPARATOR . $entry;
203 // Check if the entry is a directory and not . or ..
204 if (is_dir($fullPath) && $entry !== '.' && $entry !== '..') {
205 $directories[] = $fullPath;
206 }
207 }
208
209 // Close the directory handle
210 closedir($dirHandle);
211
212 // Check if there is exactly one directory
213 if (count($directories) === 1) {
214 return $directories[0];
215 } elseif (count($directories) === 0) {
216 return "No directories found after extracting. Possibly missing php-zip extention. Aborting upgrade.";
217 } else {
218 return "Multiple directories found. Previous cleanup was unsuccessful for some reason, maybe a permissions error? Aborting upgrade.";
219 }
8fed0ffb
VP
220}
221
222
223function deleteDirectoryContents($dir) {
224 error_log("Deleting directory contents at $dir");
225 if (!is_dir($dir)) {
226 echo "The provided path is not a directory.";
227 return false;
228 }
229
230 // Open the directory
231 $handle = opendir($dir);
232 if ($handle === false) {
233 echo "Failed to open the directory.";
234 return false;
235 }
236
237 // Loop through the directory contents
238 while (($item = readdir($handle)) !== false) {
239 // Skip the special entries "." and ".."
240 if ($item == "." || $item == "..") {
241 continue;
242 }
243
244 $itemPath = $dir."/".$item;
245
246 // If the item is a directory, recursively delete its contents
247 if (is_dir($itemPath)) {
248 deleteDirectoryContents($itemPath);
249 // Remove the empty directory
250 rmdir($itemPath);
251 } else {
252 // If the item is a file, delete it
253 unlink($itemPath);
254 }
255 }
256
257 // Close the directory handle
258 closedir($handle);
259
260 return true;
24432aab 261}