MediaWiki  master
DeletedContribsPager.php
Go to the documentation of this file.
1 <?php
30 
32 
37 
41  public $messages;
42 
46  public $target;
47 
51  public $namespace = '';
52 
56  public $mDb;
57 
61  protected $mNavigationBar;
62 
63  public function __construct( IContextSource $context, $target, $namespace = false ) {
64  parent::__construct( $context );
65  $msgs = [ 'deletionlog', 'undeleteviewlink', 'diff' ];
66  foreach ( $msgs as $msg ) {
67  $this->messages[$msg] = $this->msg( $msg )->text();
68  }
69  $this->target = $target;
70  $this->namespace = $namespace;
71  $this->mDb = wfGetDB( DB_REPLICA, 'contributions' );
72  }
73 
74  function getDefaultQuery() {
75  $query = parent::getDefaultQuery();
76  $query['target'] = $this->target;
77 
78  return $query;
79  }
80 
81  function getQueryInfo() {
82  $userCond = [
83  // ->getJoin() below takes care of any joins needed
84  ActorMigration::newMigration()->getWhere(
85  wfGetDB( DB_REPLICA ), 'ar_user', User::newFromName( $this->target, false ), false
86  )['conds']
87  ];
88  $conds = array_merge( $userCond, $this->getNamespaceCond() );
89  $user = $this->getUser();
90  // Paranoia: avoid brute force searches (T19792)
91  if ( !$user->isAllowed( 'deletedhistory' ) ) {
92  $conds[] = $this->mDb->bitAnd( 'ar_deleted', RevisionRecord::DELETED_USER ) . ' = 0';
93  } elseif ( !MediaWikiServices::getInstance()
94  ->getPermissionManager()
95  ->userHasAnyRight( $user, 'suppressrevision', 'viewsuppressed' )
96  ) {
97  $conds[] = $this->mDb->bitAnd( 'ar_deleted', RevisionRecord::SUPPRESSED_USER ) .
98  ' != ' . RevisionRecord::SUPPRESSED_USER;
99  }
100 
101  $commentQuery = CommentStore::getStore()->getJoin( 'ar_comment' );
102  $actorQuery = ActorMigration::newMigration()->getJoin( 'ar_user' );
103 
104  return [
105  'tables' => [ 'archive' ] + $commentQuery['tables'] + $actorQuery['tables'],
106  'fields' => [
107  'ar_rev_id', 'ar_namespace', 'ar_title', 'ar_timestamp',
108  'ar_minor_edit', 'ar_deleted'
109  ] + $commentQuery['fields'] + $actorQuery['fields'],
110  'conds' => $conds,
111  'options' => [],
112  'join_conds' => $commentQuery['joins'] + $actorQuery['joins'],
113  ];
114  }
115 
125  function reallyDoQuery( $offset, $limit, $order ) {
126  $data = [ parent::reallyDoQuery( $offset, $limit, $order ) ];
127 
128  // This hook will allow extensions to add in additional queries, nearly
129  // identical to ContribsPager::reallyDoQuery.
130  Hooks::run(
131  'DeletedContribsPager::reallyDoQuery',
132  [ &$data, $this, $offset, $limit, $order ]
133  );
134 
135  $result = [];
136 
137  // loop all results and collect them in an array
138  foreach ( $data as $query ) {
139  foreach ( $query as $i => $row ) {
140  // use index column as key, allowing us to easily sort in PHP
141  $result[$row->{$this->getIndexField()} . "-$i"] = $row;
142  }
143  }
144 
145  // sort results
146  if ( $order === self::QUERY_ASCENDING ) {
147  ksort( $result );
148  } else {
149  krsort( $result );
150  }
151 
152  // enforce limit
153  $result = array_slice( $result, 0, $limit );
154 
155  // get rid of array keys
156  $result = array_values( $result );
157 
158  return new FakeResultWrapper( $result );
159  }
160 
161  function getIndexField() {
162  return 'ar_timestamp';
163  }
164 
168  public function getTarget() {
169  return $this->target;
170  }
171 
175  public function getNamespace() {
176  return $this->namespace;
177  }
178 
179  protected function getStartBody() {
180  return "<ul>\n";
181  }
182 
183  protected function getEndBody() {
184  return "</ul>\n";
185  }
186 
187  function getNavigationBar() {
188  if ( isset( $this->mNavigationBar ) ) {
189  return $this->mNavigationBar;
190  }
191 
192  $linkTexts = [
193  'prev' => $this->msg( 'pager-newer-n' )->numParams( $this->mLimit )->escaped(),
194  'next' => $this->msg( 'pager-older-n' )->numParams( $this->mLimit )->escaped(),
195  'first' => $this->msg( 'histlast' )->escaped(),
196  'last' => $this->msg( 'histfirst' )->escaped()
197  ];
198 
199  $pagingLinks = $this->getPagingLinks( $linkTexts );
200  $limitLinks = $this->getLimitLinks();
201  $lang = $this->getLanguage();
202  $limits = $lang->pipeList( $limitLinks );
203 
204  $firstLast = $lang->pipeList( [ $pagingLinks['first'], $pagingLinks['last'] ] );
205  $firstLast = $this->msg( 'parentheses' )->rawParams( $firstLast )->escaped();
206  $prevNext = $this->msg( 'viewprevnext' )
207  ->rawParams(
208  $pagingLinks['prev'],
209  $pagingLinks['next'],
210  $limits
211  )->escaped();
212  $separator = $this->msg( 'word-separator' )->escaped();
213  $this->mNavigationBar = $firstLast . $separator . $prevNext;
214 
215  return $this->mNavigationBar;
216  }
217 
218  function getNamespaceCond() {
219  if ( $this->namespace !== '' ) {
220  return [ 'ar_namespace' => (int)$this->namespace ];
221  } else {
222  return [];
223  }
224  }
225 
233  function formatRow( $row ) {
234  $ret = '';
235  $classes = [];
236  $attribs = [];
237 
238  /*
239  * There may be more than just revision rows. To make sure that we'll only be processing
240  * revisions here, let's _try_ to build a revision out of our row (without displaying
241  * notices though) and then trying to grab data from the built object. If we succeed,
242  * we're definitely dealing with revision data and we may proceed, if not, we'll leave it
243  * to extensions to subscribe to the hook to parse the row.
244  */
245  Wikimedia\suppressWarnings();
246  try {
248  $validRevision = (bool)$rev->getId();
249  } catch ( Exception $e ) {
250  $validRevision = false;
251  }
252  Wikimedia\restoreWarnings();
253 
254  if ( $validRevision ) {
255  $attribs['data-mw-revid'] = $rev->getId();
256  $ret = $this->formatRevisionRow( $row );
257  }
258 
259  // Let extensions add data
260  Hooks::run( 'DeletedContributionsLineEnding', [ $this, &$ret, $row, &$classes, &$attribs ] );
261  $attribs = array_filter( $attribs,
262  [ Sanitizer::class, 'isReservedDataAttribute' ],
263  ARRAY_FILTER_USE_KEY
264  );
265 
266  if ( $classes === [] && $attribs === [] && $ret === '' ) {
267  wfDebug( "Dropping Special:DeletedContribution row that could not be formatted\n" );
268  $ret = "<!-- Could not format Special:DeletedContribution row. -->\n";
269  } else {
270  $attribs['class'] = $classes;
271  $ret = Html::rawElement( 'li', $attribs, $ret ) . "\n";
272  }
273 
274  return $ret;
275  }
276 
289  function formatRevisionRow( $row ) {
290  $page = Title::makeTitle( $row->ar_namespace, $row->ar_title );
291 
292  $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
293 
294  $rev = new Revision( [
295  'title' => $page,
296  'id' => $row->ar_rev_id,
297  'comment' => CommentStore::getStore()->getComment( 'ar_comment', $row )->text,
298  'user' => $row->ar_user,
299  'user_text' => $row->ar_user_text,
300  'actor' => $row->ar_actor ?? null,
301  'timestamp' => $row->ar_timestamp,
302  'minor_edit' => $row->ar_minor_edit,
303  'deleted' => $row->ar_deleted,
304  ] );
305 
306  $undelete = SpecialPage::getTitleFor( 'Undelete' );
307 
308  $logs = SpecialPage::getTitleFor( 'Log' );
309  $dellog = $linkRenderer->makeKnownLink(
310  $logs,
311  $this->messages['deletionlog'],
312  [],
313  [
314  'type' => 'delete',
315  'page' => $page->getPrefixedText()
316  ]
317  );
318 
319  $reviewlink = $linkRenderer->makeKnownLink(
320  SpecialPage::getTitleFor( 'Undelete', $page->getPrefixedDBkey() ),
321  $this->messages['undeleteviewlink']
322  );
323 
324  $user = $this->getUser();
325 
326  if ( $user->isAllowed( 'deletedtext' ) ) {
327  $last = $linkRenderer->makeKnownLink(
328  $undelete,
329  $this->messages['diff'],
330  [],
331  [
332  'target' => $page->getPrefixedText(),
333  'timestamp' => $rev->getTimestamp(),
334  'diff' => 'prev'
335  ]
336  );
337  } else {
338  $last = htmlspecialchars( $this->messages['diff'] );
339  }
340 
341  $comment = Linker::revComment( $rev );
342  $date = $this->getLanguage()->userTimeAndDate( $rev->getTimestamp(), $user );
343 
344  if ( !$user->isAllowed( 'undelete' ) || !$rev->userCan( RevisionRecord::DELETED_TEXT, $user ) ) {
345  $link = htmlspecialchars( $date ); // unusable link
346  } else {
347  $link = $linkRenderer->makeKnownLink(
348  $undelete,
349  $date,
350  [ 'class' => 'mw-changeslist-date' ],
351  [
352  'target' => $page->getPrefixedText(),
353  'timestamp' => $rev->getTimestamp()
354  ]
355  );
356  }
357  // Style deleted items
358  if ( $rev->isDeleted( RevisionRecord::DELETED_TEXT ) ) {
359  $link = '<span class="history-deleted">' . $link . '</span>';
360  }
361 
362  $pagelink = $linkRenderer->makeLink(
363  $page,
364  null,
365  [ 'class' => 'mw-changeslist-title' ]
366  );
367 
368  if ( $rev->isMinor() ) {
369  $mflag = ChangesList::flag( 'minor' );
370  } else {
371  $mflag = '';
372  }
373 
374  // Revision delete link
375  $del = Linker::getRevDeleteLink( $user, $rev, $page );
376  if ( $del ) {
377  $del .= ' ';
378  }
379 
380  $tools = Html::rawElement(
381  'span',
382  [ 'class' => 'mw-deletedcontribs-tools' ],
383  $this->msg( 'parentheses' )->rawParams( $this->getLanguage()->pipeList(
384  [ $last, $dellog, $reviewlink ] ) )->escaped()
385  );
386 
387  $separator = '<span class="mw-changeslist-separator">. .</span>';
388  $ret = "{$del}{$link} {$tools} {$separator} {$mflag} {$pagelink} {$comment}";
389 
390  # Denote if username is redacted for this edit
391  if ( $rev->isDeleted( RevisionRecord::DELETED_USER ) ) {
392  $ret .= " <strong>" . $this->msg( 'rev-deleted-user-contribs' )->escaped() . "</strong>";
393  }
394 
395  return $ret;
396  }
397 
403  public function getDatabase() {
404  return $this->mDb;
405  }
406 }
const DIR_DESCENDING
Backwards-compatible constant for $mDefaultDirection field (do not change)
Definition: IndexPager.php:75
static newFromArchiveRow( $row, $overrides=[])
Make a fake revision object from an archive table row.
Definition: Revision.php:171
return true to allow those checks to and false if checking is done remove or add to the links of a group of changes in EnhancedChangesList Hook subscribers can return false to omit this line from recentchanges use this to change the tables headers change it to an object instance and return false override the list derivative used $groups Array of ChangesListFilterGroup objects(added in 1.34) 'FileDeleteComplete' 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:1535
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:1983
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:1983
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2158
if(!isset( $args[0])) $lang
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition: Html.php:209
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:671
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. 'ImgAuthModifyHeaders':Executed just before a file is streamed to a user via img_auth.php, allowing headers to be modified beforehand. $title:LinkTarget object & $headers:HTTP headers(name=> value, names are case insensitive). Two headers get special handling:If-Modified-Since(value must be a valid HTTP date) and Range(must be of the form "bytes=(\*-\*)") will be honored when streaming the file. '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:1981
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:1274
$last
IndexPager is an efficient pager which uses a (roughly unique) index in the data set to implement pag...
Definition: IndexPager.php:71
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:1983
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:773
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
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:1759
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
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:592
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:2107
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:1574
const DB_REPLICA
Definition: defines.php:25
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
Definition: User.php:535
return true to allow those checks to and false if checking is done & $user
Definition: hooks.txt:1460
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200