MediaWiki  master
SpecialNewpages.php
Go to the documentation of this file.
1 <?php
25 
35  protected $opts;
37  protected $customFilters;
38 
39  protected $showNavigation = false;
40 
41  public function __construct() {
42  parent::__construct( 'Newpages' );
43  }
44 
48  protected function setup( $par ) {
49  $opts = new FormOptions();
50  $this->opts = $opts; // bind
51  $opts->add( 'hideliu', false );
52  $opts->add( 'hidepatrolled', $this->getUser()->getBoolOption( 'newpageshidepatrolled' ) );
53  $opts->add( 'hidebots', false );
54  $opts->add( 'hideredirs', true );
55  $opts->add( 'limit', $this->getUser()->getIntOption( 'rclimit' ) );
56  $opts->add( 'offset', '' );
57  $opts->add( 'namespace', '0' );
58  $opts->add( 'username', '' );
59  $opts->add( 'feed', '' );
60  $opts->add( 'tagfilter', '' );
61  $opts->add( 'invert', false );
62  $opts->add( 'associated', false );
63  $opts->add( 'size-mode', 'max' );
64  $opts->add( 'size', 0 );
65 
66  $this->customFilters = [];
67  Hooks::run( 'SpecialNewPagesFilters', [ $this, &$this->customFilters ] );
68  // @phan-suppress-next-line PhanEmptyForeach False positive
69  foreach ( $this->customFilters as $key => $params ) {
70  $opts->add( $key, $params['default'] );
71  }
72 
74  if ( $par ) {
75  $this->parseParams( $par );
76  }
77 
78  $opts->validateIntBounds( 'limit', 0, 5000 );
79  }
80 
84  protected function parseParams( $par ) {
85  $bits = preg_split( '/\s*,\s*/', trim( $par ) );
86  foreach ( $bits as $bit ) {
87  if ( $bit === 'shownav' ) {
88  $this->showNavigation = true;
89  }
90  if ( $bit === 'hideliu' ) {
91  $this->opts->setValue( 'hideliu', true );
92  }
93  if ( $bit === 'hidepatrolled' ) {
94  $this->opts->setValue( 'hidepatrolled', true );
95  }
96  if ( $bit === 'hidebots' ) {
97  $this->opts->setValue( 'hidebots', true );
98  }
99  if ( $bit === 'showredirs' ) {
100  $this->opts->setValue( 'hideredirs', false );
101  }
102  if ( is_numeric( $bit ) ) {
103  $this->opts->setValue( 'limit', intval( $bit ) );
104  }
105 
106  $m = [];
107  if ( preg_match( '/^limit=(\d+)$/', $bit, $m ) ) {
108  $this->opts->setValue( 'limit', intval( $m[1] ) );
109  }
110  // PG offsets not just digits!
111  if ( preg_match( '/^offset=([^=]+)$/', $bit, $m ) ) {
112  $this->opts->setValue( 'offset', intval( $m[1] ) );
113  }
114  if ( preg_match( '/^username=(.*)$/', $bit, $m ) ) {
115  $this->opts->setValue( 'username', $m[1] );
116  }
117  if ( preg_match( '/^namespace=(.*)$/', $bit, $m ) ) {
118  $ns = $this->getLanguage()->getNsIndex( $m[1] );
119  if ( $ns !== false ) {
120  $this->opts->setValue( 'namespace', $ns );
121  }
122  }
123  }
124  }
125 
131  public function execute( $par ) {
132  $out = $this->getOutput();
133 
134  $this->setHeaders();
135  $this->outputHeader();
136 
137  $this->showNavigation = !$this->including(); // Maybe changed in setup
138  $this->setup( $par );
139 
140  $this->addHelpLink( 'Help:New pages' );
141 
142  if ( !$this->including() ) {
143  // Settings
144  $this->form();
145 
146  $feedType = $this->opts->getValue( 'feed' );
147  if ( $feedType ) {
148  $this->feed( $feedType );
149 
150  return;
151  }
152 
153  $allValues = $this->opts->getAllValues();
154  unset( $allValues['feed'] );
155  $out->setFeedAppendQuery( wfArrayToCgi( $allValues ) );
156  }
157 
158  $pager = new NewPagesPager( $this, $this->opts );
159  $pager->mLimit = $this->opts->getValue( 'limit' );
160  $pager->mOffset = $this->opts->getValue( 'offset' );
161 
162  if ( $pager->getNumRows() ) {
163  $navigation = '';
164  if ( $this->showNavigation ) {
165  $navigation = $pager->getNavigationBar();
166  }
167  $out->addHTML( $navigation . $pager->getBody() . $navigation );
168  // Add styles for change tags
169  $out->addModuleStyles( 'mediawiki.interface.helpers.styles' );
170  } else {
171  $out->addWikiMsg( 'specialpage-empty' );
172  }
173  }
174 
175  protected function filterLinks() {
176  // show/hide links
177  $showhide = [ $this->msg( 'show' )->escaped(), $this->msg( 'hide' )->escaped() ];
178 
179  // Option value -> message mapping
180  $filters = [
181  'hideliu' => 'rcshowhideliu',
182  'hidepatrolled' => 'rcshowhidepatr',
183  'hidebots' => 'rcshowhidebots',
184  'hideredirs' => 'whatlinkshere-hideredirs'
185  ];
186  foreach ( $this->customFilters as $key => $params ) {
187  $filters[$key] = $params['msg'];
188  }
189 
190  // Disable some if needed
191  if ( !MediaWikiServices::getInstance()->getPermissionManager()
192  ->groupHasPermission( '*', 'createpage' )
193  ) {
194  unset( $filters['hideliu'] );
195  }
196  if ( !$this->getUser()->useNPPatrol() ) {
197  unset( $filters['hidepatrolled'] );
198  }
199 
200  $links = [];
201  $changed = $this->opts->getChangedValues();
202  unset( $changed['offset'] ); // Reset offset if query type changes
203 
204  // wfArrayToCgi(), called from LinkRenderer/Title, will not output null and false values
205  // to the URL, which would omit some options (T158504). Fix it by explicitly setting them
206  // to 0 or 1.
207  // Also do this only for boolean options, not eg. namespace or tagfilter
208  foreach ( $changed as $key => $value ) {
209  if ( array_key_exists( $key, $filters ) ) {
210  $changed[$key] = $changed[$key] ? '1' : '0';
211  }
212  }
213 
214  $self = $this->getPageTitle();
215  $linkRenderer = $this->getLinkRenderer();
216  foreach ( $filters as $key => $msg ) {
217  $onoff = 1 - $this->opts->getValue( $key );
218  $link = $linkRenderer->makeLink(
219  $self,
220  new HtmlArmor( $showhide[$onoff] ),
221  [],
222  [ $key => $onoff ] + $changed
223  );
224  $links[$key] = $this->msg( $msg )->rawParams( $link )->escaped();
225  }
226 
227  return $this->getLanguage()->pipeList( $links );
228  }
229 
230  protected function form() {
231  $out = $this->getOutput();
232 
233  // Consume values
234  $this->opts->consumeValue( 'offset' ); // don't carry offset, DWIW
235  $namespace = $this->opts->consumeValue( 'namespace' );
236  $username = $this->opts->consumeValue( 'username' );
237  $tagFilterVal = $this->opts->consumeValue( 'tagfilter' );
238  $nsinvert = $this->opts->consumeValue( 'invert' );
239  $nsassociated = $this->opts->consumeValue( 'associated' );
240 
241  $size = $this->opts->consumeValue( 'size' );
242  $max = $this->opts->consumeValue( 'size-mode' ) === 'max';
243 
244  // Check username input validity
245  $ut = Title::makeTitleSafe( NS_USER, $username );
246  $userText = $ut ? $ut->getText() : '';
247 
248  $formDescriptor = [
249  'namespace' => [
250  'type' => 'namespaceselect',
251  'name' => 'namespace',
252  'label-message' => 'namespace',
253  'default' => $namespace,
254  ],
255  'nsinvert' => [
256  'type' => 'check',
257  'name' => 'invert',
258  'label-message' => 'invert',
259  'default' => $nsinvert,
260  'tooltip' => 'invert',
261  ],
262  'nsassociated' => [
263  'type' => 'check',
264  'name' => 'associated',
265  'label-message' => 'namespace_association',
266  'default' => $nsassociated,
267  'tooltip' => 'namespace_association',
268  ],
269  'tagFilter' => [
270  'type' => 'tagfilter',
271  'name' => 'tagfilter',
272  'label-raw' => $this->msg( 'tag-filter' )->parse(),
273  'default' => $tagFilterVal,
274  ],
275  'username' => [
276  'type' => 'user',
277  'name' => 'username',
278  'label-message' => 'newpages-username',
279  'default' => $userText,
280  'id' => 'mw-np-username',
281  'size' => 30,
282  ],
283  'size' => [
284  'type' => 'sizefilter',
285  'name' => 'size',
286  'default' => -$max * $size,
287  ],
288  ];
289 
290  $htmlForm = HTMLForm::factory( 'ooui', $formDescriptor, $this->getContext() );
291 
292  // Store query values in hidden fields so that form submission doesn't lose them
293  foreach ( $this->opts->getUnconsumedValues() as $key => $value ) {
294  $htmlForm->addHiddenField( $key, $value );
295  }
296 
297  $htmlForm
298  ->setMethod( 'get' )
299  ->setFormIdentifier( 'newpagesform' )
300  // The form should be visible on each request (inclusive requests with submitted forms), so
301  // return always false here.
302  ->setSubmitCallback(
303  function () {
304  return false;
305  }
306  )
307  ->setSubmitText( $this->msg( 'newpages-submit' )->text() )
308  ->setWrapperLegend( $this->msg( 'newpages' )->text() )
309  ->addFooterText( Html::rawElement(
310  'div',
311  null,
312  $this->filterLinks()
313  ) )
314  ->show();
315  $out->addModuleStyles( 'mediawiki.special' );
316  }
317 
323  protected function revisionFromRcResult( stdClass $result, Title $title ) {
324  return new Revision( [
325  'comment' => CommentStore::getStore()->getComment( 'rc_comment', $result )->text,
326  'deleted' => $result->rc_deleted,
327  'user_text' => $result->rc_user_text,
328  'user' => $result->rc_user,
329  'actor' => $result->rc_actor,
330  ], 0, $title );
331  }
332 
340  public function formatRow( $result ) {
341  $title = Title::newFromRow( $result );
342 
343  // Revision deletion works on revisions,
344  // so cast our recent change row to a revision row.
345  $rev = $this->revisionFromRcResult( $result, $title );
346 
347  $classes = [];
348  $attribs = [ 'data-mw-revid' => $result->rev_id ];
349 
350  $lang = $this->getLanguage();
351  $dm = $lang->getDirMark();
352 
353  $spanTime = Html::element( 'span', [ 'class' => 'mw-newpages-time' ],
354  $lang->userTimeAndDate( $result->rc_timestamp, $this->getUser() )
355  );
356  $linkRenderer = $this->getLinkRenderer();
357  $time = $linkRenderer->makeKnownLink(
358  $title,
359  new HtmlArmor( $spanTime ),
360  [],
361  [ 'oldid' => $result->rc_this_oldid ]
362  );
363 
364  $query = $title->isRedirect() ? [ 'redirect' => 'no' ] : [];
365 
366  $plink = $linkRenderer->makeKnownLink(
367  $title,
368  null,
369  [ 'class' => 'mw-newpages-pagename' ],
370  $query
371  );
372  $histLink = $linkRenderer->makeKnownLink(
373  $title,
374  $this->msg( 'hist' )->text(),
375  [],
376  [ 'action' => 'history' ]
377  );
378  $hist = Html::rawElement( 'span', [ 'class' => 'mw-newpages-history' ],
379  $this->msg( 'parentheses' )->rawParams( $histLink )->escaped() );
380 
381  $length = Html::rawElement(
382  'span',
383  [ 'class' => 'mw-newpages-length' ],
384  $this->msg( 'brackets' )->rawParams(
385  $this->msg( 'nbytes' )->numParams( $result->length )->escaped()
386  )->escaped()
387  );
388 
389  $ulink = Linker::revUserTools( $rev );
390  $comment = Linker::revComment( $rev );
391 
392  if ( $this->patrollable( $result ) ) {
393  $classes[] = 'not-patrolled';
394  }
395 
396  # Add a class for zero byte pages
397  if ( $result->length == 0 ) {
398  $classes[] = 'mw-newpages-zero-byte-page';
399  }
400 
401  # Tags, if any.
402  if ( isset( $result->ts_tags ) ) {
403  list( $tagDisplay, $newClasses ) = ChangeTags::formatSummaryRow(
404  $result->ts_tags,
405  'newpages',
406  $this->getContext()
407  );
408  $classes = array_merge( $classes, $newClasses );
409  } else {
410  $tagDisplay = '';
411  }
412 
413  # Display the old title if the namespace/title has been changed
414  $oldTitleText = '';
415  $oldTitle = Title::makeTitle( $result->rc_namespace, $result->rc_title );
416 
417  if ( !$title->equals( $oldTitle ) ) {
418  $oldTitleText = $oldTitle->getPrefixedText();
419  $oldTitleText = Html::rawElement(
420  'span',
421  [ 'class' => 'mw-newpages-oldtitle' ],
422  $this->msg( 'rc-old-title' )->params( $oldTitleText )->escaped()
423  );
424  }
425 
426  $ret = "{$time} {$dm}{$plink} {$hist} {$dm}{$length} {$dm}{$ulink} {$comment} "
427  . "{$tagDisplay} {$oldTitleText}";
428 
429  // Let extensions add data
430  Hooks::run( 'NewPagesLineEnding', [ $this, &$ret, $result, &$classes, &$attribs ] );
431  $attribs = array_filter( $attribs,
432  [ Sanitizer::class, 'isReservedDataAttribute' ],
433  ARRAY_FILTER_USE_KEY
434  );
435 
436  if ( count( $classes ) ) {
437  $attribs['class'] = implode( ' ', $classes );
438  }
439 
440  return Html::rawElement( 'li', $attribs, $ret ) . "\n";
441  }
442 
449  protected function patrollable( $result ) {
450  return ( $this->getUser()->useNPPatrol() && !$result->rc_patrolled );
451  }
452 
458  protected function feed( $type ) {
459  if ( !$this->getConfig()->get( 'Feed' ) ) {
460  $this->getOutput()->addWikiMsg( 'feed-unavailable' );
461 
462  return;
463  }
464 
465  $feedClasses = $this->getConfig()->get( 'FeedClasses' );
466  if ( !isset( $feedClasses[$type] ) ) {
467  $this->getOutput()->addWikiMsg( 'feed-invalid' );
468 
469  return;
470  }
471 
472  $feed = new $feedClasses[$type](
473  $this->feedTitle(),
474  $this->msg( 'tagline' )->text(),
475  $this->getPageTitle()->getFullURL()
476  );
477 
478  $pager = new NewPagesPager( $this, $this->opts );
479  $limit = $this->opts->getValue( 'limit' );
480  $pager->mLimit = min( $limit, $this->getConfig()->get( 'FeedLimit' ) );
481 
482  $feed->outHeader();
483  if ( $pager->getNumRows() > 0 ) {
484  foreach ( $pager->mResult as $row ) {
485  $feed->outItem( $this->feedItem( $row ) );
486  }
487  }
488  $feed->outFooter();
489  }
490 
491  protected function feedTitle() {
492  $desc = $this->getDescription();
493  $code = $this->getConfig()->get( 'LanguageCode' );
494  $sitename = $this->getConfig()->get( 'Sitename' );
495 
496  return "$sitename - $desc [$code]";
497  }
498 
499  protected function feedItem( $row ) {
500  $title = Title::makeTitle( intval( $row->rc_namespace ), $row->rc_title );
501  if ( $title ) {
502  $date = $row->rc_timestamp;
503  $comments = $title->getTalkPage()->getFullURL();
504 
505  return new FeedItem(
506  $title->getPrefixedText(),
507  $this->feedItemDesc( $row ),
508  $title->getFullURL(),
509  $date,
510  $this->feedItemAuthor( $row ),
511  $comments
512  );
513  } else {
514  return null;
515  }
516  }
517 
518  protected function feedItemAuthor( $row ) {
519  return $row->rc_user_text ?? '';
520  }
521 
522  protected function feedItemDesc( $row ) {
523  $revision = Revision::newFromId( $row->rev_id );
524  if ( !$revision ) {
525  return '';
526  }
527 
528  $content = $revision->getContent();
529  if ( $content === null ) {
530  return '';
531  }
532 
533  // XXX: include content model/type in feed item?
534  return '<p>' . htmlspecialchars( $revision->getUserText() ) .
535  $this->msg( 'colon-separator' )->inContentLanguage()->escaped() .
536  htmlspecialchars( FeedItem::stripComment( $revision->getComment() ) ) .
537  "</p>\n<hr />\n<div>" .
538  nl2br( htmlspecialchars( $content->serialize() ) ) . "</div>";
539  }
540 
541  protected function getGroupName() {
542  return 'changes';
543  }
544 
545  protected function getCacheTTL() {
546  return 60 * 5;
547  }
548 }
static stripComment( $text)
Quickie hack...
Definition: FeedItem.php:218
Helper class to keep track of options when mixing links and form elements.
Definition: FormOptions.php:35
revisionFromRcResult(stdClass $result, Title $title)
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition: Html.php:231
getContext()
Gets the context this SpecialPage is executed in.
including( $x=null)
Whether the special page is being evaluated via transclusion.
if(!isset( $args[0])) $lang
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition: Html.php:209
A special page that list newly created pages.
array [] $customFilters
addHelpLink( $to, $overrideBaseUrl=false)
Adds help link with an icon via page indicators.
getOutput()
Get the OutputPage being used for this instance.
static newFromRow( $row)
Make a Title object from a DB row.
Definition: Title.php:518
add( $name, $default, $type=self::AUTO)
Add an option to be handled by this FormOptions instance.
Definition: FormOptions.php:83
feed( $type)
Output a subscription feed listing recent edits to this page.
validateIntBounds( $name, $min, $max)
patrollable( $result)
Should a specific result row provide "patrollable" links?
fetchValuesFromRequest(WebRequest $r, $optionKeys=null)
Fetch values for all options (or selected options) from the given WebRequest, making them available f...
FormOptions $opts
wfArrayToCgi( $array1, $array2=null, $prefix='')
This function takes one or two arrays as input, and returns a CGI-style string, e.g.
getPermissionManager()
msg( $key,... $params)
Wrapper around wfMessage that sets the current context.
static factory( $displayFormat,... $arguments)
Construct a HTMLForm object for given display type.
Definition: HTMLForm.php:307
Shortcut to construct an includable special page.
$self
getDescription()
Returns the name that goes in the <h1> in the special page itself, and also the name that will be l...
setHeaders()
Sets headers - this should be called from the execute() method of all derived classes! ...
A base class for outputting syndication feeds (e.g.
Definition: FeedItem.php:33
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:612
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:586
static getStore()
getUser()
Shortcut to get the User executing this instance.
getConfig()
Shortcut to get main config object.
getLanguage()
Shortcut to get user&#39;s language.
execute( $par)
Show a form for filtering namespace and username.
static formatSummaryRow( $tags, $page, IContextSource $context=null)
Creates HTML for the given tags.
Definition: ChangeTags.php:94
static revComment(Revision $rev, $local=false, $isPublic=false, $useParentheses=true)
Wrap and format the given revision&#39;s comment block, if the current user is allowed to view it...
Definition: Linker.php:1572
$content
Definition: router.php:78
getRequest()
Get the WebRequest being used for this instance.
static newFromId( $id, $flags=0)
Load a page revision from a given revision ID number.
Definition: Revision.php:119
outputHeader( $summaryMessageKey='')
Outputs a summary message on top of special pages Per default the message key is the canonical name o...
getPageTitle( $subpage=false)
Get a self-referential title object.
formatRow( $result)
Format a row, providing the timestamp, links to the page/history, size, user links, and a comment.
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200
static revUserTools( $rev, $isPublic=false, $useParentheses=true)
Generate a user tool link cluster if the current user is allowed to view it.
Definition: Linker.php:1124
MediaWiki Linker LinkRenderer null $linkRenderer
Definition: SpecialPage.php:67