diff --git "a/include/class-mw\\API.php" "b/include/class-mw\\API.php" index de66ebb..d8b647e 100644 --- "a/include/class-mw\\API.php" +++ "b/include/class-mw\\API.php" @@ -1,284 +1,293 @@ . # MediaWiki namespace mw; use cli\Log; /** * 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 response format * * @var string */ static $DEFAULT_FORMAT = 'json'; /** * Inspect POST flag * * @var bool */ public static $INSPECT_BEFORE_POST = false; /** * 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(); } if( static::$INSPECT_BEFORE_POST ) { print_r( $data ); \cli\Input::askInput( "Press ENTER to submit" ); } return parent::post( $data, $args ); } /** * Fetch response * * @param $data array GET/POST data * @return mixed */ public function fetch( $data = [], $args = [] ) { if( [] === $data ) { throw \InvalidArgumentException( 'empty data' ); } return parent::fetch( $data, $args ); } /** * Preload some tokens * * @return self */ 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; } + /** + * Get the username used for the login + * + * @return string|null + */ + public function getUsername() { + return $this->username; + } + /** * Check if it's already logged in. * * @return bool */ public function isLogged() { - return isset( $this->username ); + return $this->getUsername() !== null; } /** * 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 ) ) { // remove duplicates (API netiquette) $v = array_unique( $v ); // index alphabetically (API netiquette) sort( $v, SORT_STRING ); $data[ $k ] = implode( '|', $v ); } } if( $this->isLogged() ) { $data = array_replace( [ - 'assertuser' => $this->username + 'assertuser' => $this->getUsername(), ], $data ); } return $data; } /** * JSON decode and check formal API errors * * @param $response mixed Response * @param $request_data array GET/POST request data * @override \network\HTTPRequest#onFetched() * @throws \mw\API\Exception */ protected function onFetched( $response, $request_data ) { $response = json_decode( $response ); if( null === $response ) { throw new \Exception( 'response not JSON-encoded: ' . $response ); } if( isset( $response->warnings ) ) { foreach( $response->warnings as $subject => $warning ) { Log::warn( sprintf( '%s: %s', $subject, $warning->{'*'} ) ); } } if( isset( $response->error ) ) { $exception = API\Exception::createFromApiError( $response->error ); if( $exception instanceof API\MaxLagException ) { // retry after some time when server lags Log::warn( "Lag! ({$this->api})" ); $response = $this->fetch( $request_data, [ 'wait' => self::WAIT_DOS ] ); } else { throw $exception; } } return $response; } } diff --git "a/include/class-mw\\Site.php" "b/include/class-mw\\Site.php" index 9bfe091..a8ef5f8 100644 --- "a/include/class-mw\\Site.php" +++ "b/include/class-mw\\Site.php" @@ -1,302 +1,321 @@ . # MediaWiki namespace mw; class Site { /** * A sort of $wgCapitalLinks * * @see https://www.mediawiki.org/wiki/Manual:$wgCapitalLinks */ const CAPITAL_LINKS = true; /** * 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 ); } /** * Do an API edit request * * @param $data array API request data * @return mixed * @see https://www.mediawiki.org/wiki/API:Edit */ public function edit( $data ) { return $this->getApi()->post( array_replace( $data, [ 'action' => 'edit', 'token' => $this->getToken( \mw\Tokens::CSRF ) ] ) ); } + /** + * Check if I'm logged + * + * @return bool + */ + public function isLogged() { + return $this->getApi()->isLogged(); + } + + /** + * Get the username used for the login (if any) + * + * @return string|null + */ + public function getUsername() { + return $this->getApi()->getUsername(); + } + + /** * Preload some tokens * * @return self */ 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; } /** * Find a namespace by it's name * * @param $name string * @return object|false */ public function findNamespace( $name ) { $name = Ns::normalizeName( $name ); foreach( $this->namespaces as $ns ) { if( $ns->getName() === $name ) { return $ns; } } return false; } /** * 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 CompleteTitle object * * @param $title string Page title without namespace prefix * @param $ns int Namespace number * @return object */ public function createTitle( $title, $ns = 0 ) { return new CompleteTitle( $this, $this->getNamespace( $ns ), new Title( $title, $this ) ); } /** * Create a CompleteTitle object * * @param $s Page title with namespace prefix * @return object */ public function createTitleParsing( $s ) { return CompleteTitle::createParsingTitle( $this, $s ); } /** * Create a wikilink object * * @deprecate Unuseful, just use createTitleParsing()->createWikilink() * @return object */ public function createWikilink( CompleteTitle $title, $alias = null ) { return $title->createWikilink( $alias ); } /** * Check if in this wiki the first case is insensitive * * @TODO generalize * @return boolean */ public function hasCapitalLinks() { return static::CAPITAL_LINKS; } /** * Create from an API URL * * @param $url string MediaWiki API URL * @return self */ public static function createFromAPIURL( $url ) { return new static( $url ); } }