diff options
Diffstat (limited to 'includes/logging')
-rw-r--r-- | includes/logging/LogEntry.php | 518 | ||||
-rw-r--r-- | includes/logging/LogEventsList.php | 751 | ||||
-rw-r--r-- | includes/logging/LogFormatter.php | 673 | ||||
-rw-r--r-- | includes/logging/LogPage.php | 634 | ||||
-rw-r--r-- | includes/logging/LogPager.php | 356 | ||||
-rw-r--r-- | includes/logging/PatrolLog.php | 58 |
6 files changed, 2990 insertions, 0 deletions
diff --git a/includes/logging/LogEntry.php b/includes/logging/LogEntry.php new file mode 100644 index 00000000..4aa6a826 --- /dev/null +++ b/includes/logging/LogEntry.php @@ -0,0 +1,518 @@ +<?php +/** + * Contain classes for dealing with individual log entries + * + * This is how I see the log system history: + * - appending to plain wiki pages + * - formatting log entries based on database fields + * - user is now part of the action message + * + * @file + * @author Niklas Laxström + * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License 2.0 or later + * @since 1.19 + */ + +/** + * Interface for log entries. Every log entry has these methods. + * @since 1.19 + */ +interface LogEntry { + + /** + * The main log type. + * @return string + */ + public function getType(); + + /** + * The log subtype. + * @return string + */ + public function getSubtype(); + + /** + * The full logtype in format maintype/subtype. + * @return string + */ + public function getFullType(); + + /** + * Get the extra parameters stored for this message. + * @return array + */ + public function getParameters(); + + /** + * Get the user for performed this action. + * @return User + */ + public function getPerformer(); + + /** + * Get the target page of this action. + * @return Title + */ + public function getTarget(); + + /** + * Get the timestamp when the action was executed. + * @return string + */ + public function getTimestamp(); + + /** + * Get the user provided comment. + * @return string + */ + public function getComment(); + + /** + * Get the access restriction. + * @return string + */ + public function getDeleted(); + + /** + * @param $field Integer: one of LogPage::DELETED_* bitfield constants + * @return Boolean + */ + public function isDeleted( $field ); +} + +/** + * Extends the LogEntryInterface with some basic functionality + * @since 1.19 + */ +abstract class LogEntryBase implements LogEntry { + + public function getFullType() { + return $this->getType() . '/' . $this->getSubtype(); + } + + public function isDeleted( $field ) { + return ( $this->getDeleted() & $field ) === $field; + } + + /** + * Whether the parameters for this log are stored in new or + * old format. + */ + public function isLegacy() { + return false; + } + +} + +/** + * This class wraps around database result row. + * @since 1.19 + */ +class DatabaseLogEntry extends LogEntryBase { + // Static-> + + /** + * Returns array of information that is needed for querying + * log entries. Array contains the following keys: + * tables, fields, conds, options and join_conds + * @return array + */ + public static function getSelectQueryData() { + $tables = array( 'logging', 'user' ); + $fields = array( + 'log_id', 'log_type', 'log_action', 'log_timestamp', + 'log_user', 'log_user_text', + 'log_namespace', 'log_title', // unused log_page + 'log_comment', 'log_params', 'log_deleted', + 'user_id', 'user_name', 'user_editcount', + ); + + $joins = array( + // IP's don't have an entry in user table + 'user' => array( 'LEFT JOIN', 'log_user=user_id' ), + ); + + return array( + 'tables' => $tables, + 'fields' => $fields, + 'conds' => array(), + 'options' => array(), + 'join_conds' => $joins, + ); + } + + /** + * Constructs new LogEntry from database result row. + * Supports rows from both logging and recentchanges table. + * @param $row + * @return DatabaseLogEntry + */ + public static function newFromRow( $row ) { + if ( is_array( $row ) && isset( $row['rc_logid'] ) ) { + return new RCDatabaseLogEntry( (object) $row ); + } else { + return new self( $row ); + } + } + + // Non-static-> + + /// Database result row. + protected $row; + + protected function __construct( $row ) { + $this->row = $row; + } + + /** + * Returns the unique database id. + * @return int + */ + public function getId() { + return (int)$this->row->log_id; + } + + /** + * Returns whatever is stored in the database field. + * @return string + */ + protected function getRawParameters() { + return $this->row->log_params; + } + + // LogEntryBase-> + + public function isLegacy() { + // This does the check + $this->getParameters(); + return $this->legacy; + } + + // LogEntry-> + + public function getType() { + return $this->row->log_type; + } + + public function getSubtype() { + return $this->row->log_action; + } + + public function getParameters() { + if ( !isset( $this->params ) ) { + $blob = $this->getRawParameters(); + wfSuppressWarnings(); + $params = unserialize( $blob ); + wfRestoreWarnings(); + if ( $params !== false ) { + $this->params = $params; + $this->legacy = false; + } else { + $this->params = $blob === '' ? array() : explode( "\n", $blob ); + $this->legacy = true; + } + } + return $this->params; + } + + public function getPerformer() { + $userId = (int) $this->row->log_user; + if ( $userId !== 0 ) { // logged-in users + if ( isset( $this->row->user_name ) ) { + return User::newFromRow( $this->row ); + } else { + return User::newFromId( $userId ); + } + } else { // IP users + $userText = $this->row->log_user_text; + return User::newFromName( $userText, false ); + } + } + + public function getTarget() { + $namespace = $this->row->log_namespace; + $page = $this->row->log_title; + $title = Title::makeTitle( $namespace, $page ); + return $title; + } + + public function getTimestamp() { + return wfTimestamp( TS_MW, $this->row->log_timestamp ); + } + + public function getComment() { + return $this->row->log_comment; + } + + public function getDeleted() { + return $this->row->log_deleted; + } + +} + +class RCDatabaseLogEntry extends DatabaseLogEntry { + + public function getId() { + return $this->row->rc_logid; + } + + protected function getRawParameters() { + return $this->row->rc_params; + } + + // LogEntry-> + + public function getType() { + return $this->row->rc_log_type; + } + + public function getSubtype() { + return $this->row->rc_log_action; + } + + public function getPerformer() { + $userId = (int) $this->row->rc_user; + if ( $userId !== 0 ) { + return User::newFromId( $userId ); + } else { + $userText = $this->row->rc_user_text; + // Might be an IP, don't validate the username + return User::newFromName( $userText, false ); + } + } + + public function getTarget() { + $namespace = $this->row->rc_namespace; + $page = $this->row->rc_title; + $title = Title::makeTitle( $namespace, $page ); + return $title; + } + + public function getTimestamp() { + return wfTimestamp( TS_MW, $this->row->rc_timestamp ); + } + + public function getComment() { + return $this->row->rc_comment; + } + + public function getDeleted() { + return $this->row->rc_deleted; + } + +} + +/** + * Class for creating log entries manually, for + * example to inject them into the database. + * @since 1.19 + */ +class ManualLogEntry extends LogEntryBase { + protected $type; ///!< @var string + protected $subtype; ///!< @var string + protected $parameters = array(); ///!< @var array + protected $performer; ///!< @var User + protected $target; ///!< @var Title + protected $timestamp; ///!< @var string + protected $comment = ''; ///!< @var string + protected $deleted; ///!< @var int + + /** + * Constructor. + * + * @since 1.19 + * + * @param string $type + * @param string $subtype + */ + public function __construct( $type, $subtype ) { + $this->type = $type; + $this->subtype = $subtype; + } + + /** + * Set extra log parameters. + * You can pass params to the log action message + * by prefixing the keys with a number and colon. + * The numbering should start with number 4, the + * first three parameters are hardcoded for every + * message. Example: + * $entry->setParameters( + * '4:color' => 'blue', + * 'animal' => 'dog' + * ); + * + * @since 1.19 + * + * @param $parameters Associative array + */ + public function setParameters( $parameters ) { + $this->parameters = $parameters; + } + + /** + * Set the user that performed the action being logged. + * + * @since 1.19 + * + * @param User $performer + */ + public function setPerformer( User $performer ) { + $this->performer = $performer; + } + + /** + * Set the title of the object changed. + * + * @since 1.19 + * + * @param Title $target + */ + public function setTarget( Title $target ) { + $this->target = $target; + } + + /** + * Set the timestamp of when the logged action took place. + * + * @since 1.19 + * + * @param string $timestamp + */ + public function setTimestamp( $timestamp ) { + $this->timestamp = $timestamp; + } + + /** + * Set a comment associated with the action being logged. + * + * @since 1.19 + * + * @param string $comment + */ + public function setComment( $comment ) { + $this->comment = $comment; + } + + /** + * TODO: document + * + * @since 1.19 + * + * @param integer $deleted + */ + public function setDeleted( $deleted ) { + $this->deleted = $deleted; + } + + /** + * Inserts the entry into the logging table. + * @return int If of the log entry + */ + public function insert() { + global $wgContLang; + + $dbw = wfGetDB( DB_MASTER ); + $id = $dbw->nextSequenceValue( 'logging_log_id_seq' ); + + if ( $this->timestamp === null ) { + $this->timestamp = wfTimestampNow(); + } + + # Truncate for whole multibyte characters. + $comment = $wgContLang->truncate( $this->getComment(), 255 ); + + $data = array( + 'log_id' => $id, + 'log_type' => $this->getType(), + 'log_action' => $this->getSubtype(), + 'log_timestamp' => $dbw->timestamp( $this->getTimestamp() ), + 'log_user' => $this->getPerformer()->getId(), + 'log_user_text' => $this->getPerformer()->getName(), + 'log_namespace' => $this->getTarget()->getNamespace(), + 'log_title' => $this->getTarget()->getDBkey(), + 'log_page' => $this->getTarget()->getArticleId(), + 'log_comment' => $comment, + 'log_params' => serialize( (array) $this->getParameters() ), + ); + $dbw->insert( 'logging', $data, __METHOD__ ); + $this->id = !is_null( $id ) ? $id : $dbw->insertId(); + return $this->id; + } + + /** + * Publishes the log entry. + * @param $newId int id of the log entry. + * @param $to string: rcandudp (default), rc, udp + */ + public function publish( $newId, $to = 'rcandudp' ) { + $log = new LogPage( $this->getType() ); + if ( $log->isRestricted() ) { + return; + } + + $formatter = LogFormatter::newFromEntry( $this ); + $context = RequestContext::newExtraneousContext( $this->getTarget() ); + $formatter->setContext( $context ); + + $logpage = SpecialPage::getTitleFor( 'Log', $this->getType() ); + $user = $this->getPerformer(); + $rc = RecentChange::newLogEntry( + $this->getTimestamp(), + $logpage, + $user, + $formatter->getIRCActionText(), // Used for IRC feeds + $user->isAnon() ? $user->getName() : '', + $this->getType(), + $this->getSubtype(), + $this->getTarget(), + $this->getComment(), + serialize( (array) $this->getParameters() ), + $newId + ); + + if ( $to === 'rc' || $to === 'rcandudp' ) { + $rc->save( 'pleasedontudp' ); + } + + if ( $to === 'udp' || $to === 'rcandudp' ) { + $rc->notifyRC2UDP(); + } + } + + // LogEntry-> + + public function getType() { + return $this->type; + } + + public function getSubtype() { + return $this->subtype; + } + + public function getParameters() { + return $this->parameters; + } + + public function getPerformer() { + return $this->performer; + } + + public function getTarget() { + return $this->target; + } + + public function getTimestamp() { + $ts = $this->timestamp !== null ? $this->timestamp : wfTimestampNow(); + return wfTimestamp( TS_MW, $ts ); + } + + public function getComment() { + return $this->comment; + } + + public function getDeleted() { + return (int) $this->deleted; + } + +} diff --git a/includes/logging/LogEventsList.php b/includes/logging/LogEventsList.php new file mode 100644 index 00000000..437670d0 --- /dev/null +++ b/includes/logging/LogEventsList.php @@ -0,0 +1,751 @@ +<?php +/** + * Contain classes to list log entries + * + * Copyright © 2004 Brion Vibber <brion@pobox.com>, 2008 Aaron Schulz + * http://www.mediawiki.org/ + * + * 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 + */ + +class LogEventsList { + const NO_ACTION_LINK = 1; + const NO_EXTRA_USER_LINKS = 2; + + /** + * @var Skin + */ + private $skin; + + /** + * @var OutputPage + */ + private $out; + public $flags; + + /** + * @var Array + */ + protected $message; + + /** + * @var Array + */ + protected $mDefaultQuery; + + public function __construct( $skin, $out, $flags = 0 ) { + $this->skin = $skin; + $this->out = $out; + $this->flags = $flags; + $this->preCacheMessages(); + } + + /** + * As we use the same small set of messages in various methods and that + * they are called often, we call them once and save them in $this->message + */ + private function preCacheMessages() { + // Precache various messages + if( !isset( $this->message ) ) { + $messages = array( 'revertmerge', 'protect_change', 'unblocklink', 'change-blocklink', + 'revertmove', 'undeletelink', 'undeleteviewlink', 'revdel-restore', 'hist', 'diff', + 'pipe-separator', 'revdel-restore-deleted', 'revdel-restore-visible' ); + foreach( $messages as $msg ) { + $this->message[$msg] = wfMsgExt( $msg, array( 'escapenoentities' ) ); + } + } + } + + /** + * Set page title and show header for this log type + * @param $type Array + * @deprecated in 1.19 + */ + public function showHeader( $type ) { + wfDeprecated( __METHOD__, '1.19' ); + // If only one log type is used, then show a special message... + $headerType = (count($type) == 1) ? $type[0] : ''; + if( LogPage::isLogType( $headerType ) ) { + $page = new LogPage( $headerType ); + $this->out->setPageTitle( $page->getName()->text() ); + $this->out->addHTML( $page->getDescription()->parseAsBlock() ); + } else { + $this->out->addHTML( wfMsgExt('alllogstext',array('parseinline')) ); + } + } + + /** + * Show options for the log list + * + * @param $types string or Array + * @param $user String + * @param $page String + * @param $pattern String + * @param $year Integer: year + * @param $month Integer: month + * @param $filter: array + * @param $tagFilter: array? + */ + public function showOptions( $types=array(), $user='', $page='', $pattern='', $year='', + $month = '', $filter = null, $tagFilter='' ) { + global $wgScript, $wgMiserMode; + + $action = $wgScript; + $title = SpecialPage::getTitleFor( 'Log' ); + $special = $title->getPrefixedDBkey(); + + // For B/C, we take strings, but make sure they are converted... + $types = ($types === '') ? array() : (array)$types; + + $tagSelector = ChangeTags::buildTagFilterSelector( $tagFilter ); + + $html = Html::hidden( 'title', $special ); + + // Basic selectors + $html .= $this->getTypeMenu( $types ) . "\n"; + $html .= $this->getUserInput( $user ) . "\n"; + $html .= $this->getTitleInput( $page ) . "\n"; + $html .= $this->getExtraInputs( $types ) . "\n"; + + // Title pattern, if allowed + if (!$wgMiserMode) { + $html .= $this->getTitlePattern( $pattern ) . "\n"; + } + + // date menu + $html .= Xml::tags( 'p', null, Xml::dateMenu( $year, $month ) ); + + // Tag filter + if ($tagSelector) { + $html .= Xml::tags( 'p', null, implode( ' ', $tagSelector ) ); + } + + // Filter links + if ($filter) { + $html .= Xml::tags( 'p', null, $this->getFilterLinks( $filter ) ); + } + + // Submit button + $html .= Xml::submitButton( wfMsg( 'allpagessubmit' ) ); + + // Fieldset + $html = Xml::fieldset( wfMsg( 'log' ), $html ); + + // Form wrapping + $html = Xml::tags( 'form', array( 'action' => $action, 'method' => 'get' ), $html ); + + $this->out->addHTML( $html ); + } + + /** + * @param $filter Array + * @return String: Formatted HTML + */ + private function getFilterLinks( $filter ) { + global $wgLang; + // show/hide links + $messages = array( wfMsgHtml( 'show' ), wfMsgHtml( 'hide' ) ); + // Option value -> message mapping + $links = array(); + $hiddens = ''; // keep track for "go" button + foreach( $filter as $type => $val ) { + // Should the below assignment be outside the foreach? + // Then it would have to be copied. Not certain what is more expensive. + $query = $this->getDefaultQuery(); + $queryKey = "hide_{$type}_log"; + + $hideVal = 1 - intval($val); + $query[$queryKey] = $hideVal; + + $link = Linker::link( + $this->getDisplayTitle(), + $messages[$hideVal], + array(), + $query, + array( 'known', 'noclasses' ) + ); + + $links[$type] = wfMsgHtml( "log-show-hide-{$type}", $link ); + $hiddens .= Html::hidden( "hide_{$type}_log", $val ) . "\n"; + } + // Build links + return '<small>'.$wgLang->pipeList( $links ) . '</small>' . $hiddens; + } + + private function getDefaultQuery() { + global $wgRequest; + + if ( !isset( $this->mDefaultQuery ) ) { + $this->mDefaultQuery = $wgRequest->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 Title object of the page the links should point to. + * This is NOT the Title of the page the entries should be restricted to. + * + * @return Title object + */ + public function getDisplayTitle() { + return $this->out->getTitle(); + } + + public function getContext() { + return $this->out->getContext(); + } + + /** + * @param $queryTypes Array + * @return String: Formatted HTML + */ + private function getTypeMenu( $queryTypes ) { + $queryType = count($queryTypes) == 1 ? $queryTypes[0] : ''; + $selector = $this->getTypeSelector(); + $selector->setDefault( $queryType ); + return $selector->getHtml(); + } + + /** + * Returns log page selector. + * @return XmlSelect + * @since 1.19 + */ + public function getTypeSelector() { + global $wgUser; + + $typesByName = array(); // Temporary array + // First pass to load the log names + foreach( LogPage::validTypes() as $type ) { + $page = new LogPage( $type ); + $restriction = $page->getRestriction(); + if ( $wgUser->isAllowed( $restriction ) ) { + $typesByName[$type] = $page->getName()->text(); + } + } + + // Second pass to sort by name + asort($typesByName); + + // Always put "All public logs" on top + $public = $typesByName['']; + unset( $typesByName[''] ); + $typesByName = array( '' => $public ) + $typesByName; + + $select = new XmlSelect( 'type' ); + foreach( $typesByName as $type => $name ) { + $select->addOption( $name, $type ); + } + + return $select; + } + + /** + * @param $user String + * @return String: Formatted HTML + */ + private function getUserInput( $user ) { + return '<span style="white-space: nowrap">' . + Xml::inputLabel( wfMsg( 'specialloguserlabel' ), 'user', 'mw-log-user', 15, $user ) . + '</span>'; + } + + /** + * @param $title String + * @return String: Formatted HTML + */ + private function getTitleInput( $title ) { + return '<span style="white-space: nowrap">' . + Xml::inputLabel( wfMsg( 'speciallogtitlelabel' ), 'page', 'mw-log-page', 20, $title ) . + '</span>'; + } + + /** + * @param $pattern + * @return string Checkbox + */ + private function getTitlePattern( $pattern ) { + return '<span style="white-space: nowrap">' . + Xml::checkLabel( wfMsg( 'log-title-wildcard' ), 'pattern', 'pattern', $pattern ) . + '</span>'; + } + + /** + * @param $types + * @return string + */ + private function getExtraInputs( $types ) { + global $wgRequest; + $offender = $wgRequest->getVal('offender'); + $user = User::newFromName( $offender, false ); + if( !$user || ($user->getId() == 0 && !IP::isIPAddress($offender) ) ) { + $offender = ''; // Blank field if invalid + } + if( count($types) == 1 && $types[0] == 'suppress' ) { + return Xml::inputLabel( wfMsg('revdelete-offender'), 'offender', + 'mw-log-offender', 20, $offender ); + } + return ''; + } + + /** + * @return string + */ + public function beginLogEventsList() { + return "<ul>\n"; + } + + /** + * @return string + */ + public function endLogEventsList() { + return "</ul>\n"; + } + + /** + * @param $row Row: a single row from the result set + * @return String: Formatted HTML list item + */ + public function logLine( $row ) { + $entry = DatabaseLogEntry::newFromRow( $row ); + $formatter = LogFormatter::newFromEntry( $entry ); + $formatter->setShowUserToolLinks( !( $this->flags & self::NO_EXTRA_USER_LINKS ) ); + + $action = $formatter->getActionText(); + $comment = $formatter->getComment(); + + $classes = array( 'mw-logline-' . $entry->getType() ); + $title = $entry->getTarget(); + $time = $this->logTimestamp( $entry ); + + // Extract extra parameters + $paramArray = LogPage::extractParams( $row->log_params ); + // Add review/revert links and such... + $revert = $this->logActionLinks( $row, $title, $paramArray, $comment ); + + // Some user can hide log items and have review links + $del = $this->getShowHideLinks( $row ); + if( $del != '' ) $del .= ' '; + + // Any tags... + list( $tagDisplay, $newClasses ) = ChangeTags::formatSummaryRow( $row->ts_tags, 'logevent' ); + $classes = array_merge( $classes, $newClasses ); + + return Xml::tags( 'li', array( "class" => implode( ' ', $classes ) ), + $del . "$time $action $comment $revert $tagDisplay" ) . "\n"; + } + + private function logTimestamp( LogEntry $entry ) { + global $wgLang; + $time = $wgLang->timeanddate( wfTimestamp( TS_MW, $entry->getTimestamp() ), true ); + return htmlspecialchars( $time ); + } + + /** + * @TODO: split up! + * + * @param $row + * @param Title $title + * @param Array $paramArray + * @param $comment + * @return String + */ + private function logActionLinks( $row, $title, $paramArray, &$comment ) { + global $wgUser; + if( ( $this->flags & self::NO_ACTION_LINK ) // we don't want to see the action + || self::isDeleted( $row, LogPage::DELETED_ACTION ) ) // action is hidden + { + return ''; + } + $revert = ''; + if( self::typeAction( $row, 'move', 'move', 'move' ) && !empty( $paramArray[0] ) ) { + $destTitle = Title::newFromText( $paramArray[0] ); + if( $destTitle ) { + $revert = '(' . Linker::link( + SpecialPage::getTitleFor( 'Movepage' ), + $this->message['revertmove'], + array(), + array( + 'wpOldTitle' => $destTitle->getPrefixedDBkey(), + 'wpNewTitle' => $title->getPrefixedDBkey(), + 'wpReason' => wfMsgForContent( 'revertmove' ), + 'wpMovetalk' => 0 + ), + array( 'known', 'noclasses' ) + ) . ')'; + } + // Show undelete link + } elseif( self::typeAction( $row, array( 'delete', 'suppress' ), 'delete', 'deletedhistory' ) ) { + if( !$wgUser->isAllowed( 'undelete' ) ) { + $viewdeleted = $this->message['undeleteviewlink']; + } else { + $viewdeleted = $this->message['undeletelink']; + } + $revert = '(' . Linker::link( + SpecialPage::getTitleFor( 'Undelete' ), + $viewdeleted, + array(), + array( 'target' => $title->getPrefixedDBkey() ), + array( 'known', 'noclasses' ) + ) . ')'; + // Show unblock/change block link + } elseif( self::typeAction( $row, array( 'block', 'suppress' ), array( 'block', 'reblock' ), 'block' ) ) { + $revert = '(' . + Linker::link( + SpecialPage::getTitleFor( 'Unblock', $row->log_title ), + $this->message['unblocklink'], + array(), + array(), + 'known' + ) . + $this->message['pipe-separator'] . + Linker::link( + SpecialPage::getTitleFor( 'Block', $row->log_title ), + $this->message['change-blocklink'], + array(), + array(), + 'known' + ) . + ')'; + // Show change protection link + } elseif( self::typeAction( $row, 'protect', array( 'modify', 'protect', 'unprotect' ) ) ) { + $revert .= ' (' . + Linker::link( $title, + $this->message['hist'], + array(), + array( + 'action' => 'history', + 'offset' => $row->log_timestamp + ) + ); + if( $wgUser->isAllowed( 'protect' ) ) { + $revert .= $this->message['pipe-separator'] . + Linker::link( $title, + $this->message['protect_change'], + array(), + array( 'action' => 'protect' ), + 'known' ); + } + $revert .= ')'; + // Show unmerge link + } elseif( self::typeAction( $row, 'merge', 'merge', 'mergehistory' ) ) { + $revert = '(' . Linker::link( + SpecialPage::getTitleFor( 'MergeHistory' ), + $this->message['revertmerge'], + array(), + array( + 'target' => $paramArray[0], + 'dest' => $title->getPrefixedDBkey(), + 'mergepoint' => $paramArray[1] + ), + array( 'known', 'noclasses' ) + ) . ')'; + // If an edit was hidden from a page give a review link to the history + } elseif( self::typeAction( $row, array( 'delete', 'suppress' ), 'revision', 'deletedhistory' ) ) { + $revert = RevisionDeleter::getLogLinks( $title, $paramArray, + $this->message ); + // Hidden log items, give review link + } elseif( self::typeAction( $row, array( 'delete', 'suppress' ), 'event', 'deletedhistory' ) ) { + if( count($paramArray) >= 1 ) { + $revdel = SpecialPage::getTitleFor( 'Revisiondelete' ); + // $paramArray[1] is a CSV of the IDs + $query = $paramArray[0]; + // Link to each hidden object ID, $paramArray[1] is the url param + $revert = '(' . Linker::link( + $revdel, + $this->message['revdel-restore'], + array(), + array( + 'target' => $title->getPrefixedText(), + 'type' => 'logging', + 'ids' => $query + ), + array( 'known', 'noclasses' ) + ) . ')'; + } + // Do nothing. The implementation is handled by the hook modifiying the passed-by-ref parameters. + } else { + wfRunHooks( 'LogLine', array( $row->log_type, $row->log_action, $title, $paramArray, + &$comment, &$revert, $row->log_timestamp ) ); + } + if( $revert != '' ) { + $revert = '<span class="mw-logevent-actionlink">' . $revert . '</span>'; + } + return $revert; + } + + /** + * @param $row Row + * @return string + */ + private function getShowHideLinks( $row ) { + global $wgUser; + if( ( $this->flags & self::NO_ACTION_LINK ) // we don't want to see the links + || $row->log_type == 'suppress' ) { // no one can hide items from the suppress log + return ''; + } + $del = ''; + // Don't show useless link to people who cannot hide revisions + if( $wgUser->isAllowed( 'deletedhistory' ) ) { + if( $row->log_deleted || $wgUser->isAllowed( 'deleterevision' ) ) { + $canHide = $wgUser->isAllowed( 'deleterevision' ); + // If event was hidden from sysops + if( !self::userCan( $row, LogPage::DELETED_RESTRICTED ) ) { + $del = Linker::revDeleteLinkDisabled( $canHide ); + } else { + $target = SpecialPage::getTitleFor( 'Log', $row->log_type ); + $query = array( + 'target' => $target->getPrefixedDBkey(), + 'type' => 'logging', + 'ids' => $row->log_id, + ); + $del = Linker::revDeleteLink( $query, + self::isDeleted( $row, LogPage::DELETED_RESTRICTED ), $canHide ); + } + } + } + return $del; + } + + /** + * @param $row Row + * @param $type Mixed: string/array + * @param $action Mixed: string/array + * @param $right string + * @return Boolean + */ + public static function typeAction( $row, $type, $action, $right='' ) { + $match = is_array($type) ? + in_array( $row->log_type, $type ) : $row->log_type == $type; + if( $match ) { + $match = is_array( $action ) ? + in_array( $row->log_action, $action ) : $row->log_action == $action; + if( $match && $right ) { + global $wgUser; + $match = $wgUser->isAllowed( $right ); + } + } + return $match; + } + + /** + * Determine if the current user is allowed to view a particular + * field of this log row, if it's marked as deleted. + * + * @param $row Row + * @param $field Integer + * @param $user User object to check, or null to use $wgUser + * @return Boolean + */ + public static function userCan( $row, $field, User $user = null ) { + return self::userCanBitfield( $row->log_deleted, $field, $user ); + } + + /** + * Determine if the current user is allowed to view a particular + * field of this log row, if it's marked as deleted. + * + * @param $bitfield Integer (current field) + * @param $field Integer + * @param $user User object to check, or null to use $wgUser + * @return Boolean + */ + public static function userCanBitfield( $bitfield, $field, User $user = null ) { + if( $bitfield & $field ) { + if ( $bitfield & LogPage::DELETED_RESTRICTED ) { + $permission = 'suppressrevision'; + } else { + $permission = 'deletedhistory'; + } + wfDebug( "Checking for $permission due to $field match on $bitfield\n" ); + if ( $user === null ) { + global $wgUser; + $user = $wgUser; + } + return $user->isAllowed( $permission ); + } else { + return true; + } + } + + /** + * @param $row Row + * @param $field Integer: one of DELETED_* bitfield constants + * @return Boolean + */ + public static function isDeleted( $row, $field ) { + return ( $row->log_deleted & $field ) == $field; + } + + /** + * Show log extract. Either with text and a box (set $msgKey) or without (don't set $msgKey) + * + * @param $out OutputPage|String-by-reference + * @param $types String|Array Log types to show + * @param $page String|Title The page title to show log entries for + * @param $user String The user who made the log entries + * @param $param Associative Array with the following additional options: + * - lim Integer Limit of items to show, default is 50 + * - conds Array Extra conditions for the query (e.g. "log_action != 'revision'") + * - showIfEmpty boolean Set to false if you don't want any output in case the loglist is empty + * if set to true (default), "No matching items in log" is displayed if loglist is empty + * - msgKey Array If you want a nice box with a message, set this to the key of the message. + * First element is the message key, additional optional elements are parameters for the key + * that are processed with wfMsgExt and option 'parse' + * - offset Set to overwrite offset parameter in $wgRequest + * set to '' to unset offset + * - wrap String Wrap the message in html (usually something like "<div ...>$1</div>"). + * - flags Integer display flags (NO_ACTION_LINK,NO_EXTRA_USER_LINKS) + * @return Integer Number of total log items (not limited by $lim) + */ + public static function showLogExtract( + &$out, $types=array(), $page='', $user='', $param = array() + ) { + $defaultParameters = array( + 'lim' => 25, + 'conds' => array(), + 'showIfEmpty' => true, + 'msgKey' => array(''), + 'wrap' => "$1", + 'flags' => 0 + ); + # The + operator appends elements of remaining keys from the right + # handed array to the left handed, whereas duplicated keys are NOT overwritten. + $param += $defaultParameters; + # Convert $param array to individual variables + $lim = $param['lim']; + $conds = $param['conds']; + $showIfEmpty = $param['showIfEmpty']; + $msgKey = $param['msgKey']; + $wrap = $param['wrap']; + $flags = $param['flags']; + if ( !is_array( $msgKey ) ) { + $msgKey = array( $msgKey ); + } + + if ( $out instanceof OutputPage ) { + $context = $out->getContext(); + } else { + $context = RequestContext::getMain(); + } + + # Insert list of top 50 (or top $lim) items + $loglist = new LogEventsList( $context->getSkin(), $context->getOutput(), $flags ); + $pager = new LogPager( $loglist, $types, $user, $page, '', $conds ); + if ( isset( $param['offset'] ) ) { # Tell pager to ignore $wgRequest offset + $pager->setOffset( $param['offset'] ); + } + if( $lim > 0 ) $pager->mLimit = $lim; + $logBody = $pager->getBody(); + $s = ''; + if( $logBody ) { + if ( $msgKey[0] ) { + $s = '<div class="mw-warning-with-logexcerpt">'; + + if ( count( $msgKey ) == 1 ) { + $s .= wfMsgExt( $msgKey[0], array( 'parse' ) ); + } else { // Process additional arguments + $args = $msgKey; + array_shift( $args ); + $s .= wfMsgExt( $msgKey[0], array( 'parse' ), $args ); + } + } + $s .= $loglist->beginLogEventsList() . + $logBody . + $loglist->endLogEventsList(); + } else { + if ( $showIfEmpty ) { + $s = Html::rawElement( 'div', array( 'class' => 'mw-warning-logempty' ), + wfMsgExt( 'logempty', array( 'parseinline' ) ) ); + } + } + if( $pager->getNumRows() > $pager->mLimit ) { # Show "Full log" link + $urlParam = array(); + if ( $page instanceof Title ) { + $urlParam['page'] = $page->getPrefixedDBkey(); + } elseif ( $page != '' ) { + $urlParam['page'] = $page; + } + if ( $user != '') + $urlParam['user'] = $user; + if ( !is_array( $types ) ) # Make it an array, if it isn't + $types = array( $types ); + # If there is exactly one log type, we can link to Special:Log?type=foo + if ( count( $types ) == 1 ) + $urlParam['type'] = $types[0]; + $s .= Linker::link( + SpecialPage::getTitleFor( 'Log' ), + wfMsgHtml( 'log-fulllog' ), + array(), + $urlParam + ); + } + if ( $logBody && $msgKey[0] ) { + $s .= '</div>'; + } + + if ( $wrap != '' ) { // Wrap message in html + $s = str_replace( '$1', $s, $wrap ); + } + + /* hook can return false, if we don't want the message to be emitted (Wikia BugId:7093) */ + if ( wfRunHooks( 'LogEventsListShowLogExtract', array( &$s, $types, $page, $user, $param ) ) ) { + // $out can be either an OutputPage object or a String-by-reference + if ( $out instanceof OutputPage ){ + $out->addHTML( $s ); + } else { + $out = $s; + } + } + + return $pager->getNumRows(); + } + + /** + * SQL clause to skip forbidden log types for this user + * + * @param $db DatabaseBase + * @param $audience string, public/user + * @return Mixed: string or false + */ + public static function getExcludeClause( $db, $audience = 'public' ) { + global $wgLogRestrictions, $wgUser; + // Reset the array, clears extra "where" clauses when $par is used + $hiddenLogs = array(); + // Don't show private logs to unprivileged users + foreach( $wgLogRestrictions as $logType => $right ) { + if( $audience == 'public' || !$wgUser->isAllowed($right) ) { + $safeType = $db->strencode( $logType ); + $hiddenLogs[] = $safeType; + } + } + if( count($hiddenLogs) == 1 ) { + return 'log_type != ' . $db->addQuotes( $hiddenLogs[0] ); + } elseif( $hiddenLogs ) { + return 'log_type NOT IN (' . $db->makeList($hiddenLogs) . ')'; + } + return false; + } + } diff --git a/includes/logging/LogFormatter.php b/includes/logging/LogFormatter.php new file mode 100644 index 00000000..24490eed --- /dev/null +++ b/includes/logging/LogFormatter.php @@ -0,0 +1,673 @@ +<?php +/** + * Contains classes for formatting log entries + * + * @file + * @author Niklas Laxström + * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License 2.0 or later + * @since 1.19 + */ + +/** + * Implements the default log formatting. + * Can be overridden by subclassing and setting + * $wgLogActionsHandlers['type/subtype'] = 'class'; or + * $wgLogActionsHandlers['type/*'] = 'class'; + * @since 1.19 + */ +class LogFormatter { + // Audience options for viewing usernames, comments, and actions + const FOR_PUBLIC = 1; + const FOR_THIS_USER = 2; + + // Static-> + + /** + * Constructs a new formatter suitable for given entry. + * @param $entry LogEntry + * @return LogFormatter + */ + public static function newFromEntry( LogEntry $entry ) { + global $wgLogActionsHandlers; + $fulltype = $entry->getFullType(); + $wildcard = $entry->getType() . '/*'; + $handler = ''; + + if ( isset( $wgLogActionsHandlers[$fulltype] ) ) { + $handler = $wgLogActionsHandlers[$fulltype]; + } elseif ( isset( $wgLogActionsHandlers[$wildcard] ) ) { + $handler = $wgLogActionsHandlers[$wildcard]; + } + + if ( $handler !== '' && is_string( $handler ) && class_exists( $handler ) ) { + return new $handler( $entry ); + } + + return new LegacyLogFormatter( $entry ); + } + + /** + * Handy shortcut for constructing a formatter directly from + * database row. + * @param $row + * @see DatabaseLogEntry::getSelectQueryData + * @return LogFormatter + */ + public static function newFromRow( $row ) { + return self::newFromEntry( DatabaseLogEntry::newFromRow( $row ) ); + } + + // Nonstatic-> + + /// @var LogEntry + protected $entry; + + /// Integer constant for handling log_deleted + protected $audience = self::FOR_PUBLIC; + + /// Whether to output user tool links + protected $linkFlood = false; + + /** + * Set to true if we are constructing a message text that is going to + * be included in page history or send to IRC feed. Links are replaced + * with plaintext or with [[pagename]] kind of syntax, that is parsed + * by page histories and IRC feeds. + * @var boolean + */ + protected $plaintext = false; + + protected $irctext = false; + + protected function __construct( LogEntry $entry ) { + $this->entry = $entry; + $this->context = RequestContext::getMain(); + } + + /** + * Replace the default context + * @param $context IContextSource + */ + public function setContext( IContextSource $context ) { + $this->context = $context; + } + + /** + * Set the visibility restrictions for displaying content. + * If set to public, and an item is deleted, then it will be replaced + * with a placeholder even if the context user is allowed to view it. + * @param $audience integer self::FOR_THIS_USER or self::FOR_PUBLIC + */ + public function setAudience( $audience ) { + $this->audience = ( $audience == self::FOR_THIS_USER ) + ? self::FOR_THIS_USER + : self::FOR_PUBLIC; + } + + /** + * Check if a log item can be displayed + * @param $field integer LogPage::DELETED_* constant + * @return bool + */ + protected function canView( $field ) { + if ( $this->audience == self::FOR_THIS_USER ) { + return LogEventsList::userCanBitfield( + $this->entry->getDeleted(), $field, $this->context->getUser() ); + } else { + return !$this->entry->isDeleted( $field ); + } + } + + /** + * If set to true, will produce user tool links after + * the user name. This should be replaced with generic + * CSS/JS solution. + * @param $value boolean + */ + public function setShowUserToolLinks( $value ) { + $this->linkFlood = $value; + } + + /** + * Ugly hack to produce plaintext version of the message. + * Usually you also want to set extraneous request context + * to avoid formatting for any particular user. + * @see getActionText() + * @return string text + */ + public function getPlainActionText() { + $this->plaintext = true; + $text = $this->getActionText(); + $this->plaintext = false; + return $text; + } + + /** + * Even uglier hack to maintain backwards compatibilty with IRC bots + * (bug 34508). + * @see getActionText() + * @return string text + */ + public function getIRCActionText() { + $this->plaintext = true; + $text = $this->getActionText(); + + $entry = $this->entry; + $parameters = $entry->getParameters(); + // @see LogPage::actionText() + $msgOpts = array( 'parsemag', 'escape', 'replaceafter', 'content' ); + // Text of title the action is aimed at. + $target = $entry->getTarget()->getPrefixedText() ; + $text = null; + switch( $entry->getType() ) { + case 'move': + switch( $entry->getSubtype() ) { + case 'move': + $movesource = $parameters['4::target']; + $text = wfMsgExt( '1movedto2', $msgOpts, $target, $movesource ); + break; + case 'move_redir': + $movesource = $parameters['4::target']; + $text = wfMsgExt( '1movedto2_redir', $msgOpts, $target, $movesource ); + break; + case 'move-noredirect': + break; + case 'move_redir-noredirect': + break; + } + break; + + case 'delete': + switch( $entry->getSubtype() ) { + case 'delete': + $text = wfMsgExt( 'deletedarticle', $msgOpts, $target ); + break; + case 'restore': + $text = wfMsgExt( 'undeletedarticle', $msgOpts, $target ); + break; + //case 'revision': // Revision deletion + //case 'event': // Log deletion + // see https://svn.wikimedia.org/viewvc/mediawiki/trunk/phase3/includes/LogPage.php?&pathrev=97044&r1=97043&r2=97044 + //default: + } + break; + + case 'patrol': + // https://svn.wikimedia.org/viewvc/mediawiki/trunk/phase3/includes/PatrolLog.php?&pathrev=97495&r1=97494&r2=97495 + // Create a diff link to the patrolled revision + if ( $entry->getSubtype() === 'patrol' ) { + $diffLink = htmlspecialchars( + wfMsgForContent( 'patrol-log-diff', $parameters['4::curid'] ) ); + $text = wfMsgForContent( 'patrol-log-line', $diffLink, "[[$target]]", "" ); + } else { + // broken?? + } + break; + + case 'newusers': + switch( $entry->getSubtype() ) { + case 'newusers': + case 'create': + $text = wfMsgExt( 'newuserlog-create-entry', $msgOpts /* no params */ ); + break; + case 'create2': + $text = wfMsgExt( 'newuserlog-create2-entry', $msgOpts, $target ); + break; + case 'autocreate': + $text = wfMsgExt( 'newuserlog-autocreate-entry', $msgOpts /* no params */ ); + break; + } + break; + + case 'upload': + switch( $entry->getSubtype() ) { + case 'upload': + $text = wfMsgExt( 'uploadedimage', $msgOpts, $target ); + break; + case 'overwrite': + $text = wfMsgExt( 'overwroteimage', $msgOpts, $target ); + break; + } + break; + + // case 'suppress' --private log -- aaron (sign your messages so we know who to blame in a few years :-D) + // default: + } + if( is_null( $text ) ) { + $text = $this->getPlainActionText(); + } + + $this->plaintext = false; + return $text; + } + + /** + * Gets the log action, including username. + * @return string HTML + */ + public function getActionText() { + if ( $this->canView( LogPage::DELETED_ACTION ) ) { + $element = $this->getActionMessage(); + if ( $element instanceof Message ) { + $element = $this->plaintext ? $element->text() : $element->escaped(); + } + if ( $this->entry->isDeleted( LogPage::DELETED_ACTION ) ) { + $element = $this->styleRestricedElement( $element ); + } + } else { + $performer = $this->getPerformerElement() . $this->msg( 'word-separator' )->text(); + $element = $performer . $this->getRestrictedElement( 'rev-deleted-event' ); + } + + return $element; + } + + /** + * Returns a sentence describing the log action. Usually + * a Message object is returned, but old style log types + * and entries might return pre-escaped html string. + * @return Message|pre-escaped html + */ + protected function getActionMessage() { + $message = $this->msg( $this->getMessageKey() ); + $message->params( $this->getMessageParameters() ); + return $message; + } + + /** + * Returns a key to be used for formatting the action sentence. + * Default is logentry-TYPE-SUBTYPE for modern logs. Legacy log + * types will use custom keys, and subclasses can also alter the + * key depending on the entry itself. + * @return string message key + */ + protected function getMessageKey() { + $type = $this->entry->getType(); + $subtype = $this->entry->getSubtype(); + + return "logentry-$type-$subtype"; + } + + /** + * Extracts the optional extra parameters for use in action messages. + * The array indexes start from number 3. + * @return array + */ + protected function extractParameters() { + $entry = $this->entry; + $params = array(); + + if ( $entry->isLegacy() ) { + foreach ( $entry->getParameters() as $index => $value ) { + $params[$index + 3] = $value; + } + } + + // Filter out parameters which are not in format #:foo + foreach ( $entry->getParameters() as $key => $value ) { + if ( strpos( $key, ':' ) === false ) continue; + list( $index, $type, $name ) = explode( ':', $key, 3 ); + $params[$index - 1] = $value; + } + + /* Message class doesn't like non consecutive numbering. + * Fill in missing indexes with empty strings to avoid + * incorrect renumbering. + */ + if ( count( $params ) ) { + $max = max( array_keys( $params ) ); + for ( $i = 4; $i < $max; $i++ ) { + if ( !isset( $params[$i] ) ) { + $params[$i] = ''; + } + } + } + return $params; + } + + /** + * Formats parameters intented for action message from + * array of all parameters. There are three hardcoded + * parameters (array is zero-indexed, this list not): + * - 1: user name with premade link + * - 2: usable for gender magic function + * - 3: target page with premade link + * @return array + */ + protected function getMessageParameters() { + if ( isset( $this->parsedParameters ) ) { + return $this->parsedParameters; + } + + $entry = $this->entry; + $params = $this->extractParameters(); + $params[0] = Message::rawParam( $this->getPerformerElement() ); + $params[1] = $entry->getPerformer()->getName(); + $params[2] = Message::rawParam( $this->makePageLink( $entry->getTarget() ) ); + + // Bad things happens if the numbers are not in correct order + ksort( $params ); + return $this->parsedParameters = $params; + } + + /** + * Helper to make a link to the page, taking the plaintext + * value in consideration. + * @param $title Title the page + * @param $parameters array query parameters + * @return String + */ + protected function makePageLink( Title $title = null, $parameters = array() ) { + if ( !$this->plaintext ) { + $link = Linker::link( $title, null, array(), $parameters ); + } else { + if ( !$title instanceof Title ) { + throw new MWException( "Expected title, got null" ); + } + $link = '[[' . $title->getPrefixedText() . ']]'; + } + return $link; + } + + /** + * Provides the name of the user who performed the log action. + * Used as part of log action message or standalone, depending + * which parts of the log entry has been hidden. + */ + public function getPerformerElement() { + if ( $this->canView( LogPage::DELETED_USER ) ) { + $performer = $this->entry->getPerformer(); + $element = $this->makeUserLink( $performer ); + if ( $this->entry->isDeleted( LogPage::DELETED_USER ) ) { + $element = $this->styleRestricedElement( $element ); + } + } else { + $element = $this->getRestrictedElement( 'rev-deleted-user' ); + } + + return $element; + } + + /** + * Gets the luser provided comment + * @return string HTML + */ + public function getComment() { + if ( $this->canView( LogPage::DELETED_COMMENT ) ) { + $comment = Linker::commentBlock( $this->entry->getComment() ); + // No hard coded spaces thanx + $element = ltrim( $comment ); + if ( $this->entry->isDeleted( LogPage::DELETED_COMMENT ) ) { + $element = $this->styleRestricedElement( $element ); + } + } else { + $element = $this->getRestrictedElement( 'rev-deleted-comment' ); + } + + return $element; + } + + /** + * Helper method for displaying restricted element. + * @param $message string + * @return string HTML or wikitext + */ + protected function getRestrictedElement( $message ) { + if ( $this->plaintext ) { + return $this->msg( $message )->text(); + } + + $content = $this->msg( $message )->escaped(); + $attribs = array( 'class' => 'history-deleted' ); + return Html::rawElement( 'span', $attribs, $content ); + } + + /** + * Helper method for styling restricted element. + * @param $content string + * @return string HTML or wikitext + */ + protected function styleRestricedElement( $content ) { + if ( $this->plaintext ) { + return $content; + } + $attribs = array( 'class' => 'history-deleted' ); + return Html::rawElement( 'span', $attribs, $content ); + } + + /** + * Shortcut for wfMessage which honors local context. + * @todo Would it be better to require replacing the global context instead? + * @param $key string + * @return Message + */ + protected function msg( $key ) { + return wfMessage( $key ) + ->inLanguage( $this->context->getLanguage() ) + ->title( $this->context->getTitle() ); + } + + protected function makeUserLink( User $user ) { + if ( $this->plaintext ) { + $element = $user->getName(); + } else { + $element = Linker::userLink( + $user->getId(), + $user->getName() + ); + + if ( $this->linkFlood ) { + $element .= Linker::userToolLinks( + $user->getId(), + $user->getName(), + true, // Red if no edits + 0, // Flags + $user->getEditCount() + ); + } + } + return $element; + } + + /** + * @return Array of titles that should be preloaded with LinkBatch. + */ + public function getPreloadTitles() { + return array(); + } + +} + +/** + * This class formats all log entries for log types + * which have not been converted to the new system. + * This is not about old log entries which store + * parameters in a different format - the new + * LogFormatter classes have code to support formatting + * those too. + * @since 1.19 + */ +class LegacyLogFormatter extends LogFormatter { + protected function getActionMessage() { + $entry = $this->entry; + $action = LogPage::actionText( + $entry->getType(), + $entry->getSubtype(), + $entry->getTarget(), + $this->plaintext ? null : $this->context->getSkin(), + (array)$entry->getParameters(), + !$this->plaintext // whether to filter [[]] links + ); + + $performer = $this->getPerformerElement(); + return $performer . $this->msg( 'word-separator' )->text() . $action; + } + +} + +/** + * This class formats move log entries. + * @since 1.19 + */ +class MoveLogFormatter extends LogFormatter { + public function getPreloadTitles() { + $params = $this->extractParameters(); + return array( Title::newFromText( $params[3] ) ); + } + + protected function getMessageKey() { + $key = parent::getMessageKey(); + $params = $this->getMessageParameters(); + if ( isset( $params[4] ) && $params[4] === '1' ) { + $key .= '-noredirect'; + } + return $key; + } + + protected function getMessageParameters() { + $params = parent::getMessageParameters(); + $oldname = $this->makePageLink( $this->entry->getTarget(), array( 'redirect' => 'no' ) ); + $newname = $this->makePageLink( Title::newFromText( $params[3] ) ); + $params[2] = Message::rawParam( $oldname ); + $params[3] = Message::rawParam( $newname ); + return $params; + } +} + +/** + * This class formats delete log entries. + * @since 1.19 + */ +class DeleteLogFormatter extends LogFormatter { + protected function getMessageKey() { + $key = parent::getMessageKey(); + if ( in_array( $this->entry->getSubtype(), array( 'event', 'revision' ) ) ) { + if ( count( $this->getMessageParameters() ) < 5 ) { + return "$key-legacy"; + } + } + return $key; + } + + protected function getMessageParameters() { + if ( isset( $this->parsedParametersDeleteLog ) ) { + return $this->parsedParametersDeleteLog; + } + + $params = parent::getMessageParameters(); + $subtype = $this->entry->getSubtype(); + if ( in_array( $subtype, array( 'event', 'revision' ) ) ) { + if ( + ($subtype === 'event' && count( $params ) === 6 ) || + ($subtype === 'revision' && isset( $params[3] ) && $params[3] === 'revision' ) + ) { + $paramStart = $subtype === 'revision' ? 4 : 3; + + $old = $this->parseBitField( $params[$paramStart+1] ); + $new = $this->parseBitField( $params[$paramStart+2] ); + list( $hid, $unhid, $extra ) = RevisionDeleter::getChanges( $new, $old ); + $changes = array(); + foreach ( $hid as $v ) { + $changes[] = $this->msg( "$v-hid" )->plain(); + } + foreach ( $unhid as $v ) { + $changes[] = $this->msg( "$v-unhid" )->plain(); + } + foreach ( $extra as $v ) { + $changes[] = $this->msg( $v )->plain(); + } + $changeText = $this->context->getLanguage()->listToText( $changes ); + + + $newParams = array_slice( $params, 0, 3 ); + $newParams[3] = $changeText; + $count = count( explode( ',', $params[$paramStart] ) ); + $newParams[4] = $this->context->getLanguage()->formatNum( $count ); + return $this->parsedParametersDeleteLog = $newParams; + } else { + return $this->parsedParametersDeleteLog = array_slice( $params, 0, 3 ); + } + } + + return $this->parsedParametersDeleteLog = $params; + } + + protected function parseBitField( $string ) { + // Input is like ofield=2134 or just the number + if ( strpos( $string, 'field=' ) === 1 ) { + list( , $field ) = explode( '=', $string ); + return (int) $field; + } else { + return (int) $string; + } + } +} + +/** + * This class formats patrol log entries. + * @since 1.19 + */ +class PatrolLogFormatter extends LogFormatter { + protected function getMessageKey() { + $key = parent::getMessageKey(); + $params = $this->getMessageParameters(); + if ( isset( $params[5] ) && $params[5] ) { + $key .= '-auto'; + } + return $key; + } + + protected function getMessageParameters() { + $params = parent::getMessageParameters(); + $newParams = array_slice( $params, 0, 3 ); + + $target = $this->entry->getTarget(); + $oldid = $params[3]; + $revision = $this->context->getLanguage()->formatNum( $oldid, true ); + + if ( $this->plaintext ) { + $revlink = $revision; + } elseif ( $target->exists() ) { + $query = array( + 'oldid' => $oldid, + 'diff' => 'prev' + ); + $revlink = Linker::link( $target, htmlspecialchars( $revision ), array(), $query ); + } else { + $revlink = htmlspecialchars( $revision ); + } + + $newParams[3] = Message::rawParam( $revlink ); + return $newParams; + } +} + +/** + * This class formats new user log entries. + * @since 1.19 + */ +class NewUsersLogFormatter extends LogFormatter { + protected function getMessageParameters() { + $params = parent::getMessageParameters(); + if ( $this->entry->getSubtype() === 'create2' ) { + if ( isset( $params[3] ) ) { + $target = User::newFromId( $params[3] ); + } else { + $target = User::newFromName( $this->entry->getTarget()->getText(), false ); + } + $params[2] = Message::rawParam( $this->makeUserLink( $target ) ); + $params[3] = $target->getName(); + } + return $params; + } + + public function getComment() { + $timestamp = wfTimestamp( TS_MW, $this->entry->getTimestamp() ); + if ( $timestamp < '20080129000000' ) { + # Suppress $comment from old entries (before 2008-01-29), + # not needed and can contain incorrect links + return ''; + } + return parent::getComment(); + } +} diff --git a/includes/logging/LogPage.php b/includes/logging/LogPage.php new file mode 100644 index 00000000..bbb4de8f --- /dev/null +++ b/includes/logging/LogPage.php @@ -0,0 +1,634 @@ +<?php +/** + * Contain log classes + * + * Copyright © 2002, 2004 Brion Vibber <brion@pobox.com> + * http://www.mediawiki.org/ + * + * 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 + */ + +/** + * Class to simplify the use of log pages. + * The logs are now kept in a table which is easier to manage and trim + * than ever-growing wiki pages. + * + */ +class LogPage { + const DELETED_ACTION = 1; + const DELETED_COMMENT = 2; + const DELETED_USER = 4; + const DELETED_RESTRICTED = 8; + // Convenience fields + const SUPPRESSED_USER = 12; + const SUPPRESSED_ACTION = 9; + /* @access private */ + var $type, $action, $comment, $params; + + /** + * @var User + */ + var $doer; + + /** + * @var Title + */ + var $target; + + /* @acess public */ + var $updateRecentChanges, $sendToUDP; + + /** + * Constructor + * + * @param $type String: one of '', 'block', 'protect', 'rights', 'delete', + * 'upload', 'move' + * @param $rc Boolean: whether to update recent changes as well as the logging table + * @param $udp String: pass 'UDP' to send to the UDP feed if NOT sent to RC + */ + public function __construct( $type, $rc = true, $udp = 'skipUDP' ) { + $this->type = $type; + $this->updateRecentChanges = $rc; + $this->sendToUDP = ( $udp == 'UDP' ); + } + + /** + * @return bool|int|null + */ + protected function saveContent() { + global $wgLogRestrictions; + + $dbw = wfGetDB( DB_MASTER ); + $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' ); + + $this->timestamp = $now = wfTimestampNow(); + $data = array( + 'log_id' => $log_id, + 'log_type' => $this->type, + 'log_action' => $this->action, + 'log_timestamp' => $dbw->timestamp( $now ), + 'log_user' => $this->doer->getId(), + 'log_user_text' => $this->doer->getName(), + 'log_namespace' => $this->target->getNamespace(), + 'log_title' => $this->target->getDBkey(), + 'log_page' => $this->target->getArticleId(), + 'log_comment' => $this->comment, + 'log_params' => $this->params + ); + $dbw->insert( 'logging', $data, __METHOD__ ); + $newId = !is_null( $log_id ) ? $log_id : $dbw->insertId(); + + # And update recentchanges + if( $this->updateRecentChanges ) { + $titleObj = SpecialPage::getTitleFor( 'Log', $this->type ); + + RecentChange::notifyLog( + $now, $titleObj, $this->doer, $this->getRcComment(), '', + $this->type, $this->action, $this->target, $this->comment, + $this->params, $newId + ); + } elseif( $this->sendToUDP ) { + # Don't send private logs to UDP + if( isset( $wgLogRestrictions[$this->type] ) && $wgLogRestrictions[$this->type] != '*' ) { + return true; + } + + # Notify external application via UDP. + # We send this to IRC but do not want to add it the RC table. + $titleObj = SpecialPage::getTitleFor( 'Log', $this->type ); + $rc = RecentChange::newLogEntry( + $now, $titleObj, $this->doer, $this->getRcComment(), '', + $this->type, $this->action, $this->target, $this->comment, + $this->params, $newId + ); + $rc->notifyRC2UDP(); + } + return $newId; + } + + /** + * Get the RC comment from the last addEntry() call + * + * @return string + */ + public function getRcComment() { + $rcComment = $this->actionText; + + if( $this->comment != '' ) { + if ( $rcComment == '' ) { + $rcComment = $this->comment; + } else { + $rcComment .= wfMsgForContent( 'colon-separator' ) . $this->comment; + } + } + + return $rcComment; + } + + /** + * Get the comment from the last addEntry() call + */ + public function getComment() { + return $this->comment; + } + + /** + * Get the list of valid log types + * + * @return Array of strings + */ + public static function validTypes() { + global $wgLogTypes; + return $wgLogTypes; + } + + /** + * Is $type a valid log type + * + * @param $type String: log type to check + * @return Boolean + */ + public static function isLogType( $type ) { + return in_array( $type, LogPage::validTypes() ); + } + + /** + * Get the name for the given log type + * + * @param $type String: logtype + * @return String: log name + * @deprecated in 1.19, warnings in 1.21. Use getName() + */ + public static function logName( $type ) { + wfDeprecated( __METHOD__, '1.19' ); + global $wgLogNames; + + if( isset( $wgLogNames[$type] ) ) { + return str_replace( '_', ' ', wfMsg( $wgLogNames[$type] ) ); + } else { + // Bogus log types? Perhaps an extension was removed. + return $type; + } + } + + /** + * Get the log header for the given log type + * + * @todo handle missing log types + * @param $type String: logtype + * @return String: headertext of this logtype + * @deprecated in 1.19, warnings in 1.21. Use getDescription() + */ + public static function logHeader( $type ) { + wfDeprecated( __METHOD__, '1.19' ); + global $wgLogHeaders; + return wfMsgExt( $wgLogHeaders[$type], array( 'parseinline' ) ); + } + + /** + * Generate text for a log entry. + * Only LogFormatter should call this function. + * + * @param $type String: log type + * @param $action String: log action + * @param $title Mixed: Title object or null + * @param $skin Mixed: Skin object or null. If null, we want to use the wiki + * content language, since that will go to the IRC feed. + * @param $params Array: parameters + * @param $filterWikilinks Boolean: whether to filter wiki links + * @return HTML string + */ + public static function actionText( $type, $action, $title = null, $skin = null, + $params = array(), $filterWikilinks = false ) + { + global $wgLang, $wgContLang, $wgLogActions; + + if ( is_null( $skin ) ) { + $langObj = $wgContLang; + $langObjOrNull = null; + } else { + $langObj = $wgLang; + $langObjOrNull = $wgLang; + } + + $key = "$type/$action"; + + if( isset( $wgLogActions[$key] ) ) { + if( is_null( $title ) ) { + $rv = wfMsgExt( $wgLogActions[$key], array( 'parsemag', 'escape', 'language' => $langObj ) ); + } else { + $titleLink = self::getTitleLink( $type, $langObjOrNull, $title, $params ); + + if( preg_match( '/^rights\/(rights|autopromote)/', $key ) ) { + $rightsnone = wfMsgExt( 'rightsnone', array( 'parsemag', 'language' => $langObj ) ); + + if( $skin ) { + foreach ( $params as &$param ) { + $groupArray = array_map( 'trim', explode( ',', $param ) ); + $groupArray = array_map( array( 'User', 'getGroupMember' ), $groupArray ); + $param = $wgLang->listToText( $groupArray ); + } + } + + if( !isset( $params[0] ) || trim( $params[0] ) == '' ) { + $params[0] = $rightsnone; + } + + if( !isset( $params[1] ) || trim( $params[1] ) == '' ) { + $params[1] = $rightsnone; + } + } + + if( count( $params ) == 0 ) { + $rv = wfMsgExt( $wgLogActions[$key], array( 'parsemag', 'escape', 'replaceafter', 'language' => $langObj ), $titleLink ); + } else { + $details = ''; + array_unshift( $params, $titleLink ); + + // User suppression + if ( preg_match( '/^(block|suppress)\/(block|reblock)$/', $key ) ) { + if ( $skin ) { + $params[1] = '<span class="blockExpiry" dir="ltr" title="' . htmlspecialchars( $params[1] ). '">' . + $wgLang->translateBlockExpiry( $params[1] ) . '</span>'; + } else { + $params[1] = $wgContLang->translateBlockExpiry( $params[1] ); + } + + $params[2] = isset( $params[2] ) ? + self::formatBlockFlags( $params[2], $langObj ) : ''; + // Page protections + } elseif ( $type == 'protect' && count($params) == 3 ) { + // Restrictions and expiries + if( $skin ) { + $details .= $wgLang->getDirMark() . htmlspecialchars( " {$params[1]}" ); + } else { + $details .= " {$params[1]}"; + } + + // Cascading flag... + if( $params[2] ) { + $details .= ' [' . wfMsgExt( 'protect-summary-cascade', array( 'parsemag', 'language' => $langObj ) ) . ']'; + } + } + + $rv = wfMsgExt( $wgLogActions[$key], array( 'parsemag', 'escape', 'replaceafter', 'language' => $langObj ), $params ) . $details; + } + } + } else { + global $wgLogActionsHandlers; + + if( isset( $wgLogActionsHandlers[$key] ) ) { + $args = func_get_args(); + $rv = call_user_func_array( $wgLogActionsHandlers[$key], $args ); + } else { + wfDebug( "LogPage::actionText - unknown action $key\n" ); + $rv = "$action"; + } + } + + // For the perplexed, this feature was added in r7855 by Erik. + // The feature was added because we liked adding [[$1]] in our log entries + // but the log entries are parsed as Wikitext on RecentChanges but as HTML + // on Special:Log. The hack is essentially that [[$1]] represented a link + // to the title in question. The first parameter to the HTML version (Special:Log) + // is that link in HTML form, and so this just gets rid of the ugly [[]]. + // However, this is a horrible hack and it doesn't work like you expect if, say, + // you want to link to something OTHER than the title of the log entry. + // The real problem, which Erik was trying to fix (and it sort-of works now) is + // that the same messages are being treated as both wikitext *and* HTML. + if( $filterWikilinks ) { + $rv = str_replace( '[[', '', $rv ); + $rv = str_replace( ']]', '', $rv ); + } + + return $rv; + } + + /** + * TODO document + * @param $type String + * @param $lang Language or null + * @param $title Title + * @param $params Array + * @return String + */ + protected static function getTitleLink( $type, $lang, $title, &$params ) { + global $wgContLang, $wgUserrightsInterwikiDelimiter; + + if( !$lang ) { + return $title->getPrefixedText(); + } + + switch( $type ) { + case 'move': + $titleLink = Linker::link( + $title, + htmlspecialchars( $title->getPrefixedText() ), + array(), + array( 'redirect' => 'no' ) + ); + + $targetTitle = Title::newFromText( $params[0] ); + + if ( !$targetTitle ) { + # Workaround for broken database + $params[0] = htmlspecialchars( $params[0] ); + } else { + $params[0] = Linker::link( + $targetTitle, + htmlspecialchars( $params[0] ) + ); + } + break; + case 'block': + if( substr( $title->getText(), 0, 1 ) == '#' ) { + $titleLink = $title->getText(); + } else { + // @todo Store the user identifier in the parameters + // to make this faster for future log entries + $id = User::idFromName( $title->getText() ); + $titleLink = Linker::userLink( $id, $title->getText() ) + . Linker::userToolLinks( $id, $title->getText(), false, Linker::TOOL_LINKS_NOBLOCK ); + } + break; + case 'rights': + $text = $wgContLang->ucfirst( $title->getText() ); + $parts = explode( $wgUserrightsInterwikiDelimiter, $text, 2 ); + + if ( count( $parts ) == 2 ) { + $titleLink = WikiMap::foreignUserLink( $parts[1], $parts[0], + htmlspecialchars( $title->getPrefixedText() ) ); + + if ( $titleLink !== false ) { + break; + } + } + $titleLink = Linker::link( Title::makeTitle( NS_USER, $text ) ); + break; + case 'merge': + $titleLink = Linker::link( + $title, + $title->getPrefixedText(), + array(), + array( 'redirect' => 'no' ) + ); + $params[0] = Linker::link( + Title::newFromText( $params[0] ), + htmlspecialchars( $params[0] ) + ); + $params[1] = $lang->timeanddate( $params[1] ); + break; + default: + if( $title->isSpecialPage() ) { + list( $name, $par ) = SpecialPageFactory::resolveAlias( $title->getDBkey() ); + + # Use the language name for log titles, rather than Log/X + if( $name == 'Log' ) { + $titleLink = '(' . Linker::link( $title, LogPage::logName( $par ) ) . ')'; + } else { + $titleLink = Linker::link( $title ); + } + } else { + $titleLink = Linker::link( $title ); + } + } + + return $titleLink; + } + + /** + * Add a log entry + * + * @param $action String: one of '', 'block', 'protect', 'rights', 'delete', 'upload', 'move', 'move_redir' + * @param $target Title object + * @param $comment String: description associated + * @param $params Array: parameters passed later to wfMsg.* functions + * @param $doer User object: the user doing the action + * + * @return bool|int|null + * @TODO: make this use LogEntry::saveContent() + */ + public function addEntry( $action, $target, $comment, $params = array(), $doer = null ) { + global $wgContLang; + + if ( !is_array( $params ) ) { + $params = array( $params ); + } + + if ( $comment === null ) { + $comment = ''; + } + + # Truncate for whole multibyte characters. + $comment = $wgContLang->truncate( $comment, 255 ); + + $this->action = $action; + $this->target = $target; + $this->comment = $comment; + $this->params = LogPage::makeParamBlob( $params ); + + if ( $doer === null ) { + global $wgUser; + $doer = $wgUser; + } elseif ( !is_object( $doer ) ) { + $doer = User::newFromId( $doer ); + } + + $this->doer = $doer; + + $logEntry = new ManualLogEntry( $this->type, $action ); + $logEntry->setTarget( $target ); + $logEntry->setPerformer( $doer ); + $logEntry->setParameters( $params ); + + $formatter = LogFormatter::newFromEntry( $logEntry ); + $context = RequestContext::newExtraneousContext( $target ); + $formatter->setContext( $context ); + + $this->actionText = $formatter->getPlainActionText(); + + return $this->saveContent(); + } + + /** + * Add relations to log_search table + * + * @param $field String + * @param $values Array + * @param $logid Integer + * @return Boolean + */ + public function addRelations( $field, $values, $logid ) { + if( !strlen( $field ) || empty( $values ) ) { + return false; // nothing + } + + $data = array(); + + foreach( $values as $value ) { + $data[] = array( + 'ls_field' => $field, + 'ls_value' => $value, + 'ls_log_id' => $logid + ); + } + + $dbw = wfGetDB( DB_MASTER ); + $dbw->insert( 'log_search', $data, __METHOD__, 'IGNORE' ); + + return true; + } + + /** + * Create a blob from a parameter array + * + * @param $params Array + * @return String + */ + public static function makeParamBlob( $params ) { + return implode( "\n", $params ); + } + + /** + * Extract a parameter array from a blob + * + * @param $blob String + * @return Array + */ + public static function extractParams( $blob ) { + if ( $blob === '' ) { + return array(); + } else { + return explode( "\n", $blob ); + } + } + + /** + * Convert a comma-delimited list of block log flags + * into a more readable (and translated) form + * + * @param $flags Flags to format + * @param $lang Language object to use + * @return String + */ + public static function formatBlockFlags( $flags, $lang ) { + $flags = explode( ',', trim( $flags ) ); + + if( count( $flags ) > 0 ) { + for( $i = 0; $i < count( $flags ); $i++ ) { + $flags[$i] = self::formatBlockFlag( $flags[$i], $lang ); + } + return '(' . $lang->commaList( $flags ) . ')'; + } else { + return ''; + } + } + + /** + * Translate a block log flag if possible + * + * @param $flag int Flag to translate + * @param $lang Language object to use + * @return String + */ + public static function formatBlockFlag( $flag, $lang ) { + static $messages = array(); + + if( !isset( $messages[$flag] ) ) { + $messages[$flag] = htmlspecialchars( $flag ); // Fallback + + // For grepping. The following core messages can be used here: + // * block-log-flags-angry-autoblock + // * block-log-flags-anononly + // * block-log-flags-hiddenname + // * block-log-flags-noautoblock + // * block-log-flags-nocreate + // * block-log-flags-noemail + // * block-log-flags-nousertalk + $msg = wfMessage( 'block-log-flags-' . $flag )->inLanguage( $lang ); + + if ( $msg->exists() ) { + $messages[$flag] = $msg->escaped(); + } + } + + return $messages[$flag]; + } + + + /** + * Name of the log. + * @return Message + * @since 1.19 + */ + public function getName() { + global $wgLogNames; + + // BC + if ( isset( $wgLogNames[$this->type] ) ) { + $key = $wgLogNames[$this->type]; + } else { + $key = 'log-name-' . $this->type; + } + + return wfMessage( $key ); + } + + /** + * Description of this log type. + * @return Message + * @since 1.19 + */ + public function getDescription() { + global $wgLogHeaders; + // BC + if ( isset( $wgLogHeaders[$this->type] ) ) { + $key = $wgLogHeaders[$this->type]; + } else { + $key = 'log-description-' . $this->type; + } + return wfMessage( $key ); + } + + /** + * Returns the right needed to read this log type. + * @return string + * @since 1.19 + */ + public function getRestriction() { + global $wgLogRestrictions; + if ( isset( $wgLogRestrictions[$this->type] ) ) { + $restriction = $wgLogRestrictions[$this->type]; + } else { + // '' always returns true with $user->isAllowed() + $restriction = ''; + } + return $restriction; + } + + /** + * Tells if this log is not viewable by all. + * @return bool + * @since 1.19 + */ + public function isRestricted() { + $restriction = $this->getRestriction(); + return $restriction !== '' && $restriction !== '*'; + } + +} diff --git a/includes/logging/LogPager.php b/includes/logging/LogPager.php new file mode 100644 index 00000000..16781a6e --- /dev/null +++ b/includes/logging/LogPager.php @@ -0,0 +1,356 @@ +<?php +/** + * Contain classes to list log entries + * + * Copyright © 2004 Brion Vibber <brion@pobox.com>, 2008 Aaron Schulz + * http://www.mediawiki.org/ + * + * 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 + */ +class LogPager extends ReverseChronologicalPager { + private $types = array(), $performer = '', $title = '', $pattern = ''; + private $typeCGI = ''; + public $mLogEventsList; + + /** + * Constructor + * + * @param $list LogEventsList + * @param $types String or Array: log types to show + * @param $performer String: the user who made the log entries + * @param $title String|Title: the page title the log entries are for + * @param $pattern String: do a prefix search rather than an exact title match + * @param $conds Array: extra conditions for the query + * @param $year Integer: the year to start from + * @param $month Integer: the month to start from + * @param $tagFilter String: tag + */ + public function __construct( $list, $types = array(), $performer = '', $title = '', $pattern = '', + $conds = array(), $year = false, $month = false, $tagFilter = '' ) { + parent::__construct( $list->getContext() ); + $this->mConds = $conds; + + $this->mLogEventsList = $list; + + $this->limitType( $types ); // also excludes hidden types + $this->limitPerformer( $performer ); + $this->limitTitle( $title, $pattern ); + $this->getDateCond( $year, $month ); + $this->mTagFilter = $tagFilter; + } + + public function getDefaultQuery() { + $query = parent::getDefaultQuery(); + $query['type'] = $this->typeCGI; // arrays won't work here + $query['user'] = $this->performer; + $query['month'] = $this->mMonth; + $query['year'] = $this->mYear; + return $query; + } + + // Call ONLY after calling $this->limitType() already! + public function getFilterParams() { + global $wgFilterLogTypes; + $filters = array(); + if( count($this->types) ) { + return $filters; + } + foreach( $wgFilterLogTypes as $type => $default ) { + // Avoid silly filtering + if( $type !== 'patrol' || $this->getUser()->useNPPatrol() ) { + $hide = $this->getRequest()->getInt( "hide_{$type}_log", $default ); + $filters[$type] = $hide; + if( $hide ) + $this->mConds[] = 'log_type != ' . $this->mDb->addQuotes( $type ); + } + } + return $filters; + } + + /** + * Set the log reader to return only entries of the given type. + * Type restrictions enforced here + * + * @param $types String or array: Log types ('upload', 'delete', etc); + * empty string means no restriction + */ + private function limitType( $types ) { + global $wgLogRestrictions; + // If $types is not an array, make it an array + $types = ($types === '') ? array() : (array)$types; + // Don't even show header for private logs; don't recognize it... + $needReindex = false; + foreach ( $types as $type ) { + if( isset( $wgLogRestrictions[$type] ) + && !$this->getUser()->isAllowed($wgLogRestrictions[$type]) + ) { + $needReindex = true; + $types = array_diff( $types, array( $type ) ); + } + } + if ( $needReindex ) { + // Lots of this code makes assumptions that + // the first entry in the array is $types[0]. + $types = array_values( $types ); + } + $this->types = $types; + // Don't show private logs to unprivileged users. + // Also, only show them upon specific request to avoid suprises. + $audience = $types ? 'user' : 'public'; + $hideLogs = LogEventsList::getExcludeClause( $this->mDb, $audience ); + if( $hideLogs !== false ) { + $this->mConds[] = $hideLogs; + } + if( count($types) ) { + $this->mConds['log_type'] = $types; + // Set typeCGI; used in url param for paging + if( count($types) == 1 ) $this->typeCGI = $types[0]; + } + } + + /** + * Set the log reader to return only entries by the given user. + * + * @param $name String: (In)valid user name + */ + private function limitPerformer( $name ) { + if( $name == '' ) { + return false; + } + $usertitle = Title::makeTitleSafe( NS_USER, $name ); + if( is_null($usertitle) ) { + return false; + } + /* Fetch userid at first, if known, provides awesome query plan afterwards */ + $userid = User::idFromName( $name ); + if( !$userid ) { + /* It should be nicer to abort query at all, + but for now it won't pass anywhere behind the optimizer */ + $this->mConds[] = "NULL"; + } else { + $this->mConds['log_user'] = $userid; + // Paranoia: avoid brute force searches (bug 17342) + $user = $this->getUser(); + if( !$user->isAllowed( 'deletedhistory' ) ) { + $this->mConds[] = $this->mDb->bitAnd('log_deleted', LogPage::DELETED_USER) . ' = 0'; + } elseif( !$user->isAllowed( 'suppressrevision' ) ) { + $this->mConds[] = $this->mDb->bitAnd('log_deleted', LogPage::SUPPRESSED_USER) . + ' != ' . LogPage::SUPPRESSED_USER; + } + $this->performer = $usertitle->getText(); + } + } + + /** + * Set the log reader to return only entries affecting the given page. + * (For the block and rights logs, this is a user page.) + * + * @param $page String or Title object: Title name + * @param $pattern String + */ + private function limitTitle( $page, $pattern ) { + global $wgMiserMode; + + if ( $page instanceof Title ) { + $title = $page; + } else { + $title = Title::newFromText( $page ); + if( strlen( $page ) == 0 || !$title instanceof Title ) { + return false; + } + } + + $this->title = $title->getPrefixedText(); + $ns = $title->getNamespace(); + $db = $this->mDb; + + # Using the (log_namespace, log_title, log_timestamp) index with a + # range scan (LIKE) on the first two parts, instead of simple equality, + # makes it unusable for sorting. Sorted retrieval using another index + # would be possible, but then we might have to scan arbitrarily many + # nodes of that index. Therefore, we need to avoid this if $wgMiserMode + # is on. + # + # This is not a problem with simple title matches, because then we can + # use the page_time index. That should have no more than a few hundred + # log entries for even the busiest pages, so it can be safely scanned + # in full to satisfy an impossible condition on user or similar. + if( $pattern && !$wgMiserMode ) { + $this->mConds['log_namespace'] = $ns; + $this->mConds[] = 'log_title ' . $db->buildLike( $title->getDBkey(), $db->anyString() ); + $this->pattern = $pattern; + } else { + $this->mConds['log_namespace'] = $ns; + $this->mConds['log_title'] = $title->getDBkey(); + } + // Paranoia: avoid brute force searches (bug 17342) + $user = $this->getUser(); + if( !$user->isAllowed( 'deletedhistory' ) ) { + $this->mConds[] = $db->bitAnd('log_deleted', LogPage::DELETED_ACTION) . ' = 0'; + } elseif( !$user->isAllowed( 'suppressrevision' ) ) { + $this->mConds[] = $db->bitAnd('log_deleted', LogPage::SUPPRESSED_ACTION) . + ' != ' . LogPage::SUPPRESSED_ACTION; + } + } + + /** + * Constructs the most part of the query. Extra conditions are sprinkled in + * all over this class. + * @return array + */ + public function getQueryInfo() { + $basic = DatabaseLogEntry::getSelectQueryData(); + + $tables = $basic['tables']; + $fields = $basic['fields']; + $conds = $basic['conds']; + $options = $basic['options']; + $joins = $basic['join_conds']; + + $index = array(); + # Add log_search table if there are conditions on it. + # This filters the results to only include log rows that have + # log_search records with the specified ls_field and ls_value values. + if( array_key_exists( 'ls_field', $this->mConds ) ) { + $tables[] = 'log_search'; + $index['log_search'] = 'ls_field_val'; + $index['logging'] = 'PRIMARY'; + if ( !$this->hasEqualsClause( 'ls_field' ) + || !$this->hasEqualsClause( 'ls_value' ) ) + { + # Since (ls_field,ls_value,ls_logid) is unique, if the condition is + # to match a specific (ls_field,ls_value) tuple, then there will be + # no duplicate log rows. Otherwise, we need to remove the duplicates. + $options[] = 'DISTINCT'; + } + # Avoid usage of the wrong index by limiting + # the choices of available indexes. This mainly + # avoids site-breaking filesorts. + } elseif( $this->title || $this->pattern || $this->performer ) { + $index['logging'] = array( 'page_time', 'user_time' ); + if( count($this->types) == 1 ) { + $index['logging'][] = 'log_user_type_time'; + } + } elseif( count($this->types) == 1 ) { + $index['logging'] = 'type_time'; + } else { + $index['logging'] = 'times'; + } + $options['USE INDEX'] = $index; + # Don't show duplicate rows when using log_search + $joins['log_search'] = array( 'INNER JOIN', 'ls_log_id=log_id' ); + + $info = array( + 'tables' => $tables, + 'fields' => $fields, + 'conds' => array_merge( $conds, $this->mConds ), + 'options' => $options, + 'join_conds' => $joins, + ); + # Add ChangeTags filter query + ChangeTags::modifyDisplayQuery( $info['tables'], $info['fields'], $info['conds'], + $info['join_conds'], $info['options'], $this->mTagFilter ); + return $info; + } + + /** + * Checks if $this->mConds has $field matched to a *single* value + * @param $field + * @return bool + */ + protected function hasEqualsClause( $field ) { + return ( + array_key_exists( $field, $this->mConds ) && + ( !is_array( $this->mConds[$field] ) || count( $this->mConds[$field] ) == 1 ) + ); + } + + function getIndexField() { + return 'log_timestamp'; + } + + public function getStartBody() { + wfProfileIn( __METHOD__ ); + # Do a link batch query + if( $this->getNumRows() > 0 ) { + $lb = new LinkBatch; + foreach ( $this->mResult as $row ) { + $lb->add( $row->log_namespace, $row->log_title ); + $lb->addObj( Title::makeTitleSafe( NS_USER, $row->user_name ) ); + $lb->addObj( Title::makeTitleSafe( NS_USER_TALK, $row->user_name ) ); + $formatter = LogFormatter::newFromRow( $row ); + foreach ( $formatter->getPreloadTitles() as $title ) { + $lb->addObj( $title ); + } + } + $lb->execute(); + $this->mResult->seek( 0 ); + } + wfProfileOut( __METHOD__ ); + return ''; + } + + public function formatRow( $row ) { + return $this->mLogEventsList->logLine( $row ); + } + + public function getType() { + return $this->types; + } + + /** + * @return string + */ + public function getPerformer() { + return $this->performer; + } + + /** + * @return string + */ + public function getPage() { + return $this->title; + } + + public function getPattern() { + return $this->pattern; + } + + public function getYear() { + return $this->mYear; + } + + public function getMonth() { + return $this->mMonth; + } + + public function getTagFilter() { + return $this->mTagFilter; + } + + public function doQuery() { + // Workaround MySQL optimizer bug + $this->mDb->setBigSelects(); + parent::doQuery(); + $this->mDb->setBigSelects( 'default' ); + } +} diff --git a/includes/logging/PatrolLog.php b/includes/logging/PatrolLog.php new file mode 100644 index 00000000..04fdc4f2 --- /dev/null +++ b/includes/logging/PatrolLog.php @@ -0,0 +1,58 @@ +<?php + +/** + * Class containing static functions for working with + * logs of patrol events + * + * @author Rob Church <robchur@gmail.com> + * @author Niklas Laxström + */ +class PatrolLog { + + /** + * Record a log event for a change being patrolled + * + * @param $rc Mixed: change identifier or RecentChange object + * @param $auto Boolean: was this patrol event automatic? + * + * @return bool + */ + public static function record( $rc, $auto = false ) { + if ( !$rc instanceof RecentChange ) { + $rc = RecentChange::newFromId( $rc ); + if ( !is_object( $rc ) ) { + return false; + } + } + + $title = Title::makeTitleSafe( $rc->getAttribute( 'rc_namespace' ), $rc->getAttribute( 'rc_title' ) ); + if( $title ) { + $entry = new ManualLogEntry( 'patrol', 'patrol' ); + $entry->setTarget( $title ); + $entry->setParameters( self::buildParams( $rc, $auto ) ); + $entry->setPerformer( User::newFromName( $rc->getAttribute( 'rc_user_text' ), false ) ); + $logid = $entry->insert(); + if ( !$auto ) { + $entry->publish( $logid, 'udp' ); + } + return true; + } + return false; + } + + /** + * Prepare log parameters for a patrolled change + * + * @param $change RecentChange to represent + * @param $auto Boolean: whether the patrol event was automatic + * @return Array + */ + private static function buildParams( $change, $auto ) { + return array( + '4::curid' => $change->getAttribute( 'rc_this_oldid' ), + '5::previd' => $change->getAttribute( 'rc_last_oldid' ), + '6::auto' => (int)$auto + ); + } + +} |