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