MediaWiki  master
DeletedContribsPager.php
Go to the documentation of this file.
1 <?php
29 
31 
36 
40  public $messages;
41 
45  public $target;
46 
50  public $namespace = '';
51 
55  public $mDb;
56 
60  protected $mNavigationBar;
61 
62  public function __construct( IContextSource $context, $target, $namespace = false ) {
63  parent::__construct( $context );
64  $msgs = [ 'deletionlog', 'undeleteviewlink', 'diff' ];
65  foreach ( $msgs as $msg ) {
66  $this->messages[$msg] = $this->msg( $msg )->text();
67  }
68  $this->target = $target;
69  $this->namespace = $namespace;
70  $this->mDb = wfGetDB( DB_REPLICA, 'contributions' );
71  }
72 
73  function getDefaultQuery() {
74  $query = parent::getDefaultQuery();
75  $query['target'] = $this->target;
76 
77  return $query;
78  }
79 
80  function getQueryInfo() {
81  $userCond = [
82  // ->getJoin() below takes care of any joins needed
83  ActorMigration::newMigration()->getWhere(
84  wfGetDB( DB_REPLICA ), 'ar_user', User::newFromName( $this->target, false ), false
85  )['conds']
86  ];
87  $conds = array_merge( $userCond, $this->getNamespaceCond() );
88  $user = $this->getUser();
89  // Paranoia: avoid brute force searches (T19792)
90  if ( !$user->isAllowed( 'deletedhistory' ) ) {
91  $conds[] = $this->mDb->bitAnd( 'ar_deleted', Revision::DELETED_USER ) . ' = 0';
92  } elseif ( !$user->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
93  $conds[] = $this->mDb->bitAnd( 'ar_deleted', Revision::SUPPRESSED_USER ) .
95  }
96 
97  $commentQuery = CommentStore::getStore()->getJoin( 'ar_comment' );
98  $actorQuery = ActorMigration::newMigration()->getJoin( 'ar_user' );
99 
100  return [
101  'tables' => [ 'archive' ] + $commentQuery['tables'] + $actorQuery['tables'],
102  'fields' => [
103  'ar_rev_id', 'ar_namespace', 'ar_title', 'ar_timestamp',
104  'ar_minor_edit', 'ar_deleted'
105  ] + $commentQuery['fields'] + $actorQuery['fields'],
106  'conds' => $conds,
107  'options' => [],
108  'join_conds' => $commentQuery['joins'] + $actorQuery['joins'],
109  ];
110  }
111 
121  function reallyDoQuery( $offset, $limit, $order ) {
122  $data = [ parent::reallyDoQuery( $offset, $limit, $order ) ];
123 
124  // This hook will allow extensions to add in additional queries, nearly
125  // identical to ContribsPager::reallyDoQuery.
126  Hooks::run(
127  'DeletedContribsPager::reallyDoQuery',
128  [ &$data, $this, $offset, $limit, $order ]
129  );
130 
131  $result = [];
132 
133  // loop all results and collect them in an array
134  foreach ( $data as $query ) {
135  foreach ( $query as $i => $row ) {
136  // use index column as key, allowing us to easily sort in PHP
137  $result[$row->{$this->getIndexField()} . "-$i"] = $row;
138  }
139  }
140 
141  // sort results
142  if ( $order === self::QUERY_ASCENDING ) {
143  ksort( $result );
144  } else {
145  krsort( $result );
146  }
147 
148  // enforce limit
149  $result = array_slice( $result, 0, $limit );
150 
151  // get rid of array keys
152  $result = array_values( $result );
153 
154  return new FakeResultWrapper( $result );
155  }
156 
157  function getIndexField() {
158  return 'ar_timestamp';
159  }
160 
164  public function getTarget() {
165  return $this->target;
166  }
167 
171  public function getNamespace() {
172  return $this->namespace;
173  }
174 
175  protected function getStartBody() {
176  return "<ul>\n";
177  }
178 
179  protected function getEndBody() {
180  return "</ul>\n";
181  }
182 
183  function getNavigationBar() {
184  if ( isset( $this->mNavigationBar ) ) {
185  return $this->mNavigationBar;
186  }
187 
188  $linkTexts = [
189  'prev' => $this->msg( 'pager-newer-n' )->numParams( $this->mLimit )->escaped(),
190  'next' => $this->msg( 'pager-older-n' )->numParams( $this->mLimit )->escaped(),
191  'first' => $this->msg( 'histlast' )->escaped(),
192  'last' => $this->msg( 'histfirst' )->escaped()
193  ];
194 
195  $pagingLinks = $this->getPagingLinks( $linkTexts );
196  $limitLinks = $this->getLimitLinks();
197  $lang = $this->getLanguage();
198  $limits = $lang->pipeList( $limitLinks );
199 
200  $firstLast = $lang->pipeList( [ $pagingLinks['first'], $pagingLinks['last'] ] );
201  $firstLast = $this->msg( 'parentheses' )->rawParams( $firstLast )->escaped();
202  $prevNext = $this->msg( 'viewprevnext' )
203  ->rawParams(
204  $pagingLinks['prev'],
205  $pagingLinks['next'],
206  $limits
207  )->escaped();
208  $separator = $this->msg( 'word-separator' )->escaped();
209  $this->mNavigationBar = $firstLast . $separator . $prevNext;
210 
211  return $this->mNavigationBar;
212  }
213 
214  function getNamespaceCond() {
215  if ( $this->namespace !== '' ) {
216  return [ 'ar_namespace' => (int)$this->namespace ];
217  } else {
218  return [];
219  }
220  }
221 
229  function formatRow( $row ) {
230  $ret = '';
231  $classes = [];
232  $attribs = [];
233 
234  /*
235  * There may be more than just revision rows. To make sure that we'll only be processing
236  * revisions here, let's _try_ to build a revision out of our row (without displaying
237  * notices though) and then trying to grab data from the built object. If we succeed,
238  * we're definitely dealing with revision data and we may proceed, if not, we'll leave it
239  * to extensions to subscribe to the hook to parse the row.
240  */
241  Wikimedia\suppressWarnings();
242  try {
244  $validRevision = (bool)$rev->getId();
245  } catch ( Exception $e ) {
246  $validRevision = false;
247  }
248  Wikimedia\restoreWarnings();
249 
250  if ( $validRevision ) {
251  $attribs['data-mw-revid'] = $rev->getId();
252  $ret = $this->formatRevisionRow( $row );
253  }
254 
255  // Let extensions add data
256  Hooks::run( 'DeletedContributionsLineEnding', [ $this, &$ret, $row, &$classes, &$attribs ] );
257  $attribs = array_filter( $attribs,
258  [ Sanitizer::class, 'isReservedDataAttribute' ],
259  ARRAY_FILTER_USE_KEY
260  );
261 
262  if ( $classes === [] && $attribs === [] && $ret === '' ) {
263  wfDebug( "Dropping Special:DeletedContribution row that could not be formatted\n" );
264  $ret = "<!-- Could not format Special:DeletedContribution row. -->\n";
265  } else {
266  $attribs['class'] = $classes;
267  $ret = Html::rawElement( 'li', $attribs, $ret ) . "\n";
268  }
269 
270  return $ret;
271  }
272 
285  function formatRevisionRow( $row ) {
286  $page = Title::makeTitle( $row->ar_namespace, $row->ar_title );
287 
288  $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
289 
290  $rev = new Revision( [
291  'title' => $page,
292  'id' => $row->ar_rev_id,
293  'comment' => CommentStore::getStore()->getComment( 'ar_comment', $row )->text,
294  'user' => $row->ar_user,
295  'user_text' => $row->ar_user_text,
296  'actor' => $row->ar_actor ?? null,
297  'timestamp' => $row->ar_timestamp,
298  'minor_edit' => $row->ar_minor_edit,
299  'deleted' => $row->ar_deleted,
300  ] );
301 
302  $undelete = SpecialPage::getTitleFor( 'Undelete' );
303 
304  $logs = SpecialPage::getTitleFor( 'Log' );
305  $dellog = $linkRenderer->makeKnownLink(
306  $logs,
307  $this->messages['deletionlog'],
308  [],
309  [
310  'type' => 'delete',
311  'page' => $page->getPrefixedText()
312  ]
313  );
314 
315  $reviewlink = $linkRenderer->makeKnownLink(
316  SpecialPage::getTitleFor( 'Undelete', $page->getPrefixedDBkey() ),
317  $this->messages['undeleteviewlink']
318  );
319 
320  $user = $this->getUser();
321 
322  if ( $user->isAllowed( 'deletedtext' ) ) {
323  $last = $linkRenderer->makeKnownLink(
324  $undelete,
325  $this->messages['diff'],
326  [],
327  [
328  'target' => $page->getPrefixedText(),
329  'timestamp' => $rev->getTimestamp(),
330  'diff' => 'prev'
331  ]
332  );
333  } else {
334  $last = htmlspecialchars( $this->messages['diff'] );
335  }
336 
337  $comment = Linker::revComment( $rev );
338  $date = $this->getLanguage()->userTimeAndDate( $rev->getTimestamp(), $user );
339 
340  if ( !$user->isAllowed( 'undelete' ) || !$rev->userCan( Revision::DELETED_TEXT, $user ) ) {
341  $link = htmlspecialchars( $date ); // unusable link
342  } else {
343  $link = $linkRenderer->makeKnownLink(
344  $undelete,
345  $date,
346  [ 'class' => 'mw-changeslist-date' ],
347  [
348  'target' => $page->getPrefixedText(),
349  'timestamp' => $rev->getTimestamp()
350  ]
351  );
352  }
353  // Style deleted items
354  if ( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
355  $link = '<span class="history-deleted">' . $link . '</span>';
356  }
357 
358  $pagelink = $linkRenderer->makeLink(
359  $page,
360  null,
361  [ 'class' => 'mw-changeslist-title' ]
362  );
363 
364  if ( $rev->isMinor() ) {
365  $mflag = ChangesList::flag( 'minor' );
366  } else {
367  $mflag = '';
368  }
369 
370  // Revision delete link
371  $del = Linker::getRevDeleteLink( $user, $rev, $page );
372  if ( $del ) {
373  $del .= ' ';
374  }
375 
376  $tools = Html::rawElement(
377  'span',
378  [ 'class' => 'mw-deletedcontribs-tools' ],
379  $this->msg( 'parentheses' )->rawParams( $this->getLanguage()->pipeList(
380  [ $last, $dellog, $reviewlink ] ) )->escaped()
381  );
382 
383  $separator = '<span class="mw-changeslist-separator">. .</span>';
384  $ret = "{$del}{$link} {$tools} {$separator} {$mflag} {$pagelink} {$comment}";
385 
386  # Denote if username is redacted for this edit
387  if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
388  $ret .= " <strong>" . $this->msg( 'rev-deleted-user-contribs' )->escaped() . "</strong>";
389  }
390 
391  return $ret;
392  }
393 
399  public function getDatabase() {
400  return $this->mDb;
401  }
402 }
const DIR_DESCENDING
Backwards-compatible constant for $mDefaultDirection field (do not change)
Definition: IndexPager.php:73
static newFromArchiveRow( $row, $overrides=[])
Make a fake revision object from an archive table row.
Definition: Revision.php:171
null for the local wiki Added should default to null in handler for backwards compatibility add a value to it if you want to add a cookie that have to vary cache options can modify $query
Definition: hooks.txt:1585
$data
Utility to generate mapping file used in mw.Title (phpCharToUpper.json)
formatRevisionRow( $row)
Generates each row in the contributions list for archive entries.
string [] $messages
Local cache for escaped messages.
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
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 after processing after in associative array form before processing starts Return false to skip default processing and return $ret $linkRenderer
Definition: hooks.txt:1982
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2159
if(!isset( $args[0])) $lang
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition: Html.php:210
reallyDoQuery( $offset, $limit, $order)
This method basically executes the exact same code as the parent class, though with a hook added...
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
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
msg( $key)
Get a Message object with context set Parameters are the same as wfMessage()
getPagingLinks( $linkTexts, $disabledTexts=[])
Get paging links.
Definition: IndexPager.php:669
getDatabase()
Get the Database object in use.
IContextSource $context
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1980
usually copyright or history_copyright This message must be in HTML not wikitext & $link
Definition: hooks.txt:3050
passed in as a query string parameter to the various URLs constructed here(i.e. $prevlink) $ldel you ll need to handle error messages
Definition: hooks.txt:1287
$last
Wikimedia Rdbms Database $mDb
IndexPager is an efficient pager which uses a (roughly unique) index in the data set to implement pag...
Definition: IndexPager.php:69
static newMigration()
Static constructor.
string $target
User name, or a string describing an IP address range.
__construct(IContextSource $context, $target, $namespace=false)
static flag( $flag, IContextSource $context=null)
Make an "<abbr>" element for a given change flag.
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
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 after processing & $attribs
Definition: hooks.txt:1982
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
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:82
presenting them properly to the user as errors is done by the caller return true use this to change the list i e etc $rev
Definition: hooks.txt:1766
string int $namespace
A single namespace number, or an empty string for all namespaces.
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 DELETED_TEXT
Definition: Revision.php:46
const SUPPRESSED_USER
Definition: Revision.php:50
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
static getRevDeleteLink(User $user, Revision $rev, LinkTarget $title)
Get a revision-deletion link, or disabled link, or nothing, depending on user permissions & the setti...
Definition: Linker.php:2058
const DELETED_USER
Definition: Revision.php:48
static getStore()
string $mNavigationBar
Navigation bar with paging links.
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
Overloads the relevant methods of the real ResultsWrapper so it doesn&#39;t go anywhere near an actual da...
bool $mDefaultDirection
Default direction for pager.
formatRow( $row)
Generates each row in the contributions list.
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:1519
const DB_REPLICA
Definition: defines.php:25
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
Definition: User.php:587
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