Passed
Push — develop ( 16b665...d246a9 )
by Felipe
05:54
created

ViewManager::maybeRenderIframes()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 10
c 1
b 0
f 0
nc 3
nop 3
dl 0
loc 19
rs 9.9332
1
<?php
2
3
/**
4
 * PHPPgAdmin 6.0.0
5
 */
6
7
namespace PHPPgAdmin;
8
9
/**
10
 * @file
11
 * Class to hold various commonly used functions
12
 *
13
 * Id: Misc.php,v 1.171 2008/03/17 21:35:48 ioguix Exp $
14
 */
15
16
/**
17
 * Class to hold various commonly used functions.
18
 *
19
 * Release: Misc.php,v 1.171 2008/03/17 21:35:48 ioguix Exp $
20
 */
21
class ViewManager extends \Slim\Views\Twig
22
{
23
    use \PHPPgAdmin\Traits\HelperTrait;
24
25
    /**
26
     * @var string
27
     */
28
    const BASE_PATH = ContainerUtils::BASE_PATH;
29
30
    /**
31
     * @var string
32
     */
33
    const THEME_PATH = ContainerUtils::THEME_PATH;
34
    /**
35
     * @var string
36
     */
37
    const SUBFOLDER = ContainerUtils::SUBFOLDER;
38
    /**
39
     * @var string
40
     */
41
    const DEBUGMODE = ContainerUtils::DEBUGMODE;
42
43
    public $appLangFiles = [];
44
45
    public $appName = '';
46
47
    public $appVersion = '';
48
49
    public $form = '';
50
51
    public $href = '';
52
53
    public $lang = [];
54
55
    public $conf;
56
57
    public $phpMinVer;
58
59
    public $postgresqlMinVer;
60
61
    public $view;
62
63
    /**
64
     * @var \PHPPgAdmin\Misc
65
     */
66
    public $misc;
67
68
    protected $container;
69
70
    private $_connection;
0 ignored issues
show
introduced by
The private property $_connection is not used, and could be removed.
Loading history...
71
72
    private $_no_db_connection = false;
0 ignored issues
show
introduced by
The private property $_no_db_connection is not used, and could be removed.
Loading history...
73
74
    private $_reload_browser = false;
0 ignored issues
show
introduced by
The private property $_reload_browser is not used, and could be removed.
Loading history...
75
76
    private $_data;
0 ignored issues
show
introduced by
The private property $_data is not used, and could be removed.
Loading history...
77
78
    private $_database;
0 ignored issues
show
introduced by
The private property $_database is not used, and could be removed.
Loading history...
79
80
    private $_server_id;
0 ignored issues
show
introduced by
The private property $_server_id is not used, and could be removed.
Loading history...
81
82
    private $_server_info;
0 ignored issues
show
introduced by
The private property $_server_info is not used, and could be removed.
Loading history...
83
84
    private $_error_msg = '';
0 ignored issues
show
introduced by
The private property $_error_msg is not used, and could be removed.
Loading history...
85
86
    private static $instance = null;
0 ignored issues
show
introduced by
The private property $instance is not used, and could be removed.
Loading history...
Coding Style introduced by
Private member variable "instance" must be prefixed with an underscore
Loading history...
87
88
    /**
89
     * @param \Slim\Container $container The container
0 ignored issues
show
Coding Style introduced by
Doc comment for parameter $container does not match actual variable name $path
Loading history...
90
     * @param mixed           $path
0 ignored issues
show
Coding Style introduced by
Doc comment for parameter $path does not match actual variable name $settings
Loading history...
91
     * @param mixed           $settings
0 ignored issues
show
Coding Style introduced by
Doc comment for parameter $settings does not match actual variable name $c
Loading history...
92
     * @param \Slim\Container $c
93
     */
94
    public function __construct($path, $settings, \Slim\Container $c)
95
    {
96
        $this->lang = $c->get('lang');
97
        $this->conf = $c->get('conf');
98
        $this->misc = $c->get('misc');
99
        parent::__construct($path, $settings);
100
        $this->container = $c;
101
        $environment = $c->get('environment');
102
        $base_script_trailing_str = \mb_substr($environment['SCRIPT_NAME'], 1);
103
        $request_basepath = $c['request']->getUri()->getBasePath();
104
        // Instantiate and add Slim specific extension
105
        $basePath = \rtrim(\str_ireplace($base_script_trailing_str, '', $request_basepath), '/');
106
107
        $this->addExtension(new \Slim\Views\TwigExtension($c['router'], $basePath));
108
109
        $this->offsetSet('subfolder', self::SUBFOLDER);
110
        $this->offsetSet('theme', $this->misc->getConf('theme'));
111
        $this->offsetSet('Favicon', $this->icon('Favicon'));
112
        $this->offsetSet('Introduction', $this->icon('Introduction'));
113
        $this->offsetSet('lang', $this->lang);
114
115
        $this->offsetSet('applangdir', $this->lang['applangdir']);
116
117
        $this->offsetSet('appName', $c->get('settings')['appName']);
118
119
        $_theme = $this->getTheme($this->conf, $this->misc->getServerInfo());
120
121
        if (null !== $_theme && isset($_SESSION)) {
122
            /* save the selected theme in cookie for a year */
123
            \setcookie('ppaTheme', $_theme, \time() + 31536000, '/');
124
            $_SESSION['ppaTheme'] = $_theme;
125
            $this->misc->setConf('theme', $_theme);
126
        }
127
    }
128
129
    public function maybeRenderIframes($response, $subject, $query_string)
130
    {
131
        $c = $this->getContainer();
132
133
        $in_test = $this->offsetGet('in_test');
134
135
        if ('1' === $in_test) {
136
            $className = '\PHPPgAdmin\Controller\\' . \ucfirst($subject) . 'Controller';
137
            $controller = new $className($c);
138
139
            return $controller->render();
140
        }
141
142
        $viewVars = [
143
            'url' => '/src/views/' . $subject . ($query_string ? '?' . $query_string : ''),
144
            'headertemplate' => 'header.twig',
145
        ];
146
147
        return $this->render($response, 'iframe_view.twig', $viewVars);
148
    }
149
150
    /**
151
     * Gets the theme from
152
     * 1. The $_REQUEST global (when it's chosen from start screen)
153
     * 2. Server specific config theme 3.- $_SESSION global (subsequent requests after 1.) 4.- $_COOKIE global (mostly
154
     *    fallback for $_SESSION after 1.- and 3.-) 5.- theme as set in config 6.- 'default' theme.
155
     *
156
     * @param array      $conf         The conf
157
     * @param null|mixed $_server_info
158
     *
159
     * @return string the theme
160
     */
161
    public function getTheme(array $conf, $_server_info = null)
162
    {
163
        $_theme = null;
164
        // List of themes
165
        $themefolders = $this->getThemeFolders();
166
        // Check if theme is in $_REQUEST, $_SESSION or $_COOKIE
167
        // 1.- First priority: $_REQUEST, this happens when you use the selector
168
        if (\array_key_exists('theme', $_REQUEST) &&
169
            \array_key_exists($_REQUEST['theme'], $themefolders)) {
170
            $_theme = $_REQUEST['theme'];
171
        } elseif ( // otherwise, see if there's a theme associated with this particular server
0 ignored issues
show
Coding Style introduced by
First condition of a multi-line IF statement must directly follow the opening parenthesis
Loading history...
172
            null !== $_server_info &&
173
            \array_key_exists('theme', $_server_info) &&
174
            \is_string($_server_info['theme']) &&
175
            \array_key_exists($_COOKIE['ppaTheme'], $themefolders)) {
176
            $_theme = $_server_info['theme'];
177
        } elseif (isset($_SESSION) && \array_key_exists('ppaTheme', $_SESSION) &&
178
            \array_key_exists($_SESSION['ppaTheme'], $themefolders)) {
179
            // otherwise check $_SESSION
180
            $_theme = $_SESSION['ppaTheme'];
181
        } elseif (\array_key_exists('ppaTheme', $_COOKIE) &&
182
            \array_key_exists($_COOKIE['ppaTheme'], $themefolders)) {
183
            // oterwise check $_COOKIE
184
            $_theme = $_COOKIE['ppaTheme'];
185
        } elseif ( // see if there's a valid theme set in config file
0 ignored issues
show
Coding Style introduced by
First condition of a multi-line IF statement must directly follow the opening parenthesis
Loading history...
186
            \array_key_exists('theme', $conf) &&
187
            \is_string($conf['theme']) &&
188
            \array_key_exists($conf['theme'], $themefolders)) {
189
            $_theme = $conf['theme'];
190
        } else {
191
            // okay then, use default theme
192
            $_theme = 'default';
193
        }
194
195
        return $_theme;
196
    }
197
198
    /**
199
     * Sets the form tracking variable.
200
     */
201
    public function setForm()
202
    {
203
        $form = [];
204
205
        if ($this->container->server) {
206
            $form[] = \sprintf(
207
                '<input type="hidden" name="%s" value="%s" />',
208
                'server',
209
                \htmlspecialchars($this->container->server)
210
            );
211
        }
212
213
        if ($this->container->database) {
214
            $form[] = \sprintf(
215
                '<input type="hidden" name="%s" value="%s" />',
216
                'database',
217
                \htmlspecialchars($this->container->database)
218
            );
219
        }
220
221
        if ($this->container->schema) {
222
            $form[] = \sprintf(
223
                '<input type="hidden" name="%s" value="%s" />',
224
                'schema',
225
                \htmlspecialchars($this->container->schema)
226
            );
227
        }
228
        $this->form = \implode("\n", $form);
229
230
        return $this->form;
231
    }
232
233
    /**
234
     * Displays link to the context help.
235
     *
236
     * @param string $str      the string that the context help is related to (already escaped)
237
     * @param string $help     help section identifier
238
     * @param bool   $do_print true to echo, false to return
239
     */
240
    public function printHelp($str, $help = null, $do_print = true)
241
    {
242
        if (null !== $help) {
243
            $helplink = $this->getHelpLink($help);
244
            $str .= '<a class="help" href="' . $helplink . '" title="' . $this->lang['strhelp'] . '" target="phppgadminhelp">';
245
            $str .= $this->lang['strhelpicon'] . '</a>';
246
        }
247
248
        if ($do_print) {
249
            echo $str;
250
        } else {
251
            return $str;
252
        }
253
    }
254
255
    /**
256
     * Gets the help link.
257
     *
258
     * @param string $help The help subject
259
     *
260
     * @return string the help link
261
     */
262
    public function getHelpLink($help)
263
    {
264
        return \htmlspecialchars(
265
            $this->getSubfolder('help?help=') .
266
            \urlencode($help) .
267
            '&server=' .
268
            \urlencode($this->misc->getServerId())
269
        );
270
    }
271
272
    public function icon($icon)
273
    {
274
        if (!\is_string($icon)) {
275
            return '';
276
        }
277
278
        $theme = $this->conf['theme'];
279
        $path = 'assets/images/themes';
280
        $default_icon = \sprintf('%s/%s/default/DisconnectedServer.png', self::SUBFOLDER, $path);
281
282
        if (\is_readable(\sprintf('%s/%s/%s/%s.png', self::BASE_PATH, $path, $theme, $icon))) {
283
            return \sprintf('%s/%s/%s/%s.png', self::SUBFOLDER, $path, $theme, $icon);
284
        }
285
286
        if (\is_readable(\sprintf('%s/%s/%s/%s.gif', self::BASE_PATH, $path, $theme, $icon))) {
287
            return \sprintf('%s/%s/%s/%s.gif', self::SUBFOLDER, $path, $theme, $icon);
288
        }
289
290
        if (\is_readable(\sprintf('%s/%s/%s/%s.ico', self::BASE_PATH, $path, $theme, $icon))) {
291
            return \sprintf('%s/%s/%s/%s.ico', self::SUBFOLDER, $path, $theme, $icon);
292
        }
293
294
        if (\is_readable(\sprintf('%s/%s/default/%s.png', self::BASE_PATH, $path, $icon))) {
295
            return \sprintf('%s/%s/default/%s.png', self::SUBFOLDER, $path, $icon);
296
        }
297
298
        if (\is_readable(\sprintf('%s/%s/default/%s.gif', self::BASE_PATH, $path, $icon))) {
299
            return \sprintf('%s/%s/default/%s.gif', self::SUBFOLDER, $path, $icon);
300
        }
301
302
        if (\is_readable(\sprintf('%s/%s/default/%s.ico', self::BASE_PATH, $path, $icon))) {
303
            return \sprintf('%s/%s/default/%s.ico', self::SUBFOLDER, $path, $icon);
304
        }
305
306
        return $default_icon;
307
    }
308
309
    private function getContainer()
310
    {
311
        return $this->container;
312
    }
313
314
    /**
315
     * Traverse THEME_PATH, consider as theme folders those which
316
     * contain a `global.css` stylesheet.
317
     *
318
     * @return array the theme folders
319
     */
320
    private function getThemeFolders()
321
    {
322
        // no THEME_PATH (how?) then return empty array
323
        if (!$gestor = \opendir(self::THEME_PATH)) {
324
            \closedir($gestor);
0 ignored issues
show
Bug introduced by
It seems like $gestor can also be of type false; however, parameter $dir_handle of closedir() does only seem to accept resource, 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

324
            \closedir(/** @scrutinizer ignore-type */ $gestor);
Loading history...
325
326
            return [];
327
        }
328
        $themefolders = [];
329
330
        /* This is the right way to iterate on a folder */
331
        while (false !== ($foldername = \readdir($gestor))) {
332
            if ('.' === $foldername || '..' === $foldername) {
333
                continue;
334
            }
335
336
            $folderpath = \sprintf('%s%s%s', self::THEME_PATH, \DIRECTORY_SEPARATOR, $foldername);
337
            $stylesheet = \sprintf('%s%s%s', $folderpath, \DIRECTORY_SEPARATOR, 'global.css');
338
            // if $folderpath if indeed a folder and contains a global.css file, then it's a theme
339
            if (\is_dir($folderpath) &&
340
                \is_file($stylesheet)) {
341
                $themefolders[$foldername] = $folderpath;
342
            }
343
        }
344
345
        \closedir($gestor);
346
347
        return $themefolders;
348
    }
349
}
350