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