Passed
Push — develop ( 82ab63...3ea9cd )
by Nikolay
05:40
created

BaseController::setLastSentryEventId()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 7
c 0
b 0
f 0
dl 0
loc 11
rs 10
cc 3
nc 3
nop 0
1
<?php
2
/*
3
 * MikoPBX - free phone system for small business
4
 * Copyright (C) 2017-2020 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\Models\{PbxExtensionModules, PbxSettings};
23
use Phalcon\Http\ResponseInterface;
24
use Phalcon\Mvc\{Controller, View};
25
use Phalcon\Tag;
26
use Phalcon\Text;
27
use Sentry\SentrySdk;
28
29
/**
30
 * @property \Phalcon\Session\Manager session
31
 * @property \MikoPBX\Common\Providers\TranslationProvider translation
32
 * @property string language
33
 * @property bool showModuleStatusToggle if false it hides status toggle on current UI page
34
 * @property \MikoPBX\AdminCabinet\Library\Elements elements
35
 * @property \Phalcon\Flash\Session flash
36
 * @property \Phalcon\Tag tag
37
 * @property \Phalcon\Config\Adapter\Json config
38
 * @property \Phalcon\Logger loggerAuth
39
 */
40
class BaseController extends Controller
41
{
42
    protected string $actionName;
43
    protected string $controllerName;
44
    protected string $controllerNameUnCamelized;
45
    protected bool $isExternalModuleController;
46
47
    /**
48
     * Initializes base class
49
     */
50
    public function initialize(): void
51
    {
52
        $this->actionName = $this->dispatcher->getActionName();
53
        $this->controllerName = Text::camelize($this->dispatcher->getControllerName(), '_');
54
        $this->controllerNameUnCamelized = Text::uncamelize($this->controllerName, '-');
55
        $this->isExternalModuleController = str_starts_with($this->dispatcher->getNamespaceName(), '\\Module');
56
57
        if ($this->request->isAjax() === false) {
58
            $this->prepareView();
59
        }
60
    }
61
62
    /**
63
     * Prepares some environments to every controller and view
64
     *
65
     */
66
    protected function prepareView(): void
67
    {
68
        date_default_timezone_set(PbxSettings::getValueByKey('PBXTimezone'));
69
        $this->view->PBXVersion = PbxSettings::getValueByKey('PBXVersion');
70
        $this->view->MetaTegHeadDescription = $this->translation->_('MetategHeadDescription');
71
        $this->view->isExternalModuleController = $this->isExternalModuleController;
72
        if ($this->session->has(SessionController::SESSION_ID)) {
73
            $this->view->PBXLicense = PbxSettings::getValueByKey('PBXLicense');
74
        } else {
75
            $this->view->PBXLicense = '';
76
        }
77
        $this->view->urlToWiki = "https://wiki.mikopbx.com/{$this->controllerNameUnCamelized}";
78
        if ($this->language === 'ru') {
79
            $this->view->urlToSupport = 'https://www.mikopbx.ru/support/?fromPBX=true';
80
        } else {
81
            $this->view->urlToSupport = 'https://www.mikopbx.com/support/?fromPBX=true';
82
        }
83
84
        $this->view->WebAdminLanguage = PbxSettings::getValueByKey('WebAdminLanguage');
85
        $this->view->AvailableLanguages = json_encode($this->elements->getAvailableWebAdminLanguages());
86
        $this->view->submitMode = $this->session->get('SubmitMode') ?? 'SaveSettings';
87
        $this->view->lastSentryEventId = $this->setLastSentryEventId();
88
89
        $title = 'MikoPBX';
90
        switch ($this->actionName) {
91
            case'index':
92
            case'delete':
93
            case'save':
94
            case'modify':
95
            case'*** WITHOUT ACTION ***':
96
                $title .= '|' . $this->translation->_("Breadcrumb{$this->controllerName}");
97
                break;
98
            default:
99
                $title .= '|' . $this->translation->_("Breadcrumb{$this->controllerName}{$this->actionName}");
100
        }
101
        Tag::setTitle($title);
102
        $this->view->t = $this->translation;
103
        $this->view->debugMode = $this->config->path('adminApplication.debugMode');
104
        $this->view->urlToLogo = $this->url->get('assets/img/logo-mikopbx.svg');
105
        $this->view->urlToController = $this->url->get($this->controllerNameUnCamelized);
106
        $this->view->represent = '';
107
108
        // Add module variables into view
109
        if ($this->isExternalModuleController) {
110
            /** @var PbxExtensionModules $module */
111
            $module = PbxExtensionModules::findFirstByUniqid($this->controllerName);
112
            if ($module === null) {
113
                $module = new PbxExtensionModules();
114
                $module->disabled = '1';
115
                $module->name = 'Unknown module';
116
            }
117
            $this->view->setVar('module', $module);
118
            // If it is module we have to use another volt template
119
            $this->view->setVar('globalModuleUniqueId', $module->uniqid);
120
            $this->view->setTemplateAfter('modules');
121
        } else {
122
            $this->view->setVar('globalModuleUniqueId', '');
123
            $this->view->setTemplateAfter('main');
124
        }
125
    }
126
127
    /**
128
     * Changes the AJAX response by expected format
129
     *
130
     * @return \Phalcon\Http\ResponseInterface
131
     */
132
    public function afterExecuteRoute(): ResponseInterface
133
    {
134
        if ($this->request->isAjax() === true) {
135
            $this->view->setRenderLevel(View::LEVEL_NO_RENDER);
136
            $this->response->setContentType('application/json', 'UTF-8');
137
            $data = $this->view->getParamsToView();
138
139
            /* Set global params if is not set in controller/action */
140
            if (isset($data['raw_response'])) {
141
                $result = $data['raw_response'];
142
            } else {
143
                $data['success'] = $data['success'] ?? true;
144
                $data['reload'] = $data['reload'] ?? false;
145
                $data['message'] = $data['message'] ?? $this->flash->getMessages();
146
147
                // Let's add information about the last error to display a dialog window for the user.
148
                if (file_exists('/etc/sendmetrics')) {
149
                    $data['lastSentryEventId'] = SentrySdk::getCurrentHub()->getLastEventId();
150
                }
151
                $result = json_encode($data);
152
            }
153
            $this->response->setContent($result);
154
        }
155
156
        return $this->response->send();
157
    }
158
159
    /**
160
     * Callback before execute any route
161
     */
162
    public function beforeExecuteRoute(): void
163
    {
164
        if ($this->request->isPost()) {
165
            $data = $this->request->getPost('submitMode');
166
            if (!empty($data)) {
167
                $this->session->set('SubmitMode', $data);
168
            }
169
        }
170
    }
171
172
    /**
173
     * Change page without reload browser page
174
     *
175
     * @param string $uri
176
     */
177
    protected function forward(string $uri): void
178
    {
179
        $uriParts = explode('/', $uri);
180
        $params = array_slice($uriParts, 2);
181
182
        $this->dispatcher->forward(
183
            [
184
                'controller' => $uriParts[0],
185
                'action' => $uriParts[1],
186
                'params' => $params,
187
            ]
188
189
        );
190
    }
191
192
    /**
193
     * Removes all dangerous symbols from CallerID
194
     * @param string $callerId
195
     *
196
     * @return string
197
     */
198
    protected function sanitizeCallerId(string $callerId): string
199
    {
200
        return preg_replace('/[^a-zA-Zа-яА-Я0-9 ]/ui', '', $callerId);
201
    }
202
203
    /**
204
     * Sorts array by priority field
205
     *
206
     * @param $a
207
     * @param $b
208
     *
209
     * @return int|null
210
     */
211
    protected function sortArrayByPriority($a, $b): ?int
212
    {
213
        if (is_array($a)) {
214
            $a = (int)$a['priority'];
215
        } else {
216
            $a = (int)$a->priority;
217
        }
218
219
        if (is_array($b)) {
220
            $b = (int)$b['priority'];
221
        } else {
222
            $b = (int)$b->priority;
223
        }
224
225
        if ($a === $b) {
226
            return 0;
227
        } else {
228
            return ($a < $b) ? -1 : 1;
229
        }
230
    }
231
232
    /**
233
     * Prepares Sentry parameters
234
     *
235
     * @return \Sentry\EventId|null
236
     */
237
    private function setLastSentryEventId(): ?\Sentry\EventId
238
    {
239
        $result = null;
240
        // Allow anonymous statistics collection for JS code
241
        if (PbxSettings::getValueByKey('SendMetrics') === '1') {
242
            touch('/etc/sendmetrics');
243
            $result = SentrySdk::getCurrentHub()->getLastEventId();
244
        } elseif (file_exists('/etc/sendmetrics')) {
245
            unlink('/etc/sendmetrics');
246
        }
247
        return $result;
248
    }
249
}
250