Passed
Push — develop ( e54c4a...a6767a )
by Felipe
11:32 queued 05:47
created

DataexportController::render()   C

Complexity

Conditions 10
Paths 8

Size

Total Lines 62
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 62
rs 6.4192
c 0
b 0
f 0
cc 10
eloc 34
nc 8
nop 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * PHPPgAdmin v6.0.0-beta.45
5
 */
6
7
namespace PHPPgAdmin\Controller;
8
9
/**
10
 * Base controller class.
11
 *
12
 * @package PHPPgAdmin
13
 */
14
class DataexportController extends BaseController
15
{
16
    public $extensions = [
17
        'sql'  => 'sql',
18
        'copy' => 'sql',
19
        'csv'  => 'csv',
20
        'tab'  => 'txt',
21
        'html' => 'html',
22
        'xml'  => 'xml',
23
    ];
24
    public $controller_title = 'strexport';
25
26
    /**
27
     * Default method to render the controller according to the action parameter.
28
     */
29
    public function render()
30
    {
31
        $data = $this->misc->getDatabaseAccessor();
1 ignored issue
show
Unused Code introduced by
The assignment to $data is dead and can be removed.
Loading history...
32
33
        set_time_limit(0);
34
35
        // if (!isset($_REQUEST['table']) && !isset($_REQUEST['query']))
36
        // What must we do in this case? Maybe redirect to the homepage?
37
38
        $format = 'N/A';
39
        // If format is set, then perform the export
40
        if (!isset($_REQUEST['what'])) {
41
            return $this->doDefault();
42
        }
43
44
        $this->prtrace("REQUEST['what']", $_REQUEST['what']);
45
46
        // Include application functions
47
        $this->setNoOutput(true);
48
        $clean = false;
49
        $oids  = false;
50
        switch ($_REQUEST['what']) {
51
            case 'dataonly':
52
                // Check to see if they have pg_dump set up and if they do, use that
53
                // instead of custom dump code
54
                if ($this->misc->isDumpEnabled() && ('copy' == $_REQUEST['d_format'] || 'sql' == $_REQUEST['d_format'])) {
55
                    $this->prtrace('DUMP ENABLED, d_format is', $_REQUEST['d_format']);
56
                    $dbexport_controller = new \PHPPgAdmin\Controller\DbexportController($this->getContainer());
57
58
                    return $dbexport_controller->render();
59
                }
60
                $this->prtrace('d_format is', $_REQUEST['d_format'], 'd_oids is', isset($_REQUEST['d_oids']));
61
                $format = $_REQUEST['d_format'];
62
                $oids   = isset($_REQUEST['d_oids']);
63
64
                break;
65
            case 'structureonly':
66
                // Check to see if they have pg_dump set up and if they do, use that
67
                // instead of custom dump code
68
                if ($this->misc->isDumpEnabled()) {
69
                    $dbexport_controller = new \PHPPgAdmin\Controller\DbexportController($this->getContainer());
70
71
                    return $dbexport_controller->render();
72
                }
73
                $clean = isset($_REQUEST['s_clean']);
74
75
                break;
76
            case 'structureanddata':
77
                // Check to see if they have pg_dump set up and if they do, use that
78
                // instead of custom dump code
79
                if ($this->misc->isDumpEnabled()) {
80
                    $dbexport_controller = new \PHPPgAdmin\Controller\DbexportController($this->getContainer());
81
82
                    return $dbexport_controller->render();
83
                }
84
                $format = $_REQUEST['sd_format'];
85
                $clean  = isset($_REQUEST['sd_clean']);
86
                $oids   = isset($_REQUEST['sd_oids']);
87
88
                break;
89
        }
90
        return $this->mimicDumpFeature($format, $clean, $oids);
91
    }
92
93
    protected function mimicDumpFeature($format, $clean, $oids)
2 ignored issues
show
Unused Code introduced by
The parameter $format is not used and could be removed. ( Ignorable by Annotation )

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

93
    protected function mimicDumpFeature(/** @scrutinizer ignore-unused */ $format, $clean, $oids)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $clean is not used and could be removed. ( Ignorable by Annotation )

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

93
    protected function mimicDumpFeature($format, /** @scrutinizer ignore-unused */ $clean, $oids)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
94
    {
95
        $data = $this->misc->getDatabaseAccessor();
96
97
        set_time_limit(0);
98
99
        // if (!isset($_REQUEST['table']) && !isset($_REQUEST['query']))
100
        // What must we do in this case? Maybe redirect to the homepage?
101
102
        $format = 'N/A';
103
        // If format is set, then perform the export
104
        if (!isset($_REQUEST['what'])) {
105
            return $this->doDefault();
106
        }
107
108
        $this->prtrace("REQUEST['what']", $_REQUEST['what']);
109
110
        // Include application functions
111
        $this->setNoOutput(true);
112
        $clean    = false;
113
        $response = $this
114
            ->container
115
            ->responseobj;
116
117
        // Make it do a download, if necessary
118
        if ('download' == $_REQUEST['output']) {
119
            // Set headers.  MSIE is totally broken for SSL downloading, so
120
            // we need to have it download in-place as plain text
121
            if (strstr($_SERVER['HTTP_USER_AGENT'], 'MSIE') && isset($_SERVER['HTTPS'])) {
122
                $response = $response
123
                    ->withHeader('Content-type', 'text/plain');
124
            } else {
125
                $response = $response
126
                    ->withHeader('Content-type', 'application/download');
127
128
                if (isset($this->extensions[$format])) {
129
                    $ext = $this->extensions[$format];
130
                } else {
131
                    $ext = 'txt';
132
                }
133
                $response = $response
134
                    ->withHeader('Content-Disposition', 'attachment; filename=dump.' . $ext);
135
            }
136
        } else {
137
            $response = $response
138
                ->withHeader('Content-type', 'text/plain');
139
        }
140
141
        if (isset($_REQUEST['query'])) {
142
            $_REQUEST['query'] = trim(urldecode($_REQUEST['query']));
143
        }
144
145
        // Set the schema search path
146
        if (isset($_REQUEST['search_path'])) {
147
            $data->setSearchPath(array_map('trim', explode(',', $_REQUEST['search_path'])));
148
        }
149
150
        $subject = $this->coalesceArr($_REQUEST, 'subject', 'table')['subject'];
151
152
        $object = $this->coalesceArr($_REQUEST, $subject)[$subject];
153
154
        // Set up the dump transaction
155
        $status = $data->beginDump();
1 ignored issue
show
Unused Code introduced by
The assignment to $status is dead and can be removed.
Loading history...
156
        $this->prtrace('subject', $subject);
157
        $this->prtrace('object', $object);
158
159
        // If the dump is not dataonly then dump the structure prefix
160
        if ('dataonly' != $_REQUEST['what']) {
161
            $tabledefprefix = $data->getTableDefPrefix($object, $clean);
162
            $this->prtrace('tabledefprefix', $tabledefprefix);
163
            echo $tabledefprefix;
164
        }
165
166
        // If the dump is not structureonly then dump the actual data
167
        if ('structureonly' != $_REQUEST['what']) {
168
            // Get database encoding
169
            $dbEncoding = $data->getDatabaseEncoding();
1 ignored issue
show
Unused Code introduced by
The assignment to $dbEncoding is dead and can be removed.
Loading history...
170
171
            // Set fetch mode to NUM so that duplicate field names are properly returned
172
            $data->conn->setFetchMode(ADODB_FETCH_NUM);
173
174
            // Execute the query, if set, otherwise grab all rows from the table
175
            if ($object) {
176
                $rs = $data->dumpRelation($object, $oids);
177
            } else {
178
                $rs = $data->conn->Execute($_REQUEST['query']);
179
            }
180
            $this->prtrace('$_REQUEST[query]', $_REQUEST['query']);
181
182
            if ('copy' == $format) {
1 ignored issue
show
introduced by
The condition 'copy' == $format is always false.
Loading history...
183
                $data->fieldClean($object);
184
                echo "COPY \"{$_REQUEST['table']}\"";
185
                if ($oids) {
186
                    echo ' WITH OIDS';
187
                }
188
189
                echo " FROM stdin;\n";
190
                while (!$rs->EOF) {
191
                    $first = true;
192
                    //while (list($k, $v) = each($rs->fields)) {
193
                    foreach ($rs->fields as $k => $v) {
194
                        // Escape value
195
                        $v = $data->escapeBytea($v);
196
197
                        // We add an extra escaping slash onto octal encoded characters
198
                        $v = preg_replace('/\\\\([0-7]{3})/', '\\\\\1', $v);
199
                        if ($first) {
200
                            echo (is_null($v)) ? '\\N' : $v;
201
                            $first = false;
202
                        } else {
203
                            echo "\t", (is_null($v)) ? '\\N' : $v;
204
                        }
205
                    }
206
                    echo "\n";
207
                    $rs->moveNext();
208
                }
209
                echo "\\.\n";
210
            } elseif ('html' == $format) {
1 ignored issue
show
introduced by
The condition 'html' == $format is always false.
Loading history...
211
                echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n";
212
                echo "<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n";
213
                echo "<head>\r\n";
214
                echo "\t<title></title>\r\n";
215
                echo "\t<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\r\n";
216
                echo "</head>\r\n";
217
                echo "<body>\r\n";
218
                echo "<table class=\"phppgadmin\">\r\n";
219
                echo "\t<tr>\r\n";
220
                if (!$rs->EOF) {
221
                    // Output header row
222
                    $j = 0;
223
                    foreach ($rs->fields as $k => $v) {
224
                        $finfo = $rs->fetchField($j++);
225
                        if ($finfo->name == $data->id && !$oids) {
226
                            continue;
227
                        }
228
229
                        echo "\t\t<th>", $this->misc->printVal($finfo->name, true), "</th>\r\n";
230
                    }
231
                }
232
                echo "\t</tr>\r\n";
233
                while (!$rs->EOF) {
234
                    echo "\t<tr>\r\n";
235
                    $j = 0;
236
                    foreach ($rs->fields as $k => $v) {
237
                        $finfo = $rs->fetchField($j++);
238
                        if ($finfo->name == $data->id && !$oids) {
239
                            continue;
240
                        }
241
242
                        echo "\t\t<td>", $this->misc->printVal($v, true, $finfo->type), "</td>\r\n";
243
                    }
244
                    echo "\t</tr>\r\n";
245
                    $rs->moveNext();
246
                }
247
                echo "</table>\r\n";
248
                echo "</body>\r\n";
249
                echo "</html>\r\n";
250
            } elseif ('xml' == $format) {
1 ignored issue
show
introduced by
The condition 'xml' == $format is always false.
Loading history...
251
                echo "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n";
252
                echo "<data>\n";
253
                if (!$rs->EOF) {
254
                    // Output header row
255
                    $j = 0;
256
                    echo "\t<header>\n";
257
                    foreach ($rs->fields as $k => $v) {
258
                        $finfo = $rs->fetchField($j++);
259
                        $name  = htmlspecialchars($finfo->name);
260
                        $type  = htmlspecialchars($finfo->type);
261
                        echo "\t\t<column name=\"{$name}\" type=\"{$type}\" />\n";
262
                    }
263
                    echo "\t</header>\n";
264
                }
265
                echo "\t<records>\n";
266
                while (!$rs->EOF) {
267
                    $j = 0;
268
                    echo "\t\t<row>\n";
269
                    foreach ($rs->fields as $k => $v) {
270
                        $finfo = $rs->fetchField($j++);
271
                        $name  = htmlspecialchars($finfo->name);
272
                        if (!is_null($v)) {
273
                            $v = htmlspecialchars($v);
274
                        }
275
276
                        echo "\t\t\t<column name=\"{$name}\"", (is_null($v) ? ' null="null"' : ''), ">{$v}</column>\n";
277
                    }
278
                    echo "\t\t</row>\n";
279
                    $rs->moveNext();
280
                }
281
                echo "\t</records>\n";
282
                echo "</data>\n";
283
            } elseif ('sql' == $format) {
1 ignored issue
show
introduced by
The condition 'sql' == $format is always false.
Loading history...
284
                $data->fieldClean($object);
285
                while (!$rs->EOF) {
286
                    echo "INSERT INTO \"{$object}\" (";
287
                    $first = true;
288
                    $j     = 0;
289
                    foreach ($rs->fields as $k => $v) {
290
                        $finfo = $rs->fetchField($j++);
291
                        $k     = $finfo->name;
292
                        // SQL (INSERT) format cannot handle oids
293
                        //                        if ($k == $data->id) continue;
294
                        // Output field
295
                        $data->fieldClean($k);
296
                        if ($first) {
297
                            echo "\"{$k}\"";
298
                        } else {
299
                            echo ", \"{$k}\"";
300
                        }
301
302
                        if (!is_null($v)) {
303
                            // Output value
304
                            // addCSlashes converts all weird ASCII characters to octal representation,
305
                            // EXCEPT the 'special' ones like \r \n \t, etc.
306
                            $v = addcslashes($v, "\0..\37\177..\377");
307
                            // We add an extra escaping slash onto octal encoded characters
308
                            $v = preg_replace('/\\\\([0-7]{3})/', '\\\1', $v);
309
                            // Finally, escape all apostrophes
310
                            $v = str_replace("'", "''", $v);
311
                        }
312
                        if ($first) {
313
                            $values = (is_null($v) ? 'NULL' : "'{$v}'");
314
                            $first  = false;
315
                        } else {
316
                            $values .= ', ' . ((is_null($v) ? 'NULL' : "'{$v}'"));
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $values does not seem to be defined for all execution paths leading up to this point.
Loading history...
317
                        }
318
                    }
319
                    echo ") VALUES ({$values});\n";
320
                    $rs->moveNext();
321
                }
322
            } else {
323
                switch ($format) {
324
                    case 'tab':
325
                        $sep = "\t";
326
327
                        break;
328
                    case 'csv':
329
                    default:
330
                        $sep = ',';
331
332
                        break;
333
                }
334
                if (!$rs->EOF) {
335
                    // Output header row
336
                    $first = true;
337
                    foreach ($rs->fields as $k => $v) {
338
                        $finfo = $rs->fetchField($k);
339
                        $v     = $finfo->name;
340
                        if (!is_null($v)) {
341
                            $v = str_replace('"', '""', $v);
342
                        }
343
344
                        if ($first) {
345
                            echo "\"{$v}\"";
346
                            $first = false;
347
                        } else {
348
                            echo "{$sep}\"{$v}\"";
349
                        }
350
                    }
351
                    echo "\r\n";
352
                }
353
                while (!$rs->EOF) {
354
                    $first = true;
355
                    foreach ($rs->fields as $k => $v) {
356
                        if (!is_null($v)) {
357
                            $v = str_replace('"', '""', $v);
358
                        }
359
360
                        if ($first) {
361
                            echo (is_null($v)) ? '"\\N"' : "\"{$v}\"";
362
                            $first = false;
363
                        } else {
364
                            echo is_null($v) ? "{$sep}\"\\N\"" : "{$sep}\"{$v}\"";
365
                        }
366
                    }
367
                    echo "\r\n";
368
                    $rs->moveNext();
369
                }
370
            }
371
        }
372
373
        // If the dump is not dataonly then dump the structure suffix
374
        if ('dataonly' != $_REQUEST['what']) {
375
            // Set fetch mode back to ASSOC for the table suffix to work
376
            $data->conn->setFetchMode(ADODB_FETCH_ASSOC);
377
            $tabledefsuffix = $data->getTableDefSuffix($object);
378
            $this->prtrace('tabledefsuffix', $tabledefsuffix);
379
            echo $tabledefsuffix;
380
        }
381
382
        // Finish the dump transaction
383
        $status = $data->endDump();
384
        return $response;
385
    }
386
387
    public function doDefault($msg = '')
388
    {
389
        if (!isset($_REQUEST['query']) || empty($_REQUEST['query'])) {
390
            $_REQUEST['query'] = $_SESSION['sqlquery'];
391
        }
392
393
        $this->printHeader();
394
        $this->printBody();
395
        $this->printTrail(isset($_REQUEST['subject']) ? $_REQUEST['subject'] : 'database');
396
        $this->printTitle($this->lang['strexport']);
397
        if (isset($msg)) {
398
            $this->printMsg($msg);
399
        }
400
401
        echo '<form action="' . \SUBFOLDER . "/src/views/dataexport\" method=\"post\">\n";
402
        echo "<table>\n";
403
        echo "<tr><th class=\"data\">{$this->lang['strformat']}:</th><td><select name=\"d_format\">\n";
404
        // COPY and SQL require a table
405
        if (isset($_REQUEST['table'])) {
406
            echo "<option value=\"copy\">COPY</option>\n";
407
            echo "<option value=\"sql\">SQL</option>\n";
408
        }
409
        echo "<option value=\"csv\">CSV</option>\n";
410
        echo "<option value=\"tab\">{$this->lang['strtabbed']}</option>\n";
411
        echo "<option value=\"html\">XHTML</option>\n";
412
        echo "<option value=\"xml\">XML</option>\n";
413
        echo '</select></td></tr>';
414
        echo "</table>\n";
415
416
        echo "<h3>{$this->lang['stroptions']}</h3>\n";
417
        echo "<p><input type=\"radio\" id=\"output1\" name=\"output\" value=\"show\" checked=\"checked\" /><label for=\"output1\">{$this->lang['strshow']}</label>\n";
418
        echo "<br/><input type=\"radio\" id=\"output2\" name=\"output\" value=\"download\" /><label for=\"output2\">{$this->lang['strdownload']}</label></p>\n";
419
420
        echo "<p><input type=\"hidden\" name=\"action\" value=\"export\" />\n";
421
        echo "<input type=\"hidden\" name=\"what\" value=\"dataonly\" />\n";
422
        if (isset($_REQUEST['table'])) {
423
            echo '<input type="hidden" name="subject" value="table" />' . "\n";
424
            echo '<input type="hidden" name="table" value="', htmlspecialchars($_REQUEST['table']), "\" />\n";
425
        } else {
426
            echo '<input type="hidden" name="subject" value="table" />' . "\n";
427
        }
428
        $this->prtrace('$_REQUEST[query]', $_REQUEST['query'], htmlspecialchars(urlencode($_REQUEST['query'])));
429
        $this->prtrace('$_SESSION[sqlquery]', $_SESSION['sqlquery'], htmlspecialchars(urlencode($_SESSION['sqlquery'])));
430
        echo '<input type="hidden" name="query" value="', htmlspecialchars(urlencode($_REQUEST['query'])), "\" />\n";
431
        if (isset($_REQUEST['search_path'])) {
432
            echo '<input type="hidden" name="search_path" value="', htmlspecialchars($_REQUEST['search_path']), "\" />\n";
433
        }
434
        echo $this->misc->form;
435
        echo "<input type=\"submit\" value=\"{$this->lang['strexport']}\" /></p>\n";
436
        echo "</form>\n";
437
438
        $this->printFooter();
439
    }
440
}
441