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