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