Merge "Follow-up I0b781c11 (2a55449): use User::getAutomaticGroups()."
[lhc/web/wiklou.git] / includes / Category.php
index 15e56b1..b7b12e8 100644 (file)
 <?php
 /**
- * Two classes, Category and CategoryList, to deal with categories.  To reduce
- * code duplication, most of the logic is implemented for lists of categories,
- * and then single categories are a special case.  We use a separate class for
- * CategoryList so as to discourage stupid slow memory-hogging stuff like manu-
- * ally iterating through arrays of Titles and Articles, which we do way too
- * much, when a smarter class can do stuff all in one query.
+ * Representation for a category.
  *
- * Category(List) objects are immutable, strictly speaking.  If you call me-
- * thods that change the database, like to refresh link counts, the objects
- * will be appropriately reinitialized.  Member variables are lazy-initialized.
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
  *
- * TODO: Move some stuff from CategoryPage.php to here, and use that.
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * http://www.gnu.org/copyleft/gpl.html
  *
+ * @file
  * @author Simetrical
  */
 
-abstract class CategoryListBase {
-       # FIXME: Is storing all member variables as simple arrays a good idea?
-       # Should we use some kind of associative array instead?
-       /** Names of all member categories, normalized to DB-key form */
-       protected $mNames = null;
-       /** IDs of all member categories */
-       protected $mIDs = null;
+/**
+ * Category objects are immutable, strictly speaking. If you call methods that change the database,
+ * like to refresh link counts, the objects will be appropriately reinitialized.
+ * Member variables are lazy-initialized.
+ *
+ * TODO: Move some stuff from CategoryPage.php to here, and use that.
+ */
+class Category {
+       /** Name of the category, normalized to DB-key form */
+       private $mName = null;
+       private $mID = null;
        /**
-        * Counts of membership (cat_pages, cat_subcats, cat_files) for all member
-        * categories
+        * Category page title
+        * @var Title
         */
-       protected $mPages = null, $mSubcats = null, $mFiles = null;
+       private $mTitle = null;
+       /** Counts of membership (cat_pages, cat_subcats, cat_files) */
+       private $mPages = null, $mSubcats = null, $mFiles = null;
 
-       protected function __construct() {}
-
-       /** See CategoryList::newFromNames for details. */
-       protected function setNames( $names ) {
-               if( !is_array( $names ) ) {
-                       throw new MWException( __METHOD__.' passed non-array' );
-               }
-               $this->mNames = array_diff(
-                       array_map(
-                               array( 'CategoryListBase', 'setNamesCallback' ),
-                               $names
-                       ),
-                       array( false )
-               );
-       }
-
-       /**
-        * @param string $name Name of a putative category
-        * @return mixed Normalized name, or false if the name was invalid.
-        */
-       private static function setNamesCallback( $name ) {
-               $title = Title::newFromText( "Category:$name" );
-               if( !is_object( $title ) ) {
-                       return false;
-               }
-               return $title->getDBKey();
-       }
+       private function __construct() { }
 
        /**
         * Set up all member variables using a database query.
         * @return bool True on success, false on failure.
         */
        protected function initialize() {
-               if( $this->mNames === null && $this->mIDs === null ) {
-                       throw new MWException( __METHOD__.' has both names and IDs null' );
-               }
-               $dbr = wfGetDB( DB_SLAVE );
-               if( $this->mIDs === null ) {
-                       $where = array( 'cat_title' => $this->mNames );
-               } elseif( $this->mNames === null ) {
-                       $where = array( 'cat_id' => $this->mIDs );
+               if ( $this->mName === null && $this->mID === null ) {
+                       throw new MWException( __METHOD__ . ' has both names and IDs null' );
+               } elseif ( $this->mID === null ) {
+                       $where = array( 'cat_title' => $this->mName );
+               } elseif ( $this->mName === null ) {
+                       $where = array( 'cat_id' => $this->mID );
                } else {
                        # Already initialized
                        return true;
                }
-               $res = $dbr->select(
+               $dbr = wfGetDB( DB_SLAVE );
+               $row = $dbr->selectRow(
                        'category',
-                       array( 'cat_id', 'cat_title', 'cat_pages', 'cat_subcats',
-                               'cat_files' ),
+                       array( 'cat_id', 'cat_title', 'cat_pages', 'cat_subcats', 'cat_files' ),
                        $where,
                        __METHOD__
                );
-               if( !$res->fetchRow() ) {
+
+               if ( !$row ) {
                        # Okay, there were no contents.  Nothing to initialize.
-                       return false;
+                       if ( $this->mTitle ) {
+                               # If there is a title object but no record in the category table, treat this as an empty category
+                               $this->mID      = false;
+                               $this->mName    = $this->mTitle->getDBkey();
+                               $this->mPages   = 0;
+                               $this->mSubcats = 0;
+                               $this->mFiles   = 0;
+
+                               return true;
+                       } else {
+                               return false; # Fail
+                       }
                }
-               $res->rewind();
-               $this->mIDs = $this->mNames = $this->mPages = $this->mSubcats =
-               $this->mFiles = array();
-               while( $row = $res->fetchRow() ) {
-                       $this->mIDs     []= $row['cat_id'];
-                       $this->mNames   []= $row['cat_title'];
-                       $this->mPages   []= $row['cat_pages'];
-                       $this->mSubcats []= $row['cat_subcats'];
-                       $this->mFiles   []= $row['cat_files'];
+
+               $this->mID      = $row->cat_id;
+               $this->mName    = $row->cat_title;
+               $this->mPages   = $row->cat_pages;
+               $this->mSubcats = $row->cat_subcats;
+               $this->mFiles   = $row->cat_files;
+
+               # (bug 13683) If the count is negative, then 1) it's obviously wrong
+               # and should not be kept, and 2) we *probably* don't have to scan many
+               # rows to obtain the correct figure, so let's risk a one-time recount.
+               if ( $this->mPages < 0 || $this->mSubcats < 0 || $this->mFiles < 0 ) {
+                       $this->refreshCounts();
                }
-               $res->free();
+
+               return true;
        }
-}
 
-/** @todo make iterable. */
-class CategoryList extends CategoryListBase {
        /**
-        * Factory function.  Any provided elements that don't correspond to a cat-
-        * egory that actually exists will be silently dropped.  FIXME: Is this
-        * sane error-handling?
+        * Factory function.
         *
-        * @param array $names An array of category names.  They need not be norma-
-        *   lized, with spaces replaced by underscores.
-        * @return CategoryList
+        * @param $name Array: A category name (no "Category:" prefix).  It need
+        *   not be normalized, with spaces replaced by underscores.
+        * @return mixed Category, or false on a totally invalid name
         */
-       public static function newFromNames( $names ) {
+       public static function newFromName( $name ) {
                $cat = new self();
-               $cat->setNames( $names );
-               return $cat;
-       }
+               $title = Title::makeTitleSafe( NS_CATEGORY, $name );
 
-       /**
-        * Factory function.  Any provided elements that don't correspond to a cat-
-        * egory that actually exists will be silently dropped.  FIXME: Is this
-        * sane error-handling?
-        *
-        * @param array $ids An array of category ids
-        * @return CategoryList
-        */
-       public static function newFromIDs( $ids ) {
-               if( !is_array( $ids ) ) {
-                       throw new MWException( __METHOD__.' passed non-array' );
+               if ( !is_object( $title ) ) {
+                       return false;
                }
-               $cat = new self();
-               $cat->mIds = $ids;
+
+               $cat->mTitle = $title;
+               $cat->mName = $title->getDBkey();
+
                return $cat;
        }
 
-       /** @return array Simple array of DB key names */
-       public function getNames() {
-               $this->initialize();
-               return $this->mNames;
-       }
-       /**
-        * FIXME: Is this a good return type?
-        *
-        * @return array Associative array of DB key name => ID
-        */
-       public function getIDs() {
-               $this->initialize();
-               return array_fill_keys( $this->mNames, $this->mIDs );
-       }
        /**
-        * FIXME: Is this a good return type?
+        * Factory function.
         *
-        * @return array Associative array of DB key name => array(pages, subcats,
-        *   files)
+        * @param $title Title for the category page
+        * @return Category|bool on a totally invalid name
         */
-       public function getCounts() {
-               $this->initialize();
-               $ret = array();
-               foreach( array_keys( $this->mNames ) as $i ) {
-                       $ret[$this->mNames[$i]] = array(
-                               $this->mPages[$i],
-                               $this->mSubcats[$i],
-                               $this->mFiles[$i]
-                       );
-               }
-               return $ret;
+       public static function newFromTitle( $title ) {
+               $cat = new self();
+
+               $cat->mTitle = $title;
+               $cat->mName = $title->getDBkey();
+
+               return $cat;
        }
-}
 
-class Category extends CategoryListBase {
        /**
         * Factory function.
         *
-        * @param array $name A category name (no "Category:" prefix).  It need
-        *   not be normalized, with spaces replaced by underscores.
-        * @return mixed Category, or false on a totally invalid name
+        * @param $id Integer: a category id
+        * @return Category
         */
-       public static function newFromName( $name ) {
+       public static function newFromID( $id ) {
                $cat = new self();
-               $cat->setNames( array( $name ) );
-               if( count( $cat->mNames ) !== 1 ) {
-                       return false;
-               }
+               $cat->mID = intval( $id );
                return $cat;
        }
 
        /**
-        * Factory function.
+        * Factory function, for constructing a Category object from a result set
         *
-        * @param array $id A category id
+        * @param $row result set row, must contain the cat_xxx fields. If the fields are null,
+        *        the resulting Category object will represent an empty category if a title object
+        *        was given. If the fields are null and no title was given, this method fails and returns false.
+        * @param Title $title optional title object for the category represented by the given row.
+        *        May be provided if it is already known, to avoid having to re-create a title object later.
         * @return Category
         */
-       public static function newFromIDs( $id ) {
+       public static function newFromRow( $row, $title = null ) {
                $cat = new self();
-               $cat->mIDs = array( $id );
+               $cat->mTitle = $title;
+
+               # NOTE: the row often results from a LEFT JOIN on categorylinks. This may result in
+               #       all the cat_xxx fields being null, if the category page exists, but nothing
+               #       was ever added to the category. This case should be treated linke an empty
+               #       category, if possible.
+
+               if ( $row->cat_title === null ) {
+                       if ( $title === null ) {
+                               # the name is probably somewhere in the row, for example as page_title,
+                               # but we can't know that here...
+                               return false;
+                       } else {
+                               $cat->mName = $title->getDBkey(); # if we have a title object, fetch the category name from there
+                       }
+
+                       $cat->mID =   false;
+                       $cat->mSubcats = 0;
+                       $cat->mPages   = 0;
+                       $cat->mFiles   = 0;
+               } else {
+                       $cat->mName    = $row->cat_title;
+                       $cat->mID      = $row->cat_id;
+                       $cat->mSubcats = $row->cat_subcats;
+                       $cat->mPages   = $row->cat_pages;
+                       $cat->mFiles   = $row->cat_files;
+               }
+
                return $cat;
        }
 
        /** @return mixed DB key name, or false on failure */
-       public function getName() { return $this->getX( 'mNames' ); }
+       public function getName() { return $this->getX( 'mName' ); }
+
        /** @return mixed Category ID, or false on failure */
-       public function getID() { return $this->getX( 'mIDs' ); }
+       public function getID() { return $this->getX( 'mID' ); }
+
        /** @return mixed Total number of member pages, or false on failure */
        public function getPageCount() { return $this->getX( 'mPages' ); }
+
        /** @return mixed Number of subcategories, or false on failure */
        public function getSubcatCount() { return $this->getX( 'mSubcats' ); }
+
        /** @return mixed Number of member files, or false on failure */
        public function getFileCount() { return $this->getX( 'mFiles' ); }
 
        /**
-        * This is not implemented in the base class, because arrays of Titles are
-        * evil.
-        *
-        * @return mixed The Title for this category, or false on failure.
+        * @return Title|bool Title for this category, or false on failure.
         */
        public function getTitle() {
-               if( !$this->initialize() ) {
-                       return false;
-               }
-               return Title::makeTitleSafe( NS_CATEGORY, $this->mNames[0] );
-       }
+               if ( $this->mTitle ) return $this->mTitle;
 
-       /** Generic accessor */
-       private function getX( $key ) {
-               if( !$this->initialize() ) {
+               if ( !$this->initialize() ) {
                        return false;
                }
-               return $this->{$key}[0];
+
+               $this->mTitle = Title::makeTitleSafe( NS_CATEGORY, $this->mName );
+               return $this->mTitle;
        }
 
        /**
-        * Override the parent class so that we can return false if things muck
-        * up, i.e., the name/ID we got was invalid.  Currently CategoryList si-
-        * lently eats errors so as not to kill the whole array for one bad name.
-        *
-        * @return bool True on success, false on failure.
+        * Fetch a TitleArray of up to $limit category members, beginning after the
+        * category sort key $offset.
+        * @param $limit integer
+        * @param $offset string
+        * @return TitleArray object for category members.
         */
-       protected function initialize() {
-               parent::initialize();
+       public function getMembers( $limit = false, $offset = '' ) {
+               $dbr = wfGetDB( DB_SLAVE );
 
-               # (bug 13683) If the count is negative, then 1) it's obviously wrong
-               # and should not be kept, and 2) we *probably* don't have to scan many
-               # rows to obtain the correct figure, so let's risk a one-time recount.
-               if( $this->mPages[0] < 0 || $this->mSubcats[0] < 0 ||
-               $this->mFiles[0] < 0 ) {
-                       $this->refreshCounts();
+               $conds = array( 'cl_to' => $this->getName(), 'cl_from = page_id' );
+               $options = array( 'ORDER BY' => 'cl_sortkey' );
+
+               if ( $limit ) {
+                       $options[ 'LIMIT' ] = $limit;
+               }
+
+               if ( $offset !== '' ) {
+                       $conds[] = 'cl_sortkey > ' . $dbr->addQuotes( $offset );
                }
 
-               if( count( $this->mNames ) != 1 || count( $this->mIDs ) != 1 ) {
+               return TitleArray::newFromResult(
+                       $dbr->select(
+                               array( 'page', 'categorylinks' ),
+                               array( 'page_id', 'page_namespace', 'page_title', 'page_len',
+                                       'page_is_redirect', 'page_latest' ),
+                               $conds,
+                               __METHOD__,
+                               $options
+                       )
+               );
+       }
+
+       /**
+        * Generic accessor
+        * @return bool
+        */
+       private function getX( $key ) {
+               if ( !$this->initialize() ) {
                        return false;
                }
-               return true;
+               return $this-> { $key } ;
        }
 
        /**
         * Refresh the counts for this category.
         *
-        * FIXME: If there were some way to do this in MySQL 4 without an UPDATE
-        * for every row, it would be nice to move this to the parent class.
-        *
         * @return bool True on success, false on failure
         */
        public function refreshCounts() {
-               if( wfReadOnly() ) {
+               if ( wfReadOnly() ) {
                        return false;
                }
-               $dbw = wfGetDB( DB_MASTER );
-               $dbw->begin();
+
                # Note, we must use names for this, since categorylinks does.
-               if( $this->mNames === null ) {
-                       if( !$this->initialize() ) {
+               if ( $this->mName === null ) {
+                       if ( !$this->initialize() ) {
                                return false;
                        }
-               } else {
-                       # Let's be sure that the row exists in the table.  We don't need to
-                       # do this if we got the row from the table in initialization!
-                       $dbw->insert(
-                               'category',
-                               array( 'cat_title' => $this->mNames[0] ),
-                               __METHOD__,
-                               'IGNORE'
-                       );
                }
 
-               $cond1 = $dbw->conditional( 'page_namespace='.NS_CATEGORY, 1, 'NULL' );
-               $cond2 = $dbw->conditional( 'page_namespace='.NS_IMAGE, 1, 'NULL' );
+               $dbw = wfGetDB( DB_MASTER );
+               $dbw->begin( __METHOD__  );
+
+               # Insert the row if it doesn't exist yet (e.g., this is being run via
+               # update.php from a pre-1.16 schema).  TODO: This will cause lots and
+               # lots of gaps on some non-MySQL DBMSes if you run populateCategory.php
+               # repeatedly.  Plus it's an extra query that's unneeded almost all the
+               # time.  This should be rewritten somehow, probably.
+               $seqVal = $dbw->nextSequenceValue( 'category_cat_id_seq' );
+               $dbw->insert(
+                       'category',
+                       array(
+                               'cat_id' => $seqVal,
+                               'cat_title' => $this->mName
+                       ),
+                       __METHOD__,
+                       'IGNORE'
+               );
+
+               $cond1 = $dbw->conditional( array( 'page_namespace' => NS_CATEGORY ), 1, 'NULL' );
+               $cond2 = $dbw->conditional( array( 'page_namespace' => NS_FILE ), 1, 'NULL' );
                $result = $dbw->selectRow(
                        array( 'categorylinks', 'page' ),
-                       array( 'COUNT(*) AS pages',
-                                  "COUNT($cond1) AS subcats",
-                                  "COUNT($cond2) AS files"
+                       array( 'pages' => 'COUNT(*)',
+                                  'subcats' => "COUNT($cond1)",
+                                  'files' => "COUNT($cond2)"
                        ),
-                       array( 'cl_to' => $this->mNames[0], 'page_id = cl_from' ),
+                       array( 'cl_to' => $this->mName, 'page_id = cl_from' ),
                        __METHOD__,
                        'LOCK IN SHARE MODE'
                );
@@ -301,15 +316,15 @@ class Category extends CategoryListBase {
                                'cat_subcats' => $result->subcats,
                                'cat_files' => $result->files
                        ),
-                       array( 'cat_title' => $this->mNames[0] ),
+                       array( 'cat_title' => $this->mName ),
                        __METHOD__
                );
-               $dbw->commit();
+               $dbw->commit( __METHOD__ );
 
                # Now we should update our local counts.
-               $this->mPages   = array( $result->pages );
-               $this->mSubcats = array( $result->subcats );
-               $this->mFiles   = array( $result->files );
+               $this->mPages   = $result->pages;
+               $this->mSubcats = $result->subcats;
+               $this->mFiles   = $result->files;
 
                return $ret;
        }