Passed
Push — develop ( 442876...34732b )
by Felipe
46s
created

SqlController::doDefault()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 21
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 14
nc 5
nop 0
dl 0
loc 21
rs 9.0534
c 0
b 0
f 0
1
<?php
2
0 ignored issues
show
Coding Style introduced by
You must use "/**" style comments for a file comment
Loading history...
3
/*
4
 * PHPPgAdmin v6.0.0-beta.30
5
 */
6
7
namespace PHPPgAdmin\Controller;
8
9
/**
10
 * Base controller class.
11
 */
5 ignored issues
show
Coding Style introduced by
Missing @category tag in class comment
Loading history...
Coding Style introduced by
Missing @package tag in class comment
Loading history...
Coding Style introduced by
Missing @author tag in class comment
Loading history...
Coding Style introduced by
Missing @license tag in class comment
Loading history...
Coding Style introduced by
Missing @link tag in class comment
Loading history...
12
class SqlController extends BaseController
13
{
14
    public $controller_name = 'SqlController';
15
    public $query           = '';
16
    public $subject         = '';
17
    public $start_time;
18
    public $duration;
19
20
    /**
21
     * Default method to render the controller according to the action parameter.
22
     */
23
    public function render()
24
    {
25
        $lang = $this->lang;
26
27
        $data = $this->misc->getDatabaseAccessor();
28
29
        set_time_limit(0);
30
31
        // We need to store the query in a session for editing purposes
32
        // We avoid GPC vars to avoid truncating long queries
33
        if (isset($_REQUEST['subject']) && 'history' == $_REQUEST['subject']) {
34
            // Or maybe we came from the history popup
35
            $_SESSION['sqlquery'] = $_SESSION['history'][$_REQUEST['server']][$_REQUEST['database']][$_GET['queryid']]['query'];
36
            $this->query          = $_SESSION['sqlquery'];
37
        } elseif (isset($_POST['query'])) {
38
            // Or maybe we came from an sql form
39
            $_SESSION['sqlquery'] = $_POST['query'];
40
            $this->query          = $_SESSION['sqlquery'];
41
        } else {
42
            echo 'could not find the query!!';
43
        }
44
45
        // Pagination maybe set by a get link that has it as FALSE,
46
        // if that's the case, unset the variable.
47
        if (isset($_REQUEST['paginate']) && 'f' == $_REQUEST['paginate']) {
48
            unset($_REQUEST['paginate'], $_POST['paginate'], $_GET['paginate']);
49
        }
50
51
        if (isset($_REQUEST['subject'])) {
52
            $this->subject = $_REQUEST['subject'];
53
        }
54
55
        // Check to see if pagination has been specified. In that case, send to display
56
        // script for pagination
57
        // if a file is given or the request is an explain, do not paginate
58
        if (isset($_REQUEST['paginate']) && !(isset($_FILES['script']) && $_FILES['script']['size'] > 0) && (0 == preg_match('/^\s*explain/i', $this->query))) {
59
            //if (!(isset($_FILES['script']) && $_FILES['script']['size'] > 0)) {
60
61
            $display_controller = new DisplayController($this->getContainer());
62
63
            return $display_controller->render();
64
        }
65
66
        $this->printHeader($lang['strqueryresults'], null, true, 'header_sqledit.twig');
67
        $this->printBody();
68
        $this->printTrail('database');
69
        $this->printTitle($lang['strqueryresults']);
70
71
        // Set the schema search path
72
        if (isset($_REQUEST['search_path'])) {
73
            if (0 != $data->setSearchPath(array_map('trim', explode(',', $_REQUEST['search_path'])))) {
74
                return $this->printFooter();
75
            }
76
        }
77
78
        // May as well try to time the query
79
        if (function_exists('microtime')) {
80
            list($usec, $sec) = explode(' ', microtime());
81
            $this->start_time = ((float) $usec + (float) $sec);
82
        }
83
84
        $this->doDefault();
85
86
        $this->doFooter(true, 'footer_sqledit.twig');
87
    }
88
89
    public function doDefault()
1 ignored issue
show
Coding Style introduced by
Missing function doc comment
Loading history...
90
    {
91
        $conf        = $this->conf;
0 ignored issues
show
Unused Code introduced by
The assignment to $conf is dead and can be removed.
Loading history...
92
        $this->misc  = $this->misc;
93
        $lang        = $this->lang;
0 ignored issues
show
Unused Code introduced by
The assignment to $lang is dead and can be removed.
Loading history...
94
        $_connection = $this->misc->getConnection();
95
96
        try {
97
            // Execute the query.  If it's a script upload, special handling is necessary
98
            if (isset($_FILES['script']) && $_FILES['script']['size'] > 0) {
99
                return $this->execute_script();
100
            }
101
102
            return $this->execute_query();
103
        } catch (\PHPPgAdmin\ADOdbException $e) {
104
            $message   = $e->getMessage();
105
            $trace     = $e->getTraceAsString();
106
            $lastError = $_connection->getLastError();
107
            $this->prtrace(['message' => $message, 'trace' => $trace, 'lastError' => $lastError]);
108
109
            return null;
110
        }
111
    }
112
113
    private function execute_script()
2 ignored issues
show
Coding Style introduced by
Private method name "SqlController::execute_script" must be prefixed with an underscore
Loading history...
Coding Style introduced by
Missing function doc comment
Loading history...
114
    {
115
        $conf        = $this->conf;
0 ignored issues
show
Unused Code introduced by
The assignment to $conf is dead and can be removed.
Loading history...
116
        $misc        = $this->misc;
117
        $lang        = $this->lang;
118
        $data        = $this->misc->getDatabaseAccessor();
119
        $_connection = $this->misc->getConnection();
120
121
        /**
122
         * This is a callback function to display the result of each separate query.
123
         *
124
         * @param ADORecordSet $rs The recordset returned by the script execetor
125
         */
126
        $sqlCallback = function ($query, $rs, $lineno) use ($data, $misc, $lang, $_connection) {
127
            // Check if $rs is false, if so then there was a fatal error
128
            if (false === $rs) {
129
                echo htmlspecialchars($_FILES['script']['name']), ':', $lineno, ': ', nl2br(htmlspecialchars($_connection->getLastError())), "<br/>\n";
130
            } else {
131
                // Print query results
132
                switch (pg_result_status($rs)) {
133
                    case PGSQL_TUPLES_OK:
134
                        // If rows returned, then display the results
135
                        $num_fields = pg_numfields($rs);
136
                        echo "<p><table>\n<tr>";
137
                        for ($k = 0; $k < $num_fields; ++$k) {
138
                            echo '<th class="data">', $misc->printVal(pg_fieldname($rs, $k)), '</th>';
139
                        }
140
141
                        $i   = 0;
142
                        $row = pg_fetch_row($rs);
143
                        while (false !== $row) {
144
                            $id = (0 == ($i % 2) ? '1' : '2');
145
                            echo "<tr class=\"data{$id}\">\n";
146
                            foreach ($row as $k => $v) {
147
                                echo '<td style="white-space:nowrap;">', $misc->printVal($v, pg_fieldtype($rs, $k), ['null' => true]), '</td>';
148
                            }
149
                            echo "</tr>\n";
150
                            $row = pg_fetch_row($rs);
151
                            ++$i;
152
                        }
153
154
                        echo "</table><br/>\n";
155
                        echo $i, " {$lang['strrows']}</p>\n";
156
157
                        break;
158
                    case PGSQL_COMMAND_OK:
159
                        // If we have the command completion tag
160
                        if (version_compare(phpversion(), '4.3', '>=')) {
161
                            echo htmlspecialchars(pg_result_status($rs, PGSQL_STATUS_STRING)), "<br/>\n";
162
                        }
163
                        // Otherwise if any rows have been affected
164
                        elseif ($data->conn->Affected_Rows() > 0) {
0 ignored issues
show
Coding Style introduced by
Expected "} elseif (...) \n"; found "\n // Otherwise if any rows have been affected\n elseif (...) {\n"
Loading history...
165
                            echo $data->conn->Affected_Rows(), " {$lang['strrowsaff']}<br/>\n";
166
                        }
167
                        // Otherwise output nothing...
168
                        break;
169
                    case PGSQL_EMPTY_QUERY:
170
                        break;
171
                    default:
172
                        break;
173
                }
174
            }
175
        };
176
177
        return $data->executeScript('script', $sqlCallback);
178
    }
179
180
    private function execute_query()
2 ignored issues
show
Coding Style introduced by
Private method name "SqlController::execute_query" must be prefixed with an underscore
Loading history...
Coding Style introduced by
Missing function doc comment
Loading history...
181
    {
182
        $lang = $this->lang;
183
        $data = $this->misc->getDatabaseAccessor();
184
185
        // Set fetch mode to NUM so that duplicate field names are properly returned
186
        $data->conn->setFetchMode(ADODB_FETCH_NUM);
187
188
        $rs = $data->conn->Execute($this->query);
189
190
        echo '<form method="post" id="sqlform" action="' . $_SERVER['REQUEST_URI'] . '">';
191
        echo '<textarea width="90%" name="query"  id="query" rows="5" cols="100" resizable="true">';
192
193
        echo htmlspecialchars($this->query);
194
        echo '</textarea><br>';
195
        echo $this->misc->setForm();
196
        echo '<input type="submit"/></form>';
197
198
        // $rs will only be an object if there is no error
199
        if (is_object($rs)) {
200
            // Request was run, saving it in history
201
            if (!isset($_REQUEST['nohistory'])) {
202
                $this->misc->saveScriptHistory($this->query);
203
            }
204
205
            // Now, depending on what happened do various things
206
207
            // First, if rows returned, then display the results
208
            if ($rs->recordCount() > 0) {
209
                echo "<table>\n<tr>";
210
                foreach ($rs->fields as $k => $v) {
211
                    $finfo = $rs->fetchField($k);
212
                    echo '<th class="data">', $this->misc->printVal($finfo->name), '</th>';
213
                }
214
                echo "</tr>\n";
215
                $i = 0;
216
                while (!$rs->EOF) {
217
                    $id = (0 == ($i % 2) ? '1' : '2');
218
                    echo "<tr class=\"data{$id}\">\n";
219
                    foreach ($rs->fields as $k => $v) {
220
                        $finfo = $rs->fetchField($k);
221
                        echo '<td style="white-space:nowrap;">', $this->misc->printVal($v, $finfo->type, ['null' => true]), '</td>';
222
                    }
223
                    echo "</tr>\n";
224
                    $rs->moveNext();
225
                    ++$i;
226
                }
227
                echo "</table>\n";
228
                echo '<p>', $rs->recordCount(), " {$lang['strrows']}</p>\n";
229
            } elseif ($data->conn->Affected_Rows() > 0) {
230
                // Otherwise if any rows have been affected
231
                echo '<p>', $data->conn->Affected_Rows(), " {$lang['strrowsaff']}</p>\n";
232
            } else {
233
                // Otherwise nodata to print
234
                echo '<p>', $lang['strnodata'], "</p>\n";
235
            }
236
        }
237
    }
238
239
    private function doFooter($doBody = true, $template = 'footer.twig')
2 ignored issues
show
Coding Style introduced by
Missing function doc comment
Loading history...
Coding Style introduced by
Private method name "SqlController::doFooter" must be prefixed with an underscore
Loading history...
240
    {
241
        $lang = $this->lang;
242
        $data = $this->misc->getDatabaseAccessor();
243
244
        // May as well try to time the query
245
        if (null !== $this->start_time) {
246
            list($usec, $sec) = explode(' ', microtime());
247
            $end_time         = ((float) $usec + (float) $sec);
248
            // Get duration in milliseconds, round to 3dp's
249
            $this->duration = number_format(($end_time - $this->start_time) * 1000, 3);
250
        }
251
252
        // Reload the browser as we may have made schema changes
253
        $this->misc->setReloadBrowser(true);
254
255
        // Display duration if we know it
256
        if (null !== $this->duration) {
257
            echo '<p>', sprintf($lang['strruntime'], $this->duration), "</p>\n";
258
        }
259
260
        echo "<p>{$lang['strsqlexecuted']}</p>\n";
261
262
        $navlinks = [];
263
        $fields   = [
264
            'server'   => $_REQUEST['server'],
265
            'database' => $_REQUEST['database'],
266
        ];
267
268
        if (isset($_REQUEST['schema'])) {
269
            $fields['schema'] = $_REQUEST['schema'];
270
        }
271
272
        // Return
273
        if (isset($_REQUEST['return'])) {
274
            $urlvars          = $this->misc->getSubjectParams($_REQUEST['return']);
275
            $navlinks['back'] = [
276
                'attr'    => [
277
                    'href' => [
278
                        'url'     => $urlvars['url'],
279
                        'urlvars' => $urlvars['params'],
280
                    ],
281
                ],
282
                'content' => $lang['strback'],
283
            ];
284
        }
285
286
        // Edit
287
        $navlinks['alter'] = [
288
            'attr'    => [
289
                'href' => [
290
                    'url'     => 'database.php',
291
                    'urlvars' => array_merge($fields, [
1 ignored issue
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
292
                        'action' => 'sql',
293
                    ]),
1 ignored issue
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
294
                ],
295
            ],
296
            'content' => $lang['streditsql'],
297
        ];
298
299
        // Create view and download
300
        if ('' !== $this->query && isset($rs) && is_object($rs) && $rs->recordCount() > 0) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $rs seems to never exist and therefore isset should always be false.
Loading history...
301
            // Report views don't set a schema, so we need to disable create view in that case
302
            if (isset($_REQUEST['schema'])) {
303
                $navlinks['createview'] = [
304
                    'attr'    => [
305
                        'href' => [
306
                            'url'     => 'views.php',
307
                            'urlvars' => array_merge($fields, [
1 ignored issue
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
308
                                'action' => 'create',
309
                            ]),
1 ignored issue
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
310
                        ],
311
                    ],
312
                    'content' => $lang['strcreateview'],
313
                ];
314
            }
315
316
            if (isset($_REQUEST['search_path'])) {
317
                $fields['search_path'] = $_REQUEST['search_path'];
318
            }
319
320
            $navlinks['download'] = [
321
                'attr'    => [
322
                    'href' => [
323
                        'url'     => 'dataexport.php',
324
                        'urlvars' => $fields,
325
                    ],
326
                ],
327
                'content' => $lang['strdownload'],
328
            ];
329
        }
330
331
        $this->printNavLinks($navlinks, 'sql-form', get_defined_vars());
332
333
        return $this->printFooter($doBody, $template);
334
    }
335
}
336