MediaWiki  master
SpecialLog.php
Go to the documentation of this file.
1 <?php
29 use Wikimedia\IPUtils;
31 use Wikimedia\Timestamp\TimestampException;
32 
38 class SpecialLog extends SpecialPage {
39 
42 
44  private $loadBalancer;
45 
48 
51 
58  public function __construct(
63  ) {
64  parent::__construct( 'Log' );
65  $this->linkBatchFactory = $linkBatchFactory;
66  $this->loadBalancer = $loadBalancer;
67  $this->actorNormalization = $actorNormalization;
68  $this->userIdentityLookup = $userIdentityLookup;
69  }
70 
71  public function execute( $par ) {
72  $this->setHeaders();
73  $this->outputHeader();
74  $out = $this->getOutput();
75  $out->addModules( 'mediawiki.userSuggest' );
76  $out->addModuleStyles( 'mediawiki.interface.helpers.styles' );
77  $this->addHelpLink( 'Help:Log' );
78 
79  $opts = new FormOptions;
80  $opts->add( 'type', '' );
81  $opts->add( 'user', '' );
82  $opts->add( 'page', '' );
83  $opts->add( 'pattern', false );
84  $opts->add( 'year', null, FormOptions::INTNULL );
85  $opts->add( 'month', null, FormOptions::INTNULL );
86  $opts->add( 'day', null, FormOptions::INTNULL );
87  $opts->add( 'tagfilter', '' );
88  $opts->add( 'offset', '' );
89  $opts->add( 'dir', '' );
90  $opts->add( 'offender', '' );
91  $opts->add( 'subtype', '' );
92  $opts->add( 'logid', '' );
93 
94  // Set values
95  $opts->fetchValuesFromRequest( $this->getRequest() );
96  if ( $par !== null ) {
97  $this->parseParams( $opts, (string)$par );
98  }
99 
100  // Set date values
101  $dateString = $this->getRequest()->getVal( 'wpdate' );
102  if ( !empty( $dateString ) ) {
103  try {
104  $dateStamp = MWTimestamp::getInstance( $dateString . ' 00:00:00' );
105  } catch ( TimestampException $e ) {
106  // If users provide an invalid date, silently ignore it
107  // instead of letting an exception bubble up (T201411)
108  $dateStamp = false;
109  }
110  if ( $dateStamp ) {
111  $opts->setValue( 'year', (int)$dateStamp->format( 'Y' ) );
112  $opts->setValue( 'month', (int)$dateStamp->format( 'm' ) );
113  $opts->setValue( 'day', (int)$dateStamp->format( 'd' ) );
114  }
115  }
116 
117  # Don't let the user get stuck with a certain date
118  if ( $opts->getValue( 'offset' ) || $opts->getValue( 'dir' ) == 'prev' ) {
119  $opts->setValue( 'year', '' );
120  $opts->setValue( 'month', '' );
121  }
122 
123  // If the user doesn't have the right permission to view the specific
124  // log type, throw a PermissionsError
125  // If the log type is invalid, just show all public logs
126  $logRestrictions = $this->getConfig()->get( MainConfigNames::LogRestrictions );
127  $type = $opts->getValue( 'type' );
128  if ( !LogPage::isLogType( $type ) ) {
129  $opts->setValue( 'type', '' );
130  } elseif ( isset( $logRestrictions[$type] )
131  && !$this->getAuthority()->isAllowed( $logRestrictions[$type] )
132  ) {
133  throw new PermissionsError( $logRestrictions[$type] );
134  }
135 
136  # Handle type-specific inputs
137  $qc = [];
138  if ( $opts->getValue( 'type' ) == 'suppress' ) {
139  $dbr = $this->loadBalancer->getConnectionRef( DB_REPLICA );
140  $offenderName = $opts->getValue( 'offender' );
141  $offenderId = $this->actorNormalization->findActorIdByName( $offenderName, $dbr );
142  if ( $offenderId ) {
143  $qc = [ 'ls_field' => 'target_author_actor', 'ls_value' => $offenderId ];
144  }
145  } else {
146  // Allow extensions to add relations to their search types
147  $this->getHookRunner()->onSpecialLogAddLogSearchRelations(
148  $opts->getValue( 'type' ), $this->getRequest(), $qc );
149  }
150 
151  # Some log types are only for a 'User:' title but we might have been given
152  # only the username instead of the full title 'User:username'. This part try
153  # to lookup for a user by that name and eventually fix user input. See T3697.
154  if ( in_array( $opts->getValue( 'type' ), self::getLogTypesOnUser( $this->getHookRunner() ) ) ) {
155  # ok we have a type of log which expect a user title.
156  $page = $opts->getValue( 'page' );
157  $target = Title::newFromText( $page );
158  if ( $target && $target->getNamespace() === NS_MAIN ) {
159  if ( IPUtils::isValidRange( $target->getText() ) ) {
160  $page = IPUtils::sanitizeRange( $target->getText() );
161  }
162  # User forgot to add 'User:', we are adding it for him
163  $opts->setValue( 'page',
164  Title::makeTitleSafe( NS_USER, $page )
165  );
166  } elseif ( $target && $target->getNamespace() === NS_USER
167  && IPUtils::isValidRange( $target->getText() )
168  ) {
169  $page = IPUtils::sanitizeRange( $target->getText() );
170  if ( $page !== $target->getText() ) {
171  $opts->setValue( 'page', Title::makeTitleSafe( NS_USER, $page ) );
172  }
173  }
174  }
175 
176  $this->show( $opts, $qc );
177  }
178 
190  public static function getLogTypesOnUser( HookRunner $runner = null ) {
191  static $types = null;
192  if ( $types !== null ) {
193  return $types;
194  }
195  $types = [
196  'block',
197  'newusers',
198  'rights',
199  ];
200 
201  ( $runner ?? Hooks::runner() )->onGetLogTypesOnUser( $types );
202  return $types;
203  }
204 
210  public function getSubpagesForPrefixSearch() {
211  $subpages = LogPage::validTypes();
212  $subpages[] = 'all';
213  sort( $subpages );
214  return $subpages;
215  }
216 
226  private function parseParams( FormOptions $opts, $par ) {
227  # Get parameters
228  $par = $par ?? '';
229  $parms = explode( '/', $par );
230  $symsForAll = [ '*', 'all' ];
231  if ( $parms[0] != '' &&
232  ( in_array( $par, LogPage::validTypes() ) || in_array( $par, $symsForAll ) )
233  ) {
234  $opts->setValue( 'type', $par );
235  } elseif ( count( $parms ) == 2 ) {
236  $opts->setValue( 'type', $parms[0] );
237  $opts->setValue( 'user', $parms[1] );
238  } elseif ( $par != '' ) {
239  $opts->setValue( 'user', $par );
240  }
241  }
242 
243  private function show( FormOptions $opts, array $extraConds ) {
244  # Create a LogPager item to get the results and a LogEventsList item to format them...
245  $loglist = new LogEventsList(
246  $this->getContext(),
247  $this->getLinkRenderer(),
249  );
250  $pager = new LogPager(
251  $loglist,
252  $opts->getValue( 'type' ),
253  $opts->getValue( 'user' ),
254  $opts->getValue( 'page' ),
255  $opts->getValue( 'pattern' ),
256  $extraConds,
257  $opts->getValue( 'year' ),
258  $opts->getValue( 'month' ),
259  $opts->getValue( 'day' ),
260  $opts->getValue( 'tagfilter' ),
261  $opts->getValue( 'subtype' ),
262  $opts->getValue( 'logid' ),
263  $this->linkBatchFactory,
264  $this->loadBalancer,
265  $this->actorNormalization
266  );
267 
268  $this->addHeader( $opts->getValue( 'type' ) );
269 
270  # Set relevant user
271  $performer = $pager->getPerformer();
272  if ( $performer ) {
273  $performerUser = $this->userIdentityLookup->getUserIdentityByName( $performer );
274  if ( $performerUser ) {
275  $this->getSkin()->setRelevantUser( $performerUser );
276  }
277  }
278 
279  # Show form options
280  $loglist->showOptions(
281  $pager->getType(),
282  $performer,
283  $pager->getPage(),
284  $pager->getPattern(),
285  $pager->getYear(),
286  $pager->getMonth(),
287  $pager->getDay(),
288  $pager->getFilterParams(),
289  $pager->getTagFilter(),
290  $pager->getAction()
291  );
292 
293  # Insert list
294  $logBody = $pager->getBody();
295  if ( $logBody ) {
296  $this->getOutput()->addHTML(
297  $pager->getNavigationBar() .
298  $this->getActionButtons(
299  $loglist->beginLogEventsList() .
300  $logBody .
301  $loglist->endLogEventsList()
302  ) .
303  $pager->getNavigationBar()
304  );
305  } else {
306  $this->getOutput()->addWikiMsg( 'logempty' );
307  }
308  }
309 
310  private function getActionButtons( $formcontents ) {
311  $canRevDelete = $this->getAuthority()
312  ->isAllowedAll( 'deletedhistory', 'deletelogentry' );
313  $showTagEditUI = ChangeTags::showTagEditingUI( $this->getAuthority() );
314  # If the user doesn't have the ability to delete log entries nor edit tags,
315  # don't bother showing them the button(s).
316  if ( !$canRevDelete && !$showTagEditUI ) {
317  return $formcontents;
318  }
319 
320  # Show button to hide log entries and/or edit change tags
322  'form',
323  [ 'action' => wfScript(), 'id' => 'mw-log-deleterevision-submit' ]
324  ) . "\n";
325  $s .= Html::hidden( 'action', 'historysubmit' ) . "\n";
326  $s .= Html::hidden( 'type', 'logging' ) . "\n";
327 
328  // If no title is set, the fallback is to use the main page, as defined
329  // by MediaWiki:Mainpage
330  // On wikis where the main page can be translated, MediaWiki:Mainpage
331  // is sometimes set to use Special:MyLanguage to redirect to the
332  // appropriate version. This is interpreted as a special page, and
333  // Action::getActionName forces the action to be 'view' if the title
334  // cannot be used as a WikiPage, which includes all pages in NS_SPECIAL.
335  // Set a dummy title to avoid this. The title provided is unused
336  // by the SpecialPageAction class and does not matter.
337  // See T205908
338  $s .= Html::hidden( 'title', 'Unused' ) . "\n";
339 
340  $buttons = '';
341  if ( $canRevDelete ) {
342  $buttons .= Html::element(
343  'button',
344  [
345  'type' => 'submit',
346  'name' => 'revisiondelete',
347  'value' => '1',
348  'class' => "deleterevision-log-submit mw-log-deleterevision-button mw-ui-button"
349  ],
350  $this->msg( 'showhideselectedlogentries' )->text()
351  ) . "\n";
352  }
353  if ( $showTagEditUI ) {
354  $buttons .= Html::element(
355  'button',
356  [
357  'type' => 'submit',
358  'name' => 'editchangetags',
359  'value' => '1',
360  'class' => "editchangetags-log-submit mw-log-editchangetags-button mw-ui-button"
361  ],
362  $this->msg( 'log-edit-tags' )->text()
363  ) . "\n";
364  }
365 
366  $buttons .= ( new ListToggle( $this->getOutput() ) )->getHTML();
367 
368  $s .= $buttons . $formcontents . $buttons;
369  $s .= Html::closeElement( 'form' );
370 
371  return $s;
372  }
373 
379  protected function addHeader( $type ) {
380  $page = new LogPage( $type );
381  $this->getOutput()->setPageTitle( $page->getName() );
382  $this->getOutput()->addHTML( $page->getDescription()
383  ->setContext( $this->getContext() )->parseAsBlock() );
384  }
385 
386  protected function getGroupName() {
387  return 'changes';
388  }
389 }
const NS_USER
Definition: Defines.php:66
const NS_MAIN
Definition: Defines.php:64
wfScript( $script='index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
static showTagEditingUI(Authority $performer)
Indicate whether change tag editing UI is relevant.
Helper class to keep track of options when mixing links and form elements.
Definition: FormOptions.php:35
add( $name, $default, $type=self::AUTO)
Add an option to be handled by this FormOptions instance.
Definition: FormOptions.php:83
setValue( $name, $value, $force=false)
Use to set the value of an option.
const INTNULL
Integer type or null, maps to WebRequest::getIntOrNull() This is useful for the namespace selector.
Definition: FormOptions.php:55
getValue( $name)
Get the value for the given option name.
static runner()
Get a HookRunner instance for calling hooks using the new interfaces.
Definition: Hooks.php:173
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition: Html.php:236
static openElement( $element, $attribs=[])
Identical to rawElement(), but has no third parameter and omits the end tag (and the self-closing '/'...
Definition: Html.php:256
static closeElement( $element)
Returns "</$element>".
Definition: Html.php:320
static hidden( $name, $value, array $attribs=[])
Convenience function to produce an input element with type=hidden.
Definition: Html.php:851
Class for generating clickable toggle links for a list of checkboxes.
Definition: ListToggle.php:31
const USE_CHECKBOXES
Class to simplify the use of log pages.
Definition: LogPage.php:39
static isLogType( $type)
Is $type a valid log type.
Definition: LogPage.php:219
static validTypes()
Get the list of valid log types.
Definition: LogPage.php:207
static getInstance( $ts=false)
Get a timestamp instance in GMT.
Definition: MWTimestamp.php:46
This class provides an implementation of the core hook interfaces, forwarding hook calls to HookConta...
Definition: HookRunner.php:562
A class containing constants representing the names of configuration variables.
Show an error when a user tries to do something they do not have the necessary permissions for.
A special page that lists log entries.
Definition: SpecialLog.php:38
getSubpagesForPrefixSearch()
Return an array of subpages that this special page will accept.
Definition: SpecialLog.php:210
static getLogTypesOnUser(HookRunner $runner=null)
List log type for which the target is a user Thus if the given target is in NS_MAIN we can alter it t...
Definition: SpecialLog.php:190
execute( $par)
Default execute method Checks user permissions.
Definition: SpecialLog.php:71
show(FormOptions $opts, array $extraConds)
Definition: SpecialLog.php:243
UserIdentityLookup $userIdentityLookup
Definition: SpecialLog.php:50
ActorNormalization $actorNormalization
Definition: SpecialLog.php:47
parseParams(FormOptions $opts, $par)
Set options based on the subpage title parts:
Definition: SpecialLog.php:226
ILoadBalancer $loadBalancer
Definition: SpecialLog.php:44
LinkBatchFactory $linkBatchFactory
Definition: SpecialLog.php:41
getActionButtons( $formcontents)
Definition: SpecialLog.php:310
__construct(LinkBatchFactory $linkBatchFactory, ILoadBalancer $loadBalancer, ActorNormalization $actorNormalization, UserIdentityLookup $userIdentityLookup)
Definition: SpecialLog.php:58
addHeader( $type)
Set page title and show header for this log type.
Definition: SpecialLog.php:379
getGroupName()
Under which header this special page is listed in Special:SpecialPages See messages 'specialpages-gro...
Definition: SpecialLog.php:386
Parent class for all special pages.
Definition: SpecialPage.php:44
outputHeader( $summaryMessageKey='')
Outputs a summary message on top of special pages Per default the message key is the canonical name o...
setHeaders()
Sets headers - this should be called from the execute() method of all derived classes!
getOutput()
Get the OutputPage being used for this instance.
getSkin()
Shortcut to get the skin being used for this instance.
getContext()
Gets the context this SpecialPage is executed in.
msg( $key,... $params)
Wrapper around wfMessage that sets the current context.
getAuthority()
Shortcut to get the Authority executing this instance.
getConfig()
Shortcut to get main config object.
getRequest()
Get the WebRequest being used for this instance.
addHelpLink( $to, $overrideBaseUrl=false)
Adds help link with an icon via page indicators.
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:370
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:664
$runner
Service for dealing with the actor table.
Database cluster connection, tracking, load balancing, and transaction manager interface.
foreach( $mmfl['setupFiles'] as $fileName) if( $queue) if(empty( $mmfl['quiet'])) $s
const DB_REPLICA
Definition: defines.php:26