Passed
Push — develop ( a4a90f...fc5c50 )
by Nikolay
05:38
created

BaseController::beforeExecuteRoute()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 11
rs 10
c 0
b 0
f 0
cc 3
nc 3
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\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
use function MikoPBX\Common\Config\appPath;
31
32
/**
33
 * @property \Phalcon\Session\Manager session
34
 * @property \MikoPBX\Common\Providers\TranslationProvider translation
35
 * @property string language
36
 * @property bool showModuleStatusToggle if false it hides status toggle on current UI page
37
 * @property \MikoPBX\AdminCabinet\Library\Elements elements
38
 * @property \Phalcon\Flash\Session flash
39
 * @property \Phalcon\Tag tag
40
 * @property \Phalcon\Config\Adapter\Json config
41
 * @property \Phalcon\Logger loggerAuth
42
 */
43
class BaseController extends Controller
44
{
45
    protected string $actionName;
46
    protected string $controllerName;
47
    protected string $controllerClass;
48
    protected string $controllerNameUnCamelized;
49
    protected bool $isExternalModuleController;
50
51
    /**
52
     * Initializes base class
53
     */
54
    public function initialize(): void
55
    {
56
        $this->actionName = $this->dispatcher->getActionName();
57
        $this->controllerClass = $this->dispatcher->getHandlerClass();
0 ignored issues
show
Bug introduced by
The method getHandlerClass() does not exist on Phalcon\Mvc\DispatcherInterface. Did you maybe mean getHandlerSuffix()? ( Ignorable by Annotation )

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

57
        /** @scrutinizer ignore-call */ 
58
        $this->controllerClass = $this->dispatcher->getHandlerClass();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
58
        $this->controllerName = Text::camelize($this->dispatcher->getControllerName(), '_');
59
        $this->controllerNameUnCamelized = Text::uncamelize($this->controllerName, '-');
60
        $this->isExternalModuleController = str_starts_with($this->dispatcher->getNamespaceName(), 'Modules');
61
62
        if ($this->request->isAjax() === false) {
63
            $this->prepareView();
64
        }
65
    }
66
67
    /**
68
     * Prepares the view by setting necessary variables and configurations.
69
     *
70
     * @return void
71
     */
72
    protected function prepareView(): void
73
    {
74
        // Set the default timezone based on PBX settings
75
        date_default_timezone_set(PbxSettings::getValueByKey('PBXTimezone'));
76
77
        // Set PBXLicense view variable if session exists
78
        if ($this->session->has(SessionController::SESSION_ID)) {
79
            $this->view->PBXLicense = PbxSettings::getValueByKey('PBXLicense');
80
        } else {
81
            $this->view->PBXLicense = '';
82
        }
83
84
        // Set URLs for Wiki and Support based on language
85
        $this->view->urlToWiki = "https://wiki.mikopbx.com/{$this->controllerNameUnCamelized}";
86
        if ($this->language === 'ru') {
87
            $this->view->urlToSupport = 'https://www.mikopbx.ru/support/?fromPBX=true';
88
        } else {
89
            $this->view->urlToSupport = 'https://www.mikopbx.com/support/?fromPBX=true';
90
        }
91
92
        // Set the title based on the current action
93
        $title = 'MikoPBX';
94
        switch ($this->actionName) {
95
            case'index':
96
            case'delete':
97
            case'save':
98
            case'modify':
99
            case'*** WITHOUT ACTION ***':
100
                $title .= '|' . $this->translation->_("Breadcrumb{$this->controllerName}");
101
                break;
102
            default:
103
                $title .= '|' . $this->translation->_("Breadcrumb{$this->controllerName}{$this->actionName}");
104
        }
105
        Tag::setTitle($title);
106
107
        // Set other view variables
108
        $this->view->t = $this->translation;
109
        $this->view->debugMode = $this->config->path('adminApplication.debugMode');
110
        $this->view->urlToLogo = $this->url->get('assets/img/logo-mikopbx.svg');
111
        $this->view->urlToController = $this->url->get($this->controllerNameUnCamelized);
112
        $this->view->represent = '';
113
        $this->view->WebAdminLanguage = PbxSettings::getValueByKey('WebAdminLanguage');
114
        $this->view->AvailableLanguages = json_encode($this->elements->getAvailableWebAdminLanguages());
115
        $this->view->submitMode = $this->session->get('SubmitMode') ?? 'SaveSettings';
116
        $this->view->lastSentryEventId = $this->setLastSentryEventId();
117
        $this->view->PBXVersion = PbxSettings::getValueByKey('PBXVersion');
118
        $this->view->MetaTegHeadDescription = $this->translation->_('MetaTegHeadDescription');
119
        $this->view->isExternalModuleController = $this->isExternalModuleController;
120
121
        if ($this->controllerName!=='Session'){
122
            $this->view->setTemplateAfter('main');
123
        }
124
125
        $this->view->globalModuleUniqueId = '';
126
        $this->view->actionName = $this->actionName;
127
        $this->view->controllerName = $this->controllerName;
128
        $this->view->controllerClass = $this->controllerClass;
129
130
        // Add module variables into view if it is an external module controller
131
        if ($this->isExternalModuleController) {
132
            /** @var PbxExtensionModules $module */
133
            $module = PbxExtensionModules::findFirstByUniqid($this->getModuleUniqueId());
134
            if ($module === null) {
135
                $module = new PbxExtensionModules();
136
                $module->disabled = '1';
137
                $module->name = 'Unknown module';
138
            }
139
            $this->view->module = $module->toArray();
140
            $this->view->globalModuleUniqueId = $module->uniqid;
141
            $this->view->pick("Modules/{$module->uniqid}/{$this->controllerName}/{$this->actionName}");
142
        }
143
    }
144
145
    /**
146
     * Performs actions after executing the route and returns the response.
147
     *
148
     * @return \Phalcon\Http\ResponseInterface
149
     */
150
    public function afterExecuteRoute(): ResponseInterface
151
    {
152
153
        if ($this->request->isAjax() === true) {
154
            $this->view->setRenderLevel(View::LEVEL_NO_RENDER);
155
            $this->response->setContentType('application/json', 'UTF-8');
156
            $data = $this->view->getParamsToView();
157
158
            /* Set global params if is not set in controller/action */
159
            if (isset($data['raw_response'])) {
160
                $result = $data['raw_response'];
161
            } else {
162
                $data['success'] = $data['success'] ?? true;
163
                $data['reload'] = $data['reload'] ?? false;
164
                $data['message'] = $data['message'] ?? $this->flash->getMessages();
165
166
                // Let's add information about the last error to display a dialog window for the user.
167
                if (file_exists('/etc/sendmetrics')) {
168
                    $data['lastSentryEventId'] = SentrySdk::getCurrentHub()->getLastEventId();
169
                }
170
                $result = json_encode($data);
171
            }
172
            $this->response->setContent($result);
173
        }
174
175
        PBXConfModulesProvider::hookModulesMethod(WebUIConfigInterface::ON_AFTER_EXECUTE_ROUTE,[$this]);
176
177
        return $this->response->send();
178
    }
179
180
    /**
181
     * Performs actions before executing the route.
182
     *
183
     * @return void
184
     */
185
    public function beforeExecuteRoute(): void
186
    {
187
        PBXConfModulesProvider::hookModulesMethod(WebUIConfigInterface::ON_BEFORE_EXECUTE_ROUTE,[$this]);
188
189
        // Check if the request method is POST
190
        if ($this->request->isPost()) {
191
            // Retrieve the 'submitMode' data from the request
192
            $data = $this->request->getPost('submitMode');
193
            if (!empty($data)) {
194
                // Set the 'SubmitMode' session variable to the retrieved data
195
                $this->session->set('SubmitMode', $data);
196
            }
197
        }
198
    }
199
200
    /**
201
     * Forwards the request to a different controller and action based on the provided URI.
202
     *
203
     * @param string $uri The URI to forward to.
204
     * @return void
205
     */
206
    protected function forward(string $uri): void
207
    {
208
        $uriParts = explode('/', $uri);
209
        $params = array_slice($uriParts, 2);
210
211
        $this->dispatcher->forward(
212
            [
213
                'controller' => $uriParts[0],
214
                'action' => $uriParts[1],
215
                'params' => $params,
216
            ]
217
218
        );
219
    }
220
221
    /**
222
     * Sanitizes the caller ID by removing any characters that are not alphanumeric or spaces.
223
     *
224
     * @param string $callerId The caller ID to sanitize.
225
     * @return string The sanitized caller ID.
226
     */
227
    protected function sanitizeCallerId(string $callerId): string
228
    {
229
        return preg_replace('/[^a-zA-Zа-яА-Я0-9 ]/ui', '', $callerId);
230
    }
231
232
    /**
233
     * Sorts array by priority field
234
     *
235
     * @param $a
236
     * @param $b
237
     *
238
     * @return int|null
239
     */
240
    protected function sortArrayByPriority($a, $b): ?int
241
    {
242
        if (is_array($a)) {
243
            $a = (int)$a['priority'];
244
        } else {
245
            $a = (int)$a->priority;
246
        }
247
248
        if (is_array($b)) {
249
            $b = (int)$b['priority'];
250
        } else {
251
            $b = (int)$b->priority;
252
        }
253
254
        if ($a === $b) {
255
            return 0;
256
        } else {
257
            return ($a < $b) ? -1 : 1;
258
        }
259
    }
260
261
    /**
262
     * Sets the last Sentry event ID.
263
     *
264
     * @return \Sentry\EventId|null The last Sentry event ID, or null if metrics sending is disabled.
265
     */
266
    private function setLastSentryEventId(): ?\Sentry\EventId
267
    {
268
        $result = null;
269
        // Allow anonymous statistics collection for JS code
270
        if (PbxSettings::getValueByKey('SendMetrics') === '1') {
271
            touch('/etc/sendmetrics');
272
            $result = SentrySdk::getCurrentHub()->getLastEventId();
273
        } elseif (file_exists('/etc/sendmetrics')) {
274
            unlink('/etc/sendmetrics');
275
        }
276
        return $result;
277
    }
278
279
    /**
280
     *  Returns the unique ID of the module parsing controller namespace;
281
     * @return string
282
     */
283
    private function getModuleUniqueId():string
284
    {
285
        // Split the namespace into an array using the backslash as a separator
286
        $parts = explode('\\', get_class($this));
287
288
        // Get the second part of the namespace
289
        return $parts[1];
290
    }
291
292
    /**
293
     * Save an entity and handle success or error messages.
294
     *
295
     * @param mixed $entity The entity to be saved.
296
     * @return bool True if the entity was successfully saved, false otherwise.
297
     */
298
    protected function saveEntity($entity): bool
299
    {
300
        $success = $entity->save();
301
302
        if (!$success) {
303
            $errors = $entity->getMessages();
304
            $this->flash->error(implode('<br>', $errors));
305
        } elseif (!$this->request->isAjax()) {
306
            $this->flash->success($this->translation->_('ms_SuccessfulSaved'));
307
        }
308
309
        if ($this->request->isAjax()) {
310
            $this->view->success = $success;
311
        }
312
313
        return $success;
314
    }
315
}
316