Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
89.74% covered (warning)
89.74%
70 / 78
72.73% covered (warning)
72.73%
8 / 11
CRAP
0.00% covered (danger)
0.00%
0 / 1
Jetpack_Sitemap_Buffer_XMLWriter
93.33% covered (success)
93.33%
70 / 75
72.73% covered (warning)
72.73%
8 / 11
25.19
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
16 / 16
100.00% covered (success)
100.00%
1 / 1
1
 initialize_buffer
n/a
0 / 0
n/a
0 / 0
0
 start_root
n/a
0 / 0
n/a
0 / 0
0
 ensure_root_started
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
 finalize_writer_output
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
2
 append
84.21% covered (warning)
84.21%
16 / 19
0.00% covered (danger)
0.00%
0 / 1
8.25
 append_item
n/a
0 / 0
n/a
0 / 0
0
 array_to_xml
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
3
 contents
83.33% covered (warning)
83.33%
5 / 6
0.00% covered (danger)
0.00%
0 / 1
3.04
 is_full
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 is_empty
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 view_time
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 last_modified
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_document
88.89% covered (warning)
88.89%
8 / 9
0.00% covered (danger)
0.00%
0 / 1
2.01
1<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName
2/**
3 * XMLWriter implementation of the sitemap buffer.
4 *
5 * @since 14.6
6 * @package automattic/jetpack
7 */
8
9if ( ! defined( 'ABSPATH' ) ) {
10    exit( 0 );
11}
12
13require_once __DIR__ . '/sitemap-stylist.php';
14
15/**
16 * A buffer for constructing sitemap xml files using XMLWriter.
17 *
18 * @since 14.6
19 */
20abstract class Jetpack_Sitemap_Buffer_XMLWriter {
21
22    /**
23     * Largest number of items the buffer can hold.
24     *
25     * @access protected
26     * @since 14.6
27     * @var int $item_capacity The item capacity.
28     */
29    protected $item_capacity;
30
31    /**
32     * Largest number of bytes the buffer can hold.
33     *
34     * @access protected
35     * @since 14.6
36     * @var int $byte_capacity The byte capacity.
37     */
38    protected $byte_capacity;
39
40    /**
41     * Flag which detects when the buffer is full.
42     *
43     * @access protected
44     * @since 14.6
45     * @var bool $is_full_flag The flag value.
46     */
47    protected $is_full_flag;
48
49    /**
50     * Flag which detects when the buffer is empty.
51     * Set true on construction and flipped to false only after a successful append.
52     *
53     * @since 15.0
54     * @var bool
55     */
56    protected $is_empty_flag = true;
57
58    /**
59     * The most recent timestamp seen by the buffer.
60     *
61     * @access protected
62     * @since 14.6
63     * @var string $timestamp Must be in 'YYYY-MM-DD hh:mm:ss' format.
64     */
65    protected $timestamp;
66
67    /**
68     * The XMLWriter instance used to construct the XML.
69     *
70     * @access protected
71     * @since 14.6
72     * @var XMLWriter $writer
73     */
74    protected $writer;
75
76    /**
77     * Helper class to construct sitemap paths.
78     *
79     * @since 14.6
80     * @protected
81     * @var Jetpack_Sitemap_Finder
82     */
83    protected $finder;
84
85    /**
86     * The XML content chunks collected from XMLWriter.
87     *
88     * Collect chunks and join once at the end to reduce string reallocations
89     * and improve performance on large sitemaps.
90     *
91     * @access protected
92     * @since 15.0
93     * @var array $chunks
94     */
95    protected $chunks = array();
96
97    /**
98     * Tracks whether the root element has been started.
99     *
100     * @since 15.0
101     * @var bool
102     */
103    protected $root_started = false;
104
105    /**
106     * Mirror DOMDocument built on-demand for jetpack_print_sitemap compatibility.
107     *
108     * @since 15.0
109     * @var DOMDocument|null
110     */
111    protected $dom_document = null;
112
113    /**
114     * Tracks whether XMLWriter document has been finalized (closed and flushed).
115     *
116     * @since 15.0
117     * @var bool
118     */
119    protected $is_finalized = false;
120
121    /**
122     * Construct a new Jetpack_Sitemap_Buffer_XMLWriter.
123     *
124     * @since 14.6
125     *
126     * @param int    $item_limit The maximum size of the buffer in items.
127     * @param int    $byte_limit The maximum size of the buffer in bytes.
128     * @param string $time The initial datetime of the buffer. Must be in 'YYYY-MM-DD hh:mm:ss' format.
129     */
130    public function __construct( $item_limit, $byte_limit, $time ) {
131        $this->is_full_flag  = false;
132        $this->is_empty_flag = true;
133        $this->timestamp     = $time;
134        $this->finder        = new Jetpack_Sitemap_Finder();
135
136        $this->writer = new XMLWriter();
137        $this->writer->openMemory();
138        $this->writer->setIndent( true );
139        $this->writer->startDocument( '1.0', 'UTF-8' );
140
141        $this->item_capacity = max( 1, (int) $item_limit );
142        $this->byte_capacity = max( 1, (int) $byte_limit );
143
144        // Capture and account the XML declaration bytes to mirror DOM behavior.
145        $declaration          = $this->writer->outputMemory( true );
146        $this->chunks[]       = $declaration;
147        $this->byte_capacity -= strlen( $declaration );
148
149        // Allow subclasses to write comments and processing instructions only.
150        $this->initialize_buffer();
151
152        // Capture pre-root bytes (comments/PI). Do not subtract from capacity.
153        $pre_root_output = $this->writer->outputMemory( true );
154        $this->chunks[]  = $pre_root_output;
155    }
156
157    /**
158     * Initialize the buffer with any required headers or setup.
159     * This should be implemented by child classes.
160     *
161     * @access protected
162     * @since 14.6
163     */
164    abstract protected function initialize_buffer();
165
166    /**
167     * Start the root element (e.g., urlset or sitemapindex) and write its attributes.
168     * Implemented by subclasses.
169     *
170     * @since 15.0
171     * @access protected
172     * @return void
173     */
174    abstract protected function start_root();
175
176    /**
177     * Ensure the root element has been started and account its bytes once.
178     *
179     * @since 15.0
180     * @access protected
181     * @return void
182     */
183    protected function ensure_root_started() {
184        if ( $this->root_started ) {
185            return;
186        }
187        $this->start_root();
188        $root_chunk           = $this->writer->outputMemory( true );
189        $this->chunks[]       = $root_chunk;
190        $this->byte_capacity -= strlen( $root_chunk );
191        $this->root_started   = true;
192    }
193
194    /**
195     * Finalize writer output once by closing the root and document and flushing.
196     *
197     * @since 15.0
198     * @access protected
199     * @return void
200     */
201    protected function finalize_writer_output() {
202        if ( $this->is_finalized ) {
203            return;
204        }
205        $this->ensure_root_started();
206        $this->writer->endElement(); // End root element (urlset/sitemapindex)
207        $this->writer->endDocument();
208        $final_content      = $this->writer->outputMemory( true );
209        $this->chunks[]     = $final_content;
210        $this->is_finalized = true;
211    }
212
213    /**
214     * Append an item to the buffer.
215     *
216     * @since 14.6
217     *
218     * @param array $array The item to be added.
219     * @return bool True if the append succeeded, False if not.
220     */
221    public function append( $array ) {
222        if ( $array === null ) {
223            return true;
224        }
225
226        if ( $this->is_full_flag ) {
227            return false;
228        }
229
230        if ( 0 >= $this->item_capacity || 0 >= $this->byte_capacity ) {
231            $this->is_full_flag = true;
232            return false;
233        }
234
235        // Ensure root is started on first append and account its bytes.
236        $this->ensure_root_started();
237
238        // Attempt to render the item. Subclasses may decide to skip writing
239        // if the input structure is invalid for that sitemap type.
240        $this->append_item( $array );
241
242        // Capture only the bytes produced by this item.
243        $new_content = $this->writer->outputMemory( true );
244
245        // If nothing was written, treat as a no-op: keep the buffer "empty"
246        // and do not consume item/byte capacities.
247        if ( '' === $new_content ) {
248            return true;
249        }
250
251        // Persist newly written bytes and update capacities.
252        $this->chunks[]       = $new_content;
253        $this->item_capacity -= 1;
254        $this->byte_capacity -= strlen( $new_content );
255        $this->is_empty_flag  = false;
256
257        // Check both capacity limits.
258        if ( 0 >= $this->item_capacity || $this->byte_capacity <= 0 ) {
259            $this->is_full_flag = true;
260        }
261
262        return true;
263    }
264
265    /**
266     * Append a specific item to the buffer.
267     * This should be implemented by child classes.
268     *
269     * @access protected
270     * @since 14.6
271     * @param array $array The item to be added.
272     */
273    abstract protected function append_item( $array );
274
275    /**
276     * Recursively writes XML elements from an associative array.
277     *
278     * This method iterates through an array and writes XML elements using the XMLWriter instance.
279     * If a value in the array is itself an array, it calls itself recursively.
280     *
281     * @access protected
282     * @since 15.0
283     *
284     * @param array $data The array to convert to XML.
285     */
286    protected function array_to_xml( $data ) {
287        foreach ( (array) $data as $tag => $value ) {
288            if ( is_array( $value ) ) {
289                $this->writer->startElement( $tag );
290                $this->array_to_xml( $value );
291                $this->writer->endElement();
292            } else {
293                // Write raw text; XMLWriter will escape XML-reserved chars, matching DOMDocument behavior.
294                $this->writer->writeElement( $tag, (string) $value );
295            }
296        }
297    }
298
299    /**
300     * Retrieve the contents of the buffer.
301     *
302     * @since 14.6
303     * @return string The contents of the buffer.
304     */
305    public function contents() {
306        $this->finalize_writer_output();
307        if ( $this->dom_document instanceof DOMDocument ) {
308            return $this->dom_document->saveXML();
309        }
310        if ( empty( $this->chunks ) ) {
311            // If buffer is empty, return a minimal valid XML structure
312            return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\"></urlset>";
313        }
314        return implode( '', $this->chunks );
315    }
316
317    /**
318     * Detect whether the buffer is full.
319     *
320     * @since 14.6
321     * @return bool True if the buffer is full, false otherwise.
322     */
323    public function is_full() {
324        return $this->is_full_flag;
325    }
326
327    /**
328     * Detect whether the buffer is empty.
329     *
330     * @since 14.6
331     * @return bool True if the buffer is empty, false otherwise.
332     */
333    public function is_empty() {
334        return $this->is_empty_flag;
335    }
336
337    /**
338     * Update the timestamp of the buffer.
339     *
340     * @since 14.6
341     * @param string $new_time A datetime string in 'YYYY-MM-DD hh:mm:ss' format.
342     */
343    public function view_time( $new_time ) {
344        $this->timestamp = max( $this->timestamp, $new_time );
345    }
346
347    /**
348     * Retrieve the timestamp of the buffer.
349     *
350     * @since 14.6
351     * @return string A datetime string in 'YYYY-MM-DD hh:mm:ss' format.
352     */
353    public function last_modified() {
354        return $this->timestamp;
355    }
356
357    /**
358     * Compatibility method for the old DOMDocument implementation.
359     * This is only here to satisfy the jetpack_print_sitemap filter.
360     *
361     * @since 14.6
362     * @return DOMDocument DOM representation of the current sitemap contents.
363     */
364    public function get_document() {
365        if ( $this->dom_document instanceof DOMDocument ) {
366            return $this->dom_document;
367        }
368
369        $this->finalize_writer_output();
370
371        $dom                     = new DOMDocument( '1.0', 'UTF-8' );
372        $dom->formatOutput       = true; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
373        $dom->preserveWhiteSpace = false; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
374        // Load current XML content into DOM for compatibility with filters.
375        @$dom->loadXML( implode( '', $this->chunks ) ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- Avoid fatal on unexpected content
376
377        $this->dom_document = $dom;
378        return $this->dom_document;
379    }
380}