Welcome to mirror list, hosted at ThFree Co, Russian Federation.

DataexportController.php « controllers « src - github.com/HuasoFoundries/phpPgAdmin6.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: defdacb7cdad8ebd1a283de6d34c9a37855d21af (plain)
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
<?php

/**
 * PHPPgAdmin v6.0.0-RC4
 */

namespace PHPPgAdmin\Controller;

/**
 * Base controller class.
 *
 * @package PHPPgAdmin
 */
class DataexportController extends BaseController
{
    public $extensions = [
        'sql'  => 'sql',
        'copy' => 'sql',
        'csv'  => 'csv',
        'tab'  => 'txt',
        'html' => 'html',
        'xml'  => 'xml',
    ];
    public $controller_title = 'strexport';

    /**
     * Default method to render the controller according to the action parameter.
     */
    public function render()
    {
        set_time_limit(0);

        // if (!isset($_REQUEST['table']) && !isset($_REQUEST['query']))
        // What must we do in this case? Maybe redirect to the homepage?

        $format = 'N/A';

        // force behavior to assume there is no pg_dump in the system
        $forcemimic = isset($_REQUEST['forcemimic']) ? $_REQUEST['forcemimic'] : false;

        // If format is set, then perform the export
        if (!isset($_REQUEST['what'])) {
            return $this->doDefault();
        }

        $this->prtrace("REQUEST['what']", $_REQUEST['what']);

        // Include application functions
        $this->setNoOutput(true);
        $clean = false;
        $oids  = false;
        switch ($_REQUEST['what']) {
            case 'dataonly':
                // Check to see if they have pg_dump set up and if they do, use that
                // instead of custom dump code
                if (!$forcemimic && $this->misc->isDumpEnabled() && ('copy' == $_REQUEST['d_format'] || 'sql' == $_REQUEST['d_format'])) {
                    $this->prtrace('DUMP ENABLED, d_format is', $_REQUEST['d_format']);
                    $dbexport_controller = new \PHPPgAdmin\Controller\DbexportController($this->getContainer());

                    return $dbexport_controller->render();
                }
                $this->prtrace('d_format is', $_REQUEST['d_format'], 'd_oids is', isset($_REQUEST['d_oids']));
                $format = $_REQUEST['d_format'];
                $oids   = isset($_REQUEST['d_oids']);

                break;
            case 'structureonly':
                // Check to see if they have pg_dump set up and if they do, use that
                // instead of custom dump code
                if (!$forcemimic && $this->misc->isDumpEnabled()) {
                    $dbexport_controller = new \PHPPgAdmin\Controller\DbexportController($this->getContainer());

                    return $dbexport_controller->render();
                }
                $clean = isset($_REQUEST['s_clean']);

                break;
            case 'structureanddata':
                // Check to see if they have pg_dump set up and if they do, use that
                // instead of custom dump code
                if (!$forcemimic && $this->misc->isDumpEnabled()) {
                    $dbexport_controller = new \PHPPgAdmin\Controller\DbexportController($this->getContainer());

                    return $dbexport_controller->render();
                }
                $format = $_REQUEST['sd_format'];
                $clean  = isset($_REQUEST['sd_clean']);
                $oids   = isset($_REQUEST['sd_oids']);

                break;
        }
        $cleanprefix = $clean ? '' : '-- ';

        return $this->mimicDumpFeature($format, $cleanprefix, $oids);
    }

    protected function mimicDumpFeature($format, $cleanprefix, $oids)
    {
        $data = $this->misc->getDatabaseAccessor();

        set_time_limit(0);

        // if (!isset($_REQUEST['table']) && !isset($_REQUEST['query']))
        // What must we do in this case? Maybe redirect to the homepage?

        // If format is set, then perform the export
        if (!isset($_REQUEST['what'])) {
            return $this->doDefault();
        }

        $this->prtrace("REQUEST['what']", $_REQUEST['what']);

        // Include application functions
        $this->setNoOutput(true);

        $response = $this->_getResponse($format);

        $this->coalesceArr($_REQUEST, 'query', '');

        $_REQUEST['query'] = trim(urldecode($_REQUEST['query']));

        // Set the schema search path
        if (isset($_REQUEST['search_path'])) {
            $data->setSearchPath(array_map('trim', explode(',', $_REQUEST['search_path'])));
        } elseif (isset($_REQUEST['schema'])) {
            $data->setSearchPath($_REQUEST['schema']);
        }

        $subject = $this->coalesceArr($_REQUEST, 'subject', 'table')['subject'];

        $object = $this->coalesceArr($_REQUEST, $subject)[$subject];

        // Set up the dump transaction
        $status = $data->beginDump();
        $this->prtrace('subject', $subject);
        $this->prtrace('object', $object);
        $tabledefprefix = '';
        $tabledefsuffix = '';

        // If the dump is not dataonly then dump the structure prefix
        if ('dataonly' != $_REQUEST['what']) {
            $tabledefprefix = $data->getTableDefPrefix($object, $cleanprefix);
            $this->prtrace('tabledefprefix', $tabledefprefix);
            echo $tabledefprefix;
        }

        // If the dump is not structureonly then dump the actual data
        if ('structureonly' != $_REQUEST['what']) {
            // Get database encoding
            //$dbEncoding = $data->getDatabaseEncoding();

            // Set fetch mode to NUM so that duplicate field names are properly returned
            $data->conn->setFetchMode(\ADODB_FETCH_NUM);

            // Execute the query, if set, otherwise grab all rows from the table
            $rs = $this->_getRS($data, $object, $oids);

            $response = $this->pickFormat($data, $object, $oids, $rs, $format, $response);
        }
        if ('dataonly' != $_REQUEST['what']) {
            $data->conn->setFetchMode(\ADODB_FETCH_ASSOC);
            $tabledefsuffix = $data->getTableDefSuffix($object);
            $this->prtrace('tabledefsuffix', $tabledefsuffix);
            echo $tabledefsuffix;
        }

        // Finish the dump transaction
        $status = $data->endDump();

        return $response;
    }

    private function _getRS($data, $object, $oids)
    {
        if ($object) {
            return $data->dumpRelation($object, $oids);
        }

        $this->prtrace('$_REQUEST[query]', $_REQUEST['query']);

        return $data->conn->Execute($_REQUEST['query']);
    }

    private function _getResponse($format)
    {
        $response = $this
            ->container
            ->responseobj;

        // Make it do a download, if necessary
        if ('download' !== $_REQUEST['output']) {
            return $response
                ->withHeader('Content-type', 'text/plain');
        }
        // Set headers.  MSIE is totally broken for SSL downloading, so
        // we need to have it download in-place as plain text
        if (strstr($_SERVER['HTTP_USER_AGENT'], 'MSIE') && isset($_SERVER['HTTPS'])) {
            return $response
                ->withHeader('Content-type', 'text/plain');
        }
        $response = $response
            ->withHeader('Content-type', 'application/download');

        $ext = 'txt';
        if (isset($this->extensions[$format])) {
            $ext = $this->extensions[$format];
        }

        return $response
            ->withHeader('Content-Disposition', 'attachment; filename=dump.'.$ext);
    }

    private function pickFormat($data, $object, $oids, $rs, $format, $response)
    {
        if ('copy' == $format) {
            $this->_mimicCopy($data, $object, $oids, $rs);
        } elseif ('html' == $format) {
            $response = $response
                ->withHeader('Content-type', 'text/html');
            $this->_mimicHtml($data, $object, $oids, $rs);
        } elseif ('xml' == $format) {
            $response = $response
                ->withHeader('Content-type', 'application/xml');
            $this->_mimicXml($data, $object, $oids, $rs);
        } elseif ('sql' == $format) {
            $this->_mimicSQL($data, $object, $oids, $rs);
        }
        $this->_csvOrTab($data, $object, $oids, $rs, $format);

        return $response;
    }

    public function doDefault($msg = '')
    {
        if (!isset($_REQUEST['query']) || empty($_REQUEST['query'])) {
            $_REQUEST['query'] = $_SESSION['sqlquery'];
        }

        $this->printHeader();
        $this->printBody();
        $this->printTrail(isset($_REQUEST['subject']) ? $_REQUEST['subject'] : 'database');
        $this->printTitle($this->lang['strexport']);
        if (isset($msg)) {
            $this->printMsg($msg);
        }

        echo '<form action="'.\SUBFOLDER.'/src/views/dataexport" method="post">'.PHP_EOL;
        echo '<table>'.PHP_EOL;
        echo "<tr><th class=\"data\">{$this->lang['strformat']}:</th><td><select name=\"d_format\">".PHP_EOL;
        // COPY and SQL require a table
        if (isset($_REQUEST['table'])) {
            echo '<option value="copy">COPY</option>'.PHP_EOL;
            echo '<option value="sql">SQL</option>'.PHP_EOL;
        }
        echo '<option value="csv">CSV</option>'.PHP_EOL;
        echo "<option value=\"tab\">{$this->lang['strtabbed']}</option>".PHP_EOL;
        echo '<option value="html">XHTML</option>'.PHP_EOL;
        echo '<option value="xml">XML</option>'.PHP_EOL;
        echo '</select></td></tr>';
        echo '</table>'.PHP_EOL;

        echo "<h3>{$this->lang['stroptions']}</h3>".PHP_EOL;
        echo "<p><input type=\"radio\" id=\"output1\" name=\"output\" value=\"show\" checked=\"checked\" /><label for=\"output1\">{$this->lang['strshow']}</label>".PHP_EOL;
        echo "<br/><input type=\"radio\" id=\"output2\" name=\"output\" value=\"download\" /><label for=\"output2\">{$this->lang['strdownload']}</label></p>".PHP_EOL;

        echo '<p><input type="hidden" name="action" value="export" />'.PHP_EOL;
        echo '<input type="hidden" name="what" value="dataonly" />'.PHP_EOL;
        if (isset($_REQUEST['table'])) {
            echo '<input type="hidden" name="subject" value="table" />'.PHP_EOL;
            echo '<input type="hidden" name="table" value="', htmlspecialchars($_REQUEST['table']), '" />'.PHP_EOL;
        } else {
            echo '<input type="hidden" name="subject" value="table" />'.PHP_EOL;
        }
        $this->prtrace('$_REQUEST[query]', $_REQUEST['query'], htmlspecialchars(urlencode($_REQUEST['query'])));
        $this->prtrace('$_SESSION[sqlquery]', $_SESSION['sqlquery'], htmlspecialchars(urlencode($_SESSION['sqlquery'])));
        echo '<input type="hidden" name="query" value="', htmlspecialchars(urlencode($_REQUEST['query'])), '" />'.PHP_EOL;
        if (isset($_REQUEST['search_path'])) {
            echo '<input type="hidden" name="search_path" value="', htmlspecialchars($_REQUEST['search_path']), '" />'.PHP_EOL;
        }
        echo $this->misc->form;
        echo "<input type=\"submit\" value=\"{$this->lang['strexport']}\" /></p>".PHP_EOL;
        echo '</form>'.PHP_EOL;

        $this->printFooter();
    }

    private function _mimicCopy($data, $object, $oids, $rs)
    {
        $data->fieldClean($object);
        echo "COPY \"{$_REQUEST['table']}\"";
        if ($oids) {
            echo ' WITH OIDS';
        }

        echo " FROM stdin;\n";
        while (!$rs->EOF) {
            $first = true;
            //while (list($k, $v) = each($rs->fields)) {
            foreach ($rs->fields as $k => $v) {
                // Escape value
                $v = $data->escapeBytea($v);

                // We add an extra escaping slash onto octal encoded characters
                $v = preg_replace('/\\\\([0-7]{3})/', '\\\\\1', $v);
                if ($first) {
                    echo (is_null($v)) ? '\\N' : $v;
                    $first = false;
                } else {
                    echo "\t", (is_null($v)) ? '\\N' : $v;
                }
            }
            echo PHP_EOL;
            $rs->moveNext();
        }
        echo "\\.\n";
    }

    private function _mimicHtml($data, $object, $oids, $rs)
    {
        echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n";
        echo "<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n";
        echo "<head>\r\n";
        echo "\t<title></title>\r\n";
        echo "\t<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\r\n";
        echo "</head>\r\n";
        echo "<body>\r\n";
        echo "<table class=\"phppgadmin\">\r\n";
        echo "\t<tr>\r\n";
        if (!$rs->EOF) {
            // Output header row
            $j = 0;
            foreach ($rs->fields as $k => $v) {
                $finfo = $rs->fetchField($j++);
                if ($finfo->name == $data->id && !$oids) {
                    continue;
                }

                echo "\t\t<th>", $this->misc->printVal($finfo->name, 'verbatim'), "</th>\r\n";
            }
        }
        echo "\t</tr>\r\n";
        while (!$rs->EOF) {
            echo "\t<tr>\r\n";
            $j = 0;
            foreach ($rs->fields as $k => $v) {
                $finfo = $rs->fetchField($j++);
                if ($finfo->name == $data->id && !$oids) {
                    continue;
                }

                echo "\t\t<td>", $this->misc->printVal($v, 'verbatim', $finfo->type), "</td>\r\n";
            }
            echo "\t</tr>\r\n";
            $rs->moveNext();
        }
        echo "</table>\r\n";
        echo "</body>\r\n";
        echo "</html>\r\n";
    }

    private function _mimicXml($data, $object, $oids, $rs)
    {
        echo '<?xml version="1.0" encoding="utf-8" ?>'.PHP_EOL;
        echo '<data>'.PHP_EOL;
        if (!$rs->EOF) {
            // Output header row
            $j = 0;
            echo "\t<header>".PHP_EOL;
            foreach ($rs->fields as $k => $v) {
                $finfo = $rs->fetchField($j++);
                $name  = htmlspecialchars($finfo->name);
                $type  = htmlspecialchars($finfo->type);
                echo "\t\t<column name=\"{$name}\" type=\"{$type}\" />".PHP_EOL;
            }
            echo "\t</header>".PHP_EOL;
        }
        echo "\t<records>".PHP_EOL;
        while (!$rs->EOF) {
            $j = 0;
            echo "\t\t<row>".PHP_EOL;
            foreach ($rs->fields as $k => $v) {
                $finfo = $rs->fetchField($j++);
                $name  = htmlspecialchars($finfo->name);
                if (!is_null($v)) {
                    $v = htmlspecialchars($v);
                }

                echo "\t\t\t<column name=\"{$name}\"", (is_null($v) ? ' null="null"' : ''), ">{$v}</column>".PHP_EOL;
            }
            echo "\t\t</row>".PHP_EOL;
            $rs->moveNext();
        }
        echo "\t</records>".PHP_EOL;
        echo '</data>'.PHP_EOL;
    }

    private function _mimicSQL($data, $object, $oids, $rs)
    {
        $data->fieldClean($object);
        $values = '';
        while (!$rs->EOF) {
            echo "INSERT INTO \"{$object}\" (";
            $first = true;
            $j     = 0;
            foreach ($rs->fields as $k => $v) {
                $finfo = $rs->fetchField($j++);
                $k     = $finfo->name;
                // SQL (INSERT) format cannot handle oids
                //                        if ($k == $data->id) continue;
                // Output field
                $data->fieldClean($k);
                if ($first) {
                    echo "\"{$k}\"";
                } else {
                    echo ", \"{$k}\"";
                }

                if (!is_null($v)) {
                    // Output value
                    // addCSlashes converts all weird ASCII characters to octal representation,
                    // EXCEPT the 'special' ones like \r \n \t, etc.
                    $v = addcslashes($v, "\0..\37\177..\377");
                    // We add an extra escaping slash onto octal encoded characters
                    $v = preg_replace('/\\\\([0-7]{3})/', '\\\1', $v);
                    // Finally, escape all apostrophes
                    $v = str_replace("'", "''", $v);
                }
                if ($first) {
                    $values = (is_null($v) ? 'NULL' : "'{$v}'");
                    $first  = false;
                } else {
                    $values .= ', '.((is_null($v) ? 'NULL' : "'{$v}'"));
                }
            }
            echo ") VALUES ({$values});\n";
            $rs->moveNext();
        }
    }

    private function _csvOrTab($data, $object, $oids, $rs, $format)
    {
        switch ($format) {
            case 'tab':
                $sep = "\t";

                break;
            case 'csv':
            default:
                $sep = ',';

                break;
        }
        if (!$rs->EOF) {
            // Output header row
            $first = true;
            foreach ($rs->fields as $k => $v) {
                $finfo = $rs->fetchField($k);
                $v     = $finfo->name;
                if (!is_null($v)) {
                    $v = str_replace('"', '""', $v);
                }

                if ($first) {
                    echo "\"{$v}\"";
                    $first = false;
                } else {
                    echo "{$sep}\"{$v}\"";
                }
            }
            echo "\r\n";
        }
        while (!$rs->EOF) {
            $first = true;
            foreach ($rs->fields as $k => $v) {
                if (!is_null($v)) {
                    $v = str_replace('"', '""', $v);
                }

                if ($first) {
                    echo (is_null($v)) ? '"\\N"' : "\"{$v}\"";
                    $first = false;
                } else {
                    echo is_null($v) ? "{$sep}\"\\N\"" : "{$sep}\"{$v}\"";
                }
            }
            echo "\r\n";
            $rs->moveNext();
        }
    }
}