Added sites functionality, a much more generic and flexible version of the existing...
authorjeroendedauw <jeroendedauw@gmail.com>
Wed, 12 Sep 2012 17:22:39 +0000 (19:22 +0200)
committerjeroendedauw <jeroendedauw@gmail.com>
Fri, 12 Oct 2012 15:47:44 +0000 (17:47 +0200)
This code is meant to replace the current interwiki code, but does not do so just yet. It is however used by the Wikibase extension. This allows us to try out some more things and have the code stabilize more before we migrate over existing interwiki functionality.

Change-Id: I23c47c2c3909a1500350fb560a5f2ec654e2c37e

21 files changed:
includes/AutoLoader.php
includes/DefaultSettings.php
includes/installer/MysqlUpdater.php
includes/installer/SqliteUpdater.php
includes/site/MediaWikiSite.php [new file with mode: 0644]
includes/site/Site.php [new file with mode: 0644]
includes/site/SiteArray.php [new file with mode: 0644]
includes/site/SiteList.php [new file with mode: 0644]
includes/site/SiteObject.php [new file with mode: 0644]
includes/site/Sites.php [new file with mode: 0644]
includes/site/SitesTable.php [new file with mode: 0644]
maintenance/archives/patch-sites.sql [new file with mode: 0644]
maintenance/sqlite/archives/patch-sites.sql [new file with mode: 0644]
maintenance/tables.sql
tests/phpunit/includes/libs/GenericArrayObjectTest.php
tests/phpunit/includes/site/MediaWikiSiteTest.php [new file with mode: 0644]
tests/phpunit/includes/site/SiteArrayTest.php [new file with mode: 0644]
tests/phpunit/includes/site/SiteListTest.php [new file with mode: 0644]
tests/phpunit/includes/site/SiteObjectTest.php [new file with mode: 0644]
tests/phpunit/includes/site/SitesTest.php [new file with mode: 0644]
tests/phpunit/includes/site/TestSites.php [new file with mode: 0644]

index 7deeec0..e8df8d4 100644 (file)
@@ -874,6 +874,15 @@ $wgAutoloadLocalClasses = array(
        'SqliteSearchResultSet' => 'includes/search/SearchSqlite.php',
        'SqlSearchResultSet' => 'includes/search/SearchEngine.php',
 
+       # includes/site
+       'MediaWikiSite' => 'includes/site/MediaWikiSite.php',
+       'Site' => 'includes/site/Site.php',
+       'SiteArray' => 'includes/site/SiteArray.php',
+       'SiteList' => 'includes/site/SiteList.php',
+       'SiteObject' => 'includes/site/SiteObject.php',
+       'Sites' => 'includes/site/Sites.php',
+       'SitesTable' => 'includes/site/SitesTable.php',
+
        # includes/specials
        'ActiveUsersPager' => 'includes/specials/SpecialActiveusers.php',
        'AllmessagesTablePager' => 'includes/specials/SpecialAllmessages.php',
@@ -1092,6 +1101,10 @@ $wgAutoloadLocalClasses = array(
        # tests/phpunit/includes/db
        'ORMRowTest' => 'tests/phpunit/includes/db/ORMRowTest.php',
 
+       # tests/phpunit/includes/site
+       'SiteObjectTest' => 'tests/phpunit/includes/site/SiteObjectTest.php',
+       'TestSites' => 'tests/phpunit/includes/site/TestSites.php',
+
        # tests/parser
        'ParserTest' => 'tests/parser/parserTest.inc',
        'ParserTestParserHook' => 'tests/parser/parserTestsParserHook.php',
index ae8ff58..159ed29 100644 (file)
@@ -6293,6 +6293,14 @@ $wgContentHandlerUseDB = true;
  */
 $wgRequirePasswordforEmailChange = true;
 
+/**
+ * Register handlers for specific types of sites.
+ *
+ * @since 1.20
+ */
+$wgSiteTypes = array();
+$wgSiteTypes['mediawiki'] = 'MediaWikiSite';
+
 /**
  * For really cool vim folding this needs to be at the end:
  * vim: foldmarker=@{,@} foldmethod=marker
index 00009ca..d787b5c 100644 (file)
@@ -224,6 +224,7 @@ class MysqlUpdater extends DatabaseUpdater {
                        array( 'addField',      'page',     'page_content_model',               'patch-page-page_content_model.sql' ),
                        array( 'dropField', 'site_stats',   'ss_admins',        'patch-drop-ss_admins.sql' ),
                        array( 'dropField', 'recentchanges', 'rc_moved_to_title',            'patch-rc_moved.sql' ),
+                       array( 'addTable', 'sites',                            'patch-sites.sql' ),
                );
        }
 
index e26aa78..eaec3d5 100644 (file)
@@ -104,6 +104,7 @@ class SqliteUpdater extends DatabaseUpdater {
 
                        array( 'dropField', 'site_stats',    'ss_admins',         'patch-drop-ss_admins.sql' ),
                        array( 'dropField', 'recentchanges', 'rc_moved_to_title', 'patch-rc_moved.sql' ),
+                       array( 'addTable', 'sites',                            'patch-sites.sql' ),
                );
        }
 
diff --git a/includes/site/MediaWikiSite.php b/includes/site/MediaWikiSite.php
new file mode 100644 (file)
index 0000000..6f1b578
--- /dev/null
@@ -0,0 +1,320 @@
+<?php
+
+/**
+ * Class representing a MediaWiki site.
+ *
+ * @since 1.20
+ *
+ * @file
+ * @ingroup Site
+ *
+ * @licence GNU GPL v2+
+ * @author John Erling Blad < jeblad@gmail.com >
+ * @author Daniel Kinzler
+ * @author Jeroen De Dauw < jeroendedauw@gmail.com >
+ */
+class MediaWikiSite extends SiteObject {
+
+       const PATH_FILE = 'file_path';
+       const PATH_PAGE = 'page_path';
+
+       /**
+        * @since 1.20
+        *
+        * @param integer $globalId
+        *
+        * @return MediaWikiSite
+        */
+       public static function newFromGlobalId( $globalId ) {
+               return SitesTable::singleton()->newRow( array(
+                       'type' => Site::TYPE_MEDIAWIKI,
+                       'global_key' => $globalId,
+               ), true );
+       }
+
+       /**
+        * Returns the database form of the given title.
+        *
+        * @since 1.20
+        *
+        * @param String $title the target page's title, in normalized form.
+        *
+        * @return String
+        */
+       public function toDBKey( $title ) {
+               return str_replace( ' ', '_', $title );
+       }
+
+       /**
+        * Returns the normalized form of the given page title, using the normalization rules of the given site.
+        * If the given title is a redirect, the redirect weill be resolved and the redirect target is returned.
+        *
+        * @note  : This actually makes an API request to the remote site, so beware that this function is slow and depends
+        *          on an external service.
+        *
+        * @note  : If MW_PHPUNIT_TEST is defined or $egWBRemoteTitleNormalization is set to false, the call to the
+        *          external site is skipped, and the title is normalized using the local normalization rules as
+        *          implemented by the Title class.
+        *
+        * @see Site::normalizePageName
+        *
+        * @since 1.20
+        *
+        * @param string $pageName
+        *
+        * @return string
+        * @throws MWException
+        */
+       public function normalizePageName( $pageName ) {
+               global $egWBRemoteTitleNormalization;
+
+               // Check if we have strings as arguments.
+               if ( !is_string( $pageName ) ) {
+                       throw new MWException( '$pageName must be a string' );
+               }
+
+               // Go on call the external site
+               if ( defined( 'MW_PHPUNIT_TEST' ) ) {
+                       // If the code is under test, don't call out to other sites, just normalize locally.
+                       // Note: this may cause results to be inconsistent with the actual normalization used by the respective remote site!
+
+                       $t = Title::newFromText( $pageName );
+                       return $t->getPrefixedText();
+               } else {
+
+                       // Make sure the string is normalized into NFC (due to the bug 40017)
+                       // but do nothing to the whitespaces, that should work appropriately.
+                       // @see https://bugzilla.wikimedia.org/show_bug.cgi?id=40017
+                       $pageName = UtfNormal::cleanUp( $pageName );
+
+                       // Build the args for the specific call
+                       $args = array(
+                               'action' => 'query',
+                               'prop' => 'info',
+                               'redirects' => true,
+                               'converttitles' => true,
+                               'format' => 'json',
+                               'titles' => $pageName,
+                               //@todo: options for maxlag and maxage
+                               // Note that maxlag will lead to a long delay before a reply is made,
+                               // but that maxage can avoid the extreme delay. On the other hand
+                               // maxage could be nice to use anyhow as it stops unnecessary requests.
+                               // Also consider smaxage if maxage is used.
+                       );
+
+                       $url = $this->getFileUrl( 'api.php' ) . '?' . wfArrayToCgi( $args );
+
+                       // Go on call the external site
+                       //@todo: we need a good way to specify a timeout here.
+                       $ret = Http::get( $url );
+               }
+
+               if ( $ret === false ) {
+                       wfDebugLog( "MediaWikiSite", "call to external site failed: $url" );
+                       return false;
+               }
+
+               $data = FormatJson::decode( $ret, true );
+
+               if ( !is_array( $data ) ) {
+                       wfDebugLog( "MediaWikiSite", "call to <$url> returned bad json: " . $ret );
+                       return false;
+               }
+
+               $page = static::extractPageRecord( $data, $pageName );
+
+               if ( isset( $page['missing'] ) ) {
+                       wfDebugLog( "MediaWikiSite", "call to <$url> returned a missing page title! " . $ret );
+                       return false;
+               }
+
+               if ( !isset( $page['title'] ) ) {
+                       wfDebugLog( "MediaWikiSite", "call to <$url> did not return a page title! " . $ret );
+                       return false;
+               }
+
+               return $page['title'];
+       }
+
+
+       /**
+        * Get normalization record for a given page title from an API response.
+        *
+        * @since 1.20
+        *
+        * @param array $externalData A reply from the API on a external server.
+        * @param string $pageTitle Identifies the page at the external site, needing normalization.
+        *
+        * @return array|false a 'page' structure representing the page identified by $pageTitle.
+        */
+       private static function extractPageRecord( $externalData, $pageTitle ) {
+               // If there is a special case with only one returned page
+               // we can cheat, and only return
+               // the single page in the "pages" substructure.
+               if ( isset( $externalData['query']['pages'] ) ) {
+                       $pages = array_values( $externalData['query']['pages'] );
+                       if ( count( $pages) === 1 ) {
+                               return $pages[0];
+                       }
+               }
+               // This is only used during internal testing, as it is assumed
+               // a more optimal (and lossfree) storage.
+               // Make initial checks and return if prerequisites are not meet.
+               if ( !is_array( $externalData ) || !isset( $externalData['query'] ) ) {
+                       return false;
+               }
+               // Loop over the tree different named structures, that otherwise are similar
+               $structs = array(
+                       'normalized' => 'from',
+                       'converted' => 'from',
+                       'redirects' => 'from',
+                       'pages' => 'title'
+               );
+               foreach ( $structs as $listId => $fieldId ) {
+                       // Check if the substructure exist at all.
+                       if ( !isset( $externalData['query'][$listId] ) ) {
+                               continue;
+                       }
+                       // Filter the substructure down to what we actually are using.
+                       $collectedHits = array_filter(
+                               array_values( $externalData['query'][$listId] ),
+                               function( $a ) use ( $fieldId, $pageTitle ) {
+                                       return $a[$fieldId] === $pageTitle;
+                               }
+                       );
+                       // If still looping over normalization, conversion or redirects,
+                       // then we need to keep the new page title for later rounds.
+                       if ( $fieldId === 'from' && is_array( $collectedHits ) ) {
+                               switch ( count( $collectedHits ) ) {
+                                       case 0:
+                                               break;
+                                       case 1:
+                                               $pageTitle = $collectedHits[0]['to'];
+                                               break;
+                                       default:
+                                               return false;
+                               }
+                       }
+                       // If on the pages structure we should prepare for returning.
+                       elseif ( $fieldId === 'title' && is_array( $collectedHits ) ) {
+                               switch ( count( $collectedHits ) ) {
+                                       case 0:
+                                               return false;
+                                       case 1:
+                                               return array_shift( $collectedHits );
+                                       default:
+                                               return false;
+                               }
+                       }
+               }
+               // should never be here
+               return false;
+       }
+
+       /**
+        * @see Site::getLinkPathType
+        * Returns Site::PATH_PAGE
+        *
+        * @since 1.20
+        *
+        * @return string
+        */
+       public function getLinkPathType() {
+               return self::PATH_PAGE;
+       }
+
+       /**
+        * Returns the relative page path.
+        *
+        * @since 1.20
+        *
+        * @return string
+        */
+       public function getRelativePagePath() {
+               return parse_url( $this->getPath( self::PATH_PAGE ), PHP_URL_PATH );
+       }
+
+       /**
+        * Returns the relative file path.
+        *
+        * @since 1.20
+        *
+        * @return string
+        */
+       public function getRelativeFilePath() {
+               return parse_url( $this->getPath( self::PATH_FILE ), PHP_URL_PATH );
+       }
+
+       /**
+        * Sets the relative page path.
+        *
+        * @since 1.20
+        *
+        * @param string $path
+        */
+       public function setPagePath( $path ) {
+               $this->setPath( self::PATH_PAGE, $path );
+       }
+
+       /**
+        * Sets the relative file path.
+        *
+        * @since 1.20
+        *
+        * @param string $path
+        */
+       public function setFilePath( $path ) {
+               $this->setPath( self::PATH_FILE, $path );
+       }
+
+       /**
+        * @see Site::getPagePath
+        *
+        * This implementation returns a URL constructed using the path returned by getLinkPath().
+        * In addition to the default behaviour implemented by SiteObject::getPageUrl(), this
+        * method converts the $pageName to DBKey-format by replacing spaces with underscores
+        * before using it in the URL.
+        *
+        * @since 1.20
+        *
+        * @param string|false
+        *
+        * @return string
+        */
+       public function getPageUrl( $pageName = false ) {
+               $url = $this->getLinkPath();
+
+               if ( $url === false ) {
+                       return false;
+               }
+
+               if ( $pageName !== false ) {
+                       $pageName = $this->toDBKey( trim( $pageName ) );
+                       $url = str_replace( '$1', wfUrlencode( $pageName ), $url ) ;
+               }
+
+               return $url;
+       }
+
+       /**
+        * Returns the full file path (ie site url + relative file path).
+        * The path should go at the $1 marker. If the $path
+        * argument is provided, the marker will be replaced by it's value.
+        *
+        * @since 1.20
+        *
+        * @param string|false $path
+        *
+        * @return string
+        */
+       public function getFileUrl( $path = false ) {
+               $filePath = $this->getPath( self::PATH_FILE );
+
+               if ( $filePath !== false ) {
+                       $filePath = str_replace( '$1', $path, $filePath );
+               }
+
+               return $filePath;
+       }
+
+}
diff --git a/includes/site/Site.php b/includes/site/Site.php
new file mode 100644 (file)
index 0000000..a0e2b56
--- /dev/null
@@ -0,0 +1,316 @@
+<?php
+
+/**
+ * Interface for site objects.
+ *
+ * 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.
+ *
+ * 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
+ *
+ * @since 1.20
+ *
+ * @file
+ * @ingroup Site
+ *
+ * @licence GNU GPL v2+
+ * @author Jeroen De Dauw < jeroendedauw@gmail.com >
+ */
+interface Site {
+
+       const TYPE_UNKNOWN = 'unknown';
+       const TYPE_MEDIAWIKI = 'mediawiki';
+
+       const GROUP_NONE = 'none';
+
+       const ID_INTERWIKI = 'interwiki';
+       const ID_EQUIVALENT = 'equivalent';
+
+       const SOURCE_LOCAL = 'local';
+
+       /**
+        * Returns the global site identifier (ie enwiktionary).
+        *
+        * @since 1.20
+        *
+        * @return string
+        */
+       public function getGlobalId();
+
+       /**
+        * Sets the global site identifier (ie enwiktionary).
+        *
+        * @since 1.20
+        *
+        * @param string $globalId
+        */
+       public function setGlobalId( $globalId );
+
+       /**
+        * Returns the type of the site (ie mediawiki).
+        *
+        * @since 1.20
+        *
+        * @return string
+        */
+       public function getType();
+
+       /**
+        * Sets the type of the site (ie mediawiki).
+        * TODO: remove, we cannot change this after instantiation
+        *
+        * @since 1.20
+        *
+        * @param string $type
+        */
+       public function setType( $type );
+
+       /**
+        * Gets the type of the site (ie wikipedia).
+        *
+        * @since 1.20
+        *
+        * @return string
+        */
+       public function getGroup();
+
+       /**
+        * Sets the type of the site (ie wikipedia).
+        *
+        * @since 1.20
+        *
+        * @param string $group
+        */
+       public function setGroup( $group );
+
+       /**
+        * Returns the source of the site data (ie 'local', 'wikidata', 'my-magical-repo').
+        *
+        * @since 1.20
+        *
+        * @return string
+        */
+       public function getSource();
+
+       /**
+        * Sets the source of the site data (ie 'local', 'wikidata', 'my-magical-repo').
+        *
+        * @since 1.20
+        *
+        * @param string $source
+        */
+       public function setSource( $source );
+
+       /**
+        * Returns the protocol of the site, ie 'http://', 'irc://', '//'
+        * Or false if it's not known.
+        *
+        * @since 1.20
+        *
+        * @return string|false
+        */
+       public function getProtocol();
+
+       /**
+        * Returns the domain of the site, ie en.wikipedia.org
+        * Or false if it's not known.
+        *
+        * @since 1.20
+        *
+        * @return string|false
+        */
+       public function getDomain();
+
+       /**
+        * Returns the full URL for the given page on the site.
+        * Or false if the needed information is not known.
+        *
+        * This generated URL is usually based upon the path returned by getLinkPath(),
+        * but this is not a requirement.
+        *
+        * @since 1.20
+        * @see Site::getLinkPath()
+        *
+        * @param bool|String $page
+        *
+        * @return string|false
+        */
+       public function getPageUrl( $page = false );
+
+       /**
+        * Returns language code of the sites primary language.
+        * Or false if it's not known.
+        *
+        * @since 1.20
+        *
+        * @return string|false
+        */
+       public function getLanguageCode();
+
+       /**
+        * Sets language code of the sites primary language.
+        *
+        * @since 1.20
+        *
+        * @param string $languageCode
+        */
+       public function setLanguageCode( $languageCode );
+
+       /**
+        * Returns the normalized, canonical form of the given page name.
+        * How normalization is performed or what the properties of a normalized name are depends on the site.
+        * The general contract of this method is that the normalized form shall refer to the same content
+        * as the original form, and any other page name referring to the same content will have the same normalized form.
+        *
+        * Note that this method may call out to the target site to perform the normalization, so it may be slow
+        * and fail due to IO errors.
+        *
+        * @since 1.20
+        *
+        * @param string $pageName
+        *
+        * @return string the normalized page name
+        */
+       public function normalizePageName( $pageName );
+
+       /**
+        * Returns the interwiki link identifiers that can be used for this site.
+        *
+        * @since 1.20
+        *
+        * @return array of string
+        */
+       public function getInterwikiIds();
+
+       /**
+        * Returns the equivalent link identifiers that can be used to make
+        * the site show up in interfaces such as the "language links" section.
+        *
+        * @since 1.20
+        *
+        * @return array of string
+        */
+       public function getNavigationIds();
+
+       /**
+        * Adds an local identifier to the site.
+        *
+        * @since 1.20
+        *
+        * @param string $type The type of the identifier, element of the Site::ID_ enum
+        * @param string $identifier
+        */
+       public function addLocalId( $type, $identifier );
+
+       /**
+        * Adds an interwiki id to the site.
+        *
+        * @since 1.20
+        *
+        * @param string $identifier
+        */
+       public function addInterwikiId( $identifier );
+
+       /**
+        * Adds a navigation id to the site.
+        *
+        * @since 1.20
+        *
+        * @param string $identifier
+        */
+       public function addNavigationId( $identifier );
+
+       /**
+        * Saves the site.
+        *
+        * @since 1.20
+        *
+        * @param string|null $functionName
+        */
+       public function save( $functionName = null );
+
+       /**
+        * Returns the internal ID of the site.
+        *
+        * @since 1.20
+        *
+        * @return integer
+        */
+       public function getInternalId();
+
+       /**
+        * Sets the provided url as path of the specified type.
+        *
+        * @since 1.20
+        *
+        * @param string $pathType
+        * @param string $fullUrl
+        */
+       public function setPath( $pathType, $fullUrl );
+
+       /**
+        * Returns the path of the provided type or false if there is no such path.
+        *
+        * @since 1.20
+        *
+        * @param string $pathType
+        *
+        * @return string|false
+        */
+       public function getPath( $pathType );
+
+       /**
+        * Sets the path used to construct links with.
+        * Shall be equivalent to setPath( getLinkPathType(), $fullUrl ).
+        *
+        * @param string $fullUrl
+        *
+        * @since 1.20
+        */
+       public function setLinkPath( $fullUrl );
+
+       /**
+        * Returns the path used to construct links with or false if there is no such path.
+        * Shall be equivalent to getPath( getLinkPathType() ).
+        *
+        * @return string|false
+        */
+       public function getLinkPath();
+
+       /**
+        * Returns the path type used to construct links with.
+        *
+        * @return string|false
+        */
+       public function getLinkPathType();
+
+       /**
+        * Returns the paths as associative array.
+        * The keys are path types, the values are the path urls.
+        *
+        * @since 1.20
+        *
+        * @return array of string
+        */
+       public function getAllPaths();
+
+       /**
+        * Removes the path of the provided type if it's set.
+        *
+        * @since 1.20
+        *
+        * @param string $pathType
+        */
+       public function removePath( $pathType );
+
+}
\ No newline at end of file
diff --git a/includes/site/SiteArray.php b/includes/site/SiteArray.php
new file mode 100644 (file)
index 0000000..f0a595d
--- /dev/null
@@ -0,0 +1,205 @@
+<?php
+
+/**
+ * Implementation of SiteList using GenericArrayObject.
+ *
+ * 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.
+ *
+ * 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
+ *
+ * @since 1.20
+ *
+ * @file
+ * @ingroup Site
+ *
+ * @licence GNU GPL v2+
+ * @author Jeroen De Dauw < jeroendedauw@gmail.com >
+ */
+class SiteArray extends GenericArrayObject implements SiteList {
+
+       /**
+        * Internal site identifiers pointing to their sites offset value.
+        *
+        * @since 1.20
+        *
+        * @var array of integer
+        */
+       protected $byInternalId = array();
+
+       /**
+        * Global site identifiers pointing to their sites offset value.
+        *
+        * @since 1.20
+        *
+        * @var array of string
+        */
+       protected $byGlobalId = array();
+
+       /**
+        * @see GenericArrayObject::getObjectType
+        *
+        * @since 1.20
+        *
+        * @return string
+        */
+       public function getObjectType() {
+               return 'Site';
+       }
+
+       /**
+        * @see GenericArrayObject::preSetElement
+        *
+        * @since 1.20
+        *
+        * @param int|string $index
+        * @param Site $site
+        *
+        * @return boolean
+        */
+       protected function preSetElement( $index, $site ) {
+               if ( $this->hasSite( $site->getGlobalId() ) ) {
+                       $this->removeSite( $site->getGlobalId() );
+               }
+
+               $this->byGlobalId[$site->getGlobalId()] = $index;
+               $this->byInternalId[$site->getInternalId()] = $index;
+
+               return true;
+       }
+
+       /**
+        * @see ArrayObject::offsetUnset()
+        *
+        * @since 1.20
+        *
+        * @param mixed $index
+        */
+       public function offsetUnset( $index ) {
+               /**
+                * @var Site $site
+                */
+               $site = $this->offsetGet( $index );
+
+               if ( $site !== false ) {
+                       unset( $this->byGlobalId[$site->getGlobalId()] );
+                       unset( $this->byInternalId[$site->getInternalId()] );
+               }
+
+               parent::offsetUnset( $index );
+       }
+
+       /**
+        * @see SiteList::getGlobalIdentifiers
+        *
+        * @since 1.20
+        *
+        * @return array
+        */
+       public function getGlobalIdentifiers() {
+               return array_keys( $this->byGlobalId );
+       }
+
+       /**
+        * @see SiteList::hasSite
+        *
+        * @param string $globalSiteId
+        *
+        * @return boolean
+        */
+       public function hasSite( $globalSiteId ) {
+               return array_key_exists( $globalSiteId, $this->byGlobalId );
+       }
+
+       /**
+        * @see SiteList::getSite
+        *
+        * @since 1.20
+        *
+        * @param string $globalSiteId
+        *
+        * @return Site
+        */
+       public function getSite( $globalSiteId ) {
+               return $this->offsetGet( $this->byGlobalId[$globalSiteId] );
+       }
+
+       /**
+        * @see SiteList::removeSite
+        *
+        * @since 1.20
+        *
+        * @param string $globalSiteId
+        */
+       public function removeSite( $globalSiteId ) {
+               $this->offsetUnset( $this->byGlobalId[$globalSiteId] );
+       }
+
+       /**
+        * @see SiteList::isEmpty
+        *
+        * @since 1.20
+        *
+        * @return boolean
+        */
+       public function isEmpty() {
+               return $this->byGlobalId === array();
+       }
+
+       /**
+        * @see SiteList::hasInternalId
+        *
+        * @param integer $id
+        *
+        * @return boolean
+        */
+       public function hasInternalId( $id ) {
+               return array_key_exists( $id, $this->byInternalId );
+       }
+
+       /**
+        * @see SiteList::getSiteByInternalId
+        *
+        * @since 1.20
+        *
+        * @param integer $id
+        *
+        * @return Site
+        */
+       public function getSiteByInternalId( $id ) {
+               return $this->offsetGet( $this->byInternalId[$id] );
+       }
+
+       /**
+        * @see SiteList::removeSiteByInternalId
+        *
+        * @since 1.20
+        *
+        * @param integer $id
+        */
+       public function removeSiteByInternalId( $id ) {
+               $this->offsetUnset( $this->byInternalId[$id] );
+       }
+
+       /**
+        * @see SiteList::setSite
+        *
+        * @since 1.20
+        *
+        * @param Site $site
+        */
+       public function setSite( Site $site ) {
+               $this[] = $site;
+       }
+
+}
diff --git a/includes/site/SiteList.php b/includes/site/SiteList.php
new file mode 100644 (file)
index 0000000..f9c01f5
--- /dev/null
@@ -0,0 +1,122 @@
+<?php
+
+/**
+ * Interface for lists of Site objects.
+ *
+ * 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.
+ *
+ * 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
+ *
+ * @since 1.20
+ *
+ * @file
+ * @ingroup Site
+ *
+ * @licence GNU GPL v2+
+ * @author Jeroen De Dauw < jeroendedauw@gmail.com >
+ */
+interface SiteList extends Countable, Traversable, Serializable, ArrayAccess {
+
+       /**
+        * Returns all the global site identifiers.
+        * Optionally only those belonging to the specified group.
+        *
+        * @since 1.20
+        *
+        * @return array
+        */
+       public function getGlobalIdentifiers();
+
+       /**
+        * Returns if the list contains the site with the provided global site identifier.
+        *
+        * @param string $globalSiteId
+        *
+        * @return boolean
+        */
+       public function hasSite( $globalSiteId );
+
+       /**
+        * Returns the Site with the provided global site identifier.
+        * The site needs to exist, so if not sure, call hasGlobalId first.
+        *
+        * @since 1.20
+        *
+        * @param string $globalSiteId
+        *
+        * @return Site
+        */
+       public function getSite( $globalSiteId );
+
+       /**
+        * Removes the site with the specified global site identifier.
+        * The site needs to exist, so if not sure, call hasGlobalId first.
+        *
+        * @since 1.20
+        *
+        * @param string $globalSiteId
+        */
+       public function removeSite( $globalSiteId );
+
+       /**
+        * Returns if the list contains the site with the provided site id.
+        *
+        * @param integer $id
+        *
+        * @return boolean
+        */
+       public function hasInternalId( $id );
+
+       /**
+        * Returns the Site with the provided site id.
+        * The site needs to exist, so if not sure, call has first.
+        *
+        * @since 1.20
+        *
+        * @param integer $id
+        *
+        * @return Site
+        */
+       public function getSiteByInternalId( $id );
+
+       /**
+        * Removes the site with the specified site id.
+        * The site needs to exist, so if not sure, call has first.
+        *
+        * @since 1.20
+        *
+        * @param integer $id
+        */
+       public function removeSiteByInternalId( $id );
+
+       /**
+        * Sets a site in the list. If the site was not there,
+        * it will be added. If it was, it will be updated.
+        *
+        * @since 1.20
+        *
+        * @param Site $site
+        */
+       public function setSite( Site $site );
+
+       /**
+        * Returns if the site list contains no sites.
+        *
+        * @since 1.20
+        *
+        * @return boolean
+        */
+       public function isEmpty();
+
+}
\ No newline at end of file
diff --git a/includes/site/SiteObject.php b/includes/site/SiteObject.php
new file mode 100644 (file)
index 0000000..688b970
--- /dev/null
@@ -0,0 +1,537 @@
+<?php
+
+/**
+ * Class representing a single site.
+ *
+ * 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.
+ *
+ * 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
+ *
+ * @since 1.20
+ *
+ * @file
+ * @ingroup Site
+ *
+ * @licence GNU GPL v2+
+ * @author Jeroen De Dauw < jeroendedauw@gmail.com >
+ * @author Daniel Werner
+ */
+class SiteObject extends ORMRow implements Site {
+
+       const PATH_LINK = 'link';
+
+       /**
+        * Holds the local ids for this site.
+        * You can obtain them via @see getLocalIds
+        *
+        * @since 1.20
+        *
+        * @var array|false
+        */
+       protected $localIds = false;
+
+       /**
+        * @see Site::getGlobalId
+        *
+        * @since 1.20
+        *
+        * @return string
+        */
+       public function getGlobalId() {
+               return $this->getField( 'global_key' );
+       }
+
+       /**
+        * @see Site::setGlobalId
+        *
+        * @since 1.20
+        *
+        * @param string $globalId
+        */
+       public function setGlobalId( $globalId ) {
+               $this->setField( 'global_key', $globalId );
+       }
+
+       /**
+        * @see Site::getType
+        *
+        * @since 1.20
+        *
+        * @return string
+        */
+       public function getType() {
+               return $this->getField( 'type' );
+       }
+
+       /**
+        * @see Site::setType
+        *
+        * @since 1.20
+        *
+        * @param string $type
+        */
+       public function setType( $type ) {
+               $this->setField( 'type', $type );
+       }
+
+       /**
+        * @see Site::getGroup
+        *
+        * @since 1.20
+        *
+        * @return string
+        */
+       public function getGroup() {
+               return $this->getField( 'group' );
+       }
+
+       /**
+        * @see Site::setGroup
+        *
+        * @since 1.20
+        *
+        * @param string $group
+        */
+       public function setGroup( $group ) {
+               $this->setField( 'group', $group );
+       }
+
+       /**
+        * @see Site::getSource
+        *
+        * @since 1.20
+        *
+        * @return string
+        */
+       public function getSource() {
+               return $this->getField( 'source' );
+       }
+
+       /**
+        * @see Site::setSource
+        *
+        * @since 1.20
+        *
+        * @param string $source
+        */
+       public function setSource( $source ) {
+               $this->setField( 'source', $source );
+       }
+
+       /**
+        * @see Site::getDomain
+        *
+        * @since 1.20
+        *
+        * @return string|false
+        */
+       public function getDomain() {
+               $path = $this->getLinkPath();
+
+               if ( $path === false ) {
+                       return false;
+               }
+
+               return parse_url( $path, PHP_URL_HOST );
+       }
+
+       /**
+        * @see Site::getProtocol
+        *
+        * @since 1.20
+        *
+        * @return string|false
+        */
+       public function getProtocol() {
+               $path = $this->getLinkPath();
+
+               if ( $path === false ) {
+                       return false;
+               }
+
+               return parse_url( $path, PHP_URL_SCHEME );
+       }
+
+       /**
+        * Sets the path used to construct links with.
+        * @see Site::setLinkPath
+        *
+        * @param string $fullUrl
+        *
+        * @since 1.20
+        *
+        * @throws MWException
+        */
+       public function setLinkPath( $fullUrl ) {
+               $type = $this->getLinkPathType();
+
+               if ( $type === false ) {
+                       throw new MWException( "This SiteObject does not support link paths." );
+               }
+
+               $this->setPath( $type, $fullUrl );
+       }
+
+       /**
+        * Returns the path path used to construct links with or false if there is no such path.
+        *
+        * @see Site::getLinkPath
+        *
+        * @return string|false
+        */
+       public function getLinkPath() {
+               $type = $this->getLinkPathType();
+               return $type === false ? false : $this->getPath( $type );
+       }
+
+       /**
+        * @see Site::getLinkPathType
+        *
+        * Returns the main path type, that is the type of the path that should generally be used to construct links
+        * to the target site.
+        *
+        * This default implementation returns SiteObject::PATH_LINK as the default path type. Subclasses can override this
+        * to define a different default path type, or return false to disable site links.
+        *
+        * @since 1.20
+        *
+        * @return string|false
+        */
+       public function getLinkPathType() {
+               return self::PATH_LINK;
+       }
+
+       /**
+        * @see Site::getPageUrl
+        *
+        * This implementation returns a URL constructed using the path returned by getLinkPath().
+        *
+        * @since 1.20
+        *
+        * @param bool|String $pageName
+        *
+        * @return string|false
+        */
+       public function getPageUrl( $pageName = false ) {
+               $url = $this->getLinkPath();
+
+               if ( $url === false ) {
+                       return false;
+               }
+
+               if ( $pageName !== false ) {
+                       $url = str_replace( '$1', rawurlencode( $pageName ), $url ) ;
+               }
+
+               return $url;
+       }
+
+       /**
+        * Returns $pageName without changes.
+        * Subclasses may override this to apply some kind of normalization.
+        *
+        * @see Site::normalizePageName
+        *
+        * @since 1.20
+        *
+        * @param string $pageName
+        *
+        * @return string
+        */
+       public function normalizePageName( $pageName ) {
+               return $pageName;
+       }
+
+       /**
+        * Returns the value of a type specific field, or the value
+        * of the $default parameter in case it's not set.
+        *
+        * @since 1.20
+        *
+        * @param string $fieldName
+        * @param mixed $default
+        *
+        * @return array
+        */
+       protected function getExtraData( $fieldName, $default = null ) {
+               $data = $this->getField( 'data', array() );
+               return array_key_exists( $fieldName,$data ) ? $data[$fieldName] : $default;
+       }
+
+       /**
+        * Sets the value of a type specific field.
+        * @since 1.20
+        *
+        * @param string $fieldName
+        * @param mixed $value
+        */
+       protected function setExtraData( $fieldName, $value = null ) {
+               $data = $this->getField( 'data', array() );
+               $data[$fieldName] = $value;
+               $this->setField( 'data', $data );
+       }
+
+       /**
+        * @see Site::getLanguageCode
+        *
+        * @since 1.20
+        *
+        * @return string|false
+        */
+       public function getLanguageCode() {
+               return $this->getField( 'language', false );
+       }
+
+       /**
+        * @see Site::setLanguageCode
+        *
+        * @since 1.20
+        *
+        * @param string $languageCode
+        */
+       public function setLanguageCode( $languageCode ) {
+               $this->setField( 'language', $languageCode );
+       }
+
+       /**
+        * Returns the local identifiers of this site.
+        *
+        * @since 1.20
+        *
+        * @param string $type
+        *
+        * @return array
+        */
+       protected function getLocalIds( $type ) {
+               if ( $this->localIds === false ) {
+                       $this->loadLocalIds();
+               }
+
+               return array_key_exists( $type, $this->localIds ) ? $this->localIds[$type] : array();
+       }
+
+       /**
+        * Loads the local ids for the site.
+        *
+        * @since 1.20
+        */
+       protected function loadLocalIds() {
+               $dbr = wfGetDB( $this->getTable()->getReadDb() );
+
+               $ids = $dbr->select(
+                       'site_identifiers',
+                       array(
+                               'si_type',
+                               'si_key',
+                       ),
+                       array(
+                               'si_site' => $this->getId(),
+                       ),
+                       __METHOD__
+               );
+
+               $this->localIds = array();
+
+               foreach ( $ids as $id ) {
+                       $this->addLocalId( $id->si_type, $id->si_key );
+               }
+       }
+
+       /**
+        * Adds a local identifier.
+        *
+        * @since 1.20
+        *
+        * @param string $type
+        * @param string $identifier
+        */
+       public function addLocalId( $type, $identifier ) {
+               if ( $this->localIds === false ) {
+                       $this->localIds = array();
+               }
+
+               if ( !array_key_exists( $type, $this->localIds ) ) {
+                       $this->localIds[$type] = array();
+               }
+
+               if ( !in_array( $identifier, $this->localIds[$type] ) ) {
+                       $this->localIds[$type][] = $identifier;
+               }
+       }
+
+       /**
+        * @see Site::addInterwikiId
+        *
+        * @since 1.20
+        *
+        * @param string $identifier
+        */
+       public function addInterwikiId( $identifier ) {
+               $this->addLocalId( 'interwiki', $identifier );
+       }
+
+       /**
+        * @see Site::addNavigationId
+        *
+        * @since 1.20
+        *
+        * @param string $identifier
+        */
+       public function addNavigationId( $identifier ) {
+               $this->addLocalId( 'equivalent', $identifier );
+       }
+
+       /**
+        * @see Site::getInterwikiIds
+        *
+        * @since 1.20
+        *
+        * @return array of string
+        */
+       public function getInterwikiIds() {
+               return $this->getLocalIds( 'interwiki' );
+       }
+
+       /**
+        * @see Site::getNavigationIds
+        *
+        * @since 1.20
+        *
+        * @return array of string
+        */
+       public function getNavigationIds() {
+               return $this->getLocalIds( 'equivalent' );
+       }
+
+       /**
+        * @see Site::getInternalId
+        *
+        * @since 1.20
+        *
+        * @return integer
+        */
+       public function getInternalId() {
+               return $this->getId();
+       }
+
+       /**
+        * @see ORMRow::save
+        * @see Site::save
+        *
+        * @since 1.20
+        *
+        * @param string|null $functionName
+        *
+        * @return boolean Success indicator
+        */
+       public function save( $functionName = null ) {
+               $dbw = wfGetDB( DB_MASTER );
+
+               $trx = $dbw->trxLevel();
+
+               if ( $trx == 0 ) {
+                       $dbw->begin( __METHOD__ );
+               }
+
+               $this->setField( 'protocol', $this->getProtocol() );
+               $this->setField( 'domain', strrev( $this->getDomain() ) . '.' );
+
+               $existedAlready = $this->hasIdField();
+
+               $success = parent::save( $functionName );
+
+               if ( $success && $existedAlready ) {
+                       $dbw->delete(
+                               'site_identifiers',
+                               array( 'si_site' => $this->getId() ),
+                               __METHOD__
+                       );
+               }
+
+               if ( $success && $this->localIds !== false ) {
+                       foreach ( $this->localIds as $type => $ids ) {
+                               foreach ( $ids as $id ) {
+                                       $dbw->insert(
+                                               'site_identifiers',
+                                               array(
+                                                       'si_site' => $this->getId(),
+                                                       'si_type' => $type,
+                                                       'si_key' => $id,
+                                               ),
+                                               __METHOD__
+                                       );
+                               }
+                       }
+               }
+
+               if ( $trx == 0 ) {
+                       $dbw->commit( __METHOD__ );
+               }
+
+               return $success;
+       }
+
+       /**
+        * @see Site::setPath
+        *
+        * @since 1.20
+        *
+        * @param string $pathType
+        * @param string $fullUrl
+        */
+       public function setPath( $pathType, $fullUrl ) {
+               $paths = $this->getExtraData( 'paths', array() );
+               $paths[$pathType] = $fullUrl;
+               $this->setExtraData( 'paths', $paths );
+       }
+
+       /**
+        * @see Sitres::getPath
+        *
+        * @since 1.20
+        *
+        * @param string $pathType
+        *
+        * @return string|false
+        */
+       public function getPath( $pathType ) {
+               $paths = $this->getExtraData( 'paths', array() );
+               return array_key_exists( $pathType, $paths ) ? $paths[$pathType] : false;
+       }
+
+       /**
+        * @see Sitres::getAll
+        *
+        * @since 1.20
+        *
+        * @return array of string
+        */
+       public function getAllPaths() {
+               return $this->getExtraData( 'paths', array() );
+       }
+
+       /**
+        * @see Sitres::removePath
+        *
+        * @since 1.20
+        *
+        * @param string $pathType
+        */
+       public function removePath( $pathType ) {
+               $paths = $this->getExtraData( 'paths', array() );
+               unset( $paths[$pathType] );
+               $this->setExtraData( 'paths', $paths );
+       }
+
+}
diff --git a/includes/site/Sites.php b/includes/site/Sites.php
new file mode 100644 (file)
index 0000000..5e9ce21
--- /dev/null
@@ -0,0 +1,194 @@
+<?php
+
+/**
+ * Represents the site configuration of a wiki.
+ * Holds a list of sites (ie SiteList) and takes care
+ * of retrieving and caching site information when appropriate.
+ *
+ * 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.
+ *
+ * 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
+ *
+ * @since 1.20
+ *
+ * @file
+ * @ingroup Site
+ *
+ * @licence GNU GPL v2+
+ * @author Jeroen De Dauw < jeroendedauw@gmail.com >
+ */
+class Sites {
+
+       /**
+        * @since 1.20
+        * @var SiteList|false
+        */
+       protected $sites = false;
+
+       /**
+        * Constructor.
+        *
+        * @since 1.20
+        */
+       protected function __construct() {}
+
+       /**
+        * Returns an instance of Sites.
+        *
+        * @since 1.20
+        *
+        * @return Sites
+        */
+       public static function singleton() {
+               static $instance = false;
+
+               if ( $instance === false ) {
+                       $instance = new static();
+               }
+
+               return $instance;
+       }
+
+       /**
+        * Factory for creating new site objects.
+        *
+        * @since 1.20
+        *
+        * @param string|false $globalId
+        *
+        * @return Site
+        */
+       public static function newSite( $globalId = false ) {
+               /**
+                * @var Site $site
+                */
+               $site = SitesTable::singleton()->newRow( array(), true );
+
+               if ( $globalId !== false ) {
+                       $site->setGlobalId( $globalId );
+               }
+
+               return $site;
+       }
+
+       /**
+        * Returns a list of all sites. By default this site is
+        * fetched from the cache, which can be changed to loading
+        * the list from the database using the $useCache parameter.
+        *
+        * @since 1.20
+        *
+        * @param string $source either 'cache' or 'recache'
+        *
+        * @return SiteList
+        */
+       public function getSites( $source = 'cache' ) {
+               if ( $source === 'cache' ) {
+                       if ( $this->sites === false ) {
+                               $cache = wfGetMainCache();
+                               $sites = $cache->get( 'sites-cache' );
+
+                               if ( is_object( $sites ) ) {
+                                       $this->sites = $sites;
+                               }
+                               else {
+                                       $this->loadSites();
+                               }
+                       }
+               }
+               else {
+                       $this->loadSites();
+               }
+
+               return $this->sites;
+       }
+
+       /**
+        * Returns a list of sites in the given group. Calling getGroup() on any of
+        * the sites in the resulting SiteList shall return $group.
+        *
+        * @since 1.20
+        *
+        * @param string $group th group to get.
+        *
+        * @return SiteList
+        */
+       public function getSiteGroup( $group ) {
+               $sites = self::getSites();
+
+               $siteGroup = new SiteArray();
+
+               /* @var Site $site */
+               foreach ( $sites as $site ) {
+                       if ( $site->getGroup() == $group ) {
+                               $siteGroup->append( $site );
+                       }
+               }
+
+               return $siteGroup;
+       }
+
+       /**
+        * Fetches the site from the database and loads them into the sites field.
+        *
+        * @since 1.20
+        */
+       protected function loadSites() {
+               $this->sites = new SiteArray( SitesTable::singleton()->select() );
+
+               // Batch load the local site identifiers.
+               $dbr = wfGetDB( SitesTable::singleton()->getReadDb() );
+
+               $ids = $dbr->select(
+                       'site_identifiers',
+                       array(
+                               'si_site',
+                               'si_type',
+                               'si_key',
+                       ),
+                       array(),
+                       __METHOD__
+               );
+
+               foreach ( $ids as $id ) {
+                       if ( $this->sites->hasInternalId( $id->si_site ) ) {
+                               $site = $this->sites->getSiteByInternalId( $id->si_site );
+                               $site->addLocalId( $id->si_type, $id->si_key );
+                               $this->sites->setSite( $site );
+                       }
+               }
+
+               $cache = wfGetMainCache();
+               $cache->set( 'sites-cache', $this->sites );
+       }
+
+       /**
+        * Returns the site with provided global id, or false if there is no such site.
+        *
+        * @since 1.20
+        *
+        * @param string $globalId
+        * @param string $source
+        *
+        * @return Site|false
+        */
+       public function getSite( $globalId, $source = 'cache' ) {
+               if ( $source === 'cache' && $this->sites !== false ) {
+                       return $this->sites->hasSite( $globalId ) ? $this->sites->getSite( $globalId ) : false;
+               }
+
+               return SitesTable::singleton()->selectRow( null, array( 'global_key' => $globalId ) );
+       }
+
+}
diff --git a/includes/site/SitesTable.php b/includes/site/SitesTable.php
new file mode 100644 (file)
index 0000000..9994be7
--- /dev/null
@@ -0,0 +1,135 @@
+<?php
+
+/**
+ * Represents the sites database table.
+ * All access to this table should be done through this class.
+ *
+ * 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.
+ *
+ * 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
+ *
+ * @since 1.20
+ *
+ * @file
+ * @ingroup Site
+ *
+ * @licence GNU GPL v2+
+ * @author Jeroen De Dauw < jeroendedauw@gmail.com >
+ */
+class SitesTable extends ORMTable {
+
+       /**
+        * @see IORMTable::getName()
+        * @since 1.20
+        * @return string
+        */
+       public function getName() {
+               return 'sites';
+       }
+
+       /**
+        * @see IORMTable::getFieldPrefix()
+        * @since 1.20
+        * @return string
+        */
+       public function getFieldPrefix() {
+               return 'site_';
+       }
+
+       /**
+        * @see IORMTable::getRowClass()
+        * @since 1.20
+        * @return string
+        */
+       public function getRowClass() {
+               return 'SiteObject';
+       }
+
+       /**
+        * @see IORMTable::getFields()
+        * @since 1.20
+        * @return array
+        */
+       public function getFields() {
+               return array(
+                       'id' => 'id',
+
+                       // Site data
+                       'global_key' => 'str',
+                       'type' => 'str',
+                       'group' => 'str',
+                       'source' => 'str',
+                       'language' => 'str',
+                       'protocol' => 'str',
+                       'domain' => 'str',
+                       'data' => 'array',
+
+                       // Site config
+                       'forward' => 'bool',
+                       'config' => 'array',
+               );
+       }
+
+       /**
+        * @see IORMTable::getDefaults()
+        * @since 1.20
+        * @return array
+        */
+       public function getDefaults() {
+               return array(
+                       'type' => Site::TYPE_UNKNOWN,
+                       'group' => Site::GROUP_NONE,
+                       'source' => Site::SOURCE_LOCAL,
+                       'data' => array(),
+
+                       'forward' => false,
+                       'config' => array(),
+               );
+       }
+
+       /**
+        * Returns the class name for the provided site type.
+        *
+        * @since 1.20
+        *
+        * @param integer $siteType
+        *
+        * @return string
+        */
+       protected static function getClassForType( $siteType ) {
+               global $wgSiteTypes;
+               return array_key_exists( $siteType, $wgSiteTypes ) ? $wgSiteTypes[$siteType] : 'SiteObject';
+       }
+
+       /**
+        * Factory method to construct a new Site instance.
+        *
+        * @since 1.20
+        *
+        * @param array $data
+        * @param boolean $loadDefaults
+        *
+        * @return Site
+        */
+       public function newRow( array $data, $loadDefaults = false ) {
+               if ( !array_key_exists( 'type', $data ) ) {
+                       $data['type'] = Site::TYPE_UNKNOWN;
+               }
+
+               $class = static::getClassForType( $data['type'] );
+
+               return new $class( $this, $data, $loadDefaults );
+       }
+
+}
\ No newline at end of file
diff --git a/maintenance/archives/patch-sites.sql b/maintenance/archives/patch-sites.sql
new file mode 100644 (file)
index 0000000..8839274
--- /dev/null
@@ -0,0 +1,71 @@
+-- Patch to add the sites and site_identifiers tables.
+-- Licence: GNU GPL v2+
+-- Author: Jeroen De Dauw < jeroendedauw@gmail.com >
+
+
+-- Holds all the sites known to the wiki.
+CREATE TABLE IF NOT EXISTS /*_*/sites (
+-- Numeric id of the site
+  site_id                    INT UNSIGNED        NOT NULL PRIMARY KEY AUTO_INCREMENT,
+
+  -- Global identifier for the site, ie 'enwiktionary'
+  site_global_key            varbinary(32)       NOT NULL,
+
+  -- Type of the site, ie 'mediawiki'
+  site_type                  varbinary(32)       NOT NULL,
+
+  -- Group of the site, ie 'wikipedia'
+  site_group                 varbinary(32)       NOT NULL,
+
+  -- Source of the site data, ie 'local', 'wikidata', 'my-magical-repo'
+  site_source                varbinary(32)       NOT NULL,
+
+  -- Language code of the sites primary language.
+  site_language              varbinary(32)       NOT NULL,
+
+  -- Protocol of the site, ie 'http://', 'irc://', '//'
+  -- This field is an index for lookups and is build from type specific data in site_data.
+  site_protocol              varbinary(32)       NOT NULL,
+
+  -- Domain of the site in reverse order, ie 'org.mediawiki.www.'
+  -- This field is an index for lookups and is build from type specific data in site_data.
+  site_domain                VARCHAR(255)        NOT NULL,
+
+  -- Type dependent site data.
+  site_data                  BLOB                NOT NULL,
+
+  -- If site.tld/path/key:pageTitle should forward users to  the page on
+  -- the actual site, where "key" is the local identifier.
+  site_forward              bool                NOT NULL,
+
+  -- Type dependent site config.
+  -- For instance if template transclusion should be allowed if it's a MediaWiki.
+  site_config               BLOB                NOT NULL
+) /*$wgDBTableOptions*/;
+
+CREATE UNIQUE INDEX /*i*/sites_global_key ON /*_*/sites (site_global_key);
+CREATE INDEX /*i*/sites_type ON /*_*/sites (site_type);
+CREATE INDEX /*i*/sites_group ON /*_*/sites (site_group);
+CREATE INDEX /*i*/sites_source ON /*_*/sites (site_source);
+CREATE INDEX /*i*/sites_language ON /*_*/sites (site_language);
+CREATE INDEX /*i*/sites_protocol ON /*_*/sites (site_protocol);
+CREATE INDEX /*i*/sites_domain ON /*_*/sites (site_domain);
+CREATE INDEX /*i*/sites_forward ON /*_*/sites (site_forward);
+
+
+
+-- Links local site identifiers to their corresponding site.
+CREATE TABLE IF NOT EXISTS /*_*/site_identifiers (
+  -- Key on site.site_id
+  si_site                    INT UNSIGNED        NOT NULL,
+
+  -- local key type, ie 'interwiki' or 'langlink'
+  si_type                    varbinary(32)       NOT NULL,
+
+  -- local key value, ie 'en' or 'wiktionary'
+  si_key                     varbinary(32)       NOT NULL
+) /*$wgDBTableOptions*/;
+
+CREATE UNIQUE INDEX /*i*/site_ids_type ON /*_*/site_identifiers (si_type, si_key);
+CREATE INDEX /*i*/site_ids_site ON /*_*/site_identifiers (si_site);
+CREATE INDEX /*i*/site_ids_key ON /*_*/site_identifiers (si_key);
\ No newline at end of file
diff --git a/maintenance/sqlite/archives/patch-sites.sql b/maintenance/sqlite/archives/patch-sites.sql
new file mode 100644 (file)
index 0000000..8839274
--- /dev/null
@@ -0,0 +1,71 @@
+-- Patch to add the sites and site_identifiers tables.
+-- Licence: GNU GPL v2+
+-- Author: Jeroen De Dauw < jeroendedauw@gmail.com >
+
+
+-- Holds all the sites known to the wiki.
+CREATE TABLE IF NOT EXISTS /*_*/sites (
+-- Numeric id of the site
+  site_id                    INT UNSIGNED        NOT NULL PRIMARY KEY AUTO_INCREMENT,
+
+  -- Global identifier for the site, ie 'enwiktionary'
+  site_global_key            varbinary(32)       NOT NULL,
+
+  -- Type of the site, ie 'mediawiki'
+  site_type                  varbinary(32)       NOT NULL,
+
+  -- Group of the site, ie 'wikipedia'
+  site_group                 varbinary(32)       NOT NULL,
+
+  -- Source of the site data, ie 'local', 'wikidata', 'my-magical-repo'
+  site_source                varbinary(32)       NOT NULL,
+
+  -- Language code of the sites primary language.
+  site_language              varbinary(32)       NOT NULL,
+
+  -- Protocol of the site, ie 'http://', 'irc://', '//'
+  -- This field is an index for lookups and is build from type specific data in site_data.
+  site_protocol              varbinary(32)       NOT NULL,
+
+  -- Domain of the site in reverse order, ie 'org.mediawiki.www.'
+  -- This field is an index for lookups and is build from type specific data in site_data.
+  site_domain                VARCHAR(255)        NOT NULL,
+
+  -- Type dependent site data.
+  site_data                  BLOB                NOT NULL,
+
+  -- If site.tld/path/key:pageTitle should forward users to  the page on
+  -- the actual site, where "key" is the local identifier.
+  site_forward              bool                NOT NULL,
+
+  -- Type dependent site config.
+  -- For instance if template transclusion should be allowed if it's a MediaWiki.
+  site_config               BLOB                NOT NULL
+) /*$wgDBTableOptions*/;
+
+CREATE UNIQUE INDEX /*i*/sites_global_key ON /*_*/sites (site_global_key);
+CREATE INDEX /*i*/sites_type ON /*_*/sites (site_type);
+CREATE INDEX /*i*/sites_group ON /*_*/sites (site_group);
+CREATE INDEX /*i*/sites_source ON /*_*/sites (site_source);
+CREATE INDEX /*i*/sites_language ON /*_*/sites (site_language);
+CREATE INDEX /*i*/sites_protocol ON /*_*/sites (site_protocol);
+CREATE INDEX /*i*/sites_domain ON /*_*/sites (site_domain);
+CREATE INDEX /*i*/sites_forward ON /*_*/sites (site_forward);
+
+
+
+-- Links local site identifiers to their corresponding site.
+CREATE TABLE IF NOT EXISTS /*_*/site_identifiers (
+  -- Key on site.site_id
+  si_site                    INT UNSIGNED        NOT NULL,
+
+  -- local key type, ie 'interwiki' or 'langlink'
+  si_type                    varbinary(32)       NOT NULL,
+
+  -- local key value, ie 'en' or 'wiktionary'
+  si_key                     varbinary(32)       NOT NULL
+) /*$wgDBTableOptions*/;
+
+CREATE UNIQUE INDEX /*i*/site_ids_type ON /*_*/site_identifiers (si_type, si_key);
+CREATE INDEX /*i*/site_ids_site ON /*_*/site_identifiers (si_site);
+CREATE INDEX /*i*/site_ids_key ON /*_*/site_identifiers (si_key);
\ No newline at end of file
index 4a707fd..51115f1 100644 (file)
@@ -1498,4 +1498,69 @@ CREATE TABLE /*_*/config (
 -- Should cover *most* configuration - strings, ints, bools, etc.
 CREATE INDEX /*i*/cf_name_value ON /*_*/config (cf_name,cf_value(255));
 
+-- Holds all the sites known to the wiki.
+CREATE TABLE /*_*/sites (
+-- Numeric id of the site
+  site_id                    INT UNSIGNED        NOT NULL PRIMARY KEY AUTO_INCREMENT,
+
+  -- Global identifier for the site, ie 'enwiktionary'
+  site_global_key            varbinary(32)       NOT NULL,
+
+  -- Type of the site, ie 'mediawiki'
+  site_type                  varbinary(32)       NOT NULL,
+
+  -- Group of the site, ie 'wikipedia'
+  site_group                 varbinary(32)       NOT NULL,
+
+  -- Source of the site data, ie 'local', 'wikidata', 'my-magical-repo'
+  site_source                varbinary(32)       NOT NULL,
+
+  -- Language code of the sites primary language.
+  site_language              varbinary(32)       NOT NULL,
+
+  -- Protocol of the site, ie 'http://', 'irc://', '//'
+  -- This field is an index for lookups and is build from type specific data in site_data.
+  site_protocol              varbinary(32)       NOT NULL,
+
+  -- Domain of the site in reverse order, ie 'org.mediawiki.www.'
+  -- This field is an index for lookups and is build from type specific data in site_data.
+  site_domain                VARCHAR(255)        NOT NULL,
+
+  -- Type dependent site data.
+  site_data                  BLOB                NOT NULL,
+
+  -- If site.tld/path/key:pageTitle should forward users to  the page on
+  -- the actual site, where "key" is the local identifier.
+  site_forward              bool                NOT NULL,
+
+  -- Type dependent site config.
+  -- For instance if template transclusion should be allowed if it's a MediaWiki.
+  site_config               BLOB                NOT NULL
+) /*$wgDBTableOptions*/;
+
+CREATE UNIQUE INDEX /*i*/sites_global_key ON /*_*/sites (site_global_key);
+CREATE INDEX /*i*/sites_type ON /*_*/sites (site_type);
+CREATE INDEX /*i*/sites_group ON /*_*/sites (site_group);
+CREATE INDEX /*i*/sites_source ON /*_*/sites (site_source);
+CREATE INDEX /*i*/sites_language ON /*_*/sites (site_language);
+CREATE INDEX /*i*/sites_protocol ON /*_*/sites (site_protocol);
+CREATE INDEX /*i*/sites_domain ON /*_*/sites (site_domain);
+CREATE INDEX /*i*/sites_forward ON /*_*/sites (site_forward);
+
+-- Links local site identifiers to their corresponding site.
+CREATE TABLE /*_*/site_identifiers (
+  -- Key on site.site_id
+  si_site                    INT UNSIGNED        NOT NULL,
+
+  -- local key type, ie 'interwiki' or 'langlink'
+  si_type                    varbinary(32)       NOT NULL,
+
+  -- local key value, ie 'en' or 'wiktionary'
+  si_key                     varbinary(32)       NOT NULL
+) /*$wgDBTableOptions*/;
+
+CREATE UNIQUE INDEX /*i*/site_ids_type ON /*_*/site_identifiers (si_type, si_key);
+CREATE INDEX /*i*/site_ids_site ON /*_*/site_identifiers (si_site);
+CREATE INDEX /*i*/site_ids_key ON /*_*/site_identifiers (si_key);
+
 -- vim: sw=2 sts=2 et
index 70fce11..398ad2d 100644 (file)
@@ -58,7 +58,7 @@ abstract class GenericArrayObjectTest extends MediaWikiTestCase {
                $instances = array();
 
                foreach ( $this->elementInstancesProvider() as $elementInstances ) {
-                       $instances[] = $this->getNew( $elementInstances );
+                       $instances[] = $this->getNew( $elementInstances[0] );
                }
 
                return $this->arrayWrap( $instances );
diff --git a/tests/phpunit/includes/site/MediaWikiSiteTest.php b/tests/phpunit/includes/site/MediaWikiSiteTest.php
new file mode 100644 (file)
index 0000000..db5761b
--- /dev/null
@@ -0,0 +1,108 @@
+<?php
+
+/**
+ * Tests for the MediaWikiSite class.
+ *
+ * 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.
+ *
+ * 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
+ * @since 1.20
+ *
+ * @ingroup Site
+ * @ingroup Test
+ *
+ * @group Site
+ * @group Database
+ *
+ * @licence GNU GPL v2+
+ * @author Jeroen De Dauw < jeroendedauw@gmail.com >
+ */
+class MediaWikiSiteTest extends SiteObjectTest {
+
+       public function setUp() {
+               parent::setUp();
+
+               static $hasSites = false;
+
+               if ( !$hasSites ) {
+                       TestSites::insertIntoDb();
+                       $hasSites = true;
+               }
+       }
+
+       public function testFactoryConstruction() {
+               $this->assertInstanceOf( 'MediaWikiSite', MediaWikiSite::newFromGlobalId( 'enwiki' ) );
+               $this->assertInstanceOf( 'Site', MediaWikiSite::newFromGlobalId( 'enwiki' ) );
+               $this->assertInstanceOf( 'MediaWikiSite', SitesTable::singleton()->newRow( array( 'type' => Site::TYPE_MEDIAWIKI ) ) );
+       }
+
+       public function testNormalizePageTitle() {
+               $site = MediaWikiSite::newFromGlobalId( 'enwiki' );
+
+               //NOTE: this does not actually call out to the enwiki site to perform the normalization,
+               //      but uses a local Title object to do so. This is hardcoded on SiteLink::normalizePageTitle
+               //      for the case that MW_PHPUNIT_TEST is set.
+               $this->assertEquals( 'Foo', $site->normalizePageName( ' foo ' ) );
+       }
+
+       public function fileUrlProvider() {
+               return array(
+                       // url, filepath, path arg, expected
+                       array( 'https://en.wikipedia.org', '/w/$1', 'api.php', 'https://en.wikipedia.org/w/api.php' ),
+                       array( 'https://en.wikipedia.org', '/w/', 'api.php', 'https://en.wikipedia.org/w/' ),
+                       array( 'https://en.wikipedia.org', '/foo/page.php?name=$1', 'api.php', 'https://en.wikipedia.org/foo/page.php?name=api.php' ),
+                       array( 'https://en.wikipedia.org', '/w/$1', '', 'https://en.wikipedia.org/w/' ),
+                       array( 'https://en.wikipedia.org', '/w/$1', 'foo/bar/api.php', 'https://en.wikipedia.org/w/foo/bar/api.php' ),
+               );
+       }
+
+       /**
+        * @dataProvider fileUrlProvider
+        */
+       public function testGetFileUrl( $url, $filePath, $pathArgument, $expected ) {
+               $site = MediaWikiSite::newFromGlobalId( 'enwiki' );
+
+               $site->setFilePath( $url . $filePath );
+
+               $this->assertEquals( $expected, $site->getFileUrl( $pathArgument ) );
+       }
+
+       public function provideGetPageUrl() {
+               return array(
+                       // path, page, expected substring
+                       array( 'http://acme.test/wiki/$1', 'Berlin', '/wiki/Berlin' ),
+                       array( 'http://acme.test/wiki/', 'Berlin', '/wiki/' ),
+                       array( 'http://acme.test/w/index.php?title=$1', 'Berlin', '/w/index.php?title=Berlin' ),
+                       array( 'http://acme.test/wiki/$1', '', '/wiki/' ),
+                       array( 'http://acme.test/wiki/$1', 'Berlin/sub page', '/wiki/Berlin/sub_page' ),
+                       array( 'http://acme.test/wiki/$1', 'Cork (city)   ', '/Cork_(city)' ),
+                       array( 'http://acme.test/wiki/$1', 'M&M', '/wiki/M%26M' ),
+               );
+       }
+
+       /**
+        * @dataProvider provideGetPageUrl
+        */
+       public function testGetPageUrl( $path, $page, $expected ) {
+               /* @var MediaWikiSite $site */
+               $site = MediaWikiSite::newFromGlobalId( 'enwiki' );
+
+               $site->setLinkPath( $path );
+               $this->assertContains( $path, $site->getPageUrl() );
+               $this->assertContains( $expected, $site->getPageUrl( $page ) );
+       }
+
+}
diff --git a/tests/phpunit/includes/site/SiteArrayTest.php b/tests/phpunit/includes/site/SiteArrayTest.php
new file mode 100644 (file)
index 0000000..c590b7d
--- /dev/null
@@ -0,0 +1,68 @@
+<?php
+
+/**
+ * Tests for the SiteArray class.
+ * The tests for methods defined in the SiteList interface are in SiteListTest.
+ *
+ * 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.
+ *
+ * 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
+ *Both
+ * Bith
+ * @file
+ * @since 1.20
+ *
+ * @ingroup Site
+ * @ingroup Test
+ *
+ * @group Site
+ *
+ * @licence GNU GPL v2+
+ * @author Jeroen De Dauw < jeroendedauw@gmail.com >
+ */
+class SiteArrayTest extends GenericArrayObjectTest {
+
+       /**
+        * @see GenericArrayObjectTest::elementInstancesProvider
+        *
+        * @since 1.20
+        *
+        * @return array
+        */
+       public function elementInstancesProvider() {
+               $sites = TestSites::getSites();
+
+               $siteArrays = array();
+
+               $siteArrays[] = $sites;
+
+               $siteArrays[] = array( array_shift( $sites ) );
+
+               $siteArrays[] = array( array_shift( $sites ), array_shift( $sites ) );
+
+               return $this->arrayWrap( $siteArrays );
+       }
+
+       /**
+        * @see GenericArrayObjectTest::getInstanceClass
+        *
+        * @since 1.20
+        *
+        * @return array
+        */
+       public function getInstanceClass() {
+               return 'SiteArray';
+       }
+
+}
\ No newline at end of file
diff --git a/tests/phpunit/includes/site/SiteListTest.php b/tests/phpunit/includes/site/SiteListTest.php
new file mode 100644 (file)
index 0000000..ccb4c5a
--- /dev/null
@@ -0,0 +1,168 @@
+<?php
+
+/**
+ * Tests for the SiteList implementing classes.
+ *
+ * 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.
+ *
+ * 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
+ * @since 1.20
+ *
+ * @ingroup Site
+ * @ingroup Test
+ *
+ * @group Site
+ *
+ * @licence GNU GPL v2+
+ * @author Jeroen De Dauw < jeroendedauw@gmail.com >
+ */
+class SiteListTest extends MediaWikiTestCase {
+
+       /**
+        * Returns instances of SiteList implementing objects.
+        * @return array
+        */
+       public function siteListProvider() {
+               $sitesArrays = $this->siteArrayProvider();
+
+               $listInstances = array();
+
+               foreach ( $sitesArrays as $sitesArray ) {
+                       $listInstances[] = new SiteArray( $sitesArray[0] );
+               }
+
+               return $this->arrayWrap( $listInstances );
+       }
+
+       /**
+        * Returns arrays with instances of Site implementing objects.
+        * @return array
+        */
+       public function siteArrayProvider() {
+               $sites = TestSites::getSites();
+
+               $siteArrays = array();
+
+               $siteArrays[] = $sites;
+
+               $siteArrays[] = array( array_shift( $sites ) );
+
+               $siteArrays[] = array( array_shift( $sites ), array_shift( $sites ) );
+
+               return $this->arrayWrap( $siteArrays );
+       }
+
+       /**
+        * @dataProvider siteListProvider
+        * @param SiteList $sites
+        */
+       public function testIsEmpty( SiteList $sites ) {
+               $this->assertEquals( count( $sites ) === 0, $sites->isEmpty() );
+       }
+
+       /**
+        * @dataProvider siteListProvider
+        * @param SiteList $sites
+        */
+       public function testGetSiteByGlobalId( SiteList $sites ) {
+               if ( $sites->isEmpty() ) {
+                       $this->assertTrue( true );
+               }
+               else {
+                       /**
+                        * @var Site $site
+                        */
+                       foreach ( $sites as $site ) {
+                               $this->assertEquals( $site, $sites->getSite( $site->getGlobalId() ) );
+                       }
+               }
+       }
+
+       /**
+        * @dataProvider siteListProvider
+        * @param SiteList $sites
+        */
+       public function testGetSiteByInternalId( $sites ) {
+               /**
+                * @var Site $site
+                */
+               foreach ( $sites as $site ) {
+                       if ( is_integer( $site->getInternalId() ) ) {
+                               $this->assertEquals( $site, $sites->getSiteByInternalId( $site->getInternalId() ) );
+                       }
+               }
+
+               $this->assertTrue( true );
+       }
+
+       /**
+        * @dataProvider siteListProvider
+        * @param SiteList $sites
+        */
+       public function testHasGlobalId( $sites ) {
+               $this->assertFalse( $sites->hasSite( 'non-existing-global-id' ) );
+               $this->assertFalse( $sites->hasInternalId( 72010101010 ) );
+
+               if ( !$sites->isEmpty() ) {
+                       /**
+                        * @var Site $site
+                        */
+                       foreach ( $sites as $site ) {
+                               $this->assertTrue( $sites->hasSite( $site->getGlobalId() ) );
+                       }
+               }
+       }
+
+       /**
+        * @dataProvider siteListProvider
+        * @param SiteList $sites
+        */
+       public function testHasInternallId( $sites ) {
+               /**
+                * @var Site $site
+                */
+               foreach ( $sites as $site ) {
+                       if ( is_integer( $site->getInternalId() ) ) {
+                               $this->assertTrue( $site, $sites->hasInternalId( $site->getInternalId() ) );
+                       }
+               }
+
+               $this->assertFalse( $sites->hasInternalId( -1 ) );
+       }
+
+       /**
+        * @dataProvider siteListProvider
+        * @param SiteList $sites
+        */
+       public function testGetGlobalIdentifiers( SiteList $sites ) {
+               $identifiers = $sites->getGlobalIdentifiers();
+
+               $this->assertTrue( is_array( $identifiers ) );
+
+               $expected = array();
+
+               /**
+                * @var Site $site
+                */
+               foreach ( $sites as $site ) {
+                       $expected[] = $site->getGlobalId();
+               }
+
+               $this->assertArrayEquals( $expected, $identifiers );
+       }
+
+
+}
\ No newline at end of file
diff --git a/tests/phpunit/includes/site/SiteObjectTest.php b/tests/phpunit/includes/site/SiteObjectTest.php
new file mode 100644 (file)
index 0000000..cb5e07e
--- /dev/null
@@ -0,0 +1,282 @@
+<?php
+
+/**
+ * Tests for the SiteObject class.
+ *
+ * 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.
+ *
+ * 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
+ * @since 1.20
+ *
+ * @ingroup Site
+ * @ingroup Test
+ *
+ * @group Site
+ *
+ * @licence GNU GPL v2+
+ * @author Jeroen De Dauw < jeroendedauw@gmail.com >
+ */
+class SiteObjectTest extends ORMRowTest {
+
+       /**
+        * @see ORMRowTest::getRowClass
+        * @since 1.20
+        * @return string
+        */
+       protected function getRowClass() {
+               return 'SiteObject';
+       }
+
+       /**
+        * @see ORMRowTest::getTableInstance
+        * @since 1.20
+        * @return IORMTable
+        */
+       protected function getTableInstance() {
+               return SitesTable::singleton();
+       }
+
+       /**
+        * @see ORMRowTest::constructorTestProvider
+        * @since 1.20
+        * @return array
+        */
+       public function constructorTestProvider() {
+               $argLists = array();
+
+               $argLists[] = array( 'global_key' => '42' );
+
+               $argLists[] = array( 'global_key' => '42', 'type' => Site::TYPE_MEDIAWIKI );
+
+               $constructorArgs = array();
+
+               foreach ( $argLists as $argList ) {
+                       $constructorArgs[] = array( $argList, true );
+               }
+
+               return $constructorArgs;
+       }
+
+       /**
+        * @dataProvider instanceProvider
+        * @param Site $site
+        */
+       public function testGetInterwikiIds( Site $site ) {
+               $this->assertInternalType( 'array', $site->getInterwikiIds() );
+       }
+
+       /**
+        * @dataProvider instanceProvider
+        * @param Site $site
+        */
+       public function testGetNavigationIds( Site $site ) {
+               $this->assertInternalType( 'array', $site->getNavigationIds() );
+       }
+
+       /**
+        * @dataProvider instanceProvider
+        * @param Site $site
+        */
+       public function testAddNavigationId( Site $site ) {
+               $site->addNavigationId( 'foobar' );
+               $this->assertTrue( in_array( 'foobar', $site->getNavigationIds(), true ) );
+       }
+
+       /**
+        * @dataProvider instanceProvider
+        * @param Site $site
+        */
+       public function testAddInterwikiId( Site $site ) {
+               $site->addInterwikiId( 'foobar' );
+               $this->assertTrue( in_array( 'foobar', $site->getInterwikiIds(), true ) );
+       }
+
+       /**
+        * @dataProvider instanceProvider
+        * @param Site $site
+        */
+       public function testGetLanguageCode( Site $site ) {
+               $this->assertTypeOrFalse( 'string', $site->getLanguageCode() );
+       }
+
+       /**
+        * @dataProvider instanceProvider
+        * @param Site $site
+        */
+       public function testSetLanguageCode( Site $site ) {
+               $site->setLanguageCode( 'en' );
+               $this->assertEquals( 'en', $site->getLanguageCode() );
+       }
+
+       /**
+        * @dataProvider instanceProvider
+        * @param Site $site
+        */
+       public function testNormalizePageName( Site $site ) {
+               $this->assertInternalType( 'string', $site->normalizePageName( 'Foobar' ) );
+       }
+
+       /**
+        * @dataProvider instanceProvider
+        * @param Site $site
+        */
+       public function testGetGlobalId( Site $site ) {
+               $this->assertInternalType( 'string', $site->getGlobalId() );
+       }
+
+       /**
+        * @dataProvider instanceProvider
+        * @param Site $site
+        */
+       public function testSetGlobalId( Site $site ) {
+               $site->setGlobalId( 'foobar' );
+               $this->assertEquals( 'foobar', $site->getGlobalId() );
+       }
+
+       /**
+        * @dataProvider instanceProvider
+        * @param Site $site
+        */
+       public function testGetType( Site $site ) {
+               $this->assertInternalType( 'string', $site->getType() );
+       }
+
+       /**
+        * @dataProvider instanceProvider
+        * @param Site $site
+        */
+       public function testGetPath( Site $site ) {
+               $this->assertTypeOrFalse( 'string', $site->getPath( 'page_path' ) );
+               $this->assertTypeOrFalse( 'string', $site->getPath( 'file_path' ) );
+               $this->assertTypeOrFalse( 'string', $site->getPath( 'foobar' ) );
+       }
+
+       /**
+        * @dataProvider instanceProvider
+        * @param Site $site
+        */
+       public function testGetAllPaths( Site $site ) {
+               $this->assertInternalType( 'array', $site->getAllPaths() );
+       }
+
+       /**
+        * @dataProvider instanceProvider
+        * @param Site $site
+        */
+       public function testSetAndRemovePath( Site $site ) {
+               $count = count( $site->getAllPaths() );
+
+               $site->setPath( 'spam', 'http://www.wikidata.org/$1' );
+               $site->setPath( 'spam', 'http://www.wikidata.org/foo/$1' );
+               $site->setPath( 'foobar', 'http://www.wikidata.org/bar/$1' );
+
+               $this->assertEquals( $count + 2, count( $site->getAllPaths() ) );
+
+               $this->assertInternalType( 'string', $site->getPath( 'foobar' ) );
+               $this->assertEquals( 'http://www.wikidata.org/foo/$1', $site->getPath( 'spam' ) );
+
+               $site->removePath( 'spam' );
+               $site->removePath( 'foobar' );
+
+               $this->assertEquals( $count, count( $site->getAllPaths() ) );
+
+               $this->assertFalse( $site->getPath( 'foobar' ) );
+               $this->assertFalse( $site->getPath( 'spam' ) );
+       }
+
+       public function testSetLinkPath() {
+               /* @var SiteObject $site */
+               $site = $this->getRowInstance( $this->getMockFields(), false );
+               $path = "TestPath/$1";
+
+               $site->setLinkPath( $path );
+               $this->assertEquals( $path, $site->getLinkPath() );
+       }
+
+       public function testGetLinkPathType() {
+               /* @var SiteObject $site */
+               $site = $this->getRowInstance( $this->getMockFields(), false );
+
+               $path = 'TestPath/$1';
+               $site->setLinkPath( $path );
+               $this->assertEquals( $path, $site->getPath( $site->getLinkPathType() ) );
+
+               $path = 'AnotherPath/$1';
+               $site->setPath( $site->getLinkPathType(), $path );
+               $this->assertEquals( $path, $site->getLinkPath() );
+       }
+
+       public function testSetPath() {
+               /* @var SiteObject $site */
+               $site = $this->getRowInstance( $this->getMockFields(), false );
+
+               $path = 'TestPath/$1';
+               $site->setPath( 'foo', $path );
+
+               $this->assertEquals( $path, $site->getPath( 'foo' ) );
+       }
+
+       public function provideGetPageUrl() {
+               //NOTE: the assumption that the URL is built by replacing $1
+               //      with the urlencoded version of $page
+               //      is true for SiteObject but not guaranteed for subclasses.
+               //      Subclasses need to override this provider appropriately.
+
+               return array(
+                       array( #0
+                               'http://acme.test/TestPath/$1',
+                               'Foo',
+                               '/TestPath/Foo',
+                       ),
+                       array( #1
+                               'http://acme.test/TestScript?x=$1&y=bla',
+                               'Foo',
+                               'TestScript?x=Foo&y=bla',
+                       ),
+                       array( #2
+                               'http://acme.test/TestPath/$1',
+                               'foo & bar/xyzzy (quux-shmoox?)',
+                               '/TestPath/foo%20%26%20bar%2Fxyzzy%20%28quux-shmoox%3F%29',
+                       ),
+               );
+       }
+
+       /**
+        * @dataProvider provideGetPageUrl
+        */
+       public function testGetPageUrl( $path, $page, $expected ) {
+               /* @var SiteObject $site */
+               $site = $this->getRowInstance( $this->getMockFields(), false );
+
+               //NOTE: the assumption that getPageUrl is based on getLinkPath
+               //      is true for SiteObject but not guaranteed for subclasses.
+               //      Subclasses need to override this test case appropriately.
+               $site->setLinkPath( $path );
+               $this->assertContains( $path, $site->getPageUrl() );
+
+               $this->assertContains( $expected, $site->getPageUrl( $page ) );
+       }
+
+       protected function assertTypeOrFalse( $type, $value ) {
+               if ( $value === false ) {
+                       $this->assertTrue( true );
+               }
+               else {
+                       $this->assertInternalType( $type, $value );
+               }
+       }
+
+}
\ No newline at end of file
diff --git a/tests/phpunit/includes/site/SitesTest.php b/tests/phpunit/includes/site/SitesTest.php
new file mode 100644 (file)
index 0000000..4c74215
--- /dev/null
@@ -0,0 +1,87 @@
+<?php
+
+/**
+ * Tests for the Sites class.
+ *
+ * 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.
+ *
+ * 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
+ * @since 1.20
+ *
+ * @ingroup Site
+ * @ingroup Test
+ *
+ * @group Site
+ * @group Database
+ *
+ * @licence GNU GPL v2+
+ * @author Jeroen De Dauw < jeroendedauw@gmail.com >
+ */
+class SitesTest extends MediaWikiTestCase {
+
+       public function setUp() {
+               parent::setUp();
+               TestSites::insertIntoDb();
+       }
+
+       public function testSingleton() {
+               $this->assertInstanceOf( 'Sites', Sites::singleton() );
+               $this->assertTrue( Sites::singleton() === Sites::singleton() );
+       }
+
+       public function testGetSites() {
+               $this->assertInstanceOf( 'SiteList', Sites::singleton()->getSites() );
+       }
+
+
+       public function testGetSite() {
+               $count = 0;
+               $sites = Sites::singleton()->getSites();
+
+               /**
+                * @var Site $site
+                */
+               foreach ( $sites as $site ) {
+                       $this->assertInstanceOf( 'Site', $site );
+
+                       $this->assertEquals(
+                               $site,
+                               Sites::singleton()->getSite( $site->getGlobalId() )
+                       );
+
+                       if ( ++$count > 100 ) {
+                               break;
+                       }
+               }
+       }
+
+       public function testNewSite() {
+               $this->assertInstanceOf( 'Site', Sites::newSite() );
+               $this->assertInstanceOf( 'Site', Sites::newSite( 'enwiki' ) );
+       }
+
+       public function testGetGroup() {
+               $wikipedias = Sites::singleton()->getSiteGroup( "wikipedia" );
+
+               $this->assertFalse( $wikipedias->isEmpty() );
+
+               /* @var Site $site */
+               foreach ( $wikipedias as $site ) {
+                       $this->assertEquals( 'wikipedia', $site->getGroup() );
+               }
+       }
+
+}
diff --git a/tests/phpunit/includes/site/TestSites.php b/tests/phpunit/includes/site/TestSites.php
new file mode 100644 (file)
index 0000000..1d4ffec
--- /dev/null
@@ -0,0 +1,114 @@
+<?php
+
+/**
+ * Holds sites for testing purposes.
+ *
+ * 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.
+ *
+ * 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
+ * @since 1.20
+ *
+ * @ingroup Site
+ * @ingroup Test
+ *
+ * @group Site
+ *
+ * @licence GNU GPL v2+
+ * @author Jeroen De Dauw < jeroendedauw@gmail.com >
+ */
+class TestSites {
+
+       /**
+        * @since 1.20
+        *
+        * @return array
+        */
+       public static function getSites() {
+               $sites = array();
+
+               $site = Sites::newSite( 'foobar' );
+               $sites[] = $site;
+
+               $site = Sites::newSite( 'enwiktionary' );
+               $site->setGroup( 'wiktionary' );
+               $site->setType( Site::TYPE_MEDIAWIKI );
+               $site->setLanguageCode( 'en' );
+               $site->addNavigationId( 'enwiktionary' );
+               $site->setPath( MediaWikiSite::PATH_PAGE, "https://en.wiktionary.org/wiki/$1" );
+               $site->setPath( MediaWikiSite::PATH_FILE, "https://en.wiktionary.org/w/$1" );
+               $sites[] = $site;
+
+               $site = Sites::newSite( 'dewiktionary' );
+               $site->setGroup( 'wiktionary' );
+               $site->setType( Site::TYPE_MEDIAWIKI );
+               $site->setLanguageCode( 'de' );
+               $site->addInterwikiId( 'dewiktionary' );
+               $site->addInterwikiId( 'wiktionaryde' );
+               $site->setPath( MediaWikiSite::PATH_PAGE, "https://de.wiktionary.org/wiki/$1" );
+               $site->setPath( MediaWikiSite::PATH_FILE, "https://de.wiktionary.org/w/$1" );
+               $sites[] = $site;
+
+               $site = Sites::newSite( 'spam' );
+               $site->setGroup( 'spam' );
+               $site->setType( Site::TYPE_UNKNOWN );
+               $site->setLanguageCode( 'en' );
+               $site->addNavigationId( 'spam' );
+               $site->addNavigationId( 'spamz' );
+               $site->addInterwikiId( 'spamzz' );
+               $site->setLinkPath( "http://spamzz.test/testing/" );
+               $sites[] = $site;
+
+               foreach ( array( 'en', 'de', 'nl', 'sv', 'sr', 'no', 'nn' ) as $langCode ) {
+                       $site = Sites::newSite( $langCode . 'wiki' );
+                       $site->setGroup( 'wikipedia' );
+                       $site->setType( Site::TYPE_MEDIAWIKI );
+                       $site->setLanguageCode( $langCode );
+                       $site->addInterwikiId( $langCode );
+                       $site->addNavigationId( $langCode );
+                       $site->setPath( MediaWikiSite::PATH_PAGE, "https://$langCode.wikipedia.org/wiki/$1" );
+                       $site->setPath( MediaWikiSite::PATH_FILE, "https://$langCode.wikipedia.org/w/$1" );
+                       $sites[] = $site;
+               }
+
+               return $sites;
+       }
+
+       /**
+        * Inserts sites into the database for the unit tests that need them.
+        *
+        * @since 0.1
+        */
+       public static function insertIntoDb() {
+               $dbw = wfGetDB( DB_MASTER );
+
+               $dbw->begin( __METHOD__ );
+
+               $dbw->delete( 'sites', '*', __METHOD__ );
+               $dbw->delete( 'site_identifiers', '*', __METHOD__ );
+
+               /**
+                * @var Site $site
+                */
+               foreach ( TestSites::getSites() as $site ) {
+                       $site->save();
+               }
+
+               $dbw->commit( __METHOD__ );
+
+               Sites::singleton()->getSites( false ); // re-cache
+       }
+
+}
\ No newline at end of file