Test Failed
Push — master ( cd3718...faedb3 )
by Fran
03:03
created

AdminServices::setAdminHeaders()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 0
dl 0
loc 7
ccs 0
cts 6
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
namespace PSFS\services;
3
4
use PSFS\base\config\Config;
5
use PSFS\base\Security;
6
use PSFS\base\Service;
7
use Symfony\Component\Finder\Finder;
8
9
class AdminServices extends Service
10
{
11
12
    /**
13
     * @Injectable
14
     * @var \PSFS\base\config\Config Servicio de configuración
15
     */
16
    protected $config;
17
    /**
18
     * @Injectable
19
     * @var \PSFS\base\Security Servicio de autenticación
20
     */
21
    protected $security;
22
    /**
23
     * @Injectable
24
     * @var \PSFS\base\Template Servicio de gestión de plantillas
25
     */
26
    protected $tpl;
27
28
    /**
29
     * Servicio que devuelve las cabeceras de autenticación
30
     * @return string HTML
31
     */
32
    public function setAdminHeaders()
33
    {
34
        $platform = trim(Config::getInstance()->get('platform.name'));
35
        header('HTTP/1.1 401 Unauthorized');
36
        header('WWW-Authenticate: Basic Realm="' . $platform . '"');
37
        echo t('Zona restringida');
38
        exit();
39
    }
40
41
    /**
42
     * Servicio que devuelve los administradores de la plataforma
43
     * @return array|mixed
44
     */
45 1
    public function getAdmins()
46
    {
47 1
        $admins = $this->security->getAdmins();
48 1
        if (!empty($admins)) {
49
            if (!$this->security->checkAdmin()) {
50
                $this->setAdminHeaders();
51
            }
52
        }
53 1
        $this->parseAdmins($admins);
54 1
        return $admins;
55
    }
56
57
    /**
58
     * Servicio que parsea los administradores para mostrarlos en la gestión de usuarios
59
     * @param array $admins
60
     */
61 1
    private function parseAdmins(&$admins)
62
    {
63 1
        if (!empty($admins)) {
64
            foreach ($admins as &$admin) {
65
                if (isset($admin['profile'])) {
66
                    switch ($admin['profile']) {
67
                        case Security::MANAGER_ID_TOKEN:
68
                            $admin['class'] = 'warning';
69
                            break;
70
                        case Security::ADMIN_ID_TOKEN:
71
                            $admin['class'] = 'info';
72
                            break;
73
                        default:
74
                        case Security::USER_ID_TOKEN:
75
                            $admin['class'] = 'primary';
76
                            break;
77
                    }
78
                } else {
79
                    $admin['class'] = 'primary';
80
                }
81
            }
82
        }
83 1
    }
84
85
    /**
86
     * Servicio que lee los logs y los formatea para listarlos
87
     * @return array
88
     */
89
    public function getLogFiles()
90
    {
91
        $files = new Finder();
92
        $files->files()->in(LOG_DIR)->name('*.log')->sortByModifiedTime();
93
        $logs = array();
94
        /** @var \SplFileInfo $file */
95
        foreach ($files as $file) {
96
            $size = $file->getSize() / 8 / 1024;
97
            $time = date('c', $file->getMTime());
98
            $dateTime = new \DateTime($time);
99
            if (!isset($logs[$dateTime->format('Y')])) {
100
                $logs[$dateTime->format('Y')] = [];
101
            }
102
            $logs[$dateTime->format('Y')][$dateTime->format('m')][$time] = [
103
                'filename' => $file->getFilename(),
104
                'size' => round($size, 3),
105
            ];
106
            krsort($logs[$dateTime->format('Y')][$dateTime->format('m')]);
107
            krsort($logs[$dateTime->format('Y')]);
108
        }
109
        return $logs;
110
    }
111
112
    /**
113
     * Servicio que parsea el fichero de log seleccionado
114
     * @param string|null $selectedLog
115
     *
116
     * @return array
117
     */
118
    public function formatLogFile($selectedLog)
119
    {
120
        $monthOpen = null;
121
        $files = new Finder();
122
        $files->files()->in(LOG_DIR)->name($selectedLog);
123
        $file = $match = null;
124
        $log = array();
125
        foreach($files as $item) {
126
            $file = $item;
127
            $match = $item;
128
            break;
129
        }
130
        /** @var \SplFileInfo $file */
131
        if (null !== $file) {
132
            $time = date('c', $file->getMTime());
133
            $dateTime = new \DateTime($time);
134
            $monthOpen = $dateTime->format('m');
135
            $content = file($file->getPath() . DIRECTORY_SEPARATOR . $file->getFilename());
136
            krsort($content);
0 ignored issues
show
Bug introduced by
It seems like $content can also be of type false; however, parameter $array of krsort() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

136
            krsort(/** @scrutinizer ignore-type */ $content);
Loading history...
137
            $detailLog = array();
138
            foreach ($content as &$line) {
139
                list($line, $detail) = $this->parseLogLine($line, $match);
140
                $detailLog[] = array_merge([
141
                    'log' => $line,
142
                ], $detail);
143
                if (count($detailLog) >= 1000) {
144
                    break;
145
                }
146
            }
147
            unset($line);
148
            $log = $detailLog;
149
        }
150
        return [$log, $monthOpen];
151
    }
152
153
    /**
154
     * Servicio que trata la línea del log para procesarle en el front end
155
     * @param $line
156
     * @param $match
157
     *
158
     * @return array
159
     */
160
    private function parseLogLine($line, $match)
161
    {
162
        $line = preg_replace(array('/^\[(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})\]/'), '<span class="label label-success">$4:$5:$6  $3-$2-$1</span>', $line);
163
        preg_match_all('/\{(.*)\}/', $line, $match);
164
        try {
165
            if (!empty($match[0])) {
166
                $line = str_replace('[]', '', str_replace($match[0][0], '', $line));
167
168
                $detail = json_decode($match[0][0], TRUE);
169
            }
170
            if (empty($detail)) {
171
                $detail = array();
172
            }
173
            preg_match_all('/\>\ (.*):/', $line, $match);
174
175
            $type = isset($match[1][0]) ? $match[1][0] : '';
176
            $type = explode('.', $type);
177
            $type = count($type) > 1 ? $type[1] : $type[0];
178
            switch ($type) {
179
                case 'INFO':
180
                    $detail['type'] = 'success';
181
                    break;
182
                case 'DEBUG':
183
                    $detail['type'] = 'info';
184
                    break;
185
                case 'ERROR':
186
                    $detail['type'] = 'danger';
187
                    break;
188
                case 'WARN':
189
                    $detail['type'] = 'warning';
190
                    break;
191
            }
192
193
        } catch (\Exception $e) {
194
            $detail = [
195
                'type' => 'danger',
196
            ];
197
        }
198
199
        return [$line, $detail];
200
    }
201
}
202