* @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\driver; interface driver_interface { /** * Set value for load_time debug parameter * * @param bool $value */ public function set_debug_load_time($value); /** * Set value for sql_explain debug parameter * * @param bool $value */ public function set_debug_sql_explain($value); /** * Gets the name of the sql layer. * * @return string */ public function get_sql_layer(); /** * Gets the name of the database. * * @return string */ public function get_db_name(); /** * Wildcards for matching any (%) character within LIKE expressions * * @return string */ public function get_any_char(); /** * Wildcards for matching exactly one (_) character within LIKE expressions * * @return string */ public function get_one_char(); /** * Gets the time spent into the queries * * @return int */ public function get_sql_time(); /** * Gets the connect ID. * * @return mixed */ public function get_db_connect_id(); /** * Indicates if an error was triggered. * * @return bool */ public function get_sql_error_triggered(); /** * Gets the last faulty query * * @return string */ public function get_sql_error_sql(); /** * Indicates if we are in a transaction. * * @return bool */ public function get_transaction(); /** * Gets the returned error. * * @return array */ public function get_sql_error_returned(); /** * Indicates if multiple insertion can be used * * @return bool */ public function get_multi_insert(); /** * Set if multiple insertion can be used * * @param bool $multi_insert */ public function set_multi_insert($multi_insert); /** * Gets the exact number of rows in a specified table. * * @param string $table_name Table name * @return string Exact number of rows in $table_name. */ public function get_row_count($table_name); /** * Gets the estimated number of rows in a specified table. * * @param string $table_name Table name * @return string Number of rows in $table_name. * Prefixed with ~ if estimated (otherwise exact). */ public function get_estimated_row_count($table_name); /** * Run LOWER() on DB column of type text (i.e. neither varchar nor char). * * @param string $column_name The column name to use * @return string A SQL statement like "LOWER($column_name)" */ public function sql_lower_text($column_name); /** * Display sql error page * * @param string $sql The SQL query causing the error * @return mixed Returns the full error message, if $this->return_on_error * is set, null otherwise */ public function sql_error($sql = ''); /** * Returns whether results of a query need to be buffered to run a * transaction while iterating over them. * * @return bool Whether buffering is required. */ public function sql_buffer_nested_transactions(); /** * Run binary OR operator on DB column. * * @param string $column_name The column name to use * @param int $bit The value to use for the OR operator, * will be converted to (1 << $bit). Is used by options, * using the number schema... 0, 1, 2...29 * @param string $compare Any custom SQL code after the check (e.g. "= 0") * @return string A SQL statement like "$column | (1 << $bit) {$compare}" */ public function sql_bit_or($column_name, $bit, $compare = ''); /** * Version information about used database * * @param bool $raw Only return the fetched sql_server_version * @param bool $use_cache Is it safe to retrieve the value from the cache * @return string sql server version */ public function sql_server_info($raw = false, $use_cache = true); /** * Return on error or display error message * * @param bool $fail Should we return on errors, or stop * @return null */ public function sql_return_on_error($fail = false); /** * Build sql statement from an array * * @param string $query Should be on of the following strings: * INSERT, INSERT_SELECT, UPDATE, SELECT, DELETE * @param array $assoc_ary Array with "column => value" pairs * @return string A SQL statement like "c1 = 'a' AND c2 = 'b'" */ public function sql_build_array($query, $assoc_ary = array()); /** * Fetch all rows * * @param mixed $query_id Already executed query to get the rows from, * if false, the last query will be used. * @return mixed Nested array if the query had rows, false otherwise */ public function sql_fetchrowset($query_id = false); /** * SQL Transaction * * @param string $status Should be one of the following strings: * begin, commit, rollback * @return mixed Buffered, seekable result handle, false on error */ public function sql_transaction($status = 'begin'); /** * Build a concatenated expression * * @param string $expr1 Base SQL expression where we append the second one * @param string $expr2 SQL expression that is appended to the first expression * @return string Concatenated string */ public function sql_concatenate($expr1, $expr2); /** * Build a case expression * * Note: The two statements action_true and action_false must have the same * data type (int, vchar, ...) in the database! * * @param string $condition The condition which must be true, * to use action_true rather then action_else * @param string $action_true SQL expression that is used, if the condition is true * @param mixed $action_false SQL expression that is used, if the condition is false * @return string CASE expression including the condition and statements */ public function sql_case($condition, $action_true, $action_false = false); /** * Build sql statement from array for select and select distinct statements * * Possible query values: SELECT, SELECT_DISTINCT * * @param string $query Should be one of: SELECT, SELECT_DISTINCT * @param array $array Array with the query data: * SELECT A comma imploded list of columns to select * FROM Array with "table => alias" pairs, * (alias can also be an array) * Optional: LEFT_JOIN Array of join entries: * FROM Table that should be joined * ON Condition for the join * Optional: WHERE Where SQL statement * Optional: GROUP_BY Group by SQL statement * Optional: ORDER_BY Order by SQL statement * @return string A SQL statement ready for execution */ public function sql_build_query($query, $array); /** * Fetch field * if rownum is false, the current row is used, else it is pointing to the row (zero-based) * * @param string $field Name of the column * @param mixed $rownum Row number, if false the current row will be used * and the row curser will point to the next row * Note: $rownum is 0 based * @param mixed $query_id Already executed query to get the rows from, * if false, the last query will be used. * @return mixed String value of the field in the selected row, * false, if the row does not exist */ public function sql_fetchfield($field, $rownum = false, $query_id = false); /** * Fetch current row * * @param mixed $query_id Already executed query to get the rows from, * if false, the last query will be used. * @return mixed Array with the current row, * false, if the row does not exist */ public function sql_fetchrow($query_id = false); /** * Returns SQL string to cast a string expression to an int. * * @param string $expression An expression evaluating to string * @return string Expression returning an int */ public function cast_expr_to_bigint($expression); /** * Get last inserted id after insert statement * * @return string Autoincrement value of the last inserted row */ public function sql_nextid(); /** * Add to query count * * @param bool $cached Is this query cached? * @return null */ public function sql_add_num_queries($cached = false); /** * Build LIMIT query * * @param string $query The SQL query to execute * @param int $total The number of rows to select * @param int $offset * @param int $cache_ttl Either 0 to avoid caching or * the time in seconds which the result shall be kept in cache * @return mixed Buffered, seekable result handle, false on error */ public function sql_query_limit($query, $total, $offset = 0, $cache_ttl = 0); /** * Base query method * * @param string $query The SQL query to execute * @param int $cache_ttl Either 0 to avoid caching or * the time in seconds which the result shall be kept in cache * @return mixed Buffered, seekable result handle, false on error */ public function sql_query($query = '', $cache_ttl = 0); /** * Returns SQL string to cast an integer expression to a string. * * @param string $expression An expression evaluating to int * @return string Expression returning a string */ public function cast_expr_to_string($expression); /** * Connect to server * * @param string $sqlserver Address of the database server * @param string $sqluser User name of the SQL user * @param string $sqlpassword Password of the SQL user * @param string $database Name of the database * @param mixed $port Port of the database server * @param bool $persistency * @param bool $new_link Should a new connection be established * @return mixed Connection ID on success, string error message otherwise */ public function sql_connect($sqlserver, $sqluser, $sqlpassword, $database, $port = false, $persistency = false, $new_link = false); /** * Run binary AND operator on DB column. * Results in sql statement: "{$column_name} & (1 << {$bit}) {$compare}" * * @param string $column_name The column name to use * @param int $bit The value to use for the AND operator, * will be converted to (1 << $bit). Is used by * options, using the number schema: 0, 1, 2...29 * @param string $compare Any custom SQL code after the check (for example "= 0") * @return string A SQL statement like: "{$column} & (1 << {$bit}) {$compare}" */ public function sql_bit_and($column_name, $bit, $compare = ''); /** * Free sql result * * @param mixed $query_id Already executed query result, * if false, the last query will be used. * @return null */ public function sql_freeresult($query_id = false); /** * Return number of sql queries and cached sql queries used * * @param bool $cached Should we return the number of cached or normal queries? * @return int Number of queries that have been executed */ public function sql_num_queries($cached = false); /** * Run more than one insert statement. * * @param string $table Table name to run the statements on * @param array $sql_ary Multi-dimensional array holding the statement data * @return bool false if no statements were executed. */ public function sql_multi_insert($table, $sql_ary); /** * Return number of affected rows * * @return mixed Number of the affected rows by the last query * false if no query has been run before */ public function sql_affectedrows(); /** * DBAL garbage collection, close SQL connection * * @return mixed False if no connection was opened before, * Server response otherwise */ public function sql_close(); /** * Seek to given row number * * @param mixed $rownum Row number the curser should point to * Note: $rownum is 0 based * @param mixed $query_id ID of the query to set the row cursor on * if false, the last query will be used. * $query_id will then be set correctly * @return bool False if something went wrong */ public function sql_rowseek($rownum, &$query_id); /** * Escape string used in sql query * * @param string $msg String to be escaped * @return string Escaped version of $msg */ public function sql_escape($msg); /** * Correctly adjust LIKE expression for special characters * Some DBMS are handling them in a different way * * @param string $expression The expression to use. Every wildcard is * escaped, except $this->any_char and $this->one_char * @return string A SQL statement like: "LIKE 'bertie_%'" */ public function sql_like_expression($expression); /** * Correctly adjust NOT LIKE expression for special characters * Some DBMS are handling them in a different way * * @param string $expression The expression to use. Every wildcard is * escaped, except $this->any_char and $this->one_char * @return string A SQL statement like: "NOT LIKE 'bertie_%'" */ public function sql_not_like_expression($expression); /** * Explain queries * * @param string $mode Available modes: display, start, stop, * add_select_row, fromcache, record_fromcache * @param string $query The Query that should be explained * @return mixed Either a full HTML page, boolean or null */ public function sql_report($mode, $query = ''); /** * Build IN or NOT IN sql comparison string, uses <> or = on single element * arrays to improve comparison speed * * @param string $field Name of the sql column that shall be compared * @param array $array Array of values that are (not) allowed * @param bool $negate true for NOT IN (), false for IN () * @param bool $allow_empty_set If true, allow $array to be empty, * this function will return 1=1 or 1=0 then. * @return string A SQL statement like: "IN (1, 2, 3, 4)" or "= 1" */ public function sql_in_set($field, $array, $negate = false, $allow_empty_set = false); } ' href='#n310'>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 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
# vim: set et ts=4 sw=4:
package AdminPanel::Rpmdragora::pkg;
#*****************************************************************************
#
#  Copyright (c) 2002 Guillaume Cottenceau
#  Copyright (c) 2002-2007 Thierry Vignaud <tvignaud@mandriva.com>
#  Copyright (c) 2003, 2004, 2005 MandrakeSoft SA
#  Copyright (c) 2005-2007 Mandriva SA
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License version 2, as
#  published by the Free Software Foundation.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
#*****************************************************************************
#
# $Id: pkg.pm 270160 2010-06-22 19:55:40Z jvictor $

use strict;
use MDK::Common::Func 'any';
use MDK::Common::DataStructure;
use MDK::Common::System;
use MDK::Common::File;
use MDK::Common::Various;

use POSIX qw(_exit ceil);
use URPM;
use utf8;
use AdminPanel::rpmdragora;
use AdminPanel::Rpmdragora::open_db;
use AdminPanel::Rpmdragora::gurpm;
use AdminPanel::Rpmdragora::formatting;
use AdminPanel::Rpmdragora::rpmnew;

use AdminPanel::rpmdragora;
use urpm;
use urpm::lock;
use urpm::install;
use urpm::signature;
use urpm::get_pkgs;
use urpm::select;
use urpm::main_loop;
use urpm::args qw();
use urpm::util;
use Carp;

my $loc = AdminPanel::rpmdragora::locale();

use Exporter;
our @ISA = qw(Exporter);
our @EXPORT = qw(
                    $priority_up_alread_warned
                    download_callback
                    extract_header
                    find_installed_version
                    get_pkgs
                    perform_installation
                    perform_removal
                    run_rpm
                    sort_packages
                    );

our $priority_up_alread_warned;

sub sort_packages_biarch {
    sort {
        my ($na, $aa) = $a =~ /^(.*-[^-]+-[^-]+)\.([^.-]+)$/;
        my ($nb, $ab) = $b =~ /^(.*-[^-]+-[^-]+)\.([^.-]+)$/;
        !defined($na) ?
            (!defined($nb) ? 0 : 1) :
            (!defined($nb) ? -1 : $na cmp $nb || ($ab =~ /64$/) <=> ($aa =~ /64$/));
    } @_;
}

sub sort_packages_monoarch {
    sort { uc($a) cmp uc($b) } @_;
}

*sort_packages = MDK::Common::System::arch() =~ /x86_64/ ? \&sort_packages_biarch : \&sort_packages_monoarch;

sub run_rpm {
    foreach (qw(LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT LC_IDENTIFICATION LC_ALL)) {
        local $ENV{$_} = $ENV{$_} . '.UTF-8' if $ENV{$_} && $ENV{$_} !~ /UTF-8/;
    }
    my @l = map { ensure_utf8($_); $_ } run_program::get_stdout(@_);
    wantarray() ? @l : join('', @l);
}


sub extract_header {
    my ($pkg, $urpm, $xml_info, $o_installed_version) = @_;
    my %fields = (
        info      => 'description',
        files     => 'files',
        changelog => 'changelog',
    );
    # already extracted:
    return if $pkg->{$fields{$xml_info}};

    my $p = $pkg->{pkg};

    if (!$p) {
        warn ">> ghost package '$pkg' has no URPM object!!!\n";
        return;
    }

    my $name = $p->fullname;
    # fix extracting info for SRPMS and RPM GPG keys:
    $name =~ s!\.src!!;

    if ($p->flag_installed && !$p->flag_upgrade) {
        my @files = map { MDK::Common::Various::chomp_($_) } run_rpm("rpm -ql $name");
        MDK::Common::DataStructure::add2hash($pkg, { files => [ @files ? @files : $loc->N("(none)") ],
            description => rpm_description(scalar(run_rpm("rpm -q --qf '%{description}' $name"))),
                 changelog => format_changelog_string($o_installed_version, scalar(run_rpm("rpm -q --changelog $name"))) });
    } else {
        my $medium = pkg2medium($p, $urpm);
        my ($local_source, %xml_info_pkgs, $bar_id);
        my $_statusbar_clean_guard = MDK::Common::Func::before_leaving { $bar_id and statusbar_msg_remove($bar_id) };
        my $dir = urpm::file_from_local_url($medium->{url});

        print "p->filename: ". $p->filename."\n";
        $local_source = "$dir/" . $p->filename if $dir;
        print "local_source: " . ($local_source ? $local_source : "") . "\n";

        if ($local_source && -e $local_source) {
            $bar_id = statusbar_msg($loc->N("Getting information from %s...", $dir), 0);
            $urpm->{log}("getting information from rpms from $dir");
        } else {
            my $gurpm;
            $bar_id = statusbar_msg($loc->N("Getting '%s' from XML meta-data...", $xml_info), 0);
            my $_gurpm_clean_guard = MDK::Common::Func::before_leaving { undef $gurpm };
            if (my $xml_info_file = eval { urpm::media::any_xml_info($urpm, $medium, $xml_info, undef, sub {
                $gurpm ||= AdminPanel::Rpmdragora::gurpm->new($loc->N("Please wait"),
                                                              '', # FIXME: add a real string after cooker
                                                              transient => $::main_window);
                download_callback($gurpm, @_)
                or goto header_non_available;
            }) }) {
                require urpm::xml_info;
                require urpm::xml_info_pkg;
                $urpm->{log}("getting information from $xml_info_file");
                my %nodes = eval { urpm::xml_info::get_nodes($xml_info, $xml_info_file, [ $name ]) };
                goto header_non_available if $@;
                MDK::Common::DataStructure::put_in_hash($xml_info_pkgs{$name} ||= {}, $nodes{$name});
            } else {
                if ($xml_info eq 'info') {
                    $urpm->{info}($loc->N("No xml info for medium \"%s\", only partial result for package %s", $medium->{name}, $name));
                } else {
                    $urpm->{error}($loc->N("No xml info for medium \"%s\", unable to return any result for package %s", $medium->{name}, $name));
                }
            }
        }

        #- even if non-root, search for a header in the global cachedir
        if ($local_source && -s $local_source) {
            $p->update_header($local_source) or do {
                warn "Warning, could not extract header for $name from $medium!";
                goto header_non_available;
            };
            my @files = $p->files;
            @files = $loc->N("(none)") if !@files;
            MDK::Common::DataStructure::add2hash($pkg, { description => rpm_description($p->description),
                files => \@files,
                url => $p->url,
                changelog => format_changelog_changelogs($o_installed_version, $p->changelogs) });
            $p->pack_header; # needed in order to call methods on objects outside ->traverse
        } elsif ($xml_info_pkgs{$name}) {
            if ($xml_info eq 'info') {
                MDK::Common::DataStructure::add2hash($pkg, { description => rpm_description($xml_info_pkgs{$name}{description}),
                         url => $xml_info_pkgs{$name}{url}
                });
            } elsif ($xml_info eq 'files') {
                my @files = map { MDK::Common::Various::chomp_($loc->to_utf8($_)) } split("\n", $xml_info_pkgs{$name}{files});
                MDK::Common::DataStructure::add2hash($pkg, { files => scalar(@files) ? \@files : [ $loc->N("(none)") ] });
            } elsif ($xml_info eq 'changelog') {
                MDK::Common::DataStructure::add2hash($pkg, {
                    changelog => format_changelog_changelogs($o_installed_version,
                                                             @{$xml_info_pkgs{$name}{changelogs}})
                });
            }
        } else {
            goto header_non_available;
        }
        return;
        header_non_available:
        MDK::Common::DataStructure::add2hash($pkg, { summary => $p->summary || $loc->N("(Not available)"), description => undef });
    }
}

sub find_installed_version {
    my ($p) = @_;

    my $version = $loc->N("(none)");
    open_rpm_db()->traverse_tag_find('name', $p->name, sub { $version = $_[0]->EVR; return ($version ? 1 : 0) }) if $p;
    return $version;
}

my $canceled;
sub download_callback {
    my ($gurpm, $mode, $file, $percent, $total, $eta, $speed) = @_;
    $canceled = 0;

#     $DB::single = 1;

    if ($mode eq 'start') {
        $gurpm->label($loc->N("Downloading package `%s'...", urpm::util::basename($file)));
        $gurpm->validate_cancel(but($loc->N("Cancel")), sub { $canceled = 1 });
    } elsif ($mode eq 'progress') {
        $gurpm->label(
            join("\n",
                 $loc->N("Downloading package `%s'...", urpm::util::basename($file)),
                 (defined $total && defined $eta ?
                    $loc->N("        %s%% of %s completed, ETA = %s, speed = %s", $percent, $total, $eta, $speed)
                      : $loc->N("        %s%% completed, speed = %s", $percent, $speed)
                  ) =~ /^\s*(.*)/
              ),
        );
	#$gurpm->progress($percenti/100);
        $gurpm->progress(ceil($percent*100));
    } elsif ($mode eq 'end') {
        $gurpm->progress(100);
        $gurpm->invalidate_cancel;
    }
    !$canceled;
}


# -=-=-=---=-=-=---=-=-=-- install packages -=-=-=---=-=-=---=-=-=-

my (@update_medias, $is_update_media_already_asked);

sub warn_about_media {
    my ($w, %options) = @_;

    return if $::MODE ne 'update';
    return if $::rpmdragora_options{'no-media-update'};

    # we use our own instance of the urpmi db in order not to mess up with skip-list managment (#31092):
    # and no need to fully configure urpmi since we may have to do it again anyway because of new media:
    my $urpm = fast_open_urpmi_db();

    my $_lock = urpm::lock::urpmi_db($urpm, undef, wait => $urpm->{options}{wait_lock});

    # build media list:
    @update_medias = get_update_medias($urpm);

    # do not update again media after installing/removing some packages:
    $::rpmdragora_options{'no-media-update'} ||= 1;

	    if (@update_medias > 0) {
		if (!$options{skip_updating_mu} && !$is_update_media_already_asked) {
              $is_update_media_already_asked = 1;
		     $::rpmdragora_options{'no-confirmation'} or interactive_msg($loc->N("Confirmation"),
$loc->N("I need to contact the mirror to get latest update packages.
Please check that your network is currently running.

Is it ok to continue?"), yesno => 1
# TODO                   widget =>  gtknew('CheckButton', text => $loc->N("Do not ask me next time"),
#                                      active_ref => \$::rpmdragora_options{'no-confirmation'}
#                                  )
                                                                        ) or myexit(-1);
		    writeconf();
		    urpm::media::select_media($urpm, map { $_->{name} } @update_medias);
		    update_sources($urpm, noclean => 1, medialist => [ map { $_->{name} } @update_medias ]);
		}
	    } else {
		if (any { $_->{update} } @{$urpm->{media}}) {
		    interactive_msg($loc->N("Already existing update media"),
$loc->N("You already have at least one update medium configured, but
all of them are currently disabled. You should run the Software
Media Manager to enable at least one (check it in the \"%s\"
column).

Then, restart \"%s\".", $loc->N("Enabled"), $AdminPanel::rpmdragora::myname_update));
		    myexit(-1);
		}
		my ($mirror) = choose_mirror($urpm, transient => $w->{real_window} || $::main_window,
                                       message => join("\n\n",
                                                       $loc->N("You have no configured update media. MageiaUpdate cannot operate without any update media."),
                                                       $loc->N("I need to contact the Mageia website to get the mirror list.
Please check that your network is currently running.

Is it ok to continue?"),
                                                         ),
                                   );
		my $m = ref($mirror) ? $mirror->{url} : '';
		$m or interactive_msg($loc->N("How to choose manually your mirror"),
$loc->N("You may also choose your desired mirror manually: to do so,
launch the Software Media Manager, and then add a `Security
updates' medium.

Then, restart %s.", $AdminPanel::rpmdragora::myname_update)), myexit(-1);
		add_distrib_update_media($urpm, $mirror, only_updates => 1);
	    }
}


sub get_parallel_group() {
    $::rpmdragora_options{parallel} ? $::rpmdragora_options{parallel}[0] : undef;
}

my ($count, $level, $limit, $new_stage, $prev_stage, $total);

sub init_progress_bar {
    my ($urpm) = @_;
    undef $_ foreach $count, $prev_stage, $new_stage, $limit;
    $level = 0.05;
    $total = @{$urpm->{depslist}};
}

sub reset_pbar_count {
    undef $prev_stage;
    $count = 0;
    $limit = $_[0];
}

sub update_pbar {
    my ($gurpm) = @_;
    return if !$total;          # don't die if there's no source
    $count++;
    $new_stage = $level+($limit-$level)*$count/$total;
    $prev_stage = 0 if(!defined($prev_stage));
    if ($prev_stage + 0.01*100 < $new_stage) {
        $prev_stage = $new_stage;
        $gurpm->progress(ceil($new_stage));
    }
}


sub get_installed_packages {
    my ($urpm, $db, $all_pkgs, $gurpm) = @_;

    $urpm->{global_config}{'prohibit-remove'} = '' if(!defined($urpm->{global_config}{'prohibit-remove'}));
    my @base = ("basesystem", split /,\s*/, $urpm->{global_config}{'prohibit-remove'});
    my (%base, %basepackages, @installed_pkgs, @processed_base);
    reset_pbar_count(0.33);
    while (defined(local $_ = shift @base)) {
	exists $basepackages{$_} and next;
	$db->traverse_tag(m|^/| ? 'path' : 'whatprovides', [ $_ ], sub {
			      update_pbar($gurpm);
			      my $name = $_[0]->fullname;
			      # workaround looping in URPM:
			      return if MDK::Common::DataStructure::member($name, @processed_base);
			      push @processed_base, $name;
			      push @{$basepackages{$_}}, $name;
			      push @base, $_[0]->requires_nosense;
			  });
    }
    foreach (values %basepackages) {
	my $n = @$_;            #- count number of times it's provided
	foreach (@$_) {
	    $base{$_} = \$n;
	}
    }
    # costly:
    $db->traverse(sub {
                      my ($pkg) = @_;
                      update_pbar($gurpm);
                      my $fullname = urpm_name($pkg);
                      return if $fullname =~ /@/;
                      $all_pkgs->{$fullname} = {
                          pkg => $pkg, urpm_name => $fullname,
                      } if !($all_pkgs->{$fullname} && $all_pkgs->{$fullname}{description});
                      if (my $name = $base{$fullname}) {
                          $all_pkgs->{$fullname}{base} = \$name;
                          $pkg->set_flag_base(1) if $$name == 1;
                      }
                      push @installed_pkgs, $fullname;
                      $pkg->set_flag_installed;
                      $pkg->pack_header; # needed in order to call methods on objects outside ->traverse
                  });
    @installed_pkgs;
}

urpm::select::add_packages_to_priority_upgrade_list('rpmdragora', 'perl-Glib', 'perl-Gtk2');

my ($priority_state, $priority_requested);
our $need_restart;

our $probe_only_for_updates;

sub get_updates_list {
    my ($urpm, $db, $state, $requested, $requested_list, $requested_strict, $all_pkgs, %limit_preselect) = @_;

    $urpm->request_packages_to_upgrade(
	$db,
	$state,
	$requested,
	%limit_preselect
    );

    my %common_opts = (
        callback_choices => \&AdminPanel::Rpmdragora::gui::callback_choices,
        priority_upgrade => $urpm->{options}{'priority-upgrade'},
    );

    if ($urpm->{options}{'priority-upgrade'}) {
        $need_restart =
          urpm::select::resolve_priority_upgrades_after_auto_select($urpm, $db, $state,
                                                                    $requested, %common_opts);
    }

    # list of updates (including those matching /etc/urpmi/skip.list):
    @$requested_list = sort map {
	my $name = urpm_name($_);
        $all_pkgs->{$name} = { pkg => $_ };
	$name;
    } @{$urpm->{depslist}}[keys %$requested];

    # list of pure updates (w/o those matching /etc/urpmi/skip.list but with their deps):
    if ($probe_only_for_updates && !$need_restart) {
        @$requested_strict = sort map {
            urpm_name($_);
        } $urpm->resolve_requested($db, $state, $requested, callback_choices => \&AdminPanel::Rpmdragora::gui::callback_choices);

        if (my @l = grep { $state->{selected}{$_->id} }
              urpm::select::_priority_upgrade_pkgs($urpm, $urpm->{options}{'priority-upgrade'})) {
            if (!$need_restart) {
                $need_restart =
                  urpm::select::_resolve_priority_upgrades($urpm, $db, $state, $state->{selected},
                                                           \@l, %common_opts);
            }
        }
    }

    if ($need_restart) {
        $requested_strict = [ map { scalar $_->fullname } @{$urpm->{depslist}}[keys %{$state->{selected}}] ];
        # drop non priority updates:
        @$requested_list = ();
    }

    # list updates including skiped ones + their deps in MageiaUpdate:
    @$requested_list = MDK::Common::DataStructure::uniq(@$requested_list, @$requested_strict);

    # do not pre select updates in rpmdragora:
    @$requested_strict = () if !$probe_only_for_updates;
}

sub get_pkgs {
    my (%options) = @_;
    my $w = $::main_window;

    my $gurpm = AdminPanel::Rpmdragora::gurpm->new(1 ? $loc->N("Please wait") : $loc->N("Package installation..."), $loc->N("Initializing..."), transient => $::main_window);
    my $_gurpm_clean_guard = MDK::Common::Func::before_leaving { undef $gurpm };
    #my $_flush_guard = Gtk2::GUI_Update_Guard->new;

    warn_about_media($w, %options);

    my $urpm = open_urpmi_db(update => $probe_only_for_updates && !is_it_a_devel_distro());

    my $_drop_lock = MDK::Common::Func::before_leaving { undef $urpm->{lock} };

    $priority_up_alread_warned = 0;

    # update media list in case warn_about_media() added some:
    @update_medias = get_update_medias($urpm);

    $gurpm->label($loc->N("Reading updates description"));
    $gurpm->progress(100);

	#- parse the description file
    my $update_descr = urpm::get_updates_description($urpm, @update_medias);

    my $_unused = $loc->N("Please wait, finding available packages...");

    # find out installed packages:

    init_progress_bar($urpm);

    $gurpm->label($loc->N("Please wait, listing base packages..."));
    $gurpm->progress(ceil($level*100));

    my $db = eval { open_rpm_db() };
    if (my $err = $@) {
	interactive_msg($loc->N("Error"), $loc->N("A fatal error occurred: %s.", $err));
        return;
    }

    my $sig_handler = sub { undef $db; exit 3 };
    local $SIG{INT} = $sig_handler;
    local $SIG{QUIT} = $sig_handler;

    $gurpm->label($loc->N("Please wait, finding installed packages..."));
    $level = 0.33*100;
    $gurpm->progress(ceil($level));
    reset_pbar_count(0.66*100);
    my (@installed_pkgs, %all_pkgs);
    if (!$probe_only_for_updates) {
        @installed_pkgs = get_installed_packages($urpm, $db, \%all_pkgs, $gurpm);
    }

    if (my $group = get_parallel_group()) {
        urpm::media::configure($urpm, parallel => $group);
    }

    # find out availlable packages:

    $urpm->{state} = {};

    $gurpm->label($loc->N("Please wait, finding available packages..."));
    $level = 0.66*100;
    $gurpm->progress(ceil($level));

    check_update_media_version($urpm, @update_medias);

    my $requested = {};
    my $state = {};
    my (@requested, @requested_strict);

    if ($compute_updates->[0] || $::MODE eq 'update') {
        my %filter;
        if ($options{pure_updates}) {
            # limit to packages from update-media (dependencies can still come from other media)
            %filter = (idlist => [ map { $_->{start} .. $_->{end} } @update_medias ]);
        }
        get_updates_list($urpm, $db, $state, $requested, \@requested, \@requested_strict, \%all_pkgs, %filter);
    }

    if ($need_restart) {
        $priority_state = $state;
        $priority_requested = $requested;
    } else {
        ($priority_state, $priority_requested) = ();
    }

    if (!$probe_only_for_updates) {
        $urpm->compute_installed_flags($db); # TODO/FIXME: not for updates
        $urpm->{depslist}[$_]->set_flag_installed foreach keys %$requested; #- pretend it's installed
    }
    $urpm->{rpmdragora_state} = $state; #- Don't forget it
    $level = 0.7*100;
    $gurpm->progress(ceil($level));

    my %l;
    reset_pbar_count(1);
    foreach my $pkg (@{$urpm->{depslist}}) {
        update_pbar($gurpm);
	$pkg->flag_upgrade or next;
	my $key = $pkg->name . $pkg->arch;
	$l{$key} = $pkg if !$l{$key} || $l{$key}->compare_pkg($pkg);
    }
    my @installable_pkgs = map { my $n = $_->fullname; $all_pkgs{$n} = { pkg => $_ }; $n } values %l;
    undef %l;

    my @inactive_backports;
    my @active_backports;
    my @backport_medias = get_backport_media($urpm);

    foreach my $medium (@backport_medias) {
        update_pbar($gurpm);

        # The 'searchmedia' flag differentiates inactive backport medias
        # (because that option was passed to urpm::media::configure to
        # temporarily enable them)

        my $backports =
            $medium->{searchmedia} ? \@inactive_backports : \@active_backports;
        if (defined($medium->{start}) || defined($medium->{end})) {
            foreach my $pkg_id ($medium->{start} .. $medium->{end}) {
                next if !$pkg_id;
                my $pkg = $urpm->{depslist}[$pkg_id];
                $pkg->flag_upgrade or next;
                my $name = $pkg->fullname;
                push @$backports, $name;
                $all_pkgs{$name} = { pkg => $pkg, is_backport => 1 };
            }
        }
    }
    my @updates = @requested;
    # selecting updates by default but skipped ones (MageiaUpdate only):
    foreach (@requested_strict) {
	$all_pkgs{$_}{selected} = 1;
    }

    # urpmi only care about the first medium where it found the package,
    # so there's no need to list the same package several time:
    @installable_pkgs = MDK::Common::DataStructure::uniq(MDK::Common::DataStructure::difference2(\@installable_pkgs, \@updates));

    my @meta_pkgs = grep { /^task-|^basesystem/ } keys %all_pkgs;

    my @gui_pkgs = map { chomp; $_ } MDK::Common::File::cat_('/usr/share/rpmdrake/gui.lst');
    # add meta packages to GUI packages list (which expect basic names not fullnames):
    push @gui_pkgs, map { (split_fullname($_))[0] } @meta_pkgs;

    +{ urpm => $urpm,
       all_pkgs => \%all_pkgs,
       installed => \@installed_pkgs,
       installable => \@installable_pkgs,
       updates => \@updates,
       meta_pkgs => \@meta_pkgs,
       gui_pkgs => [ grep { my $p = $all_pkgs{$_}{pkg}; $p && MDK::Common::DataStructure::member(($p->fullname)[0], @gui_pkgs) } keys %all_pkgs ],
       update_descr => $update_descr,
       backports => [ @inactive_backports, @active_backports ],
       inactive_backports => \@inactive_backports
   };
}

sub _display_READMEs_if_needed {
    my $urpm = shift;
    return if !$urpm->{readmes};

    my %Readmes = %{$urpm->{readmes}};
    return if ! scalar keys %Readmes;

    my $appTitle = yui::YUI::app()->applicationTitle();

    ## set new title to get it in dialog
    yui::YUI::app()->setApplicationTitle($loc->N("Upgrade information"));
    my $factory      = yui::YUI::widgetFactory;

    ## | [msg-label]                      |
    ## |                                  |
    ## | pkg-list                         |
    ## |                                  |
    ## | info on selected pkg             |(1)
    ## |                                  |
    ## |             [ok]                 |
    ####
    # (1) info on pkg list:
    #  selected package readmi.urpmi

    my $dialog       = $factory->createPopupDialog;
    my $vbox         = $factory->createVBox( $dialog );
    my $msgBox       = $factory->createLabel($vbox, $loc->N("These packages come with upgrade information"), 1);
    my $tree         = $factory->createTree($vbox, $loc->N("Select a package"));
                       $factory->createVSpacing($vbox, 1);
    my $infoBox      = $factory->createRichText($vbox, "", 0);
                       $tree->setWeight($yui::YD_HORIZ, 2);
                       $infoBox->setWeight($yui::YD_HORIZ, 4);
                       $tree->setWeight($yui::YD_VERT,  10);
                       $infoBox->setWeight($yui::YD_VERT,  10);
                       $factory->createVSpacing($vbox, 1);
    my $hbox         = $factory->createHBox( $vbox );
    my $align        = $factory->createHCenter($hbox);
    my $okButton     = $factory->createPushButton($align,  $loc->N("Ok"));
                       $okButton->setDefaultButton(1);

    # adding packages to the list
    my $itemColl = new yui::YItemCollection;
    foreach my $f (sort keys %Readmes) {
        my $item  = new yui::YTreeItem ("$Readmes{$f}");
        my $child = new yui::YTreeItem ($item, "$f");
        $child->DISOWN();
        $itemColl->push($item);
        $item->DISOWN();
    }
    $tree->addItems($itemColl);
    $tree->setImmediateMode(1);

    while(1) {
        my $event     = $dialog->waitForEvent();
        my $eventType = $event->eventType();

        #event type checking
        if ($eventType == $yui::YEvent::CancelEvent) {
            last;
        }
        elsif ($eventType == $yui::YEvent::WidgetEvent) {
            ### widget
            my $widget = $event->widget();
            if ($widget == $tree) {
                my $content = "";
                my $item = $tree->selectedItem();
                if ($item && !$item->hasChildren()) {
                    my $filename = $tree->currentItem()->label();
                    $content = scalar MDK::Common::File::cat_($filename);
                    $content = $loc->N("(none)") if !$content; # should not happen
                    ensure_utf8($content);
                    $content =~ s/\n/<br>/g;
                }
                $infoBox->setValue($content);
            }
            elsif ($widget == $okButton) {
                last;
            }
        }
    }

    destroy $dialog;

    # restore original title
    yui::YUI::app()->setApplicationTitle($appTitle) if $appTitle;

    return;
}

sub perform_parallel_install {
    my ($urpm, $group, $w, $statusbar_msg_id) = @_;
    my @pkgs = map { MDK::Common::Func::if_($_->flag_requested, urpm_name($_)) } @{$urpm->{depslist}};

    my @error_msgs;
    my $res = !run_program::run('urpmi', '2>', \@error_msgs, '-v', '--X', '--parallel', $group, @pkgs);

    if ($res) {
        $$statusbar_msg_id = statusbar_msg(
            #$loc->N("Everything installed successfully"),
            $loc->N("All requested packages were installed successfully."),
        );
    } else {
        interactive_msg(
            $loc->N("Problem during installation"),
            $loc->N("There was a problem during the installation:\n\n%s", join("\n", @error_msgs)),
            scroll => 1,
        );
    }
    open_rpm_db('force_sync');
    $w->set_sensitive(1);
    return 0;
}

sub perform_installation {  #- (partially) duplicated from /usr/sbin/urpmi :-(
    my ($urpm, $pkgs) = @_;

    my @error_msgs;
    my $statusbar_msg_id;
    my $gurpm;
    local $urpm->{fatal} = sub {
        my $fatal_msg = $_[1];
        printf STDERR "Fatal: %s\n", $fatal_msg;
        undef $gurpm;
        interactive_msg($loc->N("Installation failed"),
                        $loc->N("There was a problem during the installation:\n\n%s", $fatal_msg));
        goto return_with_exit_code;
    };
    local $urpm->{error} = sub { printf STDERR "Error: %s\n", $_[0]; push @error_msgs, $_[0] };

    my $w = $::main_window;
    #$w->set_sensitive(0);
    #my $_restore_sensitive = MDK::Common::Func::before_leaving { $w->set_sensitive(1) };

    # my $_flush_guard = Gtk2::GUI_Update_Guard->new;

    if (my $group = get_parallel_group()) {
        return perform_parallel_install($urpm, $group, $w, \$statusbar_msg_id);
    }

    my ($lock, $rpm_lock);
    if (!$::env) {
        $lock = urpm::lock::urpmi_db($urpm, undef, wait => $urpm->{options}{wait_lock});
        $rpm_lock = urpm::lock::rpm_db($urpm, 'exclusive');
    }
    my $state = $priority_state || $probe_only_for_updates ? { } : $urpm->{rpmdragora_state};

    my $bar_id = statusbar_msg($loc->N("Checking validity of requested packages..."), 0);

    # FIXME: THIS SET flag_requested on all packages!!!!
    # select packages to install / enssure selected pkg set is consistant:
    my %saved_flags;
    my $requested = { map {
        $saved_flags{$_->id} = $_->flag_requested;
        $_->id => undef;
    } grep { $_->flag_selected } @{$urpm->{depslist}} };
    urpm::select::resolve_dependencies(
        $urpm, $state, $requested,
        rpmdb => $::env && "$::env/rpmdb.cz",
        callback_choices => \&AdminPanel::Rpmdragora::gui::callback_choices,
    );
    statusbar_msg_remove($bar_id);

    my ($local_sources, $blist) = urpm::get_pkgs::selected2local_and_blists($urpm, $state->{selected});
    if (!$local_sources && (!$blist || !@$blist)) {
        interactive_msg(
	    $loc->N("Unable to get source packages."),
	    $loc->N("Unable to get source packages, sorry. %s",
		@error_msgs ? $loc->N("\n\nError(s) reported:\n%s", join("\n", @error_msgs)) : ''),
	    scroll => 1,
	);
        goto return_with_exit_code;
    }