aboutsummaryrefslogtreecommitdiffstats
path: root/includes/api/ApiFeedContributions.php
blob: fccffe2f3ac7a10f86719c87b802d138088515b6 (plain) (blame)
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
<?php
/**
 * Copyright © 2011 Sam Reed
 *
 * 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.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 */

use MediaWiki\Api\ApiHookRunner;
use MediaWiki\Cache\LinkBatchFactory;
use MediaWiki\CommentFormatter\CommentFormatter;
use MediaWiki\Feed\FeedItem;
use MediaWiki\HookContainer\HookContainer;
use MediaWiki\Linker\LinkRenderer;
use MediaWiki\MainConfigNames;
use MediaWiki\Pager\ContribsPager;
use MediaWiki\ParamValidator\TypeDef\UserDef;
use MediaWiki\Revision\RevisionAccessException;
use MediaWiki\Revision\RevisionRecord;
use MediaWiki\Revision\RevisionStore;
use MediaWiki\Revision\SlotRecord;
use MediaWiki\SpecialPage\SpecialPage;
use MediaWiki\Title\NamespaceInfo;
use MediaWiki\Title\Title;
use MediaWiki\Title\TitleParser;
use MediaWiki\User\ExternalUserNames;
use MediaWiki\User\UserFactory;
use MediaWiki\User\UserRigorOptions;
use Wikimedia\ParamValidator\ParamValidator;
use Wikimedia\Rdbms\IConnectionProvider;

/**
 * @ingroup API
 */
class ApiFeedContributions extends ApiBase {

	private RevisionStore $revisionStore;
	private TitleParser $titleParser;
	private LinkRenderer $linkRenderer;
	private LinkBatchFactory $linkBatchFactory;
	private HookContainer $hookContainer;
	private IConnectionProvider $dbProvider;
	private NamespaceInfo $namespaceInfo;
	private UserFactory $userFactory;
	private CommentFormatter $commentFormatter;
	private ApiHookRunner $hookRunner;

	/**
	 * @param ApiMain $main
	 * @param string $action
	 * @param RevisionStore $revisionStore
	 * @param TitleParser $titleParser
	 * @param LinkRenderer $linkRenderer
	 * @param LinkBatchFactory $linkBatchFactory
	 * @param HookContainer $hookContainer
	 * @param IConnectionProvider $dbProvider
	 * @param NamespaceInfo $namespaceInfo
	 * @param UserFactory $userFactory
	 * @param CommentFormatter $commentFormatter
	 */
	public function __construct(
		ApiMain $main,
		$action,
		RevisionStore $revisionStore,
		TitleParser $titleParser,
		LinkRenderer $linkRenderer,
		LinkBatchFactory $linkBatchFactory,
		HookContainer $hookContainer,
		IConnectionProvider $dbProvider,
		NamespaceInfo $namespaceInfo,
		UserFactory $userFactory,
		CommentFormatter $commentFormatter
	) {
		parent::__construct( $main, $action );
		$this->revisionStore = $revisionStore;
		$this->titleParser = $titleParser;
		$this->linkRenderer = $linkRenderer;
		$this->linkBatchFactory = $linkBatchFactory;
		$this->hookContainer = $hookContainer;
		$this->dbProvider = $dbProvider;
		$this->namespaceInfo = $namespaceInfo;
		$this->userFactory = $userFactory;
		$this->commentFormatter = $commentFormatter;

		$this->hookRunner = new ApiHookRunner( $hookContainer );
	}

	/**
	 * This module uses a custom feed wrapper printer.
	 *
	 * @return ApiFormatFeedWrapper
	 */
	public function getCustomPrinter() {
		return new ApiFormatFeedWrapper( $this->getMain() );
	}

	public function execute() {
		$params = $this->extractRequestParams();

		$config = $this->getConfig();
		if ( !$config->get( MainConfigNames::Feed ) ) {
			$this->dieWithError( 'feed-unavailable' );
		}

		$feedClasses = $config->get( MainConfigNames::FeedClasses );
		if ( !isset( $feedClasses[$params['feedformat']] ) ) {
			$this->dieWithError( 'feed-invalid' );
		}

		if ( $params['showsizediff'] && $this->getConfig()->get( MainConfigNames::MiserMode ) ) {
			$this->dieWithError( 'apierror-sizediffdisabled' );
		}

		$msg = $this->msg( 'Contributions' )->inContentLanguage()->text();
		$feedTitle = $config->get( MainConfigNames::Sitename ) . ' - ' . $msg .
			' [' . $config->get( MainConfigNames::LanguageCode ) . ']';

		$target = $params['user'];
		if ( ExternalUserNames::isExternal( $target ) ) {
			// Interwiki names make invalid titles, so put the target in the query instead.
			$feedUrl = SpecialPage::getTitleFor( 'Contributions' )->getFullURL( [ 'target' => $target ] );
		} else {
			$feedUrl = SpecialPage::getTitleFor( 'Contributions', $target )->getFullURL();
		}

		$feed = new $feedClasses[$params['feedformat']] (
			$feedTitle,
			htmlspecialchars( $msg ),
			$feedUrl
		);

		// Convert year/month parameters to end parameter
		$params['start'] = '';
		$params['end'] = '';
		$params = ContribsPager::processDateFilter( $params );

		$targetUser = $this->userFactory->newFromName( $target, UserRigorOptions::RIGOR_NONE );

		$pager = new ContribsPager(
			$this->getContext(), [
				'target' => $target,
				'namespace' => $params['namespace'],
				'start' => $params['start'],
				'end' => $params['end'],
				'tagFilter' => $params['tagfilter'],
				'deletedOnly' => $params['deletedonly'],
				'topOnly' => $params['toponly'],
				'newOnly' => $params['newonly'],
				'hideMinor' => $params['hideminor'],
				'showSizeDiff' => $params['showsizediff'],
			],
			$this->linkRenderer,
			$this->linkBatchFactory,
			$this->hookContainer,
			$this->dbProvider,
			$this->revisionStore,
			$this->namespaceInfo,
			$targetUser,
			$this->commentFormatter
		);

		$feedLimit = $this->getConfig()->get( MainConfigNames::FeedLimit );
		if ( $pager->getLimit() > $feedLimit ) {
			$pager->setLimit( $feedLimit );
		}

		$feedItems = [];
		if ( $pager->getNumRows() > 0 ) {
			$count = 0;
			$limit = $pager->getLimit();
			foreach ( $pager->mResult as $row ) {
				// ContribsPager selects one more row for navigation, skip that row
				if ( ++$count > $limit ) {
					break;
				}
				$item = $this->feedItem( $row );
				if ( $item !== null ) {
					$feedItems[] = $item;
				}
			}
		}

		ApiFormatFeedWrapper::setResult( $this->getResult(), $feed, $feedItems );
	}

	protected function feedItem( $row ) {
		// This hook is the api contributions equivalent to the
		// ContributionsLineEnding hook. Hook implementers may cancel
		// the hook to signal the user is not allowed to read this item.
		$feedItem = null;
		$hookResult = $this->hookRunner->onApiFeedContributions__feedItem(
			$row, $this->getContext(), $feedItem );
		// Hook returned a valid feed item
		if ( $feedItem instanceof FeedItem ) {
			return $feedItem;
		// Hook was canceled and did not return a valid feed item
		} elseif ( !$hookResult ) {
			return null;
		}

		// Hook completed and did not return a valid feed item
		$title = Title::makeTitle( (int)$row->page_namespace, $row->page_title );

		if ( $title && $this->getAuthority()->authorizeRead( 'read', $title ) ) {
			$date = $row->rev_timestamp;
			$comments = $title->getTalkPage()->getFullURL();
			$revision = $this->revisionStore->newRevisionFromRow( $row, 0, $title );

			return new FeedItem(
				$title->getPrefixedText(),
				$this->feedItemDesc( $revision ),
				$title->getFullURL( [ 'diff' => $revision->getId() ] ),
				$date,
				$this->feedItemAuthor( $revision ),
				$comments
			);
		}

		return null;
	}

	/**
	 * @since 1.32, takes a RevisionRecord instead of a Revision
	 * @param RevisionRecord $revision
	 * @return string
	 */
	protected function feedItemAuthor( RevisionRecord $revision ) {
		$user = $revision->getUser();
		return $user ? $user->getName() : '';
	}

	/**
	 * @since 1.32, takes a RevisionRecord instead of a Revision
	 * @param RevisionRecord $revision
	 * @return string
	 */
	protected function feedItemDesc( RevisionRecord $revision ) {
		$msg = $this->msg( 'colon-separator' )->inContentLanguage()->text();
		try {
			$content = $revision->getContent( SlotRecord::MAIN );
		} catch ( RevisionAccessException $e ) {
			$content = null;
		}

		if ( $content instanceof TextContent ) {
			// only textual content has a "source view".
			$html = nl2br( htmlspecialchars( $content->getText(), ENT_COMPAT ) );
		} else {
			// XXX: we could get an HTML representation of the content via getParserOutput, but that may
			//     contain JS magic and generally may not be suitable for inclusion in a feed.
			//     Perhaps Content should have a getDescriptiveHtml method and/or a getSourceText method.
			// Compare also MediaWiki\Feed\FeedUtils::formatDiffRow.
			$html = '';
		}

		$comment = $revision->getComment();

		return '<p>' . htmlspecialchars( $this->feedItemAuthor( $revision ) ) . $msg .
			htmlspecialchars( FeedItem::stripComment( $comment->text ?? '' ) ) .
			"</p>\n<hr />\n<div>" . $html . '</div>';
	}

	public function getAllowedParams() {
		$feedFormatNames = array_keys( $this->getConfig()->get( MainConfigNames::FeedClasses ) );

		$ret = [
			'feedformat' => [
				ParamValidator::PARAM_DEFAULT => 'rss',
				ParamValidator::PARAM_TYPE => $feedFormatNames
			],
			'user' => [
				ParamValidator::PARAM_TYPE => 'user',
				UserDef::PARAM_ALLOWED_USER_TYPES => [ 'name', 'ip', 'cidr', 'id', 'interwiki' ],
				ParamValidator::PARAM_REQUIRED => true,
			],
			'namespace' => [
				ParamValidator::PARAM_TYPE => 'namespace'
			],
			'year' => [
				ParamValidator::PARAM_TYPE => 'integer'
			],
			'month' => [
				ParamValidator::PARAM_TYPE => 'integer'
			],
			'tagfilter' => [
				ParamValidator::PARAM_ISMULTI => true,
				ParamValidator::PARAM_TYPE => array_values( ChangeTags::listDefinedTags() ),
				ParamValidator::PARAM_DEFAULT => '',
			],
			'deletedonly' => false,
			'toponly' => false,
			'newonly' => false,
			'hideminor' => false,
			'showsizediff' => [
				ParamValidator::PARAM_DEFAULT => false,
			],
		];

		if ( $this->getConfig()->get( MainConfigNames::MiserMode ) ) {
			$ret['showsizediff'][ApiBase::PARAM_HELP_MSG] = 'api-help-param-disabled-in-miser-mode';
		}

		return $ret;
	}

	protected function getExamplesMessages() {
		return [
			'action=feedcontributions&user=Example'
				=> 'apihelp-feedcontributions-example-simple',
		];
	}
}