Refbase update_2021-01-28_15_58

This commit is contained in:
root
2021-01-28 15:58:21 +01:00
commit 64e7261da6
300 changed files with 164739 additions and 0 deletions

156
contrib/mediawiki/README Normal file
View File

@@ -0,0 +1,156 @@
refbase extension for MediaWiki
===============================
Authors
-------
Richard Karnesky <karnesky@gmail.com>
Thibault Marin <thibault.marin at gmx dot com>
About
-----
This is an extension to MediaWiki:
<https://www.mediawiki.org/>
It allows you to cite references by enclosing the serial or the citation key
in tags such as:
<refbase>17</refbase> or <refbase>Author2000</refbase>
To install the extension, download and extract the files in a directory called
Refbase in your mediawiki extensions/ folder. Add the following code at the
bottom of your LocalSettings.php:
require_once( "$IP/extensions/Refbase/Refbase.php" );
To verify that the extension is successfully installed, go to the
"Special:Version" page on your wiki, you should see the Refbase extension in
the list of parser hook extensions.
To configure the extension, add the following lines (modified to match your
setup) after the 'require_once' line in your LocalSettings.php (omitted fields
take the default value indicated here):
$wgRefbaseDbHost = "localhost"; // refbase database host
$wgRefbaseDbName = "literature"; // Database name
$wgRefbaseDbUser = "litwww"; // User name for database
$wgRefbaseDbPass = "%l1t3ratur3?"; // Database password
$wgRefbaseDbCharset = "utf8"; // Database charset
$wgRefbaseDbRefTable = "refs"; // Table with references
$wgRefbaseDbUserDataTable = "user_data"; // Table with cite_key field
$wgRefbaseDbAccessMethod = "mysql"; // Database access mode
// 'mysql' or 'PDO'
// Host for refbase instance (used for url links). This may differ from the
// database host (requires a trailing slash)
$wgRefbaseURL = "http://".$_SERVER['HTTP_HOST']."/refbase/";
// HTTP (basic) authentication mode when accessing refbase instance (only
// used with 'cite' and 'link' output types, when using a 'rb-*' citation
// type), see below for details.
$wgRefbaseURLAuth = ''; // '', 'default' or 'user:pass'
A few options can also be set (see below for description):
// Tag type
$wgRefbaseDefaultTagType = 'serial'; // 'serial' or 'citekey'
// Output type
$wgRefbaseDefaultOutputType = 'cite_journal'; // 'cite_journal', 'cite'
// or 'link'
// Citation type
$wgRefbaseDefaultCitationType = 'minimal'; // 'minimal' or 'rb-*'
Options
-------
0. Scope
All options are set globally (by the $wgRefbaseDefault* variables) for the
whole wiki. Most can also be modified for individual instances of the
<refbase> tag by passing extra arguments to the tag, e.g. <refbase
tagtype='citekey' output='cite'>XXX</refbase>.
1. Tag type
Possible values: 'serial', 'citekey'
Global setting
$wgRefbaseDefaultTagType = 'serial';
Individual setting
<refbase tagtype='serial'>XXX</refbase>
This option controls the interpretation of the tag input: when using the
refbase tag in wikipages, e.g. <refbase>XXX</refbase>, the input key (XXX)
can refer to the serial number ('serial' type) or the citation key
('citekey' type). Note that if no entry is found using the selected tag
type, a second search is performed with the other tag type.
2. Output type
Possible values: 'cite_journal', 'cite', 'link'
Global setting
$wgRefbaseDefaultOutputType = 'cite_journal';
Individual setting
<refbase output='cite_journal'>XXX</refbase>
This option determines the way citations are rendered in the wikipage. There
are several modes:
.'cite_journal': This is the default mode, used in version 0.9 of the
extension. The output will use citation templates, as are used on
Wikipedia:
<https://en.wikipedia.org/wiki/Wikipedia:Citation_templates>
Currently, only journal articles may be cited with this output type. In
the future, this extension is likely to be modified. 'refbase' should
be able to generate WP citation templates as an export format & this
extension should make use of that functionality directly.
.'cite': This mode uses the Cite extension
<https://www.mediawiki.org/wiki/Extension:Cite>
A footnote is generated for each citation using the <ref> tag. Multiple
references to the same entry are automatically combined using the <ref
name=YYY> option. To see the list of references a <references/> tag
must be added to the wikipage where the bibliography should be
displayed. See the Cite extension documentation for details. The
footnote text is a citation following the 'citation type' option (see
below).
.'link': This is a simple renderer which does not require any installed
template/extension. It simply writes the tag input (serial or citation
key) to the wikipage, adding a tooltip and a hyperlink to the refbase
entry. The tooltip contains the citation text (controlled by the
citation type variable) and the hyperlink links to the refbase page (the
base refbase installation location is given by the $wgRefbaseURL
variable).
3. Citation type
Possible values: 'minimal, 'rb-default', 'rb-MLA', 'rb-APA', etc.
Global setting
$wgRefbaseDefaultCitationType = 'minimal';
Individual setting
<refbase citationtype='minimal'>XXX</refbase>
This option determines how citations are rendered in the 'cite' and 'link'
output modes (it has no effect when using the 'cite_journal' output type).
The two possible modes are:
.'minimal': This generates a simple citation with the authors, title,
publication and year.
.'rb-*': This requests the citation text from the refbase web interface.
The * in 'rb-*' can be 'default' (i.e. 'rb-default') or any acceptable
citation style (defined in the 'styles' database).
4. Database connection mode
Possible values: 'mysql', 'PDO'
Global setting
$wgRefbaseDbAccessMethod = 'mysql';
Individual setting
This option can only be set at the global level.
This option selects the way the extension connects to the mysql database.
The 'mysql' mode is getting deprecated in recent versions of php, but is
still available for older installations.
5. HTTP authentication for requests to refbase instance
Possible values: '', 'default' or 'user:pass'
Global setting
$wgRefbaseURLAuth = '';
Individual setting
This option can only be set at the global level.
This option is used to pass an HTTP authentication token to the server
hosting the refbase installation (basic authentication e.g. from apache
server). If $wgRefbaseURLAuth is empty (''), no authentication is passed.
If set to 'default', the current user/password token will be passed when
requesting data from the refbase web interface (this is useful when both
mediawiki and refbase are under the same basic server authentication). To
specify an arbitrary user and password, set $wgRefbaseURLAuth to 'user:pass'
where 'user' is the username and 'pass' the password for that user (note
that the username cannot contain colon characters ':'). This option is
relevant only when using the 'cite' or 'link' output types along with one of
the 'rb-*' citation type.
Notes
-----
You may also be interested in the MonoBook skin, included in the
'contrib/skins/mediawiki-monobook' directory from refbase.
An installation of MediaWiki that uses this extension is the Northwestern
University Center for Atom-Probe Tomography:
<http://arc.nucapt.northwestern.edu/#Literature>

View File

@@ -0,0 +1,113 @@
<?php
/**
* Refbase hooks and parser
*/
class RefbaseHooks {
/**
* Register <refbase> hook
*/
public static function efRefbaseParserInit( $parser ) {
$parser->setHook( 'refbase',
'RefbaseHooks::efRefbaseRender' );
return true;
}
/**
* Define special formatting for this tag
*/
private static function makeOutputString ( $str ) {
return $str;
}
/**
* Add <pre></pre> tags around error message and return
*/
private static function makeErrorOutputString ( $errMsg ) {
$errMsg = "Refbase: <br/>" . $errMsg;
$preMsg = Html::openElement( 'pre' ) . $errMsg .
Html::closeElement( 'pre' );
return self::makeOutputString( $preMsg );
}
/**
* Main function: parse input and create HTML table with events
*/
public static function efRefbaseRender( $input, array $args,
Parser $parser,
PPFrame $frame ) {
// Global parameters
global $wgRefbaseDefaultTagType;
global $wgRefbaseDefaultOutputType;
global $wgRefbaseDefaultCitationType;
// Read arguments
if ( isset( $args['tagtype'] ) ) {
$tagType = $args['tagtype'];
} else {
$tagType = $wgRefbaseDefaultTagType;
}
if ( ! ( strtolower( $tagType ) === 'serial' ) &&
! ( strtolower( $tagType ) === 'citekey' ) ) {
$errStr = wfMessage( 'refbase-error-tagtype' )->text();
return self::makeErrorOutputString( $errStr );
}
if ( isset( $args['output'] ) ) {
$outputType = $args['output'];
} else {
$outputType = $wgRefbaseDefaultOutputType;
}
if ( ! ( strtolower( $outputType ) === 'cite_journal' ) &&
! ( strtolower( $outputType ) === 'link' ) &&
! ( strtolower( $outputType ) === 'cite' ) ) {
$errStr = wfMessage( 'refbase-error-outputtype' )->text();
return self::makeErrorOutputString( $errStr );
}
if ( isset( $args['citationtype'] ) ) {
$citationType = $args['citationtype'];
} else {
$citationType = $wgRefbaseDefaultCitationType;
}
if ( ! ( strtolower( $citationType ) === 'minimal' ) &&
! ( strtolower( substr( $citationType, 0, 3 ) ) === 'rb-' ) ) {
$errStr = wfMessage( 'refbase-error-citation-type' )->text();
return self::makeErrorOutputString( $errStr );
}
// Order tag types
switch ( strtolower( $tagType ) ) {
case 'serial':
$tagTypeList = array( 'serial', 'citekey' );
break;
case 'citekey':
$tagTypeList = array( 'citekey', 'serial' );
break;
}
// Instantiate renderer based on options
$refbaseRenderer = RefbaseRenderer::create( $outputType,
$citationType );
// Request list of fields to extract
$fieldList = $refbaseRenderer->getFieldList();
// Perform database query to get entry
$refbaseDbConnector = new RefbaseConnector();
$entry = "";
if ( !$refbaseDbConnector->getEntry( $input, $tagTypeList, $entry,
$fieldList ) ) {
return self::makeErrorOutputString( $entry );
}
// Generate output
$citekey = $input;
$renderOpts = array( 'citekey' => $citekey );
$outputStr = "";
if ( !$refbaseRenderer->render( $entry, $outputStr, $renderOpts ) ) {
return self::makeErrorOutputString( $outputStr );
}
$outputStr = $parser->recursiveTagParse( $outputStr );
return self::makeOutputString( $outputStr );
}
}

View File

@@ -0,0 +1,35 @@
<?php
/**
* This is a backwards-compatibility shim, generated by:
* https://git.wikimedia.org/blob/mediawiki%2Fcore.git/HEAD/maintenance%2FgenerateJsonI18n.php
*
* Beginning with MediaWiki 1.23, translation strings are stored in json files,
* and the EXTENSION.i18n.php file only exists to provide compatibility with
* older releases of MediaWiki. For more information about this migration, see:
* https://www.mediawiki.org/wiki/Requests_for_comment/Localisation_format
*
* This shim maintains compatibility back to MediaWiki 1.17.
*/
$messages = array();
if ( !function_exists( 'wfJsonI18nShime97052c48294abb71' ) ) {
function wfJsonI18nShime97052c48294abb71( $cache, $code, &$cachedData ) {
$codeSequence = array_merge( array( $code ), $cachedData['fallbackSequence'] );
foreach ( $codeSequence as $csCode ) {
$fileName = dirname( __FILE__ ) . "/i18n/$csCode.json";
if ( is_readable( $fileName ) ) {
$data = FormatJson::decode( file_get_contents( $fileName ), true );
foreach ( array_keys( $data ) as $key ) {
if ( $key === '' || $key[0] === '@' ) {
unset( $data[$key] );
}
}
$cachedData['messages'] = array_merge( $data, $cachedData['messages'] );
}
$cachedData['deps'][] = new FileDependency( $fileName );
}
return true;
}
$GLOBALS['wgHooks']['LocalisationCacheRecache'][] = 'wfJsonI18nShime97052c48294abb71';
}

View File

@@ -0,0 +1,105 @@
<?php
// Copyright: Richard Karnesky <mailto:karnesky@gmail.com>
// This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY.
// Please see the GNU General Public License for more details.
if( !defined( 'MEDIAWIKI' ) )
{
echo( "This is an extension to the MediaWiki package and cannot be run standalone.\n" );
die( -1 );
}
$wgExtensionCredits['parserhook'][] = array(
'path' => __FILE__,
'name' => 'Refbase',
'author' => array( 'Richard Karnesky', 'Thibault Marin' ),
'url' => 'https://www.mediawiki.org/wiki/Extension:Refbase',
'descriptionmsg' => 'refbase-desc',
'version' => '1.0',
'license-name' => '' // Short name of the license, links LICENSE or COPYING file if existing - string, added in 1.23.0
);
/**
* Extension class
*/
$wgAutoloadClasses['RefbaseHooks'] =
dirname( __FILE__ ) . '/Refbase.Hooks.php';
$wgAutoloadClasses['RefbaseRenderer'] =
dirname( __FILE__ ) . '/include/Refbase.Renderer.php';
$wgAutoloadClasses['RefbaseRendererCitationTemplate'] =
dirname( __FILE__ ) . '/include/Refbase.Renderer.CitationTemplate.php';
$wgAutoloadClasses['RefbaseRendererLink'] =
dirname( __FILE__ ) . '/include/Refbase.Renderer.Link.php';
$wgAutoloadClasses['RefbaseRendererCite'] =
dirname( __FILE__ ) . '/include/Refbase.Renderer.Cite.php';
$wgAutoloadClasses['RefbaseConnector'] =
dirname( __FILE__ ) . '/include/Refbase.Connector.php';
$wgAutoloadClasses['RefbaseCitationCreator'] =
dirname( __FILE__ ) . '/include/Refbase.CitationCreator.php';
$wgAutoloadClasses['RefbaseCitationType'] =
dirname( __FILE__ ) . '/include/Refbase.CitationCreator.php';
$wgAutoloadClasses['RefbaseTools'] =
dirname( __FILE__ ) . '/include/Refbase.Tools.php';
/**
* Register hooks
*/
$wgHooks['ParserFirstCallInit'][] = 'RefbaseHooks::efRefbaseParserInit';
/**
* Internationalization
*/
$wgMessagesDirs['Refbase'] = __DIR__ . '/i18n';
$wgExtensionMessagesFiles['Refbase'] =
dirname( __FILE__ ) . '/Refbase.i18n.php';
/**
* Parameters (modify in LocalSettings.php)
*/
// refbase database host
$wgRefbaseDbHost = "localhost";
// Database name
$wgRefbaseDbName = "literature";
// User name for database
$wgRefbaseDbUser = "litwww";
// Database password
$wgRefbaseDbPass = "%l1t3ratur3?";
// Database charset
$wgRefbaseDbCharset = "utf8";
// Table with references
$wgRefbaseDbRefTable = "refs";
// Table with user data (cite key)
$wgRefbaseDbUserDataTable = "user_data";
// Extension to interface with database ('mysql' or 'PDO')
$wgRefbaseDbAccessMethod = "mysql";
// Host for refbase instance (used for url links). This may differ from the
// database host if using https for instance (requires a trailing slash)
$wgRefbaseURL = "http://".$_SERVER['HTTP_HOST']."/refbase/";
// Default tag input: when using <refbase>XXX</refbase>, XXX can refer to the
// serial number ('serial' type) or the citation key ('citekey' type)
$wgRefbaseDefaultTagType = "serial";
// Default output type: may use cite_journal, cite or link
$wgRefbaseDefaultOutputType = 'cite_journal';
// Default citation type: 'minimal' or 'rb-default' (only for 'link' and 'cite' modes)
//$wgRefbaseDefaultCitationType = 'minimal';
$wgRefbaseDefaultCitationType = 'rb-default';
// Option to pass http authentication token when accessing the refbase web
// interface (used for rb-* citation types). If empty, authentication is
// disabled. If set to 'default', use the same token as the one used for the
// mediawiki web site (if any). If this option is set to 'user:pass', then
// 'user' and 'pass' will be used to form the token (the colon character ':' is
// not allowed in the username).
$wgRefbaseURLAuth = '';

View File

@@ -0,0 +1,16 @@
{
"@metadata": {
"authors": [
"thibault marin"
]
},
"refbase-desc": "This extension allows inclusion of bibliographic references from a refbase installation.",
"refbase-error-tagtype" : "Unsupported tag type (should be 'serial' or 'citekey').",
"refbase-error-outputtype" : "Unsupported output type (should be 'cite_journal', 'cite' or 'link').",
"refbase-error-dbquery" : "Error in database query: ",
"refbase-error-mysqlconn" : "Could not connect to mysql database.",
"refbase-error-mysqldb" : "Could not select mysql database: ",
"refbase-error-notfound" : "Entry not found.",
"refbase-error-cite_journal-type": "cite_journal mode can only display journal articles.",
"refbase-error-citation-type" : "Citation type unsupported (should be 'minimal' or 'rb-???')."
}

View File

@@ -0,0 +1,16 @@
{
"@metadata": {
"authors": [
"thibault marin"
]
},
"refbase-desc": "{{desc}}",
"refbase-error-tagtype" : "Error message displayed when the tag type used is not supported.",
"refbase-error-outputttype" : "Error message displayed when the output type used is not supported.",
"refbase-error-dbquery" : "Error message displayed when refbase database query failed (followed by error message).",
"refbase-error-mysqlconn" : "Error message displayed when mysql connection failed (using the mysql extension).",
"refbase-error-mysqldb" : "Error message displayed when mysql database selection failed (using the mysql extension), error message follows",
"refbase-error-notfound" : "Error message displayed when key was not gound in database",
"refbase-error-cite_journal-type": "Error message displayed when cite_journal is used with non-journal entry.",
"refbase-error-citation-type" : "Error message displayed when trying to create a citation of an unsupported type."
}

View File

@@ -0,0 +1,144 @@
<?php
/**
* Enum for citation types
*/
abstract class RefbaseCitationType {
// Minimal reference type (author, title, publication, year)
const CT_MINIMAL = 0;
// Request citation from refbase installation (using show.php interface)
const CT_RB = 1;
/**
* Convert string to RefbaseCitationType
*/
static public function decodeCitationType ( $str, & $citeStyle ) {
if ( strtolower( $str ) == 'minimal' ) {
return self::CT_MINIMAL;
} elseif ( preg_match( '/rb-(.*)/', strtolower( $str ),
$citeStyle ) ) {
return self::CT_RB;
} else {
return null;
}
}
}
/**
* Helper class to generate citation text
*/
class RefbaseCitationCreator {
/// Citation type
private $citationType;
/// Citation style (only with $citationType = CT_RB)
private $citationStyle = "";
/// Location of refbase installation (may differ from $dbHost if using https
/// for instance)
protected $refbaseURL = "";
/**
* Constructor
*/
public function __construct( $citationTypeStr ) {
global $wgRefbaseURL;
$this->refbaseURL = $wgRefbaseURL;
$this->citationType =
RefbaseCitationType::decodeCitationType( $citationTypeStr,
$citeStyle );
if ( !empty( $citeStyle ) ) {
$this->citationStyle = $citeStyle[1];
}
wfDebug('refbase-decode-in:' . $citationTypeStr . "\n");
wfDebug('refbase-decode:' . $this->citationType . ", " . var_export($this->citationStyle,true)."\n");
}
/**
* Create citation text
*/
public function createCitation( $entry, & $cite ) {
switch( $this->citationType ) {
case RefbaseCitationType::CT_MINIMAL:
$cite = $entry['author'] . ", " . $entry['title'] . ", " .
$entry['publication'] . ", " . $entry['year'] . ".";
break;
case RefbaseCitationType::CT_RB:
$url = $this->refbaseURL . "show.php?" .
"record=" . "27711"//$entry['serial'] .
"&submit=Cite&exportType=text&citeType=ASCII";
if ( !empty( $this->citationStyle ) ) {
$url .= "&citeStyle=" . $this->citationStyle;
}
wfDebug('refbase-getcite:' . $url . "\n");
// Get citation from url (add http authentication if desired)
global $wgRefbaseURLAuth;
if ( !empty( $wgRefbaseURLAuth ) ) {
if ( strcmp( strtolower( $wgRefbaseURLAuth ),
'default' ) == 0 ) {
if ( isset( $_SERVER['PHP_AUTH_USER'] ) &&
isset( $_SERVER['PHP_AUTH_PW'] ) ) {
$username = $_SERVER['PHP_AUTH_USER'];
$password = $_SERVER['PHP_AUTH_PW'];
$authStr = "Authorization: Basic " .
base64_encode( "$username:$password" );
} else {
$authStr = '';
}
} else {
preg_match( "/([^:]*):(.*)$/", $wgRefbaseURLAuth, $out);
$username = $out[1];
$password = $out[2];
$authStr = "Authorization: Basic " .
base64_encode( "$username:$password" );
}
$param = array( 'http' => array( 'header' => $authStr ) );
$context = stream_context_create( $param );
$cite = trim( file_get_contents( $url, false, $context ) );
} else {
$cite = trim( file_get_contents( $url ) );
}
break;
default:
$cite = wfMessage( 'refbase-error-citation-type' )->text();
}
return true;
}
/*
* Get list of required fields to produce the citation in the desired format
*/
public function getFieldList() {
switch( $this->citationType ) {
case RefbaseCitationType::CT_MINIMAL:
$fieldList = array( 'author',
'title',
'publication',
'year' );
break;
case RefbaseCitationType::CT_RB:
$fieldList = array( 'serial' );
break;
default:
$fieldList = array();
}
return $fieldList;
}
}

View File

@@ -0,0 +1,139 @@
<?php
/**
* Refbase database connector
*/
class RefbaseConnector {
/// Database location
private $dbHost = "";
/// Database name
private $dbName = "";
/// Database user
private $dbUser = "";
/// Database password
private $dbPass = "";
/// Character set
private $dbCharset = "";
/// Reference table
private $dbRefTable = "";
/// User data table (for cite key entry)
private $dbUserDataTable = "";
/// Method to access database (mysql or PDO)
private $dbAccessMethod = "";
/**
* Constructor
*/
public function __construct() {
global $wgRefbaseDbHost;
global $wgRefbaseDbName;
global $wgRefbaseDbUser;
global $wgRefbaseDbPass;
global $wgRefbaseDbRefTable;
global $wgRefbaseDbUserDataTable;
global $wgRefbaseDbCharset;
global $wgRefbaseDbAccessMethod;
// Read from global configuration
$this->dbHost = $wgRefbaseDbHost;
$this->dbName = $wgRefbaseDbName;
$this->dbUser = $wgRefbaseDbUser;
$this->dbPass = $wgRefbaseDbPass;
$this->dbRefTable = $wgRefbaseDbRefTable;
$this->dbUserDataTable = $wgRefbaseDbUserDataTable;
$this->dbCharset = $wgRefbaseDbCharset;
$this->dbAccessMethod = $wgRefbaseDbAccessMethod;
}
/**
* Query by serial number or cite key entry
*/
public function getEntry( $input, $tagTypeList, & $outputEntry,
$fieldList ) {
// List of fields to extract (prefix 'r.' to each element)
$fieldPref = $fieldList;
array_walk( $fieldPref, function ( &$value, $key) {
$value="r.$value";
} );
$fieldPref = join(",", $fieldPref);
$flagFound = false;
for ( $i = 0; $i < count($tagTypeList) && ! $flagFound; $i++ ) {
$tagType = $tagTypeList[$i];
// Query string
$queryStr = "";
if ( $tagType === 'citekey' ) {
$queryStr = "SELECT $fieldPref " .
"FROM " . $this->dbRefTable . " r " .
"INNER JOIN " . $this->dbUserDataTable . " u " .
"ON r.serial = u.record_id " .
"WHERE u.cite_key='$input'";
} else {
$queryStr = "SELECT $fieldPref " .
"FROM " . $this->dbRefTable . " r " .
"WHERE r.serial='$input'";
}
if ( strtolower( $this->dbAccessMethod ) === 'pdo' ) {
// Connect and query
$link = new PDO( 'mysql:host=' . $this->dbHost . ';dbname=' .
$this->dbName . ';charset=' . $this->dbCharset,
$this->dbUser, $this->dbPass );
$dbexec = $link->prepare( $queryStr );
try {
// Perform query
$outputEntry = $dbexec->execute();
} catch( PDOException $ex ) {
$outputEntry = wfMessage( 'refbase-error-dbquery' )->text() .
$ex->getMessage();
return false;
}
$outputEntry = $dbexec->fetch(PDO::FETCH_ASSOC);
} elseif ( strtolower( $this->dbAccessMethod ) === 'mysql' ) {
$link = mysqli_connect( $this->dbHost, $this->dbUser, $this->dbPass, $this->dbName ) or die("db error");
if ( !$link ) {
$outputEntry = wfMessage( 'refbase-error-mysqlconn' )->text();
return false;
}
$result = mysqli_query($link, $queryStr );
if ( !$result ) {
$outputEntry = wfMessage( 'refbase-error-dbquery' )->text() .
mysqli_error($link);
return false;
}
$outputEntry = mysqli_fetch_array($result);
}
if ( !empty( $outputEntry ) ) {
$flagFound = true;
}
}
if ( empty( $outputEntry ) ) {
$outputEntry = wfMessage( 'refbase-error-notfound' )->text();
return false;
}
return true;
}
}

View File

@@ -0,0 +1,113 @@
<?php
/**
* Refbase entry renderer using citation templates (cite_journal only for now)
*/
class RefbaseRendererCitationTemplate extends RefbaseRenderer {
/**
* Constructor (simply inherit from parent)
*/
public function __construct() {
parent::__construct();
}
/**
* List fields required to build template
*/
public function getFieldList() {
return array( 'type',
'serial',
'author',
'year',
'title',
'language',
'publication',
'volume',
'issue',
'pages',
'place',
'publisher',
'issn',
'doi' );
}
/**
* Prepare text for template (supports journal articles only)
*/
public function render( $entry, & $cite, $options ) {
$cite = "";
$ret = true;
if ( $entry["type"] == "Journal Article" ) {
$cite .= "{{cite_journal|url=" . $this->refbaseURL . "show.php?";
$cite .= "record=" . $entry['serial'];
if( !empty( $entry["author"] ) ) {
$author = $entry["author"];
$aulast = RefbaseTools::extractAuthorsLastName
( " *; *", " *, *", 1, $author );
$aufirst = RefbaseTools::extractAuthorsGivenName
( " *; *", " *, *", 1, $author );
if( !empty( $aulast ) ) {
$cite .= "|last=" . $aulast;
}
if( !empty( $aufirst ) ) {
$cite .= "|first=" . $aufirst;
if( !empty( $aulast ) ) {
$cite .= "|authorlink=$aufirst $aulast";
}
}
$authorcount = count( preg_split( "/ *; */", $author ) );
$au = "";
for ( $i=0; $i < $authorcount - 1; $i++ ) {
$aul = RefbaseTools::extractAuthorsLastName
( " *; *", " *, *", $i + 2, $author );
$auf = RefbaseTools::extractAuthorsGivenName
( " *; *", " *, *", $i + 2, $author );
if ( !empty( $aul ) ) {
if ( !empty( $auf ) ) {
$au .= "[[$auf $aul|$aul, $auf]]; ";
}
}
}
if ( !empty( $au ) ) {
$cite .= "|coauthors=" . trim( $au, '; ' );
}
}
if( !empty( $entry["year"] ) ) {
$cite .= "|year=" . $entry['year'];
}
if( !empty( $entry["title"] ) ) {
$title = RefbaseTools::searchReplaceText( $entry['title'],
true );
$cite .= "|title=" . $title;
}
if( !empty( $entry["language"] ) )
$cite .= "|language=" . $entry['language'];
if( !empty( $entry["publication"] ) )
$cite .= "|journal=" . $entry['publication'];
if( !empty( $entry["volume"] ) )
$cite .= "|volume=" . $entry['volume'];
if( !empty( $entry["issue"] ) )
$cite .= "|issue=" . $entry['issue'];
if( !empty( $entry["pages"] ) )
$cite .= "|pages=" . $entry['pages'];
if( !empty( $entry["place"] ) )
$cite .= "|location=" . $entry['place'];
if( !empty( $entry["publiser"] ) )
$cite .= "|publisher=" . $entry['publisher'];
if( !empty( $entry["issn"] ) )
$cite .= "|issn=" . $entry['issn'];
if( !empty( $entry["doi"] ) )
$cite .= "|doi=" . $entry['doi'];
$cite .= "}}";
$ret &= true;
} else {
$cite .= wfMessage( 'refbase-error-cite_journal-type' )->text();
$ret &= false;
}
return $ret;
}
}

View File

@@ -0,0 +1,48 @@
<?php
/**
* Refbase entry renderer using the Cite extension tag (<ref>)
*/
class RefbaseRendererCite extends RefbaseRenderer {
/// Object generating citations
private $citationCreator;
/**
* Constructor (simply inherit from parent)
*/
public function __construct( $citationType ) {
parent::__construct();
$this->citationCreator = new RefbaseCitationCreator( $citationType );
}
/**
* List fields required to build template
*/
public function getFieldList() {
$citeList = $this->citationCreator->getFieldList();
return array_unique( array_merge( array(), $citeList ) );
}
/**
* Render output: add wiki link to refbase page, include citation in tooltip
*/
public function render( $entry, & $cite, $options ) {
$citekey = $options['citekey'];
$cite = "";
// Simply link to refbase, and add tooltip
// (form string [URL <span title="CITATION"> KEY </span>] )
$citation = "";
$this->citationCreator->createCitation( $entry, $citation );
// Use #tag method to properly pass inputs to <ref>
$cite .= "{{#tag:ref|$citation|name=$citekey}}";
return true;
}
}

View File

@@ -0,0 +1,56 @@
<?php
/**
* Refbase entry renderer using simple hyperlink and tooltip
*/
class RefbaseRendererLink extends RefbaseRenderer {
/// Object generating citations
private $citationCreator;
/**
* Constructor (simply inherit from parent)
*/
public function __construct( $citationType ) {
parent::__construct();
$this->citationCreator = new RefbaseCitationCreator( $citationType );
}
/**
* List fields required to build template
*/
public function getFieldList() {
$citeList = $this->citationCreator->getFieldList();
return array_unique( array_merge( array( 'serial' ), $citeList ) );
}
/**
* Render output: add wiki link to refbase page, include citation in tooltip
*/
public function render( $entry, & $cite, $options ) {
$citekey = $options['citekey'];
$cite = "";
// Simply link to refbase, and add tooltip
// (form string [URL <span title="CITATION"> KEY </span>] )
// Display the key (cite_key or serial number as wiki text)
$wikiText = $citekey;
// Add full citation as a tooltip
$toolTip = "";
$this->citationCreator->createCitation( $entry, $toolTip );
// Link to refbase page for current entry
$link = $this->refbaseURL . "show.php?record=" . $entry['serial'];
// Build full string
$cite .= "[" . $link . " ";
$cite .= Html::openElement( 'span', array( 'title' => "\"" . $toolTip . "\"" ) );
$cite .= $wikiText . Html::closeElement( 'span' ) . "]";
return true;
}
}

View File

@@ -0,0 +1,46 @@
<?php
/**
* Refbase entry renderer
*/
abstract class RefbaseRenderer {
/// Location of refbase installation (may differ from $dbHost if using https
/// for instance)
protected $refbaseURL = "";
/**
* Constructor
*/
public function __construct() {
global $wgRefbaseURL;
$this->refbaseURL = $wgRefbaseURL;
}
/**
* Instantiation subclass instances
*/
public static function create( $outputType, $citationType = "" ) {
if ( strtolower( $outputType ) == 'cite_journal' ) {
return new RefbaseRendererCitationTemplate();
} elseif ( strtolower( $outputType ) == 'link' ) {
return new RefbaseRendererLink( $citationType );
} elseif ( strtolower( $outputType ) == 'cite' ) {
return new RefbaseRendererCite( $citationType );
} else {
return false;
}
}
/**
* Returns the list of fields to extract from the database
*/
abstract public function getFieldList();
/**
* Render entries
*/
abstract public function render( $entry, & $cite, $options );
}

View File

@@ -0,0 +1,130 @@
<?php
/**
* Refbase helper functions (cleanup strings, author extraction)
*/
class RefbaseTools {
/// Character translation table
private static $transtab_refbase_html = array(
"/__(?!_)(.+?)__/" => "<u>\\1</u>", // the pattern for underline (__...__) must come before the one for italic (_..._)
"/_(.+?)_/" => "<i>\\1</i>",
"/\\*\\*(.+?)\\*\\*/" => "<b>\\1</b>",
"/\\[super:(.+?)\\]/i" => "<sup>\\1</sup>",
"/\\[sub:(.+?)\\]/i" => "<sub>\\1</sub>",
"/\\[permil\\]/" => "&permil;",
"/\\[infinity\\]/" => "&infin;",
"/\\[alpha\\]/" => "&alpha;",
"/\\[beta\\]/" => "&beta;",
"/\\[gamma\\]/" => "&gamma;",
"/\\[delta\\]/" => "&delta;",
"/\\[epsilon\\]/" => "&epsilon;",
"/\\[zeta\\]/" => "&zeta;",
"/\\[eta\\]/" => "&eta;",
"/\\[theta\\]/" => "&theta;",
"/\\[iota\\]/" => "&iota;",
"/\\[kappa\\]/" => "&kappa;",
"/\\[lambda\\]/" => "&lambda;",
"/\\[mu\\]/" => "&mu;",
"/\\[nu\\]/" => "&nu;",
"/\\[xi\\]/" => "&xi;",
"/\\[omicron\\]/" => "&omicron;",
"/\\[pi\\]/" => "&pi;",
"/\\[rho\\]/" => "&rho;",
"/\\[sigmaf\\]/" => "&sigmaf;",
"/\\[sigma\\]/" => "&sigma;",
"/\\[tau\\]/" => "&tau;",
"/\\[upsilon\\]/" => "&upsilon;",
"/\\[phi\\]/" => "&phi;",
"/\\[chi\\]/" => "&chi;",
"/\\[psi\\]/" => "&psi;",
"/\\[omega\\]/" => "&omega;",
"/\\[Alpha\\]/" => "&Alpha;",
"/\\[Beta\\]/" => "&Beta;",
"/\\[Gamma\\]/" => "&Gamma;",
"/\\[Delta\\]/" => "&Delta;",
"/\\[Epsilon\\]/" => "&Epsilon;",
"/\\[Zeta\\]/" => "&Zeta;",
"/\\[Eta\\]/" => "&Eta;",
"/\\[Theta\\]/" => "&Theta;",
"/\\[Iota\\]/" => "&Iota;",
"/\\[Kappa\\]/" => "&Kappa;",
"/\\[Lambda\\]/" => "&Lambda;",
"/\\[Mu\\]/" => "&Mu;",
"/\\[Nu\\]/" => "&Nu;",
"/\\[Xi\\]/" => "&Xi;",
"/\\[Omicron\\]/" => "&Omicron;",
"/\\[Pi\\]/" => "&Pi;",
"/\\[Rho\\]/" => "&Rho;",
"/\\[Sigma\\]/" => "&Sigma;",
"/\\[Tau\\]/" => "&Tau;",
"/\\[Upsilon\\]/" => "&Upsilon;",
"/\\[Phi\\]/" => "&Phi;",
"/\\[Chi\\]/" => "&Chi;",
"/\\[Psi\\]/" => "&Psi;",
"/\\[Omega\\]/" => "&Omega;",
"/(?:\"|&quot;)(.+?)(?:\"|&quot;)/" => "&ldquo;\\1&rdquo;",
"/ +- +/" => " &#8211; "
);
// EXTRACT AUTHOR'S LAST NAME
// this function takes the contents of the author field and will extract the last name of a particular author (specified by position)
// (e.g., setting '$authorPosition' to "1" will return the 1st author's last name)
// Note: this function assumes that:
// 1. within one author object, there's only *one* delimiter separating author name & initials!
// 2. author objects are stored in the db as "<author_name><author_initials_delimiter><author_initials>", i.e., initials follow *after* the author's name!
// Required Parameters:
// 1. pattern describing delimiter that separates different authors
// 2. pattern describing delimiter that separates author name & initials (within one author)
// 3. position of the author whose last name shall be extracted (e.g., "1" will return the 1st author's last name)
// 4. contents of the author field
public static function extractAuthorsLastName( $oldBetweenAuthorsDelim, $oldAuthorsInitialsDelim, $authorPosition, $authorContents ) {
$authorsArray = preg_split( "/" . $oldBetweenAuthorsDelim . "/", $authorContents ); // get a list of all authors for this record
$authorPosition = $authorPosition - 1; // php array elements start with "0", so we decrease the authors position by 1
$singleAuthor = $authorsArray[$authorPosition]; // for the author in question, extract the full author name (last name & initials)
$singleAuthorArray = preg_split( "/" . $oldAuthorsInitialsDelim . "/", $singleAuthor ); // then, extract author name & initials to separate list items
$singleAuthorsLastName = $singleAuthorArray[0]; // extract this author's last name into a new variable
return $singleAuthorsLastName;
}
// EXTRACT AUTHOR'S GIVEN NAME
// this function takes the contents of the author field and will extract the given name of a particular author (specified by position)
// (e.g., setting '$authorPosition' to "1" will return the 1st author's given name)
// Required Parameters:
// 1. pattern describing delimiter that separates different authors
// 2. pattern describing delimiter that separates author name & initials (within one author)
// 3. position of the author whose last name shall be extracted (e.g., "1" will return the 1st author's last name)
// 4. contents of the author field
public static function extractAuthorsGivenName( $oldBetweenAuthorsDelim, $oldAuthorsInitialsDelim, $authorPosition, $authorContents ) {
$authorsArray = preg_split( "/" . $oldBetweenAuthorsDelim . "/", $authorContents ); // get a list of all authors for this record
$authorPosition = $authorPosition - 1; // php array elements start with "0", so we decrease the authors position by 1
$singleAuthor = $authorsArray[$authorPosition]; // for the author in question, extract the full author name (last name & initials)
$singleAuthorArray = preg_split( "/" . $oldAuthorsInitialsDelim . "/", $singleAuthor ); // then, extract author name & initials to separate list items
if ( !empty($singleAuthorArray[1]) ) {
$singleAuthorsGivenName = $singleAuthorArray[1]; // extract this author's last name into a new variable
} else {
$singleAuthorsGivenName = '';
}
return $singleAuthorsGivenName;
}
// Perform search & replace actions on the given text input:
// ('$includesSearchPatternDelimiters' must be a boolean value that specifies whether the leading and trailing slashes
// are included within the search pattern ['true'] or not ['false'])
public static function searchReplaceText( $sourceString, $includesSearchPatternDelimiters ) {
// apply the search & replace actions defined in '$transtab_refbase_html' to the text passed in '$sourceString':
foreach ( self::$transtab_refbase_html as $searchString => $replaceString ) {
if ( !$includesSearchPatternDelimiters ) {
$searchString = "/" . $searchString . "/"; // add search pattern delimiters
}
if ( preg_match($searchString, $sourceString ) ) {
$sourceString = preg_replace( $searchString, $replaceString, $sourceString );
}
}
return $sourceString;
}
}