Completed
Push — branch-4.8 ( 1fcc02...bc9f13 )
by
unknown
84:03 queued 74:02
created

sitemaps.php ➔ jetpack_sitemap_uri()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 24
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 10
nc 3
nop 1
dl 0
loc 24
rs 8.9713
c 0
b 0
f 0
1
<?php
2
/**
3
 * Generate sitemap files in base XML as well as some namespace extensions.
4
 *
5
 * This module generates two different base sitemaps.
6
 *
7
 * 1. sitemap.xml
8
 *    The basic sitemap is updated regularly by wp-cron. It is stored in the
9
 *    database and retrieved when requested. This sitemap aims to include canonical
10
 *    URLs for all published content and abide by the sitemap spec. This is the root
11
 *    of a tree of sitemap and sitemap index xml files, depending on the number of URLs.
12
 *
13
 *    By default the sitemap contains published posts of type 'post' and 'page', as
14
 *    well as the home url. To include other post types use the 'jetpack_sitemap_post_types'
15
 *    filter.
16
 *
17
 * @link http://sitemaps.org/protocol.php Base sitemaps protocol.
18
 * @link https://support.google.com/webmasters/answer/178636 Image sitemap extension.
19
 * @link https://developers.google.com/webmasters/videosearch/sitemaps Video sitemap extension.
20
 *
21
 * 2. news-sitemap.xml
22
 *    The news sitemap is generated on the fly when requested. It does not aim for
23
 *    completeness, instead including at most 1000 of the most recent published posts
24
 *    from the previous 2 days, per the news-sitemap spec.
25
 *
26
 * @link http://www.google.com/support/webmasters/bin/answer.py?answer=74288 News sitemap extension.
27
 *
28
 * @package Jetpack
29
 * @since 3.9.0
30
 * @since 4.8.0 Remove 1000 post limit.
31
 * @author Automattic
32
 */
33
34
require_once dirname( __FILE__ ) . '/sitemap-constants.php';
35
require_once dirname( __FILE__ ) . '/sitemap-buffer.php';
36
require_once dirname( __FILE__ ) . '/sitemap-stylist.php';
37
require_once dirname( __FILE__ ) . '/sitemap-librarian.php';
38
require_once dirname( __FILE__ ) . '/sitemap-finder.php';
39
require_once dirname( __FILE__ ) . '/sitemap-builder.php';
40
41
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
42
	require_once dirname( __FILE__ ) . '/sitemap-logger.php';
43
}
44
45
/**
46
 * Governs the generation, storage, and serving of sitemaps.
47
 *
48
 * @since 4.8.0
49
 */
50
class Jetpack_Sitemap_Manager {
51
52
	/**
53
	 * @see Jetpack_Sitemap_Librarian
54
	 * @since 4.8.0
55
	 * @var Jetpack_Sitemap_Librarian $librarian Librarian object for storing and retrieving sitemap data.
56
	 */
57
	private $librarian;
58
59
	/**
60
	 * @see Jetpack_Sitemap_Logger
61
	 * @since 4.8.0
62
	 * @var Jetpack_Sitemap_Logger $logger Logger object for reporting debug messages.
63
	 */
64
	private $logger;
65
66
	/**
67
	 * @see Jetpack_Sitemap_Finder
68
	 * @since 4.8.0
69
	 * @var Jetpack_Sitemap_Finder $finder Finder object for dealing with sitemap URIs.
70
	 */
71
	private $finder;
72
73
	/**
74
	 * Construct a new Jetpack_Sitemap_Manager.
75
	 *
76
	 * @access public
77
	 * @since 4.8.0
78
	 */
79
	public function __construct() {
80
		$this->librarian = new Jetpack_Sitemap_Librarian();
81
		$this->finder = new Jetpack_Sitemap_Finder();
82
83
		if ( defined( 'WP_DEBUG' ) && ( true === WP_DEBUG ) ) {
84
			$this->logger = new Jetpack_Sitemap_Logger();
85
		}
86
87
		// Add callback for sitemap URL handler.
88
		add_action(
89
			'init',
90
			array( $this, 'callback_action_catch_sitemap_urls' )
91
		);
92
93
		// Add generator to wp_cron task list.
94
		$this->schedule_sitemap_generation();
95
96
		// Add sitemap to robots.txt.
97
		add_action(
98
			'do_robotstxt',
99
			array( $this, 'callback_action_do_robotstxt' ),
100
			20
101
		);
102
103
		// The news sitemap is cached; here we add a callback to
104
		// flush the cached news sitemap when a post is published.
105
		add_action(
106
			'publish_post',
107
			array( $this, 'callback_action_flush_news_sitemap_cache' ),
108
			10
109
		);
110
111
		/*
112
		 * Module parameters are stored as options in the database.
113
		 * This allows us to avoid having to process all of init
114
		 * before serving the sitemap data. The following actions
115
		 * process and store these filters.
116
		 */
117
118
		// Process filters and store location string for sitemap.
119
		add_action(
120
			'init',
121
			array( $this, 'callback_action_filter_sitemap_location' ),
122
			999
123
		);
124
125
		return;
126
	}
127
128
	/**
129
	 * Echo a raw string of given content-type.
130
	 *
131
	 * @access private
132
	 * @since 4.8.0
133
	 *
134
	 * @param string $the_content_type The content type to be served.
135
	 * @param string $the_content The string to be echoed.
136
	 */
137
	private function serve_raw_and_die( $the_content_type, $the_content ) {
138
		header( 'Content-Type: ' . $the_content_type . '; charset=UTF-8' );
139
140
		if ( '' === $the_content ) {
141
			http_response_code( 404 );
142
			wp_die(
143
				esc_html__( "No sitemap found. Maybe it's being generated. Please try again later.", 'jetpack' ),
144
				esc_html__( 'Sitemaps', 'jetpack' ),
145
				array(
146
					'response' => 404,
147
				)
148
			);
149
		}
150
151
		echo $the_content;
152
153
		die();
0 ignored issues
show
Coding Style Compatibility introduced by
The method serve_raw_and_die() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
154
	}
155
156
	/**
157
	 * Callback to intercept sitemap url requests and serve sitemap files.
158
	 *
159
	 * @access public
160
	 * @since 4.8.0
161
	 */
162
	public function callback_action_catch_sitemap_urls() {
163
		// Regular expressions for sitemap URL routing.
164
		$regex = array(
165
			'master'        => '/^sitemap\.xml$/',
166
			'sitemap'       => '/^sitemap-[1-9][0-9]*\.xml$/',
167
			'index'         => '/^sitemap-index-[1-9][0-9]*\.xml$/',
168
			'sitemap-style' => '/^sitemap\.xsl$/',
169
			'index-style'   => '/^sitemap-index\.xsl$/',
170
			'image'         => '/^image-sitemap-[1-9][0-9]*\.xml$/',
171
			'image-index'   => '/^image-sitemap-index-[1-9][0-9]*\.xml$/',
172
			'image-style'   => '/^image-sitemap\.xsl$/',
173
			'video'         => '/^video-sitemap-[1-9][0-9]*\.xml$/',
174
			'video-index'   => '/^video-sitemap-index-[1-9][0-9]*\.xml$/',
175
			'video-style'   => '/^video-sitemap\.xsl$/',
176
			'news'          => '/^news-sitemap\.xml$/',
177
			'news-style'    => '/^news-sitemap\.xsl$/',
178
		);
179
180
		// The raw path(+query) of the requested URI.
181
		if ( isset( $_SERVER['REQUEST_URI'] ) ) { // WPCS: Input var okay.
182
			$raw_uri = sanitize_text_field(
183
				wp_unslash( $_SERVER['REQUEST_URI'] ) // WPCS: Input var okay.
184
			);
185
		} else {
186
			$raw_uri = '';
187
		}
188
189
		$request = $this->finder->recognize_sitemap_uri( $raw_uri );
190
191
		if ( isset( $request['sitemap_name'] ) ) {
192
193
			/**
194
			 * Filter the content type used to serve the sitemap XML files.
195
			 *
196
			 * @module sitemaps
197
			 *
198
			 * @since 3.9.0
199
			 *
200
			 * @param string $xml_content_type By default, it's 'text/xml'.
201
			 */
202
			$xml_content_type = apply_filters( 'jetpack_sitemap_content_type', 'text/xml' );
203
204
			// Catch master sitemap xml.
205
			if ( preg_match( $regex['master'], $request['sitemap_name'] ) ) {
206
				$this->serve_raw_and_die(
207
					$xml_content_type,
208
					$this->librarian->get_sitemap_text(
209
						jp_sitemap_filename( JP_MASTER_SITEMAP_TYPE, 0 ),
210
						JP_MASTER_SITEMAP_TYPE
211
					)
212
				);
213
			}
214
215
			// Catch sitemap xml.
216 View Code Duplication
			if ( preg_match( $regex['sitemap'], $request['sitemap_name'] ) ) {
217
				$this->serve_raw_and_die(
218
					$xml_content_type,
219
					$this->librarian->get_sitemap_text(
220
						$request['sitemap_name'],
221
						JP_PAGE_SITEMAP_TYPE
222
					)
223
				);
224
			}
225
226
			// Catch sitemap index xml.
227 View Code Duplication
			if ( preg_match( $regex['index'], $request['sitemap_name'] ) ) {
228
				$this->serve_raw_and_die(
229
					$xml_content_type,
230
					$this->librarian->get_sitemap_text(
231
						$request['sitemap_name'],
232
						JP_PAGE_SITEMAP_INDEX_TYPE
233
					)
234
				);
235
			}
236
237
			// Catch sitemap xsl.
238
			if ( preg_match( $regex['sitemap-style'], $request['sitemap_name'] ) ) {
239
				$this->serve_raw_and_die(
240
					'application/xml',
241
					Jetpack_Sitemap_Stylist::sitemap_xsl()
242
				);
243
			}
244
245
			// Catch sitemap index xsl.
246
			if ( preg_match( $regex['index-style'], $request['sitemap_name'] ) ) {
247
				$this->serve_raw_and_die(
248
					'application/xml',
249
					Jetpack_Sitemap_Stylist::sitemap_index_xsl()
250
				);
251
			}
252
253
			// Catch image sitemap xml.
254 View Code Duplication
			if ( preg_match( $regex['image'], $request['sitemap_name'] ) ) {
255
				$this->serve_raw_and_die(
256
					$xml_content_type,
257
					$this->librarian->get_sitemap_text(
258
						$request['sitemap_name'],
259
						JP_IMAGE_SITEMAP_TYPE
260
					)
261
				);
262
			}
263
264
			// Catch image sitemap index xml.
265 View Code Duplication
			if ( preg_match( $regex['image-index'], $request['sitemap_name'] ) ) {
266
				$this->serve_raw_and_die(
267
					$xml_content_type,
268
					$this->librarian->get_sitemap_text(
269
						$request['sitemap_name'],
270
						JP_IMAGE_SITEMAP_INDEX_TYPE
271
					)
272
				);
273
			}
274
275
			// Catch image sitemap xsl.
276
			if ( preg_match( $regex['image-style'], $request['sitemap_name'] ) ) {
277
				$this->serve_raw_and_die(
278
					'application/xml',
279
					Jetpack_Sitemap_Stylist::image_sitemap_xsl()
280
				);
281
			}
282
283
			// Catch video sitemap xml.
284 View Code Duplication
			if ( preg_match( $regex['video'], $request['sitemap_name'] ) ) {
285
				$this->serve_raw_and_die(
286
					$xml_content_type,
287
					$this->librarian->get_sitemap_text(
288
						$request['sitemap_name'],
289
						JP_VIDEO_SITEMAP_TYPE
290
					)
291
				);
292
			}
293
294
			// Catch video sitemap index xml.
295 View Code Duplication
			if ( preg_match( $regex['video-index'], $request['sitemap_name'] ) ) {
296
				$this->serve_raw_and_die(
297
					$xml_content_type,
298
					$this->librarian->get_sitemap_text(
299
						$request['sitemap_name'],
300
						JP_VIDEO_SITEMAP_INDEX_TYPE
301
					)
302
				);
303
			}
304
305
			// Catch video sitemap xsl.
306
			if ( preg_match( $regex['video-style'], $request['sitemap_name'] ) ) {
307
				$this->serve_raw_and_die(
308
					'application/xml',
309
					Jetpack_Sitemap_Stylist::video_sitemap_xsl()
310
				);
311
			}
312
313
			// Catch news sitemap xml.
314
			if ( preg_match( $regex['news'], $request['sitemap_name'] ) ) {
315
				$sitemap_builder = new Jetpack_Sitemap_Builder();
316
				$this->serve_raw_and_die(
317
					$xml_content_type,
318
					$sitemap_builder->news_sitemap_xml()
319
				);
320
			}
321
322
			// Catch news sitemap xsl.
323
			if ( preg_match( $regex['news-style'], $request['sitemap_name'] ) ) {
324
				$this->serve_raw_and_die(
325
					'application/xml',
326
					Jetpack_Sitemap_Stylist::news_sitemap_xsl()
327
				);
328
			}
329
		}
330
331
		// URL did not match any sitemap patterns.
332
		return;
333
	}
334
335
	/**
336
	 * Callback for adding sitemap-interval to the list of schedules.
337
	 *
338
	 * @access public
339
	 * @since 4.8.0
340
	 *
341
	 * @param array $schedules The array of WP_Cron schedules.
342
	 *
343
	 * @return array The updated array of WP_Cron schedules.
344
	 */
345
	public function callback_add_sitemap_schedule( $schedules ) {
346
		$schedules['sitemap-interval'] = array(
347
			'interval' => JP_SITEMAP_INTERVAL,
348
			'display'  => __( 'Sitemap Interval', 'jetpack' ),
349
		);
350
		return $schedules;
351
	}
352
353
	/**
354
	 * Add actions to schedule sitemap generation.
355
	 * Should only be called once, in the constructor.
356
	 *
357
	 * @access private
358
	 * @since 4.8.0
359
	 */
360
	private function schedule_sitemap_generation() {
361
		// Add cron schedule.
362
		add_filter( 'cron_schedules', array( $this, 'callback_add_sitemap_schedule' ) );
363
364
		$sitemap_builder = new Jetpack_Sitemap_Builder();
365
366
		add_action(
367
			'jp_sitemap_cron_hook',
368
			array( $sitemap_builder, 'update_sitemap' )
369
		);
370
371
		if ( ! wp_next_scheduled( 'jp_sitemap_cron_hook' ) ) {
372
			wp_schedule_event(
373
				time(),
374
				'sitemap-interval',
375
				'jp_sitemap_cron_hook'
376
			);
377
		}
378
379
		return;
380
	}
381
382
	/**
383
	 * Callback to add sitemap to robots.txt.
384
	 *
385
	 * @access public
386
	 * @since 4.8.0
387
	 */
388
	public function callback_action_do_robotstxt() {
389
390
		/**
391
		 * Filter whether to make the default sitemap discoverable to robots or not. Default true.
392
		 *
393
		 * @module sitemaps
394
		 * @since 3.9.0
395
		 *
396
		 * @param bool $discover_sitemap Make default sitemap discoverable to robots.
397
		 */
398
		$discover_sitemap = apply_filters( 'jetpack_sitemap_generate', true );
399
400 View Code Duplication
		if ( true === $discover_sitemap ) {
401
			$sitemap_url      = $this->finder->construct_sitemap_url( 'sitemap.xml' );
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned correctly; expected 1 space but found 6 spaces

This check looks for improperly formatted assignments.

Every assignment must have exactly one space before and one space after the equals operator.

To illustrate:

$a = "a";
$ab = "ab";
$abc = "abc";

will have no issues, while

$a   = "a";
$ab  = "ab";
$abc = "abc";

will report issues in lines 1 and 2.

Loading history...
402
			echo 'Sitemap: ' . esc_url( $sitemap_url ) . "\n";
403
		}
404
405
		/**
406
		 * Filter whether to make the news sitemap discoverable to robots or not. Default true.
407
		 *
408
		 * @module sitemaps
409
		 * @since 3.9.0
410
		 *
411
		 * @param bool $discover_news_sitemap Make default news sitemap discoverable to robots.
412
		 */
413
		$discover_news_sitemap = apply_filters( 'jetpack_news_sitemap_generate', true );
414
415 View Code Duplication
		if ( true === $discover_news_sitemap ) {
416
			$news_sitemap_url = $this->finder->construct_sitemap_url( 'news-sitemap.xml' );
417
			echo 'Sitemap: ' . esc_url( $news_sitemap_url ) . "\n";
418
		}
419
420
		return;
421
	}
422
423
	/**
424
	 * Callback to delete the news sitemap cache.
425
	 *
426
	 * @access public
427
	 * @since 4.8.0
428
	 */
429
	public function callback_action_flush_news_sitemap_cache() {
430
		delete_transient( 'jetpack_news_sitemap_xml' );
431
	}
432
433
	/**
434
	 * Callback to set the sitemap location.
435
	 *
436
	 * @access public
437
	 * @since 4.8.0
438
	 */
439
	public function callback_action_filter_sitemap_location() {
440
		update_option(
441
			'jetpack_sitemap_location',
442
			/**
443
			 * Additional path for sitemap URIs. Default value is empty.
444
			 *
445
			 * This string is any additional path fragment you want included between
446
			 * the home URL and the sitemap filenames. Exactly how this fragment is
447
			 * interpreted depends on your permalink settings. For example:
448
			 *
449
			 *   Pretty permalinks:
450
			 *     home_url() . jetpack_sitemap_location . '/sitemap.xml'
451
			 *
452
			 *   Plain ("ugly") permalinks:
453
			 *     home_url() . jetpack_sitemap_location . '/?jetpack-sitemap=sitemap.xml'
454
			 *
455
			 *   PATHINFO permalinks:
456
			 *     home_url() . '/index.php' . jetpack_sitemap_location . '/sitemap.xml'
457
			 *
458
			 * where 'sitemap.xml' is the name of a specific sitemap file.
459
			 * The value of this filter must be a valid path fragment per RFC 3986;
460
			 * in particular it must either be empty or begin with a '/'.
461
			 * Also take care that any restrictions on sitemap location imposed by
462
			 * the sitemap protocol are satisfied.
463
			 *
464
			 * The result of this filter is stored in an option, 'jetpack_sitemap_location';
465
			 * that option is what gets read when the sitemap location is needed.
466
			 * This way we don't have to wait for init to finish before building sitemaps.
467
			 *
468
			 * @link https://tools.ietf.org/html/rfc3986#section-3.3 RFC 3986
469
			 * @link http://www.sitemaps.org/ The sitemap protocol
470
			 *
471
			 * @since 4.8.0
472
			 */
473
			apply_filters(
474
				'jetpack_sitemap_location',
475
				''
476
			)
477
		);
478
479
		return;
480
	}
481
482
} // End Jetpack_Sitemap_Manager class.
483
484
new Jetpack_Sitemap_Manager();
485
486
/**
487
 * Absolute URL of the current blog's sitemap.
488
 *
489
 * @module sitemaps
490
 *
491
 * @since  3.9.0
492
 * @since  4.8.1 Code uses method found in Jetpack_Sitemap_Finder::construct_sitemap_url in 4.8.0.
493
 *                It has been moved here to avoid fatal errors with other plugins that were expecting to find this function.
494
 *
495
 * @param string $filename Sitemap file name. Defaults to 'sitemap.xml', the initial sitemaps page.
496
 *
497
 * @return string Sitemap URL.
498
 */
499
function jetpack_sitemap_uri( $filename = 'sitemap.xml' ) {
500
	global $wp_rewrite;
501
502
	$location = Jetpack_Options::get_option_and_ensure_autoload( 'jetpack_sitemap_location', '' );
503
504
	if ( $wp_rewrite->using_index_permalinks() ) {
505
		$sitemap_url = home_url( '/index.php' . $location . '/' . $filename );
506
	} elseif ( $wp_rewrite->using_permalinks() ) {
507
		$sitemap_url = home_url( $location . '/' . $filename );
508
	} else {
509
		$sitemap_url = home_url( $location . '/?jetpack-sitemap=' . $filename );
510
	}
511
512
	/**
513
	 * Filter sitemap URL relative to home URL.
514
	 *
515
	 * @module sitemaps
516
	 *
517
	 * @since 3.9.0
518
	 *
519
	 * @param string $sitemap_url Sitemap URL.
520
	 */
521
	return apply_filters( 'jetpack_sitemap_location', $sitemap_url );
522
}