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.

396 lines
21 KiB

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