fbf43e0f3d24f49e1e5c0d8e79471f36faf63820
[lhc/web/wiklou.git] / includes / actions / HistoryAction.php
1 <?php
2 /**
3 * Page history
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 Actions
22 */
23
24 use MediaWiki\MediaWikiServices;
25 use Wikimedia\Rdbms\ResultWrapper;
26 use Wikimedia\Rdbms\FakeResultWrapper;
27
28 /**
29 * This class handles printing the history page for an article. In order to
30 * be efficient, it uses timestamps rather than offsets for paging, to avoid
31 * costly LIMIT,offset queries.
32 *
33 * Construct it by passing in an Article, and call $h->history() to print the
34 * history.
35 *
36 * @ingroup Actions
37 */
38 class HistoryAction extends FormlessAction {
39 const DIR_PREV = 0;
40 const DIR_NEXT = 1;
41
42 /** @var array Array of message keys and strings */
43 public $message;
44
45 public function getName() {
46 return 'history';
47 }
48
49 public function requiresWrite() {
50 return false;
51 }
52
53 public function requiresUnblock() {
54 return false;
55 }
56
57 protected function getPageTitle() {
58 return $this->msg( 'history-title', $this->getTitle()->getPrefixedText() )->text();
59 }
60
61 protected function getDescription() {
62 // Creation of a subtitle link pointing to [[Special:Log]]
63 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
64 $subtitle = $linkRenderer->makeKnownLink(
65 SpecialPage::getTitleFor( 'Log' ),
66 $this->msg( 'viewpagelogs' )->text(),
67 [],
68 [ 'page' => $this->getTitle()->getPrefixedText() ]
69 );
70
71 $links = [];
72 // Allow extensions to add more links
73 Hooks::run( 'HistoryPageToolLinks', [ $this->getContext(), $linkRenderer, &$links ] );
74 if ( $links ) {
75 $subtitle .= ''
76 . $this->msg( 'word-separator' )->escaped()
77 . $this->msg( 'parentheses' )
78 ->rawParams( $this->getLanguage()->pipeList( $links ) )
79 ->escaped();
80 }
81 return $subtitle;
82 }
83
84 /**
85 * @return WikiPage|Article|ImagePage|CategoryPage|Page The Article object we are working on.
86 */
87 public function getArticle() {
88 return $this->page;
89 }
90
91 /**
92 * As we use the same small set of messages in various methods and that
93 * they are called often, we call them once and save them in $this->message
94 */
95 private function preCacheMessages() {
96 // Precache various messages
97 if ( !isset( $this->message ) ) {
98 $msgs = [ 'cur', 'last', 'pipe-separator' ];
99 foreach ( $msgs as $msg ) {
100 $this->message[$msg] = $this->msg( $msg )->escaped();
101 }
102 }
103 }
104
105 /**
106 * Print the history page for an article.
107 */
108 function onView() {
109 $out = $this->getOutput();
110 $request = $this->getRequest();
111
112 /**
113 * Allow client caching.
114 */
115 if ( $out->checkLastModified( $this->page->getTouched() ) ) {
116 return; // Client cache fresh and headers sent, nothing more to do.
117 }
118
119 $this->preCacheMessages();
120 $config = $this->context->getConfig();
121
122 # Fill in the file cache if not set already
123 if ( HTMLFileCache::useFileCache( $this->getContext() ) ) {
124 $cache = new HTMLFileCache( $this->getTitle(), 'history' );
125 if ( !$cache->isCacheGood( /* Assume up to date */ ) ) {
126 ob_start( [ &$cache, 'saveToFileCache' ] );
127 }
128 }
129
130 // Setup page variables.
131 $out->setFeedAppendQuery( 'action=history' );
132 $out->addModules( 'mediawiki.action.history' );
133 $out->addModuleStyles( [
134 'mediawiki.interface.helpers.styles',
135 'mediawiki.action.history.styles',
136 'mediawiki.special.changeslist',
137 ] );
138 if ( $config->get( 'UseMediaWikiUIEverywhere' ) ) {
139 $out = $this->getOutput();
140 $out->addModuleStyles( [
141 'mediawiki.ui.input',
142 'mediawiki.ui.checkbox',
143 ] );
144 }
145
146 // Handle atom/RSS feeds.
147 $feedType = $request->getVal( 'feed' );
148 if ( $feedType ) {
149 $this->feed( $feedType );
150
151 return;
152 }
153
154 $this->addHelpLink( '//meta.wikimedia.org/wiki/Special:MyLanguage/Help:Page_history', true );
155
156 // Fail nicely if article doesn't exist.
157 if ( !$this->page->exists() ) {
158 global $wgSend404Code;
159 if ( $wgSend404Code ) {
160 $out->setStatusCode( 404 );
161 }
162 $out->addWikiMsg( 'nohistory' );
163
164 $dbr = wfGetDB( DB_REPLICA );
165
166 # show deletion/move log if there is an entry
167 LogEventsList::showLogExtract(
168 $out,
169 [ 'delete', 'move', 'protect' ],
170 $this->getTitle(),
171 '',
172 [ 'lim' => 10,
173 'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
174 'showIfEmpty' => false,
175 'msgKey' => [ 'moveddeleted-notice' ]
176 ]
177 );
178
179 return;
180 }
181
182 /**
183 * Add date selector to quickly get to a certain time
184 */
185 $year = $request->getInt( 'year' );
186 $month = $request->getInt( 'month' );
187 $tagFilter = $request->getVal( 'tagfilter' );
188 $tagSelector = ChangeTags::buildTagFilterSelector( $tagFilter, false, $this->getContext() );
189
190 /**
191 * Option to show only revisions that have been (partially) hidden via RevisionDelete
192 */
193 if ( $request->getBool( 'deleted' ) ) {
194 $conds = [ 'rev_deleted != 0' ];
195 } else {
196 $conds = [];
197 }
198 if ( $this->getUser()->isAllowed( 'deletedhistory' ) ) {
199 $checkDeleted = Xml::checkLabel( $this->msg( 'history-show-deleted' )->text(),
200 'deleted', 'mw-show-deleted-only', $request->getBool( 'deleted' ) ) . "\n";
201 } else {
202 $checkDeleted = '';
203 }
204
205 // Add the general form
206 $action = htmlspecialchars( wfScript() );
207 $content = Html::hidden( 'title', $this->getTitle()->getPrefixedDBkey() ) . "\n";
208 $content .= Html::hidden( 'action', 'history' ) . "\n";
209 $content .= Xml::dateMenu(
210 ( $year == null ? MWTimestamp::getLocalInstance()->format( 'Y' ) : $year ),
211 $month
212 ) . "\u{00A0}";
213 $content .= $tagSelector ? ( implode( "\u{00A0}", $tagSelector ) . "\u{00A0}" ) : '';
214 $content .= $checkDeleted . Html::submitButton(
215 $this->msg( 'historyaction-submit' )->text(),
216 [],
217 [ 'mw-ui-progressive' ]
218 );
219 $out->addHTML(
220 "<form action=\"$action\" method=\"get\" id=\"mw-history-searchform\">" .
221 Xml::fieldset(
222 $this->msg( 'history-fieldset-title' )->text(),
223 $content,
224 [ 'id' => 'mw-history-search' ]
225 ) .
226 '</form>'
227 );
228
229 Hooks::run( 'PageHistoryBeforeList', [ &$this->page, $this->getContext() ] );
230
231 // Create and output the list.
232 $pager = new HistoryPager( $this, $year, $month, $tagFilter, $conds );
233 $out->addHTML(
234 $pager->getNavigationBar() .
235 $pager->getBody() .
236 $pager->getNavigationBar()
237 );
238 $out->preventClickjacking( $pager->getPreventClickjacking() );
239 }
240
241 /**
242 * Fetch an array of revisions, specified by a given limit, offset and
243 * direction. This is now only used by the feeds. It was previously
244 * used by the main UI but that's now handled by the pager.
245 *
246 * @param int $limit The limit number of revisions to get
247 * @param int $offset
248 * @param int $direction Either self::DIR_PREV or self::DIR_NEXT
249 * @return ResultWrapper
250 */
251 function fetchRevisions( $limit, $offset, $direction ) {
252 // Fail if article doesn't exist.
253 if ( !$this->getTitle()->exists() ) {
254 return new FakeResultWrapper( [] );
255 }
256
257 $dbr = wfGetDB( DB_REPLICA );
258
259 if ( $direction === self::DIR_PREV ) {
260 list( $dirs, $oper ) = [ "ASC", ">=" ];
261 } else { /* $direction === self::DIR_NEXT */
262 list( $dirs, $oper ) = [ "DESC", "<=" ];
263 }
264
265 if ( $offset ) {
266 $offsets = [ "rev_timestamp $oper " . $dbr->addQuotes( $dbr->timestamp( $offset ) ) ];
267 } else {
268 $offsets = [];
269 }
270
271 $page_id = $this->page->getId();
272
273 $revQuery = Revision::getQueryInfo();
274 return $dbr->select(
275 $revQuery['tables'],
276 $revQuery['fields'],
277 array_merge( [ 'rev_page' => $page_id ], $offsets ),
278 __METHOD__,
279 [
280 'ORDER BY' => "rev_timestamp $dirs",
281 'USE INDEX' => [ 'revision' => 'page_timestamp' ],
282 'LIMIT' => $limit
283 ],
284 $revQuery['joins']
285 );
286 }
287
288 /**
289 * Output a subscription feed listing recent edits to this page.
290 *
291 * @param string $type Feed type
292 */
293 function feed( $type ) {
294 if ( !FeedUtils::checkFeedOutput( $type ) ) {
295 return;
296 }
297 $request = $this->getRequest();
298
299 $feedClasses = $this->context->getConfig()->get( 'FeedClasses' );
300 /** @var RSSFeed|AtomFeed $feed */
301 $feed = new $feedClasses[$type](
302 $this->getTitle()->getPrefixedText() . ' - ' .
303 $this->msg( 'history-feed-title' )->inContentLanguage()->text(),
304 $this->msg( 'history-feed-description' )->inContentLanguage()->text(),
305 $this->getTitle()->getFullURL( 'action=history' )
306 );
307
308 // Get a limit on number of feed entries. Provide a sane default
309 // of 10 if none is defined (but limit to $wgFeedLimit max)
310 $limit = $request->getInt( 'limit', 10 );
311 $limit = min(
312 max( $limit, 1 ),
313 $this->context->getConfig()->get( 'FeedLimit' )
314 );
315
316 $items = $this->fetchRevisions( $limit, 0, self::DIR_NEXT );
317
318 // Generate feed elements enclosed between header and footer.
319 $feed->outHeader();
320 if ( $items->numRows() ) {
321 foreach ( $items as $row ) {
322 $feed->outItem( $this->feedItem( $row ) );
323 }
324 } else {
325 $feed->outItem( $this->feedEmpty() );
326 }
327 $feed->outFooter();
328 }
329
330 function feedEmpty() {
331 return new FeedItem(
332 $this->msg( 'nohistory' )->inContentLanguage()->text(),
333 $this->msg( 'history-feed-empty' )->inContentLanguage()->parseAsBlock(),
334 $this->getTitle()->getFullURL(),
335 wfTimestamp( TS_MW ),
336 '',
337 $this->getTitle()->getTalkPage()->getFullURL()
338 );
339 }
340
341 /**
342 * Generate a FeedItem object from a given revision table row
343 * Borrows Recent Changes' feed generation functions for formatting;
344 * includes a diff to the previous revision (if any).
345 *
346 * @param stdClass|array $row Database row
347 * @return FeedItem
348 */
349 function feedItem( $row ) {
350 $rev = new Revision( $row, 0, $this->getTitle() );
351
352 $text = FeedUtils::formatDiffRow(
353 $this->getTitle(),
354 $this->getTitle()->getPreviousRevisionID( $rev->getId() ),
355 $rev->getId(),
356 $rev->getTimestamp(),
357 $rev->getComment()
358 );
359 if ( $rev->getComment() == '' ) {
360 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
361 $title = $this->msg( 'history-feed-item-nocomment',
362 $rev->getUserText(),
363 $contLang->timeanddate( $rev->getTimestamp() ),
364 $contLang->date( $rev->getTimestamp() ),
365 $contLang->time( $rev->getTimestamp() )
366 )->inContentLanguage()->text();
367 } else {
368 $title = $rev->getUserText() .
369 $this->msg( 'colon-separator' )->inContentLanguage()->text() .
370 FeedItem::stripComment( $rev->getComment() );
371 }
372
373 return new FeedItem(
374 $title,
375 $text,
376 $this->getTitle()->getFullURL( 'diff=' . $rev->getId() . '&oldid=prev' ),
377 $rev->getTimestamp(),
378 $rev->getUserText(),
379 $this->getTitle()->getTalkPage()->getFullURL()
380 );
381 }
382 }