MediaWiki master
ApiFeedContributions.php
Go to the documentation of this file.
1<?php
9namespace MediaWiki\Api;
10
32use stdClass;
35
40
41 private ApiHookRunner $hookRunner;
42
43 public function __construct(
44 ApiMain $main,
45 string $action,
46 private readonly RevisionStore $revisionStore,
47 private readonly LinkRenderer $linkRenderer,
48 private readonly LinkBatchFactory $linkBatchFactory,
49 private readonly HookContainer $hookContainer,
50 private readonly IConnectionProvider $dbProvider,
51 private readonly NamespaceInfo $namespaceInfo,
52 private readonly UserFactory $userFactory,
53 private readonly CommentFormatter $commentFormatter,
54 ) {
55 parent::__construct( $main, $action );
56
57 $this->hookRunner = new ApiHookRunner( $hookContainer );
58 }
59
65 public function getCustomPrinter() {
66 return new ApiFormatFeedWrapper( $this->getMain() );
67 }
68
69 public function execute() {
70 $params = $this->extractRequestParams();
71
72 $config = $this->getConfig();
73 if ( !$config->get( MainConfigNames::Feed ) ) {
74 $this->dieWithError( 'feed-unavailable' );
75 }
76
77 $feedClasses = $config->get( MainConfigNames::FeedClasses );
78 '@phan-var array<string,class-string<ChannelFeed>> $feedClasses';
79 if ( !isset( $feedClasses[$params['feedformat']] ) ) {
80 $this->dieWithError( 'feed-invalid' );
81 }
82
83 if ( $params['showsizediff'] && $config->get( MainConfigNames::MiserMode ) ) {
84 $this->dieWithError( 'apierror-sizediffdisabled' );
85 }
86
87 $msg = $this->msg( 'Contributions' )->inContentLanguage()->escaped();
88 $feedTitle = $config->get( MainConfigNames::Sitename )
89 . " - $msg "
90 . $this->msg( 'brackets', $config->get( MainConfigNames::LanguageCode ) )->inContentLanguage()->text();
91
92 $target = $params['user'];
93 if ( ExternalUserNames::isExternal( $target ) ) {
94 // Interwiki names make invalid titles, so put the target in the query instead.
95 $feedUrl = SpecialPage::getTitleFor( 'Contributions' )->getFullURL( [ 'target' => $target ] );
96 } else {
97 $feedUrl = SpecialPage::getTitleFor( 'Contributions', $target )->getFullURL();
98 }
99
100 $feed = new $feedClasses[$params['feedformat']](
101 $feedTitle,
102 $msg,
103 $feedUrl
104 );
105
106 // Convert year/month parameters to end parameter
107 $params['start'] = '';
108 $params['end'] = '';
109 $params = ContribsPager::processDateFilter( $params );
110
111 $targetUser = $this->userFactory->newFromName( $target, UserRigorOptions::RIGOR_NONE );
112
113 $pager = new ContribsPager(
114 $this->getContext(), [
115 'target' => $target,
116 'namespace' => $params['namespace'],
117 'start' => $params['start'],
118 'end' => $params['end'],
119 'tagFilter' => $params['tagfilter'],
120 'deletedOnly' => $params['deletedonly'],
121 'topOnly' => $params['toponly'],
122 'newOnly' => $params['newonly'],
123 'hideMinor' => $params['hideminor'],
124 'showSizeDiff' => $params['showsizediff'],
125 ],
126 $this->linkRenderer,
127 $this->linkBatchFactory,
128 $this->hookContainer,
129 $this->dbProvider,
130 $this->revisionStore,
131 $this->namespaceInfo,
132 $targetUser,
133 $this->commentFormatter
134 );
135
136 $feedLimit = $config->get( MainConfigNames::FeedLimit );
137 if ( $pager->getLimit() > $feedLimit ) {
138 $pager->setLimit( $feedLimit );
139 }
140
141 $feedItems = [];
142 if ( $pager->getNumRows() > 0 ) {
143 $count = 0;
144 $limit = $pager->getLimit();
145 foreach ( $pager->mResult as $row ) {
146 // ContribsPager selects one more row for navigation, skip that row
147 if ( ++$count > $limit ) {
148 break;
149 }
150 $item = $this->feedItem( $row );
151 if ( $item !== null ) {
152 $feedItems[] = $item;
153 }
154 }
155 }
156
157 ApiFormatFeedWrapper::setResult( $this->getResult(), $feed, $feedItems );
158 }
159
164 protected function feedItem( $row ): ?FeedItem {
165 // This hook is the api contributions equivalent to the
166 // ContributionsLineEnding hook. Hook implementers may cancel
167 // the hook to signal the user is not allowed to read this item.
168 $feedItem = null;
169 $hookResult = $this->hookRunner->onApiFeedContributions__feedItem(
170 $row, $this->getContext(), $feedItem );
171 // Hook returned a valid feed item
172 if ( $feedItem instanceof FeedItem ) {
173 return $feedItem;
174 // Hook was canceled and did not return a valid feed item
175 } elseif ( !$hookResult ) {
176 return null;
177 }
178
179 // Hook completed and did not return a valid feed item
180 $title = Title::makeTitle( (int)$row->page_namespace, $row->page_title );
181
182 if ( $this->getAuthority()->authorizeRead( 'read', $title ) ) {
183 $date = $row->rev_timestamp;
184 $comments = $title->getTalkPage()->getFullURL();
185 $revision = $this->revisionStore->newRevisionFromRow( $row, 0, $title );
186
187 return new FeedItem(
188 $title->getPrefixedText(),
189 $this->feedItemDesc( $revision ),
190 $title->getFullURL( [ 'diff' => $revision->getId() ] ),
191 $date,
192 $this->feedItemAuthor( $revision ),
193 $comments
194 );
195 }
196
197 return null;
198 }
199
205 protected function feedItemAuthor( RevisionRecord $revision ) {
206 $user = $revision->getUser();
207 return $user ? $user->getName() : '';
208 }
209
215 protected function feedItemDesc( RevisionRecord $revision ) {
216 $msg = $this->msg( 'colon-separator' )->inContentLanguage()->escaped();
217 try {
218 $content = $revision->getContent( SlotRecord::MAIN );
219 } catch ( RevisionAccessException ) {
220 $content = null;
221 }
222
223 if ( $content instanceof TextContent ) {
224 // only textual content has a "source view".
225 $html = nl2br( htmlspecialchars( $content->getText(), ENT_COMPAT ) );
226 } else {
227 // XXX: we could get an HTML representation of the content via getParserOutput, but that may
228 // contain JS magic and generally may not be suitable for inclusion in a feed.
229 // Perhaps Content should have a getDescriptiveHtml method and/or a getSourceText method.
230 // Compare also MediaWiki\Feed\FeedUtils::formatDiffRow.
231 $html = '';
232 }
233
234 $comment = $revision->getComment();
235
236 return '<p>' . htmlspecialchars( $this->feedItemAuthor( $revision ) ) . $msg .
237 htmlspecialchars( FeedItem::stripComment( $comment->text ?? '' ) ) .
238 "</p>\n<hr />\n<div>" . $html . '</div>';
239 }
240
242 public function getAllowedParams() {
243 $feedFormatNames = array_keys( $this->getConfig()->get( MainConfigNames::FeedClasses ) );
244
245 $ret = [
246 'feedformat' => [
247 ParamValidator::PARAM_DEFAULT => 'rss',
248 ParamValidator::PARAM_TYPE => $feedFormatNames
249 ],
250 'user' => [
251 ParamValidator::PARAM_TYPE => 'user',
252 UserDef::PARAM_ALLOWED_USER_TYPES => [ 'name', 'ip', 'temp', 'cidr', 'id', 'interwiki' ],
253 ParamValidator::PARAM_REQUIRED => true,
254 ],
255 'namespace' => [
256 ParamValidator::PARAM_TYPE => 'namespace'
257 ],
258 'year' => [
259 ParamValidator::PARAM_TYPE => 'integer'
260 ],
261 'month' => [
262 ParamValidator::PARAM_TYPE => 'integer'
263 ],
264 'tagfilter' => [
265 ParamValidator::PARAM_ISMULTI => true,
266 ParamValidator::PARAM_TYPE => array_values( MediaWikiServices::getInstance()
267 ->getChangeTagsStore()->listDefinedTags()
268 ),
269 ParamValidator::PARAM_DEFAULT => '',
270 ],
271 'deletedonly' => false,
272 'toponly' => false,
273 'newonly' => false,
274 'hideminor' => false,
275 'showsizediff' => [
276 ParamValidator::PARAM_DEFAULT => false,
277 ],
278 ];
279
280 if ( $this->getConfig()->get( MainConfigNames::MiserMode ) ) {
281 $ret['showsizediff'][ApiBase::PARAM_HELP_MSG] = 'api-help-param-disabled-in-miser-mode';
282 }
283
284 return $ret;
285 }
286
288 protected function getExamplesMessages() {
289 return [
290 'action=feedcontributions&user=Example'
291 => 'apihelp-feedcontributions-example-simple',
292 ];
293 }
294
296 public function getHelpUrls() {
297 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Feedcontributions';
298 }
299}
300
302class_alias( ApiFeedContributions::class, 'ApiFeedContributions' );
This abstract class implements many basic API functions, and is the base of all API classes.
Definition ApiBase.php:60
dieWithError( $msg, $code=null, $data=null, $httpCode=0)
Abort execution with an error.
Definition ApiBase.php:1522
getMain()
Get the main module.
Definition ApiBase.php:575
getResult()
Get the result object.
Definition ApiBase.php:696
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition ApiBase.php:166
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition ApiBase.php:837
feedItem( $row)
TODO: use stdClass type hint without T398925.
execute()
Evaluates the parameters, performs the requested query, and sets up the result.
getCustomPrinter()
This module uses a custom feed wrapper printer.
getHelpUrls()
Return links to more detailed help pages about the module.1.25, returning boolean false is deprecated...
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
getExamplesMessages()
Returns usage examples for this module.Return value has query strings as keys, with values being eith...
__construct(ApiMain $main, string $action, private readonly RevisionStore $revisionStore, private readonly LinkRenderer $linkRenderer, private readonly LinkBatchFactory $linkBatchFactory, private readonly HookContainer $hookContainer, private readonly IConnectionProvider $dbProvider, private readonly NamespaceInfo $namespaceInfo, private readonly UserFactory $userFactory, private readonly CommentFormatter $commentFormatter,)
This printer is used to wrap an instance of the Feed class.
static setResult( $result, $feed, $feedItems)
Call this method to initialize output data.
This class provides an implementation of the hook interfaces used by the core Action API,...
This is the main API class, used for both external and internal processing.
Definition ApiMain.php:66
This is the main service interface for converting single-line comments from various DB comment fields...
Content object implementation for representing flat text.
msg( $key,... $params)
Get a Message object with context set Parameters are the same as wfMessage()
makeTitle( $linkId)
Convert a link ID to a Title.to override Title
Class to support the outputting of syndication feeds in Atom and RSS format.
A base class for outputting syndication feeds (e.g.
Definition FeedItem.php:26
Class that generates HTML for internal links.
A class containing constants representing the names of configuration variables.
const FeedClasses
Name constant for the FeedClasses setting, for use with Config::get()
const Feed
Name constant for the Feed setting, for use with Config::get()
const Sitename
Name constant for the Sitename setting, for use with Config::get()
const LanguageCode
Name constant for the LanguageCode setting, for use with Config::get()
const MiserMode
Name constant for the MiserMode setting, for use with Config::get()
const FeedLimit
Name constant for the FeedLimit setting, for use with Config::get()
Service locator for MediaWiki core services.
static getInstance()
Returns the global default instance of the top level service locator.
Factory for LinkBatch objects to batch query page metadata.
Type definition for user types.
Definition UserDef.php:27
Exception representing a failure to look up a revision.
Page revision base class.
getContent( $role, $audience=self::FOR_PUBLIC, ?Authority $performer=null)
Returns the Content of the given slot of this revision.
getUser( $audience=self::FOR_PUBLIC, ?Authority $performer=null)
Fetch revision's author's user identity, if it's available to the specified audience.
getComment( $audience=self::FOR_PUBLIC, ?Authority $performer=null)
Fetch revision comment, if it's available to the specified audience.
Service for looking up page revisions.
Value object representing a content slot associated with a page revision.
Parent class for all special pages.
static getTitleFor( $name, $subpage=false, $fragment='')
Get a localised Title object for a specified special page name If you don't need a full Title object,...
Pager for Special:Contributions.
static processDateFilter(array $opts)
Set up date filter options, given request data.
This is a utility class for dealing with namespaces that encodes all the "magic" behaviors of them ba...
Represents a title within MediaWiki.
Definition Title.php:69
Class to parse and build external user names.
Create User objects.
Service for formatting and validating API parameters.
Shared interface for rigor levels when dealing with User methods.
Provide primary and replica IDatabase connections.