diff --git "a/class-mw\\API.php" "b/class-mw\\API.php" index 9c04cb7..526a86b 100644 --- "a/class-mw\\API.php" +++ "b/class-mw\\API.php" @@ -1,249 +1,290 @@ . # 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. */ private $username; /** * Frequent API response token to continue a result set. * * @var mixed */ private $continue = null; /** * Flag to avoid duplicate logins */ private $logged = false; /** * Last API response * * @var mixed */ private $last = null; + /** + * Constructor + * + * @param $api string API endpoint + */ + public function __construct( $api ) { + parent::__construct( $api, [], [] ); + $this->tokens = new Tokens( $this ); + } + /** * 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 ); } /** * Check if there are other requests to do to fetch the whole result set. * * @return bool */ public function hasNext() { // Note that as default continue is NULL return false !== $this->continue; } /** * Fetch the next result set. * * @return mixed */ public function fetchNext() { $data = $this->getData(); if( $this->continue ) { self::log('INFO', "Will continue"); foreach( $this->continue as $arg => $value ) { $data[ $arg ] = $value; } } $next = $this->fetch( $data ); $this->continue = isset( $next->continue ) ? $next->continue : false; return $next; } + /** + * Require some tokens + * + * @return self + */ + public function requireTokens( $tokens ) { + $this->tokens->require( $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 $this->logged; } /** * 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 ) { $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__ ) ); } - // Fetch the login token - $logintoken = $this->fetch( [ - 'action' => 'query', - 'meta' => 'tokens', - 'type' => 'login' - ] )->query->tokens->logintoken; - // Login $response = parent::post( [ 'action' => 'login', 'lgname' => $username, 'lgpassword' => $password, - 'lgtoken' => $logintoken + 'lgtoken' => $this->getToken( Tokens::LOGIN ), ] ); if( ! isset( $response->login->result ) || $response->login->result !== 'Success' ) { throw new \Exception("login failed"); } $this->username = $response->login->lgusername; $this->logged = true; return $this; } /** * Set GET/POST data. * * As default, it propose a maxlag and a format. * * @param $data array GET/POST data * @override \network\HTTPRequest#setData() */ public function setData( $data ) { $this->continue = null; $data = array_replace( [ 'maxlag' => self::$DEFAULT_MAXLAG, 'format' => self::$DEFAULT_FORMAT ], $data ); return parent::setData( $data ); } /** * 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 ) { 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->error ) ) { $exception = API\Exception::createFromApiError( $result->error ); if( $exception instanceof MaxLagException ) { // Retry after some time when server lags self::log( 'WARN', "Lag!" ); $args = array_replace( [ 'wait' => self::WAIT_DOS ], $this->getArgs() ); $result = $this->fetch( $data , $args ); } else { throw $exception; } } return $this->last = $result; } } diff --git "a/class-mw\\Site.php" "b/class-mw\\Site.php" index ff385d6..fc2a74e 100644 --- "a/class-mw\\Site.php" +++ "b/class-mw\\Site.php" @@ -1,215 +1,246 @@ . # 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 = self::createApi( $url ); } /** * 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 + * + * @return self + */ + public function requireTokens( $tokens ) { + $this->getApi()->requireTokens( $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 we can continue fetching the next result set * * @see API#hasNext() * @return bool */ public function hasNext() { return $this->getApi()->hasNext(); } /** * Fetch the next result set * * @see API#fetchNext() * @return mixed Response */ public function fetchNext() { return $this->getApi()->fetchNext(); } /** * Set the default API data * * @see API#setData() * @data array HTTP GET/POST data * @return self */ public function setApiData( $data ) { $this->getApi()->setData( $data ); 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 ); } /** * Create a MediaWiki API object from an API URL * * @param $url string API URL * @return API */ private static function createApi( $url ) { return new API( $url ); } } diff --git "a/class-mw\\Tokens.php" "b/class-mw\\Tokens.php" new file mode 100644 index 0000000..f4cdf35 --- /dev/null +++ "b/class-mw\\Tokens.php" @@ -0,0 +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 ]; + } + + /** + * 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 + * + * This will fetch only the uncached + * + * @param $tokens array Token names + * @return self + */ + public function require( $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 }; + } + } +}