Debian Codegraph @

includes/recentchanges/CategoryMembershipChange.php

raw symbols SCIP
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20
21 use MediaWiki\Cache\BacklinkCache;
22 use MediaWiki\MediaWikiServices;
23 use MediaWiki\Page\PageIdentity;
24 use MediaWiki\Revision\RevisionRecord;
25 use MediaWiki\Title\Title;
26 use MediaWiki\User\User;
27 use MediaWiki\User\UserIdentity;
28 use Wikimedia\Rdbms\IDBAccessObject;
29
30 /**
31 * Helper class for category membership changes
32 *
33 * @since 1.27
34 * @ingroup RecentChanges
35 * @author Kai Nissen
36 * @author Addshore
37 */
38 class CategoryMembershipChange {
39
40 private const CATEGORY_ADDITION = 1;
41 private const CATEGORY_REMOVAL = -1;
42
43 /**
44 * @var string Current timestamp, set during CategoryMembershipChange::__construct()
45 */
46 private $timestamp;
47
48 /**
49 * @var Title Title instance of the categorized page
50 */
51 private $pageTitle;
52
53 /**
54 * @var RevisionRecord|null Latest revision of the categorized page
55 */
56 private $revision;
57
58 /** @var bool Whether this was caused by an import */
59 private $forImport;
60
61 /**
62 * @var int
63 * Number of pages this WikiPage is embedded by
64 * Set by CategoryMembershipChange::checkTemplateLinks()
65 */
66 private $numTemplateLinks = 0;
67
68 /**
69 * @var callable|null
70 */
71 private $newForCategorizationCallback = null;
72
73 /** @var BacklinkCache */
74 private $backlinkCache;
75
76 /**
77 * @param Title $pageTitle Title instance of the categorized page
78 * @param BacklinkCache $backlinkCache
79 * @param RevisionRecord|null $revision Latest revision of the categorized page.
80 * @param bool $forImport Whether this was caused by a import
81 */
82 public function __construct(
83 Title $pageTitle, BacklinkCache $backlinkCache, ?RevisionRecord $revision = null, bool $forImport = false
84 ) {
85 // TODO: Update callers of this method to pass for import
86 $this->pageTitle = $pageTitle;
87 $this->revision = $revision;
88
89 // Use the current timestamp for creating the RC entry when dealing with imported revisions,
90 // since their timestamp may be significantly older than the current time.
91 // This ensures the resulting RC entry won't be immediately reaped by probabilistic RC purging if
92 // the imported revision is older than $wgRCMaxAge (T377392).
93 if ( $revision === null || $forImport ) {
94 $this->timestamp = wfTimestampNow();
95 } else {
96 $this->timestamp = $revision->getTimestamp();
97 }
98 $this->newForCategorizationCallback = [ RecentChange::class, 'newForCategorization' ];
99 $this->backlinkCache = $backlinkCache;
100 $this->forImport = $forImport;
101 }
102
103 /**
104 * Overrides the default new for categorization callback
105 * This is intended for use while testing and will fail if MW_PHPUNIT_TEST is not defined.
106 *
107 * @param callable $callback
108 * @see RecentChange::newForCategorization for callback signiture
109 */
110 public function overrideNewForCategorizationCallback( callable $callback ) {
111 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
112 throw new LogicException( 'Cannot override newForCategorization callback in operation.' );
113 }
114 $this->newForCategorizationCallback = $callback;
115 }
116
117 /**
118 * Determines the number of template links for recursive link updates
119 */
120 public function checkTemplateLinks() {
121 $this->numTemplateLinks = $this->backlinkCache->getNumLinks( 'templatelinks' );
122 }
123
124 /**
125 * Create a recentchanges entry for category additions
126 *
127 * @param PageIdentity $categoryPage
128 */
129 public function triggerCategoryAddedNotification( PageIdentity $categoryPage ) {
130 $this->createRecentChangesEntry( $categoryPage, self::CATEGORY_ADDITION );
131 }
132
133 /**
134 * Create a recentchanges entry for category removals
135 *
136 * @param PageIdentity $categoryPage
137 */
138 public function triggerCategoryRemovedNotification( PageIdentity $categoryPage ) {
139 $this->createRecentChangesEntry( $categoryPage, self::CATEGORY_REMOVAL );
140 }
141
142 /**
143 * Create a recentchanges entry using RecentChange::notifyCategorization()
144 *
145 * @param PageIdentity $categoryPage
146 * @param int $type
147 */
148 private function createRecentChangesEntry( PageIdentity $categoryPage, $type ) {
149 $this->notifyCategorization(
150 $this->timestamp,
151 $categoryPage,
152 $this->getUser(),
153 $this->getChangeMessageText(
154 $type,
155 $this->pageTitle->getPrefixedText(),
156 $this->numTemplateLinks
157 ),
158 $this->pageTitle,
159 $this->getPreviousRevisionTimestamp(),
160 $this->revision,
161 $this->forImport,
162 $type === self::CATEGORY_ADDITION
163 );
164 }
165
166 /**
167 * @param string $timestamp Timestamp of the recent change to occur in TS_MW format
168 * @param PageIdentity $categoryPage Page of the category a page is being added to or removed from
169 * @param UserIdentity|null $user User object of the user that made the change
170 * @param string $comment Change summary
171 * @param PageIdentity $page Page that is being added or removed
172 * @param string $lastTimestamp Parent revision timestamp of this change in TS_MW format
173 * @param RevisionRecord|null $revision
174 * @param bool $forImport Whether the associated revision was imported
175 * @param bool $added true, if the category was added, false for removed
176 */
177 private function notifyCategorization(
178 $timestamp,
179 PageIdentity $categoryPage,
180 ?UserIdentity $user,
181 $comment,
182 PageIdentity $page,
183 $lastTimestamp,
184 $revision,
185 bool $forImport,
186 $added
187 ) {
188 $deleted = $revision ? $revision->getVisibility() & RevisionRecord::SUPPRESSED_USER : 0;
189 $newRevId = $revision ? $revision->getId() : 0;
190
191 /**
192 * T109700 - Default bot flag to true when there is no corresponding RC entry
193 * This means all changes caused by parser functions & Lua on reparse are marked as bot
194 * Also in the case no RC entry could be found due to replica DB lag
195 */
196 $bot = 1;
197 $lastRevId = 0;
198 $ip = '';
199
200 # If no revision is given, the change was probably triggered by parser functions
201 if ( $revision !== null ) {
202 $revisionStore = MediaWikiServices::getInstance()->getRevisionStore();
203
204 $correspondingRc = $revisionStore->getRecentChange( $this->revision ) ??
205 $revisionStore->getRecentChange( $this->revision, IDBAccessObject::READ_LATEST );
206 if ( $correspondingRc !== null ) {
207 $bot = $correspondingRc->getAttribute( 'rc_bot' ) ?: 0;
208 $ip = $correspondingRc->getAttribute( 'rc_ip' ) ?: '';
209 $lastRevId = $correspondingRc->getAttribute( 'rc_last_oldid' ) ?: 0;
210 }
211 }
212
213 /** @var RecentChange $rc */
214 $rc = ( $this->newForCategorizationCallback )(
215 $timestamp,
216 $categoryPage,
217 $user,
218 $comment,
219 $page,
220 $lastRevId,
221 $newRevId,
222 $lastTimestamp,
223 $bot,
224 $ip,
225 $deleted,
226 $added,
227 $forImport
228 );
229 $rc->save();
230 }
231
232 /**
233 * Get the user associated with this change.
234 *
235 * If there is no revision associated with the change and thus no editing user
236 * fallback to a default.
237 *
238 * False will be returned if the user name specified in the
239 * 'autochange-username' message is invalid.
240 *
241 * @return UserIdentity|null
242 */
243 private function getUser(): ?UserIdentity {
244 if ( $this->revision ) {
245 $user = $this->revision->getUser( RevisionRecord::RAW );
246 if ( $user ) {
247 return $user;
248 }
249 }
250
251 $username = wfMessage( 'autochange-username' )->inContentLanguage()->text();
252
253 $user = User::newSystemUser( $username );
254 if ( $user && !$user->isRegistered() ) {
255 $user->addToDatabase();
256 }
257
258 return $user ?: null;
259 }
260
261 /**
262 * Returns the change message according to the type of category membership change
263 *
264 * The message keys created in this method may be one of:
265 * - recentchanges-page-added-to-category
266 * - recentchanges-page-added-to-category-bundled
267 * - recentchanges-page-removed-from-category
268 * - recentchanges-page-removed-from-category-bundled
269 *
270 * @param int $type may be CategoryMembershipChange::CATEGORY_ADDITION
271 * or CategoryMembershipChange::CATEGORY_REMOVAL
272 * @param string $prefixedText result of Title::->getPrefixedText()
273 * @param int $numTemplateLinks
274 *
275 * @return string
276 */
277 private function getChangeMessageText( $type, $prefixedText, $numTemplateLinks ) {
278 $array = [
279 self::CATEGORY_ADDITION => 'recentchanges-page-added-to-category',
280 self::CATEGORY_REMOVAL => 'recentchanges-page-removed-from-category',
281 ];
282
283 $msgKey = $array[$type];
284
285 if ( intval( $numTemplateLinks ) > 0 ) {
286 $msgKey .= '-bundled';
287 }
288
289 return wfMessage( $msgKey, $prefixedText )->inContentLanguage()->text();
290 }
291
292 /**
293 * Returns the timestamp of the page's previous revision or null if the latest revision
294 * does not refer to a parent revision
295 *
296 * @return null|string
297 */
298 private function getPreviousRevisionTimestamp() {
299 $rl = MediaWikiServices::getInstance()->getRevisionLookup();
300 $latestRev = $rl->getRevisionByTitle( $this->pageTitle );
301 if ( $latestRev ) {
302 $previousRev = $rl->getPreviousRevision( $latestRev );
303 if ( $previousRev ) {
304 return $previousRev->getTimestamp();
305 }
306 }
307 return null;
308 }
309
310 }