Completed
Push — master ( 587793...0cd805 )
by Naveen
01:22 queued 12s
created
src/includes/class-wordlift-post-to-jsonld-converter.php 2 patches
Indentation   +518 added lines, -518 removed lines patch added patch discarded remove patch
@@ -19,542 +19,542 @@
 block discarded – undo
19 19
  */
20 20
 class Wordlift_Post_To_Jsonld_Converter extends Wordlift_Abstract_Post_To_Jsonld_Converter {
21 21
 
22
-	/**
23
-	 * @var Wordlift_Post_To_Jsonld_Converter
24
-	 */
25
-	private static $instance;
26
-
27
-	/**
28
-	 * A {@link Wordlift_Log_Service} instance.
29
-	 *
30
-	 * @since  3.10.0
31
-	 * @access private
32
-	 * @var Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
33
-	 */
34
-	private $log;
35
-
36
-	/**
37
-	 * @var false
38
-	 */
39
-	private $disable_convert_filters;
40
-	/**
41
-	 * @var Object_Relation_Service
42
-	 */
43
-	private $object_relation_service;
44
-
45
-	/**
46
-	 * Wordlift_Post_To_Jsonld_Converter constructor.
47
-	 *
48
-	 * @param \Wordlift_Entity_Type_Service $entity_type_service A {@link Wordlift_Entity_Type_Service} instance.
49
-	 * @param \Wordlift_User_Service        $user_service A {@link Wordlift_User_Service} instance.
50
-	 * @param \Wordlift_Attachment_Service  $attachment_service A {@link Wordlift_Attachment_Service} instance.
51
-	 *
52
-	 * @since 3.10.0
53
-	 */
54
-	public function __construct( $entity_type_service, $user_service, $attachment_service, $disable_convert_filters = false ) {
55
-		parent::__construct( $entity_type_service, $user_service, $attachment_service, Wordlift_Property_Getter_Factory::create() );
56
-		$this->disable_convert_filters = $disable_convert_filters;
57
-		$this->object_relation_service = Object_Relation_Service::get_instance();
58
-		// Set a reference to the logger.
59
-		$this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Post_To_Jsonld_Converter' );
60
-
61
-		self::$instance = $this;
62
-
63
-	}
64
-
65
-	public static function get_instance() {
66
-
67
-		return self::$instance;
68
-	}
69
-
70
-	public function new_instance_with_filters_disabled() {
71
-		return new static( $this->entity_type_service, $this->user_service, $this->attachment_service, true );
72
-	}
73
-
74
-	/**
75
-	 * Convert the provided {@link WP_Post} to a JSON-LD array. Any entity reference
76
-	 * found while processing the post is set in the $references array.
77
-	 *
78
-	 * @param int              $post_id The post id.
79
-	 * @param array<Reference> $references An array of entity references.
80
-	 * @param array            $references_infos
81
-	 *
82
-	 * @return array A JSON-LD array.
83
-	 * @since 3.10.0
84
-	 */
85
-	public function convert( $post_id, &$references = array(), &$references_infos = array() ) {
86
-
87
-		// Get the post instance.
88
-		$post = get_post( $post_id );
89
-		if ( null === $post ) {
90
-			// Post not found.
91
-			return null;
92
-		}
93
-
94
-		// Get the base JSON-LD and the list of entities referenced by this entity.
95
-		$jsonld = parent::convert( $post_id, $references, $references_infos );
96
-
97
-		// Set WebPage by default.
98
-		if ( empty( $jsonld['@type'] ) ) {
99
-			$jsonld['@type'] = 'WebPage';
100
-		}
101
-
102
-		// Get the entity name.
103
-		$jsonld['headline'] = $post->post_title;
104
-
105
-		$custom_fields = $this->entity_type_service->get_custom_fields_for_post( $post_id );
106
-
107
-		if ( isset( $custom_fields ) ) {
108
-			$this->process_type_custom_fields( $jsonld, $custom_fields, $post, $references, $references_infos );
109
-		}
110
-
111
-		// Set the published and modified dates.
112
-		/*
22
+    /**
23
+     * @var Wordlift_Post_To_Jsonld_Converter
24
+     */
25
+    private static $instance;
26
+
27
+    /**
28
+     * A {@link Wordlift_Log_Service} instance.
29
+     *
30
+     * @since  3.10.0
31
+     * @access private
32
+     * @var Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
33
+     */
34
+    private $log;
35
+
36
+    /**
37
+     * @var false
38
+     */
39
+    private $disable_convert_filters;
40
+    /**
41
+     * @var Object_Relation_Service
42
+     */
43
+    private $object_relation_service;
44
+
45
+    /**
46
+     * Wordlift_Post_To_Jsonld_Converter constructor.
47
+     *
48
+     * @param \Wordlift_Entity_Type_Service $entity_type_service A {@link Wordlift_Entity_Type_Service} instance.
49
+     * @param \Wordlift_User_Service        $user_service A {@link Wordlift_User_Service} instance.
50
+     * @param \Wordlift_Attachment_Service  $attachment_service A {@link Wordlift_Attachment_Service} instance.
51
+     *
52
+     * @since 3.10.0
53
+     */
54
+    public function __construct( $entity_type_service, $user_service, $attachment_service, $disable_convert_filters = false ) {
55
+        parent::__construct( $entity_type_service, $user_service, $attachment_service, Wordlift_Property_Getter_Factory::create() );
56
+        $this->disable_convert_filters = $disable_convert_filters;
57
+        $this->object_relation_service = Object_Relation_Service::get_instance();
58
+        // Set a reference to the logger.
59
+        $this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Post_To_Jsonld_Converter' );
60
+
61
+        self::$instance = $this;
62
+
63
+    }
64
+
65
+    public static function get_instance() {
66
+
67
+        return self::$instance;
68
+    }
69
+
70
+    public function new_instance_with_filters_disabled() {
71
+        return new static( $this->entity_type_service, $this->user_service, $this->attachment_service, true );
72
+    }
73
+
74
+    /**
75
+     * Convert the provided {@link WP_Post} to a JSON-LD array. Any entity reference
76
+     * found while processing the post is set in the $references array.
77
+     *
78
+     * @param int              $post_id The post id.
79
+     * @param array<Reference> $references An array of entity references.
80
+     * @param array            $references_infos
81
+     *
82
+     * @return array A JSON-LD array.
83
+     * @since 3.10.0
84
+     */
85
+    public function convert( $post_id, &$references = array(), &$references_infos = array() ) {
86
+
87
+        // Get the post instance.
88
+        $post = get_post( $post_id );
89
+        if ( null === $post ) {
90
+            // Post not found.
91
+            return null;
92
+        }
93
+
94
+        // Get the base JSON-LD and the list of entities referenced by this entity.
95
+        $jsonld = parent::convert( $post_id, $references, $references_infos );
96
+
97
+        // Set WebPage by default.
98
+        if ( empty( $jsonld['@type'] ) ) {
99
+            $jsonld['@type'] = 'WebPage';
100
+        }
101
+
102
+        // Get the entity name.
103
+        $jsonld['headline'] = $post->post_title;
104
+
105
+        $custom_fields = $this->entity_type_service->get_custom_fields_for_post( $post_id );
106
+
107
+        if ( isset( $custom_fields ) ) {
108
+            $this->process_type_custom_fields( $jsonld, $custom_fields, $post, $references, $references_infos );
109
+        }
110
+
111
+        // Set the published and modified dates.
112
+        /*
113 113
 		 * Set the `datePublished` and `dateModified` using the local timezone.
114 114
 		 *
115 115
 		 * @see https://github.com/insideout10/wordlift-plugin/issues/887
116 116
 		 *
117 117
 		 * @since 3.20.0
118 118
 		 */
119
-		try {
120
-			$default_timezone = date_default_timezone_get();
121
-			$timezone         = get_option( 'timezone_string' );
122
-			if ( ! empty( $timezone ) ) {
123
-				date_default_timezone_set( $timezone ); //phpcs:ignore WordPress.DateTime.RestrictedFunctions.timezone_change_date_default_timezone_set
124
-				$jsonld['datePublished'] = get_post_time( 'Y-m-d\TH:i:sP', false, $post );
125
-				$jsonld['dateModified']  = get_post_modified_time( 'Y-m-d\TH:i:sP', false, $post );
126
-				date_default_timezone_set( $default_timezone ); //phpcs:ignore WordPress.DateTime.RestrictedFunctions.timezone_change_date_default_timezone_set
127
-			} else {
128
-				$jsonld['datePublished'] = get_post_time( 'Y-m-d\TH:i', true, $post, false );
129
-				$jsonld['dateModified']  = get_post_modified_time( 'Y-m-d\TH:i', true, $post, false );
130
-			}
131
-		} catch ( Exception $e ) {
132
-			$jsonld['datePublished'] = get_post_time( 'Y-m-d\TH:i', true, $post, false );
133
-			$jsonld['dateModified']  = get_post_modified_time( 'Y-m-d\TH:i', true, $post, false );
134
-		}
135
-
136
-		// Get the word count for the post.
137
-		/*
119
+        try {
120
+            $default_timezone = date_default_timezone_get();
121
+            $timezone         = get_option( 'timezone_string' );
122
+            if ( ! empty( $timezone ) ) {
123
+                date_default_timezone_set( $timezone ); //phpcs:ignore WordPress.DateTime.RestrictedFunctions.timezone_change_date_default_timezone_set
124
+                $jsonld['datePublished'] = get_post_time( 'Y-m-d\TH:i:sP', false, $post );
125
+                $jsonld['dateModified']  = get_post_modified_time( 'Y-m-d\TH:i:sP', false, $post );
126
+                date_default_timezone_set( $default_timezone ); //phpcs:ignore WordPress.DateTime.RestrictedFunctions.timezone_change_date_default_timezone_set
127
+            } else {
128
+                $jsonld['datePublished'] = get_post_time( 'Y-m-d\TH:i', true, $post, false );
129
+                $jsonld['dateModified']  = get_post_modified_time( 'Y-m-d\TH:i', true, $post, false );
130
+            }
131
+        } catch ( Exception $e ) {
132
+            $jsonld['datePublished'] = get_post_time( 'Y-m-d\TH:i', true, $post, false );
133
+            $jsonld['dateModified']  = get_post_modified_time( 'Y-m-d\TH:i', true, $post, false );
134
+        }
135
+
136
+        // Get the word count for the post.
137
+        /*
138 138
 		 * Do not display the `wordCount` on a `WebPage`.
139 139
 		 *
140 140
 		 * @see https://github.com/insideout10/wordlift-plugin/issues/888
141 141
 		 *
142 142
 		 * @since 3.20.0
143 143
 		 */
144
-		if ( ! empty( $jsonld['@type'] ) && 'WebPage' !== $jsonld['@type'] ) {
145
-			$post_adapter        = new Wordlift_Post_Adapter( $post_id );
146
-			$jsonld['wordCount'] = $post_adapter->word_count();
147
-		}
144
+        if ( ! empty( $jsonld['@type'] ) && 'WebPage' !== $jsonld['@type'] ) {
145
+            $post_adapter        = new Wordlift_Post_Adapter( $post_id );
146
+            $jsonld['wordCount'] = $post_adapter->word_count();
147
+        }
148 148
 
149
-		/*
149
+        /*
150 150
 		 * Add keywords, articleSection, commentCount and inLanguage properties to `Article` JSON-LD
151 151
 		 *
152 152
 		 * @see https://github.com/insideout10/wordlift-plugin/issues/1140
153 153
 		 *
154 154
 		 * @since 3.27.2
155 155
 		 */
156
-		if ( ! empty( $jsonld['@type'] ) && 'WebPage' !== $jsonld['@type'] ) {
157
-			$post_adapter    = new Wordlift_Post_Adapter( $post_id );
158
-			$keywords        = $post_adapter->keywords();
159
-			$article_section = $post_adapter->article_section();
160
-			$comment_count   = $post_adapter->comment_count();
161
-			$locale          = $post_adapter->locale();
162
-
163
-			if ( isset( $keywords ) ) {
164
-				$jsonld['keywords'] = $keywords;
165
-			}
166
-			if ( ! empty( $article_section ) ) {
167
-				$jsonld['articleSection'] = $article_section;
168
-			}
169
-			$jsonld['commentCount'] = $comment_count;
170
-			$jsonld['inLanguage']   = $locale;
171
-			$post_adapter->add_references( $post_id, $references );
172
-		}
173
-
174
-		// Set the publisher.
175
-		$this->set_publisher( $jsonld );
176
-
177
-		$references = $this->convert_references( $references );
178
-
179
-		// Process the references if any.
180
-		$this->set_mentions_and_about( $references, $post, $jsonld );
181
-
182
-		// Finally set the author.
183
-		$jsonld['author'] = $this->get_author( $post->post_author, $references );
184
-
185
-		// Return the JSON-LD if filters are disabled by the client.
186
-		if ( $this->disable_convert_filters ) {
187
-			return $jsonld;
188
-		}
189
-
190
-		/**
191
-		 * Call the `wl_post_jsonld_array` filter. This filter allows 3rd parties to also modify the references.
192
-		 *
193
-		 * @param array $value {
194
-		 *
195
-		 * @type array $jsonld The JSON-LD structure.
196
-		 * @type int[] $references An array of post IDs.
197
-		 * }
198
-		 * @since 3.25.0
199
-		 *
200
-		 * @see https://www.geeklab.info/2010/04/wordpress-pass-variables-by-reference-with-apply_filter/
201
-		 *
202
-		 * @api
203
-		 */
204
-		$ret_val = apply_filters(
205
-			'wl_post_jsonld_array',
206
-			array(
207
-				'jsonld'     => $jsonld,
208
-				'references' => $references,
209
-			),
210
-			$post_id
211
-		);
212
-
213
-		$jsonld     = $ret_val['jsonld'];
214
-		$references = $ret_val['references'];
215
-
216
-		/**
217
-		 * Call the `wl_post_jsonld` filter.
218
-		 *
219
-		 * @param array $jsonld The JSON-LD structure.
220
-		 * @param int $post_id The {@link WP_Post} `id`.
221
-		 * @param array $references The array of referenced entities.
222
-		 *
223
-		 * @since 3.14.0
224
-		 *
225
-		 * @api
226
-		 */
227
-		return apply_filters( 'wl_post_jsonld', $jsonld, $post_id, $references );
228
-	}
229
-
230
-	/**
231
-	 * Get the author's JSON-LD fragment.
232
-	 *
233
-	 * The JSON-LD fragment is generated using the {@link WP_User}'s data or
234
-	 * the referenced entity if configured for the {@link WP_User}.
235
-	 *
236
-	 * @param int   $author_id The author {@link WP_User}'s `id`.
237
-	 * @param array $references An array of referenced entities.
238
-	 *
239
-	 * @return string|array A JSON-LD structure.
240
-	 * @since 3.14.0
241
-	 */
242
-	public function get_author( $author_id, &$references ) {
243
-
244
-		// Get the entity bound to this user.
245
-		$entity_id = $this->user_service->get_entity( $author_id );
246
-
247
-		// If there's no entity bound return a simple author structure.
248
-		if ( empty( $entity_id ) || 'publish' !== get_post_status( $entity_id ) ) {
249
-
250
-			$author            = get_the_author_meta( 'display_name', $author_id );
251
-			$author_first_name = get_the_author_meta( 'first_name', $author_id );
252
-			$author_last_name  = get_the_author_meta( 'last_name', $author_id );
253
-			$author_uri        = $this->user_service->get_uri( $author_id );
254
-
255
-			return array(
256
-				'@type'      => 'Person',
257
-				'@id'        => $author_uri,
258
-				'name'       => $author,
259
-				'givenName'  => $author_first_name,
260
-				'familyName' => $author_last_name,
261
-				'url'        => get_author_posts_url( $author_id ),
262
-			);
263
-		}
264
-
265
-		// Add the author to the references.
266
-		$author_uri   = Wordlift_Entity_Service::get_instance()->get_uri( $entity_id );
267
-		$references[] = $entity_id;
268
-
269
-		// Return the JSON-LD for the referenced entity.
270
-		return array(
271
-			'@id' => $author_uri,
272
-		);
273
-	}
274
-
275
-	/**
276
-	 * Enrich the provided params array with publisher data, if available.
277
-	 *
278
-	 * @param array $params The parameters array.
279
-	 *
280
-	 * @since 3.10.0
281
-	 */
282
-	protected function set_publisher( &$params ) {
283
-
284
-		// If the publisher id isn't set don't do anything.
285
-		$publisher_id = Wordlift_Configuration_Service::get_instance()->get_publisher_id();
286
-		if ( null === $publisher_id ) {
287
-			return;
288
-		}
289
-
290
-		// Get the post instance.
291
-		$post = get_post( $publisher_id );
292
-		if ( null === $post ) {
293
-			// Publisher not found.
294
-			return;
295
-		}
296
-
297
-		// Get the item id.
298
-		$id = Wordlift_Entity_Service::get_instance()->get_uri( $publisher_id );
299
-
300
-		// Get the type.
301
-		$type = $this->entity_type_service->get( $publisher_id );
302
-
303
-		// Get the name.
304
-		$name = $post->post_title;
305
-
306
-		// Set the publisher data.
307
-		$params['publisher'] = array(
308
-			'@type' => $this->relative_to_context( $type['uri'] ),
309
-			'@id'   => $id,
310
-			'name'  => $name,
311
-		);
312
-
313
-		// Add the sameAs values associated with the publisher.
314
-		$storage_factory = Wordlift_Storage_Factory::get_instance();
315
-		$sameas          = $storage_factory->post_meta( Wordlift_Schema_Service::FIELD_SAME_AS )->get( $publisher_id );
316
-		if ( ! empty( $sameas ) ) {
317
-			$params['publisher']['sameAs'] = $sameas;
318
-		}
319
-
320
-		// Set the logo, only for http://schema.org/Organization as Person doesn't
321
-		// support the logo property.
322
-		//
323
-		// See http://schema.org/logo.
324
-		if ( 1 !== preg_match( '~Organization$~', $type['uri'] ) ) {
325
-			return;
326
-		}
327
-
328
-		// Get the publisher logo.
329
-		$publisher_logo = $this->get_publisher_logo( $post->ID );
330
-
331
-		// Bail out if the publisher logo isn't set.
332
-		if ( false === $publisher_logo ) {
333
-			return;
334
-		}
335
-
336
-		// Copy over some useful properties.
337
-		//
338
-		// See https://developers.google.com/search/docs/data-types/articles.
339
-		$params['publisher']['logo']['@type'] = 'ImageObject';
340
-		$params['publisher']['logo']['url']   = $publisher_logo['url'];
341
-
342
-		// If you specify a "width" or "height" value you should leave out
343
-		// 'px'. For example: "width":"4608px" should be "width":"4608".
344
-		//
345
-		// See https://github.com/insideout10/wordlift-plugin/issues/451.
346
-		$params['publisher']['logo']['width']  = $publisher_logo['width'];
347
-		$params['publisher']['logo']['height'] = $publisher_logo['height'];
348
-
349
-	}
350
-
351
-	/**
352
-	 * Get the publisher logo structure.
353
-	 *
354
-	 * The function returns false when the publisher logo cannot be determined, i.e.:
355
-	 *  - the post has no featured image.
356
-	 *  - the featured image has no file.
357
-	 *  - a wp_image_editor instance cannot be instantiated on the original file or on the publisher logo file.
358
-	 *
359
-	 * @param int $post_id The post id.
360
-	 *
361
-	 * @return array|false Returns an array with the `url`, `width` and `height` for the publisher logo or false in case
362
-	 *  of errors.
363
-	 * @since 3.19.2
364
-	 * @see https://github.com/insideout10/wordlift-plugin/issues/823 related issue.
365
-	 */
366
-	private function get_publisher_logo( $post_id ) {
367
-
368
-		// Get the featured image for the post.
369
-		$thumbnail_id = get_post_thumbnail_id( $post_id );
370
-
371
-		// Bail out if thumbnail not available.
372
-		if ( empty( $thumbnail_id ) || 0 === $thumbnail_id ) {
373
-			$this->log->info( "Featured image not set for post $post_id." );
374
-
375
-			return false;
376
-		}
377
-
378
-		// Get the uploads base URL.
379
-		$uploads_dir = wp_upload_dir();
380
-
381
-		// Get the attachment metadata.
382
-		$metadata = wp_get_attachment_metadata( $thumbnail_id );
383
-
384
-		// Bail out if the file isn't set.
385
-		if ( ! isset( $metadata['file'] ) ) {
386
-			$this->log->warn( "Featured image file not found for post $post_id." );
387
-
388
-			return false;
389
-		}
390
-
391
-		// Retrieve the relative filename, e.g. "2018/05/logo_publisher.png"
392
-		$path = $uploads_dir['basedir'] . DIRECTORY_SEPARATOR . $metadata['file'];
393
-
394
-		// Use image src, if local file does not exist. @see https://github.com/insideout10/wordlift-plugin/issues/1149
395
-		if ( ! file_exists( $path ) ) {
396
-			$this->log->warn( "Featured image file $path doesn't exist for post $post_id." );
397
-
398
-			$attachment_image_src = wp_get_attachment_image_src( $thumbnail_id, '' );
399
-			if ( $attachment_image_src ) {
400
-				return array(
401
-					'url'    => $attachment_image_src[0],
402
-					'width'  => $attachment_image_src[1],
403
-					'height' => $attachment_image_src[2],
404
-				);
405
-			}
406
-
407
-			// Bail out if we cant fetch wp_get_attachment_image_src
408
-			return false;
409
-
410
-		}
411
-
412
-		// Try to get the image editor and bail out if the editor cannot be instantiated.
413
-		$original_file_editor = wp_get_image_editor( $path );
414
-		if ( is_wp_error( $original_file_editor ) ) {
415
-			$this->log->warn( "Cannot instantiate WP Image Editor on file $path for post $post_id." );
416
-
417
-			return false;
418
-		}
419
-
420
-		// Generate the publisher logo filename, we cannot use the `width` and `height` because we're scaling
421
-		// and we don't actually know the end values.
422
-		$publisher_logo_path = $original_file_editor->generate_filename( '-publisher-logo' );
423
-
424
-		// If the file doesn't exist yet, create it.
425
-		if ( ! file_exists( $publisher_logo_path ) ) {
426
-			$original_file_editor->resize( 600, 60 );
427
-			$original_file_editor->save( $publisher_logo_path );
428
-		}
429
-
430
-		// Try to get the image editor and bail out if the editor cannot be instantiated.
431
-		$publisher_logo_editor = wp_get_image_editor( $publisher_logo_path );
432
-		if ( is_wp_error( $publisher_logo_editor ) ) {
433
-			$this->log->warn( "Cannot instantiate WP Image Editor on file $publisher_logo_path for post $post_id." );
434
-
435
-			return false;
436
-		}
437
-
438
-		// Get the actual size.
439
-		$size = $publisher_logo_editor->get_size();
440
-
441
-		// Finally return the array with data.
442
-		return array(
443
-			'url'    => $uploads_dir['baseurl'] . substr( $publisher_logo_path, strlen( $uploads_dir['basedir'] ) ),
444
-			'width'  => $size['width'],
445
-			'height' => $size['height'],
446
-		);
447
-	}
448
-
449
-	/**
450
-	 * @param $references
451
-	 * @param $post
452
-	 * @param $jsonld
453
-	 *
454
-	 * @return void
455
-	 */
456
-	private function set_mentions_and_about( $references, $post, &$jsonld ) {
457
-
458
-		if ( count( $references ) === 0 ) {
459
-			return;
460
-		}
461
-
462
-		// Prepare the `about` and `mentions` array.
463
-		$mentions = array();
464
-		$about    = array();
465
-
466
-		// If the entity is in the title, then it should be an `about`.
467
-		foreach ( $references as $reference ) {
468
-
469
-			if ( ! $reference instanceof Reference ) {
470
-				// This condition should never be reached.
471
-				continue;
472
-			}
473
-
474
-			// Get the entity labels.
475
-			$labels = Wordlift_Entity_Service::get_instance()->get_labels( $reference->get_id(), $reference->get_type() );
476
-			// Get the entity URI.
477
-			$item = array(
478
-				'@id' => Wordlift_Entity_Service::get_instance()->get_uri( $reference->get_id(), $reference->get_type() ),
479
-			);
480
-
481
-			$escaped_labels = array_map(
482
-				function ( $value ) {
483
-					return preg_quote( $value, '/' );
484
-				},
485
-				$labels
486
-			);
487
-
488
-			$matches = false;
489
-
490
-			// When the title is empty, then we shouldn't yield a match to about section.
491
-			if ( array_filter( $escaped_labels ) ) {
492
-				// Check if the labels match any part of the title.
493
-				$matches = $this->check_title_match( $escaped_labels, $post->post_title );
494
-			}
495
-
496
-			// If the title matches, assign the entity to the about, otherwise to the mentions.
497
-			if ( $matches ) {
498
-				$about[] = $item;
499
-			} else {
500
-				$mentions[] = $item;
501
-			}
502
-		}
503
-
504
-		// If we have abouts, assign them to the JSON-LD.
505
-		if ( 0 < count( $about ) ) {
506
-			$jsonld['about'] = $about;
507
-		}
508
-
509
-		// If we have mentions, assign them to the JSON-LD.
510
-		if ( 0 < count( $mentions ) ) {
511
-			$jsonld['mentions'] = $mentions;
512
-		}
513
-
514
-		return $jsonld;
515
-	}
516
-
517
-	/**
518
-	 * Check if the labels match any part of the title.
519
-	 *
520
-	 * @param $labels array The labels to check.
521
-	 * @param $title string The title to check.
522
-	 *
523
-	 * @return boolean
524
-	 */
525
-	public function check_title_match( $labels, $title ) {
526
-
527
-		// If the title is empty, then we shouldn't yield a match to about section.
528
-		if ( empty( $title ) ) {
529
-			return false;
530
-		}
531
-
532
-		// Check if the labels match any part of the title.
533
-		return 1 === preg_match( '/\b(' . implode( '|', $labels ) . ')\b/iu', $title );
534
-
535
-	}
536
-
537
-	/**
538
-	 * Convert references to abstract data type if we find any.
539
-	 *
540
-	 * @param $references array<int|Reference>
541
-	 *
542
-	 * @return Reference[]
543
-	 */
544
-	private function convert_references( $references ) {
545
-		return array_map(
546
-			function ( $reference ) {
547
-				// Legacy code may still push numerical references to this
548
-				// $references variable, so convert it to post references.
549
-				if ( is_numeric( $reference ) ) {
550
-					  return new Post_Reference( $reference );
551
-				}
552
-
553
-				return $reference;
554
-
555
-			},
556
-			$references
557
-		);
558
-	}
156
+        if ( ! empty( $jsonld['@type'] ) && 'WebPage' !== $jsonld['@type'] ) {
157
+            $post_adapter    = new Wordlift_Post_Adapter( $post_id );
158
+            $keywords        = $post_adapter->keywords();
159
+            $article_section = $post_adapter->article_section();
160
+            $comment_count   = $post_adapter->comment_count();
161
+            $locale          = $post_adapter->locale();
162
+
163
+            if ( isset( $keywords ) ) {
164
+                $jsonld['keywords'] = $keywords;
165
+            }
166
+            if ( ! empty( $article_section ) ) {
167
+                $jsonld['articleSection'] = $article_section;
168
+            }
169
+            $jsonld['commentCount'] = $comment_count;
170
+            $jsonld['inLanguage']   = $locale;
171
+            $post_adapter->add_references( $post_id, $references );
172
+        }
173
+
174
+        // Set the publisher.
175
+        $this->set_publisher( $jsonld );
176
+
177
+        $references = $this->convert_references( $references );
178
+
179
+        // Process the references if any.
180
+        $this->set_mentions_and_about( $references, $post, $jsonld );
181
+
182
+        // Finally set the author.
183
+        $jsonld['author'] = $this->get_author( $post->post_author, $references );
184
+
185
+        // Return the JSON-LD if filters are disabled by the client.
186
+        if ( $this->disable_convert_filters ) {
187
+            return $jsonld;
188
+        }
189
+
190
+        /**
191
+         * Call the `wl_post_jsonld_array` filter. This filter allows 3rd parties to also modify the references.
192
+         *
193
+         * @param array $value {
194
+         *
195
+         * @type array $jsonld The JSON-LD structure.
196
+         * @type int[] $references An array of post IDs.
197
+         * }
198
+         * @since 3.25.0
199
+         *
200
+         * @see https://www.geeklab.info/2010/04/wordpress-pass-variables-by-reference-with-apply_filter/
201
+         *
202
+         * @api
203
+         */
204
+        $ret_val = apply_filters(
205
+            'wl_post_jsonld_array',
206
+            array(
207
+                'jsonld'     => $jsonld,
208
+                'references' => $references,
209
+            ),
210
+            $post_id
211
+        );
212
+
213
+        $jsonld     = $ret_val['jsonld'];
214
+        $references = $ret_val['references'];
215
+
216
+        /**
217
+         * Call the `wl_post_jsonld` filter.
218
+         *
219
+         * @param array $jsonld The JSON-LD structure.
220
+         * @param int $post_id The {@link WP_Post} `id`.
221
+         * @param array $references The array of referenced entities.
222
+         *
223
+         * @since 3.14.0
224
+         *
225
+         * @api
226
+         */
227
+        return apply_filters( 'wl_post_jsonld', $jsonld, $post_id, $references );
228
+    }
229
+
230
+    /**
231
+     * Get the author's JSON-LD fragment.
232
+     *
233
+     * The JSON-LD fragment is generated using the {@link WP_User}'s data or
234
+     * the referenced entity if configured for the {@link WP_User}.
235
+     *
236
+     * @param int   $author_id The author {@link WP_User}'s `id`.
237
+     * @param array $references An array of referenced entities.
238
+     *
239
+     * @return string|array A JSON-LD structure.
240
+     * @since 3.14.0
241
+     */
242
+    public function get_author( $author_id, &$references ) {
243
+
244
+        // Get the entity bound to this user.
245
+        $entity_id = $this->user_service->get_entity( $author_id );
246
+
247
+        // If there's no entity bound return a simple author structure.
248
+        if ( empty( $entity_id ) || 'publish' !== get_post_status( $entity_id ) ) {
249
+
250
+            $author            = get_the_author_meta( 'display_name', $author_id );
251
+            $author_first_name = get_the_author_meta( 'first_name', $author_id );
252
+            $author_last_name  = get_the_author_meta( 'last_name', $author_id );
253
+            $author_uri        = $this->user_service->get_uri( $author_id );
254
+
255
+            return array(
256
+                '@type'      => 'Person',
257
+                '@id'        => $author_uri,
258
+                'name'       => $author,
259
+                'givenName'  => $author_first_name,
260
+                'familyName' => $author_last_name,
261
+                'url'        => get_author_posts_url( $author_id ),
262
+            );
263
+        }
264
+
265
+        // Add the author to the references.
266
+        $author_uri   = Wordlift_Entity_Service::get_instance()->get_uri( $entity_id );
267
+        $references[] = $entity_id;
268
+
269
+        // Return the JSON-LD for the referenced entity.
270
+        return array(
271
+            '@id' => $author_uri,
272
+        );
273
+    }
274
+
275
+    /**
276
+     * Enrich the provided params array with publisher data, if available.
277
+     *
278
+     * @param array $params The parameters array.
279
+     *
280
+     * @since 3.10.0
281
+     */
282
+    protected function set_publisher( &$params ) {
283
+
284
+        // If the publisher id isn't set don't do anything.
285
+        $publisher_id = Wordlift_Configuration_Service::get_instance()->get_publisher_id();
286
+        if ( null === $publisher_id ) {
287
+            return;
288
+        }
289
+
290
+        // Get the post instance.
291
+        $post = get_post( $publisher_id );
292
+        if ( null === $post ) {
293
+            // Publisher not found.
294
+            return;
295
+        }
296
+
297
+        // Get the item id.
298
+        $id = Wordlift_Entity_Service::get_instance()->get_uri( $publisher_id );
299
+
300
+        // Get the type.
301
+        $type = $this->entity_type_service->get( $publisher_id );
302
+
303
+        // Get the name.
304
+        $name = $post->post_title;
305
+
306
+        // Set the publisher data.
307
+        $params['publisher'] = array(
308
+            '@type' => $this->relative_to_context( $type['uri'] ),
309
+            '@id'   => $id,
310
+            'name'  => $name,
311
+        );
312
+
313
+        // Add the sameAs values associated with the publisher.
314
+        $storage_factory = Wordlift_Storage_Factory::get_instance();
315
+        $sameas          = $storage_factory->post_meta( Wordlift_Schema_Service::FIELD_SAME_AS )->get( $publisher_id );
316
+        if ( ! empty( $sameas ) ) {
317
+            $params['publisher']['sameAs'] = $sameas;
318
+        }
319
+
320
+        // Set the logo, only for http://schema.org/Organization as Person doesn't
321
+        // support the logo property.
322
+        //
323
+        // See http://schema.org/logo.
324
+        if ( 1 !== preg_match( '~Organization$~', $type['uri'] ) ) {
325
+            return;
326
+        }
327
+
328
+        // Get the publisher logo.
329
+        $publisher_logo = $this->get_publisher_logo( $post->ID );
330
+
331
+        // Bail out if the publisher logo isn't set.
332
+        if ( false === $publisher_logo ) {
333
+            return;
334
+        }
335
+
336
+        // Copy over some useful properties.
337
+        //
338
+        // See https://developers.google.com/search/docs/data-types/articles.
339
+        $params['publisher']['logo']['@type'] = 'ImageObject';
340
+        $params['publisher']['logo']['url']   = $publisher_logo['url'];
341
+
342
+        // If you specify a "width" or "height" value you should leave out
343
+        // 'px'. For example: "width":"4608px" should be "width":"4608".
344
+        //
345
+        // See https://github.com/insideout10/wordlift-plugin/issues/451.
346
+        $params['publisher']['logo']['width']  = $publisher_logo['width'];
347
+        $params['publisher']['logo']['height'] = $publisher_logo['height'];
348
+
349
+    }
350
+
351
+    /**
352
+     * Get the publisher logo structure.
353
+     *
354
+     * The function returns false when the publisher logo cannot be determined, i.e.:
355
+     *  - the post has no featured image.
356
+     *  - the featured image has no file.
357
+     *  - a wp_image_editor instance cannot be instantiated on the original file or on the publisher logo file.
358
+     *
359
+     * @param int $post_id The post id.
360
+     *
361
+     * @return array|false Returns an array with the `url`, `width` and `height` for the publisher logo or false in case
362
+     *  of errors.
363
+     * @since 3.19.2
364
+     * @see https://github.com/insideout10/wordlift-plugin/issues/823 related issue.
365
+     */
366
+    private function get_publisher_logo( $post_id ) {
367
+
368
+        // Get the featured image for the post.
369
+        $thumbnail_id = get_post_thumbnail_id( $post_id );
370
+
371
+        // Bail out if thumbnail not available.
372
+        if ( empty( $thumbnail_id ) || 0 === $thumbnail_id ) {
373
+            $this->log->info( "Featured image not set for post $post_id." );
374
+
375
+            return false;
376
+        }
377
+
378
+        // Get the uploads base URL.
379
+        $uploads_dir = wp_upload_dir();
380
+
381
+        // Get the attachment metadata.
382
+        $metadata = wp_get_attachment_metadata( $thumbnail_id );
383
+
384
+        // Bail out if the file isn't set.
385
+        if ( ! isset( $metadata['file'] ) ) {
386
+            $this->log->warn( "Featured image file not found for post $post_id." );
387
+
388
+            return false;
389
+        }
390
+
391
+        // Retrieve the relative filename, e.g. "2018/05/logo_publisher.png"
392
+        $path = $uploads_dir['basedir'] . DIRECTORY_SEPARATOR . $metadata['file'];
393
+
394
+        // Use image src, if local file does not exist. @see https://github.com/insideout10/wordlift-plugin/issues/1149
395
+        if ( ! file_exists( $path ) ) {
396
+            $this->log->warn( "Featured image file $path doesn't exist for post $post_id." );
397
+
398
+            $attachment_image_src = wp_get_attachment_image_src( $thumbnail_id, '' );
399
+            if ( $attachment_image_src ) {
400
+                return array(
401
+                    'url'    => $attachment_image_src[0],
402
+                    'width'  => $attachment_image_src[1],
403
+                    'height' => $attachment_image_src[2],
404
+                );
405
+            }
406
+
407
+            // Bail out if we cant fetch wp_get_attachment_image_src
408
+            return false;
409
+
410
+        }
411
+
412
+        // Try to get the image editor and bail out if the editor cannot be instantiated.
413
+        $original_file_editor = wp_get_image_editor( $path );
414
+        if ( is_wp_error( $original_file_editor ) ) {
415
+            $this->log->warn( "Cannot instantiate WP Image Editor on file $path for post $post_id." );
416
+
417
+            return false;
418
+        }
419
+
420
+        // Generate the publisher logo filename, we cannot use the `width` and `height` because we're scaling
421
+        // and we don't actually know the end values.
422
+        $publisher_logo_path = $original_file_editor->generate_filename( '-publisher-logo' );
423
+
424
+        // If the file doesn't exist yet, create it.
425
+        if ( ! file_exists( $publisher_logo_path ) ) {
426
+            $original_file_editor->resize( 600, 60 );
427
+            $original_file_editor->save( $publisher_logo_path );
428
+        }
429
+
430
+        // Try to get the image editor and bail out if the editor cannot be instantiated.
431
+        $publisher_logo_editor = wp_get_image_editor( $publisher_logo_path );
432
+        if ( is_wp_error( $publisher_logo_editor ) ) {
433
+            $this->log->warn( "Cannot instantiate WP Image Editor on file $publisher_logo_path for post $post_id." );
434
+
435
+            return false;
436
+        }
437
+
438
+        // Get the actual size.
439
+        $size = $publisher_logo_editor->get_size();
440
+
441
+        // Finally return the array with data.
442
+        return array(
443
+            'url'    => $uploads_dir['baseurl'] . substr( $publisher_logo_path, strlen( $uploads_dir['basedir'] ) ),
444
+            'width'  => $size['width'],
445
+            'height' => $size['height'],
446
+        );
447
+    }
448
+
449
+    /**
450
+     * @param $references
451
+     * @param $post
452
+     * @param $jsonld
453
+     *
454
+     * @return void
455
+     */
456
+    private function set_mentions_and_about( $references, $post, &$jsonld ) {
457
+
458
+        if ( count( $references ) === 0 ) {
459
+            return;
460
+        }
461
+
462
+        // Prepare the `about` and `mentions` array.
463
+        $mentions = array();
464
+        $about    = array();
465
+
466
+        // If the entity is in the title, then it should be an `about`.
467
+        foreach ( $references as $reference ) {
468
+
469
+            if ( ! $reference instanceof Reference ) {
470
+                // This condition should never be reached.
471
+                continue;
472
+            }
473
+
474
+            // Get the entity labels.
475
+            $labels = Wordlift_Entity_Service::get_instance()->get_labels( $reference->get_id(), $reference->get_type() );
476
+            // Get the entity URI.
477
+            $item = array(
478
+                '@id' => Wordlift_Entity_Service::get_instance()->get_uri( $reference->get_id(), $reference->get_type() ),
479
+            );
480
+
481
+            $escaped_labels = array_map(
482
+                function ( $value ) {
483
+                    return preg_quote( $value, '/' );
484
+                },
485
+                $labels
486
+            );
487
+
488
+            $matches = false;
489
+
490
+            // When the title is empty, then we shouldn't yield a match to about section.
491
+            if ( array_filter( $escaped_labels ) ) {
492
+                // Check if the labels match any part of the title.
493
+                $matches = $this->check_title_match( $escaped_labels, $post->post_title );
494
+            }
495
+
496
+            // If the title matches, assign the entity to the about, otherwise to the mentions.
497
+            if ( $matches ) {
498
+                $about[] = $item;
499
+            } else {
500
+                $mentions[] = $item;
501
+            }
502
+        }
503
+
504
+        // If we have abouts, assign them to the JSON-LD.
505
+        if ( 0 < count( $about ) ) {
506
+            $jsonld['about'] = $about;
507
+        }
508
+
509
+        // If we have mentions, assign them to the JSON-LD.
510
+        if ( 0 < count( $mentions ) ) {
511
+            $jsonld['mentions'] = $mentions;
512
+        }
513
+
514
+        return $jsonld;
515
+    }
516
+
517
+    /**
518
+     * Check if the labels match any part of the title.
519
+     *
520
+     * @param $labels array The labels to check.
521
+     * @param $title string The title to check.
522
+     *
523
+     * @return boolean
524
+     */
525
+    public function check_title_match( $labels, $title ) {
526
+
527
+        // If the title is empty, then we shouldn't yield a match to about section.
528
+        if ( empty( $title ) ) {
529
+            return false;
530
+        }
531
+
532
+        // Check if the labels match any part of the title.
533
+        return 1 === preg_match( '/\b(' . implode( '|', $labels ) . ')\b/iu', $title );
534
+
535
+    }
536
+
537
+    /**
538
+     * Convert references to abstract data type if we find any.
539
+     *
540
+     * @param $references array<int|Reference>
541
+     *
542
+     * @return Reference[]
543
+     */
544
+    private function convert_references( $references ) {
545
+        return array_map(
546
+            function ( $reference ) {
547
+                // Legacy code may still push numerical references to this
548
+                // $references variable, so convert it to post references.
549
+                if ( is_numeric( $reference ) ) {
550
+                        return new Post_Reference( $reference );
551
+                }
552
+
553
+                return $reference;
554
+
555
+            },
556
+            $references
557
+        );
558
+    }
559 559
 
560 560
 }
Please login to merge, or discard this patch.
Spacing   +100 added lines, -100 removed lines patch added patch discarded remove patch
@@ -51,12 +51,12 @@  discard block
 block discarded – undo
51 51
 	 *
52 52
 	 * @since 3.10.0
53 53
 	 */
54
-	public function __construct( $entity_type_service, $user_service, $attachment_service, $disable_convert_filters = false ) {
55
-		parent::__construct( $entity_type_service, $user_service, $attachment_service, Wordlift_Property_Getter_Factory::create() );
54
+	public function __construct($entity_type_service, $user_service, $attachment_service, $disable_convert_filters = false) {
55
+		parent::__construct($entity_type_service, $user_service, $attachment_service, Wordlift_Property_Getter_Factory::create());
56 56
 		$this->disable_convert_filters = $disable_convert_filters;
57 57
 		$this->object_relation_service = Object_Relation_Service::get_instance();
58 58
 		// Set a reference to the logger.
59
-		$this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Post_To_Jsonld_Converter' );
59
+		$this->log = Wordlift_Log_Service::get_logger('Wordlift_Post_To_Jsonld_Converter');
60 60
 
61 61
 		self::$instance = $this;
62 62
 
@@ -68,7 +68,7 @@  discard block
 block discarded – undo
68 68
 	}
69 69
 
70 70
 	public function new_instance_with_filters_disabled() {
71
-		return new static( $this->entity_type_service, $this->user_service, $this->attachment_service, true );
71
+		return new static($this->entity_type_service, $this->user_service, $this->attachment_service, true);
72 72
 	}
73 73
 
74 74
 	/**
@@ -82,30 +82,30 @@  discard block
 block discarded – undo
82 82
 	 * @return array A JSON-LD array.
83 83
 	 * @since 3.10.0
84 84
 	 */
85
-	public function convert( $post_id, &$references = array(), &$references_infos = array() ) {
85
+	public function convert($post_id, &$references = array(), &$references_infos = array()) {
86 86
 
87 87
 		// Get the post instance.
88
-		$post = get_post( $post_id );
89
-		if ( null === $post ) {
88
+		$post = get_post($post_id);
89
+		if (null === $post) {
90 90
 			// Post not found.
91 91
 			return null;
92 92
 		}
93 93
 
94 94
 		// Get the base JSON-LD and the list of entities referenced by this entity.
95
-		$jsonld = parent::convert( $post_id, $references, $references_infos );
95
+		$jsonld = parent::convert($post_id, $references, $references_infos);
96 96
 
97 97
 		// Set WebPage by default.
98
-		if ( empty( $jsonld['@type'] ) ) {
98
+		if (empty($jsonld['@type'])) {
99 99
 			$jsonld['@type'] = 'WebPage';
100 100
 		}
101 101
 
102 102
 		// Get the entity name.
103 103
 		$jsonld['headline'] = $post->post_title;
104 104
 
105
-		$custom_fields = $this->entity_type_service->get_custom_fields_for_post( $post_id );
105
+		$custom_fields = $this->entity_type_service->get_custom_fields_for_post($post_id);
106 106
 
107
-		if ( isset( $custom_fields ) ) {
108
-			$this->process_type_custom_fields( $jsonld, $custom_fields, $post, $references, $references_infos );
107
+		if (isset($custom_fields)) {
108
+			$this->process_type_custom_fields($jsonld, $custom_fields, $post, $references, $references_infos);
109 109
 		}
110 110
 
111 111
 		// Set the published and modified dates.
@@ -118,19 +118,19 @@  discard block
 block discarded – undo
118 118
 		 */
119 119
 		try {
120 120
 			$default_timezone = date_default_timezone_get();
121
-			$timezone         = get_option( 'timezone_string' );
122
-			if ( ! empty( $timezone ) ) {
123
-				date_default_timezone_set( $timezone ); //phpcs:ignore WordPress.DateTime.RestrictedFunctions.timezone_change_date_default_timezone_set
124
-				$jsonld['datePublished'] = get_post_time( 'Y-m-d\TH:i:sP', false, $post );
125
-				$jsonld['dateModified']  = get_post_modified_time( 'Y-m-d\TH:i:sP', false, $post );
126
-				date_default_timezone_set( $default_timezone ); //phpcs:ignore WordPress.DateTime.RestrictedFunctions.timezone_change_date_default_timezone_set
121
+			$timezone         = get_option('timezone_string');
122
+			if ( ! empty($timezone)) {
123
+				date_default_timezone_set($timezone); //phpcs:ignore WordPress.DateTime.RestrictedFunctions.timezone_change_date_default_timezone_set
124
+				$jsonld['datePublished'] = get_post_time('Y-m-d\TH:i:sP', false, $post);
125
+				$jsonld['dateModified']  = get_post_modified_time('Y-m-d\TH:i:sP', false, $post);
126
+				date_default_timezone_set($default_timezone); //phpcs:ignore WordPress.DateTime.RestrictedFunctions.timezone_change_date_default_timezone_set
127 127
 			} else {
128
-				$jsonld['datePublished'] = get_post_time( 'Y-m-d\TH:i', true, $post, false );
129
-				$jsonld['dateModified']  = get_post_modified_time( 'Y-m-d\TH:i', true, $post, false );
128
+				$jsonld['datePublished'] = get_post_time('Y-m-d\TH:i', true, $post, false);
129
+				$jsonld['dateModified']  = get_post_modified_time('Y-m-d\TH:i', true, $post, false);
130 130
 			}
131
-		} catch ( Exception $e ) {
132
-			$jsonld['datePublished'] = get_post_time( 'Y-m-d\TH:i', true, $post, false );
133
-			$jsonld['dateModified']  = get_post_modified_time( 'Y-m-d\TH:i', true, $post, false );
131
+		} catch (Exception $e) {
132
+			$jsonld['datePublished'] = get_post_time('Y-m-d\TH:i', true, $post, false);
133
+			$jsonld['dateModified']  = get_post_modified_time('Y-m-d\TH:i', true, $post, false);
134 134
 		}
135 135
 
136 136
 		// Get the word count for the post.
@@ -141,8 +141,8 @@  discard block
 block discarded – undo
141 141
 		 *
142 142
 		 * @since 3.20.0
143 143
 		 */
144
-		if ( ! empty( $jsonld['@type'] ) && 'WebPage' !== $jsonld['@type'] ) {
145
-			$post_adapter        = new Wordlift_Post_Adapter( $post_id );
144
+		if ( ! empty($jsonld['@type']) && 'WebPage' !== $jsonld['@type']) {
145
+			$post_adapter        = new Wordlift_Post_Adapter($post_id);
146 146
 			$jsonld['wordCount'] = $post_adapter->word_count();
147 147
 		}
148 148
 
@@ -153,37 +153,37 @@  discard block
 block discarded – undo
153 153
 		 *
154 154
 		 * @since 3.27.2
155 155
 		 */
156
-		if ( ! empty( $jsonld['@type'] ) && 'WebPage' !== $jsonld['@type'] ) {
157
-			$post_adapter    = new Wordlift_Post_Adapter( $post_id );
156
+		if ( ! empty($jsonld['@type']) && 'WebPage' !== $jsonld['@type']) {
157
+			$post_adapter    = new Wordlift_Post_Adapter($post_id);
158 158
 			$keywords        = $post_adapter->keywords();
159 159
 			$article_section = $post_adapter->article_section();
160 160
 			$comment_count   = $post_adapter->comment_count();
161 161
 			$locale          = $post_adapter->locale();
162 162
 
163
-			if ( isset( $keywords ) ) {
163
+			if (isset($keywords)) {
164 164
 				$jsonld['keywords'] = $keywords;
165 165
 			}
166
-			if ( ! empty( $article_section ) ) {
166
+			if ( ! empty($article_section)) {
167 167
 				$jsonld['articleSection'] = $article_section;
168 168
 			}
169 169
 			$jsonld['commentCount'] = $comment_count;
170 170
 			$jsonld['inLanguage']   = $locale;
171
-			$post_adapter->add_references( $post_id, $references );
171
+			$post_adapter->add_references($post_id, $references);
172 172
 		}
173 173
 
174 174
 		// Set the publisher.
175
-		$this->set_publisher( $jsonld );
175
+		$this->set_publisher($jsonld);
176 176
 
177
-		$references = $this->convert_references( $references );
177
+		$references = $this->convert_references($references);
178 178
 
179 179
 		// Process the references if any.
180
-		$this->set_mentions_and_about( $references, $post, $jsonld );
180
+		$this->set_mentions_and_about($references, $post, $jsonld);
181 181
 
182 182
 		// Finally set the author.
183
-		$jsonld['author'] = $this->get_author( $post->post_author, $references );
183
+		$jsonld['author'] = $this->get_author($post->post_author, $references);
184 184
 
185 185
 		// Return the JSON-LD if filters are disabled by the client.
186
-		if ( $this->disable_convert_filters ) {
186
+		if ($this->disable_convert_filters) {
187 187
 			return $jsonld;
188 188
 		}
189 189
 
@@ -224,7 +224,7 @@  discard block
 block discarded – undo
224 224
 		 *
225 225
 		 * @api
226 226
 		 */
227
-		return apply_filters( 'wl_post_jsonld', $jsonld, $post_id, $references );
227
+		return apply_filters('wl_post_jsonld', $jsonld, $post_id, $references);
228 228
 	}
229 229
 
230 230
 	/**
@@ -239,18 +239,18 @@  discard block
 block discarded – undo
239 239
 	 * @return string|array A JSON-LD structure.
240 240
 	 * @since 3.14.0
241 241
 	 */
242
-	public function get_author( $author_id, &$references ) {
242
+	public function get_author($author_id, &$references) {
243 243
 
244 244
 		// Get the entity bound to this user.
245
-		$entity_id = $this->user_service->get_entity( $author_id );
245
+		$entity_id = $this->user_service->get_entity($author_id);
246 246
 
247 247
 		// If there's no entity bound return a simple author structure.
248
-		if ( empty( $entity_id ) || 'publish' !== get_post_status( $entity_id ) ) {
248
+		if (empty($entity_id) || 'publish' !== get_post_status($entity_id)) {
249 249
 
250
-			$author            = get_the_author_meta( 'display_name', $author_id );
251
-			$author_first_name = get_the_author_meta( 'first_name', $author_id );
252
-			$author_last_name  = get_the_author_meta( 'last_name', $author_id );
253
-			$author_uri        = $this->user_service->get_uri( $author_id );
250
+			$author            = get_the_author_meta('display_name', $author_id);
251
+			$author_first_name = get_the_author_meta('first_name', $author_id);
252
+			$author_last_name  = get_the_author_meta('last_name', $author_id);
253
+			$author_uri        = $this->user_service->get_uri($author_id);
254 254
 
255 255
 			return array(
256 256
 				'@type'      => 'Person',
@@ -258,12 +258,12 @@  discard block
 block discarded – undo
258 258
 				'name'       => $author,
259 259
 				'givenName'  => $author_first_name,
260 260
 				'familyName' => $author_last_name,
261
-				'url'        => get_author_posts_url( $author_id ),
261
+				'url'        => get_author_posts_url($author_id),
262 262
 			);
263 263
 		}
264 264
 
265 265
 		// Add the author to the references.
266
-		$author_uri   = Wordlift_Entity_Service::get_instance()->get_uri( $entity_id );
266
+		$author_uri   = Wordlift_Entity_Service::get_instance()->get_uri($entity_id);
267 267
 		$references[] = $entity_id;
268 268
 
269 269
 		// Return the JSON-LD for the referenced entity.
@@ -279,41 +279,41 @@  discard block
 block discarded – undo
279 279
 	 *
280 280
 	 * @since 3.10.0
281 281
 	 */
282
-	protected function set_publisher( &$params ) {
282
+	protected function set_publisher(&$params) {
283 283
 
284 284
 		// If the publisher id isn't set don't do anything.
285 285
 		$publisher_id = Wordlift_Configuration_Service::get_instance()->get_publisher_id();
286
-		if ( null === $publisher_id ) {
286
+		if (null === $publisher_id) {
287 287
 			return;
288 288
 		}
289 289
 
290 290
 		// Get the post instance.
291
-		$post = get_post( $publisher_id );
292
-		if ( null === $post ) {
291
+		$post = get_post($publisher_id);
292
+		if (null === $post) {
293 293
 			// Publisher not found.
294 294
 			return;
295 295
 		}
296 296
 
297 297
 		// Get the item id.
298
-		$id = Wordlift_Entity_Service::get_instance()->get_uri( $publisher_id );
298
+		$id = Wordlift_Entity_Service::get_instance()->get_uri($publisher_id);
299 299
 
300 300
 		// Get the type.
301
-		$type = $this->entity_type_service->get( $publisher_id );
301
+		$type = $this->entity_type_service->get($publisher_id);
302 302
 
303 303
 		// Get the name.
304 304
 		$name = $post->post_title;
305 305
 
306 306
 		// Set the publisher data.
307 307
 		$params['publisher'] = array(
308
-			'@type' => $this->relative_to_context( $type['uri'] ),
308
+			'@type' => $this->relative_to_context($type['uri']),
309 309
 			'@id'   => $id,
310 310
 			'name'  => $name,
311 311
 		);
312 312
 
313 313
 		// Add the sameAs values associated with the publisher.
314 314
 		$storage_factory = Wordlift_Storage_Factory::get_instance();
315
-		$sameas          = $storage_factory->post_meta( Wordlift_Schema_Service::FIELD_SAME_AS )->get( $publisher_id );
316
-		if ( ! empty( $sameas ) ) {
315
+		$sameas          = $storage_factory->post_meta(Wordlift_Schema_Service::FIELD_SAME_AS)->get($publisher_id);
316
+		if ( ! empty($sameas)) {
317 317
 			$params['publisher']['sameAs'] = $sameas;
318 318
 		}
319 319
 
@@ -321,15 +321,15 @@  discard block
 block discarded – undo
321 321
 		// support the logo property.
322 322
 		//
323 323
 		// See http://schema.org/logo.
324
-		if ( 1 !== preg_match( '~Organization$~', $type['uri'] ) ) {
324
+		if (1 !== preg_match('~Organization$~', $type['uri'])) {
325 325
 			return;
326 326
 		}
327 327
 
328 328
 		// Get the publisher logo.
329
-		$publisher_logo = $this->get_publisher_logo( $post->ID );
329
+		$publisher_logo = $this->get_publisher_logo($post->ID);
330 330
 
331 331
 		// Bail out if the publisher logo isn't set.
332
-		if ( false === $publisher_logo ) {
332
+		if (false === $publisher_logo) {
333 333
 			return;
334 334
 		}
335 335
 
@@ -363,14 +363,14 @@  discard block
 block discarded – undo
363 363
 	 * @since 3.19.2
364 364
 	 * @see https://github.com/insideout10/wordlift-plugin/issues/823 related issue.
365 365
 	 */
366
-	private function get_publisher_logo( $post_id ) {
366
+	private function get_publisher_logo($post_id) {
367 367
 
368 368
 		// Get the featured image for the post.
369
-		$thumbnail_id = get_post_thumbnail_id( $post_id );
369
+		$thumbnail_id = get_post_thumbnail_id($post_id);
370 370
 
371 371
 		// Bail out if thumbnail not available.
372
-		if ( empty( $thumbnail_id ) || 0 === $thumbnail_id ) {
373
-			$this->log->info( "Featured image not set for post $post_id." );
372
+		if (empty($thumbnail_id) || 0 === $thumbnail_id) {
373
+			$this->log->info("Featured image not set for post $post_id.");
374 374
 
375 375
 			return false;
376 376
 		}
@@ -379,24 +379,24 @@  discard block
 block discarded – undo
379 379
 		$uploads_dir = wp_upload_dir();
380 380
 
381 381
 		// Get the attachment metadata.
382
-		$metadata = wp_get_attachment_metadata( $thumbnail_id );
382
+		$metadata = wp_get_attachment_metadata($thumbnail_id);
383 383
 
384 384
 		// Bail out if the file isn't set.
385
-		if ( ! isset( $metadata['file'] ) ) {
386
-			$this->log->warn( "Featured image file not found for post $post_id." );
385
+		if ( ! isset($metadata['file'])) {
386
+			$this->log->warn("Featured image file not found for post $post_id.");
387 387
 
388 388
 			return false;
389 389
 		}
390 390
 
391 391
 		// Retrieve the relative filename, e.g. "2018/05/logo_publisher.png"
392
-		$path = $uploads_dir['basedir'] . DIRECTORY_SEPARATOR . $metadata['file'];
392
+		$path = $uploads_dir['basedir'].DIRECTORY_SEPARATOR.$metadata['file'];
393 393
 
394 394
 		// Use image src, if local file does not exist. @see https://github.com/insideout10/wordlift-plugin/issues/1149
395
-		if ( ! file_exists( $path ) ) {
396
-			$this->log->warn( "Featured image file $path doesn't exist for post $post_id." );
395
+		if ( ! file_exists($path)) {
396
+			$this->log->warn("Featured image file $path doesn't exist for post $post_id.");
397 397
 
398
-			$attachment_image_src = wp_get_attachment_image_src( $thumbnail_id, '' );
399
-			if ( $attachment_image_src ) {
398
+			$attachment_image_src = wp_get_attachment_image_src($thumbnail_id, '');
399
+			if ($attachment_image_src) {
400 400
 				return array(
401 401
 					'url'    => $attachment_image_src[0],
402 402
 					'width'  => $attachment_image_src[1],
@@ -410,27 +410,27 @@  discard block
 block discarded – undo
410 410
 		}
411 411
 
412 412
 		// Try to get the image editor and bail out if the editor cannot be instantiated.
413
-		$original_file_editor = wp_get_image_editor( $path );
414
-		if ( is_wp_error( $original_file_editor ) ) {
415
-			$this->log->warn( "Cannot instantiate WP Image Editor on file $path for post $post_id." );
413
+		$original_file_editor = wp_get_image_editor($path);
414
+		if (is_wp_error($original_file_editor)) {
415
+			$this->log->warn("Cannot instantiate WP Image Editor on file $path for post $post_id.");
416 416
 
417 417
 			return false;
418 418
 		}
419 419
 
420 420
 		// Generate the publisher logo filename, we cannot use the `width` and `height` because we're scaling
421 421
 		// and we don't actually know the end values.
422
-		$publisher_logo_path = $original_file_editor->generate_filename( '-publisher-logo' );
422
+		$publisher_logo_path = $original_file_editor->generate_filename('-publisher-logo');
423 423
 
424 424
 		// If the file doesn't exist yet, create it.
425
-		if ( ! file_exists( $publisher_logo_path ) ) {
426
-			$original_file_editor->resize( 600, 60 );
427
-			$original_file_editor->save( $publisher_logo_path );
425
+		if ( ! file_exists($publisher_logo_path)) {
426
+			$original_file_editor->resize(600, 60);
427
+			$original_file_editor->save($publisher_logo_path);
428 428
 		}
429 429
 
430 430
 		// Try to get the image editor and bail out if the editor cannot be instantiated.
431
-		$publisher_logo_editor = wp_get_image_editor( $publisher_logo_path );
432
-		if ( is_wp_error( $publisher_logo_editor ) ) {
433
-			$this->log->warn( "Cannot instantiate WP Image Editor on file $publisher_logo_path for post $post_id." );
431
+		$publisher_logo_editor = wp_get_image_editor($publisher_logo_path);
432
+		if (is_wp_error($publisher_logo_editor)) {
433
+			$this->log->warn("Cannot instantiate WP Image Editor on file $publisher_logo_path for post $post_id.");
434 434
 
435 435
 			return false;
436 436
 		}
@@ -440,7 +440,7 @@  discard block
 block discarded – undo
440 440
 
441 441
 		// Finally return the array with data.
442 442
 		return array(
443
-			'url'    => $uploads_dir['baseurl'] . substr( $publisher_logo_path, strlen( $uploads_dir['basedir'] ) ),
443
+			'url'    => $uploads_dir['baseurl'].substr($publisher_logo_path, strlen($uploads_dir['basedir'])),
444 444
 			'width'  => $size['width'],
445 445
 			'height' => $size['height'],
446 446
 		);
@@ -453,9 +453,9 @@  discard block
 block discarded – undo
453 453
 	 *
454 454
 	 * @return void
455 455
 	 */
456
-	private function set_mentions_and_about( $references, $post, &$jsonld ) {
456
+	private function set_mentions_and_about($references, $post, &$jsonld) {
457 457
 
458
-		if ( count( $references ) === 0 ) {
458
+		if (count($references) === 0) {
459 459
 			return;
460 460
 		}
461 461
 
@@ -464,23 +464,23 @@  discard block
 block discarded – undo
464 464
 		$about    = array();
465 465
 
466 466
 		// If the entity is in the title, then it should be an `about`.
467
-		foreach ( $references as $reference ) {
467
+		foreach ($references as $reference) {
468 468
 
469
-			if ( ! $reference instanceof Reference ) {
469
+			if ( ! $reference instanceof Reference) {
470 470
 				// This condition should never be reached.
471 471
 				continue;
472 472
 			}
473 473
 
474 474
 			// Get the entity labels.
475
-			$labels = Wordlift_Entity_Service::get_instance()->get_labels( $reference->get_id(), $reference->get_type() );
475
+			$labels = Wordlift_Entity_Service::get_instance()->get_labels($reference->get_id(), $reference->get_type());
476 476
 			// Get the entity URI.
477 477
 			$item = array(
478
-				'@id' => Wordlift_Entity_Service::get_instance()->get_uri( $reference->get_id(), $reference->get_type() ),
478
+				'@id' => Wordlift_Entity_Service::get_instance()->get_uri($reference->get_id(), $reference->get_type()),
479 479
 			);
480 480
 
481 481
 			$escaped_labels = array_map(
482
-				function ( $value ) {
483
-					return preg_quote( $value, '/' );
482
+				function($value) {
483
+					return preg_quote($value, '/');
484 484
 				},
485 485
 				$labels
486 486
 			);
@@ -488,13 +488,13 @@  discard block
 block discarded – undo
488 488
 			$matches = false;
489 489
 
490 490
 			// When the title is empty, then we shouldn't yield a match to about section.
491
-			if ( array_filter( $escaped_labels ) ) {
491
+			if (array_filter($escaped_labels)) {
492 492
 				// Check if the labels match any part of the title.
493
-				$matches = $this->check_title_match( $escaped_labels, $post->post_title );
493
+				$matches = $this->check_title_match($escaped_labels, $post->post_title);
494 494
 			}
495 495
 
496 496
 			// If the title matches, assign the entity to the about, otherwise to the mentions.
497
-			if ( $matches ) {
497
+			if ($matches) {
498 498
 				$about[] = $item;
499 499
 			} else {
500 500
 				$mentions[] = $item;
@@ -502,12 +502,12 @@  discard block
 block discarded – undo
502 502
 		}
503 503
 
504 504
 		// If we have abouts, assign them to the JSON-LD.
505
-		if ( 0 < count( $about ) ) {
505
+		if (0 < count($about)) {
506 506
 			$jsonld['about'] = $about;
507 507
 		}
508 508
 
509 509
 		// If we have mentions, assign them to the JSON-LD.
510
-		if ( 0 < count( $mentions ) ) {
510
+		if (0 < count($mentions)) {
511 511
 			$jsonld['mentions'] = $mentions;
512 512
 		}
513 513
 
@@ -522,15 +522,15 @@  discard block
 block discarded – undo
522 522
 	 *
523 523
 	 * @return boolean
524 524
 	 */
525
-	public function check_title_match( $labels, $title ) {
525
+	public function check_title_match($labels, $title) {
526 526
 
527 527
 		// If the title is empty, then we shouldn't yield a match to about section.
528
-		if ( empty( $title ) ) {
528
+		if (empty($title)) {
529 529
 			return false;
530 530
 		}
531 531
 
532 532
 		// Check if the labels match any part of the title.
533
-		return 1 === preg_match( '/\b(' . implode( '|', $labels ) . ')\b/iu', $title );
533
+		return 1 === preg_match('/\b('.implode('|', $labels).')\b/iu', $title);
534 534
 
535 535
 	}
536 536
 
@@ -541,13 +541,13 @@  discard block
 block discarded – undo
541 541
 	 *
542 542
 	 * @return Reference[]
543 543
 	 */
544
-	private function convert_references( $references ) {
544
+	private function convert_references($references) {
545 545
 		return array_map(
546
-			function ( $reference ) {
546
+			function($reference) {
547 547
 				// Legacy code may still push numerical references to this
548 548
 				// $references variable, so convert it to post references.
549
-				if ( is_numeric( $reference ) ) {
550
-					  return new Post_Reference( $reference );
549
+				if (is_numeric($reference)) {
550
+					  return new Post_Reference($reference);
551 551
 				}
552 552
 
553 553
 				return $reference;
Please login to merge, or discard this patch.
src/wordlift/metabox/field/class-wl-metabox-field-sameas.php 2 patches
Indentation   +177 added lines, -177 removed lines patch added patch discarded remove patch
@@ -23,102 +23,102 @@  discard block
 block discarded – undo
23 23
 // phpcs:ignore PEAR.NamingConventions.ValidClassName.Invalid
24 24
 class Wl_Metabox_Field_sameas extends Wl_Metabox_Field {
25 25
 
26
-	/**
27
-	 * @inheritdoc
28
-	 */
29
-	public function __construct( $args, $id, $type ) {
30
-		parent::__construct( $args['sameas'], $id, $type );
31
-	}
32
-
33
-	/**
34
-	 * @inheritdoc
35
-	 */
36
-	public function save_data( $values ) {
37
-		// The autocomplete select may send JSON arrays in input values.
38
-
39
-		// Only use mb_* functions when mbstring is available.
40
-		//
41
-		// See https://github.com/insideout10/wordlift-plugin/issues/693.
42
-		if ( extension_loaded( 'mbstring' ) ) {
43
-			mb_regex_encoding( 'UTF-8' );
44
-
45
-			$merged = array_reduce(
46
-				(array) $values,
47
-				function ( $carry, $item ) {
48
-					return array_merge( $carry, mb_split( "\x{2063}", wp_unslash( $item ) ) );
49
-				},
50
-				array()
51
-			);
52
-		} else {
53
-			$merged = array_reduce(
54
-				(array) $values,
55
-				function ( $carry, $item ) {
56
-					return array_merge( $carry, preg_split( "/\x{2063}/u", wp_unslash( $item ) ) );
57
-				},
58
-				array()
59
-			);
60
-		}
61
-
62
-		// Convert all escaped special characters to their original.
63
-		$merged = array_map( 'urldecode', $merged );
64
-
65
-		$merged = $this->filter_urls( $merged );
66
-
67
-		parent::save_data( $merged );
68
-	}
69
-
70
-	/**
71
-	 * Encode URL Path to fix non ASCII characters.
72
-	 *
73
-	 * @param string $url URL to check.
74
-	 *
75
-	 * @return string Encoded URL.
76
-	 */
77
-	public function encode_path( $url ) {
78
-		$path         = wp_parse_url( $url, PHP_URL_PATH );
79
-		$encoded_path = array_map( 'urlencode', explode( '/', $path ) );
80
-		return str_replace( $path, implode( '/', $encoded_path ), $url );
81
-	}
82
-
83
-	/**
84
-	 * @inheritdoc
85
-	 */
86
-	public function sanitize_data_filter( $value ) {
87
-
88
-		// Call our sanitizer helper.
89
-		return Wordlift_Sanitizer::sanitize_url( $value );
90
-	}
91
-
92
-	/**
93
-	 * @inheritdoc
94
-	 */
95
-	protected function get_heading_html() {
96
-
97
-		// Add the select html fragment after the heading.
98
-		return parent::get_heading_html()
99
-			   . $this->get_select_html();
100
-	}
101
-
102
-	/**
103
-	 * Get the select html fragment.
104
-	 *
105
-	 * @return string The html fragment.
106
-	 * @since 3.15.0
107
-	 */
108
-	private function get_select_html() {
109
-		// Return an element where the new Autocomplete Select will attach to.
110
-		return '<p>'
111
-			   . esc_html__( 'Use the search below to link this entity with equivalent entities in the linked data cloud.', 'wordlift' )
112
-			   . '<div id="wl-metabox-field-sameas"></div></p>';
113
-	}
114
-
115
-	/**
116
-	 * @inheritdoc
117
-	 */
118
-	protected function get_add_button_html( $count ) {
119
-
120
-		return sprintf(
121
-			'
26
+    /**
27
+     * @inheritdoc
28
+     */
29
+    public function __construct( $args, $id, $type ) {
30
+        parent::__construct( $args['sameas'], $id, $type );
31
+    }
32
+
33
+    /**
34
+     * @inheritdoc
35
+     */
36
+    public function save_data( $values ) {
37
+        // The autocomplete select may send JSON arrays in input values.
38
+
39
+        // Only use mb_* functions when mbstring is available.
40
+        //
41
+        // See https://github.com/insideout10/wordlift-plugin/issues/693.
42
+        if ( extension_loaded( 'mbstring' ) ) {
43
+            mb_regex_encoding( 'UTF-8' );
44
+
45
+            $merged = array_reduce(
46
+                (array) $values,
47
+                function ( $carry, $item ) {
48
+                    return array_merge( $carry, mb_split( "\x{2063}", wp_unslash( $item ) ) );
49
+                },
50
+                array()
51
+            );
52
+        } else {
53
+            $merged = array_reduce(
54
+                (array) $values,
55
+                function ( $carry, $item ) {
56
+                    return array_merge( $carry, preg_split( "/\x{2063}/u", wp_unslash( $item ) ) );
57
+                },
58
+                array()
59
+            );
60
+        }
61
+
62
+        // Convert all escaped special characters to their original.
63
+        $merged = array_map( 'urldecode', $merged );
64
+
65
+        $merged = $this->filter_urls( $merged );
66
+
67
+        parent::save_data( $merged );
68
+    }
69
+
70
+    /**
71
+     * Encode URL Path to fix non ASCII characters.
72
+     *
73
+     * @param string $url URL to check.
74
+     *
75
+     * @return string Encoded URL.
76
+     */
77
+    public function encode_path( $url ) {
78
+        $path         = wp_parse_url( $url, PHP_URL_PATH );
79
+        $encoded_path = array_map( 'urlencode', explode( '/', $path ) );
80
+        return str_replace( $path, implode( '/', $encoded_path ), $url );
81
+    }
82
+
83
+    /**
84
+     * @inheritdoc
85
+     */
86
+    public function sanitize_data_filter( $value ) {
87
+
88
+        // Call our sanitizer helper.
89
+        return Wordlift_Sanitizer::sanitize_url( $value );
90
+    }
91
+
92
+    /**
93
+     * @inheritdoc
94
+     */
95
+    protected function get_heading_html() {
96
+
97
+        // Add the select html fragment after the heading.
98
+        return parent::get_heading_html()
99
+                . $this->get_select_html();
100
+    }
101
+
102
+    /**
103
+     * Get the select html fragment.
104
+     *
105
+     * @return string The html fragment.
106
+     * @since 3.15.0
107
+     */
108
+    private function get_select_html() {
109
+        // Return an element where the new Autocomplete Select will attach to.
110
+        return '<p>'
111
+                . esc_html__( 'Use the search below to link this entity with equivalent entities in the linked data cloud.', 'wordlift' )
112
+                . '<div id="wl-metabox-field-sameas"></div></p>';
113
+    }
114
+
115
+    /**
116
+     * @inheritdoc
117
+     */
118
+    protected function get_add_button_html( $count ) {
119
+
120
+        return sprintf(
121
+            '
122 122
             <button type="button" class="wl-add-input wl-add-input--link">%1$s</button>
123 123
 	        <div style="display: none;">
124 124
 	            <div class="wl-input-wrapper">
@@ -128,60 +128,60 @@  discard block
 block discarded – undo
128 128
             </div>
129 129
             <fieldset id="wl-input-container">%4$s</fieldset>
130 130
             ',
131
-			esc_html__( 'Click here to manually add URLs', 'wordlift' ),
132
-			esc_attr( $this->meta_name ),
133
-			esc_attr_x( 'Type here the URL of an equivalent entity from another dataset.', 'sameAs metabox input', 'wordlift' ),
134
-			$this->get_stored_values_html( $count )
135
-		) .
136
-			   parent::get_add_custom_button_html( $count, 'Add Another URL', 'hide' );
137
-
138
-	}
139
-
140
-	/**
141
-	 * @inheritdoc
142
-	 */
143
-	public function html() {
144
-
145
-		/**
146
-		 * Filter: wl_feature__enable__metabox-sameas.
147
-		 *
148
-		 * @param bool whether the sameAs metabox should be shown, defaults to true.
149
-		 *
150
-		 * @return bool
151
-		 * @since 3.29.1
152
-		 */
153
-		// phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
154
-		if ( apply_filters( 'wl_feature__enable__metabox-sameas', true ) ) {
155
-
156
-			// Open main <div> for the Field.
157
-			$html = $this->html_wrapper_open();
158
-
159
-			// Label.
160
-			$html .= $this->get_heading_html();
161
-
162
-			// print nonce.
163
-			$html .= $this->html_nonce();
164
-
165
-			// print data loaded from DB.
166
-			$count = 0;
167
-
168
-			// If cardinality allows it, print button to add new values.
169
-			$html .= $this->get_add_button_html( $count );
170
-
171
-			// Close the HTML wrapper.
172
-			$html .= $this->html_wrapper_close();
173
-
174
-			return $html;
175
-		}
176
-	}
177
-
178
-	/**
179
-	 * @inheritdoc
180
-	 */
181
-	public function html_input( $value ) {
182
-		// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
183
-		@ob_start();
184
-		?>
131
+            esc_html__( 'Click here to manually add URLs', 'wordlift' ),
132
+            esc_attr( $this->meta_name ),
133
+            esc_attr_x( 'Type here the URL of an equivalent entity from another dataset.', 'sameAs metabox input', 'wordlift' ),
134
+            $this->get_stored_values_html( $count )
135
+        ) .
136
+                parent::get_add_custom_button_html( $count, 'Add Another URL', 'hide' );
137
+
138
+    }
139
+
140
+    /**
141
+     * @inheritdoc
142
+     */
143
+    public function html() {
144
+
145
+        /**
146
+         * Filter: wl_feature__enable__metabox-sameas.
147
+         *
148
+         * @param bool whether the sameAs metabox should be shown, defaults to true.
149
+         *
150
+         * @return bool
151
+         * @since 3.29.1
152
+         */
153
+        // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
154
+        if ( apply_filters( 'wl_feature__enable__metabox-sameas', true ) ) {
155
+
156
+            // Open main <div> for the Field.
157
+            $html = $this->html_wrapper_open();
158
+
159
+            // Label.
160
+            $html .= $this->get_heading_html();
161
+
162
+            // print nonce.
163
+            $html .= $this->html_nonce();
164
+
165
+            // print data loaded from DB.
166
+            $count = 0;
167
+
168
+            // If cardinality allows it, print button to add new values.
169
+            $html .= $this->get_add_button_html( $count );
170
+
171
+            // Close the HTML wrapper.
172
+            $html .= $this->html_wrapper_close();
173
+
174
+            return $html;
175
+        }
176
+    }
177
+
178
+    /**
179
+     * @inheritdoc
180
+     */
181
+    public function html_input( $value ) {
182
+        // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
183
+        @ob_start();
184
+        ?>
185 185
 		<div class="wl-input-wrapper wl-input-wrapper-readonly">
186 186
 			<input
187 187
 					type="text"
@@ -195,32 +195,32 @@  discard block
 block discarded – undo
195 195
 		</div>
196 196
 		<?php
197 197
 
198
-		$html = ob_get_clean();
199
-
200
-		return $html;
201
-	}
202
-
203
-	/**
204
-	 * @param array $urls
205
-	 *
206
-	 * @return array
207
-	 */
208
-	private function filter_urls( $urls ) {
209
-		$configuration_service = Wordlift_Configuration_Service::get_instance();
210
-		$dataset_uri           = $configuration_service->get_dataset_uri();
211
-
212
-		return array_filter(
213
-			$urls,
214
-			function ( $url ) use ( $dataset_uri ) {
215
-				$url_validation = filter_var( $this->encode_path( $url ), FILTER_VALIDATE_URL );
216
-				if ( null === $dataset_uri ) {
217
-					return $url_validation;
218
-				}
219
-
220
-				// URLs should not start with local dataset uri.
221
-				return $url_validation && ( empty( $dataset_uri ) || 0 !== strpos( $url, $dataset_uri ) );
222
-			}
223
-		);
224
-	}
198
+        $html = ob_get_clean();
199
+
200
+        return $html;
201
+    }
202
+
203
+    /**
204
+     * @param array $urls
205
+     *
206
+     * @return array
207
+     */
208
+    private function filter_urls( $urls ) {
209
+        $configuration_service = Wordlift_Configuration_Service::get_instance();
210
+        $dataset_uri           = $configuration_service->get_dataset_uri();
211
+
212
+        return array_filter(
213
+            $urls,
214
+            function ( $url ) use ( $dataset_uri ) {
215
+                $url_validation = filter_var( $this->encode_path( $url ), FILTER_VALIDATE_URL );
216
+                if ( null === $dataset_uri ) {
217
+                    return $url_validation;
218
+                }
219
+
220
+                // URLs should not start with local dataset uri.
221
+                return $url_validation && ( empty( $dataset_uri ) || 0 !== strpos( $url, $dataset_uri ) );
222
+            }
223
+        );
224
+    }
225 225
 
226 226
 }
Please login to merge, or discard this patch.
Spacing   +37 added lines, -37 removed lines patch added patch discarded remove patch
@@ -26,45 +26,45 @@  discard block
 block discarded – undo
26 26
 	/**
27 27
 	 * @inheritdoc
28 28
 	 */
29
-	public function __construct( $args, $id, $type ) {
30
-		parent::__construct( $args['sameas'], $id, $type );
29
+	public function __construct($args, $id, $type) {
30
+		parent::__construct($args['sameas'], $id, $type);
31 31
 	}
32 32
 
33 33
 	/**
34 34
 	 * @inheritdoc
35 35
 	 */
36
-	public function save_data( $values ) {
36
+	public function save_data($values) {
37 37
 		// The autocomplete select may send JSON arrays in input values.
38 38
 
39 39
 		// Only use mb_* functions when mbstring is available.
40 40
 		//
41 41
 		// See https://github.com/insideout10/wordlift-plugin/issues/693.
42
-		if ( extension_loaded( 'mbstring' ) ) {
43
-			mb_regex_encoding( 'UTF-8' );
42
+		if (extension_loaded('mbstring')) {
43
+			mb_regex_encoding('UTF-8');
44 44
 
45 45
 			$merged = array_reduce(
46 46
 				(array) $values,
47
-				function ( $carry, $item ) {
48
-					return array_merge( $carry, mb_split( "\x{2063}", wp_unslash( $item ) ) );
47
+				function($carry, $item) {
48
+					return array_merge($carry, mb_split("\x{2063}", wp_unslash($item)));
49 49
 				},
50 50
 				array()
51 51
 			);
52 52
 		} else {
53 53
 			$merged = array_reduce(
54 54
 				(array) $values,
55
-				function ( $carry, $item ) {
56
-					return array_merge( $carry, preg_split( "/\x{2063}/u", wp_unslash( $item ) ) );
55
+				function($carry, $item) {
56
+					return array_merge($carry, preg_split("/\x{2063}/u", wp_unslash($item)));
57 57
 				},
58 58
 				array()
59 59
 			);
60 60
 		}
61 61
 
62 62
 		// Convert all escaped special characters to their original.
63
-		$merged = array_map( 'urldecode', $merged );
63
+		$merged = array_map('urldecode', $merged);
64 64
 
65
-		$merged = $this->filter_urls( $merged );
65
+		$merged = $this->filter_urls($merged);
66 66
 
67
-		parent::save_data( $merged );
67
+		parent::save_data($merged);
68 68
 	}
69 69
 
70 70
 	/**
@@ -74,19 +74,19 @@  discard block
 block discarded – undo
74 74
 	 *
75 75
 	 * @return string Encoded URL.
76 76
 	 */
77
-	public function encode_path( $url ) {
78
-		$path         = wp_parse_url( $url, PHP_URL_PATH );
79
-		$encoded_path = array_map( 'urlencode', explode( '/', $path ) );
80
-		return str_replace( $path, implode( '/', $encoded_path ), $url );
77
+	public function encode_path($url) {
78
+		$path         = wp_parse_url($url, PHP_URL_PATH);
79
+		$encoded_path = array_map('urlencode', explode('/', $path));
80
+		return str_replace($path, implode('/', $encoded_path), $url);
81 81
 	}
82 82
 
83 83
 	/**
84 84
 	 * @inheritdoc
85 85
 	 */
86
-	public function sanitize_data_filter( $value ) {
86
+	public function sanitize_data_filter($value) {
87 87
 
88 88
 		// Call our sanitizer helper.
89
-		return Wordlift_Sanitizer::sanitize_url( $value );
89
+		return Wordlift_Sanitizer::sanitize_url($value);
90 90
 	}
91 91
 
92 92
 	/**
@@ -108,14 +108,14 @@  discard block
 block discarded – undo
108 108
 	private function get_select_html() {
109 109
 		// Return an element where the new Autocomplete Select will attach to.
110 110
 		return '<p>'
111
-			   . esc_html__( 'Use the search below to link this entity with equivalent entities in the linked data cloud.', 'wordlift' )
111
+			   . esc_html__('Use the search below to link this entity with equivalent entities in the linked data cloud.', 'wordlift')
112 112
 			   . '<div id="wl-metabox-field-sameas"></div></p>';
113 113
 	}
114 114
 
115 115
 	/**
116 116
 	 * @inheritdoc
117 117
 	 */
118
-	protected function get_add_button_html( $count ) {
118
+	protected function get_add_button_html($count) {
119 119
 
120 120
 		return sprintf(
121 121
 			'
@@ -128,12 +128,12 @@  discard block
 block discarded – undo
128 128
             </div>
129 129
             <fieldset id="wl-input-container">%4$s</fieldset>
130 130
             ',
131
-			esc_html__( 'Click here to manually add URLs', 'wordlift' ),
132
-			esc_attr( $this->meta_name ),
133
-			esc_attr_x( 'Type here the URL of an equivalent entity from another dataset.', 'sameAs metabox input', 'wordlift' ),
134
-			$this->get_stored_values_html( $count )
135
-		) .
136
-			   parent::get_add_custom_button_html( $count, 'Add Another URL', 'hide' );
131
+			esc_html__('Click here to manually add URLs', 'wordlift'),
132
+			esc_attr($this->meta_name),
133
+			esc_attr_x('Type here the URL of an equivalent entity from another dataset.', 'sameAs metabox input', 'wordlift'),
134
+			$this->get_stored_values_html($count)
135
+		).
136
+			   parent::get_add_custom_button_html($count, 'Add Another URL', 'hide');
137 137
 
138 138
 	}
139 139
 
@@ -151,7 +151,7 @@  discard block
 block discarded – undo
151 151
 		 * @since 3.29.1
152 152
 		 */
153 153
 		// phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
154
-		if ( apply_filters( 'wl_feature__enable__metabox-sameas', true ) ) {
154
+		if (apply_filters('wl_feature__enable__metabox-sameas', true)) {
155 155
 
156 156
 			// Open main <div> for the Field.
157 157
 			$html = $this->html_wrapper_open();
@@ -166,7 +166,7 @@  discard block
 block discarded – undo
166 166
 			$count = 0;
167 167
 
168 168
 			// If cardinality allows it, print button to add new values.
169
-			$html .= $this->get_add_button_html( $count );
169
+			$html .= $this->get_add_button_html($count);
170 170
 
171 171
 			// Close the HTML wrapper.
172 172
 			$html .= $this->html_wrapper_close();
@@ -178,7 +178,7 @@  discard block
 block discarded – undo
178 178
 	/**
179 179
 	 * @inheritdoc
180 180
 	 */
181
-	public function html_input( $value ) {
181
+	public function html_input($value) {
182 182
 		// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
183 183
 		@ob_start();
184 184
 		?>
@@ -186,9 +186,9 @@  discard block
 block discarded – undo
186 186
 			<input
187 187
 					type="text"
188 188
 					readonly="readonly"
189
-					id="<?php echo esc_attr( $this->meta_name ); ?>"
190
-					name="wl_metaboxes[<?php echo esc_attr( $this->meta_name ); ?>][]"
191
-					value="<?php echo esc_attr( $value ); ?>"
189
+					id="<?php echo esc_attr($this->meta_name); ?>"
190
+					name="wl_metaboxes[<?php echo esc_attr($this->meta_name); ?>][]"
191
+					value="<?php echo esc_attr($value); ?>"
192 192
 			/>
193 193
 
194 194
 			<button class="wl-remove-input wl-remove-input--sameas"></button>
@@ -205,20 +205,20 @@  discard block
 block discarded – undo
205 205
 	 *
206 206
 	 * @return array
207 207
 	 */
208
-	private function filter_urls( $urls ) {
208
+	private function filter_urls($urls) {
209 209
 		$configuration_service = Wordlift_Configuration_Service::get_instance();
210 210
 		$dataset_uri           = $configuration_service->get_dataset_uri();
211 211
 
212 212
 		return array_filter(
213 213
 			$urls,
214
-			function ( $url ) use ( $dataset_uri ) {
215
-				$url_validation = filter_var( $this->encode_path( $url ), FILTER_VALIDATE_URL );
216
-				if ( null === $dataset_uri ) {
214
+			function($url) use ($dataset_uri) {
215
+				$url_validation = filter_var($this->encode_path($url), FILTER_VALIDATE_URL);
216
+				if (null === $dataset_uri) {
217 217
 					return $url_validation;
218 218
 				}
219 219
 
220 220
 				// URLs should not start with local dataset uri.
221
-				return $url_validation && ( empty( $dataset_uri ) || 0 !== strpos( $url, $dataset_uri ) );
221
+				return $url_validation && (empty($dataset_uri) || 0 !== strpos($url, $dataset_uri));
222 222
 			}
223 223
 		);
224 224
 	}
Please login to merge, or discard this patch.
src/wordlift/jsonld/class-mentions.php 2 patches
Indentation   +222 added lines, -222 removed lines patch added patch discarded remove patch
@@ -16,242 +16,242 @@
 block discarded – undo
16 16
 
17 17
 class Mentions {
18 18
 
19
-	private static $schema_descendants = array(
20
-		'AmpStory',
21
-		'ArchiveComponent',
22
-		'Article',
23
-		'Atlas',
24
-		'Blog',
25
-		'Book',
26
-		'Chapter',
27
-		'Claim',
28
-		'Clip',
29
-		'Code',
30
-		'Collection',
31
-		'ComicStory',
32
-		'Comment',
33
-		'Conversation',
34
-		'Course',
35
-		'CreativeWorkSeason',
36
-		'CreativeWorkSeries',
37
-		'DataCatalog',
38
-		'Dataset',
39
-		'DefinedTermSet',
40
-		'Diet',
41
-		'DigitalDocument',
42
-		'Drawing',
43
-		'EducationalOccupationalCredential',
44
-		'Episode',
45
-		'ExercisePlan',
46
-		'Game',
47
-		'Guide',
48
-		'HowTo',
49
-		'HowToDirection',
50
-		'HowToSection',
51
-		'HowToStep',
52
-		'HowToTip',
53
-		'HyperToc',
54
-		'HyperTocEntry',
55
-		'LearningResource',
56
-		'Legislation',
57
-		'Manuscript',
58
-		'Map',
59
-		'MathSolver',
60
-		'MediaObject',
61
-		'Menu',
62
-		'MenuSection',
63
-		'Message',
64
-		'Movie',
65
-		'MusicComposition',
66
-		'MusicPlaylist',
67
-		'MusicRecording',
68
-		'Painting',
69
-		'Photograph',
70
-		'Play',
71
-		'Poster',
72
-		'PublicationIssue',
73
-		'PublicationVolume',
74
-		'Quotation',
75
-		'Review',
76
-		'Sculpture',
77
-		'Season',
78
-		'SheetMusic',
79
-		'ShortStory',
80
-		'SoftwareApplication',
81
-		'SoftwareSourceCode',
82
-		'SpecialAnnouncement',
83
-		'Thesis',
84
-		'TvSeason',
85
-		'TvSeries',
86
-		'VisualArtwork',
87
-		'WebContent',
88
-		'WebPage',
89
-		'WebPageElement',
90
-		'WebSite',
91
-		'AdvertiserContentArticle',
92
-		'NewsArticle',
93
-		'Report',
94
-		'SatiricalArticle',
95
-		'ScholarlyArticle',
96
-		'SocialMediaPosting',
97
-		'TechArticle',
98
-		'AnalysisNewsArticle',
99
-		'AskPublicNewsArticle',
100
-		'BackgroundNewsArticle',
101
-		'OpinionNewsArticle',
102
-		'ReportageNewsArticle',
103
-		'ReviewNewsArticle',
104
-		'MedicalScholarlyArticle',
105
-		'BlogPosting',
106
-		'DiscussionForumPosting',
107
-		'LiveBlogPosting',
108
-		'ApiReference',
109
-		'Audiobook',
110
-		'MovieClip',
111
-		'RadioClip',
112
-		'TvClip',
113
-		'VideoGameClip',
114
-		'ProductCollection',
115
-		'ComicCoverArt',
116
-		'Answer',
117
-		'CorrectionComment',
118
-		'Question',
119
-		'PodcastSeason',
120
-		'RadioSeason',
121
-		'TvSeason',
122
-		'BookSeries',
123
-		'MovieSeries',
124
-		'Periodical',
125
-		'PodcastSeries',
126
-		'RadioSeries',
127
-		'TvSeries',
128
-		'VideoGameSeries',
129
-		'ComicSeries',
130
-		'Newspaper',
131
-		'DataFeed',
132
-		'CompleteDataFeed',
133
-		'CategoryCodeSet',
134
-		'NoteDigitalDocument',
135
-		'PresentationDigitalDocument',
136
-		'SpreadsheetDigitalDocument',
137
-		'TextDigitalDocument',
138
-		'PodcastEpisode',
139
-		'RadioEpisode',
140
-		'TvEpisode',
141
-		'VideoGame',
142
-		'Recipe',
143
-		'Course',
144
-		'Quiz',
145
-		'LegislationObject',
146
-		'AudioObject',
147
-		'DModel',
148
-		'DataDownload',
149
-		'ImageObject',
150
-		'LegislationObject',
151
-		'MusicVideoObject',
152
-		'VideoObject',
153
-		'Audiobook',
154
-		'Barcode',
155
-		'EmailMessage',
156
-		'MusicAlbum',
157
-		'MusicRelease',
158
-		'ComicIssue',
159
-		'ClaimReview',
160
-		'CriticReview',
161
-		'EmployerReview',
162
-		'MediaReview',
163
-		'Recommendation',
164
-		'UserReview',
165
-		'ReviewNewsArticle',
166
-		'MobileApplication',
167
-		'VideoGame',
168
-		'WebApplication',
169
-		'CoverArt',
170
-		'ComicCoverArt',
171
-		'HealthTopicContent',
172
-		'AboutPage',
173
-		'CheckoutPage',
174
-		'CollectionPage',
175
-		'ContactPage',
176
-		'FaqPage',
177
-		'ItemPage',
178
-		'MedicalWebPage',
179
-		'ProfilePage',
180
-		'QaPage',
181
-		'RealEstateListing',
182
-		'SearchResultsPage',
183
-		'MediaGallery',
184
-		'ImageGallery',
185
-		'VideoGallery',
186
-		'SiteNavigationElement',
187
-		'Table',
188
-		'WpAdBlock',
189
-		'WpFooter',
190
-		'WpHeader',
191
-		'WpSideBar',
192
-	);
19
+    private static $schema_descendants = array(
20
+        'AmpStory',
21
+        'ArchiveComponent',
22
+        'Article',
23
+        'Atlas',
24
+        'Blog',
25
+        'Book',
26
+        'Chapter',
27
+        'Claim',
28
+        'Clip',
29
+        'Code',
30
+        'Collection',
31
+        'ComicStory',
32
+        'Comment',
33
+        'Conversation',
34
+        'Course',
35
+        'CreativeWorkSeason',
36
+        'CreativeWorkSeries',
37
+        'DataCatalog',
38
+        'Dataset',
39
+        'DefinedTermSet',
40
+        'Diet',
41
+        'DigitalDocument',
42
+        'Drawing',
43
+        'EducationalOccupationalCredential',
44
+        'Episode',
45
+        'ExercisePlan',
46
+        'Game',
47
+        'Guide',
48
+        'HowTo',
49
+        'HowToDirection',
50
+        'HowToSection',
51
+        'HowToStep',
52
+        'HowToTip',
53
+        'HyperToc',
54
+        'HyperTocEntry',
55
+        'LearningResource',
56
+        'Legislation',
57
+        'Manuscript',
58
+        'Map',
59
+        'MathSolver',
60
+        'MediaObject',
61
+        'Menu',
62
+        'MenuSection',
63
+        'Message',
64
+        'Movie',
65
+        'MusicComposition',
66
+        'MusicPlaylist',
67
+        'MusicRecording',
68
+        'Painting',
69
+        'Photograph',
70
+        'Play',
71
+        'Poster',
72
+        'PublicationIssue',
73
+        'PublicationVolume',
74
+        'Quotation',
75
+        'Review',
76
+        'Sculpture',
77
+        'Season',
78
+        'SheetMusic',
79
+        'ShortStory',
80
+        'SoftwareApplication',
81
+        'SoftwareSourceCode',
82
+        'SpecialAnnouncement',
83
+        'Thesis',
84
+        'TvSeason',
85
+        'TvSeries',
86
+        'VisualArtwork',
87
+        'WebContent',
88
+        'WebPage',
89
+        'WebPageElement',
90
+        'WebSite',
91
+        'AdvertiserContentArticle',
92
+        'NewsArticle',
93
+        'Report',
94
+        'SatiricalArticle',
95
+        'ScholarlyArticle',
96
+        'SocialMediaPosting',
97
+        'TechArticle',
98
+        'AnalysisNewsArticle',
99
+        'AskPublicNewsArticle',
100
+        'BackgroundNewsArticle',
101
+        'OpinionNewsArticle',
102
+        'ReportageNewsArticle',
103
+        'ReviewNewsArticle',
104
+        'MedicalScholarlyArticle',
105
+        'BlogPosting',
106
+        'DiscussionForumPosting',
107
+        'LiveBlogPosting',
108
+        'ApiReference',
109
+        'Audiobook',
110
+        'MovieClip',
111
+        'RadioClip',
112
+        'TvClip',
113
+        'VideoGameClip',
114
+        'ProductCollection',
115
+        'ComicCoverArt',
116
+        'Answer',
117
+        'CorrectionComment',
118
+        'Question',
119
+        'PodcastSeason',
120
+        'RadioSeason',
121
+        'TvSeason',
122
+        'BookSeries',
123
+        'MovieSeries',
124
+        'Periodical',
125
+        'PodcastSeries',
126
+        'RadioSeries',
127
+        'TvSeries',
128
+        'VideoGameSeries',
129
+        'ComicSeries',
130
+        'Newspaper',
131
+        'DataFeed',
132
+        'CompleteDataFeed',
133
+        'CategoryCodeSet',
134
+        'NoteDigitalDocument',
135
+        'PresentationDigitalDocument',
136
+        'SpreadsheetDigitalDocument',
137
+        'TextDigitalDocument',
138
+        'PodcastEpisode',
139
+        'RadioEpisode',
140
+        'TvEpisode',
141
+        'VideoGame',
142
+        'Recipe',
143
+        'Course',
144
+        'Quiz',
145
+        'LegislationObject',
146
+        'AudioObject',
147
+        'DModel',
148
+        'DataDownload',
149
+        'ImageObject',
150
+        'LegislationObject',
151
+        'MusicVideoObject',
152
+        'VideoObject',
153
+        'Audiobook',
154
+        'Barcode',
155
+        'EmailMessage',
156
+        'MusicAlbum',
157
+        'MusicRelease',
158
+        'ComicIssue',
159
+        'ClaimReview',
160
+        'CriticReview',
161
+        'EmployerReview',
162
+        'MediaReview',
163
+        'Recommendation',
164
+        'UserReview',
165
+        'ReviewNewsArticle',
166
+        'MobileApplication',
167
+        'VideoGame',
168
+        'WebApplication',
169
+        'CoverArt',
170
+        'ComicCoverArt',
171
+        'HealthTopicContent',
172
+        'AboutPage',
173
+        'CheckoutPage',
174
+        'CollectionPage',
175
+        'ContactPage',
176
+        'FaqPage',
177
+        'ItemPage',
178
+        'MedicalWebPage',
179
+        'ProfilePage',
180
+        'QaPage',
181
+        'RealEstateListing',
182
+        'SearchResultsPage',
183
+        'MediaGallery',
184
+        'ImageGallery',
185
+        'VideoGallery',
186
+        'SiteNavigationElement',
187
+        'Table',
188
+        'WpAdBlock',
189
+        'WpFooter',
190
+        'WpHeader',
191
+        'WpSideBar',
192
+    );
193 193
 
194
-	public function __construct() {
195
-		add_filter( 'wl_after_get_jsonld', array( $this, 'wl_after_get_jsonld' ), 10, 2 );
196
-	}
194
+    public function __construct() {
195
+        add_filter( 'wl_after_get_jsonld', array( $this, 'wl_after_get_jsonld' ), 10, 2 );
196
+    }
197 197
 
198
-	public function wl_after_get_jsonld( $jsonld, $post_id ) {
198
+    public function wl_after_get_jsonld( $jsonld, $post_id ) {
199 199
 
200
-		if ( count( $jsonld ) === 0 || ! is_array( $jsonld[0] ) || ! array_key_exists( '@type', $jsonld[0] ) || array_key_exists( 'mentions', $jsonld[0] ) ) {
201
-			return $jsonld;
202
-		}
200
+        if ( count( $jsonld ) === 0 || ! is_array( $jsonld[0] ) || ! array_key_exists( '@type', $jsonld[0] ) || array_key_exists( 'mentions', $jsonld[0] ) ) {
201
+            return $jsonld;
202
+        }
203 203
 
204
-		$type = $jsonld[0]['@type'];
204
+        $type = $jsonld[0]['@type'];
205 205
 
206
-		if ( ! $this->entity_is_descendant_of_creative_work( $type ) && ! $this->entity_is_creative_work( $type ) ) {
207
-			return $jsonld;
208
-		}
206
+        if ( ! $this->entity_is_descendant_of_creative_work( $type ) && ! $this->entity_is_creative_work( $type ) ) {
207
+            return $jsonld;
208
+        }
209 209
 
210
-		$entity_references = Object_Relation_Service::get_instance()
211
-													->get_references( $post_id, Object_Type_Enum::POST );
210
+        $entity_references = Object_Relation_Service::get_instance()
211
+                                                    ->get_references( $post_id, Object_Type_Enum::POST );
212 212
 
213
-		$about_id = array();
214
-		if ( array_key_exists( 'about', $jsonld[0] ) ) {
215
-			foreach ( $jsonld[0]['about'] as $about ) {
216
-				$about_id[] = $about['@id'];
217
-			}
218
-		}
213
+        $about_id = array();
214
+        if ( array_key_exists( 'about', $jsonld[0] ) ) {
215
+            foreach ( $jsonld[0]['about'] as $about ) {
216
+                $about_id[] = $about['@id'];
217
+            }
218
+        }
219 219
 
220
-		$jsonld[0]['mentions'] = array_values(
221
-			array_filter(
222
-				array_map(
223
-					function ( $item ) use ( $about_id ) {
224
-						$id = \Wordlift_Entity_Service::get_instance()->get_uri( $item->get_id() );
225
-						if ( ! $id || in_array( $id, $about_id, true ) ) {
226
-							return false;
227
-						}
220
+        $jsonld[0]['mentions'] = array_values(
221
+            array_filter(
222
+                array_map(
223
+                    function ( $item ) use ( $about_id ) {
224
+                        $id = \Wordlift_Entity_Service::get_instance()->get_uri( $item->get_id() );
225
+                        if ( ! $id || in_array( $id, $about_id, true ) ) {
226
+                            return false;
227
+                        }
228 228
 
229
-						return array( '@id' => $id );
229
+                        return array( '@id' => $id );
230 230
 
231
-					},
232
-					$entity_references
233
-				)
234
-			)
235
-		);
231
+                    },
232
+                    $entity_references
233
+                )
234
+            )
235
+        );
236 236
 
237
-		// Remove mentions if the count is zero.
238
-		if ( count( $jsonld[0]['mentions'] ) === 0 ) {
239
-			unset( $jsonld[0]['mentions'] );
240
-		}
237
+        // Remove mentions if the count is zero.
238
+        if ( count( $jsonld[0]['mentions'] ) === 0 ) {
239
+            unset( $jsonld[0]['mentions'] );
240
+        }
241 241
 
242
-		return $jsonld;
243
-	}
242
+        return $jsonld;
243
+    }
244 244
 
245
-	private function entity_is_descendant_of_creative_work( $type ) {
246
-		if ( is_string( $type ) ) {
247
-			$type = array( $type );
248
-		}
245
+    private function entity_is_descendant_of_creative_work( $type ) {
246
+        if ( is_string( $type ) ) {
247
+            $type = array( $type );
248
+        }
249 249
 
250
-		return count( array_intersect( $type, $this::$schema_descendants ) ) > 0;
251
-	}
250
+        return count( array_intersect( $type, $this::$schema_descendants ) ) > 0;
251
+    }
252 252
 
253
-	private function entity_is_creative_work( $type ) {
254
-		return ( 'CreativeWork' === $type ) || ( is_array( $type ) && in_array( 'CreativeWork', $type, true ) );
255
-	}
253
+    private function entity_is_creative_work( $type ) {
254
+        return ( 'CreativeWork' === $type ) || ( is_array( $type ) && in_array( 'CreativeWork', $type, true ) );
255
+    }
256 256
 
257 257
 }
Please login to merge, or discard this patch.
Spacing   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -192,27 +192,27 @@  discard block
 block discarded – undo
192 192
 	);
193 193
 
194 194
 	public function __construct() {
195
-		add_filter( 'wl_after_get_jsonld', array( $this, 'wl_after_get_jsonld' ), 10, 2 );
195
+		add_filter('wl_after_get_jsonld', array($this, 'wl_after_get_jsonld'), 10, 2);
196 196
 	}
197 197
 
198
-	public function wl_after_get_jsonld( $jsonld, $post_id ) {
198
+	public function wl_after_get_jsonld($jsonld, $post_id) {
199 199
 
200
-		if ( count( $jsonld ) === 0 || ! is_array( $jsonld[0] ) || ! array_key_exists( '@type', $jsonld[0] ) || array_key_exists( 'mentions', $jsonld[0] ) ) {
200
+		if (count($jsonld) === 0 || ! is_array($jsonld[0]) || ! array_key_exists('@type', $jsonld[0]) || array_key_exists('mentions', $jsonld[0])) {
201 201
 			return $jsonld;
202 202
 		}
203 203
 
204 204
 		$type = $jsonld[0]['@type'];
205 205
 
206
-		if ( ! $this->entity_is_descendant_of_creative_work( $type ) && ! $this->entity_is_creative_work( $type ) ) {
206
+		if ( ! $this->entity_is_descendant_of_creative_work($type) && ! $this->entity_is_creative_work($type)) {
207 207
 			return $jsonld;
208 208
 		}
209 209
 
210 210
 		$entity_references = Object_Relation_Service::get_instance()
211
-													->get_references( $post_id, Object_Type_Enum::POST );
211
+													->get_references($post_id, Object_Type_Enum::POST);
212 212
 
213 213
 		$about_id = array();
214
-		if ( array_key_exists( 'about', $jsonld[0] ) ) {
215
-			foreach ( $jsonld[0]['about'] as $about ) {
214
+		if (array_key_exists('about', $jsonld[0])) {
215
+			foreach ($jsonld[0]['about'] as $about) {
216 216
 				$about_id[] = $about['@id'];
217 217
 			}
218 218
 		}
@@ -220,13 +220,13 @@  discard block
 block discarded – undo
220 220
 		$jsonld[0]['mentions'] = array_values(
221 221
 			array_filter(
222 222
 				array_map(
223
-					function ( $item ) use ( $about_id ) {
224
-						$id = \Wordlift_Entity_Service::get_instance()->get_uri( $item->get_id() );
225
-						if ( ! $id || in_array( $id, $about_id, true ) ) {
223
+					function($item) use ($about_id) {
224
+						$id = \Wordlift_Entity_Service::get_instance()->get_uri($item->get_id());
225
+						if ( ! $id || in_array($id, $about_id, true)) {
226 226
 							return false;
227 227
 						}
228 228
 
229
-						return array( '@id' => $id );
229
+						return array('@id' => $id);
230 230
 
231 231
 					},
232 232
 					$entity_references
@@ -235,23 +235,23 @@  discard block
 block discarded – undo
235 235
 		);
236 236
 
237 237
 		// Remove mentions if the count is zero.
238
-		if ( count( $jsonld[0]['mentions'] ) === 0 ) {
239
-			unset( $jsonld[0]['mentions'] );
238
+		if (count($jsonld[0]['mentions']) === 0) {
239
+			unset($jsonld[0]['mentions']);
240 240
 		}
241 241
 
242 242
 		return $jsonld;
243 243
 	}
244 244
 
245
-	private function entity_is_descendant_of_creative_work( $type ) {
246
-		if ( is_string( $type ) ) {
247
-			$type = array( $type );
245
+	private function entity_is_descendant_of_creative_work($type) {
246
+		if (is_string($type)) {
247
+			$type = array($type);
248 248
 		}
249 249
 
250
-		return count( array_intersect( $type, $this::$schema_descendants ) ) > 0;
250
+		return count(array_intersect($type, $this::$schema_descendants)) > 0;
251 251
 	}
252 252
 
253
-	private function entity_is_creative_work( $type ) {
254
-		return ( 'CreativeWork' === $type ) || ( is_array( $type ) && in_array( 'CreativeWork', $type, true ) );
253
+	private function entity_is_creative_work($type) {
254
+		return ('CreativeWork' === $type) || (is_array($type) && in_array('CreativeWork', $type, true));
255 255
 	}
256 256
 
257 257
 }
Please login to merge, or discard this patch.
src/wordlift/configuration/class-config.php 2 patches
Indentation   +183 added lines, -183 removed lines patch added patch discarded remove patch
@@ -3,191 +3,191 @@
 block discarded – undo
3 3
 namespace Wordlift\Configuration;
4 4
 
5 5
 class Config {
6
-	/**
7
-	 * @var \Wordlift_Admin_Setup
8
-	 */
9
-	private $admin_setup;
10
-	/**
11
-	 * @var \Wordlift_Key_Validation_Service
12
-	 */
13
-	private $key_validation_service;
14
-
15
-	/**
16
-	 * Config constructor.
17
-	 *
18
-	 * @param $admin_setup \Wordlift_Admin_Setup
19
-	 * @param $key_validation_service \Wordlift_Key_Validation_Service
20
-	 */
21
-	public function __construct( $admin_setup, $key_validation_service ) {
22
-
23
-		$this->admin_setup            = $admin_setup;
24
-		$this->key_validation_service = $key_validation_service;
25
-		add_action( 'wp_ajax_nopriv_wl_config_plugin', array( $this, 'config' ) );
26
-
27
-	}
28
-
29
-	/**
30
-	 * Check if the key is valid and also not bound to any domain.
31
-	 *
32
-	 * @param $key string
33
-	 *
34
-	 * @return bool
35
-	 */
36
-	private function is_key_valid_and_not_bound_to_any_domain( $key ) {
37
-		$account_info = $this->key_validation_service->get_account_info( $key );
38
-
39
-		/**
40
-		 * we need to check if the key is not associated with any account
41
-		 * before setting it, we should check if the url is null.
42
-		 */
43
-		if ( is_wp_error( $account_info )
44
-			 || wp_remote_retrieve_response_code( $account_info ) !== 200 ) {
45
-			return false;
46
-		}
47
-
48
-		$account_info_json = $account_info['body'];
49
-
50
-		$account_info_data = json_decode( $account_info_json, true );
51
-
52
-		if ( ! $account_info_data ) {
53
-			// Invalid json returned by api.
54
-			return false;
55
-		}
56
-
57
-		$site_url = apply_filters( 'wl_production_site_url', untrailingslashit( get_option( 'home' ) ) );
58
-
59
-		if ( null === $account_info_data['url'] ) {
60
-			return true;
61
-		}
62
-
63
-		// Check if the key belongs to same site.
64
-		if ( untrailingslashit( $account_info_data['url'] ) !== $site_url ) {
65
-			// key already associated with another account.
66
-			return false;
67
-		}
68
-
69
-		// Return true if the key domain and site domain are the same.
70
-		return true;
71
-	}
72
-
73
-	public function config() {
74
-
75
-		// Perform validation check for all the parameters.
76
-		$required_fields = array(
77
-			'diagnostic',
78
-			'vocabulary',
79
-			// Don't ask for language from webapp.
80
-			// 'language',
81
-				'country',
82
-			'publisherName',
83
-			'publisher',
84
-			'license',
85
-		);
86
-
87
-		header( 'Access-Control-Allow-Origin: *' );
88
-
89
-		// validate all the fields before processing
90
-		foreach ( $required_fields as $field ) {
91
-			if ( ! array_key_exists( $field, $_POST ) ) { //phpcs:ignore WordPress.Security.NonceVerification.Missing
92
-				/* translators: %s: field name */
93
-				wp_send_json_error( sprintf( __( 'Field %s is required', 'wordlift' ), $field ), 422 );
94
-
95
-				return;
96
-			}
97
-		}
98
-
99
-		$key = isset( $_POST['license'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['license'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing
100
-
101
-		if ( ! $this->is_key_valid_and_not_bound_to_any_domain( $key ) ) {
102
-			wp_send_json_error( __( 'Key is not valid or associated with other domain', 'wordlift' ), 403 );
103
-
104
-			// exit if not valid.
105
-			return;
106
-		}
107
-
108
-		// check if key is already configured, if yes then dont save settings.
109
-		if ( \Wordlift_Configuration_Service::get_instance()->get_key() ) {
110
-			wp_send_json_error( __( 'Key already configured.', 'wordlift' ), 403 );
111
-
112
-			// key already configured
113
-			return;
114
-		}
115
-
116
-		$this->admin_setup->save_configuration( $this->get_params() );
117
-
118
-		// This prevents invalid key issue with automatic installation in sites which have redis cache enabled.
119
-		wp_cache_flush();
120
-
121
-		wp_send_json_success( __( 'Configuration Saved', 'wordlift' ) );
122
-	}
123
-
124
-	/**
125
-	 *
126
-	 * @return array
127
-	 */
128
-	private function get_params() {
129
-
130
-		$attachment_id = $this->may_be_get_attachment_id();
131
-
132
-		$params = array(
133
-			'key'             => isset( $_POST['license'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['license'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification.Missing
134
-			'vocabulary'      => isset( $_POST['vocabulary'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['vocabulary'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification.Missing
135
-			'wl-country-code' => isset( $_POST['country'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['country'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification.Missing
136
-			'name'            => isset( $_POST['publisherName'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['publisherName'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification.Missing
137
-			'user_type'       => isset( $_POST['publisher'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['publisher'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification.Missing
138
-			'logo'            => $attachment_id,
139
-		);
140
-
141
-		$diagnostic = isset( $_POST['diagnostic'] ) ? (bool) $_POST['diagnostic'] : false; // phpcs:ignore WordPress.Security.NonceVerification.Missing
142
-		if ( $diagnostic ) {
143
-			$params['share-diagnostic'] = 'on';
144
-		}
6
+    /**
7
+     * @var \Wordlift_Admin_Setup
8
+     */
9
+    private $admin_setup;
10
+    /**
11
+     * @var \Wordlift_Key_Validation_Service
12
+     */
13
+    private $key_validation_service;
14
+
15
+    /**
16
+     * Config constructor.
17
+     *
18
+     * @param $admin_setup \Wordlift_Admin_Setup
19
+     * @param $key_validation_service \Wordlift_Key_Validation_Service
20
+     */
21
+    public function __construct( $admin_setup, $key_validation_service ) {
22
+
23
+        $this->admin_setup            = $admin_setup;
24
+        $this->key_validation_service = $key_validation_service;
25
+        add_action( 'wp_ajax_nopriv_wl_config_plugin', array( $this, 'config' ) );
26
+
27
+    }
28
+
29
+    /**
30
+     * Check if the key is valid and also not bound to any domain.
31
+     *
32
+     * @param $key string
33
+     *
34
+     * @return bool
35
+     */
36
+    private function is_key_valid_and_not_bound_to_any_domain( $key ) {
37
+        $account_info = $this->key_validation_service->get_account_info( $key );
38
+
39
+        /**
40
+         * we need to check if the key is not associated with any account
41
+         * before setting it, we should check if the url is null.
42
+         */
43
+        if ( is_wp_error( $account_info )
44
+             || wp_remote_retrieve_response_code( $account_info ) !== 200 ) {
45
+            return false;
46
+        }
47
+
48
+        $account_info_json = $account_info['body'];
49
+
50
+        $account_info_data = json_decode( $account_info_json, true );
51
+
52
+        if ( ! $account_info_data ) {
53
+            // Invalid json returned by api.
54
+            return false;
55
+        }
56
+
57
+        $site_url = apply_filters( 'wl_production_site_url', untrailingslashit( get_option( 'home' ) ) );
58
+
59
+        if ( null === $account_info_data['url'] ) {
60
+            return true;
61
+        }
62
+
63
+        // Check if the key belongs to same site.
64
+        if ( untrailingslashit( $account_info_data['url'] ) !== $site_url ) {
65
+            // key already associated with another account.
66
+            return false;
67
+        }
68
+
69
+        // Return true if the key domain and site domain are the same.
70
+        return true;
71
+    }
72
+
73
+    public function config() {
74
+
75
+        // Perform validation check for all the parameters.
76
+        $required_fields = array(
77
+            'diagnostic',
78
+            'vocabulary',
79
+            // Don't ask for language from webapp.
80
+            // 'language',
81
+                'country',
82
+            'publisherName',
83
+            'publisher',
84
+            'license',
85
+        );
86
+
87
+        header( 'Access-Control-Allow-Origin: *' );
88
+
89
+        // validate all the fields before processing
90
+        foreach ( $required_fields as $field ) {
91
+            if ( ! array_key_exists( $field, $_POST ) ) { //phpcs:ignore WordPress.Security.NonceVerification.Missing
92
+                /* translators: %s: field name */
93
+                wp_send_json_error( sprintf( __( 'Field %s is required', 'wordlift' ), $field ), 422 );
94
+
95
+                return;
96
+            }
97
+        }
98
+
99
+        $key = isset( $_POST['license'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['license'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing
100
+
101
+        if ( ! $this->is_key_valid_and_not_bound_to_any_domain( $key ) ) {
102
+            wp_send_json_error( __( 'Key is not valid or associated with other domain', 'wordlift' ), 403 );
103
+
104
+            // exit if not valid.
105
+            return;
106
+        }
107
+
108
+        // check if key is already configured, if yes then dont save settings.
109
+        if ( \Wordlift_Configuration_Service::get_instance()->get_key() ) {
110
+            wp_send_json_error( __( 'Key already configured.', 'wordlift' ), 403 );
111
+
112
+            // key already configured
113
+            return;
114
+        }
115
+
116
+        $this->admin_setup->save_configuration( $this->get_params() );
117
+
118
+        // This prevents invalid key issue with automatic installation in sites which have redis cache enabled.
119
+        wp_cache_flush();
120
+
121
+        wp_send_json_success( __( 'Configuration Saved', 'wordlift' ) );
122
+    }
123
+
124
+    /**
125
+     *
126
+     * @return array
127
+     */
128
+    private function get_params() {
129
+
130
+        $attachment_id = $this->may_be_get_attachment_id();
131
+
132
+        $params = array(
133
+            'key'             => isset( $_POST['license'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['license'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification.Missing
134
+            'vocabulary'      => isset( $_POST['vocabulary'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['vocabulary'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification.Missing
135
+            'wl-country-code' => isset( $_POST['country'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['country'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification.Missing
136
+            'name'            => isset( $_POST['publisherName'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['publisherName'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification.Missing
137
+            'user_type'       => isset( $_POST['publisher'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['publisher'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification.Missing
138
+            'logo'            => $attachment_id,
139
+        );
140
+
141
+        $diagnostic = isset( $_POST['diagnostic'] ) ? (bool) $_POST['diagnostic'] : false; // phpcs:ignore WordPress.Security.NonceVerification.Missing
142
+        if ( $diagnostic ) {
143
+            $params['share-diagnostic'] = 'on';
144
+        }
145 145
 
146
-		return $params;
147
-	}
148
-
149
-	/**
150
-	 * @return int | bool
151
-	 */
152
-	private function may_be_get_attachment_id() {
153
-
154
-		// if image or image extension not posted then return false.
155
-		if ( ! isset( $_POST['image'] ) || ! isset( $_POST['imageExtension'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing
156
-			return false;
157
-		}
158
-
159
-		$allowed_extensions = array( 'png', 'jpeg', 'jpg' );
160
-		$image_string       = sanitize_text_field( wp_unslash( (string) $_POST['image'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing
161
-		$image_ext          = sanitize_text_field( wp_unslash( (string) $_POST['imageExtension'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing
162
-
163
-		if ( ! in_array( $image_ext, $allowed_extensions, true ) ) {
164
-			return false;
165
-		}
166
-
167
-		// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode
168
-		$image_decoded_string = base64_decode( $image_string );
169
-
170
-		$upload_dir = wp_upload_dir();
171
-
172
-		$file_path = $upload_dir['path'] . DIRECTORY_SEPARATOR . md5( $image_string ) . '.' . $image_ext;
173
-
174
-		// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_read_file_put_contents
175
-		file_put_contents( $file_path, $image_decoded_string );
176
-
177
-		$attachment_id = wp_insert_attachment(
178
-			array(
179
-				'post_status'    => 'inherit',
180
-				'post_mime_type' => "image/$image_ext",
181
-			),
182
-			$file_path
183
-		);
146
+        return $params;
147
+    }
148
+
149
+    /**
150
+     * @return int | bool
151
+     */
152
+    private function may_be_get_attachment_id() {
153
+
154
+        // if image or image extension not posted then return false.
155
+        if ( ! isset( $_POST['image'] ) || ! isset( $_POST['imageExtension'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing
156
+            return false;
157
+        }
158
+
159
+        $allowed_extensions = array( 'png', 'jpeg', 'jpg' );
160
+        $image_string       = sanitize_text_field( wp_unslash( (string) $_POST['image'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing
161
+        $image_ext          = sanitize_text_field( wp_unslash( (string) $_POST['imageExtension'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing
162
+
163
+        if ( ! in_array( $image_ext, $allowed_extensions, true ) ) {
164
+            return false;
165
+        }
166
+
167
+        // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode
168
+        $image_decoded_string = base64_decode( $image_string );
169
+
170
+        $upload_dir = wp_upload_dir();
171
+
172
+        $file_path = $upload_dir['path'] . DIRECTORY_SEPARATOR . md5( $image_string ) . '.' . $image_ext;
173
+
174
+        // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_read_file_put_contents
175
+        file_put_contents( $file_path, $image_decoded_string );
176
+
177
+        $attachment_id = wp_insert_attachment(
178
+            array(
179
+                'post_status'    => 'inherit',
180
+                'post_mime_type' => "image/$image_ext",
181
+            ),
182
+            $file_path
183
+        );
184 184
 
185
-		// Generate the metadata for the attachment, and update the database record.
186
-		$attachment_data = wp_generate_attachment_metadata( $attachment_id, $file_path );
187
-		// Update the attachment metadata.
188
-		wp_update_attachment_metadata( $attachment_id, $attachment_data );
185
+        // Generate the metadata for the attachment, and update the database record.
186
+        $attachment_data = wp_generate_attachment_metadata( $attachment_id, $file_path );
187
+        // Update the attachment metadata.
188
+        wp_update_attachment_metadata( $attachment_id, $attachment_data );
189 189
 
190
-		return $attachment_id;
191
-	}
190
+        return $attachment_id;
191
+    }
192 192
 
193 193
 }
Please login to merge, or discard this patch.
Spacing   +39 added lines, -39 removed lines patch added patch discarded remove patch
@@ -18,11 +18,11 @@  discard block
 block discarded – undo
18 18
 	 * @param $admin_setup \Wordlift_Admin_Setup
19 19
 	 * @param $key_validation_service \Wordlift_Key_Validation_Service
20 20
 	 */
21
-	public function __construct( $admin_setup, $key_validation_service ) {
21
+	public function __construct($admin_setup, $key_validation_service) {
22 22
 
23 23
 		$this->admin_setup            = $admin_setup;
24 24
 		$this->key_validation_service = $key_validation_service;
25
-		add_action( 'wp_ajax_nopriv_wl_config_plugin', array( $this, 'config' ) );
25
+		add_action('wp_ajax_nopriv_wl_config_plugin', array($this, 'config'));
26 26
 
27 27
 	}
28 28
 
@@ -33,35 +33,35 @@  discard block
 block discarded – undo
33 33
 	 *
34 34
 	 * @return bool
35 35
 	 */
36
-	private function is_key_valid_and_not_bound_to_any_domain( $key ) {
37
-		$account_info = $this->key_validation_service->get_account_info( $key );
36
+	private function is_key_valid_and_not_bound_to_any_domain($key) {
37
+		$account_info = $this->key_validation_service->get_account_info($key);
38 38
 
39 39
 		/**
40 40
 		 * we need to check if the key is not associated with any account
41 41
 		 * before setting it, we should check if the url is null.
42 42
 		 */
43
-		if ( is_wp_error( $account_info )
44
-			 || wp_remote_retrieve_response_code( $account_info ) !== 200 ) {
43
+		if (is_wp_error($account_info)
44
+			 || wp_remote_retrieve_response_code($account_info) !== 200) {
45 45
 			return false;
46 46
 		}
47 47
 
48 48
 		$account_info_json = $account_info['body'];
49 49
 
50
-		$account_info_data = json_decode( $account_info_json, true );
50
+		$account_info_data = json_decode($account_info_json, true);
51 51
 
52
-		if ( ! $account_info_data ) {
52
+		if ( ! $account_info_data) {
53 53
 			// Invalid json returned by api.
54 54
 			return false;
55 55
 		}
56 56
 
57
-		$site_url = apply_filters( 'wl_production_site_url', untrailingslashit( get_option( 'home' ) ) );
57
+		$site_url = apply_filters('wl_production_site_url', untrailingslashit(get_option('home')));
58 58
 
59
-		if ( null === $account_info_data['url'] ) {
59
+		if (null === $account_info_data['url']) {
60 60
 			return true;
61 61
 		}
62 62
 
63 63
 		// Check if the key belongs to same site.
64
-		if ( untrailingslashit( $account_info_data['url'] ) !== $site_url ) {
64
+		if (untrailingslashit($account_info_data['url']) !== $site_url) {
65 65
 			// key already associated with another account.
66 66
 			return false;
67 67
 		}
@@ -84,41 +84,41 @@  discard block
 block discarded – undo
84 84
 			'license',
85 85
 		);
86 86
 
87
-		header( 'Access-Control-Allow-Origin: *' );
87
+		header('Access-Control-Allow-Origin: *');
88 88
 
89 89
 		// validate all the fields before processing
90
-		foreach ( $required_fields as $field ) {
91
-			if ( ! array_key_exists( $field, $_POST ) ) { //phpcs:ignore WordPress.Security.NonceVerification.Missing
90
+		foreach ($required_fields as $field) {
91
+			if ( ! array_key_exists($field, $_POST)) { //phpcs:ignore WordPress.Security.NonceVerification.Missing
92 92
 				/* translators: %s: field name */
93
-				wp_send_json_error( sprintf( __( 'Field %s is required', 'wordlift' ), $field ), 422 );
93
+				wp_send_json_error(sprintf(__('Field %s is required', 'wordlift'), $field), 422);
94 94
 
95 95
 				return;
96 96
 			}
97 97
 		}
98 98
 
99
-		$key = isset( $_POST['license'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['license'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing
99
+		$key = isset($_POST['license']) ? sanitize_text_field(wp_unslash((string) $_POST['license'])) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing
100 100
 
101
-		if ( ! $this->is_key_valid_and_not_bound_to_any_domain( $key ) ) {
102
-			wp_send_json_error( __( 'Key is not valid or associated with other domain', 'wordlift' ), 403 );
101
+		if ( ! $this->is_key_valid_and_not_bound_to_any_domain($key)) {
102
+			wp_send_json_error(__('Key is not valid or associated with other domain', 'wordlift'), 403);
103 103
 
104 104
 			// exit if not valid.
105 105
 			return;
106 106
 		}
107 107
 
108 108
 		// check if key is already configured, if yes then dont save settings.
109
-		if ( \Wordlift_Configuration_Service::get_instance()->get_key() ) {
110
-			wp_send_json_error( __( 'Key already configured.', 'wordlift' ), 403 );
109
+		if (\Wordlift_Configuration_Service::get_instance()->get_key()) {
110
+			wp_send_json_error(__('Key already configured.', 'wordlift'), 403);
111 111
 
112 112
 			// key already configured
113 113
 			return;
114 114
 		}
115 115
 
116
-		$this->admin_setup->save_configuration( $this->get_params() );
116
+		$this->admin_setup->save_configuration($this->get_params());
117 117
 
118 118
 		// This prevents invalid key issue with automatic installation in sites which have redis cache enabled.
119 119
 		wp_cache_flush();
120 120
 
121
-		wp_send_json_success( __( 'Configuration Saved', 'wordlift' ) );
121
+		wp_send_json_success(__('Configuration Saved', 'wordlift'));
122 122
 	}
123 123
 
124 124
 	/**
@@ -130,16 +130,16 @@  discard block
 block discarded – undo
130 130
 		$attachment_id = $this->may_be_get_attachment_id();
131 131
 
132 132
 		$params = array(
133
-			'key'             => isset( $_POST['license'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['license'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification.Missing
134
-			'vocabulary'      => isset( $_POST['vocabulary'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['vocabulary'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification.Missing
135
-			'wl-country-code' => isset( $_POST['country'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['country'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification.Missing
136
-			'name'            => isset( $_POST['publisherName'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['publisherName'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification.Missing
137
-			'user_type'       => isset( $_POST['publisher'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['publisher'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification.Missing
133
+			'key'             => isset($_POST['license']) ? sanitize_text_field(wp_unslash((string) $_POST['license'])) : '', // phpcs:ignore WordPress.Security.NonceVerification.Missing
134
+			'vocabulary'      => isset($_POST['vocabulary']) ? sanitize_text_field(wp_unslash((string) $_POST['vocabulary'])) : '', // phpcs:ignore WordPress.Security.NonceVerification.Missing
135
+			'wl-country-code' => isset($_POST['country']) ? sanitize_text_field(wp_unslash((string) $_POST['country'])) : '', // phpcs:ignore WordPress.Security.NonceVerification.Missing
136
+			'name'            => isset($_POST['publisherName']) ? sanitize_text_field(wp_unslash((string) $_POST['publisherName'])) : '', // phpcs:ignore WordPress.Security.NonceVerification.Missing
137
+			'user_type'       => isset($_POST['publisher']) ? sanitize_text_field(wp_unslash((string) $_POST['publisher'])) : '', // phpcs:ignore WordPress.Security.NonceVerification.Missing
138 138
 			'logo'            => $attachment_id,
139 139
 		);
140 140
 
141
-		$diagnostic = isset( $_POST['diagnostic'] ) ? (bool) $_POST['diagnostic'] : false; // phpcs:ignore WordPress.Security.NonceVerification.Missing
142
-		if ( $diagnostic ) {
141
+		$diagnostic = isset($_POST['diagnostic']) ? (bool) $_POST['diagnostic'] : false; // phpcs:ignore WordPress.Security.NonceVerification.Missing
142
+		if ($diagnostic) {
143 143
 			$params['share-diagnostic'] = 'on';
144 144
 		}
145 145
 
@@ -152,27 +152,27 @@  discard block
 block discarded – undo
152 152
 	private function may_be_get_attachment_id() {
153 153
 
154 154
 		// if image or image extension not posted then return false.
155
-		if ( ! isset( $_POST['image'] ) || ! isset( $_POST['imageExtension'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing
155
+		if ( ! isset($_POST['image']) || ! isset($_POST['imageExtension'])) { // phpcs:ignore WordPress.Security.NonceVerification.Missing
156 156
 			return false;
157 157
 		}
158 158
 
159
-		$allowed_extensions = array( 'png', 'jpeg', 'jpg' );
160
-		$image_string       = sanitize_text_field( wp_unslash( (string) $_POST['image'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing
161
-		$image_ext          = sanitize_text_field( wp_unslash( (string) $_POST['imageExtension'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing
159
+		$allowed_extensions = array('png', 'jpeg', 'jpg');
160
+		$image_string       = sanitize_text_field(wp_unslash((string) $_POST['image'])); // phpcs:ignore WordPress.Security.NonceVerification.Missing
161
+		$image_ext          = sanitize_text_field(wp_unslash((string) $_POST['imageExtension'])); // phpcs:ignore WordPress.Security.NonceVerification.Missing
162 162
 
163
-		if ( ! in_array( $image_ext, $allowed_extensions, true ) ) {
163
+		if ( ! in_array($image_ext, $allowed_extensions, true)) {
164 164
 			return false;
165 165
 		}
166 166
 
167 167
 		// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode
168
-		$image_decoded_string = base64_decode( $image_string );
168
+		$image_decoded_string = base64_decode($image_string);
169 169
 
170 170
 		$upload_dir = wp_upload_dir();
171 171
 
172
-		$file_path = $upload_dir['path'] . DIRECTORY_SEPARATOR . md5( $image_string ) . '.' . $image_ext;
172
+		$file_path = $upload_dir['path'].DIRECTORY_SEPARATOR.md5($image_string).'.'.$image_ext;
173 173
 
174 174
 		// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_read_file_put_contents
175
-		file_put_contents( $file_path, $image_decoded_string );
175
+		file_put_contents($file_path, $image_decoded_string);
176 176
 
177 177
 		$attachment_id = wp_insert_attachment(
178 178
 			array(
@@ -183,9 +183,9 @@  discard block
 block discarded – undo
183 183
 		);
184 184
 
185 185
 		// Generate the metadata for the attachment, and update the database record.
186
-		$attachment_data = wp_generate_attachment_metadata( $attachment_id, $file_path );
186
+		$attachment_data = wp_generate_attachment_metadata($attachment_id, $file_path);
187 187
 		// Update the attachment metadata.
188
-		wp_update_attachment_metadata( $attachment_id, $attachment_data );
188
+		wp_update_attachment_metadata($attachment_id, $attachment_data);
189 189
 
190 190
 		return $attachment_id;
191 191
 	}
Please login to merge, or discard this patch.
src/modules/food-kg/includes/Preconditions.php 2 patches
Indentation   +34 added lines, -34 removed lines patch added patch discarded remove patch
@@ -4,39 +4,39 @@
 block discarded – undo
4 4
 
5 5
 class Preconditions {
6 6
 
7
-	/**
8
-	 * @var Notices
9
-	 */
10
-	private $notices;
11
-
12
-	public function __construct( Notices $notices ) {
13
-		$this->notices = $notices;
14
-	}
15
-
16
-	public function pass() {
17
-		return $this->has_prerequisites() && $this->check_version();
18
-	}
19
-
20
-	private function has_prerequisites() {
21
-		return defined( 'WPRM_VERSION' )
22
-			   && class_exists( 'WP_Recipe_Maker' )
23
-		       // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
24
-			   && apply_filters( 'wl_feature__enable__food-kg', false );
25
-	}
26
-
27
-	private function check_version() {
28
-		$check = version_compare( WPRM_VERSION, '8.1.0', '>=' )
29
-				&& version_compare( WPRM_VERSION, '8.7.0', '<' );
30
-
31
-		if ( ! $check ) {
32
-			$this->notices->queue(
33
-				'warning',
34
-				/* translators: 1: minimum supported WPRM version, 2: maximum supported WPRM version, 3: Detected WP Recipe Maker version. */
35
-				sprintf( __( 'WordLift Food KG support requires WP Recipe Maker %1$s-%2$s, %3$s found.', 'wordlift' ), '8.1.0', '8.5.0', WPRM_VERSION )
36
-			);
37
-		}
38
-
39
-		return $check;
40
-	}
7
+    /**
8
+     * @var Notices
9
+     */
10
+    private $notices;
11
+
12
+    public function __construct( Notices $notices ) {
13
+        $this->notices = $notices;
14
+    }
15
+
16
+    public function pass() {
17
+        return $this->has_prerequisites() && $this->check_version();
18
+    }
19
+
20
+    private function has_prerequisites() {
21
+        return defined( 'WPRM_VERSION' )
22
+               && class_exists( 'WP_Recipe_Maker' )
23
+                // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
24
+               && apply_filters( 'wl_feature__enable__food-kg', false );
25
+    }
26
+
27
+    private function check_version() {
28
+        $check = version_compare( WPRM_VERSION, '8.1.0', '>=' )
29
+                && version_compare( WPRM_VERSION, '8.7.0', '<' );
30
+
31
+        if ( ! $check ) {
32
+            $this->notices->queue(
33
+                'warning',
34
+                /* translators: 1: minimum supported WPRM version, 2: maximum supported WPRM version, 3: Detected WP Recipe Maker version. */
35
+                sprintf( __( 'WordLift Food KG support requires WP Recipe Maker %1$s-%2$s, %3$s found.', 'wordlift' ), '8.1.0', '8.5.0', WPRM_VERSION )
36
+            );
37
+        }
38
+
39
+        return $check;
40
+    }
41 41
 
42 42
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -9,7 +9,7 @@  discard block
 block discarded – undo
9 9
 	 */
10 10
 	private $notices;
11 11
 
12
-	public function __construct( Notices $notices ) {
12
+	public function __construct(Notices $notices) {
13 13
 		$this->notices = $notices;
14 14
 	}
15 15
 
@@ -18,21 +18,21 @@  discard block
 block discarded – undo
18 18
 	}
19 19
 
20 20
 	private function has_prerequisites() {
21
-		return defined( 'WPRM_VERSION' )
22
-			   && class_exists( 'WP_Recipe_Maker' )
21
+		return defined('WPRM_VERSION')
22
+			   && class_exists('WP_Recipe_Maker')
23 23
 		       // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
24
-			   && apply_filters( 'wl_feature__enable__food-kg', false );
24
+			   && apply_filters('wl_feature__enable__food-kg', false);
25 25
 	}
26 26
 
27 27
 	private function check_version() {
28
-		$check = version_compare( WPRM_VERSION, '8.1.0', '>=' )
29
-				&& version_compare( WPRM_VERSION, '8.7.0', '<' );
28
+		$check = version_compare(WPRM_VERSION, '8.1.0', '>=')
29
+				&& version_compare(WPRM_VERSION, '8.7.0', '<');
30 30
 
31
-		if ( ! $check ) {
31
+		if ( ! $check) {
32 32
 			$this->notices->queue(
33 33
 				'warning',
34 34
 				/* translators: 1: minimum supported WPRM version, 2: maximum supported WPRM version, 3: Detected WP Recipe Maker version. */
35
-				sprintf( __( 'WordLift Food KG support requires WP Recipe Maker %1$s-%2$s, %3$s found.', 'wordlift' ), '8.1.0', '8.5.0', WPRM_VERSION )
35
+				sprintf(__('WordLift Food KG support requires WP Recipe Maker %1$s-%2$s, %3$s found.', 'wordlift'), '8.1.0', '8.5.0', WPRM_VERSION)
36 36
 			);
37 37
 		}
38 38
 
Please login to merge, or discard this patch.
src/wordlift.php 2 patches
Indentation   +142 added lines, -142 removed lines patch added patch discarded remove patch
@@ -33,7 +33,7 @@  discard block
 block discarded – undo
33 33
 
34 34
 // If this file is called directly, abort.
35 35
 if ( ! defined( 'WPINC' ) ) {
36
-	die;
36
+    die;
37 37
 }
38 38
 
39 39
 define( 'WORDLIFT_VERSION', '3.40.0' );
@@ -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,29 +76,29 @@  discard block
 block discarded – undo
76 76
  */
77 77
 function activate_wordlift() {
78 78
 
79
-	$log = Wordlift_Log_Service::get_logger( 'activate_wordlift' );
80
-
81
-	$log->info( 'Activating WordLift...' );
82
-
83
-	require_once plugin_dir_path( __FILE__ ) . 'includes/class-wordlift-activator.php';
84
-	Wordlift_Activator::activate();
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();
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();
79
+    $log = Wordlift_Log_Service::get_logger( 'activate_wordlift' );
80
+
81
+    $log->info( 'Activating WordLift...' );
82
+
83
+    require_once plugin_dir_path( __FILE__ ) . 'includes/class-wordlift-activator.php';
84
+    Wordlift_Activator::activate();
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();
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();
102 102
 }
103 103
 
104 104
 /**
@@ -107,21 +107,21 @@  discard block
 block discarded – undo
107 107
  */
108 108
 function deactivate_wordlift() {
109 109
 
110
-	require_once plugin_dir_path( __FILE__ ) . 'includes/class-wordlift-deactivator.php';
111
-	Wordlift_Deactivator::deactivate();
112
-	Wordlift_Http_Api::deactivate();
113
-	Ttl_Cache_Cleaner::deactivate();
114
-	/**
115
-	 * @since 3.27.7
116
-	 * @see https://github.com/insideout10/wordlift-plugin/issues/1214
117
-	 */
118
-	Top_Entities::deactivate();
119
-	/**
120
-	 * @since 3.27.8
121
-	 * Remove notification flag on deactivation.
122
-	 */
123
-	Key_Validation_Notice::remove_notification_flag();
124
-	flush_rewrite_rules();
110
+    require_once plugin_dir_path( __FILE__ ) . 'includes/class-wordlift-deactivator.php';
111
+    Wordlift_Deactivator::deactivate();
112
+    Wordlift_Http_Api::deactivate();
113
+    Ttl_Cache_Cleaner::deactivate();
114
+    /**
115
+     * @since 3.27.7
116
+     * @see https://github.com/insideout10/wordlift-plugin/issues/1214
117
+     */
118
+    Top_Entities::deactivate();
119
+    /**
120
+     * @since 3.27.8
121
+     * Remove notification flag on deactivation.
122
+     */
123
+    Key_Validation_Notice::remove_notification_flag();
124
+    flush_rewrite_rules();
125 125
 
126 126
 }
127 127
 
@@ -144,84 +144,84 @@  discard block
 block discarded – undo
144 144
  * @since    1.0.0
145 145
  */
146 146
 function run_wordlift() {
147
-	/**
148
-	 * Filter: wl_feature__enable__widgets.
149
-	 *
150
-	 * @param bool whether the widgets needed to be registered, defaults to true.
151
-	 *
152
-	 * @return bool
153
-	 * @since 3.27.6
154
-	 */
155
-	if ( apply_filters( 'wl_feature__enable__widgets', true ) ) {
156
-		add_action( 'widgets_init', 'wl_register_chord_widget' );
157
-		add_action( 'widgets_init', 'wl_register_geo_widget' );
158
-		add_action( 'widgets_init', 'wl_register_timeline_widget' );
159
-	}
160
-	add_filter( 'widget_text', 'do_shortcode' );
161
-
162
-	/**
163
-	 * Filter: wl_feature__enable__analysis
164
-	 *
165
-	 * @param bool Whether to send api request to analysis or not
166
-	 *
167
-	 * @return bool
168
-	 * @since 3.27.6
169
-	 */
170
-	if ( apply_filters( 'wl_feature__enable__analysis', true ) ) {
171
-		add_action( 'wp_ajax_wl_analyze', 'wl_ajax_analyze_action' );
172
-	} else {
173
-		add_action( 'wp_ajax_wl_analyze', 'wl_ajax_analyze_disabled_action' );
174
-	}
175
-
176
-	$plugin = new Wordlift();
177
-	$plugin->run();
178
-
179
-	// Initialize the TTL Cache Cleaner.
180
-	new Ttl_Cache_Cleaner();
181
-
182
-	// Load the new Post Adapter.
183
-	new Post_Adapter();
184
-
185
-	// Load the API Data Hooks.
186
-	new Api_Data_Hooks();
187
-
188
-	add_action(
189
-		'plugins_loaded',
190
-		function () {
191
-			// All features from registry should be initialized here.
192
-			$features_registry = Features_Registry::get_instance();
193
-			$features_registry->initialize_all_features();
194
-		},
195
-		5
196
-	);
197
-
198
-	add_action(
199
-		'plugins_loaded',
200
-		// phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
201
-		function () use ( $plugin ) {
202
-
203
-			new Wordlift_Products_Navigator_Shortcode_REST();
204
-
205
-			// Register the Dataset module, requires `$api_service`.
206
-			require_once plugin_dir_path( __FILE__ ) . 'wordlift/dataset/index.php';
207
-			require_once plugin_dir_path( __FILE__ ) . 'wordlift/shipping-data/index.php';
208
-
209
-			/*
147
+    /**
148
+     * Filter: wl_feature__enable__widgets.
149
+     *
150
+     * @param bool whether the widgets needed to be registered, defaults to true.
151
+     *
152
+     * @return bool
153
+     * @since 3.27.6
154
+     */
155
+    if ( apply_filters( 'wl_feature__enable__widgets', true ) ) {
156
+        add_action( 'widgets_init', 'wl_register_chord_widget' );
157
+        add_action( 'widgets_init', 'wl_register_geo_widget' );
158
+        add_action( 'widgets_init', 'wl_register_timeline_widget' );
159
+    }
160
+    add_filter( 'widget_text', 'do_shortcode' );
161
+
162
+    /**
163
+     * Filter: wl_feature__enable__analysis
164
+     *
165
+     * @param bool Whether to send api request to analysis or not
166
+     *
167
+     * @return bool
168
+     * @since 3.27.6
169
+     */
170
+    if ( apply_filters( 'wl_feature__enable__analysis', true ) ) {
171
+        add_action( 'wp_ajax_wl_analyze', 'wl_ajax_analyze_action' );
172
+    } else {
173
+        add_action( 'wp_ajax_wl_analyze', 'wl_ajax_analyze_disabled_action' );
174
+    }
175
+
176
+    $plugin = new Wordlift();
177
+    $plugin->run();
178
+
179
+    // Initialize the TTL Cache Cleaner.
180
+    new Ttl_Cache_Cleaner();
181
+
182
+    // Load the new Post Adapter.
183
+    new Post_Adapter();
184
+
185
+    // Load the API Data Hooks.
186
+    new Api_Data_Hooks();
187
+
188
+    add_action(
189
+        'plugins_loaded',
190
+        function () {
191
+            // All features from registry should be initialized here.
192
+            $features_registry = Features_Registry::get_instance();
193
+            $features_registry->initialize_all_features();
194
+        },
195
+        5
196
+    );
197
+
198
+    add_action(
199
+        'plugins_loaded',
200
+        // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
201
+        function () use ( $plugin ) {
202
+
203
+            new Wordlift_Products_Navigator_Shortcode_REST();
204
+
205
+            // Register the Dataset module, requires `$api_service`.
206
+            require_once plugin_dir_path( __FILE__ ) . 'wordlift/dataset/index.php';
207
+            require_once plugin_dir_path( __FILE__ ) . 'wordlift/shipping-data/index.php';
208
+
209
+            /*
210 210
 			* Require the Entity annotation cleanup module.
211 211
 			*
212 212
 			* @since 3.34.6
213 213
 			*/
214
-			require_once plugin_dir_path( __FILE__ ) . 'wordlift/cleanup/index.php';
214
+            require_once plugin_dir_path( __FILE__ ) . 'wordlift/cleanup/index.php';
215 215
 
216
-			/*
216
+            /*
217 217
 			* Import LOD entities.
218 218
 			*
219 219
 			* @since 3.35.0
220 220
 			*/
221
-			require_once plugin_dir_path( __FILE__ ) . 'wordlift/lod-import/index.php';
221
+            require_once plugin_dir_path( __FILE__ ) . 'wordlift/lod-import/index.php';
222 222
 
223
-		}
224
-	);
223
+        }
224
+    );
225 225
 
226 226
 }
227 227
 
@@ -235,45 +235,45 @@  discard block
 block discarded – undo
235 235
  */
236 236
 function wordlift_plugin_autoload_register() {
237 237
 
238
-	spl_autoload_register(
239
-		function ( $class_name ) {
238
+    spl_autoload_register(
239
+        function ( $class_name ) {
240 240
 
241
-			// Bail out if these are not our classes.
242
-			if ( 0 !== strpos( $class_name, 'Wordlift\\' ) ) {
243
-				return false;
244
-			}
241
+            // Bail out if these are not our classes.
242
+            if ( 0 !== strpos( $class_name, 'Wordlift\\' ) ) {
243
+                return false;
244
+            }
245 245
 
246
-			$class_name_lc = strtolower( str_replace( '_', '-', $class_name ) );
246
+            $class_name_lc = strtolower( str_replace( '_', '-', $class_name ) );
247 247
 
248
-			preg_match( '|^(?:(.*)\\\\)?(.+?)$|', $class_name_lc, $matches );
248
+            preg_match( '|^(?:(.*)\\\\)?(.+?)$|', $class_name_lc, $matches );
249 249
 
250
-			$path = str_replace( '\\', DIRECTORY_SEPARATOR, $matches[1] );
251
-			$file = 'class-' . $matches[2] . '.php';
250
+            $path = str_replace( '\\', DIRECTORY_SEPARATOR, $matches[1] );
251
+            $file = 'class-' . $matches[2] . '.php';
252 252
 
253
-			$full_path = plugin_dir_path( __FILE__ ) . $path . DIRECTORY_SEPARATOR . $file;
253
+            $full_path = plugin_dir_path( __FILE__ ) . $path . DIRECTORY_SEPARATOR . $file;
254 254
 
255
-			if ( ! file_exists( $full_path ) ) {
256
-				return false;
257
-			}
255
+            if ( ! file_exists( $full_path ) ) {
256
+                return false;
257
+            }
258 258
 
259
-			require_once $full_path;
259
+            require_once $full_path;
260 260
 
261
-			return true;
262
-		}
263
-	);
261
+            return true;
262
+        }
263
+    );
264 264
 
265 265
 }
266 266
 
267 267
 function wl_block_categories( $categories ) {
268
-	return array_merge(
269
-		$categories,
270
-		array(
271
-			array(
272
-				'slug'  => 'wordlift',
273
-				'title' => __( 'WordLift', 'wordlift' ),
274
-			),
275
-		)
276
-	);
268
+    return array_merge(
269
+        $categories,
270
+        array(
271
+            array(
272
+                'slug'  => 'wordlift',
273
+                'title' => __( 'WordLift', 'wordlift' ),
274
+            ),
275
+        )
276
+    );
277 277
 }
278 278
 
279 279
 /**
@@ -281,19 +281,19 @@  discard block
 block discarded – undo
281 281
  * this has to be removed when removing the legacy fields from the ui.
282 282
  */
283 283
 function wl_enqueue_leaflet( $in_footer = false ) {
284
-	// Leaflet.
285
-	wp_enqueue_style( 'wl-leaflet', plugin_dir_url( __FILE__ ) . 'js/leaflet/leaflet.css', array(), '1.6.0' );
286
-	wp_enqueue_script( 'wl-leaflet', plugin_dir_url( __FILE__ ) . 'js/leaflet/leaflet.js', array(), '1.6.0', $in_footer );
284
+    // Leaflet.
285
+    wp_enqueue_style( 'wl-leaflet', plugin_dir_url( __FILE__ ) . 'js/leaflet/leaflet.css', array(), '1.6.0' );
286
+    wp_enqueue_script( 'wl-leaflet', plugin_dir_url( __FILE__ ) . 'js/leaflet/leaflet.js', array(), '1.6.0', $in_footer );
287 287
 }
288 288
 
289 289
 add_filter( 'block_categories', 'wl_block_categories', 10 );
290 290
 
291 291
 // Temporary fix for a typo in WooCommerce Extension.
292 292
 add_filter(
293
-	'wl_feature__enable__dataset',
294
-	function ( $value ) {
295
-		return apply_filters( 'wl_features__enable__dataset', $value );
296
-	}
293
+    'wl_feature__enable__dataset',
294
+    function ( $value ) {
295
+        return apply_filters( 'wl_features__enable__dataset', $value );
296
+    }
297 297
 );
298 298
 
299 299
 require_once __DIR__ . '/modules/food-kg/load.php';
Please login to merge, or discard this patch.
Spacing   +50 added lines, -50 removed lines patch added patch discarded remove patch
@@ -32,25 +32,25 @@  discard block
 block discarded – undo
32 32
 use Wordlift\Post\Post_Adapter;
33 33
 
34 34
 // If this file is called directly, abort.
35
-if ( ! defined( 'WPINC' ) ) {
35
+if ( ! defined('WPINC')) {
36 36
 	die;
37 37
 }
38 38
 
39
-define( 'WORDLIFT_VERSION', '3.40.0' );
39
+define('WORDLIFT_VERSION', '3.40.0');
40 40
 
41
-require_once __DIR__ . '/modules/common/load.php';
42
-require_once __DIR__ . '/modules/include-exclude/load.php';
41
+require_once __DIR__.'/modules/common/load.php';
42
+require_once __DIR__.'/modules/include-exclude/load.php';
43 43
 
44 44
 /**
45 45
  * Filter to disable WLP on any request, defaults to true.
46 46
  *
47 47
  * @since 3.33.6
48 48
  */
49
-if ( ! apply_filters( 'wl_is_enabled', true ) ) {
49
+if ( ! apply_filters('wl_is_enabled', true)) {
50 50
 	return;
51 51
 }
52 52
 
53
-require_once plugin_dir_path( __FILE__ ) . 'vendor/autoload.php';
53
+require_once plugin_dir_path(__FILE__).'vendor/autoload.php';
54 54
 
55 55
 /*
56 56
 	 * We introduce the WordLift autoloader, since we start using classes in namespaces, i.e. Wordlift\Http.
@@ -60,15 +60,15 @@  discard block
 block discarded – undo
60 60
 wordlift_plugin_autoload_register();
61 61
 
62 62
 // Include WordLift constants.
63
-require_once plugin_dir_path( __FILE__ ) . 'wordlift-constants.php';
63
+require_once plugin_dir_path(__FILE__).'wordlift-constants.php';
64 64
 
65 65
 // Load modules.
66
-require_once plugin_dir_path( __FILE__ ) . 'modules/core/wordlift-core.php';
66
+require_once plugin_dir_path(__FILE__).'modules/core/wordlift-core.php';
67 67
 
68
-require_once plugin_dir_path( __FILE__ ) . 'deprecations.php';
68
+require_once plugin_dir_path(__FILE__).'deprecations.php';
69 69
 
70 70
 // Load early to enable/disable features.
71
-require_once plugin_dir_path( __FILE__ ) . 'wordlift/features/index.php';
71
+require_once plugin_dir_path(__FILE__).'wordlift/features/index.php';
72 72
 
73 73
 /**
74 74
  * The code that runs during plugin activation.
@@ -76,11 +76,11 @@  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';
83
+	require_once plugin_dir_path(__FILE__).'includes/class-wordlift-activator.php';
84 84
 	Wordlift_Activator::activate();
85 85
 
86 86
 	/**
@@ -107,7 +107,7 @@  discard block
 block discarded – undo
107 107
  */
108 108
 function deactivate_wordlift() {
109 109
 
110
-	require_once plugin_dir_path( __FILE__ ) . 'includes/class-wordlift-deactivator.php';
110
+	require_once plugin_dir_path(__FILE__).'includes/class-wordlift-deactivator.php';
111 111
 	Wordlift_Deactivator::deactivate();
112 112
 	Wordlift_Http_Api::deactivate();
113 113
 	Ttl_Cache_Cleaner::deactivate();
@@ -125,14 +125,14 @@  discard block
 block discarded – undo
125 125
 
126 126
 }
127 127
 
128
-register_activation_hook( __FILE__, 'activate_wordlift' );
129
-register_deactivation_hook( __FILE__, 'deactivate_wordlift' );
128
+register_activation_hook(__FILE__, 'activate_wordlift');
129
+register_deactivation_hook(__FILE__, 'deactivate_wordlift');
130 130
 
131 131
 /**
132 132
  * The core plugin class that is used to define internationalization,
133 133
  * admin-specific hooks, and public-facing site hooks.
134 134
  */
135
-require plugin_dir_path( __FILE__ ) . 'includes/class-wordlift.php';
135
+require plugin_dir_path(__FILE__).'includes/class-wordlift.php';
136 136
 
137 137
 /**
138 138
  * Begins execution of the plugin.
@@ -152,12 +152,12 @@  discard block
 block discarded – undo
152 152
 	 * @return bool
153 153
 	 * @since 3.27.6
154 154
 	 */
155
-	if ( apply_filters( 'wl_feature__enable__widgets', true ) ) {
156
-		add_action( 'widgets_init', 'wl_register_chord_widget' );
157
-		add_action( 'widgets_init', 'wl_register_geo_widget' );
158
-		add_action( 'widgets_init', 'wl_register_timeline_widget' );
155
+	if (apply_filters('wl_feature__enable__widgets', true)) {
156
+		add_action('widgets_init', 'wl_register_chord_widget');
157
+		add_action('widgets_init', 'wl_register_geo_widget');
158
+		add_action('widgets_init', 'wl_register_timeline_widget');
159 159
 	}
160
-	add_filter( 'widget_text', 'do_shortcode' );
160
+	add_filter('widget_text', 'do_shortcode');
161 161
 
162 162
 	/**
163 163
 	 * Filter: wl_feature__enable__analysis
@@ -167,10 +167,10 @@  discard block
 block discarded – undo
167 167
 	 * @return bool
168 168
 	 * @since 3.27.6
169 169
 	 */
170
-	if ( apply_filters( 'wl_feature__enable__analysis', true ) ) {
171
-		add_action( 'wp_ajax_wl_analyze', 'wl_ajax_analyze_action' );
170
+	if (apply_filters('wl_feature__enable__analysis', true)) {
171
+		add_action('wp_ajax_wl_analyze', 'wl_ajax_analyze_action');
172 172
 	} else {
173
-		add_action( 'wp_ajax_wl_analyze', 'wl_ajax_analyze_disabled_action' );
173
+		add_action('wp_ajax_wl_analyze', 'wl_ajax_analyze_disabled_action');
174 174
 	}
175 175
 
176 176
 	$plugin = new Wordlift();
@@ -187,7 +187,7 @@  discard block
 block discarded – undo
187 187
 
188 188
 	add_action(
189 189
 		'plugins_loaded',
190
-		function () {
190
+		function() {
191 191
 			// All features from registry should be initialized here.
192 192
 			$features_registry = Features_Registry::get_instance();
193 193
 			$features_registry->initialize_all_features();
@@ -198,27 +198,27 @@  discard block
 block discarded – undo
198 198
 	add_action(
199 199
 		'plugins_loaded',
200 200
 		// phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
201
-		function () use ( $plugin ) {
201
+		function() use ($plugin) {
202 202
 
203 203
 			new Wordlift_Products_Navigator_Shortcode_REST();
204 204
 
205 205
 			// Register the Dataset module, requires `$api_service`.
206
-			require_once plugin_dir_path( __FILE__ ) . 'wordlift/dataset/index.php';
207
-			require_once plugin_dir_path( __FILE__ ) . 'wordlift/shipping-data/index.php';
206
+			require_once plugin_dir_path(__FILE__).'wordlift/dataset/index.php';
207
+			require_once plugin_dir_path(__FILE__).'wordlift/shipping-data/index.php';
208 208
 
209 209
 			/*
210 210
 			* Require the Entity annotation cleanup module.
211 211
 			*
212 212
 			* @since 3.34.6
213 213
 			*/
214
-			require_once plugin_dir_path( __FILE__ ) . 'wordlift/cleanup/index.php';
214
+			require_once plugin_dir_path(__FILE__).'wordlift/cleanup/index.php';
215 215
 
216 216
 			/*
217 217
 			* Import LOD entities.
218 218
 			*
219 219
 			* @since 3.35.0
220 220
 			*/
221
-			require_once plugin_dir_path( __FILE__ ) . 'wordlift/lod-import/index.php';
221
+			require_once plugin_dir_path(__FILE__).'wordlift/lod-import/index.php';
222 222
 
223 223
 		}
224 224
 	);
@@ -236,23 +236,23 @@  discard block
 block discarded – undo
236 236
 function wordlift_plugin_autoload_register() {
237 237
 
238 238
 	spl_autoload_register(
239
-		function ( $class_name ) {
239
+		function($class_name) {
240 240
 
241 241
 			// Bail out if these are not our classes.
242
-			if ( 0 !== strpos( $class_name, 'Wordlift\\' ) ) {
242
+			if (0 !== strpos($class_name, 'Wordlift\\')) {
243 243
 				return false;
244 244
 			}
245 245
 
246
-			$class_name_lc = strtolower( str_replace( '_', '-', $class_name ) );
246
+			$class_name_lc = strtolower(str_replace('_', '-', $class_name));
247 247
 
248
-			preg_match( '|^(?:(.*)\\\\)?(.+?)$|', $class_name_lc, $matches );
248
+			preg_match('|^(?:(.*)\\\\)?(.+?)$|', $class_name_lc, $matches);
249 249
 
250
-			$path = str_replace( '\\', DIRECTORY_SEPARATOR, $matches[1] );
251
-			$file = 'class-' . $matches[2] . '.php';
250
+			$path = str_replace('\\', DIRECTORY_SEPARATOR, $matches[1]);
251
+			$file = 'class-'.$matches[2].'.php';
252 252
 
253
-			$full_path = plugin_dir_path( __FILE__ ) . $path . DIRECTORY_SEPARATOR . $file;
253
+			$full_path = plugin_dir_path(__FILE__).$path.DIRECTORY_SEPARATOR.$file;
254 254
 
255
-			if ( ! file_exists( $full_path ) ) {
255
+			if ( ! file_exists($full_path)) {
256 256
 				return false;
257 257
 			}
258 258
 
@@ -264,13 +264,13 @@  discard block
 block discarded – undo
264 264
 
265 265
 }
266 266
 
267
-function wl_block_categories( $categories ) {
267
+function wl_block_categories($categories) {
268 268
 	return array_merge(
269 269
 		$categories,
270 270
 		array(
271 271
 			array(
272 272
 				'slug'  => 'wordlift',
273
-				'title' => __( 'WordLift', 'wordlift' ),
273
+				'title' => __('WordLift', 'wordlift'),
274 274
 			),
275 275
 		)
276 276
 	);
@@ -280,22 +280,22 @@  discard block
 block discarded – undo
280 280
  * This function is created temporarily to handle the legacy library,
281 281
  * this has to be removed when removing the legacy fields from the ui.
282 282
  */
283
-function wl_enqueue_leaflet( $in_footer = false ) {
283
+function wl_enqueue_leaflet($in_footer = false) {
284 284
 	// Leaflet.
285
-	wp_enqueue_style( 'wl-leaflet', plugin_dir_url( __FILE__ ) . 'js/leaflet/leaflet.css', array(), '1.6.0' );
286
-	wp_enqueue_script( 'wl-leaflet', plugin_dir_url( __FILE__ ) . 'js/leaflet/leaflet.js', array(), '1.6.0', $in_footer );
285
+	wp_enqueue_style('wl-leaflet', plugin_dir_url(__FILE__).'js/leaflet/leaflet.css', array(), '1.6.0');
286
+	wp_enqueue_script('wl-leaflet', plugin_dir_url(__FILE__).'js/leaflet/leaflet.js', array(), '1.6.0', $in_footer);
287 287
 }
288 288
 
289
-add_filter( 'block_categories', 'wl_block_categories', 10 );
289
+add_filter('block_categories', 'wl_block_categories', 10);
290 290
 
291 291
 // Temporary fix for a typo in WooCommerce Extension.
292 292
 add_filter(
293 293
 	'wl_feature__enable__dataset',
294
-	function ( $value ) {
295
-		return apply_filters( 'wl_features__enable__dataset', $value );
294
+	function($value) {
295
+		return apply_filters('wl_features__enable__dataset', $value);
296 296
 	}
297 297
 );
298 298
 
299
-require_once __DIR__ . '/modules/food-kg/load.php';
300
-require_once __DIR__ . '/modules/acf4so/load.php';
301
-require_once __DIR__ . '/modules/pods/load.php';
299
+require_once __DIR__.'/modules/food-kg/load.php';
300
+require_once __DIR__.'/modules/acf4so/load.php';
301
+require_once __DIR__.'/modules/pods/load.php';
Please login to merge, or discard this patch.