Browse Source

Auto-cleanup to Drupal coding standards

This commit leverages PHPCBF, an automated cleanup technique from PHP_CodeSniffer
installed via the Drupal contrib Coder module version 8.2.12
roblib
James Wilson 8 years ago
parent
commit
520a49147d
  1. 103
      ebsco/css/ebsco.css
  2. 428
      ebsco/ebsco.module
  3. 385
      ebsco/lib/EBSCOAPI.php
  4. 269
      ebsco/lib/EBSCOConnector.php
  5. 472
      ebsco/lib/EBSCODocument.php
  6. 163
      ebsco/lib/EBSCORecord.php
  7. 212
      ebsco/lib/EBSCOResponse.php
  8. 370
      ebsco/lib/sanitizer.class.php
  9. 1
      ebsco/templates/ebsco-advanced-search.tpl.php
  10. 8
      ebsco/templates/ebsco-basic-search.tpl.php
  11. 28
      ebsco/templates/ebsco-result.tpl.php
  12. 185
      ebsco/templates/ebsco-results.tpl.php
  13. 2
      ebsco/templates/ebsco-side-facets.tpl.php

103
ebsco/css/ebsco.css

@ -97,7 +97,7 @@
padding-left: 0;
padding-right: 10px;
margin-left: 10px;
border-right: 1px solid #CCCCCC;
border-right: 1px solid #cccccc;
}
.ebsco ul.custom-links li:first-child {
@ -178,7 +178,7 @@
/** Detailed view ***/
.ebsco-record .toolbar {
border-bottom: 1px solid #EEEEEE;
border-bottom: 1px solid #eeeeee;
margin-bottom: 1em;
min-height: 2em;
padding-left: 1em;
@ -224,7 +224,7 @@
padding-left: 0;
padding-right: 10px;
margin-left: 10px;
border-right: 1px solid #CCCCCC;
border-right: 1px solid #cccccc;
line-height: 32px;
margin: 5px;
}
@ -239,7 +239,7 @@
}
.top-login-message {
margin-top:10px;
margin-top: 10px;
width: 100%;
text-align: center;
}
@ -255,7 +255,7 @@
.ebsco-record .html {
background-color: white;
padding:10px 0;
padding: 10px 0;
border: 0;
}
@ -284,11 +284,11 @@
}
#ebsco-sort-form {
margin : 10px 0;
margin: 10px 0;
}
#ebsco-sort-form > div {
border-bottom: 1px solid #CCCCCC;
border-bottom: 1px solid #cccccc;
}
#ebsco-sort-form label,
@ -384,8 +384,8 @@
.ebsco-advanced #edit-limiters hr {
margin: 15px 0;
height: 1px;
background-color: #CCCCCC;
color: #CCCCCC;
background-color: #cccccc;
color: #cccccc;
border: 0 none;
}
@ -447,74 +447,67 @@
/* RS, EMP carousel */
#quote-carousel
{
#quote-carousel {
padding: 0 10px 30px 10px;
margin-top: 30px;
}
}
/* Control buttons */
#quote-carousel .carousel-control
{
/* Control buttons */
#quote-carousel .carousel-control {
background: none;
color: #222;
font-size: 2.3em;
text-shadow: none;
margin-top: 30px;
}
/* Previous button */
#quote-carousel .carousel-control.left
{
}
/* Previous button */
#quote-carousel .carousel-control.left {
left: -12px;
}
/* Next button */
#quote-carousel .carousel-control.right
{
}
/* Next button */
#quote-carousel .carousel-control.right {
right: -12px !important;
}
/* Changes the position of the indicators */
#quote-carousel .carousel-indicators
{
}
/* Changes the position of the indicators */
#quote-carousel .carousel-indicators {
right: 50%;
top: auto;
bottom: 0px;
margin-right: -19px;
}
/* Changes the color of the indicators */
#quote-carousel .carousel-indicators li
{
}
/* Changes the color of the indicators */
#quote-carousel .carousel-indicators li {
background: #c0c0c0;
}
#quote-carousel .carousel-indicators .active
{
}
#quote-carousel .carousel-indicators .active {
background: #333333;
}
#quote-carousel img
{
}
#quote-carousel img {
width: 250px;
height: 100px
}
/* End carousel */
}
/* End carousel */
.item blockquote {
.item blockquote {
border-left: none;
margin: 0;
}
}
.item blockquote img {
.item blockquote img {
margin-bottom: 10px;
}
}
.item blockquote p:before {
.item blockquote p:before {
content: "\f10d";
font-family: 'Fontawesome';
float: left;
margin-right: 10px;
}
#relatedInformation img { padding-right :10px;}
}
.glyphicon {
#relatedInformation img {
padding-right: 10px;
}
.glyphicon {
position: relative;
top: 1px;
display: inline-block;
@ -524,21 +517,21 @@
line-height: 1;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
}
.carousel-control .glyphicon-chevron-right {
position: absolute;
top: 50%;
z-index: 5;
display: inline-block;
}
.carousel-control.left span, .carousel-control.right span {
.carousel-control.left span,
.carousel-control.right span {
background-color: #000;
}
h3.relatedTitle a{
font-size:24px;
}
h3.relatedTitle a {
font-size: 24px;
}
/* */
/* */

428
ebsco/ebsco.module

File diff suppressed because it is too large Load Diff

385
ebsco/lib/EBSCOAPI.php

@ -1,7 +1,7 @@
<?php
/**
* EBSCO EDS API class
* EBSCO EDS API class.
*
* PHP version 5
*
@ -19,7 +19,6 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
require_once 'EBSCOConnector.php';
@ -27,39 +26,42 @@ require_once 'EBSCOResponse.php';
/**
* EBSCO API class
* EBSCO API class.
*/
class EBSCOAPI
{
class EBSCOAPI {
/**
* The authentication token used for API transactions
* The authentication token used for API transactions.
*
* @global string
*/
private $authenticationToken;
/**
* The session token for API transactions
* The session token for API transactions.
*
* @global string
*/
private $sessionToken;
/**
* The EBSCOConnector object used for API transactions
* The EBSCOConnector object used for API transactions.
*
* @global object EBSCOConnector
*/
private $connector;
/**
* Configuration options
* Configuration options.
*/
private $config;
/**
* VuFind search types mapped to EBSCO search types
* used for urls in search results / detailed result
* used for urls in search results / detailed result.
*
* @global array
*/
private static $search_tags = array(
@ -71,25 +73,27 @@ class EBSCOAPI
'Subject' => 'SU',
'Title' => 'TI',
'ISBN' => 'IB',
'ISSN' => 'IS'
'ISSN' => 'IS',
);
/**
* EBSCO sort options
* EBSCO sort options .
*
* @global array
*/
private static $sort_options = array(
'relevance',
'date',
'date2',
'source'
'source',
);
/**
* VuFind sort types mapped to EBSCO sort types
* used for urls in Search results / Detailed view
* used for urls in Search results / Detailed view.
*
* @global array
*/
private static $mapped_sort_options = array(
@ -101,136 +105,134 @@ class EBSCOAPI
'date_desc' => 'date',
'callnumber' => 'date',
'author' => 'author',
'title' => 'date'
'title' => 'date',
);
/**
* Constructor
*
* Constructor.
*
* @param array config
*
* @access public
*/
public function __construct($config)
{
public function __construct($config) {
$this->config = $config;
}
/**
* Setter / Getter for authentication token
* Setter / Getter for authentication token.
*
* @param string The authentication token
*
* @return string or none
*
* @access public
*/
public function authenticationToken($token = null)
{
public function authenticationToken($token = NULL) {
if (empty($token)) {
$token = $this->readSession('authenticationToken');
return !empty($token) ? $token : $this->authenticationToken;
} else {
}
else {
$this->authenticationToken = $token;
$this->writeSession('authenticationToken', $token);
}
}
/**
* Setter / Getter for session token
* Setter / Getter for session token.
*
* @param string The session token
*
* @return string or none
*
* @access public
*/
public function sessionToken($token = null)
{
public function sessionToken($token = NULL) {
if (empty($token)) {
$token = $this->readSession('sessionToken');
return !empty($token) ? $token : $this->sessionToken;
} else {
}
else {
$this->sessionToken = $token;
$this->writeSession('sessionToken', $token);
}
}
/**
* Getter for isGuest
* Getter for isGuest.
*
* @param string 'y' or 'n'
*
* @return string or none
*
* @access public
*/
public function isGuest($boolean = null)
{
public function isGuest($boolean = NULL) {
if (empty($boolean)) {
return $this->readSession('isGuest');
} else {
}
else {
$this->writeSession('isGuest', $boolean);
}
}
/**
* Create a new EBSCOConnector object or reuse an existing one
* Create a new EBSCOConnector object or reuse an existing one.
*
* @param none
*
* @return EBSCOConnector object
*
* @access public
*/
public function connector()
{
public function connector() {
if (empty($this->connector)) {
$this->connector = new EBSCOConnector($this->config);
}
return $this->connector;
}
/**
* Create a new EBSCOResponse object
* Create a new EBSCOResponse object.
*
* @param object $response
*
* @return EBSCOResponse object
*
* @access public
*/
public function response($response)
{
public function response($response) {
$responseObj = new EBSCOResponse($response);
return $responseObj;
}
/**
* Request authentication and session tokens, then send the API request.
* Retry the request if authentication errors occur
* Retry the request if authentication errors occur.
*
* @param string $action The EBSCOConnector method name
* @param array $params The parameters of the HTTP request
* @param integer $attempts The number of retries
* @param string $action
* The EBSCOConnector method name.
* @param array $params
* The parameters of the HTTP request.
* @param int $attempts
* The number of retries.
*
* @return object SimpleXml DOM or PEAR Error
*
* @access protected
*/
protected function request($action, $params = null, $attempts = 5)
{
protected function request($action, $params = NULL, $attempts = 5) {
$authenticationToken = $this->authenticationToken();
$sessionToken = $this->sessionToken();
// If authentication token is missing then the session token is missing too, so get both tokens
// If session token is missing then the authentication token may be invalid, so get both tokens
// If session token is missing then the authentication token may be invalid, so get both tokens.
if (empty($authenticationToken) || empty($sessionToken)) {
$result = $this->apiAuthenticationAndSessionToken();
if ($this->isError($result)) {
// Any error should terminate the request immediately
// in order to prevent infinite recursion
// in order to prevent infinite recursion.
return $result;
}
}
@ -244,165 +246,183 @@ class EBSCOAPI
$headers = array(
'x-authenticationToken' => $this->authenticationToken(),
'x-sessionToken' => $this->sessionToken()
'x-sessionToken' => $this->sessionToken(),
);
$response = call_user_func_array(array($this->connector(), "request{$action}"), array($params, $headers));
if ($this->isError($response)) {
// Retry the request if there were authentication errors
// Retry the request if there were authentication errors.
$code = $response->getCode();
switch ($code) {
// If authentication token is invalid then the session token is invalid too, so get both tokens
// If session token is invalid then the authentication token may be invalid too, so get both tokens
// If session token is invalid then the authentication token may be invalid too, so get both tokens.
case EBSCOConnector::EDS_AUTH_TOKEN_INVALID:
$result = $this->apiAuthenticationToken();
if ($this->isError($result)) {
// Any error should terminate the request immediately
// in order to prevent infinite recursion
// in order to prevent infinite recursion.
return $result;
}
if ($attempts > 0) {
$result = $this->request($action, $params, --$attempts);
}
break;
case EBSCOConnector::EDS_SESSION_TOKEN_INVALID:
$result = $this->apiAuthenticationAndSessionToken();
if ($this->isError($result)) {
// Any error should terminate the request immediately
// in order to prevent infinite recursion
// in order to prevent infinite recursion.
return $result;
}
if ($attempts > 0) {
$result = $this->request($action, $params, --$attempts);
}
break;
default:
$result = $this->handleError($response);
break;
}
} else {
}
else {
$result = $this->response($response)->result();
}
return $result;
}
/**
* Wrapper for authentication API call
* Wrapper for authentication API call.
*
* @param none
*
* @access public
*/
public function apiAuthenticationToken()
{
public function apiAuthenticationToken() {
$response = $this->connector()->requestAuthenticationToken();
if ($this->isError($response)) {
return $response;
} else {
}
else {
$result = $this->response($response)->result();
if (isset($result['authenticationToken'])) {
$this->authenticationToken($result['authenticationToken']);
return $result['authenticationToken'];
} else {
}
else {
return new EBSCOException("No authentication token was found in the response.");
}
}
}
/**
* Wrapper for session API call
* Wrapper for session API call.
*
* @param none
*
* @access public
*/
public function apiSessionToken()
{
// Add authentication tokens to headers
public function apiSessionToken() {
// Add authentication tokens to headers.
$headers = array(
'x-authenticationToken' => $this->authenticationToken()
'x-authenticationToken' => $this->authenticationToken(),
);
$response = $this->connector()->requestSessionToken($headers);
// Raise the exception so that any code running this method should exit immediately
// Raise the exception so that any code running this method should exit immediately.
if ($this->isError($response)) {
return $response;
} else {
}
else {
$result = $this->response($response)->result();
if (is_string($result)) {
$this->sessionToken($result);
return $result;
} else {
}
else {
return new EBSCOException("No session token was found in the response.");
}
}
}
/**
* Initialize the authentication and session tokens
* Initialize the authentication and session tokens.
*
* @param none
*
* @access public
*/
public function apiAuthenticationAndSessionToken()
{
public function apiAuthenticationAndSessionToken() {
$authenticationToken = $this->apiAuthenticationToken();
if ($this->isError($authenticationToken)) {
// An authentication error should terminate the request immediately
// An authentication error should terminate the request immediately.
return $authenticationToken;
}
$sessionToken = $this->apiSessionToken();
if ($this->isError($sessionToken)) {
// A session error should terminate the request immediately
// A session error should terminate the request immediately.
return $sessionToken;
}
// We don't have to return anything, both tokens can be accessed using the getters
return true;
// We don't have to return anything, both tokens can be accessed using the getters.
return TRUE;
}
/**
* Wrapper for search API call
*
* @param array $search The search terms
* @param array $filters The facet filters
* @param string $start The page to start with
* @param string $limit The number of records to return
* @param string $sortBy The value to be used by for sorting
* @param string $amount The amount of data to be returned
* @param string $mode The search mode
* Wrapper for search API call.
*
* @param array $search
* The search terms.
* @param array $filters
* The facet filters.
* @param string $start
* The page to start with.
* @param string $limit
* The number of records to return.
* @param string $sortBy
* The value to be used by for sorting.
* @param string $amount
* The amount of data to be returned.
* @param string $mode
* The search mode.
*
* @throws object PEAR Error
*
* @return array An array of query results
*
* @access public
*/
public function apiSearch($search, $filters,
$start = 1, $limit = 10, $sortBy = 'relevance', $amount = 'detailed', $mode = 'all', $rs=false, $emp=false,$autosuggest=false) {
public function apiSearch($search,
$filters,
$start = 1,
$limit = 10,
$sortBy = 'relevance',
$amount = 'detailed',
$mode = 'all',
$rs = FALSE,
$emp = FALSE,
$autosuggest = FALSE) {
$query = array();
// Basic search
if(!empty($search['lookfor'])) {
// Basic search.
if (!empty($search['lookfor'])) {
$lookfor = $search['lookfor'];
$type = isset($search['index']) && !empty($search['index']) ? $search['index'] : 'AllFields';
// escape some characters from lookfor term
// Escape some characters from lookfor term.
$term = str_replace(array(',', ':', '(', ')'), array('\,', '\:', '\(', '\)'), $lookfor);
// replace multiple consecutive empty spaces with one empty space
// Replace multiple consecutive empty spaces with one empty space.
$term = preg_replace("/\s+/", ' ', $term);
// search terms
// Complex search term
// Search terms
// Complex search term.
if (preg_match('/(.*) (AND|OR) (.*)/i', $term)) {
$query['query'] = $term;
} else {
}
else {
$tag = self::$search_tags[$type];
$op = 'AND';
$query_str = implode(',', array($op, $tag));
@ -410,9 +430,9 @@ class EBSCOAPI
$query['query-1'] = $query_str;
}
// Advanced search
// Advanced search.
}
else if(!empty($search['group'])) {
elseif (!empty($search['group'])) {
$counter = 1;
foreach ($search['group'] as $group) {
@ -422,9 +442,9 @@ class EBSCOAPI
$op = $group['bool'];
$tag = $type && isset(self::$search_tags[$type]) ? self::$search_tags[$type] : '';
// escape some characters from lookfor term
// Escape some characters from lookfor term.
$term = str_replace(array(',', ':', '(', ')'), array('\,', '\:', '\(', '\)'), $term);
// replace multiple consecutive empty spaces with one empty space
// Replace multiple consecutive empty spaces with one empty space.
$term = preg_replace("/\s+/", ' ', $term);
if (!empty($term)) {
$query_str = implode(',', array($op, $tag));
@ -435,177 +455,185 @@ class EBSCOAPI
}
}
// No search term, return an empty array
} else {
// No search term, return an empty array.
}
else {
$results = array(
'recordCount' => 0,
'numFound' => 0,
'start' => 0,
'documents' => array(),
'facets' => array()
'facets' => array(),
);
return $results;
}
// Add filters
// Add filters.
$limiters = array(); $expanders = array(); $facets = array();
foreach ($filters as $filter) {
if (preg_match('/addlimiter/', $filter)) {
list($action, $str) = explode('(', $filter, 2);
$field_and_value = substr($str, 0, -1); // e.g. FT:y or GZ:Student Research, Projects and Publications
// e.g. FT:y or GZ:Student Research, Projects and Publications.
$field_and_value = substr($str, 0, -1);
list($field, $value) = explode(':', $field_and_value, 2);
$limiters[$field][] = $value;
} else if (preg_match('/addexpander/', $filter)) {
}
elseif (preg_match('/addexpander/', $filter)) {
list($action, $str) = explode('(', $filter, 2);
$field = substr($str, 0, -1); // expanders don't have value
// Expanders don't have value.
$field = substr($str, 0, -1);
$expanders[] = $field;
} else if (preg_match('/addfacetfilter/', $filter)) {
}
elseif (preg_match('/addfacetfilter/', $filter)) {
list($action, $str) = explode('(', $filter, 2);
$field_and_value = substr($str, 0, -1); // e.g. ZG:FRANCE
// e.g. ZG:FRANCE.
$field_and_value = substr($str, 0, -1);
list($field, $value) = explode(':', $field_and_value, 2);
$facets[$field][] = $field_and_value;
}
}
if (!empty($limiters)) {
foreach($limiters as $field => $limiter) {
$query['limiter'][] = $field . ':' . implode(',', $limiter); // e.g. LA99:English,French,German
foreach ($limiters as $field => $limiter) {
// e.g. LA99:English,French,German.
$query['limiter'][] = $field . ':' . implode(',', $limiter);
}
}
if (!empty($expanders)) {
$query['expander'] = implode(',', $expanders); // e.g. fulltext, thesaurus
// e.g. fulltext, thesaurus.
$query['expander'] = implode(',', $expanders);
}
if (!empty($facets)) {
$groupId = 1;
foreach($facets as $field => $facet) {
$query['facetfilter'][] = $groupId . ',' . implode(',', $facet); // e.g. 1,DE:Math,DE:History
foreach ($facets as $field => $facet) {
// e.g. 1,DE:Math,DE:History.
$query['facetfilter'][] = $groupId . ',' . implode(',', $facet);
$groupId += 1;
}
}
//2014-03-26 - new action to jump to page
if ($start>1) {
$query['action']="GoToPage(".$start.")";
// 2014-03-26 - new action to jump to page.
if ($start > 1) {
$query['action'] = "GoToPage(" . $start . ")";
}
// Add the sort option
// Add the sort option.
$sortBy = in_array($sortBy, self::$sort_options) ? $sortBy : self::$mapped_sort_options[$sortBy];
// Add the HTTP query params
// Add the HTTP query params.
$params = array(
// Specifies the sort. Valid options are:
// relevance, date, date2
// date = Date descending
// date2 = Date ascending
// date2 = Date ascending.
'sort' => $sortBy,
// Specifies the search mode. Valid options are:
// bool, any, all, smart
// bool, any, all, smart.
'searchmode' => $mode,
// Specifies the amount of data to return with the response
// Valid options are:
// title: Title only
// brief: Title + Source, Subjects
// detailed: Brief + full abstract
// detailed: Brief + full abstract.
'view' => $amount,
/// Specifies whether or not to include facets
// Specifies whether or not to include facets.
'includefacets' => 'y',
'resultsperpage' => $limit,
//2014-03-26 RF
// 2014-03-26 RF.
'pagenumber' => $start,
//'pagenumber' => 1,
// Specifies whether or not to include highlighting in the search results
'highlight' => 'y'
// 'pagenumber' => 1,
// Specifies whether or not to include highlighting in the search results.
'highlight' => 'y',
);
if($autosuggest==true) {
$params["autosuggest"]="y";
if ($autosuggest == TRUE) {
$params["autosuggest"] = "y";
}
if ($rs==true){
$params["relatedcontent"]="rs";
if ($rs == TRUE) {
$params["relatedcontent"] = "rs";
}
if ($emp==true){
if ($emp == TRUE) {
if (isset($params["relatedcontent"])) {
$params["relatedcontent"].=",emp";
$params["relatedcontent"] .= ",emp";
}
else
{
$params["relatedcontent"]="emp";
else {
$params["relatedcontent"] = "emp";
}
}
$params = array_merge($params, $query);
$result = $this->request('Search', $params);
return $result;
}
/**
* Wrapper for retrieve API call
* Wrapper for retrieve API call.
*
* @param array $an The accession number
* @param string $start The short database name
* @param array $an
* The accession number.
* @param string $start
* The short database name.
*
* @throws object PEAR Error
*
* @return array An associative array of data
*
* @access public
*/
public function apiRetrieve($an, $db)
{
// Add the HTTP query params
public function apiRetrieve($an, $db) {
// Add the HTTP query params.
$params = array(
'an' => $an,
'dbid' => $db,
'highlight' => 'y'
'highlight' => 'y',
);
$result = $this->request('Retrieve', $params);
return $result;
}
/**
* Wrapper for info API call
* Wrapper for info API call.
*
* @throws object PEAR Error
*
* @return array An associative array of data
*
* @access public
*/
public function apiInfo()
{
public function apiInfo() {
if ($result = $this->readSession('info')) {
return $result;
}
$result = $this->request('Info');
if(!$this->isError($result)) {
if (!$this->isError($result)) {
$this->writeSession('info', $result);
}
return $result;
}
/**
* Handle a PEAR_Error. Return :
* - if the error is critical : an associative array with the current error message
* - if the error is not critical : the error message
* - if the error is not critical : the error message .
*
* @param Pear_Error $exception
*
* @return array or the Pear_Error exception
*
* @access protected
*/
private function handleError($error) {
$errorCode = $error->getCode();
switch($errorCode) {
// This kind of error was generated by user , so display it to user
switch ($errorCode) {
// This kind of error was generated by user , so display it to user.
case EBSCOConnector::EDS_INVALID_ARGUMENT_VALUE:
// Any other errors are system errors, don't display them to user
// Any other errors are system errors, don't display them to user.
default:
$errorMessage = 'An error occurred when getting the data.';
break;
@ -616,58 +644,55 @@ class EBSCOAPI
'numFound' => 0,
'start' => 0,
'documents' => array(),
'facets' => array()
'facets' => array(),
);
return $result;
}
/**
* Store the given object into session
* Store the given object into session.
*
* @param string $key The key used for reading the value
* @param object $value The object stored in session
* @param string $key
* The key used for reading the value.
* @param object $value
* The object stored in session.
*
* @return none
*
* @access protected
*/
protected function writeSession($key, $value)
{
if(!empty($key) && !empty($value)) {
protected function writeSession($key, $value) {
if (!empty($key) && !empty($value)) {
$_SESSION['EBSCO'][$key] = $value;
}
}
/**
* Read from session the object having the given key
* Read from session the object having the given key.
*
* @param string $key The key used for reading the object
* @param string $key
* The key used for reading the object.
*
* @return object
*
* @access protected
*/
protected function readSession($key)
{
protected function readSession($key) {
$value = isset($_SESSION['EBSCO'][$key]) ? $_SESSION['EBSCO'][$key] : '';
return $value;
}
/**
* Check if given object is an EBSCOException object
* Check if given object is an EBSCOException object.
*
* @param object $object
*
* @return boolean
* @return bool
*
* @access protected
*/
protected function isError($object)
{
protected function isError($object) {
return is_a($object, 'EBSCOException');
}
}
?>

269
ebsco/lib/EBSCOConnector.php

@ -1,9 +1,9 @@
<?php
/**
* @file
* EBSCOException class
* Used when EBSCO API calls return error messages
*
* Used when EBSCO API calls return error messages.
*
* Copyright [2017] [EBSCO Information Services]
*
@ -19,23 +19,27 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
class EBSCOException extends Exception
{
/**
*
*/
class EBSCOException extends Exception {
const CRITICAL_ERROR = 1;
// Make message argument mandatory
public function __construct($message, $code = self::CRITICAL_ERROR, Exception $previous = null) {
/**
* Make message argument mandatory.
*/
public function __construct($message, $code = self::CRITICAL_ERROR, Exception $previous = NULL) {
parent::__construct($message, $code, $previous);
}
}
class EBSCOConnector
{
}
/**
* Error codes defined by EDS API
*
*/
class EBSCOConnector {
/**
* Error codes defined by EDS API.
*/
const EDS_UNKNOWN_PARAMETER = 100;
const EDS_INCORRECT_PARAMETER_FORMAT = 101;
@ -79,7 +83,7 @@ class EBSCOConnector
/**
* HTTP status codes constants
* http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
* http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.
*
* @global integer HTTP_OK The request has succeeded
* @global integer HTTP_NOT_FOUND The server has not found anything matching the Request-URI
@ -91,107 +95,117 @@ class EBSCOConnector
/**
* The HTTP_Request object used for API transactions
* The HTTP_Request object used for API transactions.
*
* @global object HTTP_Request
*/
private $client;
/**
* The URL of the EBSCO API server
* The URL of the EBSCO API server.
*
* @global string
*/
private static $end_point = 'http://eds-api.ebscohost.com/EDSAPI/rest';
/**
* The URL of the EBSCO API server
* The URL of the EBSCO API server.
*
* @global string
*/
private static $authentication_end_point = 'https://eds-api.ebscohost.com/AuthService/rest';
/**
* The password used for API transactions
* The password used for API transactions.
*
* @global string
*/
private $password;
/**
* The user id used for API transactions
* The user id used for API transactions.
*
* @global string
*/
private $userId;
/**
* The profile ID used for API transactions
* The profile ID used for API transactions.
*
* @global string
*/
private $profileId;
/**
* The interface ID used for API transactions
* The interface ID used for API transactions.
*
* @global string
*/
private $interfaceId;
/**
* The customer ID used for API transactions
* The customer ID used for API transactions.
*
* @global string
*/
private $orgId;
/**
* The isGuest used for API transactions
* The isGuest used for API transactions.
*
* @global string 'y' or 'n'
*/
private $isGuest;
/**
* Contains the list of ip addresses
* Contains the list of ip addresses.
*
* @global string
*/
private $local_ip_address;
/*
* You can log HTTP_Request requests using this option
/**
* You can log HTTP_Request requests using this option.
*
* @global bool logAPIRequests
*/
private $logAPIRequests;
/**
* The logger object
* The logger object.
*
* @global object Logger
*/
private $logger;
/**
* Constructor
* Constructor.
*
* Sets up the EBSCO API settings
* Sets up the EBSCO API settings.
*
* @param none
*
* @access public
*/
public function __construct($config)
{
public function __construct($config) {
$this->password = $config['password'];
$this->userId = $config['user'];
$this->interfaceId = $config['interface'];
$this->profileId = $config['profile'];
$this->orgId = $config['organization'];
$this->local_ip_address = $config['local_ip_address'];
$this->isGuest = (user_is_logged_in() || $this->isGuestIPAddress($_SERVER["REMOTE_ADDR"]))? 'n' : 'y';
$this->isGuest = (user_is_logged_in() || $this->isGuestIPAddress($_SERVER["REMOTE_ADDR"])) ? 'n' : 'y';
$this->logAPIRequests = ($config['log'] == 1);
if ($this->logAPIRequests) {
$writer = new Zend_Log_Writer_Stream('php://output');
@ -199,59 +213,56 @@ class EBSCOConnector
}
}
/**
* Detects if the user is authorized based on the IP address
* Detects if the user is authorized based on the IP address.
*
* @return string
*/
public function isGuestIPAddress($ipUser)
{
$s= $this->local_ip_address;
public function isGuestIPAddress($ipUser) {
$s = $this->local_ip_address;
if (trim($s)=="") {
return false;
if (trim($s) == "") {
return FALSE;
}
//break records
$m=explode(",",$s);
// Break records.
$m = explode(",", $s);
foreach($m as $ip) {
if ( strcmp(substr($ipUser,0,strlen(trim($ip))),trim($ip))==0) {
// inside of ip address range of customer
return true;
foreach ($m as $ip) {
if (strcmp(substr($ipUser, 0, strlen(trim($ip))), trim($ip)) == 0) {
// Inside of ip address range of customer.
return TRUE;
}
}
return false;
return FALSE;
}
/**
* Public getter for private isGuest
* Public getter for private isGuest .
*
* @param none
*
* @return string isGuest
*
* @access public
*/
public function isGuest()
{
public function isGuest() {
return $this->isGuest;
}
/**
* Request the authentication token
* Request the authentication token.
*
* @param none
*
* @return object SimpleXml or PEAR_Error
*
* @access public
*/
public function requestAuthenticationToken()
{
public function requestAuthenticationToken() {
$url = self::$authentication_end_point . '/UIDAuth';
// Add the body of the request
$params =<<<BODY
// Add the body of the request.
$params = <<<BODY
<UIDAuthRequestMessage xmlns="http://www.ebscohost.com/services/public/AuthService/Response/2012/06/01">
<UserId>{$this->userId}</UserId>
<Password>{$this->password}</Password>
@ -263,78 +274,81 @@ BODY;
return $response;
}
/**
* Request the session token
* Request the session token.
*
* @param array $headers Authentication token
* @param array $headers
* Authentication token.
*
* @return object SimpleXml or PEAR_Error
*
* @access public
*/
public function requestSessionToken($headers)
{
public function requestSessionToken($headers) {
$url = self::$end_point . '/CreateSession';
// Add the HTTP query params
// Add the HTTP query params.
$params = array(
'profile' => $this->profileId,
'org' => $this->orgId,
'guest' => $this->isGuest
'guest' => $this->isGuest,
);
$response = $this->request($url, $params, $headers);
return $response;
}
/**
* Request the search records
* Request the search records.
*
* @param array $params Search specific parameters
* @param array $headers Authentication and session tokens
* @param array $params
* Search specific parameters.
* @param array $headers
* Authentication and session tokens.
*
* @return object SimpleXml or PEAR_Error
*
* @access public
*/
public function requestSearch($params, $headers)
{
public function requestSearch($params, $headers) {
$url = self::$end_point . '/Search';
$response = $this->request($url, $params, $headers);
return $response;
}
/**
* Request a specific record
* Request a specific record.
*
* @param array $params Retrieve specific parameters
* @param array $headers Authentication and session tokens
* @param array $params
* Retrieve specific parameters.
* @param array $headers
* Authentication and session tokens.
*
* @return object SimpleXml or PEAR_Error
*
* @access public
*/
public function requestRetrieve($params, $headers)
{
public function requestRetrieve($params, $headers) {
$url = self::$end_point . '/Retrieve';
$response = $this->request($url, $params, $headers);
return $response;
}
/**
* Request the info data
* Request the info data.
*
* @param null $params Not used
* @param array $headers Authentication and session tokens
* @param null $params
* Not used.
* @param array $headers
* Authentication and session tokens.
*
* @return object SimpleXml or PEAR_Error
*
* @access public
*/
public function requestInfo($params, $headers)
{
public function requestInfo($params, $headers) {
$url = self::$end_point . '/Info';
$response = $this->request($url, $params, $headers);
@ -342,34 +356,38 @@ BODY;
return $response;
}
/**
* Send an HTTP request and inspect the response
* Send an HTTP request and inspect the response.
*
* @param string $url The url of the HTTP request
* @param array $params The parameters of the HTTP request
* @param array $headers The headers of the HTTP request
* @param array $body The body of the HTTP request
* @param string $method The HTTP method, default is 'GET'
* @param string $url
* The url of the HTTP request.
* @param array $params
* The parameters of the HTTP request.
* @param array $headers
* The headers of the HTTP request.
* @param array $body
* The body of the HTTP request.
* @param string $method
* The HTTP method, default is 'GET'.
*
* @return object SimpleXml or PEAR_Error
*
* @access protected
*/
protected function request($url, $params, $headers = array(), $method = 'GET')
{
$xml = false;
$return = false;
$data = null;
protected function request($url, $params, $headers = array(), $method = 'GET') {
$xml = FALSE;
$return = FALSE;
$data = NULL;
if (!empty($params)) {
// Arrays of parameters are used only for GET requests
// Arrays of parameters are used only for GET requests.
if (is_array($params)) {
$query = http_build_query($params, '', '&');
$query = preg_replace('/\%5B\d+\%5D/', '', $query);
$url = $url . '?' . $query;
// String parameters are used only for POST requests
} else {
// String parameters are used only for POST requests.
}
else {
$data = $params;
$headers = array_merge(
array('content-type' => 'text/xml'),
@ -378,8 +396,7 @@ BODY;
}
}
//add compression in case its not there
// Add compression in case its not there.
$headers = array_merge(
array('Accept-Encoding' => 'gzip,deflate'),
$headers
@ -388,15 +405,14 @@ BODY;
$options = array(
'headers' => $headers,
'method' => $method,
'data' => $data
'data' => $data,
);
// Send the request
// Send the request.
try {
$response = drupal_http_request($url, $options);
//print_r($url);
//print_r($response);
// print_r($url);
// print_r($response);
$code = $response->code;
if (isset($response->headers['content-encoding'])) {
if ($response->headers['content-encoding'] == 'gzip') {
@ -412,11 +428,12 @@ BODY;
$xml_str = $response->data;
try {
// clean EMP namespace
$xml_str=str_replace(array("<a:","</a:"),array("<","</"),$xml_str);
// Clean EMP namespace.
$xml_str = str_replace(array("<a:", "</a:"), array("<", "</"), $xml_str);
$xml = simplexml_load_string($xml_str);
$return = $xml;
} catch(Exception $e) {
}
catch (Exception $e) {
$return = new EBSCOException($xml);
}
break;
@ -426,28 +443,33 @@ BODY;
try {
$xml = simplexml_load_string($xml_str);
// If the response is an API error
// If the response is an API error.
$isError = isset($xml->ErrorNumber) || isset($xml->ErrorCode);
if ($isError) {
$error = ''; $code = 0;
if (isset($xml->DetailedErrorDescription) && !empty($xml->DetailedErrorDescription)) {
$error = (string) $xml->DetailedErrorDescription;
} else if (isset($xml->ErrorDescription)) {
}
elseif (isset($xml->ErrorDescription)) {
$error = (string) $xml->ErrorDescription;
} else if (isset($xml->Reason)) {
}
elseif (isset($xml->Reason)) {
$error = (string) $xml->Reason;
}
if (isset($xml->ErrorNumber)) {
$code = (integer) $xml->ErrorNumber;
} else if (isset($xml->ErrorCode)) {
}
elseif (isset($xml->ErrorCode)) {
$code = (integer) $xml->ErrorCode;
}
$return = new EBSCOException($error, $code);
} else {
}
else {
$return = new EBSCOException("HTTP {$code} : The request could not be understood
by the server due to malformed syntax. Modify your search before retrying.");
}
} catch (Exception $e) {
}
catch (Exception $e) {
$return = new EBSCOException($xml);
}
break;
@ -466,8 +488,10 @@ BODY;
$return = new EBSCOException("HTTP {$code} : Unexpected HTTP error.");
break;
}
} catch (Exception $e) {
$message = $this->toString($client); // or $this->toString($response)
}
catch (Exception $e) {
// Or $this->toString($response)
$message = $this->toString($client);
$this->logger->log($message, Zend_Log::ERR);
$return = new EBSCOException($response);
}
@ -483,22 +507,17 @@ BODY;
return $return;
}
/*
* Capture the output of print_r into a string
/**
* Capture the output of print_r into a string.
*
* @param object Any object
*
* @access private
*/
private function toString($object)
{
private function toString($object) {
ob_start();
print_r($object);
return ob_get_clean();
}
}
?>

472
ebsco/lib/EBSCODocument.php

File diff suppressed because it is too large Load Diff

163
ebsco/lib/EBSCORecord.php

@ -1,6 +1,7 @@
<?php
/**
* The EBSCO record object
* The EBSCO record object.
*
* PHP version 5
*
@ -20,132 +21,148 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
class EBSCORecord
{
class EBSCORecord {
/**
* The array of data
* The array of data.
*
* @global array
*/
private $data = array();
/**
* The result id (the EBSCO counter) of the record
* The result id (the EBSCO counter) of the record.
*
* @global integer
*/
public $result_id = null;
public $result_id = NULL;
/**
* The id of the record
* The id of the record.
*
* @global integer
*/
public $record_id = null;
public $record_id = NULL;
/**
* The summary of the record.
*
* @global string
*/
public $summary = null;
public $summary = NULL;
/**
* The authors of the record.
*
* @global string
*/
public $authors = null;
public $authors = NULL;
/**
* The subjects of the record.
*
* @global string
*/
public $subjects = null;
public $subjects = NULL;
/**
* The custom links provided for the record.
*
* @global array
*/
public $custom_links = array();
/**
* The database label of the record.
*
* @global string
*/
public $db_label = null;
public $db_label = NULL;
/**
* The full-text availability of the record.
*
* @global boolean
*/
public $full_text_availability = null;
public $full_text_availability = NULL;
/**
* The full text of the record.
*
* @global string
*/
public $full_text = null;
public $full_text = NULL;
/**
* The PDF availability of the record.
*
* @global boolean
*/
public $pdf_availability = null;
public $pdf_availability = NULL;
/**
* The items of the record.
*
* @global array
*/
public $items = array();
/**
* The external link of the record.
*
* @global string
*/
public $p_link = null;
public $p_link = NULL;
/**
* The external link to the PDF version of the record.
*
* @global string
*/
public $pdf_link = null;
public $pdf_link = NULL;
/**
* The publication type link of the record.
*
* @global string
*/
public $publication_type = null;
public $publication_type = NULL;
/**
* The external thumbnails links of the record.
*
* @global string
*/
public $small_thumb_link = null;
public $medium_thumb_link = null;
public $small_thumb_link = NULL;
public $medium_thumb_link = NULL;
/**
* The title of the record.
*
* @global string
*/
public $title = null;
public $title = NULL;
/**
* The source of the record.
*
* @global string
*/
public $source = null;
public $source = NULL;
/**
* The access level of the record.
*
* @global string
*/
public $access_level = null;
public $access_level = NULL;
/**
* Constructor.
*
* @param array $data Raw data from the EBSCO search representing the record.
* @param array $data
* Raw data from the EBSCO search representing the record.
*/
public function __construct($data = array())
{
public function __construct($data = array()) {
$this->data = $data;
$this->record_id = $this->record_id();
$this->result_id = $this->result_id();
@ -168,152 +185,127 @@ class EBSCORecord
$this->access_level = $this->access_level();
}
/********************************************************
*
* Getters
*
********************************************************/
/**
* Get the summary of the record.
*
* @return string
*/
public function access_level()
{
public function access_level() {
return isset($this->data['AccessLevel']) ?
$this->data['AccessLevel'] : '';
}
/**
* Get the summary of the record.
*
* @return string
*/
public function summary()
{
public function summary() {
return isset($this->data['Items']['Abstract']) ?
$this->data['Items']['Abstract']['Data'] : '';
}
/**
* Get the authors of the record.
*
* @return string
*/
public function authors()
{
public function authors() {
return isset($this->data['Items']['Author']) ?
$this->data['Items']['Author']['Data'] : '';
}
/**
* Get the custom links of the record.
*
* @return array
*/
public function custom_links()
{
public function custom_links() {
return isset($this->data['CustomLinks']) ?
$this->data['CustomLinks'] : array();
}
/**
* Get the database label of the record.
*
* @return string
*/
public function db_label()
{
public function db_label() {
return isset($this->data['DbLabel']) ?
$this->data['DbLabel'] : '';
}
/**
* Get the full text availability of the record.
*
* @return boolean
* @return bool
*/
public function full_text()
{
public function full_text() {
return isset($this->data['FullText']) &&
isset($this->data['FullText']['Value']) ? $this->data['FullText']['Value'] : '';
}
/**
* Get the full text availability of the record.
*
* @return boolean
* @return bool
*/
public function full_text_availability()
{
public function full_text_availability() {
return isset($this->data['FullText']) &&
$this->data['FullText']['Availability'];
}
/**
* Get the items of the record.
*
* @return array
*/
public function items()
{
public function items() {
return isset($this->data['Items']) ? $this->data['Items'] : array();
}
/**
* Get the external url of the record.
*
* @return string
*/
public function p_link()
{
public function p_link() {
return isset($this->data['PLink']) ? $this->data['PLink'] : '';
}
/**
* Get the publication type of the record.
*
* @return string
*/
public function publication_type()
{
public function publication_type() {
return isset($this->data['PubType']) ? $this->data['PubType'] : '';
}
/**
* Get the PDF availability of the record.
*
* @return boolean
* @return bool
*/
public function pdf_availability()
{
public function pdf_availability() {
return isset($this->data['FullText']) &&
isset($this->data['FullText']['Links']) &&
isset($this->data['FullText']['Links']['pdflink']) &&
$this->data['FullText']['Links']['pdflink'];
}
/**
* Get the PDF url of the record.
*
* @return string
*/
public function pdf_link()
{
public function pdf_link() {
return isset($this->data['FullText']) &&
isset($this->data['FullText']['Links']) &&
isset($this->data['FullText']['Links']['pdflink']) ?
@ -321,91 +313,82 @@ class EBSCORecord
'';
}
/**
* Get the result id of the record.
*
* @return integer
* @return int
*/
public function result_id()
{
public function result_id() {
return isset($this->data['ResultId']) ?
$this->data['ResultId'] : '';
}
/**
* Get the subject data of the record.
*
* @return string
*/
public function subjects()
{
public function subjects() {
return isset($this->data['Items']['Subject']) ?
$this->data['Items']['Subject']['Data'] : '';
}
/**
* Return a URL to a thumbnail preview of the record, if available; false
* otherwise.
*
* @param string $size Size of thumbnail (small, medium or large -- small is
* @param string $size
* Size of thumbnail (small, medium or large -- small is
* default).
*
* @return string
*/
public function thumb_link($size = 'small')
{
public function thumb_link($size = 'small') {
$imageInfo = isset($this->data['ImageInfo']) ? $this->data['ImageInfo'] : '';
if ($imageInfo && isset($imageInfo['thumb'])) {
switch ($size) {
case 'large':
case 'medium':
return $imageInfo['medium'];
break;
case 'small':
default:
return $imageInfo['thumb'];
break;
}
}
return false;
return FALSE;
}
/**
* Get the title of the record.
*
* @return string
*/
public function title()
{
public function title() {
return isset($this->data['Items']['Title']) ?
$this->data['Items']['Title']['Data'] : '';
}
/**
* Get the source of the record.
*
* @return string
*/
public function source()
{
public function source() {
return isset($this->data['Items']['TitleSource']) ?
$this->data['Items']['TitleSource']['Data'] : '';
}
/**
* Return the identifier of this record within the EBSCO databases
* Return the identifier of this record within the EBSCO databases.
*
* @return string Unique identifier.
*/
public function record_id()
{
public function record_id() {
return isset($this->data['id']) ?
$this->data['id'] : '';
}

212
ebsco/lib/EBSCOResponse.php

@ -1,8 +1,7 @@
<?php
/**
* EBSCO Response class
* EBSCO Response class.
*
* PHP version 5
*
@ -26,80 +25,77 @@ require_once 'sanitizer.class.php';
/**
* EBSCOResponse class
* EBSCOResponse class.
*/
class EBSCOResponse
{
class EBSCOResponse {
/**
* A SimpleXml object
* A SimpleXml object.
*
* @global object
*/
private $response;
/**
* Constructor
* Constructor.
*
* Sets up the EBSCO Response
* Sets up the EBSCO Response.
*
* @param none
*
* @access public
*/
public function __construct($response)
{
public function __construct($response) {
$this->response = $response;
}
/**
* Returns the XML as an associative array of data
* Returns the XML as an associative array of data.
*
* @param none
*
* @return array An associative array of data
*
* @access public
*/
public function result()
{
public function result() {
if (!empty($this->response->AuthToken)) {
return $this->buildAuthenticationToken();
}
else if (!empty($this->response->SessionToken)) {
elseif (!empty($this->response->SessionToken)) {
return (string) $this->response->SessionToken;
}
else if (!empty($this->response->SearchResult)) {
elseif (!empty($this->response->SearchResult)) {
return $this->buildSearch();
}
else if(!empty($this->response->Record)) {
elseif (!empty($this->response->Record)) {
return $this->buildRetrieve();
}
else if(!empty($this->response->AvailableSearchCriteria)) {
elseif (!empty($this->response->AvailableSearchCriteria)) {
return $this->buildInfo();
}
else { // Should not happen, it may be an exception
// Should not happen, it may be an exception.
else {
return $this->response;
}
}
/**
* Parse the SimpleXml object when an AuthenticationToken API call was executed
* Parse the SimpleXml object when an AuthenticationToken API call was executed.
*
* @param none
*
* @return array An associative array of data
*
* @access private
*/
private function buildAuthenticationToken()
{
private function buildAuthenticationToken() {
$token = (string) $this->response->AuthToken;
$timeout = (integer) $this->response->AuthTimeout;
$result = array(
'authenticationToken' => $token,
'authenticationTimeout' => $timeout
'authenticationTimeout' => $timeout,
);
return $result;
@ -107,15 +103,15 @@ class EBSCOResponse
/**
* Parse a SimpleXml object and
* return it as an associative array
* return it as an associative array.
*
* @param none
*
* @return array An associative array of data
*
* @access private
*/
private function buildSearch()
{
private function buildSearch() {
$hits = (integer) $this->response->SearchResult->Statistics->TotalHits;
$searchTime = (integer) $this->response->SearchResult->Statistics->TotalSearchTime / 1000;
$records = array();
@ -125,17 +121,17 @@ class EBSCOResponse
$facets = $this->buildFacets();
}
// research Starters & emp
$relatedC=null;
// Research Starters & emp.
$relatedC = NULL;
if ($this->response->SearchResult->RelatedContent) {
$result =json_decode(json_encode($this->response->SearchResult->RelatedContent), TRUE);;
$result = json_decode(json_encode($this->response->SearchResult->RelatedContent), TRUE);;
$relatedC = $result;
}
//did you mean / auto suggest
$autoSuggestTerms=null;
// Did you mean / auto suggest.
$autoSuggestTerms = NULL;
if ($this->response->SearchResult->AutoSuggestedTerms) {
$result =json_decode(json_encode($this->response->SearchResult->AutoSuggestedTerms), TRUE);;
$result = json_decode(json_encode($this->response->SearchResult->AutoSuggestedTerms), TRUE);;
$autoSuggestTerms = $result;
}
@ -147,31 +143,29 @@ class EBSCOResponse
'documents' => $records,
'relatedContent' => $relatedC,
'autoSuggestTerms' => $autoSuggestTerms,
'facets' => $facets
'facets' => $facets,
);
return $results;
}
/**
* Parse a SimpleXml object and
* return it as an associative array
* return it as an associative array.
*
* @param none
*
* @return array An associative array of data
*
* @access private
*/
private function buildRecords()
{
private function buildRecords() {
$results = array();
$records = $this->response->SearchResult->Data->Records->Record;
foreach ($records as $record) {
$result = array();
//var_dump($record);
// var_dump($record);
$result['ResultId'] = $record->ResultId ? (integer) $record->ResultId : '';
$result['DbId'] = $record->Header->DbId ? (string) $record->Header->DbId : '';
$result['DbLabel'] = $record->Header->DbLabel ? (string) $record->Header->DbLabel : '';
@ -186,16 +180,16 @@ class EBSCOResponse
$target = (string) $image->Target;
$result['ImageInfo'][$size] = $target;
}
} else {
}
else {
$result['ImageInfo'] = '';
}
if ($record->FullText) {
$availability = (integer) $record->FullText->Text->Availability == 1;
$links = array();
//RF 2012-12-18
if (isset($record->FullText->Links))
{
// RF 2012-12-18.
if (isset($record->FullText->Links)) {
foreach ($record->FullText->Links->Link as $link) {
$type = (string) $link->Type;
$url = (string) $link->Url;
@ -207,7 +201,7 @@ class EBSCOResponse
}
$result['FullText'] = array(
'Availability' => $availability,
'Links' => $links
'Links' => $links,
);
}
@ -226,12 +220,12 @@ class EBSCOResponse
'MouseOverText' => $mouseOverText,
'Name' => $name,
'Text' => $text,
'Url' => $url
'Url' => $url,
);
}
}
if($record->Items) {
if ($record->Items) {
$result['Items'] = array();
foreach ($record->Items->Item as $item) {
$name = $item->Name ? (string) $item->Name : '';
@ -242,31 +236,28 @@ class EBSCOResponse
'Name' => $name,
'Label' => $label,
'Group' => $group,
'Data' => $this->toHTML($data, $group)
'Data' => $this->toHTML($data, $group),
);
}
}
$results[] = $result;
}
return $results;
}
/**
* Parse a SimpleXml object and
* return it as an associative array
* return it as an associative array.
*
* @param none
*
* @return array An associative array of data
*
* @access private
*/
private function buildFacets()
{
private function buildFacets() {
$results = array();
$facets = $this->response->SearchResult->AvailableFacets->AvailableFacet;
@ -275,13 +266,13 @@ class EBSCOResponse
$values = array();
foreach ($facet->AvailableFacetValues->AvailableFacetValue as $value) {
$this_value = (string) $value->Value;
$this_value = str_replace(array('\(','\)'), array('(', ')'), $this_value);
$this_value = str_replace(array('\(', '\)'), array('(', ')'), $this_value);
$this_action = (string) $value->AddAction;
$this_action = str_replace(array('\(','\)'), array('(', ')'), $this_action);
$this_action = str_replace(array('\(', '\)'), array('(', ')'), $this_action);
$values[] = array(
'Value' => $this_value,
'Action' => $this_action,
'Count' => (string) $value->Count
'Count' => (string) $value->Count,
);
}
$id = (string) $facet->Id;
@ -291,7 +282,7 @@ class EBSCOResponse
'Id' => $id,
'Label' => $label,
'Values' => $values,
'isApplied' => false
'isApplied' => FALSE,
);
}
}
@ -300,40 +291,39 @@ class EBSCOResponse
return $results;
}
/**
* Parse a SimpleXml object and
* return it as an associative array
* return it as an associative array.
*
* @param none
*
* @return array An associative array of data
*
* @access private
*/
private function buildInfo()
{
// Sort options
private function buildInfo() {
// Sort options.
$elements = $this->response->AvailableSearchCriteria->AvailableSorts->AvailableSort;
$sort = array();
foreach ($elements as $element) {
$sort[] = array(
'Id' => (string) $element->Id,
'Label' => (string) $element->Label,
'Action' => (string) $element->AddAction
'Action' => (string) $element->AddAction,
);
}
// Search fields
// Search fields.
$elements = $this->response->AvailableSearchCriteria->AvailableSearchFields->AvailableSearchField;
$tags = array();
foreach ($elements as $element) {
$tags[] = array(
'Label' => (string) $element->Label,
'Code' => (string) $element->FieldCode
'Code' => (string) $element->FieldCode,
);
}
// Expanders
// Expanders.
$elements = $this->response->AvailableSearchCriteria->AvailableExpanders->AvailableExpander;
$expanders = array();
foreach ($elements as $element) {
@ -341,11 +331,12 @@ class EBSCOResponse
'Id' => (string) $element->Id,
'Label' => (string) $element->Label,
'Action' => (string) $element->AddAction,
'selected' => false // Added because of the checkboxes
// Added because of the checkboxes.
'selected' => FALSE,
);
}
// RelatedContent
// RelatedContent.
$elements = $this->response->AvailableSearchCriteria->AvailableRelatedContent->AvailableRelatedContent;
$relatedContent = array();
foreach ($elements as $element) {
@ -353,33 +344,34 @@ class EBSCOResponse
'Type' => (string) $element->Type,
'Label' => (string) $element->Label,
'Action' => (string) $element->AddAction,
'DefaultOn' => (string) $element->DefaultOn
'DefaultOn' => (string) $element->DefaultOn,
);
}
// Did you mean
// Did you mean.
$elements = $this->response->AvailableSearchCriteria->AvailableDidYouMeanOptions->AvailableDidYouMeanOption;
$didYouMean = array();
foreach ($elements as $element) {
$didYouMean[] = array(
'Id' => (string) $element->Id,
'Label' => (string) $element->Label,
'DefaultOn' => (string) $element->DefaultOn
'DefaultOn' => (string) $element->DefaultOn,
);
}
// Limiters
// Limiters.
$elements = $this->response->AvailableSearchCriteria->AvailableLimiters->AvailableLimiter;
$limiters = array();
$values = array();
foreach ($elements as $element) {
if ($element->LimiterValues) {
$items = $element->LimiterValues->LimiterValue;
foreach($items as $item) {
foreach ($items as $item) {
$values[] = array(
'Value' => (string) $item->Value,
'Action' => (string) $item->AddAction,
'selected' => false // Added because of the checkboxes
// Added because of the checkboxes.
'selected' => FALSE,
);
}
}
@ -389,7 +381,7 @@ class EBSCOResponse
'Action' => (string) $element->AddAction,
'Type' => (string) $element->Type,
'Values' => $values,
'selected' => false
'selected' => FALSE,
);
}
@ -399,27 +391,27 @@ class EBSCOResponse
'expanders' => $expanders,
'limiters' => $limiters,
'relatedContent' => $relatedContent,
'didYouMean' => $didYouMean
'didYouMean' => $didYouMean,
);
return $result;
}
/**
* Parse a SimpleXml object and
* return it as an associative array
* return it as an associative array.
*
* @param none
*
* @return array An associative array of data
*
* @access private
*/
private function buildRetrieve()
{
private function buildRetrieve() {
$record = $this->response->Record;
if ($record) {
$record = $record[0]; // there is only one record
// There is only one record.
$record = $record[0];
}
$result = array();
@ -437,8 +429,7 @@ class EBSCOResponse
$result['ImageInfo'][$size] = $target;
}
}
else
{
else {
$result['ImageInfo'] = '';
}
@ -457,7 +448,7 @@ class EBSCOResponse
$result['FullText'] = array(
'Availability' => $availability,
'Links' => $links,
'Value' => $value
'Value' => $value,
);
}
@ -476,12 +467,12 @@ class EBSCOResponse
'MouseOverText' => $mouseOverText,
'Name' => $name,
'Text' => $text,
'Url' => $url
'Url' => $url,
);
}
}
if($record->Items) {
if ($record->Items) {
$result['Items'] = array();
foreach ($record->Items->Item as $item) {
$name = $item->Name ? (string) $item->Name : '';
@ -492,7 +483,7 @@ class EBSCOResponse
'Name' => $name,
'Label' => $label,
'Group' => $group,
'Data' => $this->toHTML($data, $group)
'Data' => $this->toHTML($data, $group),
);
}
}
@ -500,30 +491,32 @@ class EBSCOResponse
return $result;
}
/**
* Parse a SimpleXml element and
* return it's inner XML as an HTML string
* return it's inner XML as an HTML string.
*
* @param SimpleXml $element A SimpleXml DOM
* @param SimpleXml $element
* A SimpleXml DOM.
*
* @return string The HTML string
*
* @access protected
*/
private function toHTML($data, $group = null)
{
private function toHTML($data, $group = NULL) {
// Any group can be added here, but we only use Au (Author)
// Other groups, not present here, won't be transformed to HTML links
// Other groups, not present here, won't be transformed to HTML links.
$allowed_searchlink_groups = array('au');
// Map xml tags to the HTML tags
// This is just a small list, the total number of xml tags is far more greater
// This is just a small list, the total number of xml tags is far more greater.
$xml_to_html_tags = array(
'<jsection' => '<section',
'</jsection' => '</section',
'<highlight' => '<span class="highlight"',
'<highligh' => '<span class="highlight"', // Temporary bug fix
'</highlight>' => '</span>', // Temporary bug fix
// Temporary bug fix.
'<highligh' => '<span class="highlight"',
// Temporary bug fix.
'</highlight>' => '</span>',
'</highligh' => '</span>',
'<text' => '<div',
'</text' => '</div',
@ -552,34 +545,34 @@ class EBSCOResponse
'<ulink' => '<a',
'</ulink' => '</a',
'<superscript' => '<sup',
'</superscript'=> '</sup',
'</superscript' => '</sup',
'<relatesTo' => '<sup',
'</relatesTo' => '</sup'
'</relatesTo' => '</sup',
);
// Map xml types to Search types used by the UI
// Map xml types to Search types used by the UI.
$xml_to_search_types = array(
'au' => 'Author',
'su' => 'Subject'
'su' => 'Subject',
);
// The XML data is XML escaped, let's unescape html entities (e.g. &lt; => <)
$data = html_entity_decode($data);
// Start parsing the xml data
// Start parsing the xml data.
if (!empty($data)) {
// Replace the XML tags with HTML tags
// Replace the XML tags with HTML tags.
$search = array_keys($xml_to_html_tags);
$replace = array_values($xml_to_html_tags);
$data = str_replace($search, $replace, $data);
// Temporary : fix unclosed tags
// Temporary : fix unclosed tags.
$data = preg_replace('/<\/highlight/', '</span>', $data);
$data = preg_replace('/<\/span>>/', '</span>', $data);
$data = preg_replace('/<\/searchLink/', '</searchLink>', $data);
$data = preg_replace('/<\/searchLink>>/', '</searchLink>', $data);
// Parse searchLinks
// Parse searchLinks.
if (!empty($group)) {
$group = strtolower($group);
if (in_array($group, $allowed_searchlink_groups)) {
@ -592,7 +585,7 @@ class EBSCOResponse
}
}
// Replace the rest of searchLinks with simple spans
// Replace the rest of searchLinks with simple spans.
$link_xml = '/<searchLink fieldCode="([^\"]*)" term="%22([^\"]*)%22">/';
$link_html = '<span>';
$data = preg_replace($link_xml, $link_html, $data);
@ -603,13 +596,10 @@ class EBSCOResponse
$data = preg_replace('/<a id="([^\"]*)" idref="([^\"]*)" type="([^\"]*)"/', '<a id="$1" href="#$2"', $data);
}
$sanitizer = new HTML_Sanitizer;
$sanitizer = new HTML_Sanitizer();
$data = $sanitizer->sanitize($data);
return $data;
}
}
?>

370
ebsco/lib/sanitizer.class.php

@ -1,40 +1,44 @@
<?php // $Id$
<?php
// vim: expandtab sw=4 ts=4 sts=4:
# ***** BEGIN LICENSE BLOCK *****
# This file is part of HTML Sanitizer.
# Copyright (c) 2005-2011 Frederic Minne <zefredz@gmail.com>.
# All rights reserved.
#
# HTML Sanitizer is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# HTML Sanitizer is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with HTML Sanitizer; if not, see <http://www.gnu.org/licenses/>.
#
# ***** END LICENSE BLOCK *****
/**
* @file
* $Id$.
*/
// vim: expandtab sw=4 ts=4 sts=4:
// ***** BEGIN LICENSE BLOCK *****
// This file is part of HTML Sanitizer.
// Copyright (c) 2005-2011 Frederic Minne <zefredz@gmail.com>.
// All rights reserved.
//
// HTML Sanitizer is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// (at your option) any later version.
//
// HTML Sanitizer is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with HTML Sanitizer; if not, see <http://www.gnu.org/licenses/>.
//
// ***** END LICENSE BLOCK *****.
/**
* Sanitize HTML contents :
* Remove dangerous tags and attributes that can lead to security issues like
* XSS or HTTP response splitting
* XSS or HTTP response splitting.
*
* @author Frederic Minne <zefredz@gmail.com>
* @copyright Copyright &copy; 2005-2011, Frederic Minne
* @license http://www.gnu.org/licenses/lgpl.txt GNU Lesser General Public License version 3 or later
* @version 1.1
*/
class HTML_Sanitizer
{
// Private fields
class HTML_Sanitizer {
/**
* Private fields.
*/
private $_allowedTags;
private $_allowJavascriptEvents;
private $_allowJavascriptInUrls;
@ -44,125 +48,123 @@ class HTML_Sanitizer
private $_additionalTags;
/**
* Constructor
* Constructor.
*/
public function __construct()
{
public function __construct() {
$this->resetAll();
}
/**
* (re)set all options to default value
* (re)set all options to default value.
*/
public function resetAll()
{
$this->_allowDOMEvents = false;
$this->_allowJavascriptInUrls = false;
$this->_allowStyle = false;
$this->_allowScript = false;
$this->_allowObjects = false;
$this->_allowStyle = false;
public function resetAll() {
$this->_allowDOMEvents = FALSE;
$this->_allowJavascriptInUrls = FALSE;
$this->_allowStyle = FALSE;
$this->_allowScript = FALSE;
$this->_allowObjects = FALSE;
$this->_allowStyle = FALSE;
$this->_allowedTags = '<a><br><b><h1><h2><h3><h4><h5><h6>'
. '<img><li><ol><p><strong><table><tr><td><th><u><ul><thead>'
. '<tbody><tfoot><em><dd><dt><dl><span><div><del><add><i><hr>'
. '<pre><br><blockquote><address><code><caption><abbr><acronym>'
. '<cite><dfn><q><ins><sup><sub><kbd><samp><var><tt><small><big>'
;
. '<cite><dfn><q><ins><sup><sub><kbd><samp><var><tt><small><big>';
$this->_additionalTags = '';
}
/**
* Add additional tags to allowed tags
* Add additional tags to allowed tags.
*
* @param string
*
* @access public
*/
public function addAdditionalTags( $tags )
{
public function addAdditionalTags($tags) {
$this->_additionalTags .= $tags;
}
/**
* Allow iframes
* Allow iframes.
*
* @access public
*/
public function allowIframes()
{
$this->addAdditionalTags( '<iframe>' );
public function allowIframes() {
$this->addAdditionalTags('<iframe>');
}
/**
* Allow HTML5 media tags
* Allow HTML5 media tags.
*
* @access public
*/
public function allowHtml5Media()
{
$this->addAdditionalTags( '<canvas><video><audio>' );
public function allowHtml5Media() {
$this->addAdditionalTags('<canvas><video><audio>');
}
/**
* Allow object, embed, applet and param tags in html
* Allow object, embed, applet and param tags in html.
*
* @access public
*/
public function allowObjects()
{
$this->_allowObjects = true;
public function allowObjects() {
$this->_allowObjects = TRUE;
}
/**
* Allow DOM event on DOM elements
* Allow DOM event on DOM elements.
*
* @access public
*/
public function allowDOMEvents()
{
$this->_allowDOMEvents = true;
public function allowDOMEvents() {
$this->_allowDOMEvents = TRUE;
}
/**
* Allow script tags
* Allow script tags.
*
* @access public
*/
public function allowScript()
{
$this->_allowScript = true;
public function allowScript() {
$this->_allowScript = TRUE;
}
/**
* Allow the use of javascript: in urls
* Allow the use of javascript: in urls.
*
* @access public
*/
public function allowJavascriptInUrls()
{
$this->_allowJavascriptInUrls = true;
public function allowJavascriptInUrls() {
$this->_allowJavascriptInUrls = TRUE;
}
/**
* Allow style tags and attributes
* Allow style tags and attributes.
*
* @access public
*/
public function allowStyle()
{
$this->_allowStyle = true;
public function allowStyle() {
$this->_allowStyle = TRUE;
}
/**
* Helper to allow all javascript related tags and attributes
* Helper to allow all javascript related tags and attributes.
*
* @access public
*/
public function allowAllJavascript()
{
public function allowAllJavascript() {
$this->allowDOMEvents();
$this->allowScript();
$this->allowJavascriptInUrls();
}
/**
* Allow all tags and attributes
* Allow all tags and attributes.
*
* @access public
*/
public function allowAll()
{
public function allowAll() {
$this->allowAllJavascript();
$this->allowObjects();
$this->allowStyle();
@ -171,225 +173,220 @@ class HTML_Sanitizer
}
/**
* Filter URLs to avoid HTTP response splitting attacks
* Filter URLs to avoid HTTP response splitting attacks.
*
* @access public
* @param string url
*
* @return string filtered url
*/
public function filterHTTPResponseSplitting( $url )
{
public function filterHTTPResponseSplitting($url) {
$dangerousCharactersPattern = '~(\r\n|\r|\n|%0a|%0d|%0D|%0A)~';
return preg_replace( $dangerousCharactersPattern, '', $url );
return preg_replace($dangerousCharactersPattern, '', $url);
}
/**
* Remove potential javascript in urls
* Remove potential javascript in urls.
*
* @access public
* @param string url
*
* @return string filtered url
*/
public function removeJavascriptURL( $str )
{
public function removeJavascriptURL($str) {
$HTML_Sanitizer_stripJavascriptURL = 'javascript:[^"]+';
$str = preg_replace("/$HTML_Sanitizer_stripJavascriptURL/i"
, '__forbidden__'
, $str );
$str = preg_replace("/$HTML_Sanitizer_stripJavascriptURL/i", '__forbidden__', $str);
return $str;
}
/**
* Remove potential flaws in urls
* Remove potential flaws in urls.
*
* @access private
* @param string url
*
* @return string filtered url
*/
private function sanitizeURL( $url )
{
if ( ! $this->_allowJavascriptInUrls )
{
$url = $this->removeJavascriptURL( $url );
private function sanitizeURL($url) {
if (!$this->_allowJavascriptInUrls) {
$url = $this->removeJavascriptURL($url);
}
$url = $this->filterHTTPResponseSplitting( $url );
$url = $this->filterHTTPResponseSplitting($url);
return $url;
}
/**
* Callback for PCRE
* Callback for PCRE.
*
* @access private
* @param matches array
*
* @return string
*
* @see sanitizeURL
*/
private function _sanitizeURLCallback( $matches )
{
return 'href="'.$this->sanitizeURL( $matches[1] ).'"';
private function _sanitizeURLCallback($matches) {
return 'href="' . $this->sanitizeURL($matches[1]) . '"';
}
/**
* Remove potential flaws in href attributes
* Remove potential flaws in href attributes.
*
* @access private
* @param string html tag
*
* @return string filtered html tag
*/
private function sanitizeHref( $str )
{
private function sanitizeHref($str) {
$HTML_Sanitizer_URL = 'href="([^"]+)"';
return preg_replace_callback("/$HTML_Sanitizer_URL/i"
, array( &$this, '_sanitizeURLCallback' )
, $str );
return preg_replace_callback("/$HTML_Sanitizer_URL/i", array(&$this, '_sanitizeURLCallback'), $str);
}
/**
* Callback for PCRE
* Callback for PCRE.
*
* @access private
* @param matches array
*
* @return string
*
* @see sanitizeURL
*/
private function _sanitizeSrcCallback( $matches )
{
return 'src="'.$this->sanitizeURL( $matches[1] ).'"';
private function _sanitizeSrcCallback($matches) {
return 'src="' . $this->sanitizeURL($matches[1]) . '"';
}
/**
* Remove potential flaws in href attributes
* Remove potential flaws in href attributes.
*
* @access private
* @param string html tag
*
* @return string filtered html tag
*/
private function sanitizeSrc( $str )
{
private function sanitizeSrc($str) {
$HTML_Sanitizer_URL = 'src="([^"]+)"';
return preg_replace_callback("/$HTML_Sanitizer_URL/i"
, array( &$this, '_sanitizeSrcCallback' )
, $str );
return preg_replace_callback("/$HTML_Sanitizer_URL/i", array(&$this, '_sanitizeSrcCallback'), $str);
}
/**
* Remove dangerous attributes from html tags
* Remove dangerous attributes from html tags.
*
* @access private
* @param string html tag
*
* @return string filtered html tag
*/
private function removeEvilAttributes( $str )
{
if ( ! $this->_allowDOMEvents )
{
$str = preg_replace_callback('/<(.*?)>/i'
, array( &$this, '_removeDOMEventsCallback' )
, $str );
private function removeEvilAttributes($str) {
if (!$this->_allowDOMEvents) {
$str = preg_replace_callback('/<(.*?)>/i', array(&$this, '_removeDOMEventsCallback'), $str);
}
if ( ! $this->_allowStyle )
{
$str = preg_replace_callback('/<(.*?)>/i'
, array( &$this, '_removeStyleCallback' )
, $str );
if (!$this->_allowStyle) {
$str = preg_replace_callback('/<(.*?)>/i', array(&$this, '_removeStyleCallback'), $str);
}
return $str;
}
/**
* Remove DOM events attributes from html tags
* Remove DOM events attributes from html tags.
*
* @access private
* @param string html tag
*
* @return string filtered html tag
*/
private function removeDOMEvents( $str )
{
$str = preg_replace ( '/\s*=\s*/', '=', $str );
private function removeDOMEvents($str) {
$str = preg_replace('/\s*=\s*/', '=', $str);
$HTML_Sanitizer_stripAttrib = '(onclick|ondblclick|onmousedown|'
. 'onmouseup|onmouseover|onmousemove|onmouseout|onkeypress|onkeydown|'
. 'onkeyup|onfocus|onblur|onabort|onerror|onload)'
;
. 'onkeyup|onfocus|onblur|onabort|onerror|onload)';
$str = stripslashes( preg_replace("/$HTML_Sanitizer_stripAttrib/i"
, 'forbidden'
, $str ) );
$str = stripslashes(preg_replace("/$HTML_Sanitizer_stripAttrib/i", 'forbidden', $str));
return $str;
}
/**
* Callback for PCRE
* Callback for PCRE.
*
* @access private
* @param matches array
*
* @return string
*
* @see removeDOMEvents
*/
private function _removeDOMEventsCallback( $matches )
{
return '<' . $this->removeDOMEvents( $matches[1] ) . '>';
private function _removeDOMEventsCallback($matches) {
return '<' . $this->removeDOMEvents($matches[1]) . '>';
}
/**
* Remove style attributes from html tags
* Remove style attributes from html tags.
*
* @access private
* @param string html tag
*
* @return string filtered html tag
*/
private function removeStyle( $str )
{
$str = preg_replace ( '/\s*=\s*/', '=', $str );
private function removeStyle($str) {
$str = preg_replace('/\s*=\s*/', '=', $str);
$HTML_Sanitizer_stripAttrib = '(style)'
;
$HTML_Sanitizer_stripAttrib = '(style)';
$str = stripslashes( preg_replace("/$HTML_Sanitizer_stripAttrib/i"
, 'forbidden'
, $str ) );
$str = stripslashes(preg_replace("/$HTML_Sanitizer_stripAttrib/i", 'forbidden', $str));
return $str;
}
/**
* Callback for PCRE
* Callback for PCRE.
*
* @access private
* @param matches array
*
* @return string
*
* @see removeStyle
*/
private function _removeStyleCallback( $matches )
{
return '<' . $this->removeStyle( $matches[1] ) . '>';
private function _removeStyleCallback($matches) {
return '<' . $this->removeStyle($matches[1]) . '>';
}
/**
* Remove dangerous HTML tags
* Remove dangerous HTML tags.
*
* @access private
* @param string html code
*
* @return string filtered url
*/
private function removeEvilTags( $str )
{
private function removeEvilTags($str) {
$allowedTags = $this->_allowedTags;
if ( $this->_allowScript )
{
if ($this->_allowScript) {
$allowedTags .= '<script>';
}
if ( $this->_allowStyle )
{
if ($this->_allowStyle) {
$allowedTags .= '<style>';
}
if ( $this->_allowObjects )
{
if ($this->_allowObjects) {
$allowedTags .= '<object><embed><applet><param>';
}
$allowedTags .= $this->_additionalTags;
$str = strip_tags($str, $allowedTags );
$str = strip_tags($str, $allowedTags);
return $str;
}
@ -397,48 +394,51 @@ class HTML_Sanitizer
/**
* Sanitize HTML
* remove dangerous tags and attributes
* clean urls
* clean urls.
*
* @access public
* @param string html code
*
* @return string sanitized html code
*/
public function sanitize( $html )
{
$html = $this->removeEvilTags( $html );
public function sanitize($html) {
$html = $this->removeEvilTags($html);
$html = $this->removeEvilAttributes( $html );
$html = $this->removeEvilAttributes($html);
$html = $this->sanitizeHref( $html );
$html = $this->sanitizeHref($html);
$html = $this->sanitizeSrc( $html );
$html = $this->sanitizeSrc($html);
return $html;
}
}
function html_sanitize( $str )
{
static $san = null;
/**
*
*/
function html_sanitize($str) {
static $san = NULL;
if ( empty( $san ) )
{
$san = new HTML_Sanitizer;
if (empty($san)) {
$san = new HTML_Sanitizer();
}
return $san->sanitize( $str );
return $san->sanitize($str);
}
function html_loose_sanitize( $str )
{
static $san = null;
/**
*
*/
function html_loose_sanitize($str) {
static $san = NULL;
if ( empty( $san ) )
{
$san = new HTML_Sanitizer;
if (empty($san)) {
$san = new HTML_Sanitizer();
$san->allowAll();
}
return $san->sanitize( $str );
return $san->sanitize($str);
}

1
ebsco/templates/ebsco-advanced-search.tpl.php

@ -51,7 +51,6 @@
<option value="Abstract">Abstract</option>
<option value="ISBN">ISBN</option>
<option value="ISSN">ISSN</option>
</select>
</div>
<div class="delete-search">

8
ebsco/templates/ebsco-basic-search.tpl.php

@ -30,11 +30,11 @@
}
elseif ($search_view == 'advanced'){
echo '<a href="'.url('ebsco/advanced', array('query' => array('edit' => 1))).'" class="small">'.t('Edit this Advanced Search')."</a> |";
echo '<a href="'.url('ebsco/advanced').'" class="small">'.t('Start a new Advanced Search').'</a> |';
echo '<a href="'.url('ebsco/results').'" class="small">'.t('Start a new Basic Search').'</a>';
echo '<a href="' . url('ebsco/advanced', array('query' => array('edit' => 1))) . '" class="small">' . t('Edit this Advanced Search') . "</a> |";
echo '<a href="' . url('ebsco/advanced') . '" class="small">' . t('Start a new Advanced Search') . '</a> |';
echo '<a href="' . url('ebsco/results') . '" class="small">' . t('Start a new Basic Search') . '</a>';
echo "<br/>";
echo t('Your search terms').": <strong>".check_plain($lookfor); "</strong>";
echo t('Your search terms') . ": <strong>" . check_plain($lookfor); "</strong>";
}
?>
</div>

28
ebsco/templates/ebsco-result.tpl.php

@ -41,13 +41,13 @@
<div class="floatright">
<?php
if ($last_search['previous']){
echo '<a href="'.url('ebsco/result', array('query' => array('id' => $last_search['previous'], 'op' => 'Previous'))).'" class="_record_link">&laquo; '.t('Previous').'</a>';
echo '<a href="' . url('ebsco/result', array('query' => array('id' => $last_search['previous'], 'op' => 'Previous'))) . '" class="_record_link">&laquo; ' . t('Previous') . '</a>';
}
echo "#";
print $last_search['current_index']; ?> of <?php print $last_search['count'];
if ($last_search['next']){
echo '<a href="'.url('ebsco/result', array('query' => array('id' => $last_search['next'], 'op' => 'Next'))).'" class="_record_link">'.t('Next').' &raquo;</a>';
echo '<a href="' . url('ebsco/result', array('query' => array('id' => $last_search['next'], 'op' => 'Next'))) . '" class="_record_link">' . t('Next') . ' &raquo;</a>';
}
?>
@ -67,20 +67,20 @@
<ul class="external-links">
<?php
if($record->p_link){
echo "<li> <a href='".$record->p_link."'>".t('View in EDS')."</a></li>";
echo "<li> <a href='" . $record->p_link . "'>" . t('View in EDS') . "</a></li>";
}
if ($record->pdf_link){
echo '
<li>
<a href="'.$pdfUrl.'" class="icon pdf fulltext">'.t('PDF full text').'</a>
<a href="' . $pdfUrl . '" class="icon pdf fulltext">' . t('PDF full text') . '</a>
</li>';
}
if ($record->full_text_availability){
echo '
<li>
<a href="'.( (!user_is_logged_in())?$fulltextUrl:"").'#html" class="icon html fulltext">'.t('HTML full text').'</a>
<a href="' . ((!user_is_logged_in()) ? $fulltextUrl : "") . '#html" class="icon html fulltext">' . t('HTML full text') . '</a>
</li>';
}
@ -88,7 +88,7 @@
foreach ($record->custom_links as $link){
echo '
<li>
<a href="'.$link['Url'].'" target="_blank" title="'.$link['MouseOverText'].'" class="external-link">'. ($link['Icon'])? '<img src="'.$link['Icon'].'" />':''.$link['Name'].'</a>
<a href="' . $link['Url'] . '" target="_blank" title="' . $link['MouseOverText'] . '" class="external-link">' . ($link['Icon']) ? '<img src="' . $link['Icon'] . '" />' : '' . $link['Name'] . '</a>
</li>';
}
}
@ -103,8 +103,8 @@
if (!empty($item['Data'])){
echo '
<tr valign="top">
<th width="150">'.t($item['Label']).':</th>
<td>'.auto_link($item['Data']).'</td>
<th width="150">' . t($item['Label']) . ':</th>
<td>' . auto_link($item['Data']) . '</td>
</tr>';
}
}
@ -112,23 +112,23 @@
if ($record->db_label){
echo '
<tr valign="top">
<th width="150">'.t('Database').':</th><td>'.check_plain($record->db_label).'</td>
<th width="150">' . t('Database') . ':</th><td>' . check_plain($record->db_label) . '</td>
</tr>';
}
if ($record->full_text){
echo '
<tr id="html" valign="top">
<td colspan="2" class="html">'.$record->full_text.'</td>
<td colspan="2" class="html">' . $record->full_text . '</td>
</tr>';
}
elseif ($record->access_level && !user_is_logged_in()){
echo '
<tr id="html" valign="top">
<td colspan="2" class="html">
<p>'.t('The full text cannot be displayed to guests.').'<br />.';
<p>' . t('The full text cannot be displayed to guests.') . '<br />.';
$link = '<a href="' . url('user') . '">' . t('Login') . '</a>';
echo '<strong>'.sprintf(t('%s for full access.'), $link).'</strong>
echo '<strong>' . sprintf(t('%s for full access.'), $link) . '</strong>
</p>
</td>
</tr>
@ -141,11 +141,11 @@
<div class="span-4">
<?php
if ($record->medium_thumb_link){
echo '<img src="'.check_url($record->medium_thumb_link).'" class="book-jacket" alt="'.t('Book jacket').'"/>';
echo '<img src="' . check_url($record->medium_thumb_link) . '" class="book-jacket" alt="' . t('Book jacket') . '"/>';
}
if ($record->publication_type){
echo '<p>'. check_plain($record->publication_type).'</p>';
echo '<p>' . check_plain($record->publication_type) . '</p>';
}
?>
</div>

185
ebsco/templates/ebsco-results.tpl.php

@ -22,28 +22,27 @@
* limitations under the License.
*/
if (isset ($autoSuggestTerms) ) {
if (count($autoSuggestTerms)>0) {
$suggestString="";
foreach ($autoSuggestTerms as $term ) {
if (isset($autoSuggestTerms)) {
if (count($autoSuggestTerms) > 0) {
$suggestString = "";
foreach ($autoSuggestTerms as $term) {
$path = url('ebsco/results', array('query' => array('type' => "")));
$suggestString.="<a href=\"{$path}&lookfor=$term\">".$term."</a> ";
$suggestString .= "<a href=\"{$path}&lookfor=$term\">" . $term . "</a> ";
}
echo "<p><strong>Did you mean ".$suggestString."?</strong></p>";
echo "<p><strong>Did you mean " . $suggestString . "?</strong></p>";
}
}
if ($records){
echo t('Showing')." <strong>".$record_start."</strong> - <strong> ".$record_end."</strong> ".t('of')." <strong>".$record_count."</strong> ";
echo t('Showing') . " <strong>" . $record_start . "</strong> - <strong> " . $record_end . "</strong> " . t('of') . " <strong>" . $record_count . "</strong> ";
if ($search_view == 'basic') {
echo t('for search')." <strong>'".check_plain($lookfor)."'</strong> ";
echo t('for search') . " <strong>'" . check_plain($lookfor) . "'</strong> ";
}
if ($search_time){
echo "," .t('query time').":".check_plain(round($search_time, 2))." s";
echo "," . t('query time') . ":" . check_plain(round($search_time, 2)) . " s";
}
print $sort_form;
@ -56,134 +55,136 @@
echo '</p>';
}
$tabs="";
$tabsContent="";
$tabs = "";
$tabsContent = "";
$counter=0;
$rsItem=null;
$counter = 0;
$rsItem = NULL;
if (isset ($relatedContent) ) {
foreach ($relatedContent as $item ) {
if (isset($relatedContent)) {
foreach ($relatedContent as $item) {
if (isset($item["RelatedRecord"])) {
$tabs.='<li data-target="#researchstarters" data-slide-to="'.$counter.'" '.($counter==0?' class="active" ':' ').'></li>';
$tabs .= '<li data-target="#researchstarters" data-slide-to="' . $counter . '" ' . ($counter == 0 ? ' class="active" ' : ' ') . '></li>';
$counter++;
if (isset($item["RelatedRecord"]["Records"]["Record"][0])) {
$rsItem=$item["RelatedRecord"]["Records"]["Record"][0];
$rsItem = $item["RelatedRecord"]["Records"]["Record"][0];
}
else
{
if (isset($item["Records"]["Record"])) {
$rsItem=$item["Records"]["Record"];
$rsItem = $item["Records"]["Record"];
}
}
if ($rsItem==null) {
continue ;
if ($rsItem == NULL) {
continue;
}
//var_dump($rsItem);
$rsTitle="";
$rsSubjects="";
$rsAbstract="";
$rsSource="";
$rsImage="";
$rsAN=$rsItem["Header"]["An"];
$rsDB=$rsItem["Header"]["DbId"];
$rsUrl = url('ebsco/result', array('query' => array('id' => $rsAN."|".$rsDB)));
// var_dump($rsItem);
$rsTitle = "";
$rsSubjects = "";
$rsAbstract = "";
$rsSource = "";
$rsImage = "";
$rsAN = $rsItem["Header"]["An"];
$rsDB = $rsItem["Header"]["DbId"];
$rsUrl = url('ebsco/result', array('query' => array('id' => $rsAN . "|" . $rsDB)));
if (isset($rsItem["ImageInfo"]["CoverArt"])) {
$rsImage=$rsItem["ImageInfo"]["CoverArt"]["Target"];
$rsImage = $rsItem["ImageInfo"]["CoverArt"]["Target"];
}
foreach($rsItem["Items"]["Item"] as $it) {
switch ($it["Group"]) {
case "Ti":
$rsTitle=$it["Data"];
$rsTitle = $it["Data"];
break;
case "Src":
$rsSource=$it["Data"];
$rsSource = $it["Data"];
break;
case "Su":
$rsSubjects=$it["Data"];
$rsSubjects = $it["Data"];
break;
case "Ab":
$rsAbstract=$it["Data"];
$rsAbstract = $it["Data"];
break;
}
}
$tabsContent.='<div class="item" ><div class="carousel-caption">';
if ($rsImage<>"") {
$tabsContent.='<img src="'.$rsImage.'" alt="'.$rsTitle.'" style="float:left">';
$tabsContent .= '<div class="item" ><div class="carousel-caption">';
if ($rsImage <> "") {
$tabsContent .= '<img src="' . $rsImage . '" alt="' . $rsTitle . '" style="float:left">';
}
if ($rsTitle<>""){
$tabsContent.='<h3 class="relatedTitle"><a href="'.$rsUrl.'" class="title _record_link">'.$rsTitle.'</a></h3>';
if ($rsTitle <> ""){
$tabsContent .= '<h3 class="relatedTitle"><a href="' . $rsUrl . '" class="title _record_link">' . $rsTitle . '</a></h3>';
}
if ($rsSubjects<>""){
if ($rsSubjects <> ""){
$path = url('ebsco/results', array('query' => array('type' => "Subject")));
$link_xml = '/<searchLink fieldCode="([^\"]*)" term="%22([^\"]*)%22">/';
$link_html = "<a href=\"{$path}&lookfor=$2\">";
$rsSubjects = preg_replace($link_xml, $link_html, $rsSubjects);
$rsSubjects = str_replace('</searchLink>', '</a>', $rsSubjects);
$tabsContent.='<p><strong>'.t('Subjects').'</strong>:<span class="quotestart">'.str_replace(array("<br>","<br />"), ', ', $rsSubjects).'</span></p>';
$tabsContent .= '<p><strong>' . t('Subjects') . '</strong>:<span class="quotestart">' . str_replace(array("<br>", "<br />"), ', ', $rsSubjects) . '</span></p>';
}
if ($rsSource<>""){
$tabsContent.='<p>'.$rsSource.'</p>';
if ($rsSource <> ""){
$tabsContent .= '<p>' . $rsSource . '</p>';
}
if ($rsAbstract<>""){
$tabsContent.='<p><cite>'.$rsAbstract.'</cite></p>';
if ($rsAbstract <> ""){
$tabsContent .= '<p><cite>' . $rsAbstract . '</cite></p>';
}
$tabsContent.='</div></div>';
$tabsContent .= '</div></div>';
}
// replated publications
// Replated publications.
if (isset($item["RelatedPublication"])) {
//var_dump($item);
$tabs.='<li data-target="#ematchplacard" data-slide-to="'.$counter.'" '.($counter==0?' class="active" ':' ').'></li>';
// var_dump($item);
$tabs .= '<li data-target="#ematchplacard" data-slide-to="' . $counter . '" ' . ($counter == 0 ? ' class="active" ' : ' ') . '></li>';
$counter++;
$tabsContent.='<div class="item" ><div class="carousel-caption">';
$tabsContent.='
$tabsContent .= '<div class="item" ><div class="carousel-caption">';
$tabsContent .= '
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>
';
foreach ($item["RelatedPublication"]["PublicationRecords"] as $pub){
$plink = $pub["PLink"];
foreach($pub["Items"]["Item"] as $item) {
if ($item["Group"]=="Ti")
if ($item["Group"] == "Ti")
{
$tabsContent.='<h3 class="relatedTitle"><a href="'.$plink.' target="_blank" >'.$item["Data"].'</a></h3>';
$tabsContent .= '<h3 class="relatedTitle"><a href="' . $plink . ' target="_blank" >' . $item["Data"] . '</a></h3>';
}
else
{
$tabsContent.="<strong>".$item["Label"]."</strong> : ".$item["Data"]."<br/>";
$tabsContent .= "<strong>" . $item["Label"] . "</strong> : " . $item["Data"] . "<br/>";
}
}
$tabsContent.='<div id="publicationList"><ul>';
$tabsContent .= '<div id="publicationList"><ul>';
foreach($pub["FullTextHoldings"]["FullTextHolding"] as $itemHoldings) {
$hURL=isset($itemHoldings["URL"])?$itemHoldings["URL"] :"";
$hName=isset($itemHoldings["Name"])?$itemHoldings["Name"] :"";
$hCoverage=isset($itemHoldings["CoverageStatement"])?$itemHoldings["CoverageStatement"] :"";
$hEmbargo="";
$hURL = isset($itemHoldings["URL"]) ? $itemHoldings["URL"] : "";
$hName = isset($itemHoldings["Name"]) ? $itemHoldings["Name"] : "";
$hCoverage = isset($itemHoldings["CoverageStatement"]) ? $itemHoldings["CoverageStatement"] : "";
$hEmbargo = "";
if (isset($itemHoldings["EmbargoDescription"])) {
// if no embargo, zero size array
if (!is_array($itemHoldings["EmbargoDescription"] )) {
$hEmbargo=$itemHoldings["EmbargoDescription"];
// If no embargo, zero size array.
if (!is_array($itemHoldings["EmbargoDescription"])) {
$hEmbargo = $itemHoldings["EmbargoDescription"];
}
}
$tabsContent.='<li>
<a href="'.$hURL.'" target="_blank">'.$hName.'</a>;
<ul><li>Coverage:'.$hCoverage.'; ';
$tabsContent .= '<li>
<a href="' . $hURL . '" target="_blank">' . $hName . '</a>;
<ul><li>Coverage:' . $hCoverage . '; ';
if ($hEmbargo<>'') {
$tabsContent.='</li><li>Embargo:'.$hEmbargo;
if ($hEmbargo <> '') {
$tabsContent .= '</li><li>Embargo:' . $hEmbargo;
}
$tabsContent.='</li></ul></li>';
// Notes
$tabsContent .= '</li></ul></li>';
// Notes.
}
$tabsContent.='</ul></div>';
$tabsContent .= '</ul></div>';
}
$tabsContent.='
$tabsContent .= '
<script>
jQuery("#publicationList").jstree().on("changed.jstree", function (e, data) {
var pubURL = data.instance.get_node(data.node, true).children("a").attr("href");
@ -192,21 +193,21 @@
}
});
</script>';
$tabsContent.='</div></div>';
$tabsContent .= '</div></div>';
break;
}
}
}
if ($tabsContent<>"") {
if ($tabsContent <> "") {
echo '<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<div id="relatedInformation" class="carousel slide" data-ride="carousel" style="display:block;">
<!-- Indicators -->
<ol class="carousel-indicators">'.$tabs.'</ol>';
echo '<div class="carousel-inner" role="listbox" >'.$tabsContent.'</div>';
<ol class="carousel-indicators">' . $tabs . '</ol>';
echo '<div class="carousel-inner" role="listbox" >' . $tabsContent . '</div>';
echo '<!-- Left and right controls -->
<a class="left carousel-control" href="#myCarousel" role="button" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left" ></span>
@ -244,9 +245,9 @@
<div class="span-2">
<?php
if ($record->small_thumb_link){
echo'
<a href="'.$recordUrl.'" class="_record_link">
<img src="'.$record->small_thumb_link.'" class="book-jacket" alt="'.t('Book jacket').'"/>
echo '
<a href="' . $recordUrl . '" class="_record_link">
<img src="' . $record->small_thumb_link . '" class="book-jacket" alt="' . t('Book jacket') . '"/>
</a>';
}
?>
@ -260,11 +261,11 @@
echo '<p>';
$label = '<strong>' . check_plain($record->db_label) . '</strong>';
$link = '<a href="' . url('user') . '">' . t('Login') . '</a>';
echo sprintf(t('This result from %s cannot be displayed to guests.'), $label)."<br /><strong>".sprintf(t('%s for full access.'), $link)."</strong>";
echo sprintf(t('This result from %s cannot be displayed to guests.'), $label) . "<br /><strong>" . sprintf(t('%s for full access.'), $link) . "</strong>";
echo "</p>";
}
elseif ($record->title){
echo '<a href="'.$recordUrl.'" class="title _record_link">'.$record->title.'</a>';
echo '<a href="' . $recordUrl . '" class="title _record_link">' . $record->title . '</a>';
}
?>
</div>
@ -272,11 +273,11 @@
<div class="result-line2">
<?php
if (!empty($record->authors)){
echo "<span>".t('by'). " ".str_replace(array("<br>","<br />"), ', ', $record->authors)." </span>";
echo "<span>" . t('by') . " " . str_replace(array("<br>", "<br />"), ', ', $record->authors) . " </span>";
}
if (!empty($record->source)){
echo '<p>'.t('Published in')." ".$record->source.'</p>';
echo '<p>' . t('Published in') . " " . $record->source . '</p>';
}
?>
@ -286,11 +287,11 @@
<?php
if (!empty($record->summary)){
echo '<cite>'.$record->summary.'</cite><br />';
echo '<cite>' . $record->summary . '</cite><br />';
}
if (!empty($record->subjects)){
echo '<strong>'.t('Subjects').'</strong>:<span class="quotestart">'.str_replace('<br />', ', ', $record->subjects).'</span>';
echo '<strong>' . t('Subjects') . '</strong>:<span class="quotestart">' . str_replace('<br />', ', ', $record->subjects) . '</span>';
}
?>
@ -305,7 +306,8 @@
foreach ($record->custom_links as $link){ ?>
<li>
<a href="<?php print $link['Url']; ?>" target="_blank" title="<?php print $link['MouseOverText']; ?>" class="external-link">
<?php if ($link['Icon']): ?><img src="<?php print $link['Icon']?>" /><?php endif; ?><?php print $link['Name']; ?>
<?php if ($link['Icon']): ?><img src="<?php print $link['Icon']?>" /><?php
endif; ?><?php print $link['Name']; ?>
</a>
</li>
<?php } ?>
@ -316,13 +318,13 @@
<div class="result-line5">
<?php
if ($record->full_text_availability){
echo '<a href="'.$fulltextUrl.'#html" class="icon html fulltext _record_link">';
echo '<a href="' . $fulltextUrl . '#html" class="icon html fulltext _record_link">';
echo t('HTML full text');
echo "</a>&nbsp; &nbsp;";
}
if ($record->pdf_availability){
echo ' <a href="'.$pdfUrl.'" class="icon pdf fulltext">';
echo ' <a href="' . $pdfUrl . '" class="icon pdf fulltext">';
echo t('PDF full text');
echo "</a>";
}
@ -340,9 +342,8 @@
<?php
}
elseif (!empty($lookfor)) {
echo "<h2>".t('Your search did not match any resources.')."</h2>";
// check for autocomplete
echo "<h2>" . t('Your search did not match any resources.') . "</h2>";
// Check for autocomplete.
/*
if (isset ($autoSuggestTerms) ) {
if (count($autoSuggestTerms)>0) {

2
ebsco/templates/ebsco-side-facets.tpl.php

@ -2,7 +2,7 @@
/**
* @file
* Display the sidebar block with facets filters
* Display the sidebar block with facets filters.
*
* @see template_preprocess_ebsco_side_facets()
*

Loading…
Cancel
Save