Passed
Pull Request — develop (#92)
by Felipe
04:25
created

DataexportController::doDefault()   C

Complexity

Conditions 8
Paths 32

Size

Total Lines 51
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 37
nc 32
nop 1
dl 0
loc 51
rs 6.5978
c 0
b 0
f 0

How to fix   Long Method   

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
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 DataexportController extends BaseController
13
{
14
    public $controller_name = 'DataexportController';
15
    public $extensions      = [
16
        'sql'  => 'sql',
17
        'copy' => 'sql',
18
        'csv'  => 'csv',
19
        'tab'  => 'txt',
20
        'html' => 'html',
21
        'xml'  => 'xml',
22
    ];
23
24
    /**
25
     * Default method to render the controller according to the action parameter.
26
     */
27
    public function render()
28
    {
29
        $lang   = $this->lang;
1 ignored issue
show
Unused Code introduced by
The assignment to $lang is dead and can be removed.
Loading history...
30
        $data   = $this->misc->getDatabaseAccessor();
31
        $action = $this->action;
1 ignored issue
show
Unused Code introduced by
The assignment to $action 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
        // If format is set, then perform the export
39
        if (isset($_REQUEST['what'])) {
40
            $this->prtrace("REQUEST['what']", $_REQUEST['what']);
41
42
            // Include application functions
43
            $this->setNoOutput(true);
44
45
            switch ($_REQUEST['what']) {
46
                case 'dataonly':
47
                    // Check to see if they have pg_dump set up and if they do, use that
48
                    // instead of custom dump code
49
                    if ($this->misc->isDumpEnabled() && ('copy' == $_REQUEST['d_format'] || 'sql' == $_REQUEST['d_format'])) {
50
                        $this->prtrace('DUMP ENABLED, d_format is', $_REQUEST['d_format']);
51
                        $dbexport_controller = new \PHPPgAdmin\Controller\DbexportController($this->getContainer());
52
53
                        return $dbexport_controller->render();
54
                    }
55
                    $this->prtrace('d_format is', $_REQUEST['d_format'], 'd_oids is', isset($_REQUEST['d_oids']));
56
                    $format = $_REQUEST['d_format'];
57
                    $oids   = isset($_REQUEST['d_oids']);
58
59
                    break;
60
                case 'structureonly':
61
                    // Check to see if they have pg_dump set up and if they do, use that
62
                    // instead of custom dump code
63
                    if ($this->misc->isDumpEnabled()) {
64
                        $dbexport_controller = new \PHPPgAdmin\Controller\DbexportController($this->getContainer());
65
66
                        return $dbexport_controller->render();
67
                    }
68
                    $clean = isset($_REQUEST['s_clean']);
69
70
                    break;
71
                case 'structureanddata':
72
                    // Check to see if they have pg_dump set up and if they do, use that
73
                    // instead of custom dump code
74
                    if ($this->misc->isDumpEnabled()) {
75
                        $dbexport_controller = new \PHPPgAdmin\Controller\DbexportController($this->getContainer());
76
77
                        return $dbexport_controller->render();
78
                    }
79
                    $format = $_REQUEST['sd_format'];
80
                    $clean  = isset($_REQUEST['sd_clean']);
81
                    $oids   = isset($_REQUEST['sd_oids']);
82
83
                    break;
84
            }
85
86
            // Make it do a download, if necessary
87
            if ('download' == $_REQUEST['output']) {
88
                // Set headers.  MSIE is totally broken for SSL downloading, so
89
                // we need to have it download in-place as plain text
90
                if (strstr($_SERVER['HTTP_USER_AGENT'], 'MSIE') && isset($_SERVER['HTTPS'])) {
91
                    header('Content-Type: text/plain');
92
                } else {
93
                    header('Content-Type: application/download');
94
95
                    if (isset($extensions[$format])) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $extensions seems to never exist and therefore isset should always be false.
Loading history...
Comprehensibility Best Practice introduced by
The variable $format does not seem to be defined for all execution paths leading up to this point.
Loading history...
96
                        $ext = $extensions[$format];
97
                    } else {
98
                        $ext = 'txt';
99
                    }
100
101
                    header('Content-Disposition: attachment; filename=dump.' . $ext);
102
                }
103
            } else {
104
                header('Content-Type: text/plain');
105
            }
106
107
            if (isset($_REQUEST['query'])) {
108
                $_REQUEST['query'] = trim(urldecode($_REQUEST['query']));
109
            }
110
111
            // Set the schema search path
112
            if (isset($_REQUEST['search_path'])) {
113
                $data->setSearchPath(array_map('trim', explode(',', $_REQUEST['search_path'])));
114
            }
115
116
            // Set up the dump transaction
117
            $status = $data->beginDump();
1 ignored issue
show
Unused Code introduced by
The assignment to $status is dead and can be removed.
Loading history...
118
119
            // If the dump is not dataonly then dump the structure prefix
120
            if ('dataonly' != $_REQUEST['what']) {
121
                echo $data->getTableDefPrefix($_REQUEST['table'], $clean);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $clean does not seem to be defined for all execution paths leading up to this point.
Loading history...
122
            }
123
124
            // If the dump is not structureonly then dump the actual data
125
            if ('structureonly' != $_REQUEST['what']) {
126
                // Get database encoding
127
                $dbEncoding = $data->getDatabaseEncoding();
1 ignored issue
show
Unused Code introduced by
The assignment to $dbEncoding is dead and can be removed.
Loading history...
128
129
                // Set fetch mode to NUM so that duplicate field names are properly returned
130
                $data->conn->setFetchMode(ADODB_FETCH_NUM);
131
132
                // Execute the query, if set, otherwise grab all rows from the table
133
                if (isset($_REQUEST['table'])) {
134
                    $rs = $data->dumpRelation($_REQUEST['table'], $oids);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $oids does not seem to be defined for all execution paths leading up to this point.
Loading history...
135
                } else {
136
                    $rs = $data->conn->Execute($_REQUEST['query']);
137
                }
138
139
                if ('copy' == $format) {
140
                    $data->fieldClean($_REQUEST['table']);
141
                    echo "COPY \"{$_REQUEST['table']}\"";
142
                    if ($oids) {
143
                        echo ' WITH OIDS';
144
                    }
145
146
                    echo " FROM stdin;\n";
147
                    while (!$rs->EOF) {
148
                        $first = true;
149
                        //while (list($k, $v) = each($rs->fields)) {
150
                        foreach ($rs->fields as $k => $v) {
151
                            // Escape value
152
                            $v = $data->escapeBytea($v);
153
154
                            // We add an extra escaping slash onto octal encoded characters
155
                            $v = preg_replace('/\\\\([0-7]{3})/', '\\\\\1', $v);
156
                            if ($first) {
157
                                echo (is_null($v)) ? '\\N' : $v;
158
                                $first = false;
159
                            } else {
160
                                echo "\t", (is_null($v)) ? '\\N' : $v;
161
                            }
162
                        }
163
                        echo "\n";
164
                        $rs->moveNext();
165
                    }
166
                    echo "\\.\n";
167
                } elseif ('html' == $format) {
168
                    echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n";
169
                    echo "<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n";
170
                    echo "<head>\r\n";
171
                    echo "\t<title></title>\r\n";
172
                    echo "\t<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\r\n";
173
                    echo "</head>\r\n";
174
                    echo "<body>\r\n";
175
                    echo "<table class=\"phppgadmin\">\r\n";
176
                    echo "\t<tr>\r\n";
177
                    if (!$rs->EOF) {
178
                        // Output header row
179
                        $j = 0;
180
                        foreach ($rs->fields as $k => $v) {
181
                            $finfo = $rs->fetchField($j++);
182
                            if ($finfo->name == $data->id && !$oids) {
183
                                continue;
184
                            }
185
186
                            echo "\t\t<th>", $this->misc->printVal($finfo->name, true), "</th>\r\n";
187
                        }
188
                    }
189
                    echo "\t</tr>\r\n";
190
                    while (!$rs->EOF) {
191
                        echo "\t<tr>\r\n";
192
                        $j = 0;
193
                        foreach ($rs->fields as $k => $v) {
194
                            $finfo = $rs->fetchField($j++);
195
                            if ($finfo->name == $data->id && !$oids) {
196
                                continue;
197
                            }
198
199
                            echo "\t\t<td>", $this->misc->printVal($v, true, $finfo->type), "</td>\r\n";
200
                        }
201
                        echo "\t</tr>\r\n";
202
                        $rs->moveNext();
203
                    }
204
                    echo "</table>\r\n";
205
                    echo "</body>\r\n";
206
                    echo "</html>\r\n";
207
                } elseif ('xml' == $format) {
208
                    echo "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n";
209
                    echo "<data>\n";
210
                    if (!$rs->EOF) {
211
                        // Output header row
212
                        $j = 0;
213
                        echo "\t<header>\n";
214
                        foreach ($rs->fields as $k => $v) {
215
                            $finfo = $rs->fetchField($j++);
216
                            $name  = htmlspecialchars($finfo->name);
217
                            $type  = htmlspecialchars($finfo->type);
218
                            echo "\t\t<column name=\"{$name}\" type=\"{$type}\" />\n";
219
                        }
220
                        echo "\t</header>\n";
221
                    }
222
                    echo "\t<records>\n";
223
                    while (!$rs->EOF) {
224
                        $j = 0;
225
                        echo "\t\t<row>\n";
226
                        foreach ($rs->fields as $k => $v) {
227
                            $finfo = $rs->fetchField($j++);
228
                            $name  = htmlspecialchars($finfo->name);
229
                            if (!is_null($v)) {
230
                                $v = htmlspecialchars($v);
231
                            }
232
233
                            echo "\t\t\t<column name=\"{$name}\"", (is_null($v) ? ' null="null"' : ''), ">{$v}</column>\n";
234
                        }
235
                        echo "\t\t</row>\n";
236
                        $rs->moveNext();
237
                    }
238
                    echo "\t</records>\n";
239
                    echo "</data>\n";
240
                } elseif ('sql' == $format) {
241
                    $data->fieldClean($_REQUEST['table']);
242
                    while (!$rs->EOF) {
243
                        echo "INSERT INTO \"{$_REQUEST['table']}\" (";
244
                        $first = true;
245
                        $j     = 0;
246
                        foreach ($rs->fields as $k => $v) {
247
                            $finfo = $rs->fetchField($j++);
248
                            $k     = $finfo->name;
249
                            // SQL (INSERT) format cannot handle oids
250
                            //                        if ($k == $data->id) continue;
251
                            // Output field
252
                            $data->fieldClean($k);
253
                            if ($first) {
254
                                echo "\"{$k}\"";
255
                            } else {
256
                                echo ", \"{$k}\"";
257
                            }
258
259
                            if (!is_null($v)) {
260
                                // Output value
261
                                // addCSlashes converts all weird ASCII characters to octal representation,
262
                                // EXCEPT the 'special' ones like \r \n \t, etc.
263
                                $v = addcslashes($v, "\0..\37\177..\377");
264
                                // We add an extra escaping slash onto octal encoded characters
265
                                $v = preg_replace('/\\\\([0-7]{3})/', '\\\1', $v);
266
                                // Finally, escape all apostrophes
267
                                $v = str_replace("'", "''", $v);
268
                            }
269
                            if ($first) {
270
                                $values = (is_null($v) ? 'NULL' : "'{$v}'");
271
                                $first  = false;
272
                            } else {
273
                                $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...
274
                            }
275
                        }
276
                        echo ") VALUES ({$values});\n";
277
                        $rs->moveNext();
278
                    }
279
                } else {
280
                    switch ($format) {
281
                        case 'tab':
282
                            $sep = "\t";
283
284
                            break;
285
                        case 'csv':
286
                        default:
287
                            $sep = ',';
288
289
                            break;
290
                    }
291
                    if (!$rs->EOF) {
292
                        // Output header row
293
                        $first = true;
294
                        foreach ($rs->fields as $k => $v) {
295
                            $finfo = $rs->fetchField($k);
296
                            $v     = $finfo->name;
297
                            if (!is_null($v)) {
298
                                $v = str_replace('"', '""', $v);
299
                            }
300
301
                            if ($first) {
302
                                echo "\"{$v}\"";
303
                                $first = false;
304
                            } else {
305
                                echo "{$sep}\"{$v}\"";
306
                            }
307
                        }
308
                        echo "\r\n";
309
                    }
310
                    while (!$rs->EOF) {
311
                        $first = true;
312
                        foreach ($rs->fields as $k => $v) {
313
                            if (!is_null($v)) {
314
                                $v = str_replace('"', '""', $v);
315
                            }
316
317
                            if ($first) {
318
                                echo (is_null($v)) ? '"\\N"' : "\"{$v}\"";
319
                                $first = false;
320
                            } else {
321
                                echo is_null($v) ? "{$sep}\"\\N\"" : "{$sep}\"{$v}\"";
322
                            }
323
                        }
324
                        echo "\r\n";
325
                        $rs->moveNext();
326
                    }
327
                }
328
            }
329
330
            // If the dump is not dataonly then dump the structure suffix
331
            if ('dataonly' != $_REQUEST['what']) {
332
                // Set fetch mode back to ASSOC for the table suffix to work
333
                $data->conn->setFetchMode(ADODB_FETCH_ASSOC);
334
                echo $data->getTableDefSuffix($_REQUEST['table']);
335
            }
336
337
            // Finish the dump transaction
338
            $status = $data->endDump();
339
        } else {
340
            return $this->doDefault();
341
        }
342
    }
343
344
    public function doDefault($msg = '')
1 ignored issue
show
Coding Style introduced by
Missing function doc comment
Loading history...
345
    {
346
        $lang   = $this->lang;
347
        $data   = $this->misc->getDatabaseAccessor();
1 ignored issue
show
Unused Code introduced by
The assignment to $data is dead and can be removed.
Loading history...
348
        $action = $this->action;
1 ignored issue
show
Unused Code introduced by
The assignment to $action is dead and can be removed.
Loading history...
349
350
        if (!isset($_REQUEST['query']) or empty($_REQUEST['query'])) {
351
            $_REQUEST['query'] = $_SESSION['sqlquery'];
352
        }
353
354
        $this->printHeader($lang['strexport']);
355
        $this->printBody();
356
        $this->printTrail(isset($_REQUEST['subject']) ? $_REQUEST['subject'] : 'database');
357
        $this->printTitle($lang['strexport']);
358
        if (isset($msg)) {
359
            $this->printMsg($msg);
360
        }
361
362
        echo '<form action="' . \SUBFOLDER . "/src/views/dataexport.php\" method=\"post\">\n";
363
        echo "<table>\n";
364
        echo "<tr><th class=\"data\">{$lang['strformat']}:</th><td><select name=\"d_format\">\n";
365
        // COPY and SQL require a table
366
        if (isset($_REQUEST['table'])) {
367
            echo "<option value=\"copy\">COPY</option>\n";
368
            echo "<option value=\"sql\">SQL</option>\n";
369
        }
370
        echo "<option value=\"csv\">CSV</option>\n";
371
        echo "<option value=\"tab\">{$lang['strtabbed']}</option>\n";
372
        echo "<option value=\"html\">XHTML</option>\n";
373
        echo "<option value=\"xml\">XML</option>\n";
374
        echo '</select></td></tr>';
375
        echo "</table>\n";
376
377
        echo "<h3>{$lang['stroptions']}</h3>\n";
378
        echo "<p><input type=\"radio\" id=\"output1\" name=\"output\" value=\"show\" checked=\"checked\" /><label for=\"output1\">{$lang['strshow']}</label>\n";
379
        echo "<br/><input type=\"radio\" id=\"output2\" name=\"output\" value=\"download\" /><label for=\"output2\">{$lang['strdownload']}</label></p>\n";
380
381
        echo "<p><input type=\"hidden\" name=\"action\" value=\"export\" />\n";
382
        echo "<input type=\"hidden\" name=\"what\" value=\"dataonly\" />\n";
383
        if (isset($_REQUEST['table'])) {
384
            echo '<input type="hidden" name="table" value="', htmlspecialchars($_REQUEST['table']), "\" />\n";
385
        }
386
        echo '<input type="hidden" name="query" value="', htmlspecialchars(urlencode($_REQUEST['query'])), "\" />\n";
387
        if (isset($_REQUEST['search_path'])) {
388
            echo '<input type="hidden" name="search_path" value="', htmlspecialchars($_REQUEST['search_path']), "\" />\n";
389
        }
390
        echo $this->misc->form;
391
        echo "<input type=\"submit\" value=\"{$lang['strexport']}\" /></p>\n";
392
        echo "</form>\n";
393
394
        $this->printFooter();
395
    }
396
}
397