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

View File

@@ -0,0 +1,23 @@
refbase command line clients
============================
Author
------
Matthias Steffens <refbase@extracts.de>
About
-----
'refbase' is a command line client (written in perl) to search refbase.
'refbase_import' is a client to import references into refbase.
Use
---
Part I: Configuration
- Both scripts may be edited in a text editor. It is suggested that you set:
- %hosts
- %loginParams
Part II: Use
- Both scripts will print help if run with an argument of '-h' or '--help'
- They will print usage examples if run with '-X' or '--examples'
See also:
<http://cli.refbase.net>

1183
contrib/command_line/refbase Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,459 @@
#!/usr/bin/perl
# Project: Web Reference Database (refbase) <http://www.refbase.net>
# Copyright: Matthias Steffens <mailto:refbase@extracts.de> and the file's
# original author(s).
#
# 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.
#
# File: ./contrib/command_line/refbase_import
# Repository: $HeadURL: file:///svn/p/refbase/code/branches/bleeding-edge/contrib/command_line/refbase_import $
# Author(s): Matthias Steffens <mailto:refbase@extracts.de>
#
# Created: 06-Jun-06, 18:00
# Modified: $Date: 2008-10-30 18:16:54 +0000 (Thu, 30 Oct 2008) $
# $Author: msteffens $
# $Revision: 1289 $
# REFBASE_IMPORT -- a refbase command line interface
# Purpose: Perl script that allows to upload data in various formats to a refbase online database from the command line
# Usage: refbase_import [OPTIONS] [FILE]
# Help: For help with the syntax type 'refbase_import -h'
# To view some usage examples type 'refbase_import -X'
# Further information is available at <http://cli.refbase.net/>
# A list of supported import formats is given at <http://import.refbase.net/>
# Version: 1.2
# Requires: - a shell with Perl execution capabilities
# - the Perl CPAN modules LWP::UserAgent, HTTP::Request::Common, HTTP::Response, HTTP::Cookies and URI::URL
# - access with import permissions to a refbase database (refbase-0.9.0 or greater)
# Limits: - The character encoding of your import data must match the encoding of your refbase database (i.e., 'latin1' or 'utf8')
# - The authentication mechanism is currently limited in that a given password will be transferred as parameter in the POST request
# --------------------------------------------------------------------------------------------------------------
$version = "1.2";
# Configure variables:
# Specify the full URLs to any refbase servers that shall be queried:
# Notes: - the given hash keys will work as shortcuts, e.g. '--host=local' would upload
# data to your local refbase installation; one hash key must be named 'default',
# all other keys can be freely chosen
# - by default, data will be uploaded to the server labeled with key 'default'
%hosts = (
'default' => 'http://beta.refbase.net/',
'local' => 'http://localhost/refs/',
'beta' => 'http://beta.refbase.net/',
'beta2' => 'http://refbase.textdriven.com/beta/',
'demo' => 'http://demo.refbase.net/',
'org' => 'http://www.refbase.org/'
);
# Specify the default values for all options that are not explicitly specified:
%params = (
# import options:
'skipBadRecords' => '0', # -b|--skipbad -> must be '0' (don't skip records with unrecognized data format) or '1' (skip records with unrecognized data format)
'importRecordsRadio' => 'all', # -i|--import -> must be 'all' (import all records) or 'only' (import only those records specified in 'importRecords')
'sourceIDs' => '', # -p|--pmid -> this also applies for '--arxiv|--doi|--openurl' since they are essentially just aliases for '-p'
'importRecords' => '1', # -r|--records -> must be a list of numbers and/or ranges (e.g., '1-5' will import the first five records; '1 3-5 7' will import records 1, 3, 4, 5 and 7)
'formType' => 'data', # -t|--type -> must be 'data' (generic data import) or 'id' (import via ID)
# fixed parameters:
'client' => "cli-refbase_import-" . $version # the client ID of this command line utility
);
%outputParams = (
# output options:
'citeStyle' => '', # -C|--style => desired citation style, given name must match an entry within the database's MySQL table 'styles' (keep empty to use the database default)
'format' => 'ascii', # -F|--format => output format must be 'html', 'rtf', 'pdf', 'latex', 'latex_bbl', 'markdown', 'ascii', 'ads', 'bibtex', 'endnote', 'isi', 'ris', 'atom', 'mods', 'oai_dc', 'odf', 'srw_dc', 'srw_mods', 'word' or '' (the empty string '' will produce the default 'ascii' output style)
'showLinks' => '1', # -L|--showlinks => hide/display links column in HTML output; must be '0', '1', or '' (the empty string '' will produce the default output style, i.e. print any links)
'citeOrder' => 'author', # -O|--order => cite order must be 'author', 'year', 'type', 'type-year', 'creation-date' or '' (the empty string '' will produce the default 'author' sort order)
'viewType' => 'web' # -V|--view => view type of HTML output; must be 'Web', 'Print', 'Mobile' or '' (the empty string '' will produce the default 'Web' output style)
);
# Specify the default login credentials for a refbase user account:
# Imported data will get associated with this user account
%loginParams = (
'loginEmail' => '', # -U|--user -> the login email address of an existing refbase user with import permissions
'loginPassword' => '' # -P|--password -> the password for the given user account
);
# Specify the location of the cookie jar file:
# This file will be used to store & retrieve cookies
$cookieJarFile = "$ENV{HOME}/.lwpcookies.txt";
# --------------------------------------------------------------------------------
# NOTE: You shouldn't need to change anything below this line
# CPAN modules:
use LWP::UserAgent; # more info: <http://search.cpan.org/~gaas/libwww-perl-5.805/lib/LWP/UserAgent.pm>
use HTTP::Request::Common; # more info: <http://search.cpan.org/~gaas/libwww-perl-5.805/lib/HTTP/Request/Common.pm>
use HTTP::Response; # more info: <http://search.cpan.org/~gaas/libwww-perl-5.805/lib/HTTP/Response.pm>
use HTTP::Cookies; # more info: <http://search.cpan.org/~gaas/libwww-perl-5.805/lib/HTTP/Cookies.pm>
use URI::URL; # more info: <http://search.cpan.org/~gaas/URI-1.35/URI/URL.pm>
# initialize variables:
$host = $hosts{'default'};
$format = '';
# Extract options:
# TODO: use Getopt::Long
# general options:
if (($ARGV[0] eq '--help') or ($ARGV[0] eq '-h') or ($ARGV[0] eq '')) { &usage (0); } # if the user asked for --help/-h or didn't provide any input, call the 'usage' subroutine
elsif (($ARGV[0] eq '--version') or ($ARGV[0] eq '-v')) { &version (0); } # show version information
elsif (($ARGV[0] eq '--examples') or ($ARGV[0] eq '-X')) { &examples (0); } # print some usage examples
else {
foreach (@ARGV) {
# extract import options:
if ($_ =~ /^(?:-b|--skipbad)=(.+)$/) { $params{'skipBadRecords'} = $1; }
elsif ($_ =~ /^(?:-i|--import)=(.+)$/) { $params{'importRecordsRadio'} = $1; }
elsif ($_ =~ /^(?:-p|--pmid|--arxiv|--doi|--openurl)=(.+)$/) { $params{'sourceIDs'} = $1; }
elsif ($_ =~ /^(?:-r|--records)=(.+)$/) { $params{'importRecords'} = $1; }
elsif ($_ =~ /^(?:-t|--type)=(.+)$/) { $params{'formType'} = $1; }
# extract output options:
elsif ($_ =~ /^(?:-C|--style)=(.+)$/) { $outputParams{'citeStyle'} = $1; }
elsif ($_ =~ /^(?:-F|--format)=(.+)$/) { $outputParams{'format'} = $1; }
elsif ($_ =~ /^(?:-L|--showlinks)=(.+)$/) { $outputParams{'showLinks'} = $1; }
elsif ($_ =~ /^(?:-O|--order)=(.+)$/) { $outputParams{'citeOrder'} = $1; }
elsif ($_ =~ /^(?:-V|--view)=(.+)$/) { $outputParams{'viewType'} = $1; }
# extract server options:
elsif ($_ =~ /^(?:-H|--host)=(.+)$/) { $host = $1; }
elsif ($_ =~ /^(?:-P|--password)=(.+)$/) { $loginParams{'loginPassword'} = $1; }
elsif ($_ =~ /^(?:-U|--user)=(.+)$/) { $loginParams{'loginEmail'} = $1; }
# extract file:
# (note that if multiple files were given, only the last given file will be honoured)
elsif ($_ =~ /^(?!(-[biprtCFLOVHPU]|--(?:skipbad|import|pmid|arxiv|doi|openurl|records|type|style|format|showlinks|order|view|host|password|user))=)([^ ]+)/) { @sourceFile = $2; }
}
}
# for '--type=data', check if a source file was specified:
if (($params{'formType'} =~ /^data$/i) && (scalar @sourceFile == 0)) {
print "There were validation errors regarding the data you submitted:\n\n";
print "FILE: The file operand is missing! The generic data import feature ('--type=data')\n"
. " requires a FILE to be specified. Type 'refbase_import -X' to see some usage\n"
. " examples. For general help with the syntax type 'refbase_import -h'.\n\n";
exit;
}
# for '--type=id' (or, previously: --type=pmid), check if at least one PubMed ID, arXiv ID, DOI or OpenURL was given:
# TODO: improve identification/verification of the given IDs
elsif (($params{'formType'} =~ /^(pm)?id$/i) && ($params{'sourceIDs'} !~ /\d+/)) {
print "There were validation errors regarding the data you submitted:\n\n";
print "sourceIDs: You must specify at least one PubMed ID, arXiv ID, DOI or OpenURL! The 'import via ID'\n"
. " feature ('--type=id') requires the '-p, --pmid' option or one of '--arxiv|--doi|--openurl'\n"
. " to be specified. Type 'refbase_import -X' to see some usage examples. For general help\n"
. " with the syntax type 'refbase_import -h'.\n\n";
exit;
}
# adjust form type value:
if ($params{'formType'} =~ /^(pm)?id$/i) { # --type=id (or, previously: --type=pmid)
$params{'formType'} = "importID";
}
else { # --type=data
$params{'formType'} = "import";
}
# resolve any host shortcuts:
if (exists($hosts{$host})) {
$host = $hosts{$host};
}
elsif ($host !~ /^https?:\/\//i) {
$host = $hosts{'default'}; # can't resolve given host, reset back to default
}
# assign correct URL params based on the '-F|--format' option:
if (exists($outputParams{'format'})) {
$format = $outputParams{'format'};
if ($format =~ /^(html|rtf|pdf|latex|latex_bbl|markdown|ascii)$/i) {
$outputParams{'submit'} = "Cite";
}
if ($format =~ /^(html|rtf|pdf|latex|latex_bbl|markdown|ascii)$/i) {
$format =~ s/^latex_bbl$/LaTeX .bbl/i;
$outputParams{'citeType'} = $format;
}
elsif ($format =~ /^(ads|bibtex|endnote|isi|ris|atom|mods|oai_dc|odf|srw(_dc|_mods)?|word)$/i) {
$outputParams{'submit'} = "Export";
$outputParams{'exportType'} = "file";
if ($format =~ /^(ads|bibtex|endnote|isi|ris)$/i) {
$outputParams{'exportFormat'} = $format;
}
elsif ($format =~ /^(atom|mods|oai_dc|odf|srw(_dc|_mods)?|word)$/i) {
$outputParams{'exportFormat'} = $format . " xml";
}
}
else {
$outputParams{'citeType'} = "ascii";
}
delete($outputParams{'format'});
}
# construct URL:
# (uses URI::URL)
$importScript = "import_modify.php";
$importURL = url($host . $importScript);
# initialize new user agent:
# (uses LWP::UserAgent)
$userAgent = LWP::UserAgent->new;
# set user agent string:
$userAgent->agent("refbase_import/" . $version . " (http://cli.refbase.net/) ");
# set cookie jar object:
# LWP will collect cookies and respond to cookie requests via its cookie jar, thus
# enabling the user agent to fetch a PHP session ID from the refbase login response
# and automatically resend it upon next import request
$userAgent->cookie_jar({ file => $cookieJarFile, autosave => 1 });
# attempt to authenticate using the given login credentials:
if (($loginParams{'loginEmail'} ne '') && ($loginParams{'loginPassword'} ne '')) {
$loginSuccessful = &login(0); # call the 'login' subroutine
}
else {
$loginSuccessful = 0;
}
if (!$loginSuccessful) {
print "Login failed! You provided an incorrect email address or password.\n\n";
exit;
}
# send POST request:
# (uses HTTP::Request::Common & HTTP::Response)
if ($params{'formType'} =~ /^importID$/i) { # --type=id (or, previously: --type=pmid)
$request = POST $importURL, \%params;
}
else { # --type=data
$params{'uploadFile'} = \@sourceFile;
$request = POST $importURL, Content_Type => 'form-data', Content => \%params;
}
$response = $userAgent->request($request);
if ($response->is_error()) {
print STDERR $response->status_line, "\n";
}
else {
$location = $response->header('Location');
if ($location ne '') {
if ($location =~ /show.php/) {
# display imported records:
foreach $key (keys %outputParams) {
$location .= "&" . $key . "=" . $outputParams{$key};
}
if ($location =~ /&headerMsg=\D*(\d+)/i) {
$location .= "&showRows=" . $1;
}
}
# construct URL:
# (uses URI::URL)
$responseURL = url($host . $location);
# send GET request:
# (uses HTTP::Request::Common & HTTP::Response)
$request = GET $responseURL;
$response = $userAgent->request($request); # or use: $response = $userAgent->get($responseURL);
}
binmode STDOUT;
print $response->content();
}
# --------------------------------------------------------------------------------
# Login with login credentials given in '%loginParams':
sub login
{
local ($status) = @_;
# construct URL:
# (uses URI::URL)
$loginScript = "user_login.php";
$loginURL = url($host . $loginScript);
# send POST request:
# (uses HTTP::Request::Common & HTTP::Response)
$request = POST $loginURL, \%loginParams;
$response = $userAgent->request($request);
if ($response->is_error()) {
print STDERR $response->status_line, "\n";
exit $status;
}
else {
$location = $response->header('Location');
# upon successful login, refbase will redirect to 'index.php'
if ($location =~ /index.php/) {
return 1; # login successful
}
else {
return 0; # login NOT successful
}
}
}
# --------------------------------------------------------------------------------
# Print usage and exit:
sub usage
{
local ($status) = @_;
print "\nrefbase_import command line client, v" . $version . " by Matthias Steffens, http://cli.refbase.net/\n\n"
. "Usage: refbase_import [OPTIONS] [FILE]\n\n"
. "Notes: - Two import modes are supported:\n"
. " 1) '--type=data' requires an import FILE to be specified;\n"
. " for supported import formats, see: http://import.refbase.net/\n"
. " 2) '--type=id' requires the '-p, --pmid' option or one of '--arxiv|--doi|--openurl' with\n"
. " one or more whitespace-delimited PubMed IDs, arXiv IDs, DOIs or OpenURLs, respectively.\n"
. " - Options syntax: [OPTION]=[VALUE], e.g. '-p=16351846' or '--pmid=\"16351846 16783713\"'.\n"
. " - For each option, default values can be specified at the top of the script.\n"
. " Current defaults are given in parentheses.\n\n"
. "General Options: -h, --help - display this help text\n"
. " -v, --version - display version information\n"
. " -X, --examples - display usage examples\n\n"
. "Import Options: -b, --skipbad - skip records with unrecognized data format ('" . $params{'skipBadRecords'} . "')\n"
. " possible values: 0, 1\n"
. " -i, --import - import all or only some records ('" . $params{'importRecordsRadio'} . "')\n"
. " possible values: all, only\n"
. " -p, --pmid, - IDs of records to import ('" . $params{'sourceIDs'} . "')\n"
. " --arxiv, supported IDs: PubMed ID (PMID), arXiv ID, DOI, OpenURL\n"
. " --doi, \n"
. " --openurl \n"
. " -r, --records - positional numbers and/or ranges of records to import ('" . $params{'importRecords'} . "')\n"
. " requires the '--import=only' option\n"
. " -t, --type - import type ('" . $params{'formType'} . "')\n"
. " possible values: data, id\n\n"
. "Output Options: -C, --style - citation style ('" . $outputParams{'citeStyle'} . "')\n"
. " -F, --format - output format ('" . $outputParams{'format'} . "')\n"
. " possible values: html, rtf, pdf, latex, latex_bbl, markdown, ascii,\n"
. " ads, bibtex, endnote, isi, ris, atom, mods, oai_dc,\n"
. " odf, srw_dc, srw_mods, word\n"
. " -L, --showlinks - hide/display links column in html output ('" . $outputParams{'showLinks'} . "')\n"
. " possible values: 0, 1\n"
. " -O, --order - sort order of returned records ('" . $outputParams{'citeOrder'} . "')\n"
. " possible values: author, year, type, type-year, creation-date\n"
. " -V, --view - view type of html output ('" . $outputParams{'viewType'} . "')\n"
. " possible values: web, print, mobile\n\n"
. "Server Options: -H, --host - URL of the refbase database ('" . $host . "')\n"
. " defined shortcuts: " . join(', ', sort keys(%hosts)) . "\n"
. " -P, --password - password for given '-U, --user' account";
if ($loginParams{'loginPassword'} ne '') {
print "\n (a default pwd has been defined)\n";
}
else {
print " ('')\n";
}
print " -U, --user - login email address of an existing refbase user with\n"
. " import permissions ('" . $loginParams{'loginEmail'} . "')\n\n";
exit $status;
}
# --------------------------------------------------------------------------------
# Print version number and exit:
sub version
{
local ($status) = @_;
print "\nrefbase_import command line client, version " . $version
. "\ncheck for updates at http://cli.refbase.net/\n\n";
exit $status;
}
# --------------------------------------------------------------------------------
# Print examples and exit:
sub examples
{
local ($status) = @_;
print <<'END_EXAMPLES';
--------------------------------------------------------------------------------
REFBASE_IMPORT USAGE EXAMPLES:
--------------------------------------------------------------------------------
1) Import BibTeX records from file 'import.bib' using the defaults defined
within the refbase_import script:
refbase_import import.bib
--------------------------------------------------------------------------------
2) Import all Endnote records given in file 'import.enw' into your default
refbase database:
refbase_import -t=data -i=all import.enw
--------------------------------------------------------------------------------
3) Take RIS records from file 'import.ris' but import only the first three as
well as the fifth and the tenth record into your local refbase database:
refbase_import -H=local -t=data -i=only -r=1-3,5,10 import.ris
--------------------------------------------------------------------------------
4) Import MODS XML records from file 'mods.xml' into the refbase demo database
using the defaults defined within the refbase_import script:
refbase_import -H=http://demo.refbase.net/ -U=user@refbase.net -P=user mods.xml
--------------------------------------------------------------------------------
5) Fetch two records from PubMed.gov via their PMID (i.e. the unique PubMed
identifier, in this example, records with PMIDs 16351846 and 16783713) and
import them into your local refbase database:
refbase_import -H=local -t=id -p="16351846 16783713"
--------------------------------------------------------------------------------
6) Fetch two records from CrossRef.org via their DOI (i.e. the unique Document
Object Identifier, in this example, records with DOIs 10.3354/meps251037 and
10.1103/PhysRev.47.777) and import them into your local refbase database:
refbase_import -H=local -t=id --doi="10.3354/meps251037 10.1103/PhysRev.47.777"
--------------------------------------------------------------------------------
7) Fetch three records from arXiv.org via their arXiv ID (i.e. the unique arXiv
identifier, in this example, records with arXiv IDs astro-ph/0609768, 0806.1829
and 0802.0204v1) and import them into your local refbase database:
refbase_import -H=local -t=id --arxiv="astro-ph/0609768 0806.1829 0802.0204v1"
--------------------------------------------------------------------------------
END_EXAMPLES
exit $status;
}
__END__

42
contrib/endnote/README Normal file
View File

@@ -0,0 +1,42 @@
endnote2refbase
===============
Author
------
Richard Karnesky <karnesky@gmail.com>
About
-----
This is an alternative to refbase's web-based import of Endnote data. It
allows Endnote users to export a text file which can be imported into the
refbase MySQL database.
Use
---
Part I: Endnote
- Copy refbase.ens into your Endnote styles directory.
On win32 systems, this is typically:
C:\Program Files\Endnote\Styles
On Mac systems, this is typically:
Macintosh HD\Applications\EndNote #\Styles
(where # corresponds to a version #)
- Open the Endnote file you wish to import into refbase.
- Choose the refbase Output Style
- Export to 'endnote.txt'
Part II: PHP [*]
- Executing 'php endnote2mysql.php' will produce 'import.txt'
('php' must be in your path or you should prefix it with the path to php)
Part III: Check it!
- As this is a preliminary script that has undergone little testing, it is
suggested that you look at 'import.txt' in spreadsheet software.
- New versions of Endnote dump UTF-8 data. You should be able to use this as
is if you have a UTF-8 database. If you don't have a UTF-8 database, you
should convert the file to the character encoding you do use (using iconv,
recode, or <http://www.motobit.com/util/charset-codepage-conversion.asp>).
Part IV: MySQL [*]
- From within your MySQL command line interpreter (mysql -u root literature -p):
LOAD DATA LOCAL INFILE "import.txt" INTO TABLE refs;
[*]If you are comfortable that the script works and are on a system with a POSIX
shell (nearly all *nix, including OS X; Windows through Cygwin or similar),
you may use Andreas Czerniak's en-importer.sh to automate Parts II-IV.

View File

@@ -0,0 +1,51 @@
#!/bin/bash
#
# EndNote - Importer to RefBase MySQL table
#
# Andreas Czerniak <ac@oceanlibrary.org>
#
# initial: 05-11-2005
#
# modified:
# 2005-12-11 ; ac ; clean up static codes
# 2005-12-15 ; rk ; remove "v.9", import into CVS
# 2006-01-03 ; ac ; replace LOAD DATA INTO statement with mysqlimport - Thx. Matthias Steffens <refbase@extracts.de>
#
if [ $# -lt 1 ]; then
echo "Which endnote file ?"
echo -e "\nusage: $0 endnote.file [database [mysql-options] ]\n"
exit 127
fi
ENFILE=$1
MYSQLDB=$2 || MYSQLDB="literature" # default: literature
MYSQLOPTION=$3 || MYSQLOPTION="-p" # default: with password
if [ ! -d imported ] ; then
mkdir imported
fi
./endnote2mysql.php $1
if [ ! -f import.txt ] ; then
echo "endnote2mysql convert failed !"
exit 0
fi
mv import.txt refs.txt
mysqlimport --local $MYSQLOPTION $MYSQLDB "refs.txt" > sqloutput.txt
cat sqloutput.txt
rm refs.txt
rm sqloutput.txt
cat $ENFILE | tail
echo "\n\nrows imported: "
cat $ENFILE | wc -l
mv $ENFILE imported/.

View File

@@ -0,0 +1,63 @@
<?php
// Project: Web Reference Database (refbase) <http://www.refbase.net>
// Copyright: Matthias Steffens <mailto:refbase@extracts.de> and the file's
// original author.
//
// 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.
//
// File: ./contrib/endnote/endnote2mysql.php
// Author: Richard Karnesky <mailto:karnesky@northwestern.edu>
//
// Created: 18-Mar-05, 17:10
// Modified: 19-Mar-05, 13:50
// WARNING
// This hasn't been tested extensively & can cause weirdness. Give the data
// a once over in a spreadsheet to confirm it looks OK before import!!!
// This processes the text file produced by using refbase.ens in Endnote:
// - Fixes linefeeds, which Endnote can't handle well:
// - trims carriage returns
// - replaces newlines with '\n'
// - trims '<REFBASE>' from the start of each citation
// - replaces '</REFBASE>' with a newline character
// - Replaces '<REFBASE J/>' with 'Journal' (a Field Name in Endnote)
// - Inserts '\N' between multiple tabs (to explicitly NULL empty fields)
// - Replaces '<Go to ISI>://*\t' with '\N' (bad URLs in Endnote)
// TODO:
// - Tabs within fields aren't replaced! This can screw things up!
// - Allow people to change import & export filenames
// - More fields (particularly all dates, first author, number of authors)
// - Better parsing of current fields (correct use of 'ed' vs 'eds)
// - Automatically import via mysql (intentionally unimplemented for safety)
// - Deprecate this whole darn mess by adding native import facilities ;-)
$fin = file_get_contents('endnote.txt');
if (!$fin) {
echo "Error! Couldn't open endnote.txt.";
}
else {
$fin = str_replace("\r","",$fin);
$fin = str_replace("\n","\\n",$fin);
$fin = str_replace("<REFBASE>","",$fin);
$fin = str_replace("</REFBASE>\\n","\n",$fin);
$fin = str_replace("<REFBASE J/>","Journal",$fin);
$fin = preg_replace("/(?<=\t)(?=\t)/","\\N",$fin);
$fin = preg_replace("/<Go to ISI>:\/\/\S*/","\\N",$fin);
}
do {
if (!($fout = fopen('import.txt', "w"))) {
$rc = 1; break;
}
if (!fwrite($fout, $fin)) {
$rc = 2; break;
}
$rc = true;
} while (0);
if ($fout) {
fclose($fout);
}
?>

BIN
contrib/endnote/refbase.ens Normal file

Binary file not shown.

View File

@@ -0,0 +1,209 @@
<?php
// Project: Web Reference Database (refbase) <http://www.refbase.net>
// Copyright: Matthias Steffens <mailto:refbase@extracts.de> and the file's
// original author(s).
//
// 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.
//
// File: ./import_template_base.php
// Repository: $HeadURL: file:///svn/p/refbase/code/branches/bleeding-edge/contrib/import_templates/import_template_base.php $
// Author(s): Matthias Steffens <mailto:refbase@extracts.de>
//
// Created: 11-Jan-06, 18:36
// Modified: $Date: 2012-02-27 20:25:30 +0000 (Mon, 27 Feb 2012) $
// $Author: msteffens $
// $Revision: 1337 $
// Template for a batch import script.
// Use this script to develop your own batch importer.
// See the scripts 'import.php' and 'import_modify.php' for a working example.
// Incorporate some include files:
include 'initialize/db.inc.php'; // 'db.inc.php' is included to hide username and password
include 'includes/include.inc.php'; // include common functions
include 'initialize/ini.inc.php'; // include common variables
// --------------------------------------------------------------------
// START A SESSION:
// call the 'start_session()' function (from 'include.inc.php') which will also read out available session variables:
start_session(true);
// --------------------------------------------------------------------
// Initialize preferred display language:
// (note that 'locales.inc.php' has to be included *after* the call to the 'start_session()' function)
include 'includes/locales.inc.php'; // include the locales
// --------------------------------------------------------------------
// Get the referring page (or set a default one if no referrer is available):
if (!empty($_SERVER['HTTP_REFERER'])) // if the referrer variable isn't empty
$referer = $_SERVER['HTTP_REFERER']; // on error, redirect to calling page
else
$referer = "import.php"; // on error, redirect to the web import form (if you've got your own import form, insert it's script name here)
// First of all, check if the user is logged in:
if (!isset($_SESSION['loginEmail'])) // -> if the user isn't logged in
{
header("Location: user_login.php?referer=" . rawurlencode($referer)); // ask the user to login first, then he'll get directed back to the calling page
exit; // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> !EXIT! <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
}
// now, check if the (logged in) user is allowed to import any record into the database:
if (isset($_SESSION['user_permissions']) AND !preg_match("/allow_import|allow_batch_import/", $_SESSION['user_permissions'])) // if the 'user_permissions' session variable does NOT contain either 'allow_import' or 'allow_batch_import'...
{
// return an appropriate error message:
$HeaderString = returnMsg($loc["NoPermission"] . $loc["NoPermission_ForImport"] . "!", "warning", "strong", "HeaderString"); // function 'returnMsg()' is defined in 'include.inc.php'
header("Location: index.php"); // redirect back to main page ('index.php')
exit; // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> !EXIT! <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
}
// --------------------------------------------------------------------
// PROCESS SOURCE DATA:
$parsedRecordsArray = array(); // initialize array variable which will hold parsed data of all records that shall be imported
// >>> insert your own code here that parses your source data into an array of arrays holding the extracted field data <<<
// ToDo:
// (1) Obtain your source data via a web form, file upload, direct read-in of a local source file, etc
// If your script allows input from the web, make sure to validate your data, see 'import.php' & 'import_modify.php' for an example
// (2) Split your source data into individual bits representing individual records
// (3) Loop over each record and extract the record's field data into an array;
// For each record you should end up with an array structure similar to the one below ('$recordFieldParametersArray'):
// NOTES: - you can safely omit unneeded fields from your data array; for any fields that aren't present in the data array, the database will insert its default values
// - the 'addRecords()' function will take care of the calculation fields ('first_author', 'author_count', 'first_page', 'volume_numeric' and 'series_volume_numeric')
// - similarly, the *date/*time/*by fields ('created_date', 'created_time', 'created_by', 'modified_date', 'modified_time', 'modified_by') will be filled automatically
// if no custom values (in correct date ['YYYY-MM-DD'] and time ['HH:MM:SS'] format) are given in your array
// - you can pass any custom info for the 'location' field in your array; however, if you omit the 'location' field from the array
// the 'addRecords()' function will insert name & email address of the currently logged-in user (e.g. 'Matthias Steffens (refbase@extracts.de)')
// - the serial number(s) will be assigned automatically (and returned by the 'addRecords()' function in form of an array)
// - this import example will only add to the main MySQL table ('refs'), but not to the 'user_data' table
// Example record data array. Commented fields will be filled automatically if not present (see notes above).
// Comments behind field spec give the resulting calculation field values for this example:
$recordFieldParametersArray = array(
'author' => "FirstAuthor, Initials; SecondAuthor, Initials", // 'first_author' = "FirstAuthor, Initials"; 'author_count' = "2"
'address' => "Address",
'corporate_author' => "Corporate Author",
'title' => "Title",
'orig_title' => "Orig Title",
'publication' => "Publication",
'abbrev_journal' => "Abbrev Journal",
'year' => "2005",
'volume' => "2nd Volume", // 'volume_numeric' = "2"
'issue' => "Issue",
'pages' => "5 Pages", // 'first_page' = "5"
'keywords' => "Keywords",
'abstract' => "Abstract",
'edition' => "2",
'editor' => "Editor",
'publisher' => "Publisher",
'place' => "Place",
'medium' => "Medium",
'series_editor' => "Series Editor",
'series_title' => "Series Title",
'abbrev_series_title' => "Abbrev Series Title",
'series_volume' => "3rd Series Volume", // 'series_volume_numeric' = "3"
'series_issue' => "Series Issue",
'issn' => "ISSN",
'isbn' => "ISBN",
'language' => "Language",
'summary_language' => "Summary Language",
'area' => "Area",
'type' => "Type",
'thesis' => "Diploma thesis",
'expedition' => "Expedition",
'doi' => "DOI",
'conference' => "Conference",
'url' => "URL",
'call_number' => "Call Number",
// 'location' => "Location",
'contribution_id' => "Contribution Id",
'online_publication' => "no",
'online_citation' => "Online Citation",
'file' => "File",
'notes' => "Notes",
'approved' => "no",
// 'created_date' => "1999-11-30",
// 'created_time' => "00:00:01",
// 'created_by' => "Created By",
// 'modified_date' => "1999-11-31",
// 'modified_time' => "00:00:02",
// 'modified_by' => "Modified By",
'orig_record' => "-123"
);
// (4) Append the array of extracted field data to the main data array which holds all records to import:
$parsedRecordsArray[] = $recordFieldParametersArray; // in this example, we simply import a single record, adopt to your needs
$recordsCount = count($parsedRecordsArray); // count how many records are available
// check if the current user has batch import permission:
if (($recordsCount > 1) AND isset($_SESSION['user_permissions']) AND !preg_match("/allow_batch_import/", $_SESSION['user_permissions'])) // if we're supposed to import several records BUT the 'user_permissions' session variable does NOT contain 'allow_batch_import'...
{
// return an appropriate error message:
// (note that this error message will overwrite any '$headerMessage' that gets specified below)
$HeaderString = returnMsg($loc["NoPermission"] . $loc["NoPermission_ForBatchImport"] . "!", "warning", "strong", "HeaderString", "", " " . $loc["Warning_OnlyFirstRecordImported"]) . ":"; // function 'returnMsg()' is defined in 'include.inc.php'
array_splice($parsedRecordsArray, 1); // remove all but the first record from the array of records that shall be imported
}
// --------------------------------------------------------------------
// IMPORT RECORDS:
// Build an array structure suitable for passing to the 'addRecords()' function:
$importDataArray = array(); // for an explanation of the structure of '$importDataArray', see the comments above the 'addRecords()' function (in 'include.inc.php')
$importDataArray['type'] = "refbase"; // we use the "refbase" array format
$importDataArray['version'] = "1.0"; // we use version "1.0" of the array structure
$importDataArray['creator'] = "http://refbase.net"; // calling script/importer is "refbase" (insert the unique name of your importer here or give the web address of it's home page)
$importDataArray['author'] = "Matthias Steffens"; // author/contact name of the person who's responsible for this script/importer (insert your own name here)
$importDataArray['contact'] = "refbase@extracts.de"; // author's email/contact address (insert your email address here)
$importDataArray['options'] = array('prefix_call_number' => "true"); // if "true", any 'call_number' string will be prefixed with the correct call number prefix of the currently logged-in user (e.g. 'IP<49> @ msteffens @ ')
$importDataArray['records'] = $parsedRecordsArray; // this array will hold the record(s) (with each record being a sub-array of fields)
// Add all records to the database (i.e., for each record, add a row entry to MySQL table 'refs'):
// ('$importedRecordsArray' will hold the serial numbers of all newly imported records)
$importedRecordsArray = addRecords($importDataArray); // function 'addRecords()' is defined in 'include.inc.php'
// --------------------------------------------------------------------
// DISPLAY RESULTS:
if (!empty($importedRecordsArray)) // if some records were successfully imported
{
$recordSerialsQueryString = "^(" . implode("|", $importedRecordsArray) . ")$";
$importedRecordsCount = count($importedRecordsArray);
if ($importedRecordsCount == 1)
$headerMessage = $importedRecordsCount . " " . $loc["RecordSuccessfullyImported"] . ":";
else // $importedRecordsCount > 1
$headerMessage = $importedRecordsCount . " " . $loc["RecordsSuccessfullyImported"] . ":";
// display all newly added records:
header("Location: show.php?serial=" . rawurlencode($recordSerialsQueryString) . "&headerMsg=" . rawurlencode($headerMessage));
}
else // nothing imported
{
// return an appropriate error message:
$HeaderString = returnMsg($loc["NoRecordsImported"] . "!", "warning", "strong", "HeaderString"); // function 'returnMsg()' is defined in 'include.inc.php'
if (!empty($_SERVER['HTTP_REFERER'])) // if the referer variable isn't empty
header("Location: " . $_SERVER['HTTP_REFERER']); // redirect to calling page
else
header("Location: index.php"); // redirect to main page ('index.php')
}
// --------------------------------------------------------------------
?>

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;
}
}

4
contrib/skins/README Normal file
View File

@@ -0,0 +1,4 @@
The current method to change the appearance of refbase is to edit the style
files in the 'css' subdirectory and/or to replace the 'header.inc.php' and
'footer.inc.php' in the 'includes' subdirectory. This directory contains
examples of customized versions of these files.

View File

@@ -0,0 +1,20 @@
mediawiki-monobook skin for refbase
===================================
Author
------
Richard Karnesky <karnesky@gmail.com>
About
-----
These files mimic the Monobook skin from MediaWiki:
<http://www.mediawiki.org/>
This is the default skin for the Wikipedia:
<http://wikipedia.org/>
You may also be interested in the refbase extension for MediaWiki, included in the
'contrib/mediawiki' directory from refbase.
An installation of refbase that uses this skin is the Northwestern University
Center for Atom-Probe Tomography:
<http://arc.nucapt.northwestern.edu/refbase/>

View File

@@ -0,0 +1,235 @@
<?php
// Copyright: Richard Karnesky <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.
// File: ./includes/footer.inc.php
// --------------------------------------------------------------------
// Inserts the closing HTML </body> and </html> tags:
function displayHTMLfoot()
{
?>
</body>
</html>
<?php
}
// --------------------------------------------------------------------
// Displays the visible footer:
function showPageFooter($HeaderString)
{
global $officialDatabaseName; // usage example: <a href="index.php">[? echo encodeHTML($officialDatabaseName); ?]</a>
global $hostInstitutionAbbrevName; // usage example: <a href="[? echo $hostInstitutionURL; ?]">[? echo encodeHTML($hostInstitutionAbbrevName); ?] Home</a>
global $hostInstitutionName; // (note: in the examples above, square brackets must be replaced by their respective angle brackets)
global $hostInstitutionURL;
global $helpResourcesURL;
global $loginWelcomeMsg; // these variables are globally defined in function 'showLogin()' in 'include.inc.php'
global $loginStatus;
global $loginLinks;
global $loc; // '$loc' is made globally available in 'core.php'
?>
</div></div></div>
<div id="column-one">
<div id="p-cactions" class="portlet">
<h5>Views</h5>
<ul>
<li id="ca-talk"
class="selected" ><a href="index.php">References</a></li><li id="search"><a href="simple_search.php" title="search the main fields of the database">Simple Search</a></li>
<li><a href="advanced_search.php" title="search all fields of the database">Advanced Search</a></li>
<?php
// -------------------------------------------------------
if (isset($_SESSION['user_permissions']) AND preg_match("/allow_add/", $_SESSION['user_permissions'])) // if the 'user_permissions' session variable contains 'allow_add'...
{
// ... include a link to 'record.php?recordAction=add...':
?>
<LI id="ca-watch"><a href="record.php?recordAction=add" title="add a record to the database">Add Record</a>
<?php
}
else {?>
<LI id="ca-watch"><a href="/refbase-svn/record.php?recordAction=add" title="add a suggested record to the database">Add Record (suggest)</a>
<?php }
// -------------------------------------------------------
if (isset($_SESSION['user_permissions']) AND preg_match("/allow_import|allow_batch_import/", $_SESSION['user_permissions'])) // if the 'user_permissions' session variable contains either 'allow_import' or 'allow_batch_import'...
{
// ... include a link to 'import.php':
?>
<LI><a href="import.php" title="import records">Import</a>
<?php
} else {
?>
<LI><a href="/refbase-svn/import.php" title="import suggested records">Import (suggest)</a>
<?php
}?>
</ul>
</div>
<div class="portlet" id="p-personal">
<h5>Personal tools</h5>
<div class="pBody">
<ul>
<li id="pt-userpage"><? echo preg_replace('/You\'re logged in as<br>/','',$loginStatus); ?></li><li id="pt-mytalk">
<? echo $loginLinks; ?></li>
</ul>
</div>
</div>
<div class="portlet" id="p-logo">
<a style="background-image:
url(../skins/common/images/wiki.png);"
href="../index.php/Seidman_Group"
title="Seidman Group"></a>
</div>
<div class='portlet' id='p-Seidman_Group'>
<h5>Seidman Group</h5>
<div class='pBody'>
<ul>
<li id="n-Seidman-Group"><a href="/Seidman_Group">Seidman Group</a></li>
<li id="n-Research"><a href="/Category:Research">Research</a></li>
<li id="n-People"><a href="/Category:People">People</a></li>
</ul>
</div>
</div>
<div class='portlet' id='p-NUCAPT'>
<h5>NUCAPT</h5>
<div class='pBody'>
<ul>
<li id="n-Instruments"><a href="/Category:Tools">Instruments</a></li>
<li id="n-Calendar"><a href="http://arc.nucapt.northwestern.edu/phpicalendar">Calendar</a></li>
<li id="n-Visit"><a href="/Visit">Visit</a></li>
</ul>
</div>
</div>
<div class='portlet' id='p-Atom-Probe_Tomography'>
<h5>Atom-Probe Tomography</h5>
<div class='pBody'>
<ul>
<li id="n-References"><a href="http://arc.nucapt.northwestern.edu/refbase">References</a></li>
<li id="n-AtomProbe-mailing-list"><a href="http://arc.nucapt.northwestern.edu/mailman/listinfo/atomprobe">AtomProbe mailing list</a></li>
</ul>
</div>
</div>
<div class="portlet" id="p-tb">
<h5>Search</h5>
<div class="pBody">
<?php echo buildQuickSearchElements($query, $queryURL, $showQuery, $showLinks, $showRows, $citeStyle, $citeOrder, $displayType); ?>
<ul>
<li><a href="simple_search.php" title="search the main fields of the database">Simple Search</a>
<li><a href="advanced_search.php" title="search all fields of the database">Advanced Search</a>
<?php
// -------------------------------------------------------
if (isset($_SESSION['user_permissions']) AND preg_match("/allow_sql_search/", $_SESSION['user_permissions'])) // if the 'user_permissions' session variable contains 'allow_sql_search'...
{
// ... include a link to 'sql_search.php':
?>
<li><a href="sql_search.php" title="search the database by use of a SQL query">SQL Search</a>
<?php
}
// -------------------------------------------------------
?>
<li><a href="library_search.php" title="search the library of the <? echo encodeHTML($hostInstitutionAbbrevName); ?>">Library Search</a>
</ul>
</div></div>
<div class="portlet" id="p-tc">
<h5>Toolbox</h5>
<div class="pBody">
<ul>
<?php
// -------------------------------------------------------
if (isset($_SESSION['user_permissions']) AND preg_match("/allow_add/", $_SESSION['user_permissions'])) // if the 'user_permissions' session variable contains 'allow_add'...
{
// ... include a link to 'record.php?recordAction=add...':
?>
<LI><a href="record.php?recordAction=add" title="add a record to the database">Add Record</a>
<?php
}
// -------------------------------------------------------
if (isset($_SESSION['user_permissions']) AND preg_match("/allow_import|allow_batch_import/", $_SESSION['user_permissions'])) // if the 'user_permissions' session variable contains either 'allow_import' or 'allow_batch_import'...
{
// ... include a link to 'import.php':
?>
<LI><a href="import.php" title="import records">Import</a>
<?php
}
// -------------------------------------------------------
if (isset($_SESSION['user_permissions']) AND preg_match("/allow_details_view/", $_SESSION['user_permissions'])) // if the 'user_permissions' session variable contains 'allow_details_view'...
{
// ... include a link to 'show.php':
?>
<LI><a href="show.php" title="display details for a particular record by entering its database serial number">Show Record</a>
<?php
}
if (isset($_SESSION['user_permissions']) AND preg_match("/allow_cite/", $_SESSION['user_permissions'])) // if the 'user_permissions' session variable contains 'allow_cite'...
{
// ... include a link to 'extract.php':
?>
<LI><a href="extract.php" title="extract citations from a text and build an appropriate reference list">Extract Citations</a><?php
}
// -------------------------------------------------------
?>
</ul>
</div></div></div>
<div class="visualClear"></div>
<div id="footer">
<div id="f-poweredbyico"><a href="http://www.refbase.net/"><img src="img/refbase_credit.gif" alt="refbase"></a></div><ul id="f-list">
<li><? echo date('j M Y'); ?></li>
<li id="f-about"><a
href="/index.php/Seidman_Group" title="Seidman Group">NUCAPT: Northwestern University Center for Atom-Probe Tomography</a></li> </ul>
</div>
</div>
<?php
}
?>

View File

@@ -0,0 +1,164 @@
<?php
// Project: Web Reference Database (refbase) <http://www.refbase.net>
// Copyright: Matthias Steffens <mailto:refbase@extracts.de> and the file's
// original author(s).
//
// 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.
//
// File: ./contrib/skins/mediawiki-monobook/header.inc.php
// Repository: $HeadURL: file:///svn/p/refbase/code/branches/bleeding-edge/contrib/skins/mediawiki-monobook/header.inc.php $
// Author(s): Richard Karnesky <mailto:karnesky@gmail.com>
//
// Created: 31-Oct-06, 00:28
// Modified: $Date: 2012-02-27 20:25:30 +0000 (Mon, 27 Feb 2012) $
// $Author: msteffens $
// $Revision: 1337 $
// This is the header include file.
// It contains functions that provide the HTML header
// as well as the visible header that gets displayed on every page.
// --------------------------------------------------------------------
// Inserts the HTML <head>...</head> block as well as the initial <body> tag:
//
// TODO: include OpenSearch elements in HTML header
// (see examples at <http://www.opensearch.org/Specifications/OpenSearch/1.1#Response_metadata_in_HTML.2FXHTML>)
function displayHTMLhead($pageTitle, $metaRobots, $metaDescription, $additionalMeta, $includeJavaScript, $includeJavaScriptFile, $viewType, $rssURLArray)
{
global $officialDatabaseName; // these variables are defined in 'ini.inc.php'
global $contentTypeCharset;
global $defaultStyleSheet;
global $printStyleSheet;
global $mobileStyleSheet;
global $useVisualEffects;
global $databaseBaseURL;
global $databaseKeywords;
global $defaultFeedFormat;
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head profile="http://a9.com/-/spec/opensearch/1.1/">
<title><?php echo $pageTitle; ?></title>
<meta name="date" content="<?php echo date('d-M-y'); ?>">
<meta name="robots" content="<?php echo $metaRobots; ?>">
<meta name="description" lang="en" content="<?php echo $metaDescription; ?>">
<meta name="keywords" lang="en" content="<?php echo $databaseKeywords; ?>"><?php
if (!empty($additionalMeta))
echo $additionalMeta;
?>
<meta http-equiv="content-language" content="<?php echo getUserLanguage(); ?>">
<meta http-equiv="content-type" content="text/html; charset=<?php echo $contentTypeCharset; ?>">
<meta http-equiv="Content-Style-Type" content="text/css"><?php
if (preg_match("/^Print$/i", $viewType))
{
?>
<link rel="stylesheet" href="<?php echo $printStyleSheet; ?>" type="text/css" title="CSS Definition"><?php
}
elseif (preg_match("/^Mobile$/i", $viewType))
{
?>
<link rel="stylesheet" href="<?php echo $mobileStyleSheet; ?>" type="text/css" title="CSS Definition"><?php
}
else
{
?>
<link rel="stylesheet" href="<?php echo $defaultStyleSheet; ?>" type="text/css" title="CSS Definition"><?php
}
if (!empty($rssURLArray) AND isset($_SESSION['user_permissions']) AND preg_match("/allow_rss_feeds/", $_SESSION['user_permissions'])) // if some RSS URLs were specified AND the 'user_permissions' session variable contains 'allow_rss_feeds'...
{
foreach ($rssURLArray as $rssURL)
{
if ($defaultFeedFormat == "Atom XML")
$feedContentType = "application/atom+xml";
else // RSS XML
$feedContentType = "application/rss+xml";
// ...include a link tag pointing to a dynamic RSS feed for the current query:
?>
<link rel="alternate" type="<?php echo $feedContentType; ?>" href="<?php echo $databaseBaseURL . $rssURL['href']; ?>" title="<?php echo $rssURL['title']; ?>"><?php
}
}
?>
<link rel="unapi-server" type="application/xml" title="unAPI" href="<?php echo $databaseBaseURL; ?>unapi.php">
<link rel="search" type="application/opensearchdescription+xml" title="<?php echo encodeHTML($officialDatabaseName); ?>" href="<?php echo $databaseBaseURL; ?>opensearch.php?operation=explain"><?php
if ($includeJavaScript OR (isset($_SESSION['userAutoCompletions']) AND ($_SESSION['userAutoCompletions'] == "yes")) OR ($useVisualEffects == "yes"))
{
// ...include common refbase JavaScript functions:
?>
<script language="JavaScript" type="text/javascript" src="javascript/common.js"></script><?php
}
if ((isset($_SESSION['userAutoCompletions']) AND ($_SESSION['userAutoCompletions'] == "yes")) OR ($useVisualEffects == "yes"))
{
// ...include the Prototype & script.aculo.us JavaScript frameworks:
?>
<script language="JavaScript" type="text/javascript" src="javascript/prototype.js"></script>
<script language="JavaScript" type="text/javascript" src="javascript/scriptaculous.js?load=effects,controls"></script><?php
}
if (!empty($includeJavaScriptFile))
{
// ...include additional JavaScript functions:
?>
<script language="JavaScript" type="text/javascript" src="<?php echo $includeJavaScriptFile; ?>"></script><?php
}
?>
</head>
<body><?php
}
// --------------------------------------------------------------------
// Displays the visible header:
function showPageHeader($HeaderString)
{
global $officialDatabaseName; // these variables are defined in 'ini.inc.php'
global $hostInstitutionAbbrevName;
global $hostInstitutionName;
global $hostInstitutionURL;
global $helpResourcesURL;
global $loginWelcomeMsg; // these variables are globally defined in function 'showLogin()' in 'include.inc.php'
global $loginStatus;
global $loginLinks;
global $loc; // '$loc' is made globally available in 'core.php'
?>
<div id="globalWrapper">
<div id="column-content">
<div id="content">
<a name="top" id="contentTop"></a>
<h1 class="firstHeading"><? echo encodeHTML($officialDatabaseName); ?></h1>
<div id="bodyContent">
<h3 id="siteSub">From NUCAPT</h3>
<div id="contentSub"></div>
<!-- start content -->
<h2><? echo $HeaderString; ?></h2>
<?php
}
// --------------------------------------------------------------------
?>

File diff suppressed because it is too large Load Diff