Category.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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. /**
  24. * Category objects are immutable, strictly speaking. If you call methods that change the database,
  25. * like to refresh link counts, the objects will be appropriately reinitialized.
  26. * Member variables are lazy-initialized.
  27. *
  28. * @todo Move some stuff from CategoryPage.php to here, and use that.
  29. */
  30. class Category {
  31. /** Name of the category, normalized to DB-key form */
  32. private $mName = null;
  33. private $mID = null;
  34. /**
  35. * Category page title
  36. * @var Title
  37. */
  38. private $mTitle = null;
  39. /** Counts of membership (cat_pages, cat_subcats, cat_files) */
  40. private $mPages = null, $mSubcats = null, $mFiles = null;
  41. const LOAD_ONLY = 0;
  42. const LAZY_INIT_ROW = 1;
  43. private function __construct() {
  44. }
  45. /**
  46. * Set up all member variables using a database query.
  47. * @param int $mode
  48. * @throws MWException
  49. * @return bool True on success, false on failure.
  50. */
  51. protected function initialize( $mode = self::LOAD_ONLY ) {
  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. $dbr = wfGetDB( DB_REPLICA );
  63. $row = $dbr->selectRow(
  64. 'category',
  65. [ 'cat_id', 'cat_title', 'cat_pages', 'cat_subcats', 'cat_files' ],
  66. $where,
  67. __METHOD__
  68. );
  69. if ( !$row ) {
  70. # Okay, there were no contents. Nothing to initialize.
  71. if ( $this->mTitle ) {
  72. # If there is a title object but no record in the category table,
  73. # treat this as an empty category.
  74. $this->mID = false;
  75. $this->mName = $this->mTitle->getDBkey();
  76. $this->mPages = 0;
  77. $this->mSubcats = 0;
  78. $this->mFiles = 0;
  79. # If the title exists, call refreshCounts to add a row for it.
  80. if ( $mode === self::LAZY_INIT_ROW && $this->mTitle->exists() ) {
  81. DeferredUpdates::addCallableUpdate( [ $this, 'refreshCounts' ] );
  82. }
  83. return true;
  84. } else {
  85. return false; # Fail
  86. }
  87. }
  88. $this->mID = $row->cat_id;
  89. $this->mName = $row->cat_title;
  90. $this->mPages = $row->cat_pages;
  91. $this->mSubcats = $row->cat_subcats;
  92. $this->mFiles = $row->cat_files;
  93. # (T15683) If the count is negative, then 1) it's obviously wrong
  94. # and should not be kept, and 2) we *probably* don't have to scan many
  95. # rows to obtain the correct figure, so let's risk a one-time recount.
  96. if ( $this->mPages < 0 || $this->mSubcats < 0 || $this->mFiles < 0 ) {
  97. $this->mPages = max( $this->mPages, 0 );
  98. $this->mSubcats = max( $this->mSubcats, 0 );
  99. $this->mFiles = max( $this->mFiles, 0 );
  100. if ( $mode === self::LAZY_INIT_ROW ) {
  101. DeferredUpdates::addCallableUpdate( [ $this, 'refreshCounts' ] );
  102. }
  103. }
  104. return true;
  105. }
  106. /**
  107. * Factory function.
  108. *
  109. * @param string $name A category name (no "Category:" prefix). It need
  110. * not be normalized, with spaces replaced by underscores.
  111. * @return Category|bool Category, or false on a totally invalid name
  112. */
  113. public static function newFromName( $name ) {
  114. $cat = new self();
  115. $title = Title::makeTitleSafe( NS_CATEGORY, $name );
  116. if ( !is_object( $title ) ) {
  117. return false;
  118. }
  119. $cat->mTitle = $title;
  120. $cat->mName = $title->getDBkey();
  121. return $cat;
  122. }
  123. /**
  124. * Factory function.
  125. *
  126. * @param Title $title Title for the category page
  127. * @return Category|bool On a totally invalid name
  128. */
  129. public static function newFromTitle( $title ) {
  130. $cat = new self();
  131. $cat->mTitle = $title;
  132. $cat->mName = $title->getDBkey();
  133. return $cat;
  134. }
  135. /**
  136. * Factory function.
  137. *
  138. * @param int $id A category id
  139. * @return Category
  140. */
  141. public static function newFromID( $id ) {
  142. $cat = new self();
  143. $cat->mID = intval( $id );
  144. return $cat;
  145. }
  146. /**
  147. * Factory function, for constructing a Category object from a result set
  148. *
  149. * @param object $row Result set row, must contain the cat_xxx fields. If the
  150. * fields are null, the resulting Category object will represent an empty
  151. * category if a title object was given. If the fields are null and no
  152. * title was given, this method fails and returns false.
  153. * @param Title $title Optional title object for the category represented by
  154. * the given row. May be provided if it is already known, to avoid having
  155. * to re-create a title object later.
  156. * @return Category|false
  157. */
  158. public static function newFromRow( $row, $title = null ) {
  159. $cat = new self();
  160. $cat->mTitle = $title;
  161. # NOTE: the row often results from a LEFT JOIN on categorylinks. This may result in
  162. # all the cat_xxx fields being null, if the category page exists, but nothing
  163. # was ever added to the category. This case should be treated link an empty
  164. # category, if possible.
  165. if ( $row->cat_title === null ) {
  166. if ( $title === null ) {
  167. # the name is probably somewhere in the row, for example as page_title,
  168. # but we can't know that here...
  169. return false;
  170. } else {
  171. # if we have a title object, fetch the category name from there
  172. $cat->mName = $title->getDBkey();
  173. }
  174. $cat->mID = false;
  175. $cat->mSubcats = 0;
  176. $cat->mPages = 0;
  177. $cat->mFiles = 0;
  178. } else {
  179. $cat->mName = $row->cat_title;
  180. $cat->mID = $row->cat_id;
  181. $cat->mSubcats = $row->cat_subcats;
  182. $cat->mPages = $row->cat_pages;
  183. $cat->mFiles = $row->cat_files;
  184. }
  185. return $cat;
  186. }
  187. /**
  188. * @return mixed DB key name, or false on failure
  189. */
  190. public function getName() {
  191. return $this->getX( 'mName' );
  192. }
  193. /**
  194. * @return mixed Category ID, or false on failure
  195. */
  196. public function getID() {
  197. return $this->getX( 'mID' );
  198. }
  199. /**
  200. * @return mixed Total number of member pages, or false on failure
  201. */
  202. public function getPageCount() {
  203. return $this->getX( 'mPages' );
  204. }
  205. /**
  206. * @return mixed Number of subcategories, or false on failure
  207. */
  208. public function getSubcatCount() {
  209. return $this->getX( 'mSubcats' );
  210. }
  211. /**
  212. * @return mixed Number of member files, or false on failure
  213. */
  214. public function getFileCount() {
  215. return $this->getX( 'mFiles' );
  216. }
  217. /**
  218. * @return Title|bool Title for this category, or false on failure.
  219. */
  220. public function getTitle() {
  221. if ( $this->mTitle ) {
  222. return $this->mTitle;
  223. }
  224. if ( !$this->initialize( self::LAZY_INIT_ROW ) ) {
  225. return false;
  226. }
  227. $this->mTitle = Title::makeTitleSafe( NS_CATEGORY, $this->mName );
  228. return $this->mTitle;
  229. }
  230. /**
  231. * Fetch a TitleArray of up to $limit category members, beginning after the
  232. * category sort key $offset.
  233. * @param int|bool $limit
  234. * @param string $offset
  235. * @return TitleArray TitleArray object for category members.
  236. */
  237. public function getMembers( $limit = false, $offset = '' ) {
  238. $dbr = wfGetDB( DB_REPLICA );
  239. $conds = [ 'cl_to' => $this->getName(), 'cl_from = page_id' ];
  240. $options = [ 'ORDER BY' => 'cl_sortkey' ];
  241. if ( $limit ) {
  242. $options['LIMIT'] = $limit;
  243. }
  244. if ( $offset !== '' ) {
  245. $conds[] = 'cl_sortkey > ' . $dbr->addQuotes( $offset );
  246. }
  247. $result = TitleArray::newFromResult(
  248. $dbr->select(
  249. [ 'page', 'categorylinks' ],
  250. [ 'page_id', 'page_namespace', 'page_title', 'page_len',
  251. 'page_is_redirect', 'page_latest' ],
  252. $conds,
  253. __METHOD__,
  254. $options
  255. )
  256. );
  257. return $result;
  258. }
  259. /**
  260. * Generic accessor
  261. * @param string $key
  262. * @return bool
  263. */
  264. private function getX( $key ) {
  265. if ( !$this->initialize( self::LAZY_INIT_ROW ) ) {
  266. return false;
  267. }
  268. return $this->{$key};
  269. }
  270. /**
  271. * Refresh the counts for this category.
  272. *
  273. * @return bool True on success, false on failure
  274. */
  275. public function refreshCounts() {
  276. if ( wfReadOnly() ) {
  277. return false;
  278. }
  279. # If we have just a category name, find out whether there is an
  280. # existing row. Or if we have just an ID, get the name, because
  281. # that's what categorylinks uses.
  282. if ( !$this->initialize( self::LOAD_ONLY ) ) {
  283. return false;
  284. }
  285. $dbw = wfGetDB( DB_MASTER );
  286. # Avoid excess contention on the same category (T162121)
  287. $name = __METHOD__ . ':' . md5( $this->mName );
  288. $scopedLock = $dbw->getScopedLockAndFlush( $name, __METHOD__, 0 );
  289. if ( !$scopedLock ) {
  290. return false;
  291. }
  292. $dbw->startAtomic( __METHOD__ );
  293. $cond1 = $dbw->conditional( [ 'page_namespace' => NS_CATEGORY ], 1, 'NULL' );
  294. $cond2 = $dbw->conditional( [ 'page_namespace' => NS_FILE ], 1, 'NULL' );
  295. $result = $dbw->selectRow(
  296. [ 'categorylinks', 'page' ],
  297. [ 'pages' => 'COUNT(*)',
  298. 'subcats' => "COUNT($cond1)",
  299. 'files' => "COUNT($cond2)"
  300. ],
  301. [ 'cl_to' => $this->mName, 'page_id = cl_from' ],
  302. __METHOD__,
  303. [ 'LOCK IN SHARE MODE' ]
  304. );
  305. $shouldExist = $result->pages > 0 || $this->getTitle()->exists();
  306. if ( $this->mID ) {
  307. if ( $shouldExist ) {
  308. # The category row already exists, so do a plain UPDATE instead
  309. # of INSERT...ON DUPLICATE KEY UPDATE to avoid creating a gap
  310. # in the cat_id sequence. The row may or may not be "affected".
  311. $dbw->update(
  312. 'category',
  313. [
  314. 'cat_pages' => $result->pages,
  315. 'cat_subcats' => $result->subcats,
  316. 'cat_files' => $result->files
  317. ],
  318. [ 'cat_title' => $this->mName ],
  319. __METHOD__
  320. );
  321. } else {
  322. # The category is empty and has no description page, delete it
  323. $dbw->delete(
  324. 'category',
  325. [ 'cat_title' => $this->mName ],
  326. __METHOD__
  327. );
  328. $this->mID = false;
  329. }
  330. } elseif ( $shouldExist ) {
  331. # The category row doesn't exist but should, so create it. Use
  332. # upsert in case of races.
  333. $dbw->upsert(
  334. 'category',
  335. [
  336. 'cat_title' => $this->mName,
  337. 'cat_pages' => $result->pages,
  338. 'cat_subcats' => $result->subcats,
  339. 'cat_files' => $result->files
  340. ],
  341. [ 'cat_title' ],
  342. [
  343. 'cat_pages' => $result->pages,
  344. 'cat_subcats' => $result->subcats,
  345. 'cat_files' => $result->files
  346. ],
  347. __METHOD__
  348. );
  349. // @todo: Should we update $this->mID here? Or not since Category
  350. // objects tend to be short lived enough to not matter?
  351. }
  352. $dbw->endAtomic( __METHOD__ );
  353. # Now we should update our local counts.
  354. $this->mPages = $result->pages;
  355. $this->mSubcats = $result->subcats;
  356. $this->mFiles = $result->files;
  357. return true;
  358. }
  359. }