MediaWiki  master
HistoryAction.php
Go to the documentation of this file.
1 <?php
27 
39  const DIR_PREV = 0;
40  const DIR_NEXT = 1;
41 
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 Html::rawElement( 'div', [ 'class' => 'mw-history-subtitle' ], $subtitle );
82  }
83 
87  public function getArticle() {
88  return $this->page;
89  }
90 
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 
110  // Backwards compatibility checks for URIs with only year and/or month.
111  $year = $request->getInt( 'year' );
112  $month = $request->getInt( 'month' );
113  $day = null;
114  if ( $year !== 0 || $month !== 0 ) {
115  if ( $year === 0 ) {
116  $year = MWTimestamp::getLocalInstance()->format( 'Y' );
117  }
118  if ( $month < 1 || $month > 12 ) {
119  // month is invalid so treat as December (all months)
120  $month = 12;
121  }
122  // month is valid so check day
123  $day = cal_days_in_month( CAL_GREGORIAN, $month, $year );
124 
125  // Left pad the months and days
126  $month = str_pad( $month, 2, "0", STR_PAD_LEFT );
127  $day = str_pad( $day, 2, "0", STR_PAD_LEFT );
128  }
129 
130  $before = $request->getVal( 'date-range-to' );
131  if ( $before ) {
132  $parts = explode( '-', $before );
133  $year = $parts[0];
134  // check date input is valid
135  if ( count( $parts ) === 3 ) {
136  $month = $parts[1];
137  $day = $parts[2];
138  }
139  }
140  return $year && $month && $day ? $year . '-' . $month . '-' . $day : '';
141  }
142 
147  function onView() {
148  $out = $this->getOutput();
149  $request = $this->getRequest();
150 
151  // Allow client-side HTTP caching of the history page.
152  // But, always ignore this cache if the (logged-in) user has this page on their watchlist
153  // and has one or more unseen revisions. Otherwise, we might be showing stale update markers.
154  // The Last-Modified for the history page does not change when user's markers are cleared,
155  // so going from "some unseen" to "all seen" would not clear the cache.
156  // But, when all of the revisions are marked as seen, then only way for new unseen revision
157  // markers to appear, is for the page to be edited, which updates page_touched/Last-Modified.
158  if (
159  !$this->hasUnseenRevisionMarkers() &&
160  $out->checkLastModified( $this->page->getTouched() )
161  ) {
162  return null; // Client cache fresh and headers sent, nothing more to do.
163  }
164 
165  $this->preCacheMessages();
166  $config = $this->context->getConfig();
167 
168  # Fill in the file cache if not set already
169  if ( HTMLFileCache::useFileCache( $this->getContext() ) ) {
170  $cache = new HTMLFileCache( $this->getTitle(), 'history' );
171  if ( !$cache->isCacheGood( /* Assume up to date */ ) ) {
172  ob_start( [ &$cache, 'saveToFileCache' ] );
173  }
174  }
175 
176  // Setup page variables.
177  $out->setFeedAppendQuery( 'action=history' );
178  $out->addModules( 'mediawiki.action.history' );
179  $out->addModuleStyles( [
180  'mediawiki.interface.helpers.styles',
181  'mediawiki.action.history.styles',
182  'mediawiki.special.changeslist',
183  ] );
184  if ( $config->get( 'UseMediaWikiUIEverywhere' ) ) {
185  $out = $this->getOutput();
186  $out->addModuleStyles( [
187  'mediawiki.ui.input',
188  'mediawiki.ui.checkbox',
189  ] );
190  }
191 
192  // Handle atom/RSS feeds.
193  $feedType = $request->getRawVal( 'feed' );
194  if ( $feedType !== null ) {
195  $this->feed( $feedType );
196  return null;
197  }
198 
199  $this->addHelpLink(
200  'https://meta.wikimedia.org/wiki/Special:MyLanguage/Help:Page_history',
201  true
202  );
203 
204  // Fail nicely if article doesn't exist.
205  if ( !$this->page->exists() ) {
206  global $wgSend404Code;
207  if ( $wgSend404Code ) {
208  $out->setStatusCode( 404 );
209  }
210  $out->addWikiMsg( 'nohistory' );
211 
212  $dbr = wfGetDB( DB_REPLICA );
213 
214  # show deletion/move log if there is an entry
216  $out,
217  [ 'delete', 'move', 'protect' ],
218  $this->getTitle(),
219  '',
220  [ 'lim' => 10,
221  'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
222  'showIfEmpty' => false,
223  'msgKey' => [ 'moveddeleted-notice' ]
224  ]
225  );
226 
227  return null;
228  }
229 
230  $ts = $this->getTimestampFromRequest( $request );
231  $tagFilter = $request->getVal( 'tagfilter' );
232 
236  if ( $request->getBool( 'deleted' ) ) {
237  $conds = [ 'rev_deleted != 0' ];
238  } else {
239  $conds = [];
240  }
241 
242  // Add the general form.
243  $fields = [
244  [
245  'name' => 'title',
246  'type' => 'hidden',
247  'default' => $this->getTitle()->getPrefixedDBkey(),
248  ],
249  [
250  'name' => 'action',
251  'type' => 'hidden',
252  'default' => 'history',
253  ],
254  [
255  'type' => 'date',
256  'default' => $ts,
257  'label' => $this->msg( 'date-range-to' )->text(),
258  'name' => 'date-range-to',
259  ],
260  [
261  'label-raw' => $this->msg( 'tag-filter' )->parse(),
262  'type' => 'tagfilter',
263  'id' => 'tagfilter',
264  'name' => 'tagfilter',
265  'value' => $tagFilter,
266  ]
267  ];
268  $permissionManager = MediaWikiServices::getInstance()->getPermissionManager();
269  if ( $permissionManager->userHasRight( $this->getUser(), 'deletedhistory' ) ) {
270  $fields[] = [
271  'type' => 'check',
272  'label' => $this->msg( 'history-show-deleted' )->text(),
273  'default' => $request->getBool( 'deleted' ),
274  'name' => 'deleted',
275  ];
276  }
277 
278  $out->enableOOUI();
279  $htmlForm = HTMLForm::factory( 'ooui', $fields, $this->getContext() );
280  $htmlForm
281  ->setMethod( 'get' )
282  ->setAction( wfScript() )
283  ->setCollapsibleOptions( true )
284  ->setId( 'mw-history-searchform' )
285  ->setSubmitText( $this->msg( 'historyaction-submit' )->text() )
286  ->setWrapperAttributes( [ 'id' => 'mw-history-search' ] )
287  ->setWrapperLegend( $this->msg( 'history-fieldset-title' )->text() );
288  $htmlForm->loadData();
289 
290  $out->addHTML( $htmlForm->getHTML( false ) );
291 
292  Hooks::run( 'PageHistoryBeforeList', [ &$this->page, $this->getContext() ] );
293 
294  // Create and output the list.
295  $dateComponents = explode( '-', $ts );
296  if ( count( $dateComponents ) > 1 ) {
297  $y = $dateComponents[0];
298  $m = $dateComponents[1];
299  $d = $dateComponents[2];
300  } else {
301  $y = '';
302  $m = '';
303  $d = '';
304  }
305  $pager = new HistoryPager( $this, $y, $m, $tagFilter, $conds, $d );
306  $out->addHTML(
307  $pager->getNavigationBar() .
308  $pager->getBody() .
309  $pager->getNavigationBar()
310  );
311  $out->preventClickjacking( $pager->getPreventClickjacking() );
312 
313  return null;
314  }
315 
319  private function hasUnseenRevisionMarkers() {
320  return (
321  $this->getContext()->getConfig()->get( 'ShowUpdatedMarker' ) &&
322  $this->getTitle()->getNotificationTimestamp( $this->getUser() )
323  );
324  }
325 
336  function fetchRevisions( $limit, $offset, $direction ) {
337  // Fail if article doesn't exist.
338  if ( !$this->getTitle()->exists() ) {
339  return new FakeResultWrapper( [] );
340  }
341 
342  $dbr = wfGetDB( DB_REPLICA );
343 
344  if ( $direction === self::DIR_PREV ) {
345  list( $dirs, $oper ) = [ "ASC", ">=" ];
346  } else { /* $direction === self::DIR_NEXT */
347  list( $dirs, $oper ) = [ "DESC", "<=" ];
348  }
349 
350  if ( $offset ) {
351  $offsets = [ "rev_timestamp $oper " . $dbr->addQuotes( $dbr->timestamp( $offset ) ) ];
352  } else {
353  $offsets = [];
354  }
355 
356  $page_id = $this->page->getId();
357 
359  return $dbr->select(
360  $revQuery['tables'],
361  $revQuery['fields'],
362  array_merge( [ 'rev_page' => $page_id ], $offsets ),
363  __METHOD__,
364  [
365  'ORDER BY' => "rev_timestamp $dirs",
366  'USE INDEX' => [ 'revision' => 'page_timestamp' ],
367  'LIMIT' => $limit
368  ],
369  $revQuery['joins']
370  );
371  }
372 
378  function feed( $type ) {
379  if ( !FeedUtils::checkFeedOutput( $type ) ) {
380  return;
381  }
382  $request = $this->getRequest();
383 
384  $feedClasses = $this->context->getConfig()->get( 'FeedClasses' );
386  $feed = new $feedClasses[$type](
387  $this->getTitle()->getPrefixedText() . ' - ' .
388  $this->msg( 'history-feed-title' )->inContentLanguage()->text(),
389  $this->msg( 'history-feed-description' )->inContentLanguage()->text(),
390  $this->getTitle()->getFullURL( 'action=history' )
391  );
392 
393  // Get a limit on number of feed entries. Provide a sane default
394  // of 10 if none is defined (but limit to $wgFeedLimit max)
395  $limit = $request->getInt( 'limit', 10 );
396  $limit = min(
397  max( $limit, 1 ),
398  $this->context->getConfig()->get( 'FeedLimit' )
399  );
400 
401  $items = $this->fetchRevisions( $limit, 0, self::DIR_NEXT );
402 
403  // Generate feed elements enclosed between header and footer.
404  $feed->outHeader();
405  if ( $items->numRows() ) {
406  foreach ( $items as $row ) {
407  $feed->outItem( $this->feedItem( $row ) );
408  }
409  } else {
410  $feed->outItem( $this->feedEmpty() );
411  }
412  $feed->outFooter();
413  }
414 
415  function feedEmpty() {
416  return new FeedItem(
417  $this->msg( 'nohistory' )->inContentLanguage()->text(),
418  $this->msg( 'history-feed-empty' )->inContentLanguage()->parseAsBlock(),
419  $this->getTitle()->getFullURL(),
420  wfTimestamp( TS_MW ),
421  '',
422  $this->getTitle()->getTalkPage()->getFullURL()
423  );
424  }
425 
434  function feedItem( $row ) {
435  $rev = new Revision( $row, 0, $this->getTitle() );
436 
437  $text = FeedUtils::formatDiffRow(
438  $this->getTitle(),
439  $this->getTitle()->getPreviousRevisionID( $rev->getId() ),
440  $rev->getId(),
441  $rev->getTimestamp(),
442  $rev->getComment()
443  );
444  if ( $rev->getComment() == '' ) {
445  $contLang = MediaWikiServices::getInstance()->getContentLanguage();
446  $title = $this->msg( 'history-feed-item-nocomment',
447  $rev->getUserText(),
448  $contLang->timeanddate( $rev->getTimestamp() ),
449  $contLang->date( $rev->getTimestamp() ),
450  $contLang->time( $rev->getTimestamp() )
451  )->inContentLanguage()->text();
452  } else {
453  $title = $rev->getUserText() .
454  $this->msg( 'colon-separator' )->inContentLanguage()->text() .
455  FeedItem::stripComment( $rev->getComment() );
456  }
457 
458  return new FeedItem(
459  $title,
460  $text,
461  $this->getTitle()->getFullURL( 'diff=' . $rev->getId() . '&oldid=prev' ),
462  $rev->getTimestamp(),
463  $rev->getUserText(),
464  $this->getTitle()->getTalkPage()->getFullURL()
465  );
466  }
467 }
static stripComment( $text)
Quickie hack...
Definition: FeedItem.php:218
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
getInt( $name, $default=0)
Fetch an integer value from the input or return $default if not set.
Definition: WebRequest.php:534
getOutput()
Get the OutputPage being used for this instance.
Definition: Action.php:208
feed( $type)
Output a subscription feed listing recent edits to this page.
static getLocalInstance( $ts=false)
Get a timestamp instance in the server local timezone ($wgLocaltimezone)
addHelpLink( $to, $overrideBaseUrl=false)
Adds help link with an icon via page indicators.
Definition: Action.php:394
getTitle()
Shortcut to get the Title object from the page.
Definition: Action.php:247
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses after processing after in associative array form before processing starts Return false to skip default processing and return $ret $linkRenderer
Definition: hooks.txt:1983
getVal( $name, $default=null)
Fetch a scalar from the input or return $default if it&#39;s not set.
Definition: WebRequest.php:448
static useFileCache(IContextSource $context, $mode=self::MODE_NORMAL)
Check if pages can be cached for this request/user.
getUser()
Shortcut to get the User being used for this instance.
Definition: Action.php:218
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition: Html.php:209
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Page view caching in the file system.
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
Definition: injection.txt:23
static formatDiffRow( $title, $oldid, $newid, $timestamp, $comment, $actiontext='')
Really format a diff for the newsfeed.
Definition: FeedUtils.php:91
getLanguage()
Shortcut to get the user Language being used for this instance.
Definition: Action.php:237
target page
static factory( $displayFormat)
Construct a HTMLForm object for given display type.
Definition: HTMLForm.php:299
static exists( $name)
Check if a given action is recognised, even if it&#39;s disabled.
Definition: Action.php:170
This list may contain false positives That usually means there is additional text with links below the first Each row contains links to the first and second as well as the first line of the second redirect text
wfScript( $script='index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output $out
Definition: hooks.txt:773
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
feedItem( $row)
Generate a FeedItem object from a given revision table row Borrows Recent Changes&#39; feed generation fu...
onView()
Print the history page for an article.
preCacheMessages()
As we use the same small set of messages in various methods and that they are called often...
$cache
Definition: mcc.php:33
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:773
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:918
static getQueryInfo( $options=[])
Return the tables, fields, and join conditions to be selected to create a new revision object...
Definition: Revision.php:511
getContext()
Get the IContextSource in use here.
Definition: Action.php:179
static getTitleFor( $name, $subpage=false, $fragment='')
Get a localised Title object for a specified special page name If you don&#39;t need a full Title object...
Definition: SpecialPage.php:83
presenting them properly to the user as errors is done by the caller return true use this to change the list i e etc $rev
Definition: hooks.txt:1759
A base class for outputting syndication feeds (e.g.
Definition: FeedItem.php:33
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
$page
Page on which we&#39;re performing the action.
Definition: Action.php:46
$fields
The fields used to create the HTMLForm.
Definition: Action.php:60
An action which just does something, without showing a form first.
This class handles printing the history page for an article.
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
fetchRevisions( $limit, $offset, $direction)
Fetch an array of revisions, specified by a given limit, offset and direction.
Overloads the relevant methods of the real ResultsWrapper so it doesn&#39;t go anywhere near an actual da...
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation use $formDescriptor instead default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a message
Definition: hooks.txt:2150
$revQuery
array $message
Array of message keys and strings.
getTimestampFromRequest(WebRequest $request)
static checkFeedOutput( $type)
Check whether feeds can be used and that $type is a valid feed type.
Definition: FeedUtils.php:39
const DB_REPLICA
Definition: defines.php:25
$wgSend404Code
Some web hosts attempt to rewrite all responses with a 404 (not found) status code, mangling or hiding MediaWiki&#39;s output.
msg( $key)
Get a Message object with context set Parameters are the same as wfMessage()
Definition: Action.php:257
getRequest()
Get the WebRequest being used for this instance.
Definition: Action.php:198
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on $request
Definition: hooks.txt:2632
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200
static showLogExtract(&$out, $types=[], $page='', $user='', $param=[])
Show log extract.