Issues (942)

Security Analysis    not enabled

This project does not seem to handle request data directly as such no vulnerable execution paths were found.

  Cross-Site Scripting
Cross-Site Scripting enables an attacker to inject code into the response of a web-request that is viewed by other users. It can for example be used to bypass access controls, or even to take over other users' accounts.
  File Exposure
File Exposure allows an attacker to gain access to local files that he should not be able to access. These files can for example include database credentials, or other configuration files.
  File Manipulation
File Manipulation enables an attacker to write custom data to files. This potentially leads to injection of arbitrary code on the server.
  Object Injection
Object Injection enables an attacker to inject an object into PHP code, and can lead to arbitrary code execution, file exposure, or file manipulation attacks.
  Code Injection
Code Injection enables an attacker to execute arbitrary code on the server.
  Response Splitting
Response Splitting can be used to send arbitrary responses.
  File Inclusion
File Inclusion enables an attacker to inject custom files into PHP's file loading mechanism, either explicitly passed to include, or for example via PHP's auto-loading mechanism.
  Command Injection
Command Injection enables an attacker to inject a shell command that is execute with the privileges of the web-server. This can be used to expose sensitive data, or gain access of your server.
  SQL Injection
SQL Injection enables an attacker to execute arbitrary SQL code on your database server gaining access to user data, or manipulating user data.
  XPath Injection
XPath Injection enables an attacker to modify the parts of XML document that are read. If that XML document is for example used for authentication, this can lead to further vulnerabilities similar to SQL Injection.
  LDAP Injection
LDAP Injection enables an attacker to inject LDAP statements potentially granting permission to run unauthorized queries, or modify content inside the LDAP tree.
  Header Injection
  Other Vulnerability
This category comprises other attack vectors such as manipulating the PHP runtime, loading custom extensions, freezing the runtime, or similar.
  Regex Injection
Regex Injection enables an attacker to execute arbitrary code in your PHP process.
  XML Injection
XML Injection enables an attacker to read files on your local filesystem including configuration files, or can be abused to freeze your web-server process.
  Variable Injection
Variable Injection enables an attacker to overwrite program variables with custom data, and can lead to further vulnerabilities.
Unfortunately, the security analysis is currently not available for your project. If you are a non-commercial open-source project, please contact support to gain access.

includes/class-wc-structured-data.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
/**
3
 * Structured data's handler and generator using JSON-LD format.
4
 *
5
 * @package WooCommerce/Classes
6
 * @since   3.0.0
7
 * @version 3.0.0
8
 */
9
10
defined( 'ABSPATH' ) || exit;
11
12
/**
13
 * Structured data class.
14
 */
15
class WC_Structured_Data {
16
17
	/**
18
	 * Stores the structured data.
19
	 *
20
	 * @var array $_data Array of structured data.
21
	 */
22
	private $_data = array();
23
24
	/**
25
	 * Constructor.
26
	 */
27
	public function __construct() {
28
		// Generate structured data.
29
		add_action( 'woocommerce_before_main_content', array( $this, 'generate_website_data' ), 30 );
30
		add_action( 'woocommerce_breadcrumb', array( $this, 'generate_breadcrumblist_data' ), 10 );
31
		add_action( 'woocommerce_single_product_summary', array( $this, 'generate_product_data' ), 60 );
32
		add_action( 'woocommerce_review_meta', array( $this, 'generate_review_data' ), 20 );
33
		add_action( 'woocommerce_email_order_details', array( $this, 'generate_order_data' ), 20, 3 );
34
35
		// Output structured data.
36
		add_action( 'woocommerce_email_order_details', array( $this, 'output_email_structured_data' ), 30, 3 );
37
		add_action( 'wp_footer', array( $this, 'output_structured_data' ), 10 );
38
	}
39
40
	/**
41
	 * Sets data.
42
	 *
43
	 * @param  array $data  Structured data.
44
	 * @param  bool  $reset Unset data (default: false).
45
	 * @return bool
46
	 */
47
	public function set_data( $data, $reset = false ) {
48
		if ( ! isset( $data['@type'] ) || ! preg_match( '|^[a-zA-Z]{1,20}$|', $data['@type'] ) ) {
49
			return false;
50
		}
51
52
		if ( $reset && isset( $this->_data ) ) {
53
			unset( $this->_data );
54
		}
55
56
		$this->_data[] = $data;
57
58
		return true;
59
	}
60
61
	/**
62
	 * Gets data.
63
	 *
64
	 * @return array
65
	 */
66
	public function get_data() {
67
		return $this->_data;
68
	}
69
70
	/**
71
	 * Structures and returns data.
72
	 *
73
	 * List of types available by default for specific request:
74
	 *
75
	 * 'product',
76
	 * 'review',
77
	 * 'breadcrumblist',
78
	 * 'website',
79
	 * 'order',
80
	 *
81
	 * @param  array $types Structured data types.
82
	 * @return array
83
	 */
84
	public function get_structured_data( $types ) {
85
		$data = array();
86
87
		// Put together the values of same type of structured data.
88
		foreach ( $this->get_data() as $value ) {
89
			$data[ strtolower( $value['@type'] ) ][] = $value;
90
		}
91
92
		// Wrap the multiple values of each type inside a graph... Then add context to each type.
93
		foreach ( $data as $type => $value ) {
94
			$data[ $type ] = count( $value ) > 1 ? array( '@graph' => $value ) : $value[0];
95
			$data[ $type ] = apply_filters( 'woocommerce_structured_data_context', array( '@context' => 'https://schema.org/' ), $data, $type, $value ) + $data[ $type ];
96
		}
97
98
		// If requested types, pick them up... Finally change the associative array to an indexed one.
99
		$data = $types ? array_values( array_intersect_key( $data, array_flip( $types ) ) ) : array_values( $data );
100
101
		if ( ! empty( $data ) ) {
102
			if ( 1 < count( $data ) ) {
103
				$data = apply_filters( 'woocommerce_structured_data_context', array( '@context' => 'https://schema.org/' ), $data, '', '' ) + array( '@graph' => $data );
104
			} else {
105
				$data = $data[0];
106
			}
107
		}
108
109
		return $data;
110
	}
111
112
	/**
113
	 * Get data types for pages.
114
	 *
115
	 * @return array
116
	 */
117
	protected function get_data_type_for_page() {
118
		$types   = array();
119
		$types[] = is_shop() || is_product_category() || is_product() ? 'product' : '';
120
		$types[] = is_shop() && is_front_page() ? 'website' : '';
121
		$types[] = is_product() ? 'review' : '';
122
		$types[] = 'breadcrumblist';
123
		$types[] = 'order';
124
125
		return array_filter( apply_filters( 'woocommerce_structured_data_type_for_page', $types ) );
126
	}
127
128
	/**
129
	 * Makes sure email structured data only outputs on non-plain text versions.
130
	 *
131
	 * @param WP_Order $order         Order data.
132
	 * @param bool     $sent_to_admin Send to admin (default: false).
133
	 * @param bool     $plain_text    Plain text email (default: false).
134
	 */
135
	public function output_email_structured_data( $order, $sent_to_admin = false, $plain_text = false ) {
136
		if ( $plain_text ) {
137
			return;
138
		}
139
		echo '<div style="display: none; font-size: 0; max-height: 0; line-height: 0; padding: 0; mso-hide: all;">';
140
		$this->output_structured_data();
141
		echo '</div>';
142
	}
143
144
	/**
145
	 * Sanitizes, encodes and outputs structured data.
146
	 *
147
	 * Hooked into `wp_footer` action hook.
148
	 * Hooked into `woocommerce_email_order_details` action hook.
149
	 */
150
	public function output_structured_data() {
151
		$types = $this->get_data_type_for_page();
152
		$data  = $this->get_structured_data( $types );
153
154
		if ( $data ) {
155
			echo '<script type="application/ld+json">' . wc_esc_json( wp_json_encode( $data ), true ) . '</script>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
156
		}
157
	}
158
159
	/*
160
	|--------------------------------------------------------------------------
161
	| Generators
162
	|--------------------------------------------------------------------------
163
	|
164
	| Methods for generating specific structured data types:
165
	|
166
	| - Product
167
	| - Review
168
	| - BreadcrumbList
169
	| - WebSite
170
	| - Order
171
	|
172
	| The generated data is stored into `$this->_data`.
173
	| See the methods above for handling `$this->_data`.
174
	|
175
	*/
176
177
	/**
178
	 * Generates Product structured data.
179
	 *
180
	 * Hooked into `woocommerce_single_product_summary` action hook.
181
	 *
182
	 * @param WC_Product $product Product data (default: null).
183
	 */
184
	public function generate_product_data( $product = null ) {
185
		if ( ! is_object( $product ) ) {
186
			global $product;
187
		}
188
189
		if ( ! is_a( $product, 'WC_Product' ) ) {
190
			return;
191
		}
192
193
		$shop_name = get_bloginfo( 'name' );
194
		$shop_url  = home_url();
195
		$currency  = get_woocommerce_currency();
196
		$permalink = get_permalink( $product->get_id() );
197
		$image     = wp_get_attachment_url( $product->get_image_id() );
0 ignored issues
show
It seems like $product is not always an object, but can also be of type null. Maybe add an additional type check?

If a variable is not always an object, we recommend to add an additional type check to ensure your method call is safe:

function someFunction(A $objectMaybe = null)
{
    if ($objectMaybe instanceof A) {
        $objectMaybe->doSomething();
    }
}
Loading history...
198
199
		$markup = array(
200
			'@type'       => 'Product',
201
			'@id'         => $permalink . '#product', // Append '#product' to differentiate between this @id and the @id generated for the Breadcrumblist.
202
			'name'        => $product->get_name(),
203
			'url'         => $permalink,
204
			'description' => wp_strip_all_tags( do_shortcode( $product->get_short_description() ? $product->get_short_description() : $product->get_description() ) ),
205
		);
206
207
		if ( $image ) {
208
			$markup['image'] = $image;
209
		}
210
211
		// Declare SKU or fallback to ID.
212
		if ( $product->get_sku() ) {
213
			$markup['sku'] = $product->get_sku();
214
		} else {
215
			$markup['sku'] = $product->get_id();
216
		}
217
218
		if ( '' !== $product->get_price() ) {
219
			// Assume prices will be valid until the end of next year, unless on sale and there is an end date.
220
			$price_valid_until = date( 'Y-12-31', current_time( 'timestamp', true ) + YEAR_IN_SECONDS );
221
222
			if ( $product->is_type( 'variable' ) ) {
223
				$lowest  = $product->get_variation_price( 'min', false );
224
				$highest = $product->get_variation_price( 'max', false );
225
226
				if ( $lowest === $highest ) {
227
					$markup_offer = array(
228
						'@type'              => 'Offer',
229
						'price'              => wc_format_decimal( $lowest, wc_get_price_decimals() ),
230
						'priceValidUntil'    => $price_valid_until,
231
						'priceSpecification' => array(
232
							'price'                 => wc_format_decimal( $lowest, wc_get_price_decimals() ),
233
							'priceCurrency'         => $currency,
234
							'valueAddedTaxIncluded' => wc_prices_include_tax() ? 'true' : 'false',
235
						),
236
					);
237
				} else {
238
					$markup_offer = array(
239
						'@type'      => 'AggregateOffer',
240
						'lowPrice'   => wc_format_decimal( $lowest, wc_get_price_decimals() ),
241
						'highPrice'  => wc_format_decimal( $highest, wc_get_price_decimals() ),
242
						'offerCount' => count( $product->get_children() ),
243
					);
244
				}
245
			} else {
246
				if ( $product->is_on_sale() && $product->get_date_on_sale_to() ) {
247
					$price_valid_until = date( 'Y-m-d', $product->get_date_on_sale_to()->getTimestamp() );
248
				}
249
				$markup_offer = array(
250
					'@type'              => 'Offer',
251
					'price'              => wc_format_decimal( $product->get_price(), wc_get_price_decimals() ),
252
					'priceValidUntil'    => $price_valid_until,
253
					'priceSpecification' => array(
254
						'price'                 => wc_format_decimal( $product->get_price(), wc_get_price_decimals() ),
255
						'priceCurrency'         => $currency,
256
						'valueAddedTaxIncluded' => wc_prices_include_tax() ? 'true' : 'false',
257
					),
258
				);
259
			}
260
261
			$markup_offer += array(
262
				'priceCurrency' => $currency,
263
				'availability'  => 'http://schema.org/' . ( $product->is_in_stock() ? 'InStock' : 'OutOfStock' ),
264
				'url'           => $permalink,
265
				'seller'        => array(
266
					'@type' => 'Organization',
267
					'name'  => $shop_name,
268
					'url'   => $shop_url,
269
				),
270
			);
271
272
			$markup['offers'] = array( apply_filters( 'woocommerce_structured_data_product_offer', $markup_offer, $product ) );
273
		}
274
275
		if ( $product->get_rating_count() && wc_review_ratings_enabled() ) {
276
			$markup['aggregateRating'] = array(
277
				'@type'       => 'AggregateRating',
278
				'ratingValue' => $product->get_average_rating(),
279
				'reviewCount' => $product->get_review_count(),
280
			);
281
282
			// Markup most recent rating/review.
283
			$comments = get_comments(
284
				array(
285
					'number'      => 1,
286
					'post_id'     => $product->get_id(),
287
					'status'      => 'approve',
288
					'post_status' => 'publish',
289
					'post_type'   => 'product',
290
					'parent'      => 0,
291
					'meta_key'    => 'rating',
292
					'orderby'     => 'meta_value_num',
293
				)
294
			);
295
296
			if ( $comments ) {
297
				foreach ( $comments as $comment ) {
298
					$rating = get_comment_meta( $comment->comment_ID, 'rating', true );
299
300
					if ( ! $rating ) {
301
						continue;
302
					}
303
304
					$markup['review'] = array(
305
						'@type'        => 'Review',
306
						'reviewRating' => array(
307
							'@type'       => 'Rating',
308
							'ratingValue' => $rating,
309
						),
310
						'author'       => array(
311
							'@type' => 'Person',
312
							'name'  => get_comment_author( $comment->comment_ID ),
313
						),
314
					);
315
				}
316
			}
317
		}
318
319
		// Check we have required data.
320
		if ( empty( $markup['aggregateRating'] ) && empty( $markup['offers'] ) && empty( $markup['review'] ) ) {
321
			return;
322
		}
323
324
		$this->set_data( apply_filters( 'woocommerce_structured_data_product', $markup, $product ) );
325
	}
326
327
	/**
328
	 * Generates Review structured data.
329
	 *
330
	 * Hooked into `woocommerce_review_meta` action hook.
331
	 *
332
	 * @param WP_Comment $comment Comment data.
333
	 */
334
	public function generate_review_data( $comment ) {
335
		$markup                  = array();
336
		$markup['@type']         = 'Review';
337
		$markup['@id']           = get_comment_link( $comment->comment_ID );
338
		$markup['datePublished'] = get_comment_date( 'c', $comment->comment_ID );
339
		$markup['description']   = get_comment_text( $comment->comment_ID );
340
		$markup['itemReviewed']  = array(
341
			'@type' => 'Product',
342
			'name'  => get_the_title( $comment->comment_post_ID ),
343
		);
344
345
		// Skip replies unless they have a rating.
346
		$rating = get_comment_meta( $comment->comment_ID, 'rating', true );
347
348
		if ( $rating ) {
349
			$markup['reviewRating'] = array(
350
				'@type'       => 'Rating',
351
				'ratingValue' => $rating,
352
			);
353
		} elseif ( $comment->comment_parent ) {
354
			return;
355
		}
356
357
		$markup['author'] = array(
358
			'@type' => 'Person',
359
			'name'  => get_comment_author( $comment->comment_ID ),
360
		);
361
362
		$this->set_data( apply_filters( 'woocommerce_structured_data_review', $markup, $comment ) );
363
	}
364
365
	/**
366
	 * Generates BreadcrumbList structured data.
367
	 *
368
	 * Hooked into `woocommerce_breadcrumb` action hook.
369
	 *
370
	 * @param WC_Breadcrumb $breadcrumbs Breadcrumb data.
371
	 */
372
	public function generate_breadcrumblist_data( $breadcrumbs ) {
373
		$crumbs = $breadcrumbs->get_breadcrumb();
374
375
		if ( empty( $crumbs ) || ! is_array( $crumbs ) ) {
376
			return;
377
		}
378
379
		$markup                    = array();
380
		$markup['@type']           = 'BreadcrumbList';
381
		$markup['itemListElement'] = array();
382
383
		foreach ( $crumbs as $key => $crumb ) {
384
			$markup['itemListElement'][ $key ] = array(
385
				'@type'    => 'ListItem',
386
				'position' => $key + 1,
387
				'item'     => array(
388
					'name' => $crumb[0],
389
				),
390
			);
391
392
			if ( ! empty( $crumb[1] ) ) {
393
				$markup['itemListElement'][ $key ]['item'] += array( '@id' => $crumb[1] );
394
			} elseif ( isset( $_SERVER['HTTP_HOST'], $_SERVER['REQUEST_URI'] ) ) {
395
				$current_url = set_url_scheme( 'http://' . wp_unslash( $_SERVER['HTTP_HOST'] ) . wp_unslash( $_SERVER['REQUEST_URI'] ) ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
396
397
				$markup['itemListElement'][ $key ]['item'] += array( '@id' => $current_url );
398
			}
399
		}
400
401
		$this->set_data( apply_filters( 'woocommerce_structured_data_breadcrumblist', $markup, $breadcrumbs ) );
402
	}
403
404
	/**
405
	 * Generates WebSite structured data.
406
	 *
407
	 * Hooked into `woocommerce_before_main_content` action hook.
408
	 */
409
	public function generate_website_data() {
410
		$markup                    = array();
411
		$markup['@type']           = 'WebSite';
412
		$markup['name']            = get_bloginfo( 'name' );
413
		$markup['url']             = home_url();
414
		$markup['potentialAction'] = array(
415
			'@type'       => 'SearchAction',
416
			'target'      => home_url( '?s={search_term_string}&post_type=product' ),
417
			'query-input' => 'required name=search_term_string',
418
		);
419
420
		$this->set_data( apply_filters( 'woocommerce_structured_data_website', $markup ) );
421
	}
422
423
	/**
424
	 * Generates Order structured data.
425
	 *
426
	 * Hooked into `woocommerce_email_order_details` action hook.
427
	 *
428
	 * @param WP_Order $order         Order data.
429
	 * @param bool     $sent_to_admin Send to admin (default: false).
430
	 * @param bool     $plain_text    Plain text email (default: false).
431
	 */
432
	public function generate_order_data( $order, $sent_to_admin = false, $plain_text = false ) {
433
		if ( $plain_text || ! is_a( $order, 'WC_Order' ) ) {
434
			return;
435
		}
436
437
		$shop_name      = get_bloginfo( 'name' );
438
		$shop_url       = home_url();
439
		$order_url      = $sent_to_admin ? $order->get_edit_order_url() : $order->get_view_order_url();
440
		$order_statuses = array(
441
			'pending'    => 'https://schema.org/OrderPaymentDue',
442
			'processing' => 'https://schema.org/OrderProcessing',
443
			'on-hold'    => 'https://schema.org/OrderProblem',
444
			'completed'  => 'https://schema.org/OrderDelivered',
445
			'cancelled'  => 'https://schema.org/OrderCancelled',
446
			'refunded'   => 'https://schema.org/OrderReturned',
447
			'failed'     => 'https://schema.org/OrderProblem',
448
		);
449
450
		$markup_offers = array();
451
		foreach ( $order->get_items() as $item ) {
452
			if ( ! apply_filters( 'woocommerce_order_item_visible', true, $item ) ) {
453
				continue;
454
			}
455
456
			$product        = $order->get_product_from_item( $item );
457
			$product_exists = is_object( $product );
458
			$is_visible     = $product_exists && $product->is_visible();
459
460
			$markup_offers[] = array(
461
				'@type'              => 'Offer',
462
				'price'              => $order->get_line_subtotal( $item ),
463
				'priceCurrency'      => $order->get_currency(),
464
				'priceSpecification' => array(
465
					'price'            => $order->get_line_subtotal( $item ),
466
					'priceCurrency'    => $order->get_currency(),
467
					'eligibleQuantity' => array(
468
						'@type' => 'QuantitativeValue',
469
						'value' => apply_filters( 'woocommerce_email_order_item_quantity', $item['qty'], $item ),
470
					),
471
				),
472
				'itemOffered'        => array(
473
					'@type' => 'Product',
474
					'name'  => apply_filters( 'woocommerce_order_item_name', $item['name'], $item, $is_visible ),
475
					'sku'   => $product_exists ? $product->get_sku() : '',
476
					'image' => $product_exists ? wp_get_attachment_image_url( $product->get_image_id() ) : '',
477
					'url'   => $is_visible ? get_permalink( $product->get_id() ) : get_home_url(),
478
				),
479
				'seller'             => array(
480
					'@type' => 'Organization',
481
					'name'  => $shop_name,
482
					'url'   => $shop_url,
483
				),
484
			);
485
		}
486
487
		$markup                       = array();
488
		$markup['@type']              = 'Order';
489
		$markup['url']                = $order_url;
490
		$markup['orderStatus']        = isset( $order_statuses[ $order->get_status() ] ) ? $order_statuses[ $order->get_status() ] : '';
491
		$markup['orderNumber']        = $order->get_order_number();
492
		$markup['orderDate']          = $order->get_date_created()->format( 'c' );
493
		$markup['acceptedOffer']      = $markup_offers;
494
		$markup['discount']           = $order->get_total_discount();
495
		$markup['discountCurrency']   = $order->get_currency();
496
		$markup['price']              = $order->get_total();
497
		$markup['priceCurrency']      = $order->get_currency();
498
		$markup['priceSpecification'] = array(
499
			'price'                 => $order->get_total(),
500
			'priceCurrency'         => $order->get_currency(),
501
			'valueAddedTaxIncluded' => 'true',
502
		);
503
		$markup['billingAddress']     = array(
504
			'@type'           => 'PostalAddress',
505
			'name'            => $order->get_formatted_billing_full_name(),
506
			'streetAddress'   => $order->get_billing_address_1(),
507
			'postalCode'      => $order->get_billing_postcode(),
508
			'addressLocality' => $order->get_billing_city(),
509
			'addressRegion'   => $order->get_billing_state(),
510
			'addressCountry'  => $order->get_billing_country(),
511
			'email'           => $order->get_billing_email(),
512
			'telephone'       => $order->get_billing_phone(),
513
		);
514
		$markup['customer']           = array(
515
			'@type' => 'Person',
516
			'name'  => $order->get_formatted_billing_full_name(),
517
		);
518
		$markup['merchant']           = array(
519
			'@type' => 'Organization',
520
			'name'  => $shop_name,
521
			'url'   => $shop_url,
522
		);
523
		$markup['potentialAction']    = array(
524
			'@type'  => 'ViewAction',
525
			'name'   => 'View Order',
526
			'url'    => $order_url,
527
			'target' => $order_url,
528
		);
529
530
		$this->set_data( apply_filters( 'woocommerce_structured_data_order', $markup, $sent_to_admin, $order ), true );
531
	}
532
}
533