-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfn.php
More file actions
280 lines (242 loc) · 8.01 KB
/
fn.php
File metadata and controls
280 lines (242 loc) · 8.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
<?php
// ANSI Color Codes for console output
const COLOR_GREEN = "\033[0;32m";
const COLOR_RED = "\033[0;31m";
const COLOR_BLUE = "\033[0;34m";
const COLOR_YELLOW = "\033[0;33m";
const COLOR_NC = "\033[0m"; // No Color
/**
* Ensure a directory exists and has 0777 permissions.
*
* @param string $path The path of the directory to ensure.
*/
function ensureDirectory($path)
{
if (!file_exists($path)) {
mkdir($path, 0777, true);
} else {
chmod($path, 0777);
}
}
/**
* Replace the ${INSTALL_DIR} placeholder in a template file and
* write the result to the given output path.
*
* @param string $templatePath The source template file.
* @param string $outputPath The destination output file.
*/
function replaceAndWrite($templatePath, $outputPath)
{
$installDir = str_replace("\\", "/", __DIR__);
$content = file_get_contents($templatePath);
$content = str_replace('${INSTALL_DIR}', $installDir, $content);
file_put_contents($outputPath, $content);
}
/**
* Adds a directory to the system PATH environment variable if it's not already present.
*
* @param string $newPath The directory path to add.
*/
function addPathToEnvironment($newPath)
{
$newPath = rtrim($newPath, DIRECTORY_SEPARATOR);
$os = strtoupper(substr(PHP_OS, 0, 3));
if ($os === 'WIN') {
// Windows system
$currentPath = trim(shell_exec('echo %PATH%'));
$separator = ';';
$commandPrefix = 'setx PATH ';
} else {
// Unix/Linux/macOS system
$currentPath = getenv('PATH');
$separator = ':';
}
$paths = explode($separator, $currentPath);
$normalizedPaths = array_map('trim', $paths);
// Check if new path is already in PATH
if (in_array($newPath, $normalizedPaths)) {
echo "Path already exists in PATH.\n";
return;
}
// Append the new path
$updatedPath = $currentPath . $separator . $newPath;
if ($os === 'WIN') {
// Use setx to persist environment variable in Windows
$command = $commandPrefix . escapeshellarg($updatedPath);
exec($command, $output, $resultCode);
if ($resultCode === 0) {
echo "Path successfully added to PATH.\n";
} else {
echo "Failed to update PATH. You may need to run this script as administrator.\n";
}
} else {
// For Unix/Linux, suggest user to manually update shell profile
echo "To update your PATH, add the following to your shell profile:\n";
echo 'export PATH="$PATH:' . $newPath . '"' . "\n";
}
}
/**
* Attempts to stop all running processes by their executable name (Windows only).
*
* @param string $name The process executable name (e.g., "notepad.exe").
*/
function stopProcessByName($name)
{
echo "Stopping $name...\n";
$output = [];
exec("taskkill /F /IM $name", $output);
exec("tasklist /FI \"IMAGENAME eq $name\" 2>NUL", $output);
if (count($output) <= 1) {
echo " [INFO] $name is not running.\n";
return;
}
// Kill all processes with this name
exec("taskkill /F /IM $name", $result, $exitCode);
if ($exitCode === 0) {
echo " [OK] $name stopped successfully.\n";
} else {
echo " [ERROR] Failed to stop $name.\n";
}
}
/**
* Deletes a folder and all its contents.
*
* @param string $path The directory to delete.
*/
function deleteFolder($path)
{
if (!file_exists($path)) {
return;
}
$items = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($items as $item) {
$item->isDir()
? rmdir($item->getRealPath())
: unlink($item->getRealPath());
}
rmdir($path);
}
/**
* Fetch JSON data from a given URL (with SSL verification disabled).
*
* @param string $url The URL to fetch.
* @return array|null The parsed JSON response, or null on failure.
*/
function fetchJson($url)
{
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_USERAGENT => 'MagicServerInstaller/1.0',
CURLOPT_HTTPHEADER => ['Accept: application/vnd.github.v3+json'],
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_TIMEOUT => 20,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false
]);
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$err = curl_error($ch);
curl_close($ch);
if ($httpCode !== 200 || !$result) {
echo "❌ Failed to fetch JSON. HTTP Code: $httpCode\n";
if ($err) {
echo "cURL Error: $err\n";
}
return null;
}
return json_decode($result, true);
}
function getGithubAssetSizes($owner, $repo, $tag = 'latest')
{
$url = "https://api.github.com/repos/{$owner}/{$repo}/releases/" . $tag;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'PHP'); // GitHub API butuh user-agent
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$response = curl_exec($ch);
curl_close($ch);
if (!$response) {
return false;
}
$data = json_decode($response, true);
if (!isset($data['assets'])) {
return false;
}
$sizes = array();
foreach ($data['assets'] as $asset) {
$sizes[] = array(
'name' => $asset['name'],
'size' => $asset['size'], // dalam byte
'download_url' => $asset['browser_download_url']
);
}
return $sizes;
}
/**
* Fetch a binary stream from the given URL.
*
* @param string $url The URL to fetch.
* @param callable|null $progressCallback A callback function for download progress.
* @return string|false The downloaded data, or false on failure.
*/
function fetchStream($url, $progressCallback = null)
{
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_USERAGENT => 'MagicServerInstaller/1.0',
CURLOPT_NOPROGRESS => false, // Required to enable progress function
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false
]);
if ($progressCallback !== null && is_callable($progressCallback)) {
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, $progressCallback);
}
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
/**
* Downloads a file from a URL and saves it to a destination, showing progress.
*
* @param string $url The URL of the file to download.
* @param string $destination The path to save the file.
* @return bool True on success, false on failure.
*/
function downloadFileWithProgress($url, $destination)
{
$fileHandle = fopen($destination, 'w');
if ($fileHandle === false) {
echo COLOR_RED . "❌ Could not open file for writing: $destination\n" . COLOR_NC;
return false;
}
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FILE, $fileHandle);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'MagicAppBuilder Installer');
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Add this line
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // Add this line
curl_setopt($ch, CURLOPT_NOPROGRESS, false);
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, function ($resource, $download_size, $downloaded) {
if ($download_size > 0) {
$percentage = round($downloaded * 100 / $download_size);
$barLength = 40;
$filledLength = round($barLength * $percentage / 100);
$bar = str_repeat('=', $filledLength) . str_repeat(' ', $barLength - $filledLength);
printf("\rDownloading: [%s] %d%%", $bar, $percentage);
}
});
$result = curl_exec($ch);
curl_close($ch);
fclose($fileHandle);
echo "\n"; // New line after progress bar
return $result;
}