File: ChartController.php

package info (click to toggle)
phpmyadmin 4%3A5.2.1%2Bdfsg-1%2Bdeb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 131,332 kB
  • sloc: javascript: 212,681; php: 168,094; xml: 18,098; sql: 504; sh: 274; makefile: 205; python: 199
file content (229 lines) | stat: -rw-r--r-- 7,315 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
<?php

declare(strict_types=1);

namespace PhpMyAdmin\Controllers\Table;

use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\DbTableExists;
use PhpMyAdmin\FieldMetadata;
use PhpMyAdmin\Html\Generator;
use PhpMyAdmin\Message;
use PhpMyAdmin\ResponseRenderer;
use PhpMyAdmin\SqlParser\Components\Limit;
use PhpMyAdmin\SqlParser\Parser;
use PhpMyAdmin\SqlParser\Statements\SelectStatement;
use PhpMyAdmin\Template;
use PhpMyAdmin\Url;
use PhpMyAdmin\Util;

use function __;
use function array_keys;
use function htmlspecialchars;
use function json_encode;
use function min;
use function strlen;

/**
 * Handles creation of the chart.
 */
class ChartController extends AbstractController
{
    /** @var DatabaseInterface */
    private $dbi;

    public function __construct(
        ResponseRenderer $response,
        Template $template,
        string $db,
        string $table,
        DatabaseInterface $dbi
    ) {
        parent::__construct($response, $template, $db, $table);
        $this->dbi = $dbi;
    }

    public function __invoke(): void
    {
        global $db, $table, $cfg, $sql_query, $errorUrl;

        if (isset($_REQUEST['pos'], $_REQUEST['session_max_rows']) && $this->response->isAjax()) {
            $this->ajax();

            return;
        }

        // Throw error if no sql query is set
        if (! isset($sql_query) || $sql_query == '') {
            $this->response->setRequestStatus(false);
            $this->response->addHTML(
                Message::error(__('No SQL query was set to fetch data.'))->getDisplay()
            );

            return;
        }

        $this->addScriptFiles([
            'chart.js',
            'table/chart.js',
            'vendor/jqplot/jquery.jqplot.js',
            'vendor/jqplot/plugins/jqplot.barRenderer.js',
            'vendor/jqplot/plugins/jqplot.canvasAxisLabelRenderer.js',
            'vendor/jqplot/plugins/jqplot.canvasTextRenderer.js',
            'vendor/jqplot/plugins/jqplot.categoryAxisRenderer.js',
            'vendor/jqplot/plugins/jqplot.dateAxisRenderer.js',
            'vendor/jqplot/plugins/jqplot.pointLabels.js',
            'vendor/jqplot/plugins/jqplot.pieRenderer.js',
            'vendor/jqplot/plugins/jqplot.enhancedPieLegendRenderer.js',
            'vendor/jqplot/plugins/jqplot.highlighter.js',
        ]);

        $url_params = [];

        /**
         * Runs common work
         */
        if (strlen($table) > 0) {
            Util::checkParameters(['db', 'table']);

            $url_params = ['db' => $db, 'table' => $table];
            $errorUrl = Util::getScriptNameForOption($cfg['DefaultTabTable'], 'table');
            $errorUrl .= Url::getCommon($url_params, '&');

            DbTableExists::check();

            $url_params['goto'] = Util::getScriptNameForOption($cfg['DefaultTabTable'], 'table');
            $url_params['back'] = Url::getFromRoute('/table/sql');
            $this->dbi->selectDb($db);
        } elseif (strlen($db) > 0) {
            $url_params['goto'] = Util::getScriptNameForOption($cfg['DefaultTabDatabase'], 'database');
            $url_params['back'] = Url::getFromRoute('/sql');

            Util::checkParameters(['db']);

            $errorUrl = Util::getScriptNameForOption($cfg['DefaultTabDatabase'], 'database');
            $errorUrl .= Url::getCommon(['db' => $db], '&');

            if (! $this->hasDatabase()) {
                return;
            }
        } else {
            $url_params['goto'] = Util::getScriptNameForOption($cfg['DefaultTabServer'], 'server');
            $url_params['back'] = Url::getFromRoute('/sql');
            $errorUrl = Url::getFromRoute('/');

            if ($this->dbi->isSuperUser()) {
                $this->dbi->selectDb('mysql');
            }
        }

        $result = $this->dbi->tryQuery($sql_query);
        $fields_meta = $row = [];
        if ($result !== false) {
            $fields_meta = $this->dbi->getFieldsMeta($result);
            $row = $result->fetchAssoc();
        }

        $keys = array_keys($row);
        $numericColumnFound = false;
        foreach (array_keys($keys) as $idx) {
            if (
                isset($fields_meta[$idx]) && (
                $fields_meta[$idx]->isType(FieldMetadata::TYPE_INT)
                || $fields_meta[$idx]->isType(FieldMetadata::TYPE_REAL)
                )
            ) {
                $numericColumnFound = true;
                break;
            }
        }

        if (! $numericColumnFound) {
            $this->response->setRequestStatus(false);
            $this->response->addJSON(
                'message',
                __('No numeric columns present in the table to plot.')
            );

            return;
        }

        $url_params['db'] = $db;
        $url_params['reload'] = 1;

        $startAndNumberOfRowsFieldset = Generator::getStartAndNumberOfRowsFieldsetData($sql_query);

        /**
         * Displays the page
         */
        $this->render('table/chart/tbl_chart', [
            'url_params' => $url_params,
            'keys' => $keys,
            'fields_meta' => $fields_meta,
            'table_has_a_numeric_column' => $numericColumnFound,
            'start_and_number_of_rows_fieldset' => $startAndNumberOfRowsFieldset,
        ]);
    }

    /**
     * Handle ajax request
     */
    public function ajax(): void
    {
        global $db, $table, $sql_query, $urlParams, $errorUrl, $cfg;

        if (strlen($table) > 0 && strlen($db) > 0) {
            Util::checkParameters(['db', 'table']);

            $urlParams = ['db' => $db, 'table' => $table];
            $errorUrl = Util::getScriptNameForOption($cfg['DefaultTabTable'], 'table');
            $errorUrl .= Url::getCommon($urlParams, '&');

            DbTableExists::check();
        }

        $parser = new Parser($sql_query);
        /**
         * @var SelectStatement $statement
         */
        $statement = $parser->statements[0];
        if (empty($statement->limit)) {
            $statement->limit = new Limit($_REQUEST['session_max_rows'], $_REQUEST['pos']);
        } else {
            $start = $statement->limit->offset + $_REQUEST['pos'];
            $rows = min($_REQUEST['session_max_rows'], $statement->limit->rowCount - $_REQUEST['pos']);
            $statement->limit = new Limit($rows, $start);
        }

        $sql_with_limit = $statement->build();

        $result = $this->dbi->tryQuery($sql_with_limit);
        $data = [];
        if ($result !== false) {
            $data = $result->fetchAllAssoc();
        }

        if ($data === []) {
            $this->response->setRequestStatus(false);
            $this->response->addJSON('message', __('No data to display'));

            return;
        }

        $sanitized_data = [];

        foreach ($data as $data_row) {
            $tmp_row = [];
            foreach ($data_row as $data_column => $data_value) {
                $escaped_value = $data_value === null ? null : htmlspecialchars($data_value);
                $tmp_row[htmlspecialchars($data_column)] = $escaped_value;
            }

            $sanitized_data[] = $tmp_row;
        }

        $this->response->setRequestStatus(true);
        $this->response->addJSON('message', null);
        $this->response->addJSON('chartData', json_encode($sanitized_data));
    }
}