1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
|
<?php
/**
* Copyright (C) 2011-2020 Wikimedia Foundation and others.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
namespace MediaWiki\Rest\Handler;
use Composer\Semver\Semver;
use InvalidArgumentException;
use Liuggio\StatsdClient\Factory\StatsdDataFactoryInterface;
use LogicException;
use MediaWiki\Content\WikitextContent;
use MediaWiki\Context\RequestContext;
use MediaWiki\Language\LanguageCode;
use MediaWiki\Logger\LoggerFactory;
use MediaWiki\MainConfigNames;
use MediaWiki\MediaWikiServices;
use MediaWiki\Page\PageIdentity;
use MediaWiki\Page\ProperPageIdentity;
use MediaWiki\Parser\ParserOutput;
use MediaWiki\Parser\Parsoid\Config\SiteConfig;
use MediaWiki\Registration\ExtensionRegistry;
use MediaWiki\Rest\Handler;
use MediaWiki\Rest\Handler\Helper\HtmlInputTransformHelper;
use MediaWiki\Rest\Handler\Helper\HtmlOutputRendererHelper;
use MediaWiki\Rest\Handler\Helper\ParsoidFormatHelper;
use MediaWiki\Rest\HttpException;
use MediaWiki\Rest\LocalizedHttpException;
use MediaWiki\Rest\Response;
use MediaWiki\Revision\MutableRevisionRecord;
use MediaWiki\Revision\RevisionAccessException;
use MediaWiki\Revision\RevisionLookup;
use MediaWiki\Revision\SlotRecord;
use MediaWiki\Revision\SuppressedDataException;
use MediaWiki\Title\MalformedTitleException;
use MediaWiki\Title\Title;
use MediaWiki\WikiMap\WikiMap;
use MobileContext;
use Wikimedia\Http\HttpAcceptParser;
use Wikimedia\Message\DataMessageValue;
use Wikimedia\Message\MessageValue;
use Wikimedia\Parsoid\Config\DataAccess;
use Wikimedia\Parsoid\Config\PageConfig;
use Wikimedia\Parsoid\Config\PageConfigFactory;
use Wikimedia\Parsoid\Core\ClientError;
use Wikimedia\Parsoid\Core\PageBundle;
use Wikimedia\Parsoid\Core\ResourceLimitExceededException;
use Wikimedia\Parsoid\DOM\Document;
use Wikimedia\Parsoid\Parsoid;
use Wikimedia\Parsoid\Utils\ContentUtils;
use Wikimedia\Parsoid\Utils\DOMCompat;
use Wikimedia\Parsoid\Utils\DOMUtils;
use Wikimedia\Parsoid\Utils\Timing;
// TODO logging, timeouts(?), CORS
// TODO content negotiation (routes.js routes.acceptable)
// TODO handle MaxConcurrentCallsError (pool counter?)
/**
* Base class for Parsoid handlers.
* @internal For use by the Parsoid extension
*/
abstract class ParsoidHandler extends Handler {
private RevisionLookup $revisionLookup;
protected SiteConfig $siteConfig;
protected PageConfigFactory $pageConfigFactory;
protected DataAccess $dataAccess;
/** @var ExtensionRegistry */
protected $extensionRegistry;
/** @var ?StatsdDataFactoryInterface A statistics aggregator */
protected $metrics;
/** @var array */
private $requestAttributes;
/**
* @return static
*/
public static function factory(): ParsoidHandler {
$services = MediaWikiServices::getInstance();
// @phan-suppress-next-line PhanTypeInstantiateAbstractStatic
return new static(
$services->getRevisionLookup(),
$services->getParsoidSiteConfig(),
$services->getParsoidPageConfigFactory(),
$services->getParsoidDataAccess()
);
}
public function __construct(
RevisionLookup $revisionLookup,
SiteConfig $siteConfig,
PageConfigFactory $pageConfigFactory,
DataAccess $dataAccess
) {
$this->revisionLookup = $revisionLookup;
$this->siteConfig = $siteConfig;
$this->pageConfigFactory = $pageConfigFactory;
$this->dataAccess = $dataAccess;
$this->extensionRegistry = ExtensionRegistry::getInstance();
$this->metrics = $siteConfig->metrics();
}
public function getSupportedRequestTypes(): array {
return array_merge( parent::getSupportedRequestTypes(), [
'application/x-www-form-urlencoded',
'multipart/form-data'
] );
}
/**
* Verify that the {domain} path parameter matches the actual domain.
* @todo Remove this when we no longer need to support the {domain}
* parameter with backwards compatibility with the parsoid
* extension.
* @param string $domain Domain name parameter to validate
*/
protected function assertDomainIsCorrect( $domain ): void {
// We are cutting some corners here (IDN, non-ASCII casing)
// since domain name support is provisional.
// TODO use a proper validator instead
$server = RequestContext::getMain()->getConfig()->get( MainConfigNames::Server );
$expectedDomain = parse_url( $server, PHP_URL_HOST );
if ( !$expectedDomain ) {
throw new LogicException( 'Cannot parse $wgServer' );
}
if ( strcasecmp( $expectedDomain, $domain ) === 0 ) {
return;
}
// TODO: This should really go away! It's only acceptable because
// this entire method is going to be removed once we no longer
// need the parsoid extension endpoints with the {domain} parameter.
if ( $this->extensionRegistry->isLoaded( 'MobileFrontend' ) ) {
// @phan-suppress-next-line PhanUndeclaredClassMethod
$mobileServer = MobileContext::singleton()->getMobileUrl( $server );
$expectedMobileDomain = parse_url( $mobileServer, PHP_URL_HOST );
if ( $expectedMobileDomain && strcasecmp( $expectedMobileDomain, $domain ) === 0 ) {
return;
}
}
$msg = new DataMessageValue(
'mwparsoid-invalid-domain',
[],
'invalid-domain',
[ 'expected' => $expectedDomain, 'actual' => $domain, ]
);
throw new LocalizedHttpException( $msg, 400, [
'error' => 'parameter-validation-failed',
'name' => 'domain',
'value' => $domain,
'failureCode' => $msg->getCode(),
'failureData' => $msg->getData(),
] );
}
/**
* Get the parsed body by content-type
*
* @return array
*/
protected function getParsedBody(): array {
$request = $this->getRequest();
[ $contentType ] = explode( ';', $request->getHeader( 'Content-Type' )[0] ?? '', 2 );
switch ( $contentType ) {
case 'application/x-www-form-urlencoded':
case 'multipart/form-data':
return $request->getPostParams();
case 'application/json':
$json = json_decode( $request->getBody()->getContents(), true );
if ( !is_array( $json ) ) {
throw new LocalizedHttpException(
new MessageValue( "rest-json-body-parse-error", [ 'not a valid JSON object' ] ), 400 );
}
return $json;
default:
throw new LocalizedHttpException(
new MessageValue( "rest-unsupported-content-type", [ $contentType ?? '(null)' ] ),
415
);
}
}
/**
* Rough equivalent of req.local from Parsoid-JS.
* FIXME most of these should be replaced with more native ways of handling the request.
* @return array
*/
protected function &getRequestAttributes(): array {
if ( $this->requestAttributes ) {
return $this->requestAttributes;
}
$request = $this->getRequest();
$body = ( $request->getMethod() === 'POST' ) ? $this->getParsedBody() : [];
$opts = array_merge( $body, array_intersect_key( $request->getPathParams(),
[ 'from' => true, 'format' => true ] ) );
'@phan-var array<string,array|bool|string> $opts'; // @var array<string,array|bool|string> $opts
$contentLanguage = $request->getHeaderLine( 'Content-Language' ) ?: null;
if ( $contentLanguage ) {
$contentLanguage = LanguageCode::normalizeNonstandardCodeAndWarn(
$contentLanguage
);
}
$attribs = [
'pageName' => $request->getPathParam( 'title' ) ?? '',
'oldid' => $request->getPathParam( 'revision' ),
// "body_only" flag to return just the body (instead of the entire HTML doc)
// We would like to deprecate use of this flag: T181657
'body_only' => $request->getQueryParams()['body_only'] ?? $body['body_only'] ?? null,
'errorEnc' => ParsoidFormatHelper::ERROR_ENCODING[$opts['format']] ?? 'plain',
'iwp' => WikiMap::getCurrentWikiId(), // PORT-FIXME verify
'offsetType' => $body['offsetType']
?? $request->getQueryParams()['offsetType']
// Lint requests should return UCS2 offsets by default
?? ( $opts['format'] === ParsoidFormatHelper::FORMAT_LINT ? 'ucs2' : 'byte' ),
'pagelanguage' => $contentLanguage,
];
// For use in getHtmlOutputRendererHelper
$opts['stash'] = $request->getQueryParams()['stash'] ?? false;
if ( $request->getMethod() === 'POST' ) {
if ( isset( $opts['original']['revid'] ) ) {
$attribs['oldid'] = $opts['original']['revid'];
}
if ( isset( $opts['original']['title'] ) ) {
$attribs['pageName'] = $opts['original']['title'];
}
}
if ( $attribs['oldid'] !== null ) {
if ( $attribs['oldid'] === '' ) {
$attribs['oldid'] = null;
} else {
$attribs['oldid'] = (int)$attribs['oldid'];
}
}
// For use in getHtmlOutputRendererHelper
$opts['accept-language'] = $request->getHeaderLine( 'Accept-Language' ) ?: null;
$acceptLanguage = null;
if ( $opts['accept-language'] !== null ) {
$acceptLanguage = LanguageCode::normalizeNonstandardCodeAndWarn(
$opts['accept-language']
);
}
// Init pageName if oldid is provided and is a valid revision
if ( ( $attribs['pageName'] === '' ) && $attribs['oldid'] ) {
$rev = $this->revisionLookup->getRevisionById( $attribs['oldid'] );
if ( $rev ) {
$attribs['pageName'] = $rev->getPage()->getDBkey();
}
}
$attribs['envOptions'] = [
// We use `prefix` but ought to use `domain` (T206764)
'prefix' => $attribs['iwp'],
// For the legacy "domain" path parameter used by the endpoints exposed
// by the parsoid extension. Will be null for core endpoints.
'domain' => $request->getPathParam( 'domain' ),
'pageName' => $attribs['pageName'],
'cookie' => $request->getHeaderLine( 'Cookie' ),
'reqId' => $request->getHeaderLine( 'X-Request-Id' ),
'userAgent' => $request->getHeaderLine( 'User-Agent' ),
'htmlVariantLanguage' => $acceptLanguage,
// Semver::satisfies checks below expect a valid outputContentVersion value.
// Better to set it here instead of adding the default value at every check.
'outputContentVersion' => Parsoid::defaultHTMLVersion(),
];
# Convert language codes in $opts['updates']['variant'] if present
$sourceVariant = $opts['updates']['variant']['source'] ?? null;
if ( $sourceVariant ) {
$sourceVariant = LanguageCode::normalizeNonstandardCodeAndWarn(
$sourceVariant
);
$opts['updates']['variant']['source'] = $sourceVariant;
}
$targetVariant = $opts['updates']['variant']['target'] ?? null;
if ( $targetVariant ) {
$targetVariant = LanguageCode::normalizeNonstandardCodeAndWarn(
$targetVariant
);
$opts['updates']['variant']['target'] = $targetVariant;
}
if ( isset( $opts['wikitext']['headers']['content-language'] ) ) {
$contentLanguage = $opts['wikitext']['headers']['content-language'];
$contentLanguage = LanguageCode::normalizeNonstandardCodeAndWarn(
$contentLanguage
);
$opts['wikitext']['headers']['content-language'] = $contentLanguage;
}
if ( isset( $opts['original']['wikitext']['headers']['content-language'] ) ) {
$contentLanguage = $opts['original']['wikitext']['headers']['content-language'];
$contentLanguage = LanguageCode::normalizeNonstandardCodeAndWarn(
$contentLanguage
);
$opts['original']['wikitext']['headers']['content-language'] = $contentLanguage;
}
$attribs['opts'] = $opts;
// TODO: Remove assertDomainIsCorrect() once we no longer need to support the {domain}
// parameter for the endpoints exposed by the parsoid extension.
if ( $attribs['envOptions']['domain'] !== null ) {
$this->assertDomainIsCorrect( $attribs['envOptions']['domain'] );
}
$this->requestAttributes = $attribs;
return $this->requestAttributes;
}
/**
* @param array $attribs
* @param ?string $source
* @param PageIdentity $page
* @param ?int $revId
*
* @return HtmlOutputRendererHelper
*/
private function getHtmlOutputRendererHelper(
array $attribs,
?string $source,
PageIdentity $page,
?int $revId
): HtmlOutputRendererHelper {
$services = MediaWikiServices::getInstance();
// Request lenient rev handling
$lenientRevHandling = true;
$authority = $this->getAuthority();
$params = [];
$helper = $services->getPageRestHelperFactory()->newHtmlOutputRendererHelper(
$page, $params, $authority, $revId, $lenientRevHandling
);
// XXX: should default to the page's content model?
$model = $attribs['opts']['contentmodel']
?? ( $attribs['envOptions']['contentmodel'] ?? CONTENT_MODEL_WIKITEXT );
if ( $source !== null ) {
$helper->setContentSource( $source, $model );
}
if ( isset( $attribs['opts']['stash'] ) ) {
$helper->setStashingEnabled( $attribs['opts']['stash'] );
}
if ( isset( $attribs['envOptions']['outputContentVersion'] ) ) {
$helper->setOutputProfileVersion( $attribs['envOptions']['outputContentVersion'] );
}
if ( isset( $attribs['pagelanguage'] ) ) {
$helper->setPageLanguage( $attribs['pagelanguage'] );
}
if ( isset( $attribs['opts']['accept-language'] ) ) {
$helper->setVariantConversionLanguage( $attribs['opts']['accept-language'] );
}
return $helper;
}
/**
* @param array $attribs
* @param string $html
* @param PageIdentity $page
*
* @return HtmlInputTransformHelper
*/
protected function getHtmlInputTransformHelper(
array $attribs,
string $html,
PageIdentity $page
): HtmlInputTransformHelper {
$services = MediaWikiServices::getInstance();
$parameters = $attribs['opts'] + $attribs;
$body = $attribs['opts'];
$body['html'] = $html;
$helper = $services->getPageRestHelperFactory()->newHtmlInputTransformHelper(
$attribs['envOptions'] + [
'offsetType' => $attribs['offsetType'],
],
$page,
$body,
$parameters
);
$helper->setMetrics( $this->siteConfig->prefixedStatsFactory() );
return $helper;
}
/**
* FIXME: Combine with ParsoidFormatHelper::parseContentTypeHeader
*/
private const NEW_SPEC =
'#^https://www.mediawiki.org/wiki/Specs/(HTML|pagebundle)/(\d+\.\d+\.\d+)$#D';
/**
* This method checks if we support the requested content formats
* As a side-effect, it updates $attribs to set outputContentVersion
* that Parsoid should generate based on request headers.
*
* @param array &$attribs Request attributes from getRequestAttributes()
* @return bool
*/
protected function acceptable( array &$attribs ): bool {
$request = $this->getRequest();
$format = $attribs['opts']['format'];
if ( $format === ParsoidFormatHelper::FORMAT_WIKITEXT ) {
return true;
}
$acceptHeader = $request->getHeader( 'Accept' );
if ( !$acceptHeader ) {
return true;
}
$parser = new HttpAcceptParser();
$acceptableTypes = $parser->parseAccept( $acceptHeader[0] ); // FIXME: Multiple headers valid?
if ( !$acceptableTypes ) {
return true;
}
// `acceptableTypes` is already sorted by quality.
foreach ( $acceptableTypes as $t ) {
$type = "{$t['type']}/{$t['subtype']}";
$profile = $t['params']['profile'] ?? null;
if (
( $format === ParsoidFormatHelper::FORMAT_HTML && $type === 'text/html' ) ||
( $format === ParsoidFormatHelper::FORMAT_PAGEBUNDLE && $type === 'application/json' )
) {
if ( $profile ) {
preg_match( self::NEW_SPEC, $profile, $matches );
if ( $matches && strtolower( $matches[1] ) === $format ) {
$contentVersion = Parsoid::resolveContentVersion( $matches[2] );
if ( $contentVersion ) {
// $attribs mutated here!
$attribs['envOptions']['outputContentVersion'] = $contentVersion;
return true;
} else {
continue;
}
} else {
continue;
}
} else {
return true;
}
} elseif (
( $type === '*/*' ) ||
( $format === ParsoidFormatHelper::FORMAT_HTML && $type === 'text/*' )
) {
return true;
}
}
return false;
}
/**
* Try to create a PageConfig object. If we get an exception (because content
* may be missing or inaccessible), throw an appropriate HTTP response object
* for callers to handle.
*
* @param array $attribs
* @param ?string $wikitextOverride
* Custom wikitext to use instead of the real content of the page.
* @param bool $html2WtMode
* @return PageConfig
* @throws HttpException
*/
protected function tryToCreatePageConfig(
array $attribs, ?string $wikitextOverride = null, bool $html2WtMode = false
): PageConfig {
$revId = $attribs['oldid'];
$pagelanguageOverride = $attribs['pagelanguage'];
$title = $attribs['pageName'];
$title = ( $title !== '' ) ? Title::newFromText( $title ) : Title::newMainPage();
if ( !$title ) {
// TODO use proper validation
throw new LogicException( 'Title not found!' );
}
$user = RequestContext::getMain()->getUser();
if ( $wikitextOverride === null ) {
$revisionRecord = null;
} else {
// Create a mutable revision record point to the same revision
// and set to the desired wikitext.
$revisionRecord = new MutableRevisionRecord( $title );
// Don't set id to $revId if we have $wikitextOverride
// A revision corresponds to specific wikitext, which $wikitextOverride
// might not be.
$revisionRecord->setId( 0 );
$revisionRecord->setSlot(
SlotRecord::newUnsaved(
SlotRecord::MAIN,
new WikitextContent( $wikitextOverride )
)
);
}
$hasOldId = ( $revId !== null );
$ensureAccessibleContent = !$html2WtMode || $hasOldId;
try {
// Note: Parsoid by design isn't supposed to use the user
// context right now, and all user state is expected to be
// introduced as a post-parse transform. So although we pass a
// User here, it only currently affects the output in obscure
// corner cases; see PageConfigFactory::create() for more.
// @phan-suppress-next-line PhanUndeclaredMethod method defined in subtype
$pageConfig = $this->pageConfigFactory->create(
$title, $user, $revisionRecord ?? $revId, null, $pagelanguageOverride,
$ensureAccessibleContent
);
} catch ( SuppressedDataException $e ) {
throw new LocalizedHttpException(
new MessageValue( "rest-permission-denied-revision", [ $e->getMessage() ] ), 403
);
} catch ( RevisionAccessException $e ) {
throw new LocalizedHttpException(
new MessageValue( "rest-specified-revision-unavailable", [ $e->getMessage() ] ), 404
);
}
// All good!
return $pageConfig;
}
/**
* Try to create a PageIdentity object.
* If no page is specified in the request, this will return the wiki's main page.
* If an invalid page is requested, this throws an appropriate HTTPException.
*
* @param array $attribs
* @return PageIdentity
* @throws HttpException
*/
protected function tryToCreatePageIdentity( array $attribs ): PageIdentity {
if ( $attribs['pageName'] === '' ) {
return Title::newMainPage();
}
// XXX: Should be injected, but the Parsoid extension relies on the
// constructor signature. Also, ParsoidHandler should go away soon anyway.
$pageStore = MediaWikiServices::getInstance()->getPageStore();
$page = $pageStore->getPageByText( $attribs['pageName'] );
if ( !$page ) {
throw new LocalizedHttpException(
new MessageValue( "rest-invalid-title", [ 'pageName' ] ), 400
);
}
return $page;
}
/**
* Get the path for the transform endpoint. May be overwritten to override the path.
*
* This is done in the parsoid extension, for backwards compatibility
* with the old endpoint URLs.
*
* @stable to override
*
* @param string $format The format the endpoint is expected to return.
*
* @return string
*/
protected function getTransformEndpoint( string $format = ParsoidFormatHelper::FORMAT_HTML ): string {
return '/coredev/v0/transform/{from}/to/{format}/{title}/{revision}';
}
/**
* Get the path for the page content endpoint. May be overwritten to override the path.
*
* This is done in the parsoid extension, for backwards compatibility
* with the old endpoint URLs.
*
* @stable to override
*
* @param string $format The format the endpoint is expected to return.
*
* @return string
*/
protected function getPageContentEndpoint( string $format = ParsoidFormatHelper::FORMAT_HTML ): string {
if ( $format !== ParsoidFormatHelper::FORMAT_HTML ) {
throw new InvalidArgumentException( 'Unsupported page content format: ' . $format );
}
return '/v1/page/{title}/html';
}
/**
* Get the path for the page content endpoint. May be overwritten to override the path.
*
* This is done in the parsoid extension, for backwards compatibility
* with the old endpoint URLs.
*
* @stable to override
*
* @param string $format The format the endpoint is expected to return.
*
* @return string
*/
protected function getRevisionContentEndpoint( string $format = ParsoidFormatHelper::FORMAT_HTML ): string {
if ( $format !== ParsoidFormatHelper::FORMAT_HTML ) {
throw new InvalidArgumentException( 'Unsupported revision content format: ' . $format );
}
return '/v1/revision/{revision}/html';
}
private function wtLint(
PageConfig $pageConfig, array $attribs, ?array $linterOverrides = []
) {
$envOptions = $attribs['envOptions'] + [
'linterOverrides' => $linterOverrides,
'offsetType' => $attribs['offsetType'],
];
try {
$parsoid = $this->newParsoid();
$parserOutput = new ParserOutput();
return $parsoid->wikitext2lint( $pageConfig, $envOptions, $parserOutput );
} catch ( ClientError $e ) {
throw new LocalizedHttpException( new MessageValue( "rest-parsoid-error", [ $e->getMessage() ] ), 400 );
} catch ( ResourceLimitExceededException $e ) {
throw new LocalizedHttpException(
new MessageValue( "rest-parsoid-resource-exceeded", [ $e->getMessage() ] ), 413
);
}
}
/**
* Wikitext -> HTML helper.
* Spec'd in https://phabricator.wikimedia.org/T75955 and the API tests.
*
* @param PageConfig $pageConfig
* @param array $attribs Request attributes from getRequestAttributes()
* @param ?string $wikitext Wikitext to transform (or null to use the
* page specified in the request attributes).
*
* @return Response
*/
protected function wt2html(
PageConfig $pageConfig, array $attribs, ?string $wikitext = null
) {
$request = $this->getRequest();
$opts = $attribs['opts'];
$format = $opts['format'];
$oldid = $attribs['oldid'];
$stash = $opts['stash'] ?? false;
if ( $format === ParsoidFormatHelper::FORMAT_LINT ) {
$linterOverrides = [];
if ( $this->extensionRegistry->isLoaded( 'Linter' ) ) { // T360809
$disabled = [];
$services = MediaWikiServices::getInstance();
$linterCategories = $services->getMainConfig()->get( 'LinterCategories' );
foreach ( $linterCategories as $name => $cat ) {
if ( $cat['priority'] === 'none' ) {
$disabled[] = $name;
}
}
$linterOverrides['disabled'] = $disabled;
}
$lints = $this->wtLint( $pageConfig, $attribs, $linterOverrides );
$response = $this->getResponseFactory()->createJson( $lints );
return $response;
}
// TODO: This method should take a PageIdentity + revId,
// to reduce the usage of PageConfig in MW core.
$helper = $this->getHtmlOutputRendererHelper(
$attribs,
$wikitext,
$this->pageConfigToPageIdentity( $pageConfig ),
// Id will be 0 if we have $wikitext but that isn't valid
// to call $helper->setRevision with. In any case, the revision
// will be reset when $helper->setContent is called with $wikitext.
// Ideally, the revision would be pass through here instead of
// the id and wikitext.
$pageConfig->getRevisionId() ?: null
);
$needsPageBundle = ( $format === ParsoidFormatHelper::FORMAT_PAGEBUNDLE );
if ( $attribs['body_only'] ) {
$helper->setFlavor( 'fragment' );
} elseif ( !$needsPageBundle ) {
// Inline data-parsoid. This will happen when no special params are set.
$helper->setFlavor( 'edit' );
}
if ( $wikitext === null && $oldid !== null ) {
$mstr = 'pageWithOldid';
} else {
$mstr = 'wt';
}
$parseTiming = Timing::start();
if ( $needsPageBundle ) {
$pb = $helper->getPageBundle();
// Handle custom offset requests as a pb2pb transform
if ( $attribs['offsetType'] !== 'byte' ) {
$parsoid = $this->newParsoid();
$pb = $parsoid->pb2pb(
$pageConfig,
'convertoffsets',
$pb,
[
'inputOffsetType' => 'byte',
'outputOffsetType' => $attribs['offsetType']
]
);
}
$response = $this->getResponseFactory()->createJson( $pb->responseData() );
$helper->putHeaders( $response, false );
ParsoidFormatHelper::setContentType(
$response,
ParsoidFormatHelper::FORMAT_PAGEBUNDLE,
$pb->version
);
} else {
$out = $helper->getHtml();
// TODO: offsetType conversion isn't supported right now for non-pagebundle endpoints
// Once the OutputTransform framework lands, we might revisit this.
$response = $this->getResponseFactory()->create();
$response->getBody()->write( $out->getRawText() );
$helper->putHeaders( $response, true );
// Emit an ETag only if stashing is enabled. It's not reliably useful otherwise.
if ( $stash ) {
$eTag = $helper->getETag();
if ( $eTag ) {
$response->setHeader( 'ETag', $eTag );
}
}
}
// XXX: For pagebundle requests, this can be somewhat inflated
// because of pagebundle json-encoding overheads
$outSize = $response->getBody()->getSize();
$parseTime = $parseTiming->end();
// Ignore slow parse metrics for non-oldid parses
if ( $mstr === 'pageWithOldid' ) {
if ( $parseTime > 3000 ) {
LoggerFactory::getInstance( 'slow-parsoid' )
->info( 'Parsing {title} was slow, took {time} seconds', [
'time' => number_format( $parseTime / 1000, 2 ),
'title' => Title::newFromLinkTarget( $pageConfig->getLinkTarget() )->getPrefixedText(),
] );
}
if ( $parseTime > 10 && $outSize > 100 ) {
// * Don't bother with this metric for really small parse times
// p99 for initialization time is ~7ms according to grafana.
// So, 10ms ensures that startup overheads don't skew the metrics
// * For body_only=false requests, <head> section isn't generated
// and if the output is small, per-request overheads can skew
// the timePerKB metrics.
// NOTE: This is slightly misleading since there are fixed costs
// for generating output like the <head> section and should be factored in,
// but this is good enough for now as a useful first degree of approxmation.
$timePerKB = $parseTime * 1024 / $outSize;
if ( $timePerKB > 500 ) {
// At 100ms/KB, even a 100KB page which isn't that large will take 10s.
// So, we probably want to shoot for a threshold under 100ms.
// But, let's start with 500ms+ outliers first and see what we uncover.
LoggerFactory::getInstance( 'slow-parsoid' )
->info( 'Parsing {title} was slow, timePerKB took {timePerKB} ms, total: {time} seconds', [
'time' => number_format( $parseTime / 1000, 2 ),
'timePerKB' => number_format( $timePerKB, 1 ),
'title' => Title::newFromLinkTarget( $pageConfig->getLinkTarget() )->getPrefixedText(),
] );
}
}
}
if ( $wikitext !== null ) {
// Don't cache requests when wt is set in case somebody uses
// GET for wikitext parsing
// XXX: can we just refuse to do wikitext parsing in a GET request?
$response->setHeader( 'Cache-Control', 'private,no-cache,s-maxage=0' );
} elseif ( $oldid !== null ) {
// XXX: can this go away? Parsoid's PageContent class doesn't expose supressed revision content.
if ( $request->getHeaderLine( 'Cookie' ) ||
$request->getHeaderLine( 'Authorization' ) ) {
// Don't cache requests with a session.
$response->setHeader( 'Cache-Control', 'private,no-cache,s-maxage=0' );
}
}
return $response;
}
protected function newParsoid(): Parsoid {
return new Parsoid( $this->siteConfig, $this->dataAccess );
}
protected function parseHTML( string $html, bool $validateXMLNames = false ): Document {
return DOMUtils::parseHTML( $html, $validateXMLNames );
}
/**
* @param PageConfig|PageIdentity $page
* @param array $attribs Attributes gotten from requests
* @param string $html Original HTML
*
* @return Response
* @throws HttpException
*/
protected function html2wt(
$page, array $attribs, string $html
) {
if ( $page instanceof PageConfig ) {
// TODO: Deprecate passing a PageConfig.
// Ideally, callers would use HtmlToContentTransform directly.
$page = Title::newFromLinkTarget( $page->getLinkTarget() );
}
try {
$transform = $this->getHtmlInputTransformHelper( $attribs, $html, $page );
$response = $this->getResponseFactory()->create();
$transform->putContent( $response );
return $response;
} catch ( ClientError $e ) {
throw new LocalizedHttpException( new MessageValue( "rest-parsoid-error", [ $e->getMessage() ] ), 400 );
}
}
/**
* Pagebundle -> pagebundle helper.
*
* @param array<string,array|string> $attribs
* @return Response
* @throws HttpException
*/
protected function pb2pb( array $attribs ) {
$opts = $attribs['opts'];
$revision = $opts['previous'] ?? $opts['original'] ?? null;
if ( !isset( $revision['html'] ) ) {
throw new LocalizedHttpException( new MessageValue( "rest-missing-revision-html" ), 400 );
}
$vOriginal = ParsoidFormatHelper::parseContentTypeHeader(
$revision['html']['headers']['content-type'] ?? '' );
if ( $vOriginal === null ) {
throw new LocalizedHttpException( new MessageValue( "rest-missing-revision-html-content-type" ), 400 );
}
$attribs['envOptions']['inputContentVersion'] = $vOriginal;
'@phan-var array<string,array|string> $attribs'; // @var array<string,array|string> $attribs
$this->metrics->increment(
'pb2pb.original.version.' . $attribs['envOptions']['inputContentVersion']
);
if ( !empty( $opts['updates'] ) ) {
// FIXME: Handling missing revisions uniformly for all update types
// is not probably the right thing to do but probably okay for now.
// This might need revisiting as we add newer types.
$pageConfig = $this->tryToCreatePageConfig( $attribs, null, true );
// If we're only updating parts of the original version, it should
// satisfy the requested content version, since we'll be returning
// that same one.
// FIXME: Since this endpoint applies the acceptable middleware,
// `getOutputContentVersion` is not what's been passed in, but what
// can be produced. Maybe that should be selectively applied so
// that we can update older versions where it makes sense?
// Uncommenting below implies that we can only update the latest
// version, since carrot semantics is applied in both directions.
// if ( !Semver::satisfies(
// $attribs['envOptions']['inputContentVersion'],
// "^{$attribs['envOptions']['outputContentVersion']}"
// ) ) {
// throw new HttpException(
// 'We do not know how to do this conversion.', 415
// );
// }
if ( !empty( $opts['updates']['redlinks'] ) ) {
// Q(arlolra): Should redlinks be more complex than a bool?
// See gwicke's proposal at T114413#2240381
return $this->updateRedLinks( $pageConfig, $attribs, $revision );
} elseif ( isset( $opts['updates']['variant'] ) ) {
return $this->languageConversion( $pageConfig, $attribs, $revision );
} else {
throw new LocalizedHttpException( new MessageValue( "rest-unknown-parsoid-transformation" ), 400 );
}
}
// TODO(arlolra): subbu has some sage advice in T114413#2365456 that
// we should probably be more explicit about the pb2pb conversion
// requested rather than this increasingly complex fallback logic.
$downgrade = Parsoid::findDowngrade(
$attribs['envOptions']['inputContentVersion'],
$attribs['envOptions']['outputContentVersion']
);
if ( $downgrade ) {
$pb = new PageBundle(
$revision['html']['body'],
$revision['data-parsoid']['body'] ?? null,
$revision['data-mw']['body'] ?? null
);
$this->validatePb( $pb, $attribs['envOptions']['inputContentVersion'] );
Parsoid::downgrade( $downgrade, $pb );
if ( !empty( $attribs['body_only'] ) ) {
$doc = $this->parseHTML( $pb->html );
$body = DOMCompat::getBody( $doc );
$pb->html = ContentUtils::toXML( $body, [ 'innerXML' => true ] );
}
$response = $this->getResponseFactory()->createJson( $pb->responseData() );
ParsoidFormatHelper::setContentType(
$response, ParsoidFormatHelper::FORMAT_PAGEBUNDLE, $pb->version
);
return $response;
// Ensure we only reuse from semantically similar content versions.
} elseif ( Semver::satisfies( $attribs['envOptions']['outputContentVersion'],
'^' . $attribs['envOptions']['inputContentVersion'] ) ) {
$pageConfig = $this->tryToCreatePageConfig( $attribs );
return $this->wt2html( $pageConfig, $attribs );
} else {
throw new LocalizedHttpException( new MessageValue( "rest-unsupported-profile-conversion" ), 415 );
}
}
/**
* Update red links on a document.
*
* @param PageConfig $pageConfig
* @param array $attribs
* @param array $revision
* @return Response
*/
protected function updateRedLinks(
PageConfig $pageConfig, array $attribs, array $revision
) {
$parsoid = $this->newParsoid();
$pb = new PageBundle(
$revision['html']['body'],
$revision['data-parsoid']['body'] ?? null,
$revision['data-mw']['body'] ?? null,
$attribs['envOptions']['inputContentVersion'],
$revision['html']['headers'] ?? null,
$revision['contentmodel'] ?? null
);
$out = $parsoid->pb2pb( $pageConfig, 'redlinks', $pb, [] );
$this->validatePb( $out, $attribs['envOptions']['inputContentVersion'] );
$response = $this->getResponseFactory()->createJson( $out->responseData() );
ParsoidFormatHelper::setContentType(
$response, ParsoidFormatHelper::FORMAT_PAGEBUNDLE, $out->version
);
return $response;
}
/**
* Do variant conversion on a document.
*
* @param PageConfig $pageConfig
* @param array $attribs
* @param array $revision
* @return Response
* @throws HttpException
*/
protected function languageConversion(
PageConfig $pageConfig, array $attribs, array $revision
) {
$opts = $attribs['opts'];
$target = $opts['updates']['variant']['target'] ??
$attribs['envOptions']['htmlVariantLanguage'];
$source = $opts['updates']['variant']['source'] ?? null;
if ( !$target ) {
throw new LocalizedHttpException( new MessageValue( "rest-target-variant-required" ), 400 );
}
$pageIdentity = $this->tryToCreatePageIdentity( $attribs );
$pb = new PageBundle(
$revision['html']['body'],
$revision['data-parsoid']['body'] ?? null,
$revision['data-mw']['body'] ?? null,
$attribs['envOptions']['inputContentVersion'],
$revision['html']['headers'] ?? null,
$revision['contentmodel'] ?? null
);
// XXX: DI should inject HtmlTransformFactory
$languageVariantConverter = MediaWikiServices::getInstance()
->getHtmlTransformFactory()
->getLanguageVariantConverter( $pageIdentity );
$languageVariantConverter->setPageConfig( $pageConfig );
$httpContentLanguage = $attribs['pagelanguage' ] ?? null;
if ( $httpContentLanguage ) {
$languageVariantConverter->setPageLanguageOverride( $httpContentLanguage );
}
try {
$out = $languageVariantConverter->convertPageBundleVariant( $pb, $target, $source );
} catch ( InvalidArgumentException $e ) {
throw new LocalizedHttpException(
new MessageValue( "rest-unsupported-language-conversion", [ $source ?? '(unspecified)', $target ] ),
400,
[ 'reason' => $e->getMessage() ]
);
}
$response = $this->getResponseFactory()->createJson( $out->responseData() );
ParsoidFormatHelper::setContentType(
$response, ParsoidFormatHelper::FORMAT_PAGEBUNDLE, $out->version
);
return $response;
}
/** @inheritDoc */
abstract public function execute(): Response;
/**
* Validate a PageBundle against the given contentVersion, and throw
* an HttpException if it does not match.
* @param PageBundle $pb
* @param string $contentVersion
* @throws HttpException
*/
private function validatePb( PageBundle $pb, string $contentVersion ): void {
$errorMessage = '';
if ( !$pb->validate( $contentVersion, $errorMessage ) ) {
throw new LocalizedHttpException(
new MessageValue( "rest-page-bundle-validation-error", [ $errorMessage ] ),
400
);
}
}
/**
* @param PageConfig $page
*
* @return ProperPageIdentity
* @throws HttpException
*/
private function pageConfigToPageIdentity( PageConfig $page ): ProperPageIdentity {
$services = MediaWikiServices::getInstance();
$title = $page->getLinkTarget();
try {
$page = $services->getPageStore()->getPageForLink( $title );
} catch ( MalformedTitleException | InvalidArgumentException $e ) {
// Note that even some well-formed links are still invalid
// parameters for getPageForLink(), e.g. interwiki links or special pages.
throw new HttpException(
"Bad title: $title", # uses LinkTarget::__toString()
400
);
}
return $page;
}
}
|