Passed
Push — develop ( db553e...8a684e )
by Nikolay
06:02
created

LicenseManagementProcessor::pingAction()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 5
c 0
b 0
f 0
dl 0
loc 7
rs 10
cc 1
nc 1
nop 0
1
<?php
2
/*
3
 * MikoPBX - free phone system for small business
4
 * Copyright © 2017-2023 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;
21
22
use MikoPBX\Common\Models\Extensions;
23
use MikoPBX\Common\Models\ModelsBase;
24
use MikoPBX\Common\Models\PbxSettings;
25
use MikoPBX\Core\System\MikoPBXConfig;
26
use Phalcon\Di\Injectable;
27
use Phalcon\Text;
28
use SimpleXMLElement;
29
30
31
/**
32
 * Class LicenseManagementProcessor
33
 *
34
 * @package MikoPBX\PBXCoreREST\Lib
35
 * @property \MikoPBX\Common\Providers\LicenseProvider     license
36
 * @property \MikoPBX\Common\Providers\TranslationProvider translation
37
 * @property \Phalcon\Config                               config
38
 */
39
class LicenseManagementProcessor extends Injectable
40
{
41
42
    /**
43
     * Process the license callback.
44
     *
45
     * @param array $request The request data.
46
     *
47
     * @return PBXApiResult An object containing the result of the API call.
48
     */
49
    public static function callBack(array $request): PBXApiResult
50
    {
51
        $action         = $request['action'];
52
        $data           = $request['data'];
53
        $res            = new PBXApiResult();
54
        $res->processor = __METHOD__;
55
        switch ($action) {
56
            case 'resetKey':
57
                $proc = new LicenseManagementProcessor();
58
                $res = $proc->resetLicenseAction();
59
                break;
60
            case 'processUserRequest':
61
                $proc = new LicenseManagementProcessor();
62
                $res = $proc->processUserRequestAction($data);
63
                break;
64
            case 'getLicenseInfo':
65
                $proc = new LicenseManagementProcessor();
66
                $res = $proc->getLicenseInfoAction();
67
                break;
68
            case 'getMikoPBXFeatureStatus':
69
                $proc = new LicenseManagementProcessor();
70
                $res = $proc->getMikoPBXFeatureStatusAction();
71
                break;
72
            case 'captureFeatureForProductId':
73
                $proc = new LicenseManagementProcessor();
74
                $res = $proc->captureFeatureForProductIdAction($data);
75
                break;
76
            case 'sendPBXMetrics':
77
                $proc = new LicenseManagementProcessor();
78
                $res = $proc->sendMetricsAction();
79
                break;
80
            case 'ping':
81
                $proc = new LicenseManagementProcessor();
82
                $res = $proc->pingAction();
83
                break;
84
            default:
85
                $res->messages[] = "Unknown action - {$action} in licenseCallBack";
86
        }
87
88
        $res->function = $action;
89
90
        return $res;
91
    }
92
93
    /**
94
     * Reset license key.
95
     *
96
     * @return PBXApiResult An object containing the result of the API call.
97
     */
98
    private function resetLicenseAction():PBXApiResult
99
    {
100
        $mikoPBXConfig = new MikoPBXConfig();
101
        $res           = new PBXApiResult();
102
        $res->processor = __METHOD__;
103
        $mikoPBXConfig->deleteGeneralSettings('PBXLicense');
104
        $res->success = true;
105
        $this->license->changeLicenseKey('');
106
        return $res;
107
    }
108
109
    /**
110
     * Check and update license key on database.
111
     *
112
     * @param array $data
113
     *
114
     * @return PBXApiResult An object containing the result of the API call.
115
     */
116
    private function processUserRequestAction(array $data): PBXApiResult
117
    {
118
        $mikoPBXConfig = new MikoPBXConfig();
119
        $res           = new PBXApiResult();
120
        $res->processor = __METHOD__;
121
        if (strlen($data['licKey']) === 28 && Text::startsWith($data['licKey'], 'MIKO-')) {
122
            ModelsBase::clearCache(PbxSettings::class);
123
            $oldLicKey = $mikoPBXConfig->getGeneralSettings('PBXLicense');
124
            if ($oldLicKey !== $data['licKey']) {
125
                $licenseInfo = $this->license->getLicenseInfo($data['licKey']);
126
                if ($licenseInfo instanceof SimpleXMLElement) {
127
                    $mikoPBXConfig->setGeneralSettings('PBXLicense', $data['licKey']);
128
                    $this->license->changeLicenseKey($data['licKey']);
129
                    $this->license->addTrial('11'); // MikoPBX forever license
130
                    $res->success = true;
131
                } elseif ( ! empty($licenseInfo) && strpos($licenseInfo, '2026') !== false) {
132
                    $res->success    = false;
133
                    $res->messages[] = $this->translation->_('lic_FailedCheckLicense2026');
134
                } elseif ( ! empty($licenseInfo)) {
135
                    $res->messages[] = $licenseInfo;
136
                    $res->success    = false;
137
                } else {
138
                    $res->messages[] = $this->translation->_('lic_FailedCheckLicense');
139
                    $res->success    = false;
140
                }
141
            }
142
            if ( ! empty($data['coupon'])) {
143
                $result = $this->license->activateCoupon($data['coupon']);
144
                if ($result === true) {
145
                    $res->messages[] = $this->translation->_('lic_SuccessfulСuponActivation');
146
                    $res->success    = true;
147
                } else {
148
                    $res->messages[] = $this->license->translateLicenseErrorMessage((string)$result);
149
                    $res->success    = false;
150
                }
151
            }
152
        } else { // Only add trial for license key
153
            $newLicenseKey = (string)$this->license->getTrialLicense($data);
154
            if (strlen($newLicenseKey) === 28
155
                && Text::startsWith($newLicenseKey, 'MIKO-')) {
156
                $mikoPBXConfig->setGeneralSettings('PBXLicense', $newLicenseKey);
157
                $this->license->changeLicenseKey($newLicenseKey);
158
                $res->success    = true;
159
                $res->data['PBXLicense'] = $newLicenseKey;
160
            } else {
161
                // No internet connection, or wrong data sent to license server, or something else
162
                $res->messages[] = $this->license->translateLicenseErrorMessage($newLicenseKey);
163
                $res->success    = false;
164
            }
165
        }
166
        return $res;
167
    }
168
169
    /**
170
     * Returns license info from license server by key.
171
     *
172
     * @return PBXApiResult An object containing the result of the API call.
173
     */
174
    private function getLicenseInfoAction(): PBXApiResult
175
    {
176
        $res = new PBXApiResult();
177
        $res->processor = __METHOD__;
178
        $licenseKey = PbxSettings::getValueByKey('PBXLicense');
179
        if ((strlen($licenseKey) === 28
180
            && Text::startsWith($licenseKey, 'MIKO-')
181
        )) {
182
            $licenseInfo              = $this->license->getLicenseInfo($licenseKey);
183
            $res->success             = true;
184
            $res->data['licenseInfo'] = json_encode($licenseInfo);
185
        } else {
186
            $res->messages[] = 'License key is wrong or empty';
187
        }
188
189
        return $res;
190
    }
191
192
    /**
193
     * Check for free MikoPBX base license.
194
     *
195
     * @return PBXApiResult An object containing the result of the API call.
196
     */
197
    private function getMikoPBXFeatureStatusAction(): PBXApiResult
198
    {
199
        $res = new PBXApiResult();
200
        $res->processor = __METHOD__;
201
        $checkBaseFeature = $this->license->featureAvailable(33);
202
        if ($checkBaseFeature['success'] === false) {
203
            $res->success = false;
204
            $textError = (string)($checkBaseFeature['error']??'');
205
            $res->messages[] = $this->license->translateLicenseErrorMessage($textError);
206
        } else {
207
            $res->success = true;
208
        }
209
        return $res;
210
    }
211
212
    /**
213
     * Tries to capture feature.
214
     *
215
     * If it fails we try to get trial and then try capture again.
216
     *
217
     * @param array $data
218
     *
219
     * @return PBXApiResult An object containing the result of the API call.
220
     */
221
    private function captureFeatureForProductIdAction(array $data): PBXApiResult
222
    {
223
        $res = new PBXApiResult();
224
        $res->processor = __METHOD__;
225
        $licFeatureId = $data['licFeatureId'];
226
        $licProductId = $data['licProductId'];
227
228
        if ( ! isset($licFeatureId, $licProductId)) {
229
            $res->messages[]='The feature id or product id is empty.';
230
            return $res;
231
        }
232
        $res->success = true;
233
        if ($licFeatureId > 0) {
234
            // 1.Try to capture feature
235
            $result = $this->license->captureFeature($licFeatureId);
236
            if ($result['success'] === false) {
237
                // Add trial
238
                $this->license->addTrial($licProductId);
239
                // 2.Try to capture feature
240
                $result = $this->license->captureFeature($licFeatureId);
241
                if ($result['success'] === false) {
242
                    $textError = (string)($result['error']??'');
243
                    $res->messages[] = $this->license->translateLicenseErrorMessage($textError);
244
                    $res->success = false;
245
                }
246
            }
247
        }
248
        return $res;
249
    }
250
251
    /**
252
     * Sends PBX metrics to the license server.
253
     *
254
     * @return PBXApiResult An object containing the result of the API call.
255
     */
256
    private function sendMetricsAction(): PBXApiResult
257
    {
258
        $res = new PBXApiResult();
259
        $res->processor = __METHOD__;
260
        $res->success= true;
261
262
        // License Key
263
        $licenseKey = PbxSettings::getValueByKey('PBXLicense');
264
265
        $dataMetrics = [];
266
267
        // PBXVersion
268
        $dataMetrics['PBXname'] = 'MikoPBX@' . PbxSettings::getValueByKey('PBXVersion');
269
270
        // SIP Extensions count
271
        $extensions                   = Extensions::find('type="'.Extensions::TYPE_SIP.'"');
272
        $dataMetrics['CountSipExtensions'] = $extensions->count();
273
274
        // Interface language
275
        $dataMetrics['WebAdminLanguage'] = PbxSettings::getValueByKey('WebAdminLanguage');
276
277
        // PBX language
278
        $dataMetrics['PBXLanguage'] = PbxSettings::getValueByKey('PBXLanguage');
279
280
        $this->license->sendLicenseMetrics($licenseKey, $dataMetrics);
281
282
        return $res;
283
    }
284
285
    /**
286
     * Sends ping request to the license server.
287
     *
288
     * @return PBXApiResult An object containing the result of the API call.
289
     */
290
    private function pingAction(): PBXApiResult
291
    {
292
        $res = new PBXApiResult();
293
        $res->processor = __METHOD__;
294
        $result = $this->license->ping();
295
        $res->success= $result['success'] === true;
296
        return $res;
297
    }
298
}