Passed
Push — develop ( 843492...60d531 )
by Nikolay
06:55 queued 12s
created

PostController::fileReadContent()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 24
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 18
c 0
b 0
f 0
dl 0
loc 24
rs 9.6666
cc 3
nc 3
nop 0
1
<?php
2
/**
3
 * Copyright (C) MIKO LLC - All Rights Reserved
4
 * Unauthorized copying of this file, via any medium is strictly prohibited
5
 * Proprietary and confidential
6
 * Written by Nikolay Beketov, 4 2020
7
 *
8
 */
9
10
namespace MikoPBX\PBXCoreREST\Controllers\System;
11
12
use MikoPBX\Common\Models\SoundFiles;
13
use MikoPBX\PBXCoreREST\Controllers\BaseController;
14
use Phalcon\Di;
15
16
/**
17
 * /pbxcore/api/system/{name}' Управление системой в целом (POST).
18
 *
19
 * Установка системного времени
20
 *   curl -X POST -d '{"date": "2015.12.31-01:01:20"}' http://172.16.156.212/pbxcore/api/system/setDate;
21
 *
22
 * Отправка email.
23
 *   curl -X POST -d '{"email": "[email protected]", "subject":"Привет от mikopbx", "body":"Тестовое сообщение", "encode":
24
 *   ""}' http://172.16.156.223/pbxcore/api/system/sendMail;
25
 *     'encode' - может быть пустой строкой или 'base64', на случай, если subject и body передаются в base64;
26
 *
27
 * Снятие бана IP адреса
28
 *   curl -X POST -d '{"ip": "172.16.156.1"}' http://172.16.156.212/pbxcore/api/system/unBanIp;
29
 *   Пример ответа:
30
 *   {"result":"Success","data":[{"jail":"asterisk","ip":"172.16.156.1","timeofban":1522326119}],"function":"getBanIp"}
31
 *
32
 * Получение содержимого файла.
33
 *   curl -X POST -d '{"filename": "/etc/asterisk/asterisk.conf"}'
34
 *   http://172.16.156.212/pbxcore/api/system/fileReadContent; Примеры ответа:
35
 *   {"result":"ERROR","message":"API action not found;","function":"fileReadContent"}
36
 *   {"result":"Success","data":"W2RpcmVj","function":"fileReadContent"}
37
 *
38
 * Конвертация аудио файла:
39
 *   curl -X POST -d '{"filename": "/tmp/WelcomeMaleMusic.mp3"}'
40
 *   http://172.16.156.212/pbxcore/api/system/convertAudioFile; Пример ответа:
41
 *   {
42
 *      "result": "Success",
43
 *      "filename": "/tmp/WelcomeMaleMusic.wav",
44
 *      "function": "convertAudioFile"
45
 *   }
46
 *
47
 * Загрузка аудио файла на АТС:
48
 *   curl  -X POST -d '{"filename": "/storage/usbdisk1/mikopbx/tmp/1577195443/test.mp3"}'
49
 *   http://127.0.0.1/pbxcore/api/system/uploadAudioFile -H 'Cookie: XDEBUG_SESSION=PHPSTORM'; curl  -F
50
 *   "file=@/storage/usbdisk1/mikopbx/voicemailarchive/monitor/2019/11/29/10/mikopbx-15750140_201_YNrXH1KHDj.mp3"
51
 *   http://127.0.0.1/pbxcore/api/system/uploadAudioFile;
52
 *
53
 * Пример ответа:
54
 *   {
55
 *      "result": "Success",
56
 *      "filename": "/tmp/WelcomeMaleMusic.wav",
57
 *      "function": "uploadAudioFile"
58
 *   }
59
 *
60
 * Удаление аудио файла:
61
 *   curl -X POST -d '{"filename": "/storage/usbdisk1/mikopbx/tmp/2233333.wav"}'
62
 *   http://172.16.156.212/pbxcore/api/system/removeAudioFile;
63
 *
64
 *
65
 * Обновление системы (офлайн) curl -X POST -d
66
 *   '{"filename": "/storage/usbdisk1/mikopbx/tmp/2019.4.200-mikopbx-generic-x86-64-linux.img"}'
67
 *   http://127.0.0.1/pbxcore/api/system/upgrade -H 'Cookie: XDEBUG_SESSION=PHPSTORM'; curl -F
68
 *   "[email protected]" http://172.16.156.212/pbxcore/api/system/upgrade;
69
 *
70
 *
71
 * Онлайн обновление АТС. curl -X POST -d '{"md5":"df7622068d0d58700a2a624d991b6c1f", "url":
72
 *   "https://www.askozia.ru/upload/update/firmware/6.2.96-9.0-svn-mikopbx-x86-64-cross-linux.img"}'
73
 *   http://172.16.156.223/pbxcore/api/system/upgradeOnline;
74
 *
75
 *
76
 * Install new module with params by URL
77
 * curl -X POST -d '{"uniqid":"ModuleCTIClient", "md5":"fd9fbf38298dea83667a36d1d0464eae", "url":
78
 * "https://www.askozia.ru/upload/update/modules/ModuleCTIClient/ModuleCTIClientv01.zip"}'
79
 * http://172.16.156.223/pbxcore/api/modules/uploadNewModule;
80
 *
81
 *
82
 * Receive uploading status
83
 * curl  -X POST -d '{"uniqid":"ModuleSmartIVR"} http://172.16.156.223/pbxcore/api/system/statusUploadingNewModule
84
 *
85
 *
86
 * Install new module from ZIP archive:
87
 * curl -F "[email protected]" http://127.0.0.1/pbxcore/api/modules/uploadNewModule;
88
 *
89
 *
90
 * Uninstall module:
91
 * curl -X POST -d '{"uniqid":"ModuleSmartIVR"} http://172.16.156.223/pbxcore/api/system/uninstallModule
92
 *
93
 *
94
 */
95
class PostController extends BaseController
96
{
97
    public function callAction($actionName): void
98
    {
99
        $data = null;
100
        switch ($actionName) {
101
            case 'convertAudioFile':
102
                $data = $this->convertAudioFile();
103
                if ($data === null) {
104
                    return;
105
                }
106
                break;
107
            case 'fileReadContent':
108
                $this->fileReadContent();
109
                break;
110
            default:
111
                $data = $this->request->getPost();
112
                $this->sendRequestToBackendWorker('system', $actionName, $data);
113
        }
114
    }
115
116
    /**
117
     * Categorize and store uploaded audio files
118
     *
119
     * @return array|null
120
     */
121
    private function convertAudioFile(): ?array
122
    {
123
        $data                  = [];
124
        $category              = $this->request->getPost('category');
125
        $data['temp_filename'] = $this->request->getPost('temp_filename');
126
        $di                    = Di::getDefault();
127
        $mediaDir              = $di->getShared('config')->path('asterisk.mediadir');
128
        $mohDir                = $di->getShared('config')->path('asterisk.mohdir');
129
        switch ($category) {
130
            case SoundFiles::CATEGORY_MOH:
131
                $data['filename'] = "{$mohDir}/" . basename($data['temp_filename']);
132
                break;
133
            case SoundFiles::CATEGORY_CUSTOM:
134
                $data['filename'] = "{$mediaDir}/" . basename($data['temp_filename']);
135
                break;
136
            default:
137
                $this->sendError(400, 'Category not set');
138
139
                return null;
140
        }
141
142
        return $data;
143
    }
144
145
    /**
146
     * Parses content of file and puts it to answer
147
     *
148
     */
149
    private function fileReadContent(): void
150
    {
151
        $requestMessage = json_encode(
152
            [
153
                'processor' => 'system',
154
                'data'      => $this->request->getPost(),
155
                'action'    => 'fileReadContent',
156
            ]
157
        );
158
        $connection     = $this->di->getShared('beanstalkConnection');
159
        $response       = $connection->request($requestMessage, 5, 0);
160
        if ($response !== false) {
161
            $response = json_decode($response, true);
162
            $filename = $response['data']['filename'] ?? '';
163
            if ( ! file_exists($filename)) {
164
                $response['messages'][] = 'Config file not found';
165
            } else {
166
                $response['data']['filename'] = $filename;
167
                $response['data']['content']  = '' . file_get_contents($filename);
168
                unlink($filename);
169
            }
170
            $this->response->setPayloadSuccess($response);
0 ignored issues
show
Bug introduced by
The method setPayloadSuccess() does not exist on Phalcon\Http\ResponseInterface. It seems like you code against a sub-type of Phalcon\Http\ResponseInterface such as MikoPBX\PBXCoreREST\Http\Response. ( Ignorable by Annotation )

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

170
            $this->response->/** @scrutinizer ignore-call */ 
171
                             setPayloadSuccess($response);
Loading history...
introduced by
The method setPayloadSuccess() does not exist on Phalcon\Http\Response. Are you sure you never get this type here, but always one of the subclasses? ( Ignorable by Annotation )

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

170
            $this->response->/** @scrutinizer ignore-call */ 
171
                             setPayloadSuccess($response);
Loading history...
171
        } else {
172
            $this->sendError(500);
173
        }
174
    }
175
176
}