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