Passed
Push — develop ( c8e8dc...cb2748 )
by Nikolay
06:11 queued 13s
created

GetFileContent::main()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 24
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 19
c 1
b 0
f 0
dl 0
loc 24
rs 9.6333
cc 4
nc 3
nop 2
1
<?php
2
/*
3
 * MikoPBX - free phone system for small business
4
 * Copyright © 2017-2024 Alexey Portnov and Nikolay Beketov
5
 *
6
 * This program is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation; either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License along with this program.
17
 * If not, see <https://www.gnu.org/licenses/>.
18
 */
19
20
namespace MikoPBX\PBXCoreREST\Lib\Files;
21
22
23
use MikoPBX\Common\Models\CustomFiles;
24
use MikoPBX\Core\System\Processes;
25
use MikoPBX\Core\System\Util;
26
use MikoPBX\PBXCoreREST\Lib\PBXApiResult;
27
use Phalcon\Di;
28
29
/**
30
 *  Class GetFileContent
31
 * Returns file content
32
 *
33
 * @package MikoPBX\PBXCoreREST\Lib\Modules
34
 */
35
class GetFileContent extends \Phalcon\Di\Injectable
36
{
37
    /**
38
     * Returns file content
39
     *
40
     * @param string $filename
41
     * @param bool   $needOriginal
42
     *
43
     * @return PBXApiResult An object containing the result of the API call.
44
     */
45
    public static function main(string $filename, bool $needOriginal = true): PBXApiResult
46
    {
47
        $res            = new PBXApiResult();
48
        $res->processor = __METHOD__;
49
        $customFile     = CustomFiles::findFirst("filepath = '{$filename}'");
50
        if ($customFile !== null) {
51
            $filename_orgn = "{$filename}.orgn";
52
            if ($needOriginal && file_exists($filename_orgn)) {
53
                $filename = $filename_orgn;
54
            }
55
            $res->success = true;
56
            $cat          = Util::which('cat');
57
            $di           = Di::getDefault();
58
            $dirsConfig   = $di->getShared('config');
59
            $filenameTmp  = $dirsConfig->path('www.downloadCacheDir') . '/' . __FUNCTION__ . '_' .time(). '.conf';
60
            $cmd          = "{$cat} {$filename} > {$filenameTmp}";
61
            Processes::mwExec("{$cmd}; chown www:www {$filenameTmp}");
62
            $res->data['filename'] = $filenameTmp;
63
        } else {
64
            $res->success    = false;
65
            $res->messages[] = 'No access to the file ' . $filename;
66
        }
67
68
        return $res;
69
    }
70
}