You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

393 lines
21 KiB

  1. <?php
  2. // Project: Web Reference Database (refbase) <http://www.refbase.net>
  3. // Copyright: Matthias Steffens <mailto:refbase@extracts.de> and the file's
  4. // original author(s).
  5. //
  6. // This code is distributed in the hope that it will be useful,
  7. // but WITHOUT ANY WARRANTY. Please see the GNU General Public
  8. // License for more details.
  9. //
  10. // File: ./sru.php
  11. // Repository: $HeadURL: file:///svn/p/refbase/code/branches/bleeding-edge/sru.php $
  12. // Author(s): Matthias Steffens <mailto:refbase@extracts.de>
  13. //
  14. // Created: 17-May-05, 16:22
  15. // Modified: $Date: 2015-01-07 23:50:55 +0000 (Wed, 07 Jan 2015) $
  16. // $Author: karnesky $
  17. // $Revision: 1399 $
  18. // This script serves as a (faceless) routing page which takes a SRU query and
  19. // converts the query into a native refbase query which is then passed to 'search.php'.
  20. // More info is given at <http://sru.refbase.net/>.
  21. // Supports 'explain' and 'searchRetrieve' operations (but not 'scan') and outputs
  22. // records as DC XML or MODS XML wrapped into SRW XML. Allows to query all global
  23. // refbase fields (the given index name must match either one of the 'set.index'
  24. // names listed in the explain response or match a refbase field name directly).
  25. // If no index name is given the 'serial' field will be searched by default.
  26. // Examples for recognized SRU/CQL queries:
  27. //
  28. // - ask the server to explain its SRW/U server & capabilities:
  29. // sru.php
  30. // sru.php?
  31. // sru.php?operation=explain&version=1.1
  32. //
  33. // - return record with serial number 1:
  34. // sru.php?version=1.1&query=1
  35. // sru.php?version=1.1&query=1&operation=searchRetrieve&recordPacking=xml&recordSchema=mods
  36. //
  37. // - find all records where the title field contains either 'ecology' or 'diversity':
  38. // sru.php?version=1.1&query=title%20any%20ecology%20diversity
  39. //
  40. // - find all records where the author field contains both 'dieckmann' and 'thomas':
  41. // sru.php?version=1.1&query=author%20all%20dieckmann%20thomas
  42. //
  43. // - find all records where the publication field equals exactly 'Marine Ecology Progress Series':
  44. // sru.php?version=1.1&query=publication%20exact%20Marine%20Ecology%20Progress%20Series
  45. //
  46. // - find all records where the year field is greater than or equals '2005':
  47. // sru.php?version=1.1&query=year>=2005
  48. //
  49. // - find records with serial numbers 1, 123, 499, 612, 21654 & 23013 but
  50. // return only the three last records:
  51. // sru.php?version=1.1&query=1%20123%20499%20612%2021654%2023013&startRecord=4&maximumRecords=3
  52. //
  53. // - return just the number of found records (but not the full record data):
  54. // sru.php?version=1.1&query=1%20123%20499%20612%2021654%2023013&maximumRecords=0
  55. //
  56. // - suppress the default stylesheet or specify your own:
  57. // sru.php?version=1.1&query=1&stylesheet=
  58. // sru.php?version=1.1&query=1&stylesheet=xml2html.xsl
  59. // Note that (if the 'version' & 'query' parameters are present in the
  60. // query) 'operation=searchRetrieve' is assumed if omitted. Additionally,
  61. // only 'recordPacking=xml' and 'recordSchema=dc' or 'recordSchema=mods' are
  62. // supported and 'sru.php' will default to 'recordSchema=mods' if these settings
  63. // weren't given in the query. Data will be returned together with a default
  64. // stylesheet if the 'stylesheet' parameter wasn't given in the query. XPath,
  65. // sort and result sets are not supported and only SRW/SRU version 1.1 is recognized.
  66. // For more on SRW/SRU, see:
  67. // <http://www.loc.gov/standards/sru>
  68. // TODO: - proper parsing of CQL query string (currently, 'sru.php' allows only for a limited set of CQL queries)
  69. // - offer support for the boolean CQL operators 'and/or/not' and parentheses
  70. // - honour the 'sortKeys' parameter and return records sorted accordingly
  71. // - create an XSLT stylesheet for SRW diagnostics
  72. // Incorporate some include files:
  73. include 'initialize/db.inc.php'; // 'db.inc.php' is included to hide username and password
  74. include 'includes/include.inc.php'; // include common functions
  75. include 'initialize/ini.inc.php'; // include common variables
  76. include 'includes/srwxml.inc.php'; // include functions that deal with SRW XML
  77. include_once 'includes/webservice.inc.php'; // include functions that are commonly used with the refbase webservices
  78. // --------------------------------------------------------------------
  79. // START A SESSION:
  80. // call the 'start_session()' function (from 'include.inc.php') which will also read out available session variables:
  81. start_session(true);
  82. // --------------------------------------------------------------------
  83. // Initialize preferred display language:
  84. // (note that 'locales.inc.php' has to be included *after* the call to the 'start_session()' function)
  85. include 'includes/locales.inc.php'; // include the locales
  86. // --------------------------------------------------------------------
  87. // Extract mandatory parameters passed to the script:
  88. if (isset($_REQUEST['query']))
  89. $sruQuery = $_REQUEST['query'];
  90. else
  91. $sruQuery = "";
  92. if (isset($_REQUEST['version']))
  93. $sruVersion = $_REQUEST['version'];
  94. else
  95. $sruVersion = "";
  96. // Extract optional parameters passed to the script:
  97. if (isset($_REQUEST['operation']) AND !empty($_REQUEST['operation']))
  98. $sruOperation = $_REQUEST['operation'];
  99. else
  100. $sruOperation = "searchRetrieve"; // we assume a 'searchRetrieve' operation if not given
  101. if (isset($_REQUEST['recordSchema']) AND !empty($_REQUEST['recordSchema'])) // 'recordSchema' must be either 'dc' or 'mods'
  102. $sruRecordSchema = $_REQUEST['recordSchema'];
  103. else
  104. $sruRecordSchema = "mods"; // we default to 'mods' if not given
  105. if (isset($_REQUEST['recordPacking']) AND !empty($_REQUEST['recordPacking'])) // note that we'll currently always output as 'xml'
  106. $sruRecordPacking = $_REQUEST['recordPacking'];
  107. else
  108. $sruRecordPacking = "xml";
  109. if (isset($_REQUEST['maximumRecords'])) // contains the desired number of search results (OpenSearch equivalent: '{count}')
  110. $showRows = $_REQUEST['maximumRecords'];
  111. else
  112. $showRows = $_SESSION['userRecordsPerPage']; // get the default number of records per page preferred by the current user
  113. if (isset($_REQUEST['startRecord'])) // contains the offset of the first search result, starting with one (OpenSearch equivalent: '{startIndex}')
  114. $rowOffset = ($_REQUEST['startRecord']) - 1; // first row number in a MySQL result set is 0 (not 1)
  115. else
  116. $rowOffset = ""; // if no value to the 'startRecord' parameter is given, we'll output records starting with the first record in the result set
  117. if (isset($_REQUEST['stylesheet'])) { // contains the desired stylesheet to be returned for transformation of XML data
  118. $stylesheet = $REQUEST['stylesheet'];
  119. $stylesheets = array("srwmods2html.xsl","srwExplainResponse2html.xsl","srwdc2html.xsl","DEFAULT");
  120. if (in_array($stylesheet,$stylesheets))
  121. $exportSylesheet = $stylesheet;
  122. else
  123. $exportStylesheet = "DEFAULT"; //invalid stylesheet specified
  124. } else
  125. $exportStylesheet = "DEFAULT"; // the special keyword "DEFAULT" causes a default stylesheet to be assigned below based on the requested operation and response format
  126. // Note that PHP will translate dots ('.') in parameter names into substrings ('_'). This is so that the
  127. // import_request_variables function can generate legitimate variable names (and a . is not permissable
  128. // in variable names in PHP). See the section labelled "Dots in incoming variable names" on this page:
  129. // <http://uk.php.net/variables.external>. So "$_REQUEST['x-info-2-auth1_0-authenticationToken']" will catch
  130. // the 'x-info-2-auth1.0-authenticationToken' parameter (thanks to Matthew J. Dovey for pointing this out!).
  131. if (isset($_REQUEST['x-info-2-auth1_0-authenticationToken'])) // PHP converts the dot in 'x-info-2-auth1.0-authenticationToken' into a substring!
  132. $authenticationToken = $_REQUEST['x-info-2-auth1_0-authenticationToken'];
  133. else
  134. $authenticationToken = "";
  135. // The following (optional) parameters are extracted but are not supported yet:
  136. if (isset($_REQUEST['sortKeys']))
  137. $sruSortKeys = $_REQUEST['sortKeys'];
  138. else
  139. $sruSortKeys = "";
  140. if (isset($_REQUEST['recordXPath']))
  141. $sruRecordXPath = $_REQUEST['recordXPath'];
  142. else
  143. $sruRecordXPath = "";
  144. if (isset($_REQUEST['resultSetTTL']))
  145. $sruResultSetTTL = $_REQUEST['resultSetTTL'];
  146. else
  147. $sruResultSetTTL = "";
  148. if (isset($_REQUEST['extraRequestData']))
  149. $sruExtraRequestData = $_REQUEST['extraRequestData'];
  150. else
  151. $sruExtraRequestData = "";
  152. // For the context of 'sru.php' we set some parameters explicitly:
  153. $displayType = "Export";
  154. if (preg_match("#^((oai_|srw_)?dc|info:srw/schema/1/dc-v1\.1|http://purl\.org/dc/elements/1\.1/)$#i", $sruRecordSchema)) // simple Dublin Core was requested as record schema
  155. $exportFormat = "SRW_DC XML";
  156. else
  157. $exportFormat = "SRW_MODS XML";
  158. $exportType = "xml";
  159. $showLinks = "1";
  160. $exportContentType = "application/xml";
  161. // -------------------------------------------------------------------------------------------------------------------
  162. $userID = "";
  163. if (preg_match('/^(marked|copy|selected|user_keys|user_notes|user_file|user_groups|bib\.citekey|cite_key|related)( +(all|any|exact|within) +| *(<>|<=|>=|<|>|=) *)/', $sruQuery)) // if the given index is a recognized user-specific field
  164. $userSpecificIndex = true;
  165. else
  166. $userSpecificIndex = false;
  167. if (preg_match('/^(marked|copy|selected|user_keys|user_notes|user_file|user_groups|related)( +(all|any|exact|within) +| *(<>|<=|>=|<|>|=) *)/', $sruQuery)) // if the given index is one of the private fields (i.e. any user-specific field but the 'cite_key' field)
  168. $privateIndex = true;
  169. else
  170. $privateIndex = false;
  171. // return diagnostic if no authentication token was given while querying a user-specific index:
  172. if (empty($authenticationToken) AND $userSpecificIndex)
  173. {
  174. returnDiagnostic(3, "Querying of user-specific fields requires the 'x-info-2-auth1.0-authenticationToken' parameter (format: 'email=EMAIL_ADDRESS')"); // authentication error: 'x-...authenticationToken' parameter is missing but required
  175. exit;
  176. }
  177. else if (!empty($authenticationToken)) // extract any authentication information that was passed with the query:
  178. {
  179. if (preg_match('/^email=.+/i', $authenticationToken))
  180. {
  181. $userEmail = preg_replace('/^email=(.+)/i', '\\1', $authenticationToken);
  182. $userID = getUserID($userEmail); // get the correct user ID for the passed email address (function 'getUserID()' is defined in 'include.inc.php')
  183. }
  184. // if an unrecognized email address was given while querying a user-specific index:
  185. if (empty($userID) AND $userSpecificIndex)
  186. {
  187. returnDiagnostic(3, "Couldn't map given authentication token to an existing user (expecting format: 'email=EMAIL_ADDRESS')"); // authentication error: couldn't map email address to user ID
  188. exit;
  189. }
  190. // if the passed email address could be resolved to a user ID but the current user has no permission to query/view the contents of any private fields for this user ID:
  191. // (i.e. if the user isn't logged in OR if the found user ID is not his own)
  192. elseif (!empty($userID) AND $privateIndex AND (!isset($_SESSION['loginEmail']) OR (isset($_SESSION['loginEmail']) AND ($loginUserID != $userID)))) // '$loginUserID' is provided as session variable
  193. {
  194. returnDiagnostic(68, "You have no permission to query or view any private data for the given email address"); // not authorised to request other user's private data
  195. exit;
  196. }
  197. }
  198. // -------------------------------------------------------------------------------------------------------------------
  199. // Parse CQL query:
  200. $searchArray = parseCQL($sruVersion, $sruQuery); // function 'parseCQL()' is defined in 'webservice.inc.php'
  201. // -------------------------------------------------------------------------------------------------------------------
  202. // Check for operation and that mandatory parameters have been passed:
  203. if ($sruOperation == "explain" OR (!isset($_REQUEST['query']) AND !isset($_REQUEST['version']) AND !isset($_REQUEST['operation']) AND !isset($_REQUEST['recordSchema']) AND !isset($_REQUEST['recordPacking']) AND !isset($_REQUEST['maximumRecords']) AND !isset($_REQUEST['startRecord']) AND !isset($_REQUEST['sortKeys']) AND !isset($_REQUEST['recordXPath']) AND !isset($_REQUEST['stylesheet']) AND !isset($_REQUEST['x-info-2-auth1_0-authenticationToken'])))
  204. {
  205. // if 'sru.php' was called with 'operation=explain' -OR- without any recognized parameters, we'll return an appropriate 'explainResponse':
  206. // use an appropriate default stylesheet:
  207. if ($exportStylesheet == "DEFAULT")
  208. $exportStylesheet = "srwExplainResponse2html.xsl";
  209. // Set the appropriate mimetype & set the character encoding to the one given
  210. // in '$contentTypeCharset' (which is defined in 'ini.inc.php'):
  211. setHeaderContentType($exportContentType, $contentTypeCharset); // function 'setHeaderContentType()' is defined in 'include.inc.php'
  212. echo srwExplainResponse($exportStylesheet); // function 'srwExplainResponse()' is defined in 'srwxml.inc.php'
  213. }
  214. // if 'sru.php' was called without any valid (or with incorrect) parameters, we'll return appropriate 'diagnostics':
  215. elseif (!preg_match("/^(explain|searchRetrieve)$/i",$sruOperation))
  216. returnDiagnostic(4, "Only 'explain' and 'searchRetrieve' operations are supported");
  217. elseif (empty($sruQuery))
  218. returnDiagnostic(7, "query"); // required 'query' parameter is missing
  219. elseif (empty($sruVersion))
  220. returnDiagnostic(7, "version"); // required 'version' parameter is missing
  221. elseif ($sruVersion != "1.1")
  222. returnDiagnostic(5, "1.1"); // only SRW version 1.1 is supported
  223. elseif (!preg_match("#^((srw_)?mods|info:srw/schema/1/mods-v3\.2|http://www\.loc\.gov/mods/v3)$#i",$sruRecordSchema) AND !preg_match("#^((oai_|srw_)?dc|info:srw/schema/1/dc-v1\.1|http://purl\.org/dc/elements/1\.1/)$#i",$sruRecordSchema))
  224. returnDiagnostic(66, $sruRecordSchema); // no other schema than MODS v3.2 or DC v1.1 (i.e. simple Dublin Core aka OAI_DC) is supported
  225. elseif (!preg_match("/^xml$/i",$sruRecordPacking))
  226. returnDiagnostic(71, "Only 'recordPacking=xml' is supported"); // no other record packing than XML is supported
  227. elseif (!empty($sruRecordXPath))
  228. returnDiagnostic(72, ""); // XPath isn't supported yet
  229. elseif (!empty($sruSortKeys))
  230. returnDiagnostic(80, ""); // Sort isn't supported yet
  231. elseif (!empty($sruResultSetTTL))
  232. returnDiagnostic(50, ""); // Result sets aren't supported
  233. // -------------------------------------------------------------------------------------------------------------------
  234. else // the script was called at least with the required parameters 'query' and 'version'
  235. {
  236. // use an appropriate default stylesheet:
  237. if ($exportStylesheet == "DEFAULT")
  238. {
  239. if (preg_match("#^((oai_|srw_)?dc|info:srw/schema/1/dc-v1\.1|http://purl\.org/dc/elements/1\.1/)$#i", $sruRecordSchema)) // simple Dublin Core was requested as record schema
  240. $exportStylesheet = "srwdc2html.xsl"; // use a stylesheet that's appropriate for SRW+DC XML
  241. else // use a stylesheet that's appropriate for SRW+MODS XML:
  242. $exportStylesheet = "srwmods2html.xsl";
  243. }
  244. // // NOTE: the generation of SQL queries (or parts of) should REALLY be modular and be moved to separate dedicated functions!
  245. // CONSTRUCT SQL QUERY:
  246. // TODO: build the complete SQL query using functions 'buildFROMclause()' and 'buildORDERclause()'
  247. // Note: the 'verifySQLQuery()' function that gets called by 'search.php' to process query data with "$formType = sqlSearch" will add the user-specific fields to the 'SELECT' clause
  248. // (with one exception: see note below!) and the 'LEFT JOIN...' part to the 'FROM' clause of the SQL query if a user is logged in. It will also add 'orig_record', 'serial', 'file',
  249. // 'url' & 'doi' columns as required. Therefore it's sufficient to provide just the plain SQL query here:
  250. // Build SELECT clause:
  251. // if a user-specific index was queried together with an authentication token that could be resolved to a user ID
  252. // - AND no user is logged in
  253. // - OR a user is logged in but the user ID does not match the current user's own ID
  254. // then we'll add user-specific fields here (as opposed to have them added by function 'verifySQLQuery()').
  255. // By adding fields after ", call_number, serial" we'll avoid the described query completion from function 'verifySQLQuery()'. This is done on purpose
  256. // here since (while user 'A' should be allowed to query cite keys of user 'B') we don't want user 'A' to be able to view other user-specific content of
  257. // user 'B'. By adding only 'cite_key' here, no other user-specific fields will be disclosed in case a logged-in user queries another user's cite keys.
  258. if ($userSpecificIndex AND (!empty($userID)) AND (!isset($_SESSION['loginEmail']) OR (isset($_SESSION['loginEmail']) AND ($userID != getUserID($loginEmail))))) // the session variable '$loginEmail' is made available globally by the 'start_session()' function
  259. $additionalFields = "cite_key"; // add 'cite_key' field
  260. else
  261. $additionalFields = "";
  262. $query = buildSELECTclause($displayType, $showLinks, $additionalFields, false, false); // function 'buildSELECTclause()' is defined in 'include.inc.php'
  263. // Build FROM clause:
  264. // We'll explicitly add the 'LEFT JOIN...' part to the 'FROM' clause of the SQL query if '$userID' isn't empty. This is done to allow querying
  265. // of the user-specific 'cite_key' field by users who are not logged in (function 'verifySQLQuery()' won't touch the 'LEFT JOIN...' or WHERE clause part
  266. // for users who aren't logged in if the query originates from 'sru.php'). For logged in users, the 'verifySQLQuery()' function would add a 'LEFT JOIN...'
  267. // statement (if not present) containing the users *own* user ID. By adding the 'LEFT JOIN...' statement explicitly here (which won't get touched by
  268. // 'verifySQLQuery()') we allow any user's 'cite_key' field to be queried by every user (e.g., by URLs like: 'sru.php?version=1.1&query=bib.citekey=...&x-info-2-auth1.0-authenticationToken=email=...').
  269. if (!empty($userID)) // the 'x-...authenticationToken' parameter was specified containing an email address that could be resolved to a user ID -> include user specific fields
  270. $query .= " FROM $tableRefs LEFT JOIN $tableUserData ON serial = record_id AND user_id = " . quote_smart($userID); // add FROM clause (including the 'LEFT JOIN...' part); '$tableRefs' and '$tableUserData' are defined in 'db.inc.php'
  271. else
  272. $query .= " FROM $tableRefs"; // add FROM clause
  273. if (!empty($searchArray))
  274. {
  275. // Build WHERE clause:
  276. $query .= " WHERE";
  277. appendToWhereClause($searchArray); // function 'appendToWhereClause()' is defined in 'include.inc.php'
  278. }
  279. // Build ORDER BY clause:
  280. $query .= " ORDER BY serial";
  281. // --------------------------------------------------------------------
  282. // Build the correct query URL:
  283. // (we skip unnecessary parameters here since 'search.php' will use it's default values for them)
  284. $queryParametersArray = array("sqlQuery" => $query,
  285. "formType" => "sqlSearch",
  286. // "submit" => $displayType, // this parameter is set automatically by function 'generateURL()' for the export formats 'SRW_DC XML' & 'SRW_MODS XML'
  287. "showLinks" => $showLinks,
  288. // "exportType" => $exportType, // this parameter is set automatically by function 'generateURL()' if the export format name contains "XML"
  289. "exportStylesheet" => $exportStylesheet
  290. );
  291. // call 'search.php' with the correct query URL in order to display record details:
  292. $queryURL = generateURL("search.php", $exportFormat, $queryParametersArray, false, $showRows, $rowOffset); // function 'generateURL()' is defined in 'include.inc.php'
  293. header("Location: $queryURL");
  294. }
  295. // -------------------------------------------------------------------------------------------------------------------
  296. // Return a diagnostic error message:
  297. function returnDiagnostic($diagCode, $diagDetails)
  298. {
  299. global $exportContentType;
  300. global $contentTypeCharset; // '$contentTypeCharset' is defined in 'ini.inc.php'
  301. global $exportStylesheet;
  302. // use an appropriate default stylesheet:
  303. if ($exportStylesheet == "DEFAULT")
  304. $exportStylesheet = ""; // TODO: create a stylesheet ('diag2html.xsl') that's appropriate for SRW diagnostics
  305. // Set the appropriate mimetype & set the character encoding to the one given in '$contentTypeCharset':
  306. setHeaderContentType($exportContentType, $contentTypeCharset); // function 'setHeaderContentType()' is defined in 'include.inc.php'
  307. // Return SRW diagnostics (i.e. SRW error information) wrapped into SRW XML ('searchRetrieveResponse'):
  308. echo srwDiagnostics($diagCode, $diagDetails, $exportStylesheet); // function 'srwDiagnostics()' is defined in 'srwxml.inc.php'
  309. }
  310. // -------------------------------------------------------------------------------------------------------------------
  311. ?>