Файловый менеджер - Редактировать - /var/www/html/pager.zip
Ðазад
PK ! �8� � Pager.phpnu �Iw�� <?php /** * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * http://www.gnu.org/copyleft/gpl.html * * @file */ /** * @defgroup Pager Pager */ namespace MediaWiki\Pager; /** * Basic pager interface for efficient paging through SQL queries. * * Must not be implemented directly by extensions, * instead extend IndexPager or one of its subclasses. * * @stable to type * @ingroup Pager */ interface Pager { public function getNavigationBar(); public function getBody(); } /** @deprecated class alias since 1.41 */ class_alias( Pager::class, 'Pager' ); PK ! e��$H H RangeChronologicalPager.phpnu �Iw�� <?php /** * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * http://www.gnu.org/copyleft/gpl.html * * @file */ namespace MediaWiki\Pager; use MediaWiki\Utils\MWTimestamp; use Wikimedia\Timestamp\TimestampException; /** * Pager for filtering by a range of dates. * * @stable to extend * @ingroup Pager */ abstract class RangeChronologicalPager extends ReverseChronologicalPager { /** * @var string[] * @deprecated since 1.40, use $startOffset and $endOffset instead. */ protected $rangeConds; /** @var string */ protected $startOffset; /** * Set and return a date range condition using timestamps provided by the user. * We want the revisions between the two timestamps. * Also supports only having a start or end timestamp. * Assumes that the start timestamp comes before the end timestamp. * * @stable to override * * @param string $startTime Timestamp of the beginning of the date range (or empty) * @param string $endTime Timestamp of the end of the date range (or empty) * @return array|null Database conditions to satisfy the specified date range * or null if dates are invalid */ public function getDateRangeCond( $startTime, $endTime ) { // Construct the conds array for compatibility with callers and derived classes $this->rangeConds = []; try { if ( $startTime !== '' ) { $startTimestamp = MWTimestamp::getInstance( $startTime ); $this->startOffset = $this->mDb->timestamp( $startTimestamp->getTimestamp() ); $this->rangeConds[] = $this->mDb->buildComparison( '>=', [ $this->getTimestampField() => $this->startOffset ] ); } if ( $endTime !== '' ) { $endTimestamp = MWTimestamp::getInstance( $endTime ); // Turned to use '<' for consistency with the parent class, // add one second for compatibility with existing use cases $endTimestamp->timestamp = $endTimestamp->timestamp->modify( '+1 second' ); $this->endOffset = $this->mDb->timestamp( $endTimestamp->getTimestamp() ); $this->rangeConds[] = $this->mDb->buildComparison( '<', [ $this->getTimestampField() => $this->endOffset ] ); // populate existing variables for compatibility with parent $this->mYear = (int)$endTimestamp->format( 'Y' ); $this->mMonth = (int)$endTimestamp->format( 'm' ); $this->mDay = (int)$endTimestamp->format( 'd' ); } } catch ( TimestampException $ex ) { return null; } return $this->rangeConds; } /** * Return the range of date offsets, in the format of [ endOffset, startOffset ]. * Extensions can use this to get the range if they are not in the context of subclasses. * * @since 1.40 * @return string[] */ public function getRangeOffsets() { return [ $this->endOffset, $this->startOffset ]; } /** * @inheritDoc */ protected function buildQueryInfo( $offset, $limit, $order ) { [ $tables, $fields, $conds, $fname, $options, $join_conds ] = parent::buildQueryInfo( $offset, $limit, $order ); // End of the range has been added by ReverseChronologicalPager if ( $this->startOffset ) { $conds[] = $this->mDb->expr( $this->getTimestampField(), '>=', $this->startOffset ); } elseif ( $this->rangeConds ) { // Keep compatibility with some derived classes, T325034 $conds = array_merge( $conds, $this->rangeConds ); } return [ $tables, $fields, $conds, $fname, $options, $join_conds ]; } } /** @deprecated class alias since 1.41 */ class_alias( RangeChronologicalPager::class, 'RangeChronologicalPager' ); PK ! 3�lt lt IndexPager.phpnu �Iw�� <?php /** * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * http://www.gnu.org/copyleft/gpl.html * * @file */ namespace MediaWiki\Pager; use HtmlArmor; use MediaWiki\Context\ContextSource; use MediaWiki\Context\IContextSource; use MediaWiki\Html\Html; use MediaWiki\Linker\LinkRenderer; use MediaWiki\MediaWikiServices; use MediaWiki\Navigation\PagerNavigationBuilder; use MediaWiki\Request\WebRequest; use stdClass; use Wikimedia\Rdbms\IReadableDatabase; use Wikimedia\Rdbms\IResultWrapper; /** * Efficient paging for SQL queries that use a (roughly unique) index. * * This is for paging through data sets stored in tables with a unique * index, instead of a naive "LIMIT offset,limit" clause. * * In MySQL, such a limit/offset clause requires counting through the * specified number of offset rows to find the desired data, which can be * expensive for large offsets. * * ReverseChronologicalPager is a child class of the abstract IndexPager, and * contains some formatting and display code which is specific to the use of * timestamps as indexes. Here is a synopsis of its operation: * * * The query is specified by the offset, limit and direction (dir) * parameters, in addition to any subclass-specific parameters. * * The offset is the non-inclusive start of the DB query. A row with an * index value equal to the offset will never be shown. * * The query may either be done backwards, where the rows are returned by * the database in the opposite order to which they are displayed to the * user, or forwards. This is specified by the "dir" parameter, dir=prev * means backwards, anything else means forwards. The offset value * specifies the start of the database result set, which may be either * the start or end of the displayed data set. This allows "previous" * links to be implemented without knowledge of the index value at the * start of the previous page. * * An additional row beyond the user-specified limit is always requested. * This allows us to tell whether we should display a "next" link in the * case of forwards mode, or a "previous" link in the case of backwards * mode. Determining whether to display the other link (the one for the * page before the start of the database result set) can be done * heuristically by examining the offset. * * * An empty offset indicates that the offset condition should be omitted * from the query. This naturally produces either the first page or the * last page depending on the dir parameter. * * Subclassing the pager to implement concrete functionality should be fairly * simple, please see the examples in HistoryAction.php and * SpecialBlockList.php. You just need to override formatRow(), * getQueryInfo() and getIndexField(). Don't forget to call the parent * constructor if you override it. * * @stable to extend * @ingroup Pager */ abstract class IndexPager extends ContextSource implements Pager { /** Backwards-compatible constant for $mDefaultDirection field (do not change) */ public const DIR_ASCENDING = false; /** Backwards-compatible constant for $mDefaultDirection field (do not change) */ public const DIR_DESCENDING = true; /** Backwards-compatible constant for reallyDoQuery() (do not change) */ public const QUERY_ASCENDING = true; /** Backwards-compatible constant for reallyDoQuery() (do not change) */ public const QUERY_DESCENDING = false; /** @var WebRequest */ public $mRequest; /** @var int[] List of default entry limit options to be presented to clients */ public $mLimitsShown = [ 20, 50, 100, 250, 500 ]; /** @var int The default entry limit choosen for clients */ public $mDefaultLimit = 50; /** @var mixed The starting point to enumerate entries */ public $mOffset; /** @var int The maximum number of entries to show */ public $mLimit; /** @var bool Whether the listing query completed */ public $mQueryDone = false; /** @var IReadableDatabase */ public $mDb; /** @var stdClass|bool|null Extra row fetched at the end to see if the end was reached */ public $mPastTheEndRow; /** * The index to actually be used for ordering. This can be a single column, * an array of single columns, or an array of arrays of columns. See getIndexField * for more details. * @var string|string[] */ protected $mIndexField; /** * An array of secondary columns to order by. These fields are not part of the offset. * This is a column list for one ordering, even if multiple orderings are supported. * @var string[] */ protected $mExtraSortFields; /** For pages that support multiple types of ordering, which one to use. * @var string|null */ protected $mOrderType; /** * $mDefaultDirection gives the direction to use when sorting results: * DIR_ASCENDING or DIR_DESCENDING. If $mIsBackwards is set, we start from * the opposite end, but we still sort the page itself according to * $mDefaultDirection. For example, if $mDefaultDirection is DIR_ASCENDING * but we're going backwards, we'll display the last page of results, but * the last result will be at the bottom, not the top. * * Like $mIndexField, $mDefaultDirection will be a single value even if the * class supports multiple default directions for different order types. * @var bool */ public $mDefaultDirection; /** @var bool */ public $mIsBackwards; /** @var bool True if the current result set is the first one */ public $mIsFirst; /** @var bool */ public $mIsLast; /** @var array */ protected $mLastShown; /** @var array */ protected $mFirstShown; /** @var array */ protected $mPastTheEndIndex; /** @var array */ protected $mDefaultQuery; /** @var string */ protected $mNavigationBar; /** * Whether to include the offset in the query * @var bool */ protected $mIncludeOffset = false; /** * Result object for the query. Warning: seek before use. * * @var IResultWrapper */ public $mResult; /** @var LinkRenderer */ private $linkRenderer; /** * @stable to call * * @param IContextSource|null $context * @param LinkRenderer|null $linkRenderer */ public function __construct( ?IContextSource $context = null, ?LinkRenderer $linkRenderer = null ) { if ( $context ) { $this->setContext( $context ); } $this->mRequest = $this->getRequest(); # NB: the offset is quoted, not validated. It is treated as an # arbitrary string to support the widest variety of index types. Be # careful outputting it into HTML! $this->mOffset = $this->mRequest->getText( 'offset' ); # Use consistent behavior for the limit options $this->mDefaultLimit = MediaWikiServices::getInstance() ->getUserOptionsLookup() ->getIntOption( $this->getUser(), 'rclimit' ); if ( !$this->mLimit ) { // Don't override if a subclass calls $this->setLimit() in its constructor. [ $this->mLimit, /* $offset */ ] = $this->mRequest ->getLimitOffsetForUser( $this->getUser() ); } $this->mIsBackwards = ( $this->mRequest->getVal( 'dir' ) == 'prev' ); // Let the subclass set the DB here; otherwise use a replica DB for the current wiki if ( !$this->mDb ) { $this->mDb = MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase(); } $index = $this->getIndexField(); // column to sort on $extraSort = $this->getExtraSortFields(); // extra columns to sort on for query planning $order = $this->mRequest->getVal( 'order' ); if ( is_array( $index ) && isset( $index[$order] ) ) { $this->mOrderType = $order; $this->mIndexField = $index[$order]; $this->mExtraSortFields = isset( $extraSort[$order] ) ? (array)$extraSort[$order] : []; } elseif ( is_array( $index ) ) { # First element is the default $this->mIndexField = reset( $index ); $this->mOrderType = key( $index ); $this->mExtraSortFields = isset( $extraSort[$this->mOrderType] ) ? (array)$extraSort[$this->mOrderType] : []; } else { # $index is not an array $this->mOrderType = null; $this->mIndexField = $index; $isSortAssociative = array_values( $extraSort ) !== $extraSort; if ( $isSortAssociative ) { $this->mExtraSortFields = isset( $extraSort[$index] ) ? (array)$extraSort[$index] : []; } else { $this->mExtraSortFields = (array)$extraSort; } } if ( !isset( $this->mDefaultDirection ) ) { $dir = $this->getDefaultDirections(); $this->mDefaultDirection = is_array( $dir ) ? $dir[$this->mOrderType] : $dir; } $this->linkRenderer = $linkRenderer; } /** * Get the Database object in use * * @since 1.20 * * @return IReadableDatabase */ public function getDatabase() { return $this->mDb; } /** * Do the query, using information from the object context. This function * has been kept minimal to make it overridable if necessary, to allow for * result sets formed from multiple DB queries. * * @stable to override */ public function doQuery() { $defaultOrder = ( $this->mDefaultDirection === self::DIR_ASCENDING ) ? self::QUERY_ASCENDING : self::QUERY_DESCENDING; $order = $this->mIsBackwards ? self::oppositeOrder( $defaultOrder ) : $defaultOrder; # Plus an extra row so that we can tell the "next" link should be shown $queryLimit = $this->mLimit + 1; if ( $this->mOffset == '' ) { $isFirst = true; } else { // If there's an offset, we may or may not be at the first entry. // The only way to tell is to run the query in the opposite // direction see if we get a row. $oldIncludeOffset = $this->mIncludeOffset; $this->mIncludeOffset = !$this->mIncludeOffset; $oppositeOrder = self::oppositeOrder( $order ); $isFirst = !$this->reallyDoQuery( $this->mOffset, 1, $oppositeOrder )->numRows(); $this->mIncludeOffset = $oldIncludeOffset; } $this->mResult = $this->reallyDoQuery( $this->mOffset, $queryLimit, $order ); $this->extractResultInfo( $isFirst, $queryLimit, $this->mResult ); $this->mQueryDone = true; $this->preprocessResults( $this->mResult ); $this->mResult->rewind(); // Paranoia } /** * @param bool $order One of the IndexPager::QUERY_* class constants * @return bool The opposite query order as an IndexPager::QUERY_ constant */ final protected static function oppositeOrder( $order ) { return ( $order === self::QUERY_ASCENDING ) ? self::QUERY_DESCENDING : self::QUERY_ASCENDING; } /** * @return IResultWrapper The result wrapper. */ public function getResult() { return $this->mResult; } /** * @return int The current offset into the result. Valid during formatRow(). */ public function getResultOffset() { return $this->mResult->key(); } /** * Set the offset from an other source than the request * * @param int|string $offset */ public function setOffset( $offset ) { $this->mOffset = $offset; } /** * Set the limit from an other source than the request * * Verifies limit is between 1 and 5000 * * @stable to override * * @param int|string $limit */ public function setLimit( $limit ) { $limit = (int)$limit; // WebRequest::getLimitOffsetForUser() puts a cap of 5000, so do same here. if ( $limit > 5000 ) { $limit = 5000; } if ( $limit > 0 ) { $this->mLimit = $limit; } } /** * Get the current limit * * @return int */ public function getLimit() { return $this->mLimit; } /** * Set whether a row matching exactly the offset should be also included * in the result or not. By default this is not the case, but when the * offset is user-supplied this might be wanted. * * @param bool $include */ public function setIncludeOffset( $include ) { $this->mIncludeOffset = $include; } /** * Extract some useful data from the result object for use by * the navigation bar, put it into $this * * @stable to override * * @param bool $isFirst False if there are rows before those fetched (i.e. * if a "previous" link would make sense) * @param int $limit Exact query limit * @param IResultWrapper $res */ protected function extractResultInfo( $isFirst, $limit, IResultWrapper $res ) { $numRows = $res->numRows(); $firstIndex = []; $lastIndex = []; $this->mPastTheEndIndex = []; $this->mPastTheEndRow = null; if ( $numRows ) { $indexColumns = array_map( static function ( $v ) { // Remove any table prefix from index field $parts = explode( '.', $v ); return end( $parts ); }, (array)$this->mIndexField ); $row = $res->fetchRow(); foreach ( $indexColumns as $indexColumn ) { $firstIndex[] = $row[$indexColumn]; } # Discard the extra result row if there is one if ( $numRows > $this->mLimit && $numRows > 1 ) { $res->seek( $numRows - 1 ); $this->mPastTheEndRow = $res->fetchObject(); foreach ( $indexColumns as $indexColumn ) { $this->mPastTheEndIndex[] = $this->mPastTheEndRow->$indexColumn; } $res->seek( $numRows - 2 ); $row = $res->fetchRow(); foreach ( $indexColumns as $indexColumn ) { $lastIndex[] = $row[$indexColumn]; } } else { $this->mPastTheEndRow = null; $res->seek( $numRows - 1 ); $row = $res->fetchRow(); foreach ( $indexColumns as $indexColumn ) { $lastIndex[] = $row[$indexColumn]; } } } if ( $this->mIsBackwards ) { $this->mIsFirst = ( $numRows < $limit ); $this->mIsLast = $isFirst; $this->mLastShown = $firstIndex; $this->mFirstShown = $lastIndex; } else { $this->mIsFirst = $isFirst; $this->mIsLast = ( $numRows < $limit ); $this->mLastShown = $lastIndex; $this->mFirstShown = $firstIndex; } } /** * Get some text to go in brackets in the "function name" part of the SQL comment * * @stable to override * * @return string */ protected function getSqlComment() { return static::class; } /** * Do a query with specified parameters, rather than using the object context * * @note For b/c, query direction is true for ascending and false for descending * * @stable to override * * @param string $offset Index offset, inclusive * @param int $limit Exact query limit * @param bool $order IndexPager::QUERY_ASCENDING or IndexPager::QUERY_DESCENDING * @return IResultWrapper */ public function reallyDoQuery( $offset, $limit, $order ) { [ $tables, $fields, $conds, $fname, $options, $join_conds ] = $this->buildQueryInfo( $offset, $limit, $order ); return $this->mDb->newSelectQueryBuilder() ->rawTables( $tables ) ->fields( $fields ) ->conds( $conds ) ->caller( $fname ) ->options( $options ) ->joinConds( $join_conds ) ->fetchResultSet(); } /** * Build variables to use by the database wrapper. * * @note For b/c, query direction is true for ascending and false for descending * * @stable to override * * @param int|string|null $offset Index offset, inclusive * @param int $limit Exact query limit * @param bool $order IndexPager::QUERY_ASCENDING or IndexPager::QUERY_DESCENDING * @return array */ protected function buildQueryInfo( $offset, $limit, $order ) { $fname = __METHOD__ . ' (' . $this->getSqlComment() . ')'; $info = $this->getQueryInfo(); $tables = $info['tables']; $fields = $info['fields']; $conds = $info['conds'] ?? []; $options = $info['options'] ?? []; $join_conds = $info['join_conds'] ?? []; $indexColumns = (array)$this->mIndexField; $sortColumns = array_merge( $indexColumns, $this->mExtraSortFields ); if ( $order === self::QUERY_ASCENDING ) { $options['ORDER BY'] = $sortColumns; $operator = $this->mIncludeOffset ? '>=' : '>'; } else { $orderBy = []; foreach ( $sortColumns as $col ) { $orderBy[] = $col . ' DESC'; } $options['ORDER BY'] = $orderBy; $operator = $this->mIncludeOffset ? '<=' : '<'; } if ( $offset ) { $offsets = explode( '|', $offset, /* Limit to max of indices */ count( $indexColumns ) ); $conds[] = $this->buildOffsetConds( $offsets, $indexColumns, $operator ); } $options['LIMIT'] = intval( $limit ); return [ $tables, $fields, $conds, $fname, $options, $join_conds ]; } /** * Build the conditions for the offset, given that we may be paginating on a * single column or multiple columns. Where we paginate on multiple columns, * the sort order is defined by the order of the columns in $mIndexField. * * @param string[] $offsets The offset for each index field * @param string[] $columns The name of each index field * @param string $operator Operator for the final part of each inner * condition. This will be '>' if the query order is ascending, or '<' if * the query order is descending. If the offset should be included, it will * also have '=' appended. * @return string The conditions for getting results from the offset */ private function buildOffsetConds( $offsets, $columns, $operator ) { // $offsets may be shorter than $columns, in which case the remaining columns should be ignored // (T318080) $columns = array_slice( $columns, 0, count( $offsets ) ); $conds = array_combine( $columns, $offsets ); return $this->mDb->buildComparison( $operator, $conds ); } /** * Pre-process results; useful for performing batch existence checks, etc. * * @stable to override * * @param IResultWrapper $result */ protected function preprocessResults( $result ) { } /** * Get the HTML of a pager row. * * @stable to override * @since 1.38 * @param stdClass $row * @return string */ protected function getRow( $row ): string { return $this->formatRow( $row ); } /** * Get the formatted result list. Calls getStartBody(), formatRow() and * getEndBody(), concatenates the results and returns them. * * @stable to override * * @return string */ public function getBody() { $this->getOutput()->addModuleStyles( $this->getModuleStyles() ); if ( !$this->mQueryDone ) { $this->doQuery(); } if ( $this->mResult->numRows() ) { # Do any special query batches before display $this->doBatchLookups(); } # Don't use any extra rows returned by the query $numRows = min( $this->mResult->numRows(), $this->mLimit ); $s = $this->getStartBody(); if ( $numRows ) { if ( $this->mIsBackwards ) { for ( $i = $numRows - 1; $i >= 0; $i-- ) { $this->mResult->seek( $i ); $row = $this->mResult->fetchObject(); $s .= $this->getRow( $row ); } } else { $this->mResult->seek( 0 ); for ( $i = 0; $i < $numRows; $i++ ) { $row = $this->mResult->fetchObject(); $s .= $this->getRow( $row ); } } $s .= $this->getFooter(); } else { $s .= $this->getEmptyBody(); } $s .= $this->getEndBody(); return $s; } /** * ResourceLoader modules that must be loaded to provide correct styling for this pager * * @stable to override * @since 1.38 * @return string[] */ public function getModuleStyles() { return [ 'mediawiki.pager.styles' ]; } /** * Classes can extend to output a footer at the bottom of the pager list. * * @since 1.38 * @return string */ protected function getFooter(): string { return ''; } /** * Make a self-link * * @stable to call (since 1.39) * * @param string $text Text displayed on the link * @param array|null $query Associative array of parameter to be in the query string. * If null, no link is generated. * @param string|null $type Link type used to create additional attributes, like "rel", "class" or * "title". Valid values (non-exhaustive list): 'first', 'last', 'prev', 'next', 'asc', 'desc'. * @return string HTML fragment */ protected function makeLink( $text, ?array $query = null, $type = null ) { $attrs = []; if ( $query !== null && in_array( $type, [ 'prev', 'next' ] ) ) { $attrs['rel'] = $type; } if ( in_array( $type, [ 'asc', 'desc' ] ) ) { $attrs['title'] = $this->msg( $type == 'asc' ? 'sort-ascending' : 'sort-descending' )->text(); } if ( $type ) { $attrs['class'] = "mw-{$type}link"; } if ( $query !== null ) { return $this->getLinkRenderer()->makeKnownLink( $this->getTitle(), new HtmlArmor( $text ), $attrs, $query + $this->getDefaultQuery() ); } else { return Html::rawElement( 'span', $attrs, $text ); } } /** * Called from getBody(), before getStartBody() is called and * after doQuery() was called. This will be called only if there * are rows in the result set. * * @stable to override * * @return void */ protected function doBatchLookups() { } /** * Hook into getBody(), allows text to be inserted at the start. This * will be called even if there are no rows in the result set. * * @return string */ protected function getStartBody() { return ''; } /** * Hook into getBody() for the end of the list * * @stable to override * * @return string */ protected function getEndBody() { return ''; } /** * Hook into getBody(), for the bit between the start and the * end when there are no rows * * @stable to override * * @return string */ protected function getEmptyBody() { return ''; } /** * Get an array of query parameters that should be put into self-links. * By default, all parameters passed in the URL are used, apart from a * few exceptions. * * @stable to override * * @return array Associative array */ public function getDefaultQuery() { if ( !isset( $this->mDefaultQuery ) ) { $this->mDefaultQuery = $this->getRequest()->getQueryValues(); unset( $this->mDefaultQuery['title'] ); unset( $this->mDefaultQuery['dir'] ); unset( $this->mDefaultQuery['offset'] ); unset( $this->mDefaultQuery['limit'] ); unset( $this->mDefaultQuery['order'] ); unset( $this->mDefaultQuery['month'] ); unset( $this->mDefaultQuery['year'] ); } return $this->mDefaultQuery; } /** * Get the number of rows in the result set * * @return int */ public function getNumRows() { if ( !$this->mQueryDone ) { $this->doQuery(); } return $this->mResult->numRows(); } /** * Get a URL query array for the prev, next, first and last links. * * @stable to override * * @return array */ public function getPagingQueries() { if ( !$this->mQueryDone ) { $this->doQuery(); } # Don't announce the limit everywhere if it's the default $urlLimit = $this->mLimit == $this->mDefaultLimit ? null : $this->mLimit; if ( $this->mIsFirst ) { $prev = false; $first = false; } else { $prev = [ 'dir' => 'prev', 'offset' => implode( '|', (array)$this->mFirstShown ), 'limit' => $urlLimit ]; $first = [ 'offset' => null, 'limit' => $urlLimit ]; } if ( $this->mIsLast ) { $next = false; $last = false; } else { $next = [ 'offset' => implode( '|', (array)$this->mLastShown ), 'limit' => $urlLimit ]; $last = [ 'dir' => 'prev', 'offset' => null, 'limit' => $urlLimit ]; } return [ 'prev' => $prev, 'next' => $next, 'first' => $first, 'last' => $last ]; } /** * Get the current offset for the URL query parameter. * * @stable to override * @since 1.39 * @return string */ public function getOffsetQuery() { if ( $this->mIsBackwards ) { return implode( '|', (array)$this->mPastTheEndIndex ); } else { return $this->mOffset; } } /** * @stable to override * @since 1.39 * @return PagerNavigationBuilder */ public function getNavigationBuilder(): PagerNavigationBuilder { $pagingQueries = $this->getPagingQueries(); $baseQuery = array_merge( $this->getDefaultQuery(), [ // These query parameters are all defined here, even though some are null, // to ensure consistent order of parameters when they're used. 'dir' => null, 'offset' => $this->getOffsetQuery(), 'limit' => null, ] ); $navBuilder = new PagerNavigationBuilder( $this->getContext() ); $navBuilder ->setPage( $this->getTitle() ) ->setLinkQuery( $baseQuery ) ->setLimits( $this->mLimitsShown ) ->setLimitLinkQueryParam( 'limit' ) ->setCurrentLimit( $this->mLimit ) ->setPrevLinkQuery( $pagingQueries['prev'] ?: null ) ->setNextLinkQuery( $pagingQueries['next'] ?: null ) ->setFirstLinkQuery( $pagingQueries['first'] ?: null ) ->setLastLinkQuery( $pagingQueries['last'] ?: null ); return $navBuilder; } /** * Returns whether to show the "navigation bar" * @stable to override * * @return bool */ protected function isNavigationBarShown() { if ( !$this->mQueryDone ) { $this->doQuery(); } // Hide navigation by default if there is nothing to page return !( $this->mIsFirst && $this->mIsLast ); } /** * Returns an HTML string representing the result row $row. * Rows will be concatenated and returned by getBody() * * @param array|stdClass $row Database row * @return string */ abstract public function formatRow( $row ); /** * Provides all parameters needed for the main paged query. It returns * an associative array with the following elements: * tables => Table(s) for passing to Database::select() * fields => Field(s) for passing to Database::select(), may be * * conds => WHERE conditions * options => option array * join_conds => JOIN conditions * * @return array */ abstract public function getQueryInfo(); /** * Returns the name of the index field. If the pager supports multiple * orders, it may return an array of 'querykey' => 'indexfield' pairs, * so that a request with &order=querykey will use indexfield to sort. * In this case, the first returned key is the default. * * Needless to say, it's really not a good idea to use a non-unique index * for this! That won't page right. * * The pager may paginate on multiple fields in combination. If paginating * on multiple fields, they should be unique in combination (e.g. when * paginating on user and timestamp, rows may have the same user, rows may * have the same timestamp, but rows should all have a different combination * of user and timestamp). * * Examples: * - Always paginate on the user field: * 'user' * - Paginate on either the user or the timestamp field (default to user): * [ * 'name' => 'user', * 'time' => 'timestamp', * ] * - Always paginate on the combination of user and timestamp: * [ * [ 'user', 'timestamp' ] * ] * - Paginate on the user then timestamp, or the timestamp then user: * [ * 'nametime' => [ 'user', 'timestamp' ], * 'timename' => [ 'timestamp', 'user' ], * ] * * * @return string|string[]|array[] */ abstract public function getIndexField(); /** * Returns the names of secondary columns to order by in addition to the * column in getIndexField(). These fields will not be used in the pager * offset or in any links for users. * * If getIndexField() returns an array of 'querykey' => 'indexfield' pairs then * this must return a corresponding array of 'querykey' => [ fields... ] pairs * in order for a request with &order=querykey to use [ fields... ] to sort. * * If getIndexField() returns a string with the field to sort by, this must either: * 1 - return an associative array like above, but only the elements for the current * field will be used. * 2 - return a non-associative array, for secondary keys to use always. * * This is useful for pagers that GROUP BY a unique column (say page_id) * and ORDER BY another (say page_len). Using GROUP BY and ORDER BY both on * page_len,page_id avoids temp tables (given a page_len index). This would * also work if page_id was non-unique but we had a page_len,page_id index. * * @stable to override * * @return string[]|array[] */ protected function getExtraSortFields() { return []; } /** * Return the default sorting direction: DIR_ASCENDING or DIR_DESCENDING. * You can also have an associative array of ordertype => dir, * if multiple order types are supported. In this case getIndexField() * must return an array, and the keys of that must exactly match the keys * of this. * * For backward compatibility, this method's return value will be ignored * if $this->mDefaultDirection is already set when the constructor is * called, for instance if it's statically initialized. In that case the * value of that variable (which must be a boolean) will be used. * * Note that despite its name, this does not return the value of the * $this->mDefaultDirection member variable. That's the default for this * particular instantiation, which is a single value. This is the set of * all defaults for the class. * * @stable to override * * @return bool */ protected function getDefaultDirections() { return self::DIR_ASCENDING; } /** * @since 1.34 * @return LinkRenderer */ protected function getLinkRenderer() { if ( $this->linkRenderer === null ) { $this->linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer(); } return $this->linkRenderer; } } /** @deprecated class alias since 1.41 */ class_alias( IndexPager::class, 'IndexPager' ); PK ! \<X�2 �2 TablePager.phpnu �Iw�� <?php /** * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * http://www.gnu.org/copyleft/gpl.html * * @file */ namespace MediaWiki\Pager; use MediaWiki\Context\IContextSource; use MediaWiki\Html\Html; use MediaWiki\Linker\LinkRenderer; use MediaWiki\Parser\ParserOutput; use MediaWiki\Xml\XmlSelect; use OOUI\ButtonGroupWidget; use OOUI\ButtonWidget; use stdClass; /** * Table-based display with a user-selectable sort order * * @stable to extend * @ingroup Pager */ abstract class TablePager extends IndexPager { /** @var string */ protected $mSort; /** @var stdClass */ protected $mCurrentRow; /** * @stable to call * * @param IContextSource|null $context * @param LinkRenderer|null $linkRenderer */ public function __construct( ?IContextSource $context = null, ?LinkRenderer $linkRenderer = null ) { if ( $context ) { $this->setContext( $context ); } $this->mSort = $this->getRequest()->getText( 'sort' ); if ( !array_key_exists( $this->mSort, $this->getFieldNames() ) || !$this->isFieldSortable( $this->mSort ) ) { $this->mSort = $this->getDefaultSort(); } if ( $this->getRequest()->getBool( 'asc' ) ) { $this->mDefaultDirection = IndexPager::DIR_ASCENDING; } elseif ( $this->getRequest()->getBool( 'desc' ) ) { $this->mDefaultDirection = IndexPager::DIR_DESCENDING; } /* Else leave it at whatever the class default is */ // Parent constructor needs mSort set, so we call it last parent::__construct( null, $linkRenderer ); } /** * Get the formatted result list. * * Calls getBody() and getModuleStyles() and builds a ParserOutput object. (This is a bit hacky * but works well.) * * @since 1.24 * @return ParserOutput */ public function getBodyOutput() { $body = parent::getBody(); $pout = new ParserOutput; $pout->setRawText( $body ); return $pout; } /** * Get the formatted result list, with navigation bars. * * Calls getBody(), getNavigationBar() and getModuleStyles() and * builds a ParserOutput object. (This is a bit hacky but works well.) * * @since 1.24 * @return ParserOutput */ public function getFullOutput() { $navigation = $this->getNavigationBar(); $body = parent::getBody(); $pout = new ParserOutput; $pout->setRawText( $navigation . $body . $navigation ); $pout->addModuleStyles( $this->getModuleStyles() ); return $pout; } /** * @stable to override * @return string */ protected function getStartBody() { $sortClass = $this->getSortHeaderClass(); $s = ''; $fields = $this->getFieldNames(); // Make table header foreach ( $fields as $field => $name ) { if ( strval( $name ) == '' ) { $s .= Html::rawElement( 'th', [], "\u{00A0}" ) . "\n"; } elseif ( $this->isFieldSortable( $field ) ) { $query = [ 'sort' => $field, 'limit' => $this->mLimit ]; $linkType = null; $class = null; if ( $this->mSort == $field ) { // The table is sorted by this field already, make a link to sort in the other direction // We don't actually know in which direction other fields will be sorted by default… if ( $this->mDefaultDirection == IndexPager::DIR_DESCENDING ) { $linkType = 'asc'; $class = "$sortClass mw-datatable-is-sorted mw-datatable-is-descending"; $query['asc'] = '1'; $query['desc'] = ''; } else { $linkType = 'desc'; $class = "$sortClass mw-datatable-is-sorted mw-datatable-is-ascending"; $query['asc'] = ''; $query['desc'] = '1'; } } $link = $this->makeLink( htmlspecialchars( $name ), $query, $linkType ); $s .= Html::rawElement( 'th', [ 'class' => $class ], $link ) . "\n"; } else { $s .= Html::element( 'th', [], $name ) . "\n"; } } $ret = Html::openElement( 'table', [ 'class' => $this->getTableClass() ] ); $ret .= Html::rawElement( 'thead', [], Html::rawElement( 'tr', [], "\n" . $s . "\n" ) ); $ret .= Html::openElement( 'tbody' ) . "\n"; return $ret; } /** * @stable to override * @return string */ protected function getEndBody() { return "</tbody></table>\n"; } /** * @return string */ protected function getEmptyBody() { $colspan = count( $this->getFieldNames() ); $msgEmpty = $this->msg( 'table_pager_empty' )->text(); return Html::rawElement( 'tr', [], Html::element( 'td', [ 'colspan' => $colspan ], $msgEmpty ) ); } /** * @stable to override * @param stdClass $row * @return string HTML */ public function formatRow( $row ) { $this->mCurrentRow = $row; // In case formatValue etc need to know $s = Html::openElement( 'tr', $this->getRowAttrs( $row ) ) . "\n"; $fieldNames = $this->getFieldNames(); foreach ( $fieldNames as $field => $name ) { $value = $row->$field ?? null; $formatted = strval( $this->formatValue( $field, $value ) ); if ( $formatted == '' ) { $formatted = "\u{00A0}"; } $s .= Html::rawElement( 'td', $this->getCellAttrs( $field, $value ), $formatted ) . "\n"; } $s .= Html::closeElement( 'tr' ) . "\n"; return $s; } /** * Get a class name to be applied to the given row. * * @stable to override * * @param stdClass $row The database result row * @return string */ protected function getRowClass( $row ) { return ''; } /** * Get attributes to be applied to the given row. * * @stable to override * * @param stdClass $row The database result row * @return array Array of attribute => value */ protected function getRowAttrs( $row ) { return [ 'class' => $this->getRowClass( $row ) ]; } /** * @return stdClass */ protected function getCurrentRow() { return $this->mCurrentRow; } /** * Get any extra attributes to be applied to the given cell. Don't * take this as an excuse to hardcode styles; use classes and * CSS instead. Row context is available in $this->mCurrentRow * * @stable to override * * @param string $field The column * @param string $value The cell contents * @return array Array of attr => value */ protected function getCellAttrs( $field, $value ) { return [ 'class' => 'TablePager_col_' . $field ]; } /** * @inheritDoc * @stable to override */ public function getIndexField() { return $this->mSort; } /** * TablePager relies on `mw-datatable` for styling, see T214208 * * @stable to override * @return string */ protected function getTableClass() { return 'mw-datatable'; } /** * @stable to override * @return string */ protected function getNavClass() { return 'TablePager_nav'; } /** * @stable to override * @return string */ protected function getSortHeaderClass() { return 'TablePager_sort'; } /** * A navigation bar with images * * @stable to override * @return string HTML */ public function getNavigationBar() { if ( !$this->isNavigationBarShown() ) { return ''; } $this->getOutput()->enableOOUI(); $types = [ 'first', 'prev', 'next', 'last' ]; $queries = $this->getPagingQueries(); $buttons = []; $title = $this->getTitle(); foreach ( $types as $type ) { $buttons[] = new ButtonWidget( [ // Messages used here: // * table_pager_first // * table_pager_prev // * table_pager_next // * table_pager_last 'classes' => [ 'TablePager-button-' . $type ], 'flags' => [ 'progressive' ], 'framed' => false, 'label' => $this->msg( 'table_pager_' . $type )->text(), 'href' => $queries[ $type ] ? $title->getLinkURL( $queries[ $type ] + $this->getDefaultQuery() ) : null, 'icon' => $type === 'prev' ? 'previous' : $type, 'disabled' => $queries[ $type ] === false ] ); } return new ButtonGroupWidget( [ 'classes' => [ $this->getNavClass() ], 'items' => $buttons, ] ); } /** * @inheritDoc */ public function getModuleStyles() { return array_merge( parent::getModuleStyles(), [ 'oojs-ui.styles.icons-movement' ] ); } /** * Get a "<select>" element which has options for each of the allowed limits * * @param string[] $attribs Extra attributes to set * @return string HTML fragment */ public function getLimitSelect( $attribs = [] ) { $select = new XmlSelect( 'limit', false, $this->mLimit ); $select->addOptions( $this->getLimitSelectList() ); foreach ( $attribs as $name => $value ) { $select->setAttribute( $name, $value ); } return $select->getHTML(); } /** * Get a list of items to show in a "<select>" element of limits. * This can be passed directly to XmlSelect::addOptions(). * * @since 1.22 * @return array */ public function getLimitSelectList() { # Add the current limit from the query string # to avoid that the limit is lost after clicking Go next time if ( !in_array( $this->mLimit, $this->mLimitsShown ) ) { $this->mLimitsShown[] = $this->mLimit; sort( $this->mLimitsShown ); } $ret = []; foreach ( $this->mLimitsShown as $key => $value ) { # The pair is either $index => $limit, in which case the $value # will be numeric, or $limit => $text, in which case the $value # will be a string. if ( is_int( $value ) ) { $limit = $value; $text = $this->getLanguage()->formatNum( $limit ); } else { $limit = $key; $text = $value; } $ret[$text] = $limit; } return $ret; } /** * Get \<input type="hidden"\> elements for use in a method="get" form. * Resubmits all defined elements of the query string, except for a * exclusion list, passed in the $noResubmit parameter. * Also array values are discarded for security reasons (per WebRequest::getVal) * * @param array $noResubmit Parameters from the request query which should not be resubmitted * @return string HTML fragment */ public function getHiddenFields( $noResubmit = [] ) { $noResubmit = (array)$noResubmit; $query = $this->getRequest()->getQueryValues(); foreach ( $noResubmit as $name ) { unset( $query[$name] ); } $s = ''; foreach ( $query as $name => $value ) { if ( is_array( $value ) ) { // Per WebRequest::getVal: Array values are discarded for security reasons. continue; } $s .= Html::hidden( $name, $value ) . "\n"; } return $s; } /** * Get a form containing a limit selection dropdown * * @return string HTML fragment */ public function getLimitForm() { return Html::rawElement( 'form', [ 'method' => 'get', 'action' => wfScript(), ], "\n" . $this->getLimitDropdown() ) . "\n"; } /** * Gets a limit selection dropdown * * @return string */ private function getLimitDropdown() { # Make the select with some explanatory text $msgSubmit = $this->msg( 'table_pager_limit_submit' )->escaped(); return $this->msg( 'table_pager_limit' ) ->rawParams( $this->getLimitSelect() )->escaped() . "\n<input type=\"submit\" value=\"$msgSubmit\"/>\n" . $this->getHiddenFields( [ 'limit' ] ); } /** * Return true if the named field should be sortable by the UI, false * otherwise * * @param string $field * @return bool */ abstract protected function isFieldSortable( $field ); /** * Format a table cell. The return value should be HTML, but use an empty * string not   for empty cells. Do not include the <td> and </td>. * * The current result row is available as $this->mCurrentRow, in case you * need more context. * * @param string $name The database field name * @param string|null $value The value retrieved from the database, or null if * the row doesn't contain this field */ abstract public function formatValue( $name, $value ); /** * The database field name used as a default sort order. * * Note that this field will only be sorted on if isFieldSortable returns * true for this field. If not (e.g. paginating on multiple columns), this * should return empty string, and getIndexField should be overridden. * * @return string */ abstract public function getDefaultSort(); /** * An array mapping database field names to a textual description of the * field name, for use in the table header. The description should be plain * text, it will be HTML-escaped later. * * @return string[] */ abstract protected function getFieldNames(); } /** @deprecated class alias since 1.41 */ class_alias( TablePager::class, 'TablePager' ); PK ! ޢi % % ReverseChronologicalPager.phpnu �Iw�� <?php /** * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * http://www.gnu.org/copyleft/gpl.html * * @file */ namespace MediaWiki\Pager; use DateTime; use MediaWiki\Html\Html; use MediaWiki\Utils\MWTimestamp; use Wikimedia\Timestamp\TimestampException; /** * IndexPager with a formatted navigation bar. * * @stable to extend * @ingroup Pager */ abstract class ReverseChronologicalPager extends IndexPager { /** @var bool */ public $mDefaultDirection = IndexPager::DIR_DESCENDING; /** @var bool Whether to group items by date */ public $mGroupByDate = false; /** @var int */ public $mYear; /** @var int */ public $mMonth; /** @var int */ public $mDay; /** @var string */ private $lastHeaderDate; /** @var string */ protected $endOffset; /** * @param string $date * @return string */ protected function getHeaderRow( string $date ): string { $headingClass = $this->isFirstHeaderRow() ? // We use mw-index-pager- prefix here on the anticipation that this method will // eventually be upstreamed to apply to other pagers. For now we constrain the // change to ReverseChronologicalPager to reduce the risk of pages this touches // in case there are any bugs. 'mw-index-pager-list-header-first mw-index-pager-list-header' : 'mw-index-pager-list-header'; $s = $this->isFirstHeaderRow() ? '' : $this->getEndGroup(); $s .= Html::element( 'h4', [ 'class' => $headingClass, ], $date ); $s .= $this->getStartGroup(); return $s; } /** * Determines if a header row is needed based on the current state of the IndexPager. * * @since 1.38 * @param string $date Formatted date header * @return bool */ protected function isHeaderRowNeeded( string $date ): bool { if ( !$this->mGroupByDate ) { return false; } return $date && $this->lastHeaderDate !== $date; } /** * Determines whether the header row is the first that will be outputted to the page. * * @since 1.38 * @return bool */ final protected function isFirstHeaderRow(): bool { return $this->lastHeaderDate === null; } /** * Returns the name of the timestamp field. Subclass can override this to provide the * timestamp field if they are using a aliased field for getIndexField() * * @since 1.40 * @return string */ public function getTimestampField() { // This is a chronological pager, so the first column should be some kind of timestamp return is_array( $this->mIndexField ) ? $this->mIndexField[0] : $this->mIndexField; } /** * Get date from the timestamp * * @since 1.38 * @param string $timestamp * @return string Formatted date header */ final protected function getDateFromTimestamp( string $timestamp ) { return $this->getLanguage()->userDate( $timestamp, $this->getUser() ); } /** * @inheritDoc */ protected function getRow( $row ): string { $s = ''; $timestampField = $this->getTimestampField(); $timestamp = $row->$timestampField ?? null; $date = $timestamp ? $this->getDateFromTimestamp( $timestamp ) : null; if ( $date && $this->isHeaderRowNeeded( $date ) ) { $s .= $this->getHeaderRow( $date ); $this->lastHeaderDate = $date; } $s .= $this->formatRow( $row ); return $s; } /** * Start a new group of page rows. * * @stable to override * @since 1.38 * @return string */ protected function getStartGroup(): string { return "<ul class=\"mw-contributions-list\">\n"; } /** * End an existing group of page rows. * * @stable to override * @since 1.38 * @return string */ protected function getEndGroup(): string { return '</ul>'; } /** * @inheritDoc */ protected function getFooter(): string { return $this->getEndGroup(); } /** * @stable to override * @return string HTML */ public function getNavigationBar() { if ( !$this->isNavigationBarShown() ) { return ''; } if ( isset( $this->mNavigationBar ) ) { return $this->mNavigationBar; } $navBuilder = $this->getNavigationBuilder() ->setPrevMsg( 'pager-newer-n' ) ->setNextMsg( 'pager-older-n' ) ->setFirstMsg( 'histlast' ) ->setLastMsg( 'histfirst' ); $this->mNavigationBar = $navBuilder->getHtml(); return $this->mNavigationBar; } /** * Set and return the offset timestamp such that we can get all revisions with * a timestamp up to the specified parameters. * * @stable to override * * @param int $year Year up to which we want revisions * @param int $month Month up to which we want revisions * @param int $day [optional] Day up to which we want revisions. Default is end of month. * @return string|null Timestamp or null if year and month are false/invalid */ public function getDateCond( $year, $month, $day = -1 ) { $year = (int)$year; $month = (int)$month; $day = (int)$day; // Basic validity checks for year and month // If year and month are invalid, don't update the offset if ( $year <= 0 && ( $month <= 0 || $month >= 13 ) ) { return null; } $timestamp = self::getOffsetDate( $year, $month, $day ); try { // The timestamp used for DB queries is at midnight of the *next* day after the selected date. $selectedDate = new DateTime( $timestamp->getTimestamp( TS_ISO_8601 ) ); $selectedDate = $selectedDate->modify( '-1 day' ); $this->mYear = (int)$selectedDate->format( 'Y' ); $this->mMonth = (int)$selectedDate->format( 'm' ); $this->mDay = (int)$selectedDate->format( 'd' ); // Don't mess with mOffset which IndexPager uses $this->endOffset = $this->mDb->timestamp( $timestamp->getTimestamp() ); } catch ( TimestampException $e ) { // Invalid user provided timestamp (T149257) return null; } return $this->endOffset; } /** * Core logic of determining the offset timestamp such that we can get all items with * a timestamp up to the specified parameters. Given parameters for a day up to which to get * items, this function finds the timestamp of the day just after the end of the range for use * in a database strict inequality filter. * * This is separate from getDateCond so we can use this logic in other places, such as in * RangeChronologicalPager, where this function is used to convert year/month/day filter options * into a timestamp. * * @param int $year Year up to which we want revisions * @param int $month Month up to which we want revisions * @param int $day [optional] Day up to which we want revisions. Default is end of month. * @return MWTimestamp Timestamp or null if year and month are false/invalid */ public static function getOffsetDate( $year, $month, $day = -1 ) { // Given an optional year, month, and day, we need to generate a timestamp // to use as "WHERE rev_timestamp <= result" // Examples: year = 2006 equals < 20070101 (+000000) // year=2005, month=1 equals < 20050201 // year=2005, month=12 equals < 20060101 // year=2005, month=12, day=5 equals < 20051206 if ( $year <= 0 ) { // If no year given, assume the current one $timestamp = MWTimestamp::getInstance(); $year = $timestamp->format( 'Y' ); // If this month hasn't happened yet this year, go back to last year's month if ( $month > $timestamp->format( 'n' ) ) { $year--; } } if ( $month && $month > 0 && $month < 13 ) { // Day validity check after we have month and year checked $day = checkdate( $month, $day, $year ) ? $day : false; if ( $day && $day > 0 ) { // If we have a day, we want up to the day immediately afterward $day++; // Did we overflow the current month? if ( !checkdate( $month, $day, $year ) ) { $day = 1; $month++; } } else { // If no day, assume beginning of next month $day = 1; $month++; } // Did we overflow the current year? if ( $month > 12 ) { $month = 1; $year++; } } else { // No month implies we want up to the end of the year in question $month = 1; $day = 1; $year++; } $ymd = sprintf( "%04d%02d%02d", $year, $month, $day ); return MWTimestamp::getInstance( "{$ymd}000000" ); } /** * Return the end offset, extensions can use this if they are not in the context of subclass. * * @since 1.40 * @return string */ public function getEndOffset() { return $this->endOffset; } /** * @inheritDoc */ protected function buildQueryInfo( $offset, $limit, $order ) { [ $tables, $fields, $conds, $fname, $options, $join_conds ] = parent::buildQueryInfo( $offset, $limit, $order ); if ( $this->endOffset ) { $conds[] = $this->mDb->expr( $this->getTimestampField(), '<', $this->endOffset ); } return [ $tables, $fields, $conds, $fname, $options, $join_conds ]; } } /** @deprecated class alias since 1.41 */ class_alias( ReverseChronologicalPager::class, 'ReverseChronologicalPager' ); PK ! _�Y�� �� ContributionsPager.phpnu �Iw�� <?php /** * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * http://www.gnu.org/copyleft/gpl.html * * @file * @ingroup Pager */ namespace MediaWiki\Pager; use ChangesList; use ChangeTags; use HtmlArmor; use InvalidArgumentException; use MapCacheLRU; use MediaWiki\Cache\LinkBatchFactory; use MediaWiki\CommentFormatter\CommentFormatter; use MediaWiki\Context\IContextSource; use MediaWiki\HookContainer\HookContainer; use MediaWiki\HookContainer\HookRunner; use MediaWiki\Html\Html; use MediaWiki\Html\TemplateParser; use MediaWiki\Linker\Linker; use MediaWiki\Linker\LinkRenderer; use MediaWiki\MainConfigNames; use MediaWiki\MediaWikiServices; use MediaWiki\Parser\Sanitizer; use MediaWiki\Revision\RevisionRecord; use MediaWiki\Revision\RevisionStore; use MediaWiki\SpecialPage\SpecialPage; use MediaWiki\Title\NamespaceInfo; use MediaWiki\Title\Title; use MediaWiki\User\UserFactory; use MediaWiki\User\UserIdentity; use MediaWiki\User\UserRigorOptions; use stdClass; use Wikimedia\Rdbms\FakeResultWrapper; use Wikimedia\Rdbms\IResultWrapper; /** * Pager for Special:Contributions * @ingroup Pager */ abstract class ContributionsPager extends RangeChronologicalPager { /** @inheritDoc */ public $mGroupByDate = true; /** * @var string[] Local cache for escaped messages */ protected $messages; /** * @var bool Get revisions from the archive table (if true) or the revision table (if false) */ protected $isArchive; /** * @var string User name, or a string describing an IP address range */ protected $target; /** * @var string|int A single namespace number, or an empty string for all namespaces */ private $namespace; /** * @var string[]|false Name of tag to filter, or false to ignore tags */ private $tagFilter; /** * @var bool Set to true to invert the tag selection */ private $tagInvert; /** * @var bool Set to true to invert the namespace selection */ private $nsInvert; /** * @var bool Set to true to show both the subject and talk namespace, no matter which got * selected */ private $associated; /** * @var bool Set to true to show only deleted revisions */ private $deletedOnly; /** * @var bool Set to true to show only latest (a.k.a. current) revisions */ private $topOnly; /** * @var bool Set to true to show only new pages */ private $newOnly; /** * @var bool Set to true to hide edits marked as minor by the user */ private $hideMinor; /** * @var bool Set to true to only include mediawiki revisions. * (restricts extensions from executing additional queries to include their own contributions) */ private $revisionsOnly; /** @var bool */ private $preventClickjacking = false; protected ?Title $currentPage; protected ?RevisionRecord $currentRevRecord; /** * @var array */ private $mParentLens; /** @var UserIdentity */ protected $targetUser; /** * Set to protected to allow subclasses access for overrides */ protected TemplateParser $templateParser; private CommentFormatter $commentFormatter; private HookRunner $hookRunner; private LinkBatchFactory $linkBatchFactory; private NamespaceInfo $namespaceInfo; protected RevisionStore $revisionStore; /** @var string[] */ private $formattedComments = []; /** @var RevisionRecord[] Cached revisions by ID */ private $revisions = []; /** @var MapCacheLRU */ private $tagsCache; /** * Field names for various attributes. These may be overridden in a subclass, * for example for getting revisions from the archive table. */ protected string $revisionIdField = 'rev_id'; protected string $revisionParentIdField = 'rev_parent_id'; protected string $revisionTimestampField = 'rev_timestamp'; protected string $revisionLengthField = 'rev_len'; protected string $revisionDeletedField = 'rev_deleted'; protected string $revisionMinorField = 'rev_minor_edit'; protected string $userNameField = 'rev_user_text'; protected string $pageNamespaceField = 'page_namespace'; protected string $pageTitleField = 'page_title'; /** * @param LinkRenderer $linkRenderer * @param LinkBatchFactory $linkBatchFactory * @param HookContainer $hookContainer * @param RevisionStore $revisionStore * @param NamespaceInfo $namespaceInfo * @param CommentFormatter $commentFormatter * @param UserFactory $userFactory * @param IContextSource $context * @param array $options * @param UserIdentity|null $targetUser */ public function __construct( LinkRenderer $linkRenderer, LinkBatchFactory $linkBatchFactory, HookContainer $hookContainer, RevisionStore $revisionStore, NamespaceInfo $namespaceInfo, CommentFormatter $commentFormatter, UserFactory $userFactory, IContextSource $context, array $options, ?UserIdentity $targetUser ) { $this->isArchive = $options['isArchive'] ?? false; // Set ->target before calling parent::__construct() so // parent can call $this->getIndexField() and get the right result. Set // the rest too just to keep things simple. if ( $targetUser ) { $this->target = $options['target'] ?? $targetUser->getName(); $this->targetUser = $targetUser; } else { // Use target option // It's possible for the target to be empty. This is used by // ContribsPagerTest and does not cause newFromName() to return // false. It's probably not used by any production code. $this->target = $options['target'] ?? ''; // @phan-suppress-next-line PhanPossiblyNullTypeMismatchProperty RIGOR_NONE never returns null $this->targetUser = $userFactory->newFromName( $this->target, UserRigorOptions::RIGOR_NONE ); if ( !$this->targetUser ) { // This can happen if the target contained "#". Callers // typically pass user input through title normalization to // avoid it. throw new InvalidArgumentException( __METHOD__ . ': the user name is too ' . 'broken to use even with validation disabled.' ); } } $this->namespace = $options['namespace'] ?? ''; $this->tagFilter = $options['tagfilter'] ?? false; $this->tagInvert = $options['tagInvert'] ?? false; $this->nsInvert = $options['nsInvert'] ?? false; $this->associated = $options['associated'] ?? false; $this->deletedOnly = !empty( $options['deletedOnly'] ); $this->topOnly = !empty( $options['topOnly'] ); $this->newOnly = !empty( $options['newOnly'] ); $this->hideMinor = !empty( $options['hideMinor'] ); $this->revisionsOnly = !empty( $options['revisionsOnly'] ); parent::__construct( $context, $linkRenderer ); $msgs = [ 'diff', 'hist', 'pipe-separator', 'uctop', 'changeslist-nocomment', 'undeleteviewlink', 'undeleteviewlink', 'deletionlog', ]; foreach ( $msgs as $msg ) { $this->messages[$msg] = $this->msg( $msg )->escaped(); } // Date filtering: use timestamp if available $startTimestamp = ''; $endTimestamp = ''; if ( isset( $options['start'] ) && $options['start'] ) { $startTimestamp = $options['start'] . ' 00:00:00'; } if ( isset( $options['end'] ) && $options['end'] ) { $endTimestamp = $options['end'] . ' 23:59:59'; } $this->getDateRangeCond( $startTimestamp, $endTimestamp ); $this->templateParser = new TemplateParser(); $this->linkBatchFactory = $linkBatchFactory; $this->hookRunner = new HookRunner( $hookContainer ); $this->revisionStore = $revisionStore; $this->namespaceInfo = $namespaceInfo; $this->commentFormatter = $commentFormatter; $this->tagsCache = new MapCacheLRU( 50 ); } public function getDefaultQuery() { $query = parent::getDefaultQuery(); $query['target'] = $this->target; return $query; } /** * This method basically executes the exact same code as the parent class, though with * a hook added, to allow extensions to add additional queries. * * @param string $offset Index offset, inclusive * @param int $limit Exact query limit * @param bool $order IndexPager::QUERY_ASCENDING or IndexPager::QUERY_DESCENDING * @return IResultWrapper */ public function reallyDoQuery( $offset, $limit, $order ) { [ $tables, $fields, $conds, $fname, $options, $join_conds ] = $this->buildQueryInfo( $offset, $limit, $order ); $options['MAX_EXECUTION_TIME'] = $this->getConfig()->get( MainConfigNames::MaxExecutionTimeForExpensiveQueries ); /* * This hook will allow extensions to add in additional queries, so they can get their data * in My Contributions as well. Extensions should append their results to the $data array. * * Extension queries have to implement the navbar requirement as well. They should * - have a column aliased as $pager->getIndexField() * - have LIMIT set * - have a WHERE-clause that compares the $pager->getIndexField()-equivalent column to the offset * - have the ORDER BY specified based upon the details provided by the navbar * * See includes/Pager.php buildQueryInfo() method on how to build LIMIT, WHERE & ORDER BY * * &$data: an array of results of all contribs queries * $pager: the ContribsPager object hooked into * $offset: see phpdoc above * $limit: see phpdoc above * $descending: see phpdoc above */ $dbr = $this->getDatabase(); $data = [ $dbr->newSelectQueryBuilder() ->tables( is_array( $tables ) ? $tables : [ $tables ] ) ->fields( $fields ) ->conds( $conds ) ->caller( $fname ) ->options( $options ) ->joinConds( $join_conds ) ->setMaxExecutionTime( $this->getConfig()->get( MainConfigNames::MaxExecutionTimeForExpensiveQueries ) ) ->fetchResultSet() ]; if ( !$this->revisionsOnly ) { // These hooks were moved from ContribsPager and DeletedContribsPager. For backwards // compatability, they keep the same names. But they should be run for any contributions // pager, otherwise the entries from extensions would be missing. $reallyDoQueryHook = $this->isArchive ? 'onDeletedContribsPager__reallyDoQuery' : 'onContribsPager__reallyDoQuery'; // TODO: Range offsets are fairly important and all handlers should take care of it. // If this hook will be replaced (e.g. unified with the DeletedContribsPager one), // please consider passing [ $this->endOffset, $this->startOffset ] to it (T167577). $this->hookRunner->$reallyDoQueryHook( $data, $this, $offset, $limit, $order ); } $result = []; // loop all results and collect them in an array foreach ( $data as $query ) { foreach ( $query as $i => $row ) { // If the query results are in descending order, the indexes must also be in descending order $index = $order === self::QUERY_ASCENDING ? $i : $limit - 1 - $i; // Left-pad with zeroes, because these values will be sorted as strings $index = str_pad( (string)$index, strlen( (string)$limit ), '0', STR_PAD_LEFT ); // use index column as key, allowing us to easily sort in PHP $result[$row->{$this->getIndexField()} . "-$index"] = $row; } } // sort results if ( $order === self::QUERY_ASCENDING ) { ksort( $result ); } else { krsort( $result ); } // enforce limit $result = array_slice( $result, 0, $limit ); // get rid of array keys $result = array_values( $result ); return new FakeResultWrapper( $result ); } /** * Get queryInfo for the main query selecting revisions, not including * filtering on namespace, date, etc. * * @return array */ abstract protected function getRevisionQuery(); public function getQueryInfo() { $queryInfo = $this->getRevisionQuery(); if ( $this->deletedOnly ) { $queryInfo['conds'][] = $this->revisionDeletedField . ' != 0'; } if ( !$this->isArchive && $this->topOnly ) { $queryInfo['conds'][] = $this->revisionIdField . ' = page_latest'; } if ( $this->newOnly ) { $queryInfo['conds'][] = $this->revisionParentIdField . ' = 0'; } if ( $this->hideMinor ) { $queryInfo['conds'][] = $this->revisionMinorField . ' = 0'; } $queryInfo['conds'] = array_merge( $queryInfo['conds'], $this->getNamespaceCond() ); // Paranoia: avoid brute force searches (T19342) $dbr = $this->getDatabase(); if ( !$this->getAuthority()->isAllowed( 'deletedhistory' ) ) { $queryInfo['conds'][] = $dbr->bitAnd( $this->revisionDeletedField, RevisionRecord::DELETED_USER ) . ' = 0'; } elseif ( !$this->getAuthority()->isAllowedAny( 'suppressrevision', 'viewsuppressed' ) ) { $queryInfo['conds'][] = $dbr->bitAnd( $this->revisionDeletedField, RevisionRecord::SUPPRESSED_USER ) . ' != ' . RevisionRecord::SUPPRESSED_USER; } // $this->getIndexField() must be in the result rows, as reallyDoQuery() tries to access it. $indexField = $this->getIndexField(); if ( $indexField !== $this->revisionTimestampField ) { $queryInfo['fields'][] = $indexField; } MediaWikiServices::getInstance()->getChangeTagsStore()->modifyDisplayQuery( $queryInfo['tables'], $queryInfo['fields'], $queryInfo['conds'], $queryInfo['join_conds'], $queryInfo['options'], $this->tagFilter, $this->tagInvert, ); if ( !$this->isArchive ) { $this->hookRunner->onContribsPager__getQueryInfo( $this, $queryInfo ); } return $queryInfo; } protected function getNamespaceCond() { if ( $this->namespace !== '' ) { $dbr = $this->getDatabase(); $namespaces = [ $this->namespace ]; $eq_op = $this->nsInvert ? '!=' : '='; if ( $this->associated ) { $namespaces[] = $this->namespaceInfo->getAssociated( $this->namespace ); } return [ $dbr->expr( $this->pageNamespaceField, $eq_op, $namespaces ) ]; } return []; } /** * @return false|string[] */ public function getTagFilter() { return $this->tagFilter; } /** * @return bool */ public function getTagInvert() { return $this->tagInvert; } /** * @return string */ public function getTarget() { return $this->target; } /** * @return bool */ public function isNewOnly() { return $this->newOnly; } /** * @return int|string */ public function getNamespace() { return $this->namespace; } protected function doBatchLookups() { # Do a link batch query $this->mResult->seek( 0 ); $parentRevIds = []; $this->mParentLens = []; $revisions = []; $linkBatch = $this->linkBatchFactory->newLinkBatch(); # Give some pointers to make (last) links foreach ( $this->mResult as $row ) { $revisionRecord = $this->tryCreatingRevisionRecord( $row ); if ( !$revisionRecord ) { continue; } if ( isset( $row->{$this->revisionParentIdField} ) && $row->{$this->revisionParentIdField} ) { $parentRevIds[] = (int)$row->{$this->revisionParentIdField}; } $this->mParentLens[(int)$row->{$this->revisionIdField}] = $row->{$this->revisionLengthField}; if ( $this->target !== $row->{$this->userNameField} ) { // If the target does not match the author, batch the author's talk page $linkBatch->add( NS_USER_TALK, $row->{$this->userNameField} ); } $linkBatch->add( $row->{$this->pageNamespaceField}, $row->{$this->pageTitleField} ); $revisions[$row->{$this->revisionIdField}] = $this->createRevisionRecord( $row ); } // Fetch rev_len/ar_len for revisions not already scanned above // TODO: is it possible to make this fully abstract? if ( $this->isArchive ) { $parentRevIds = array_diff( $parentRevIds, array_keys( $this->mParentLens ) ); if ( $parentRevIds ) { $result = $this->revisionStore ->newArchiveSelectQueryBuilder( $this->getDatabase() ) ->clearFields() ->fields( [ $this->revisionIdField, $this->revisionLengthField ] ) ->where( [ $this->revisionIdField => $parentRevIds ] ) ->caller( __METHOD__ ) ->fetchResultSet(); foreach ( $result as $row ) { $this->mParentLens[(int)$row->{$this->revisionIdField}] = $row->{$this->revisionLengthField}; } } } $this->mParentLens += $this->revisionStore->getRevisionSizes( array_diff( $parentRevIds, array_keys( $this->mParentLens ) ) ); $linkBatch->execute(); $revisionBatch = $this->commentFormatter->createRevisionBatch() ->authority( $this->getAuthority() ) ->revisions( $revisions ); if ( !$this->isArchive ) { // Only show public comments, because this page might be public $revisionBatch = $revisionBatch->hideIfDeleted(); } $this->formattedComments = $revisionBatch->execute(); # For performance, save the revision objects for later. # The array is indexed by rev_id. doBatchLookups() may be called # multiple times with different results, so merge the revisions array, # ignoring any duplicates. $this->revisions += $revisions; } /** * @inheritDoc */ protected function getStartBody() { return "<section class='mw-pager-body'>\n"; } /** * @inheritDoc */ protected function getEndBody() { return "</section>\n"; } /** * If the object looks like a revision row, or corresponds to a previously * cached revision, return the RevisionRecord. Otherwise, return null. * * @since 1.35 * * @param mixed $row * @param Title|null $title * @return RevisionRecord|null */ public function tryCreatingRevisionRecord( $row, $title = null ) { if ( $row instanceof stdClass && isset( $row->{$this->revisionIdField} ) && isset( $this->revisions[$row->{$this->revisionIdField}] ) ) { return $this->revisions[$row->{$this->revisionIdField}]; } if ( $this->isArchive && $this->revisionStore->isRevisionRow( $row, 'archive' ) ) { return $this->revisionStore->newRevisionFromArchiveRow( $row, 0, $title ); } if ( !$this->isArchive && $this->revisionStore->isRevisionRow( $row ) ) { return $this->revisionStore->newRevisionFromRow( $row, 0, $title ); } return null; } /** * Create a revision record from a $row that models a revision. * * @param mixed $row * @param Title|null $title * @return RevisionRecord */ public function createRevisionRecord( $row, $title = null ) { if ( $this->isArchive ) { return $this->revisionStore->newRevisionFromArchiveRow( $row, 0, $title ); } return $this->revisionStore->newRevisionFromRow( $row, 0, $title ); } /** * Populate the HTML attributes. * * @param mixed $row * @param string[] &$attributes */ protected function populateAttributes( $row, &$attributes ) { $attributes['data-mw-revid'] = $this->currentRevRecord->getId(); } /** * Format a link to an article. * * @param mixed $row * @return string */ protected function formatArticleLink( $row ) { if ( !$this->currentPage ) { return ''; } $dir = $this->getLanguage()->getDir(); return Html::rawElement( 'bdi', [ 'dir' => $dir ], $this->getLinkRenderer()->makeLink( $this->currentPage, $this->currentPage->getPrefixedText(), [ 'class' => 'mw-contributions-title' ], $this->currentPage->isRedirect() ? [ 'redirect' => 'no' ] : [] ) ); } /** * Format diff and history links. * * @param mixed $row * @return string */ protected function formatDiffHistLinks( $row ) { if ( !$this->currentPage || !$this->currentRevRecord ) { return ''; } if ( $this->isArchive ) { // Add the same links as DeletedContribsPager::formatRevisionRow $undelete = SpecialPage::getTitleFor( 'Undelete' ); if ( $this->getAuthority()->isAllowed( 'deletedtext' ) ) { $last = $this->getLinkRenderer()->makeKnownLink( $undelete, new HtmlArmor( $this->messages['diff'] ), [], [ 'target' => $this->currentPage->getPrefixedText(), 'timestamp' => $this->currentRevRecord->getTimestamp(), 'diff' => 'prev' ] ); } else { $last = $this->messages['diff']; } $logs = SpecialPage::getTitleFor( 'Log' ); $dellog = $this->getLinkRenderer()->makeKnownLink( $logs, new HtmlArmor( $this->messages['deletionlog'] ), [], [ 'type' => 'delete', 'page' => $this->currentPage->getPrefixedText() ] ); $reviewlink = $this->getLinkRenderer()->makeKnownLink( SpecialPage::getTitleFor( 'Undelete', $this->currentPage->getPrefixedDBkey() ), new HtmlArmor( $this->messages['undeleteviewlink'] ) ); return Html::rawElement( 'span', [ 'class' => 'mw-deletedcontribs-tools' ], $this->msg( 'parentheses' )->rawParams( $this->getLanguage()->pipeList( [ $last, $dellog, $reviewlink ] ) )->escaped() ); } else { # Is there a visible previous revision? if ( $this->currentRevRecord->getParentId() !== 0 && $this->currentRevRecord->userCan( RevisionRecord::DELETED_TEXT, $this->getAuthority() ) ) { $difftext = $this->getLinkRenderer()->makeKnownLink( $this->currentPage, new HtmlArmor( $this->messages['diff'] ), [ 'class' => 'mw-changeslist-diff' ], [ 'diff' => 'prev', 'oldid' => $row->{$this->revisionIdField}, ] ); } else { $difftext = $this->messages['diff']; } $histlink = $this->getLinkRenderer()->makeKnownLink( $this->currentPage, new HtmlArmor( $this->messages['hist'] ), [ 'class' => 'mw-changeslist-history' ], [ 'action' => 'history' ] ); // While it might be tempting to use a list here // this would result in clutter and slows down navigating the content // in assistive technology. // See https://phabricator.wikimedia.org/T205581#4734812 return Html::rawElement( 'span', [ 'class' => 'mw-changeslist-links' ], // The spans are needed to ensure the dividing '|' elements are not // themselves styled as links. Html::rawElement( 'span', [], $difftext ) . ' ' . // Space needed for separating two words. Html::rawElement( 'span', [], $histlink ) ); } } /** * Format a date link. * * @param mixed $row * @return string */ protected function formatDateLink( $row ) { if ( !$this->currentPage || !$this->currentRevRecord ) { return ''; } if ( $this->isArchive ) { $date = $this->getLanguage()->userTimeAndDate( $this->currentRevRecord->getTimestamp(), $this->getUser() ); if ( $this->getAuthority()->isAllowed( 'undelete' ) && $this->currentRevRecord->userCan( RevisionRecord::DELETED_TEXT, $this->getAuthority() ) ) { $dateLink = $this->getLinkRenderer()->makeKnownLink( SpecialPage::getTitleFor( 'Undelete' ), $date, [ 'class' => 'mw-changeslist-date' ], [ 'target' => $this->currentPage->getPrefixedText(), 'timestamp' => $this->currentRevRecord->getTimestamp() ] ); } else { $dateLink = htmlspecialchars( $date ); } if ( $this->currentRevRecord->isDeleted( RevisionRecord::DELETED_TEXT ) ) { $class = Linker::getRevisionDeletedClass( $this->currentRevRecord ); $dateLink = Html::rawElement( 'span', [ 'class' => $class ], $dateLink ); } } else { $dateLink = ChangesList::revDateLink( $this->currentRevRecord, $this->getAuthority(), $this->getLanguage(), $this->currentPage ); } return $dateLink; } /** * Format annotation and add extra class if a row represents a latest revision. * * @param mixed $row * @param string[] &$classes * @return string */ protected function formatTopMarkText( $row, &$classes ) { if ( !$this->currentPage || !$this->currentRevRecord ) { return ''; } $topmarktext = ''; if ( !$this->isArchive ) { $pagerTools = new PagerTools( $this->currentRevRecord, null, $row->{$this->revisionIdField} === $row->page_latest && !$row->page_is_new, $this->hookRunner, $this->currentPage, $this->getContext(), $this->getLinkRenderer() ); if ( $row->{$this->revisionIdField} === $row->page_latest ) { $topmarktext .= '<span class="mw-uctop">' . $this->messages['uctop'] . '</span>'; $classes[] = 'mw-contributions-current'; } if ( $pagerTools->shouldPreventClickjacking() ) { $this->setPreventClickjacking( true ); } $topmarktext .= $pagerTools->toHTML(); } return $topmarktext; } /** * Format annotation to show the size of a diff. * * @param mixed $row * @return string */ protected function formatCharDiff( $row ) { if ( $row->{$this->revisionParentIdField} === null ) { // For some reason rev_parent_id isn't populated for this row. // Its rumoured this is true on wikipedia for some revisions (T36922). // Next best thing is to have the total number of bytes. $chardiff = ' <span class="mw-changeslist-separator"></span> '; $chardiff .= Linker::formatRevisionSize( $row->{$this->revisionLengthField} ); $chardiff .= ' <span class="mw-changeslist-separator"></span> '; } else { $parentLen = 0; if ( isset( $this->mParentLens[$row->{$this->revisionParentIdField}] ) ) { $parentLen = $this->mParentLens[$row->{$this->revisionParentIdField}]; } $chardiff = ' <span class="mw-changeslist-separator"></span> '; $chardiff .= ChangesList::showCharacterDifference( $parentLen, $row->{$this->revisionLengthField}, $this->getContext() ); $chardiff .= ' <span class="mw-changeslist-separator"></span> '; } return $chardiff; } /** * Format a comment for a revision. * * @param mixed $row * @return string */ protected function formatComment( $row ) { $comment = $this->formattedComments[$row->{$this->revisionIdField}]; if ( $comment === '' ) { $defaultComment = $this->messages['changeslist-nocomment']; $comment = "<span class=\"comment mw-comment-none\">$defaultComment</span>"; } // Don't wrap result of this with <bdi> or any other element, see T377555 return $comment; } /** * Format a user link. * * @param mixed $row * @return string */ protected function formatUserLink( $row ) { if ( !$this->currentRevRecord ) { return ''; } $dir = $this->getLanguage()->getDir(); // When the author is different from the target, always show user and user talk links $userlink = ''; $revUser = $this->currentRevRecord->getUser(); $revUserId = $revUser ? $revUser->getId() : 0; $revUserText = $revUser ? $revUser->getName() : ''; if ( $this->target !== $revUserText ) { $userlink = ' <span class="mw-changeslist-separator"></span> ' . Html::rawElement( 'bdi', [ 'dir' => $dir ], Linker::userLink( $revUserId, $revUserText ) ); $userlink .= ' ' . $this->msg( 'parentheses' )->rawParams( Linker::userTalkLink( $revUserId, $revUserText ) )->escaped() . ' '; } return $userlink; } /** * @param mixed $row * @return string[] */ protected function formatFlags( $row ) { if ( !$this->currentRevRecord ) { return []; } $flags = []; if ( $this->currentRevRecord->getParentId() === 0 ) { $flags[] = ChangesList::flag( 'newpage' ); } if ( $this->currentRevRecord->isMinor() ) { $flags[] = ChangesList::flag( 'minor' ); } return $flags; } /** * Format link for changing visibility. * * @param mixed $row * @return string */ protected function formatVisibilityLink( $row ) { if ( !$this->currentPage || !$this->currentRevRecord ) { return ''; } $del = Linker::getRevDeleteLink( $this->getAuthority(), $this->currentRevRecord, $this->currentPage ); if ( $del !== '' ) { $del .= ' '; } return $del; } /** * @param mixed $row * @param string[] &$classes * @return string */ protected function formatTags( $row, &$classes ) { # Tags, if any. Save some time using a cache. [ $tagSummary, $newClasses ] = $this->tagsCache->getWithSetCallback( $this->tagsCache->makeKey( $row->ts_tags ?? '', $this->getUser()->getName(), $this->getLanguage()->getCode() ), fn () => ChangeTags::formatSummaryRow( $row->ts_tags, null, $this->getContext() ) ); $classes = array_merge( $classes, $newClasses ); return $tagSummary; } /** * Check whether the revision author is deleted * * @param mixed $row * @return bool */ public function revisionUserIsDeleted( $row ) { return $this->currentRevRecord->isDeleted( RevisionRecord::DELETED_USER ); } /** * Generates each row in the contributions list. * * Contributions which are marked "top" are currently on top of the history. * For these contributions, a [rollback] link is shown for users with roll- * back privileges. The rollback link restores the most recent version that * was not written by the target user. * * @todo This would probably look a lot nicer in a table. * @param stdClass|mixed $row * @return string */ public function formatRow( $row ) { $ret = ''; $classes = []; $attribs = []; $this->currentPage = null; $this->currentRevRecord = null; // Create a title for the revision if possible // Rows from the hook may not include title information if ( isset( $row->{$this->pageNamespaceField} ) && isset( $row->{$this->pageTitleField} ) ) { $this->currentPage = Title::makeTitle( $row->{$this->pageNamespaceField}, $row->{$this->pageTitleField} ); } // Flow overrides the ContribsPager::reallyDoQuery hook, causing this // function to be called with a special object for $row. It expects us // skip formatting so that the row can be formatted by the // ContributionsLineEnding hook below. // FIXME: have some better way for extensions to provide formatted rows. $this->currentRevRecord = $this->tryCreatingRevisionRecord( $row, $this->currentPage ); if ( $this->revisionsOnly || ( $this->currentRevRecord && $this->currentPage ) ) { $this->populateAttributes( $row, $attribs ); $templateParams = $this->getTemplateParams( $row, $classes ); $ret = $this->getProcessedTemplate( $templateParams ); } // Let extensions add data $lineEndingsHook = $this->isArchive ? 'onDeletedContributionsLineEnding' : 'onContributionsLineEnding'; $this->hookRunner->$lineEndingsHook( $this, $ret, $row, $classes, $attribs ); $attribs = array_filter( $attribs, [ Sanitizer::class, 'isReservedDataAttribute' ], ARRAY_FILTER_USE_KEY ); // TODO: Handle exceptions in the catch block above. Do any extensions rely on // receiving empty rows? if ( $classes === [] && $attribs === [] && $ret === '' ) { wfDebug( "Dropping ContributionsSpecialPage row that could not be formatted" ); return "<!-- Could not format ContributionsSpecialPage row. -->\n"; } $attribs['class'] = $classes; // FIXME: The signature of the ContributionsLineEnding hook makes it // very awkward to move this LI wrapper into the template. return Html::rawElement( 'li', $attribs, $ret ) . "\n"; } /** * Generate array of template parameters to pass to the template for rendering. * Function can be overriden by classes to add/remove their own parameters. * * @since 1.43 * * @param stdClass|mixed $row * @param string[] &$classes * @return mixed[] */ public function getTemplateParams( $row, &$classes ) { $link = $this->formatArticleLink( $row ); $topmarktext = $this->formatTopMarkText( $row, $classes ); $diffHistLinks = $this->formatDiffHistLinks( $row ); $dateLink = $this->formatDateLink( $row ); $chardiff = $this->formatCharDiff( $row ); $comment = $this->formatComment( $row ); $userlink = $this->formatUserLink( $row ); $flags = $this->formatFlags( $row ); $del = $this->formatVisibilityLink( $row ); $tagSummary = $this->formatTags( $row, $classes ); if ( !$this->isArchive ) { $this->hookRunner->onSpecialContributions__formatRow__flags( $this->getContext(), $row, $flags ); } $templateParams = [ 'del' => $del, 'timestamp' => $dateLink, 'diffHistLinks' => $diffHistLinks, 'charDifference' => $chardiff, 'flags' => $flags, 'articleLink' => $link, 'userlink' => $userlink, 'logText' => $comment, 'topmarktext' => $topmarktext, 'tagSummary' => $tagSummary, ]; # Denote if username is redacted for this edit if ( $this->revisionUserIsDeleted( $row ) ) { $templateParams['rev-deleted-user-contribs'] = $this->msg( 'rev-deleted-user-contribs' )->escaped(); } return $templateParams; } /** * Return the processed template. Function can be overriden by classes * to provide their own template parser. * * @since 1.43 * * @param string[] $templateParams * @return string */ public function getProcessedTemplate( $templateParams ) { return $this->templateParser->processTemplate( 'SpecialContributionsLine', $templateParams ); } /** * Overwrite Pager function and return a helpful comment * @return string */ protected function getSqlComment() { if ( $this->namespace || $this->deletedOnly ) { // potentially slow, see CR r58153 return 'contributions page filtered for namespace or RevisionDeleted edits'; } else { return 'contributions page unfiltered'; } } /** * @deprecated since 1.38, use ::setPreventClickjacking() instead */ protected function preventClickjacking() { $this->setPreventClickjacking( true ); } /** * @param bool $enable * @since 1.38 */ protected function setPreventClickjacking( bool $enable ) { $this->preventClickjacking = $enable; } /** * @return bool */ public function getPreventClickjacking() { return $this->preventClickjacking; } } PK ! ��HC( ( AlphabeticPager.phpnu �Iw�� <?php /** * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * http://www.gnu.org/copyleft/gpl.html * * @file */ namespace MediaWiki\Pager; /** * IndexPager with an alphabetic list and a formatted navigation bar * * @stable to extend * @ingroup Pager */ abstract class AlphabeticPager extends IndexPager { /** * @stable to override * @return string HTML */ public function getNavigationBar() { if ( !$this->isNavigationBarShown() ) { return ''; } if ( isset( $this->mNavigationBar ) ) { return $this->mNavigationBar; } $navBuilder = $this->getNavigationBuilder() ->setPrevMsg( 'prevn' ) ->setNextMsg( 'nextn' ) ->setFirstMsg( 'page_first' ) ->setLastMsg( 'page_last' ); $this->mNavigationBar = $navBuilder->getHtml(); return $this->mNavigationBar; } } /** @deprecated class alias since 1.41 */ class_alias( AlphabeticPager::class, 'AlphabeticPager' ); PK ! �8� � Pager.phpnu �Iw�� PK ! e��$H H RangeChronologicalPager.phpnu �Iw�� PK ! 3�lt lt � IndexPager.phpnu �Iw�� PK ! \<X�2 �2 K� TablePager.phpnu �Iw�� PK ! ޢi % % � ReverseChronologicalPager.phpnu �Iw�� PK ! _�Y�� �� u� ContributionsPager.phpnu �Iw�� PK ! ��HC( ( Kf AlphabeticPager.phpnu �Iw�� PK F �l
| ver. 1.1 | |
.
| PHP 8.4.22 | Ð“ÐµÐ½ÐµÑ€Ð°Ñ†Ð¸Ñ Ñтраницы: 0.01 |
proxy
|
phpinfo
|
ÐаÑтройка