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