Passed
Push — master ( 47fa0d...b0e5a9 )
by Maurício
07:00
created

Footer   B

Complexity

Total Complexity 52

Size/Duplication

Total Lines 350
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 52
eloc 137
dl 0
loc 350
rs 7.44
c 0
b 0
f 0

13 Methods

Rating   Name   Duplication   Size   Complexity  
A disable() 0 3 1
A __construct() 0 7 1
B getDisplay() 0 59 10
A getDebugMessage() 0 16 5
F getSelfUrl() 0 41 13
B _removeRecursion() 0 15 7
A getScripts() 0 3 1
A setMinimal() 0 3 1
A getErrorMessages() 0 13 2
A setAjax() 0 3 1
A _getDemoMessage() 0 17 2
A _setHistory() 0 13 6
A _getSelfLink() 0 17 2

How to fix   Complexity   

Complex Class

Complex classes like Footer often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Footer, and based on these observations, apply Extract Interface, too.

1
<?php
2
/* vim: set expandtab sw=4 ts=4 sts=4: */
3
/**
4
 * Used to render the footer of PMA's pages
5
 *
6
 * @package PhpMyAdmin
7
 */
8
declare(strict_types=1);
9
10
namespace PhpMyAdmin;
11
12
use Traversable;
13
14
/**
15
 * Class used to output the footer
16
 *
17
 * @package PhpMyAdmin
18
 */
19
class Footer
20
{
21
    /**
22
     * Scripts instance
23
     *
24
     * @access private
25
     * @var Scripts
26
     */
27
    private $_scripts;
28
    /**
29
     * Whether we are servicing an ajax request.
30
     *
31
     * @access private
32
     * @var bool
33
     */
34
    private $_isAjax;
35
    /**
36
     * Whether to only close the BODY and HTML tags
37
     * or also include scripts, errors and links
38
     *
39
     * @access private
40
     * @var bool
41
     */
42
    private $_isMinimal;
43
    /**
44
     * Whether to display anything
45
     *
46
     * @access private
47
     * @var bool
48
     */
49
    private $_isEnabled;
50
51
    /**
52
     * @var Relation
53
     */
54
    private $relation;
55
56
    /**
57
     * @var Template
58
     */
59
    private $template;
60
61
    /**
62
     * Creates a new class instance
63
     */
64
    public function __construct()
65
    {
66
        $this->template = new Template();
67
        $this->_isEnabled = true;
68
        $this->_scripts = new Scripts();
69
        $this->_isMinimal = false;
70
        $this->relation = new Relation($GLOBALS['dbi']);
71
    }
72
73
    /**
74
     * Returns the message for demo server to error messages
75
     *
76
     * @return string
77
     */
78
    private function _getDemoMessage(): string
79
    {
80
        $message = '<a href="/">' . __('phpMyAdmin Demo Server') . '</a>: ';
81
        if (@file_exists(ROOT_PATH . 'revision-info.php')) {
82
            include ROOT_PATH . 'revision-info.php';
83
            $message .= sprintf(
84
                __('Currently running Git revision %1$s from the %2$s branch.'),
85
                '<a target="_blank" rel="noopener noreferrer" href="' . $repobase . $fullrevision . '">'
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $fullrevision seems to be never defined.
Loading history...
Comprehensibility Best Practice introduced by
The variable $repobase seems to be never defined.
Loading history...
86
                . $revision . '</a>',
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $revision seems to be never defined.
Loading history...
87
                '<a target="_blank" rel="noopener noreferrer" href="' . $repobranchbase . $branch . '">'
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $branch seems to be never defined.
Loading history...
Comprehensibility Best Practice introduced by
The variable $repobranchbase seems to be never defined.
Loading history...
88
                . $branch . '</a>'
89
            );
90
        } else {
91
            $message .= __('Git information missing!');
92
        }
93
94
        return Message::notice($message)->getDisplay();
95
    }
96
97
    /**
98
     * Remove recursions and iterator objects from an object
99
     *
100
     * @param object|array $object Object to clean
101
     * @param array        $stack  Stack used to keep track of recursion,
102
     *                             need not be passed for the first time
103
     *
104
     * @return object Reference passed object
105
     */
106
    private static function _removeRecursion(&$object, array $stack = [])
107
    {
108
        if ((is_object($object) || is_array($object)) && $object) {
0 ignored issues
show
introduced by
The condition is_array($object) is always true.
Loading history...
109
            if ($object instanceof Traversable) {
110
                $object = "***ITERATOR***";
111
            } elseif (! in_array($object, $stack, true)) {
112
                $stack[] = $object;
113
                foreach ($object as &$subobject) {
114
                    self::_removeRecursion($subobject, $stack);
115
                }
116
            } else {
117
                $object = "***RECURSION***";
118
            }
119
        }
120
        return $object;
121
    }
122
123
    /**
124
     * Renders the debug messages
125
     *
126
     * @return string
127
     */
128
    public function getDebugMessage(): string
129
    {
130
        $retval = '\'null\'';
131
        if ($GLOBALS['cfg']['DBG']['sql']
132
            && empty($_REQUEST['no_debug'])
133
            && ! empty($_SESSION['debug'])
134
        ) {
135
            // Remove recursions and iterators from $_SESSION['debug']
136
            self::_removeRecursion($_SESSION['debug']);
137
138
            $retval = json_encode($_SESSION['debug']);
139
            $_SESSION['debug'] = [];
140
            return json_last_error() ? '\'false\'' : $retval;
141
        }
142
        $_SESSION['debug'] = [];
143
        return $retval;
144
    }
145
146
    /**
147
     * Returns the url of the current page
148
     *
149
     * @return string
150
     */
151
    public function getSelfUrl(): string
152
    {
153
        $db = isset($GLOBALS['db']) && strlen($GLOBALS['db']) ? $GLOBALS['db'] : '';
154
        $table = isset($GLOBALS['table']) && strlen($GLOBALS['table']) ? $GLOBALS['table'] : '';
155
        $target = isset($_REQUEST['target']) && strlen($_REQUEST['target']) ? $_REQUEST['target'] : '';
156
        $params = [
157
            'db' => $db,
158
            'table' => $table,
159
            'server' => $GLOBALS['server'],
160
            'target' => $target,
161
        ];
162
        // needed for server privileges tabs
163
        if (isset($_GET['viewing_mode'])
164
            && in_array($_GET['viewing_mode'], ['server', 'db', 'table'])
165
        ) {
166
            $params['viewing_mode'] = $_GET['viewing_mode'];
167
        }
168
        /*
169
         * @todo    coming from server_privileges.php, here $db is not set,
170
         *          add the following condition below when that is fixed
171
         *          && $_GET['checkprivsdb'] == $db
172
         */
173
        if (isset($_GET['checkprivsdb'])
174
        ) {
175
            $params['checkprivsdb'] = $_GET['checkprivsdb'];
176
        }
177
        /*
178
         * @todo    coming from server_privileges.php, here $table is not set,
179
         *          add the following condition below when that is fixed
180
         *          && $_REQUEST['checkprivstable'] == $table
181
         */
182
        if (isset($_GET['checkprivstable'])
183
        ) {
184
            $params['checkprivstable'] = $_GET['checkprivstable'];
185
        }
186
        if (isset($_REQUEST['single_table'])
187
            && in_array($_REQUEST['single_table'], [true, false])
188
        ) {
189
            $params['single_table'] = $_REQUEST['single_table'];
190
        }
191
        return basename(Core::getenv('SCRIPT_NAME')) . Url::getCommonRaw($params);
192
    }
193
194
    /**
195
     * Renders the link to open a new page
196
     *
197
     * @param string $url The url of the page
198
     *
199
     * @return string
200
     */
201
    private function _getSelfLink(string $url): string
202
    {
203
        $retval  = '';
204
        $retval .= '<div id="selflink" class="print_ignore">';
205
        $retval .= '<a href="' . htmlspecialchars($url) . '"'
206
            . ' title="' . __('Open new phpMyAdmin window') . '" target="_blank" rel="noopener noreferrer">';
207
        if (Util::showIcons('TabsMode')) {
208
            $retval .= Util::getImage(
209
                'window-new',
210
                __('Open new phpMyAdmin window')
211
            );
212
        } else {
213
            $retval .=  __('Open new phpMyAdmin window');
214
        }
215
        $retval .= '</a>';
216
        $retval .= '</div>';
217
        return $retval;
218
    }
219
220
    /**
221
     * Renders the link to open a new page
222
     *
223
     * @return string
224
     */
225
    public function getErrorMessages(): string
226
    {
227
        $retval = '';
228
        if ($GLOBALS['error_handler']->hasDisplayErrors()) {
229
            $retval .= $GLOBALS['error_handler']->getDispErrors();
230
        }
231
232
        /**
233
         * Report php errors
234
         */
235
        $GLOBALS['error_handler']->reportErrors();
236
237
        return $retval;
238
    }
239
240
    /**
241
     * Saves query in history
242
     *
243
     * @return void
244
     */
245
    private function _setHistory(): void
246
    {
247
        if (! Core::isValid($_REQUEST['no_history'])
248
            && empty($GLOBALS['error_message'])
249
            && ! empty($GLOBALS['sql_query'])
250
            && isset($GLOBALS['dbi'])
251
            && $GLOBALS['dbi']->isUserType('logged')
252
        ) {
253
            $this->relation->setHistory(
254
                Core::ifSetOr($GLOBALS['db'], ''),
255
                Core::ifSetOr($GLOBALS['table'], ''),
256
                $GLOBALS['cfg']['Server']['user'],
257
                $GLOBALS['sql_query']
258
            );
259
        }
260
    }
261
262
    /**
263
     * Disables the rendering of the footer
264
     *
265
     * @return void
266
     */
267
    public function disable(): void
268
    {
269
        $this->_isEnabled = false;
270
    }
271
272
    /**
273
     * Set the ajax flag to indicate whether
274
     * we are servicing an ajax request
275
     *
276
     * @param bool $isAjax Whether we are servicing an ajax request
277
     *
278
     * @return void
279
     */
280
    public function setAjax(bool $isAjax): void
281
    {
282
        $this->_isAjax = $isAjax;
283
    }
284
285
    /**
286
     * Turn on minimal display mode
287
     *
288
     * @return void
289
     */
290
    public function setMinimal(): void
291
    {
292
        $this->_isMinimal = true;
293
    }
294
295
    /**
296
     * Returns the Scripts object
297
     *
298
     * @return Scripts object
299
     */
300
    public function getScripts(): Scripts
301
    {
302
        return $this->_scripts;
303
    }
304
305
    /**
306
     * Renders the footer
307
     *
308
     * @return string
309
     */
310
    public function getDisplay(): string
311
    {
312
        $this->_setHistory();
313
        if ($this->_isEnabled) {
314
            if (! $this->_isAjax && ! $this->_isMinimal) {
315
                if (Core::getenv('SCRIPT_NAME')
316
                    && empty($_POST)
317
                    && ! $this->_isAjax
318
                ) {
319
                    $url = $this->getSelfUrl();
320
                    $header = Response::getInstance()->getHeader();
321
                    $scripts = $header->getScripts()->getFiles();
322
                    $menuHash = $header->getMenu()->getHash();
323
                    // prime the client-side cache
324
                    $this->_scripts->addCode(
325
                        sprintf(
326
                            'if (! (history && history.pushState)) '
327
                            . 'PMA_MicroHistory.primer = {'
328
                            . ' url: "%s",'
329
                            . ' scripts: %s,'
330
                            . ' menuHash: "%s"'
331
                            . '};',
332
                            Sanitize::escapeJsString($url),
333
                            json_encode($scripts),
334
                            Sanitize::escapeJsString($menuHash)
335
                        )
336
                    );
337
                }
338
                if (Core::getenv('SCRIPT_NAME')
339
                    && ! $this->_isAjax
340
                ) {
341
                    $url = $this->getSelfUrl();
342
                    $selfLink = $this->_getSelfLink($url);
343
                }
344
                $this->_scripts->addCode(
345
                    'var debugSQLInfo = ' . $this->getDebugMessage() . ';'
346
                );
347
348
                $errorMessages = $this->getErrorMessages();
349
                $scripts = $this->_scripts->getDisplay();
350
351
                if ($GLOBALS['cfg']['DBG']['demo']) {
352
                    $demoMessage = $this->_getDemoMessage();
353
                }
354
355
                $footer = Config::renderFooter();
356
            }
357
            return $this->template->render('footer', [
358
                'is_ajax' => $this->_isAjax,
359
                'is_minimal' => $this->_isMinimal,
360
                'self_link' => $selfLink ?? '',
361
                'error_messages' => $errorMessages ?? '',
362
                'scripts' => $scripts ?? '',
363
                'is_demo' => $GLOBALS['cfg']['DBG']['demo'],
364
                'demo_message' => $demoMessage ?? '',
365
                'footer' => $footer ?? '',
366
            ]);
367
        }
368
        return '';
369
    }
370
}
371