diff --git "a/class-mw\\API.php" "b/class-mw\\API.php" index a76497e..f8b32e9 100644 --- "a/class-mw\\API.php" +++ "b/class-mw\\API.php" @@ -1,260 +1,260 @@ . # MediaWiki namespace mw; /** * Make HTTP request to a MediaWiki API */ class API extends \network\HTTPRequest { /** * MediaWiki tokens handler * * @var mw\Tokens */ private $tokens; /** * Default MediaWiki login username * * @var string */ static $DEFAULT_USERNAME; /** * Default MediaWiki login password * * @var string */ static $DEFAULT_PASSWORD; /** * Default MediaWiki API maxlag * * @var int */ static $DEFAULT_MAXLAG = 5; /** * Default MediaWiki API result format * * @var string */ static $DEFAULT_FORMAT = 'json'; /** * Username used for the login. * * @var string */ private $username; /** * Constructor * * @param $api string API endpoint */ public function __construct( $api ) { parent::__construct( $api, [] ); $this->tokens = new Tokens( $this ); } /** * Create an API query with continuation handler * * @param $data array Data * @return mw\APIQuery */ public function createQuery( $data ) { return new APIQuery( $this, $data ); } /** * Effectuate an HTTP POST request but only after a login. * * @param $data array GET/POST data * @param $args array Internal arguments * @override \network\HTTPRequest#post() * @return mixed */ public function post( $data = [], $args = [] ) { if( ! $this->isLogged() ) { $this->login(); } return parent::post( $data, $args ); } /** * Fetch results * * @param $data array GET/POST data * @return mixed */ public function fetch( $data = [], $args = [] ) { if( [] === $data ) { throw \InvalidArgumentException( 'empty data' ); } return parent::fetch( $data, $args ); } /** - * Require some tokens + * Preload some tokens * * @return self */ - public function requireTokens( $tokens ) { - $this->tokens->require( $tokens ); + public function preloadTokens( $tokens ) { + $this->tokens->preload( $tokens ); return $this; } /** * Get the value of a token * * @param $token string Token name * @return string Token value */ public function getToken( $token ) { return $this->tokens->get( $token ); } /** * Invalidate a token * * @param $token string Token name * @return self */ public function invalidateToken( $token ) { $this->tokens->invalidate( $token ); return $this; } /** * Check if it's already logged in. * * @return bool */ public function isLogged() { return isset( $this->username ); } /** * Login into MediaWiki using an username/password pair. * * Yes, I'm talking about a bot password. */ public function login( $username = null, $password = null ) { // Can use a default set of credentials if( ! $username && ! $password ) { if( $this->isLogged() ) { return $this; } $username = self::$DEFAULT_USERNAME; $password = self::$DEFAULT_PASSWORD; } if( ! $username || ! $password ) { throw new \Exception( sprintf( 'you must call %1$s#login( $username, $password ) or '. 'set %1$s::$DEFAULT_USERNAME and %1$s::$DEFAULT_PASSWORD ' . 'before POSTing', __CLASS__ ) ); } // Login $response = parent::post( [ 'action' => 'login', 'lgname' => $username, 'lgpassword' => $password, 'lgtoken' => $this->getToken( Tokens::LOGIN ), ], [ 'sensitive' => true ] ); if( ! isset( $response->login->result ) || $response->login->result !== 'Success' ) { print_r( $response ); throw new \Exception("login failed"); } $this->username = $response->login->lgusername; return $this; } /** * Filters the data before using it. * * Array elements are imploded by a pipe * NULL values are unset * * @override network\HTTPRequest::onDataReady() * @param $data array GET/POST data * @return array */ protected function onDataReady( $data ) { // Some default values $data = array_replace( [ 'maxlag' => self::$DEFAULT_MAXLAG, 'format' => self::$DEFAULT_FORMAT, ], $data ); foreach( $data as $k => $v ) { if( null === $v ) { unset( $data[ $k ] ); } elseif( is_array( $v ) ) { $data[ $k ] = implode( '|', $v ); } } if( $this->isLogged() ) { $data = array_replace( [ 'assertuser' => $this->username ], $data ); } return $data; } /** * JSON decode and check formal API errors * * @param $result mixed Result * @override \network\HTTPRequest#onFetched() * @throws \mw\API\Exception */ protected function onFetched( $result ) { $result = json_decode( $result ); if( isset( $result->warnings ) ) { Log::warn( $result->warnings->main->{'*'} ); } if( isset( $result->error ) ) { $exception = API\Exception::createFromApiError( $result->error ); if( $exception instanceof MaxLagException ) { // Retry after some time when server lags Log::warn( "Lag!" ); $args = array_replace( [ 'wait' => self::WAIT_DOS ], $this->getArgs() ); $result = $this->fetch( $data , $args ); } else { throw $exception; } } return $result; } } diff --git "a/class-mw\\Site.php" "b/class-mw\\Site.php" index 15f1157..692fc10 100644 --- "a/class-mw\\Site.php" +++ "b/class-mw\\Site.php" @@ -1,214 +1,214 @@ . # MediaWiki namespace mw; class Site { /** * MediaWiki API * * @var API */ private $api; /** * Site namespaces * * @var array Array of namespaces */ private $namespaces = []; /** * A sort of internal UID * * @var null|string E.g. 'enwiki' */ private $uid; /** * Constructor * * @param $url string MediaWiki API URL */ public function __construct( $url ) { $this->api = new API( $url ); } /** * Create an API query with continuation handler * * @param $data array GET/POST data arguments * @return mw\APIQuery */ public function createQuery( $data ) { return $this->getApi()->createQuery( $data ); } /** * Make an HTTP GET request to the API * * @param $data array HTTP GET data * @return mixed API result */ public function fetch( $data ) { return $this->getApi()->fetch( $data ); } /** * Make an HTTP POST request to the API * * This method will call the API#login() method. * * @param $data array HTTP GET data * @return mixed API result */ public function post( $data ) { return $this->getApi()->post( $data ); } /** - * Require some tokens + * Preload some tokens * * @return self */ - public function requireTokens( $tokens ) { - $this->getApi()->requireTokens( $tokens ); + public function preloadTokens( $tokens ) { + $this->getApi()->preloadTokens( $tokens ); return $this; } /** * Get the value of a token * * @param $token string Token name * @return string Token value */ public function getToken( $token ) { return $this->getApi()->getToken( $token ); } /** * Invalidate a token * * @param $token string Token name * @return self */ public function invalidateToken( $token ) { $this->getApi()->invalidateToken( $token ); return $this; } /** * Make a login * * @see API#login() * @param $username string MediaWiki username * @param $password string MediaWiki password * @return self */ public function login( $username = null, $password = null ) { $this->getApi()->login( $username, $password ); return $this; } /** * Check if a certain namespace ID is registered * * @param int $id Namespace ID * @return bool */ public function hasNamespace( $id ) { return array_key_exists( $id, $this->namespaces ); } /** * Get the namespace related to the specified ID * * @param int $id Namespace ID * @return Ns Corresponding namespace */ public function getNamespace( $id ) { if( ! $this->hasNamespace( $id ) ) { throw new \Exception( sprintf( 'missing namespace %d', $id ) ); } return $this->namespaces[ $id ]; } /** * Set/overwrite a namespace * * @param $namespace Ns Namespace to be set/overwrited * @return self */ public function setNamespace( Ns $namespace ) { $id = $namespace->getID(); $this->namespaces[ $id ] = $namespace; return $this; } /** * Stupid shortcut for setting multiple namespaces * * @param $namespaces array Array of namespaces * @return self */ public function setNamespaces( $namespaces ) { foreach( $namespaces as $namespace ) { $this->setNamespace( $namespace ); } return $this; } /** * Set the UID * * @param string E.g. 'enwiki' * @return self */ public function setUID( $uid ) { $this->uid = $uid; return $this; } /** * Get internal MediaWiki API object * * @return API */ public function getApi() { return $this->api; } /** * Get the UID * * @return null|string e.g. 'enwiki' */ public function getUID() { return $this->uid; } /** * Create a Wikitext object * * @return Wikitext */ public function createWikitext( $wikitext ) { return new Wikitext( $this, $wikitext ); } } diff --git "a/class-mw\\Tokens.php" "b/class-mw\\Tokens.php" index f4cdf35..49a29dd 100644 --- "a/class-mw\\Tokens.php" +++ "b/class-mw\\Tokens.php" @@ -1,183 +1,183 @@ . # MediaWiki namespace mw; /** * Handle MediaWiki API tokens * * @see https://it.wikipedia.org/w/api.php?action=help&modules=query%2Btokens */ class Tokens { /** * To create an account */ const CREATE_ACCOUNT = 'createaccount'; /** * To do some actions like edit */ const CSRF = 'csrf'; /** * To delete the global account */ const DELETE_GLOBAL_ACCOUNT = 'deleteglobalaccount'; /** * To login */ const LOGIN = 'login'; /** * To patrol */ const PATROL = 'patrol'; /** * To do a rollback */ const ROLLBACK = 'rollback'; /** * To set the global account status */ const SET_GLOBAL_ACCOUNT_STATUS = 'setglobalaccountstatus'; /** * To set user rights */ const USER_RIGHTS = 'userrights'; /** * To watch a page */ const WATCH = 'watch'; /** * MediaWiki API object to be used to retrieve the tokens * * @var \mw\API */ private $api; /** * An associative array of obtained token values * * @var array */ private $tokensCache = []; /** * A whitelist of all the available tokens */ private $whitelist; /** * Create a Tokens handler * * @param $api \mw\API MediaWiki API object */ public function __construct( \mw\API $api ) { // Dependency injection $this->api = $api; // populate the whitelist $self = new \ReflectionClass( $this ); $this->whitelist = $self->getConstants(); } /** * Get the value of a token, eventually fetching it * * @param $token string Token name * @return string Token value */ public function get( $token ) { - return $this->require( [ $token ] )->tokensCache[ $token ]; + return $this->preload( [ $token ] )->tokensCache[ $token ]; } /** * Check if a token exists * * @param $token Token name * @return bool */ public function exists( $token ) { return in_array( $token, $this->whitelist, true ); } /** - * Require multiple tokens + * Preload multiple tokens * * This will fetch only the uncached * * @param $tokens array Token names * @return self */ - public function require( $tokens ) { + public function preload( $tokens ) { $missings = []; foreach( $tokens as $token ) { if( ! $this->exists( $token ) ) { throw new \InvalidArgumentException( 'formally unexisting token' ); } if( ! isset( $this->tokensCache[ $token ] ) ) { $missings[] = $token; } } if( $missings ) { $this->fetch( $missings ); } return $this; } /** * Invalidate the value of a token * * Useful to force a future re-fetch of it * * @param $token string Token name * @return self */ public function invalidate( $token ) { unset( $this->tokensCache[ $token ] ); return $this; } /** * Fetch tokens and cache * * @param $tokens array Token names * @see https://it.wikipedia.org/w/api.php?action=help&modules=query%2Btokens */ private function fetch( $tokens ) { $response_tokens = $this->api->fetch( [ 'action' => 'query', 'meta' => 'tokens', 'type' => $tokens, ] )->query->tokens; foreach( $tokens as $token ) { $token_name = $token . 'token'; if( ! isset( $response_tokens->{ $token_name } ) ) { throw new \Exception( 'the server is not giving correctly one of the asked token' ); } $this->tokensCache[ $token ] = $response_tokens->{ $token_name }; } } }