forked from humanmade/WordPress-Importer
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathclass-wxr-transform.php
436 lines (364 loc) · 12.9 KB
/
class-wxr-transform.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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
<?php
/**
* Transform from WXR 1.0, 1.1 or 1.2 instance into a proposed WXR 1.3 instance
*
* There is a very simple XSLT transform that accomplishes this; however,
* since this importer is intended to be a 'true' streaming parser, that XSLT
* transform is not a viable solution, since PHP's implementation of XSLT
* must load the source document completely into memory (as either a DOMDocument
* or a SimpleXML).
*
* The XSLT version of this transform is available at https://github.com/pbiron/wxr/1.3-proposed/transforms.
* It is available there in 4 different versions: XSLT 3.0 (which should be considered
* the version this class implements), XSLT 2.0 and 2 different implementations for
* XSLT 1.0.
*
* And to boot, the XSLT 3.0 version of the transform is even guaranteed-streamable
* as specified in https://www.w3.org/TR/xslt-30/#dt-guaranteed-streamable.
*
* Unfortunately, PHP's XSLTProcessor class can only handle XSLT 1.0 transforms.
* Given that XSLT 2.0 is 10 years old, there is little chance that PHP will support
* XSLT 3.0 any time soon (if ever) :-( Hense, the need for this class.
*
* WXR_Importer_Transform_WXR::transform_wxr() is intended to be called
* from within a function hooked to `admin_action_wxr-import-upload'...so that
* WXR_Importer can seemlessly handle "native" WXR 1.3 instances as well as
* old WXR 1.0, 1.1 or 1.2 instances.
*
* @author pbiron
*/
class Transform_WXR {
/**
* The WXR namespace URI
* @var string
*/
const WXR_NAMESPACE_URI = 'http://wordpress.org/export/';
/**
* The prefix to use for elements/attributes in the WXR namespace
* @var string
*/
const WXR_PREFIX = 'wxr';
/**
* The version of WXR we transform into
* @var string
*/
const WXR_VERSION = '1.3';
/**
* Original filename
* @var unknown
*/
protected $org_filename;
/**
* Name of temporary file.
* @var string
*/
protected $tempnam ;
/**
* Check whether a namespaceURI is one that has been used for WXR
*
* @param string $namespaceURI The namespaceURI to check.
* @param bool $accept_excerpt_ns Whether to accept the WXR 'excerpt' namespaceURIs.
* @return bool
*/
protected function is_wxr_namespaceURI( $namespaceURI, $accept_excerpt_ns = false ) {
$regex = '#^' . self::WXR_NAMESPACE_URI . '\d+\.\d+/';
if ( ! preg_match( "{$regex}#", $namespaceURI ) ) {
return false;
}
if ( ! $accept_excerpt_ns && preg_match( "{$regex}excerpt/$#", $namespaceURI ) ) {
return false;
}
return true;
}
/**
* Get a stream reader for the file.
*
* @param string $file Path to the XML file.
* @return XMLReader|WP_Error Reader instance on success, error otherwise.
*/
protected function get_reader( $file ) {
// Avoid loading external entities for security
$old_value = null;
if ( function_exists( 'libxml_disable_entity_loader' ) ) {
// $old_value = libxml_disable_entity_loader( true );
}
$reader = new XMLReader();
$status = $reader->open( $file );
if ( ! is_null( $old_value ) ) {
// libxml_disable_entity_loader( $old_value );
}
if ( ! $status ) {
return new WP_Error( 'wxr_importer.cannot_parse', __( 'Could not open the file for parsing', 'wordpress-importer' ) );
}
return $reader;
}
/**
* Get a stream writer for output of the transform file.
*
* @param string $file Path to the XML file.
* @return XMLReader|WP_Error Writer instance on success, error otherwise.
*/
function get_writer( $file ) {
$writer = new XMLWriter();
$this->tempnam = tempnam( dirname( $file ), 'transform' );
$status = $writer->openUri( $this->tempnam );
if ( ! $status ) {
return new WP_Error( 'wxr_importer.cannot_transform', __( 'Could not open the file for writing', 'wordpress-importer' ) );
}
$writer->setIndent( true );
$writer->setIndentString( "\t" );
return $writer;
}
/**
*
* @param XMLReader $reader
* @param XMLWriter $writer
* @param array $parent
* @return boolean
*/
function startElement( $reader, $writer, $parent ) {
if ( $this->is_wxr_namespaceURI( $reader->namespaceURI, true ) ) {
// element is from one of the old WXR namespaces
if ( in_array( $reader->localName, array( 'wxr_version', 'base_blog_url' ) ) ) {
// skip the old wp:wxr_version & base_blog_url elements
$reader->next();
return true;
}
elseif ( 'encoded' === $reader->localName ) {
// rewrite <excerpt:encoded> to RSS standard <description>
$writer->startElement( 'description' );
return true;
}
$localName = $this->map_localName( $reader, $parent );
$writer->startElementNs( self::WXR_PREFIX, $localName, null );
}
elseif ( '' !== $reader->namespaceURI ) {
// element is from a "foreign" namespace, e.g., dublin core, rss_content
// or a plugin-specific namespace...just copy the start tag unchanged
$writer->startElementNs( $reader->prefix, $reader->localName, null );
}
else {
// element is from the empty namespace, i.e., standard RSS
if ( isset( $parent['localName'] ) &&
'' === $parent['namespaceURI'] && 'item' === $parent['localName'] &&
'description' === $reader->localName ) {
// skip item/description element
$reader->next();
return true;
}
$writer->startElement( $reader->localName );
if ( 'generator' === $reader->localName ) {
$wp_version = $reader->readString();
$wp_version = substr( $wp_version, stripos( $wp_version, '?v=' ) + 3 );
$writer->writeAttributeNS( 'wxr', 'wp_version', null, $wp_version );
$writer->endElement();
$reader->next();
}
if ( 'rss' === $reader->localName && 0 === $reader->depth ) {
if ( $reader->moveToAttributeNS( 'version', self::WXR_NAMESPACE_URI ) ) {
// file is already in the WXR 1.3 (or later) markup, no need to transform
return false;
}
// passing the WXR namespaceURI here will cause XMLWriter to also
// generate a namespace decl for it. After this, we always pass
// null for our namespace; otherwise, XMLWriter will generate additional
// namespace decls for it...which, while perfectly fine from a
// namespace-aware XML perspective, it results in instances that are
// much larger than they need to be.
// @link https://bugs.php.net/bug.php?id=74491
$writer->writeAttributeNS( self::WXR_PREFIX, 'version', self::WXR_NAMESPACE_URI, '1.3' );
}
}
// save whether we are currently processing an RSS category element
// so that we can rewrite @nicename
$category = '' === $reader->namespaceURI && $reader->localName;
if ( $reader->hasAttributes ) {
$this->transformAttributes( $reader, $writer, $category );
}
if ( $reader->isEmptyElement ) {
$writer->endElement();
}
return true;
}
/**
*
* @param XMLReader $reader
* @param XMLWriter $writer
* @param bool $is_rss_category
*/
function transformAttributes( $reader, $writer, $is_rss_category ) {
// save whether we are currently processing an RSS category element
// so that we can rewrite @nicename
$is_rss_category = '' === $reader->namespaceURI && $reader->localName;
while ( $reader->moveToNextAttribute() ) {
if ( '' === $reader->namespaceURI ) {
if ( $is_rss_category && 'nicename' === $reader->name ) {
// rewrite category/@nicename to category/@wxr:slug
$writer->writeAttributeNs( self::WXR_PREFIX, 'slug', null, $reader->value );
}
else {
$writer->writeAttribute( $reader->name, $reader->value );
}
}
elseif ( 'http://www.w3.org/2000/xmlns/' === $reader->namespaceURI ) {
// stupid XMLReader treats namespace decls as attributes :-(
if ( $this->is_wxr_namespaceURI( $reader->value, true ) ) {
// strip the old WXR namespace decl
continue;
}
// because of what I consider a bug in XMLWriter,
// if you write these namespace decl "attributes" via
// XMLWriter::writeAttributeNs() then it generates an
// illegal xmlns:xmlns='http://www.w3.org/2000/xmlns/'
$writer->writeAttribute( $reader->name, $reader->value );
}
else {
// namespace-qualified attribute
if ( $reader->lookupNamespace( $reader->prefix ) ) {
$writer->writeAttributeNs( $reader->prefix, $reader->localName, null, $reader->value );
}
else {
$writer->writeAttributeNs( $reader->prefix, $reader->localName, $reader->namespaceURI, $reader->value );
}
}
}
$reader->moveToElement();
}
/**
* Transform a WXR 1.0, 1.1 or 1.2 instance into the proposed 1.3 markup
*
* @param string $file ??
* @return boolean|WP_Error true if transformation performed, false if no transformation necessary,
* WP_Error on error
*/
function transform( $file ) {
$this->org_filename = $file;
$reader = $this->get_reader( $file );
if ( is_wp_error( $reader ) ) {
return $reader;
}
$writer = $this->get_writer( $file );
if ( is_wp_error( $writer ) ) {
return $writer;
}
// @todo XMLReader::read() never returns XMLReader::XML_DECLARATION
// so we just have to "guess" and hardcode the xmldecl
// I don't think it really matters because XMLReader will do any necessary
// decoding
$writer->startDocument( '1.0', 'UTF-8' );
$ancestors = array();
while ( $reader->read() ) {
switch ( $reader->nodeType ) {
case XMLReader::ELEMENT:
if ( ! $this->startElement( $reader, $writer, count( $ancestors ) > 0 ? $ancestors[0] : null ) ) {
$this->cleanup( $reader, $writer, false );
return false;
}
array_unshift( $ancestors,
array(
'namespaceURI' => $reader->namespaceURI,
'localName' => $reader->localName,
)
);
break;
case XMLReader::CDATA:
case XMLReader::TEXT:
// outputing CDATA sections when not necessary needlessly increases file size
$writer->text( $reader->value );
break;
case XMLReader::END_ELEMENT:
if ( $this->is_wxr_namespaceURI( $reader->namespaceURI, true ) ) {
if ( in_array( $reader->localName, array( 'tag', 'category' ) ) ) {
// add the appropriate <wxr:taxonomy> before closing the <wxr:term>
$writer->startElementNs( self::WXR_PREFIX, 'taxonomy', null );
$writer->text( 'category' === $reader->localName ? 'category' : 'post_tag' );
$writer->endElement();
}
}
$writer->endElement();
array_shift( $ancestors );
break;
case XMLReader::COMMENT:
$writer->writeComment( $reader->value );
break;
case XMLReader::PI:
// the standard exporter doesn't generate any PIs and it is unlikely a plugin
// will either, but just in case...
$writer->writePI( $reader->localName, $reader->value );
break;
}
}
$this->cleanup( $reader, $writer, true );
return true;
}
/**
* This implements the <xsl:variable> statement in the template with
* @match='*[starts-with( namespace-uri(), "http://wordpress.org/export/" )]'>
* in the XSLT transforms this class mimics.
*
* @param XMLReader $reader
* @param array $parent
* @return string
*/
function map_localName( $reader, $parent ) {
// first, start with the simple renames
if ( in_array( $reader->localName, array( 'tag', 'category' ) ) ) {
return 'term';
}
elseif ( 'author' === $reader->localName ) {
return 'user';
}
elseif ( in_array( $reader->localName, array( 'termmeta', 'postmeta', 'commentmeta' ) ) ) {
return 'meta';
}
elseif ( 'category_nicename' === $reader->localName ) {
return 'slug';
}
// // even tho this keeps the current local-name(), we have to do it here
// // rather than in <xsl:otherwise/> or else it would get handled by
// // the "strip a leading" <xsl:when/>
// if ( 'comment_status' === $reader->localName ) {
// return $reader->localName;
// }
// store the location of the 1st '_' character. We need it several times below
// and this saves up having to call strpos() multiple times
$_underscore = strpos( $reader->localName, '_' ) + 1;
// strip leading string before "_" in SOME localName's
if ( ( in_array(
substr ( $reader->localName, 0, $_underscore ),
array( 'author_', 'post_', 'meta_', 'comment_', 'base_' ) ) &&
'comment_status' !== $reader->localName ) ||
( $this->is_wxr_namespaceURI( $parent['namespaceURI'] ) &&
in_array( $parent['localName'], array( 'tag', 'category', 'term' ) ) ) ) {
return substr( $reader->localName, $_underscore );
}
// localName is unchanged
return $reader->localName;
}
/**
* Cleanup at the end of the transform
*
* If $success is true, then rename the temporary file to the original file;
* If $success is false, then unlink the temporary file and the original file
* in tact.
*
* @param XMLReader $reader
* @param XMLWriter $writer
* @param bool $success
* @param string $file
*/
function cleanup( $reader, &$writer, $success ) {
$reader->close();
$writer->endDocument();
// set $writer to null so that it closes the file...otherwise
// the rename() will fail! The $writer parameter to this method must be
// declared 'by-reference' for this to work.
$writer = null;
if ( $success ) {
rename( $this->tempnam, $this->org_filename );
}
else {
unlink( $this->tempnam );
}
}
}