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