Refactor MergeHistory to subclass SpecialPage. Ohai unloved code :)
[lhc/web/wiklou.git] / includes / specials / SpecialMergeHistory.php
1 <?php
2 /**
3 * Special page allowing users with the appropriate permissions to
4 * merge article histories, with some restrictions
5 *
6 * @ingroup SpecialPage
7 */
8 class SpecialMergeHistory extends SpecialPage {
9 var $mAction, $mTarget, $mDest, $mTimestamp, $mTargetID, $mDestID, $mComment;
10 var $mTargetObj, $mDestObj;
11
12 public function __construct() {
13 parent::__construct( 'MergeHistory', 'mergehistory' );
14 }
15
16 private function loadRequestParams( $request ) {
17 global $wgUser;
18 $this->mAction = $request->getVal( 'action' );
19 $this->mTarget = $request->getVal( 'target' );
20 $this->mDest = $request->getVal( 'dest' );
21 $this->mSubmitted = $request->getBool( 'submitted' );
22
23 $this->mTargetID = intval( $request->getVal( 'targetID' ) );
24 $this->mDestID = intval( $request->getVal( 'destID' ) );
25 $this->mTimestamp = $request->getVal( 'mergepoint' );
26 if( !preg_match("/[0-9]{14}/",$this->mTimestamp) ) {
27 $this->mTimestamp = '';
28 }
29 $this->mComment = $request->getText( 'wpComment' );
30
31 $this->mMerge = $request->wasPosted() && $wgUser->matchEditToken( $request->getVal( 'wpEditToken' ) );
32 // target page
33 if( $this->mSubmitted ) {
34 $this->mTargetObj = Title::newFromURL( $this->mTarget );
35 $this->mDestObj = Title::newFromURL( $this->mDest );
36 } else {
37 $this->mTargetObj = null;
38 $this->mDestObj = null;
39 }
40 $this->preCacheMessages();
41 }
42
43 /**
44 * As we use the same small set of messages in various methods and that
45 * they are called often, we call them once and save them in $this->message
46 */
47 function preCacheMessages() {
48 // Precache various messages
49 if( !isset( $this->message ) ) {
50 $this->message['last'] = wfMsgExt( 'last', array( 'escape') );
51 }
52 }
53
54 function execute( $par = '' ) {
55 global $wgOut, $wgRequest, $wgUser;
56
57 if( !$wgUser->isAllowed( 'mergehistory' ) ) {
58 $wgOut->permissionRequired( 'mergehistory' );
59 return;
60 }
61
62 $this->loadRequestParams( $wgRequest );
63
64 $wgOut->setPagetitle( wfMsgHtml( "mergehistory" ) );
65
66 if( $this->mTargetID && $this->mDestID && $this->mAction=="submit" && $this->mMerge ) {
67 return $this->merge();
68 }
69
70 if ( !$this->mSubmitted ) {
71 $this->showMergeForm();
72 return;
73 }
74
75 $errors = array();
76 if ( !$this->mTargetObj instanceof Title ) {
77 $errors[] = wfMsgExt( 'mergehistory-invalid-source', array( 'parse' ) );
78 } elseif( !$this->mTargetObj->exists() ) {
79 $errors[] = wfMsgExt( 'mergehistory-no-source', array( 'parse' ),
80 wfEscapeWikiText( $this->mTargetObj->getPrefixedText() )
81 );
82 }
83
84 if ( !$this->mDestObj instanceof Title) {
85 $errors[] = wfMsgExt( 'mergehistory-invalid-destination', array( 'parse' ) );
86 } elseif( !$this->mDestObj->exists() ) {
87 $errors[] = wfMsgExt( 'mergehistory-no-destination', array( 'parse' ),
88 wfEscapeWikiText( $this->mDestObj->getPrefixedText() )
89 );
90 }
91
92 if ( $this->mTargetObj && $this->mDestObj && $this->mTargetObj->equals( $this->mDestObj ) ) {
93 $errors[] = wfMsgExt( 'mergehistory-same-destination', array( 'parse' ) );
94 }
95
96 if ( count( $errors ) ) {
97 $this->showMergeForm();
98 $wgOut->addHTML( implode( "\n", $errors ) );
99 } else {
100 $this->showHistory();
101 }
102
103 }
104
105 function showMergeForm() {
106 global $wgOut, $wgScript;
107
108 $wgOut->addWikiMsg( 'mergehistory-header' );
109
110 $wgOut->addHTML(
111 Xml::openElement( 'form', array(
112 'method' => 'get',
113 'action' => $wgScript ) ) .
114 '<fieldset>' .
115 Xml::element( 'legend', array(),
116 wfMsg( 'mergehistory-box' ) ) .
117 Xml::hidden( 'title', $this->getTitle()->getPrefixedDbKey() ) .
118 Xml::hidden( 'submitted', '1' ) .
119 Xml::hidden( 'mergepoint', $this->mTimestamp ) .
120 Xml::openElement( 'table' ) .
121 "<tr>
122 <td>".Xml::label( wfMsg( 'mergehistory-from' ), 'target' )."</td>
123 <td>".Xml::input( 'target', 30, $this->mTarget, array('id'=>'target') )."</td>
124 </tr><tr>
125 <td>".Xml::label( wfMsg( 'mergehistory-into' ), 'dest' )."</td>
126 <td>".Xml::input( 'dest', 30, $this->mDest, array('id'=>'dest') )."</td>
127 </tr><tr><td>" .
128 Xml::submitButton( wfMsg( 'mergehistory-go' ) ) .
129 "</td></tr>" .
130 Xml::closeElement( 'table' ) .
131 '</fieldset>' .
132 '</form>' );
133 }
134
135 private function showHistory() {
136 global $wgLang, $wgUser, $wgOut;
137
138 $this->sk = $wgUser->getSkin();
139
140 $wgOut->setPagetitle( wfMsg( "mergehistory" ) );
141
142 $this->showMergeForm();
143
144 # List all stored revisions
145 $revisions = new MergeHistoryPager( $this, array(), $this->mTargetObj, $this->mDestObj );
146 $haveRevisions = $revisions && $revisions->getNumRows() > 0;
147
148 $titleObj = $this->getTitle();
149 $action = $titleObj->getLocalURL( array( 'action' => 'submit' ) );
150 # Start the form here
151 $top = Xml::openElement( 'form', array( 'method' => 'post', 'action' => $action, 'id' => 'merge' ) );
152 $wgOut->addHTML( $top );
153
154 if( $haveRevisions ) {
155 # Format the user-visible controls (comment field, submission button)
156 # in a nice little table
157 $table =
158 Xml::openElement( 'fieldset' ) .
159 wfMsgExt( 'mergehistory-merge', array('parseinline'),
160 $this->mTargetObj->getPrefixedText(), $this->mDestObj->getPrefixedText() ) .
161 Xml::openElement( 'table', array( 'id' => 'mw-mergehistory-table' ) ) .
162 "<tr>
163 <td class='mw-label'>" .
164 Xml::label( wfMsg( 'mergehistory-reason' ), 'wpComment' ) .
165 "</td>
166 <td class='mw-input'>" .
167 Xml::input( 'wpComment', 50, $this->mComment, array('id' => 'wpComment') ) .
168 "</td>
169 </tr>
170 <tr>
171 <td>&nbsp;</td>
172 <td class='mw-submit'>" .
173 Xml::submitButton( wfMsg( 'mergehistory-submit' ), array( 'name' => 'merge', 'id' => 'mw-merge-submit' ) ) .
174 "</td>
175 </tr>" .
176 Xml::closeElement( 'table' ) .
177 Xml::closeElement( 'fieldset' );
178
179 $wgOut->addHTML( $table );
180 }
181
182 $wgOut->addHTML( "<h2 id=\"mw-mergehistory\">" . wfMsgHtml( "mergehistory-list" ) . "</h2>\n" );
183
184 if( $haveRevisions ) {
185 $wgOut->addHTML( $revisions->getNavigationBar() );
186 $wgOut->addHTML( "<ul>" );
187 $wgOut->addHTML( $revisions->getBody() );
188 $wgOut->addHTML( "</ul>" );
189 $wgOut->addHTML( $revisions->getNavigationBar() );
190 } else {
191 $wgOut->addWikiMsg( "mergehistory-empty" );
192 }
193
194 # Show relevant lines from the deletion log:
195 $wgOut->addHTML( "<h2>" . htmlspecialchars( LogPage::logName( 'merge' ) ) . "</h2>\n" );
196 LogEventsList::showLogExtract( $wgOut, 'merge', $this->mTargetObj->getPrefixedText() );
197
198 # When we submit, go by page ID to avoid some nasty but unlikely collisions.
199 # Such would happen if a page was renamed after the form loaded, but before submit
200 $misc = Xml::hidden( 'targetID', $this->mTargetObj->getArticleID() );
201 $misc .= Xml::hidden( 'destID', $this->mDestObj->getArticleID() );
202 $misc .= Xml::hidden( 'target', $this->mTarget );
203 $misc .= Xml::hidden( 'dest', $this->mDest );
204 $misc .= Xml::hidden( 'wpEditToken', $wgUser->editToken() );
205 $misc .= Xml::closeElement( 'form' );
206 $wgOut->addHTML( $misc );
207
208 return true;
209 }
210
211 function formatRevisionRow( $row ) {
212 global $wgLang;
213
214 $rev = new Revision( $row );
215
216 $stxt = '';
217 $last = $this->message['last'];
218
219 $ts = wfTimestamp( TS_MW, $row->rev_timestamp );
220 $checkBox = Xml::radio( "mergepoint", $ts, false );
221
222 $pageLink = $this->sk->linkKnown(
223 $rev->getTitle(),
224 htmlspecialchars( $wgLang->timeanddate( $ts ) ),
225 array(),
226 array( 'oldid' => $rev->getId() )
227 );
228 if( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
229 $pageLink = '<span class="history-deleted">' . $pageLink . '</span>';
230 }
231
232 # Last link
233 if( !$rev->userCan( Revision::DELETED_TEXT ) )
234 $last = $this->message['last'];
235 else if( isset($this->prevId[$row->rev_id]) )
236 $last = $this->sk->linkKnown(
237 $rev->getTitle(),
238 $this->message['last'],
239 array(),
240 array(
241 'diff' => $row->rev_id,
242 'oldid' => $this->prevId[$row->rev_id]
243 )
244 );
245
246 $userLink = $this->sk->revUserTools( $rev );
247
248 if(!is_null($size = $row->rev_len)) {
249 $stxt = $this->sk->formatRevisionSize( $size );
250 }
251 $comment = $this->sk->revComment( $rev );
252
253 return "<li>$checkBox ($last) $pageLink . . $userLink $stxt $comment</li>";
254 }
255
256 /**
257 * Fetch revision text link if it's available to all users
258 * @return string
259 */
260 function getPageLink( $row, $titleObj, $ts, $target ) {
261 global $wgLang;
262
263 if( !$this->userCan($row, Revision::DELETED_TEXT) ) {
264 return '<span class="history-deleted">' . $wgLang->timeanddate( $ts, true ) . '</span>';
265 } else {
266 $link = $this->sk->linkKnown(
267 $titleObj,
268 $wgLang->timeanddate( $ts, true ),
269 array(),
270 array(
271 'target' => $target,
272 'timestamp' => $ts
273 )
274 );
275 if( $this->isDeleted($row, Revision::DELETED_TEXT) )
276 $link = '<span class="history-deleted">' . $link . '</span>';
277 return $link;
278 }
279 }
280
281 function merge() {
282 global $wgOut;
283 # Get the titles directly from the IDs, in case the target page params
284 # were spoofed. The queries are done based on the IDs, so it's best to
285 # keep it consistent...
286 $targetTitle = Title::newFromID( $this->mTargetID );
287 $destTitle = Title::newFromID( $this->mDestID );
288 if( is_null($targetTitle) || is_null($destTitle) )
289 return false; // validate these
290 if( $targetTitle->getArticleId() == $destTitle->getArticleId() )
291 return false;
292 # Verify that this timestamp is valid
293 # Must be older than the destination page
294 $dbw = wfGetDB( DB_MASTER );
295 # Get timestamp into DB format
296 $this->mTimestamp = $this->mTimestamp ? $dbw->timestamp($this->mTimestamp) : '';
297 # Max timestamp should be min of destination page
298 $maxtimestamp = $dbw->selectField( 'revision', 'MIN(rev_timestamp)',
299 array('rev_page' => $this->mDestID ),
300 __METHOD__ );
301 # Destination page must exist with revisions
302 if( !$maxtimestamp ) {
303 $wgOut->addWikiMsg('mergehistory-fail');
304 return false;
305 }
306 # Get the latest timestamp of the source
307 $lasttimestamp = $dbw->selectField( array('page','revision'),
308 'rev_timestamp',
309 array('page_id' => $this->mTargetID, 'page_latest = rev_id' ),
310 __METHOD__ );
311 # $this->mTimestamp must be older than $maxtimestamp
312 if( $this->mTimestamp >= $maxtimestamp ) {
313 $wgOut->addWikiMsg('mergehistory-fail');
314 return false;
315 }
316 # Update the revisions
317 if( $this->mTimestamp ) {
318 $timewhere = "rev_timestamp <= {$this->mTimestamp}";
319 $TimestampLimit = wfTimestamp(TS_MW,$this->mTimestamp);
320 } else {
321 $timewhere = "rev_timestamp <= {$maxtimestamp}";
322 $TimestampLimit = wfTimestamp(TS_MW,$lasttimestamp);
323 }
324 # Do the moving...
325 $dbw->update( 'revision',
326 array( 'rev_page' => $this->mDestID ),
327 array( 'rev_page' => $this->mTargetID,
328 $timewhere ),
329 __METHOD__ );
330
331 $count = $dbw->affectedRows();
332 # Make the source page a redirect if no revisions are left
333 $haveRevisions = $dbw->selectField( 'revision',
334 'rev_timestamp',
335 array( 'rev_page' => $this->mTargetID ),
336 __METHOD__,
337 array( 'FOR UPDATE' ) );
338 if( !$haveRevisions ) {
339 if( $this->mComment ) {
340 $comment = wfMsgForContent( 'mergehistory-comment', $targetTitle->getPrefixedText(),
341 $destTitle->getPrefixedText(), $this->mComment );
342 } else {
343 $comment = wfMsgForContent( 'mergehistory-autocomment', $targetTitle->getPrefixedText(),
344 $destTitle->getPrefixedText() );
345 }
346 $mwRedir = MagicWord::get( 'redirect' );
347 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $destTitle->getPrefixedText() . "]]\n";
348 $redirectArticle = new Article( $targetTitle );
349 $redirectRevision = new Revision( array(
350 'page' => $this->mTargetID,
351 'comment' => $comment,
352 'text' => $redirectText ) );
353 $redirectRevision->insertOn( $dbw );
354 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision );
355
356 # Now, we record the link from the redirect to the new title.
357 # It should have no other outgoing links...
358 $dbw->delete( 'pagelinks', array( 'pl_from' => $this->mDestID ), __METHOD__ );
359 $dbw->insert( 'pagelinks',
360 array(
361 'pl_from' => $this->mDestID,
362 'pl_namespace' => $destTitle->getNamespace(),
363 'pl_title' => $destTitle->getDBkey() ),
364 __METHOD__ );
365 } else {
366 $targetTitle->invalidateCache(); // update histories
367 }
368 $destTitle->invalidateCache(); // update histories
369 # Check if this did anything
370 if( !$count ) {
371 $wgOut->addWikiMsg('mergehistory-fail');
372 return false;
373 }
374 # Update our logs
375 $log = new LogPage( 'merge' );
376 $log->addEntry( 'merge', $targetTitle, $this->mComment,
377 array($destTitle->getPrefixedText(),$TimestampLimit) );
378
379 $wgOut->addHTML( wfMsgExt( 'mergehistory-success', array('parseinline'),
380 $targetTitle->getPrefixedText(), $destTitle->getPrefixedText(), $count ) );
381
382 wfRunHooks( 'ArticleMergeComplete', array( $targetTitle, $destTitle ) );
383
384 return true;
385 }
386 }
387
388 class MergeHistoryPager extends ReverseChronologicalPager {
389 public $mForm, $mConds;
390
391 function __construct( $form, $conds = array(), $source, $dest ) {
392 $this->mForm = $form;
393 $this->mConds = $conds;
394 $this->title = $source;
395 $this->articleID = $source->getArticleID();
396
397 $dbr = wfGetDB( DB_SLAVE );
398 $maxtimestamp = $dbr->selectField( 'revision', 'MIN(rev_timestamp)',
399 array('rev_page' => $dest->getArticleID() ),
400 __METHOD__ );
401 $this->maxTimestamp = $maxtimestamp;
402
403 parent::__construct();
404 }
405
406 function getStartBody() {
407 wfProfileIn( __METHOD__ );
408 # Do a link batch query
409 $this->mResult->seek( 0 );
410 $batch = new LinkBatch();
411 # Give some pointers to make (last) links
412 $this->mForm->prevId = array();
413 while( $row = $this->mResult->fetchObject() ) {
414 $batch->addObj( Title::makeTitleSafe( NS_USER, $row->rev_user_text ) );
415 $batch->addObj( Title::makeTitleSafe( NS_USER_TALK, $row->rev_user_text ) );
416
417 $rev_id = isset($rev_id) ? $rev_id : $row->rev_id;
418 if( $rev_id > $row->rev_id )
419 $this->mForm->prevId[$rev_id] = $row->rev_id;
420 else if( $rev_id < $row->rev_id )
421 $this->mForm->prevId[$row->rev_id] = $rev_id;
422
423 $rev_id = $row->rev_id;
424 }
425
426 $batch->execute();
427 $this->mResult->seek( 0 );
428
429 wfProfileOut( __METHOD__ );
430 return '';
431 }
432
433 function formatRow( $row ) {
434 $block = new Block;
435 return $this->mForm->formatRevisionRow( $row );
436 }
437
438 function getQueryInfo() {
439 $conds = $this->mConds;
440 $conds['rev_page'] = $this->articleID;
441 $conds[] = 'page_id = rev_page';
442 $conds[] = "rev_timestamp < {$this->maxTimestamp}";
443 return array(
444 'tables' => array('revision','page'),
445 'fields' => array( 'rev_minor_edit', 'rev_timestamp', 'rev_user', 'rev_user_text', 'rev_comment',
446 'rev_id', 'rev_page', 'rev_parent_id', 'rev_text_id', 'rev_len', 'rev_deleted' ),
447 'conds' => $conds
448 );
449 }
450
451 function getIndexField() {
452 return 'rev_timestamp';
453 }
454 }