MediaWiki  master
ContribsPager.php
Go to the documentation of this file.
1 <?php
31 
33 
37  private $messages;
38 
42  private $target;
43 
48  private $contribs;
49 
53  private $namespace = '';
54 
58  private $tagFilter;
59 
63  private $nsInvert;
64 
69  private $associated;
70 
74  private $deletedOnly;
75 
79  private $topOnly;
80 
84  private $newOnly;
85 
89  private $hideMinor;
90 
91  private $preventClickjacking = false;
92 
94  private $mDbSecondary;
95 
99  private $mParentLens;
100 
105 
106  public function __construct( IContextSource $context, array $options ) {
107  // Set ->target and ->contribs before calling parent::__construct() so
108  // parent can call $this->getIndexField() and get the right result. Set
109  // the rest too just to keep things simple.
110  $this->target = $options['target'] ?? '';
111  $this->contribs = $options['contribs'] ?? 'users';
112  $this->namespace = $options['namespace'] ?? '';
113  $this->tagFilter = $options['tagfilter'] ?? false;
114  $this->nsInvert = $options['nsInvert'] ?? false;
115  $this->associated = $options['associated'] ?? false;
116 
117  $this->deletedOnly = !empty( $options['deletedOnly'] );
118  $this->topOnly = !empty( $options['topOnly'] );
119  $this->newOnly = !empty( $options['newOnly'] );
120  $this->hideMinor = !empty( $options['hideMinor'] );
121 
122  parent::__construct( $context );
123 
124  $msgs = [
125  'diff',
126  'hist',
127  'pipe-separator',
128  'uctop'
129  ];
130 
131  foreach ( $msgs as $msg ) {
132  $this->messages[$msg] = $this->msg( $msg )->escaped();
133  }
134 
135  // Date filtering: use timestamp if available
136  $startTimestamp = '';
137  $endTimestamp = '';
138  if ( $options['start'] ) {
139  $startTimestamp = $options['start'] . ' 00:00:00';
140  }
141  if ( $options['end'] ) {
142  $endTimestamp = $options['end'] . ' 23:59:59';
143  }
144  $this->getDateRangeCond( $startTimestamp, $endTimestamp );
145 
146  // Most of this code will use the 'contributions' group DB, which can map to replica DBs
147  // with extra user based indexes or partioning by user. The additional metadata
148  // queries should use a regular replica DB since the lookup pattern is not all by user.
149  $this->mDbSecondary = wfGetDB( DB_REPLICA ); // any random replica DB
150  $this->mDb = wfGetDB( DB_REPLICA, 'contributions' );
151  $this->templateParser = new TemplateParser();
152  }
153 
154  function getDefaultQuery() {
155  $query = parent::getDefaultQuery();
156  $query['target'] = $this->target;
157 
158  return $query;
159  }
160 
168  function getNavigationBar() {
169  return Html::rawElement( 'p', [ 'class' => 'mw-pager-navigation-bar' ],
170  parent::getNavigationBar()
171  );
172  }
173 
183  function reallyDoQuery( $offset, $limit, $order ) {
184  list( $tables, $fields, $conds, $fname, $options, $join_conds ) = $this->buildQueryInfo(
185  $offset,
186  $limit,
187  $order
188  );
189 
190  /*
191  * This hook will allow extensions to add in additional queries, so they can get their data
192  * in My Contributions as well. Extensions should append their results to the $data array.
193  *
194  * Extension queries have to implement the navbar requirement as well. They should
195  * - have a column aliased as $pager->getIndexField()
196  * - have LIMIT set
197  * - have a WHERE-clause that compares the $pager->getIndexField()-equivalent column to the offset
198  * - have the ORDER BY specified based upon the details provided by the navbar
199  *
200  * See includes/Pager.php buildQueryInfo() method on how to build LIMIT, WHERE & ORDER BY
201  *
202  * &$data: an array of results of all contribs queries
203  * $pager: the ContribsPager object hooked into
204  * $offset: see phpdoc above
205  * $limit: see phpdoc above
206  * $descending: see phpdoc above
207  */
208  $data = [ $this->mDb->select(
209  $tables, $fields, $conds, $fname, $options, $join_conds
210  ) ];
211  Hooks::run(
212  'ContribsPager::reallyDoQuery',
213  [ &$data, $this, $offset, $limit, $order ]
214  );
215 
216  $result = [];
217 
218  // loop all results and collect them in an array
219  foreach ( $data as $query ) {
220  foreach ( $query as $i => $row ) {
221  // use index column as key, allowing us to easily sort in PHP
222  $result[$row->{$this->getIndexField()} . "-$i"] = $row;
223  }
224  }
225 
226  // sort results
227  if ( $order === self::QUERY_ASCENDING ) {
228  ksort( $result );
229  } else {
230  krsort( $result );
231  }
232 
233  // enforce limit
234  $result = array_slice( $result, 0, $limit );
235 
236  // get rid of array keys
237  $result = array_values( $result );
238 
239  return new FakeResultWrapper( $result );
240  }
241 
251  private function getTargetTable() {
252  if ( $this->contribs == 'newbie' ) {
253  return 'revision';
254  }
255 
256  $user = User::newFromName( $this->target, false );
257  $ipRangeConds = $user->isAnon() ? $this->getIpRangeConds( $this->mDb, $this->target ) : null;
258  if ( $ipRangeConds ) {
259  return 'ip_changes';
260  } else {
261  $conds = ActorMigration::newMigration()->getWhere( $this->mDb, 'rev_user', $user );
262  if ( isset( $conds['orconds']['actor'] ) ) {
263  // @todo: This will need changing when revision_actor_temp goes away
264  return 'revision_actor_temp';
265  }
266  }
267 
268  return 'revision';
269  }
270 
271  function getQueryInfo() {
272  $revQuery = Revision::getQueryInfo( [ 'page', 'user' ] );
273  $queryInfo = [
274  'tables' => $revQuery['tables'],
275  'fields' => array_merge( $revQuery['fields'], [ 'page_is_new' ] ),
276  'conds' => [],
277  'options' => [],
278  'join_conds' => $revQuery['joins'],
279  ];
280 
281  // WARNING: Keep this in sync with getTargetTable()!
282 
283  if ( $this->contribs == 'newbie' ) {
284  $max = $this->mDb->selectField( 'user', 'max(user_id)', '', __METHOD__ );
285  $queryInfo['conds'][] = $revQuery['fields']['rev_user'] . ' >' . (int)( $max - $max / 100 );
286  # ignore local groups with the bot right
287  # @todo FIXME: Global groups may have 'bot' rights
288  $groupsWithBotPermission = User::getGroupsWithPermission( 'bot' );
289  if ( count( $groupsWithBotPermission ) ) {
290  $queryInfo['tables'][] = 'user_groups';
291  $queryInfo['conds'][] = 'ug_group IS NULL';
292  $queryInfo['join_conds']['user_groups'] = [
293  'LEFT JOIN', [
294  'ug_user = ' . $revQuery['fields']['rev_user'],
295  'ug_group' => $groupsWithBotPermission,
296  'ug_expiry IS NULL OR ug_expiry >= ' .
297  $this->mDb->addQuotes( $this->mDb->timestamp() )
298  ]
299  ];
300  }
301  // (T140537) Disallow looking too far in the past for 'newbies' queries. If the user requested
302  // a timestamp offset far in the past such that there are no edits by users with user_ids in
303  // the range, we would end up scanning all revisions from that offset until start of time.
304  $queryInfo['conds'][] = 'rev_timestamp > ' .
305  $this->mDb->addQuotes( $this->mDb->timestamp( wfTimestamp() - 30 * 24 * 60 * 60 ) );
306  } else {
307  $user = User::newFromName( $this->target, false );
308  $ipRangeConds = $user->isAnon() ? $this->getIpRangeConds( $this->mDb, $this->target ) : null;
309  if ( $ipRangeConds ) {
310  $queryInfo['tables'][] = 'ip_changes';
311  $queryInfo['join_conds']['ip_changes'] = [
312  'LEFT JOIN', [ 'ipc_rev_id = rev_id' ]
313  ];
314  $queryInfo['conds'][] = $ipRangeConds;
315  } else {
316  // tables and joins are already handled by Revision::getQueryInfo()
317  $conds = ActorMigration::newMigration()->getWhere( $this->mDb, 'rev_user', $user );
318  $queryInfo['conds'][] = $conds['conds'];
319  // Force the appropriate index to avoid bad query plans (T189026)
320  if ( isset( $conds['orconds']['actor'] ) ) {
321  // @todo: This will need changing when revision_actor_temp goes away
322  $queryInfo['options']['USE INDEX']['temp_rev_user'] = 'actor_timestamp';
323  } else {
324  $queryInfo['options']['USE INDEX']['revision'] =
325  isset( $conds['orconds']['userid'] ) ? 'user_timestamp' : 'usertext_timestamp';
326  }
327  }
328  }
329 
330  if ( $this->deletedOnly ) {
331  $queryInfo['conds'][] = 'rev_deleted != 0';
332  }
333 
334  if ( $this->topOnly ) {
335  $queryInfo['conds'][] = 'rev_id = page_latest';
336  }
337 
338  if ( $this->newOnly ) {
339  $queryInfo['conds'][] = 'rev_parent_id = 0';
340  }
341 
342  if ( $this->hideMinor ) {
343  $queryInfo['conds'][] = 'rev_minor_edit = 0';
344  }
345 
346  $user = $this->getUser();
347  $queryInfo['conds'] = array_merge( $queryInfo['conds'], $this->getNamespaceCond() );
348 
349  // Paranoia: avoid brute force searches (T19342)
350  if ( !$user->isAllowed( 'deletedhistory' ) ) {
351  $queryInfo['conds'][] = $this->mDb->bitAnd(
352  'rev_deleted', RevisionRecord::DELETED_USER
353  ) . ' = 0';
354  } elseif ( !$user->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) {
355  $queryInfo['conds'][] = $this->mDb->bitAnd(
356  'rev_deleted', RevisionRecord::SUPPRESSED_USER
357  ) . ' != ' . RevisionRecord::SUPPRESSED_USER;
358  }
359 
360  // $this->getIndexField() must be in the result rows, as reallyDoQuery() tries to access it.
361  $indexField = $this->getIndexField();
362  if ( $indexField !== 'rev_timestamp' ) {
363  $queryInfo['fields'][] = $indexField;
364  }
365 
367  $queryInfo['tables'],
368  $queryInfo['fields'],
369  $queryInfo['conds'],
370  $queryInfo['join_conds'],
371  $queryInfo['options'],
372  $this->tagFilter
373  );
374 
375  // Avoid PHP 7.1 warning from passing $this by reference
376  $pager = $this;
377  Hooks::run( 'ContribsPager::getQueryInfo', [ &$pager, &$queryInfo ] );
378 
379  return $queryInfo;
380  }
381 
382  function getNamespaceCond() {
383  if ( $this->namespace !== '' ) {
384  $selectedNS = $this->mDb->addQuotes( $this->namespace );
385  $eq_op = $this->nsInvert ? '!=' : '=';
386  $bool_op = $this->nsInvert ? 'AND' : 'OR';
387 
388  if ( !$this->associated ) {
389  return [ "page_namespace $eq_op $selectedNS" ];
390  }
391 
392  $associatedNS = $this->mDb->addQuotes(
393  MediaWikiServices::getInstance()->getNamespaceInfo()->getAssociated( $this->namespace )
394  );
395 
396  return [
397  "page_namespace $eq_op $selectedNS " .
398  $bool_op .
399  " page_namespace $eq_op $associatedNS"
400  ];
401  }
402 
403  return [];
404  }
405 
412  private function getIpRangeConds( $db, $ip ) {
413  // First make sure it is a valid range and they are not outside the CIDR limit
414  if ( !$this->isQueryableRange( $ip ) ) {
415  return false;
416  }
417 
418  list( $start, $end ) = IP::parseRange( $ip );
419 
420  return 'ipc_hex BETWEEN ' . $db->addQuotes( $start ) . ' AND ' . $db->addQuotes( $end );
421  }
422 
430  public function isQueryableRange( $ipRange ) {
431  $limits = $this->getConfig()->get( 'RangeContributionsCIDRLimit' );
432 
433  $bits = IP::parseCIDR( $ipRange )[1];
434  if (
435  ( $bits === false ) ||
436  ( IP::isIPv4( $ipRange ) && $bits < $limits['IPv4'] ) ||
437  ( IP::isIPv6( $ipRange ) && $bits < $limits['IPv6'] )
438  ) {
439  return false;
440  }
441 
442  return true;
443  }
444 
448  public function getIndexField() {
449  // The returned column is used for sorting and continuation, so we need to
450  // make sure to use the right denormalized column depending on which table is
451  // being targeted by the query to avoid bad query plans.
452  // See T200259, T204669, T220991, and T221380.
453  $target = $this->getTargetTable();
454  switch ( $target ) {
455  case 'revision':
456  return 'rev_timestamp';
457  case 'ip_changes':
458  return 'ipc_rev_timestamp';
459  case 'revision_actor_temp':
460  return 'revactor_timestamp';
461  default:
462  wfWarn(
463  __METHOD__ . ": Unknown value '$target' from " . static::class . '::getTargetTable()', 0
464  );
465  return 'rev_timestamp';
466  }
467  }
468 
472  public function getTagFilter() {
473  return $this->tagFilter;
474  }
475 
479  public function getContribs() {
480  return $this->contribs;
481  }
482 
486  public function getTarget() {
487  return $this->target;
488  }
489 
493  public function isNewOnly() {
494  return $this->newOnly;
495  }
496 
500  public function getNamespace() {
501  return $this->namespace;
502  }
503 
507  protected function getExtraSortFields() {
508  // The returned columns are used for sorting, so we need to make sure
509  // to use the right denormalized column depending on which table is
510  // being targeted by the query to avoid bad query plans.
511  // See T200259, T204669, T220991, and T221380.
512  $target = $this->getTargetTable();
513  switch ( $target ) {
514  case 'revision':
515  return [ 'rev_id' ];
516  case 'ip_changes':
517  return [ 'ipc_rev_id' ];
518  case 'revision_actor_temp':
519  return [ 'revactor_rev' ];
520  default:
521  wfWarn(
522  __METHOD__ . ": Unknown value '$target' from " . static::class . '::getTargetTable()', 0
523  );
524  return [ 'rev_id' ];
525  }
526  }
527 
528  protected function doBatchLookups() {
529  # Do a link batch query
530  $this->mResult->seek( 0 );
531  $parentRevIds = [];
532  $this->mParentLens = [];
533  $batch = new LinkBatch();
534  $isIpRange = $this->isQueryableRange( $this->target );
535  # Give some pointers to make (last) links
536  foreach ( $this->mResult as $row ) {
537  if ( isset( $row->rev_parent_id ) && $row->rev_parent_id ) {
538  $parentRevIds[] = $row->rev_parent_id;
539  }
540  if ( isset( $row->rev_id ) ) {
541  $this->mParentLens[$row->rev_id] = $row->rev_len;
542  if ( $this->contribs === 'newbie' ) { // multiple users
543  $batch->add( NS_USER, $row->user_name );
544  $batch->add( NS_USER_TALK, $row->user_name );
545  } elseif ( $isIpRange ) {
546  // If this is an IP range, batch the IP's talk page
547  $batch->add( NS_USER_TALK, $row->rev_user_text );
548  }
549  $batch->add( $row->page_namespace, $row->page_title );
550  }
551  }
552  # Fetch rev_len for revisions not already scanned above
553  $this->mParentLens += Revision::getParentLengths(
554  $this->mDbSecondary,
555  array_diff( $parentRevIds, array_keys( $this->mParentLens ) )
556  );
557  $batch->execute();
558  $this->mResult->seek( 0 );
559  }
560 
564  protected function getStartBody() {
565  return "<ul class=\"mw-contributions-list\">\n";
566  }
567 
571  protected function getEndBody() {
572  return "</ul>\n";
573  }
574 
583  public function tryToCreateValidRevision( $row, $title = null ) {
584  /*
585  * There may be more than just revision rows. To make sure that we'll only be processing
586  * revisions here, let's _try_ to build a revision out of our row (without displaying
587  * notices though) and then trying to grab data from the built object. If we succeed,
588  * we're definitely dealing with revision data and we may proceed, if not, we'll leave it
589  * to extensions to subscribe to the hook to parse the row.
590  */
591  Wikimedia\suppressWarnings();
592  try {
593  $rev = new Revision( $row, 0, $title );
594  $validRevision = (bool)$rev->getId();
595  } catch ( Exception $e ) {
596  $validRevision = false;
597  }
598  Wikimedia\restoreWarnings();
599  return $validRevision ? $rev : null;
600  }
601 
614  function formatRow( $row ) {
615  $ret = '';
616  $classes = [];
617  $attribs = [];
618 
619  $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
620 
621  $page = null;
622  // Create a title for the revision if possible
623  // Rows from the hook may not include title information
624  if ( isset( $row->page_namespace ) && isset( $row->page_title ) ) {
625  $page = Title::newFromRow( $row );
626  }
627  $rev = $this->tryToCreateValidRevision( $row, $page );
628  if ( $rev ) {
629  $attribs['data-mw-revid'] = $rev->getId();
630 
631  $link = $linkRenderer->makeLink(
632  $page,
633  $page->getPrefixedText(),
634  [ 'class' => 'mw-contributions-title' ],
635  $page->isRedirect() ? [ 'redirect' => 'no' ] : []
636  );
637  # Mark current revisions
638  $topmarktext = '';
639  $user = $this->getUser();
640 
641  if ( $row->rev_id === $row->page_latest ) {
642  $topmarktext .= '<span class="mw-uctop">' . $this->messages['uctop'] . '</span>';
643  $classes[] = 'mw-contributions-current';
644  # Add rollback link
645  if ( !$row->page_is_new && $page->quickUserCan( 'rollback', $user )
646  && $page->quickUserCan( 'edit', $user )
647  ) {
648  $this->preventClickjacking();
649  $topmarktext .= ' ' . Linker::generateRollback( $rev, $this->getContext(),
650  [ 'noBrackets' ] );
651  }
652  }
653  # Is there a visible previous revision?
654  if ( $rev->userCan( RevisionRecord::DELETED_TEXT, $user ) && $rev->getParentId() !== 0 ) {
655  $difftext = $linkRenderer->makeKnownLink(
656  $page,
657  new HtmlArmor( $this->messages['diff'] ),
658  [ 'class' => 'mw-changeslist-diff' ],
659  [
660  'diff' => 'prev',
661  'oldid' => $row->rev_id
662  ]
663  );
664  } else {
665  $difftext = $this->messages['diff'];
666  }
667  $histlink = $linkRenderer->makeKnownLink(
668  $page,
669  new HtmlArmor( $this->messages['hist'] ),
670  [ 'class' => 'mw-changeslist-history' ],
671  [ 'action' => 'history' ]
672  );
673 
674  if ( $row->rev_parent_id === null ) {
675  // For some reason rev_parent_id isn't populated for this row.
676  // Its rumoured this is true on wikipedia for some revisions (T36922).
677  // Next best thing is to have the total number of bytes.
678  $chardiff = ' <span class="mw-changeslist-separator"></span> ';
679  $chardiff .= Linker::formatRevisionSize( $row->rev_len );
680  $chardiff .= ' <span class="mw-changeslist-separator"></span> ';
681  } else {
682  $parentLen = 0;
683  if ( isset( $this->mParentLens[$row->rev_parent_id] ) ) {
684  $parentLen = $this->mParentLens[$row->rev_parent_id];
685  }
686 
687  $chardiff = ' <span class="mw-changeslist-separator"></span> ';
689  $parentLen,
690  $row->rev_len,
691  $this->getContext()
692  );
693  $chardiff .= ' <span class="mw-changeslist-separator"></span> ';
694  }
695 
696  $lang = $this->getLanguage();
697  $comment = $lang->getDirMark() . Linker::revComment( $rev, false, true, false );
698  $d = ChangesList::revDateLink( $rev, $user, $lang, $page );
699 
700  # Show user names for /newbies as there may be different users.
701  # Note that only unprivileged users have rows with hidden user names excluded.
702  # When querying for an IP range, we want to always show user and user talk links.
703  $userlink = '';
704  if ( ( $this->contribs == 'newbie' && !$rev->isDeleted( RevisionRecord::DELETED_USER ) )
705  || $this->isQueryableRange( $this->target ) ) {
706  $userlink = ' <span class="mw-changeslist-separator"></span> '
707  . $lang->getDirMark()
708  . Linker::userLink( $rev->getUser(), $rev->getUserText() );
709  $userlink .= ' ' . $this->msg( 'parentheses' )->rawParams(
710  Linker::userTalkLink( $rev->getUser(), $rev->getUserText() ) )->escaped() . ' ';
711  }
712 
713  $flags = [];
714  if ( $rev->getParentId() === 0 ) {
715  $flags[] = ChangesList::flag( 'newpage' );
716  }
717 
718  if ( $rev->isMinor() ) {
719  $flags[] = ChangesList::flag( 'minor' );
720  }
721 
722  $del = Linker::getRevDeleteLink( $user, $rev, $page );
723  if ( $del !== '' ) {
724  $del .= ' ';
725  }
726 
727  // While it might be tempting to use a list here
728  // this would result in clutter and slows down navigating the content
729  // in assistive technology.
730  // See https://phabricator.wikimedia.org/T205581#4734812
731  $diffHistLinks = Html::rawElement( 'span',
732  [ 'class' => 'mw-changeslist-links' ],
733  // The spans are needed to ensure the dividing '|' elements are not
734  // themselves styled as links.
735  Html::rawElement( 'span', [], $difftext ) .
736  ' ' . // Space needed for separating two words.
737  Html::rawElement( 'span', [], $histlink )
738  );
739 
740  # Tags, if any.
741  list( $tagSummary, $newClasses ) = ChangeTags::formatSummaryRow(
742  $row->ts_tags,
743  'contributions',
744  $this->getContext()
745  );
746  $classes = array_merge( $classes, $newClasses );
747 
748  Hooks::run( 'SpecialContributions::formatRow::flags', [ $this->getContext(), $row, &$flags ] );
749 
750  $templateParams = [
751  'del' => $del,
752  'timestamp' => $d,
753  'diffHistLinks' => $diffHistLinks,
754  'charDifference' => $chardiff,
755  'flags' => $flags,
756  'articleLink' => $link,
757  'userlink' => $userlink,
758  'logText' => $comment,
759  'topmarktext' => $topmarktext,
760  'tagSummary' => $tagSummary,
761  ];
762 
763  # Denote if username is redacted for this edit
764  if ( $rev->isDeleted( RevisionRecord::DELETED_USER ) ) {
765  $templateParams['rev-deleted-user-contribs'] =
766  $this->msg( 'rev-deleted-user-contribs' )->escaped();
767  }
768 
769  $ret = $this->templateParser->processTemplate(
770  'SpecialContributionsLine',
771  $templateParams
772  );
773  }
774 
775  // Let extensions add data
776  Hooks::run( 'ContributionsLineEnding', [ $this, &$ret, $row, &$classes, &$attribs ] );
777  $attribs = array_filter( $attribs,
778  [ Sanitizer::class, 'isReservedDataAttribute' ],
779  ARRAY_FILTER_USE_KEY
780  );
781 
782  // TODO: Handle exceptions in the catch block above. Do any extensions rely on
783  // receiving empty rows?
784 
785  if ( $classes === [] && $attribs === [] && $ret === '' ) {
786  wfDebug( "Dropping Special:Contribution row that could not be formatted\n" );
787  return "<!-- Could not format Special:Contribution row. -->\n";
788  }
789  $attribs['class'] = $classes;
790 
791  // FIXME: The signature of the ContributionsLineEnding hook makes it
792  // very awkward to move this LI wrapper into the template.
793  return Html::rawElement( 'li', $attribs, $ret ) . "\n";
794  }
795 
800  function getSqlComment() {
801  if ( $this->namespace || $this->deletedOnly ) {
802  // potentially slow, see CR r58153
803  return 'contributions page filtered for namespace or RevisionDeleted edits';
804  } else {
805  return 'contributions page unfiltered';
806  }
807  }
808 
809  protected function preventClickjacking() {
810  $this->preventClickjacking = true;
811  }
812 
816  public function getPreventClickjacking() {
818  }
819 
826  public static function processDateFilter( array $opts ) {
827  $start = $opts['start'] ?? '';
828  $end = $opts['end'] ?? '';
829  $year = $opts['year'] ?? '';
830  $month = $opts['month'] ?? '';
831 
832  if ( $start !== '' && $end !== '' && $start > $end ) {
833  $temp = $start;
834  $start = $end;
835  $end = $temp;
836  }
837 
838  // If year/month legacy filtering options are set, convert them to display the new stamp
839  if ( $year !== '' || $month !== '' ) {
840  // Reuse getDateCond logic, but subtract a day because
841  // the endpoints of our date range appear inclusive
842  // but the internal end offsets are always exclusive
843  $legacyTimestamp = ReverseChronologicalPager::getOffsetDate( $year, $month );
844  $legacyDateTime = new DateTime( $legacyTimestamp->getTimestamp( TS_ISO_8601 ) );
845  $legacyDateTime = $legacyDateTime->modify( '-1 day' );
846 
847  // Clear the new timestamp range options if used and
848  // replace with the converted legacy timestamp
849  $start = '';
850  $end = $legacyDateTime->format( 'Y-m-d' );
851  }
852 
853  $opts['start'] = $start;
854  $opts['end'] = $end;
855 
856  return $opts;
857  }
858 }
static modifyDisplayQuery(&$tables, &$fields, &$conds, &$join_conds, &$options, $filter_tag='')
Applies all tags-related changes to a query.
Definition: ChangeTags.php:772
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
wfWarn( $msg, $callerOffset=1, $level=E_USER_NOTICE)
Send a warning either to the debug log or in a PHP error depending on $wgDevelopmentWarnings.
return true to allow those checks to and false if checking is done remove or add to the links of a group of changes in EnhancedChangesList Hook subscribers can return false to omit this line from recentchanges use this to change the tables headers change it to an object instance and return false override the list derivative used $groups Array of ChangesListFilterGroup objects(added in 1.34) 'FileDeleteComplete' null for the local wiki Added should default to null in handler for backwards compatibility add a value to it if you want to add a cookie that have to vary cache options can modify $query
Definition: hooks.txt:1529
isQueryableRange( $ipRange)
Is the given IP a range and within the CIDR limit?
bool $deletedOnly
Set to true to show only deleted revisions.
static processDateFilter(array $opts)
Set up date filter options, given request data.
static parseRange( $range)
Given a string range in a number of formats, return the start and end of the range in hexadecimal...
Definition: IP.php:500
static formatRevisionSize( $size)
Definition: Linker.php:1597
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 & $ret
Definition: hooks.txt:1972
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:1972
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2147
bool $hideMinor
Set to true to hide edits marked as minor by the user.
if(!isset( $args[0])) $lang
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition: Html.php:209
bool $associated
Set to true to show both the subject and talk namespace, no matter which got selected.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
static getParentLengths( $db, array $revIds)
Do a batched query to get the parent revision lengths.
Definition: Revision.php:538
string $contribs
Set to "newbie" to list contributions from the most recent 1% registered users.
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
msg( $key)
Get a Message object with context set Parameters are the same as wfMessage()
static newFromRow( $row)
Make a Title object from a DB row.
Definition: Title.php:522
static generateRollback( $rev, IContextSource $context=null, $options=[ 'verify'])
Generate a rollback link for a given revision.
Definition: Linker.php:1806
bool $nsInvert
Set to true to invert the namespace selection.
IContextSource $context
tryToCreateValidRevision( $row, $title=null)
Check whether the revision associated is valid for formatting.
this hook is for auditing only RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist & $tables
Definition: hooks.txt:960
__construct(IContextSource $context, array $options)
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImgAuthModifyHeaders':Executed just before a file is streamed to a user via img_auth.php, allowing headers to be modified beforehand. $title:LinkTarget object & $headers:HTTP headers(name=> value, names are case insensitive). Two headers get special handling:If-Modified-Since(value must be a valid HTTP date) and Range(must be of the form "bytes=(\*-\*)") will be honored when streaming the file. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1970
$batch
Definition: linkcache.txt:23
usually copyright or history_copyright This message must be in HTML not wikitext & $link
Definition: hooks.txt:3039
passed in as a query string parameter to the various URLs constructed here(i.e. $prevlink) $ldel you ll need to handle error messages
Definition: hooks.txt:1268
Class representing a list of titles The execute() method checks them all for existence and adds them ...
Definition: LinkBatch.php:34
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
static newMigration()
Static constructor.
static flag( $flag, IContextSource $context=null)
Make an "<abbr>" element for a given change flag.
static getGroupsWithPermission( $role)
Get all the groups who have a given permission.
Definition: User.php:4812
reallyDoQuery( $offset, $limit, $order)
This method basically executes the exact same code as the parent class, though with a hook added...
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
getDateRangeCond( $startStamp, $endStamp)
Set and return a date range condition using timestamps provided by the user.
string $target
User name, or a string describing an IP address range.
getContext()
Get the base IContextSource object.
static revDateLink(Revision $rev, User $user, Language $lang, $title=null)
Render the date and time of a revision in the current user language based on whether the user is able...
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 & $options
Definition: hooks.txt:1972
getTargetTable()
Return the table targeted for ordering and continuation.
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 & $attribs
Definition: hooks.txt:1972
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:767
string false $tagFilter
Name of tag to filter, or false to ignore tags.
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:912
static getQueryInfo( $options=[])
Return the tables, fields, and join conditions to be selected to create a new revision object...
Definition: Revision.php:511
formatRow( $row)
Generates each row in the contributions list.
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:1748
TemplateParser $templateParser
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
static showCharacterDifference( $old, $new, IContextSource $context=null)
Show formatted char difference.
getSqlComment()
Overwrite Pager function and return a helpful comment.
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings, LocalSettings).
Definition: Setup.php:131
string int $namespace
A single namespace number, or an empty string for all namespaces.
static userLink( $userId, $userName, $altUserName=false)
Make user link (or user contributions for unregistered users)
Definition: Linker.php:895
buildQueryInfo( $offset, $limit, $order)
Build variables to use by the database wrapper.
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
static isIPv6( $ip)
Given a string, determine if it as valid IP in IPv6 only.
Definition: IP.php:88
static getRevDeleteLink(User $user, Revision $rev, LinkTarget $title)
Get a revision-deletion link, or disabled link, or nothing, depending on user permissions & the setti...
Definition: Linker.php:2105
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
static userTalkLink( $userId, $userText)
Definition: Linker.php:1031
Overloads the relevant methods of the real ResultsWrapper so it doesn&#39;t go anywhere near an actual da...
getNavigationBar()
Wrap the navigation bar in a p element with identifying class.
static getOffsetDate( $year, $month, $day=-1)
Core logic of determining the mOffset timestamp such that we can get all items with a timestamp up to...
string [] $messages
Local cache for escaped messages.
$revQuery
static isIPv4( $ip)
Given a string, determine if it as valid IP in IPv4 only.
Definition: IP.php:99
static formatSummaryRow( $tags, $page, IContextSource $context=null)
Creates HTML for the given tags.
Definition: ChangeTags.php:94
static revComment(Revision $rev, $local=false, $isPublic=false, $useParentheses=true)
Wrap and format the given revision&#39;s comment block, if the current user is allowed to view it...
Definition: Linker.php:1572
const DB_REPLICA
Definition: defines.php:25
Pager for filtering by a range of dates.
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
Definition: User.php:535
static parseCIDR( $range)
Convert a network specification in CIDR notation to an integer network and a number of bits...
Definition: IP.php:457
const NS_USER_TALK
Definition: Defines.php:63
bool $topOnly
Set to true to show only latest (a.k.a.
getIpRangeConds( $db, $ip)
Get SQL conditions for an IP range, if applicable.
return true to allow those checks to and false if checking is done & $user
Definition: hooks.txt:1454
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200
IDatabase $mDbSecondary
bool $newOnly
Set to true to show only new pages.