MediaWiki  master
Category.php
Go to the documentation of this file.
1 <?php
29 class Category {
31  private $mName = null;
32  private $mID = null;
37  private $mTitle = null;
40 
41  const LOAD_ONLY = 0;
42  const LAZY_INIT_ROW = 1;
43 
44  private function __construct() {
45  }
46 
53  protected function initialize( $mode = self::LOAD_ONLY ) {
54  if ( $this->mName === null && $this->mID === null ) {
55  throw new MWException( __METHOD__ . ' has both names and IDs null' );
56  } elseif ( $this->mID === null ) {
57  $where = [ 'cat_title' => $this->mName ];
58  } elseif ( $this->mName === null ) {
59  $where = [ 'cat_id' => $this->mID ];
60  } else {
61  # Already initialized
62  return true;
63  }
64 
65  $dbr = wfGetDB( DB_REPLICA );
66  $row = $dbr->selectRow(
67  'category',
68  [ 'cat_id', 'cat_title', 'cat_pages', 'cat_subcats', 'cat_files' ],
69  $where,
70  __METHOD__
71  );
72 
73  if ( !$row ) {
74  # Okay, there were no contents. Nothing to initialize.
75  if ( $this->mTitle ) {
76  # If there is a title object but no record in the category table,
77  # treat this as an empty category.
78  $this->mID = false;
79  $this->mName = $this->mTitle->getDBkey();
80  $this->mPages = 0;
81  $this->mSubcats = 0;
82  $this->mFiles = 0;
83 
84  # If the title exists, call refreshCounts to add a row for it.
85  if ( $mode === self::LAZY_INIT_ROW && $this->mTitle->exists() ) {
86  DeferredUpdates::addCallableUpdate( [ $this, 'refreshCounts' ] );
87  }
88 
89  return true;
90  } else {
91  return false; # Fail
92  }
93  }
94 
95  $this->mID = $row->cat_id;
96  $this->mName = $row->cat_title;
97  $this->mPages = $row->cat_pages;
98  $this->mSubcats = $row->cat_subcats;
99  $this->mFiles = $row->cat_files;
100 
101  # (T15683) If the count is negative, then 1) it's obviously wrong
102  # and should not be kept, and 2) we *probably* don't have to scan many
103  # rows to obtain the correct figure, so let's risk a one-time recount.
104  if ( $this->mPages < 0 || $this->mSubcats < 0 || $this->mFiles < 0 ) {
105  $this->mPages = max( $this->mPages, 0 );
106  $this->mSubcats = max( $this->mSubcats, 0 );
107  $this->mFiles = max( $this->mFiles, 0 );
108 
109  if ( $mode === self::LAZY_INIT_ROW ) {
110  DeferredUpdates::addCallableUpdate( [ $this, 'refreshCounts' ] );
111  }
112  }
113 
114  return true;
115  }
116 
124  public static function newFromName( $name ) {
125  $cat = new self();
127 
128  if ( !is_object( $title ) ) {
129  return false;
130  }
131 
132  $cat->mTitle = $title;
133  $cat->mName = $title->getDBkey();
134 
135  return $cat;
136  }
137 
144  public static function newFromTitle( $title ) {
145  $cat = new self();
146 
147  $cat->mTitle = $title;
148  $cat->mName = $title->getDBkey();
149 
150  return $cat;
151  }
152 
159  public static function newFromID( $id ) {
160  $cat = new self();
161  $cat->mID = intval( $id );
162  return $cat;
163  }
164 
177  public static function newFromRow( $row, $title = null ) {
178  $cat = new self();
179  $cat->mTitle = $title;
180 
181  # NOTE: the row often results from a LEFT JOIN on categorylinks. This may result in
182  # all the cat_xxx fields being null, if the category page exists, but nothing
183  # was ever added to the category. This case should be treated link an empty
184  # category, if possible.
185 
186  if ( $row->cat_title === null ) {
187  if ( $title === null ) {
188  # the name is probably somewhere in the row, for example as page_title,
189  # but we can't know that here...
190  return false;
191  } else {
192  # if we have a title object, fetch the category name from there
193  $cat->mName = $title->getDBkey();
194  }
195 
196  $cat->mID = false;
197  $cat->mSubcats = 0;
198  $cat->mPages = 0;
199  $cat->mFiles = 0;
200  } else {
201  $cat->mName = $row->cat_title;
202  $cat->mID = $row->cat_id;
203  $cat->mSubcats = $row->cat_subcats;
204  $cat->mPages = $row->cat_pages;
205  $cat->mFiles = $row->cat_files;
206  }
207 
208  return $cat;
209  }
210 
214  public function getName() {
215  return $this->getX( 'mName' );
216  }
217 
221  public function getID() {
222  return $this->getX( 'mID' );
223  }
224 
228  public function getPageCount() {
229  return $this->getX( 'mPages' );
230  }
231 
235  public function getSubcatCount() {
236  return $this->getX( 'mSubcats' );
237  }
238 
242  public function getFileCount() {
243  return $this->getX( 'mFiles' );
244  }
245 
249  public function getTitle() {
250  if ( $this->mTitle ) {
251  return $this->mTitle;
252  }
253 
254  if ( !$this->initialize( self::LAZY_INIT_ROW ) ) {
255  return false;
256  }
257 
258  $this->mTitle = Title::makeTitleSafe( NS_CATEGORY, $this->mName );
259  return $this->mTitle;
260  }
261 
269  public function getMembers( $limit = false, $offset = '' ) {
270  $dbr = wfGetDB( DB_REPLICA );
271 
272  $conds = [ 'cl_to' => $this->getName(), 'cl_from = page_id' ];
273  $options = [ 'ORDER BY' => 'cl_sortkey' ];
274 
275  if ( $limit ) {
276  $options['LIMIT'] = $limit;
277  }
278 
279  if ( $offset !== '' ) {
280  $conds[] = 'cl_sortkey > ' . $dbr->addQuotes( $offset );
281  }
282 
284  $dbr->select(
285  [ 'page', 'categorylinks' ],
286  [ 'page_id', 'page_namespace', 'page_title', 'page_len',
287  'page_is_redirect', 'page_latest' ],
288  $conds,
289  __METHOD__,
290  $options
291  )
292  );
293 
294  return $result;
295  }
296 
302  private function getX( $key ) {
303  if ( $this->{$key} === null && !$this->initialize( self::LAZY_INIT_ROW ) ) {
304  return false;
305  }
306  return $this->{$key};
307  }
308 
314  public function refreshCounts() {
315  if ( wfReadOnly() ) {
316  return false;
317  }
318 
319  # If we have just a category name, find out whether there is an
320  # existing row. Or if we have just an ID, get the name, because
321  # that's what categorylinks uses.
322  if ( !$this->initialize( self::LOAD_ONLY ) ) {
323  return false;
324  }
325 
326  $dbw = wfGetDB( DB_MASTER );
327  # Avoid excess contention on the same category (T162121)
328  $name = __METHOD__ . ':' . md5( $this->mName );
329  $scopedLock = $dbw->getScopedLockAndFlush( $name, __METHOD__, 0 );
330  if ( !$scopedLock ) {
331  return false;
332  }
333 
334  $dbw->startAtomic( __METHOD__ );
335 
336  // Lock the `category` row before locking `categorylinks` rows to try
337  // to avoid deadlocks with LinksDeletionUpdate (T195397)
338  $dbw->lockForUpdate( 'category', [ 'cat_title' => $this->mName ], __METHOD__ );
339 
340  // Lock all the `categorylinks` records and gaps for this category;
341  // this is a separate query due to postgres/oracle limitations
342  $dbw->selectRowCount(
343  [ 'categorylinks', 'page' ],
344  '*',
345  [ 'cl_to' => $this->mName, 'page_id = cl_from' ],
346  __METHOD__,
347  [ 'LOCK IN SHARE MODE' ]
348  );
349  // Get the aggregate `categorylinks` row counts for this category
350  $catCond = $dbw->conditional( [ 'page_namespace' => NS_CATEGORY ], 1, 'NULL' );
351  $fileCond = $dbw->conditional( [ 'page_namespace' => NS_FILE ], 1, 'NULL' );
352  $result = $dbw->selectRow(
353  [ 'categorylinks', 'page' ],
354  [
355  'pages' => 'COUNT(*)',
356  'subcats' => "COUNT($catCond)",
357  'files' => "COUNT($fileCond)"
358  ],
359  [ 'cl_to' => $this->mName, 'page_id = cl_from' ],
360  __METHOD__
361  );
362 
363  $shouldExist = $result->pages > 0 || $this->getTitle()->exists();
364 
365  if ( $this->mID ) {
366  if ( $shouldExist ) {
367  # The category row already exists, so do a plain UPDATE instead
368  # of INSERT...ON DUPLICATE KEY UPDATE to avoid creating a gap
369  # in the cat_id sequence. The row may or may not be "affected".
370  $dbw->update(
371  'category',
372  [
373  'cat_pages' => $result->pages,
374  'cat_subcats' => $result->subcats,
375  'cat_files' => $result->files
376  ],
377  [ 'cat_title' => $this->mName ],
378  __METHOD__
379  );
380  } else {
381  # The category is empty and has no description page, delete it
382  $dbw->delete(
383  'category',
384  [ 'cat_title' => $this->mName ],
385  __METHOD__
386  );
387  $this->mID = false;
388  }
389  } elseif ( $shouldExist ) {
390  # The category row doesn't exist but should, so create it. Use
391  # upsert in case of races.
392  $dbw->upsert(
393  'category',
394  [
395  'cat_title' => $this->mName,
396  'cat_pages' => $result->pages,
397  'cat_subcats' => $result->subcats,
398  'cat_files' => $result->files
399  ],
400  [ 'cat_title' ],
401  [
402  'cat_pages' => $result->pages,
403  'cat_subcats' => $result->subcats,
404  'cat_files' => $result->files
405  ],
406  __METHOD__
407  );
408  // @todo: Should we update $this->mID here? Or not since Category
409  // objects tend to be short lived enough to not matter?
410  }
411 
412  $dbw->endAtomic( __METHOD__ );
413 
414  # Now we should update our local counts.
415  $this->mPages = $result->pages;
416  $this->mSubcats = $result->subcats;
417  $this->mFiles = $result->files;
418 
419  return true;
420  }
421 
433  public function refreshCountsIfEmpty() {
434  $dbw = wfGetDB( DB_MASTER );
435 
436  $hasLink = $dbw->selectField(
437  'categorylinks',
438  '1',
439  [ 'cl_to' => $this->getName() ],
440  __METHOD__
441  );
442  if ( !$hasLink ) {
443  $this->refreshCounts(); // delete any category table entry
444 
445  return true;
446  }
447 
448  $hasBadRow = $dbw->selectField(
449  'category',
450  '1',
451  [ 'cat_title' => $this->getName(), 'cat_pages <= 0' ],
452  __METHOD__
453  );
454  if ( $hasBadRow ) {
455  $this->refreshCounts(); // clean up this row
456 
457  return true;
458  }
459 
460  return false;
461  }
462 }
$mName
Name of the category, normalized to DB-key form.
Definition: Category.php:31
static newFromRow( $row, $title=null)
Factory function, for constructing a Category object from a result set.
Definition: Category.php:177
static newFromName( $name)
Factory function.
Definition: Category.php:124
const LOAD_ONLY
Definition: Category.php:41
static newFromTitle( $title)
Factory function.
Definition: Category.php:144
Title $mTitle
Category page title.
Definition: Category.php:37
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
getSubcatCount()
Definition: Category.php:235
refreshCountsIfEmpty()
Call refreshCounts() if there are no entries in the categorylinks table or if the category table has ...
Definition: Category.php:433
static newFromID( $id)
Factory function.
Definition: Category.php:159
const DB_MASTER
Definition: defines.php:26
getMembers( $limit=false, $offset='')
Fetch a TitleArray of up to $limit category members, beginning after the category sort key $offset...
Definition: Category.php:269
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1980
static addCallableUpdate( $callable, $stage=self::POSTSEND, $dbw=null)
Add a callable update.
getTitle()
Definition: Category.php:249
wfReadOnly()
Check whether the wiki is in read-only mode.
refreshCounts()
Refresh the counts for this category.
Definition: Category.php:314
getFileCount()
Definition: Category.php:242
const NS_CATEGORY
Definition: Defines.php:78
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition: hooks.txt:1982
$mPages
Counts of membership (cat_pages, cat_subcats, cat_files)
Definition: Category.php:39
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:780
static newFromResult( $res)
Definition: TitleArray.php:40
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:925
getPageCount()
Definition: Category.php:228
const NS_FILE
Definition: Defines.php:70
getX( $key)
Generic accessor.
Definition: Category.php:302
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:617
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
const LAZY_INIT_ROW
Definition: Category.php:42
__construct()
Definition: Category.php:44
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:271
const DB_REPLICA
Definition: defines.php:25
initialize( $mode=self::LOAD_ONLY)
Set up all member variables using a database query.
Definition: Category.php:53