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