Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
82.14% covered (warning)
82.14%
46 / 56
66.67% covered (warning)
66.67%
6 / 9
CRAP
0.00% covered (danger)
0.00%
0 / 1
Jetpack_Sitemap_Buffer
86.79% covered (warning)
86.79%
46 / 53
66.67% covered (warning)
66.67%
6 / 9
22.02
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
1
 get_root_element
n/a
0 / 0
n/a
0 / 0
0
 append
81.82% covered (warning)
81.82%
9 / 11
0.00% covered (danger)
0.00%
0 / 1
5.15
 contents
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 get_document
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 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%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 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
 array_to_xml_string
82.61% covered (warning)
82.61%
19 / 23
0.00% covered (danger)
0.00%
0 / 1
7.26
1<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName
2/**
3 * Sitemaps (per the protocol) are essentially lists of XML fragments;
4 * lists which are subject to size constraints. The Jetpack_Sitemap_Buffer
5 * class abstracts the details of constructing these lists while
6 * maintaining the constraints.
7 *
8 * @since 4.8.0
9 * @package automattic/jetpack
10 */
11
12if ( ! defined( 'ABSPATH' ) ) {
13    exit( 0 );
14}
15
16require_once __DIR__ . '/sitemap-stylist.php';
17
18/**
19 * A buffer for constructing sitemap xml files.
20 *
21 * Models a list of strings such that
22 *
23 * 1. the list must have a bounded number of entries,
24 * 2. the concatenation of the strings must have bounded
25 *      length (including some header and footer strings), and
26 * 3. each item has a timestamp, and we need to keep track
27 *      of the most recent timestamp of the items in the list.
28 *
29 * @since 4.8.0
30 */
31abstract class Jetpack_Sitemap_Buffer {
32
33    /**
34     * Largest number of items the buffer can hold.
35     *
36     * @access protected
37     * @since 4.8.0
38     * @var int $item_capacity The item capacity.
39     */
40    protected $item_capacity;
41
42    /**
43     * Largest number of bytes the buffer can hold.
44     *
45     * @access protected
46     * @since 4.8.0
47     * @var int $byte_capacity The byte capacity.
48     */
49    protected $byte_capacity;
50
51    /**
52     * Flag which detects when the buffer is full.
53     *
54     * @access protected
55     * @since 4.8.0
56     * @var bool $is_full_flag The flag value. This flag is set to false on construction and only flipped to true if we've tried to add something and failed.
57     */
58    protected $is_full_flag;
59
60    /**
61     * Flag which detects when the buffer is empty.
62     *
63     * @access protected
64     * @since 4.8.0
65     * @var bool $is_empty_flag The flag value. This flag is set to true on construction and only flipped to false if we've tried to add something and succeeded.
66     */
67    protected $is_empty_flag;
68
69    /**
70     * The most recent timestamp seen by the buffer.
71     *
72     * @access protected
73     * @since 4.8.0
74     * @var string $timestamp Must be in 'YYYY-MM-DD hh:mm:ss' format.
75     */
76    protected $timestamp;
77
78    /**
79     * The DOM document object that is currently being used to construct the XML doc.
80     *
81     * @access protected
82     * @since 5.3.0
83     * @var DOMDocument $doc
84     */
85    protected $doc = null;
86
87    /**
88     * The root DOM element object that holds everything inside. Do not use directly, call
89     * the get_root_element getter method instead.
90     *
91     * @access protected
92     * @since 5.3.0
93     * @var DOMElement $doc
94     */
95    protected $root = null;
96
97    /**
98     * Helper class to construct sitemap paths.
99     *
100     * @since 5.3.0
101     * @protected
102     * @var Jetpack_Sitemap_Finder
103     */
104    protected $finder;
105
106    /**
107     * Construct a new Jetpack_Sitemap_Buffer.
108     *
109     * @since 4.8.0
110     *
111     * @param int    $item_limit The maximum size of the buffer in items.
112     * @param int    $byte_limit The maximum size of the buffer in bytes.
113     * @param string $time The initial datetime of the buffer. Must be in 'YYYY-MM-DD hh:mm:ss' format.
114     */
115    public function __construct( $item_limit, $byte_limit, $time ) {
116        $this->is_full_flag = false;
117        $this->timestamp    = $time;
118
119        $this->finder                  = new Jetpack_Sitemap_Finder();
120        $this->doc                     = new DOMDocument( '1.0', 'UTF-8' );
121        $this->doc->formatOutput       = true;
122        $this->doc->preserveWhiteSpace = false;
123
124        $this->item_capacity = max( 1, (int) $item_limit );
125        $this->byte_capacity = max( 1, (int) $byte_limit ) - strlen( $this->doc->saveXML() );
126    }
127
128    /**
129     * Returns a DOM element that contains all sitemap elements.
130     *
131     * @access protected
132     * @since 5.3.0
133     * @return DOMElement $root
134     */
135    abstract protected function get_root_element();
136
137    /**
138     * Append an item to the buffer, if there is room for it,
139     * and set is_empty_flag to false. If there is no room,
140     * we set is_full_flag to true. If $item is null,
141     * don't do anything and report success.
142     *
143     * @since 5.3.0
144     *
145     * @param array $array The item to be added.
146     *
147     * @return bool True if the append succeeded, False if not.
148     */
149    public function append( $array ) {
150        if ( $array === null ) {
151            return true;
152        }
153
154        if ( $this->is_full_flag ) {
155            return false;
156        }
157
158        if ( 0 >= $this->item_capacity || 0 >= $this->byte_capacity ) {
159            $this->is_full_flag = true;
160            return false;
161        } else {
162            $this->item_capacity -= 1;
163            $added_element        = $this->array_to_xml_string( $array, $this->get_root_element(), $this->doc );
164
165            $this->byte_capacity -= strlen( $this->doc->saveXML( $added_element ) );
166
167            return true;
168        }
169    }
170
171    /**
172     * Retrieve the contents of the buffer.
173     *
174     * @since 4.8.0
175     *
176     * @return string The contents of the buffer (with the footer included).
177     */
178    public function contents() {
179        if ( $this->is_empty() ) {
180            // The sitemap should have at least the root element added to the DOM.
181            $this->get_root_element();
182        }
183        return $this->doc->saveXML();
184    }
185
186    /**
187     * Retrieve the document object.
188     *
189     * @since 5.3.0
190     * @return DOMDocument $doc
191     */
192    public function get_document() {
193        return $this->doc;
194    }
195
196    /**
197     * Detect whether the buffer is full.
198     *
199     * @since 4.8.0
200     *
201     * @return bool True if the buffer is full, false otherwise.
202     */
203    public function is_full() {
204        return $this->is_full_flag;
205    }
206
207    /**
208     * Detect whether the buffer is empty.
209     *
210     * @since 4.8.0
211     *
212     * @return bool True if the buffer is empty, false otherwise.
213     */
214    public function is_empty() {
215        return (
216            ! isset( $this->root )
217            || ! $this->root->hasChildNodes()
218        );
219    }
220
221    /**
222     * Update the timestamp of the buffer.
223     *
224     * @since 4.8.0
225     *
226     * @param string $new_time A datetime string in 'YYYY-MM-DD hh:mm:ss' format.
227     */
228    public function view_time( $new_time ) {
229        $this->timestamp = max( $this->timestamp, $new_time );
230    }
231
232    /**
233     * Retrieve the timestamp of the buffer.
234     *
235     * @since 4.8.0
236     *
237     * @return string A datetime string in 'YYYY-MM-DD hh:mm:ss' format.
238     */
239    public function last_modified() {
240        return $this->timestamp;
241    }
242
243    /**
244     * Render an associative array as an XML string. This is needed because
245     * SimpleXMLElement only handles valid XML, but we sometimes want to
246     * pass around (possibly invalid) fragments. Note that 'null' values make
247     * a tag self-closing; this is only sometimes correct (depending on the
248     * version of HTML/XML); see the list of 'void tags'.
249     *
250     * Example:
251     *
252     * array(
253     *   'html' => array(                    |<html xmlns="foo">
254     *     'head' => array(                  |  <head>
255     *       'title' => 'Woo!',              |    <title>Woo!</title>
256     *     ),                                |  </head>
257     *     'body' => array(             ==>  |  <body>
258     *       'h2' => 'Some thing',           |    <h2>Some thing</h2>
259     *       'p'  => 'it's all up ons',      |    <p>it's all up ons</p>
260     *       'br' => null,                   |    <br />
261     *     ),                                |  </body>
262     *   ),                                  |</html>
263     * )
264     *
265     * @access protected
266     * @since 3.9.0
267     * @since 4.8.0 Rename, add $depth parameter, and change return type.
268     * @since 5.3.0 Refactor, remove $depth parameter, add $parent and $root, make access protected.
269     *
270     * @param array       $array A recursive associative array of tag/child relationships.
271     * @param DOMElement  $parent (optional) an element to which new children should be added.
272     * @param DOMDocument $root (optional) the parent document.
273     *
274     * @return string|DOMDocument The rendered XML string or an object if root element is specified.
275     */
276    protected function array_to_xml_string( $array, $parent = null, $root = null ) {
277        $element       = null;
278        $return_string = false;
279
280        if ( null === $parent ) {
281            $return_string = true;
282            $root          = new DOMDocument();
283            $parent        = $root;
284        }
285
286        if ( is_array( $array ) ) {
287
288            foreach ( $array as $key => $value ) {
289                $element = $root->createElement( $key );
290                $parent->appendChild( $element );
291
292                if ( is_array( $value ) ) {
293                    foreach ( $value as $child_key => $child_value ) {
294                        $child = $root->createElement( $child_key );
295                        $element->appendChild( $child );
296                        $child->appendChild( self::array_to_xml_string( $child_value, $child, $root ) );
297                    }
298                } else {
299                    $element->appendChild(
300                        $root->createTextNode( $value )
301                    );
302                }
303            }
304        } else {
305            $element = $root->createTextNode( $array );
306            $parent->appendChild( $element );
307        }
308
309        if ( $return_string ) {
310            return $root->saveHTML();
311        } else {
312            return $element;
313        }
314    }
315}