Completed
Push — develop ( 2591ef...d29aab )
by David
01:50
created
src/includes/class-wordlift-post-to-jsonld-converter.php 1 patch
Indentation   +428 added lines, -428 removed lines patch added patch discarded remove patch
@@ -18,452 +18,452 @@
 block discarded – undo
18 18
  */
19 19
 class Wordlift_Post_To_Jsonld_Converter extends Wordlift_Abstract_Post_To_Jsonld_Converter {
20 20
 
21
-	/**
22
-	 * @var Wordlift_Post_To_Jsonld_Converter
23
-	 */
24
-	private static $instance;
25
-
26
-	/**
27
-	 * A {@link Wordlift_Log_Service} instance.
28
-	 *
29
-	 * @since  3.10.0
30
-	 * @access private
31
-	 * @var Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
32
-	 */
33
-	private $log;
34
-
35
-	/**
36
-	 * @var false
37
-	 */
38
-	private $disable_convert_filters;
39
-
40
-	/**
41
-	 * Wordlift_Post_To_Jsonld_Converter constructor.
42
-	 *
43
-	 * @param Wordlift_Entity_Type_Service $entity_type_service A {@link Wordlift_Entity_Type_Service} instance.
44
-	 * @param Wordlift_User_Service        $user_service A {@link Wordlift_User_Service} instance.
45
-	 * @param Wordlift_Attachment_Service  $attachment_service A {@link Wordlift_Attachment_Service} instance.
46
-	 *
47
-	 * @since 3.10.0
48
-	 */
49
-	public function __construct( $entity_type_service, $user_service, $attachment_service, $disable_convert_filters = false ) {
50
-		parent::__construct( $entity_type_service, $user_service, $attachment_service, Wordlift_Property_Getter_Factory::create() );
51
-		$this->disable_convert_filters = $disable_convert_filters;
52
-		// Set a reference to the logger.
53
-		$this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Post_To_Jsonld_Converter' );
54
-
55
-		self::$instance = $this;
56
-
57
-	}
58
-
59
-	public static function get_instance() {
60
-
61
-		return self::$instance;
62
-	}
63
-
64
-	public function new_instance_with_filters_disabled() {
65
-		return new static( $this->entity_type_service, $this->user_service, $this->attachment_service, true );
66
-	}
67
-
68
-	/**
69
-	 * Convert the provided {@link WP_Post} to a JSON-LD array. Any entity reference
70
-	 * found while processing the post is set in the $references array.
71
-	 *
72
-	 * @param int              $post_id The post id.
73
-	 * @param array<Reference> $references An array of entity references.
74
-	 * @param array            $references_infos
75
-	 *
76
-	 * @return array A JSON-LD array.
77
-	 * @since 3.10.0
78
-	 */
79
-	public function convert( $post_id, &$references = array(), &$references_infos = array(), $relations = null ) {
80
-
81
-		// Get the post instance.
82
-		$post = get_post( $post_id );
83
-		if ( null === $post ) {
84
-			// Post not found.
85
-			return null;
86
-		}
87
-
88
-		// Get the base JSON-LD and the list of entities referenced by this entity.
89
-		$jsonld = parent::convert( $post_id, $references, $references_infos, $relations );
90
-
91
-		// Set WebPage by default.
92
-		if ( empty( $jsonld['@type'] ) ) {
93
-			$jsonld['@type'] = 'WebPage';
94
-		}
95
-
96
-		// Get the entity name.
97
-		$jsonld['headline'] = $post->post_title;
98
-
99
-		$custom_fields = $this->entity_type_service->get_custom_fields_for_post( $post_id );
100
-
101
-		if ( isset( $custom_fields ) ) {
102
-			$this->process_type_custom_fields( $jsonld, $custom_fields, $post, $references, $references_infos );
103
-		}
104
-
105
-		// Set the published and modified dates.
106
-		/*
21
+    /**
22
+     * @var Wordlift_Post_To_Jsonld_Converter
23
+     */
24
+    private static $instance;
25
+
26
+    /**
27
+     * A {@link Wordlift_Log_Service} instance.
28
+     *
29
+     * @since  3.10.0
30
+     * @access private
31
+     * @var Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
32
+     */
33
+    private $log;
34
+
35
+    /**
36
+     * @var false
37
+     */
38
+    private $disable_convert_filters;
39
+
40
+    /**
41
+     * Wordlift_Post_To_Jsonld_Converter constructor.
42
+     *
43
+     * @param Wordlift_Entity_Type_Service $entity_type_service A {@link Wordlift_Entity_Type_Service} instance.
44
+     * @param Wordlift_User_Service        $user_service A {@link Wordlift_User_Service} instance.
45
+     * @param Wordlift_Attachment_Service  $attachment_service A {@link Wordlift_Attachment_Service} instance.
46
+     *
47
+     * @since 3.10.0
48
+     */
49
+    public function __construct( $entity_type_service, $user_service, $attachment_service, $disable_convert_filters = false ) {
50
+        parent::__construct( $entity_type_service, $user_service, $attachment_service, Wordlift_Property_Getter_Factory::create() );
51
+        $this->disable_convert_filters = $disable_convert_filters;
52
+        // Set a reference to the logger.
53
+        $this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Post_To_Jsonld_Converter' );
54
+
55
+        self::$instance = $this;
56
+
57
+    }
58
+
59
+    public static function get_instance() {
60
+
61
+        return self::$instance;
62
+    }
63
+
64
+    public function new_instance_with_filters_disabled() {
65
+        return new static( $this->entity_type_service, $this->user_service, $this->attachment_service, true );
66
+    }
67
+
68
+    /**
69
+     * Convert the provided {@link WP_Post} to a JSON-LD array. Any entity reference
70
+     * found while processing the post is set in the $references array.
71
+     *
72
+     * @param int              $post_id The post id.
73
+     * @param array<Reference> $references An array of entity references.
74
+     * @param array            $references_infos
75
+     *
76
+     * @return array A JSON-LD array.
77
+     * @since 3.10.0
78
+     */
79
+    public function convert( $post_id, &$references = array(), &$references_infos = array(), $relations = null ) {
80
+
81
+        // Get the post instance.
82
+        $post = get_post( $post_id );
83
+        if ( null === $post ) {
84
+            // Post not found.
85
+            return null;
86
+        }
87
+
88
+        // Get the base JSON-LD and the list of entities referenced by this entity.
89
+        $jsonld = parent::convert( $post_id, $references, $references_infos, $relations );
90
+
91
+        // Set WebPage by default.
92
+        if ( empty( $jsonld['@type'] ) ) {
93
+            $jsonld['@type'] = 'WebPage';
94
+        }
95
+
96
+        // Get the entity name.
97
+        $jsonld['headline'] = $post->post_title;
98
+
99
+        $custom_fields = $this->entity_type_service->get_custom_fields_for_post( $post_id );
100
+
101
+        if ( isset( $custom_fields ) ) {
102
+            $this->process_type_custom_fields( $jsonld, $custom_fields, $post, $references, $references_infos );
103
+        }
104
+
105
+        // Set the published and modified dates.
106
+        /*
107 107
 		 * Set the `datePublished` and `dateModified` using the local timezone.
108 108
 		 *
109 109
 		 * @see https://github.com/insideout10/wordlift-plugin/issues/887
110 110
 		 *
111 111
 		 * @since 3.20.0
112 112
 		 */
113
-		try {
114
-			$default_timezone = date_default_timezone_get();
115
-			$timezone         = get_option( 'timezone_string' );
116
-			if ( ! empty( $timezone ) ) {
117
-				date_default_timezone_set( $timezone ); //phpcs:ignore WordPress.DateTime.RestrictedFunctions.timezone_change_date_default_timezone_set
118
-				$jsonld['datePublished'] = get_post_time( 'Y-m-d\TH:i:sP', false, $post );
119
-				$jsonld['dateModified']  = get_post_modified_time( 'Y-m-d\TH:i:sP', false, $post );
120
-				date_default_timezone_set( $default_timezone ); //phpcs:ignore WordPress.DateTime.RestrictedFunctions.timezone_change_date_default_timezone_set
121
-			} else {
122
-				$jsonld['datePublished'] = get_post_time( 'Y-m-d\TH:i', true, $post, false );
123
-				$jsonld['dateModified']  = get_post_modified_time( 'Y-m-d\TH:i', true, $post, false );
124
-			}
125
-		} catch ( Exception $e ) {
126
-			$jsonld['datePublished'] = get_post_time( 'Y-m-d\TH:i', true, $post, false );
127
-			$jsonld['dateModified']  = get_post_modified_time( 'Y-m-d\TH:i', true, $post, false );
128
-		}
129
-
130
-		// Get the word count for the post.
131
-		/*
113
+        try {
114
+            $default_timezone = date_default_timezone_get();
115
+            $timezone         = get_option( 'timezone_string' );
116
+            if ( ! empty( $timezone ) ) {
117
+                date_default_timezone_set( $timezone ); //phpcs:ignore WordPress.DateTime.RestrictedFunctions.timezone_change_date_default_timezone_set
118
+                $jsonld['datePublished'] = get_post_time( 'Y-m-d\TH:i:sP', false, $post );
119
+                $jsonld['dateModified']  = get_post_modified_time( 'Y-m-d\TH:i:sP', false, $post );
120
+                date_default_timezone_set( $default_timezone ); //phpcs:ignore WordPress.DateTime.RestrictedFunctions.timezone_change_date_default_timezone_set
121
+            } else {
122
+                $jsonld['datePublished'] = get_post_time( 'Y-m-d\TH:i', true, $post, false );
123
+                $jsonld['dateModified']  = get_post_modified_time( 'Y-m-d\TH:i', true, $post, false );
124
+            }
125
+        } catch ( Exception $e ) {
126
+            $jsonld['datePublished'] = get_post_time( 'Y-m-d\TH:i', true, $post, false );
127
+            $jsonld['dateModified']  = get_post_modified_time( 'Y-m-d\TH:i', true, $post, false );
128
+        }
129
+
130
+        // Get the word count for the post.
131
+        /*
132 132
 		 * Do not display the `wordCount` on a `WebPage`.
133 133
 		 *
134 134
 		 * @see https://github.com/insideout10/wordlift-plugin/issues/888
135 135
 		 *
136 136
 		 * @since 3.20.0
137 137
 		 */
138
-		if ( ! empty( $jsonld['@type'] ) && 'WebPage' !== $jsonld['@type'] ) {
139
-			$post_adapter        = new Wordlift_Post_Adapter( $post_id );
140
-			$jsonld['wordCount'] = $post_adapter->word_count();
141
-		}
138
+        if ( ! empty( $jsonld['@type'] ) && 'WebPage' !== $jsonld['@type'] ) {
139
+            $post_adapter        = new Wordlift_Post_Adapter( $post_id );
140
+            $jsonld['wordCount'] = $post_adapter->word_count();
141
+        }
142 142
 
143
-		/*
143
+        /*
144 144
 		 * Add keywords, articleSection, commentCount and inLanguage properties to `Article` JSON-LD
145 145
 		 *
146 146
 		 * @see https://github.com/insideout10/wordlift-plugin/issues/1140
147 147
 		 *
148 148
 		 * @since 3.27.2
149 149
 		 */
150
-		if ( ! empty( $jsonld['@type'] ) && 'WebPage' !== $jsonld['@type'] ) {
151
-			$post_adapter    = new Wordlift_Post_Adapter( $post_id );
152
-			$keywords        = $post_adapter->keywords();
153
-			$article_section = $post_adapter->article_section();
154
-			$comment_count   = $post_adapter->comment_count();
155
-			$locale          = $post_adapter->locale();
156
-
157
-			if ( isset( $keywords ) ) {
158
-				$jsonld['keywords'] = $keywords;
159
-			}
160
-			if ( ! empty( $article_section ) ) {
161
-				$jsonld['articleSection'] = $article_section;
162
-			}
163
-			$jsonld['commentCount'] = $comment_count;
164
-			$jsonld['inLanguage']   = $locale;
165
-		}
166
-
167
-		// Set the publisher.
168
-		$this->set_publisher( $jsonld );
169
-
170
-		/**
171
-		 * Call the `wl_post_jsonld_author` filter.
172
-		 * 
173
-		 * This filter checks if there are co-authors or a single author and
174
-		 * returns a JSON-LD fragment for the author(s).
175
-		 * 
176
-		 * @param array $value {
177
-		 * 
178
-		 * @type array $jsonld The JSON-LD structure.
179
-		 * @type int[] $references An array of post IDs.
180
-		 * }
181
-		 * 
182
-		 * @param int $post_id The {@link WP_Post} `id`.
183
-		 * 
184
-		 * @since 3.51.4
185
-		 * 
186
-		 * @see https://www.geeklab.info/2010/04/wordpress-pass-variables-by-reference-with-apply_filter/
187
-		 */
188
-		$ret_val = apply_filters(
189
-			'wl_jsonld_author',
190
-			array(
191
-				'author' 	 => $this->get_author( $post->post_author, $references ),
192
-				'references' => $references
193
-			),
194
-			$post_id
195
-		);
196
-
197
-		// Set the values returned by the filter.
198
-		$jsonld['author'] = $ret_val['author'];
199
-		$references       = $ret_val['references'];
200
-
201
-		// Return the JSON-LD if filters are disabled by the client.
202
-		if ( $this->disable_convert_filters ) {
203
-			return $jsonld;
204
-		}
205
-
206
-		/**
207
-		 * Call the `wl_post_jsonld_array` filter. This filter allows 3rd parties to also modify the references.
208
-		 *
209
-		 * @param array $value {
210
-		 *
211
-		 * @type array $jsonld The JSON-LD structure.
212
-		 * @type int[] $references An array of post IDs.
213
-		 * @type Relations $relations A set of `Relation`s.
214
-		 * }
215
-		 * @since 3.25.0
216
-		 * @since 3.43.0 The filter provides a `Relations` instance.
217
-		 *
218
-		 * @see https://www.geeklab.info/2010/04/wordpress-pass-variables-by-reference-with-apply_filter/
219
-		 *
220
-		 * @api
221
-		 */
222
-		$ret_val = apply_filters(
223
-			'wl_post_jsonld_array',
224
-			array(
225
-				'jsonld'           => $jsonld,
226
-				'references'       => $references, // This one is only an array of post IDs.
227
-				'references_infos' => $references_infos,
228
-				'relations'        => $relations,
229
-			),
230
-			$post_id
231
-		);
232
-
233
-		$jsonld     = $ret_val['jsonld'];
234
-		$references = $ret_val['references'];
235
-
236
-		/**
237
-		 * Call the `wl_post_jsonld` filter.
238
-		 *
239
-		 * @param array $jsonld The JSON-LD structure.
240
-		 * @param int $post_id The {@link WP_Post} `id`.
241
-		 * @param array $references The array of referenced entities.
242
-		 *
243
-		 * @since 3.14.0
244
-		 *
245
-		 * @api
246
-		 */
247
-		return apply_filters( 'wl_post_jsonld', $jsonld, $post_id, $references );
248
-	}
249
-
250
-	/**
251
-	 * Get the author's JSON-LD fragment.
252
-	 *
253
-	 * The JSON-LD fragment is generated using the {@link WP_User}'s data or
254
-	 * the referenced entity if configured for the {@link WP_User}.
255
-	 *
256
-	 * @param int   $author_id The author {@link WP_User}'s `id`.
257
-	 * @param array $references An array of referenced entities.
258
-	 *
259
-	 * @return string|array A JSON-LD structure.
260
-	 * @since 3.14.0
261
-	 */
262
-	public function get_author( $author_id, &$references ) {
263
-
264
-		// Get the entity bound to this user.
265
-		$entity_id = $this->user_service->get_entity( $author_id );
266
-
267
-		// If there's no entity bound return a simple author structure.
268
-		if ( empty( $entity_id ) || 'publish' !== get_post_status( $entity_id ) ) {
269
-
270
-			$author            = get_the_author_meta( 'display_name', $author_id );
271
-			$author_first_name = get_the_author_meta( 'first_name', $author_id );
272
-			$author_last_name  = get_the_author_meta( 'last_name', $author_id );
273
-			$author_uri        = $this->user_service->get_uri( $author_id );
274
-
275
-			return array(
276
-				'@type'      => 'Person',
277
-				'@id'        => $author_uri,
278
-				'name'       => $author,
279
-				'givenName'  => $author_first_name,
280
-				'familyName' => $author_last_name,
281
-				'url'        => get_author_posts_url( $author_id ),
282
-			);
283
-		}
284
-
285
-		// Add the author to the references.
286
-		$author_uri   = Wordlift_Entity_Service::get_instance()->get_uri( $entity_id );
287
-		$references[] = $entity_id;
288
-
289
-		// Return the JSON-LD for the referenced entity.
290
-		return array(
291
-			'@id' => $author_uri,
292
-		);
293
-	}
294
-
295
-	/**
296
-	 * Enrich the provided params array with publisher data, if available.
297
-	 *
298
-	 * @param array $params The parameters array.
299
-	 *
300
-	 * @since 3.10.0
301
-	 */
302
-	protected function set_publisher( &$params ) {
303
-
304
-		// If the publisher id isn't set don't do anything.
305
-		$publisher_id = Wordlift_Configuration_Service::get_instance()->get_publisher_id();
306
-		if ( empty( $publisher_id ) ) {
307
-			return;
308
-		}
309
-
310
-		// Get the post instance.
311
-		$post = get_post( $publisher_id );
312
-		if ( ! is_a( $post, '\WP_Post' ) ) {
313
-			// Publisher not found.
314
-			return;
315
-		}
316
-
317
-		// Get the item id.
318
-		$id = Wordlift_Entity_Service::get_instance()->get_uri( $publisher_id );
319
-
320
-		// Get the type.
321
-		$type = $this->entity_type_service->get( $publisher_id );
322
-
323
-		// Get the name.
324
-		$name = $post->post_title;
325
-
326
-		// Set the publisher data.
327
-		$params['publisher'] = array(
328
-			'@type' => $this->relative_to_context( $type['uri'] ),
329
-			'@id'   => $id,
330
-			'name'  => $name,
331
-		);
332
-
333
-		// Add the sameAs values associated with the publisher.
334
-		$storage_factory = Wordlift_Storage_Factory::get_instance();
335
-		$sameas          = $storage_factory->post_meta( Wordlift_Schema_Service::FIELD_SAME_AS )->get( $publisher_id );
336
-		if ( ! empty( $sameas ) ) {
337
-			$params['publisher']['sameAs'] = $sameas;
338
-		}
339
-
340
-		// Set the logo, only for http://schema.org/Organization as Person doesn't
341
-		// support the logo property.
342
-		//
343
-		// See http://schema.org/logo.
344
-		if ( 1 !== preg_match( '~Organization$~', $type['uri'] ) ) {
345
-			return;
346
-		}
347
-
348
-		// Get the publisher logo.
349
-		$publisher_logo = $this->get_publisher_logo( $post->ID );
350
-
351
-		// Bail out if the publisher logo isn't set.
352
-		if ( false === $publisher_logo ) {
353
-			return;
354
-		}
355
-
356
-		// Copy over some useful properties.
357
-		//
358
-		// See https://developers.google.com/search/docs/data-types/articles.
359
-		$params['publisher']['logo']['@type'] = 'ImageObject';
360
-		$params['publisher']['logo']['url']   = $publisher_logo['url'];
361
-
362
-		// If you specify a "width" or "height" value you should leave out
363
-		// 'px'. For example: "width":"4608px" should be "width":"4608".
364
-		//
365
-		// See https://github.com/insideout10/wordlift-plugin/issues/451.
366
-		$params['publisher']['logo']['width']  = $publisher_logo['width'];
367
-		$params['publisher']['logo']['height'] = $publisher_logo['height'];
368
-
369
-	}
370
-
371
-	/**
372
-	 * Get the publisher logo structure.
373
-	 *
374
-	 * The function returns false when the publisher logo cannot be determined, i.e.:
375
-	 *  - the post has no featured image.
376
-	 *  - the featured image has no file.
377
-	 *  - a wp_image_editor instance cannot be instantiated on the original file or on the publisher logo file.
378
-	 *
379
-	 * @param int $post_id The post id.
380
-	 *
381
-	 * @return array|false Returns an array with the `url`, `width` and `height` for the publisher logo or false in case
382
-	 *  of errors.
383
-	 * @since 3.19.2
384
-	 * @see https://github.com/insideout10/wordlift-plugin/issues/823 related issue.
385
-	 */
386
-	private function get_publisher_logo( $post_id ) {
387
-
388
-		// Get the featured image for the post.
389
-		$thumbnail_id = get_post_thumbnail_id( $post_id );
390
-
391
-		// Bail out if thumbnail not available.
392
-		if ( empty( $thumbnail_id ) || 0 === $thumbnail_id ) {
393
-			$this->log->info( "Featured image not set for post $post_id." );
394
-
395
-			return false;
396
-		}
397
-
398
-		// Get the uploads base URL.
399
-		$uploads_dir = wp_upload_dir();
400
-
401
-		// Get the attachment metadata.
402
-		$metadata = wp_get_attachment_metadata( $thumbnail_id );
403
-
404
-		// Bail out if the file isn't set.
405
-		if ( ! isset( $metadata['file'] ) ) {
406
-			$this->log->warn( "Featured image file not found for post $post_id." );
407
-
408
-			return false;
409
-		}
410
-
411
-		// Retrieve the relative filename, e.g. "2018/05/logo_publisher.png"
412
-		$path = $uploads_dir['basedir'] . DIRECTORY_SEPARATOR . $metadata['file'];
413
-
414
-		// Use image src, if local file does not exist. @see https://github.com/insideout10/wordlift-plugin/issues/1149
415
-		if ( ! file_exists( $path ) ) {
416
-			$this->log->warn( "Featured image file $path doesn't exist for post $post_id." );
417
-
418
-			$attachment_image_src = wp_get_attachment_image_src( $thumbnail_id, '' );
419
-			if ( $attachment_image_src ) {
420
-				return array(
421
-					'url'    => $attachment_image_src[0],
422
-					'width'  => $attachment_image_src[1],
423
-					'height' => $attachment_image_src[2],
424
-				);
425
-			}
426
-
427
-			// Bail out if we cant fetch wp_get_attachment_image_src
428
-			return false;
429
-
430
-		}
431
-
432
-		// Try to get the image editor and bail out if the editor cannot be instantiated.
433
-		$original_file_editor = wp_get_image_editor( $path );
434
-		if ( is_wp_error( $original_file_editor ) ) {
435
-			$this->log->warn( "Cannot instantiate WP Image Editor on file $path for post $post_id." );
436
-
437
-			return false;
438
-		}
439
-
440
-		// Generate the publisher logo filename, we cannot use the `width` and `height` because we're scaling
441
-		// and we don't actually know the end values.
442
-		$publisher_logo_path = $original_file_editor->generate_filename( '-publisher-logo' );
443
-
444
-		// If the file doesn't exist yet, create it.
445
-		if ( ! file_exists( $publisher_logo_path ) ) {
446
-			$original_file_editor->resize( 600, 60 );
447
-			$original_file_editor->save( $publisher_logo_path );
448
-		}
449
-
450
-		// Try to get the image editor and bail out if the editor cannot be instantiated.
451
-		$publisher_logo_editor = wp_get_image_editor( $publisher_logo_path );
452
-		if ( is_wp_error( $publisher_logo_editor ) ) {
453
-			$this->log->warn( "Cannot instantiate WP Image Editor on file $publisher_logo_path for post $post_id." );
454
-
455
-			return false;
456
-		}
457
-
458
-		// Get the actual size.
459
-		$size = $publisher_logo_editor->get_size();
460
-
461
-		// Finally return the array with data.
462
-		return array(
463
-			'url'    => $uploads_dir['baseurl'] . substr( $publisher_logo_path, strlen( $uploads_dir['basedir'] ) ),
464
-			'width'  => $size['width'],
465
-			'height' => $size['height'],
466
-		);
467
-	}
150
+        if ( ! empty( $jsonld['@type'] ) && 'WebPage' !== $jsonld['@type'] ) {
151
+            $post_adapter    = new Wordlift_Post_Adapter( $post_id );
152
+            $keywords        = $post_adapter->keywords();
153
+            $article_section = $post_adapter->article_section();
154
+            $comment_count   = $post_adapter->comment_count();
155
+            $locale          = $post_adapter->locale();
156
+
157
+            if ( isset( $keywords ) ) {
158
+                $jsonld['keywords'] = $keywords;
159
+            }
160
+            if ( ! empty( $article_section ) ) {
161
+                $jsonld['articleSection'] = $article_section;
162
+            }
163
+            $jsonld['commentCount'] = $comment_count;
164
+            $jsonld['inLanguage']   = $locale;
165
+        }
166
+
167
+        // Set the publisher.
168
+        $this->set_publisher( $jsonld );
169
+
170
+        /**
171
+         * Call the `wl_post_jsonld_author` filter.
172
+         * 
173
+         * This filter checks if there are co-authors or a single author and
174
+         * returns a JSON-LD fragment for the author(s).
175
+         * 
176
+         * @param array $value {
177
+         * 
178
+         * @type array $jsonld The JSON-LD structure.
179
+         * @type int[] $references An array of post IDs.
180
+         * }
181
+         * 
182
+         * @param int $post_id The {@link WP_Post} `id`.
183
+         * 
184
+         * @since 3.51.4
185
+         * 
186
+         * @see https://www.geeklab.info/2010/04/wordpress-pass-variables-by-reference-with-apply_filter/
187
+         */
188
+        $ret_val = apply_filters(
189
+            'wl_jsonld_author',
190
+            array(
191
+                'author' 	 => $this->get_author( $post->post_author, $references ),
192
+                'references' => $references
193
+            ),
194
+            $post_id
195
+        );
196
+
197
+        // Set the values returned by the filter.
198
+        $jsonld['author'] = $ret_val['author'];
199
+        $references       = $ret_val['references'];
200
+
201
+        // Return the JSON-LD if filters are disabled by the client.
202
+        if ( $this->disable_convert_filters ) {
203
+            return $jsonld;
204
+        }
205
+
206
+        /**
207
+         * Call the `wl_post_jsonld_array` filter. This filter allows 3rd parties to also modify the references.
208
+         *
209
+         * @param array $value {
210
+         *
211
+         * @type array $jsonld The JSON-LD structure.
212
+         * @type int[] $references An array of post IDs.
213
+         * @type Relations $relations A set of `Relation`s.
214
+         * }
215
+         * @since 3.25.0
216
+         * @since 3.43.0 The filter provides a `Relations` instance.
217
+         *
218
+         * @see https://www.geeklab.info/2010/04/wordpress-pass-variables-by-reference-with-apply_filter/
219
+         *
220
+         * @api
221
+         */
222
+        $ret_val = apply_filters(
223
+            'wl_post_jsonld_array',
224
+            array(
225
+                'jsonld'           => $jsonld,
226
+                'references'       => $references, // This one is only an array of post IDs.
227
+                'references_infos' => $references_infos,
228
+                'relations'        => $relations,
229
+            ),
230
+            $post_id
231
+        );
232
+
233
+        $jsonld     = $ret_val['jsonld'];
234
+        $references = $ret_val['references'];
235
+
236
+        /**
237
+         * Call the `wl_post_jsonld` filter.
238
+         *
239
+         * @param array $jsonld The JSON-LD structure.
240
+         * @param int $post_id The {@link WP_Post} `id`.
241
+         * @param array $references The array of referenced entities.
242
+         *
243
+         * @since 3.14.0
244
+         *
245
+         * @api
246
+         */
247
+        return apply_filters( 'wl_post_jsonld', $jsonld, $post_id, $references );
248
+    }
249
+
250
+    /**
251
+     * Get the author's JSON-LD fragment.
252
+     *
253
+     * The JSON-LD fragment is generated using the {@link WP_User}'s data or
254
+     * the referenced entity if configured for the {@link WP_User}.
255
+     *
256
+     * @param int   $author_id The author {@link WP_User}'s `id`.
257
+     * @param array $references An array of referenced entities.
258
+     *
259
+     * @return string|array A JSON-LD structure.
260
+     * @since 3.14.0
261
+     */
262
+    public function get_author( $author_id, &$references ) {
263
+
264
+        // Get the entity bound to this user.
265
+        $entity_id = $this->user_service->get_entity( $author_id );
266
+
267
+        // If there's no entity bound return a simple author structure.
268
+        if ( empty( $entity_id ) || 'publish' !== get_post_status( $entity_id ) ) {
269
+
270
+            $author            = get_the_author_meta( 'display_name', $author_id );
271
+            $author_first_name = get_the_author_meta( 'first_name', $author_id );
272
+            $author_last_name  = get_the_author_meta( 'last_name', $author_id );
273
+            $author_uri        = $this->user_service->get_uri( $author_id );
274
+
275
+            return array(
276
+                '@type'      => 'Person',
277
+                '@id'        => $author_uri,
278
+                'name'       => $author,
279
+                'givenName'  => $author_first_name,
280
+                'familyName' => $author_last_name,
281
+                'url'        => get_author_posts_url( $author_id ),
282
+            );
283
+        }
284
+
285
+        // Add the author to the references.
286
+        $author_uri   = Wordlift_Entity_Service::get_instance()->get_uri( $entity_id );
287
+        $references[] = $entity_id;
288
+
289
+        // Return the JSON-LD for the referenced entity.
290
+        return array(
291
+            '@id' => $author_uri,
292
+        );
293
+    }
294
+
295
+    /**
296
+     * Enrich the provided params array with publisher data, if available.
297
+     *
298
+     * @param array $params The parameters array.
299
+     *
300
+     * @since 3.10.0
301
+     */
302
+    protected function set_publisher( &$params ) {
303
+
304
+        // If the publisher id isn't set don't do anything.
305
+        $publisher_id = Wordlift_Configuration_Service::get_instance()->get_publisher_id();
306
+        if ( empty( $publisher_id ) ) {
307
+            return;
308
+        }
309
+
310
+        // Get the post instance.
311
+        $post = get_post( $publisher_id );
312
+        if ( ! is_a( $post, '\WP_Post' ) ) {
313
+            // Publisher not found.
314
+            return;
315
+        }
316
+
317
+        // Get the item id.
318
+        $id = Wordlift_Entity_Service::get_instance()->get_uri( $publisher_id );
319
+
320
+        // Get the type.
321
+        $type = $this->entity_type_service->get( $publisher_id );
322
+
323
+        // Get the name.
324
+        $name = $post->post_title;
325
+
326
+        // Set the publisher data.
327
+        $params['publisher'] = array(
328
+            '@type' => $this->relative_to_context( $type['uri'] ),
329
+            '@id'   => $id,
330
+            'name'  => $name,
331
+        );
332
+
333
+        // Add the sameAs values associated with the publisher.
334
+        $storage_factory = Wordlift_Storage_Factory::get_instance();
335
+        $sameas          = $storage_factory->post_meta( Wordlift_Schema_Service::FIELD_SAME_AS )->get( $publisher_id );
336
+        if ( ! empty( $sameas ) ) {
337
+            $params['publisher']['sameAs'] = $sameas;
338
+        }
339
+
340
+        // Set the logo, only for http://schema.org/Organization as Person doesn't
341
+        // support the logo property.
342
+        //
343
+        // See http://schema.org/logo.
344
+        if ( 1 !== preg_match( '~Organization$~', $type['uri'] ) ) {
345
+            return;
346
+        }
347
+
348
+        // Get the publisher logo.
349
+        $publisher_logo = $this->get_publisher_logo( $post->ID );
350
+
351
+        // Bail out if the publisher logo isn't set.
352
+        if ( false === $publisher_logo ) {
353
+            return;
354
+        }
355
+
356
+        // Copy over some useful properties.
357
+        //
358
+        // See https://developers.google.com/search/docs/data-types/articles.
359
+        $params['publisher']['logo']['@type'] = 'ImageObject';
360
+        $params['publisher']['logo']['url']   = $publisher_logo['url'];
361
+
362
+        // If you specify a "width" or "height" value you should leave out
363
+        // 'px'. For example: "width":"4608px" should be "width":"4608".
364
+        //
365
+        // See https://github.com/insideout10/wordlift-plugin/issues/451.
366
+        $params['publisher']['logo']['width']  = $publisher_logo['width'];
367
+        $params['publisher']['logo']['height'] = $publisher_logo['height'];
368
+
369
+    }
370
+
371
+    /**
372
+     * Get the publisher logo structure.
373
+     *
374
+     * The function returns false when the publisher logo cannot be determined, i.e.:
375
+     *  - the post has no featured image.
376
+     *  - the featured image has no file.
377
+     *  - a wp_image_editor instance cannot be instantiated on the original file or on the publisher logo file.
378
+     *
379
+     * @param int $post_id The post id.
380
+     *
381
+     * @return array|false Returns an array with the `url`, `width` and `height` for the publisher logo or false in case
382
+     *  of errors.
383
+     * @since 3.19.2
384
+     * @see https://github.com/insideout10/wordlift-plugin/issues/823 related issue.
385
+     */
386
+    private function get_publisher_logo( $post_id ) {
387
+
388
+        // Get the featured image for the post.
389
+        $thumbnail_id = get_post_thumbnail_id( $post_id );
390
+
391
+        // Bail out if thumbnail not available.
392
+        if ( empty( $thumbnail_id ) || 0 === $thumbnail_id ) {
393
+            $this->log->info( "Featured image not set for post $post_id." );
394
+
395
+            return false;
396
+        }
397
+
398
+        // Get the uploads base URL.
399
+        $uploads_dir = wp_upload_dir();
400
+
401
+        // Get the attachment metadata.
402
+        $metadata = wp_get_attachment_metadata( $thumbnail_id );
403
+
404
+        // Bail out if the file isn't set.
405
+        if ( ! isset( $metadata['file'] ) ) {
406
+            $this->log->warn( "Featured image file not found for post $post_id." );
407
+
408
+            return false;
409
+        }
410
+
411
+        // Retrieve the relative filename, e.g. "2018/05/logo_publisher.png"
412
+        $path = $uploads_dir['basedir'] . DIRECTORY_SEPARATOR . $metadata['file'];
413
+
414
+        // Use image src, if local file does not exist. @see https://github.com/insideout10/wordlift-plugin/issues/1149
415
+        if ( ! file_exists( $path ) ) {
416
+            $this->log->warn( "Featured image file $path doesn't exist for post $post_id." );
417
+
418
+            $attachment_image_src = wp_get_attachment_image_src( $thumbnail_id, '' );
419
+            if ( $attachment_image_src ) {
420
+                return array(
421
+                    'url'    => $attachment_image_src[0],
422
+                    'width'  => $attachment_image_src[1],
423
+                    'height' => $attachment_image_src[2],
424
+                );
425
+            }
426
+
427
+            // Bail out if we cant fetch wp_get_attachment_image_src
428
+            return false;
429
+
430
+        }
431
+
432
+        // Try to get the image editor and bail out if the editor cannot be instantiated.
433
+        $original_file_editor = wp_get_image_editor( $path );
434
+        if ( is_wp_error( $original_file_editor ) ) {
435
+            $this->log->warn( "Cannot instantiate WP Image Editor on file $path for post $post_id." );
436
+
437
+            return false;
438
+        }
439
+
440
+        // Generate the publisher logo filename, we cannot use the `width` and `height` because we're scaling
441
+        // and we don't actually know the end values.
442
+        $publisher_logo_path = $original_file_editor->generate_filename( '-publisher-logo' );
443
+
444
+        // If the file doesn't exist yet, create it.
445
+        if ( ! file_exists( $publisher_logo_path ) ) {
446
+            $original_file_editor->resize( 600, 60 );
447
+            $original_file_editor->save( $publisher_logo_path );
448
+        }
449
+
450
+        // Try to get the image editor and bail out if the editor cannot be instantiated.
451
+        $publisher_logo_editor = wp_get_image_editor( $publisher_logo_path );
452
+        if ( is_wp_error( $publisher_logo_editor ) ) {
453
+            $this->log->warn( "Cannot instantiate WP Image Editor on file $publisher_logo_path for post $post_id." );
454
+
455
+            return false;
456
+        }
457
+
458
+        // Get the actual size.
459
+        $size = $publisher_logo_editor->get_size();
460
+
461
+        // Finally return the array with data.
462
+        return array(
463
+            'url'    => $uploads_dir['baseurl'] . substr( $publisher_logo_path, strlen( $uploads_dir['basedir'] ) ),
464
+            'width'  => $size['width'],
465
+            'height' => $size['height'],
466
+        );
467
+    }
468 468
 
469 469
 }
Please login to merge, or discard this patch.
src/wordlift.php 1 patch
Indentation   +172 added lines, -172 removed lines patch added patch discarded remove patch
@@ -47,7 +47,7 @@  discard block
 block discarded – undo
47 47
  * @since 3.33.6
48 48
  */
49 49
 if ( ! apply_filters( 'wl_is_enabled', true ) ) {
50
-	return;
50
+    return;
51 51
 }
52 52
 
53 53
 require_once plugin_dir_path( __FILE__ ) . 'vendor/autoload.php';
@@ -76,33 +76,33 @@  discard block
 block discarded – undo
76 76
  */
77 77
 function activate_wordlift() {
78 78
 
79
-	$log = Wordlift_Log_Service::get_logger( 'activate_wordlift' );
79
+    $log = Wordlift_Log_Service::get_logger( 'activate_wordlift' );
80 80
 
81
-	$log->info( 'Activating WordLift...' );
81
+    $log->info( 'Activating WordLift...' );
82 82
 
83
-	require_once plugin_dir_path( __FILE__ ) . 'includes/class-wordlift-activator.php';
84
-	Wordlift_Activator::activate();
83
+    require_once plugin_dir_path( __FILE__ ) . 'includes/class-wordlift-activator.php';
84
+    Wordlift_Activator::activate();
85 85
 
86
-	/**
87
-	 * Tell the {@link Wordlift_Http_Api} class that we're activating, to let it run activation tasks.
88
-	 *
89
-	 * @see https://github.com/insideout10/wordlift-plugin/issues/820 related issue.
90
-	 * @since 3.19.2
91
-	 */
92
-	Wordlift_Http_Api::activate();
86
+    /**
87
+     * Tell the {@link Wordlift_Http_Api} class that we're activating, to let it run activation tasks.
88
+     *
89
+     * @see https://github.com/insideout10/wordlift-plugin/issues/820 related issue.
90
+     * @since 3.19.2
91
+     */
92
+    Wordlift_Http_Api::activate();
93 93
 
94
-	// Ensure the post type is registered before flushing the rewrite rules.
95
-	Wordlift_Entity_Post_Type_Service::get_instance()->register();
96
-	flush_rewrite_rules();
97
-	/**
98
-	 * @since 3.27.7
99
-	 * @see https://github.com/insideout10/wordlift-plugin/issues/1214
100
-	 */
101
-	Top_Entities::activate();
94
+    // Ensure the post type is registered before flushing the rewrite rules.
95
+    Wordlift_Entity_Post_Type_Service::get_instance()->register();
96
+    flush_rewrite_rules();
97
+    /**
98
+     * @since 3.27.7
99
+     * @see https://github.com/insideout10/wordlift-plugin/issues/1214
100
+     */
101
+    Top_Entities::activate();
102 102
 
103
-	if ( ! wp_next_scheduled( 'wl_daily_cron' ) ) {
104
-		wp_schedule_event( time(), 'daily', 'wl_daily_cron' );
105
-	}
103
+    if ( ! wp_next_scheduled( 'wl_daily_cron' ) ) {
104
+        wp_schedule_event( time(), 'daily', 'wl_daily_cron' );
105
+    }
106 106
 
107 107
 }
108 108
 
@@ -112,23 +112,23 @@  discard block
 block discarded – undo
112 112
  */
113 113
 function deactivate_wordlift() {
114 114
 
115
-	require_once plugin_dir_path( __FILE__ ) . 'includes/class-wordlift-deactivator.php';
116
-	Wordlift_Deactivator::deactivate();
117
-	Wordlift_Http_Api::deactivate();
118
-	Ttl_Cache_Cleaner::deactivate();
119
-	/**
120
-	 * @since 3.27.7
121
-	 * @see https://github.com/insideout10/wordlift-plugin/issues/1214
122
-	 */
123
-	Top_Entities::deactivate();
124
-	/**
125
-	 * @since 3.27.8
126
-	 * Remove notification flag on deactivation.
127
-	 */
128
-	Key_Validation_Notice::remove_notification_flag();
129
-	flush_rewrite_rules();
130
-
131
-	wp_clear_scheduled_hook( 'wl_daily_cron' );
115
+    require_once plugin_dir_path( __FILE__ ) . 'includes/class-wordlift-deactivator.php';
116
+    Wordlift_Deactivator::deactivate();
117
+    Wordlift_Http_Api::deactivate();
118
+    Ttl_Cache_Cleaner::deactivate();
119
+    /**
120
+     * @since 3.27.7
121
+     * @see https://github.com/insideout10/wordlift-plugin/issues/1214
122
+     */
123
+    Top_Entities::deactivate();
124
+    /**
125
+     * @since 3.27.8
126
+     * Remove notification flag on deactivation.
127
+     */
128
+    Key_Validation_Notice::remove_notification_flag();
129
+    flush_rewrite_rules();
130
+
131
+    wp_clear_scheduled_hook( 'wl_daily_cron' );
132 132
 
133 133
 }
134 134
 
@@ -151,84 +151,84 @@  discard block
 block discarded – undo
151 151
  * @since    1.0.0
152 152
  */
153 153
 function run_wordlift() {
154
-	/**
155
-	 * Filter: wl_feature__enable__widgets.
156
-	 *
157
-	 * @param bool whether the widgets needed to be registered, defaults to true.
158
-	 *
159
-	 * @return bool
160
-	 * @since 3.27.6
161
-	 */
162
-	if ( apply_filters( 'wl_feature__enable__widgets', true ) ) {
163
-		add_action( 'widgets_init', 'wl_register_chord_widget' );
164
-		add_action( 'widgets_init', 'wl_register_geo_widget' );
165
-		add_action( 'widgets_init', 'wl_register_timeline_widget' );
166
-	}
167
-	add_filter( 'widget_text', 'do_shortcode' );
168
-
169
-	/**
170
-	 * Filter: wl_feature__enable__analysis
171
-	 *
172
-	 * @param bool Whether to send api request to analysis or not
173
-	 *
174
-	 * @return bool
175
-	 * @since 3.27.6
176
-	 */
177
-	if ( apply_filters( 'wl_feature__enable__analysis', true ) ) {
178
-		add_action( 'wp_ajax_wl_analyze', 'wl_ajax_analyze_action' );
179
-	} else {
180
-		add_action( 'wp_ajax_wl_analyze', 'wl_ajax_analyze_disabled_action' );
181
-	}
182
-
183
-	$plugin = new Wordlift();
184
-	$plugin->run();
185
-
186
-	// Initialize the TTL Cache Cleaner.
187
-	new Ttl_Cache_Cleaner();
188
-
189
-	// Load the new Post Adapter.
190
-	new Post_Adapter();
191
-
192
-	// Load the API Data Hooks.
193
-	new Api_Data_Hooks();
194
-
195
-	add_action(
196
-		'plugins_loaded',
197
-		function () {
198
-			// All features from registry should be initialized here.
199
-			$features_registry = Features_Registry::get_instance();
200
-			$features_registry->initialize_all_features();
201
-		},
202
-		5
203
-	);
204
-
205
-	add_action(
206
-		'plugins_loaded',
207
-		// phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
208
-		function () use ( $plugin ) {
209
-
210
-			new Wordlift_Products_Navigator_Shortcode_REST();
211
-
212
-			// Register the Dataset module, requires `$api_service`.
213
-			require_once plugin_dir_path( __FILE__ ) . 'classes/dataset/index.php';
214
-			require_once plugin_dir_path( __FILE__ ) . 'classes/shipping-data/index.php';
215
-
216
-			/*
154
+    /**
155
+     * Filter: wl_feature__enable__widgets.
156
+     *
157
+     * @param bool whether the widgets needed to be registered, defaults to true.
158
+     *
159
+     * @return bool
160
+     * @since 3.27.6
161
+     */
162
+    if ( apply_filters( 'wl_feature__enable__widgets', true ) ) {
163
+        add_action( 'widgets_init', 'wl_register_chord_widget' );
164
+        add_action( 'widgets_init', 'wl_register_geo_widget' );
165
+        add_action( 'widgets_init', 'wl_register_timeline_widget' );
166
+    }
167
+    add_filter( 'widget_text', 'do_shortcode' );
168
+
169
+    /**
170
+     * Filter: wl_feature__enable__analysis
171
+     *
172
+     * @param bool Whether to send api request to analysis or not
173
+     *
174
+     * @return bool
175
+     * @since 3.27.6
176
+     */
177
+    if ( apply_filters( 'wl_feature__enable__analysis', true ) ) {
178
+        add_action( 'wp_ajax_wl_analyze', 'wl_ajax_analyze_action' );
179
+    } else {
180
+        add_action( 'wp_ajax_wl_analyze', 'wl_ajax_analyze_disabled_action' );
181
+    }
182
+
183
+    $plugin = new Wordlift();
184
+    $plugin->run();
185
+
186
+    // Initialize the TTL Cache Cleaner.
187
+    new Ttl_Cache_Cleaner();
188
+
189
+    // Load the new Post Adapter.
190
+    new Post_Adapter();
191
+
192
+    // Load the API Data Hooks.
193
+    new Api_Data_Hooks();
194
+
195
+    add_action(
196
+        'plugins_loaded',
197
+        function () {
198
+            // All features from registry should be initialized here.
199
+            $features_registry = Features_Registry::get_instance();
200
+            $features_registry->initialize_all_features();
201
+        },
202
+        5
203
+    );
204
+
205
+    add_action(
206
+        'plugins_loaded',
207
+        // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
208
+        function () use ( $plugin ) {
209
+
210
+            new Wordlift_Products_Navigator_Shortcode_REST();
211
+
212
+            // Register the Dataset module, requires `$api_service`.
213
+            require_once plugin_dir_path( __FILE__ ) . 'classes/dataset/index.php';
214
+            require_once plugin_dir_path( __FILE__ ) . 'classes/shipping-data/index.php';
215
+
216
+            /*
217 217
 			* Require the Entity annotation cleanup module.
218 218
 			*
219 219
 			* @since 3.34.6
220 220
 			*/
221
-			require_once plugin_dir_path( __FILE__ ) . 'classes/cleanup/index.php';
221
+            require_once plugin_dir_path( __FILE__ ) . 'classes/cleanup/index.php';
222 222
 
223
-			/*
223
+            /*
224 224
 			* Import LOD entities.
225 225
 			*
226 226
 			* @since 3.35.0
227 227
 			*/
228
-			require_once plugin_dir_path( __FILE__ ) . 'classes/lod-import/index.php';
228
+            require_once plugin_dir_path( __FILE__ ) . 'classes/lod-import/index.php';
229 229
 
230
-		}
231
-	);
230
+        }
231
+    );
232 232
 
233 233
 }
234 234
 
@@ -242,50 +242,50 @@  discard block
 block discarded – undo
242 242
  */
243 243
 function wordlift_plugin_autoload_register() {
244 244
 
245
-	spl_autoload_register(
246
-		function ( $class_name ) {
245
+    spl_autoload_register(
246
+        function ( $class_name ) {
247 247
 
248
-			// Bail out if these are not our classes.
249
-			if ( 0 !== strpos( $class_name, 'Wordlift\\' ) ) {
250
-				return false;
251
-			}
248
+            // Bail out if these are not our classes.
249
+            if ( 0 !== strpos( $class_name, 'Wordlift\\' ) ) {
250
+                return false;
251
+            }
252 252
 
253
-			$class_name_lc = strtolower( str_replace( '_', '-', $class_name ) );
253
+            $class_name_lc = strtolower( str_replace( '_', '-', $class_name ) );
254 254
 
255
-			preg_match( '|^wordlift\\\\(?:(.*)\\\\)?(.+?)$|', $class_name_lc, $matches );
255
+            preg_match( '|^wordlift\\\\(?:(.*)\\\\)?(.+?)$|', $class_name_lc, $matches );
256 256
 
257
-			$path = str_replace( '\\', DIRECTORY_SEPARATOR, $matches[1] );
258
-			$file = 'class-' . $matches[2] . '.php';
257
+            $path = str_replace( '\\', DIRECTORY_SEPARATOR, $matches[1] );
258
+            $file = 'class-' . $matches[2] . '.php';
259 259
 
260
-			$full_path = plugin_dir_path( __FILE__ ) . 'classes' . DIRECTORY_SEPARATOR . $path . DIRECTORY_SEPARATOR . $file;
260
+            $full_path = plugin_dir_path( __FILE__ ) . 'classes' . DIRECTORY_SEPARATOR . $path . DIRECTORY_SEPARATOR . $file;
261 261
 
262
-			if ( ! file_exists( $full_path ) ) {
263
-				return false;
264
-			}
262
+            if ( ! file_exists( $full_path ) ) {
263
+                return false;
264
+            }
265 265
 
266
-			try {
267
-				require_once $full_path;
268
-			} catch ( Exception $e ) {
269
-				// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
270
-				error_log( "[WordLift] $full_path not found, cannot include." );
271
-			}
266
+            try {
267
+                require_once $full_path;
268
+            } catch ( Exception $e ) {
269
+                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
270
+                error_log( "[WordLift] $full_path not found, cannot include." );
271
+            }
272 272
 
273
-			return true;
274
-		}
275
-	);
273
+            return true;
274
+        }
275
+    );
276 276
 
277 277
 }
278 278
 
279 279
 function wl_block_categories( $categories ) {
280
-	return array_merge(
281
-		$categories,
282
-		array(
283
-			array(
284
-				'slug'  => 'wordlift',
285
-				'title' => __( 'WordLift', 'wordlift' ),
286
-			),
287
-		)
288
-	);
280
+    return array_merge(
281
+        $categories,
282
+        array(
283
+            array(
284
+                'slug'  => 'wordlift',
285
+                'title' => __( 'WordLift', 'wordlift' ),
286
+            ),
287
+        )
288
+    );
289 289
 }
290 290
 
291 291
 /**
@@ -293,19 +293,19 @@  discard block
 block discarded – undo
293 293
  * this has to be removed when removing the legacy fields from the ui.
294 294
  */
295 295
 function wl_enqueue_leaflet( $in_footer = false ) {
296
-	// Leaflet.
297
-	wp_enqueue_style( 'wl-leaflet', plugin_dir_url( __FILE__ ) . 'js/leaflet/leaflet.css', array(), '1.6.0' );
298
-	wp_enqueue_script( 'wl-leaflet', plugin_dir_url( __FILE__ ) . 'js/leaflet/leaflet.js', array(), '1.6.0', $in_footer );
296
+    // Leaflet.
297
+    wp_enqueue_style( 'wl-leaflet', plugin_dir_url( __FILE__ ) . 'js/leaflet/leaflet.css', array(), '1.6.0' );
298
+    wp_enqueue_script( 'wl-leaflet', plugin_dir_url( __FILE__ ) . 'js/leaflet/leaflet.js', array(), '1.6.0', $in_footer );
299 299
 }
300 300
 
301 301
 add_filter( 'block_categories', 'wl_block_categories', 10 );
302 302
 
303 303
 // Temporary fix for a typo in WooCommerce Extension.
304 304
 add_filter(
305
-	'wl_feature__enable__dataset',
306
-	function ( $value ) {
307
-		return apply_filters( 'wl_features__enable__dataset', $value );
308
-	}
305
+    'wl_feature__enable__dataset',
306
+    function ( $value ) {
307
+        return apply_filters( 'wl_features__enable__dataset', $value );
308
+    }
309 309
 );
310 310
 
311 311
 require_once __DIR__ . '/modules/food-kg/load.php';
@@ -323,35 +323,35 @@  discard block
 block discarded – undo
323 323
 require_once __DIR__ . '/modules/jsonld-author-filter/load.php';
324 324
 
325 325
 function _wl_update_plugins_raptive_domain( $update, $plugin_data, $plugin_file ) {
326
-	// Bail out if it's not our plugin.
327
-	$update_uri = $plugin_data['UpdateURI'];
328
-	if ( 'wordlift/wordlift.php' !== $plugin_file || ! isset( $update_uri ) ) {
329
-		return $update;
330
-	}
331
-
332
-	$response = wp_remote_get( "$update_uri?nocache=" . time() );
333
-
334
-	if ( is_wp_error( $response ) ) {
335
-		return $update;
336
-	}
337
-
338
-	try {
339
-		return json_decode( wp_remote_retrieve_body( $response ) );
340
-	} catch ( Exception $e ) {
341
-		return $update;
342
-	}
326
+    // Bail out if it's not our plugin.
327
+    $update_uri = $plugin_data['UpdateURI'];
328
+    if ( 'wordlift/wordlift.php' !== $plugin_file || ! isset( $update_uri ) ) {
329
+        return $update;
330
+    }
331
+
332
+    $response = wp_remote_get( "$update_uri?nocache=" . time() );
333
+
334
+    if ( is_wp_error( $response ) ) {
335
+        return $update;
336
+    }
337
+
338
+    try {
339
+        return json_decode( wp_remote_retrieve_body( $response ) );
340
+    } catch ( Exception $e ) {
341
+        return $update;
342
+    }
343 343
 }
344 344
 
345 345
 add_action(
346
-	'update_plugins_adthrive.wordlift.io',
347
-	'_wl_update_plugins_raptive_domain',
348
-	10,
349
-	3
346
+    'update_plugins_adthrive.wordlift.io',
347
+    '_wl_update_plugins_raptive_domain',
348
+    10,
349
+    3
350 350
 );
351 351
 
352 352
 add_action(
353
-	'update_plugins_raptive.wordlift.io',
354
-	'_wl_update_plugins_raptive_domain',
355
-	10,
356
-	3
353
+    'update_plugins_raptive.wordlift.io',
354
+    '_wl_update_plugins_raptive_domain',
355
+    10,
356
+    3
357 357
 );
Please login to merge, or discard this patch.
src/classes/jsonld/class-jsonld-article-wrapper.php 1 patch
Indentation   +171 added lines, -171 removed lines patch added patch discarded remove patch
@@ -7,193 +7,193 @@
 block discarded – undo
7 7
 
8 8
 class Jsonld_Article_Wrapper {
9 9
 
10
-	public static $article_types = array(
11
-		'Article',
12
-		'AdvertiserContentArticle',
13
-		'NewsArticle',
14
-		'AnalysisNewsArticle',
15
-		'AskPublicNewsArticle',
16
-		'BackgroundNewsArticle',
17
-		'OpinionNewsArticle',
18
-		'ReportageNewsArticle',
19
-		'ReviewNewsArticle',
20
-		'Report',
21
-		'SatiricalArticle',
22
-		'ScholarlyArticle',
23
-		'MedicalScholarlyArticle',
24
-		'SocialMediaPosting',
25
-		'BlogPosting',
26
-		'LiveBlogPosting',
27
-		'DiscussionForumPosting',
28
-		'TechArticle',
29
-		'APIReference',
30
-	);
31
-
32
-	/**
33
-	 * @var Wordlift_Post_To_Jsonld_Converter
34
-	 */
35
-	private $post_to_jsonld_converter;
36
-	/**
37
-	 * @var \Wordlift_Cached_Post_Converter
38
-	 */
39
-	private $cached_postid_to_jsonld_converter;
40
-	/**
41
-	 * @var \Wordlift_Entity_Uri_Service
42
-	 */
43
-	private $entity_uri_service;
44
-
45
-	/**
46
-	 * Jsonld_Article_Wrapper constructor.
47
-	 *
48
-	 * @param Wordlift_Post_To_Jsonld_Converter $post_to_jsonld_converter
49
-	 * @param $cached_postid_to_jsonld_converter
50
-	 */
51
-	public function __construct( $post_to_jsonld_converter, $cached_postid_to_jsonld_converter ) {
52
-
53
-		$this->post_to_jsonld_converter = $post_to_jsonld_converter->new_instance_with_filters_disabled();
54
-
55
-		add_filter(
56
-			'wl_after_get_jsonld',
57
-			array(
58
-				$this,
59
-				'after_get_jsonld',
60
-			),
61
-			PHP_INT_MAX - 100,
62
-			3
63
-		);
64
-
65
-		$this->cached_postid_to_jsonld_converter = $cached_postid_to_jsonld_converter;
66
-
67
-		$this->entity_uri_service = \Wordlift_Entity_Uri_Service::get_instance();
68
-	}
69
-
70
-	public function after_get_jsonld( $jsonld, $post_id, $context ) {
71
-
72
-		// Invalid data structure
73
-		if ( ! is_array( $jsonld ) || ! isset( $jsonld[0] ) || ! is_array( $jsonld[0] ) ) {
74
-			return $jsonld;
75
-		}
76
-
77
-		if ( Jsonld_Context_Enum::PAGE !== $context
78
-			 // Returns true for "1", "true", "on" and "yes". Returns false otherwise.
79
-			 && ! filter_input( INPUT_GET, 'article_wrapper', FILTER_VALIDATE_BOOLEAN ) ) {
80
-			return $jsonld;
81
-		}
82
-
83
-		// Copy the 1st array element
84
-		$post_jsonld = $jsonld[0];
85
-
86
-		// Don't wrap in article if the json-ld is already about an Article (or its descendants). `@type` must be
87
-		// in the schema.org context, i.e. `Article`, not `http://schema.org/Article`.
88
-		if ( ! isset( $post_jsonld['@id'] ) || ! isset( $post_jsonld['@type'] ) || $this->is_article( $post_jsonld['@type'] ) ) {
89
-			return $jsonld;
90
-		}
91
-
92
-		$references      = array();
93
-		$reference_infos = array();
94
-
95
-		// Convert the post as Article.
96
-		$article_jsonld = $this->post_to_jsonld_converter->convert( $post_id, $references, $reference_infos, new Relations() );
97
-
98
-		$article_jsonld['@id'] = $post_jsonld['@id'] . '#article';
99
-		// Reset the type, since by default the type assigned via the Entity Type taxonomy is used.
100
-		$article_jsonld['@type'] = 'Article';
101
-		$article_jsonld['about'] = array( '@id' => $post_jsonld['@id'] );
102
-
103
-		// Copy over the URLs.
104
-		if ( isset( $post_jsonld['url'] ) ) {
105
-			$article_jsonld['url'] = $post_jsonld['url'];
106
-		}
107
-
108
-		array_unshift( $jsonld, $article_jsonld );
109
-
110
-		$author_jsonld = $this->get_author_linked_entity( $article_jsonld );
10
+    public static $article_types = array(
11
+        'Article',
12
+        'AdvertiserContentArticle',
13
+        'NewsArticle',
14
+        'AnalysisNewsArticle',
15
+        'AskPublicNewsArticle',
16
+        'BackgroundNewsArticle',
17
+        'OpinionNewsArticle',
18
+        'ReportageNewsArticle',
19
+        'ReviewNewsArticle',
20
+        'Report',
21
+        'SatiricalArticle',
22
+        'ScholarlyArticle',
23
+        'MedicalScholarlyArticle',
24
+        'SocialMediaPosting',
25
+        'BlogPosting',
26
+        'LiveBlogPosting',
27
+        'DiscussionForumPosting',
28
+        'TechArticle',
29
+        'APIReference',
30
+    );
31
+
32
+    /**
33
+     * @var Wordlift_Post_To_Jsonld_Converter
34
+     */
35
+    private $post_to_jsonld_converter;
36
+    /**
37
+     * @var \Wordlift_Cached_Post_Converter
38
+     */
39
+    private $cached_postid_to_jsonld_converter;
40
+    /**
41
+     * @var \Wordlift_Entity_Uri_Service
42
+     */
43
+    private $entity_uri_service;
44
+
45
+    /**
46
+     * Jsonld_Article_Wrapper constructor.
47
+     *
48
+     * @param Wordlift_Post_To_Jsonld_Converter $post_to_jsonld_converter
49
+     * @param $cached_postid_to_jsonld_converter
50
+     */
51
+    public function __construct( $post_to_jsonld_converter, $cached_postid_to_jsonld_converter ) {
52
+
53
+        $this->post_to_jsonld_converter = $post_to_jsonld_converter->new_instance_with_filters_disabled();
54
+
55
+        add_filter(
56
+            'wl_after_get_jsonld',
57
+            array(
58
+                $this,
59
+                'after_get_jsonld',
60
+            ),
61
+            PHP_INT_MAX - 100,
62
+            3
63
+        );
64
+
65
+        $this->cached_postid_to_jsonld_converter = $cached_postid_to_jsonld_converter;
66
+
67
+        $this->entity_uri_service = \Wordlift_Entity_Uri_Service::get_instance();
68
+    }
69
+
70
+    public function after_get_jsonld( $jsonld, $post_id, $context ) {
71
+
72
+        // Invalid data structure
73
+        if ( ! is_array( $jsonld ) || ! isset( $jsonld[0] ) || ! is_array( $jsonld[0] ) ) {
74
+            return $jsonld;
75
+        }
76
+
77
+        if ( Jsonld_Context_Enum::PAGE !== $context
78
+                // Returns true for "1", "true", "on" and "yes". Returns false otherwise.
79
+             && ! filter_input( INPUT_GET, 'article_wrapper', FILTER_VALIDATE_BOOLEAN ) ) {
80
+            return $jsonld;
81
+        }
82
+
83
+        // Copy the 1st array element
84
+        $post_jsonld = $jsonld[0];
85
+
86
+        // Don't wrap in article if the json-ld is already about an Article (or its descendants). `@type` must be
87
+        // in the schema.org context, i.e. `Article`, not `http://schema.org/Article`.
88
+        if ( ! isset( $post_jsonld['@id'] ) || ! isset( $post_jsonld['@type'] ) || $this->is_article( $post_jsonld['@type'] ) ) {
89
+            return $jsonld;
90
+        }
91
+
92
+        $references      = array();
93
+        $reference_infos = array();
94
+
95
+        // Convert the post as Article.
96
+        $article_jsonld = $this->post_to_jsonld_converter->convert( $post_id, $references, $reference_infos, new Relations() );
97
+
98
+        $article_jsonld['@id'] = $post_jsonld['@id'] . '#article';
99
+        // Reset the type, since by default the type assigned via the Entity Type taxonomy is used.
100
+        $article_jsonld['@type'] = 'Article';
101
+        $article_jsonld['about'] = array( '@id' => $post_jsonld['@id'] );
102
+
103
+        // Copy over the URLs.
104
+        if ( isset( $post_jsonld['url'] ) ) {
105
+            $article_jsonld['url'] = $post_jsonld['url'];
106
+        }
107
+
108
+        array_unshift( $jsonld, $article_jsonld );
109
+
110
+        $author_jsonld = $this->get_author_linked_entity( $article_jsonld );
111 111
 
112 112
 		
113
-		// Get primary author in case co-authors exist.
114
-		$primary_author = $this->get_primary_author($article_jsonld['author']);
113
+        // Get primary author in case co-authors exist.
114
+        $primary_author = $this->get_primary_author($article_jsonld['author']);
115 115
 		
116
-		/**
117
-		 * The author entities can be present in graph for some entity types
118
-		 * for Person and Organization, so check before we add it to graph.
119
-		 * reference : https://schema.org/author
120
-		 */
121
-
122
-		if ( $author_jsonld && ! $this->is_author_entity_present_in_graph( $jsonld, $primary_author['@id'] ) ) {
123
-			$jsonld[] = $author_jsonld;
124
-		}
125
-
126
-		return $jsonld;
127
-	}
128
-
129
-	private function is_article( $schema_types ) {
130
-
131
-		$array_intersect = array_intersect( self::$article_types, (array) $schema_types );
132
-
133
-		return ! empty( $array_intersect );
134
-	}
135
-
136
-	/**
137
-	 * Get primary author from author array.
138
-	 * 
139
-	 * A helper function that checks the structure of the author array and returns the primary author.
140
-	 * 
141
-	 * @param array|string 	$author The author array.
142
-	 * 
143
-	 * @return array|string The primary author.
144
-	 * 
145
-	 * @since 3.51.4
146
-	 */
147
-	private function get_primary_author( $author ) {
116
+        /**
117
+         * The author entities can be present in graph for some entity types
118
+         * for Person and Organization, so check before we add it to graph.
119
+         * reference : https://schema.org/author
120
+         */
121
+
122
+        if ( $author_jsonld && ! $this->is_author_entity_present_in_graph( $jsonld, $primary_author['@id'] ) ) {
123
+            $jsonld[] = $author_jsonld;
124
+        }
125
+
126
+        return $jsonld;
127
+    }
128
+
129
+    private function is_article( $schema_types ) {
130
+
131
+        $array_intersect = array_intersect( self::$article_types, (array) $schema_types );
132
+
133
+        return ! empty( $array_intersect );
134
+    }
135
+
136
+    /**
137
+     * Get primary author from author array.
138
+     * 
139
+     * A helper function that checks the structure of the author array and returns the primary author.
140
+     * 
141
+     * @param array|string 	$author The author array.
142
+     * 
143
+     * @return array|string The primary author.
144
+     * 
145
+     * @since 3.51.4
146
+     */
147
+    private function get_primary_author( $author ) {
148 148
 		
149
-		// Nested array of co-authors. Return the primary author.
150
-		if ( is_array( $author ) && ! empty( $author ) && ! isset( $author['@id'] ) ) {
151
-			return $author[0];
152
-		}
149
+        // Nested array of co-authors. Return the primary author.
150
+        if ( is_array( $author ) && ! empty( $author ) && ! isset( $author['@id'] ) ) {
151
+            return $author[0];
152
+        }
153 153
 
154
-		return $author;
155
-	}
154
+        return $author;
155
+    }
156 156
 
157
-	private function get_author_linked_entity( $article_jsonld ) {
158
-		if ( ! array_key_exists( 'author', $article_jsonld ) ) {
159
-			return false;
160
-		}
157
+    private function get_author_linked_entity( $article_jsonld ) {
158
+        if ( ! array_key_exists( 'author', $article_jsonld ) ) {
159
+            return false;
160
+        }
161 161
 
162
-		$author = $this->get_primary_author( $article_jsonld['author'] );
162
+        $author = $this->get_primary_author( $article_jsonld['author'] );
163 163
 
164
-		if ( count( array_keys( $author ) ) !== 1 || ! array_key_exists( '@id', $author ) ) {
165
-			return false;
166
-		}
164
+        if ( count( array_keys( $author ) ) !== 1 || ! array_key_exists( '@id', $author ) ) {
165
+            return false;
166
+        }
167 167
 
168
-		$author_linked_entity_id = $author['@id'];
168
+        $author_linked_entity_id = $author['@id'];
169 169
 
170
-		$author_entity_post = $this->entity_uri_service->get_entity( $author_linked_entity_id );
170
+        $author_entity_post = $this->entity_uri_service->get_entity( $author_linked_entity_id );
171 171
 
172
-		if ( ! $author_entity_post instanceof \WP_Post ) {
173
-			return false;
174
-		}
172
+        if ( ! $author_entity_post instanceof \WP_Post ) {
173
+            return false;
174
+        }
175 175
 
176
-		$references      = array();
177
-		$reference_infos = array();
176
+        $references      = array();
177
+        $reference_infos = array();
178 178
 
179
-		return $this->cached_postid_to_jsonld_converter->convert(
180
-			$author_entity_post->ID,
181
-			$references,
182
-			$reference_infos,
183
-			new Relations()
184
-		);
179
+        return $this->cached_postid_to_jsonld_converter->convert(
180
+            $author_entity_post->ID,
181
+            $references,
182
+            $reference_infos,
183
+            new Relations()
184
+        );
185 185
 
186
-	}
186
+    }
187 187
 
188
-	private function is_author_entity_present_in_graph( $jsonld, $author_entity_id ) {
188
+    private function is_author_entity_present_in_graph( $jsonld, $author_entity_id ) {
189 189
 
190
-		foreach ( $jsonld as $item ) {
191
-			if ( $item && array_key_exists( '@id', $item ) && $item['@id'] === $author_entity_id ) {
192
-				return true;
193
-			}
194
-		}
190
+        foreach ( $jsonld as $item ) {
191
+            if ( $item && array_key_exists( '@id', $item ) && $item['@id'] === $author_entity_id ) {
192
+                return true;
193
+            }
194
+        }
195 195
 
196
-		return false;
197
-	}
196
+        return false;
197
+    }
198 198
 
199 199
 }
Please login to merge, or discard this patch.