contrib / mw-to-git / git-remote-mediawiki.perlon commit git-remote-mediawiki: display message when launched directly (5ada868)
   1#! /usr/bin/perl
   2
   3# Copyright (C) 2011
   4#     Jérémie Nikaes <jeremie.nikaes@ensimag.imag.fr>
   5#     Arnaud Lacurie <arnaud.lacurie@ensimag.imag.fr>
   6#     Claire Fousse <claire.fousse@ensimag.imag.fr>
   7#     David Amouyal <david.amouyal@ensimag.imag.fr>
   8#     Matthieu Moy <matthieu.moy@grenoble-inp.fr>
   9# License: GPL v2 or later
  10
  11# Gateway between Git and MediaWiki.
  12# Documentation & bugtracker: https://github.com/moy/Git-Mediawiki/
  13
  14use strict;
  15use MediaWiki::API;
  16use DateTime::Format::ISO8601;
  17
  18# By default, use UTF-8 to communicate with Git and the user
  19binmode STDERR, ":utf8";
  20binmode STDOUT, ":utf8";
  21
  22use URI::Escape;
  23use IPC::Open2;
  24
  25use warnings;
  26
  27# Mediawiki filenames can contain forward slashes. This variable decides by which pattern they should be replaced
  28use constant SLASH_REPLACEMENT => "%2F";
  29
  30# It's not always possible to delete pages (may require some
  31# privileges). Deleted pages are replaced with this content.
  32use constant DELETED_CONTENT => "[[Category:Deleted]]\n";
  33
  34# It's not possible to create empty pages. New empty files in Git are
  35# sent with this content instead.
  36use constant EMPTY_CONTENT => "<!-- empty page -->\n";
  37
  38# used to reflect file creation or deletion in diff.
  39use constant NULL_SHA1 => "0000000000000000000000000000000000000000";
  40
  41# Used on Git's side to reflect empty edit messages on the wiki
  42use constant EMPTY_MESSAGE => '*Empty MediaWiki Message*';
  43
  44if (@ARGV != 2) {
  45        exit_error_usage();
  46}
  47
  48my $remotename = $ARGV[0];
  49my $url = $ARGV[1];
  50
  51# Accept both space-separated and multiple keys in config file.
  52# Spaces should be written as _ anyway because we'll use chomp.
  53my @tracked_pages = split(/[ \n]/, run_git("config --get-all remote.". $remotename .".pages"));
  54chomp(@tracked_pages);
  55
  56# Just like @tracked_pages, but for MediaWiki categories.
  57my @tracked_categories = split(/[ \n]/, run_git("config --get-all remote.". $remotename .".categories"));
  58chomp(@tracked_categories);
  59
  60# Import media files on pull
  61my $import_media = run_git("config --get --bool remote.". $remotename .".mediaimport");
  62chomp($import_media);
  63$import_media = ($import_media eq "true");
  64
  65# Export media files on push
  66my $export_media = run_git("config --get --bool remote.". $remotename .".mediaexport");
  67chomp($export_media);
  68$export_media = !($export_media eq "false");
  69
  70my $wiki_login = run_git("config --get remote.". $remotename .".mwLogin");
  71# Note: mwPassword is discourraged. Use the credential system instead.
  72my $wiki_passwd = run_git("config --get remote.". $remotename .".mwPassword");
  73my $wiki_domain = run_git("config --get remote.". $remotename .".mwDomain");
  74chomp($wiki_login);
  75chomp($wiki_passwd);
  76chomp($wiki_domain);
  77
  78# Import only last revisions (both for clone and fetch)
  79my $shallow_import = run_git("config --get --bool remote.". $remotename .".shallow");
  80chomp($shallow_import);
  81$shallow_import = ($shallow_import eq "true");
  82
  83# Fetch (clone and pull) by revisions instead of by pages. This behavior
  84# is more efficient when we have a wiki with lots of pages and we fetch
  85# the revisions quite often so that they concern only few pages.
  86# Possible values:
  87# - by_rev: perform one query per new revision on the remote wiki
  88# - by_page: query each tracked page for new revision
  89my $fetch_strategy = run_git("config --get remote.$remotename.fetchStrategy");
  90unless ($fetch_strategy) {
  91        $fetch_strategy = run_git("config --get mediawiki.fetchStrategy");
  92}
  93chomp($fetch_strategy);
  94unless ($fetch_strategy) {
  95        $fetch_strategy = "by_page";
  96}
  97
  98# Dumb push: don't update notes and mediawiki ref to reflect the last push.
  99#
 100# Configurable with mediawiki.dumbPush, or per-remote with
 101# remote.<remotename>.dumbPush.
 102#
 103# This means the user will have to re-import the just-pushed
 104# revisions. On the other hand, this means that the Git revisions
 105# corresponding to MediaWiki revisions are all imported from the wiki,
 106# regardless of whether they were initially created in Git or from the
 107# web interface, hence all users will get the same history (i.e. if
 108# the push from Git to MediaWiki loses some information, everybody
 109# will get the history with information lost). If the import is
 110# deterministic, this means everybody gets the same sha1 for each
 111# MediaWiki revision.
 112my $dumb_push = run_git("config --get --bool remote.$remotename.dumbPush");
 113unless ($dumb_push) {
 114        $dumb_push = run_git("config --get --bool mediawiki.dumbPush");
 115}
 116chomp($dumb_push);
 117$dumb_push = ($dumb_push eq "true");
 118
 119my $wiki_name = $url;
 120$wiki_name =~ s/[^\/]*:\/\///;
 121# If URL is like http://user:password@example.com/, we clearly don't
 122# want the password in $wiki_name. While we're there, also remove user
 123# and '@' sign, to avoid author like MWUser@HTTPUser@host.com
 124$wiki_name =~ s/^.*@//;
 125
 126# Commands parser
 127my $entry;
 128my @cmd;
 129while (<STDIN>) {
 130        chomp;
 131        @cmd = split(/ /);
 132        if (defined($cmd[0])) {
 133                # Line not blank
 134                if ($cmd[0] eq "capabilities") {
 135                        die("Too many arguments for capabilities") unless (!defined($cmd[1]));
 136                        mw_capabilities();
 137                } elsif ($cmd[0] eq "list") {
 138                        die("Too many arguments for list") unless (!defined($cmd[2]));
 139                        mw_list($cmd[1]);
 140                } elsif ($cmd[0] eq "import") {
 141                        die("Invalid arguments for import") unless ($cmd[1] ne "" && !defined($cmd[2]));
 142                        mw_import($cmd[1]);
 143                } elsif ($cmd[0] eq "option") {
 144                        die("Too many arguments for option") unless ($cmd[1] ne "" && $cmd[2] ne "" && !defined($cmd[3]));
 145                        mw_option($cmd[1],$cmd[2]);
 146                } elsif ($cmd[0] eq "push") {
 147                        mw_push($cmd[1]);
 148                } else {
 149                        print STDERR "Unknown command. Aborting...\n";
 150                        last;
 151                }
 152        } else {
 153                # blank line: we should terminate
 154                last;
 155        }
 156
 157        BEGIN { $| = 1 } # flush STDOUT, to make sure the previous
 158                         # command is fully processed.
 159}
 160
 161########################## Functions ##############################
 162
 163## error handling
 164sub exit_error_usage {
 165        die "ERROR: git-remote-mediawiki module was not called with a correct number of\n" .
 166            "parameters\n" .
 167            "You may obtain this error because you attempted to run the git-remote-mediawiki\n" .
 168            "module directly.\n" .
 169            "This module can be used the following way:\n" .
 170            "\tgit clone mediawiki://<address of a mediawiki>\n" .
 171            "Then, use git commit, push and pull as with every normal git repository.\n";
 172}
 173
 174## credential API management (generic functions)
 175
 176sub credential_read {
 177        my %credential;
 178        my $reader = shift;
 179        my $op = shift;
 180        while (<$reader>) {
 181                my ($key, $value) = /([^=]*)=(.*)/;
 182                if (not defined $key) {
 183                        die "ERROR receiving response from git credential $op:\n$_\n";
 184                }
 185                $credential{$key} = $value;
 186        }
 187        return %credential;
 188}
 189
 190sub credential_write {
 191        my $credential = shift;
 192        my $writer = shift;
 193        # url overwrites other fields, so it must come first
 194        print $writer "url=$credential->{url}\n" if exists $credential->{url};
 195        while (my ($key, $value) = each(%$credential) ) {
 196                if (length $value && $key ne 'url') {
 197                        print $writer "$key=$value\n";
 198                }
 199        }
 200}
 201
 202sub credential_run {
 203        my $op = shift;
 204        my $credential = shift;
 205        my $pid = open2(my $reader, my $writer, "git credential $op");
 206        credential_write($credential, $writer);
 207        print $writer "\n";
 208        close($writer);
 209
 210        if ($op eq "fill") {
 211                %$credential = credential_read($reader, $op);
 212        } else {
 213                if (<$reader>) {
 214                        die "ERROR while running git credential $op:\n$_";
 215                }
 216        }
 217        close($reader);
 218        waitpid($pid, 0);
 219        my $child_exit_status = $? >> 8;
 220        if ($child_exit_status != 0) {
 221                die "'git credential $op' failed with code $child_exit_status.";
 222        }
 223}
 224
 225# MediaWiki API instance, created lazily.
 226my $mediawiki;
 227
 228sub mw_connect_maybe {
 229        if ($mediawiki) {
 230                return;
 231        }
 232        $mediawiki = MediaWiki::API->new;
 233        $mediawiki->{config}->{api_url} = "$url/api.php";
 234        if ($wiki_login) {
 235                my %credential = (url => $url);
 236                $credential{username} = $wiki_login;
 237                $credential{password} = $wiki_passwd;
 238                credential_run("fill", \%credential);
 239                my $request = {lgname => $credential{username},
 240                               lgpassword => $credential{password},
 241                               lgdomain => $wiki_domain};
 242                if ($mediawiki->login($request)) {
 243                        credential_run("approve", \%credential);
 244                        print STDERR "Logged in mediawiki user \"$credential{username}\".\n";
 245                } else {
 246                        print STDERR "Failed to log in mediawiki user \"$credential{username}\" on $url\n";
 247                        print STDERR "  (error " .
 248                                $mediawiki->{error}->{code} . ': ' .
 249                                $mediawiki->{error}->{details} . ")\n";
 250                        credential_run("reject", \%credential);
 251                        exit 1;
 252                }
 253        }
 254}
 255
 256## Functions for listing pages on the remote wiki
 257sub get_mw_tracked_pages {
 258        my $pages = shift;
 259        get_mw_page_list(\@tracked_pages, $pages);
 260}
 261
 262sub get_mw_page_list {
 263        my $page_list = shift;
 264        my $pages = shift;
 265        my @some_pages = @$page_list;
 266        while (@some_pages) {
 267                my $last = 50;
 268                if ($#some_pages < $last) {
 269                        $last = $#some_pages;
 270                }
 271                my @slice = @some_pages[0..$last];
 272                get_mw_first_pages(\@slice, $pages);
 273                @some_pages = @some_pages[51..$#some_pages];
 274        }
 275}
 276
 277sub get_mw_tracked_categories {
 278        my $pages = shift;
 279        foreach my $category (@tracked_categories) {
 280                if (index($category, ':') < 0) {
 281                        # Mediawiki requires the Category
 282                        # prefix, but let's not force the user
 283                        # to specify it.
 284                        $category = "Category:" . $category;
 285                }
 286                my $mw_pages = $mediawiki->list( {
 287                        action => 'query',
 288                        list => 'categorymembers',
 289                        cmtitle => $category,
 290                        cmlimit => 'max' } )
 291                        || die $mediawiki->{error}->{code} . ': '
 292                                . $mediawiki->{error}->{details};
 293                foreach my $page (@{$mw_pages}) {
 294                        $pages->{$page->{title}} = $page;
 295                }
 296        }
 297}
 298
 299sub get_mw_all_pages {
 300        my $pages = shift;
 301        # No user-provided list, get the list of pages from the API.
 302        my $mw_pages = $mediawiki->list({
 303                action => 'query',
 304                list => 'allpages',
 305                aplimit => 'max'
 306        });
 307        if (!defined($mw_pages)) {
 308                print STDERR "fatal: could not get the list of wiki pages.\n";
 309                print STDERR "fatal: '$url' does not appear to be a mediawiki\n";
 310                print STDERR "fatal: make sure '$url/api.php' is a valid page.\n";
 311                exit 1;
 312        }
 313        foreach my $page (@{$mw_pages}) {
 314                $pages->{$page->{title}} = $page;
 315        }
 316}
 317
 318# queries the wiki for a set of pages. Meant to be used within a loop
 319# querying the wiki for slices of page list.
 320sub get_mw_first_pages {
 321        my $some_pages = shift;
 322        my @some_pages = @{$some_pages};
 323
 324        my $pages = shift;
 325
 326        # pattern 'page1|page2|...' required by the API
 327        my $titles = join('|', @some_pages);
 328
 329        my $mw_pages = $mediawiki->api({
 330                action => 'query',
 331                titles => $titles,
 332        });
 333        if (!defined($mw_pages)) {
 334                print STDERR "fatal: could not query the list of wiki pages.\n";
 335                print STDERR "fatal: '$url' does not appear to be a mediawiki\n";
 336                print STDERR "fatal: make sure '$url/api.php' is a valid page.\n";
 337                exit 1;
 338        }
 339        while (my ($id, $page) = each(%{$mw_pages->{query}->{pages}})) {
 340                if ($id < 0) {
 341                        print STDERR "Warning: page $page->{title} not found on wiki\n";
 342                } else {
 343                        $pages->{$page->{title}} = $page;
 344                }
 345        }
 346}
 347
 348# Get the list of pages to be fetched according to configuration.
 349sub get_mw_pages {
 350        mw_connect_maybe();
 351
 352        print STDERR "Listing pages on remote wiki...\n";
 353
 354        my %pages; # hash on page titles to avoid duplicates
 355        my $user_defined;
 356        if (@tracked_pages) {
 357                $user_defined = 1;
 358                # The user provided a list of pages titles, but we
 359                # still need to query the API to get the page IDs.
 360                get_mw_tracked_pages(\%pages);
 361        }
 362        if (@tracked_categories) {
 363                $user_defined = 1;
 364                get_mw_tracked_categories(\%pages);
 365        }
 366        if (!$user_defined) {
 367                get_mw_all_pages(\%pages);
 368        }
 369        if ($import_media) {
 370                print STDERR "Getting media files for selected pages...\n";
 371                if ($user_defined) {
 372                        get_linked_mediafiles(\%pages);
 373                } else {
 374                        get_all_mediafiles(\%pages);
 375                }
 376        }
 377        print STDERR (scalar keys %pages) . " pages found.\n";
 378        return %pages;
 379}
 380
 381# usage: $out = run_git("command args");
 382#        $out = run_git("command args", "raw"); # don't interpret output as UTF-8.
 383sub run_git {
 384        my $args = shift;
 385        my $encoding = (shift || "encoding(UTF-8)");
 386        open(my $git, "-|:$encoding", "git " . $args);
 387        my $res = do { local $/; <$git> };
 388        close($git);
 389
 390        return $res;
 391}
 392
 393
 394sub get_all_mediafiles {
 395        my $pages = shift;
 396        # Attach list of all pages for media files from the API,
 397        # they are in a different namespace, only one namespace
 398        # can be queried at the same moment
 399        my $mw_pages = $mediawiki->list({
 400                action => 'query',
 401                list => 'allpages',
 402                apnamespace => get_mw_namespace_id("File"),
 403                aplimit => 'max'
 404        });
 405        if (!defined($mw_pages)) {
 406                print STDERR "fatal: could not get the list of pages for media files.\n";
 407                print STDERR "fatal: '$url' does not appear to be a mediawiki\n";
 408                print STDERR "fatal: make sure '$url/api.php' is a valid page.\n";
 409                exit 1;
 410        }
 411        foreach my $page (@{$mw_pages}) {
 412                $pages->{$page->{title}} = $page;
 413        }
 414}
 415
 416sub get_linked_mediafiles {
 417        my $pages = shift;
 418        my @titles = map $_->{title}, values(%{$pages});
 419
 420        # The query is split in small batches because of the MW API limit of
 421        # the number of links to be returned (500 links max).
 422        my $batch = 10;
 423        while (@titles) {
 424                if ($#titles < $batch) {
 425                        $batch = $#titles;
 426                }
 427                my @slice = @titles[0..$batch];
 428
 429                # pattern 'page1|page2|...' required by the API
 430                my $mw_titles = join('|', @slice);
 431
 432                # Media files could be included or linked from
 433                # a page, get all related
 434                my $query = {
 435                        action => 'query',
 436                        prop => 'links|images',
 437                        titles => $mw_titles,
 438                        plnamespace => get_mw_namespace_id("File"),
 439                        pllimit => 'max'
 440                };
 441                my $result = $mediawiki->api($query);
 442
 443                while (my ($id, $page) = each(%{$result->{query}->{pages}})) {
 444                        my @media_titles;
 445                        if (defined($page->{links})) {
 446                                my @link_titles = map $_->{title}, @{$page->{links}};
 447                                push(@media_titles, @link_titles);
 448                        }
 449                        if (defined($page->{images})) {
 450                                my @image_titles = map $_->{title}, @{$page->{images}};
 451                                push(@media_titles, @image_titles);
 452                        }
 453                        if (@media_titles) {
 454                                get_mw_page_list(\@media_titles, $pages);
 455                        }
 456                }
 457
 458                @titles = @titles[($batch+1)..$#titles];
 459        }
 460}
 461
 462sub get_mw_mediafile_for_page_revision {
 463        # Name of the file on Wiki, with the prefix.
 464        my $filename = shift;
 465        my $timestamp = shift;
 466        my %mediafile;
 467
 468        # Search if on a media file with given timestamp exists on
 469        # MediaWiki. In that case download the file.
 470        my $query = {
 471                action => 'query',
 472                prop => 'imageinfo',
 473                titles => "File:" . $filename,
 474                iistart => $timestamp,
 475                iiend => $timestamp,
 476                iiprop => 'timestamp|archivename|url',
 477                iilimit => 1
 478        };
 479        my $result = $mediawiki->api($query);
 480
 481        my ($fileid, $file) = each( %{$result->{query}->{pages}} );
 482        # If not defined it means there is no revision of the file for
 483        # given timestamp.
 484        if (defined($file->{imageinfo})) {
 485                $mediafile{title} = $filename;
 486
 487                my $fileinfo = pop(@{$file->{imageinfo}});
 488                $mediafile{timestamp} = $fileinfo->{timestamp};
 489                # Mediawiki::API's download function doesn't support https URLs
 490                # and can't download old versions of files.
 491                print STDERR "\tDownloading file $mediafile{title}, version $mediafile{timestamp}\n";
 492                $mediafile{content} = download_mw_mediafile($fileinfo->{url});
 493        }
 494        return %mediafile;
 495}
 496
 497sub download_mw_mediafile {
 498        my $url = shift;
 499
 500        my $response = $mediawiki->{ua}->get($url);
 501        if ($response->code == 200) {
 502                return $response->decoded_content;
 503        } else {
 504                print STDERR "Error downloading mediafile from :\n";
 505                print STDERR "URL: $url\n";
 506                print STDERR "Server response: " . $response->code . " " . $response->message . "\n";
 507                exit 1;
 508        }
 509}
 510
 511sub get_last_local_revision {
 512        # Get note regarding last mediawiki revision
 513        my $note = run_git("notes --ref=$remotename/mediawiki show refs/mediawiki/$remotename/master 2>/dev/null");
 514        my @note_info = split(/ /, $note);
 515
 516        my $lastrevision_number;
 517        if (!(defined($note_info[0]) && $note_info[0] eq "mediawiki_revision:")) {
 518                print STDERR "No previous mediawiki revision found";
 519                $lastrevision_number = 0;
 520        } else {
 521                # Notes are formatted : mediawiki_revision: #number
 522                $lastrevision_number = $note_info[1];
 523                chomp($lastrevision_number);
 524                print STDERR "Last local mediawiki revision found is $lastrevision_number";
 525        }
 526        return $lastrevision_number;
 527}
 528
 529# Remember the timestamp corresponding to a revision id.
 530my %basetimestamps;
 531
 532# Get the last remote revision without taking in account which pages are
 533# tracked or not. This function makes a single request to the wiki thus
 534# avoid a loop onto all tracked pages. This is useful for the fetch-by-rev
 535# option.
 536sub get_last_global_remote_rev {
 537        mw_connect_maybe();
 538
 539        my $query = {
 540                action => 'query',
 541                list => 'recentchanges',
 542                prop => 'revisions',
 543                rclimit => '1',
 544                rcdir => 'older',
 545        };
 546        my $result = $mediawiki->api($query);
 547        return $result->{query}->{recentchanges}[0]->{revid};
 548}
 549
 550# Get the last remote revision concerning the tracked pages and the tracked
 551# categories.
 552sub get_last_remote_revision {
 553        mw_connect_maybe();
 554
 555        my %pages_hash = get_mw_pages();
 556        my @pages = values(%pages_hash);
 557
 558        my $max_rev_num = 0;
 559
 560        print STDERR "Getting last revision id on tracked pages...\n";
 561
 562        foreach my $page (@pages) {
 563                my $id = $page->{pageid};
 564
 565                my $query = {
 566                        action => 'query',
 567                        prop => 'revisions',
 568                        rvprop => 'ids|timestamp',
 569                        pageids => $id,
 570                };
 571
 572                my $result = $mediawiki->api($query);
 573
 574                my $lastrev = pop(@{$result->{query}->{pages}->{$id}->{revisions}});
 575
 576                $basetimestamps{$lastrev->{revid}} = $lastrev->{timestamp};
 577
 578                $max_rev_num = ($lastrev->{revid} > $max_rev_num ? $lastrev->{revid} : $max_rev_num);
 579        }
 580
 581        print STDERR "Last remote revision found is $max_rev_num.\n";
 582        return $max_rev_num;
 583}
 584
 585# Clean content before sending it to MediaWiki
 586sub mediawiki_clean {
 587        my $string = shift;
 588        my $page_created = shift;
 589        # Mediawiki does not allow blank space at the end of a page and ends with a single \n.
 590        # This function right trims a string and adds a \n at the end to follow this rule
 591        $string =~ s/\s+$//;
 592        if ($string eq "" && $page_created) {
 593                # Creating empty pages is forbidden.
 594                $string = EMPTY_CONTENT;
 595        }
 596        return $string."\n";
 597}
 598
 599# Filter applied on MediaWiki data before adding them to Git
 600sub mediawiki_smudge {
 601        my $string = shift;
 602        if ($string eq EMPTY_CONTENT) {
 603                $string = "";
 604        }
 605        # This \n is important. This is due to mediawiki's way to handle end of files.
 606        return $string."\n";
 607}
 608
 609sub mediawiki_clean_filename {
 610        my $filename = shift;
 611        $filename =~ s/@{[SLASH_REPLACEMENT]}/\//g;
 612        # [, ], |, {, and } are forbidden by MediaWiki, even URL-encoded.
 613        # Do a variant of URL-encoding, i.e. looks like URL-encoding,
 614        # but with _ added to prevent MediaWiki from thinking this is
 615        # an actual special character.
 616        $filename =~ s/[\[\]\{\}\|]/sprintf("_%%_%x", ord($&))/ge;
 617        # If we use the uri escape before
 618        # we should unescape here, before anything
 619
 620        return $filename;
 621}
 622
 623sub mediawiki_smudge_filename {
 624        my $filename = shift;
 625        $filename =~ s/\//@{[SLASH_REPLACEMENT]}/g;
 626        $filename =~ s/ /_/g;
 627        # Decode forbidden characters encoded in mediawiki_clean_filename
 628        $filename =~ s/_%_([0-9a-fA-F][0-9a-fA-F])/sprintf("%c", hex($1))/ge;
 629        return $filename;
 630}
 631
 632sub literal_data {
 633        my ($content) = @_;
 634        print STDOUT "data ", bytes::length($content), "\n", $content;
 635}
 636
 637sub literal_data_raw {
 638        # Output possibly binary content.
 639        my ($content) = @_;
 640        # Avoid confusion between size in bytes and in characters
 641        utf8::downgrade($content);
 642        binmode STDOUT, ":raw";
 643        print STDOUT "data ", bytes::length($content), "\n", $content;
 644        binmode STDOUT, ":utf8";
 645}
 646
 647sub mw_capabilities {
 648        # Revisions are imported to the private namespace
 649        # refs/mediawiki/$remotename/ by the helper and fetched into
 650        # refs/remotes/$remotename later by fetch.
 651        print STDOUT "refspec refs/heads/*:refs/mediawiki/$remotename/*\n";
 652        print STDOUT "import\n";
 653        print STDOUT "list\n";
 654        print STDOUT "push\n";
 655        print STDOUT "\n";
 656}
 657
 658sub mw_list {
 659        # MediaWiki do not have branches, we consider one branch arbitrarily
 660        # called master, and HEAD pointing to it.
 661        print STDOUT "? refs/heads/master\n";
 662        print STDOUT "\@refs/heads/master HEAD\n";
 663        print STDOUT "\n";
 664}
 665
 666sub mw_option {
 667        print STDERR "remote-helper command 'option $_[0]' not yet implemented\n";
 668        print STDOUT "unsupported\n";
 669}
 670
 671sub fetch_mw_revisions_for_page {
 672        my $page = shift;
 673        my $id = shift;
 674        my $fetch_from = shift;
 675        my @page_revs = ();
 676        my $query = {
 677                action => 'query',
 678                prop => 'revisions',
 679                rvprop => 'ids',
 680                rvdir => 'newer',
 681                rvstartid => $fetch_from,
 682                rvlimit => 500,
 683                pageids => $id,
 684        };
 685
 686        my $revnum = 0;
 687        # Get 500 revisions at a time due to the mediawiki api limit
 688        while (1) {
 689                my $result = $mediawiki->api($query);
 690
 691                # Parse each of those 500 revisions
 692                foreach my $revision (@{$result->{query}->{pages}->{$id}->{revisions}}) {
 693                        my $page_rev_ids;
 694                        $page_rev_ids->{pageid} = $page->{pageid};
 695                        $page_rev_ids->{revid} = $revision->{revid};
 696                        push(@page_revs, $page_rev_ids);
 697                        $revnum++;
 698                }
 699                last unless $result->{'query-continue'};
 700                $query->{rvstartid} = $result->{'query-continue'}->{revisions}->{rvstartid};
 701        }
 702        if ($shallow_import && @page_revs) {
 703                print STDERR "  Found 1 revision (shallow import).\n";
 704                @page_revs = sort {$b->{revid} <=> $a->{revid}} (@page_revs);
 705                return $page_revs[0];
 706        }
 707        print STDERR "  Found ", $revnum, " revision(s).\n";
 708        return @page_revs;
 709}
 710
 711sub fetch_mw_revisions {
 712        my $pages = shift; my @pages = @{$pages};
 713        my $fetch_from = shift;
 714
 715        my @revisions = ();
 716        my $n = 1;
 717        foreach my $page (@pages) {
 718                my $id = $page->{pageid};
 719
 720                print STDERR "page $n/", scalar(@pages), ": ". $page->{title} ."\n";
 721                $n++;
 722                my @page_revs = fetch_mw_revisions_for_page($page, $id, $fetch_from);
 723                @revisions = (@page_revs, @revisions);
 724        }
 725
 726        return ($n, @revisions);
 727}
 728
 729sub fe_escape_path {
 730    my $path = shift;
 731    $path =~ s/\\/\\\\/g;
 732    $path =~ s/"/\\"/g;
 733    $path =~ s/\n/\\n/g;
 734    return '"' . $path . '"';
 735}
 736
 737sub import_file_revision {
 738        my $commit = shift;
 739        my %commit = %{$commit};
 740        my $full_import = shift;
 741        my $n = shift;
 742        my $mediafile = shift;
 743        my %mediafile;
 744        if ($mediafile) {
 745                %mediafile = %{$mediafile};
 746        }
 747
 748        my $title = $commit{title};
 749        my $comment = $commit{comment};
 750        my $content = $commit{content};
 751        my $author = $commit{author};
 752        my $date = $commit{date};
 753
 754        print STDOUT "commit refs/mediawiki/$remotename/master\n";
 755        print STDOUT "mark :$n\n";
 756        print STDOUT "committer $author <$author\@$wiki_name> ", $date->epoch, " +0000\n";
 757        literal_data($comment);
 758
 759        # If it's not a clone, we need to know where to start from
 760        if (!$full_import && $n == 1) {
 761                print STDOUT "from refs/mediawiki/$remotename/master^0\n";
 762        }
 763        if ($content ne DELETED_CONTENT) {
 764                print STDOUT "M 644 inline " .
 765                    fe_escape_path($title . ".mw") . "\n";
 766                literal_data($content);
 767                if (%mediafile) {
 768                        print STDOUT "M 644 inline "
 769                            . fe_escape_path($mediafile{title}) . "\n";
 770                        literal_data_raw($mediafile{content});
 771                }
 772                print STDOUT "\n\n";
 773        } else {
 774                print STDOUT "D " . fe_escape_path($title . ".mw") . "\n";
 775        }
 776
 777        # mediawiki revision number in the git note
 778        if ($full_import && $n == 1) {
 779                print STDOUT "reset refs/notes/$remotename/mediawiki\n";
 780        }
 781        print STDOUT "commit refs/notes/$remotename/mediawiki\n";
 782        print STDOUT "committer $author <$author\@$wiki_name> ", $date->epoch, " +0000\n";
 783        literal_data("Note added by git-mediawiki during import");
 784        if (!$full_import && $n == 1) {
 785                print STDOUT "from refs/notes/$remotename/mediawiki^0\n";
 786        }
 787        print STDOUT "N inline :$n\n";
 788        literal_data("mediawiki_revision: " . $commit{mw_revision});
 789        print STDOUT "\n\n";
 790}
 791
 792# parse a sequence of
 793# <cmd> <arg1>
 794# <cmd> <arg2>
 795# \n
 796# (like batch sequence of import and sequence of push statements)
 797sub get_more_refs {
 798        my $cmd = shift;
 799        my @refs;
 800        while (1) {
 801                my $line = <STDIN>;
 802                if ($line =~ m/^$cmd (.*)$/) {
 803                        push(@refs, $1);
 804                } elsif ($line eq "\n") {
 805                        return @refs;
 806                } else {
 807                        die("Invalid command in a '$cmd' batch: ". $_);
 808                }
 809        }
 810}
 811
 812sub mw_import {
 813        # multiple import commands can follow each other.
 814        my @refs = (shift, get_more_refs("import"));
 815        foreach my $ref (@refs) {
 816                mw_import_ref($ref);
 817        }
 818        print STDOUT "done\n";
 819}
 820
 821sub mw_import_ref {
 822        my $ref = shift;
 823        # The remote helper will call "import HEAD" and
 824        # "import refs/heads/master".
 825        # Since HEAD is a symbolic ref to master (by convention,
 826        # followed by the output of the command "list" that we gave),
 827        # we don't need to do anything in this case.
 828        if ($ref eq "HEAD") {
 829                return;
 830        }
 831
 832        mw_connect_maybe();
 833
 834        print STDERR "Searching revisions...\n";
 835        my $last_local = get_last_local_revision();
 836        my $fetch_from = $last_local + 1;
 837        if ($fetch_from == 1) {
 838                print STDERR ", fetching from beginning.\n";
 839        } else {
 840                print STDERR ", fetching from here.\n";
 841        }
 842
 843        my $n = 0;
 844        if ($fetch_strategy eq "by_rev") {
 845                print STDERR "Fetching & writing export data by revs...\n";
 846                $n = mw_import_ref_by_revs($fetch_from);
 847        } elsif ($fetch_strategy eq "by_page") {
 848                print STDERR "Fetching & writing export data by pages...\n";
 849                $n = mw_import_ref_by_pages($fetch_from);
 850        } else {
 851                print STDERR "fatal: invalid fetch strategy \"$fetch_strategy\".\n";
 852                print STDERR "Check your configuration variables remote.$remotename.fetchStrategy and mediawiki.fetchStrategy\n";
 853                exit 1;
 854        }
 855
 856        if ($fetch_from == 1 && $n == 0) {
 857                print STDERR "You appear to have cloned an empty MediaWiki.\n";
 858                # Something has to be done remote-helper side. If nothing is done, an error is
 859                # thrown saying that HEAD is referring to unknown object 0000000000000000000
 860                # and the clone fails.
 861        }
 862}
 863
 864sub mw_import_ref_by_pages {
 865
 866        my $fetch_from = shift;
 867        my %pages_hash = get_mw_pages();
 868        my @pages = values(%pages_hash);
 869
 870        my ($n, @revisions) = fetch_mw_revisions(\@pages, $fetch_from);
 871
 872        @revisions = sort {$a->{revid} <=> $b->{revid}} @revisions;
 873        my @revision_ids = map $_->{revid}, @revisions;
 874
 875        return mw_import_revids($fetch_from, \@revision_ids, \%pages_hash);
 876}
 877
 878sub mw_import_ref_by_revs {
 879
 880        my $fetch_from = shift;
 881        my %pages_hash = get_mw_pages();
 882
 883        my $last_remote = get_last_global_remote_rev();
 884        my @revision_ids = $fetch_from..$last_remote;
 885        return mw_import_revids($fetch_from, \@revision_ids, \%pages_hash);
 886}
 887
 888# Import revisions given in second argument (array of integers).
 889# Only pages appearing in the third argument (hash indexed by page titles)
 890# will be imported.
 891sub mw_import_revids {
 892        my $fetch_from = shift;
 893        my $revision_ids = shift;
 894        my $pages = shift;
 895
 896        my $n = 0;
 897        my $n_actual = 0;
 898        my $last_timestamp = 0; # Placeholer in case $rev->timestamp is undefined
 899
 900        foreach my $pagerevid (@$revision_ids) {
 901                # Count page even if we skip it, since we display
 902                # $n/$total and $total includes skipped pages.
 903                $n++;
 904
 905                # fetch the content of the pages
 906                my $query = {
 907                        action => 'query',
 908                        prop => 'revisions',
 909                        rvprop => 'content|timestamp|comment|user|ids',
 910                        revids => $pagerevid,
 911                };
 912
 913                my $result = $mediawiki->api($query);
 914
 915                if (!$result) {
 916                        die "Failed to retrieve modified page for revision $pagerevid";
 917                }
 918
 919                if (defined($result->{query}->{badrevids}->{$pagerevid})) {
 920                        # The revision id does not exist on the remote wiki.
 921                        next;
 922                }
 923
 924                if (!defined($result->{query}->{pages})) {
 925                        die "Invalid revision $pagerevid.";
 926                }
 927
 928                my @result_pages = values(%{$result->{query}->{pages}});
 929                my $result_page = $result_pages[0];
 930                my $rev = $result_pages[0]->{revisions}->[0];
 931
 932                my $page_title = $result_page->{title};
 933
 934                if (!exists($pages->{$page_title})) {
 935                        print STDERR "$n/", scalar(@$revision_ids),
 936                                ": Skipping revision #$rev->{revid} of $page_title\n";
 937                        next;
 938                }
 939
 940                $n_actual++;
 941
 942                my %commit;
 943                $commit{author} = $rev->{user} || 'Anonymous';
 944                $commit{comment} = $rev->{comment} || EMPTY_MESSAGE;
 945                $commit{title} = mediawiki_smudge_filename($page_title);
 946                $commit{mw_revision} = $rev->{revid};
 947                $commit{content} = mediawiki_smudge($rev->{'*'});
 948
 949                if (!defined($rev->{timestamp})) {
 950                        $last_timestamp++;
 951                } else {
 952                        $last_timestamp = $rev->{timestamp};
 953                }
 954                $commit{date} = DateTime::Format::ISO8601->parse_datetime($last_timestamp);
 955
 956                # Differentiates classic pages and media files.
 957                my ($namespace, $filename) = $page_title =~ /^([^:]*):(.*)$/;
 958                my %mediafile;
 959                if ($namespace) {
 960                        my $id = get_mw_namespace_id($namespace);
 961                        if ($id && $id == get_mw_namespace_id("File")) {
 962                                %mediafile = get_mw_mediafile_for_page_revision($filename, $rev->{timestamp});
 963                        }
 964                }
 965                # If this is a revision of the media page for new version
 966                # of a file do one common commit for both file and media page.
 967                # Else do commit only for that page.
 968                print STDERR "$n/", scalar(@$revision_ids), ": Revision #$rev->{revid} of $commit{title}\n";
 969                import_file_revision(\%commit, ($fetch_from == 1), $n_actual, \%mediafile);
 970        }
 971
 972        return $n_actual;
 973}
 974
 975sub error_non_fast_forward {
 976        my $advice = run_git("config --bool advice.pushNonFastForward");
 977        chomp($advice);
 978        if ($advice ne "false") {
 979                # Native git-push would show this after the summary.
 980                # We can't ask it to display it cleanly, so print it
 981                # ourselves before.
 982                print STDERR "To prevent you from losing history, non-fast-forward updates were rejected\n";
 983                print STDERR "Merge the remote changes (e.g. 'git pull') before pushing again. See the\n";
 984                print STDERR "'Note about fast-forwards' section of 'git push --help' for details.\n";
 985        }
 986        print STDOUT "error $_[0] \"non-fast-forward\"\n";
 987        return 0;
 988}
 989
 990sub mw_upload_file {
 991        my $complete_file_name = shift;
 992        my $new_sha1 = shift;
 993        my $extension = shift;
 994        my $file_deleted = shift;
 995        my $summary = shift;
 996        my $newrevid;
 997        my $path = "File:" . $complete_file_name;
 998        my %hashFiles = get_allowed_file_extensions();
 999        if (!exists($hashFiles{$extension})) {
1000                print STDERR "$complete_file_name is not a permitted file on this wiki.\n";
1001                print STDERR "Check the configuration of file uploads in your mediawiki.\n";
1002                return $newrevid;
1003        }
1004        # Deleting and uploading a file requires a priviledged user
1005        if ($file_deleted) {
1006                mw_connect_maybe();
1007                my $query = {
1008                        action => 'delete',
1009                        title => $path,
1010                        reason => $summary
1011                };
1012                if (!$mediawiki->edit($query)) {
1013                        print STDERR "Failed to delete file on remote wiki\n";
1014                        print STDERR "Check your permissions on the remote site. Error code:\n";
1015                        print STDERR $mediawiki->{error}->{code} . ':' . $mediawiki->{error}->{details};
1016                        exit 1;
1017                }
1018        } else {
1019                # Don't let perl try to interpret file content as UTF-8 => use "raw"
1020                my $content = run_git("cat-file blob $new_sha1", "raw");
1021                if ($content ne "") {
1022                        mw_connect_maybe();
1023                        $mediawiki->{config}->{upload_url} =
1024                                "$url/index.php/Special:Upload";
1025                        $mediawiki->edit({
1026                                action => 'upload',
1027                                filename => $complete_file_name,
1028                                comment => $summary,
1029                                file => [undef,
1030                                         $complete_file_name,
1031                                         Content => $content],
1032                                ignorewarnings => 1,
1033                        }, {
1034                                skip_encoding => 1
1035                        } ) || die $mediawiki->{error}->{code} . ':'
1036                                 . $mediawiki->{error}->{details};
1037                        my $last_file_page = $mediawiki->get_page({title => $path});
1038                        $newrevid = $last_file_page->{revid};
1039                        print STDERR "Pushed file: $new_sha1 - $complete_file_name.\n";
1040                } else {
1041                        print STDERR "Empty file $complete_file_name not pushed.\n";
1042                }
1043        }
1044        return $newrevid;
1045}
1046
1047sub mw_push_file {
1048        my $diff_info = shift;
1049        # $diff_info contains a string in this format:
1050        # 100644 100644 <sha1_of_blob_before_commit> <sha1_of_blob_now> <status>
1051        my @diff_info_split = split(/[ \t]/, $diff_info);
1052
1053        # Filename, including .mw extension
1054        my $complete_file_name = shift;
1055        # Commit message
1056        my $summary = shift;
1057        # MediaWiki revision number. Keep the previous one by default,
1058        # in case there's no edit to perform.
1059        my $oldrevid = shift;
1060        my $newrevid;
1061
1062        if ($summary eq EMPTY_MESSAGE) {
1063                $summary = '';
1064        }
1065
1066        my $new_sha1 = $diff_info_split[3];
1067        my $old_sha1 = $diff_info_split[2];
1068        my $page_created = ($old_sha1 eq NULL_SHA1);
1069        my $page_deleted = ($new_sha1 eq NULL_SHA1);
1070        $complete_file_name = mediawiki_clean_filename($complete_file_name);
1071
1072        my ($title, $extension) = $complete_file_name =~ /^(.*)\.([^\.]*)$/;
1073        if (!defined($extension)) {
1074                $extension = "";
1075        }
1076        if ($extension eq "mw") {
1077                my $ns = get_mw_namespace_id_for_page($complete_file_name);
1078                if ($ns && $ns == get_mw_namespace_id("File") && (!$export_media)) {
1079                        print STDERR "Ignoring media file related page: $complete_file_name\n";
1080                        return ($oldrevid, "ok");
1081                }
1082                my $file_content;
1083                if ($page_deleted) {
1084                        # Deleting a page usually requires
1085                        # special privileges. A common
1086                        # convention is to replace the page
1087                        # with this content instead:
1088                        $file_content = DELETED_CONTENT;
1089                } else {
1090                        $file_content = run_git("cat-file blob $new_sha1");
1091                }
1092
1093                mw_connect_maybe();
1094
1095                my $result = $mediawiki->edit( {
1096                        action => 'edit',
1097                        summary => $summary,
1098                        title => $title,
1099                        basetimestamp => $basetimestamps{$oldrevid},
1100                        text => mediawiki_clean($file_content, $page_created),
1101                                  }, {
1102                                          skip_encoding => 1 # Helps with names with accentuated characters
1103                                  });
1104                if (!$result) {
1105                        if ($mediawiki->{error}->{code} == 3) {
1106                                # edit conflicts, considered as non-fast-forward
1107                                print STDERR 'Warning: Error ' .
1108                                    $mediawiki->{error}->{code} .
1109                                    ' from mediwiki: ' . $mediawiki->{error}->{details} .
1110                                    ".\n";
1111                                return ($oldrevid, "non-fast-forward");
1112                        } else {
1113                                # Other errors. Shouldn't happen => just die()
1114                                die 'Fatal: Error ' .
1115                                    $mediawiki->{error}->{code} .
1116                                    ' from mediwiki: ' . $mediawiki->{error}->{details};
1117                        }
1118                }
1119                $newrevid = $result->{edit}->{newrevid};
1120                print STDERR "Pushed file: $new_sha1 - $title\n";
1121        } elsif ($export_media) {
1122                $newrevid = mw_upload_file($complete_file_name, $new_sha1,
1123                                           $extension, $page_deleted,
1124                                           $summary);
1125        } else {
1126                print STDERR "Ignoring media file $title\n";
1127        }
1128        $newrevid = ($newrevid or $oldrevid);
1129        return ($newrevid, "ok");
1130}
1131
1132sub mw_push {
1133        # multiple push statements can follow each other
1134        my @refsspecs = (shift, get_more_refs("push"));
1135        my $pushed;
1136        for my $refspec (@refsspecs) {
1137                my ($force, $local, $remote) = $refspec =~ /^(\+)?([^:]*):([^:]*)$/
1138                    or die("Invalid refspec for push. Expected <src>:<dst> or +<src>:<dst>");
1139                if ($force) {
1140                        print STDERR "Warning: forced push not allowed on a MediaWiki.\n";
1141                }
1142                if ($local eq "") {
1143                        print STDERR "Cannot delete remote branch on a MediaWiki\n";
1144                        print STDOUT "error $remote cannot delete\n";
1145                        next;
1146                }
1147                if ($remote ne "refs/heads/master") {
1148                        print STDERR "Only push to the branch 'master' is supported on a MediaWiki\n";
1149                        print STDOUT "error $remote only master allowed\n";
1150                        next;
1151                }
1152                if (mw_push_revision($local, $remote)) {
1153                        $pushed = 1;
1154                }
1155        }
1156
1157        # Notify Git that the push is done
1158        print STDOUT "\n";
1159
1160        if ($pushed && $dumb_push) {
1161                print STDERR "Just pushed some revisions to MediaWiki.\n";
1162                print STDERR "The pushed revisions now have to be re-imported, and your current branch\n";
1163                print STDERR "needs to be updated with these re-imported commits. You can do this with\n";
1164                print STDERR "\n";
1165                print STDERR "  git pull --rebase\n";
1166                print STDERR "\n";
1167        }
1168}
1169
1170sub mw_push_revision {
1171        my $local = shift;
1172        my $remote = shift; # actually, this has to be "refs/heads/master" at this point.
1173        my $last_local_revid = get_last_local_revision();
1174        print STDERR ".\n"; # Finish sentence started by get_last_local_revision()
1175        my $last_remote_revid = get_last_remote_revision();
1176        my $mw_revision = $last_remote_revid;
1177
1178        # Get sha1 of commit pointed by local HEAD
1179        my $HEAD_sha1 = run_git("rev-parse $local 2>/dev/null"); chomp($HEAD_sha1);
1180        # Get sha1 of commit pointed by remotes/$remotename/master
1181        my $remoteorigin_sha1 = run_git("rev-parse refs/remotes/$remotename/master 2>/dev/null");
1182        chomp($remoteorigin_sha1);
1183
1184        if ($last_local_revid > 0 &&
1185            $last_local_revid < $last_remote_revid) {
1186                return error_non_fast_forward($remote);
1187        }
1188
1189        if ($HEAD_sha1 eq $remoteorigin_sha1) {
1190                # nothing to push
1191                return 0;
1192        }
1193
1194        # Get every commit in between HEAD and refs/remotes/origin/master,
1195        # including HEAD and refs/remotes/origin/master
1196        my @commit_pairs = ();
1197        if ($last_local_revid > 0) {
1198                my $parsed_sha1 = $remoteorigin_sha1;
1199                # Find a path from last MediaWiki commit to pushed commit
1200                print STDERR "Computing path from local to remote ...\n";
1201                my @local_ancestry = split(/\n/, run_git("rev-list --boundary --parents $local ^$parsed_sha1"));
1202                my %local_ancestry;
1203                foreach my $line (@local_ancestry) {
1204                        if (my ($child, $parents) = $line =~ m/^-?([a-f0-9]+) ([a-f0-9 ]+)/) {
1205                                foreach my $parent (split(' ', $parents)) {
1206                                        $local_ancestry{$parent} = $child;
1207                                }
1208                        } elsif (!$line =~ m/^([a-f0-9]+)/) {
1209                                die "Unexpected output from git rev-list: $line";
1210                        }
1211                }
1212                while ($parsed_sha1 ne $HEAD_sha1) {
1213                        my $child = $local_ancestry{$parsed_sha1};
1214                        if (!$child) {
1215                                printf STDERR "Cannot find a path in history from remote commit to last commit\n";
1216                                return error_non_fast_forward($remote);
1217                        }
1218                        push(@commit_pairs, [$parsed_sha1, $child]);
1219                        $parsed_sha1 = $child;
1220                }
1221        } else {
1222                # No remote mediawiki revision. Export the whole
1223                # history (linearized with --first-parent)
1224                print STDERR "Warning: no common ancestor, pushing complete history\n";
1225                my $history = run_git("rev-list --first-parent --children $local");
1226                my @history = split('\n', $history);
1227                @history = @history[1..$#history];
1228                foreach my $line (reverse @history) {
1229                        my @commit_info_split = split(/ |\n/, $line);
1230                        push(@commit_pairs, \@commit_info_split);
1231                }
1232        }
1233
1234        foreach my $commit_info_split (@commit_pairs) {
1235                my $sha1_child = @{$commit_info_split}[0];
1236                my $sha1_commit = @{$commit_info_split}[1];
1237                my $diff_infos = run_git("diff-tree -r --raw -z $sha1_child $sha1_commit");
1238                # TODO: we could detect rename, and encode them with a #redirect on the wiki.
1239                # TODO: for now, it's just a delete+add
1240                my @diff_info_list = split(/\0/, $diff_infos);
1241                # Keep the subject line of the commit message as mediawiki comment for the revision
1242                my $commit_msg = run_git("log --no-walk --format=\"%s\" $sha1_commit");
1243                chomp($commit_msg);
1244                # Push every blob
1245                while (@diff_info_list) {
1246                        my $status;
1247                        # git diff-tree -z gives an output like
1248                        # <metadata>\0<filename1>\0
1249                        # <metadata>\0<filename2>\0
1250                        # and we've split on \0.
1251                        my $info = shift(@diff_info_list);
1252                        my $file = shift(@diff_info_list);
1253                        ($mw_revision, $status) = mw_push_file($info, $file, $commit_msg, $mw_revision);
1254                        if ($status eq "non-fast-forward") {
1255                                # we may already have sent part of the
1256                                # commit to MediaWiki, but it's too
1257                                # late to cancel it. Stop the push in
1258                                # the middle, but still give an
1259                                # accurate error message.
1260                                return error_non_fast_forward($remote);
1261                        }
1262                        if ($status ne "ok") {
1263                                die("Unknown error from mw_push_file()");
1264                        }
1265                }
1266                unless ($dumb_push) {
1267                        run_git("notes --ref=$remotename/mediawiki add -f -m \"mediawiki_revision: $mw_revision\" $sha1_commit");
1268                        run_git("update-ref -m \"Git-MediaWiki push\" refs/mediawiki/$remotename/master $sha1_commit $sha1_child");
1269                }
1270        }
1271
1272        print STDOUT "ok $remote\n";
1273        return 1;
1274}
1275
1276sub get_allowed_file_extensions {
1277        mw_connect_maybe();
1278
1279        my $query = {
1280                action => 'query',
1281                meta => 'siteinfo',
1282                siprop => 'fileextensions'
1283                };
1284        my $result = $mediawiki->api($query);
1285        my @file_extensions= map $_->{ext},@{$result->{query}->{fileextensions}};
1286        my %hashFile = map {$_ => 1}@file_extensions;
1287
1288        return %hashFile;
1289}
1290
1291# In memory cache for MediaWiki namespace ids.
1292my %namespace_id;
1293
1294# Namespaces whose id is cached in the configuration file
1295# (to avoid duplicates)
1296my %cached_mw_namespace_id;
1297
1298# Return MediaWiki id for a canonical namespace name.
1299# Ex.: "File", "Project".
1300sub get_mw_namespace_id {
1301        mw_connect_maybe();
1302        my $name = shift;
1303
1304        if (!exists $namespace_id{$name}) {
1305                # Look at configuration file, if the record for that namespace is
1306                # already cached. Namespaces are stored in form:
1307                # "Name_of_namespace:Id_namespace", ex.: "File:6".
1308                my @temp = split(/[\n]/, run_git("config --get-all remote."
1309                                                . $remotename .".namespaceCache"));
1310                chomp(@temp);
1311                foreach my $ns (@temp) {
1312                        my ($n, $id) = split(/:/, $ns);
1313                        if ($id eq 'notANameSpace') {
1314                                $namespace_id{$n} = {is_namespace => 0};
1315                        } else {
1316                                $namespace_id{$n} = {is_namespace => 1, id => $id};
1317                        }
1318                        $cached_mw_namespace_id{$n} = 1;
1319                }
1320        }
1321
1322        if (!exists $namespace_id{$name}) {
1323                print STDERR "Namespace $name not found in cache, querying the wiki ...\n";
1324                # NS not found => get namespace id from MW and store it in
1325                # configuration file.
1326                my $query = {
1327                        action => 'query',
1328                        meta => 'siteinfo',
1329                        siprop => 'namespaces'
1330                };
1331                my $result = $mediawiki->api($query);
1332
1333                while (my ($id, $ns) = each(%{$result->{query}->{namespaces}})) {
1334                        if (defined($ns->{id}) && defined($ns->{canonical})) {
1335                                $namespace_id{$ns->{canonical}} = {is_namespace => 1, id => $ns->{id}};
1336                                if ($ns->{'*'}) {
1337                                        # alias (e.g. french Fichier: as alias for canonical File:)
1338                                        $namespace_id{$ns->{'*'}} = {is_namespace => 1, id => $ns->{id}};
1339                                }
1340                        }
1341                }
1342        }
1343
1344        my $ns = $namespace_id{$name};
1345        my $id;
1346
1347        unless (defined $ns) {
1348                print STDERR "No such namespace $name on MediaWiki.\n";
1349                $ns = {is_namespace => 0};
1350                $namespace_id{$name} = $ns;
1351        }
1352
1353        if ($ns->{is_namespace}) {
1354                $id = $ns->{id};
1355        }
1356
1357        # Store "notANameSpace" as special value for inexisting namespaces
1358        my $store_id = ($id || 'notANameSpace');
1359
1360        # Store explicitely requested namespaces on disk
1361        if (!exists $cached_mw_namespace_id{$name}) {
1362                run_git("config --add remote.". $remotename
1363                        .".namespaceCache \"". $name .":". $store_id ."\"");
1364                $cached_mw_namespace_id{$name} = 1;
1365        }
1366        return $id;
1367}
1368
1369sub get_mw_namespace_id_for_page {
1370        if (my ($namespace) = $_[0] =~ /^([^:]*):/) {
1371                return get_mw_namespace_id($namespace);
1372        } else {
1373                return;
1374        }
1375}