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