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