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