-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathRecordXmlFormatter.php
363 lines (336 loc) · 10.2 KB
/
RecordXmlFormatter.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
<?php
/**
* OAI-PMH XML Record Formatter
*
* PHP version 7
*
* Copyright (c) Demian Katz 2016.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program 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 General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category VuFind
* @package Harvest_Tools
* @author Demian Katz <[email protected]>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org/wiki/indexing:oai-pmh Wiki
*/
namespace VuFindHarvest\OaiPmh;
/**
* OAI-PMH XML Record Formatter
*
* @category VuFind
* @package Harvest_Tools
* @author Demian Katz <[email protected]>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org/wiki/indexing:oai-pmh Wiki
*/
class RecordXmlFormatter
{
/**
* Search strings for global search-and-replace.
*
* @var array
*/
protected $globalSearch = [];
/**
* Replacement strings for global search-and-replace.
*
* @var array
*/
protected $globalReplace = [];
/**
* Tag to use for injecting IDs into XML (false for none)
*
* @var string|bool
*/
protected $injectId = false;
/**
* Tag to use for injecting setSpecs (false for none)
*
* @var string|bool
*/
protected $injectSetSpec = false;
/**
* Tag to use for injecting set names (false for none)
*
* @var string|bool
*/
protected $injectSetName = false;
/**
* Tag to use for injecting datestamp (false for none)
*
* @var string|bool
*/
protected $injectDate = false;
/**
* List of header elements to copy into body
*
* @var array
*/
protected $injectHeaderElements = [];
/**
* Associative array of setSpec => setName
*
* @var array
*/
protected $setNames = [];
/**
* Constructor
*
* @param array $settings Configuration settings
*/
public function __construct($settings = [])
{
// Settings that may be mapped directly from $settings to class properties:
$mappableSettings = [
'globalSearch', 'globalReplace',
'injectId', 'injectDate', 'injectHeaderElements',
'injectSetName', 'injectSetSpec',
];
foreach ($mappableSettings as $current) {
if (isset($settings[$current])) {
$this->$current = $settings[$current];
}
}
// Where appropriate, normalize elements to array format:
$this->globalSearch = (array)$this->globalSearch;
$this->globalReplace = (array)$this->globalReplace;
$this->injectHeaderElements = (array)$this->injectHeaderElements;
}
/**
* Fix namespaces in the top tag of the XML document to compensate for bugs
* in the SimpleXML library.
*
* @param string $xml XML document to clean up
* @param array $ns Namespaces to check
* @param string $attr Attributes extracted from the <metadata> tag
*
* @return string
*/
protected function fixNamespaces($xml, $ns, $attr = '')
{
foreach ($ns as $key => $val) {
if (
!empty($key)
&& strstr($xml, $key . ':') && !strstr($xml, 'xmlns:' . $key)
&& !strstr($attr, 'xmlns:' . $key)
) {
$attr .= ' xmlns:' . $key . '="' . $val . '"';
}
}
if (!empty($attr)) {
$xml = preg_replace('/>/', ' ' . $attr . '>', $xml, 1);
}
return $xml;
}
/**
* Format a line of XML.
*
* @param string $tag Tag name
* @param string $value Content of tag
*
* @return string
*/
protected function createTag($tag, $value)
{
return "<{$tag}>" . htmlspecialchars($value) . "</{$tag}>";
}
/**
* Format the ID as an XML tag for inclusion in final record.
*
* @param string $id Record ID
*
* @return string
*/
protected function getIdAdditions($id)
{
return $this->injectId ? $this->createTag($this->injectId, $id) : '';
}
/**
* Format setSpec header element as XML tags for inclusion in final record.
*
* @param object $setSpec Header setSpec element (in SimpleXML format).
*
* @return string
*/
protected function getHeaderSetAdditions($setSpec)
{
$insert = '';
foreach ($setSpec as $current) {
$set = (string)$current;
if ($this->injectSetSpec) {
$insert .= $this->createTag($this->injectSetSpec, $set);
}
if ($this->injectSetName) {
$name = $this->setNames[$set] ?? $set;
$insert .= $this->createTag($this->injectSetName, $name);
}
}
return $insert;
}
/**
* Format header elements as XML tags for inclusion in final record.
*
* @param object $header Header element (in SimpleXML format).
*
* @return string
*/
protected function getHeaderAdditions($header)
{
$insert = '';
if ($this->injectDate) {
$insert .= $this
->createTag($this->injectDate, (string)$header->datestamp);
}
if (
isset($header->setSpec)
&& ($this->injectSetSpec || $this->injectSetName)
) {
$insert .= $this->getHeaderSetAdditions($header->setSpec);
}
if ($this->injectHeaderElements) {
foreach ($this->injectHeaderElements as $element) {
if (isset($header->$element)) {
$insert .= $header->$element->asXML();
}
}
}
return $insert;
}
/**
* Extract attributes from a higher-level tag that need to be inserted
* into the metadata record contained within the tag.
*
* @param string $raw The full outer XML
* @param string $tagName The name of the outermost tag in $raw
* @param string $record The metadata record with the outer <metadata> tag
* stripped off.
*
* @return array
*/
protected function extractHigherLevelAttributes(
string $raw,
string $tagName,
string $record
): array {
// remove all attributes from extractedNs that appear deeper in xml; this
// helps prevent fatal errors caused by the same namespace declaration
// appearing twice in a single tag.
$extractedNs = [];
preg_match('/^<' . $tagName . '([^\>]*)>/', $raw, $extractedNs);
$attributes = [];
preg_match_all(
'/(^| )([^"]*"?[^"]*"|[^\']*\'?[^\']*\')/',
$extractedNs[1],
$attributes
);
$extractedAttributes = [];
foreach ($attributes[0] as $attribute) {
$attribute = trim($attribute);
// if $attribute appears in xml, remove it:
if (!strstr($record, $attribute)) {
$extractedAttributes[] = $attribute;
}
}
return $extractedAttributes;
}
/**
* Perform global search and replace.
*
* @param string $xml XML to update.
*
* @return string
*/
protected function performGlobalReplace($xml)
{
return empty($this->globalSearch)
? $xml
: preg_replace($this->globalSearch, $this->globalReplace, $xml);
}
/**
* Save a record to disk.
*
* @param string $id ID of record to save.
* @param object $recordObj Record to save (in SimpleXML format).
*
* @return string
*/
public function format($id, $recordObj)
{
if (!isset($recordObj->metadata)) {
throw new \Exception('Unexpected missing record metadata.');
}
$raw = trim($recordObj->metadata->asXML());
// Extract the actual metadata from inside the <metadata></metadata> tags;
// there is probably a cleaner way to do this, but this simple method avoids
// the complexity of dealing with namespaces in SimpleXML.
//
// We should also apply global search and replace at this time, if
// applicable.
$record = $this->performGlobalReplace(
preg_replace('/(^<metadata[^\>]*>)|(<\/metadata>$)/m', '', $raw)
);
// Collect attributes (for proper namespace resolution):
$metadataAttributes = $this->extractHigherLevelAttributes(
$raw,
'metadata',
$record
);
$recordAttributes = $this->extractHigherLevelAttributes(
trim($recordObj->asXML()),
'record',
$record
);
$extraAttributes = implode(
' ',
array_unique(
array_merge($metadataAttributes, $recordAttributes)
)
);
// If we are supposed to inject any values, do so now inside the first
// tag of the file:
$insert = $this->getIdAdditions($id)
. $this->getHeaderAdditions($recordObj->header);
$xml = !empty($insert)
? preg_replace('/>/', '>' . $insert, $record, 1) : $record;
// Build the final record:
return trim(
$this->fixNamespaces(
$xml,
$recordObj->getDocNamespaces(),
$extraAttributes
)
);
}
/**
* Do we need access to set information?
*
* @return bool
*/
public function needsSetNames()
{
return $this->injectSetName;
}
/**
* Inject set name information.
*
* @param array $names Associative array of setSpec => setName
*
* @return void
*/
public function setSetNames($names)
{
$this->setNames = $names;
}
}