Passed
Push — master ( 6042d7...377078 )
by Mihail
04:38
created

Main::actionDeleteroute()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 10
nc 2
nop 0
dl 0
loc 16
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Apps\Controller\Admin;
4
5
use Apps\ActiveRecord\Session;
6
use Apps\Model\Admin\Main\EntityDeleteRoute;
7
use Apps\Model\Admin\Main\EntityUpdate;
8
use Apps\Model\Admin\Main\FormAddRoute;
9
use Apps\Model\Admin\Main\FormSettings;
10
use Apps\Model\Admin\Main\FormUpdateDatabase;
11
use Apps\Model\Admin\Main\FormUpdateDownload;
12
use Apps\Model\Install\Main\EntityCheck;
13
use Extend\Core\Arch\AdminController;
14
use Extend\Version;
15
use Ffcms\Core\App;
16
use Ffcms\Core\Exception\SyntaxException;
17
use Ffcms\Core\Helper\Environment;
18
use Ffcms\Core\Helper\FileSystem\Directory;
19
use Ffcms\Core\Helper\FileSystem\File;
20
use Ffcms\Core\Helper\Type\Str;
21
use Ffcms\Core\Helper\Url;
22
23
/**
24
 * Class Main. Admin main controller - index page, settings, file manager, security and etc.
25
 * @package Apps\Controller\Admin
26
 */
27
class Main extends AdminController
28
{
29
    public $type = 'app';
30
31
    /**
32
     * Main constructor. Disable parent inheritance of typical app version checking
33
     */
34
    public function __construct()
35
    {
36
        parent::__construct(false);
37
    }
38
39
    /**
40
     * Index page of admin dashboard
41
     * @return string
42
     * @throws \Ffcms\Core\Exception\SyntaxException
43
     * @throws \Ffcms\Core\Exception\NativeException
44
     */
45
    public function actionIndex()
46
    {
47
        // cache some data
48
        $rootSize = App::$Cache->get('root.size');
49
        if ($rootSize === null) {
50
            $rootSize = round(Directory::getSize('/') / (1024*1000), 2) . ' mb';
51
            App::$Cache->set('root.size', $rootSize, 86400); // 24 hours caching = 60 * 60 * 24
52
        }
53
        $loadAvg = App::$Cache->get('load.average');
54
        if ($loadAvg === null) {
55
            $loadAvg = Environment::loadAverage();
56
            App::$Cache->set('load.average', $loadAvg, 60*5); // 5 min cache
57
        }
58
59
        // prepare system statistic
60
        $stats = [
61
            'ff_version' => Version::VERSION . ' (' . Version::DATE . ')',
62
            'php_version' => Environment::phpVersion() . ' (' . Environment::phpSAPI() . ')',
63
            'os_name' => Environment::osName(),
64
            'database_name' => App::$Database->connection()->getDatabaseName() . ' (' . App::$Database->connection()->getDriverName() . ')',
65
            'file_size' => $rootSize,
66
            'load_avg' => $loadAvg
67
        ];
68
        // check directory chmods and other environment features
69
        $model = new EntityCheck();
70
71
        // render view output
72
        return $this->view->render('index', [
73
            'stats' => $stats,
74
            'check' => $model
75
        ]);
76
    }
77
78
    /**
79
     * Manage settings in web
80
     * @return string
81
     * @throws \Ffcms\Core\Exception\SyntaxException
82
     * @throws \Ffcms\Core\Exception\NativeException
83
     */
84 View Code Duplication
    public function actionSettings()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
85
    {
86
        // init settings model and process post send
87
        $model = new FormSettings(true);
88
        if ($model->send()) {
89
            if ($model->validate()) {
90
                if ($model->makeSave()) {
91
                    // show message about successful save and take system some time ;)
92
                    return $this->view->render('settings_save');
93
                } else {
94
                    App::$Session->getFlashBag()->add('error', __('Configuration file is not writable! Check /Private/Config/ dir and files'));
95
                }
96
            } else {
97
                App::$Session->getFlashBag()->add('error', __('Validation of form data is failed!'));
98
            }
99
        }
100
101
        // render output view
102
        return $this->view->render('settings', [
103
            'model' => $model
104
        ]);
105
    }
106
107
    /**
108
     * Manage files via elFinder
109
     * @return string
110
     * @throws \Ffcms\Core\Exception\SyntaxException
111
     * @throws \Ffcms\Core\Exception\NativeException
112
     */
113
    public function actionFiles()
114
    {
115
        return $this->view->render('files', [
116
            'connector' => App::$Alias->scriptUrl . '/api/main/files?lang=' . $this->request->getLanguage()
117
        ]);
118
    }
119
120
    /**
121
     * Show antivirus view
122
     * @return string
123
     * @throws \Ffcms\Core\Exception\SyntaxException
124
     * @throws \Ffcms\Core\Exception\NativeException
125
     */
126
    public function actionAntivirus()
127
    {
128
        return $this->view->render('antivirus');
129
    }
130
131
    /**
132
     * Set debugging cookie to current user session
133
     */
134
    public function actionDebugcookie()
135
    {
136
        $cookieProperty = App::$Properties->get('debug');
137
        // awesome bullshit in symfony: you can't set cookie headers in (new RedirectResponse) before send().
138
        // never mind what did you do, this is a easy way to do this without bug
139
        //$this->response->headers->setCookie(new Cookie($cookieProperty['cookie']['key'], $cookieProperty['cookie']['value'], strtotime('+1 month'), null, false, true));
0 ignored issues
show
Unused Code Comprehensibility introduced by
77% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
140
        setcookie($cookieProperty['cookie']['key'], $cookieProperty['cookie']['value'], strtotime('+1 month'), null, null, null, true);
141
        $this->response->redirect('/');
142
    }
143
144
    /**
145
     * List available routes
146
     * @return string
147
     * @throws \Ffcms\Core\Exception\SyntaxException
148
     * @throws \Ffcms\Core\Exception\NativeException
149
     */
150
    public function actionRouting()
151
    {
152
        $routingMap = App::$Properties->getAll('Routing');
153
154
        return $this->view->render('routing', [
155
            'routes' => $routingMap
156
        ]);
157
    }
158
159
    /**
160
     * Show add form for routing
161
     * @return string
162
     * @throws \Ffcms\Core\Exception\SyntaxException
163
     * @throws \Ffcms\Core\Exception\NativeException
164
     */
165
    public function actionAddroute()
166
    {
167
        $model = new FormAddRoute(true);
168
        
169
        if (!File::exist('/Private/Config/Routing.php') || !File::writable('/Private/Config/Routing.php')) {
170
            App::$Session->getFlashBag()->add('error', __('Routing configuration file is not allowed to write: /Private/Config/Routing.php'));
171
        } elseif ($model->send() && $model->validate()) {
172
            $model->save();
173
            return $this->view->render('add_route_save');
174
        }
175
176
        return $this->view->render('add_route', [
177
            'model' => $model
178
        ]);
179
    }
180
181
    /**
182
     * Delete scheme route
183
     * @throws SyntaxException
184
     * @return string
185
     * @throws \Ffcms\Core\Exception\NativeException
186
     */
187
    public function actionDeleteroute()
188
    {
189
        $type = (string)$this->request->query->get('type');
190
        $loader = (string)$this->request->query->get('loader');
191
        $source = Str::lowerCase((string)$this->request->query->get('path'));
192
193
        $model = new EntityDeleteRoute($type, $loader, $source);
194
        if ($model->send() && $model->validate()) {
195
            $model->make();
196
            return $this->view->render('delete_route_save');
197
        }
198
199
        return $this->view->render('delete_route', [
200
            'model' => $model
201
        ]);
202
    }
203
204
    /**
205
     * Clear cached data
206
     * @return string
207
     * @throws \Ffcms\Core\Exception\NativeException
208
     * @throws SyntaxException
209
     */
210
    public function actionCache()
211
    {
212
        $stats = App::$Cache->stats();
213
        // get size in mb from cache stats
214
        $size = round((int)$stats['size'] / (1024*1024), 2);
215
216
        // check if submited
217 View Code Duplication
        if ($this->request->request->get('clearcache', false)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
218
            // clear cache
219
            App::$Cache->clean();
220
            // add notification & redirect
221
            App::$Session->getFlashBag()->add('success', __('Cache cleared successfully'));
222
            $this->response->redirect('/');
223
        }
224
225
        // render output view
226
        return $this->view->render('clear_cache', [
227
            'size' => $size
228
        ]);
229
    }
230
231
    /**
232
     * Clear all sessions data
233
     * @return string
234
     * @throws \Ffcms\Core\Exception\NativeException
235
     * @throws SyntaxException
236
     */
237
    public function actionSessions()
238
    {
239
        // get all sessions data
240
        $sessions = Session::all();
241
242
        // check if action is submited
243 View Code Duplication
        if ($this->request->request->get('clearsessions', false)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
244
            // truncate table
245
            App::$Database->table('sessions')->truncate();
246
            // add notification and make redirect to main
247
            App::$Session->getFlashBag()->add('success', __('Sessions cleared successfully'));
248
            $this->response->redirect('/');
249
        }
250
251
        // render output view
252
        return $this->view->render('clear_sessions', [
253
            'count' => $sessions->count()
254
        ]);
255
    }
256
257
    /**
258
     * Make system update
259
     * @return string
260
     * @throws \Ffcms\Core\Exception\SyntaxException
261
     * @throws \Ffcms\Core\Exception\NativeException
262
     */
263
    public function actionUpdates()
264
    {
265
        // initialize models - entity, database, download
266
        $entityModel = new EntityUpdate();
267
        $dbModel = new FormUpdateDatabase($entityModel->dbVersion, $entityModel->scriptVersion);
268
        $downloadModel = new FormUpdateDownload($entityModel->lastInfo['download_url'], $entityModel->lastVersion);
269
270
        // find files with sql queries to update if required
271
        if (!$entityModel->versionsEqual) {
272
            $dbModel->findUpdateFiles();
273
            // if submit is pressed make update
274
            if ($dbModel->send() && $dbModel->validate()) {
275
                $dbModel->make();
276
                App::$Session->getFlashBag()->add('success', __('Database updates are successful installed'));
277
                App::$Response->redirect(Url::to(['main/updates']));
0 ignored issues
show
Documentation introduced by
array('main/updates') is of type array<integer,string,{"0":"string"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
278
            }
279
        } elseif ($entityModel->haveRemoteNew) { // download full compiled .zip archive & extract files
280
            if ($downloadModel->send()) {
281
                if ($downloadModel->make()) {
282
                    App::$Session->getFlashBag()->add('success', __('Archive with new update are successful downloaded and extracted. Please refresh this page and update database if required'));
283
                } else {
284
                    App::$Session->getFlashBag()->add('error', __('In process of downloading and extracting update archive error is occurred. Something gonna wrong'));
285
                }
286
            }
287
        }
288
289
        return $this->view->render('updates', [
290
            'entityModel' => $entityModel,
291
            'dbModel' => $dbModel,
292
            'downloadModel' => $downloadModel
293
        ]);
294
    }
295
}