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