Page MenuHomeGitPull.it

No OneTemporary

Authored By
Unknown
Size
40 KB
Referenced Files
None
Subscribers
None
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 @@
<?php
# Boz-MW - Another MediaWiki API handler in PHP
# Copyright (C) 2017, 2018 Valerio Bozzolan
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# 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\\CompleteTitle.php" "b/include/class-mw\\CompleteTitle.php"
index 5d59ead..59d86fa 100644
--- "a/include/class-mw\\CompleteTitle.php"
+++ "b/include/class-mw\\CompleteTitle.php"
@@ -1,135 +1,164 @@
<?php
# Boz-MW - Another MediaWiki API handler in PHP
# Copyright (C) 2019 Valerio Bozzolan
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# MediaWiki
namespace mw;
/**
* A MediaWiki complete title (with namespace)
*/
class CompleteTitle {
/**
* Which MediaWiki site
*
* @var object
*/
private $wiki;
/**
* @var object
*/
private $ns;
/**
* @var object
*/
private $title;
/**
* Constructor
*
* @param $wiki object
* @param $ns object
* @param $title object
*/
- public function __construct( $wiki, $ns, $title ) {
+ public function __construct( $wiki, Ns $ns, Title $title ) {
$this->wiki = $wiki;
$this->ns = $ns;
$this->title = $title;
}
/**
* Get the namespace object
*
* @return object
*/
public function getNs() {
return $this->ns;
}
/**
* Get the title object
*
* @return object
*/
public function getTitle() {
return $this->title;
}
+ /**
+ * Get the complete title, as displayed in a page
+ *
+ * @return string
+ */
+ public function getCompleteTitle() {
+ $title = $this->getTitle()->get();
+ $ns = $this->getNs()->getName();
+ if( $ns ) {
+ $ns .= ":";
+ }
+ return $ns . $title;
+ }
+
/**
* Get the regex able to match this complete title
*
* @param $args array
* ns-group-name: Name of the capturing group for the namespace
* title-group-name: Name of the capturing group for the title
* @return string
*/
public function getRegex( $args = [] ) {
// default options
$args = array_replace( [
+ 'wikilink' => true,
'ns-group-name' => null,
'title-group-name' => null,
], $args );
- // single regexes
- $ns = $this->getNs()->getRegex();
- $title = $this->title->getRegex();
+ // namespace regex
+ $ns = $this->getNs()->getRegex( [
+ 'wikilink' => $args[ 'wikilink' ],
+ ] );
+
+ // title regex
+ $title = $this->getTitle()->getRegex();
// eventually group
$ns = \regex\Generic::groupNamed( $ns, $args[ 'ns-group-name' ] );
$title = \regex\Generic::groupNamed( $title, $args[ 'title-group-name' ] );
return $ns . '[ _]*' . $title;
}
+ /**
+ * Create a Wikilink to this title
+ *
+ * @param $alias string|false|null (NULL: whatever, false: no one)
+ * @return object
+ */
+ public function createWikilink( $alias = null ) {
+ return new Wikilink( $this, $alias );
+ }
+
/**
* Static constructor parsing a string
*
* @param $wiki object
* @param $s string e.g. ' Mediawiki: test '
* @return self
*/
public static function createParsingTitle( $wiki, $s ) {
// split namespace and title
$ns_raw = '';
$tokens = explode( ':', $s, 2 );
if( count( $tokens ) === 2 ) {
$ns_raw = $tokens[ 0 ];
$title_raw = $tokens[ 1 ];
} else {
// no namespace? that's the main namespace!
$ns_raw = '';
$title_raw = $tokens[ 0 ];
}
// validate namespace
$ns = $wiki->findNamespace( $ns_raw );
if( ! $ns ) {
// that was the main namespace with a ':' in the title
$ns = $wiki->getNamespace( 0 );
$title_raw = "$ns_raw:$title_raw";
}
$title = new Title( $title_raw, $wiki );
return new self( $wiki, $ns, $title );
}
}
diff --git "a/include/class-mw\\Ns.php" "b/include/class-mw\\Ns.php"
index bc7d9b6..9b30ff1 100644
--- "a/include/class-mw\\Ns.php"
+++ "b/include/class-mw\\Ns.php"
@@ -1,261 +1,270 @@
<?php
# Boz-MW - Another MediaWiki API handler in PHP
# Copyright (C) 2017, 2019 Valerio Bozzolan
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# MediaWiki
namespace mw;
/**
* A Namespace.
*
* Yes, PHP does not allow to call a class "Namespace".
*/
class Ns {
/**
* @var int
*/
private $id;
/**
* @var object
*/
private $name;
/**
* @var object
*/
private $canonicalName;
/**
* Aliases of this namespace
*
* @var array
*/
private $aliases = [];
/**
* Constructor
*
* @var $id int
* @var $name string
* @var $aliases array
*/
public function __construct( $id, $name, $aliases = [] ) {
$this->setID( $id );
$this->setName( $name );
$canonical_name = self::existsDefaultCanonicalName( $id )
? self::defaultCanonicalName( $id )
: $name;
$this->setCanonicalName( $canonical_name );
foreach( $aliases as $alias ) {
$this->addAlias( $alias );
}
}
/**
* Get the namespace ID
*
* @return int
*/
public function getID() {
return $this->id;
}
/**
* Get the local namespace name (eventually localized)
*
* @return string
*/
public function getName() {
return $this->name->get();
}
/**
* Get the namespace canonical name (in English)
*
* @return string
*/
public function getCanonicalName() {
return $this->canonicalName->get();
}
/**
* Set the namespace ID
*
* @param $id int
* @return self
*/
public function setID( $id ) {
$this->id = $id;
return $this;
}
/**
* Set the namespace name
*
* @param $name string
* @return self
*/
public function setName( $name ) {
$this->name = new NsPart( $name );
return $this;
}
/**
* Set the namespace canonical name
*
* @param $name string
* @param $id int
* @return self
*/
public function setCanonicalName( $name ) {
$this->canonicalName = new NsPart( $name );
return $this;
}
/**
* Add another namespace alias
*
* @param $alias string
* @return self
*/
public function addAlias( $alias ) {
$this->aliases[] = new NsPart( $alias );
return $this;
}
/**
* Get all namespace parts
*
* @return array
*/
public function getParts() {
$all = [];
$all[] = $this->name;
if( $this->isCanonicalNameDifferent() ) {
$all[] = $this->canonicalName;
}
foreach( $this->aliases as $alias ) {
$all[] = $alias;
}
return $all;
}
/**
* @deprecated
* @return array
*/
public function getAllTitlePartsCapitalized() {
return $this->getParts();
}
/**
* Get a regex that matches this namespace
*
+ * @param $args array
+ * wikilink: flag indicating that the NS is inside a wikilink
* @return string
*/
- public function getRegex() {
+ public function getRegex( $args = [] ) {
+
+ // default arguments
+ $args = array_replace( [
+ 'wikilink' => true,
+ ] , $args );
+
$all = [];
foreach( $this->getParts() as $part ) {
$all[] = $part->getRegex();
}
// category corner-case: a wikilink to a category has the ':' prefix
- $catprefix = $this->getID() === 14
- ? ':'
- : '';
+ $catprefix = '';
+ if( $args[ 'wikilink' ] && $this->getID() === 14) {
+ $catprefix = ':';
+ }
// in case of a single part we can avoid the OR group
if( count( $all ) === 1 ) {
return $catprefix . $all[ 0 ];
}
// return an 'OR' query, without creating a group
$or = implode( '|', $all );
return $catprefix . "(?>$or)";
}
/**
* Check if the canonical name is different from the local one
*
* @return bool
*/
public function isCanonicalNameDifferent() {
return $this->getName() !== $this->getCanonicalName();
}
/**
* Check if it exists this default canonical name (from ID)
*
* @param $id int
* @return boolean
*/
public static function existsDefaultCanonicalName( $id ) {
return array_key_exists( $id, self::defaultCanonicalNames() );
}
/**
* Get the default canonical name from its ID
*
* @param $id int
* @return boolean
*/
public static function defaultCanonicalName( $id ) {
if( ! self::existsDefaultCanonicalName( $id ) ) {
throw new \Exception('unexisting namespace ID');
}
return self::defaultCanonicalNames()[ $id ];
}
/**
* Normalize a namespace name
*
* @param $name string
* @return string
*/
public static function normalizeName( $name ) {
return ucfirst( strtolower( trim( $name ) ) );
}
/**
* Get all the known MediaWiki default canonical names
*
* @return array
*/
public static function defaultCanonicalNames() {
return [
0 => '',
1 => 'Talk',
2 => 'User',
3 => 'User talk',
4 => 'Project',
5 => 'Project talk',
6 => 'File',
7 => 'File talk',
8 => 'MediaWiki',
9 => 'MediaWiki talk',
10 => 'Template',
11 => 'Template talk',
12 => 'Help',
13 => 'Help talk',
14 => 'Category',
15 => 'Category talk',
-1 => 'Special',
-2 => 'Media'
];
}
}
diff --git "a/include/class-mw\\Site.php" "b/include/class-mw\\Site.php"
index 93e9836..a8ef5f8 100644
--- "a/include/class-mw\\Site.php"
+++ "b/include/class-mw\\Site.php"
@@ -1,289 +1,321 @@
<?php
# Boz-MW - Another MediaWiki API handler in PHP
# Copyright (C) 2017, 2018, 2019 Valerio Bozzolan
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# 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 complete title object
+ * 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 new Wikilink( $title, $alias );
+ 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 );
}
}
diff --git "a/include/class-mw\\Wikilink.php" "b/include/class-mw\\Wikilink.php"
index bd0632b..102feba 100644
--- "a/include/class-mw\\Wikilink.php"
+++ "b/include/class-mw\\Wikilink.php"
@@ -1,181 +1,221 @@
<?php
# Boz-MW - Another MediaWiki API handler in PHP
# Copyright (C) 2019 Valerio Bozzolan
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# MediaWiki
namespace mw;
/**
* A MediaWiki wikilink
*
* Something like [[Wikipedia:Contatti|contatti]].
*/
class Wikilink {
/**
* A valid alias value
*/
const WHATEVER_ALIAS = null;
/**
* A valid alias value
*/
const NO_ALIAS = false;
/**
* MediaWiki title
*
* When falsy, it means that can be whatever
*
* @var object|null
*/
private $title;
/**
* Displayed alias
*
* When NULL, it means that can be whatever,
* When false, it means that there is no one.
*
* @var object
*/
private $alias;
/**
* Constructor
*
* @param $title object
* @param $alias string|false|null (NULL: whatever, false: no one)
*/
public function __construct( CompleteTitle $title, $alias = null ) {
$this->setTitle( $title )
->setAlias( $alias );
}
/**
* Set the title (link)
*
* @param $title object
* @return self
*/
public function setTitle( CompleteTitle $title ) {
$this->title = $title;
return $this;
}
/**
* Set the alias
*
* @param $alias string|null|false (NULL: whatever, false: no one
* @return self
*/
public function setAlias( $alias ) {
$this->alias = $alias;
return $this;
}
/**
* Get a regex matching this wikilink's title
*
* If there is no title, match a generic one.
*
+ * @param $args array Arguments
+ * 'wikilink' boolean If false, a category will categorize (default true)
* @return string
*/
- public function getRegexTitle() {
+ public function getRegexTitle( $args = [] ) {
return $this->title
- ? $this->title->getRegex()
+ ? $this->title->getRegex( $args )
: '[' . self::legalTitleCharset() . ']*';
}
/**
* Get a regex matching this wikilink's alias
*
* If there is no alias, match a generic one.
*
* @return string
*/
public function getRegexAlias() {
// match the alias exactly if present
if( $this->alias ) {
return preg_quote( $this->alias );
}
- // match whatever alias otherwise (non-greedy, because of it can contains ']')
- return '[' . self::legalAliasCharset() . ']*?';
+ // match whatever alias otherwise (non-greedy)
+ return '.*?';
+ }
+
+ /**
+ * Get the wikitext that will point to this wikilink
+ *
+ * @param $args array
+ * @return string
+ */
+ public function getWikitext( $args = [] ) {
+
+ // default arguments
+ $args = array_replace( [
+ 'wikilink' => true,
+ ], $args );
+
+ $completetitle = $this->title;
+ $ns = $completetitle->getNs();
+ $ns_name = $ns->getName();
+ $title = $completetitle->getTitle()->get();
+
+ // categories must me prefixed with ':' if you want a wikilink
+ $prefix = '';
+ if( $ns->getID() === 14 && $args[ 'wikilink' ] ) {
+ $prefix = ':';
+ }
+
+ // the alias is the piped text
+ $alias = '';
+ if( strlen( $this->alias ) > 1 ) {
+ $alias = "|$this->alias";
+ }
+
+ return "[[$prefix$ns_name:$title$alias]]";
}
/**
* Get a regex matching this wikilink
*
* @param $args array Arguments to be specified
- * 'title-group-name': If specified, the title will be captured in a group with this name
- * 'alias-group-name': If specified, the alias will be captured in a group with this name
+ * 'title-group-name' string If specified, the title will be captured in a group with this name
+ * 'alias-group-name' string If specified, the alias will be captured in a group with this name
+ * 'wikilink': bool If false, a category will categorize (default true)
*/
public function getRegex( $args = [] ) {
// default options
$args = array_replace( [
+ 'wikilink' => true,
'title-group-name' => null,
'alias-group-name' => null,
], $args );
// regex matching the title
- $title_regex = \regex\Generic::groupNamed( $this->getRegexTitle(), $args[ 'title-group-name' ] );
+ $title_regex = $this->getRegexTitle( [
+ 'wikilink' => $args[ 'wikilink' ],
+ ] );
+ $title_regex = \regex\Generic::groupNamed( $title_regex, $args[ 'title-group-name' ] );
// regex matching the alias (if any)
$alias_regex = false;
if( $this->alias !== self::NO_ALIAS ) {
$alias_regex = \regex\Generic::groupNamed( $this->getRegexAlias(), $args[ 'alias-group-name' ] );
// the alias part, when it's a captch-all, is optional
if( $this->alias === self::WHATEVER_ALIAS ) {
// note, do not try to create an atomic group, because atomic groups do not backreference past
$alias_regex = "([ _]*\|$alias_regex)?";
}
}
// complete regex
$regex = $title_regex;
if( $alias_regex ) {
$regex .= $alias_regex;
}
// surround with spaces
$regex = \regex\Generic::spaceBurger( $regex );
// surround with brackets
return "\[\[$regex\]\]";
}
/**
* Legal characters for a title
*
* @see https://www.mediawiki.org/wiki/Manual:$wgLegalTitleChars
*/
public static function legalTitleCharset() {
return ' %!\"$&\'()*,\\-.\\/0-9:;=?@A-Z\\\\^_`a-z~\\x80-\\xFF+';
}
/**
* Legal characters for an alias
*
* @see https://www.mediawiki.org/wiki/Manual:$wgLegalTitleChars
*/
public static function legalAliasCharset() {
return self::legalTitleCharset() . '#<>\[\]{}\n\t';
}
}
diff --git "a/include/class-mw\\Wikitext.php" "b/include/class-mw\\Wikitext.php"
index 200caca..cb0db41 100644
--- "a/include/class-mw\\Wikitext.php"
+++ "b/include/class-mw\\Wikitext.php"
@@ -1,408 +1,398 @@
<?php
# Boz-MW - Another MediaWiki API handler in PHP
-# Copyright (C) 2017, 2018 Valerio Bozzolan
+# Copyright (C) 2017, 2018, 2019 Valerio Bozzolan
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# MediaWiki
namespace mw;
/**
* A MediaWiki wikitext
*/
class Wikitext {
/**
* MediaWiki site
*
* @var mw\Site
*/
private $site;
/**
* Complete plain text wikitext
*
* @var string
*/
private $wikitext;
/**
* String appended to the wikitext
*
* @var string
*/
private $appended = '';
/**
* String prepended to the wikitext
*
* @var string
*/
private $prepended = '';
/**
* Strings sobstituted from the wikitext
*
* @var array [ [ 'a', 'b' ], [ 'b', 'c' ] ]
*/
private $sobstitutions = [];
/**
* Constructor
*
* @param $site mw\Site MediaWiki site
* @param $wikitext string Wikitext
*/
public function __construct( $site, $wikitext ) {
$this->setWikitext( $wikitext );
$this->setSite( $site );
}
/**
* Get the MediaWiki site
*
* @return mw\Site
*/
public function getSite() {
return $this->site;
}
/**
* Get the complete wikitext
*
* @return string
*/
public function getWikitext() {
return $this->wikitext;
}
/**
* Set the MediaWiki site
*
* @return self
*/
public function setSite( $site ) {
$this->site = $site;
return $this;
}
/**
* Set the wikitext
*
* @param $wikitext string
* @return self
*/
public function setWikitext( $wikitext ) {
$this->wikitext = $wikitext;
return $this;
}
/**
* Append some wikitext
*
* @param $wikitext string
* @return self
*/
public function appendWikitext( $wikitext ) {
$this->appended .= $wikitext;
$this->setWikitext( $this->getWikitext() . $wikitext );
return $this;
}
/**
* Prepend some wikitext
*
* @param $wikitext string
* @return self
*/
public function prependWikitext( $wikitext ) {
$this->prepended .= $wikitext;
$this->setWikitext( $wikitext . $this->getWikitext() );
return $this;
}
/**
* Run a preg_match() on the wikitext
*
* @param $pattern string Pattern
* @param $matches array Matches
* @param $flags int
* @param $offset int
* @see preg_match()
*/
public function pregMatch( $pattern, & $matches = [], $flags = 0, $offset = 0 ) {
return preg_match( $pattern, $this->getWikitext(), $matches, $flags, $offset );
}
/**
* Run a preg_match_all() on the wikitext
*
* @param $pattern string Pattern
* @param $matches array Matches
* @param $flags int
* @param $offset int
* @see preg_match_all()
* @return int|false
*/
public function pregMatchAll( $pattern, & $matches = [], $flags = 0, $offset = 0 ) {
return preg_match_all( $pattern, $this->getWikitext(), $matches, $flags, $offset );
}
/**
* Run a preg_replace() on the wikitext
*
* @param $patterns string|array Pattern
* @param $replacement mixed Replacement where you can use group placeholders such as $0, $1 or ${0}, ${1}, ecc.
* Note that it does NOT support named parameter.
* @param $limit int Sobstitution limit
* @param $count int Sobstitution count
* @see preg_replace()
*/
public function pregReplace( $patterns, $replacement, $limit = -1, &$count = 0 ) {
// note that preg_replace() supports $pattern as array, but pregMatchAll() requires a string, so let's loop
if( ! is_array( $patterns ) ) {
$patterns = [ $patterns ];
}
foreach( $patterns as $pattern ) {
$n = $this->pregMatchAll( $pattern, $matches );
if( $n ) {
$groups = count( $matches );
for( $i = 0; $i < $n; $i++ ) {
$from = $matches[ 0 ][ $i ];
$to = $replacement;
foreach( $matches as $group_name => $groups ) {
$to = str_replace( [
'\\' . $group_name, // \\1
'$' . $group_name, // $1
'${' . $group_name . '}' // ${1}
], $groups[ $i ], $to );
}
$this->sobstitutions[] = [ $from, $to ];
}
}
}
if( $n ) {
$this->setWikitext( preg_replace( $patterns, $replacement, $this->getWikitext(), $limit, $count ) );
}
return $this;
}
/**
* Run a preg_replace_callback() on the wikitext
*
* @param $patterns string|array Pattern
* @param $callback callable
* @param $limit int Sobstitution limit
* @param $count int Sobstitution count
* @see preg_replace()
*/
public function pregReplaceCallback( $patterns, $callback, $limit = -1, &$count = 0 ) {
// note that preg_replace_callback() supports $pattern as array, but pregMatchAll() requires a string, so let's loop
if( ! is_array( $patterns ) ) {
$patterns = [ $patterns ];
}
foreach( $patterns as $pattern ) {
$n = $this->pregMatchAll( $pattern, $matches );
if( $n ) {
for( $i = 0; $i < $n; $i++ ) {
$groups = [];
foreach( $matches as $key => $_ ) {
$groups[ $key ] = $matches[ $key ][ $i ];
}
$from = $matches[ 0 ][ $i ];
$to = $callback( $groups );
$this->sobstitutions[] = [ $from, $to ];
}
}
}
if( $n ) {
$this->setWikitext( preg_replace_callback( $patterns, $callback, $this->getWikitext(), $limit, $count ) );
}
return $this;
}
/**
* Search and replace all the occurrences of a string from the wikitext
*
* @param $a mixed Search
* @param $b mixed Replace
* @param $count int Sobstitution count
* @return self
*/
public function strReplace( $a, $b, & $count = 0 ) {
$this->setWikitext( str_replace( $a, $b, $this->getWikitext(), $count ) );
for( $i = 0; $i < $count; $i++ ) {
$this->sobstitutions[] = [ $a, $b ];
}
return $this;
}
/**
* It has a Category? (it checks only the wikitext)
*
* @param $category_name string Category without namespace prefix
* @return bool
*/
public function hasCategory( $category_name ) {
- $category_name_regex = Title::factory( $category_name )->getRegexFirstCaseInsensitive();
- $category_name_regex = \regex\Generic::spaceBurger( $category_name_regex );
- $category_ns_titleparts = $this->getSite()->getNamespace( 14 )->getAllTitlePartsCapitalized();
- $category_ns_regexes = [];
- foreach( $category_ns_titleparts as $category_ns_titlepart ) {
- $category_ns_regexes[] = $category_ns_titlepart->getRegexFirstCaseInsensitive();
- }
+ // category with whatever sortkey
+ $category = $this->getSite()
+ ->createTitle( $category_name, 14 )
+ ->createWikilink( Wikilink::WHATEVER_ALIAS );
- $whatever_sortkey = '(\|.*?)?';
- foreach( $category_ns_regexes as $category_ns_regex ) {
- $category_ns_regex = \regex\Generic::spaceBurger( $category_ns_regex );
- $pattern = sprintf(
- '/\[\[%s\]\]/',
- $category_ns_regex . ':' . $category_name_regex . $whatever_sortkey
- );
- if( 1 === $this->pregMatch( $pattern ) ) {
- return true;
- }
- }
+ // category wiki syntax
+ $category_regex = $category->getRegex( [
+ 'wikilink' => false,
+ ] );
- return false;
+ return 1 === $this->pregMatch( "/$category_regex/" );
}
/**
* Add a Category
*
* @param $category_name string Category name without category prefix
* @param $sortkey string
* @return bool
*/
- public function addCategory( $category_name, $sortkey = null ) {
+ public function addCategory( $category_name, $sortkey = false ) {
if( $this->hasCategory( $category_name ) ) {
return false;
}
- $category_namespace = $this->getSite()->getNamespace( 14 )->getName();
- $this->appendWikitext( sprintf(
- "\n[[%s:%s%s]]",
- $category_namespace,
- $category_name,
- $sortkey ? "|$sortkey" : ''
- ) );
+
+ $category = $this->getSite()
+ ->createTitle( $category_name, 14 )
+ ->createWikilink( $sortkey );
+
+ // [[Category:asd|sortkey]]
+ $category_wlink = $category->getWikitext( [ 'wikilink' => false ] );
+
+ $this->appendWikitext( "\n$category_wlink" );
return true;
}
/**
* Removes a category
*
* @param string $category_name Category name, unprefixed
* @return bool
*/
public function removeCategory( $category_name ) {
if( !$this->hasCategory( $category_name ) ) {
return false;
}
- $category_namespace = $this->getSite()->getNamespace( 14 )->getName();
- $this->pregReplace(
- sprintf(
- "![[%s:%s]]\s*!",
- $category_namespace,
- $category_name
- )
- ''
- );
+
+ $category = $this->getSite()
+ ->createTitle( $category_name )
+ ->createWikilink( Wikilink::WHATEVER_ALIAS );
+
+ $category_pattern = $category->getRegex( [ 'wikilink' => false ] );
+ $this->pregReplace( "/$category_pattern\s*\n?/", '' );
return true;
}
-
+
/**
* Get the prepended wikitext
*
* @return string
*/
public function getPrepended() {
return $this->prepended;
}
/**
* Get the appended wikitext
*
* @return string
*/
public function getAppended() {
return $this->appended;
}
/**
* Get the sobstituted wikitext
*
* @return array [ [ 'a', 'b' ], [ 'b', 'c' ] ]
*/
public function getSobstitutions() {
return $this->sobstitutions;
}
/**
* Count the sobstitutions in the wikitext
*
* @return int
*/
public function countSobstitutions() {
return count( $this->getSobstitutions() );
}
/**
* Check if there were changes since creation
*
* @return bool
*/
public function isChanged() {
return $this->countSobstitutions() || $this->prepended || $this->appended;
}
/**
* Get the sobstituted wikitext without repetitions
*
* It also count the repetitions
*
* @return array [ [ 'a', 'b', 1 ], [ 'b', 'c', 2 ] ]
*/
public function getUniqueSobstitutions() {
$seen = [];
foreach( $this->getSobstitutions() as $sobstitution ) {
list( $a, $b ) = $sobstitution;
@$seen[ $a ][ $b ]++;
}
$sobstitutions = [];
foreach( $seen as $a => $_ ) {
foreach( $_ as $b => $n ) {
$sobstitutions[] = [ $a, $b, $n ];
}
}
return $sobstitutions;
}
/**
* Get a boring array of human sobstitution messages
*
* @return array
*/
public function getHumanUniqueSobstitutions() {
$things = [];
foreach( $this->getUniqueSobstitutions() as $abn ) {
list( $a, $b, $n ) = $abn;
$many = 1 === $n
? "1 time"
: sprintf( "$n times", $n );
$things[] = sprintf( "%s → %s (%s)", $a, $b, $many );
}
return $things;
}
}

File Metadata

Mime Type
text/x-diff
Expires
Thu, Nov 19, 02:58 (21 h, 53 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
2263983
Default Alt Text
(40 KB)

Event Timeline