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
|
<?php
namespace MediaWiki\Rest\Handler\Helper;
use MediaWiki\ChangeTags\ChangeTagsStore;
use MediaWiki\Config\ServiceOptions;
use MediaWiki\Content\TextContent;
use MediaWiki\Content\WikitextContent;
use MediaWiki\MainConfigNames;
use MediaWiki\Message\Message;
use MediaWiki\Page\ExistingPageRecord;
use MediaWiki\Page\PageIdentity;
use MediaWiki\Page\PageLookup;
use MediaWiki\Permissions\Authority;
use MediaWiki\Rest\Handler;
use MediaWiki\Rest\LocalizedHttpException;
use MediaWiki\Rest\ResponseInterface;
use MediaWiki\Revision\MutableRevisionRecord;
use MediaWiki\Revision\RevisionAccessException;
use MediaWiki\Revision\RevisionLookup;
use MediaWiki\Revision\RevisionRecord;
use MediaWiki\Revision\SlotRecord;
use MediaWiki\Revision\SuppressedDataException;
use MediaWiki\Title\Title;
use MediaWiki\Title\TitleFactory;
use MediaWiki\Title\TitleFormatter;
use Wikimedia\Message\MessageValue;
use Wikimedia\ParamValidator\ParamValidator;
use Wikimedia\Rdbms\IConnectionProvider;
/**
* @internal for use by core REST infrastructure
*/
class PageContentHelper {
/**
* The maximum cache duration for page content.
*
* If this is set to a value higher than about 60 seconds, active purging
* will have to be employed to make sure clients do not receive overly stale
* content. This is especially important to avoid distributing vandalized
* content for too long.
*
* Active purging can be enabled by adding the relevant URLs to
* HTMLCacheUpdater. See T365630 for more discussion.
*/
private const MAX_AGE_200 = 5;
/**
* @internal
*/
public const CONSTRUCTOR_OPTIONS = [
MainConfigNames::RightsUrl,
MainConfigNames::RightsText,
];
protected ServiceOptions $options;
protected RevisionLookup $revisionLookup;
protected TitleFormatter $titleFormatter;
protected PageLookup $pageLookup;
private TitleFactory $titleFactory;
private IConnectionProvider $connectionProvider;
private ChangeTagsStore $changeTagStore;
/** @var Authority|null */
protected $authority = null;
/** @var string[] */
protected $parameters = null;
/** @var RevisionRecord|false|null */
protected $targetRevision = false;
/** @var ExistingPageRecord|false|null */
protected $pageRecord = false;
/** @var PageIdentity|false|null */
private $pageIdentity = false;
public function __construct(
ServiceOptions $options,
RevisionLookup $revisionLookup,
TitleFormatter $titleFormatter,
PageLookup $pageLookup,
TitleFactory $titleFactory,
IConnectionProvider $connectionProvider,
ChangeTagsStore $changeTagStore
) {
$this->options = $options;
$this->revisionLookup = $revisionLookup;
$this->titleFormatter = $titleFormatter;
$this->pageLookup = $pageLookup;
$this->titleFactory = $titleFactory;
$this->connectionProvider = $connectionProvider;
$this->changeTagStore = $changeTagStore;
}
/**
* @param Authority $authority
* @param string[] $parameters validated parameters
*/
public function init( Authority $authority, array $parameters ) {
$this->authority = $authority;
$this->parameters = $parameters;
}
/**
* @return string|null title text or null if unable to retrieve title
*/
public function getTitleText(): ?string {
return $this->parameters['title'] ?? null;
}
/**
* @return ExistingPageRecord|null
*/
public function getPage(): ?ExistingPageRecord {
if ( $this->pageRecord === false ) {
$titleText = $this->getTitleText();
if ( $titleText === null ) {
return null;
}
$this->pageRecord = $this->pageLookup->getExistingPageByText( $titleText );
}
return $this->pageRecord;
}
public function getPageIdentity(): ?PageIdentity {
if ( $this->pageIdentity === false ) {
$this->pageIdentity = $this->getPage();
}
if ( $this->pageIdentity === null ) {
$titleText = $this->getTitleText();
if ( $titleText === null ) {
return null;
}
$this->pageIdentity = $this->pageLookup->getPageByText( $titleText );
}
return $this->pageIdentity;
}
/**
* Returns the target revision. No permission checks are applied.
*
* @return RevisionRecord|null latest revision or null if unable to retrieve revision
*/
public function getTargetRevision(): ?RevisionRecord {
if ( $this->targetRevision === false ) {
$page = $this->getPage();
if ( $page ) {
$this->targetRevision = $this->revisionLookup->getRevisionByTitle( $page );
} else {
$this->targetRevision = null;
}
}
return $this->targetRevision;
}
// Default to main slot
public function getRole(): string {
return SlotRecord::MAIN;
}
/**
* @return TextContent
* @throws LocalizedHttpException slot content is not TextContent or RevisionRecord/Slot is inaccessible
*/
public function getContent(): TextContent {
$revision = $this->getTargetRevision();
if ( !$revision ) {
$titleText = $this->getTitleText() ?? '';
throw new LocalizedHttpException(
MessageValue::new( 'rest-no-revision' )->plaintextParams( $titleText ),
404
);
}
$slotRole = $this->getRole();
try {
$content = $revision
->getSlot( $slotRole, RevisionRecord::FOR_THIS_USER, $this->authority )
->getContent()
->convert( CONTENT_MODEL_TEXT );
if ( !( $content instanceof TextContent ) ) {
throw new LocalizedHttpException( MessageValue::new( 'rest-page-source-type-error' ), 400 );
}
} catch ( SuppressedDataException $e ) {
throw new LocalizedHttpException(
MessageValue::new( 'rest-permission-denied-revision' )->numParams( $revision->getId() ),
403
);
} catch ( RevisionAccessException $e ) {
throw new LocalizedHttpException(
MessageValue::new( 'rest-nonexistent-revision' )->numParams( $revision->getId() ),
404
);
}
return $content;
}
/**
* @return bool
*/
public function isAccessible(): bool {
$page = $this->getPageIdentity();
return $page && $this->authority->probablyCan( 'read', $page );
}
/**
* Returns an ETag representing a page's source. The ETag assumes a page's source has changed
* if the latest revision of a page has been made private, un-readable for another reason,
* or a newer revision exists.
* @return string|null
*/
public function getETag(): ?string {
$revision = $this->getTargetRevision();
$revId = $revision ? $revision->getId() : 'e0';
$isAccessible = $this->isAccessible();
$accessibleTag = $isAccessible ? 'a1' : 'a0';
$revisionTag = $revId . $accessibleTag;
return '"' . sha1( $revisionTag ) . '"';
}
/**
* @return string|null
*/
public function getLastModified(): ?string {
if ( !$this->isAccessible() ) {
return null;
}
$revision = $this->getTargetRevision();
if ( $revision ) {
return $revision->getTimestamp();
}
return null;
}
/**
* Checks whether content exists. Permission checks are not considered.
*
* @return bool
*/
public function hasContent(): bool {
return $this->useDefaultSystemMessage() || (bool)$this->getPage();
}
/**
* @return array
*/
public function constructMetadata(): array {
$revision = $this->getRevisionRecordForMetadata();
$page = $revision->getPage();
return [
'id' => $page->getId(),
'key' => $this->titleFormatter->getPrefixedDBkey( $page ),
'title' => $this->titleFormatter->getPrefixedText( $page ),
'latest' => [
'id' => $revision->getId(),
'timestamp' => wfTimestampOrNull( TS_ISO_8601, $revision->getTimestamp() )
],
'content_model' => $revision->getSlot( SlotRecord::MAIN, RevisionRecord::RAW )
->getModel(),
'license' => [
'url' => $this->options->get( MainConfigNames::RightsUrl ),
'title' => $this->options->get( MainConfigNames::RightsText )
],
];
}
/**
* @return array
*/
public function constructRestbaseCompatibleMetadata(): array {
$revision = $this->getRevisionRecordForMetadata();
$page = $revision->getPage();
$title = $this->titleFactory->newFromPageIdentity( $page );
$tags = $this->changeTagStore->getTags(
$this->connectionProvider->getReplicaDatabase(),
null, $revision->getId(), null
);
$restrictions = [];
if ( $revision->isDeleted( RevisionRecord::DELETED_COMMENT ) ) {
$restrictions[] = 'commenthidden';
}
if ( $revision->isDeleted( RevisionRecord::DELETED_USER ) ) {
$restrictions[] = 'userhidden';
}
$publicUser = $revision->getUser();
$publicComment = $revision->getComment();
return [
'title' => $title->getPrefixedDBkey(),
'page_id' => $page->getId(),
'rev' => $revision->getId(),
// We could look up the tid from a ParserOutput, but it's expensive,
// and the tid can't be used for anything anymore anyway.
// Don't use an empty string though, that may break routing when the
// value is used as a path parameter.
'tid' => 'DUMMY',
'namespace' => $page->getNamespace(),
'user_id' => $revision->getUser( RevisionRecord::RAW )->getId(),
'user_text' => $publicUser ? $publicUser->getName() : null,
'comment' => $publicComment ? $publicComment->text : null,
'timestamp' => wfTimestampOrNull( TS_ISO_8601, $revision->getTimestamp() ),
'tags' => $tags,
'restrictions' => $restrictions,
'page_language' => $title->getPageLanguage()->getCode(),
'redirect' => $title->isRedirect()
];
}
/**
* @return array[]
*/
public function getParamSettings(): array {
return [
'title' => [
Handler::PARAM_SOURCE => 'path',
ParamValidator::PARAM_TYPE => 'string',
ParamValidator::PARAM_REQUIRED => true,
],
'redirect' => [
Handler::PARAM_SOURCE => 'query',
ParamValidator::PARAM_TYPE => [ 'no' ],
ParamValidator::PARAM_REQUIRED => false,
]
];
}
/**
* Sets the 'Cache-Control' header no more then provided $expiry.
* @param ResponseInterface $response
* @param int|null $expiry
*/
public function setCacheControl( ResponseInterface $response, ?int $expiry = null ) {
if ( $expiry === null ) {
$maxAge = self::MAX_AGE_200;
} else {
$maxAge = min( self::MAX_AGE_200, $expiry );
}
$response->setHeader(
'Cache-Control',
'max-age=' . $maxAge
);
}
/**
* If the page is a system message page. When the content gets
* overridden to create an actual page, this method returns false.
*
* @return bool
*/
public function useDefaultSystemMessage(): bool {
return $this->getDefaultSystemMessage() !== null && $this->getPage() === null;
}
/**
* @return Message|null
*/
public function getDefaultSystemMessage(): ?Message {
$title = Title::newFromText( $this->getTitleText() );
return $title ? $title->getDefaultSystemMessage() : null;
}
/**
* @throws LocalizedHttpException if access is not allowed
*/
public function checkAccessPermission() {
$titleText = $this->getTitleText() ?? '';
// @phan-suppress-next-line PhanTypeMismatchArgumentNullable Validated by hasContent
if ( !$this->isAccessible() || !$this->authority->authorizeRead( 'read', $this->getPageIdentity() ) ) {
throw new LocalizedHttpException(
MessageValue::new( 'rest-permission-denied-title' )->plaintextParams( $titleText ),
403
);
}
}
/**
* @throws LocalizedHttpException if no content is available
*/
public function checkHasContent() {
$titleText = $this->getTitleText() ?? '';
$page = $this->getPageIdentity();
if ( !$page ) {
throw new LocalizedHttpException(
MessageValue::new( 'rest-invalid-title' )->plaintextParams( $titleText ),
404
);
}
if ( !$this->hasContent() ) {
// needs to check if it's possibly a variant title
throw new LocalizedHttpException(
MessageValue::new( 'rest-nonexistent-title' )->plaintextParams( $titleText ),
404
);
}
$revision = $this->getTargetRevision();
if ( !$revision && !$this->useDefaultSystemMessage() ) {
throw new LocalizedHttpException(
MessageValue::new( 'rest-no-revision' )->plaintextParams( $titleText ),
404
);
}
}
/**
* @throws LocalizedHttpException if the content is not accessible
*/
public function checkAccess() {
$this->checkHasContent(); // Status 404: Not Found
$this->checkAccessPermission(); // Status 403: Forbidden
}
/**
* @return MutableRevisionRecord|RevisionRecord|null
*/
private function getRevisionRecordForMetadata() {
if ( $this->useDefaultSystemMessage() ) {
$title = Title::newFromText( $this->getTitleText() );
$content = new WikitextContent( $title->getDefaultMessageText() );
$revision = new MutableRevisionRecord( $title );
$revision->setPageId( 0 );
$revision->setId( 0 );
$revision->setContent(
SlotRecord::MAIN,
$content
);
} else {
$revision = $this->getTargetRevision();
}
return $revision;
}
}
|