MediaWiki  1.29.1
Category.php
Go to the documentation of this file.
1 <?php
31 class Category {
33  private $mName = null;
34  private $mID = null;
39  private $mTitle = null;
41  private $mPages = null, $mSubcats = null, $mFiles = null;
42 
43  private function __construct() {
44  }
45 
51  protected function initialize() {
52  if ( $this->mName === null && $this->mID === null ) {
53  throw new MWException( __METHOD__ . ' has both names and IDs null' );
54  } elseif ( $this->mID === null ) {
55  $where = [ 'cat_title' => $this->mName ];
56  } elseif ( $this->mName === null ) {
57  $where = [ 'cat_id' => $this->mID ];
58  } else {
59  # Already initialized
60  return true;
61  }
62 
63  $dbr = wfGetDB( DB_REPLICA );
64  $row = $dbr->selectRow(
65  'category',
66  [ 'cat_id', 'cat_title', 'cat_pages', 'cat_subcats', 'cat_files' ],
67  $where,
68  __METHOD__
69  );
70 
71  if ( !$row ) {
72  # Okay, there were no contents. Nothing to initialize.
73  if ( $this->mTitle ) {
74  # If there is a title object but no record in the category table,
75  # treat this as an empty category.
76  $this->mID = false;
77  $this->mName = $this->mTitle->getDBkey();
78  $this->mPages = 0;
79  $this->mSubcats = 0;
80  $this->mFiles = 0;
81 
82  # If the title exists, call refreshCounts to add a row for it.
83  if ( $this->mTitle->exists() ) {
84  DeferredUpdates::addCallableUpdate( [ $this, 'refreshCounts' ] );
85  }
86 
87  return true;
88  } else {
89  return false; # Fail
90  }
91  }
92 
93  $this->mID = $row->cat_id;
94  $this->mName = $row->cat_title;
95  $this->mPages = $row->cat_pages;
96  $this->mSubcats = $row->cat_subcats;
97  $this->mFiles = $row->cat_files;
98 
99  # (T15683) If the count is negative, then 1) it's obviously wrong
100  # and should not be kept, and 2) we *probably* don't have to scan many
101  # rows to obtain the correct figure, so let's risk a one-time recount.
102  if ( $this->mPages < 0 || $this->mSubcats < 0 || $this->mFiles < 0 ) {
103  $this->mPages = max( $this->mPages, 0 );
104  $this->mSubcats = max( $this->mSubcats, 0 );
105  $this->mFiles = max( $this->mFiles, 0 );
106 
107  DeferredUpdates::addCallableUpdate( [ $this, 'refreshCounts' ] );
108  }
109 
110  return true;
111  }
112 
120  public static function newFromName( $name ) {
121  $cat = new self();
123 
124  if ( !is_object( $title ) ) {
125  return false;
126  }
127 
128  $cat->mTitle = $title;
129  $cat->mName = $title->getDBkey();
130 
131  return $cat;
132  }
133 
140  public static function newFromTitle( $title ) {
141  $cat = new self();
142 
143  $cat->mTitle = $title;
144  $cat->mName = $title->getDBkey();
145 
146  return $cat;
147  }
148 
155  public static function newFromID( $id ) {
156  $cat = new self();
157  $cat->mID = intval( $id );
158  return $cat;
159  }
160 
173  public static function newFromRow( $row, $title = null ) {
174  $cat = new self();
175  $cat->mTitle = $title;
176 
177  # NOTE: the row often results from a LEFT JOIN on categorylinks. This may result in
178  # all the cat_xxx fields being null, if the category page exists, but nothing
179  # was ever added to the category. This case should be treated link an empty
180  # category, if possible.
181 
182  if ( $row->cat_title === null ) {
183  if ( $title === null ) {
184  # the name is probably somewhere in the row, for example as page_title,
185  # but we can't know that here...
186  return false;
187  } else {
188  # if we have a title object, fetch the category name from there
189  $cat->mName = $title->getDBkey();
190  }
191 
192  $cat->mID = false;
193  $cat->mSubcats = 0;
194  $cat->mPages = 0;
195  $cat->mFiles = 0;
196  } else {
197  $cat->mName = $row->cat_title;
198  $cat->mID = $row->cat_id;
199  $cat->mSubcats = $row->cat_subcats;
200  $cat->mPages = $row->cat_pages;
201  $cat->mFiles = $row->cat_files;
202  }
203 
204  return $cat;
205  }
206 
210  public function getName() {
211  return $this->getX( 'mName' );
212  }
213 
217  public function getID() {
218  return $this->getX( 'mID' );
219  }
220 
224  public function getPageCount() {
225  return $this->getX( 'mPages' );
226  }
227 
231  public function getSubcatCount() {
232  return $this->getX( 'mSubcats' );
233  }
234 
238  public function getFileCount() {
239  return $this->getX( 'mFiles' );
240  }
241 
245  public function getTitle() {
246  if ( $this->mTitle ) {
247  return $this->mTitle;
248  }
249 
250  if ( !$this->initialize() ) {
251  return false;
252  }
253 
254  $this->mTitle = Title::makeTitleSafe( NS_CATEGORY, $this->mName );
255  return $this->mTitle;
256  }
257 
265  public function getMembers( $limit = false, $offset = '' ) {
266 
267  $dbr = wfGetDB( DB_REPLICA );
268 
269  $conds = [ 'cl_to' => $this->getName(), 'cl_from = page_id' ];
270  $options = [ 'ORDER BY' => 'cl_sortkey' ];
271 
272  if ( $limit ) {
273  $options['LIMIT'] = $limit;
274  }
275 
276  if ( $offset !== '' ) {
277  $conds[] = 'cl_sortkey > ' . $dbr->addQuotes( $offset );
278  }
279 
281  $dbr->select(
282  [ 'page', 'categorylinks' ],
283  [ 'page_id', 'page_namespace', 'page_title', 'page_len',
284  'page_is_redirect', 'page_latest' ],
285  $conds,
286  __METHOD__,
287  $options
288  )
289  );
290 
291  return $result;
292  }
293 
299  private function getX( $key ) {
300  if ( !$this->initialize() ) {
301  return false;
302  }
303  return $this->{$key};
304  }
305 
311  public function refreshCounts() {
312  if ( wfReadOnly() ) {
313  return false;
314  }
315 
316  # If we have just a category name, find out whether there is an
317  # existing row. Or if we have just an ID, get the name, because
318  # that's what categorylinks uses.
319  if ( !$this->initialize() ) {
320  return false;
321  }
322 
323  $dbw = wfGetDB( DB_MASTER );
324  # Avoid excess contention on the same category (T162121)
325  $name = __METHOD__ . ':' . md5( $this->mName );
326  $scopedLock = $dbw->getScopedLockAndFlush( $name, __METHOD__, 1 );
327  if ( !$scopedLock ) {
328  return;
329  }
330 
331  $dbw->startAtomic( __METHOD__ );
332 
333  $cond1 = $dbw->conditional( [ 'page_namespace' => NS_CATEGORY ], 1, 'NULL' );
334  $cond2 = $dbw->conditional( [ 'page_namespace' => NS_FILE ], 1, 'NULL' );
335  $result = $dbw->selectRow(
336  [ 'categorylinks', 'page' ],
337  [ 'pages' => 'COUNT(*)',
338  'subcats' => "COUNT($cond1)",
339  'files' => "COUNT($cond2)"
340  ],
341  [ 'cl_to' => $this->mName, 'page_id = cl_from' ],
342  __METHOD__,
343  [ 'LOCK IN SHARE MODE' ]
344  );
345 
346  $shouldExist = $result->pages > 0 || $this->getTitle()->exists();
347 
348  if ( $this->mID ) {
349  if ( $shouldExist ) {
350  # The category row already exists, so do a plain UPDATE instead
351  # of INSERT...ON DUPLICATE KEY UPDATE to avoid creating a gap
352  # in the cat_id sequence. The row may or may not be "affected".
353  $dbw->update(
354  'category',
355  [
356  'cat_pages' => $result->pages,
357  'cat_subcats' => $result->subcats,
358  'cat_files' => $result->files
359  ],
360  [ 'cat_title' => $this->mName ],
361  __METHOD__
362  );
363  } else {
364  # The category is empty and has no description page, delete it
365  $dbw->delete(
366  'category',
367  [ 'cat_title' => $this->mName ],
368  __METHOD__
369  );
370  $this->mID = false;
371  }
372  } elseif ( $shouldExist ) {
373  # The category row doesn't exist but should, so create it. Use
374  # upsert in case of races.
375  $dbw->upsert(
376  'category',
377  [
378  'cat_title' => $this->mName,
379  'cat_pages' => $result->pages,
380  'cat_subcats' => $result->subcats,
381  'cat_files' => $result->files
382  ],
383  [ 'cat_title' ],
384  [
385  'cat_pages' => $result->pages,
386  'cat_subcats' => $result->subcats,
387  'cat_files' => $result->files
388  ],
389  __METHOD__
390  );
391  // @todo: Should we update $this->mID here? Or not since Category
392  // objects tend to be short lived enough to not matter?
393  }
394 
395  $dbw->endAtomic( __METHOD__ );
396 
397  # Now we should update our local counts.
398  $this->mPages = $result->pages;
399  $this->mSubcats = $result->subcats;
400  $this->mFiles = $result->files;
401 
402  return true;
403  }
404 }
Category\getTitle
getTitle()
Definition: Category.php:245
Category\getID
getID()
Definition: Category.php:217
TitleArray\newFromResult
static newFromResult( $res)
Definition: TitleArray.php:40
Category\$mName
$mName
Name of the category, normalized to DB-key form.
Definition: Category.php:33
$result
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 '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. 'LanguageGetMagic':DEPRECATED! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) '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 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) '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! 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:1954
Category
Category objects are immutable, strictly speaking.
Definition: Category.php:31
NS_FILE
const NS_FILE
Definition: Defines.php:68
wfReadOnly
wfReadOnly()
Check whether the wiki is in read-only mode.
Definition: GlobalFunctions.php:1277
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:304
php
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
DeferredUpdates\addCallableUpdate
static addCallableUpdate( $callable, $stage=self::POSTSEND, IDatabase $dbw=null)
Add a callable update.
Definition: DeferredUpdates.php:111
Category\initialize
initialize()
Set up all member variables using a database query.
Definition: Category.php:51
MWException
MediaWiki exception.
Definition: MWException.php:26
Category\getX
getX( $key)
Generic accessor.
Definition: Category.php:299
$title
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:934
Category\$mFiles
$mFiles
Definition: Category.php:41
Category\$mID
$mID
Definition: Category.php:34
wfGetDB
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:3060
Category\refreshCounts
refreshCounts()
Refresh the counts for this category.
Definition: Category.php:311
Category\getName
getName()
Definition: Category.php:210
$limit
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context the output can only depend on parameters provided to this hook not on global state indicating whether full HTML should be generated If generation of HTML may be but other information should still be present in the ParserOutput object to manipulate or replace but no entry for that model exists in $wgContentHandlers please use GetContentModels hook to make them known to core if desired whether it is OK to use $contentModel on $title Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok inclusive $limit
Definition: hooks.txt:1049
Category\getSubcatCount
getSubcatCount()
Definition: Category.php:231
Category\getMembers
getMembers( $limit=false, $offset='')
Fetch a TitleArray of up to $limit category members, beginning after the category sort key $offset.
Definition: Category.php:265
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
NS_CATEGORY
const NS_CATEGORY
Definition: Defines.php:76
DB_MASTER
const DB_MASTER
Definition: defines.php:26
Category\$mSubcats
$mSubcats
Definition: Category.php:41
Category\newFromRow
static newFromRow( $row, $title=null)
Factory function, for constructing a Category object from a result set.
Definition: Category.php:173
Category\newFromTitle
static newFromTitle( $title)
Factory function.
Definition: Category.php:140
Title\makeTitleSafe
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:538
Category\getPageCount
getPageCount()
Definition: Category.php:224
Category\newFromID
static newFromID( $id)
Factory function.
Definition: Category.php:155
Title
Represents a title within MediaWiki.
Definition: Title.php:39
Category\getFileCount
getFileCount()
Definition: Category.php:238
$dbr
if(! $regexes) $dbr
Definition: cleanup.php:94
Category\$mTitle
Title $mTitle
Category page title.
Definition: Category.php:39
Category\__construct
__construct()
Definition: Category.php:43
Category\newFromName
static newFromName( $name)
Factory function.
Definition: Category.php:120
$options
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context $options
Definition: hooks.txt:1049
Category\$mPages
$mPages
Counts of membership (cat_pages, cat_subcats, cat_files)
Definition: Category.php:41