Debian Codegraph @

extensions/DiscussionTools/includes/ApiDiscussionToolsPageInfo.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Extension\DiscussionTools;
4
5 use MediaWiki\Api\ApiBase;
6 use MediaWiki\Api\ApiMain;
7 use MediaWiki\Api\ApiUsageException;
8 use MediaWiki\Extension\DiscussionTools\Hooks\HookUtils;
9 use MediaWiki\Extension\DiscussionTools\ThreadItem\CommentItem;
10 use MediaWiki\Extension\DiscussionTools\ThreadItem\ContentCommentItem;
11 use MediaWiki\Extension\DiscussionTools\ThreadItem\ContentHeadingItem;
12 use MediaWiki\Extension\DiscussionTools\ThreadItem\ContentThreadItem;
13 use MediaWiki\Extension\VisualEditor\VisualEditorParsoidClientFactory;
14 use MediaWiki\Revision\RevisionLookup;
15 use MediaWiki\Revision\RevisionRecord;
16 use MediaWiki\Title\Title;
17 use Wikimedia\ParamValidator\ParamValidator;
18 use Wikimedia\Parsoid\Core\ResourceLimitExceededException;
19 use Wikimedia\Parsoid\DOM\Element;
20 use Wikimedia\Parsoid\DOM\Text;
21 use Wikimedia\Parsoid\Utils\DOMUtils;
22
23 class ApiDiscussionToolsPageInfo extends ApiBase {
24
25 private CommentParser $commentParser;
26 private VisualEditorParsoidClientFactory $parsoidClientFactory;
27 private RevisionLookup $revisionLookup;
28
29 public function __construct(
30 ApiMain $main,
31 string $name,
32 VisualEditorParsoidClientFactory $parsoidClientFactory,
33 CommentParser $commentParser,
34 RevisionLookup $revisionLookup
35 ) {
36 parent::__construct( $main, $name );
37 $this->parsoidClientFactory = $parsoidClientFactory;
38 $this->commentParser = $commentParser;
39 $this->revisionLookup = $revisionLookup;
40 }
41
42 /**
43 * @inheritDoc
44 * @throws ApiUsageException
45 */
46 public function execute() {
47 $params = $this->extractRequestParams();
48 $this->requireAtLeastOneParameter( $params, 'page', 'oldid' );
49 $threadItemSet = $this->getThreadItemSet( $params );
50
51 $result = [];
52 $prop = array_fill_keys( $params['prop'], true );
53
54 if ( isset( $prop['transcludedfrom'] ) ) {
55 $result['transcludedfrom'] = static::getTranscludedFrom( $threadItemSet );
56 }
57
58 if ( isset( $prop['threaditemshtml'] ) ) {
59 $excludeSignatures = $params['excludesignatures'];
60 $result['threaditemshtml'] = static::getThreadItemsHtml( $threadItemSet, $excludeSignatures );
61 }
62
63 $this->getResult()->addValue( null, $this->getModuleName(), $result );
64 }
65
66 /**
67 * Get the thread item set for the specified revision
68 *
69 * @throws ApiUsageException
70 * @param array $params
71 * @return ContentThreadItemSet
72 */
73 private function getThreadItemSet( $params ) {
74 if ( isset( $params['page'] ) ) {
75 $title = Title::newFromText( $params['page'] );
76 if ( !$title ) {
77 throw ApiUsageException::newWithMessage(
78 $this,
79 [ 'apierror-invalidtitle', wfEscapeWikiText( $params['page'] ) ]
80 );
81 }
82 }
83
84 if ( isset( $params['oldid'] ) ) {
85 $revision = $this->revisionLookup->getRevisionById( $params['oldid'] );
86 if ( !$revision ) {
87 throw ApiUsageException::newWithMessage(
88 $this,
89 [ 'apierror-nosuchrevid', $params['oldid'] ]
90 );
91 }
92 } else {
93 $title = Title::newFromText( $params['page'] );
94 if ( !$title ) {
95 throw ApiUsageException::newWithMessage(
96 $this,
97 [ 'apierror-invalidtitle', wfEscapeWikiText( $params['page'] ) ]
98 );
99 }
100 $revision = $this->revisionLookup->getRevisionByTitle( $title );
101 if ( !$revision ) {
102 throw ApiUsageException::newWithMessage(
103 $this,
104 [ 'apierror-missingrev-title', wfEscapeWikiText( $title->getPrefixedText() ) ],
105 'nosuchrevid'
106 );
107 }
108 }
109 $title = Title::castFromPageIdentity( $revision->getPage() );
110
111 if ( !$title || !HookUtils::isAvailableForTitle( $title ) ) {
112 // T325477: don't parse non-discussion pages
113 return new ContentThreadItemSet;
114 }
115
116 $this->checkTitleUserPermissions( $title, 'read' );
117
118 if ( !$revision->audienceCan( RevisionRecord::DELETED_TEXT, RevisionRecord::FOR_PUBLIC ) ) {
119 $this->dieWithError( [ 'apierror-missingcontent-revid', $revision->getId() ], 'missingcontent' );
120 }
121
122 try {
123 return HookUtils::parseRevisionParsoidHtml( $revision, __METHOD__ );
124 } catch ( ResourceLimitExceededException $e ) {
125 $this->dieWithException( $e );
126 }
127 }
128
129 /**
130 * Get transcluded=from data for a ContentThreadItemSet
131 */
132 private static function getTranscludedFrom( ContentThreadItemSet $threadItemSet ): array {
133 $threadItems = $threadItemSet->getThreadItems();
134 $transcludedFrom = [];
135 foreach ( $threadItems as $threadItem ) {
136 $from = $threadItem->getTranscludedFrom();
137
138 // Key by IDs and names. This assumes that they can never conflict.
139
140 $transcludedFrom[ $threadItem->getId() ] = $from;
141
142 $name = $threadItem->getName();
143 if ( isset( $transcludedFrom[ $name ] ) && $transcludedFrom[ $name ] !== $from ) {
144 // Two or more items with the same name, transcluded from different pages.
145 // Consider them both to be transcluded from unknown source.
146 $transcludedFrom[ $name ] = true;
147 } else {
148 $transcludedFrom[ $name ] = $from;
149 }
150 }
151
152 return $transcludedFrom;
153 }
154
155 /**
156 * Get thread items HTML for a ContentThreadItemSet
157 */
158 private static function getThreadItemsHtml( ContentThreadItemSet $threadItemSet, bool $excludeSignatures ): array {
159 // This function assumes that the start of the ranges associated with
160 // HeadingItems are going to be at the start of their associated
161 // heading node (`<h2>^heading</h2>`), i.e. in the position generated
162 // by getHeadlineNode.
163 $threads = $threadItemSet->getThreads();
164 if ( count( $threads ) > 0 && !$threads[0]->isPlaceholderHeading() ) {
165 $firstHeading = $threads[0];
166 $firstRange = $firstHeading->getRange();
167 $rootNode = $firstHeading->getRootNode();
168 // We need a placeholder if there's content between the beginning
169 // of rootnode and the start of firstHeading. An ancestor of the
170 // first heading with a previousSibling is evidence that there's
171 // probably content. If this is giving false positives we could
172 // perhaps use linearWalkBackwards and DomUtils::isContentNode.
173 $closest = CommentUtils::closestElementWithSibling( $firstRange->startContainer, 'previous' );
174 if ( $closest && !$rootNode->isSameNode( $closest ) ) {
175 $range = new ImmutableRange( $rootNode, 0, $rootNode, 0 );
176 $fakeHeading = new ContentHeadingItem( $range, false, null );
177 $fakeHeading->setRootNode( $rootNode );
178 $fakeHeading->setName( 'h-' );
179 $fakeHeading->setId( 'h-' );
180 array_unshift( $threads, $fakeHeading );
181 }
182 }
183 $output = array_map( static function ( ContentThreadItem $item ) use ( $excludeSignatures ) {
184 return $item->jsonSerialize( true, static function ( array &$array, ContentThreadItem $item ) use (
185 $excludeSignatures
186 ) {
187 if ( $item instanceof ContentCommentItem && $excludeSignatures ) {
188 $array['html'] = $item->getBodyHTML( true );
189 } else {
190 $array['html'] = $item->getHTML();
191 }
192
193 if ( $item instanceof CommentItem ) {
194 // We want timestamps to be consistently formatted in API
195 // output instead of varying based on comment time
196 // (T315400). The format used here is equivalent to 'Y-m-d\TH:i:s\Z'
197 $array['timestamp'] = wfTimestamp( TS_ISO_8601, $item->getTimestamp()->getTimestamp() );
198 }
199 } );
200 }, $threads );
201 foreach ( $threads as $index => $item ) {
202 // need to loop over this to fix up empty sections, because we
203 // need context that's not available inside the array map
204 if ( $item instanceof ContentHeadingItem && count( $item->getReplies() ) === 0 ) {
205 // If there are no replies we want to include whatever's
206 // inside this section as "othercontent". We create a range
207 // that's between the end of this section's heading and the
208 // start of next section's heading. The main difficulty here
209 // is avoiding catching any of the heading's tags within the
210 // range.
211 $nextItem = $threads[ $index + 1 ] ?? false;
212 $startRange = $item->getRange();
213 if ( $item->isPlaceholderHeading() ) {
214 // Placeholders don't have any heading to avoid
215 $startNode = $startRange->startContainer;
216 $startOffset = $startRange->startOffset;
217 } else {
218 $startNode = CommentUtils::closestElementWithSibling( $startRange->endContainer, 'next' );
219 if ( !$startNode ) {
220 // If there's no siblings here this means we're on a
221 // heading that is the final heading on a page and
222 // which has no contents at all. We can skip the rest.
223 continue;
224 } else {
225 $startNode = $startNode->nextSibling;
226 $startOffset = 0;
227 }
228 }
229
230 if ( !$startNode ) {
231 $startNode = $startRange->endContainer;
232 $startOffset = $startRange->endOffset;
233 }
234
235 if ( $nextItem ) {
236 $nextStart = $nextItem->getRange()->startContainer;
237 $endContainer = CommentUtils::closestElementWithSibling( $nextStart, 'previous' );
238 $endContainer = $endContainer && $endContainer->previousSibling ?
239 $endContainer->previousSibling : $nextStart;
240 $endOffset = CommentUtils::childIndexOf( $endContainer );
241 if ( $endContainer instanceof Text ) {
242 // This probably means that there's a wrapping node
243 // e.g. <div>foo\n==heading==\nbar</div>
244 $endOffset += $endContainer->length;
245 } elseif ( $endContainer instanceof Element && $endContainer->tagName === 'section' ) {
246 // if we're in sections, make sure we're selecting the
247 // end of the previous section
248 $endOffset = $endContainer->childNodes->length;
249 } elseif ( $endContainer->parentNode ) {
250 $endContainer = $endContainer->parentNode;
251 }
252 $betweenRange = new ImmutableRange(
253 $startNode, $startOffset,
254 $endContainer ?: $nextStart, $endOffset
255 );
256 } else {
257 // This is the last section, so we want to go to the end of the rootnode
258 $betweenRange = new ImmutableRange(
259 $startNode, $startOffset,
260 $item->getRootNode(), $item->getRootNode()->childNodes->length
261 );
262 }
263 $fragment = $betweenRange->cloneContents();
264 CommentModifier::unwrapFragment( $fragment );
265 $otherContent = trim( DOMUtils::getFragmentInnerHTML( $fragment ) );
266 if ( $otherContent ) {
267 // A completely empty section will result in otherContent
268 // being an empty string. In this case we should just not include it.
269 $output[$index]['othercontent'] = $otherContent;
270 }
271
272 }
273 }
274 return $output;
275 }
276
277 /**
278 * @inheritDoc
279 */
280 public function getAllowedParams() {
281 return [
282 'page' => [
283 ApiBase::PARAM_HELP_MSG => 'apihelp-visualeditoredit-param-page',
284 ],
285 'oldid' => [
286 ParamValidator::PARAM_TYPE => 'integer',
287 ],
288 'prop' => [
289 ParamValidator::PARAM_DEFAULT => 'transcludedfrom',
290 ParamValidator::PARAM_ISMULTI => true,
291 ParamValidator::PARAM_TYPE => [
292 'transcludedfrom',
293 'threaditemshtml'
294 ],
295 ApiBase::PARAM_HELP_MSG_PER_VALUE => [],
296 ],
297 'excludesignatures' => false,
298 ];
299 }
300
301 /**
302 * @inheritDoc
303 */
304 public function needsToken() {
305 return false;
306 }
307
308 /**
309 * @inheritDoc
310 */
311 public function isInternal() {
312 return true;
313 }
314
315 /**
316 * @inheritDoc
317 */
318 public function isWriteMode() {
319 return false;
320 }
321 }