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