* @license GNU General Public License, version 2 (GPL-2.0) * * For full copyright and license information, please see * the docs/CREDITS.txt file. * */ namespace phpbb\db\extractor; use phpbb\db\extractor\exception\extractor_not_initialized_exception; class postgres_extractor extends base_extractor { /** * {@inheritdoc} */ public function write_start($table_prefix) { if (!$this->is_initialized) { throw new extractor_not_initialized_exception(); } $sql_data = "--\n"; $sql_data .= "-- phpBB Backup Script\n"; $sql_data .= "-- Dump of tables for $table_prefix\n"; $sql_data .= "-- DATE : " . gmdate("d-m-Y H:i:s", $this->time) . " GMT\n"; $sql_data .= "--\n"; $sql_data .= "BEGIN TRANSACTION;\n"; $this->flush($sql_data); } /** * {@inheritdoc} */ public function write_table($table_name) { static $domains_created = array(); if (!$this->is_initialized) { throw new extractor_not_initialized_exception(); } $sql = "SELECT a.domain_name, a.data_type, a.character_maximum_length, a.domain_default FROM INFORMATION_SCHEMA.domains a, INFORMATION_SCHEMA.column_domain_usage b WHERE a.domain_name = b.domain_name AND b.table_name = '{$table_name}'"; $result = $this->db->sql_query($sql); while ($row = $this->db->sql_fetchrow($result)) { if (empty($domains_created[$row['domain_name']])) { $domains_created[$row['domain_name']] = true; //$sql_data = "DROP DOMAIN {$row['domain_name']};\n"; $sql_data = "CREATE DOMAIN {$row['domain_name']} as {$row['data_type']}"; if (!empty($row['character_maximum_length'])) { $sql_data .= '(' . $row['character_maximum_length'] . ')'; } $sql_data .= ' NOT NULL'; if (!empty($row['domain_default'])) { $sql_data .= ' DEFAULT ' . $row['domain_default']; } $this->flush($sql_data . ";\n"); } } $this->db->sql_freeresult($result); $sql_data = '-- Table: ' . $table_name . "\n"; $sql_data .= "DROP TABLE $table_name;\n"; // PGSQL does not "tightly" bind sequences and tables, we must guess... $sql = "SELECT relname FROM pg_class WHERE relkind = 'S' AND relname = '{$table_name}_seq'"; $result = $this->db->sql_query($sql); // We don't even care about storing the results. We already know the answer if we get rows back. if ($this->db->sql_fetchrow($result)) { $sql_data .= "DROP SEQUENCE IF EXISTS {$table_name}_seq;\n"; $sql_data .= "CREATE SEQUENCE {$table_name}_seq;\n"; } $this->db->sql_freeresult($result); $field_query = "SELECT a.attnum, a.attname as field, t.typname as type, a.attlen as length, a.atttypmod as lengthvar, a.attnotnull as notnull FROM pg_class c, pg_attribute a, pg_type t WHERE c.relname = '" . $this->db->sql_escape($table_name) . "' AND a.attnum > 0 AND a.attrelid = c.oid AND a.atttypid = t.oid ORDER BY a.attnum"; $result = $this->db->sql_query($field_query); $sql_data .= "CREATE TABLE $table_name(\n"; $lines = array(); while ($row = $this->db->sql_fetchrow($result)) { // Get the data from the table $sql_get_default = "SELECT pg_get_expr(d.adbin, d.adrelid) as rowdefault FROM pg_attrdef d, pg_class c WHERE (c.relname = '" . $this->db->sql_escape($table_name) . "') AND (c.oid = d.adrelid) AND d.adnum = " . $row['attnum']; $def_res = $this->db->sql_query($sql_get_default); $def_row = $this->db->sql_fetchrow($def_res); $this->db->sql_freeresult($def_res); if (empty($def_row)) { unset($row['rowdefault']); } else { $row['rowdefault'] = $def_row['rowdefault']; } if ($row['type'] == 'bpchar') { // Internally stored as bpchar, but isn't accepted in a CREATE TABLE statement. $row['type'] = 'char'; } $line = ' ' . $row['field'] . ' ' . $row['type']; if (strpos($row['type'], 'char') !== false) { if ($row['lengthvar'] > 0) { $line .= '(' . ($row['lengthvar'] - 4) . ')'; } } if (strpos($row['type'], 'numeric') !== false) { $line .= '('; $line .= sprintf("%s,%s", (($row['lengthvar'] >> 16) & 0xffff), (($row['lengthvar'] - 4) & 0xffff)); $line .= ')'; } if (isset($row['rowdefault'])) { $line .= ' DEFAULT ' . $row['rowdefault']; } if ($row['notnull'] == 't') { $line .= ' NOT NULL'; } $lines[] = $line; } $this->db->sql_freeresult($result); // Get the listing of primary keys. $sql_pri_keys = "SELECT ic.relname as index_name, bc.relname as tab_name, ta.attname as column_name, i.indisunique as unique_key, i.indisprimary as primary_key FROM pg_class bc, pg_class ic, pg_index i, pg_attribute ta, pg_attribute ia WHERE (bc.oid = i.indrelid) AND (ic.oid = i.indexrelid) AND (ia.attrelid = i.indexrelid) AND (ta.attrelid = bc.oid) AND (bc.relname = '" . $this->db->sql_escape($table_name) . "') AND (ta.attrelid = i.indrelid) AND (ta.attnum = i.indkey[ia.attnum-1]) ORDER BY index_name, tab_name, column_name"; $result = $this->db->sql_query($sql_pri_keys); $index_create = $index_rows = $primary_key = array(); // We do this in two steps. It makes placing the comma easier while ($row = $this->db->sql_fetchrow($result)) { if ($row['primary_key'] == 't') { $primary_key[] = $row['column_name']; $primary_key_name = $row['index_name']; } else { // We have to store this all this info because it is possible to have a multi-column key... // we can loop through it again and build the statement $index_rows[$row['index_name']]['table'] = $table_name; $index_rows[$row['index_name']]['unique'] = ($row['unique_key'] == 't') ? true : false; $index_rows[$row['index_name']]['column_names'][] = $row['column_name']; } } $this->db->sql_freeresult($result); if (!empty($index_rows)) { foreach ($index_rows as $idx_name => $props) { $index_create[] = 'CREATE ' . ($props['unique'] ? 'UNIQUE ' : '') . "INDEX $idx_name ON $table_name (" . implode(', ', $props['column_names']) . ");"; } } if (!empty($primary_key)) { $lines[] = " CONSTRAINT $primary_key_name PRIMARY KEY (" . implode(', ', $primary_key) . ")"; } // Generate constraint clauses for CHECK constraints $sql_checks = "SELECT conname as index_name, consrc FROM pg_constraint, pg_class bc WHERE conrelid = bc.oid AND bc.relname = '" . $this->db->sql_escape($table_name) . "' AND NOT EXISTS ( SELECT * FROM pg_constraint as c, pg_inherits as i WHERE i.inhrelid = pg_constraint.conrelid AND c.conname = pg_constraint.conname AND c.consrc = pg_constraint.consrc AND c.conrelid = i.inhparent )"; $result = $this->db->sql_query($sql_checks); // Add the constraints to the sql file. while ($row = $this->db->sql_fetchrow($result)) { if (!is_null($row['consrc'])) { $lines[] = ' CONSTRAINT ' . $row['index_name'] . ' CHECK ' . $row['consrc']; } } $this->db->sql_freeresult($result); $sql_data .= implode(", \n", $lines); $sql_data .= "\n);\n"; if (!empty($index_create)) { $sql_data .= implode("\n", $index_create) . "\n\n"; } $this->flush($sql_data); } /** * {@inheritdoc} */ public function write_data($table_name) { if (!$this->is_initialized) { throw new extractor_not_initialized_exception(); } // Grab all of the data from current table. $sql = "SELECT * FROM $table_name"; $result = $this->db->sql_query($sql); $i_num_fields = pg_num_fields($result); $seq = ''; for ($i = 0; $i < $i_num_fields; $i++) { $ary_type[] = pg_field_type($result, $i); $ary_name[] = pg_field_name($result, $i); $sql = "SELECT pg_get_expr(d.adbin, d.adrelid) as rowdefault FROM pg_attrdef d, pg_class c WHERE (c.relname = '{$table_name}') AND (c.oid = d.adrelid) AND d.adnum = " . strval($i + 1); $result2 = $this->db->sql_query($sql); if ($row = $this->db->sql_fetchrow($result2)) { // Determine if we must reset the sequences if (strpos($row['rowdefault'], "nextval('") === 0) { $seq .= "SELECT SETVAL('{$table_name}_seq',(select case when max({$ary_name[$i]})>0 then max({$ary_name[$i]})+1 else 1 end FROM {$table_name}));\n"; } } } $this->flush("COPY $table_name (" . implode(', ', $ary_name) . ') FROM stdin;' . "\n"); while ($row = $this->db->sql_fetchrow($result)) { $schema_vals = array(); // Build the SQL statement to recreate the data. for ($i = 0; $i < $i_num_fields; $i++) { $str_val = $row[$ary_name[$i]]; if (preg_match('#char|text|bool|bytea#i', $ary_type[$i])) { $str_val = str_replace(array("\n", "\t", "\r", "\b", "\f", "\v"), array('\n', '\t', '\r', '\b', '\f', '\v'), addslashes($str_val)); $str_empty = ''; } else { $str_empty = '\N'; } if (empty($str_val) && $str_val !== '0') { $str_val = $str_empty; } $schema_vals[] = $str_val; } // Take the ordered fields and their associated data and build it // into a valid sql statement to recreate that field in the data. $this->flush(implode("\t", $schema_vals) . "\n"); } $this->db->sql_freeresult($result); $this->flush("\\.\n"); // Write out the sequence statements $this->flush($seq); } /** * Writes closing line(s) to database backup * * @return null * @throws \phpbb\db\extractor\exception\extractor_not_initialized_exception when calling this function before init_extractor() */ public function write_end() { if (!$this->is_initialized) { throw new extractor_not_initialized_exception(); } $this->flush("COMMIT;\n"); parent::write_end(); } } d='n223' href='#n223'>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 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598
#!/usr/bin/perl -wT
# -*- Mode: perl; indent-tabs-mode: nil -*-
#
# The contents of this file are subject to the Mozilla Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is the Bugzilla Bug Tracking System.
# 
# The Initial Developer of the Original Code is Netscape Communications
# Corporation. Portions created by Netscape are Copyright (C) 1998
# Netscape Communications Corporation. All Rights Reserved.
# 
# Contributor(s): Terry Weissman <terry@mozilla.org>
#                 Dave Miller <justdave@syndicomm.com>
#                 Joe Robins <jmrobins@tgix.com>
#                 Gervase Markham <gerv@gerv.net>
#                 Shane H. W. Travis <travis@sedsystems.ca>

##############################################################################
#
# enter_bug.cgi
# -------------
# Displays bug entry form. Bug fields are specified through popup menus, 
# drop-down lists, or text fields. Default for these values can be 
# passed in as parameters to the cgi.
#
##############################################################################

use strict;

use lib qw(. lib);

use Bugzilla;
use Bugzilla::Constants;
use Bugzilla::Util;
use Bugzilla::Error;
use Bugzilla::Bug;
use Bugzilla::User;
use Bugzilla::Hook;
use Bugzilla::Product;
use Bugzilla::Classification;
use Bugzilla::Keyword;
use Bugzilla::Token;
use Bugzilla::Field;
use Bugzilla::Status;

my $user = Bugzilla->login(LOGIN_REQUIRED);

my $cloned_bug;
my $cloned_bug_id;

my $cgi = Bugzilla->cgi;
my $dbh = Bugzilla->dbh;
my $template = Bugzilla->template;
my $vars = {};

# All pages point to the same part of the documentation.
$vars->{'doc_section'} = 'bugreports.html';

my $product_name = trim($cgi->param('product') || '');
# Will contain the product object the bug is created in.
my $product;

if ($product_name eq '') {
    # If the user cannot enter bugs in any product, stop here.
    my @enterable_products = @{$user->get_enterable_products};
    ThrowUserError('no_products') unless scalar(@enterable_products);

    my $classification = Bugzilla->params->{'useclassification'} ?
        scalar($cgi->param('classification')) : '__all';

    # Unless a real classification name is given, we sort products
    # by classification.
    my @classifications;

    unless ($classification && $classification ne '__all') {
        if (Bugzilla->params->{'useclassification'}) {
            my $class;
            # Get all classifications with at least one enterable product.
            foreach my $product (@enterable_products) {
                $class->{$product->classification_id}->{'object'} ||=
                    new Bugzilla::Classification($product->classification_id);
                # Nice way to group products per classification, without querying
                # the DB again.
                push(@{$class->{$product->classification_id}->{'products'}}, $product);
            }
            @classifications = sort {$a->{'object'}->sortkey <=> $b->{'object'}->sortkey
                                     || lc($a->{'object'}->name) cmp lc($b->{'object'}->name)}
                                    (values %$class);
        }
        else {
            @classifications = ({object => undef, products => \@enterable_products});
        }
    }

    unless ($classification) {
        # We know there is at least one classification available,
        # else we would have stopped earlier.
        if (scalar(@classifications) > 1) {
            # We only need classification objects.
            $vars->{'classifications'} = [map {$_->{'object'}} @classifications];

            $vars->{'target'} = "enter_bug.cgi";
            $vars->{'format'} = $cgi->param('format');
            $vars->{'cloned_bug_id'} = $cgi->param('cloned_bug_id');

            print $cgi->header();
            $template->process("global/choose-classification.html.tmpl", $vars)
               || ThrowTemplateError($template->error());
            exit;
        }
        # If we come here, then there is only one classification available.
        $classification = $classifications[0]->{'object'}->name;
    }

    # Keep only enterable products which are in the specified classification.
    if ($classification ne "__all") {
        my $class = new Bugzilla::Classification({'name' => $classification});
        # If the classification doesn't exist, then there is no product in it.
        if ($class) {
            @enterable_products
              = grep {$_->classification_id == $class->id} @enterable_products;
            @classifications = ({object => $class, products => \@enterable_products});
        }
        else {
            @enterable_products = ();
        }
    }

    if (scalar(@enterable_products) == 0) {
        ThrowUserError('no_products');
    }
    elsif (scalar(@enterable_products) > 1) {
        $vars->{'classifications'} = \@classifications;
        $vars->{'target'} = "enter_bug.cgi";
        $vars->{'format'} = $cgi->param('format');
        $vars->{'cloned_bug_id'} = $cgi->param('cloned_bug_id');

        print $cgi->header();
        $template->process("global/choose-product.html.tmpl", $vars)
          || ThrowTemplateError($template->error());
        exit;
    } else {
        # Only one product exists.
        $product = $enterable_products[0];
    }
}
else {
    # Do not use Bugzilla::Product::check_product() here, else the user
    # could know whether the product doesn't exist or is not accessible.
    $product = new Bugzilla::Product({'name' => $product_name});
}

# We need to check and make sure that the user has permission
# to enter a bug against this product.
$user->can_enter_product($product ? $product->name : $product_name, THROW_ERROR);

##############################################################################
# Useful Subroutines
##############################################################################
sub formvalue {
    my ($name, $default) = (@_);
    return Bugzilla->cgi->param($name) || $default || "";
}

# Takes the name of a field and a list of possible values for that 
# field. Returns the first value in the list that is actually a 
# valid value for that field.
# The field should be named after its DB table.
# Returns undef if none of the platforms match.
sub pick_valid_field_value (@) {
    my ($field, @values) = @_;
    my $dbh = Bugzilla->dbh;

    foreach my $value (@values) {
        return $value if $dbh->selectrow_array(
            "SELECT 1 FROM $field WHERE value = ?", undef, $value); 
    }
    return undef;
}

sub pickplatform {
    return formvalue("rep_platform") if formvalue("rep_platform");

    my @platform;

    if (Bugzilla->params->{'defaultplatform'}) {
        @platform = Bugzilla->params->{'defaultplatform'};
    } else {
        # If @platform is a list, this function will return the first
        # item in the list that is a valid platform choice. If
        # no choice is valid, we return "Other".
        for ($ENV{'HTTP_USER_AGENT'}) {
        #PowerPC
            /\(.*PowerPC.*\)/i && do {@platform = "Macintosh"; last;};
            /\(.*PPC.*\)/ && do {@platform = "Macintosh"; last;};
            /\(.*AIX.*\)/ && do {@platform = "Macintosh"; last;};
        #Intel x86
            /\(.*Intel.*\)/ && do {@platform = "PC"; last;};
            /\(.*[ix0-9]86.*\)/ && do {@platform = "PC"; last;};
        #Versions of Windows that only run on Intel x86
            /\(.*Win(?:dows |)[39M].*\)/ && do {@platform = "PC"; last};
            /\(.*Win(?:dows |)16.*\)/ && do {@platform = "PC"; last;};
        #Sparc
            /\(.*sparc.*\)/ && do {@platform = "Sun"; last;};
            /\(.*sun4.*\)/ && do {@platform = "Sun"; last;};
        #Alpha
            /\(.*AXP.*\)/i && do {@platform = "DEC"; last;};
            /\(.*[ _]Alpha.\D/i && do {@platform = "DEC"; last;};
            /\(.*[ _]Alpha\)/i && do {@platform = "DEC"; last;};
        #MIPS
            /\(.*IRIX.*\)/i && do {@platform = "SGI"; last;};
            /\(.*MIPS.*\)/i && do {@platform = "SGI"; last;};
        #68k
            /\(.*68K.*\)/ && do {@platform = "Macintosh"; last;};
            /\(.*680[x0]0.*\)/ && do {@platform = "Macintosh"; last;};
        #HP
            /\(.*9000.*\)/ && do {@platform = "HP"; last;};
        #ARM
#            /\(.*ARM.*\) && do {$platform = "ARM";};
        #Stereotypical and broken
            /\(.*Macintosh.*\)/ && do {@platform = "Macintosh"; last;};
            /\(.*Mac OS [89].*\)/ && do {@platform = "Macintosh"; last;};
            /\(Win.*\)/ && do {@platform = "PC"; last;};
            /\(.*Win(?:dows[ -])NT.*\)/ && do {@platform = "PC"; last;};
            /\(.*OSF.*\)/ && do {@platform = "DEC"; last;};
            /\(.*HP-?UX.*\)/i && do {@platform = "HP"; last;};
            /\(.*IRIX.*\)/i && do {@platform = "SGI"; last;};
            /\(.*(SunOS|Solaris).*\)/ && do {@platform = "Sun"; last;};
        #Braindead old browsers who didn't follow convention:
            /Amiga/ && do {@platform = "Macintosh"; last;};
            /WinMosaic/ && do {@platform = "PC"; last;};
        }
    }

    return pick_valid_field_value('rep_platform', @platform) || "Other";
}

sub pickos {
    if (formvalue('op_sys') ne "") {
        return formvalue('op_sys');
    }

    my @os = ();

    if (Bugzilla->params->{'defaultopsys'}) {
        @os = Bugzilla->params->{'defaultopsys'};
    } else {
        # This function will return the first
        # item in @os that is a valid platform choice. If
        # no choice is valid, we return "Other".
        for ($ENV{'HTTP_USER_AGENT'}) {
            /\(.*IRIX.*\)/ && do {push @os, "IRIX"; };
            /\(.*OSF.*\)/ && do {push @os, "OSF/1";};
            /\(.*Linux.*\)/ && do {push @os, "Linux";};
            /\(.*Solaris.*\)/ && do {push @os, "Solaris";};
            /\(.*SunOS.*\)/ && do {
              /\(.*SunOS 5.11.*\)/ && do {push @os, ("OpenSolaris", "Opensolaris", "Solaris 11");};
              /\(.*SunOS 5.10.*\)/ && do {push @os, "Solaris 10";};
              /\(.*SunOS 5.9.*\)/ && do {push @os, "Solaris 9";};
              /\(.*SunOS 5.8.*\)/ && do {push @os, "Solaris 8";};
              /\(.*SunOS 5.7.*\)/ && do {push @os, "Solaris 7";};
              /\(.*SunOS 5.6.*\)/ && do {push @os, "Solaris 6";};
              /\(.*SunOS 5.5.*\)/ && do {push @os, "Solaris 5";};
              /\(.*SunOS 5.*\)/ && do {push @os, "Solaris";};
              /\(.*SunOS.*sun4u.*\)/ && do {push @os, "Solaris";};
              /\(.*SunOS.*i86pc.*\)/ && do {push @os, "Solaris";};
              /\(.*SunOS.*\)/ && do {push @os, "SunOS";};
            };