MediaWiki  1.28.0
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  # (bug 13683) 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  $dbw->startAtomic( __METHOD__ );
325 
326  $cond1 = $dbw->conditional( [ 'page_namespace' => NS_CATEGORY ], 1, 'NULL' );
327  $cond2 = $dbw->conditional( [ 'page_namespace' => NS_FILE ], 1, 'NULL' );
328  $result = $dbw->selectRow(
329  [ 'categorylinks', 'page' ],
330  [ 'pages' => 'COUNT(*)',
331  'subcats' => "COUNT($cond1)",
332  'files' => "COUNT($cond2)"
333  ],
334  [ 'cl_to' => $this->mName, 'page_id = cl_from' ],
335  __METHOD__,
336  [ 'LOCK IN SHARE MODE' ]
337  );
338 
339  $shouldExist = $result->pages > 0 || $this->getTitle()->exists();
340 
341  if ( $this->mID ) {
342  if ( $shouldExist ) {
343  # The category row already exists, so do a plain UPDATE instead
344  # of INSERT...ON DUPLICATE KEY UPDATE to avoid creating a gap
345  # in the cat_id sequence. The row may or may not be "affected".
346  $dbw->update(
347  'category',
348  [
349  'cat_pages' => $result->pages,
350  'cat_subcats' => $result->subcats,
351  'cat_files' => $result->files
352  ],
353  [ 'cat_title' => $this->mName ],
354  __METHOD__
355  );
356  } else {
357  # The category is empty and has no description page, delete it
358  $dbw->delete(
359  'category',
360  [ 'cat_title' => $this->mName ],
361  __METHOD__
362  );
363  $this->mID = false;
364  }
365  } elseif ( $shouldExist ) {
366  # The category row doesn't exist but should, so create it. Use
367  # upsert in case of races.
368  $dbw->upsert(
369  'category',
370  [
371  'cat_title' => $this->mName,
372  'cat_pages' => $result->pages,
373  'cat_subcats' => $result->subcats,
374  'cat_files' => $result->files
375  ],
376  [ 'cat_title' ],
377  [
378  'cat_pages' => $result->pages,
379  'cat_subcats' => $result->subcats,
380  'cat_files' => $result->files
381  ],
382  __METHOD__
383  );
384  // @todo: Should we update $this->mID here? Or not since Category
385  // objects tend to be short lived enough to not matter?
386  }
387 
388  $dbw->endAtomic( __METHOD__ );
389 
390  # Now we should update our local counts.
391  $this->mPages = $result->pages;
392  $this->mSubcats = $result->subcats;
393  $this->mFiles = $result->files;
394 
395  return true;
396  }
397 }
$mName
Name of the category, normalized to DB-key form.
Definition: Category.php:33
wfGetDB($db, $groups=[], $wiki=false)
Get a Database object.
static newFromName($name)
Factory function.
Definition: Category.php:120
initialize()
Set up all member variables using a database query.
Definition: Category.php:51
getX($key)
Generic accessor.
Definition: Category.php:299
Title $mTitle
Category page title.
Definition: Category.php:39
getSubcatCount()
Definition: Category.php:231
getMembers($limit=false, $offset= '')
Fetch a TitleArray of up to $limit category members, beginning after the category sort key $offset...
Definition: Category.php:265
const DB_MASTER
Definition: defines.php:23
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:Associative array mapping language codes to prefixed links of the form"language:title".&$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:1934
getTitle()
Definition: Category.php:245
wfReadOnly()
Check whether the wiki is in read-only mode.
refreshCounts()
Refresh the counts for this category.
Definition: Category.php:311
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist 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:1046
getFileCount()
Definition: Category.php:238
static newFromTitle($title)
Factory function.
Definition: Category.php:140
const NS_CATEGORY
Definition: Defines.php:70
static makeTitleSafe($ns, $title, $fragment= '', $interwiki= '')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:535
$mPages
Counts of membership (cat_pages, cat_subcats, cat_files)
Definition: Category.php:41
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:953
getPageCount()
Definition: Category.php:224
const NS_FILE
Definition: Defines.php:62
static newFromResult($res)
Definition: TitleArray.php:38
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
__construct()
Definition: Category.php:43
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist 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 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:1046
static addCallableUpdate($callable, $stage=self::POSTSEND, IDatabase $dbw=null)
Add a callable update.
const DB_REPLICA
Definition: defines.php:22
static newFromID($id)
Factory function.
Definition: Category.php:155
static newFromRow($row, $title=null)
Factory function, for constructing a Category object from a result set.
Definition: Category.php:173
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:300