Passed
Push — develop ( 8fa09e...0ee469 )
by Nikolay
04:17
created

BaseController::sanitizeCallerId()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
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\AdminCabinet\Controllers;
21
22
use MikoPBX\Common\Providers\PBXConfModulesProvider;
23
use MikoPBX\Modules\Config\WebUIConfigInterface;
24
use MikoPBX\Common\Models\{PbxExtensionModules, PbxSettings};
25
use Phalcon\Http\ResponseInterface;
26
use Phalcon\Mvc\{Controller, View};
27
use Phalcon\Tag;
28
use Phalcon\Text;
29
use Sentry\SentrySdk;
30
31
/**
32
 * @property \Phalcon\Session\Manager session
33
 * @property \MikoPBX\Common\Providers\TranslationProvider translation
34
 * @property string language
35
 * @property bool showModuleStatusToggle if false it hides status toggle on current UI page
36
 * @property \MikoPBX\AdminCabinet\Library\Elements elements
37
 * @property \Phalcon\Flash\Session flash
38
 * @property \Phalcon\Tag tag
39
 * @property \Phalcon\Config\Adapter\Json config
40
 * @property \Phalcon\Logger loggerAuth
41
 */
42
class BaseController extends Controller
43
{
44
    protected string $actionName;
45
    protected string $controllerName;
46
    protected string $controllerNameUnCamelized;
47
    protected bool $isExternalModuleController;
48
49
    /**
50
     * Initializes base class
51
     */
52
    public function initialize(): void
53
    {
54
        $this->actionName = $this->dispatcher->getActionName();
55
        $this->controllerName = Text::camelize($this->dispatcher->getControllerName(), '_');
56
        $this->controllerNameUnCamelized = Text::uncamelize($this->controllerName, '-');
57
        $this->isExternalModuleController = str_starts_with($this->dispatcher->getNamespaceName(), '\\Module');
58
59
        if ($this->request->isAjax() === false) {
60
            $this->prepareView();
61
        }
62
    }
63
64
    /**
65
     * Prepares the view by setting necessary variables and configurations.
66
     *
67
     * @return void
68
     */
69
    protected function prepareView(): void
70
    {
71
        // Set the default timezone based on PBX settings
72
        date_default_timezone_set(PbxSettings::getValueByKey('PBXTimezone'));
73
74
        // Set PBXLicense view variable if session exists
75
        if ($this->session->has(SessionController::SESSION_ID)) {
76
            $this->view->PBXLicense = PbxSettings::getValueByKey('PBXLicense');
77
        } else {
78
            $this->view->PBXLicense = '';
79
        }
80
81
        // Set URLs for Wiki and Support based on language
82
        $this->view->urlToWiki = "https://wiki.mikopbx.com/{$this->controllerNameUnCamelized}";
83
        if ($this->language === 'ru') {
84
            $this->view->urlToSupport = 'https://www.mikopbx.ru/support/?fromPBX=true';
85
        } else {
86
            $this->view->urlToSupport = 'https://www.mikopbx.com/support/?fromPBX=true';
87
        }
88
89
        // Set the title based on the current action
90
        $title = 'MikoPBX';
91
        switch ($this->actionName) {
92
            case'index':
93
            case'delete':
94
            case'save':
95
            case'modify':
96
            case'*** WITHOUT ACTION ***':
97
                $title .= '|' . $this->translation->_("Breadcrumb{$this->controllerName}");
98
                break;
99
            default:
100
                $title .= '|' . $this->translation->_("Breadcrumb{$this->controllerName}{$this->actionName}");
101
        }
102
        Tag::setTitle($title);
103
104
        // Set other view variables
105
        $this->view->t = $this->translation;
106
        $this->view->debugMode = $this->config->path('adminApplication.debugMode');
107
        $this->view->urlToLogo = $this->url->get('assets/img/logo-mikopbx.svg');
108
        $this->view->urlToController = $this->url->get($this->controllerNameUnCamelized);
109
        $this->view->represent = '';
110
        $this->view->WebAdminLanguage = PbxSettings::getValueByKey('WebAdminLanguage');
111
        $this->view->AvailableLanguages = json_encode($this->elements->getAvailableWebAdminLanguages());
112
        $this->view->submitMode = $this->session->get('SubmitMode') ?? 'SaveSettings';
113
        $this->view->lastSentryEventId = $this->setLastSentryEventId();
114
        $this->view->PBXVersion = PbxSettings::getValueByKey('PBXVersion');
115
        $this->view->MetaTegHeadDescription = $this->translation->_('MetaTegHeadDescription');
116
        $this->view->isExternalModuleController = $this->isExternalModuleController;
117
        $this->view->setTemplateAfter('main');
118
        $this->view->globalModuleUniqueId = '';
119
        $this->view->actionName = $this->dispatcher->getActionName();
120
        $this->view->controllerName = $this->controllerName;
121
122
        // Add module variables into view if it is an external module controller
123
        if ($this->isExternalModuleController) {
124
            /** @var PbxExtensionModules $module */
125
            $module = PbxExtensionModules::findFirstByUniqid($this->getModuleUniqueId());
126
            if ($module === null) {
127
                $module = new PbxExtensionModules();
128
                $module->disabled = '1';
129
                $module->name = 'Unknown module';
130
            }
131
            $this->view->module = $module->toArray();
132
            $this->view->globalModuleUniqueId = $module->uniqid;
133
        }
134
    }
135
136
    /**
137
     * Performs actions after executing the route and returns the response.
138
     *
139
     * @return \Phalcon\Http\ResponseInterface
140
     */
141
    public function afterExecuteRoute(): ResponseInterface
142
    {
143
144
        if ($this->request->isAjax() === true) {
145
            $this->view->setRenderLevel(View::LEVEL_NO_RENDER);
146
            $this->response->setContentType('application/json', 'UTF-8');
147
            $data = $this->view->getParamsToView();
148
149
            /* Set global params if is not set in controller/action */
150
            if (isset($data['raw_response'])) {
151
                $result = $data['raw_response'];
152
            } else {
153
                $data['success'] = $data['success'] ?? true;
154
                $data['reload'] = $data['reload'] ?? false;
155
                $data['message'] = $data['message'] ?? $this->flash->getMessages();
156
157
                // Let's add information about the last error to display a dialog window for the user.
158
                if (file_exists('/etc/sendmetrics')) {
159
                    $data['lastSentryEventId'] = SentrySdk::getCurrentHub()->getLastEventId();
160
                }
161
                $result = json_encode($data);
162
            }
163
            $this->response->setContent($result);
164
        }
165
166
        PBXConfModulesProvider::hookModulesMethod(WebUIConfigInterface::ON_AFTER_EXECUTE_ROUTE,[$this]);
167
168
        return $this->response->send();
169
    }
170
171
    /**
172
     * Performs actions before executing the route.
173
     *
174
     * @return void
175
     */
176
    public function beforeExecuteRoute(): void
177
    {
178
        PBXConfModulesProvider::hookModulesMethod(WebUIConfigInterface::ON_BEFORE_EXECUTE_ROUTE,[$this]);
179
180
        // Check if the request method is POST
181
        if ($this->request->isPost()) {
182
            // Retrieve the 'submitMode' data from the request
183
            $data = $this->request->getPost('submitMode');
184
            if (!empty($data)) {
185
                // Set the 'SubmitMode' session variable to the retrieved data
186
                $this->session->set('SubmitMode', $data);
187
            }
188
        }
189
    }
190
191
    /**
192
     * Forwards the request to a different controller and action based on the provided URI.
193
     *
194
     * @param string $uri The URI to forward to.
195
     * @return void
196
     */
197
    protected function forward(string $uri): void
198
    {
199
        $uriParts = explode('/', $uri);
200
        $params = array_slice($uriParts, 2);
201
202
        $this->dispatcher->forward(
203
            [
204
                'controller' => $uriParts[0],
205
                'action' => $uriParts[1],
206
                'params' => $params,
207
            ]
208
209
        );
210
    }
211
212
    /**
213
     * Sanitizes the caller ID by removing any characters that are not alphanumeric or spaces.
214
     *
215
     * @param string $callerId The caller ID to sanitize.
216
     * @return string The sanitized caller ID.
217
     */
218
    protected function sanitizeCallerId(string $callerId): string
219
    {
220
        return preg_replace('/[^a-zA-Zа-яА-Я0-9 ]/ui', '', $callerId);
221
    }
222
223
    /**
224
     * Sorts array by priority field
225
     *
226
     * @param $a
227
     * @param $b
228
     *
229
     * @return int|null
230
     */
231
    protected function sortArrayByPriority($a, $b): ?int
232
    {
233
        if (is_array($a)) {
234
            $a = (int)$a['priority'];
235
        } else {
236
            $a = (int)$a->priority;
237
        }
238
239
        if (is_array($b)) {
240
            $b = (int)$b['priority'];
241
        } else {
242
            $b = (int)$b->priority;
243
        }
244
245
        if ($a === $b) {
246
            return 0;
247
        } else {
248
            return ($a < $b) ? -1 : 1;
249
        }
250
    }
251
252
    /**
253
     * Sets the last Sentry event ID.
254
     *
255
     * @return \Sentry\EventId|null The last Sentry event ID, or null if metrics sending is disabled.
256
     */
257
    private function setLastSentryEventId(): ?\Sentry\EventId
258
    {
259
        $result = null;
260
        // Allow anonymous statistics collection for JS code
261
        if (PbxSettings::getValueByKey('SendMetrics') === '1') {
262
            touch('/etc/sendmetrics');
263
            $result = SentrySdk::getCurrentHub()->getLastEventId();
264
        } elseif (file_exists('/etc/sendmetrics')) {
265
            unlink('/etc/sendmetrics');
266
        }
267
        return $result;
268
    }
269
270
    /**
271
     *  Returns the unique ID of the module parsing controller namespace;
272
     * @return string
273
     */
274
    private function getModuleUniqueId():string
275
    {
276
        // Split the namespace into an array using the backslash as a separator
277
        $parts = explode('\\', get_class($this));
278
279
        // Get the second part of the namespace
280
        return $parts[1];
281
    }
282
}
283