Passed
Push — develop ( 622b5a...9dbbd5 )
by Nikolay
06:55
created

LicenseManagementProcessor   A

Complexity

Total Complexity 31

Size/Duplication

Total Lines 241
Duplicated Lines 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 31
eloc 130
c 3
b 0
f 0
dl 0
loc 241
rs 9.92

7 Methods

Rating   Name   Duplication   Size   Complexity  
A getLicenseInfoAction() 0 16 3
A getMikoPBXFeatureStatusAction() 0 12 2
A resetLicenseAction() 0 9 1
B callBack() 0 38 7
A sendMetricsAction() 0 27 1
C processUserRequestAction() 0 50 12
A captureFeatureForProductIdAction() 0 27 5
1
<?php
2
/**
3
 * Copyright © MIKO LLC - All Rights Reserved
4
 * Unauthorized copying of this file, via any medium is strictly prohibited
5
 * Proprietary and confidential
6
 * Written by Alexey Portnov, 8 2020
7
 */
8
9
namespace MikoPBX\PBXCoreREST\Lib;
10
11
use MikoPBX\Common\Models\Extensions;
12
use MikoPBX\Common\Models\PbxSettings;
13
use MikoPBX\Core\System\MikoPBXConfig;
14
use Phalcon\Di\Injectable;
15
use Phalcon\Text;
16
use SimpleXMLElement;
17
18
19
/**
20
 * Class LicenseManagementProcessor
21
 *
22
 * @package MikoPBX\PBXCoreREST\Lib
23
 * @property \MikoPBX\Common\Providers\LicenseProvider     license
24
 * @property \MikoPBX\Common\Providers\TranslationProvider translation
25
 * @property \Phalcon\Config                               config
26
 */
27
class LicenseManagementProcessor extends Injectable
28
{
29
30
    /**
31
     * Processes requests to licensing system
32
     *
33
     * @param array $request
34
     *
35
     * @return \MikoPBX\PBXCoreREST\Lib\PBXApiResult
36
     *
37
     */
38
    public static function callBack(array $request): PBXApiResult
39
    {
40
        $action         = $request['action'];
41
        $data           = $request['data'];
42
        $res            = new PBXApiResult();
43
        $res->processor = __METHOD__;
44
        switch ($action) {
45
            case 'resetKey':
46
                $proc = new LicenseManagementProcessor();
47
                $res = $proc->resetLicenseAction();
48
                break;
49
            case 'processUserRequest':
50
                $proc = new LicenseManagementProcessor();
51
                $res = $proc->processUserRequestAction($data);
52
                break;
53
            case 'getLicenseInfo':
54
                $proc = new LicenseManagementProcessor();
55
                $res = $proc->getLicenseInfoAction();
56
                break;
57
            case 'getMikoPBXFeatureStatus':
58
                $proc = new LicenseManagementProcessor();
59
                $res = $proc->getMikoPBXFeatureStatusAction();
60
                break;
61
            case 'captureFeatureForProductId':
62
                $proc = new LicenseManagementProcessor();
63
                $res = $proc->captureFeatureForProductIdAction($data);
64
                break;
65
            case 'sendPBXMetrics':
66
                $proc = new LicenseManagementProcessor();
67
                $res = $proc->sendMetricsAction();
68
                break;
69
            default:
70
                $res->messages[] = "Unknown action - {$action} in licenseCallBack";
71
        }
72
73
        $res->function = $action;
74
75
        return $res;
76
    }
77
78
    /**
79
     * Reset license key
80
     *
81
     * @return \MikoPBX\PBXCoreREST\Lib\PBXApiResult
82
     */
83
    private function resetLicenseAction():PBXApiResult
84
    {
85
        $mikoPBXConfig = new MikoPBXConfig();
86
        $res           = new PBXApiResult();
87
        $res->processor = __METHOD__;
88
        $mikoPBXConfig->deleteGeneralSettings('PBXLicense');
89
        $res->success = true;
90
        $this->license->changeLicenseKey('');
91
        return $res;
92
    }
93
94
95
96
    /**
97
     * Check and update license key on database
98
     *
99
     * @param array $data
100
     *
101
     * @return \MikoPBX\PBXCoreREST\Lib\PBXApiResult
102
     */
103
    private function processUserRequestAction(array $data): PBXApiResult
104
    {
105
        $mikoPBXConfig = new MikoPBXConfig();
106
        $res           = new PBXApiResult();
107
        $res->processor = __METHOD__;
108
        if (strlen($data['licKey']) === 28
109
            && Text::startsWith($data['licKey'], 'MIKO-')
110
        ) {
111
            $oldLicKey = $mikoPBXConfig->getGeneralSettings('PBXLicense');
112
            if ($oldLicKey !== $data['licKey']) {
113
                $licenseInfo = $this->license->getLicenseInfo($data['licKey']);
114
                if ($licenseInfo instanceof SimpleXMLElement) {
0 ignored issues
show
introduced by
$licenseInfo is never a sub-type of SimpleXMLElement.
Loading history...
115
                    $mikoPBXConfig->setGeneralSettings('PBXLicense', $data['licKey']);
116
                    $this->license->changeLicenseKey($data['licKey']);
117
                    $this->license->addTrial('11'); // MikoPBX forever license
118
                    $res->success = true;
119
                } elseif ( ! empty($licenseInfo) && strpos($licenseInfo, '2026') !== false) {
120
                    $res->success    = false;
121
                    $res->messages[] = $this->translation->_('lic_FailedCheckLicense2026');
122
                } elseif ( ! empty($licenseInfo)) {
123
                    $res->messages[] = $licenseInfo;
124
                    $res->success    = false;
125
                } else {
126
                    $res->messages[] = $this->translation->_('lic_FailedCheckLicense');
127
                    $res->success    = false;
128
                }
129
            }
130
            if ( ! empty($data['coupon'])) {
131
                $result = $this->license->activateCoupon($data['coupon']);
132
                if ($result === true) {
133
                    $res->messages[] = $this->translation->_('lic_SuccessfulCouponActivated');
134
                    $res->success    = true;
135
                } else {
136
                    $res->messages[] = $this->license->translateLicenseErrorMessage($result);
0 ignored issues
show
Bug introduced by
$result of type false is incompatible with the type string expected by parameter $message of MikoPBX\Common\Providers...teLicenseErrorMessage(). ( Ignorable by Annotation )

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

136
                    $res->messages[] = $this->license->translateLicenseErrorMessage(/** @scrutinizer ignore-type */ $result);
Loading history...
137
                    $res->success    = false;
138
                }
139
            }
140
        } else { // Only add trial for license key
141
            $newLicenseKey = $this->license->getTrialLicense($data);
142
            if (strlen($newLicenseKey) === 28 && Text::startsWith($newLicenseKey, 'MIKO-')) {
0 ignored issues
show
Bug introduced by
$newLicenseKey of type boolean is incompatible with the type string expected by parameter $text of Phalcon\Text::startsWith(). ( Ignorable by Annotation )

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

142
            if (strlen($newLicenseKey) === 28 && Text::startsWith(/** @scrutinizer ignore-type */ $newLicenseKey, 'MIKO-')) {
Loading history...
143
                $mikoPBXConfig->setGeneralSettings('PBXLicense', $newLicenseKey);
144
                $this->license->changeLicenseKey($newLicenseKey);
145
                $res->success    = true;
146
            } else {
147
                // No internet connection, or wrong data sent to license server, or something else
148
                $res->messages[] = $this->license->translateLicenseErrorMessage($newLicenseKey);
149
                $res->success    = false;
150
            }
151
        }
152
        return $res;
153
    }
154
155
156
    /**
157
     * Returns license info from license server by key
158
     *
159
     * @return \MikoPBX\PBXCoreREST\Lib\PBXApiResult
160
     */
161
    private function getLicenseInfoAction(): PBXApiResult
162
    {
163
        $res = new PBXApiResult();
164
        $res->processor = __METHOD__;
165
        $licenseKey = PbxSettings::getValueByKey('PBXLicense');
166
        if ((strlen($licenseKey) === 28
167
            && Text::startsWith($licenseKey, 'MIKO-')
168
        )) {
169
            $licenseInfo              = $this->license->getLicenseInfo($licenseKey);
170
            $res->success             = true;
171
            $res->data['licenseInfo'] = json_encode($licenseInfo);
172
        } else {
173
            $res->messages[] = 'License key is wrong or empty';
174
        }
175
176
        return $res;
177
    }
178
179
    /**
180
     * Check for free MikoPBX base license
181
     *
182
     * @return \MikoPBX\PBXCoreREST\Lib\PBXApiResult
183
     */
184
    private function getMikoPBXFeatureStatusAction(): PBXApiResult
185
    {
186
        $res = new PBXApiResult();
187
        $res->processor = __METHOD__;
188
        $checkBaseFeature = $this->license->featureAvailable(33);
189
        if ($checkBaseFeature['success'] === false) {
190
            $res->success = false;
191
            $res->messages[] = $this->license->translateLicenseErrorMessage($checkBaseFeature['error']);
192
        } else {
193
            $res->success = true;
194
        }
195
        return $res;
196
    }
197
198
    /**
199
     * Tries to capture feature.
200
     *
201
     * If it fails we try to get trial and then try capture again.
202
     *
203
     * @param array $data
204
     *
205
     * @return \MikoPBX\PBXCoreREST\Lib\PBXApiResult
206
     */
207
    private function captureFeatureForProductIdAction(array $data): PBXApiResult
208
    {
209
        $res = new PBXApiResult();
210
        $res->processor = __METHOD__;
211
        $licFeatureId = $data['licFeatureId'];
212
        $licProductId = $data['licProductId'];
213
214
        if ( ! isset($licFeatureId, $licProductId)) {
215
            $res->messages[]='The feature id or product id is empty.';
216
            return $res;
217
        }
218
        $res->success = true;
219
        if ($licFeatureId > 0) {
220
            // 1.Try to capture feature
221
            $result = $this->license->captureFeature($licFeatureId);
222
            if ($result['success'] === false) {
223
                // Add trial
224
                $this->license->addTrial($licProductId);
225
                // 2.Try to capture feature
226
                $result = $this->license->captureFeature($licFeatureId);
227
                if ($result['success'] === false) {
228
                    $res->messages[] = $this->license->translateLicenseErrorMessage($result['error']);
229
                    $res->success = false;
230
                }
231
            }
232
        }
233
        return $res;
234
    }
235
236
    /**
237
     * Sends PBX metrics to the MIKO company
238
     *
239
     * @return \MikoPBX\PBXCoreREST\Lib\PBXApiResult
240
     */
241
    private function sendMetricsAction(): PBXApiResult
242
    {
243
        $res = new PBXApiResult();
244
        $res->processor = __METHOD__;
245
        $res->success= true;
246
247
        // License Key
248
        $licenseKey = PbxSettings::getValueByKey('PBXLicense');
249
250
        $dataMetrics = [];
251
252
        // PBXVersion
253
        $dataMetrics['PBXname'] = 'MikoPBX@' . PbxSettings::getValueByKey('PBXVersion');
254
255
        // SIP Extensions count
256
        $extensions                   = Extensions::find('type="'.Extensions::TYPE_SIP.'"');
257
        $dataMetrics['CountSipExtensions'] = $extensions->count();
258
259
        // Interface language
260
        $dataMetrics['WebAdminLanguage'] = PbxSettings::getValueByKey('WebAdminLanguage');
261
262
        // PBX language
263
        $dataMetrics['PBXLanguage'] = PbxSettings::getValueByKey('PBXLanguage');
264
265
        $this->license->sendLicenseMetrics($licenseKey, $dataMetrics);
266
267
        return $res;
268
    }
269
}