MediaWiki  master
ApiFeedContributions.php
Go to the documentation of this file.
1 <?php
28 
33 
35  private $revisionStore;
36 
38  private $titleParser;
39 
45  public function getCustomPrinter() {
46  return new ApiFormatFeedWrapper( $this->getMain() );
47  }
48 
49  public function execute() {
50  $this->revisionStore = MediaWikiServices::getInstance()->getRevisionStore();
51  $this->titleParser = MediaWikiServices::getInstance()->getTitleParser();
52 
53  $params = $this->extractRequestParams();
54 
55  $config = $this->getConfig();
56  if ( !$config->get( 'Feed' ) ) {
57  $this->dieWithError( 'feed-unavailable' );
58  }
59 
60  $feedClasses = $config->get( 'FeedClasses' );
61  if ( !isset( $feedClasses[$params['feedformat']] ) ) {
62  $this->dieWithError( 'feed-invalid' );
63  }
64 
65  if ( $params['showsizediff'] && $this->getConfig()->get( 'MiserMode' ) ) {
66  $this->dieWithError( 'apierror-sizediffdisabled' );
67  }
68 
69  $msg = wfMessage( 'Contributions' )->inContentLanguage()->text();
70  $feedTitle = $config->get( 'Sitename' ) . ' - ' . $msg .
71  ' [' . $config->get( 'LanguageCode' ) . ']';
72  $feedUrl = SpecialPage::getTitleFor( 'Contributions', $params['user'] )->getFullURL();
73 
74  $target = 'newbies';
75  if ( $params['user'] != 'newbies' ) {
76  try {
77  $target = $this->titleParser
78  ->parseTitle( $params['user'], NS_USER )
79  ->getText();
80  } catch ( MalformedTitleException $e ) {
81  $this->dieWithError(
82  [ 'apierror-baduser', 'user', wfEscapeWikiText( $params['user'] ) ],
83  'baduser_' . $this->encodeParamName( 'user' )
84  );
85  }
86  }
87 
88  $feed = new $feedClasses[$params['feedformat']] (
89  $feedTitle,
90  htmlspecialchars( $msg ),
91  $feedUrl
92  );
93 
94  // Convert year/month parameters to end parameter
95  $params['start'] = '';
96  $params['end'] = '';
97  $params = ContribsPager::processDateFilter( $params );
98 
99  $pager = new ContribsPager( $this->getContext(), [
100  'target' => $target,
101  'namespace' => $params['namespace'],
102  'start' => $params['start'],
103  'end' => $params['end'],
104  'tagFilter' => $params['tagfilter'],
105  'deletedOnly' => $params['deletedonly'],
106  'topOnly' => $params['toponly'],
107  'newOnly' => $params['newonly'],
108  'hideMinor' => $params['hideminor'],
109  'showSizeDiff' => $params['showsizediff'],
110  ] );
111 
112  $feedLimit = $this->getConfig()->get( 'FeedLimit' );
113  if ( $pager->getLimit() > $feedLimit ) {
114  $pager->setLimit( $feedLimit );
115  }
116 
117  $feedItems = [];
118  if ( $pager->getNumRows() > 0 ) {
119  $count = 0;
120  $limit = $pager->getLimit();
121  foreach ( $pager->mResult as $row ) {
122  // ContribsPager selects one more row for navigation, skip that row
123  if ( ++$count > $limit ) {
124  break;
125  }
126  $item = $this->feedItem( $row );
127  if ( $item !== null ) {
128  $feedItems[] = $item;
129  }
130  }
131  }
132 
133  ApiFormatFeedWrapper::setResult( $this->getResult(), $feed, $feedItems );
134  }
135 
136  protected function feedItem( $row ) {
137  // This hook is the api contributions equivalent to the
138  // ContributionsLineEnding hook. Hook implementers may cancel
139  // the hook to signal the user is not allowed to read this item.
140  $feedItem = null;
141  $hookResult = Hooks::run(
142  'ApiFeedContributions::feedItem',
143  [ $row, $this->getContext(), &$feedItem ]
144  );
145  // Hook returned a valid feed item
146  if ( $feedItem instanceof FeedItem ) {
147  return $feedItem;
148  // Hook was canceled and did not return a valid feed item
149  } elseif ( !$hookResult ) {
150  return null;
151  }
152 
153  // Hook completed and did not return a valid feed item
154  $title = Title::makeTitle( (int)$row->page_namespace, $row->page_title );
155  $user = $this->getUser();
156 
157  if ( $title && $this->getPermissionManager()->userCan( 'read', $user, $title ) ) {
158  $date = $row->rev_timestamp;
159  $comments = $title->getTalkPage()->getFullURL();
160  $revision = $this->revisionStore->newRevisionFromRow( $row );
161 
162  return new FeedItem(
163  $title->getPrefixedText(),
164  $this->feedItemDesc( $revision ),
165  $title->getFullURL( [ 'diff' => $revision->getId() ] ),
166  $date,
167  $this->feedItemAuthor( $revision ),
168  $comments
169  );
170  }
171 
172  return null;
173  }
174 
180  protected function feedItemAuthor( RevisionRecord $revision ) {
181  $user = $revision->getUser();
182  return $user ? $user->getName() : '';
183  }
184 
190  protected function feedItemDesc( RevisionRecord $revision ) {
191  $msg = wfMessage( 'colon-separator' )->inContentLanguage()->text();
192  try {
193  $content = $revision->getContent( SlotRecord::MAIN );
194  } catch ( RevisionAccessException $e ) {
195  $content = null;
196  }
197 
198  if ( $content instanceof TextContent ) {
199  // only textual content has a "source view".
200  $html = nl2br( htmlspecialchars( $content->getText() ) );
201  } else {
202  // XXX: we could get an HTML representation of the content via getParserOutput, but that may
203  // contain JS magic and generally may not be suitable for inclusion in a feed.
204  // Perhaps Content should have a getDescriptiveHtml method and/or a getSourceText method.
205  // Compare also FeedUtils::formatDiffRow.
206  $html = '';
207  }
208 
209  $comment = $revision->getComment();
210 
211  return '<p>' . htmlspecialchars( $this->feedItemAuthor( $revision ) ) . $msg .
212  htmlspecialchars( FeedItem::stripComment( $comment ? $comment->text : '' ) ) .
213  "</p>\n<hr />\n<div>" . $html . '</div>';
214  }
215 
216  public function getAllowedParams() {
217  $feedFormatNames = array_keys( $this->getConfig()->get( 'FeedClasses' ) );
218 
219  $ret = [
220  'feedformat' => [
221  ApiBase::PARAM_DFLT => 'rss',
222  ApiBase::PARAM_TYPE => $feedFormatNames
223  ],
224  'user' => [
225  ApiBase::PARAM_TYPE => 'user',
226  ApiBase::PARAM_REQUIRED => true,
227  ],
228  'namespace' => [
229  ApiBase::PARAM_TYPE => 'namespace'
230  ],
231  'year' => [
232  ApiBase::PARAM_TYPE => 'integer'
233  ],
234  'month' => [
235  ApiBase::PARAM_TYPE => 'integer'
236  ],
237  'tagfilter' => [
238  ApiBase::PARAM_ISMULTI => true,
240  ApiBase::PARAM_DFLT => '',
241  ],
242  'deletedonly' => false,
243  'toponly' => false,
244  'newonly' => false,
245  'hideminor' => false,
246  'showsizediff' => [
247  ApiBase::PARAM_DFLT => false,
248  ],
249  ];
250 
251  if ( $this->getConfig()->get( 'MiserMode' ) ) {
252  $ret['showsizediff'][ApiBase::PARAM_HELP_MSG] = 'api-help-param-disabled-in-miser-mode';
253  }
254 
255  return $ret;
256  }
257 
258  protected function getExamplesMessages() {
259  return [
260  'action=feedcontributions&user=Example'
261  => 'apihelp-feedcontributions-example-simple',
262  ];
263  }
264 }
static stripComment( $text)
Quickie hack...
Definition: FeedItem.php:218
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below...
Definition: ApiBase.php:94
static listDefinedTags()
Basically lists defined tags which count even if they aren&#39;t applied to anything. ...
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses & $html
Definition: hooks.txt:1972
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking, formatting, etc.
getResult()
Get the result object.
Definition: ApiBase.php:640
MalformedTitleException is thrown when a TitleParser is unable to parse a title string.
feedItemDesc(RevisionRecord $revision)
static processDateFilter(array $opts)
Set up date filter options, given request data.
feedItemAuthor(RevisionRecord $revision)
static setResult( $result, $feed, $feedItems)
Call this method to initialize output data.
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Definition: hooks.txt:1972
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2147
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition: ApiBase.php:55
getMain()
Get the main module.
Definition: ApiBase.php:536
const PARAM_REQUIRED
(boolean) Is the parameter required?
Definition: ApiBase.php:118
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
Definition: ApiBase.php:2009
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user...
Definition: ApiBase.php:761
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
Definition: injection.txt:23
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation use $formDescriptor instead default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "&lt
getContent( $role, $audience=self::FOR_PUBLIC, User $user=null)
Returns the Content of the given slot of this revision.
getContext()
Get the base IContextSource object.
$params
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:767
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:912
static getTitleFor( $name, $subpage=false, $fragment='')
Get a localised Title object for a specified special page name If you don&#39;t need a full Title object...
Definition: SpecialPage.php:83
A base class for outputting syndication feeds (e.g.
Definition: FeedItem.php:33
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter...
Definition: ApiBase.php:131
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:592
encodeParamName( $paramName)
This method mangles parameter name based on the prefix supplied to the constructor.
Definition: ApiBase.php:739
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
const PARAM_ISMULTI
(boolean) Accept multiple pipe-separated values for this parameter (e.g.
Definition: ApiBase.php:58
Exception representing a failure to look up a revision.
getPermissionManager()
Obtain a PermissionManager instance that subclasses may use in their authorization checks...
Definition: ApiBase.php:710
This abstract class implements many basic API functions, and is the base of all API classes...
Definition: ApiBase.php:42
Page revision base class.
getUser( $audience=self::FOR_PUBLIC, User $user=null)
Fetch revision&#39;s author&#39;s user identity, if it&#39;s available to the specified audience.
getCustomPrinter()
This module uses a custom feed wrapper printer.
getComment( $audience=self::FOR_PUBLIC, User $user=null)
Fetch revision comment, if it&#39;s available to the specified audience.
$content
Definition: pageupdater.txt:72
This printer is used to wrap an instance of the Feed class.
return true to allow those checks to and false if checking is done & $user
Definition: hooks.txt:1454
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200