Merge "Make DBAccessBase use DBConnRef, rename $wiki, and hide getLoadBalancer()"
[lhc/web/wiklou.git] / includes / specials / pagers / DeletedContribsPager.php
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 * @ingroup Pager
20 */
21
22 /**
23 * @ingroup Pager
24 */
25 use MediaWiki\Linker\LinkRenderer;
26 use MediaWiki\MediaWikiServices;
27 use MediaWiki\Storage\RevisionRecord;
28 use Wikimedia\Rdbms\IDatabase;
29 use Wikimedia\Rdbms\IResultWrapper;
30 use Wikimedia\Rdbms\FakeResultWrapper;
31
32 class DeletedContribsPager extends IndexPager {
33
34 /**
35 * @var bool Default direction for pager
36 */
37 public $mDefaultDirection = IndexPager::DIR_DESCENDING;
38
39 /**
40 * @var string[] Local cache for escaped messages
41 */
42 public $messages;
43
44 /**
45 * @var string User name, or a string describing an IP address range
46 */
47 public $target;
48
49 /**
50 * @var string|int A single namespace number, or an empty string for all namespaces
51 */
52 public $namespace = '';
53
54 /**
55 * @var IDatabase
56 */
57 public $mDb;
58
59 /**
60 * @var string Navigation bar with paging links.
61 */
62 protected $mNavigationBar;
63
64 public function __construct( IContextSource $context, $target, $namespace = false,
65 LinkRenderer $linkRenderer
66 ) {
67 parent::__construct( $context, $linkRenderer );
68 $msgs = [ 'deletionlog', 'undeleteviewlink', 'diff' ];
69 foreach ( $msgs as $msg ) {
70 $this->messages[$msg] = $this->msg( $msg )->text();
71 }
72 $this->target = $target;
73 $this->namespace = $namespace;
74 $this->mDb = wfGetDB( DB_REPLICA, 'contributions' );
75 }
76
77 function getDefaultQuery() {
78 $query = parent::getDefaultQuery();
79 $query['target'] = $this->target;
80
81 return $query;
82 }
83
84 function getQueryInfo() {
85 $userCond = [
86 // ->getJoin() below takes care of any joins needed
87 ActorMigration::newMigration()->getWhere(
88 wfGetDB( DB_REPLICA ), 'ar_user', User::newFromName( $this->target, false ), false
89 )['conds']
90 ];
91 $conds = array_merge( $userCond, $this->getNamespaceCond() );
92 $user = $this->getUser();
93 // Paranoia: avoid brute force searches (T19792)
94 if ( !$user->isAllowed( 'deletedhistory' ) ) {
95 $conds[] = $this->mDb->bitAnd( 'ar_deleted', RevisionRecord::DELETED_USER ) . ' = 0';
96 } elseif ( !MediaWikiServices::getInstance()
97 ->getPermissionManager()
98 ->userHasAnyRight( $user, 'suppressrevision', 'viewsuppressed' )
99 ) {
100 $conds[] = $this->mDb->bitAnd( 'ar_deleted', RevisionRecord::SUPPRESSED_USER ) .
101 ' != ' . RevisionRecord::SUPPRESSED_USER;
102 }
103
104 $commentQuery = CommentStore::getStore()->getJoin( 'ar_comment' );
105 $actorQuery = ActorMigration::newMigration()->getJoin( 'ar_user' );
106
107 return [
108 'tables' => [ 'archive' ] + $commentQuery['tables'] + $actorQuery['tables'],
109 'fields' => [
110 'ar_rev_id', 'ar_namespace', 'ar_title', 'ar_timestamp',
111 'ar_minor_edit', 'ar_deleted'
112 ] + $commentQuery['fields'] + $actorQuery['fields'],
113 'conds' => $conds,
114 'options' => [],
115 'join_conds' => $commentQuery['joins'] + $actorQuery['joins'],
116 ];
117 }
118
119 /**
120 * This method basically executes the exact same code as the parent class, though with
121 * a hook added, to allow extensions to add additional queries.
122 *
123 * @param string $offset Index offset, inclusive
124 * @param int $limit Exact query limit
125 * @param bool $order IndexPager::QUERY_ASCENDING or IndexPager::QUERY_DESCENDING
126 * @return IResultWrapper
127 */
128 function reallyDoQuery( $offset, $limit, $order ) {
129 $data = [ parent::reallyDoQuery( $offset, $limit, $order ) ];
130
131 // This hook will allow extensions to add in additional queries, nearly
132 // identical to ContribsPager::reallyDoQuery.
133 Hooks::run(
134 'DeletedContribsPager::reallyDoQuery',
135 [ &$data, $this, $offset, $limit, $order ]
136 );
137
138 $result = [];
139
140 // loop all results and collect them in an array
141 foreach ( $data as $query ) {
142 foreach ( $query as $i => $row ) {
143 // use index column as key, allowing us to easily sort in PHP
144 $result[$row->{$this->getIndexField()} . "-$i"] = $row;
145 }
146 }
147
148 // sort results
149 if ( $order === self::QUERY_ASCENDING ) {
150 ksort( $result );
151 } else {
152 krsort( $result );
153 }
154
155 // enforce limit
156 $result = array_slice( $result, 0, $limit );
157
158 // get rid of array keys
159 $result = array_values( $result );
160
161 return new FakeResultWrapper( $result );
162 }
163
164 function getIndexField() {
165 return 'ar_timestamp';
166 }
167
168 /**
169 * @return string
170 */
171 public function getTarget() {
172 return $this->target;
173 }
174
175 /**
176 * @return int|string
177 */
178 public function getNamespace() {
179 return $this->namespace;
180 }
181
182 protected function getStartBody() {
183 return "<ul>\n";
184 }
185
186 protected function getEndBody() {
187 return "</ul>\n";
188 }
189
190 function getNavigationBar() {
191 if ( isset( $this->mNavigationBar ) ) {
192 return $this->mNavigationBar;
193 }
194
195 $linkTexts = [
196 'prev' => $this->msg( 'pager-newer-n' )->numParams( $this->mLimit )->escaped(),
197 'next' => $this->msg( 'pager-older-n' )->numParams( $this->mLimit )->escaped(),
198 'first' => $this->msg( 'histlast' )->escaped(),
199 'last' => $this->msg( 'histfirst' )->escaped()
200 ];
201
202 $pagingLinks = $this->getPagingLinks( $linkTexts );
203 $limitLinks = $this->getLimitLinks();
204 $lang = $this->getLanguage();
205 $limits = $lang->pipeList( $limitLinks );
206
207 $firstLast = $lang->pipeList( [ $pagingLinks['first'], $pagingLinks['last'] ] );
208 $firstLast = $this->msg( 'parentheses' )->rawParams( $firstLast )->escaped();
209 $prevNext = $this->msg( 'viewprevnext' )
210 ->rawParams(
211 $pagingLinks['prev'],
212 $pagingLinks['next'],
213 $limits
214 )->escaped();
215 $separator = $this->msg( 'word-separator' )->escaped();
216 $this->mNavigationBar = $firstLast . $separator . $prevNext;
217
218 return $this->mNavigationBar;
219 }
220
221 function getNamespaceCond() {
222 if ( $this->namespace !== '' ) {
223 return [ 'ar_namespace' => (int)$this->namespace ];
224 } else {
225 return [];
226 }
227 }
228
229 /**
230 * Generates each row in the contributions list.
231 *
232 * @todo This would probably look a lot nicer in a table.
233 * @param stdClass $row
234 * @return string
235 */
236 function formatRow( $row ) {
237 $ret = '';
238 $classes = [];
239 $attribs = [];
240
241 /*
242 * There may be more than just revision rows. To make sure that we'll only be processing
243 * revisions here, let's _try_ to build a revision out of our row (without displaying
244 * notices though) and then trying to grab data from the built object. If we succeed,
245 * we're definitely dealing with revision data and we may proceed, if not, we'll leave it
246 * to extensions to subscribe to the hook to parse the row.
247 */
248 Wikimedia\suppressWarnings();
249 try {
250 $rev = Revision::newFromArchiveRow( $row );
251 $validRevision = (bool)$rev->getId();
252 } catch ( Exception $e ) {
253 $validRevision = false;
254 }
255 Wikimedia\restoreWarnings();
256
257 if ( $validRevision ) {
258 $attribs['data-mw-revid'] = $rev->getId();
259 $ret = $this->formatRevisionRow( $row );
260 }
261
262 // Let extensions add data
263 Hooks::run( 'DeletedContributionsLineEnding', [ $this, &$ret, $row, &$classes, &$attribs ] );
264 $attribs = array_filter( $attribs,
265 [ Sanitizer::class, 'isReservedDataAttribute' ],
266 ARRAY_FILTER_USE_KEY
267 );
268
269 if ( $classes === [] && $attribs === [] && $ret === '' ) {
270 wfDebug( "Dropping Special:DeletedContribution row that could not be formatted\n" );
271 $ret = "<!-- Could not format Special:DeletedContribution row. -->\n";
272 } else {
273 $attribs['class'] = $classes;
274 $ret = Html::rawElement( 'li', $attribs, $ret ) . "\n";
275 }
276
277 return $ret;
278 }
279
280 /**
281 * Generates each row in the contributions list for archive entries.
282 *
283 * Contributions which are marked "top" are currently on top of the history.
284 * For these contributions, a [rollback] link is shown for users with sysop
285 * privileges. The rollback link restores the most recent version that was not
286 * written by the target user.
287 *
288 * @todo This would probably look a lot nicer in a table.
289 * @param stdClass $row
290 * @return string
291 */
292 function formatRevisionRow( $row ) {
293 $page = Title::makeTitle( $row->ar_namespace, $row->ar_title );
294
295 $linkRenderer = $this->getLinkRenderer();
296
297 $rev = new Revision( [
298 'title' => $page,
299 'id' => $row->ar_rev_id,
300 'comment' => CommentStore::getStore()->getComment( 'ar_comment', $row )->text,
301 'user' => $row->ar_user,
302 'user_text' => $row->ar_user_text,
303 'actor' => $row->ar_actor ?? null,
304 'timestamp' => $row->ar_timestamp,
305 'minor_edit' => $row->ar_minor_edit,
306 'deleted' => $row->ar_deleted,
307 ] );
308
309 $undelete = SpecialPage::getTitleFor( 'Undelete' );
310
311 $logs = SpecialPage::getTitleFor( 'Log' );
312 $dellog = $linkRenderer->makeKnownLink(
313 $logs,
314 $this->messages['deletionlog'],
315 [],
316 [
317 'type' => 'delete',
318 'page' => $page->getPrefixedText()
319 ]
320 );
321
322 $reviewlink = $linkRenderer->makeKnownLink(
323 SpecialPage::getTitleFor( 'Undelete', $page->getPrefixedDBkey() ),
324 $this->messages['undeleteviewlink']
325 );
326
327 $user = $this->getUser();
328
329 if ( $user->isAllowed( 'deletedtext' ) ) {
330 $last = $linkRenderer->makeKnownLink(
331 $undelete,
332 $this->messages['diff'],
333 [],
334 [
335 'target' => $page->getPrefixedText(),
336 'timestamp' => $rev->getTimestamp(),
337 'diff' => 'prev'
338 ]
339 );
340 } else {
341 $last = htmlspecialchars( $this->messages['diff'] );
342 }
343
344 $comment = Linker::revComment( $rev );
345 $date = $this->getLanguage()->userTimeAndDate( $rev->getTimestamp(), $user );
346
347 if ( !$user->isAllowed( 'undelete' ) || !$rev->userCan( RevisionRecord::DELETED_TEXT, $user ) ) {
348 $link = htmlspecialchars( $date ); // unusable link
349 } else {
350 $link = $linkRenderer->makeKnownLink(
351 $undelete,
352 $date,
353 [ 'class' => 'mw-changeslist-date' ],
354 [
355 'target' => $page->getPrefixedText(),
356 'timestamp' => $rev->getTimestamp()
357 ]
358 );
359 }
360 // Style deleted items
361 if ( $rev->isDeleted( RevisionRecord::DELETED_TEXT ) ) {
362 $link = '<span class="history-deleted">' . $link . '</span>';
363 }
364
365 $pagelink = $linkRenderer->makeLink(
366 $page,
367 null,
368 [ 'class' => 'mw-changeslist-title' ]
369 );
370
371 if ( $rev->isMinor() ) {
372 $mflag = ChangesList::flag( 'minor' );
373 } else {
374 $mflag = '';
375 }
376
377 // Revision delete link
378 $del = Linker::getRevDeleteLink( $user, $rev, $page );
379 if ( $del ) {
380 $del .= ' ';
381 }
382
383 $tools = Html::rawElement(
384 'span',
385 [ 'class' => 'mw-deletedcontribs-tools' ],
386 $this->msg( 'parentheses' )->rawParams( $this->getLanguage()->pipeList(
387 [ $last, $dellog, $reviewlink ] ) )->escaped()
388 );
389
390 $separator = '<span class="mw-changeslist-separator">. .</span>';
391 $ret = "{$del}{$link} {$tools} {$separator} {$mflag} {$pagelink} {$comment}";
392
393 # Denote if username is redacted for this edit
394 if ( $rev->isDeleted( RevisionRecord::DELETED_USER ) ) {
395 $ret .= " <strong>" . $this->msg( 'rev-deleted-user-contribs' )->escaped() . "</strong>";
396 }
397
398 return $ret;
399 }
400
401 /**
402 * Get the Database object in use
403 *
404 * @return IDatabase
405 */
406 public function getDatabase() {
407 return $this->mDb;
408 }
409 }