Merge "CurlHttpRequest: Follow redirects even under open_basedir"
[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->useTransactionalTimeLimit();
113
114 $this->checkPermissions();
115 $this->checkReadOnly();
116
117 $this->loadRequestParams();
118
119 $this->setHeaders();
120 $this->outputHeader();
121
122 if ( $this->mTargetID && $this->mDestID && $this->mAction == 'submit' && $this->mMerge ) {
123 $this->merge();
124
125 return;
126 }
127
128 if ( !$this->mSubmitted ) {
129 $this->showMergeForm();
130
131 return;
132 }
133
134 $errors = array();
135 if ( !$this->mTargetObj instanceof Title ) {
136 $errors[] = $this->msg( 'mergehistory-invalid-source' )->parseAsBlock();
137 } elseif ( !$this->mTargetObj->exists() ) {
138 $errors[] = $this->msg( 'mergehistory-no-source',
139 wfEscapeWikiText( $this->mTargetObj->getPrefixedText() )
140 )->parseAsBlock();
141 }
142
143 if ( !$this->mDestObj instanceof Title ) {
144 $errors[] = $this->msg( 'mergehistory-invalid-destination' )->parseAsBlock();
145 } elseif ( !$this->mDestObj->exists() ) {
146 $errors[] = $this->msg( 'mergehistory-no-destination',
147 wfEscapeWikiText( $this->mDestObj->getPrefixedText() )
148 )->parseAsBlock();
149 }
150
151 if ( $this->mTargetObj && $this->mDestObj && $this->mTargetObj->equals( $this->mDestObj ) ) {
152 $errors[] = $this->msg( 'mergehistory-same-destination' )->parseAsBlock();
153 }
154
155 if ( count( $errors ) ) {
156 $this->showMergeForm();
157 $this->getOutput()->addHTML( implode( "\n", $errors ) );
158 } else {
159 $this->showHistory();
160 }
161 }
162
163 function showMergeForm() {
164 $out = $this->getOutput();
165 $out->addWikiMsg( 'mergehistory-header' );
166
167 $out->addHTML(
168 Xml::openElement( 'form', array(
169 'method' => 'get',
170 'action' => wfScript() ) ) .
171 '<fieldset>' .
172 Xml::element( 'legend', array(),
173 $this->msg( 'mergehistory-box' )->text() ) .
174 Html::hidden( 'title', $this->getPageTitle()->getPrefixedDBkey() ) .
175 Html::hidden( 'submitted', '1' ) .
176 Html::hidden( 'mergepoint', $this->mTimestamp ) .
177 Xml::openElement( 'table' ) .
178 '<tr>
179 <td>' . Xml::label( $this->msg( 'mergehistory-from' )->text(), 'target' ) . '</td>
180 <td>' . Xml::input( 'target', 30, $this->mTarget, array( 'id' => 'target' ) ) . '</td>
181 </tr><tr>
182 <td>' . Xml::label( $this->msg( 'mergehistory-into' )->text(), 'dest' ) . '</td>
183 <td>' . Xml::input( 'dest', 30, $this->mDest, array( 'id' => 'dest' ) ) . '</td>
184 </tr><tr><td>' .
185 Xml::submitButton( $this->msg( 'mergehistory-go' )->text() ) .
186 '</td></tr>' .
187 Xml::closeElement( 'table' ) .
188 '</fieldset>' .
189 '</form>'
190 );
191
192 $this->addHelpLink( 'Help:Merge history' );
193 }
194
195 private function showHistory() {
196 $this->showMergeForm();
197
198 # List all stored revisions
199 $revisions = new MergeHistoryPager(
200 $this, array(), $this->mTargetObj, $this->mDestObj
201 );
202 $haveRevisions = $revisions && $revisions->getNumRows() > 0;
203
204 $out = $this->getOutput();
205 $titleObj = $this->getPageTitle();
206 $action = $titleObj->getLocalURL( array( 'action' => 'submit' ) );
207 # Start the form here
208 $top = Xml::openElement(
209 'form',
210 array(
211 'method' => 'post',
212 'action' => $action,
213 'id' => 'merge'
214 )
215 );
216 $out->addHTML( $top );
217
218 if ( $haveRevisions ) {
219 # Format the user-visible controls (comment field, submission button)
220 # in a nice little table
221 $table =
222 Xml::openElement( 'fieldset' ) .
223 $this->msg( 'mergehistory-merge', $this->mTargetObj->getPrefixedText(),
224 $this->mDestObj->getPrefixedText() )->parse() .
225 Xml::openElement( 'table', array( 'id' => 'mw-mergehistory-table' ) ) .
226 '<tr>
227 <td class="mw-label">' .
228 Xml::label( $this->msg( 'mergehistory-reason' )->text(), 'wpComment' ) .
229 '</td>
230 <td class="mw-input">' .
231 Xml::input( 'wpComment', 50, $this->mComment, array( 'id' => 'wpComment' ) ) .
232 '</td>
233 </tr>
234 <tr>
235 <td>&#160;</td>
236 <td class="mw-submit">' .
237 Xml::submitButton(
238 $this->msg( 'mergehistory-submit' )->text(),
239 array( 'name' => 'merge', 'id' => 'mw-merge-submit' )
240 ) .
241 '</td>
242 </tr>' .
243 Xml::closeElement( 'table' ) .
244 Xml::closeElement( 'fieldset' );
245
246 $out->addHTML( $table );
247 }
248
249 $out->addHTML(
250 '<h2 id="mw-mergehistory">' .
251 $this->msg( 'mergehistory-list' )->escaped() . "</h2>\n"
252 );
253
254 if ( $haveRevisions ) {
255 $out->addHTML( $revisions->getNavigationBar() );
256 $out->addHTML( '<ul>' );
257 $out->addHTML( $revisions->getBody() );
258 $out->addHTML( '</ul>' );
259 $out->addHTML( $revisions->getNavigationBar() );
260 } else {
261 $out->addWikiMsg( 'mergehistory-empty' );
262 }
263
264 # Show relevant lines from the merge log:
265 $mergeLogPage = new LogPage( 'merge' );
266 $out->addHTML( '<h2>' . $mergeLogPage->getName()->escaped() . "</h2>\n" );
267 LogEventsList::showLogExtract( $out, 'merge', $this->mTargetObj );
268
269 # When we submit, go by page ID to avoid some nasty but unlikely collisions.
270 # Such would happen if a page was renamed after the form loaded, but before submit
271 $misc = Html::hidden( 'targetID', $this->mTargetObj->getArticleID() );
272 $misc .= Html::hidden( 'destID', $this->mDestObj->getArticleID() );
273 $misc .= Html::hidden( 'target', $this->mTarget );
274 $misc .= Html::hidden( 'dest', $this->mDest );
275 $misc .= Html::hidden( 'wpEditToken', $this->getUser()->getEditToken() );
276 $misc .= Xml::closeElement( 'form' );
277 $out->addHTML( $misc );
278
279 return true;
280 }
281
282 function formatRevisionRow( $row ) {
283 $rev = new Revision( $row );
284
285 $stxt = '';
286 $last = $this->message['last'];
287
288 $ts = wfTimestamp( TS_MW, $row->rev_timestamp );
289 $checkBox = Xml::radio( 'mergepoint', $ts, ( $this->mTimestamp === $ts ) );
290
291 $user = $this->getUser();
292
293 $pageLink = Linker::linkKnown(
294 $rev->getTitle(),
295 htmlspecialchars( $this->getLanguage()->userTimeAndDate( $ts, $user ) ),
296 array(),
297 array( 'oldid' => $rev->getId() )
298 );
299 if ( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
300 $pageLink = '<span class="history-deleted">' . $pageLink . '</span>';
301 }
302
303 # Last link
304 if ( !$rev->userCan( Revision::DELETED_TEXT, $user ) ) {
305 $last = $this->message['last'];
306 } elseif ( isset( $this->prevId[$row->rev_id] ) ) {
307 $last = Linker::linkKnown(
308 $rev->getTitle(),
309 $this->message['last'],
310 array(),
311 array(
312 'diff' => $row->rev_id,
313 'oldid' => $this->prevId[$row->rev_id]
314 )
315 );
316 }
317
318 $userLink = Linker::revUserTools( $rev );
319
320 $size = $row->rev_len;
321 if ( !is_null( $size ) ) {
322 $stxt = Linker::formatRevisionSize( $size );
323 }
324 $comment = Linker::revComment( $rev );
325
326 return Html::rawElement( 'li', array(),
327 $this->msg( 'mergehistory-revisionrow' )
328 ->rawParams( $checkBox, $last, $pageLink, $userLink, $stxt, $comment )->escaped() );
329 }
330
331 /**
332 * Actually attempt the history move
333 *
334 * @todo if all versions of page A are moved to B and then a user
335 * tries to do a reverse-merge via the "unmerge" log link, then page
336 * A will still be a redirect (as it was after the original merge),
337 * though it will have the old revisions back from before (as expected).
338 * The user may have to "undo" the redirect manually to finish the "unmerge".
339 * Maybe this should delete redirects at the target page of merges?
340 *
341 * @return bool Success
342 */
343 function merge() {
344 # Get the titles directly from the IDs, in case the target page params
345 # were spoofed. The queries are done based on the IDs, so it's best to
346 # keep it consistent...
347 $targetTitle = Title::newFromID( $this->mTargetID );
348 $destTitle = Title::newFromID( $this->mDestID );
349 if ( is_null( $targetTitle ) || is_null( $destTitle ) ) {
350 return false; // validate these
351 }
352 if ( $targetTitle->getArticleID() == $destTitle->getArticleID() ) {
353 return false;
354 }
355 # Verify that this timestamp is valid
356 # Must be older than the destination page
357 $dbw = wfGetDB( DB_MASTER );
358 # Get timestamp into DB format
359 $this->mTimestamp = $this->mTimestamp ? $dbw->timestamp( $this->mTimestamp ) : '';
360 # Max timestamp should be min of destination page
361 $maxtimestamp = $dbw->selectField(
362 'revision',
363 'MIN(rev_timestamp)',
364 array( 'rev_page' => $this->mDestID ),
365 __METHOD__
366 );
367 # Destination page must exist with revisions
368 if ( !$maxtimestamp ) {
369 $this->getOutput()->addWikiMsg( 'mergehistory-fail' );
370
371 return false;
372 }
373 # Get the latest timestamp of the source
374 $lasttimestamp = $dbw->selectField(
375 array( 'page', 'revision' ),
376 'rev_timestamp',
377 array( 'page_id' => $this->mTargetID, 'page_latest = rev_id' ),
378 __METHOD__
379 );
380 # $this->mTimestamp must be older than $maxtimestamp
381 if ( $this->mTimestamp >= $maxtimestamp ) {
382 $this->getOutput()->addWikiMsg( 'mergehistory-fail' );
383
384 return false;
385 }
386 # Get the timestamp pivot condition
387 if ( $this->mTimestamp ) {
388 $timewhere = "rev_timestamp <= {$this->mTimestamp}";
389 $timestampLimit = wfTimestamp( TS_MW, $this->mTimestamp );
390 } else {
391 $timewhere = "rev_timestamp <= {$maxtimestamp}";
392 $timestampLimit = wfTimestamp( TS_MW, $lasttimestamp );
393 }
394 # Check that there are not too many revisions to move
395 $limit = 5000; // avoid too much slave lag
396 $count = $dbw->selectRowCount( 'revision', '1',
397 array( 'rev_page' => $this->mTargetID, $timewhere ),
398 __METHOD__,
399 array( 'LIMIT' => $limit + 1 )
400 );
401 if ( $count > $limit ) {
402 $this->getOutput()->addWikiMsg( 'mergehistory-fail-toobig' );
403
404 return false;
405 }
406 # Do the moving...
407 $dbw->update(
408 'revision',
409 array( 'rev_page' => $this->mDestID ),
410 array( 'rev_page' => $this->mTargetID, $timewhere ),
411 __METHOD__
412 );
413
414 $count = $dbw->affectedRows();
415 # Make the source page a redirect if no revisions are left
416 $haveRevisions = $dbw->selectField(
417 'revision',
418 'rev_timestamp',
419 array( 'rev_page' => $this->mTargetID ),
420 __METHOD__,
421 array( 'FOR UPDATE' )
422 );
423 if ( !$haveRevisions ) {
424 if ( $this->mComment ) {
425 $comment = $this->msg(
426 'mergehistory-comment',
427 $targetTitle->getPrefixedText(),
428 $destTitle->getPrefixedText(),
429 $this->mComment
430 )->inContentLanguage()->text();
431 } else {
432 $comment = $this->msg(
433 'mergehistory-autocomment',
434 $targetTitle->getPrefixedText(),
435 $destTitle->getPrefixedText()
436 )->inContentLanguage()->text();
437 }
438
439 $contentHandler = ContentHandler::getForTitle( $targetTitle );
440 $redirectContent = $contentHandler->makeRedirectContent( $destTitle );
441
442 if ( $redirectContent ) {
443 $redirectPage = WikiPage::factory( $targetTitle );
444 $redirectRevision = new Revision( array(
445 'title' => $targetTitle,
446 'page' => $this->mTargetID,
447 'comment' => $comment,
448 'content' => $redirectContent ) );
449 $redirectRevision->insertOn( $dbw );
450 $redirectPage->updateRevisionOn( $dbw, $redirectRevision );
451
452 # Now, we record the link from the redirect to the new title.
453 # It should have no other outgoing links...
454 $dbw->delete( 'pagelinks', array( 'pl_from' => $this->mDestID ), __METHOD__ );
455 $dbw->insert( 'pagelinks',
456 array(
457 'pl_from' => $this->mDestID,
458 'pl_from_namespace' => $destTitle->getNamespace(),
459 'pl_namespace' => $destTitle->getNamespace(),
460 'pl_title' => $destTitle->getDBkey() ),
461 __METHOD__
462 );
463 } else {
464 // would be nice to show a warning if we couldn't create a redirect
465 }
466 } else {
467 $targetTitle->invalidateCache(); // update histories
468 }
469 $destTitle->invalidateCache(); // update histories
470 # Check if this did anything
471 if ( !$count ) {
472 $this->getOutput()->addWikiMsg( 'mergehistory-fail' );
473
474 return false;
475 }
476 # Update our logs
477 $logEntry = new ManualLogEntry( 'merge', 'merge' );
478 $logEntry->setPerformer( $this->getUser() );
479 $logEntry->setComment( $this->mComment );
480 $logEntry->setTarget( $targetTitle );
481 $logEntry->setParameters( array(
482 '4::dest' => $destTitle->getPrefixedText(),
483 '5::mergepoint' => $timestampLimit
484 ) );
485 $logId = $logEntry->insert();
486 $logEntry->publish( $logId );
487
488 # @todo message should use redirect=no
489 $this->getOutput()->addWikiText( $this->msg( 'mergehistory-success',
490 $targetTitle->getPrefixedText(), $destTitle->getPrefixedText() )->numParams(
491 $count )->text() );
492
493 Hooks::run( 'ArticleMergeComplete', array( $targetTitle, $destTitle ) );
494
495 return true;
496 }
497
498 protected function getGroupName() {
499 return 'pagetools';
500 }
501 }
502
503 class MergeHistoryPager extends ReverseChronologicalPager {
504 /** @var IContextSource */
505 public $mForm;
506
507 /** @var array */
508 public $mConds;
509
510 function __construct( $form, $conds, $source, $dest ) {
511 $this->mForm = $form;
512 $this->mConds = $conds;
513 $this->title = $source;
514 $this->articleID = $source->getArticleID();
515
516 $dbr = wfGetDB( DB_SLAVE );
517 $maxtimestamp = $dbr->selectField(
518 'revision',
519 'MIN(rev_timestamp)',
520 array( 'rev_page' => $dest->getArticleID() ),
521 __METHOD__
522 );
523 $this->maxTimestamp = $maxtimestamp;
524
525 parent::__construct( $form->getContext() );
526 }
527
528 function getStartBody() {
529 # Do a link batch query
530 $this->mResult->seek( 0 );
531 $batch = new LinkBatch();
532 # Give some pointers to make (last) links
533 $this->mForm->prevId = array();
534 foreach ( $this->mResult as $row ) {
535 $batch->addObj( Title::makeTitleSafe( NS_USER, $row->user_name ) );
536 $batch->addObj( Title::makeTitleSafe( NS_USER_TALK, $row->user_name ) );
537
538 $rev_id = isset( $rev_id ) ? $rev_id : $row->rev_id;
539 if ( $rev_id > $row->rev_id ) {
540 $this->mForm->prevId[$rev_id] = $row->rev_id;
541 } elseif ( $rev_id < $row->rev_id ) {
542 $this->mForm->prevId[$row->rev_id] = $rev_id;
543 }
544
545 $rev_id = $row->rev_id;
546 }
547
548 $batch->execute();
549 $this->mResult->seek( 0 );
550
551 return '';
552 }
553
554 function formatRow( $row ) {
555 return $this->mForm->formatRevisionRow( $row );
556 }
557
558 function getQueryInfo() {
559 $conds = $this->mConds;
560 $conds['rev_page'] = $this->articleID;
561 $conds[] = "rev_timestamp < " . $this->mDb->addQuotes( $this->maxTimestamp );
562
563 return array(
564 'tables' => array( 'revision', 'page', 'user' ),
565 'fields' => array_merge( Revision::selectFields(), Revision::selectUserFields() ),
566 'conds' => $conds,
567 'join_conds' => array(
568 'page' => Revision::pageJoinCond(),
569 'user' => Revision::userJoinCond() )
570 );
571 }
572
573 function getIndexField() {
574 return 'rev_timestamp';
575 }
576 }