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 374my%pages;# hash on page titles to avoid duplicates 375my$user_defined; 376if(@tracked_pages) { 377$user_defined=1; 378# The user provided a list of pages titles, but we 379# still need to query the API to get the page IDs. 380 get_mw_tracked_pages(\%pages); 381} 382if(@tracked_categories) { 383$user_defined=1; 384 get_mw_tracked_categories(\%pages); 385} 386if(!$user_defined) { 387 get_mw_all_pages(\%pages); 388} 389if($import_media) { 390print STDERR "Getting media files for selected pages...\n"; 391if($user_defined) { 392 get_linked_mediafiles(\%pages); 393}else{ 394 get_all_mediafiles(\%pages); 395} 396} 397return%pages; 398} 399 400# usage: $out = run_git("command args"); 401# $out = run_git("command args", "raw"); # don't interpret output as UTF-8. 402sub run_git { 403my$args=shift; 404my$encoding= (shift||"encoding(UTF-8)"); 405open(my$git,"-|:$encoding","git ".$args); 406my$res=do{local$/; <$git> }; 407close($git); 408 409return$res; 410} 411 412 413sub get_all_mediafiles { 414my$pages=shift; 415# Attach list of all pages for media files from the API, 416# they are in a different namespace, only one namespace 417# can be queried at the same moment 418my$mw_pages=$mediawiki->list({ 419 action =>'query', 420 list =>'allpages', 421 apnamespace => get_mw_namespace_id("File"), 422 aplimit =>'max' 423}); 424if(!defined($mw_pages)) { 425print STDERR "fatal: could not get the list of pages for media files.\n"; 426print STDERR "fatal: '$url' does not appear to be a mediawiki\n"; 427print STDERR "fatal: make sure '$url/api.php' is a valid page.\n"; 428exit1; 429} 430foreachmy$page(@{$mw_pages}) { 431$pages->{$page->{title}} =$page; 432} 433} 434 435sub get_linked_mediafiles { 436my$pages=shift; 437my@titles=map$_->{title},values(%{$pages}); 438 439# The query is split in small batches because of the MW API limit of 440# the number of links to be returned (500 links max). 441my$batch=10; 442while(@titles) { 443if($#titles<$batch) { 444$batch=$#titles; 445} 446my@slice=@titles[0..$batch]; 447 448# pattern 'page1|page2|...' required by the API 449my$mw_titles=join('|',@slice); 450 451# Media files could be included or linked from 452# a page, get all related 453my$query= { 454 action =>'query', 455 prop =>'links|images', 456 titles =>$mw_titles, 457 plnamespace => get_mw_namespace_id("File"), 458 pllimit =>'max' 459}; 460my$result=$mediawiki->api($query); 461 462while(my($id,$page) =each(%{$result->{query}->{pages}})) { 463my@media_titles; 464if(defined($page->{links})) { 465my@link_titles=map$_->{title}, @{$page->{links}}; 466push(@media_titles,@link_titles); 467} 468if(defined($page->{images})) { 469my@image_titles=map$_->{title}, @{$page->{images}}; 470push(@media_titles,@image_titles); 471} 472if(@media_titles) { 473 get_mw_page_list(\@media_titles,$pages); 474} 475} 476 477@titles=@titles[($batch+1)..$#titles]; 478} 479} 480 481sub get_mw_mediafile_for_page_revision { 482# Name of the file on Wiki, with the prefix. 483my$filename=shift; 484my$timestamp=shift; 485my%mediafile; 486 487# Search if on a media file with given timestamp exists on 488# MediaWiki. In that case download the file. 489my$query= { 490 action =>'query', 491 prop =>'imageinfo', 492 titles =>"File:".$filename, 493 iistart =>$timestamp, 494 iiend =>$timestamp, 495 iiprop =>'timestamp|archivename|url', 496 iilimit =>1 497}; 498my$result=$mediawiki->api($query); 499 500my($fileid,$file) =each( %{$result->{query}->{pages}} ); 501# If not defined it means there is no revision of the file for 502# given timestamp. 503if(defined($file->{imageinfo})) { 504$mediafile{title} =$filename; 505 506my$fileinfo=pop(@{$file->{imageinfo}}); 507$mediafile{timestamp} =$fileinfo->{timestamp}; 508# Mediawiki::API's download function doesn't support https URLs 509# and can't download old versions of files. 510print STDERR "\tDownloading file$mediafile{title}, version$mediafile{timestamp}\n"; 511$mediafile{content} = download_mw_mediafile($fileinfo->{url}); 512} 513return%mediafile; 514} 515 516sub download_mw_mediafile { 517my$url=shift; 518 519my$response=$mediawiki->{ua}->get($url); 520if($response->code==200) { 521return$response->decoded_content; 522}else{ 523print STDERR "Error downloading mediafile from :\n"; 524print STDERR "URL:$url\n"; 525print STDERR "Server response: ".$response->code." ".$response->message."\n"; 526exit1; 527} 528} 529 530sub get_last_local_revision { 531# Get note regarding last mediawiki revision 532my$note= run_git("notes --ref=$remotename/mediawikishow refs/mediawiki/$remotename/master2>/dev/null"); 533my@note_info=split(/ /,$note); 534 535my$lastrevision_number; 536if(!(defined($note_info[0]) &&$note_info[0]eq"mediawiki_revision:")) { 537print STDERR "No previous mediawiki revision found"; 538$lastrevision_number=0; 539}else{ 540# Notes are formatted : mediawiki_revision: #number 541$lastrevision_number=$note_info[1]; 542chomp($lastrevision_number); 543print STDERR "Last local mediawiki revision found is$lastrevision_number"; 544} 545return$lastrevision_number; 546} 547 548# Remember the timestamp corresponding to a revision id. 549my%basetimestamps; 550 551# Get the last remote revision without taking in account which pages are 552# tracked or not. This function makes a single request to the wiki thus 553# avoid a loop onto all tracked pages. This is useful for the fetch-by-rev 554# option. 555sub get_last_global_remote_rev { 556 mw_connect_maybe(); 557 558my$query= { 559 action =>'query', 560 list =>'recentchanges', 561 prop =>'revisions', 562 rclimit =>'1', 563 rcdir =>'older', 564}; 565my$result=$mediawiki->api($query); 566return$result->{query}->{recentchanges}[0]->{revid}; 567} 568 569# Get the last remote revision concerning the tracked pages and the tracked 570# categories. 571sub get_last_remote_revision { 572 mw_connect_maybe(); 573 574my%pages_hash= get_mw_pages(); 575my@pages=values(%pages_hash); 576 577my$max_rev_num=0; 578 579foreachmy$page(@pages) { 580my$id=$page->{pageid}; 581 582my$query= { 583 action =>'query', 584 prop =>'revisions', 585 rvprop =>'ids|timestamp', 586 pageids =>$id, 587}; 588 589my$result=$mediawiki->api($query); 590 591my$lastrev=pop(@{$result->{query}->{pages}->{$id}->{revisions}}); 592 593$basetimestamps{$lastrev->{revid}} =$lastrev->{timestamp}; 594 595$max_rev_num= ($lastrev->{revid} >$max_rev_num?$lastrev->{revid} :$max_rev_num); 596} 597 598print STDERR "Last remote revision found is$max_rev_num.\n"; 599return$max_rev_num; 600} 601 602# Clean content before sending it to MediaWiki 603sub mediawiki_clean { 604my$string=shift; 605my$page_created=shift; 606# Mediawiki does not allow blank space at the end of a page and ends with a single \n. 607# This function right trims a string and adds a \n at the end to follow this rule 608$string=~s/\s+$//; 609if($stringeq""&&$page_created) { 610# Creating empty pages is forbidden. 611$string= EMPTY_CONTENT; 612} 613return$string."\n"; 614} 615 616# Filter applied on MediaWiki data before adding them to Git 617sub mediawiki_smudge { 618my$string=shift; 619if($stringeq EMPTY_CONTENT) { 620$string=""; 621} 622# This \n is important. This is due to mediawiki's way to handle end of files. 623return$string."\n"; 624} 625 626sub mediawiki_clean_filename { 627my$filename=shift; 628$filename=~s/@{[SLASH_REPLACEMENT]}/\//g; 629# [, ], |, {, and } are forbidden by MediaWiki, even URL-encoded. 630# Do a variant of URL-encoding, i.e. looks like URL-encoding, 631# but with _ added to prevent MediaWiki from thinking this is 632# an actual special character. 633$filename=~s/[\[\]\{\}\|]/sprintf("_%%_%x", ord($&))/ge; 634# If we use the uri escape before 635# we should unescape here, before anything 636 637return$filename; 638} 639 640sub mediawiki_smudge_filename { 641my$filename=shift; 642$filename=~s/\//@{[SLASH_REPLACEMENT]}/g; 643$filename=~s/ /_/g; 644# Decode forbidden characters encoded in mediawiki_clean_filename 645$filename=~s/_%_([0-9a-fA-F][0-9a-fA-F])/sprintf("%c", hex($1))/ge; 646return$filename; 647} 648 649sub literal_data { 650my($content) =@_; 651print STDOUT "data ", bytes::length($content),"\n",$content; 652} 653 654sub literal_data_raw { 655# Output possibly binary content. 656my($content) =@_; 657# Avoid confusion between size in bytes and in characters 658 utf8::downgrade($content); 659binmode STDOUT,":raw"; 660print STDOUT "data ", bytes::length($content),"\n",$content; 661binmode STDOUT,":utf8"; 662} 663 664sub mw_capabilities { 665# Revisions are imported to the private namespace 666# refs/mediawiki/$remotename/ by the helper and fetched into 667# refs/remotes/$remotename later by fetch. 668print STDOUT "refspec refs/heads/*:refs/mediawiki/$remotename/*\n"; 669print STDOUT "import\n"; 670print STDOUT "list\n"; 671print STDOUT "push\n"; 672print STDOUT "\n"; 673} 674 675sub mw_list { 676# MediaWiki do not have branches, we consider one branch arbitrarily 677# called master, and HEAD pointing to it. 678print STDOUT "? refs/heads/master\n"; 679print STDOUT "\@refs/heads/masterHEAD\n"; 680print STDOUT "\n"; 681} 682 683sub mw_option { 684print STDERR "remote-helper command 'option$_[0]' not yet implemented\n"; 685print STDOUT "unsupported\n"; 686} 687 688sub fetch_mw_revisions_for_page { 689my$page=shift; 690my$id=shift; 691my$fetch_from=shift; 692my@page_revs= (); 693my$query= { 694 action =>'query', 695 prop =>'revisions', 696 rvprop =>'ids', 697 rvdir =>'newer', 698 rvstartid =>$fetch_from, 699 rvlimit =>500, 700 pageids =>$id, 701}; 702 703my$revnum=0; 704# Get 500 revisions at a time due to the mediawiki api limit 705while(1) { 706my$result=$mediawiki->api($query); 707 708# Parse each of those 500 revisions 709foreachmy$revision(@{$result->{query}->{pages}->{$id}->{revisions}}) { 710my$page_rev_ids; 711$page_rev_ids->{pageid} =$page->{pageid}; 712$page_rev_ids->{revid} =$revision->{revid}; 713push(@page_revs,$page_rev_ids); 714$revnum++; 715} 716last unless$result->{'query-continue'}; 717$query->{rvstartid} =$result->{'query-continue'}->{revisions}->{rvstartid}; 718} 719if($shallow_import&&@page_revs) { 720print STDERR " Found 1 revision (shallow import).\n"; 721@page_revs=sort{$b->{revid} <=>$a->{revid}} (@page_revs); 722return$page_revs[0]; 723} 724print STDERR " Found ",$revnum," revision(s).\n"; 725return@page_revs; 726} 727 728sub fetch_mw_revisions { 729my$pages=shift;my@pages= @{$pages}; 730my$fetch_from=shift; 731 732my@revisions= (); 733my$n=1; 734foreachmy$page(@pages) { 735my$id=$page->{pageid}; 736 737print STDERR "page$n/",scalar(@pages),": ".$page->{title} ."\n"; 738$n++; 739my@page_revs= fetch_mw_revisions_for_page($page,$id,$fetch_from); 740@revisions= (@page_revs,@revisions); 741} 742 743return($n,@revisions); 744} 745 746sub import_file_revision { 747my$commit=shift; 748my%commit= %{$commit}; 749my$full_import=shift; 750my$n=shift; 751my$mediafile=shift; 752my%mediafile; 753if($mediafile) { 754%mediafile= %{$mediafile}; 755} 756 757my$title=$commit{title}; 758my$comment=$commit{comment}; 759my$content=$commit{content}; 760my$author=$commit{author}; 761my$date=$commit{date}; 762 763print STDOUT "commit refs/mediawiki/$remotename/master\n"; 764print STDOUT "mark :$n\n"; 765print STDOUT "committer$author<$author\@$wiki_name> ",$date->epoch," +0000\n"; 766 literal_data($comment); 767 768# If it's not a clone, we need to know where to start from 769if(!$full_import&&$n==1) { 770print STDOUT "from refs/mediawiki/$remotename/master^0\n"; 771} 772if($contentne DELETED_CONTENT) { 773print STDOUT "M 644 inline$title.mw\n"; 774 literal_data($content); 775if(%mediafile) { 776print STDOUT "M 644 inline$mediafile{title}\n"; 777 literal_data_raw($mediafile{content}); 778} 779print STDOUT "\n\n"; 780}else{ 781print STDOUT "D$title.mw\n"; 782} 783 784# mediawiki revision number in the git note 785if($full_import&&$n==1) { 786print STDOUT "reset refs/notes/$remotename/mediawiki\n"; 787} 788print STDOUT "commit refs/notes/$remotename/mediawiki\n"; 789print STDOUT "committer$author<$author\@$wiki_name> ",$date->epoch," +0000\n"; 790 literal_data("Note added by git-mediawiki during import"); 791if(!$full_import&&$n==1) { 792print STDOUT "from refs/notes/$remotename/mediawiki^0\n"; 793} 794print STDOUT "N inline :$n\n"; 795 literal_data("mediawiki_revision: ".$commit{mw_revision}); 796print STDOUT "\n\n"; 797} 798 799# parse a sequence of 800# <cmd> <arg1> 801# <cmd> <arg2> 802# \n 803# (like batch sequence of import and sequence of push statements) 804sub get_more_refs { 805my$cmd=shift; 806my@refs; 807while(1) { 808my$line= <STDIN>; 809if($line=~m/^$cmd (.*)$/) { 810push(@refs,$1); 811}elsif($lineeq"\n") { 812return@refs; 813}else{ 814die("Invalid command in a '$cmd' batch: ".$_); 815} 816} 817} 818 819sub mw_import { 820# multiple import commands can follow each other. 821my@refs= (shift, get_more_refs("import")); 822foreachmy$ref(@refs) { 823 mw_import_ref($ref); 824} 825print STDOUT "done\n"; 826} 827 828sub mw_import_ref { 829my$ref=shift; 830# The remote helper will call "import HEAD" and 831# "import refs/heads/master". 832# Since HEAD is a symbolic ref to master (by convention, 833# followed by the output of the command "list" that we gave), 834# we don't need to do anything in this case. 835if($refeq"HEAD") { 836return; 837} 838 839 mw_connect_maybe(); 840 841print STDERR "Searching revisions...\n"; 842my$last_local= get_last_local_revision(); 843my$fetch_from=$last_local+1; 844if($fetch_from==1) { 845print STDERR ", fetching from beginning.\n"; 846}else{ 847print STDERR ", fetching from here.\n"; 848} 849 850my$n=0; 851if($fetch_strategyeq"by_rev") { 852print STDERR "Fetching & writing export data by revs...\n"; 853$n= mw_import_ref_by_revs($fetch_from); 854}elsif($fetch_strategyeq"by_page") { 855print STDERR "Fetching & writing export data by pages...\n"; 856$n= mw_import_ref_by_pages($fetch_from); 857}else{ 858print STDERR "fatal: invalid fetch strategy\"$fetch_strategy\".\n"; 859print STDERR "Check your configuration variables remote.$remotename.fetchStrategy and mediawiki.fetchStrategy\n"; 860exit1; 861} 862 863if($fetch_from==1&&$n==0) { 864print STDERR "You appear to have cloned an empty MediaWiki.\n"; 865# Something has to be done remote-helper side. If nothing is done, an error is 866# thrown saying that HEAD is refering to unknown object 0000000000000000000 867# and the clone fails. 868} 869} 870 871sub mw_import_ref_by_pages { 872 873my$fetch_from=shift; 874my%pages_hash= get_mw_pages(); 875my@pages=values(%pages_hash); 876 877my($n,@revisions) = fetch_mw_revisions(\@pages,$fetch_from); 878 879@revisions=sort{$a->{revid} <=>$b->{revid}}@revisions; 880my@revision_ids=map$_->{revid},@revisions; 881 882return mw_import_revids($fetch_from, \@revision_ids, \%pages_hash); 883} 884 885sub mw_import_ref_by_revs { 886 887my$fetch_from=shift; 888my%pages_hash= get_mw_pages(); 889 890my$last_remote= get_last_global_remote_rev(); 891my@revision_ids=$fetch_from..$last_remote; 892return mw_import_revids($fetch_from, \@revision_ids, \%pages_hash); 893} 894 895# Import revisions given in second argument (array of integers). 896# Only pages appearing in the third argument (hash indexed by page titles) 897# will be imported. 898sub mw_import_revids { 899my$fetch_from=shift; 900my$revision_ids=shift; 901my$pages=shift; 902 903my$n=0; 904my$n_actual=0; 905my$last_timestamp=0;# Placeholer in case $rev->timestamp is undefined 906 907foreachmy$pagerevid(@$revision_ids) { 908# fetch the content of the pages 909my$query= { 910 action =>'query', 911 prop =>'revisions', 912 rvprop =>'content|timestamp|comment|user|ids', 913 revids =>$pagerevid, 914}; 915 916my$result=$mediawiki->api($query); 917 918if(!$result) { 919die"Failed to retrieve modified page for revision$pagerevid"; 920} 921 922if(!defined($result->{query}->{pages})) { 923die"Invalid revision$pagerevid."; 924} 925 926my@result_pages=values(%{$result->{query}->{pages}}); 927my$result_page=$result_pages[0]; 928my$rev=$result_pages[0]->{revisions}->[0]; 929 930# Count page even if we skip it, since we display 931# $n/$total and $total includes skipped pages. 932$n++; 933 934my$page_title=$result_page->{title}; 935 936if(!exists($pages->{$page_title})) { 937print STDERR "$n/",scalar(@$revision_ids), 938": Skipping revision #$rev->{revid} of$page_title\n"; 939next; 940} 941 942$n_actual++; 943 944my%commit; 945$commit{author} =$rev->{user} ||'Anonymous'; 946$commit{comment} =$rev->{comment} || EMPTY_MESSAGE; 947$commit{title} = mediawiki_smudge_filename($page_title); 948$commit{mw_revision} =$rev->{revid}; 949$commit{content} = mediawiki_smudge($rev->{'*'}); 950 951if(!defined($rev->{timestamp})) { 952$last_timestamp++; 953}else{ 954$last_timestamp=$rev->{timestamp}; 955} 956$commit{date} = DateTime::Format::ISO8601->parse_datetime($last_timestamp); 957 958# Differentiates classic pages and media files. 959my($namespace,$filename) =$page_title=~/^([^:]*):(.*)$/; 960my%mediafile; 961if($namespace&& get_mw_namespace_id($namespace) == get_mw_namespace_id("File")) { 962%mediafile= get_mw_mediafile_for_page_revision($filename,$rev->{timestamp}); 963} 964# If this is a revision of the media page for new version 965# of a file do one common commit for both file and media page. 966# Else do commit only for that page. 967print STDERR "$n/",scalar(@$revision_ids),": Revision #$rev->{revid} of$commit{title}\n"; 968 import_file_revision(\%commit, ($fetch_from==1),$n_actual, \%mediafile); 969} 970 971return$n_actual; 972} 973 974sub error_non_fast_forward { 975my$advice= run_git("config --bool advice.pushNonFastForward"); 976chomp($advice); 977if($advicene"false") { 978# Native git-push would show this after the summary. 979# We can't ask it to display it cleanly, so print it 980# ourselves before. 981print STDERR "To prevent you from losing history, non-fast-forward updates were rejected\n"; 982print STDERR "Merge the remote changes (e.g. 'git pull') before pushing again. See the\n"; 983print STDERR "'Note about fast-forwards' section of 'git push --help' for details.\n"; 984} 985print STDOUT "error$_[0]\"non-fast-forward\"\n"; 986return0; 987} 988 989sub mw_upload_file { 990my$complete_file_name=shift; 991my$new_sha1=shift; 992my$extension=shift; 993my$file_deleted=shift; 994my$summary=shift; 995my$newrevid; 996my$path="File:".$complete_file_name; 997my%hashFiles= get_allowed_file_extensions(); 998if(!exists($hashFiles{$extension})) { 999print STDERR "$complete_file_nameis not a permitted file on this wiki.\n";1000print STDERR "Check the configuration of file uploads in your mediawiki.\n";1001return$newrevid;1002}1003# Deleting and uploading a file requires a priviledged user1004if($file_deleted) {1005 mw_connect_maybe();1006my$query= {1007 action =>'delete',1008 title =>$path,1009 reason =>$summary1010};1011if(!$mediawiki->edit($query)) {1012print STDERR "Failed to delete file on remote wiki\n";1013print STDERR "Check your permissions on the remote site. Error code:\n";1014print STDERR $mediawiki->{error}->{code} .':'.$mediawiki->{error}->{details};1015exit1;1016}1017}else{1018# Don't let perl try to interpret file content as UTF-8 => use "raw"1019my$content= run_git("cat-file blob$new_sha1","raw");1020if($contentne"") {1021 mw_connect_maybe();1022$mediawiki->{config}->{upload_url} =1023"$url/index.php/Special:Upload";1024$mediawiki->edit({1025 action =>'upload',1026 filename =>$complete_file_name,1027 comment =>$summary,1028 file => [undef,1029$complete_file_name,1030 Content =>$content],1031 ignorewarnings =>1,1032}, {1033 skip_encoding =>11034} ) ||die$mediawiki->{error}->{code} .':'1035.$mediawiki->{error}->{details};1036my$last_file_page=$mediawiki->get_page({title =>$path});1037$newrevid=$last_file_page->{revid};1038print STDERR "Pushed file:$new_sha1-$complete_file_name.\n";1039}else{1040print STDERR "Empty file$complete_file_namenot pushed.\n";1041}1042}1043return$newrevid;1044}10451046sub mw_push_file {1047my$diff_info=shift;1048# $diff_info contains a string in this format:1049# 100644 100644 <sha1_of_blob_before_commit> <sha1_of_blob_now> <status>1050my@diff_info_split=split(/[ \t]/,$diff_info);10511052# Filename, including .mw extension1053my$complete_file_name=shift;1054# Commit message1055my$summary=shift;1056# MediaWiki revision number. Keep the previous one by default,1057# in case there's no edit to perform.1058my$oldrevid=shift;1059my$newrevid;10601061if($summaryeq EMPTY_MESSAGE) {1062$summary='';1063}10641065my$new_sha1=$diff_info_split[3];1066my$old_sha1=$diff_info_split[2];1067my$page_created= ($old_sha1eq NULL_SHA1);1068my$page_deleted= ($new_sha1eq NULL_SHA1);1069$complete_file_name= mediawiki_clean_filename($complete_file_name);10701071my($title,$extension) =$complete_file_name=~/^(.*)\.([^\.]*)$/;1072if(!defined($extension)) {1073$extension="";1074}1075if($extensioneq"mw") {1076my$ns= get_mw_namespace_id_for_page($complete_file_name);1077if($ns&&$ns== get_mw_namespace_id("File") && (!$export_media)) {1078print STDERR "Ignoring media file related page:$complete_file_name\n";1079return($oldrevid,"ok");1080}1081my$file_content;1082if($page_deleted) {1083# Deleting a page usually requires1084# special priviledges. A common1085# convention is to replace the page1086# with this content instead:1087$file_content= DELETED_CONTENT;1088}else{1089$file_content= run_git("cat-file blob$new_sha1");1090}10911092 mw_connect_maybe();10931094my$result=$mediawiki->edit( {1095 action =>'edit',1096 summary =>$summary,1097 title =>$title,1098 basetimestamp =>$basetimestamps{$oldrevid},1099 text => mediawiki_clean($file_content,$page_created),1100}, {1101 skip_encoding =>1# Helps with names with accentuated characters1102});1103if(!$result) {1104if($mediawiki->{error}->{code} ==3) {1105# edit conflicts, considered as non-fast-forward1106print STDERR 'Warning: Error '.1107$mediawiki->{error}->{code} .1108' from mediwiki: '.$mediawiki->{error}->{details} .1109".\n";1110return($oldrevid,"non-fast-forward");1111}else{1112# Other errors. Shouldn't happen => just die()1113die'Fatal: Error '.1114$mediawiki->{error}->{code} .1115' from mediwiki: '.$mediawiki->{error}->{details};1116}1117}1118$newrevid=$result->{edit}->{newrevid};1119print STDERR "Pushed file:$new_sha1-$title\n";1120}elsif($export_media) {1121$newrevid= mw_upload_file($complete_file_name,$new_sha1,1122$extension,$page_deleted,1123$summary);1124}else{1125print STDERR "Ignoring media file$title\n";1126}1127$newrevid= ($newrevidor$oldrevid);1128return($newrevid,"ok");1129}11301131sub mw_push {1132# multiple push statements can follow each other1133my@refsspecs= (shift, get_more_refs("push"));1134my$pushed;1135formy$refspec(@refsspecs) {1136my($force,$local,$remote) =$refspec=~/^(\+)?([^:]*):([^:]*)$/1137or die("Invalid refspec for push. Expected <src>:<dst> or +<src>:<dst>");1138if($force) {1139print STDERR "Warning: forced push not allowed on a MediaWiki.\n";1140}1141if($localeq"") {1142print STDERR "Cannot delete remote branch on a MediaWiki\n";1143print STDOUT "error$remotecannot delete\n";1144next;1145}1146if($remotene"refs/heads/master") {1147print STDERR "Only push to the branch 'master' is supported on a MediaWiki\n";1148print STDOUT "error$remoteonly master allowed\n";1149next;1150}1151if(mw_push_revision($local,$remote)) {1152$pushed=1;1153}1154}11551156# Notify Git that the push is done1157print STDOUT "\n";11581159if($pushed&&$dumb_push) {1160print STDERR "Just pushed some revisions to MediaWiki.\n";1161print STDERR "The pushed revisions now have to be re-imported, and your current branch\n";1162print STDERR "needs to be updated with these re-imported commits. You can do this with\n";1163print STDERR "\n";1164print STDERR " git pull --rebase\n";1165print STDERR "\n";1166}1167}11681169sub mw_push_revision {1170my$local=shift;1171my$remote=shift;# actually, this has to be "refs/heads/master" at this point.1172my$last_local_revid= get_last_local_revision();1173print STDERR ".\n";# Finish sentence started by get_last_local_revision()1174my$last_remote_revid= get_last_remote_revision();1175my$mw_revision=$last_remote_revid;11761177# Get sha1 of commit pointed by local HEAD1178my$HEAD_sha1= run_git("rev-parse$local2>/dev/null");chomp($HEAD_sha1);1179# Get sha1 of commit pointed by remotes/$remotename/master1180my$remoteorigin_sha1= run_git("rev-parse refs/remotes/$remotename/master2>/dev/null");1181chomp($remoteorigin_sha1);11821183if($last_local_revid>0&&1184$last_local_revid<$last_remote_revid) {1185return error_non_fast_forward($remote);1186}11871188if($HEAD_sha1eq$remoteorigin_sha1) {1189# nothing to push1190return0;1191}11921193# Get every commit in between HEAD and refs/remotes/origin/master,1194# including HEAD and refs/remotes/origin/master1195my@commit_pairs= ();1196if($last_local_revid>0) {1197my$parsed_sha1=$remoteorigin_sha1;1198# Find a path from last MediaWiki commit to pushed commit1199print STDERR "Computing path from local to remote ...\n";1200my@local_ancestry=split(/\n/, run_git("rev-list --boundary --parents$local^$parsed_sha1"));1201my%local_ancestry;1202foreachmy$line(@local_ancestry) {1203if(my($child,$parents) =$line=~m/^-?([a-f0-9]+) ([a-f0-9 ]+)/) {1204foreachmy$parent(split(' ',$parents)) {1205$local_ancestry{$parent} =$child;1206}1207}elsif(!$line=~m/^([a-f0-9]+)/) {1208die"Unexpected output from git rev-list:$line";1209}1210}1211while($parsed_sha1ne$HEAD_sha1) {1212my$child=$local_ancestry{$parsed_sha1};1213if(!$child) {1214printf STDERR "Cannot find a path in history from remote commit to last commit\n";1215return error_non_fast_forward($remote);1216}1217push(@commit_pairs, [$parsed_sha1,$child]);1218$parsed_sha1=$child;1219}1220}else{1221# No remote mediawiki revision. Export the whole1222# history (linearized with --first-parent)1223print STDERR "Warning: no common ancestor, pushing complete history\n";1224my$history= run_git("rev-list --first-parent --children$local");1225my@history=split('\n',$history);1226@history=@history[1..$#history];1227foreachmy$line(reverse@history) {1228my@commit_info_split=split(/ |\n/,$line);1229push(@commit_pairs, \@commit_info_split);1230}1231}12321233foreachmy$commit_info_split(@commit_pairs) {1234my$sha1_child= @{$commit_info_split}[0];1235my$sha1_commit= @{$commit_info_split}[1];1236my$diff_infos= run_git("diff-tree -r --raw -z$sha1_child$sha1_commit");1237# TODO: we could detect rename, and encode them with a #redirect on the wiki.1238# TODO: for now, it's just a delete+add1239my@diff_info_list=split(/\0/,$diff_infos);1240# Keep the subject line of the commit message as mediawiki comment for the revision1241my$commit_msg= run_git("log --no-walk --format=\"%s\"$sha1_commit");1242chomp($commit_msg);1243# Push every blob1244while(@diff_info_list) {1245my$status;1246# git diff-tree -z gives an output like1247# <metadata>\0<filename1>\01248# <metadata>\0<filename2>\01249# and we've split on \0.1250my$info=shift(@diff_info_list);1251my$file=shift(@diff_info_list);1252($mw_revision,$status) = mw_push_file($info,$file,$commit_msg,$mw_revision);1253if($statuseq"non-fast-forward") {1254# we may already have sent part of the1255# commit to MediaWiki, but it's too1256# late to cancel it. Stop the push in1257# the middle, but still give an1258# accurate error message.1259return error_non_fast_forward($remote);1260}1261if($statusne"ok") {1262die("Unknown error from mw_push_file()");1263}1264}1265unless($dumb_push) {1266 run_git("notes --ref=$remotename/mediawikiadd -m\"mediawiki_revision:$mw_revision\"$sha1_commit");1267 run_git("update-ref -m\"Git-MediaWiki push\"refs/mediawiki/$remotename/master$sha1_commit$sha1_child");1268}1269}12701271print STDOUT "ok$remote\n";1272return1;1273}12741275sub get_allowed_file_extensions {1276 mw_connect_maybe();12771278my$query= {1279 action =>'query',1280 meta =>'siteinfo',1281 siprop =>'fileextensions'1282};1283my$result=$mediawiki->api($query);1284my@file_extensions=map$_->{ext},@{$result->{query}->{fileextensions}};1285my%hashFile=map{$_=>1}@file_extensions;12861287return%hashFile;1288}12891290# In memory cache for MediaWiki namespace ids.1291my%namespace_id;12921293# Namespaces whose id is cached in the configuration file1294# (to avoid duplicates)1295my%cached_mw_namespace_id;12961297# Return MediaWiki id for a canonical namespace name.1298# Ex.: "File", "Project".1299sub get_mw_namespace_id {1300 mw_connect_maybe();1301my$name=shift;13021303if(!exists$namespace_id{$name}) {1304# Look at configuration file, if the record for that namespace is1305# already cached. Namespaces are stored in form:1306# "Name_of_namespace:Id_namespace", ex.: "File:6".1307my@temp=split(/[\n]/, run_git("config --get-all remote."1308.$remotename.".namespaceCache"));1309chomp(@temp);1310foreachmy$ns(@temp) {1311my($n,$id) =split(/:/,$ns);1312$namespace_id{$n} =$id;1313$cached_mw_namespace_id{$n} =1;1314}1315}13161317if(!exists$namespace_id{$name}) {1318print STDERR "Namespace$namenot found in cache, querying the wiki ...\n";1319# NS not found => get namespace id from MW and store it in1320# configuration file.1321my$query= {1322 action =>'query',1323 meta =>'siteinfo',1324 siprop =>'namespaces'1325};1326my$result=$mediawiki->api($query);13271328while(my($id,$ns) =each(%{$result->{query}->{namespaces}})) {1329if(defined($ns->{id}) &&defined($ns->{canonical})) {1330$namespace_id{$ns->{canonical}} =$ns->{id};1331if($ns->{'*'}) {1332# alias (e.g. french Fichier: as alias for canonical File:)1333$namespace_id{$ns->{'*'}} =$ns->{id};1334}1335}1336}1337}13381339my$id=$namespace_id{$name};13401341if(defined$id) {1342# Store explicitely requested namespaces on disk1343if(!exists$cached_mw_namespace_id{$name}) {1344 run_git("config --add remote.".$remotename1345.".namespaceCache\"".$name.":".$id."\"");1346$cached_mw_namespace_id{$name} =1;1347}1348return$id;1349}else{1350die"No such namespace$nameon MediaWiki.";1351}1352}13531354sub get_mw_namespace_id_for_page {1355if(my($namespace) =$_[0] =~/^([^:]*):/) {1356return get_mw_namespace_id($namespace);1357}else{1358return;1359}1360}