Passed
Push — master ( a13744...a0b838 )
by Florent
02:41
created

AdminController::save()   A

Complexity

Conditions 6
Paths 10

Size

Total Lines 27
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 0
Metric Value
cc 6
eloc 17
c 3
b 1
f 0
nc 10
nop 2
dl 0
loc 27
rs 9.0777
1
<?php
2
3
/**
4
 *  * Admin controller
5
 *  *
6
 * The file contains all the functions used in all administration panel.
7
 * For admin posts function, please go to the Posts Controller
8
 * For admin pages function, please go to the Pages Controller
9
 *
10
 *  * @category   Controllers
11
 *  * @package    SuperHive
12
 *  * @author     Florent Kosmala <[email protected]>
13
 *  * @license    https://www.gnu.org/licenses/gpl-3.0.txt GPL-3.0
14
 *  */
15
16
declare(strict_types=1);
17
18
namespace App\Controllers;
19
20
use App\Controllers\CommonController as Common;
21
use Hive\PhpLib\Hive\Condenser as HiveCondenser;
22
use Psr\Container\ContainerInterface;
23
use Psr\Http\Message\ResponseInterface as Response;
24
use Psr\Http\Message\ServerRequestInterface as Request;
25
26
final class AdminController
27
{
28
    private ContainerInterface $app;
29
30
    /**
31
     * Admin part contructor
32
     *
33
     * This constructor is not the same as other controllers.
34
     * Administration need  to control if session exists with good account & encrypted key.
35
     *
36
     * @param \Psr\Container\ContainerInterface $app
37
     */
38
    public function __construct(ContainerInterface $app)
39
    {
40
        $this->app = $app;
41
        $genPosts = new Common($this->app);
42
        $genPosts->genPostsFile();
43
44
        /*
45
         *  Check security in session for admin functions
46
         */
47
        $settings = $this->app->get('settings');
48
        $session = $this->app->get('session');
49
        $cred = unserialize(file_get_contents($this->app->get('password')));
50
        $author = $settings['author'];
51
        $passwd = $cred[$author];
52
53
        /* If sessons keys are not set */
54
        if (! isset($session['sh_author']) || (! isset($session['sh_sign']))) {
55
            header('Location: /login');
56
            die;
57
        }
58
        /* If session keys are not good */
59
        if (($settings['author'] !== $session['sh_author']) || ($passwd !== $session['sh_sign'])) {
60
            header('Location: /login');
61
            die;
62
        }
63
    }
64
65
    /**
66
     *  * Admin index function
67
     *  *
68
     * This function display the admin index with some settings ready to be changed.
69
     * It call the admin save() functionwhen the button is clicked.
70
     *
71
     * @param \Psr\Http\Message\ResponseInterface $response
72
     *
73
     * @return \Psr\Http\Message\ResponseInterface $response
74
     *  */
75
    public function adminIndex(Response $response): Response
76
    {
77
        // Create array from config file
78
        $settings = $this->app->get('settings');
79
        $accountFile = $this->app->get('accountfile');
80
81
        $apiConfig = [
82
            'hiveNode' => $settings['api'],
83
            'debug' => false,
84
        ];
85
        $api = new HiveCondenser($apiConfig);
86
87
        $cache_interval = 300;
88
89
        $current_time = time();
90
        if ((! file_exists($accountFile)) || ($current_time - filemtime($accountFile) > $cache_interval)) {
91
            $result = json_encode($api->getAccounts($settings['author']), JSON_PRETTY_PRINT);
92
            file_put_contents($accountFile, $result);
93
        }
94
95
        $account = json_decode(file_get_contents($accountFile), true);
96
97
        return $this->app->get('view')->render($response, '/admin/admin-index.html', [
98
            'settings' => $settings,
99
            'account' => $account[0],
100
        ]);
101
    }
102
103
    /**
104
     *  * Admin settings function
105
     *  *
106
     * This function display tthe settings page
107
     * This page contains every Superhive settings (not plugins settings)..
108
     *
109
     * @param \Psr\Http\Message\ResponseInterface $response
110
     *
111
     * @return \Psr\Http\Message\ResponseInterface $response
112
     *  */
113
    public function adminSettings(Response $response): Response
114
    {
115
        // Create array from config file
116
        $settings = $this->app->get('settings');
117
        $accountFile = $this->app->get('accountfile');
118
        $langFile = $this->app->get('basedir') . 'resources/languages.json';
119
        $nodesFile = $this->app->get('basedir') . 'resources/nodes.json';
120
121
        $apiConfig = [
122
            'hiveNode' => $settings['api'],
123
            'debug' => false,
124
        ];
125
        $api = new HiveCondenser($apiConfig);
126
127
        $cache_interval = 300;
128
129
        $current_time = time();
130
        if ((! file_exists($accountFile)) || ($current_time - filemtime($accountFile) > $cache_interval)) {
131
            $result = json_encode($api->getAccounts($settings['author']), JSON_PRETTY_PRINT);
132
            file_put_contents($accountFile, $result);
133
        }
134
135
        $account = json_decode(file_get_contents($accountFile), true);
136
        $langs = json_decode(file_get_contents($langFile), true);
137
        $nodes = json_decode(file_get_contents($nodesFile), true);
138
139
        $themes = array_map('basename', glob($this->app->get('themesdir') . '*', GLOB_ONLYDIR));
140
        return $this->app->get('view')->render($response, '/admin/admin-settings.html', [
141
            'settings' => $settings,
142
            'account' => $account[0],
143
            'themes' => $themes,
144
            'languages' => $langs,
145
            'nodes' => $nodes,
146
        ]);
147
    }
148
149
    /**
150
     *  * Admin theme function
151
     *  *
152
     * This function is for the Theme page
153
     *
154
     * @param \Psr\Http\Message\ResponseInterface $response
155
     *
156
     * @return \Psr\Http\Message\ResponseInterface $response
157
     *  */
158
    public function adminThemes(Response $response): Response
159
    {
160
        // Create array from config file
161
        $settings = $this->app->get('settings');
162
163
        $themes = array_map('basename', glob($this->app->get('themesdir') . '*', GLOB_ONLYDIR));
164
        return $this->app->get('view')->render($response, '/admin/admin-themes.html', [
165
            'settings' => $settings,
166
            'themes' => $themes,
167
        ]);
168
    }
169
170
    /**
171
     *  * Admin logout function
172
     *  *
173
     * This function clear ther session, destroy it, and redirect to login page.
174
     *
175
     * @param \Psr\Http\Message\ResponseInterface $response
176
     *
177
     * @return \Psr\Http\Message\ResponseInterface $response
178
     *  */
179
    public function logout(Response $response): Response
180
    {
181
        $session = $this->app->get('session');
182
183
        $session->delete('sh_author');
184
        $session->delete('sh_sign');
185
        $session::destroy();
186
187
        return $response->withHeader('Location', '/login')->withStatus(302);
188
    }
189
190
    /**
191
     *  * Admin save function
192
     *  *
193
     * This function Take every fields in the form and convert the into a (human-readable))JSON file.
194
     * the generated file will be save in config folder.
195
     *
196
     * @param \Psr\Http\Message\ServerRequestInterface $request
197
     * @param \Psr\Http\Message\ResponseInterface $response
198
     *
199
     * @return \Psr\Http\Message\ResponseInterface $response
200
     *  */
201
    public function save(Request $request, Response $response): Response
202
    {
203
        $data = $request->getParsedBody();
204
        if (isset($data['redirect'])) {
205
            $redirect = $data['redirect'];
206
        } else $redirect = '/admin/';
207
        $settings = $this->app->get('settings');
208
209
        foreach ($data as $key => $value) {
210
            if(mb_strpos($key, "-") !== false){
211
                $pieces = explode("-", $key);
212
                if (array_key_exists($pieces[1], $settings[$pieces[0]])) {
213
                    $settings[$pieces[0]][$pieces[1]] = $value;
214
                }
215
            } else {
216
                if (array_key_exists($key, $settings)) {
217
                    $settings[$key] = $value;
218
                }
219
            }
220
        }
221
222
        $file = json_encode($settings, JSON_PRETTY_PRINT);
223
        // Create array from config file
224
        file_put_contents($this->app->get('configfile'), $file);
225
        unlink($this->app->get('blogfile'));
226
227
        return $response->withHeader('Location', $redirect)->withStatus(302);
228
    }
229
230
    /**
231
     *  * Admin theme save function
232
     *  *
233
     * This function is for save the theme into the JSON config file
234
     *
235
     * @param string $theme
236
     * @param \Psr\Http\Message\ResponseInterface $response
237
     *
238
     * @return \Psr\Http\Message\ResponseInterface $response
239
     *  */
240
    public function saveTheme(string $theme, Response $response): Response
241
    {
242
        $settings = $this->app->get('settings');
243
        $settings['theme'] = $theme;
244
        $file = json_encode($settings, JSON_PRETTY_PRINT);
245
        file_put_contents($this->app->get('configfile'), $file);
246
        return $response->withHeader('Location', '/admin/themes')->withStatus(302);
247
    }
248
}
249