eea13363bd39632b728b22f96a34be0f39a0aecd
[lhc/web/wiklou.git] / includes / specials / SpecialMergeHistory.php
1 <?php
2 /**
3 * Implements Special:MergeHistory
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup SpecialPage
22 */
23
24 /**
25 * Special page allowing users with the appropriate permissions to
26 * merge article histories, with some restrictions
27 *
28 * @ingroup SpecialPage
29 */
30 class SpecialMergeHistory extends SpecialPage {
31 /** @var string */
32 protected $mAction;
33
34 /** @var string */
35 protected $mTarget;
36
37 /** @var string */
38 protected $mDest;
39
40 /** @var string */
41 protected $mTimestamp;
42
43 /** @var int */
44 protected $mTargetID;
45
46 /** @var int */
47 protected $mDestID;
48
49 /** @var string */
50 protected $mComment;
51
52 /** @var bool Was posted? */
53 protected $mMerge;
54
55 /** @var bool Was submitted? */
56 protected $mSubmitted;
57
58 /** @var Title */
59 protected $mTargetObj;
60
61 /** @var Title */
62 protected $mDestObj;
63
64 public function __construct() {
65 parent::__construct( 'MergeHistory', 'mergehistory' );
66 }
67
68 /**
69 * @return void
70 */
71 private function loadRequestParams() {
72 $request = $this->getRequest();
73 $this->mAction = $request->getVal( 'action' );
74 $this->mTarget = $request->getVal( 'target' );
75 $this->mDest = $request->getVal( 'dest' );
76 $this->mSubmitted = $request->getBool( 'submitted' );
77
78 $this->mTargetID = intval( $request->getVal( 'targetID' ) );
79 $this->mDestID = intval( $request->getVal( 'destID' ) );
80 $this->mTimestamp = $request->getVal( 'mergepoint' );
81 if ( !preg_match( '/[0-9]{14}/', $this->mTimestamp ) ) {
82 $this->mTimestamp = '';
83 }
84 $this->mComment = $request->getText( 'wpComment' );
85
86 $this->mMerge = $request->wasPosted()
87 && $this->getUser()->matchEditToken( $request->getVal( 'wpEditToken' ) );
88
89 // target page
90 if ( $this->mSubmitted ) {
91 $this->mTargetObj = Title::newFromURL( $this->mTarget );
92 $this->mDestObj = Title::newFromURL( $this->mDest );
93 } else {
94 $this->mTargetObj = null;
95 $this->mDestObj = null;
96 }
97 $this->preCacheMessages();
98 }
99
100 /**
101 * As we use the same small set of messages in various methods and that
102 * they are called often, we call them once and save them in $this->message
103 */
104 function preCacheMessages() {
105 // Precache various messages
106 if ( !isset( $this->message ) ) {
107 $this->message['last'] = $this->msg( 'last' )->escaped();
108 }
109 }
110
111 public function execute( $par ) {
112 $this->checkPermissions();
113 $this->checkReadOnly();
114
115 $this->loadRequestParams();
116
117 $this->setHeaders();
118 $this->outputHeader();
119
120 if ( $this->mTargetID && $this->mDestID && $this->mAction == 'submit' && $this->mMerge ) {
121 $this->merge();
122
123 return;
124 }
125
126 if ( !$this->mSubmitted ) {
127 $this->showMergeForm();
128
129 return;
130 }
131
132 $errors = array();
133 if ( !$this->mTargetObj instanceof Title ) {
134 $errors[] = $this->msg( 'mergehistory-invalid-source' )->parseAsBlock();
135 } elseif ( !$this->mTargetObj->exists() ) {
136 $errors[] = $this->msg( 'mergehistory-no-source',
137 wfEscapeWikiText( $this->mTargetObj->getPrefixedText() )
138 )->parseAsBlock();
139 }
140
141 if ( !$this->mDestObj instanceof Title ) {
142 $errors[] = $this->msg( 'mergehistory-invalid-destination' )->parseAsBlock();
143 } elseif ( !$this->mDestObj->exists() ) {
144 $errors[] = $this->msg( 'mergehistory-no-destination',
145 wfEscapeWikiText( $this->mDestObj->getPrefixedText() )
146 )->parseAsBlock();
147 }
148
149 if ( $this->mTargetObj && $this->mDestObj && $this->mTargetObj->equals( $this->mDestObj ) ) {
150 $errors[] = $this->msg( 'mergehistory-same-destination' )->parseAsBlock();
151 }
152
153 if ( count( $errors ) ) {
154 $this->showMergeForm();
155 $this->getOutput()->addHTML( implode( "\n", $errors ) );
156 } else {
157 $this->showHistory();
158 }
159 }
160
161 function showMergeForm() {
162 global $wgScript;
163
164 $this->getOutput()->addWikiMsg( 'mergehistory-header' );
165
166 $this->getOutput()->addHTML(
167 Xml::openElement( 'form', array(
168 'method' => 'get',
169 'action' => $wgScript ) ) .
170 '<fieldset>' .
171 Xml::element( 'legend', array(),
172 $this->msg( 'mergehistory-box' )->text() ) .
173 Html::hidden( 'title', $this->getPageTitle()->getPrefixedDBkey() ) .
174 Html::hidden( 'submitted', '1' ) .
175 Html::hidden( 'mergepoint', $this->mTimestamp ) .
176 Xml::openElement( 'table' ) .
177 '<tr>
178 <td>' . Xml::label( $this->msg( 'mergehistory-from' )->text(), 'target' ) . '</td>
179 <td>' . Xml::input( 'target', 30, $this->mTarget, array( 'id' => 'target' ) ) . '</td>
180 </tr><tr>
181 <td>' . Xml::label( $this->msg( 'mergehistory-into' )->text(), 'dest' ) . '</td>
182 <td>' . Xml::input( 'dest', 30, $this->mDest, array( 'id' => 'dest' ) ) . '</td>
183 </tr><tr><td>' .
184 Xml::submitButton( $this->msg( 'mergehistory-go' )->text() ) .
185 '</td></tr>' .
186 Xml::closeElement( 'table' ) .
187 '</fieldset>' .
188 '</form>'
189 );
190 }
191
192 private function showHistory() {
193 $this->showMergeForm();
194
195 # List all stored revisions
196 $revisions = new MergeHistoryPager(
197 $this, array(), $this->mTargetObj, $this->mDestObj
198 );
199 $haveRevisions = $revisions && $revisions->getNumRows() > 0;
200
201 $out = $this->getOutput();
202 $titleObj = $this->getPageTitle();
203 $action = $titleObj->getLocalURL( array( 'action' => 'submit' ) );
204 # Start the form here
205 $top = Xml::openElement(
206 'form',
207 array(
208 'method' => 'post',
209 'action' => $action,
210 'id' => 'merge'
211 )
212 );
213 $out->addHTML( $top );
214
215 if ( $haveRevisions ) {
216 # Format the user-visible controls (comment field, submission button)
217 # in a nice little table
218 $table =
219 Xml::openElement( 'fieldset' ) .
220 $this->msg( 'mergehistory-merge', $this->mTargetObj->getPrefixedText(),
221 $this->mDestObj->getPrefixedText() )->parse() .
222 Xml::openElement( 'table', array( 'id' => 'mw-mergehistory-table' ) ) .
223 '<tr>
224 <td class="mw-label">' .
225 Xml::label( $this->msg( 'mergehistory-reason' )->text(), 'wpComment' ) .
226 '</td>
227 <td class="mw-input">' .
228 Xml::input( 'wpComment', 50, $this->mComment, array( 'id' => 'wpComment' ) ) .
229 '</td>
230 </tr>
231 <tr>
232 <td>&#160;</td>
233 <td class="mw-submit">' .
234 Xml::submitButton(
235 $this->msg( 'mergehistory-submit' )->text(),
236 array( 'name' => 'merge', 'id' => 'mw-merge-submit' )
237 ) .
238 '</td>
239 </tr>' .
240 Xml::closeElement( 'table' ) .
241 Xml::closeElement( 'fieldset' );
242
243 $out->addHTML( $table );
244 }
245
246 $out->addHTML(
247 '<h2 id="mw-mergehistory">' .
248 $this->msg( 'mergehistory-list' )->escaped() . "</h2>\n"
249 );
250
251 if ( $haveRevisions ) {
252 $out->addHTML( $revisions->getNavigationBar() );
253 $out->addHTML( '<ul>' );
254 $out->addHTML( $revisions->getBody() );
255 $out->addHTML( '</ul>' );
256 $out->addHTML( $revisions->getNavigationBar() );
257 } else {
258 $out->addWikiMsg( 'mergehistory-empty' );
259 }
260
261 # Show relevant lines from the merge log:
262 $mergeLogPage = new LogPage( 'merge' );
263 $out->addHTML( '<h2>' . $mergeLogPage->getName()->escaped() . "</h2>\n" );
264 LogEventsList::showLogExtract( $out, 'merge', $this->mTargetObj );
265
266 # When we submit, go by page ID to avoid some nasty but unlikely collisions.
267 # Such would happen if a page was renamed after the form loaded, but before submit
268 $misc = Html::hidden( 'targetID', $this->mTargetObj->getArticleID() );
269 $misc .= Html::hidden( 'destID', $this->mDestObj->getArticleID() );
270 $misc .= Html::hidden( 'target', $this->mTarget );
271 $misc .= Html::hidden( 'dest', $this->mDest );
272 $misc .= Html::hidden( 'wpEditToken', $this->getUser()->getEditToken() );
273 $misc .= Xml::closeElement( 'form' );
274 $out->addHTML( $misc );
275
276 return true;
277 }
278
279 function formatRevisionRow( $row ) {
280 $rev = new Revision( $row );
281
282 $stxt = '';
283 $last = $this->message['last'];
284
285 $ts = wfTimestamp( TS_MW, $row->rev_timestamp );
286 $checkBox = Xml::radio( 'mergepoint', $ts, ( $this->mTimestamp === $ts ) );
287
288 $user = $this->getUser();
289
290 $pageLink = Linker::linkKnown(
291 $rev->getTitle(),
292 htmlspecialchars( $this->getLanguage()->userTimeAndDate( $ts, $user ) ),
293 array(),
294 array( 'oldid' => $rev->getId() )
295 );
296 if ( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
297 $pageLink = '<span class="history-deleted">' . $pageLink . '</span>';
298 }
299
300 # Last link
301 if ( !$rev->userCan( Revision::DELETED_TEXT, $user ) ) {
302 $last = $this->message['last'];
303 } elseif ( isset( $this->prevId[$row->rev_id] ) ) {
304 $last = Linker::linkKnown(
305 $rev->getTitle(),
306 $this->message['last'],
307 array(),
308 array(
309 'diff' => $row->rev_id,
310 'oldid' => $this->prevId[$row->rev_id]
311 )
312 );
313 }
314
315 $userLink = Linker::revUserTools( $rev );
316
317 $size = $row->rev_len;
318 if ( !is_null( $size ) ) {
319 $stxt = Linker::formatRevisionSize( $size );
320 }
321 $comment = Linker::revComment( $rev );
322
323 return Html::rawElement( 'li', array(),
324 $this->msg( 'mergehistory-revisionrow' )
325 ->rawParams( $checkBox, $last, $pageLink, $userLink, $stxt, $comment )->escaped() );
326 }
327
328 /**
329 * Actually attempt the history move
330 *
331 * @todo: if all versions of page A are moved to B and then a user
332 * tries to do a reverse-merge via the "unmerge" log link, then page
333 * A will still be a redirect (as it was after the original merge),
334 * though it will have the old revisions back from before (as expected).
335 * The user may have to "undo" the redirect manually to finish the "unmerge".
336 * Maybe this should delete redirects at the target page of merges?
337 *
338 * @return boolean Success
339 */
340 function merge() {
341 # Get the titles directly from the IDs, in case the target page params
342 # were spoofed. The queries are done based on the IDs, so it's best to
343 # keep it consistent...
344 $targetTitle = Title::newFromID( $this->mTargetID );
345 $destTitle = Title::newFromID( $this->mDestID );
346 if ( is_null( $targetTitle ) || is_null( $destTitle ) ) {
347 return false; // validate these
348 }
349 if ( $targetTitle->getArticleID() == $destTitle->getArticleID() ) {
350 return false;
351 }
352 # Verify that this timestamp is valid
353 # Must be older than the destination page
354 $dbw = wfGetDB( DB_MASTER );
355 # Get timestamp into DB format
356 $this->mTimestamp = $this->mTimestamp ? $dbw->timestamp( $this->mTimestamp ) : '';
357 # Max timestamp should be min of destination page
358 $maxtimestamp = $dbw->selectField(
359 'revision',
360 'MIN(rev_timestamp)',
361 array( 'rev_page' => $this->mDestID ),
362 __METHOD__
363 );
364 # Destination page must exist with revisions
365 if ( !$maxtimestamp ) {
366 $this->getOutput()->addWikiMsg( 'mergehistory-fail' );
367
368 return false;
369 }
370 # Get the latest timestamp of the source
371 $lasttimestamp = $dbw->selectField(
372 array( 'page', 'revision' ),
373 'rev_timestamp',
374 array( 'page_id' => $this->mTargetID, 'page_latest = rev_id' ),
375 __METHOD__
376 );
377 # $this->mTimestamp must be older than $maxtimestamp
378 if ( $this->mTimestamp >= $maxtimestamp ) {
379 $this->getOutput()->addWikiMsg( 'mergehistory-fail' );
380
381 return false;
382 }
383 # Get the timestamp pivot condition
384 if ( $this->mTimestamp ) {
385 $timewhere = "rev_timestamp <= {$this->mTimestamp}";
386 $timestampLimit = wfTimestamp( TS_MW, $this->mTimestamp );
387 } else {
388 $timewhere = "rev_timestamp <= {$maxtimestamp}";
389 $timestampLimit = wfTimestamp( TS_MW, $lasttimestamp );
390 }
391 # Check that there are not too many revisions to move
392 $limit = 5000; // avoid too much slave lag
393 $count = $dbw->select( 'revision', '1',
394 array( 'rev_page' => $this->mTargetID, $timewhere ),
395 __METHOD__,
396 array( 'LIMIT' => $limit + 1 )
397 )->numRows();
398 if ( $count > $limit ) {
399 $this->getOutput()->addWikiMsg( 'mergehistory-fail-toobig' );
400
401 return false;
402 }
403 # Do the moving...
404 $dbw->update(
405 'revision',
406 array( 'rev_page' => $this->mDestID ),
407 array( 'rev_page' => $this->mTargetID, $timewhere ),
408 __METHOD__
409 );
410
411 $count = $dbw->affectedRows();
412 # Make the source page a redirect if no revisions are left
413 $haveRevisions = $dbw->selectField(
414 'revision',
415 'rev_timestamp',
416 array( 'rev_page' => $this->mTargetID ),
417 __METHOD__,
418 array( 'FOR UPDATE' )
419 );
420 if ( !$haveRevisions ) {
421 if ( $this->mComment ) {
422 $comment = $this->msg(
423 'mergehistory-comment',
424 $targetTitle->getPrefixedText(),
425 $destTitle->getPrefixedText(),
426 $this->mComment
427 )->inContentLanguage()->text();
428 } else {
429 $comment = $this->msg(
430 'mergehistory-autocomment',
431 $targetTitle->getPrefixedText(),
432 $destTitle->getPrefixedText()
433 )->inContentLanguage()->text();
434 }
435
436 $contentHandler = ContentHandler::getForTitle( $targetTitle );
437 $redirectContent = $contentHandler->makeRedirectContent( $destTitle );
438
439 if ( $redirectContent ) {
440 $redirectPage = WikiPage::factory( $targetTitle );
441 $redirectRevision = new Revision( array(
442 'title' => $targetTitle,
443 'page' => $this->mTargetID,
444 'comment' => $comment,
445 'content' => $redirectContent ) );
446 $redirectRevision->insertOn( $dbw );
447 $redirectPage->updateRevisionOn( $dbw, $redirectRevision );
448
449 # Now, we record the link from the redirect to the new title.
450 # It should have no other outgoing links...
451 $dbw->delete( 'pagelinks', array( 'pl_from' => $this->mDestID ), __METHOD__ );
452 $dbw->insert( 'pagelinks',
453 array(
454 'pl_from' => $this->mDestID,
455 'pl_namespace' => $destTitle->getNamespace(),
456 'pl_title' => $destTitle->getDBkey() ),
457 __METHOD__
458 );
459 } else {
460 // would be nice to show a warning if we couldn't create a redirect
461 }
462 } else {
463 $targetTitle->invalidateCache(); // update histories
464 }
465 $destTitle->invalidateCache(); // update histories
466 # Check if this did anything
467 if ( !$count ) {
468 $this->getOutput()->addWikiMsg( 'mergehistory-fail' );
469
470 return false;
471 }
472 # Update our logs
473 $log = new LogPage( 'merge' );
474 $log->addEntry(
475 'merge', $targetTitle, $this->mComment,
476 array( $destTitle->getPrefixedText(), $timestampLimit ), $this->getUser()
477 );
478
479 # @TODO: message should use redirect=no
480 $this->getOutput()->addWikiMsg( 'mergehistory-success',
481 $targetTitle->getPrefixedText(), $destTitle->getPrefixedText(), $count );
482
483 wfRunHooks( 'ArticleMergeComplete', array( $targetTitle, $destTitle ) );
484
485 return true;
486 }
487
488 protected function getGroupName() {
489 return 'pagetools';
490 }
491 }
492
493 class MergeHistoryPager extends ReverseChronologicalPager {
494 /** @var IContextSource */
495 public $mForm;
496
497 /** @var array */
498 public $mConds;
499
500 function __construct( $form, $conds = array(), $source, $dest ) {
501 $this->mForm = $form;
502 $this->mConds = $conds;
503 $this->title = $source;
504 $this->articleID = $source->getArticleID();
505
506 $dbr = wfGetDB( DB_SLAVE );
507 $maxtimestamp = $dbr->selectField(
508 'revision',
509 'MIN(rev_timestamp)',
510 array( 'rev_page' => $dest->getArticleID() ),
511 __METHOD__
512 );
513 $this->maxTimestamp = $maxtimestamp;
514
515 parent::__construct( $form->getContext() );
516 }
517
518 function getStartBody() {
519 wfProfileIn( __METHOD__ );
520 # Do a link batch query
521 $this->mResult->seek( 0 );
522 $batch = new LinkBatch();
523 # Give some pointers to make (last) links
524 $this->mForm->prevId = array();
525 foreach ( $this->mResult as $row ) {
526 $batch->addObj( Title::makeTitleSafe( NS_USER, $row->user_name ) );
527 $batch->addObj( Title::makeTitleSafe( NS_USER_TALK, $row->user_name ) );
528
529 $rev_id = isset( $rev_id ) ? $rev_id : $row->rev_id;
530 if ( $rev_id > $row->rev_id ) {
531 $this->mForm->prevId[$rev_id] = $row->rev_id;
532 } elseif ( $rev_id < $row->rev_id ) {
533 $this->mForm->prevId[$row->rev_id] = $rev_id;
534 }
535
536 $rev_id = $row->rev_id;
537 }
538
539 $batch->execute();
540 $this->mResult->seek( 0 );
541
542 wfProfileOut( __METHOD__ );
543
544 return '';
545 }
546
547 function formatRow( $row ) {
548 return $this->mForm->formatRevisionRow( $row );
549 }
550
551 function getQueryInfo() {
552 $conds = $this->mConds;
553 $conds['rev_page'] = $this->articleID;
554 $conds[] = "rev_timestamp < {$this->maxTimestamp}";
555
556 return array(
557 'tables' => array( 'revision', 'page', 'user' ),
558 'fields' => array_merge( Revision::selectFields(), Revision::selectUserFields() ),
559 'conds' => $conds,
560 'join_conds' => array(
561 'page' => Revision::pageJoinCond(),
562 'user' => Revision::userJoinCond() )
563 );
564 }
565
566 function getIndexField() {
567 return 'rev_timestamp';
568 }
569 }