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