Passed
Push — develop ( d35452...1b53f1 )
by Nikolay
06:08
created

BaseController::forward()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 10
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
/**
3
 * Copyright (C) MIKO LLC - All Rights Reserved
4
 * Unauthorized copying of this file, via any medium is strictly prohibited
5
 * Proprietary and confidential
6
 * Written by Nikolay Beketov, 6 2018
7
 *
8
 */
9
10
namespace MikoPBX\AdminCabinet\Controllers;
11
12
use MikoPBX\Common\Models\{PbxExtensionModules, PbxSettings};
13
use Phalcon\Mvc\{Controller, Dispatcher, View};
14
use Phalcon\Tag;
15
use Phalcon\Text;
16
use Sentry\SentrySdk;
17
18
19
/**
20
 * @property array                                         sessionRO
21
 * @property \Phalcon\Session\Manager                      session
22
 * @property \MikoPBX\Common\Providers\TranslationProvider translation
23
 * @property string                                        language
24
 * @property \MikoPBX\AdminCabinet\Library\Elements        elements
25
 * @property string                                        moduleName
26
 * @property \Phalcon\Flash\Session                        flash
27
 * @property \Phalcon\Tag                                  tag
28
 * @property \Phalcon\Config\Adapter\Json                  config
29
 */
30
class BaseController extends Controller
31
{
32
    protected $actionName;
33
    protected $controllerName;
34
    protected $controllerNameUnCamelized;
35
36
    /**
37
     * Инициализация базововго класса
38
     */
39
    public function initialize(): void
40
    {
41
        $this->actionName                = $this->dispatcher->getActionName();
42
        $this->controllerName            = Text::camelize($this->dispatcher->getControllerName(), '_');
43
        $this->controllerNameUnCamelized = Text::uncamelize($this->controllerName, '-');
44
45
        $this->moduleName = $this->dispatcher->getModuleName();
46
47
        if ($this->request->isAjax() === false) {
48
            $this->prepareView();
49
        }
50
    }
51
52
    /**
53
     * Инициализирует шаблонизатор View и устанавливает переменные системы для отображения
54
     */
55
    protected function prepareView(): void
56
    {
57
        date_default_timezone_set($this->getSessionData('PBXTimezone'));
58
        $roSession              = $this->sessionRO;
59
        $this->view->PBXVersion = $this->getSessionData('PBXVersion');
60
        if ($roSession !== null && array_key_exists('auth', $roSession)) {
61
            $this->view->SSHPort    = $this->getSessionData('SSHPort');
62
            $this->view->PBXLicense = $this->getSessionData('PBXLicense');
63
        } else {
64
            $this->view->SSHPort    = '';
65
            $this->view->PBXLicense = '';
66
        }
67
        // Кеш версий модулей и атс, для правильной работы АТС при установке модулей
68
        $versionHash = $this->getVersionsHash();
69
        $this->session->set('versionHash', $versionHash);
70
71
        $this->view->WebAdminLanguage   = $this->getSessionData('WebAdminLanguage');
72
        $this->view->AvailableLanguages = json_encode($this->elements->getAvailableWebAdminLanguages());
73
74
        if ($roSession !== null && array_key_exists('SubmitMode', $roSession)) {
75
            $this->view->submitMode = $roSession['SubmitMode'];
76
        } else {
77
            $this->view->submitMode = 'SaveSettings';
78
        }
79
80
        // Добавим версию модуля, если это модуль
81
        if ($this->moduleName === 'PBXExtension') {
82
            $module = PbxExtensionModules::findFirstByUniqid($this->controllerName);
83
            if ($module === null) {
84
                $module           = new PbxExtensionModules();
85
                $module->disabled = '1';
0 ignored issues
show
Documentation Bug introduced by
It seems like '1' of type string is incompatible with the declared type integer|null of property $disabled.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
86
                $module->name     = 'Unknown module';
87
            }
88
            $this->view->module = $module;
89
        }
90
91
        // Разрешим отправку анонимной информации об ошибках
92
        if ($this->getSessionData('SendMetrics') === '1') {
93
            touch('/tmp/sendmetrics');
94
            $this->view->lastSentryEventId = SentrySdk::getCurrentHub()->getLastEventId();
95
        } else {
96
            if (file_exists('/tmp/sendmetrics')) {
97
                unlink('/tmp/sendmetrics');
98
            }
99
            $this->view->lastSentryEventId = null;
100
        }
101
        $title = 'MikoPBX';
102
        switch ($this->actionName) {
103
            case'index':
104
            case'delete':
105
            case'save':
106
            case'modify':
107
            case'*** WITHOUT ACTION ***':
108
                $title .= '|'. $this->translation->_("Breadcrumb{$this->controllerName}");
109
                break;
110
            default:
111
                $title .= '|'. $this->translation->_("Breadcrumb{$this->controllerName}{$this->actionName}");
112
        }
113
        Tag::setTitle($title);
114
        $this->view->t         = $this->translation;
115
        $this->view->debugMode = $this->config->path('adminApplication.debugMode');
116
        $this->view->urlToLogo = $this->url->get('assets/img/logo-mikopbx.svg');
117
        if ($this->language === 'ru') {
118
            $this->view->urlToWiki
119
                = "https://wiki.mikopbx.com/{$this->controllerNameUnCamelized}";
120
            $this->view->urlToSupport
121
                = 'https://www.mikopbx.ru/support/?fromPBX=true';
122
        } else {
123
            $this->view->urlToWiki
124
                = "https://wiki.mikopbx.com/{$this->language}:{$this->controllerNameUnCamelized}";
125
            $this->view->urlToSupport
126
                = 'https://www.mikopbx.com/support/?fromPBX=true';
127
        }
128
129
        $this->view->urlToController = $this->url->get($this->controllerNameUnCamelized);
130
        $this->view->represent       = '';
131
        $this->view->cacheName       = "{$this->controllerName}{$this->actionName}{$this->language}{$versionHash}";
132
133
        // Подключим нужный View
134
        if ($this->moduleName === 'PBXExtension') {
135
            $this->view->setTemplateAfter('modules');
136
        } else {
137
            $this->view->setTemplateAfter('main');
138
        }
139
140
    }
141
142
    /**
143
     * Берет данные из сессии или из базы данных и записывает в кеш
144
     *
145
     * @param $key string параметры сессии
146
     *
147
     * @return string
148
     */
149
    protected function getSessionData($key): string
150
    {
151
        $roSession = $this->sessionRO;
152
        if ($roSession !== null && array_key_exists($key, $roSession) && ! empty($roSession[$key])) {
153
            $value = $roSession[$key];
154
        } else {
155
            $value = PbxSettings::getValueByKey($key);
156
            $this->session->set($key, $value);
157
        }
158
159
        return $value;
160
    }
161
162
    /**
163
     * Генерирует хеш из версий установленных модулей и АТС, для корректного склеивания JS, CSS и локализаций.
164
     *
165
     */
166
    private function getVersionsHash(): string
167
    {
168
        $result          = PbxSettings::getValueByKey('PBXVersion');
169
        $modulesVersions = PbxExtensionModules::find(['columns' => 'id,version']);
170
        foreach ($modulesVersions as $module) {
171
            $result .= "{$module->version}{$module->version}";
172
        }
173
174
        return md5($result);
175
    }
176
177
    /**
178
     * Постобработка запроса
179
     *
180
     * @param \Phalcon\Mvc\Dispatcher $dispatcher
181
     *
182
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
183
     */
184
    public function afterExecuteRoute(Dispatcher $dispatcher)
0 ignored issues
show
Unused Code introduced by
The parameter $dispatcher is not used and could be removed. ( Ignorable by Annotation )

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

184
    public function afterExecuteRoute(/** @scrutinizer ignore-unused */ Dispatcher $dispatcher)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
185
    {
186
        if ($this->request->isAjax() === true) {
187
            $this->view->disableLevel(
0 ignored issues
show
Bug introduced by
The method disableLevel() does not exist on Phalcon\Mvc\ViewInterface. Did you maybe mean disable()? ( Ignorable by Annotation )

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

187
            $this->view->/** @scrutinizer ignore-call */ 
188
                         disableLevel(

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...
188
                [
189
                    View::LEVEL_ACTION_VIEW     => true,
190
                    View::LEVEL_LAYOUT          => true,
191
                    View::LEVEL_MAIN_LAYOUT     => true,
192
                    View::LEVEL_AFTER_TEMPLATE  => true,
193
                    View::LEVEL_BEFORE_TEMPLATE => true,
194
                ]
195
            );
196
            $this->response->setContentType('application/json', 'UTF-8');
197
            $data = $this->view->getParamsToView();
198
199
            /* Set global params if is not set in controller/action */
200
            if (is_array($data) && isset($data['raw_response'])) {
201
                $result = $data['raw_response'];
202
            } elseif (is_array($data)) {
203
                $data['success'] = array_key_exists('success', $data) ? $data['success'] : true;
204
                $data['reload']  = array_key_exists('reload', $data) ? $data['reload'] : false;
205
                $data['message'] = $data['message'] ?? $this->flash->getMessages();
206
207
                // Добавим информацию о последней ошибке для отображения диалогового окна для пользователя
208
                if (file_exists('/tmp/sendmetrics')) {
209
                    $data['lastSentryEventId'] = SentrySdk::getCurrentHub()->getLastEventId();
210
                }
211
                $result = json_encode($data);
212
            } else {
213
                $result = '';
214
            }
215
216
            $this->response->setContent($result);
217
        }
218
219
        return $this->response->send();
220
    }
221
222
    /**
223
     * Перехват события перед обработкой в контроллере
224
     */
225
    public function beforeExecuteRoute(): void
226
    {
227
        if ($this->request->isPost()) {
228
            $data = $this->request->getPost('submitMode');
229
            if ( ! empty($data)) {
230
                $this->session->set('SubmitMode', $data);
231
            }
232
        }
233
    }
234
235
    /**
236
     * Перевод страниц без перезагрузки страниц
237
     *
238
     * @param string $uri
239
     */
240
    protected function forward($uri): void
241
    {
242
        $uriParts = explode('/', $uri);
243
        $params   = array_slice($uriParts, 2);
244
245
        $this->dispatcher->forward(
246
            [
247
                'controller' => $uriParts[0],
248
                'action'     => $uriParts[1],
249
                'params'     => $params,
250
            ]
251
252
        );
253
    }
254
255
    /**
256
     * Remove all dangerous symbols from CallerID
257
     * @param string $callerId
258
     *
259
     * @return string
260
     */
261
    protected function sanitizeCallerId(string $callerId): string
262
    {
263
        return preg_replace('/[^a-zA-Zа-яА-Я0-9 ]/ui', '', $callerId);
264
    }
265
}
266