MediaWiki  master
ApiFeedContributions.php
Go to the documentation of this file.
1 <?php
28 
33 
35  private $revisionStore;
36 
42  public function getCustomPrinter() {
43  return new ApiFormatFeedWrapper( $this->getMain() );
44  }
45 
46  public function execute() {
47  $this->revisionStore = MediaWikiServices::getInstance()->getRevisionStore();
48 
49  $params = $this->extractRequestParams();
50 
51  $config = $this->getConfig();
52  if ( !$config->get( 'Feed' ) ) {
53  $this->dieWithError( 'feed-unavailable' );
54  }
55 
56  $feedClasses = $config->get( 'FeedClasses' );
57  if ( !isset( $feedClasses[$params['feedformat']] ) ) {
58  $this->dieWithError( 'feed-invalid' );
59  }
60 
61  if ( $params['showsizediff'] && $this->getConfig()->get( 'MiserMode' ) ) {
62  $this->dieWithError( 'apierror-sizediffdisabled' );
63  }
64 
65  $msg = wfMessage( 'Contributions' )->inContentLanguage()->text();
66  $feedTitle = $config->get( 'Sitename' ) . ' - ' . $msg .
67  ' [' . $config->get( 'LanguageCode' ) . ']';
68  $feedUrl = SpecialPage::getTitleFor( 'Contributions', $params['user'] )->getFullURL();
69 
70  $target = $params['user'] == 'newbies'
71  ? 'newbies'
72  : Title::makeTitleSafe( NS_USER, $params['user'] )->getText();
73 
74  $feed = new $feedClasses[$params['feedformat']] (
75  $feedTitle,
76  htmlspecialchars( $msg ),
77  $feedUrl
78  );
79 
80  // Convert year/month parameters to end parameter
81  $params['start'] = '';
82  $params['end'] = '';
83  $params = ContribsPager::processDateFilter( $params );
84 
85  $pager = new ContribsPager( $this->getContext(), [
86  'target' => $target,
87  'namespace' => $params['namespace'],
88  'start' => $params['start'],
89  'end' => $params['end'],
90  'tagFilter' => $params['tagfilter'],
91  'deletedOnly' => $params['deletedonly'],
92  'topOnly' => $params['toponly'],
93  'newOnly' => $params['newonly'],
94  'hideMinor' => $params['hideminor'],
95  'showSizeDiff' => $params['showsizediff'],
96  ] );
97 
98  $feedLimit = $this->getConfig()->get( 'FeedLimit' );
99  if ( $pager->getLimit() > $feedLimit ) {
100  $pager->setLimit( $feedLimit );
101  }
102 
103  $feedItems = [];
104  if ( $pager->getNumRows() > 0 ) {
105  $count = 0;
106  $limit = $pager->getLimit();
107  foreach ( $pager->mResult as $row ) {
108  // ContribsPager selects one more row for navigation, skip that row
109  if ( ++$count > $limit ) {
110  break;
111  }
112  $item = $this->feedItem( $row );
113  if ( $item !== null ) {
114  $feedItems[] = $item;
115  }
116  }
117  }
118 
119  ApiFormatFeedWrapper::setResult( $this->getResult(), $feed, $feedItems );
120  }
121 
122  protected function feedItem( $row ) {
123  // This hook is the api contributions equivalent to the
124  // ContributionsLineEnding hook. Hook implementers may cancel
125  // the hook to signal the user is not allowed to read this item.
126  $feedItem = null;
127  $hookResult = Hooks::run(
128  'ApiFeedContributions::feedItem',
129  [ $row, $this->getContext(), &$feedItem ]
130  );
131  // Hook returned a valid feed item
132  if ( $feedItem instanceof FeedItem ) {
133  return $feedItem;
134  // Hook was canceled and did not return a valid feed item
135  } elseif ( !$hookResult ) {
136  return null;
137  }
138 
139  // Hook completed and did not return a valid feed item
140  $title = Title::makeTitle( (int)$row->page_namespace, $row->page_title );
141  $user = $this->getUser();
142 
143  if ( $title && $this->getPermissionManager()->userCan( 'read', $user, $title ) ) {
144  $date = $row->rev_timestamp;
145  $comments = $title->getTalkPage()->getFullURL();
146  $revision = $this->revisionStore->newRevisionFromRow( $row );
147 
148  return new FeedItem(
149  $title->getPrefixedText(),
150  $this->feedItemDesc( $revision ),
151  $title->getFullURL( [ 'diff' => $revision->getId() ] ),
152  $date,
153  $this->feedItemAuthor( $revision ),
154  $comments
155  );
156  }
157 
158  return null;
159  }
160 
166  protected function feedItemAuthor( RevisionRecord $revision ) {
167  $user = $revision->getUser();
168  return $user ? $user->getName() : '';
169  }
170 
176  protected function feedItemDesc( RevisionRecord $revision ) {
177  $msg = wfMessage( 'colon-separator' )->inContentLanguage()->text();
178  try {
179  $content = $revision->getContent( SlotRecord::MAIN );
180  } catch ( RevisionAccessException $e ) {
181  $content = null;
182  }
183 
184  if ( $content instanceof TextContent ) {
185  // only textual content has a "source view".
186  $html = nl2br( htmlspecialchars( $content->getText() ) );
187  } else {
188  // XXX: we could get an HTML representation of the content via getParserOutput, but that may
189  // contain JS magic and generally may not be suitable for inclusion in a feed.
190  // Perhaps Content should have a getDescriptiveHtml method and/or a getSourceText method.
191  // Compare also FeedUtils::formatDiffRow.
192  $html = '';
193  }
194 
195  $comment = $revision->getComment();
196 
197  return '<p>' . htmlspecialchars( $this->feedItemAuthor( $revision ) ) . $msg .
198  htmlspecialchars( FeedItem::stripComment( $comment ? $comment->text : '' ) ) .
199  "</p>\n<hr />\n<div>" . $html . '</div>';
200  }
201 
202  public function getAllowedParams() {
203  $feedFormatNames = array_keys( $this->getConfig()->get( 'FeedClasses' ) );
204 
205  $ret = [
206  'feedformat' => [
207  ApiBase::PARAM_DFLT => 'rss',
208  ApiBase::PARAM_TYPE => $feedFormatNames
209  ],
210  'user' => [
211  ApiBase::PARAM_TYPE => 'user',
212  ApiBase::PARAM_REQUIRED => true,
213  ],
214  'namespace' => [
215  ApiBase::PARAM_TYPE => 'namespace'
216  ],
217  'year' => [
218  ApiBase::PARAM_TYPE => 'integer'
219  ],
220  'month' => [
221  ApiBase::PARAM_TYPE => 'integer'
222  ],
223  'tagfilter' => [
224  ApiBase::PARAM_ISMULTI => true,
226  ApiBase::PARAM_DFLT => '',
227  ],
228  'deletedonly' => false,
229  'toponly' => false,
230  'newonly' => false,
231  'hideminor' => false,
232  'showsizediff' => [
233  ApiBase::PARAM_DFLT => false,
234  ],
235  ];
236 
237  if ( $this->getConfig()->get( 'MiserMode' ) ) {
238  $ret['showsizediff'][ApiBase::PARAM_HELP_MSG] = 'api-help-param-disabled-in-miser-mode';
239  }
240 
241  return $ret;
242  }
243 
244  protected function getExamplesMessages() {
245  return [
246  'action=feedcontributions&user=Example'
247  => 'apihelp-feedcontributions-example-simple',
248  ];
249  }
250 }
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:1982
getResult()
Get the result object.
Definition: ApiBase.php:639
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:1982
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:2159
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition: ApiBase.php:55
getMain()
Get the main module.
Definition: ApiBase.php:535
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:2008
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user...
Definition: ApiBase.php:760
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:780
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:925
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 makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:617
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:589
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:709
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:1473
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200