Storage::clearTmpFiles()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 26
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 16
dl 0
loc 26
rs 9.7333
c 1
b 0
f 0
cc 4
nc 4
nop 0
1
<?php
2
3
/*
4
 * MikoPBX - free phone system for small business
5
 * Copyright © 2017-2023 Alexey Portnov and Nikolay Beketov
6
 *
7
 * This program is free software: you can redistribute it and/or modify
8
 * it under the terms of the GNU General Public License as published by
9
 * the Free Software Foundation; either version 3 of the License, or
10
 * (at your option) any later version.
11
 *
12
 * This program is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU General Public License along with this program.
18
 * If not, see <https://www.gnu.org/licenses/>.
19
 */
20
21
namespace MikoPBX\Core\System;
22
23
use Error;
24
use JsonException;
25
use MikoPBX\Common\Config\ClassLoader;
26
use MikoPBX\Common\Models\PbxExtensionModules;
27
use MikoPBX\Common\Models\PbxSettings;
28
use MikoPBX\Common\Models\SoundFiles;
29
use MikoPBX\Common\Models\Storage as StorageModel;
30
use MikoPBX\Common\Providers\ConfigProvider;
31
use MikoPBX\Common\Providers\MainDatabaseProvider;
32
use MikoPBX\Core\Asterisk\CdrDb;
33
use MikoPBX\Core\Config\RegisterDIServices;
34
use MikoPBX\Core\System\Configs\PHPConf;
35
use MikoPBX\Core\System\Configs\SyslogConf;
36
use MikoPBX\Core\System\Upgrade\UpdateDatabase;
37
use MikoPBX\Modules\PbxExtensionUtils;
38
use MikoPBX\PBXCoreREST\Lib\System\ConvertAudioFileAction;
39
use MikoPBX\PBXCoreREST\Workers\WorkerApiCommands;
40
use Phalcon\Di\Injectable;
41
42
use function MikoPBX\Common\Config\appPath;
43
44
/**
45
 * Class Storage
46
 *
47
 * Manages storage-related operations.
48
 *
49
 * @package MikoPBX\Core\System
50
 * @property \Phalcon\Config\Config config
51
 */
52
class Storage extends Injectable
53
{
54
    /**
55
     * Move read-only sounds to the storage.
56
     * This function assumes a storage disk is mounted.
57
     *
58
     * @return void
59
     */
60
    public function moveReadOnlySoundsToStorage(): void
61
    {
62
        // Check if a storage disk is mounted
63
        if (!self::isStorageDiskMounted()) {
64
            return;
65
        }
66
67
        // Create the current media directory if it doesn't exist
68
        $currentMediaDir =  $this->config->path('asterisk.customSoundDir') . '/';
69
        if (!file_exists($currentMediaDir)) {
70
            Util::mwMkdir($currentMediaDir);
71
        }
72
73
        $soundFiles = SoundFiles::find();
74
75
        // Iterate through each sound file
76
        foreach ($soundFiles as $soundFile) {
77
            if (stripos($soundFile->path, '/offload/asterisk/sounds/other/') === 0) {
78
                $newPath = $currentMediaDir . pathinfo($soundFile->path)['basename'];
79
80
                // Copy the sound file to the new path
81
                if (copy($soundFile->path, $newPath)) {
82
                    ConvertAudioFileAction::main($newPath);
83
84
                    // Update the sound file path and extension
85
                    $soundFile->path = Util::trimExtensionForFile($newPath) . ".mp3";
86
87
                    // Update the sound file if the new path exists
88
                    if (file_exists($soundFile->path)) {
89
                        $soundFile->update();
90
                    }
91
                }
92
            }
93
        }
94
        unset($soundFiles);
95
    }
96
97
    /**
98
     * Check if a storage disk is mounted.
99
     *
100
     * @param string $filter Optional filter for the storage disk.
101
     * @param string $mount_dir If the disk is mounted, the mount directory will be stored in this variable.
102
     * @return bool Returns true if the storage disk is mounted, false otherwise.
103
     */
104
    public static function isStorageDiskMounted(string $filter = '', string &$mount_dir = ''): bool
105
    {
106
        // Check if it's a T2Sde Linux and /storage/usbdisk1/ exists
107
        if (
108
            !Util::isT2SdeLinux()
109
            && file_exists('/storage/usbdisk1/')
110
        ) {
111
            $mount_dir = '/storage/usbdisk1/';
112
            return true;
113
        }
114
        if ('' === $filter) {
115
            $varEtcDir = Directories::getDir(Directories::CORE_VAR_ETC_DIR);
116
            $filename = "$varEtcDir/storage_device";
117
118
            // If the storage_device file exists, read its contents as the filter,
119
            // otherwise use 'usbdisk1' as the filter
120
            if (file_exists($filename)) {
121
                $filter = file_get_contents($filename);
122
            } else {
123
                $filter = 'usbdisk1';
124
            }
125
        }
126
        $grep = Util::which('grep');
127
        $mount = Util::which('mount');
128
        $awk = Util::which('awk');
129
        $head = Util::which('head');
130
131
        $filter = escapeshellarg($filter);
132
133
        // Execute the command to filter the mount points based on the filter
134
        $out = shell_exec("$mount | $grep $filter | $awk '{print $3}' | $head -n 1");
135
        $mount_dir = trim($out ?? '');
136
        return ($mount_dir !== '');
137
    }
138
139
    /**
140
     * Copy MOH (Music on Hold) files to the storage.
141
     * This function assumes a storage disk is mounted.
142
     *
143
     * @return void
144
     */
145
    public function copyMohFilesToStorage(): void
146
    {
147
        // Check if a storage disk is mounted
148
        if (!self::isStorageDiskMounted()) {
149
            return;
150
        }
151
152
        $oldMohDir =  $this->config->path('asterisk.astvarlibdir') . '/sounds/moh';
153
        $currentMohDir = $this->config->path('asterisk.mohdir');
154
155
        // If the old MOH directory doesn't exist or unable to create the current MOH directory, return
156
        if (!file_exists($oldMohDir) || Util::mwMkdir($currentMohDir)) {
157
            return;
158
        }
159
160
        $files = scandir($oldMohDir);
161
162
        // Iterate through each file in the old MOH directory
163
        foreach ($files as $file) {
164
            if (in_array($file, ['.', '..'])) {
165
                continue;
166
            }
167
168
            // Copy the file from the old MOH directory to the current MOH directory
169
            if (copy($oldMohDir . '/' . $file, $currentMohDir . '/' . $file)) {
170
                $sound_file = new SoundFiles();
171
                $sound_file->path = $currentMohDir . '/' . $file;
172
                $sound_file->category = SoundFiles::CATEGORY_MOH;
173
                $sound_file->name = $file;
174
                $sound_file->save();
175
            }
176
        }
177
    }
178
179
    /**
180
     * Create a file system on a disk.
181
     *
182
     * @param string $dev The device path of the disk.
183
     * @return bool Returns true if the file system creation process is initiated, false otherwise.
184
     */
185
    public static function mkfsDisk(string $dev): bool
186
    {
187
        if (!file_exists($dev)) {
188
            $dev = "/dev/$dev";
189
        }
190
        if (!file_exists($dev)) {
191
            return false;
192
        }
193
        $dir = '';
194
        self::isStorageDiskMounted($dev, $dir);
195
196
        // If the disk is not mounted or successfully unmounted, proceed with the file system creation
197
        if (empty($dir) || self::umountDisk($dir)) {
198
            $st = new self();
199
            // Initiate the file system creation process
200
            $st->formatEntireDisk($dev, true);
201
            sleep(1);
202
203
            return (self::statusMkfs($dev) === 'inprogress');
204
        }
205
206
        // Error occurred during disk unmounting
207
        return false;
208
    }
209
210
    /**
211
     * Unmount a disk.
212
     *
213
     * @param string $dir The mount directory of the disk.
214
     * @return bool Returns true if the disk is successfully unmounted, false otherwise.
215
     */
216
    public static function umountDisk(string $dir): bool
217
    {
218
        $umount = Util::which('umount');
219
        $rm = Util::which('rm');
220
221
        // If the disk is mounted, terminate processes using the disk and unmount it
222
        if (self::isStorageDiskMounted($dir)) {
223
            Processes::mwExec("/sbin/shell_functions.sh 'killprocesses' '$dir' -TERM 0");
224
            Processes::mwExec("$umount $dir");
225
        }
226
        $result = !self::isStorageDiskMounted($dir);
227
228
        // If the disk is successfully unmounted and the directory exists, remove the directory
229
        if ($result && file_exists($dir)) {
230
            Processes::mwExec("$rm -rf '$dir'");
231
        }
232
233
        return $result;
234
    }
235
236
    /**
237
     * Format a disk locally using parted command and create one partition
238
     *
239
     * @param string $device The device path of the disk.
240
     * @param bool $bg Whether to run the command in the background.
241
     * @return bool Returns true if the disk formatting process is initiated, false otherwise.
242
     */
243
    public function formatEntireDisk(string $device, bool $bg = false): bool
244
    {
245
        $parted = Util::which('parted');
246
247
        // First, remove existing partitions and then create a new msdos partition table and ext4 partition
248
        // This command deletes all existing partitions and creates a new primary partition using the full disk
249
        $command = "$parted --script --align optimal '$device' 'mklabel gpt'";
250
        Processes::mwExec($command);  // Apply the command to clear the partition table
251
252
        // Now create a new partition that spans the entire disk
253
        $createPartCommand = "$parted --script --align optimal '$device' 'mkpart primary ext4 0% 100%'";
254
        $retVal = Processes::mwExec($createPartCommand);
255
256
        // Log the result of the create partition command
257
        SystemMessages::sysLogMsg(__CLASS__, "$createPartCommand returned $retVal", LOG_INFO);
258
259
        // Get the newly created partition name, assuming it's always the first partition after a fresh format
260
        $partition = self::getDevPartName($device, '1');
261
262
        return $this->formatPartition($partition, $bg);
263
    }
264
265
    /**
266
     * Format a disk locally (part 2) using mkfs command.
267
     *
268
     * @param string $partition The partition for format, "/dev/sdb1" or "/dev/nvme0n1p1".
269
     * @param bool $bg Whether to run the command in the background.
270
     * @return bool Returns true if the disk formatting process is successfully completed, false otherwise.
271
     */
272
    public function formatPartition(string $partition, bool $bg = false): bool
273
    {
274
        $mkfs = Util::which("mkfs.ext4");
275
        $cmd = "$mkfs $partition";
276
        if ($bg === false) {
277
            // Execute the mkfs command and check the return value
278
            $retVal = Processes::mwExec("$cmd 2>&1");
279
            SystemMessages::sysLogMsg(__CLASS__, "$cmd returned $retVal");
280
            $result = ($retVal === 0);
281
        } else {
282
            usleep(200000);
283
            // Execute the mkfs command in the background
284
            Processes::mwExecBg($cmd);
285
            $result = true;
286
        }
287
288
        return $result;
289
    }
290
291
    /**
292
     * Get the status of mkfs process on a disk.
293
     *
294
     * @param string $dev The device path of the disk.
295
     * @return string Returns the status of mkfs process ('inprogress' or 'ended').
296
     */
297
    public static function statusMkfs(string $dev): string
298
    {
299
        if (!file_exists($dev)) {
300
            $dev = "/dev/$dev";
301
        }
302
        $out = [];
303
        $psPath = Util::which('ps');
304
        $grepPath = Util::which('grep');
305
306
        // Execute the command to check the status of mkfs process
307
        Processes::mwExec("$psPath -A -f | $grepPath $dev | $grepPath mkfs | $grepPath -v grep", $out);
308
        $mount_dir = trim(implode('', $out));
0 ignored issues
show
Bug introduced by
It seems like $out can also be of type null; however, parameter $pieces of implode() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

308
        $mount_dir = trim(implode('', /** @scrutinizer ignore-type */ $out));
Loading history...
309
310
        return empty($mount_dir) ? 'ended' : 'inprogress';
311
    }
312
313
    /**
314
     * Selects the storage disk and performs the necessary configuration.
315
     *
316
     * @param bool $automatic Flag to determine if the disk should be selected automatically
317
     * @param bool $forceFormatStorage Flag to determine if the disk should be formatted
318
     * @return bool Returns true on success, false otherwise
319
     */
320
    public static function selectAndConfigureStorageDisk(
321
        bool $automatic = false,
322
        bool $forceFormatStorage = false
323
    ): bool {
324
        $storage = new self();
325
326
        // Check if the storage disk is already mounted
327
        if (self::isStorageDiskMounted()) {
328
            SystemMessages::echoWithSyslog(PHP_EOL . " " . Util::translate('Storage disk is already mounted...') . " ");
329
            sleep(2);
330
            return true;
331
        }
332
333
        $validDisks = [];
334
        // Get all available hard drives
335
        $all_hdd = $storage->getAllHdd();
336
        $system_disk = '';
337
        $selected_disk = ['size' => 0, 'id' => ''];
338
        // Iterate through all available hard drives
339
        foreach ($all_hdd as $disk) {
340
            $additional = '';
341
            $fourthPartitionName = self::getDevPartName($disk['id'], '4');
342
            $isLiveCd = ($disk['sys_disk'] && file_exists('/offload/livecd'));
343
            $isMountedSysDisk = (!empty($disk['mounted']) && $disk['sys_disk'] && file_exists($fourthPartitionName));
344
345
            // Check if the disk is a system disk and is mounted
346
            if ($isMountedSysDisk || $isLiveCd) {
347
                $system_disk = $disk['id'];
348
                $additional .= "\033[31;1m [SYSTEM]\033[0m";
349
            } elseif ($disk['mounted']) {
350
                // If disk is mounted but not a system disk, continue to the next iteration
351
                continue;
352
            }
353
354
            // Check if the current disk is larger than the previously selected disk
355
            if ($selected_disk['size'] === 0 || $disk['size'] > $selected_disk['size']) {
356
                $selected_disk = $disk;
357
            }
358
359
            $part = $disk['sys_disk'] ? '4' : '1';
360
            $partitionName = self::getDevPartName($disk['id'], $part);
361
            if (self::isStorageDisk($partitionName)) {
362
                $additional .= "\033[33;1m [STORAGE] \033[0m";
363
            }
364
365
            // Check if the disk is a system disk and has a valid partition
366
            if ($disk['size'] < 2 * 1024) {
367
                // If the disk size is less than 2 gb, continue to the next iteration
368
                continue;
369
            }
370
371
            // Add the valid disk to the validDisks array
372
            $validDisks[$disk['id']] = "      |- {$disk['id']}, {$disk['size_text']}, {$disk['vendor']}$additional\n";
373
        }
374
375
        if (empty($validDisks)) {
376
            // If no valid disks were found, log a message and return 0
377
            $message = '   |- ' . Util::translate('Valid disks not found...');
378
            SystemMessages::echoWithSyslog($message);
379
            SystemMessages::echoToTeletype(PHP_EOL . $message);
380
            sleep(3);
381
            return false;
382
        }
383
384
        // Check if the disk selection should be automatic
385
        if ($automatic) {
386
            $target_disk_storage = $selected_disk['id'];
387
            SystemMessages::echoToTeletype(
388
                PHP_EOL . '   - ' . "Automatically selected storage disk is $target_disk_storage"
389
            );
390
        } else {
391
            echo PHP_EOL . " " . Util::translate('Select the drive to store the data.');
392
            echo PHP_EOL . " " . Util::translate('Selected disk:') . "\033[33;1m [{$selected_disk['id']}] \033[0m " . PHP_EOL . PHP_EOL;
393
            echo(PHP_EOL . " " . Util::translate('Valid disks are:') . " " . PHP_EOL . PHP_EOL);
394
            foreach ($validDisks as $disk) {
395
                echo($disk);
396
            }
397
            echo PHP_EOL;
398
            // Open standard input in binary mode for interactive reading
399
            $fp = fopen('php://stdin', 'rb');
400
            if ($forceFormatStorage) {
401
                echo '*******************************************************************************
402
* ' . Util::translate('WARNING') . '
403
* - ' . Util::translate('everything on this device will be erased!') . '
404
* - ' . Util::translate('this cannot be undone!') . '
405
*******************************************************************************';
406
            }
407
            // Otherwise, prompt the user to enter a disk
408
            do {
409
                echo PHP_EOL . Util::translate('Enter the device name:') . Util::translate('(default value = ') . $selected_disk['id'] . ') :';
410
                $target_disk_storage = trim(fgets($fp));
411
                if ($target_disk_storage === '') {
412
                    $target_disk_storage = $selected_disk['id'];
413
                }
414
            } while (!array_key_exists($target_disk_storage, $validDisks));
415
        }
416
417
        // Determine the disk partition and format if necessary
418
        $dev_disk = "/dev/$target_disk_storage";
419
        if (!empty($system_disk) && $system_disk === $target_disk_storage) {
420
            $part = "4";
421
        } else {
422
            $part = "1";
423
        }
424
        $partitionName = self::getDevPartName($target_disk_storage, $part);
425
        if ($part === '1' && (!self::isStorageDisk($partitionName) || $forceFormatStorage)) {
426
            echo PHP_EOL . Util::translate('Partitioning and formatting storage disk') . ': ' . $dev_disk . '...' . PHP_EOL;
427
            $storage->formatEntireDisk($dev_disk);
428
        } elseif ($part === '4' && $forceFormatStorage) {
429
            echo PHP_EOL . Util::translate('Formatting storage partition 4 on disk') . ': ' . $dev_disk . '...' . PHP_EOL;
430
            passthru("exec </dev/console >/dev/console 2>/dev/console; /sbin/initial_storage_part_four create $dev_disk");
431
        } elseif ($part === '4') {
432
            echo PHP_EOL . Util::translate('Update storage partition 4 on disk') . ': ' . $dev_disk . '...' . PHP_EOL;
433
            passthru("exec </dev/console >/dev/console 2>/dev/console; /sbin/initial_storage_part_four update $dev_disk");
434
        }
435
        $partitionName = self::getDevPartName($target_disk_storage, $part);
436
        $uuid = self::getUuid($partitionName);
437
        // Create an array of disk data
438
        $data = [
439
            'device' => $dev_disk,
440
            'uniqid' => $uuid,
441
            'filesystemtype' => 'ext4',
442
            'name' => 'Storage №1'
443
        ];
444
        echo PHP_EOL . "Disk part: $dev_disk, uid: $uuid" . PHP_EOL;
445
        // Save the disk settings
446
        $storage->saveDiskSettings($data);
447
        if (file_exists('/offload/livecd')) {
448
            // Do not need to start the PBX, it's the station installation in LiveCD mode.
449
            return true;
450
        }
451
        MainDatabaseProvider::recreateDBConnections();
452
453
        // Configure the storage
454
        $storage->configure();
455
        MainDatabaseProvider::recreateDBConnections();
456
        $success = self::isStorageDiskMounted();
457
        if ($success === true && $automatic) {
458
            SystemMessages::echoToTeletype(PHP_EOL . '   |- The data storage disk has been successfully mounted ... ');
459
            sleep(2);
460
            System::reboot();
461
            return true;
462
        }
463
464
        if ($automatic) {
465
            SystemMessages::echoToTeletype(PHP_EOL . '   |- Storage disk was not mounted automatically ... ');
466
        }
467
468
        fclose(STDERR);
469
        echo('   |- Update database ... ' . PHP_EOL);
470
471
        // Update the database
472
        $dbUpdater = new UpdateDatabase();
473
        $dbUpdater->updateDatabaseStructure();
474
475
        $STDERR = fopen('php://stderr', 'wb');
476
        CdrDb::checkDb();
477
478
        // Restart syslog
479
        $sysLog = new SyslogConf();
480
        $sysLog->reStart();
481
482
        // Configure PBX
483
        $pbx = new PBX();
484
        $pbx->configure();
485
486
        // Restart processes related to storage
487
        Processes::processPHPWorker(WorkerApiCommands::class);
488
489
        // Check if the disk was mounted successfully
490
        if ($success === true) {
491
            SystemMessages::echoWithSyslog("\n   |- " . Util::translate('Storage disk was mounted successfully...') . " \n\n");
492
        } else {
493
            SystemMessages::echoWithSyslog("\n   |- " . Util::translate('Failed to mount the disc...') . " \n\n");
494
        }
495
496
        sleep(3);
497
        if ($STDERR !== false) {
498
            fclose($STDERR);
499
        }
500
501
        return $success;
502
    }
503
504
    /**
505
     * Retrieves the partition name of a device.
506
     *
507
     * @param string $dev The device name
508
     * @param string $part The partition number
509
     * @param bool $verbose print verbose messages
510
     * @return string The partition name
511
     */
512
    public static function getDevPartName(string $dev, string $part, bool $verbose = false): string
513
    {
514
        $lsBlkPath = Util::which('lsblk');
515
        $cutPath   = Util::which('cut');
516
        $grepPath  = Util::which('grep');
517
        $sortPath  = Util::which('sort');
518
519
        $basenameDisk = basename($dev);
520
        $pathToDisk = trim(shell_exec("$lsBlkPath -n -p -a -r -o NAME,TYPE | $grepPath disk | $grepPath '$basenameDisk' | $cutPath -d ' ' -f 1")??'');
521
        if ($verbose) {
522
            echo "Get dev full path..." . PHP_EOL;
523
            echo "Source dev: $dev, result full path: $pathToDisk" . PHP_EOL;
524
        }
525
            // Touch the disk to update disk tables
526
        $partProbePath = Util::which('partprobe');
527
        shell_exec($partProbePath . " '$pathToDisk'");
528
529
        // Touch the disk to update disk tables
530
        $command = "$lsBlkPath -r -p | $grepPath ' part' | $sortPath -u | $cutPath -d ' ' -f 1 | $grepPath '" . $pathToDisk . "' | $grepPath \"$part\$\"";
531
        $devName = trim(shell_exec($command??'')??'');
532
        if (empty($devName) && $verbose) {
533
            $verboseMsg = trim(shell_exec("$lsBlkPath -r -p")??'');
534
            echo "---   filtered command   ---" . PHP_EOL;
535
            echo $command . PHP_EOL;
536
            echo "---   result 'lsblk -r -p'   ---" . PHP_EOL;
537
            echo $verboseMsg . PHP_EOL;
538
            echo "---   ---   ---" . PHP_EOL;
539
        }
540
        return $devName;
541
    }
542
543
    /**
544
     * Check if a storage disk is valid.
545
     *
546
     * @param string $device The device path of the storage disk.
547
     * @return bool Returns true if the storage disk is valid, false otherwise.
548
     */
549
    public static function isStorageDisk(string $device): bool
550
    {
551
        // Check if the device path exists
552
        if (!file_exists($device)) {
553
            echo("Disk $device not found") . PHP_EOL;
554
            return false;
555
        }
556
        $result = false;
557
        $tmp_dir = '/tmp/mnt_' . time();
558
        Util::mwMkdir($tmp_dir);
559
        $out = [];
560
561
        $uid_part = 'UUID=' . self::getUuid($device);
562
        $storage = new self();
563
        $format = $storage->getFsType($device);
564
        // If the file system type is not available, return false
565
        if (empty($format)) {
566
            echo("For Disk $device ($uid_part), FS_TYPE empty...") . PHP_EOL;
567
            return false;
568
        }
569
        echo("For Disk $device get $uid_part, FS_TYPE=$format...") . PHP_EOL;
570
        $mount  = Util::which('mount');
571
        $umount = Util::which('umount');
572
        $rm     = Util::which('rm');
573
574
        Processes::mwExec("$mount -t $format $uid_part $tmp_dir", $out);
575
        if (is_dir("$tmp_dir/mikopbx") && trim(implode('', $out)) === '') {
0 ignored issues
show
Bug introduced by
It seems like $out can also be of type null; however, parameter $pieces of implode() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

575
        if (is_dir("$tmp_dir/mikopbx") && trim(implode('', /** @scrutinizer ignore-type */ $out)) === '') {
Loading history...
576
            $result = true;
577
            echo("Disk $device is storage...") . PHP_EOL;
578
        }
579
580
        // Check if the storage disk is mounted, and unmount if necessary
581
        if (self::isStorageDiskMounted($device)) {
582
            Processes::mwExec("$umount $device");
583
        }
584
585
        // Check if the storage disk is unmounted, and remove the temporary directory
586
        if (!self::isStorageDiskMounted($device)) {
587
            Processes::mwExec("$rm -rf '$tmp_dir'");
588
        }
589
590
        return $result;
591
    }
592
593
    /**
594
     * Saves the disk settings to the database.
595
     *
596
     * @param array $data The disk settings data to be saved.
597
     * @param string $id The ID of the disk settings to be updated (default: '1').
598
     * @return void
599
     */
600
    public function saveDiskSettings(array $data, string $id = '1'): void
601
    {
602
        $disk_data = $this->getDiskSettings($id);
603
        if (count($disk_data) === 0) {
604
            $storage_settings = new StorageModel();
605
        } else {
606
            $storage_settings = StorageModel::findFirst("id = '$id'");
607
        }
608
        foreach ($data as $key => $value) {
609
            $storage_settings->writeAttribute($key, $value);
610
        }
611
        if (!$storage_settings->save()) {
612
            echo PHP_EOL . "Fail save new storage ID in database..." . PHP_EOL;
613
        }
614
    }
615
616
    /**
617
     * Retrieves the disk settings from the database.
618
     *
619
     * @param string $id The ID of the disk (optional).
620
     * @return array The disk settings.
621
     */
622
    public function getDiskSettings(string $id = ''): array
623
    {
624
        $data = [];
625
        if ('' === $id) {
626
            // Return all disk settings.
627
            $data = StorageModel::find()->toArray();
628
        } else {
629
            // Return disk settings for the specified ID.
630
            $pbxSettings = StorageModel::findFirst("id='$id'");
631
            if ($pbxSettings !== null) {
632
                $data = $pbxSettings->toArray();
633
            }
634
        }
635
636
        return $data;
637
    }
638
639
    /**
640
     * Configures the storage settings.
641
     */
642
    public function configure(): void
643
    {
644
        $varEtcDir = $this->config->path(Directories::CORE_VAR_ETC_DIR);
645
        $storage_dev_file = "$varEtcDir/storage_device";
646
        if (!Util::isT2SdeLinux()) {
647
            // Configure for non-T2Sde Linux
648
            file_put_contents($storage_dev_file, "/storage/usbdisk1");
649
            $this->updateConfigWithNewMountPoint("/storage/usbdisk1");
650
            $this->createWorkDirs();
651
            PHPConf::setupLog();
652
            return;
653
        }
654
655
        $cf_disk = '';
656
657
        // Remove the storage_dev_file if it exists
658
        if (file_exists($storage_dev_file)) {
659
            unlink($storage_dev_file);
660
        }
661
662
        // Check if cfdevice file exists and get its content
663
        if (file_exists($varEtcDir . '/cfdevice')) {
664
            $cf_disk = trim(file_get_contents($varEtcDir . '/cfdevice'));
665
        }
666
667
        $disks = $this->getDiskSettings();
668
        $conf = '';
669
670
        // Loop through each disk
671
        foreach ($disks as $disk) {
672
            clearstatcache();
673
            $dev = $this->getStorageDev($disk, $cf_disk);
674
            // Check if the disk exists
675
            if (!$this->hddExists($dev)) {
676
                SystemMessages::sysLogMsg(__METHOD__, "HDD - $dev doesn't exist");
677
                continue;
678
            }
679
680
            // Check if the disk is marked as media or storage_dev_file doesn't exist
681
            if ($disk['media'] === '1' || !file_exists($storage_dev_file)) {
682
                SystemMessages::sysLogMsg(__METHOD__, "Update the storage_dev_file and the mount point configuration");
683
                file_put_contents($storage_dev_file, "/storage/usbdisk{$disk['id']}");
684
                $this->updateConfigWithNewMountPoint("/storage/usbdisk{$disk['id']}");
685
            }
686
687
            $formatFs = $this->getFsType($dev);
688
689
            // Check if the file system type matches the expected type
690
            if ($formatFs !== $disk['filesystemtype'] && !($formatFs === 'ext4' && $disk['filesystemtype'] === 'ext2')) {
691
                SystemMessages::sysLogMsg(__METHOD__, "The file system type has changed {$disk['filesystemtype']} -> $formatFs. The disk will not be connected.");
692
                continue;
693
            }
694
            $str_uid = 'UUID=' . self::getUuid($dev);
695
            $conf .= "$str_uid /storage/usbdisk{$disk['id']} $formatFs async,rw 0 0\n";
696
            $mount_point = "/storage/usbdisk{$disk['id']}";
697
            Util::mwMkdir($mount_point);
698
            SystemMessages::sysLogMsg(__METHOD__, "Create mount point: $conf");
699
700
            $mountPath = Util::which('mount');
701
            $resultMountCode = Processes::mwExec("$mountPath -t $formatFs $str_uid $mount_point", $out);
702
            if($resultMountCode !== 0){
703
                echo("Fail mount $dev whith $str_uid, FS_TYPE - $formatFs...") . PHP_EOL;
704
                echo("Trying check device $dev ...") . PHP_EOL;
705
                passthru("/sbin/fsck.$formatFs -y '$dev'");
706
                echo("Trying mount device $dev ...") . PHP_EOL;
707
                $resultMountCode = Processes::mwExec("$mountPath -t $formatFs $str_uid $mount_point", $out);
708
                echo("Result mount code $resultMountCode ...") . PHP_EOL;
709
            }
710
711
        }
712
713
        // Save the configuration to the fstab file
714
        $this->saveFstab($conf);
715
716
        // Create necessary working directories
717
        $this->createWorkDirs();
718
719
        // Set up the PHP log configuration
720
        PHPConf::setupLog();
721
    }
722
723
    /**
724
     * Updates the configuration file with the new mount point.
725
     *
726
     * After mount storage we will change /mountpoint/ to new $mount_point value
727
     *
728
     * @param string $mount_point The new mount point.
729
     * @throws Error If the original configuration file has a broken format.
730
     */
731
    private function updateConfigWithNewMountPoint(string $mount_point): void
732
    {
733
        $settingsFile = '/etc/inc/mikopbx-settings.json';
734
        $staticSettingsFileOrig = '/etc/inc/mikopbx-settings-orig.json';
735
        if (!file_exists($staticSettingsFileOrig)) {
736
            copy($settingsFile, $staticSettingsFileOrig);
737
        }
738
739
        $jsonString = file_get_contents($staticSettingsFileOrig);
740
        try {
741
            $data = json_decode($jsonString, true, 512, JSON_THROW_ON_ERROR);
742
        } catch (JsonException $exception) {
743
            throw new Error("$staticSettingsFileOrig has broken format");
744
        }
745
        foreach ($data as $rootKey => $rootEntry) {
746
            foreach ($rootEntry as $nestedKey => $entry) {
747
                if (stripos($entry, '/mountpoint') !== false) {
748
                    $data[$rootKey][$nestedKey] = str_ireplace('/mountpoint', $mount_point, $entry);
749
                }
750
            }
751
        }
752
753
        $newJsonString = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
754
        file_put_contents($settingsFile, $newJsonString);
755
        $this->updateEnvironmentAfterChangeMountPoint();
756
    }
757
758
    /**
759
     * Updates the environment after changing the mount point.
760
     * - Recreates the config provider and updates the config variable.
761
     * - Reloads classes from system and storage disks.
762
     * - Reloads all providers.
763
     */
764
    private function updateEnvironmentAfterChangeMountPoint(): void
765
    {
766
        // Update config variable
767
        ConfigProvider::recreateConfigProvider();
768
        $this->config = $this->di->getShared(ConfigProvider::SERVICE_NAME);
769
770
        // Reload cached values
771
        Directories::reset();
772
773
        // Reload classes from system and storage disks
774
        ClassLoader::init();
775
776
        // Reload all providers
777
        RegisterDIServices::init();
778
    }
779
780
    /**
781
     * Creates the necessary working directories and symlinks.
782
     *
783
     * @return void
784
     */
785
    private function createWorkDirs(): void
786
    {
787
        $path = '';
788
        $busyBoxPath = Util::which('busybox');
789
        Processes::mwExec("$busyBoxPath mount -o remount,rw /offload 2> /dev/null");
790
791
        $isLiveCd = file_exists('/offload/livecd');
792
793
        // Create directories
794
        $arrConfig = $this->config->toArray();
795
        foreach ($arrConfig as $rootEntry) {
796
            foreach ($rootEntry as $key => $entry) {
797
                if (stripos($key, 'path') === false && stripos($key, 'dir') === false) {
798
                    continue;
799
                }
800
                if (file_exists($entry)) {
801
                    continue;
802
                }
803
                if ($isLiveCd && str_starts_with($entry, '/offload/')) {
804
                    continue;
805
                }
806
                $path .= " $entry";
807
            }
808
        }
809
810
        if (!empty($path)) {
811
            Util::mwMkdir($path);
812
        }
813
814
        $downloadCacheDir = appPath('sites/pbxcore/files/cache');
815
        if (!$isLiveCd) {
816
            Util::mwMkdir($downloadCacheDir);
817
            Util::createUpdateSymlink($this->config->path('www.downloadCacheDir'), $downloadCacheDir);
818
        }
819
820
        $this->createAssetsSymlinks();
821
        $this->createViewSymlinks();
822
        $this->createAGIBINSymlinks($isLiveCd);
823
824
        Util::createUpdateSymlink($this->config->path('www.uploadDir'), '/ultmp');
825
826
        $filePath = appPath('src/Core/Asterisk/Configs/lua/extensions.lua');
827
        Util::createUpdateSymlink($filePath, '/etc/asterisk/extensions.lua');
828
829
        $this->clearCacheFiles();
830
        $this->clearTmpFiles();
831
        $this->applyFolderRights();
832
        Processes::mwExec("$busyBoxPath mount -o remount,ro /offload 2> /dev/null");
833
    }
834
835
    /**
836
     * Clears the cache files for various directories.
837
     *
838
     * @return void
839
     */
840
    public function clearCacheFiles(): void
841
    {
842
        $cacheDirs = [];
843
        $cacheDirs[] = $this->config->path(Directories::WWW_UPLOAD_DIR);
844
        $cacheDirs[] = $this->config->path(Directories::WWW_DOWNLOAD_CACHE_DIR);
845
        $cacheDirs[] = $this->config->path(Directories::APP_ASSETS_CACHE_DIR) . '/js';
846
        $cacheDirs[] = $this->config->path(Directories::APP_ASSETS_CACHE_DIR) . '/css';
847
        $cacheDirs[] = $this->config->path(Directories::APP_ASSETS_CACHE_DIR) . '/img';
848
        $cacheDirs[] = $this->config->path(Directories::APP_VIEW_CACHE_DIR);
849
        $cacheDirs[] = $this->config->path(Directories::APP_VOLT_CACHE_DIR);
850
        $rmPath = Util::which('rm');
851
852
        // Clear cache files for each directory
853
        foreach ($cacheDirs as $cacheDir) {
854
            if (!empty($cacheDir)) {
855
                Processes::mwExec("$rmPath -rf $cacheDir/*");
856
            }
857
        }
858
859
        // Delete boot cache folders if storage disk is mounted
860
        if (is_dir('/mountpoint') && self::isStorageDiskMounted()) {
861
            Processes::mwExec("$rmPath -rf /mountpoint");
862
        }
863
    }
864
865
    /**
866
     * Clear files in temp directories
867
     * @return void
868
     */
869
    private function clearTmpFiles(): void
870
    {
871
        $timeout = Util::which('timeout');
872
        $find = Util::which('find');
873
        $mv = Util::which('mv');
874
        $rm = Util::which('rm');
875
        $nice = Util::which('nice');
876
        $tmpDir = $this->config->path(Directories::CORE_TEMP_DIR);
877
        if (!file_exists($tmpDir)) {
878
            return;
879
        }
880
        // Trying to get a list of files
881
        Processes::mwExec("$timeout 10 $find $tmpDir -type f", $out, $ret);
882
        if ($ret !== 0) {
883
            // there are too many files in the temporary directory, we will clear them
884
            // it may cause a failure when setting access rights (chown)
885
            $resDirForRm = "$tmpDir-" . time();
886
            shell_exec("$mv '$tmpDir' '$resDirForRm'");
887
            if (file_exists("$resDirForRm/swapfile")) {
888
                // Saving only the swap file
889
                shell_exec("$mv '$resDirForRm/swapfile' '$tmpDir/swapfile'");
890
            }
891
            // Let's start deleting temporary files
892
            Processes::mwExecBg("$nice -n 19 $rm -rf $resDirForRm");
893
        }
894
        Util::mwMkdir($tmpDir, true);
895
    }
896
897
    /**
898
     * Retrieves the storage device for the given disk.
899
     *
900
     * @param array $disk The disk information.
901
     * @param string $cf_disk The cf_disk information.
902
     * @return string The storage device path.
903
     */
904
    private function getStorageDev(array $disk, string $cf_disk): string
905
    {
906
        if (!empty($disk['uniqid']) && !str_contains($disk['uniqid'], 'STORAGE-DISK')) {
907
            // Find the partition name by UID.
908
            $lsblk = Util::which('lsblk');
909
            $grep = Util::which('grep');
910
            $cut = Util::which('cut');
911
            $cmd = "$lsblk -r -o NAME,UUID | $grep {$disk['uniqid']} | $cut -d ' ' -f 1";
912
            $dev = '/dev/' . trim(shell_exec($cmd) ?? '');
913
            if ($this->hddExists($dev)) {
914
                // Disk exists.
915
                return $dev;
916
            }
917
        }
918
        // Determine the disk by its name.
919
        if ($disk['device'] !== "/dev/$cf_disk") {
920
            // If it's a regular disk, use partition 1.
921
            $part = "1";
922
        } else {
923
            // If it's a system disk, attempt to connect partition 4.
924
            $part = "4";
925
        }
926
        return  self::getDevPartName($disk['device'], $part);
927
    }
928
929
    /**
930
     * Checks if a hard drive exists based on the provided disk identifier.
931
     *
932
     * @param string $disk The disk identifier, such as a device path.
933
     * @return bool Returns true if the disk exists and has a non-empty UUID, false otherwise.
934
     */
935
    private function hddExists(string $disk): bool
936
    {
937
        // Check if the given disk identifier points to a directory.
938
        if (is_dir($disk)) {
939
            SystemMessages::sysLogMsg(__METHOD__, $disk . ' is a dir, not disk', LOG_DEBUG);
940
            return false;
941
        }
942
943
        // Check if the file corresponding to the disk exists.
944
        if (!file_exists($disk)) {
945
            SystemMessages::sysLogMsg(__METHOD__, "Check if the file with name $disk exists failed", LOG_DEBUG);
946
            return false;
947
        }
948
949
        // Record the start time for timeout purposes.
950
        $startTime = time();
951
952
        // Loop for up to 10 seconds or until a non-empty UUID is found.
953
        while (true) {
954
            // Retrieve the UUID for the disk.
955
            $uid = self::getUuid($disk);
956
            SystemMessages::sysLogMsg(__METHOD__, "Disk with name $disk has GUID: $uid", LOG_DEBUG);
957
958
            // If the UUID is not empty, the disk exists.
959
            if (!empty($uid)) {
960
                return true;
961
            }
962
963
            // Exit the loop if 10 seconds have passed.
964
            if ((time() - $startTime) >= 10) {
965
                break;
966
            }
967
968
            // Wait for 1 second before the next iteration to avoid high CPU usage.
969
            sleep(1);
970
        }
971
972
        // If the UUID remains empty after 10 seconds, the disk does not exist.
973
        return false;
974
    }
975
976
    /**
977
     * Saves the fstab configuration.
978
     *
979
     * @param string $conf Additional configuration to append to fstab
980
     * @return void
981
     */
982
    public function saveFstab(string $conf = ''): void
983
    {
984
        $varEtcDir = $this->config->path(Directories::CORE_VAR_ETC_DIR);
985
986
        // Create the mount point directory for additional disks
987
        Util::mwMkdir('/storage');
988
        $chmodPath = Util::which('chmod');
989
        Processes::mwExec("$chmodPath 755 /storage");
990
991
        // Check if cf device file exists
992
        if (!file_exists($varEtcDir . '/cfdevice')) {
993
            return;
994
        }
995
        $fstab = '';
996
997
        // Read cf device file
998
        $file_data = file_get_contents($varEtcDir . '/cfdevice');
999
        $cf_disk = trim($file_data);
1000
        if ('' === $cf_disk) {
1001
            return;
1002
        }
1003
        $part2 = self::getDevPartName($cf_disk, '2');
1004
        $part3 = self::getDevPartName($cf_disk, '3');
1005
1006
        $uid_part2 = 'UUID=' . self::getUuid($part2);
1007
        $format_p2 = $this->getFsType($part2);
1008
        $uid_part3 = 'UUID=' . self::getUuid($part3);
1009
        $format_p3 = $this->getFsType($part3);
1010
1011
        $fstab .= "$uid_part2 /offload $format_p2 ro 0 0\n";
1012
        $fstab .= "$uid_part3 /cf $format_p3 rw 1 1\n";
1013
        $fstab .= $conf;
1014
1015
        // Write fstab file
1016
        file_put_contents("/etc/fstab", $fstab);
1017
1018
        // Duplicate for vm tools d
1019
        file_put_contents("/etc/mtab", $fstab);
1020
1021
        // Mount the file systems
1022
        $mountPath     = Util::which('mount');
1023
        $resultOfMount = Processes::mwExec("$mountPath -a", $out);
1024
        if ($resultOfMount !== 0) {
1025
            SystemMessages::echoToTeletype(" - Error mount " . implode(' ', $out));
0 ignored issues
show
Bug introduced by
It seems like $out can also be of type null; however, parameter $pieces of implode() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1025
            SystemMessages::echoToTeletype(" - Error mount " . implode(' ', /** @scrutinizer ignore-type */ $out));
Loading history...
1026
        }
1027
        // Add regular www rights to /cf directory
1028
        Util::addRegularWWWRights('/cf');
1029
    }
1030
1031
    /**
1032
     * Returns candidates to storage
1033
     * @return array
1034
     */
1035
    public function getStorageCandidate(): array
1036
    {
1037
        $disks = $this->getLsBlkDiskInfo();
1038
        $storages = [];
1039
        foreach ($disks as $disk) {
1040
            if ($disk['type'] !== 'disk') {
1041
                continue;
1042
            }
1043
            $children = $disk['children'] ?? [];
1044
            if (count($children) === 0) {
1045
                continue;
1046
            }
1047
            if (count($children) === 1) {
1048
                $part = '1';
1049
            } else {
1050
                $part = '4';
1051
            }
1052
1053
            $dev = '';
1054
            $fs = '';
1055
            foreach ($children as $child) {
1056
                if ($child['fstype'] !== 'ext4' && $child['fstype'] !== 'ext2') {
1057
                    continue;
1058
                }
1059
                if ($disk['name'] . $part === $child['name']) {
1060
                    $dev = '/dev/' . $child['name'];
1061
                    $fs = $child['fstype'];
1062
                    break;
1063
                }
1064
            }
1065
            if (!empty($dev) && !empty($fs)) {
1066
                $storages[$dev] = $fs;
1067
            }
1068
        }
1069
1070
        return $storages;
1071
    }
1072
1073
    /**
1074
     * Get disk information using lsblk command.
1075
     *
1076
     * @return array An array containing disk information.
1077
     */
1078
    private function getLsBlkDiskInfo(): array
1079
    {
1080
        $lsBlkPath = Util::which('lsblk');
1081
1082
        // Execute lsblk command to get disk information in JSON format
1083
        Processes::mwExec(
1084
            "$lsBlkPath -J -b -o VENDOR,MODEL,SERIAL,LABEL,TYPE,FSTYPE,MOUNTPOINT,SUBSYSTEMS,NAME,UUID",
1085
            $out
1086
        );
1087
        try {
1088
            $data = json_decode(implode(PHP_EOL, $out), true, 512, JSON_THROW_ON_ERROR);
0 ignored issues
show
Bug introduced by
It seems like $out can also be of type null; however, parameter $pieces of implode() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1088
            $data = json_decode(implode(PHP_EOL, /** @scrutinizer ignore-type */ $out), true, 512, JSON_THROW_ON_ERROR);
Loading history...
1089
            $data = $data['blockdevices'] ?? [];
1090
        } catch (JsonException $e) {
1091
            $data = [];
1092
        }
1093
        return $data;
1094
    }
1095
1096
    /**
1097
     * Create system folders and links after upgrade and connect config DB
1098
     *
1099
     * @return void
1100
     */
1101
    public function createWorkDirsAfterDBUpgrade(): void
1102
    {
1103
        // Remount /offload directory as read-write
1104
        $busyBoxPath = Util::which('busybox');
1105
        Processes::mwExec("$busyBoxPath mount -o remount,rw /offload 2> /dev/null");
1106
1107
        // Create symlinks for module caches
1108
        $this->createModulesCacheSymlinks();
1109
1110
        // Apply folder rights
1111
        $this->applyFolderRights();
1112
1113
        // Remount /offload directory as read-only
1114
        Processes::mwExec("$busyBoxPath mount -o remount,ro /offload 2> /dev/null");
1115
    }
1116
1117
    /**
1118
     * Creates symlinks for module caches.
1119
     *
1120
     * @return void
1121
     */
1122
    public function createModulesCacheSymlinks(): void
1123
    {
1124
        $modules = PbxExtensionModules::getModulesArray();
1125
        foreach ($modules as $module) {
1126
            // Create cache links for JS, CSS, IMG folders
1127
            PbxExtensionUtils::createAssetsSymlinks($module['uniqid']);
1128
1129
            // Create links for the module view templates
1130
            PbxExtensionUtils::createViewSymlinks($module['uniqid']);
1131
1132
            // Create AGI bin symlinks for the module
1133
            PbxExtensionUtils::createAgiBinSymlinks($module['uniqid']);
1134
        }
1135
    }
1136
1137
    /**
1138
     * Creates symlinks for asset cache directories.
1139
     *
1140
     * @return void
1141
     */
1142
    public function createAssetsSymlinks(): void
1143
    {
1144
        // Create symlink for JS cache directory
1145
        $jsCacheDir = appPath('sites/admin-cabinet/assets/js/cache');
1146
        Util::createUpdateSymlink($this->config->path(Directories::APP_ASSETS_CACHE_DIR) . '/js', $jsCacheDir);
1147
1148
        // Create symlink for CSS cache directory
1149
        $cssCacheDir = appPath('sites/admin-cabinet/assets/css/cache');
1150
        Util::createUpdateSymlink($this->config->path(Directories::APP_ASSETS_CACHE_DIR) . '/css', $cssCacheDir);
1151
1152
        // Create symlink for image cache directory
1153
        $imgCacheDir = appPath('sites/admin-cabinet/assets/img/cache');
1154
        Util::createUpdateSymlink($this->config->path(Directories::APP_ASSETS_CACHE_DIR) . '/img', $imgCacheDir);
1155
    }
1156
1157
    /**
1158
     * Creates symlinks for modules view.
1159
     *
1160
     * @return void
1161
     */
1162
    public function createViewSymlinks(): void
1163
    {
1164
        $viewCacheDir = appPath('src/AdminCabinet/Views/Modules');
1165
        Util::createUpdateSymlink($this->config->path(Directories::APP_VIEW_CACHE_DIR), $viewCacheDir);
1166
    }
1167
1168
    /**
1169
     * Creates AGI bin symlinks for extension modules.
1170
     *
1171
     * @param bool $isLiveCd Whether the system loaded on LiveCD mode.
1172
     * @return void
1173
     */
1174
    public function createAGIBINSymlinks(bool $isLiveCd): void
1175
    {
1176
        $agiBinDir = $this->config->path(Directories::AST_AGI_BIN_DIR);
1177
        if ($isLiveCd && !str_starts_with($agiBinDir, '/offload/')) {
1178
            Util::mwMkdir($agiBinDir);
1179
        }
1180
1181
        $roAgiBinFolder = appPath('src/Core/Asterisk/agi-bin');
1182
        $files = glob("$roAgiBinFolder/*.{php}", GLOB_BRACE);
1183
        foreach ($files as $file) {
1184
            $fileInfo = pathinfo($file);
1185
            $newFilename = "$agiBinDir/{$fileInfo['filename']}.{$fileInfo['extension']}";
1186
            Util::createUpdateSymlink($file, $newFilename);
1187
        }
1188
    }
1189
1190
    /**
1191
     * Applies folder rights to the appropriate directories.
1192
     *
1193
     * @return void
1194
     */
1195
    private function applyFolderRights(): void
1196
    {
1197
1198
        $www_dirs = []; // Directories with WWW rights
1199
        $exec_dirs = []; // Directories with executable rights
1200
1201
        $arrConfig = $this->config->toArray();
1202
1203
        // Get the directories for WWW rights from the configuration
1204
        foreach ($arrConfig as $key => $entry) {
1205
            if (in_array($key, ['www', 'adminApplication'])) {
1206
                foreach ($entry as $subKey => $subEntry) {
1207
                    if (stripos($subKey, 'path') === false && stripos($subKey, 'dir') === false) {
1208
                        continue;
1209
                    }
1210
                    $www_dirs[] = $subEntry;
1211
                }
1212
            }
1213
        }
1214
1215
        // Add additional directories with WWW rights
1216
        $www_dirs[] = $this->config->path(Directories::CORE_TEMP_DIR);
1217
        $www_dirs[] = $this->config->path(Directories::CORE_LOGS_DIR);
1218
1219
        // Create empty log files with WWW rights
1220
        $logFiles = [
1221
            $this->config->path('database.debugLogFile'),
1222
            $this->config->path('cdrDatabase.debugLogFile'),
1223
        ];
1224
1225
        foreach ($logFiles as $logFile) {
1226
            $filename = (string)$logFile;
1227
            if (!file_exists($filename)) {
1228
                file_put_contents($filename, '');
1229
            }
1230
            $www_dirs[] = $filename;
1231
        }
1232
1233
        $www_dirs[] = '/etc/version';
1234
        $www_dirs[] = appPath('/');
1235
1236
        // Add read rights to the directories
1237
        Util::addRegularWWWRights(implode(' ', $www_dirs));
1238
1239
        // Add executable rights to the directories
1240
        $exec_dirs[] = appPath('src/Core/Asterisk/agi-bin');
1241
        $exec_dirs[] = appPath('src/Core/Rc');
1242
        Util::addExecutableRights(implode(' ', $exec_dirs));
1243
        $busyBoxPath = Util::which('busybox');
1244
        Processes::mwExec("$busyBoxPath mount -o remount,ro /offload 2> /dev/null");
1245
    }
1246
1247
    /**
1248
     * Mounts the swap file.
1249
     */
1250
    public function mountSwap(): void
1251
    {
1252
        $tempDir = $this->config->path(Directories::CORE_TEMP_DIR);
1253
        $swapFile = "$tempDir/swapfile";
1254
1255
        $swapOffCmd = Util::which('swapoff');
1256
        Processes::mwExec("$swapOffCmd $swapFile");
1257
1258
        $this->makeSwapFile($swapFile);
1259
        if (!file_exists($swapFile)) {
1260
            return;
1261
        }
1262
        $swapOnCmd = Util::which('swapon');
1263
        $result = Processes::mwExec("$swapOnCmd $swapFile");
1264
        SystemMessages::sysLogMsg('Swap', 'connect swap result: ' . $result, LOG_INFO);
1265
    }
1266
1267
    /**
1268
     * Creates a swap file.
1269
     *
1270
     * @param string $swapFile The path to the swap file.
1271
     */
1272
    private function makeSwapFile(string $swapFile): void
1273
    {
1274
        $swapLabel = Util::which('swaplabel');
1275
1276
        // Check if swap file already exists
1277
        if (Processes::mwExec("$swapLabel $swapFile") === 0) {
1278
            return;
1279
        }
1280
        if (file_exists($swapFile)) {
1281
            unlink($swapFile);
1282
        }
1283
1284
        $size = $this->getStorageFreeSpaceMb();
1285
        if ($size > 2000) {
1286
            $swapSize = 1024;
1287
        } elseif ($size > 1000) {
1288
            $swapSize = 512;
1289
        } else {
1290
            // Not enough free space.
1291
            return;
1292
        }
1293
        $bs = 1024;
1294
        $countBlock = $swapSize * (1024 * 1024) / $bs;
1295
        $ddCmd = Util::which('dd');
1296
1297
        SystemMessages::sysLogMsg('Swap', 'make swap ' . $swapFile, LOG_INFO);
1298
1299
        // Create swap file using dd command
1300
        Processes::mwExec("$ddCmd if=/dev/zero of=$swapFile bs=$bs count=$countBlock");
1301
1302
        $mkSwapCmd = Util::which('mkswap');
1303
1304
        // Set up swap space on the file
1305
        Processes::mwExec("$mkSwapCmd $swapFile");
1306
    }
1307
1308
    /**
1309
     * Retrieves the amount of free storage space in megabytes.
1310
     *
1311
     * @return int The amount of free storage space in megabytes.
1312
     */
1313
    public function getStorageFreeSpaceMb(): int
1314
    {
1315
        $size = 0;
1316
        $mntDir = '';
1317
        $mounted = self::isStorageDiskMounted('', $mntDir);
1318
        if (!$mounted) {
1319
            return 0;
1320
        }
1321
        $hd = $this->getAllHdd(true);
1322
        foreach ($hd as $disk) {
1323
            if ($disk['mounted'] === $mntDir) {
1324
                $size = $disk['free_space'];
1325
                break;
1326
            }
1327
        }
1328
        return $size;
1329
    }
1330
1331
    /**
1332
     * Get information about all HDD devices.
1333
     *
1334
     * @param bool $mounted_only Whether to include only mounted devices.
1335
     * @return array An array of HDD device information.
1336
     */
1337
    public function getAllHdd(bool $mounted_only = false): array
1338
    {
1339
        $res_disks = [];
1340
1341
        if (Util::isDocker()) {
1342
            // Get disk information for /storage directory
1343
            $out = [];
1344
            $grepPath = Util::which('grep');
1345
            $dfPath = Util::which('df');
1346
            $awkPath = Util::which('awk');
1347
1348
            // Execute the command to get disk information for /storage directory
1349
            Processes::mwExec(
1350
                "$dfPath -k /storage | $awkPath  '{ print \$1 \"|\" $3 \"|\" \$4} ' | $grepPath -v 'Available'",
1351
                $out
1352
            );
1353
            $disk_data = explode('|', implode(" ", $out));
0 ignored issues
show
Bug introduced by
It seems like $out can also be of type null; however, parameter $pieces of implode() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1353
            $disk_data = explode('|', implode(" ", /** @scrutinizer ignore-type */ $out));
Loading history...
1354
            if (count($disk_data) === 3) {
1355
                $m_size = round((intval($disk_data[1]) + intval($disk_data[2])) / 1024, 1);
1356
1357
                // Add Docker disk information to the result
1358
                $res_disks[] = [
1359
                    'id' => $disk_data[0],
1360
                    'size' => "" . $m_size,
1361
                    'size_text' => "" . $m_size . " Mb",
1362
                    'vendor' => 'Debian',
1363
                    'mounted' => '/storage/usbdisk',
1364
                    'free_space' => round($disk_data[2] / 1024, 1),
1365
                    'partitions' => [],
1366
                    'sys_disk' => true,
1367
                ];
1368
            }
1369
1370
            return $res_disks;
1371
        }
1372
1373
        // Get CD-ROM and HDD devices
1374
        $cd_disks = $this->cdromGetDevices();
1375
        $disks    = $this->diskGetDevices();
1376
1377
        $cf_disk = '';
1378
        $varEtcDir = $this->config->path(Directories::CORE_VAR_ETC_DIR);
1379
1380
        if (file_exists($varEtcDir . '/cfdevice')) {
1381
            $cf_disk = trim(file_get_contents($varEtcDir . '/cfdevice'));
1382
        }
1383
1384
        foreach ($disks as $disk => $diskInfo) {
1385
            $type = $diskInfo['fstype'] ?? '';
1386
1387
            // Skip Linux RAID member disks
1388
            if ($type === 'linux_raid_member') {
1389
                continue;
1390
            }
1391
1392
            // Skip CD-ROM disks
1393
            if (in_array($disk, $cd_disks, true)) {
1394
                continue;
1395
            }
1396
            unset($temp_vendor, $temp_size, $original_size);
1397
            $mounted = self::diskIsMounted($disk);
1398
            if ($mounted_only === true && $mounted === false) {
1399
                continue;
1400
            }
1401
            $sys_disk = ($cf_disk === $disk);
1402
1403
            $mb_size = 0;
1404
            if (is_file("/sys/block/" . $disk . "/size")) {
1405
                $original_size = trim(file_get_contents("/sys/block/" . $disk . "/size"));
1406
                $original_size = ($original_size * 512 / 1024 / 1024);
1407
                $mb_size = round($original_size, 1);
1408
            }
1409
            if ($mb_size > 100) {
1410
                $temp_size = sprintf("%.0f MB", $mb_size);
1411
                $temp_vendor = $this->getVendorDisk($diskInfo);
1412
                $free_space = self::getFreeSpace($disk);
1413
1414
                $arr_disk_info = $this->determineFormatFs($diskInfo);
1415
1416
                if (count($arr_disk_info) > 0) {
1417
                    $used = 0;
1418
                    foreach ($arr_disk_info as $disk_info) {
1419
                        $used += $disk_info['used_space'];
1420
                    }
1421
                    if ($used > 0) {
1422
                        $free_space = $mb_size - $used;
1423
                    }
1424
                }
1425
1426
                // Add HDD device information to the result
1427
                $res_disks[] = [
1428
                    'id' => $disk,
1429
                    'size' => $mb_size,
1430
                    'size_text' => $temp_size,
1431
                    'vendor' => $temp_vendor,
1432
                    'mounted' => $mounted,
1433
                    'free_space' => round($free_space, 1),
1434
                    'partitions' => $arr_disk_info,
1435
                    'sys_disk' => $sys_disk,
1436
                ];
1437
            }
1438
        }
1439
        return $res_disks;
1440
    }
1441
1442
    /**
1443
     * Get CD-ROM devices.
1444
     *
1445
     * @return array An array of CD-ROM device names.
1446
     */
1447
    private function cdromGetDevices(): array
1448
    {
1449
        $disks = [];
1450
        $blockDevices = $this->getLsBlkDiskInfo();
1451
        foreach ($blockDevices as $diskData) {
1452
            $type = $diskData['type'] ?? '';
1453
            $name = $diskData['name'] ?? '';
1454
1455
            // Skip devices that are not CD-ROM
1456
            if ($type !== 'rom' || $name === '') {
1457
                continue;
1458
            }
1459
            $disks[] = $name;
1460
        }
1461
        return $disks;
1462
    }
1463
1464
    /**
1465
     * Get disk devices.
1466
     *
1467
     * @param bool $diskOnly Whether to include only disk devices.
1468
     * @return array An array of disk device information.
1469
     */
1470
    public function diskGetDevices(bool $diskOnly = false): array
1471
    {
1472
        $disks = [];
1473
        $blockDevices = $this->getLsBlkDiskInfo();
1474
1475
        foreach ($blockDevices as $diskData) {
1476
            $type = $diskData['type'] ?? '';
1477
            $name = $diskData['name'] ?? '';
1478
            if ($type !== 'disk' || $name === '') {
1479
                continue;
1480
            }
1481
            $disks[$name] = $diskData;
1482
            if ($diskOnly === true) {
1483
                continue;
1484
            }
1485
            $children = $diskData['children'] ?? [];
1486
1487
            foreach ($children as $child) {
1488
                $childName = $child['name'] ?? '';
1489
                if ($childName === '') {
1490
                    continue;
1491
                }
1492
                $disks[$childName] = $child;
1493
            }
1494
        }
1495
        return $disks;
1496
    }
1497
1498
    /**
1499
     * Check if a disk is mounted.
1500
     *
1501
     * @param string $disk The name of the disk.
1502
     * @param string $filter The filter to match the disk name.
1503
     * @return string|bool The mount point if the disk is mounted, or false if not mounted.
1504
     */
1505
    public static function diskIsMounted(string $disk, string $filter = '/dev/'): bool|string
1506
    {
1507
        $out = [];
1508
        $grep = Util::which('grep');
1509
        $mount = Util::which('mount');
1510
        $head = Util::which('head');
1511
1512
        // Execute mount command and grep the output for the disk name
1513
        Processes::mwExec("$mount | $grep '{$filter}{$disk}' | $head -n 1", $out);
1514
        if (count($out) > 0) {
0 ignored issues
show
Bug introduced by
It seems like $out can also be of type null; however, parameter $value of count() does only seem to accept Countable|array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1514
        if (count(/** @scrutinizer ignore-type */ $out) > 0) {
Loading history...
1515
            $res_out = end($out);
0 ignored issues
show
Bug introduced by
It seems like $out can also be of type null; however, parameter $array of end() does only seem to accept array|object, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1515
            $res_out = end(/** @scrutinizer ignore-type */ $out);
Loading history...
1516
        } else {
1517
            $res_out = implode('', $out);
0 ignored issues
show
Bug introduced by
It seems like $out can also be of type null; however, parameter $pieces of implode() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1517
            $res_out = implode('', /** @scrutinizer ignore-type */ $out);
Loading history...
1518
        }
1519
        $data = explode(' ', trim($res_out));
1520
1521
        return (count($data) > 2) ? $data[2] : false;
1522
    }
1523
1524
    /**
1525
     * Get the vendor name for a disk.
1526
     *
1527
     * @param array $diskInfo The disk information.
1528
     * @return string The vendor name.
1529
     */
1530
    private function getVendorDisk(array $diskInfo): string
1531
    {
1532
        $temp_vendor = [];
1533
        $keys = ['vendor', 'model', 'type'];
1534
1535
        // Iterate through the keys to retrieve vendor-related data
1536
        foreach ($keys as $key) {
1537
            $data = $diskInfo[$key] ?? '';
1538
            if ($data !== '') {
1539
                $temp_vendor[] = trim(str_replace(',', '', $data));
1540
            }
1541
        }
1542
1543
        // If no vendor-related data is found, use the disk name
1544
        if (empty($temp_vendor)) {
1545
            $temp_vendor[] = $diskInfo['name'] ?? 'ERROR: NoName';
1546
        }
1547
        return implode(', ', $temp_vendor);
1548
    }
1549
1550
    /**
1551
     * Get the free space in megabytes for a given HDD.
1552
     *
1553
     * @param string $hdd The name of the HDD.
1554
     * @return float|int The free space in megabytes.
1555
     */
1556
    public static function getFreeSpace(string $hdd): float|int
1557
    {
1558
        $out = [];
1559
        $hdd = escapeshellarg($hdd);
1560
        $grep = Util::which('grep');
1561
        $awk = Util::which('awk');
1562
        $df = Util::which('df');
1563
        $head = Util::which('head');
1564
1565
        // Execute df command to get the free space for the HDD
1566
        Processes::mwExec("$df -m | $grep $hdd | $grep -v custom_modules | $head -n 1 | $awk '{print $4}'", $out);
1567
        $result = 0;
1568
1569
        // Sum up the free space values
1570
        foreach ($out as $res) {
1571
            if (!is_numeric($res)) {
1572
                continue;
1573
            }
1574
            $result += (1 * $res);
1575
        }
1576
1577
        return $result;
1578
    }
1579
1580
    /**
1581
     * Determine the format and file system information for a device.
1582
     *
1583
     * @param array $deviceInfo The device information.
1584
     * @return array An array containing format and file system information for each device partition.
1585
     */
1586
    public function determineFormatFs(array $deviceInfo): array
1587
    {
1588
        $allow_formats = ['ext2', 'ext4', 'fat', 'ntfs', 'msdos'];
1589
        $device = basename($deviceInfo['name'] ?? '');
1590
1591
        $devices = $this->getDiskParted('/dev/' . $deviceInfo['name'] ?? '');
1592
        $result_data = [];
1593
1594
        // Iterate through each device partition
1595
        foreach ($devices as $dev) {
1596
            if (empty($dev) || (count($devices) > 1 && $device === $dev) || is_dir("/sys/block/$dev")) {
1597
                continue;
1598
            }
1599
            $mb_size = 0;
1600
            $path_size_info = '';
1601
            $tmp_path = "/sys/block/$device/$dev/size";
1602
            if (file_exists($tmp_path)) {
1603
                $path_size_info = $tmp_path;
1604
            }
1605
1606
            // If the size path is not found, try an alternate path
1607
            if (empty($path_size_info)) {
1608
                $tmp_path = "/sys/block/" . substr($dev, 0, 3) . "/$dev/size";
1609
                if (file_exists($tmp_path)) {
1610
                    $path_size_info = $tmp_path;
1611
                }
1612
            }
1613
1614
            // Calculate the size in megabytes
1615
            if (!empty($path_size_info)) {
1616
                $original_size = trim(file_get_contents($path_size_info));
1617
                $original_size = ($original_size * 512 / 1024 / 1024);
1618
                $mb_size = $original_size;
1619
            }
1620
1621
            $tmp_dir = "/tmp/{$dev}_" . time();
1622
            $out = [];
1623
1624
            $fs = null;
1625
            $need_unmount = false;
1626
            $mount_dir = '';
1627
1628
            // Check if the device is currently mounted
1629
            if (self::isStorageDiskMounted("/dev/$dev ", $mount_dir)) {
1630
                $grepPath = Util::which('grep');
1631
                $awkPath = Util::which('awk');
1632
                $mountPath = Util::which('mount');
1633
1634
                // Get the file system type and free space of the mounted device
1635
                Processes::mwExec("$mountPath | $grepPath '/dev/$dev' | $awkPath '{print $5}'", $out);
1636
                $fs = trim(implode("", $out));
0 ignored issues
show
Bug introduced by
It seems like $out can also be of type null; however, parameter $pieces of implode() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1636
                $fs = trim(implode("", /** @scrutinizer ignore-type */ $out));
Loading history...
1637
                $fs = ($fs === 'fuseblk') ? 'ntfs' : $fs;
1638
                $free_space = self::getFreeSpace("/dev/$dev ");
1639
                $used_space = $mb_size - $free_space;
1640
            } else {
1641
                $format = $this->getFsType($device);
1642
1643
                // Check if the detected format is allowed
1644
                if (in_array($format, $allow_formats)) {
1645
                    $fs = $format;
1646
                }
1647
1648
                // Mount the device and determine the used space
1649
                self::mountDisk($dev, $format, $tmp_dir);
1650
1651
                $need_unmount = true;
1652
                $used_space = Util::getSizeOfFile($tmp_dir);
1653
            }
1654
1655
            // Store the partition information in the result array
1656
            $result_data[] = [
1657
                "dev" => $dev,
1658
                'size' => round($mb_size, 2),
1659
                "used_space" => round($used_space, 2),
1660
                "free_space" => round($mb_size - $used_space, 2),
1661
                "uuid" => self::getUuid("/dev/$dev "),
1662
                "fs" => $fs,
1663
            ];
1664
1665
            // Unmount the temporary mount point if needed
1666
            if ($need_unmount) {
1667
                self::umountDisk($tmp_dir);
1668
            }
1669
        }
1670
1671
        return $result_data;
1672
    }
1673
1674
    /**
1675
     * Get the disk partitions using the lsblk command.
1676
     *
1677
     * @param string $diskName The name of the disk.
1678
     * @return array An array of disk partition names.
1679
     */
1680
    private function getDiskParted(string $diskName): array
1681
    {
1682
        $result = [];
1683
        $lsBlkPath = Util::which('lsblk');
1684
1685
        // Execute lsblk command to get disk partition information in JSON format
1686
        Processes::mwExec("$lsBlkPath -J -b -o NAME,TYPE $diskName", $out);
1687
1688
        try {
1689
            $data = json_decode(implode(PHP_EOL, $out), true, 512, JSON_THROW_ON_ERROR);
0 ignored issues
show
Bug introduced by
It seems like $out can also be of type null; however, parameter $pieces of implode() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1689
            $data = json_decode(implode(PHP_EOL, /** @scrutinizer ignore-type */ $out), true, 512, JSON_THROW_ON_ERROR);
Loading history...
1690
            $data = $data['blockdevices'][0] ?? [];
1691
        } catch (\JsonException $e) {
1692
            $data = [];
1693
        }
1694
1695
        $type = $data['children'][0]['type'] ?? '';
1696
1697
        // Check if the disk is not a RAID type
1698
        if (!str_contains($type, 'raid')) {
1699
            $children = $data['children'] ?? [];
1700
            foreach ($children as $child) {
1701
                $result[] = $child['name'];
1702
            }
1703
        }
1704
1705
        return $result;
1706
    }
1707
1708
    /**
1709
     * Get the file system type of a device.
1710
     *
1711
     * @param string $device The device path.
1712
     * @return string The file system type of the device.
1713
     */
1714
    public function getFsType(string $device): string
1715
    {
1716
        $blkid = Util::which('blkid');
1717
        $sed = Util::which('sed');
1718
        $grep = Util::which('grep');
1719
        $awk = Util::which('awk');
1720
1721
        // Remove '/dev/' from the device path
1722
        $device = str_replace('/dev/', '', $device);
1723
        $out = [];
1724
1725
        // Execute the command to retrieve the file system type of the device
1726
        Processes::mwExec(
1727
            "$blkid -ofull /dev/$device | $sed -r 's/[[:alnum:]]+=/\\n&/g' | $grep \"^TYPE=\" | $awk -F \"\\\"\" '{print $2}'",
1728
            $out
1729
        );
1730
        $format = implode('', $out);
0 ignored issues
show
Bug introduced by
It seems like $out can also be of type null; however, parameter $pieces of implode() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1730
        $format = implode('', /** @scrutinizer ignore-type */ $out);
Loading history...
1731
1732
        // Check if the format is 'msdosvfat' and replace it with 'msdos'
1733
        if ($format === 'msdosvfat') {
1734
            $format = 'msdos';
1735
        }
1736
1737
        return $format;
1738
    }
1739
1740
    /**
1741
     * Mount a disk to a directory.
1742
     *
1743
     * @param string $dev The device name.
1744
     * @param string $format The file system format.
1745
     * @param string $dir The directory to mount the disk.
1746
     * @return bool True if the disk was successfully mounted, false otherwise.
1747
     */
1748
    public static function mountDisk(string $dev, string $format, string $dir): bool
1749
    {
1750
        // Check if the disk is already mounted
1751
        if (self::isStorageDiskMounted("/dev/$dev ")) {
1752
            return true;
1753
        }
1754
1755
        // Create the directory if it doesn't exist
1756
        Util::mwMkdir($dir);
1757
1758
        // Check if the directory was created successfully
1759
        if (!file_exists($dir)) {
1760
            SystemMessages::sysLogMsg(__Method__, "Unable mount $dev $format to $dir. Unable create dir.");
1761
1762
            return false;
1763
        }
1764
1765
        // Remove the '/dev/' prefix from the device name
1766
        $dev = str_replace('/dev/', '', $dev);
1767
1768
        if ('ntfs' === $format) {
1769
            // Mount NTFS disk using 'mount.ntfs-3g' command
1770
            $mountNtfs3gPath = Util::which('mount.ntfs-3g');
1771
            Processes::mwExec("$mountNtfs3gPath /dev/$dev $dir", $out);
1772
        } else {
1773
            // Mount disk using specified file system format and UUID
1774
            $uid_part = 'UUID=' . self::getUuid("/dev/$dev");
1775
            $mountPath = Util::which('mount');
1776
            Processes::mwExec("$mountPath -t $format $uid_part $dir", $out);
1777
        }
1778
1779
        // Check if the disk is now mounted
1780
        return self::isStorageDiskMounted("/dev/$dev ");
1781
    }
1782
1783
    /**
1784
     * Get the UUID (Universally Unique Identifier) of a device.
1785
     *
1786
     * @param string $device The device path.
1787
     * @return string The UUID of the device.
1788
     */
1789
    public static function getUuid(string $device): string
1790
    {
1791
        if (empty($device)) {
1792
            return '';
1793
        }
1794
        $lsblk = Util::which('lsblk');
1795
        $grep = Util::which('grep');
1796
        $cut = Util::which('cut');
1797
1798
        // Build the command to retrieve the UUID of the device
1799
        $cmd = "$lsblk -r -o NAME,UUID | $grep " . basename($device) . " | $cut -d ' ' -f 2";
1800
        $res = Processes::mwExec($cmd, $output);
1801
        if ($res === 0 && !empty($output)) {
1802
            $result = $output[0];
1803
        } else {
1804
            $result = '';
1805
        }
1806
        return $result;
1807
    }
1808
1809
    /**
1810
     * Retrieves the name of the disk used for recovery. (conf.recover.)
1811
     *
1812
     * @return string The name of the recovery disk (e.g., '/dev/sda').
1813
     */
1814
    public function getRecoverDiskName(): string
1815
    {
1816
        $disks = $this->diskGetDevices(true);
1817
        foreach ($disks as $disk => $diskInfo) {
1818
            // Check if the disk is a RAID or virtual device
1819
            if (isset($diskInfo['children'][0]['children'])) {
1820
                $diskInfo = $diskInfo['children'][0];
1821
                // Adjust the disk name for RAID or other virtual devices
1822
                $disk = $diskInfo['name'];
1823
            }
1824
            foreach ($diskInfo['children'] as $child) {
1825
                $mountpoint = $child['mountpoint'] ?? '';
1826
                $diskPath = "/dev/$disk";
1827
                if ($mountpoint === '/conf.recover' && file_exists($diskPath)) {
1828
                    return "/dev/$disk";
1829
                }
1830
            }
1831
        }
1832
        return '';
1833
    }
1834
1835
    /**
1836
     * Returns the monitor directory path.
1837
     * @deprecated Use Directories class instead
1838
     *
1839
     * @return string The monitor directory path.
1840
     */
1841
    public static function getMonitorDir(): string
1842
    {
1843
        return Directories::getDir(Directories::AST_MONITOR_DIR);
1844
    }
1845
1846
    /**
1847
     * Connect storage in a cloud if it was provisioned but not connected.
1848
     *
1849
     * @return string connection result
1850
     */
1851
    public static function connectStorageInCloud(): string
1852
    {
1853
        if (PbxSettings::findFirst('key="' . PbxSettings::CLOUD_PROVISIONING . '"') === null) {
1854
            return SystemMessages::RESULT_SKIPPED;
1855
        }
1856
1857
        // In some Clouds the virtual machine starts immediately before the storage disk was attached
1858
        if (!self::selectAndConfigureStorageDisk(true)) {
1859
            return SystemMessages::RESULT_FAILED;
1860
        }
1861
1862
        return SystemMessages::RESULT_DONE;
1863
    }
1864
}
1865