Debian Codegraph @

includes/Category/Category.php

raw symbols SCIP
1 <?php
2 /**
3 * Representation for a category.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @author Simetrical
22 */
23
24 namespace MediaWiki\Category;
25
26 use MediaWiki\Deferred\DeferredUpdates;
27 use MediaWiki\MediaWikiServices;
28 use MediaWiki\Page\PageIdentity;
29 use MediaWiki\Title\Title;
30 use MediaWiki\Title\TitleArrayFromResult;
31 use MediaWiki\Title\TitleFactory;
32 use RuntimeException;
33 use stdClass;
34 use Wikimedia\Rdbms\IConnectionProvider;
35 use Wikimedia\Rdbms\ReadOnlyMode;
36
37 /**
38 * Category objects are immutable, strictly speaking. If you call methods that change the database,
39 * like to refresh link counts, the objects will be appropriately reinitialized.
40 * Member variables are lazy-initialized.
41 */
42 class Category {
43 /** @var string|null Name of the category, normalized to DB-key form */
44 private $mName = null;
45 /** @var int|null|false */
46 private $mID = null;
47 /**
48 * Category page title
49 * @var PageIdentity
50 */
51 private $mPage = null;
52
53 /** Counts of membership (cat_pages, cat_subcats, cat_files) */
54 /** @var int */
55 private $mPages = 0;
56
57 /** @var int */
58 private $mSubcats = 0;
59
60 /** @var int */
61 private $mFiles = 0;
62
63 protected const LOAD_ONLY = 0;
64 protected const LAZY_INIT_ROW = 1;
65
66 public const ROW_COUNT_SMALL = 100;
67
68 public const COUNT_ALL_MEMBERS = 0;
69 public const COUNT_CONTENT_PAGES = 1;
70
71 /** @var IConnectionProvider */
72 private $dbProvider;
73
74 /** @var ReadOnlyMode */
75 private $readOnlyMode;
76
77 /** @var TitleFactory */
78 private $titleFactory;
79
80 private function __construct() {
81 $services = MediaWikiServices::getInstance();
82 $this->dbProvider = $services->getConnectionProvider();
83 $this->readOnlyMode = $services->getReadOnlyMode();
84 $this->titleFactory = $services->getTitleFactory();
85 }
86
87 /**
88 * Set up all member variables using a database query.
89 * @param int $mode One of (Category::LOAD_ONLY, Category::LAZY_INIT_ROW)
90 * @return bool True on success, false on failure.
91 */
92 protected function initialize( $mode = self::LOAD_ONLY ) {
93 if ( $this->mName === null && $this->mID === null ) {
94 throw new RuntimeException( __METHOD__ . ' has both names and IDs null' );
95 } elseif ( $this->mID === null ) {
96 $where = [ 'cat_title' => $this->mName ];
97 } elseif ( $this->mName === null ) {
98 $where = [ 'cat_id' => $this->mID ];
99 } else {
100 # Already initialized
101 return true;
102 }
103
104 $row = $this->dbProvider->getReplicaDatabase()->newSelectQueryBuilder()
105 ->select( [ 'cat_id', 'cat_title', 'cat_pages', 'cat_subcats', 'cat_files' ] )
106 ->from( 'category' )
107 ->where( $where )
108 ->caller( __METHOD__ )->fetchRow();
109
110 if ( !$row ) {
111 # Okay, there were no contents. Nothing to initialize.
112 if ( $this->mPage ) {
113 # If there is a page object but no record in the category table,
114 # treat this as an empty category.
115 $this->mID = false;
116 $this->mName = $this->mPage->getDBkey();
117 $this->mPages = 0;
118 $this->mSubcats = 0;
119 $this->mFiles = 0;
120
121 # If the page exists, call refreshCounts to add a row for it.
122 if ( $mode === self::LAZY_INIT_ROW && $this->mPage->exists() ) {
123 DeferredUpdates::addCallableUpdate( [ $this, 'refreshCounts' ] );
124 }
125
126 return true;
127 } else {
128 return false; # Fail
129 }
130 }
131
132 $this->mID = $row->cat_id;
133 $this->mName = $row->cat_title;
134 $this->mPages = (int)$row->cat_pages;
135 $this->mSubcats = (int)$row->cat_subcats;
136 $this->mFiles = (int)$row->cat_files;
137
138 # (T15683) If the count is negative, then 1) it's obviously wrong
139 # and should not be kept, and 2) we *probably* don't have to scan many
140 # rows to obtain the correct figure, so let's risk a one-time recount.
141 if ( $this->mPages < 0 || $this->mSubcats < 0 || $this->mFiles < 0 ) {
142 $this->mPages = max( $this->mPages, 0 );
143 $this->mSubcats = max( $this->mSubcats, 0 );
144 $this->mFiles = max( $this->mFiles, 0 );
145
146 if ( $mode === self::LAZY_INIT_ROW ) {
147 DeferredUpdates::addCallableUpdate( [ $this, 'refreshCounts' ] );
148 }
149 }
150
151 return true;
152 }
153
154 /**
155 * Factory function.
156 *
157 * @param string $name A category name (no "Category:" prefix). It need
158 * not be normalized, with spaces replaced by underscores.
159 * @return Category|bool Category, or false on a totally invalid name
160 */
161 public static function newFromName( $name ) {
162 $cat = new self();
163 $title = Title::makeTitleSafe( NS_CATEGORY, $name );
164
165 if ( !is_object( $title ) ) {
166 return false;
167 }
168
169 $cat->mPage = $title;
170 $cat->mName = $title->getDBkey();
171
172 return $cat;
173 }
174
175 /**
176 * Factory function.
177 *
178 * @param PageIdentity $page Category page. Warning, no validation is performed!
179 * @return Category
180 */
181 public static function newFromTitle( PageIdentity $page ): self {
182 $cat = new self();
183
184 $cat->mPage = $page;
185 $cat->mName = $page->getDBkey();
186
187 return $cat;
188 }
189
190 /**
191 * Factory function.
192 *
193 * @param int $id A category id. Warning, no validation is performed!
194 * @return Category
195 */
196 public static function newFromID( $id ) {
197 $cat = new self();
198 $cat->mID = intval( $id );
199 return $cat;
200 }
201
202 /**
203 * Factory function, for constructing a Category object from a result set
204 *
205 * @param stdClass $row Result set row, must contain the cat_xxx fields. If the fields are
206 * null, the resulting Category object will represent an empty category if a page object was
207 * given. If the fields are null and no PageIdentity was given, this method fails and returns
208 * false.
209 * @param PageIdentity|null $page This must be provided if there is no cat_title field in $row.
210 * @return Category|false
211 */
212 public static function newFromRow( stdClass $row, ?PageIdentity $page = null ) {
213 $cat = new self();
214 $cat->mPage = $page;
215
216 # NOTE: the row often results from a LEFT JOIN on categorylinks. This may result in
217 # all the cat_xxx fields being null, if the category page exists, but nothing
218 # was ever added to the category. This case should be treated link an empty
219 # category, if possible.
220
221 if ( $row->cat_title === null ) {
222 if ( $page === null ) {
223 # the name is probably somewhere in the row, for example as page_title,
224 # but we can't know that here...
225 return false;
226 } else {
227 # if we have a PageIdentity object, fetch the category name from there
228 $cat->mName = $page->getDBkey();
229 }
230
231 $cat->mID = false;
232 $cat->mSubcats = 0;
233 $cat->mPages = 0;
234 $cat->mFiles = 0;
235 } else {
236 $cat->mName = $row->cat_title;
237 $cat->mID = $row->cat_id;
238 $cat->mSubcats = (int)$row->cat_subcats;
239 $cat->mPages = (int)$row->cat_pages;
240 $cat->mFiles = (int)$row->cat_files;
241 }
242
243 return $cat;
244 }
245
246 /**
247 * @return string|false DB key name, or false on failure
248 */
249 public function getName() {
250 return $this->getX( 'mName' );
251 }
252
253 /**
254 * @return string|false Category ID, or false on failure
255 */
256 public function getID() {
257 return $this->getX( 'mID' );
258 }
259
260 /**
261 * @return int Total number of members count (sum of subcats, files and pages)
262 */
263 public function getMemberCount(): int {
264 $this->initialize( self::LAZY_INIT_ROW );
265
266 return $this->mPages;
267 }
268
269 /**
270 * @param int $type One of self::COUNT_ALL_MEMBERS and self::COUNT_CONTENT_PAGES
271 * @return int Total number of member count or content page count
272 */
273 public function getPageCount( $type = self::COUNT_ALL_MEMBERS ): int {
274 $allCount = $this->getMemberCount();
275
276 if ( $type === self::COUNT_CONTENT_PAGES ) {
277 return $allCount - ( $this->getSubcatCount() + $this->getFileCount() );
278 }
279
280 return $allCount;
281 }
282
283 /**
284 * @return int Number of subcategories
285 */
286 public function getSubcatCount(): int {
287 return $this->getX( 'mSubcats' );
288 }
289
290 /**
291 * @return int Number of member files
292 */
293 public function getFileCount(): int {
294 return $this->getX( 'mFiles' );
295 }
296
297 /**
298 * @since 1.37
299 * @return ?PageIdentity the page associated with this category, or null on failure. NOTE: This
300 * returns null on failure, unlike getTitle() which returns false.
301 */
302 public function getPage(): ?PageIdentity {
303 if ( $this->mPage ) {
304 return $this->mPage;
305 }
306
307 if ( !$this->initialize( self::LAZY_INIT_ROW ) ) {
308 return null;
309 }
310
311 $this->mPage = Title::makeTitleSafe( NS_CATEGORY, $this->mName );
312 return $this->mPage;
313 }
314
315 /**
316 * @deprecated since 1.37, use getPage() instead.
317 * @return Title|bool Title for this category, or false on failure.
318 */
319 public function getTitle() {
320 return Title::castFromPageIdentity( $this->getPage() ) ?? false;
321 }
322
323 /**
324 * Fetch a TitleArray of up to $limit category members, beginning after the
325 * category sort key $offset.
326 * @param int|false $limit
327 * @param string $offset
328 * @return TitleArrayFromResult Title objects for category members.
329 */
330 public function getMembers( $limit = false, $offset = '' ) {
331 $dbr = $this->dbProvider->getReplicaDatabase();
332 $queryBuilder = $dbr->newSelectQueryBuilder();
333 $queryBuilder->select( [ 'page_id', 'page_namespace', 'page_title', 'page_len',
334 'page_is_redirect', 'page_latest' ] )
335 ->from( 'categorylinks' )
336 ->join( 'page', null, [ 'cl_from = page_id' ] )
337 ->where( [ 'cl_to' => $this->getName() ] )
338 ->orderBy( 'cl_sortkey' );
339
340 if ( $limit ) {
341 $queryBuilder->limit( $limit );
342 }
343
344 if ( $offset !== '' ) {
345 $queryBuilder->andWhere( $dbr->expr( 'cl_sortkey', '>', $offset ) );
346 }
347
348 return $this->titleFactory->newTitleArrayFromResult(
349 $queryBuilder->caller( __METHOD__ )->fetchResultSet()
350 );
351 }
352
353 /**
354 * Generic accessor
355 * @param string $key
356 * @return mixed
357 */
358 private function getX( $key ) {
359 $this->initialize( self::LAZY_INIT_ROW );
360
361 return $this->{$key} ?? false;
362 }
363
364 /**
365 * Refresh the counts for this category.
366 *
367 * @return bool True on success, false on failure
368 */
369 public function refreshCounts() {
370 if ( $this->readOnlyMode->isReadOnly() ) {
371 return false;
372 }
373
374 # If we have just a category name, find out whether there is an
375 # existing row. Or if we have just an ID, get the name, because
376 # that's what categorylinks uses.
377 if ( !$this->initialize( self::LOAD_ONLY ) ) {
378 return false;
379 }
380
381 $dbw = $this->dbProvider->getPrimaryDatabase();
382 # Avoid excess contention on the same category (T162121)
383 $name = __METHOD__ . ':' . md5( $this->mName );
384 $scopedLock = $dbw->getScopedLockAndFlush( $name, __METHOD__, 0 );
385 if ( !$scopedLock ) {
386 return false;
387 }
388
389 $dbw->startAtomic( __METHOD__ );
390
391 // Lock the `category` row before potentially locking `categorylinks` rows to try
392 // to avoid deadlocks with LinksDeletionUpdate (T195397)
393 $dbw->newSelectQueryBuilder()
394 ->from( 'category' )
395 ->where( [ 'cat_title' => $this->mName ] )
396 ->caller( __METHOD__ )
397 ->forUpdate()
398 ->acquireRowLocks();
399
400 $rowCount = $dbw->newSelectQueryBuilder()
401 ->select( '*' )
402 ->from( 'categorylinks' )
403 ->join( 'page', null, 'page_id = cl_from' )
404 ->where( [ 'cl_to' => $this->mName ] )
405 ->limit( 110 )
406 ->caller( __METHOD__ )->fetchRowCount();
407 // Only lock if there are below 100 rows (T352628)
408 if ( $rowCount < 100 ) {
409 // Lock all the `categorylinks` records and gaps for this category;
410 // this is a separate query due to postgres limitations
411 $dbw->newSelectQueryBuilder()
412 ->select( '*' )
413 ->from( 'categorylinks' )
414 ->join( 'page', null, 'page_id = cl_from' )
415 ->where( [ 'cl_to' => $this->mName ] )
416 ->lockInShareMode()
417 ->caller( __METHOD__ )
418 ->acquireRowLocks();
419 }
420
421 // Get the aggregate `categorylinks` row counts for this category
422 $catCond = $dbw->conditional( [ 'page_namespace' => NS_CATEGORY ], '1', 'NULL' );
423 $fileCond = $dbw->conditional( [ 'page_namespace' => NS_FILE ], '1', 'NULL' );
424 $result = $dbw->newSelectQueryBuilder()
425 ->select( [
426 'pages' => 'COUNT(*)',
427 'subcats' => "COUNT($catCond)",
428 'files' => "COUNT($fileCond)"
429 ] )
430 ->from( 'categorylinks' )
431 ->join( 'page', null, 'page_id = cl_from' )
432 ->where( [ 'cl_to' => $this->mName ] )
433 ->caller( __METHOD__ )->fetchRow();
434
435 $shouldExist = $result->pages > 0 || $this->getPage()->exists();
436
437 if ( $this->mID ) {
438 if ( $shouldExist ) {
439 # The category row already exists, so do a plain UPDATE instead
440 # of INSERT...ON DUPLICATE KEY UPDATE to avoid creating a gap
441 # in the cat_id sequence. The row may or may not be "affected".
442 $dbw->newUpdateQueryBuilder()
443 ->update( 'category' )
444 ->set( [
445 'cat_pages' => $result->pages,
446 'cat_subcats' => $result->subcats,
447 'cat_files' => $result->files
448 ] )
449 ->where( [ 'cat_title' => $this->mName ] )
450 ->caller( __METHOD__ )->execute();
451 } else {
452 # The category is empty and has no description page, delete it
453 $dbw->newDeleteQueryBuilder()
454 ->deleteFrom( 'category' )
455 ->where( [ 'cat_title' => $this->mName ] )
456 ->caller( __METHOD__ )->execute();
457 $this->mID = false;
458 }
459 } elseif ( $shouldExist ) {
460 # The category row doesn't exist but should, so create it. Use
461 # upsert in case of races.
462 $dbw->newInsertQueryBuilder()
463 ->insertInto( 'category' )
464 ->row( [
465 'cat_title' => $this->mName,
466 'cat_pages' => $result->pages,
467 'cat_subcats' => $result->subcats,
468 'cat_files' => $result->files
469 ] )
470 ->onDuplicateKeyUpdate()
471 ->uniqueIndexFields( [ 'cat_title' ] )
472 ->set( [
473 'cat_pages' => $result->pages,
474 'cat_subcats' => $result->subcats,
475 'cat_files' => $result->files
476 ] )
477 ->caller( __METHOD__ )->execute();
478 // @todo: Should we update $this->mID here? Or not since Category
479 // objects tend to be short lived enough to not matter?
480 }
481
482 $dbw->endAtomic( __METHOD__ );
483
484 # Now we should update our local counts.
485 $this->mPages = (int)$result->pages;
486 $this->mSubcats = (int)$result->subcats;
487 $this->mFiles = (int)$result->files;
488
489 return true;
490 }
491
492 /**
493 * Call refreshCounts() if there are no entries in the categorylinks table
494 * or if the category table has a row that states that there are no entries
495 *
496 * Due to lock errors or other failures, the precomputed counts can get out of sync,
497 * making it hard to know when to delete the category row without checking the
498 * categorylinks table.
499 *
500 * @return bool Whether links were refreshed
501 * @since 1.32
502 */
503 public function refreshCountsIfEmpty() {
504 return $this->refreshCountsIfSmall( 0 );
505 }
506
507 /**
508 * Call refreshCounts() if there are few entries in the categorylinks table
509 *
510 * Due to lock errors or other failures, the precomputed counts can get out of sync,
511 * making it hard to know when to delete the category row without checking the
512 * categorylinks table.
513 *
514 * This method will do a non-locking select first to reduce contention.
515 *
516 * @param int $maxSize Only refresh if there are this or less many backlinks
517 * @return bool Whether links were refreshed
518 * @since 1.34
519 */
520 public function refreshCountsIfSmall( $maxSize = self::ROW_COUNT_SMALL ) {
521 $dbw = $this->dbProvider->getPrimaryDatabase();
522 $dbw->startAtomic( __METHOD__ );
523
524 $typeOccurances = $dbw->newSelectQueryBuilder()
525 ->select( 'cl_type' )
526 ->from( 'categorylinks' )
527 ->where( [ 'cl_to' => $this->getName() ] )
528 ->limit( $maxSize + 1 )
529 ->caller( __METHOD__ )->fetchFieldValues();
530
531 if ( !$typeOccurances ) {
532 $doRefresh = true; // delete any category table entry
533 } elseif ( count( $typeOccurances ) <= $maxSize ) {
534 $countByType = array_count_values( $typeOccurances );
535 $doRefresh = !$dbw->newSelectQueryBuilder()
536 ->select( '1' )
537 ->from( 'category' )
538 ->where( [
539 'cat_title' => $this->getName(),
540 'cat_pages' => $countByType['page'] ?? 0,
541 'cat_subcats' => $countByType['subcat'] ?? 0,
542 'cat_files' => $countByType['file'] ?? 0
543 ] )
544 ->caller( __METHOD__ )->fetchField();
545 } else {
546 $doRefresh = false; // category is too big
547 }
548
549 $dbw->endAtomic( __METHOD__ );
550
551 if ( $doRefresh ) {
552 $this->refreshCounts(); // update the row
553
554 return true;
555 }
556
557 return false;
558 }
559 }
560
561 /** @deprecated class alias since 1.40 */
562 class_alias( Category::class, 'Category' );