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