Don't double-escape the ellipses in Language::truncateForVisual()
[mediawiki.git] / includes / logging / LogPage.php
blob6b246dc33f801cb433c667ab7df94a06215846ca
1 <?php
2 /**
3 * Contain log classes
5 * Copyright © 2002, 2004 Brion Vibber <brion@pobox.com>
6 * https://www.mediawiki.org/
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
23 * @file
26 use MediaWiki\MediaWikiServices;
27 use MediaWiki\User\UserIdentity;
29 /**
30 * Class to simplify the use of log pages.
31 * The logs are now kept in a table which is easier to manage and trim
32 * than ever-growing wiki pages.
34 * @newable
35 * @note marked as newable in 1.35 for lack of a better alternative,
36 * but should become a stateless service, use the command pattern.
38 class LogPage {
39 public const DELETED_ACTION = 1;
40 public const DELETED_COMMENT = 2;
41 public const DELETED_USER = 4;
42 public const DELETED_RESTRICTED = 8;
44 // Convenience fields
45 public const SUPPRESSED_USER = self::DELETED_USER | self::DELETED_RESTRICTED;
46 public const SUPPRESSED_ACTION = self::DELETED_ACTION | self::DELETED_RESTRICTED;
48 /** @var bool */
49 public $updateRecentChanges;
51 /** @var bool */
52 public $sendToUDP;
54 /** @var string Plaintext version of the message for IRC */
55 private $ircActionText;
57 /** @var string Plaintext version of the message */
58 private $actionText;
60 /** @var string One of '', 'block', 'protect', 'rights', 'delete',
61 * 'upload', 'move'
63 private $type;
65 /** @var string One of '', 'block', 'protect', 'rights', 'delete',
66 * 'upload', 'move', 'move_redir'
68 private $action;
70 /** @var string Comment associated with action */
71 private $comment;
73 /** @var string Blob made of a parameters array */
74 private $params;
76 /** @var UserIdentity The user doing the action */
77 private $performer;
79 /** @var Title */
80 private $target;
82 /**
83 * @stable to call
84 * @param string $type One of '', 'block', 'protect', 'rights', 'delete',
85 * 'upload', 'move'
86 * @param bool $rc Whether to update recent changes as well as the logging table
87 * @param string $udp Pass 'UDP' to send to the UDP feed if NOT sent to RC
89 public function __construct( $type, $rc = true, $udp = 'skipUDP' ) {
90 $this->type = $type;
91 $this->updateRecentChanges = $rc;
92 $this->sendToUDP = ( $udp == 'UDP' );
95 /**
96 * @return int The log_id of the inserted log entry
98 protected function saveContent() {
99 $logRestrictions = MediaWikiServices::getInstance()->getMainConfig()->get( 'LogRestrictions' );
101 $dbw = wfGetDB( DB_PRIMARY );
103 $now = wfTimestampNow();
104 $actorId = MediaWikiServices::getInstance()->getActorNormalization()
105 ->acquireActorId( $this->performer, $dbw );
106 $data = [
107 'log_type' => $this->type,
108 'log_action' => $this->action,
109 'log_timestamp' => $dbw->timestamp( $now ),
110 'log_actor' => $actorId,
111 'log_namespace' => $this->target->getNamespace(),
112 'log_title' => $this->target->getDBkey(),
113 'log_page' => $this->target->getArticleID(),
114 'log_params' => $this->params
116 $data += MediaWikiServices::getInstance()->getCommentStore()->insert(
117 $dbw,
118 'log_comment',
119 $this->comment
121 $dbw->insert( 'logging', $data, __METHOD__ );
122 $newId = $dbw->insertId();
124 # And update recentchanges
125 if ( $this->updateRecentChanges ) {
126 $titleObj = SpecialPage::getTitleFor( 'Log', $this->type );
128 RecentChange::notifyLog(
129 $now, $titleObj, $this->performer, $this->getRcComment(), '',
130 $this->type, $this->action, $this->target, $this->comment,
131 $this->params, $newId, $this->getRcCommentIRC()
133 } elseif ( $this->sendToUDP ) {
134 # Don't send private logs to UDP
135 if ( isset( $logRestrictions[$this->type] ) && $logRestrictions[$this->type] != '*' ) {
136 return $newId;
139 // Notify external application via UDP.
140 // We send this to IRC but do not want to add it the RC table.
141 $titleObj = SpecialPage::getTitleFor( 'Log', $this->type );
142 $rc = RecentChange::newLogEntry(
143 $now, $titleObj, $this->performer, $this->getRcComment(), '',
144 $this->type, $this->action, $this->target, $this->comment,
145 $this->params, $newId, $this->getRcCommentIRC()
147 $rc->notifyRCFeeds();
150 return $newId;
154 * Get the RC comment from the last addEntry() call
156 * @return string
158 public function getRcComment() {
159 $rcComment = $this->actionText;
161 if ( $this->comment != '' ) {
162 if ( $rcComment == '' ) {
163 $rcComment = $this->comment;
164 } else {
165 $rcComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() .
166 $this->comment;
170 return $rcComment;
174 * Get the RC comment from the last addEntry() call for IRC
176 * @return string
178 public function getRcCommentIRC() {
179 $rcComment = $this->ircActionText;
181 if ( $this->comment != '' ) {
182 if ( $rcComment == '' ) {
183 $rcComment = $this->comment;
184 } else {
185 $rcComment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() .
186 $this->comment;
190 return $rcComment;
194 * Get the comment from the last addEntry() call
195 * @return string
197 public function getComment() {
198 return $this->comment;
202 * Get the list of valid log types
204 * @return string[]
206 public static function validTypes() {
207 $logTypes = MediaWikiServices::getInstance()->getMainConfig()->get( 'LogTypes' );
209 return $logTypes;
213 * Is $type a valid log type
215 * @param string $type Log type to check
216 * @return bool
218 public static function isLogType( $type ) {
219 return in_array( $type, self::validTypes() );
223 * Generate text for a log entry.
224 * Only LogFormatter should call this function.
226 * @param string $type Log type
227 * @param string $action Log action
228 * @param Title|null $title
229 * @param Skin|null $skin Skin object or null. If null, we want to use the wiki
230 * content language, since that will go to the IRC feed.
231 * @param array $params
232 * @param bool $filterWikilinks Whether to filter wiki links
233 * @return string HTML
235 public static function actionText( $type, $action, $title = null, $skin = null,
236 $params = [], $filterWikilinks = false
238 global $wgLang;
239 $logActions = MediaWikiServices::getInstance()->getMainConfig()->get( 'LogActions' );
240 $key = "$type/$action";
242 if ( isset( $logActions[$key] ) ) {
243 if ( $skin === null ) {
244 $langObj = MediaWikiServices::getInstance()->getContentLanguage();
245 $langObjOrNull = null;
246 } else {
247 // TODO Is $skin->getLanguage() safe here?
248 StubUserLang::unstub( $wgLang );
249 $langObj = $wgLang;
250 $langObjOrNull = $wgLang;
252 if ( $title === null ) {
253 $rv = wfMessage( $logActions[$key] )->inLanguage( $langObj )->escaped();
254 } else {
255 $titleLink = self::getTitleLink( $title, $langObjOrNull );
257 if ( count( $params ) == 0 ) {
258 // @phan-suppress-next-line SecurityCheck-XSS
259 $rv = wfMessage( $logActions[$key] )->rawParams( $titleLink )
260 ->inLanguage( $langObj )->escaped();
261 } else {
262 array_unshift( $params, $titleLink );
264 $rv = wfMessage( $logActions[$key] )->rawParams( $params )
265 ->inLanguage( $langObj )->escaped();
268 } else {
269 $logActionsHandlers = MediaWikiServices::getInstance()->getMainConfig()->get( 'LogActionsHandlers' );
271 if ( isset( $logActionsHandlers[$key] ) ) {
272 $args = func_get_args();
273 $rv = call_user_func_array( $logActionsHandlers[$key], $args );
274 } else {
275 wfDebug( "LogPage::actionText - unknown action $key" );
276 $rv = "$action";
280 // For the perplexed, this feature was added in r7855 by Erik.
281 // The feature was added because we liked adding [[$1]] in our log entries
282 // but the log entries are parsed as Wikitext on RecentChanges but as HTML
283 // on Special:Log. The hack is essentially that [[$1]] represented a link
284 // to the title in question. The first parameter to the HTML version (Special:Log)
285 // is that link in HTML form, and so this just gets rid of the ugly [[]].
286 // However, this is a horrible hack and it doesn't work like you expect if, say,
287 // you want to link to something OTHER than the title of the log entry.
288 // The real problem, which Erik was trying to fix (and it sort-of works now) is
289 // that the same messages are being treated as both wikitext *and* HTML.
290 if ( $filterWikilinks ) {
291 $rv = str_replace( '[[', '', $rv );
292 $rv = str_replace( ']]', '', $rv );
295 return $rv;
299 * @param Title $title
300 * @param ?Language $lang
301 * @return string HTML
303 private static function getTitleLink( Title $title, ?Language $lang ): string {
304 if ( !$lang ) {
305 return $title->getPrefixedText();
308 $services = MediaWikiServices::getInstance();
309 $linkRenderer = $services->getLinkRenderer();
311 if ( $title->isSpecialPage() ) {
312 [ $name, $par ] = $services->getSpecialPageFactory()->resolveAlias( $title->getDBkey() );
314 if ( $name === 'Log' ) {
315 $logPage = new LogPage( $par );
316 return wfMessage( 'parentheses' )
317 ->rawParams( $linkRenderer->makeLink( $title, $logPage->getName()->text() ) )
318 ->inLanguage( $lang )
319 ->escaped();
323 return $linkRenderer->makeLink( $title );
327 * Add a log entry
329 * @param string $action One of '', 'block', 'protect', 'rights', 'delete',
330 * 'upload', 'move', 'move_redir'
331 * @param Title $target
332 * @param string $comment Description associated
333 * @param array $params Parameters passed later to wfMessage function
334 * @param int|UserIdentity $performer The user doing the action, or their user id.
335 * Calling with user ID is deprecated since 1.36.
337 * @return int The log_id of the inserted log entry
339 public function addEntry( $action, $target, $comment, $params, $performer ) {
340 // FIXME $params is only documented to accept an array
341 if ( !is_array( $params ) ) {
342 $params = [ $params ];
345 if ( $comment === null ) {
346 $comment = '';
349 # Trim spaces on user supplied text
350 $comment = trim( $comment );
352 $this->action = $action;
353 $this->target = $target;
354 $this->comment = $comment;
355 $this->params = self::makeParamBlob( $params );
357 if ( !is_object( $performer ) ) {
358 $performer = User::newFromId( $performer );
361 $this->performer = $performer;
363 $logEntry = new ManualLogEntry( $this->type, $action );
364 $logEntry->setTarget( $target );
365 $logEntry->setPerformer( $performer );
366 $logEntry->setParameters( $params );
367 // All log entries using the LogPage to insert into the logging table
368 // are using the old logging system and therefore the legacy flag is
369 // needed to say the LogFormatter the parameters have numeric keys
370 $logEntry->setLegacy( true );
372 $formatter = LogFormatter::newFromEntry( $logEntry );
373 $context = RequestContext::newExtraneousContext( $target );
374 $formatter->setContext( $context );
376 $this->actionText = $formatter->getPlainActionText();
377 $this->ircActionText = $formatter->getIRCActionText();
379 return $this->saveContent();
383 * Add relations to log_search table
385 * @param string $field
386 * @param array $values
387 * @param int $logid
388 * @return bool
390 public function addRelations( $field, $values, $logid ) {
391 if ( !strlen( $field ) || empty( $values ) ) {
392 return false;
395 $data = [];
397 foreach ( $values as $value ) {
398 $data[] = [
399 'ls_field' => $field,
400 'ls_value' => $value,
401 'ls_log_id' => $logid
405 $dbw = wfGetDB( DB_PRIMARY );
406 $dbw->insert( 'log_search', $data, __METHOD__, [ 'IGNORE' ] );
408 return true;
412 * Create a blob from a parameter array
414 * @param array $params
415 * @return string
417 public static function makeParamBlob( $params ) {
418 return implode( "\n", $params );
422 * Extract a parameter array from a blob
424 * @param string $blob
425 * @return array
427 public static function extractParams( $blob ) {
428 if ( $blob === '' ) {
429 return [];
430 } else {
431 return explode( "\n", $blob );
436 * Name of the log.
437 * @return Message
438 * @since 1.19
440 public function getName() {
441 $logNames = MediaWikiServices::getInstance()->getMainConfig()->get( 'LogNames' );
443 // BC
444 $key = $logNames[$this->type] ?? 'log-name-' . $this->type;
446 return wfMessage( $key );
450 * Description of this log type.
451 * @return Message
452 * @since 1.19
454 public function getDescription() {
455 $logHeaders = MediaWikiServices::getInstance()->getMainConfig()->get( 'LogHeaders' );
456 // BC
457 $key = $logHeaders[$this->type] ?? 'log-description-' . $this->type;
459 return wfMessage( $key );
463 * Returns the right needed to read this log type.
464 * @return string
465 * @since 1.19
467 public function getRestriction() {
468 $logRestrictions = MediaWikiServices::getInstance()->getMainConfig()->get( 'LogRestrictions' );
469 // The empty string fallback will
470 // always return true in permission check
471 return $logRestrictions[$this->type] ?? '';
475 * Tells if this log is not viewable by all.
476 * @return bool
477 * @since 1.19
479 public function isRestricted() {
480 $restriction = $this->getRestriction();
482 return $restriction !== '' && $restriction !== '*';