Completed
Pull Request — master (#1455)
by Naveen
01:04
created
src/modules/linked_data/wordlift_linked_data.php 2 patches
Indentation   +425 added lines, -425 removed lines patch added patch discarded remove patch
@@ -20,60 +20,60 @@  discard block
 block discarded – undo
20 20
  */
21 21
 function wl_linked_data_save_post( $post_id ) {
22 22
 
23
-	$log = Wordlift_Log_Service::get_logger( 'wl_linked_data_save_post' );
24
-
25
-	$log->trace( "Saving post $post_id to Linked Data..." );
26
-
27
-	// If it's not numeric exit from here.
28
-	if ( ! is_numeric( $post_id ) || is_numeric( wp_is_post_revision( $post_id ) ) ) {
29
-		$log->debug( "Skipping $post_id, because id is not numeric or is a post revision." );
30
-
31
-		return;
32
-	}
33
-
34
-	// Get the post type and check whether it supports the editor.
35
-	//
36
-	// @see https://github.com/insideout10/wordlift-plugin/issues/659.
37
-	$post_type = get_post_type( $post_id );
38
-	/**
39
-	 * Use `wl_post_type_supports_editor` which calls a filter to allow 3rd parties to change the setting.
40
-	 *
41
-	 * @since 3.19.4
42
-	 *
43
-	 * @see https://github.com/insideout10/wordlift-plugin/issues/847.
44
-	 */
45
-	$is_editor_supported = wl_post_type_supports_editor( $post_type );
46
-
47
-	// Bail out if it's not an entity.
48
-	if ( ! $is_editor_supported ) {
49
-		$log->debug( "Skipping $post_id, because $post_type doesn't support the editor (content)." );
50
-
51
-		return;
52
-	}
53
-
54
-	/**
55
-	 * Only process valid post types
56
-	 *
57
-	 * @since 3.25.6
58
-	 *
59
-	 */
60
-	$supported_types = Wordlift_Entity_Service::valid_entity_post_types();
61
-
62
-	// Bail out if it's not a valid entity.
63
-	if ( ! in_array( $post_type, $supported_types ) ) {
64
-		$log->debug( "Skipping $post_id, because $post_type is not a valid entity." );
65
-
66
-		return;
67
-	}
68
-
69
-	// Unhook this function so it doesn't loop infinitely.
70
-	remove_action( 'save_post', 'wl_linked_data_save_post' );
71
-
72
-	// raise the *wl_linked_data_save_post* event.
73
-	do_action( 'wl_linked_data_save_post', $post_id );
74
-
75
-	// Re-hook this function.
76
-	add_action( 'save_post', 'wl_linked_data_save_post' );
23
+    $log = Wordlift_Log_Service::get_logger( 'wl_linked_data_save_post' );
24
+
25
+    $log->trace( "Saving post $post_id to Linked Data..." );
26
+
27
+    // If it's not numeric exit from here.
28
+    if ( ! is_numeric( $post_id ) || is_numeric( wp_is_post_revision( $post_id ) ) ) {
29
+        $log->debug( "Skipping $post_id, because id is not numeric or is a post revision." );
30
+
31
+        return;
32
+    }
33
+
34
+    // Get the post type and check whether it supports the editor.
35
+    //
36
+    // @see https://github.com/insideout10/wordlift-plugin/issues/659.
37
+    $post_type = get_post_type( $post_id );
38
+    /**
39
+     * Use `wl_post_type_supports_editor` which calls a filter to allow 3rd parties to change the setting.
40
+     *
41
+     * @since 3.19.4
42
+     *
43
+     * @see https://github.com/insideout10/wordlift-plugin/issues/847.
44
+     */
45
+    $is_editor_supported = wl_post_type_supports_editor( $post_type );
46
+
47
+    // Bail out if it's not an entity.
48
+    if ( ! $is_editor_supported ) {
49
+        $log->debug( "Skipping $post_id, because $post_type doesn't support the editor (content)." );
50
+
51
+        return;
52
+    }
53
+
54
+    /**
55
+     * Only process valid post types
56
+     *
57
+     * @since 3.25.6
58
+     *
59
+     */
60
+    $supported_types = Wordlift_Entity_Service::valid_entity_post_types();
61
+
62
+    // Bail out if it's not a valid entity.
63
+    if ( ! in_array( $post_type, $supported_types ) ) {
64
+        $log->debug( "Skipping $post_id, because $post_type is not a valid entity." );
65
+
66
+        return;
67
+    }
68
+
69
+    // Unhook this function so it doesn't loop infinitely.
70
+    remove_action( 'save_post', 'wl_linked_data_save_post' );
71
+
72
+    // raise the *wl_linked_data_save_post* event.
73
+    do_action( 'wl_linked_data_save_post', $post_id );
74
+
75
+    // Re-hook this function.
76
+    add_action( 'save_post', 'wl_linked_data_save_post' );
77 77
 }
78 78
 
79 79
 add_action( 'save_post', 'wl_linked_data_save_post' );
@@ -88,176 +88,176 @@  discard block
 block discarded – undo
88 88
  */
89 89
 function wl_linked_data_save_post_and_related_entities( $post_id ) {
90 90
 
91
-	$log = Wordlift_Log_Service::get_logger( 'wl_linked_data_save_post_and_related_entities' );
91
+    $log = Wordlift_Log_Service::get_logger( 'wl_linked_data_save_post_and_related_entities' );
92 92
 
93
-	$log->trace( "Saving $post_id to Linked Data along with related entities..." );
93
+    $log->trace( "Saving $post_id to Linked Data along with related entities..." );
94 94
 
95
-	// Ignore auto-saves
96
-	if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
97
-		$log->trace( 'Doing autosave, skipping...' );
95
+    // Ignore auto-saves
96
+    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
97
+        $log->trace( 'Doing autosave, skipping...' );
98 98
 
99
-		return;
100
-	}
99
+        return;
100
+    }
101 101
 
102
-	// get the current post.
103
-	$post = get_post( $post_id );
102
+    // get the current post.
103
+    $post = get_post( $post_id );
104 104
 
105
-	remove_action( 'wl_linked_data_save_post', 'wl_linked_data_save_post_and_related_entities' );
105
+    remove_action( 'wl_linked_data_save_post', 'wl_linked_data_save_post_and_related_entities' );
106 106
 
107
-	// wl_write_log( "[ post id :: $post_id ][ autosave :: false ][ post type :: $post->post_type ]" );
107
+    // wl_write_log( "[ post id :: $post_id ][ autosave :: false ][ post type :: $post->post_type ]" );
108 108
 
109
-	// Get the entity service instance.
110
-	$entity_service = Wordlift_Entity_Service::get_instance();
109
+    // Get the entity service instance.
110
+    $entity_service = Wordlift_Entity_Service::get_instance();
111 111
 
112
-	// Store mapping between tmp new entities uris and real new entities uri
113
-	$entities_uri_mapping = array();
112
+    // Store mapping between tmp new entities uris and real new entities uri
113
+    $entities_uri_mapping = array();
114 114
 
115
-	// Save the entities coming with POST data.
116
-	if ( isset( $_POST['wl_entities'] ) && isset( $_POST['wl_boxes'] ) ) {
117
-
118
-		wl_write_log( "[ post id :: $post_id ][ POST(wl_entities) :: " );
119
-		wl_write_log( json_encode( $_POST['wl_entities'] ) );
120
-		wl_write_log( "]" );
121
-		wl_write_log( "[ post id :: $post_id ][ POST(wl_boxes) :: " );
122
-		wl_write_log( json_encode( $_POST['wl_boxes'], true ) );
123
-		wl_write_log( "]" );
115
+    // Save the entities coming with POST data.
116
+    if ( isset( $_POST['wl_entities'] ) && isset( $_POST['wl_boxes'] ) ) {
117
+
118
+        wl_write_log( "[ post id :: $post_id ][ POST(wl_entities) :: " );
119
+        wl_write_log( json_encode( $_POST['wl_entities'] ) );
120
+        wl_write_log( "]" );
121
+        wl_write_log( "[ post id :: $post_id ][ POST(wl_boxes) :: " );
122
+        wl_write_log( json_encode( $_POST['wl_boxes'], true ) );
123
+        wl_write_log( "]" );
124 124
 
125
-		$entities_via_post = $_POST['wl_entities'];
126
-
127
-		foreach ( $entities_via_post as $entity_uri => $entity ) {
125
+        $entities_via_post = $_POST['wl_entities'];
126
+
127
+        foreach ( $entities_via_post as $entity_uri => $entity ) {
128 128
 
129
-			// Only if the current entity is created from scratch let's avoid to
130
-			// create more than one entity with same label & entity type.
131
-			$entity_type = ( preg_match( '/^local-entity-.+/', $entity_uri ) > 0 ) ?
132
-				$entity['main_type'] : null;
133
-
134
-			// Look if current entity uri matches an internal existing entity, meaning:
135
-			// 1. when $entity_uri is an internal uri
136
-			// 2. when $entity_uri is an external uri used as sameAs of an internal entity
137
-			$ie = $entity_service->get_entity_post_by_uri( $entity_uri );
129
+            // Only if the current entity is created from scratch let's avoid to
130
+            // create more than one entity with same label & entity type.
131
+            $entity_type = ( preg_match( '/^local-entity-.+/', $entity_uri ) > 0 ) ?
132
+                $entity['main_type'] : null;
133
+
134
+            // Look if current entity uri matches an internal existing entity, meaning:
135
+            // 1. when $entity_uri is an internal uri
136
+            // 2. when $entity_uri is an external uri used as sameAs of an internal entity
137
+            $ie = $entity_service->get_entity_post_by_uri( $entity_uri );
138 138
 
139
-			// Dont save the entities which are not found, but also local.
140
-			if ( $ie === null &&  Wordlift_Entity_Uri_Service::get_instance()->is_internal( $entity_uri ) ) {
141
-				continue;
142
-			}
143
-
144
-			// Detect the uri depending if is an existing or a new entity
145
-			$uri = ( null === $ie ) ?
146
-				Wordlift_Uri_Service::get_instance()->build_uri(
147
-					$entity['label'],
148
-					Wordlift_Entity_Service::TYPE_NAME,
149
-					$entity_type
150
-				) : wl_get_entity_uri( $ie->ID );
151
-
152
-			wl_write_log( "Map $entity_uri on $uri" );
153
-			$entities_uri_mapping[ $entity_uri ] = $uri;
154
-
155
-			// Local entities have a tmp uri with 'local-entity-' prefix
156
-			// These uris need to be rewritten here and replaced in the content
157
-			if ( preg_match( '/^local-entity-.+/', $entity_uri ) > 0 ) {
158
-				// Override the entity obj
159
-				$entity['uri'] = $uri;
160
-			}
161
-
162
-			// Update entity data with related post
163
-			$entity['related_post_id'] = $post_id;
164
-
165
-			// Save the entity if is a new entity
166
-			if ( null === $ie ) {
167
-				wl_save_entity( $entity );
168
-			}
169
-
170
-		}
171
-
172
-	}
173
-
174
-	// Replace tmp uris in content post if needed
175
-	$updated_post_content = $post->post_content;
176
-
177
-	// Update the post content if we found mappings of new entities.
178
-	if ( ! empty( $entities_uri_mapping ) ) {
179
-		// Save each entity and store the post id.
180
-		foreach ( $entities_uri_mapping as $tmp_uri => $uri ) {
181
-			if ( 1 !== preg_match( '@^(https?://|local-entity-)@', $tmp_uri ) ) {
182
-				continue;
183
-			}
184
-
185
-			$updated_post_content = str_replace( $tmp_uri, $uri, $updated_post_content );
186
-		}
187
-
188
-		// Update the post content.
189
-		/**
190
-		 * Note: wp_update_post do stripslashes before saving the
191
-		 * content, so add the slashes to prevent back slash getting
192
-		 * removed.
193
-		 */
194
-		wp_update_post( array(
195
-			'ID'           => $post->ID,
196
-			'post_content' => addslashes( $updated_post_content ),
197
-		) );
198
-	}
199
-	// Reset previously saved instances.
200
-	wl_core_delete_relation_instances( $post_id );
201
-
202
-
203
-	$relations = Object_Relation_Service::get_instance()
204
-	                                    ->get_relations_from_content( $updated_post_content, Object_Type_Enum::POST );
205
-
206
-	// Save relation instances
207
-	foreach ( $relations as $relation ) {
208
-
209
-		wl_core_add_relation_instance(
210
-			// subject id.
211
-			$post_id,
212
-			// what, where, when, who
213
-			$relation->get_relation_type(),
214
-			// object id.
215
-			$relation->get_object_id(),
216
-			// Subject type.
217
-			$relation->get_subject_type(),
218
-			// Object type.
219
-			$relation->get_object_type()
220
-		);
221
-
222
-	}
223
-
224
-	if ( isset( $_POST['wl_entities'] ) ) {
225
-		// Save post metadata if available
226
-		$metadata_via_post = ( isset( $_POST['wl_metadata'] ) ) ?
227
-			$_POST['wl_metadata'] : array();
228
-
229
-		$fields = array(
230
-			Wordlift_Schema_Service::FIELD_LOCATION_CREATED,
231
-			Wordlift_Schema_Service::FIELD_TOPIC,
232
-		);
233
-
234
-		// Unlink topic taxonomy terms
235
-		Wordlift_Topic_Taxonomy_Service::get_instance()->unlink_topic_for( $post->ID );
236
-
237
-		foreach ( $fields as $field ) {
238
-
239
-			// Delete current values
240
-			delete_post_meta( $post->ID, $field );
241
-			// Retrieve the entity uri
242
-			$uri = ( isset( $metadata_via_post[ $field ] ) ) ?
243
-				stripslashes( $metadata_via_post[ $field ] ) : '';
244
-
245
-			$entity = $entity_service->get_entity_post_by_uri( $uri );
246
-
247
-			if ( $entity ) {
248
-				add_post_meta( $post->ID, $field, $entity->ID, true );
249
-				// Set also the topic taxonomy
250
-				if ( $field === Wordlift_Schema_Service::FIELD_TOPIC ) {
251
-					Wordlift_Topic_Taxonomy_Service::get_instance()->set_topic_for( $post->ID, $entity );
252
-				}
253
-			}
254
-		}
255
-	}
256
-
257
-	// Push the post to Redlink.
258
-	do_action( 'wl_legacy_linked_data__push', $post->ID );
259
-
260
-	add_action( 'wl_linked_data_save_post', 'wl_linked_data_save_post_and_related_entities' );
139
+            // Dont save the entities which are not found, but also local.
140
+            if ( $ie === null &&  Wordlift_Entity_Uri_Service::get_instance()->is_internal( $entity_uri ) ) {
141
+                continue;
142
+            }
143
+
144
+            // Detect the uri depending if is an existing or a new entity
145
+            $uri = ( null === $ie ) ?
146
+                Wordlift_Uri_Service::get_instance()->build_uri(
147
+                    $entity['label'],
148
+                    Wordlift_Entity_Service::TYPE_NAME,
149
+                    $entity_type
150
+                ) : wl_get_entity_uri( $ie->ID );
151
+
152
+            wl_write_log( "Map $entity_uri on $uri" );
153
+            $entities_uri_mapping[ $entity_uri ] = $uri;
154
+
155
+            // Local entities have a tmp uri with 'local-entity-' prefix
156
+            // These uris need to be rewritten here and replaced in the content
157
+            if ( preg_match( '/^local-entity-.+/', $entity_uri ) > 0 ) {
158
+                // Override the entity obj
159
+                $entity['uri'] = $uri;
160
+            }
161
+
162
+            // Update entity data with related post
163
+            $entity['related_post_id'] = $post_id;
164
+
165
+            // Save the entity if is a new entity
166
+            if ( null === $ie ) {
167
+                wl_save_entity( $entity );
168
+            }
169
+
170
+        }
171
+
172
+    }
173
+
174
+    // Replace tmp uris in content post if needed
175
+    $updated_post_content = $post->post_content;
176
+
177
+    // Update the post content if we found mappings of new entities.
178
+    if ( ! empty( $entities_uri_mapping ) ) {
179
+        // Save each entity and store the post id.
180
+        foreach ( $entities_uri_mapping as $tmp_uri => $uri ) {
181
+            if ( 1 !== preg_match( '@^(https?://|local-entity-)@', $tmp_uri ) ) {
182
+                continue;
183
+            }
184
+
185
+            $updated_post_content = str_replace( $tmp_uri, $uri, $updated_post_content );
186
+        }
187
+
188
+        // Update the post content.
189
+        /**
190
+         * Note: wp_update_post do stripslashes before saving the
191
+         * content, so add the slashes to prevent back slash getting
192
+         * removed.
193
+         */
194
+        wp_update_post( array(
195
+            'ID'           => $post->ID,
196
+            'post_content' => addslashes( $updated_post_content ),
197
+        ) );
198
+    }
199
+    // Reset previously saved instances.
200
+    wl_core_delete_relation_instances( $post_id );
201
+
202
+
203
+    $relations = Object_Relation_Service::get_instance()
204
+                                        ->get_relations_from_content( $updated_post_content, Object_Type_Enum::POST );
205
+
206
+    // Save relation instances
207
+    foreach ( $relations as $relation ) {
208
+
209
+        wl_core_add_relation_instance(
210
+            // subject id.
211
+            $post_id,
212
+            // what, where, when, who
213
+            $relation->get_relation_type(),
214
+            // object id.
215
+            $relation->get_object_id(),
216
+            // Subject type.
217
+            $relation->get_subject_type(),
218
+            // Object type.
219
+            $relation->get_object_type()
220
+        );
221
+
222
+    }
223
+
224
+    if ( isset( $_POST['wl_entities'] ) ) {
225
+        // Save post metadata if available
226
+        $metadata_via_post = ( isset( $_POST['wl_metadata'] ) ) ?
227
+            $_POST['wl_metadata'] : array();
228
+
229
+        $fields = array(
230
+            Wordlift_Schema_Service::FIELD_LOCATION_CREATED,
231
+            Wordlift_Schema_Service::FIELD_TOPIC,
232
+        );
233
+
234
+        // Unlink topic taxonomy terms
235
+        Wordlift_Topic_Taxonomy_Service::get_instance()->unlink_topic_for( $post->ID );
236
+
237
+        foreach ( $fields as $field ) {
238
+
239
+            // Delete current values
240
+            delete_post_meta( $post->ID, $field );
241
+            // Retrieve the entity uri
242
+            $uri = ( isset( $metadata_via_post[ $field ] ) ) ?
243
+                stripslashes( $metadata_via_post[ $field ] ) : '';
244
+
245
+            $entity = $entity_service->get_entity_post_by_uri( $uri );
246
+
247
+            if ( $entity ) {
248
+                add_post_meta( $post->ID, $field, $entity->ID, true );
249
+                // Set also the topic taxonomy
250
+                if ( $field === Wordlift_Schema_Service::FIELD_TOPIC ) {
251
+                    Wordlift_Topic_Taxonomy_Service::get_instance()->set_topic_for( $post->ID, $entity );
252
+                }
253
+            }
254
+        }
255
+    }
256
+
257
+    // Push the post to Redlink.
258
+    do_action( 'wl_legacy_linked_data__push', $post->ID );
259
+
260
+    add_action( 'wl_linked_data_save_post', 'wl_linked_data_save_post_and_related_entities' );
261 261
 }
262 262
 
263 263
 add_action( 'wl_linked_data_save_post', 'wl_linked_data_save_post_and_related_entities' );
@@ -280,203 +280,203 @@  discard block
 block discarded – undo
280 280
  */
281 281
 function wl_save_entity( $entity_data ) {
282 282
 
283
-	// Required for REST API calls
284
-	if ( ! function_exists( 'wp_crop_image' ) ) {
285
-		require_once( ABSPATH . 'wp-admin/includes/image.php' );
286
-	}
283
+    // Required for REST API calls
284
+    if ( ! function_exists( 'wp_crop_image' ) ) {
285
+        require_once( ABSPATH . 'wp-admin/includes/image.php' );
286
+    }
287 287
 
288
-	$log = Wordlift_Log_Service::get_logger( 'wl_save_entity' );
288
+    $log = Wordlift_Log_Service::get_logger( 'wl_save_entity' );
289 289
 
290
-	$uri = $entity_data['uri'];
291
-	/*
290
+    $uri = $entity_data['uri'];
291
+    /*
292 292
 	 * Data is coming from a $_POST, sanitize it.
293 293
 	 *
294 294
 	 * @since 3.19.4
295 295
 	 *
296 296
 	 * @see https://github.com/insideout10/wordlift-plugin/issues/841
297 297
 	 */
298
-	$label            = preg_replace( '/\xEF\xBB\xBF/', '', sanitize_text_field( $entity_data['label'] ) );
299
-	$type_uri         = $entity_data['main_type'];
300
-	$entity_types     = isset( $entity_data['type'] ) ? $entity_data['type'] : array();
301
-	$description      = $entity_data['description'];
302
-	$images           = isset( $entity_data['image'] ) ? (array) $entity_data['image'] : array();
303
-	$same_as          = isset( $entity_data['sameas'] ) ? (array) $entity_data['sameas'] : array();
304
-	$related_post_id  = isset( $entity_data['related_post_id'] ) ? $entity_data['related_post_id'] : null;
305
-	$other_properties = isset( $entity_data['properties'] ) ? $entity_data['properties'] : array();
306
-
307
-	// Get the synonyms.
308
-	$synonyms = isset( $entity_data['synonym'] ) ? $entity_data['synonym'] : array();
309
-
310
-	// Check whether an entity already exists with the provided URI.
311
-	if ( null !== $post = Wordlift_Entity_Service::get_instance()->get_entity_post_by_uri( $uri ) ) {
312
-		$log->debug( "Post already exists for URI $uri." );
313
-
314
-		return $post;
315
-	}
316
-
317
-	// Prepare properties of the new entity.
318
-	$params = array(
319
-		'post_status'  => ( is_numeric( $related_post_id ) ? get_post_status( $related_post_id ) : 'draft' ),
320
-		'post_type'    => Wordlift_Entity_Service::TYPE_NAME,
321
-		'post_title'   => $label,
322
-		'post_content' => $description,
323
-		'post_excerpt' => '',
324
-		// Ensure we're using a valid slug. We're not overwriting an existing
325
-		// entity with a post_name already set, since this call is made only for
326
-		// new entities.
327
-		//
328
-		// See https://github.com/insideout10/wordlift-plugin/issues/282
329
-		'post_name'    => sanitize_title( $label ),
330
-	);
331
-
332
-	// If Yoast is installed and active, we temporary remove the save_postdata hook which causes Yoast to "pass over"
333
-	// the local SEO form values to the created entity (https://github.com/insideout10/wordlift-plugin/issues/156)
334
-	// Same thing applies to SEO Ultimate (https://github.com/insideout10/wordlift-plugin/issues/148)
335
-	// This does NOT affect saving an entity from the entity admin page since this function is called when an entity
336
-	// is created when saving a post.
337
-	global $wpseo_metabox, $seo_ultimate;
338
-	if ( isset( $wpseo_metabox ) ) {
339
-		remove_action( 'wp_insert_post', array(
340
-			$wpseo_metabox,
341
-			'save_postdata',
342
-		) );
343
-	}
344
-
345
-	if ( isset( $seo_ultimate ) ) {
346
-		remove_action( 'save_post', array(
347
-			$seo_ultimate,
348
-			'save_postmeta_box',
349
-		) );
350
-	}
351
-
352
-	// The fact that we're calling here wp_insert_post is causing issues with plugins (and ourselves too) that hook to
353
-	// save_post in order to save additional inputs from the edit page. In order to avoid issues, we pop all the hooks
354
-	// to the save_post and restore them after we saved the entity.
355
-	// see https://github.com/insideout10/wordlift-plugin/issues/203
356
-	// see https://github.com/insideout10/wordlift-plugin/issues/156
357
-	// see https://github.com/insideout10/wordlift-plugin/issues/148
358
-	global $wp_filter;
359
-	$save_post_filters = is_array( $wp_filter['save_post'] ) ? $wp_filter['save_post'] : $wp_filter['save_post']->callbacks;
360
-	is_array( $wp_filter['save_post'] ) ? $wp_filter['save_post'] = array() : $wp_filter['save_post']->remove_all_filters();
361
-
362
-
363
-	$log->trace( 'Going to insert new post...' );
364
-
365
-	// create or update the post.
366
-	$post_id = wp_insert_post( $params, true );
367
-
368
-	// Setting the alternative labels for this entity.
369
-	Wordlift_Entity_Service::get_instance()
370
-	                       ->set_alternative_labels( $post_id, $synonyms );
371
-
372
-	// Restore all the existing filters.
373
-	is_array( $wp_filter['save_post'] ) ? $wp_filter['save_post'] = $save_post_filters : $wp_filter['save_post']->callbacks = $save_post_filters;
374
-
375
-	// If Yoast is installed and active, we restore the Yoast save_postdata hook (https://github.com/insideout10/wordlift-plugin/issues/156)
376
-	if ( isset( $wpseo_metabox ) ) {
377
-		add_action( 'wp_insert_post', array(
378
-			$wpseo_metabox,
379
-			'save_postdata',
380
-		) );
381
-	}
382
-
383
-	// If SEO Ultimate is installed, add back the hook we removed a few lines above.
384
-	if ( isset( $seo_ultimate ) ) {
385
-		add_action( 'save_post', array(
386
-			$seo_ultimate,
387
-			'save_postmeta_box',
388
-		), 10, 2 );
389
-	}
390
-
391
-	// TODO: handle errors.
392
-	if ( is_wp_error( $post_id ) ) {
393
-		$log->error( 'An error occurred: ' . $post_id->get_error_message() );
394
-
395
-		// inform an error occurred.
396
-		return null;
397
-	}
398
-
399
-	wl_set_entity_main_type( $post_id, $type_uri );
400
-
401
-	// Save the entity types.
402
-	wl_set_entity_rdf_types( $post_id, $entity_types );
403
-
404
-	// Get a dataset URI for the entity.
405
-	$wl_uri = Wordlift_Entity_Service::get_instance()->get_uri( $post_id );
406
-
407
-	// Add the uri to the sameAs data if it's not a local URI.
408
-	if ( $wl_uri !== $uri ) {
409
-		array_push( $same_as, $uri );
410
-	}
411
-
412
-	// Save the sameAs data for the entity.
413
-	wl_schema_set_value( $post_id, 'sameAs', $same_as );
414
-
415
-	// Save the other properties (latitude, langitude, startDate, endDate, etc.)
416
-	foreach ( $other_properties as $property_name => $property_value ) {
417
-		wl_schema_set_value( $post_id, $property_name, $property_value );
418
-	}
419
-
420
-	// Call hooks.
421
-	do_action( 'wl_save_entity', $post_id );
422
-
423
-	foreach ( $images as $image_remote_url ) {
424
-
425
-		// Check if image is already present in local DB
426
-		if ( strpos( $image_remote_url, site_url() ) !== false ) {
427
-			// Do nothing.
428
-			continue;
429
-		}
430
-
431
-		// Check if there is an existing attachment for this post ID and source URL.
432
-		$existing_image = wl_get_attachment_for_source_url( $post_id, $image_remote_url );
433
-
434
-		// Skip if an existing image is found.
435
-		if ( null !== $existing_image ) {
436
-			continue;
437
-		}
438
-
439
-		// Save the image and get the local path.
440
-		$image = Wordlift_Remote_Image_Service::save_from_url( $image_remote_url );
441
-
442
-		if ( false === $image || is_wp_error( $image ) ) {
443
-			continue;
444
-		}
445
-
446
-		// Get the local URL.
447
-		$filename     = $image['path'];
448
-		$url          = $image['url'];
449
-		$content_type = $image['content_type'];
450
-
451
-		$attachment = array(
452
-			'guid'           => $url,
453
-			// post_title, post_content (the value for this key should be the empty string), post_status and post_mime_type
454
-			'post_title'     => $label,
455
-			// Set the title to the post title.
456
-			'post_content'   => '',
457
-			'post_status'    => 'inherit',
458
-			'post_mime_type' => $content_type,
459
-		);
298
+    $label            = preg_replace( '/\xEF\xBB\xBF/', '', sanitize_text_field( $entity_data['label'] ) );
299
+    $type_uri         = $entity_data['main_type'];
300
+    $entity_types     = isset( $entity_data['type'] ) ? $entity_data['type'] : array();
301
+    $description      = $entity_data['description'];
302
+    $images           = isset( $entity_data['image'] ) ? (array) $entity_data['image'] : array();
303
+    $same_as          = isset( $entity_data['sameas'] ) ? (array) $entity_data['sameas'] : array();
304
+    $related_post_id  = isset( $entity_data['related_post_id'] ) ? $entity_data['related_post_id'] : null;
305
+    $other_properties = isset( $entity_data['properties'] ) ? $entity_data['properties'] : array();
306
+
307
+    // Get the synonyms.
308
+    $synonyms = isset( $entity_data['synonym'] ) ? $entity_data['synonym'] : array();
309
+
310
+    // Check whether an entity already exists with the provided URI.
311
+    if ( null !== $post = Wordlift_Entity_Service::get_instance()->get_entity_post_by_uri( $uri ) ) {
312
+        $log->debug( "Post already exists for URI $uri." );
313
+
314
+        return $post;
315
+    }
316
+
317
+    // Prepare properties of the new entity.
318
+    $params = array(
319
+        'post_status'  => ( is_numeric( $related_post_id ) ? get_post_status( $related_post_id ) : 'draft' ),
320
+        'post_type'    => Wordlift_Entity_Service::TYPE_NAME,
321
+        'post_title'   => $label,
322
+        'post_content' => $description,
323
+        'post_excerpt' => '',
324
+        // Ensure we're using a valid slug. We're not overwriting an existing
325
+        // entity with a post_name already set, since this call is made only for
326
+        // new entities.
327
+        //
328
+        // See https://github.com/insideout10/wordlift-plugin/issues/282
329
+        'post_name'    => sanitize_title( $label ),
330
+    );
331
+
332
+    // If Yoast is installed and active, we temporary remove the save_postdata hook which causes Yoast to "pass over"
333
+    // the local SEO form values to the created entity (https://github.com/insideout10/wordlift-plugin/issues/156)
334
+    // Same thing applies to SEO Ultimate (https://github.com/insideout10/wordlift-plugin/issues/148)
335
+    // This does NOT affect saving an entity from the entity admin page since this function is called when an entity
336
+    // is created when saving a post.
337
+    global $wpseo_metabox, $seo_ultimate;
338
+    if ( isset( $wpseo_metabox ) ) {
339
+        remove_action( 'wp_insert_post', array(
340
+            $wpseo_metabox,
341
+            'save_postdata',
342
+        ) );
343
+    }
344
+
345
+    if ( isset( $seo_ultimate ) ) {
346
+        remove_action( 'save_post', array(
347
+            $seo_ultimate,
348
+            'save_postmeta_box',
349
+        ) );
350
+    }
351
+
352
+    // The fact that we're calling here wp_insert_post is causing issues with plugins (and ourselves too) that hook to
353
+    // save_post in order to save additional inputs from the edit page. In order to avoid issues, we pop all the hooks
354
+    // to the save_post and restore them after we saved the entity.
355
+    // see https://github.com/insideout10/wordlift-plugin/issues/203
356
+    // see https://github.com/insideout10/wordlift-plugin/issues/156
357
+    // see https://github.com/insideout10/wordlift-plugin/issues/148
358
+    global $wp_filter;
359
+    $save_post_filters = is_array( $wp_filter['save_post'] ) ? $wp_filter['save_post'] : $wp_filter['save_post']->callbacks;
360
+    is_array( $wp_filter['save_post'] ) ? $wp_filter['save_post'] = array() : $wp_filter['save_post']->remove_all_filters();
361
+
362
+
363
+    $log->trace( 'Going to insert new post...' );
364
+
365
+    // create or update the post.
366
+    $post_id = wp_insert_post( $params, true );
367
+
368
+    // Setting the alternative labels for this entity.
369
+    Wordlift_Entity_Service::get_instance()
370
+                            ->set_alternative_labels( $post_id, $synonyms );
371
+
372
+    // Restore all the existing filters.
373
+    is_array( $wp_filter['save_post'] ) ? $wp_filter['save_post'] = $save_post_filters : $wp_filter['save_post']->callbacks = $save_post_filters;
374
+
375
+    // If Yoast is installed and active, we restore the Yoast save_postdata hook (https://github.com/insideout10/wordlift-plugin/issues/156)
376
+    if ( isset( $wpseo_metabox ) ) {
377
+        add_action( 'wp_insert_post', array(
378
+            $wpseo_metabox,
379
+            'save_postdata',
380
+        ) );
381
+    }
382
+
383
+    // If SEO Ultimate is installed, add back the hook we removed a few lines above.
384
+    if ( isset( $seo_ultimate ) ) {
385
+        add_action( 'save_post', array(
386
+            $seo_ultimate,
387
+            'save_postmeta_box',
388
+        ), 10, 2 );
389
+    }
390
+
391
+    // TODO: handle errors.
392
+    if ( is_wp_error( $post_id ) ) {
393
+        $log->error( 'An error occurred: ' . $post_id->get_error_message() );
394
+
395
+        // inform an error occurred.
396
+        return null;
397
+    }
398
+
399
+    wl_set_entity_main_type( $post_id, $type_uri );
400
+
401
+    // Save the entity types.
402
+    wl_set_entity_rdf_types( $post_id, $entity_types );
403
+
404
+    // Get a dataset URI for the entity.
405
+    $wl_uri = Wordlift_Entity_Service::get_instance()->get_uri( $post_id );
406
+
407
+    // Add the uri to the sameAs data if it's not a local URI.
408
+    if ( $wl_uri !== $uri ) {
409
+        array_push( $same_as, $uri );
410
+    }
411
+
412
+    // Save the sameAs data for the entity.
413
+    wl_schema_set_value( $post_id, 'sameAs', $same_as );
414
+
415
+    // Save the other properties (latitude, langitude, startDate, endDate, etc.)
416
+    foreach ( $other_properties as $property_name => $property_value ) {
417
+        wl_schema_set_value( $post_id, $property_name, $property_value );
418
+    }
419
+
420
+    // Call hooks.
421
+    do_action( 'wl_save_entity', $post_id );
422
+
423
+    foreach ( $images as $image_remote_url ) {
424
+
425
+        // Check if image is already present in local DB
426
+        if ( strpos( $image_remote_url, site_url() ) !== false ) {
427
+            // Do nothing.
428
+            continue;
429
+        }
430
+
431
+        // Check if there is an existing attachment for this post ID and source URL.
432
+        $existing_image = wl_get_attachment_for_source_url( $post_id, $image_remote_url );
433
+
434
+        // Skip if an existing image is found.
435
+        if ( null !== $existing_image ) {
436
+            continue;
437
+        }
438
+
439
+        // Save the image and get the local path.
440
+        $image = Wordlift_Remote_Image_Service::save_from_url( $image_remote_url );
441
+
442
+        if ( false === $image || is_wp_error( $image ) ) {
443
+            continue;
444
+        }
445
+
446
+        // Get the local URL.
447
+        $filename     = $image['path'];
448
+        $url          = $image['url'];
449
+        $content_type = $image['content_type'];
450
+
451
+        $attachment = array(
452
+            'guid'           => $url,
453
+            // post_title, post_content (the value for this key should be the empty string), post_status and post_mime_type
454
+            'post_title'     => $label,
455
+            // Set the title to the post title.
456
+            'post_content'   => '',
457
+            'post_status'    => 'inherit',
458
+            'post_mime_type' => $content_type,
459
+        );
460 460
 
461
-		// Create the attachment in WordPress and generate the related metadata.
462
-		$attachment_id = wp_insert_attachment( $attachment, $filename, $post_id );
463
-
464
-		// Set the source URL for the image.
465
-		wl_set_source_url( $attachment_id, $image_remote_url );
466
-
467
-		$attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
468
-		wp_update_attachment_metadata( $attachment_id, $attachment_data );
469
-
470
-		// Set it as the featured image.
471
-		set_post_thumbnail( $post_id, $attachment_id );
472
-	}
473
-
474
-	// The entity is pushed to Redlink on save by the function hooked to save_post.
475
-	// save the entity in the triple store.
476
-	do_action( 'wl_legacy_linked_data__push', $post_id );
477
-
478
-	// finally return the entity post.
479
-	return get_post( $post_id );
461
+        // Create the attachment in WordPress and generate the related metadata.
462
+        $attachment_id = wp_insert_attachment( $attachment, $filename, $post_id );
463
+
464
+        // Set the source URL for the image.
465
+        wl_set_source_url( $attachment_id, $image_remote_url );
466
+
467
+        $attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
468
+        wp_update_attachment_metadata( $attachment_id, $attachment_data );
469
+
470
+        // Set it as the featured image.
471
+        set_post_thumbnail( $post_id, $attachment_id );
472
+    }
473
+
474
+    // The entity is pushed to Redlink on save by the function hooked to save_post.
475
+    // save the entity in the triple store.
476
+    do_action( 'wl_legacy_linked_data__push', $post_id );
477
+
478
+    // finally return the entity post.
479
+    return get_post( $post_id );
480 480
 }
481 481
 
482 482
 /**
@@ -490,41 +490,41 @@  discard block
 block discarded – undo
490 490
  */
491 491
 function wl_linked_data_content_get_embedded_entities( $content ) {
492 492
 
493
-	// Remove quote escapes.
494
-	$content = str_replace( '\\"', '"', $content );
493
+    // Remove quote escapes.
494
+    $content = str_replace( '\\"', '"', $content );
495 495
 
496
-	// Match all itemid attributes.
497
-	$pattern = '/<\w+[^>]*\sitemid="([^"]+)"[^>]*>/im';
496
+    // Match all itemid attributes.
497
+    $pattern = '/<\w+[^>]*\sitemid="([^"]+)"[^>]*>/im';
498 498
 
499
-	//	wl_write_log( "Getting entities embedded into content [ pattern :: $pattern ]" );
499
+    //	wl_write_log( "Getting entities embedded into content [ pattern :: $pattern ]" );
500 500
 
501
-	// Remove the pattern while it is found (match nested annotations).
502
-	$matches = array();
501
+    // Remove the pattern while it is found (match nested annotations).
502
+    $matches = array();
503 503
 
504
-	// In case of errors, return an empty array.
505
-	if ( false === preg_match_all( $pattern, $content, $matches ) ) {
506
-		wl_write_log( "Found no entities embedded in content" );
504
+    // In case of errors, return an empty array.
505
+    if ( false === preg_match_all( $pattern, $content, $matches ) ) {
506
+        wl_write_log( "Found no entities embedded in content" );
507 507
 
508
-		return array();
509
-	}
508
+        return array();
509
+    }
510 510
 
511 511
 //    wl_write_log("wl_update_related_entities [ content :: $content ][ data :: " . var_export($data, true). " ][ matches :: " . var_export($matches, true) . " ]");
512 512
 
513
-	$uris  = $matches[1];
514
-	// Collect the entities.
515
-	$entities = array();
516
-	foreach ( $uris as $uri ) {
517
-		$uri_d = html_entity_decode( $uri );
513
+    $uris  = $matches[1];
514
+    // Collect the entities.
515
+    $entities = array();
516
+    foreach ( $uris as $uri ) {
517
+        $uri_d = html_entity_decode( $uri );
518 518
 
519
-		$entity = Wordlift_Entity_Service::get_instance()->get_entity_post_by_uri( $uri_d );
519
+        $entity = Wordlift_Entity_Service::get_instance()->get_entity_post_by_uri( $uri_d );
520 520
 
521
-		if ( null !== $entity ) {
522
-			array_push( $entities, $entity->ID );
523
-		}
524
-	}
521
+        if ( null !== $entity ) {
522
+            array_push( $entities, $entity->ID );
523
+        }
524
+    }
525 525
 
526
-	// $count = sizeof( $entities );
527
-	// wl_write_log( "Found $count entities embedded in content" );
526
+    // $count = sizeof( $entities );
527
+    // wl_write_log( "Found $count entities embedded in content" );
528 528
 
529
-	return $entities;
529
+    return $entities;
530 530
 }
531 531
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +132 added lines, -132 removed lines patch added patch discarded remove patch
@@ -18,15 +18,15 @@  discard block
 block discarded – undo
18 18
  * @since 3.0.0
19 19
  *
20 20
  */
21
-function wl_linked_data_save_post( $post_id ) {
21
+function wl_linked_data_save_post($post_id) {
22 22
 
23
-	$log = Wordlift_Log_Service::get_logger( 'wl_linked_data_save_post' );
23
+	$log = Wordlift_Log_Service::get_logger('wl_linked_data_save_post');
24 24
 
25
-	$log->trace( "Saving post $post_id to Linked Data..." );
25
+	$log->trace("Saving post $post_id to Linked Data...");
26 26
 
27 27
 	// If it's not numeric exit from here.
28
-	if ( ! is_numeric( $post_id ) || is_numeric( wp_is_post_revision( $post_id ) ) ) {
29
-		$log->debug( "Skipping $post_id, because id is not numeric or is a post revision." );
28
+	if ( ! is_numeric($post_id) || is_numeric(wp_is_post_revision($post_id))) {
29
+		$log->debug("Skipping $post_id, because id is not numeric or is a post revision.");
30 30
 
31 31
 		return;
32 32
 	}
@@ -34,7 +34,7 @@  discard block
 block discarded – undo
34 34
 	// Get the post type and check whether it supports the editor.
35 35
 	//
36 36
 	// @see https://github.com/insideout10/wordlift-plugin/issues/659.
37
-	$post_type = get_post_type( $post_id );
37
+	$post_type = get_post_type($post_id);
38 38
 	/**
39 39
 	 * Use `wl_post_type_supports_editor` which calls a filter to allow 3rd parties to change the setting.
40 40
 	 *
@@ -42,11 +42,11 @@  discard block
 block discarded – undo
42 42
 	 *
43 43
 	 * @see https://github.com/insideout10/wordlift-plugin/issues/847.
44 44
 	 */
45
-	$is_editor_supported = wl_post_type_supports_editor( $post_type );
45
+	$is_editor_supported = wl_post_type_supports_editor($post_type);
46 46
 
47 47
 	// Bail out if it's not an entity.
48
-	if ( ! $is_editor_supported ) {
49
-		$log->debug( "Skipping $post_id, because $post_type doesn't support the editor (content)." );
48
+	if ( ! $is_editor_supported) {
49
+		$log->debug("Skipping $post_id, because $post_type doesn't support the editor (content).");
50 50
 
51 51
 		return;
52 52
 	}
@@ -60,23 +60,23 @@  discard block
 block discarded – undo
60 60
 	$supported_types = Wordlift_Entity_Service::valid_entity_post_types();
61 61
 
62 62
 	// Bail out if it's not a valid entity.
63
-	if ( ! in_array( $post_type, $supported_types ) ) {
64
-		$log->debug( "Skipping $post_id, because $post_type is not a valid entity." );
63
+	if ( ! in_array($post_type, $supported_types)) {
64
+		$log->debug("Skipping $post_id, because $post_type is not a valid entity.");
65 65
 
66 66
 		return;
67 67
 	}
68 68
 
69 69
 	// Unhook this function so it doesn't loop infinitely.
70
-	remove_action( 'save_post', 'wl_linked_data_save_post' );
70
+	remove_action('save_post', 'wl_linked_data_save_post');
71 71
 
72 72
 	// raise the *wl_linked_data_save_post* event.
73
-	do_action( 'wl_linked_data_save_post', $post_id );
73
+	do_action('wl_linked_data_save_post', $post_id);
74 74
 
75 75
 	// Re-hook this function.
76
-	add_action( 'save_post', 'wl_linked_data_save_post' );
76
+	add_action('save_post', 'wl_linked_data_save_post');
77 77
 }
78 78
 
79
-add_action( 'save_post', 'wl_linked_data_save_post' );
79
+add_action('save_post', 'wl_linked_data_save_post');
80 80
 
81 81
 /**
82 82
  * Save the post to the triple store. Also saves the entities locally and on the triple store.
@@ -86,23 +86,23 @@  discard block
 block discarded – undo
86 86
  * @since 3.0.0
87 87
  *
88 88
  */
89
-function wl_linked_data_save_post_and_related_entities( $post_id ) {
89
+function wl_linked_data_save_post_and_related_entities($post_id) {
90 90
 
91
-	$log = Wordlift_Log_Service::get_logger( 'wl_linked_data_save_post_and_related_entities' );
91
+	$log = Wordlift_Log_Service::get_logger('wl_linked_data_save_post_and_related_entities');
92 92
 
93
-	$log->trace( "Saving $post_id to Linked Data along with related entities..." );
93
+	$log->trace("Saving $post_id to Linked Data along with related entities...");
94 94
 
95 95
 	// Ignore auto-saves
96
-	if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
97
-		$log->trace( 'Doing autosave, skipping...' );
96
+	if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
97
+		$log->trace('Doing autosave, skipping...');
98 98
 
99 99
 		return;
100 100
 	}
101 101
 
102 102
 	// get the current post.
103
-	$post = get_post( $post_id );
103
+	$post = get_post($post_id);
104 104
 
105
-	remove_action( 'wl_linked_data_save_post', 'wl_linked_data_save_post_and_related_entities' );
105
+	remove_action('wl_linked_data_save_post', 'wl_linked_data_save_post_and_related_entities');
106 106
 
107 107
 	// wl_write_log( "[ post id :: $post_id ][ autosave :: false ][ post type :: $post->post_type ]" );
108 108
 
@@ -113,48 +113,48 @@  discard block
 block discarded – undo
113 113
 	$entities_uri_mapping = array();
114 114
 
115 115
 	// Save the entities coming with POST data.
116
-	if ( isset( $_POST['wl_entities'] ) && isset( $_POST['wl_boxes'] ) ) {
116
+	if (isset($_POST['wl_entities']) && isset($_POST['wl_boxes'])) {
117 117
 
118
-		wl_write_log( "[ post id :: $post_id ][ POST(wl_entities) :: " );
119
-		wl_write_log( json_encode( $_POST['wl_entities'] ) );
120
-		wl_write_log( "]" );
121
-		wl_write_log( "[ post id :: $post_id ][ POST(wl_boxes) :: " );
122
-		wl_write_log( json_encode( $_POST['wl_boxes'], true ) );
123
-		wl_write_log( "]" );
118
+		wl_write_log("[ post id :: $post_id ][ POST(wl_entities) :: ");
119
+		wl_write_log(json_encode($_POST['wl_entities']));
120
+		wl_write_log("]");
121
+		wl_write_log("[ post id :: $post_id ][ POST(wl_boxes) :: ");
122
+		wl_write_log(json_encode($_POST['wl_boxes'], true));
123
+		wl_write_log("]");
124 124
 
125 125
 		$entities_via_post = $_POST['wl_entities'];
126 126
 
127
-		foreach ( $entities_via_post as $entity_uri => $entity ) {
127
+		foreach ($entities_via_post as $entity_uri => $entity) {
128 128
 
129 129
 			// Only if the current entity is created from scratch let's avoid to
130 130
 			// create more than one entity with same label & entity type.
131
-			$entity_type = ( preg_match( '/^local-entity-.+/', $entity_uri ) > 0 ) ?
131
+			$entity_type = (preg_match('/^local-entity-.+/', $entity_uri) > 0) ?
132 132
 				$entity['main_type'] : null;
133 133
 
134 134
 			// Look if current entity uri matches an internal existing entity, meaning:
135 135
 			// 1. when $entity_uri is an internal uri
136 136
 			// 2. when $entity_uri is an external uri used as sameAs of an internal entity
137
-			$ie = $entity_service->get_entity_post_by_uri( $entity_uri );
137
+			$ie = $entity_service->get_entity_post_by_uri($entity_uri);
138 138
 
139 139
 			// Dont save the entities which are not found, but also local.
140
-			if ( $ie === null &&  Wordlift_Entity_Uri_Service::get_instance()->is_internal( $entity_uri ) ) {
140
+			if ($ie === null && Wordlift_Entity_Uri_Service::get_instance()->is_internal($entity_uri)) {
141 141
 				continue;
142 142
 			}
143 143
 
144 144
 			// Detect the uri depending if is an existing or a new entity
145
-			$uri = ( null === $ie ) ?
145
+			$uri = (null === $ie) ?
146 146
 				Wordlift_Uri_Service::get_instance()->build_uri(
147 147
 					$entity['label'],
148 148
 					Wordlift_Entity_Service::TYPE_NAME,
149 149
 					$entity_type
150
-				) : wl_get_entity_uri( $ie->ID );
150
+				) : wl_get_entity_uri($ie->ID);
151 151
 
152
-			wl_write_log( "Map $entity_uri on $uri" );
153
-			$entities_uri_mapping[ $entity_uri ] = $uri;
152
+			wl_write_log("Map $entity_uri on $uri");
153
+			$entities_uri_mapping[$entity_uri] = $uri;
154 154
 
155 155
 			// Local entities have a tmp uri with 'local-entity-' prefix
156 156
 			// These uris need to be rewritten here and replaced in the content
157
-			if ( preg_match( '/^local-entity-.+/', $entity_uri ) > 0 ) {
157
+			if (preg_match('/^local-entity-.+/', $entity_uri) > 0) {
158 158
 				// Override the entity obj
159 159
 				$entity['uri'] = $uri;
160 160
 			}
@@ -163,8 +163,8 @@  discard block
 block discarded – undo
163 163
 			$entity['related_post_id'] = $post_id;
164 164
 
165 165
 			// Save the entity if is a new entity
166
-			if ( null === $ie ) {
167
-				wl_save_entity( $entity );
166
+			if (null === $ie) {
167
+				wl_save_entity($entity);
168 168
 			}
169 169
 
170 170
 		}
@@ -175,14 +175,14 @@  discard block
 block discarded – undo
175 175
 	$updated_post_content = $post->post_content;
176 176
 
177 177
 	// Update the post content if we found mappings of new entities.
178
-	if ( ! empty( $entities_uri_mapping ) ) {
178
+	if ( ! empty($entities_uri_mapping)) {
179 179
 		// Save each entity and store the post id.
180
-		foreach ( $entities_uri_mapping as $tmp_uri => $uri ) {
181
-			if ( 1 !== preg_match( '@^(https?://|local-entity-)@', $tmp_uri ) ) {
180
+		foreach ($entities_uri_mapping as $tmp_uri => $uri) {
181
+			if (1 !== preg_match('@^(https?://|local-entity-)@', $tmp_uri)) {
182 182
 				continue;
183 183
 			}
184 184
 
185
-			$updated_post_content = str_replace( $tmp_uri, $uri, $updated_post_content );
185
+			$updated_post_content = str_replace($tmp_uri, $uri, $updated_post_content);
186 186
 		}
187 187
 
188 188
 		// Update the post content.
@@ -191,20 +191,20 @@  discard block
 block discarded – undo
191 191
 		 * content, so add the slashes to prevent back slash getting
192 192
 		 * removed.
193 193
 		 */
194
-		wp_update_post( array(
194
+		wp_update_post(array(
195 195
 			'ID'           => $post->ID,
196
-			'post_content' => addslashes( $updated_post_content ),
197
-		) );
196
+			'post_content' => addslashes($updated_post_content),
197
+		));
198 198
 	}
199 199
 	// Reset previously saved instances.
200
-	wl_core_delete_relation_instances( $post_id );
200
+	wl_core_delete_relation_instances($post_id);
201 201
 
202 202
 
203 203
 	$relations = Object_Relation_Service::get_instance()
204
-	                                    ->get_relations_from_content( $updated_post_content, Object_Type_Enum::POST );
204
+	                                    ->get_relations_from_content($updated_post_content, Object_Type_Enum::POST);
205 205
 
206 206
 	// Save relation instances
207
-	foreach ( $relations as $relation ) {
207
+	foreach ($relations as $relation) {
208 208
 
209 209
 		wl_core_add_relation_instance(
210 210
 			// subject id.
@@ -221,9 +221,9 @@  discard block
 block discarded – undo
221 221
 
222 222
 	}
223 223
 
224
-	if ( isset( $_POST['wl_entities'] ) ) {
224
+	if (isset($_POST['wl_entities'])) {
225 225
 		// Save post metadata if available
226
-		$metadata_via_post = ( isset( $_POST['wl_metadata'] ) ) ?
226
+		$metadata_via_post = (isset($_POST['wl_metadata'])) ?
227 227
 			$_POST['wl_metadata'] : array();
228 228
 
229 229
 		$fields = array(
@@ -232,35 +232,35 @@  discard block
 block discarded – undo
232 232
 		);
233 233
 
234 234
 		// Unlink topic taxonomy terms
235
-		Wordlift_Topic_Taxonomy_Service::get_instance()->unlink_topic_for( $post->ID );
235
+		Wordlift_Topic_Taxonomy_Service::get_instance()->unlink_topic_for($post->ID);
236 236
 
237
-		foreach ( $fields as $field ) {
237
+		foreach ($fields as $field) {
238 238
 
239 239
 			// Delete current values
240
-			delete_post_meta( $post->ID, $field );
240
+			delete_post_meta($post->ID, $field);
241 241
 			// Retrieve the entity uri
242
-			$uri = ( isset( $metadata_via_post[ $field ] ) ) ?
243
-				stripslashes( $metadata_via_post[ $field ] ) : '';
242
+			$uri = (isset($metadata_via_post[$field])) ?
243
+				stripslashes($metadata_via_post[$field]) : '';
244 244
 
245
-			$entity = $entity_service->get_entity_post_by_uri( $uri );
245
+			$entity = $entity_service->get_entity_post_by_uri($uri);
246 246
 
247
-			if ( $entity ) {
248
-				add_post_meta( $post->ID, $field, $entity->ID, true );
247
+			if ($entity) {
248
+				add_post_meta($post->ID, $field, $entity->ID, true);
249 249
 				// Set also the topic taxonomy
250
-				if ( $field === Wordlift_Schema_Service::FIELD_TOPIC ) {
251
-					Wordlift_Topic_Taxonomy_Service::get_instance()->set_topic_for( $post->ID, $entity );
250
+				if ($field === Wordlift_Schema_Service::FIELD_TOPIC) {
251
+					Wordlift_Topic_Taxonomy_Service::get_instance()->set_topic_for($post->ID, $entity);
252 252
 				}
253 253
 			}
254 254
 		}
255 255
 	}
256 256
 
257 257
 	// Push the post to Redlink.
258
-	do_action( 'wl_legacy_linked_data__push', $post->ID );
258
+	do_action('wl_legacy_linked_data__push', $post->ID);
259 259
 
260
-	add_action( 'wl_linked_data_save_post', 'wl_linked_data_save_post_and_related_entities' );
260
+	add_action('wl_linked_data_save_post', 'wl_linked_data_save_post_and_related_entities');
261 261
 }
262 262
 
263
-add_action( 'wl_linked_data_save_post', 'wl_linked_data_save_post_and_related_entities' );
263
+add_action('wl_linked_data_save_post', 'wl_linked_data_save_post_and_related_entities');
264 264
 
265 265
 /**
266 266
  * Save the specified data as an entity in WordPress. This method only create new entities. When an existing entity is
@@ -278,14 +278,14 @@  discard block
 block discarded – undo
278 278
  *
279 279
  * @return null|WP_Post A post instance or null in case of failure.
280 280
  */
281
-function wl_save_entity( $entity_data ) {
281
+function wl_save_entity($entity_data) {
282 282
 
283 283
 	// Required for REST API calls
284
-	if ( ! function_exists( 'wp_crop_image' ) ) {
285
-		require_once( ABSPATH . 'wp-admin/includes/image.php' );
284
+	if ( ! function_exists('wp_crop_image')) {
285
+		require_once(ABSPATH.'wp-admin/includes/image.php');
286 286
 	}
287 287
 
288
-	$log = Wordlift_Log_Service::get_logger( 'wl_save_entity' );
288
+	$log = Wordlift_Log_Service::get_logger('wl_save_entity');
289 289
 
290 290
 	$uri = $entity_data['uri'];
291 291
 	/*
@@ -295,28 +295,28 @@  discard block
 block discarded – undo
295 295
 	 *
296 296
 	 * @see https://github.com/insideout10/wordlift-plugin/issues/841
297 297
 	 */
298
-	$label            = preg_replace( '/\xEF\xBB\xBF/', '', sanitize_text_field( $entity_data['label'] ) );
298
+	$label            = preg_replace('/\xEF\xBB\xBF/', '', sanitize_text_field($entity_data['label']));
299 299
 	$type_uri         = $entity_data['main_type'];
300
-	$entity_types     = isset( $entity_data['type'] ) ? $entity_data['type'] : array();
300
+	$entity_types     = isset($entity_data['type']) ? $entity_data['type'] : array();
301 301
 	$description      = $entity_data['description'];
302
-	$images           = isset( $entity_data['image'] ) ? (array) $entity_data['image'] : array();
303
-	$same_as          = isset( $entity_data['sameas'] ) ? (array) $entity_data['sameas'] : array();
304
-	$related_post_id  = isset( $entity_data['related_post_id'] ) ? $entity_data['related_post_id'] : null;
305
-	$other_properties = isset( $entity_data['properties'] ) ? $entity_data['properties'] : array();
302
+	$images           = isset($entity_data['image']) ? (array) $entity_data['image'] : array();
303
+	$same_as          = isset($entity_data['sameas']) ? (array) $entity_data['sameas'] : array();
304
+	$related_post_id  = isset($entity_data['related_post_id']) ? $entity_data['related_post_id'] : null;
305
+	$other_properties = isset($entity_data['properties']) ? $entity_data['properties'] : array();
306 306
 
307 307
 	// Get the synonyms.
308
-	$synonyms = isset( $entity_data['synonym'] ) ? $entity_data['synonym'] : array();
308
+	$synonyms = isset($entity_data['synonym']) ? $entity_data['synonym'] : array();
309 309
 
310 310
 	// Check whether an entity already exists with the provided URI.
311
-	if ( null !== $post = Wordlift_Entity_Service::get_instance()->get_entity_post_by_uri( $uri ) ) {
312
-		$log->debug( "Post already exists for URI $uri." );
311
+	if (null !== $post = Wordlift_Entity_Service::get_instance()->get_entity_post_by_uri($uri)) {
312
+		$log->debug("Post already exists for URI $uri.");
313 313
 
314 314
 		return $post;
315 315
 	}
316 316
 
317 317
 	// Prepare properties of the new entity.
318 318
 	$params = array(
319
-		'post_status'  => ( is_numeric( $related_post_id ) ? get_post_status( $related_post_id ) : 'draft' ),
319
+		'post_status'  => (is_numeric($related_post_id) ? get_post_status($related_post_id) : 'draft'),
320 320
 		'post_type'    => Wordlift_Entity_Service::TYPE_NAME,
321 321
 		'post_title'   => $label,
322 322
 		'post_content' => $description,
@@ -326,7 +326,7 @@  discard block
 block discarded – undo
326 326
 		// new entities.
327 327
 		//
328 328
 		// See https://github.com/insideout10/wordlift-plugin/issues/282
329
-		'post_name'    => sanitize_title( $label ),
329
+		'post_name'    => sanitize_title($label),
330 330
 	);
331 331
 
332 332
 	// If Yoast is installed and active, we temporary remove the save_postdata hook which causes Yoast to "pass over"
@@ -335,18 +335,18 @@  discard block
 block discarded – undo
335 335
 	// This does NOT affect saving an entity from the entity admin page since this function is called when an entity
336 336
 	// is created when saving a post.
337 337
 	global $wpseo_metabox, $seo_ultimate;
338
-	if ( isset( $wpseo_metabox ) ) {
339
-		remove_action( 'wp_insert_post', array(
338
+	if (isset($wpseo_metabox)) {
339
+		remove_action('wp_insert_post', array(
340 340
 			$wpseo_metabox,
341 341
 			'save_postdata',
342
-		) );
342
+		));
343 343
 	}
344 344
 
345
-	if ( isset( $seo_ultimate ) ) {
346
-		remove_action( 'save_post', array(
345
+	if (isset($seo_ultimate)) {
346
+		remove_action('save_post', array(
347 347
 			$seo_ultimate,
348 348
 			'save_postmeta_box',
349
-		) );
349
+		));
350 350
 	}
351 351
 
352 352
 	// The fact that we're calling here wp_insert_post is causing issues with plugins (and ourselves too) that hook to
@@ -356,90 +356,90 @@  discard block
 block discarded – undo
356 356
 	// see https://github.com/insideout10/wordlift-plugin/issues/156
357 357
 	// see https://github.com/insideout10/wordlift-plugin/issues/148
358 358
 	global $wp_filter;
359
-	$save_post_filters = is_array( $wp_filter['save_post'] ) ? $wp_filter['save_post'] : $wp_filter['save_post']->callbacks;
360
-	is_array( $wp_filter['save_post'] ) ? $wp_filter['save_post'] = array() : $wp_filter['save_post']->remove_all_filters();
359
+	$save_post_filters = is_array($wp_filter['save_post']) ? $wp_filter['save_post'] : $wp_filter['save_post']->callbacks;
360
+	is_array($wp_filter['save_post']) ? $wp_filter['save_post'] = array() : $wp_filter['save_post']->remove_all_filters();
361 361
 
362 362
 
363
-	$log->trace( 'Going to insert new post...' );
363
+	$log->trace('Going to insert new post...');
364 364
 
365 365
 	// create or update the post.
366
-	$post_id = wp_insert_post( $params, true );
366
+	$post_id = wp_insert_post($params, true);
367 367
 
368 368
 	// Setting the alternative labels for this entity.
369 369
 	Wordlift_Entity_Service::get_instance()
370
-	                       ->set_alternative_labels( $post_id, $synonyms );
370
+	                       ->set_alternative_labels($post_id, $synonyms);
371 371
 
372 372
 	// Restore all the existing filters.
373
-	is_array( $wp_filter['save_post'] ) ? $wp_filter['save_post'] = $save_post_filters : $wp_filter['save_post']->callbacks = $save_post_filters;
373
+	is_array($wp_filter['save_post']) ? $wp_filter['save_post'] = $save_post_filters : $wp_filter['save_post']->callbacks = $save_post_filters;
374 374
 
375 375
 	// If Yoast is installed and active, we restore the Yoast save_postdata hook (https://github.com/insideout10/wordlift-plugin/issues/156)
376
-	if ( isset( $wpseo_metabox ) ) {
377
-		add_action( 'wp_insert_post', array(
376
+	if (isset($wpseo_metabox)) {
377
+		add_action('wp_insert_post', array(
378 378
 			$wpseo_metabox,
379 379
 			'save_postdata',
380
-		) );
380
+		));
381 381
 	}
382 382
 
383 383
 	// If SEO Ultimate is installed, add back the hook we removed a few lines above.
384
-	if ( isset( $seo_ultimate ) ) {
385
-		add_action( 'save_post', array(
384
+	if (isset($seo_ultimate)) {
385
+		add_action('save_post', array(
386 386
 			$seo_ultimate,
387 387
 			'save_postmeta_box',
388
-		), 10, 2 );
388
+		), 10, 2);
389 389
 	}
390 390
 
391 391
 	// TODO: handle errors.
392
-	if ( is_wp_error( $post_id ) ) {
393
-		$log->error( 'An error occurred: ' . $post_id->get_error_message() );
392
+	if (is_wp_error($post_id)) {
393
+		$log->error('An error occurred: '.$post_id->get_error_message());
394 394
 
395 395
 		// inform an error occurred.
396 396
 		return null;
397 397
 	}
398 398
 
399
-	wl_set_entity_main_type( $post_id, $type_uri );
399
+	wl_set_entity_main_type($post_id, $type_uri);
400 400
 
401 401
 	// Save the entity types.
402
-	wl_set_entity_rdf_types( $post_id, $entity_types );
402
+	wl_set_entity_rdf_types($post_id, $entity_types);
403 403
 
404 404
 	// Get a dataset URI for the entity.
405
-	$wl_uri = Wordlift_Entity_Service::get_instance()->get_uri( $post_id );
405
+	$wl_uri = Wordlift_Entity_Service::get_instance()->get_uri($post_id);
406 406
 
407 407
 	// Add the uri to the sameAs data if it's not a local URI.
408
-	if ( $wl_uri !== $uri ) {
409
-		array_push( $same_as, $uri );
408
+	if ($wl_uri !== $uri) {
409
+		array_push($same_as, $uri);
410 410
 	}
411 411
 
412 412
 	// Save the sameAs data for the entity.
413
-	wl_schema_set_value( $post_id, 'sameAs', $same_as );
413
+	wl_schema_set_value($post_id, 'sameAs', $same_as);
414 414
 
415 415
 	// Save the other properties (latitude, langitude, startDate, endDate, etc.)
416
-	foreach ( $other_properties as $property_name => $property_value ) {
417
-		wl_schema_set_value( $post_id, $property_name, $property_value );
416
+	foreach ($other_properties as $property_name => $property_value) {
417
+		wl_schema_set_value($post_id, $property_name, $property_value);
418 418
 	}
419 419
 
420 420
 	// Call hooks.
421
-	do_action( 'wl_save_entity', $post_id );
421
+	do_action('wl_save_entity', $post_id);
422 422
 
423
-	foreach ( $images as $image_remote_url ) {
423
+	foreach ($images as $image_remote_url) {
424 424
 
425 425
 		// Check if image is already present in local DB
426
-		if ( strpos( $image_remote_url, site_url() ) !== false ) {
426
+		if (strpos($image_remote_url, site_url()) !== false) {
427 427
 			// Do nothing.
428 428
 			continue;
429 429
 		}
430 430
 
431 431
 		// Check if there is an existing attachment for this post ID and source URL.
432
-		$existing_image = wl_get_attachment_for_source_url( $post_id, $image_remote_url );
432
+		$existing_image = wl_get_attachment_for_source_url($post_id, $image_remote_url);
433 433
 
434 434
 		// Skip if an existing image is found.
435
-		if ( null !== $existing_image ) {
435
+		if (null !== $existing_image) {
436 436
 			continue;
437 437
 		}
438 438
 
439 439
 		// Save the image and get the local path.
440
-		$image = Wordlift_Remote_Image_Service::save_from_url( $image_remote_url );
440
+		$image = Wordlift_Remote_Image_Service::save_from_url($image_remote_url);
441 441
 
442
-		if ( false === $image || is_wp_error( $image ) ) {
442
+		if (false === $image || is_wp_error($image)) {
443 443
 			continue;
444 444
 		}
445 445
 
@@ -459,24 +459,24 @@  discard block
 block discarded – undo
459 459
 		);
460 460
 
461 461
 		// Create the attachment in WordPress and generate the related metadata.
462
-		$attachment_id = wp_insert_attachment( $attachment, $filename, $post_id );
462
+		$attachment_id = wp_insert_attachment($attachment, $filename, $post_id);
463 463
 
464 464
 		// Set the source URL for the image.
465
-		wl_set_source_url( $attachment_id, $image_remote_url );
465
+		wl_set_source_url($attachment_id, $image_remote_url);
466 466
 
467
-		$attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
468
-		wp_update_attachment_metadata( $attachment_id, $attachment_data );
467
+		$attachment_data = wp_generate_attachment_metadata($attachment_id, $filename);
468
+		wp_update_attachment_metadata($attachment_id, $attachment_data);
469 469
 
470 470
 		// Set it as the featured image.
471
-		set_post_thumbnail( $post_id, $attachment_id );
471
+		set_post_thumbnail($post_id, $attachment_id);
472 472
 	}
473 473
 
474 474
 	// The entity is pushed to Redlink on save by the function hooked to save_post.
475 475
 	// save the entity in the triple store.
476
-	do_action( 'wl_legacy_linked_data__push', $post_id );
476
+	do_action('wl_legacy_linked_data__push', $post_id);
477 477
 
478 478
 	// finally return the entity post.
479
-	return get_post( $post_id );
479
+	return get_post($post_id);
480 480
 }
481 481
 
482 482
 /**
@@ -488,10 +488,10 @@  discard block
 block discarded – undo
488 488
  * @since 3.0.0
489 489
  *
490 490
  */
491
-function wl_linked_data_content_get_embedded_entities( $content ) {
491
+function wl_linked_data_content_get_embedded_entities($content) {
492 492
 
493 493
 	// Remove quote escapes.
494
-	$content = str_replace( '\\"', '"', $content );
494
+	$content = str_replace('\\"', '"', $content);
495 495
 
496 496
 	// Match all itemid attributes.
497 497
 	$pattern = '/<\w+[^>]*\sitemid="([^"]+)"[^>]*>/im';
@@ -502,24 +502,24 @@  discard block
 block discarded – undo
502 502
 	$matches = array();
503 503
 
504 504
 	// In case of errors, return an empty array.
505
-	if ( false === preg_match_all( $pattern, $content, $matches ) ) {
506
-		wl_write_log( "Found no entities embedded in content" );
505
+	if (false === preg_match_all($pattern, $content, $matches)) {
506
+		wl_write_log("Found no entities embedded in content");
507 507
 
508 508
 		return array();
509 509
 	}
510 510
 
511 511
 //    wl_write_log("wl_update_related_entities [ content :: $content ][ data :: " . var_export($data, true). " ][ matches :: " . var_export($matches, true) . " ]");
512 512
 
513
-	$uris  = $matches[1];
513
+	$uris = $matches[1];
514 514
 	// Collect the entities.
515 515
 	$entities = array();
516
-	foreach ( $uris as $uri ) {
517
-		$uri_d = html_entity_decode( $uri );
516
+	foreach ($uris as $uri) {
517
+		$uri_d = html_entity_decode($uri);
518 518
 
519
-		$entity = Wordlift_Entity_Service::get_instance()->get_entity_post_by_uri( $uri_d );
519
+		$entity = Wordlift_Entity_Service::get_instance()->get_entity_post_by_uri($uri_d);
520 520
 
521
-		if ( null !== $entity ) {
522
-			array_push( $entities, $entity->ID );
521
+		if (null !== $entity) {
522
+			array_push($entities, $entity->ID);
523 523
 		}
524 524
 	}
525 525
 
Please login to merge, or discard this patch.
src/includes/rebuild/class-wordlift-rebuild-service.php 2 patches
Indentation   +158 added lines, -158 removed lines patch added patch discarded remove patch
@@ -20,132 +20,132 @@  discard block
 block discarded – undo
20 20
  */
21 21
 class Wordlift_Rebuild_Service extends Wordlift_Listable {
22 22
 
23
-	/**
24
-	 * A {@link Wordlift_Log_Service} instance.
25
-	 *
26
-	 * @since  3.6.0
27
-	 * @access private
28
-	 * @var \Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
29
-	 */
30
-	private $log;
31
-
32
-	/**
33
-	 * A {@link Wordlift_Sparql_Service} instance.
34
-	 *
35
-	 * @since  3.6.0
36
-	 * @access private
37
-	 * @var \Wordlift_Sparql_Service $sparql_service A {@link Wordlift_Sparql_Service} instance.
38
-	 */
39
-	private $sparql_service;
40
-
41
-	/**
42
-	 * The {@link Wordlift_Uri_Service} instance.
43
-	 *
44
-	 * @since  3.15.0
45
-	 * @access private
46
-	 * @var \Wordlift_Uri_Service $uri_service The {@link Wordlift_Uri_Service} instance.
47
-	 */
48
-	private $uri_service;
49
-
50
-	/**
51
-	 * Create an instance of Wordlift_Rebuild_Service.
52
-	 *
53
-	 * @param \Wordlift_Sparql_Service $sparql_service A {@link Wordlift_Sparql_Service} instance used to query the remote dataset.
54
-	 * @param \Wordlift_Uri_Service $uri_service
55
-	 *
56
-	 * @since 3.6.0
57
-	 *
58
-	 */
59
-	public function __construct( $sparql_service, $uri_service ) {
60
-
61
-		$this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Rebuild_Service' );
62
-
63
-		$this->sparql_service = $sparql_service;
64
-		$this->uri_service    = $uri_service;
65
-	}
66
-
67
-	/**
68
-	 * Rebuild the Linked Data remote dataset by clearing it out and repopulating
69
-	 * it with local data.
70
-	 *
71
-	 * @since 3.6.0
72
-	 */
73
-	public function rebuild() {
74
-
75
-		ob_clean();
76
-
77
-		// Give ourselves some time to process the data.
78
-		set_time_limit( 21600 ); // 6 hours
79
-
80
-		// Send textual output.
81
-		header( 'Content-type: text/plain; charset=utf-8' );
82
-
83
-		// We start at 0 by default and get to max.
84
-		$offset = (int) $_GET['offset'] ?: 0;
85
-		$limit  = (int) $_GET['limit'] ?: 1;
86
-		$max    = $offset + $limit;
87
-
88
-		// Whether we should run queries asynchronously, this is handled in `wordlift_constants.php`.
89
-		$asynchronous = isset( $_GET['wl-async'] ) && 'true' === $_GET['wl-async'];
90
-
91
-		// If we're starting at offset 0, then delete existing URIs and data from
92
-		// the remote dataset.
93
-		if ( 0 === $offset ) {
94
-
95
-			// Clear out all generated URIs, since the dataset URI might have changed
96
-			// in the process.
97
-			$this->uri_service->delete_all();
98
-
99
-			// Delete all the triples in the remote dataset.
100
-			$this->sparql_service->execute( 'DELETE { ?s ?p ?o } WHERE { ?s ?p ?o };' );
101
-
102
-		}
103
-
104
-		// Go through the list of published entities and posts and call the (legacy)
105
-		// `wl_linked_data_save_post` function for each one. We're using the `process`
106
-		// function which is provided by the parent `Wordlift_Listable` abstract class
107
-		// and will cycle through all the posts w/ a very small memory footprint
108
-		// in order to avoid memory errors.
109
-
110
-		$count = 0;
111
-		$log   = $this->log;
112
-		$this->process( function ( $post ) use ( &$count, $log ) {
113
-			$count ++;
114
-			$log->trace( "Going to save post $count, ID $post->ID..." );
115
-			if ( function_exists( 'wl_linked_data_save_post' ) ) {
116
-				wl_linked_data_save_post( $post->ID );
117
-			}
118
-		}, array(
119
-			'post_status' => 'publish',
120
-		), $offset, $max );
121
-
122
-		// Redirect to the next chunk.
123
-		if ( $count == $limit ) {
124
-			$log->trace( 'Redirecting to post #' . ( $offset + 1 ) . '...' );
125
-			$this->redirect( admin_url( 'admin-ajax.php?action=wl_rebuild&offset=' . ( $offset + $limit ) . '&limit=' . $limit . '&wl-async=' . ( $asynchronous ? 'true' : 'false' ) ) );
126
-		}
127
-
128
-		// Flush the cache.
129
-		Wordlift_File_Cache_Service::flush_all();
130
-
131
-		// Rebuild also the references.
132
-		$this->redirect( admin_url( 'admin-ajax.php?action=wl_rebuild_references' ) );
133
-	}
134
-
135
-	/**
136
-	 * Redirect using a client-side meta to avoid browsers' redirect restrictions.
137
-	 *
138
-	 * @param string $url The URL to redirect to.
139
-	 *
140
-	 * @since 3.9.8
141
-	 *
142
-	 */
143
-	public function redirect( $url ) {
144
-
145
-		ob_clean();
146
-
147
-		@header( 'Content-Type: text/html; charset=' . get_option( 'blog_charset' ) );
148
-		?>
23
+    /**
24
+     * A {@link Wordlift_Log_Service} instance.
25
+     *
26
+     * @since  3.6.0
27
+     * @access private
28
+     * @var \Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
29
+     */
30
+    private $log;
31
+
32
+    /**
33
+     * A {@link Wordlift_Sparql_Service} instance.
34
+     *
35
+     * @since  3.6.0
36
+     * @access private
37
+     * @var \Wordlift_Sparql_Service $sparql_service A {@link Wordlift_Sparql_Service} instance.
38
+     */
39
+    private $sparql_service;
40
+
41
+    /**
42
+     * The {@link Wordlift_Uri_Service} instance.
43
+     *
44
+     * @since  3.15.0
45
+     * @access private
46
+     * @var \Wordlift_Uri_Service $uri_service The {@link Wordlift_Uri_Service} instance.
47
+     */
48
+    private $uri_service;
49
+
50
+    /**
51
+     * Create an instance of Wordlift_Rebuild_Service.
52
+     *
53
+     * @param \Wordlift_Sparql_Service $sparql_service A {@link Wordlift_Sparql_Service} instance used to query the remote dataset.
54
+     * @param \Wordlift_Uri_Service $uri_service
55
+     *
56
+     * @since 3.6.0
57
+     *
58
+     */
59
+    public function __construct( $sparql_service, $uri_service ) {
60
+
61
+        $this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Rebuild_Service' );
62
+
63
+        $this->sparql_service = $sparql_service;
64
+        $this->uri_service    = $uri_service;
65
+    }
66
+
67
+    /**
68
+     * Rebuild the Linked Data remote dataset by clearing it out and repopulating
69
+     * it with local data.
70
+     *
71
+     * @since 3.6.0
72
+     */
73
+    public function rebuild() {
74
+
75
+        ob_clean();
76
+
77
+        // Give ourselves some time to process the data.
78
+        set_time_limit( 21600 ); // 6 hours
79
+
80
+        // Send textual output.
81
+        header( 'Content-type: text/plain; charset=utf-8' );
82
+
83
+        // We start at 0 by default and get to max.
84
+        $offset = (int) $_GET['offset'] ?: 0;
85
+        $limit  = (int) $_GET['limit'] ?: 1;
86
+        $max    = $offset + $limit;
87
+
88
+        // Whether we should run queries asynchronously, this is handled in `wordlift_constants.php`.
89
+        $asynchronous = isset( $_GET['wl-async'] ) && 'true' === $_GET['wl-async'];
90
+
91
+        // If we're starting at offset 0, then delete existing URIs and data from
92
+        // the remote dataset.
93
+        if ( 0 === $offset ) {
94
+
95
+            // Clear out all generated URIs, since the dataset URI might have changed
96
+            // in the process.
97
+            $this->uri_service->delete_all();
98
+
99
+            // Delete all the triples in the remote dataset.
100
+            $this->sparql_service->execute( 'DELETE { ?s ?p ?o } WHERE { ?s ?p ?o };' );
101
+
102
+        }
103
+
104
+        // Go through the list of published entities and posts and call the (legacy)
105
+        // `wl_linked_data_save_post` function for each one. We're using the `process`
106
+        // function which is provided by the parent `Wordlift_Listable` abstract class
107
+        // and will cycle through all the posts w/ a very small memory footprint
108
+        // in order to avoid memory errors.
109
+
110
+        $count = 0;
111
+        $log   = $this->log;
112
+        $this->process( function ( $post ) use ( &$count, $log ) {
113
+            $count ++;
114
+            $log->trace( "Going to save post $count, ID $post->ID..." );
115
+            if ( function_exists( 'wl_linked_data_save_post' ) ) {
116
+                wl_linked_data_save_post( $post->ID );
117
+            }
118
+        }, array(
119
+            'post_status' => 'publish',
120
+        ), $offset, $max );
121
+
122
+        // Redirect to the next chunk.
123
+        if ( $count == $limit ) {
124
+            $log->trace( 'Redirecting to post #' . ( $offset + 1 ) . '...' );
125
+            $this->redirect( admin_url( 'admin-ajax.php?action=wl_rebuild&offset=' . ( $offset + $limit ) . '&limit=' . $limit . '&wl-async=' . ( $asynchronous ? 'true' : 'false' ) ) );
126
+        }
127
+
128
+        // Flush the cache.
129
+        Wordlift_File_Cache_Service::flush_all();
130
+
131
+        // Rebuild also the references.
132
+        $this->redirect( admin_url( 'admin-ajax.php?action=wl_rebuild_references' ) );
133
+    }
134
+
135
+    /**
136
+     * Redirect using a client-side meta to avoid browsers' redirect restrictions.
137
+     *
138
+     * @param string $url The URL to redirect to.
139
+     *
140
+     * @since 3.9.8
141
+     *
142
+     */
143
+    public function redirect( $url ) {
144
+
145
+        ob_clean();
146
+
147
+        @header( 'Content-Type: text/html; charset=' . get_option( 'blog_charset' ) );
148
+        ?>
149 149
         <html>
150 150
         <head>
151 151
             <meta http-equiv="refresh"
@@ -157,37 +157,37 @@  discard block
 block discarded – undo
157 157
         </html>
158 158
 		<?php
159 159
 
160
-		exit;
161
-
162
-	}
163
-
164
-	/**
165
-	 * List the items starting at the specified offset and up to the specified limit.
166
-	 *
167
-	 * @param int $offset The start offset.
168
-	 * @param int $limit The maximum number of items to return.
169
-	 * @param array $args Additional arguments.
170
-	 *
171
-	 * @return array A array of items (or an empty array if no items are found).
172
-	 * @since 3.19.5 remove Polylang hooks.
173
-	 * @since 3.6.0
174
-	 *
175
-	 */
176
-	function find( $offset = 0, $limit = 10, $args = array() ) {
177
-
178
-		$actual_args = wp_parse_args( $args, Wordlift_Entity_Service::add_criterias( array(
179
-			'offset'        => $offset,
180
-			'numberposts'   => $limit,
181
-			'fields'        => 'all',
182
-			'orderby'       => 'ID',
183
-			'order'         => 'ASC',
184
-			'post_status'   => 'any',
185
-			'cache_results' => false,
186
-		) ) );
187
-
188
-		$this->log->trace( 'Using ' . var_export( $actual_args, true ) );
189
-
190
-		return get_posts( $actual_args );
191
-	}
160
+        exit;
161
+
162
+    }
163
+
164
+    /**
165
+     * List the items starting at the specified offset and up to the specified limit.
166
+     *
167
+     * @param int $offset The start offset.
168
+     * @param int $limit The maximum number of items to return.
169
+     * @param array $args Additional arguments.
170
+     *
171
+     * @return array A array of items (or an empty array if no items are found).
172
+     * @since 3.19.5 remove Polylang hooks.
173
+     * @since 3.6.0
174
+     *
175
+     */
176
+    function find( $offset = 0, $limit = 10, $args = array() ) {
177
+
178
+        $actual_args = wp_parse_args( $args, Wordlift_Entity_Service::add_criterias( array(
179
+            'offset'        => $offset,
180
+            'numberposts'   => $limit,
181
+            'fields'        => 'all',
182
+            'orderby'       => 'ID',
183
+            'order'         => 'ASC',
184
+            'post_status'   => 'any',
185
+            'cache_results' => false,
186
+        ) ) );
187
+
188
+        $this->log->trace( 'Using ' . var_export( $actual_args, true ) );
189
+
190
+        return get_posts( $actual_args );
191
+    }
192 192
 
193 193
 }
Please login to merge, or discard this patch.
Spacing   +25 added lines, -25 removed lines patch added patch discarded remove patch
@@ -56,9 +56,9 @@  discard block
 block discarded – undo
56 56
 	 * @since 3.6.0
57 57
 	 *
58 58
 	 */
59
-	public function __construct( $sparql_service, $uri_service ) {
59
+	public function __construct($sparql_service, $uri_service) {
60 60
 
61
-		$this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Rebuild_Service' );
61
+		$this->log = Wordlift_Log_Service::get_logger('Wordlift_Rebuild_Service');
62 62
 
63 63
 		$this->sparql_service = $sparql_service;
64 64
 		$this->uri_service    = $uri_service;
@@ -75,10 +75,10 @@  discard block
 block discarded – undo
75 75
 		ob_clean();
76 76
 
77 77
 		// Give ourselves some time to process the data.
78
-		set_time_limit( 21600 ); // 6 hours
78
+		set_time_limit(21600); // 6 hours
79 79
 
80 80
 		// Send textual output.
81
-		header( 'Content-type: text/plain; charset=utf-8' );
81
+		header('Content-type: text/plain; charset=utf-8');
82 82
 
83 83
 		// We start at 0 by default and get to max.
84 84
 		$offset = (int) $_GET['offset'] ?: 0;
@@ -86,18 +86,18 @@  discard block
 block discarded – undo
86 86
 		$max    = $offset + $limit;
87 87
 
88 88
 		// Whether we should run queries asynchronously, this is handled in `wordlift_constants.php`.
89
-		$asynchronous = isset( $_GET['wl-async'] ) && 'true' === $_GET['wl-async'];
89
+		$asynchronous = isset($_GET['wl-async']) && 'true' === $_GET['wl-async'];
90 90
 
91 91
 		// If we're starting at offset 0, then delete existing URIs and data from
92 92
 		// the remote dataset.
93
-		if ( 0 === $offset ) {
93
+		if (0 === $offset) {
94 94
 
95 95
 			// Clear out all generated URIs, since the dataset URI might have changed
96 96
 			// in the process.
97 97
 			$this->uri_service->delete_all();
98 98
 
99 99
 			// Delete all the triples in the remote dataset.
100
-			$this->sparql_service->execute( 'DELETE { ?s ?p ?o } WHERE { ?s ?p ?o };' );
100
+			$this->sparql_service->execute('DELETE { ?s ?p ?o } WHERE { ?s ?p ?o };');
101 101
 
102 102
 		}
103 103
 
@@ -109,27 +109,27 @@  discard block
 block discarded – undo
109 109
 
110 110
 		$count = 0;
111 111
 		$log   = $this->log;
112
-		$this->process( function ( $post ) use ( &$count, $log ) {
113
-			$count ++;
114
-			$log->trace( "Going to save post $count, ID $post->ID..." );
115
-			if ( function_exists( 'wl_linked_data_save_post' ) ) {
116
-				wl_linked_data_save_post( $post->ID );
112
+		$this->process(function($post) use (&$count, $log) {
113
+			$count++;
114
+			$log->trace("Going to save post $count, ID $post->ID...");
115
+			if (function_exists('wl_linked_data_save_post')) {
116
+				wl_linked_data_save_post($post->ID);
117 117
 			}
118 118
 		}, array(
119 119
 			'post_status' => 'publish',
120
-		), $offset, $max );
120
+		), $offset, $max);
121 121
 
122 122
 		// Redirect to the next chunk.
123
-		if ( $count == $limit ) {
124
-			$log->trace( 'Redirecting to post #' . ( $offset + 1 ) . '...' );
125
-			$this->redirect( admin_url( 'admin-ajax.php?action=wl_rebuild&offset=' . ( $offset + $limit ) . '&limit=' . $limit . '&wl-async=' . ( $asynchronous ? 'true' : 'false' ) ) );
123
+		if ($count == $limit) {
124
+			$log->trace('Redirecting to post #'.($offset + 1).'...');
125
+			$this->redirect(admin_url('admin-ajax.php?action=wl_rebuild&offset='.($offset + $limit).'&limit='.$limit.'&wl-async='.($asynchronous ? 'true' : 'false')));
126 126
 		}
127 127
 
128 128
 		// Flush the cache.
129 129
 		Wordlift_File_Cache_Service::flush_all();
130 130
 
131 131
 		// Rebuild also the references.
132
-		$this->redirect( admin_url( 'admin-ajax.php?action=wl_rebuild_references' ) );
132
+		$this->redirect(admin_url('admin-ajax.php?action=wl_rebuild_references'));
133 133
 	}
134 134
 
135 135
 	/**
@@ -140,16 +140,16 @@  discard block
 block discarded – undo
140 140
 	 * @since 3.9.8
141 141
 	 *
142 142
 	 */
143
-	public function redirect( $url ) {
143
+	public function redirect($url) {
144 144
 
145 145
 		ob_clean();
146 146
 
147
-		@header( 'Content-Type: text/html; charset=' . get_option( 'blog_charset' ) );
147
+		@header('Content-Type: text/html; charset='.get_option('blog_charset'));
148 148
 		?>
149 149
         <html>
150 150
         <head>
151 151
             <meta http-equiv="refresh"
152
-                  content="0; <?php echo esc_attr( $url ); ?>">
152
+                  content="0; <?php echo esc_attr($url); ?>">
153 153
         </head>
154 154
         <body>
155 155
         Rebuilding, please wait...
@@ -173,9 +173,9 @@  discard block
 block discarded – undo
173 173
 	 * @since 3.6.0
174 174
 	 *
175 175
 	 */
176
-	function find( $offset = 0, $limit = 10, $args = array() ) {
176
+	function find($offset = 0, $limit = 10, $args = array()) {
177 177
 
178
-		$actual_args = wp_parse_args( $args, Wordlift_Entity_Service::add_criterias( array(
178
+		$actual_args = wp_parse_args($args, Wordlift_Entity_Service::add_criterias(array(
179 179
 			'offset'        => $offset,
180 180
 			'numberposts'   => $limit,
181 181
 			'fields'        => 'all',
@@ -183,11 +183,11 @@  discard block
 block discarded – undo
183 183
 			'order'         => 'ASC',
184 184
 			'post_status'   => 'any',
185 185
 			'cache_results' => false,
186
-		) ) );
186
+		)));
187 187
 
188
-		$this->log->trace( 'Using ' . var_export( $actual_args, true ) );
188
+		$this->log->trace('Using '.var_export($actual_args, true));
189 189
 
190
-		return get_posts( $actual_args );
190
+		return get_posts($actual_args);
191 191
 	}
192 192
 
193 193
 }
Please login to merge, or discard this patch.
src/includes/class-wordlift-debug-service.php 2 patches
Indentation   +45 added lines, -45 removed lines patch added patch discarded remove patch
@@ -13,62 +13,62 @@
 block discarded – undo
13 13
  */
14 14
 class Wordlift_Debug_Service {
15 15
 
16
-	/**
17
-	 * The {@link Wordlift_Entity_Service} instance.
18
-	 *
19
-	 * @since  3.7.2
20
-	 * @access private
21
-	 * @var Wordlift_Entity_Service $entity_service The {@link Wordlift_Entity_Service} instance.
22
-	 */
23
-	private $entity_service;
16
+    /**
17
+     * The {@link Wordlift_Entity_Service} instance.
18
+     *
19
+     * @since  3.7.2
20
+     * @access private
21
+     * @var Wordlift_Entity_Service $entity_service The {@link Wordlift_Entity_Service} instance.
22
+     */
23
+    private $entity_service;
24 24
 
25
-	/**
26
-	 * A {@link Wordlift_Uri_Service} instance.
27
-	 *
28
-	 * @since  3.10.0
29
-	 * @access private
30
-	 * @var \Wordlift_Uri_Service $uri_service A {@link Wordlift_Uri_Service} instance.
31
-	 */
32
-	private $uri_service;
25
+    /**
26
+     * A {@link Wordlift_Uri_Service} instance.
27
+     *
28
+     * @since  3.10.0
29
+     * @access private
30
+     * @var \Wordlift_Uri_Service $uri_service A {@link Wordlift_Uri_Service} instance.
31
+     */
32
+    private $uri_service;
33 33
 
34
-	/**
35
-	 * Wordlift_Debug_Service constructor.
36
-	 *
37
-	 * @since 3.7.2
38
-	 *
39
-	 * @param Wordlift_Entity_Service $entity_service The {@link Wordlift_Entity_Service} instance.
40
-	 * @param \Wordlift_Uri_Service   $uri_service    A {@link Wordlift_Uri_Service} instance.
41
-	 */
42
-	public function __construct( $entity_service, $uri_service ) {
34
+    /**
35
+     * Wordlift_Debug_Service constructor.
36
+     *
37
+     * @since 3.7.2
38
+     *
39
+     * @param Wordlift_Entity_Service $entity_service The {@link Wordlift_Entity_Service} instance.
40
+     * @param \Wordlift_Uri_Service   $uri_service    A {@link Wordlift_Uri_Service} instance.
41
+     */
42
+    public function __construct( $entity_service, $uri_service ) {
43 43
 
44
-		$this->entity_service = $entity_service;
45
-		$this->uri_service    = $uri_service;
44
+        $this->entity_service = $entity_service;
45
+        $this->uri_service    = $uri_service;
46 46
 
47
-		add_action( 'wp_ajax_wl_dump_uri', array( $this, 'dump_uri' ) );
47
+        add_action( 'wp_ajax_wl_dump_uri', array( $this, 'dump_uri' ) );
48 48
 
49
-	}
49
+    }
50 50
 
51
-	public function dump_uri() {
51
+    public function dump_uri() {
52 52
 
53
-		if ( ! isset( $_GET['id'] ) ) {
54
-			wp_send_json_error( 'id not set' );
55
-		}
53
+        if ( ! isset( $_GET['id'] ) ) {
54
+            wp_send_json_error( 'id not set' );
55
+        }
56 56
 
57
-		$post_id = (int) $_GET['id'];
57
+        $post_id = (int) $_GET['id'];
58 58
 
59
-		$post = get_post( $post_id );
59
+        $post = get_post( $post_id );
60 60
 
61
-		$uri       = $this->entity_service->get_uri( $post_id );
62
-		$build_uri = $this->uri_service->build_uri( $post->post_title, $post->post_type );
61
+        $uri       = $this->entity_service->get_uri( $post_id );
62
+        $build_uri = $this->uri_service->build_uri( $post->post_title, $post->post_type );
63 63
 
64
-		wp_send_json_success( array(
65
-			'uri'               => $uri,
66
-			'post_title'        => sprintf( '%s (%s)', $post->post_title, mb_detect_encoding( $post->post_title ) ),
67
-			'post_title_ascii'  => mb_convert_encoding( $post->post_title, 'ASCII' ),
68
-			'build_uri'         => $build_uri,
69
-			'build_uri_convert' => mb_convert_encoding( $build_uri, 'ASCII' ),
70
-		) );
64
+        wp_send_json_success( array(
65
+            'uri'               => $uri,
66
+            'post_title'        => sprintf( '%s (%s)', $post->post_title, mb_detect_encoding( $post->post_title ) ),
67
+            'post_title_ascii'  => mb_convert_encoding( $post->post_title, 'ASCII' ),
68
+            'build_uri'         => $build_uri,
69
+            'build_uri_convert' => mb_convert_encoding( $build_uri, 'ASCII' ),
70
+        ) );
71 71
 
72
-	}
72
+    }
73 73
 
74 74
 }
75 75
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -39,35 +39,35 @@
 block discarded – undo
39 39
 	 * @param Wordlift_Entity_Service $entity_service The {@link Wordlift_Entity_Service} instance.
40 40
 	 * @param \Wordlift_Uri_Service   $uri_service    A {@link Wordlift_Uri_Service} instance.
41 41
 	 */
42
-	public function __construct( $entity_service, $uri_service ) {
42
+	public function __construct($entity_service, $uri_service) {
43 43
 
44 44
 		$this->entity_service = $entity_service;
45 45
 		$this->uri_service    = $uri_service;
46 46
 
47
-		add_action( 'wp_ajax_wl_dump_uri', array( $this, 'dump_uri' ) );
47
+		add_action('wp_ajax_wl_dump_uri', array($this, 'dump_uri'));
48 48
 
49 49
 	}
50 50
 
51 51
 	public function dump_uri() {
52 52
 
53
-		if ( ! isset( $_GET['id'] ) ) {
54
-			wp_send_json_error( 'id not set' );
53
+		if ( ! isset($_GET['id'])) {
54
+			wp_send_json_error('id not set');
55 55
 		}
56 56
 
57 57
 		$post_id = (int) $_GET['id'];
58 58
 
59
-		$post = get_post( $post_id );
59
+		$post = get_post($post_id);
60 60
 
61
-		$uri       = $this->entity_service->get_uri( $post_id );
62
-		$build_uri = $this->uri_service->build_uri( $post->post_title, $post->post_type );
61
+		$uri       = $this->entity_service->get_uri($post_id);
62
+		$build_uri = $this->uri_service->build_uri($post->post_title, $post->post_type);
63 63
 
64
-		wp_send_json_success( array(
64
+		wp_send_json_success(array(
65 65
 			'uri'               => $uri,
66
-			'post_title'        => sprintf( '%s (%s)', $post->post_title, mb_detect_encoding( $post->post_title ) ),
67
-			'post_title_ascii'  => mb_convert_encoding( $post->post_title, 'ASCII' ),
66
+			'post_title'        => sprintf('%s (%s)', $post->post_title, mb_detect_encoding($post->post_title)),
67
+			'post_title_ascii'  => mb_convert_encoding($post->post_title, 'ASCII'),
68 68
 			'build_uri'         => $build_uri,
69
-			'build_uri_convert' => mb_convert_encoding( $build_uri, 'ASCII' ),
70
-		) );
69
+			'build_uri_convert' => mb_convert_encoding($build_uri, 'ASCII'),
70
+		));
71 71
 
72 72
 	}
73 73
 
Please login to merge, or discard this patch.
src/includes/class-wordlift-timeline-service.php 2 patches
Indentation   +362 added lines, -362 removed lines patch added patch discarded remove patch
@@ -16,367 +16,367 @@
 block discarded – undo
16 16
  */
17 17
 class Wordlift_Timeline_Service {
18 18
 
19
-	/**
20
-	 * The Log service.
21
-	 *
22
-	 * @since  3.1.0
23
-	 * @access private
24
-	 * @var \Wordlift_Log_Service $log The Log service.
25
-	 */
26
-	private $log;
27
-
28
-	/**
29
-	 * The Entity service.
30
-	 *
31
-	 * @since  3.1.0
32
-	 * @access private
33
-	 * @var \Wordlift_Entity_Service $entity_service The Entity service.
34
-	 */
35
-	private $entity_service;
36
-
37
-	/**
38
-	 * The number of words to use for the excerpt, set in the `to_json` function
39
-	 * and used by a filter.
40
-	 *
41
-	 * @since  3.7.0
42
-	 * @access private
43
-	 * @var int $excerpt_length The number of words to use for the excerpt.
44
-	 */
45
-	private $excerpt_length;
46
-
47
-	/**
48
-	 * The {@link Wordlift_Entity_Type_Service} instance.
49
-	 *
50
-	 * @since  3.15.0
51
-	 * @access private
52
-	 * @var \Wordlift_Entity_Type_Service $entity_type_service The {@link Wordlift_Entity_Type_Service} instance.
53
-	 */
54
-	private $entity_type_service;
55
-
56
-	/**
57
-	 * A singleton instance of the Timeline service (useful for unit tests).
58
-	 *
59
-	 * @since  3.1.0
60
-	 * @access private
61
-	 * @var \Wordlift_Timeline_Service $instance The singleton instance.
62
-	 */
63
-	private static $instance;
64
-
65
-	/**
66
-	 * Create a Wordlift_Timeline_Service instance.
67
-	 *
68
-	 * @param \Wordlift_Entity_Service $entity_service The Entity service.
69
-	 * @param \Wordlift_Entity_Type_Service $entity_type_service The {@link Wordlift_Entity_Type_Service} instance.
70
-	 *
71
-	 * @since 3.1.0
72
-	 *
73
-	 */
74
-	public function __construct( $entity_service, $entity_type_service ) {
75
-
76
-		$this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Timeline_Service' );
77
-
78
-		$this->entity_service      = $entity_service;
79
-		$this->entity_type_service = $entity_type_service;
80
-
81
-		self::$instance = $this;
82
-
83
-	}
84
-
85
-	/**
86
-	 * Get the singleton instance of the Wordlift_Timeline_Service
87
-	 *
88
-	 * @return \Wordlift_Timeline_Service The singleton instance of the Wordlift_Timeline_Service.
89
-	 * @since 3.1.0
90
-	 *
91
-	 */
92
-	public static function get_instance() {
93
-
94
-		return self::$instance;
95
-	}
96
-
97
-	/**
98
-	 * Retrieve timeline events and output them in JSON.
99
-	 *
100
-	 * @since 3.1.0
101
-	 */
102
-	public function ajax_timeline() {
103
-
104
-		// Get the ID of the post who requested the timeline.
105
-		$post_id = ( isset( $_REQUEST['post_id'] ) ? (int) $_REQUEST['post_id'] : null );
106
-
107
-		// Get the events and transform them for the JSON response, then send them to the client.
108
-		wp_send_json( $this->to_json( $this->get_events( $post_id ) ) );
109
-
110
-	}
111
-
112
-	/**
113
-	 * Retrieve timeline events.
114
-	 *
115
-	 * @param int $post_id The post ID.
116
-	 *
117
-	 * @return array An array of event posts.
118
-	 * @since 3.1.0
119
-	 *
120
-	 * @uses  wl_core_get_related_entity_ids() to retrieve the entities referenced by the specified post.
121
-	 *
122
-	 */
123
-	public function get_events( $post_id = null ) {
124
-
125
-		// Get the entity IDs either from the entities related to the specified post or from the last 50 published
126
-		// posts if no post has been specified.
127
-		$ids = ( is_numeric( $post_id )
128
-			? wl_core_get_related_entity_ids( $post_id )
129
-			: $this->get_all_related_to_last_50_published_posts() );
130
-
131
-		// Add the post itself if it's an entity.
132
-		if ( is_numeric( $post_id ) && $this->entity_service->is_entity( $post_id ) ) {
133
-			$ids[] = $post_id;
134
-		}
135
-
136
-		// If there's no entities, return an empty array right away.
137
-		if ( 0 === sizeof( $ids ) ) {
138
-			$this->log->trace( "No events found [ post id :: $post_id ]" );
139
-
140
-			return array();
141
-		}
142
-
143
-		$this->log->trace( 'Getting events [ entity ids :: ' . join( ', ', $ids ) . ' ]' );
144
-
145
-		$args = array(
146
-			'post__in'       => $ids,
147
-			'post_type'      => Wordlift_Entity_Service::valid_entity_post_types(),
148
-			'post_status'    => 'publish',
149
-			'posts_per_page' => - 1,
150
-			'meta_query'     => array(
151
-				'relation' => 'AND',
152
-				array(
153
-					'key'     => Wordlift_Schema_Service::FIELD_DATE_START,
154
-					'value'   => null,
155
-					'compare' => '!=',
156
-				),
157
-				array(
158
-					'key'     => Wordlift_Schema_Service::FIELD_DATE_END,
159
-					'value'   => null,
160
-					'compare' => '!=',
161
-				),
162
-			),
163
-			'tax_query'      => array(
164
-				array(
165
-					'taxonomy' => Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME,
166
-					'field'    => 'slug',
167
-					'terms'    => 'event',
168
-				),
169
-			),
170
-			'orderby'        => 'meta_value',
171
-			'order'          => 'DESC',
172
-			'meta_key'       => Wordlift_Schema_Service::FIELD_DATE_START,
173
-		);
174
-
175
-		return get_posts( $args );
176
-	}
177
-
178
-	/**
179
-	 * Convert timeline events to JSON. This function sets the global post in order
180
-	 * to get an automatic excerpt. Since we're being called inside an AJAX request,
181
-	 * we're not taking care of restoring any previous post: there isn't any.
182
-	 *
183
-	 * @param array $posts An array of posts.
184
-	 *
185
-	 * @return array|string An array of timeline events or an empty string if no posts are provided.
186
-	 * @since 3.1.0
187
-	 *
188
-	 */
189
-	public function to_json( $posts ) {
190
-
191
-		// If there are no events, return empty JSON
192
-		if ( empty( $posts ) || is_null( $posts ) ) {
193
-			return '';
194
-		}
195
-
196
-		// {media|thumbnail}: if set to 'media' the image is attached to the slide, if set to 'background' the image is set as background.
197
-		$display_images_as = isset( $_REQUEST['display_images_as'] ) ? (string) $_REQUEST['display_images_as'] : 'media';
198
-
199
-		// The number of words for the excerpt (by default 55, as WordPress).
200
-		$this->excerpt_length = $excerpt_length = isset( $_REQUEST['excerpt_length'] ) && is_numeric( $_REQUEST['excerpt_length'] ) ? $_REQUEST['excerpt_length'] : 55;
201
-		add_filter( 'excerpt_length', array( $this, 'excerpt_length' ) );
202
-
203
-		// Add a filter to remove the [...] after excerpts, since we're adding
204
-		// a link to the post itself.
205
-		add_filter( 'excerpt_more', array( $this, 'excerpt_more' ) );
206
-
207
-		// Prepare for the starting slide data. The starting slide will be the one where *now* is between *start/end* dates.
208
-		$start_at_slide = 0;
209
-		$event_index    = - 1;
210
-		$now            = time();
211
-
212
-		// Prepare the timeline variable.
213
-		$timeline = array();
214
-
215
-		// Populate the arrays.
216
-		$timeline['events'] = array_map( function ( $item ) use ( &$timeline, &$event_index, &$start_at_slide, &$now, $display_images_as, $excerpt_length ) {
217
-
218
-			// Get the start and end dates.
219
-			$start_date = strtotime( get_post_meta( $item->ID, Wordlift_Schema_Service::FIELD_DATE_START, true ) );
220
-			$end_date   = strtotime( get_post_meta( $item->ID, Wordlift_Schema_Service::FIELD_DATE_END, true ) );
221
-
222
-			// Set the starting slide.
223
-			$event_index ++;
224
-			if ( 0 === $start_at_slide && $now >= $start_date && $now <= $end_date ) {
225
-				$start_at_slide = $event_index;
226
-			}
227
-
228
-			// Load thumbnail
229
-			$thumbnail_id = get_post_thumbnail_id( $item->ID );
230
-			if ( '' !== $thumbnail_id && 0 !== $thumbnail_id
231
-			     && false !== ( $attachment = wp_get_attachment_image_src( $thumbnail_id ) )
232
-			) {
233
-
234
-				// Set the thumbnail URL.
235
-				if ( 'background' === $display_images_as ) {
236
-					$date['background'] = array( 'url' => $attachment[0] );
237
-					$date['media']      = array( 'thumbnail' => $attachment[0] );
238
-				} else {
239
-					$date['media'] = array(
240
-						'url'       => $attachment[0],
241
-						'thumbnail' => $attachment[0],
242
-					);
243
-				}
244
-			}
245
-
246
-			// Set the start/end dates by converting them to TimelineJS required format.
247
-			$date['start_date'] = Wordlift_Timeline_Service::date( $start_date );
248
-			$date['end_date']   = Wordlift_Timeline_Service::date( $end_date );
249
-
250
-			setup_postdata( $GLOBALS['post'] = $item );
251
-
252
-			$more_link_text = sprintf(
253
-				'<span aria-label="%1$s">%2$s</span>',
254
-				sprintf(
255
-				/* translators: %s: Name of current post */
256
-					__( 'Continue reading %s' ),
257
-					the_title_attribute( array( 'echo' => false ) )
258
-				),
259
-				__( '(more&hellip;)' )
260
-			);
261
-
262
-			// Set the event text only with the headline (see https://github.com/insideout10/wordlift-plugin/issues/352).
263
-			$date['text'] = array(
264
-				'headline' => '<a href="' . get_permalink( $item->ID ) . '">' . $item->post_title . '</a>',
265
-			);
266
-
267
-			// If we have an excerpt, set it.
268
-			if ( 0 < $excerpt_length ) {
269
-				$date['text']['text'] = sprintf( '%s <a href="%s">%s</a>', get_the_excerpt(), get_permalink(), $more_link_text );
270
-			}
271
-
272
-			return $date;
273
-
274
-		}, $posts );
275
-
276
-		// Finally remove the excerpt filter.
277
-		remove_filter( 'excerpt_length', array( $this, 'excerpt_length' ) );
278
-
279
-		// The JSON format is defined here: https://timeline.knightlab.com/docs/json-format.html
280
-		return array(
281
-			'timeline'       => $timeline,
282
-			'start_at_slide' => $start_at_slide,
283
-		);
284
-	}
285
-
286
-	/**
287
-	 * This function filters {@link excerpt_more} by removing it, since we're
288
-	 * adding the 'read more' link. This filter is set by {@see to_json}.
289
-	 *
290
-	 * @param string $excerpt_more The excerpt more preset.
291
-	 *
292
-	 * @return string An empty string.
293
-	 * @since 3.7.0
294
-	 *
295
-	 */
296
-	public function excerpt_more( $excerpt_more ) {
297
-
298
-		return '';
299
-	}
300
-
301
-	/**
302
-	 * A filter for the excerpt length, set by the `to_json` function, to tailor
303
-	 * how many words to return according to the client setting.
304
-	 *
305
-	 * @param int $length The preset number of words.
306
-	 *
307
-	 * @return int The number of words for the preset.
308
-	 * @since 3.7.0
309
-	 *
310
-	 */
311
-	public function excerpt_length( $length ) {
312
-
313
-		return $this->excerpt_length;
314
-	}
315
-
316
-
317
-	/**
318
-	 * Convert the date to a date array.
319
-	 *
320
-	 * @param $value int A date value.
321
-	 *
322
-	 * @return array An array containing year, month and day values.
323
-	 * @since 3.7.0
324
-	 *
325
-	 */
326
-	public static function date( $value ) {
327
-
328
-		return array(
329
-			'year'  => (int) date( 'Y', $value ),
330
-			'month' => (int) date( 'm', $value ),
331
-			'day'   => (int) date( 'd', $value ),
332
-
333
-		);
334
-	}
335
-
336
-	/**
337
-	 * Get the entities related to the last 50 posts published on this blog (we're keeping a long function name due to
338
-	 * its specific function).
339
-	 *
340
-	 * @return array An array of post IDs.
341
-	 * @since 3.1.0
342
-	 *
343
-	 */
344
-	public function get_all_related_to_last_50_published_posts() {
345
-
346
-		// Global timeline. Get entities from the latest posts.
347
-		$latest_posts_ids = get_posts( array(
348
-			'numberposts' => 50,
349
-			'fields'      => 'ids', //only get post IDs
350
-			'post_type'   => Wordlift_Entity_Service::valid_entity_post_types(),
351
-			'tax_query'   => array(
352
-				'relation' => 'OR',
353
-				array(
354
-					'taxonomy' => Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME,
355
-					'operator' => 'NOT EXISTS',
356
-				),
357
-				array(
358
-					'taxonomy' => Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME,
359
-					'field'    => 'slug',
360
-					'terms'    => 'article',
361
-				),
362
-			),
363
-			'post_status' => 'publish',
364
-		) );
365
-
366
-		if ( empty( $latest_posts_ids ) ) {
367
-			// There are no posts.
368
-			return array();
369
-		}
370
-
371
-		// Collect entities related to latest posts
372
-		$entity_ids = array();
373
-		foreach ( $latest_posts_ids as $id ) {
374
-			$entity_ids = array_merge( $entity_ids, wl_core_get_related_entity_ids( $id, array(
375
-				'status' => 'publish',
376
-			) ) );
377
-		}
378
-
379
-		return $entity_ids;
380
-	}
19
+    /**
20
+     * The Log service.
21
+     *
22
+     * @since  3.1.0
23
+     * @access private
24
+     * @var \Wordlift_Log_Service $log The Log service.
25
+     */
26
+    private $log;
27
+
28
+    /**
29
+     * The Entity service.
30
+     *
31
+     * @since  3.1.0
32
+     * @access private
33
+     * @var \Wordlift_Entity_Service $entity_service The Entity service.
34
+     */
35
+    private $entity_service;
36
+
37
+    /**
38
+     * The number of words to use for the excerpt, set in the `to_json` function
39
+     * and used by a filter.
40
+     *
41
+     * @since  3.7.0
42
+     * @access private
43
+     * @var int $excerpt_length The number of words to use for the excerpt.
44
+     */
45
+    private $excerpt_length;
46
+
47
+    /**
48
+     * The {@link Wordlift_Entity_Type_Service} instance.
49
+     *
50
+     * @since  3.15.0
51
+     * @access private
52
+     * @var \Wordlift_Entity_Type_Service $entity_type_service The {@link Wordlift_Entity_Type_Service} instance.
53
+     */
54
+    private $entity_type_service;
55
+
56
+    /**
57
+     * A singleton instance of the Timeline service (useful for unit tests).
58
+     *
59
+     * @since  3.1.0
60
+     * @access private
61
+     * @var \Wordlift_Timeline_Service $instance The singleton instance.
62
+     */
63
+    private static $instance;
64
+
65
+    /**
66
+     * Create a Wordlift_Timeline_Service instance.
67
+     *
68
+     * @param \Wordlift_Entity_Service $entity_service The Entity service.
69
+     * @param \Wordlift_Entity_Type_Service $entity_type_service The {@link Wordlift_Entity_Type_Service} instance.
70
+     *
71
+     * @since 3.1.0
72
+     *
73
+     */
74
+    public function __construct( $entity_service, $entity_type_service ) {
75
+
76
+        $this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Timeline_Service' );
77
+
78
+        $this->entity_service      = $entity_service;
79
+        $this->entity_type_service = $entity_type_service;
80
+
81
+        self::$instance = $this;
82
+
83
+    }
84
+
85
+    /**
86
+     * Get the singleton instance of the Wordlift_Timeline_Service
87
+     *
88
+     * @return \Wordlift_Timeline_Service The singleton instance of the Wordlift_Timeline_Service.
89
+     * @since 3.1.0
90
+     *
91
+     */
92
+    public static function get_instance() {
93
+
94
+        return self::$instance;
95
+    }
96
+
97
+    /**
98
+     * Retrieve timeline events and output them in JSON.
99
+     *
100
+     * @since 3.1.0
101
+     */
102
+    public function ajax_timeline() {
103
+
104
+        // Get the ID of the post who requested the timeline.
105
+        $post_id = ( isset( $_REQUEST['post_id'] ) ? (int) $_REQUEST['post_id'] : null );
106
+
107
+        // Get the events and transform them for the JSON response, then send them to the client.
108
+        wp_send_json( $this->to_json( $this->get_events( $post_id ) ) );
109
+
110
+    }
111
+
112
+    /**
113
+     * Retrieve timeline events.
114
+     *
115
+     * @param int $post_id The post ID.
116
+     *
117
+     * @return array An array of event posts.
118
+     * @since 3.1.0
119
+     *
120
+     * @uses  wl_core_get_related_entity_ids() to retrieve the entities referenced by the specified post.
121
+     *
122
+     */
123
+    public function get_events( $post_id = null ) {
124
+
125
+        // Get the entity IDs either from the entities related to the specified post or from the last 50 published
126
+        // posts if no post has been specified.
127
+        $ids = ( is_numeric( $post_id )
128
+            ? wl_core_get_related_entity_ids( $post_id )
129
+            : $this->get_all_related_to_last_50_published_posts() );
130
+
131
+        // Add the post itself if it's an entity.
132
+        if ( is_numeric( $post_id ) && $this->entity_service->is_entity( $post_id ) ) {
133
+            $ids[] = $post_id;
134
+        }
135
+
136
+        // If there's no entities, return an empty array right away.
137
+        if ( 0 === sizeof( $ids ) ) {
138
+            $this->log->trace( "No events found [ post id :: $post_id ]" );
139
+
140
+            return array();
141
+        }
142
+
143
+        $this->log->trace( 'Getting events [ entity ids :: ' . join( ', ', $ids ) . ' ]' );
144
+
145
+        $args = array(
146
+            'post__in'       => $ids,
147
+            'post_type'      => Wordlift_Entity_Service::valid_entity_post_types(),
148
+            'post_status'    => 'publish',
149
+            'posts_per_page' => - 1,
150
+            'meta_query'     => array(
151
+                'relation' => 'AND',
152
+                array(
153
+                    'key'     => Wordlift_Schema_Service::FIELD_DATE_START,
154
+                    'value'   => null,
155
+                    'compare' => '!=',
156
+                ),
157
+                array(
158
+                    'key'     => Wordlift_Schema_Service::FIELD_DATE_END,
159
+                    'value'   => null,
160
+                    'compare' => '!=',
161
+                ),
162
+            ),
163
+            'tax_query'      => array(
164
+                array(
165
+                    'taxonomy' => Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME,
166
+                    'field'    => 'slug',
167
+                    'terms'    => 'event',
168
+                ),
169
+            ),
170
+            'orderby'        => 'meta_value',
171
+            'order'          => 'DESC',
172
+            'meta_key'       => Wordlift_Schema_Service::FIELD_DATE_START,
173
+        );
174
+
175
+        return get_posts( $args );
176
+    }
177
+
178
+    /**
179
+     * Convert timeline events to JSON. This function sets the global post in order
180
+     * to get an automatic excerpt. Since we're being called inside an AJAX request,
181
+     * we're not taking care of restoring any previous post: there isn't any.
182
+     *
183
+     * @param array $posts An array of posts.
184
+     *
185
+     * @return array|string An array of timeline events or an empty string if no posts are provided.
186
+     * @since 3.1.0
187
+     *
188
+     */
189
+    public function to_json( $posts ) {
190
+
191
+        // If there are no events, return empty JSON
192
+        if ( empty( $posts ) || is_null( $posts ) ) {
193
+            return '';
194
+        }
195
+
196
+        // {media|thumbnail}: if set to 'media' the image is attached to the slide, if set to 'background' the image is set as background.
197
+        $display_images_as = isset( $_REQUEST['display_images_as'] ) ? (string) $_REQUEST['display_images_as'] : 'media';
198
+
199
+        // The number of words for the excerpt (by default 55, as WordPress).
200
+        $this->excerpt_length = $excerpt_length = isset( $_REQUEST['excerpt_length'] ) && is_numeric( $_REQUEST['excerpt_length'] ) ? $_REQUEST['excerpt_length'] : 55;
201
+        add_filter( 'excerpt_length', array( $this, 'excerpt_length' ) );
202
+
203
+        // Add a filter to remove the [...] after excerpts, since we're adding
204
+        // a link to the post itself.
205
+        add_filter( 'excerpt_more', array( $this, 'excerpt_more' ) );
206
+
207
+        // Prepare for the starting slide data. The starting slide will be the one where *now* is between *start/end* dates.
208
+        $start_at_slide = 0;
209
+        $event_index    = - 1;
210
+        $now            = time();
211
+
212
+        // Prepare the timeline variable.
213
+        $timeline = array();
214
+
215
+        // Populate the arrays.
216
+        $timeline['events'] = array_map( function ( $item ) use ( &$timeline, &$event_index, &$start_at_slide, &$now, $display_images_as, $excerpt_length ) {
217
+
218
+            // Get the start and end dates.
219
+            $start_date = strtotime( get_post_meta( $item->ID, Wordlift_Schema_Service::FIELD_DATE_START, true ) );
220
+            $end_date   = strtotime( get_post_meta( $item->ID, Wordlift_Schema_Service::FIELD_DATE_END, true ) );
221
+
222
+            // Set the starting slide.
223
+            $event_index ++;
224
+            if ( 0 === $start_at_slide && $now >= $start_date && $now <= $end_date ) {
225
+                $start_at_slide = $event_index;
226
+            }
227
+
228
+            // Load thumbnail
229
+            $thumbnail_id = get_post_thumbnail_id( $item->ID );
230
+            if ( '' !== $thumbnail_id && 0 !== $thumbnail_id
231
+                 && false !== ( $attachment = wp_get_attachment_image_src( $thumbnail_id ) )
232
+            ) {
233
+
234
+                // Set the thumbnail URL.
235
+                if ( 'background' === $display_images_as ) {
236
+                    $date['background'] = array( 'url' => $attachment[0] );
237
+                    $date['media']      = array( 'thumbnail' => $attachment[0] );
238
+                } else {
239
+                    $date['media'] = array(
240
+                        'url'       => $attachment[0],
241
+                        'thumbnail' => $attachment[0],
242
+                    );
243
+                }
244
+            }
245
+
246
+            // Set the start/end dates by converting them to TimelineJS required format.
247
+            $date['start_date'] = Wordlift_Timeline_Service::date( $start_date );
248
+            $date['end_date']   = Wordlift_Timeline_Service::date( $end_date );
249
+
250
+            setup_postdata( $GLOBALS['post'] = $item );
251
+
252
+            $more_link_text = sprintf(
253
+                '<span aria-label="%1$s">%2$s</span>',
254
+                sprintf(
255
+                /* translators: %s: Name of current post */
256
+                    __( 'Continue reading %s' ),
257
+                    the_title_attribute( array( 'echo' => false ) )
258
+                ),
259
+                __( '(more&hellip;)' )
260
+            );
261
+
262
+            // Set the event text only with the headline (see https://github.com/insideout10/wordlift-plugin/issues/352).
263
+            $date['text'] = array(
264
+                'headline' => '<a href="' . get_permalink( $item->ID ) . '">' . $item->post_title . '</a>',
265
+            );
266
+
267
+            // If we have an excerpt, set it.
268
+            if ( 0 < $excerpt_length ) {
269
+                $date['text']['text'] = sprintf( '%s <a href="%s">%s</a>', get_the_excerpt(), get_permalink(), $more_link_text );
270
+            }
271
+
272
+            return $date;
273
+
274
+        }, $posts );
275
+
276
+        // Finally remove the excerpt filter.
277
+        remove_filter( 'excerpt_length', array( $this, 'excerpt_length' ) );
278
+
279
+        // The JSON format is defined here: https://timeline.knightlab.com/docs/json-format.html
280
+        return array(
281
+            'timeline'       => $timeline,
282
+            'start_at_slide' => $start_at_slide,
283
+        );
284
+    }
285
+
286
+    /**
287
+     * This function filters {@link excerpt_more} by removing it, since we're
288
+     * adding the 'read more' link. This filter is set by {@see to_json}.
289
+     *
290
+     * @param string $excerpt_more The excerpt more preset.
291
+     *
292
+     * @return string An empty string.
293
+     * @since 3.7.0
294
+     *
295
+     */
296
+    public function excerpt_more( $excerpt_more ) {
297
+
298
+        return '';
299
+    }
300
+
301
+    /**
302
+     * A filter for the excerpt length, set by the `to_json` function, to tailor
303
+     * how many words to return according to the client setting.
304
+     *
305
+     * @param int $length The preset number of words.
306
+     *
307
+     * @return int The number of words for the preset.
308
+     * @since 3.7.0
309
+     *
310
+     */
311
+    public function excerpt_length( $length ) {
312
+
313
+        return $this->excerpt_length;
314
+    }
315
+
316
+
317
+    /**
318
+     * Convert the date to a date array.
319
+     *
320
+     * @param $value int A date value.
321
+     *
322
+     * @return array An array containing year, month and day values.
323
+     * @since 3.7.0
324
+     *
325
+     */
326
+    public static function date( $value ) {
327
+
328
+        return array(
329
+            'year'  => (int) date( 'Y', $value ),
330
+            'month' => (int) date( 'm', $value ),
331
+            'day'   => (int) date( 'd', $value ),
332
+
333
+        );
334
+    }
335
+
336
+    /**
337
+     * Get the entities related to the last 50 posts published on this blog (we're keeping a long function name due to
338
+     * its specific function).
339
+     *
340
+     * @return array An array of post IDs.
341
+     * @since 3.1.0
342
+     *
343
+     */
344
+    public function get_all_related_to_last_50_published_posts() {
345
+
346
+        // Global timeline. Get entities from the latest posts.
347
+        $latest_posts_ids = get_posts( array(
348
+            'numberposts' => 50,
349
+            'fields'      => 'ids', //only get post IDs
350
+            'post_type'   => Wordlift_Entity_Service::valid_entity_post_types(),
351
+            'tax_query'   => array(
352
+                'relation' => 'OR',
353
+                array(
354
+                    'taxonomy' => Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME,
355
+                    'operator' => 'NOT EXISTS',
356
+                ),
357
+                array(
358
+                    'taxonomy' => Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME,
359
+                    'field'    => 'slug',
360
+                    'terms'    => 'article',
361
+                ),
362
+            ),
363
+            'post_status' => 'publish',
364
+        ) );
365
+
366
+        if ( empty( $latest_posts_ids ) ) {
367
+            // There are no posts.
368
+            return array();
369
+        }
370
+
371
+        // Collect entities related to latest posts
372
+        $entity_ids = array();
373
+        foreach ( $latest_posts_ids as $id ) {
374
+            $entity_ids = array_merge( $entity_ids, wl_core_get_related_entity_ids( $id, array(
375
+                'status' => 'publish',
376
+            ) ) );
377
+        }
378
+
379
+        return $entity_ids;
380
+    }
381 381
 
382 382
 }
Please login to merge, or discard this patch.
Spacing   +54 added lines, -54 removed lines patch added patch discarded remove patch
@@ -71,9 +71,9 @@  discard block
 block discarded – undo
71 71
 	 * @since 3.1.0
72 72
 	 *
73 73
 	 */
74
-	public function __construct( $entity_service, $entity_type_service ) {
74
+	public function __construct($entity_service, $entity_type_service) {
75 75
 
76
-		$this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Timeline_Service' );
76
+		$this->log = Wordlift_Log_Service::get_logger('Wordlift_Timeline_Service');
77 77
 
78 78
 		$this->entity_service      = $entity_service;
79 79
 		$this->entity_type_service = $entity_type_service;
@@ -102,10 +102,10 @@  discard block
 block discarded – undo
102 102
 	public function ajax_timeline() {
103 103
 
104 104
 		// Get the ID of the post who requested the timeline.
105
-		$post_id = ( isset( $_REQUEST['post_id'] ) ? (int) $_REQUEST['post_id'] : null );
105
+		$post_id = (isset($_REQUEST['post_id']) ? (int) $_REQUEST['post_id'] : null);
106 106
 
107 107
 		// Get the events and transform them for the JSON response, then send them to the client.
108
-		wp_send_json( $this->to_json( $this->get_events( $post_id ) ) );
108
+		wp_send_json($this->to_json($this->get_events($post_id)));
109 109
 
110 110
 	}
111 111
 
@@ -120,33 +120,33 @@  discard block
 block discarded – undo
120 120
 	 * @uses  wl_core_get_related_entity_ids() to retrieve the entities referenced by the specified post.
121 121
 	 *
122 122
 	 */
123
-	public function get_events( $post_id = null ) {
123
+	public function get_events($post_id = null) {
124 124
 
125 125
 		// Get the entity IDs either from the entities related to the specified post or from the last 50 published
126 126
 		// posts if no post has been specified.
127
-		$ids = ( is_numeric( $post_id )
128
-			? wl_core_get_related_entity_ids( $post_id )
129
-			: $this->get_all_related_to_last_50_published_posts() );
127
+		$ids = (is_numeric($post_id)
128
+			? wl_core_get_related_entity_ids($post_id)
129
+			: $this->get_all_related_to_last_50_published_posts());
130 130
 
131 131
 		// Add the post itself if it's an entity.
132
-		if ( is_numeric( $post_id ) && $this->entity_service->is_entity( $post_id ) ) {
132
+		if (is_numeric($post_id) && $this->entity_service->is_entity($post_id)) {
133 133
 			$ids[] = $post_id;
134 134
 		}
135 135
 
136 136
 		// If there's no entities, return an empty array right away.
137
-		if ( 0 === sizeof( $ids ) ) {
138
-			$this->log->trace( "No events found [ post id :: $post_id ]" );
137
+		if (0 === sizeof($ids)) {
138
+			$this->log->trace("No events found [ post id :: $post_id ]");
139 139
 
140 140
 			return array();
141 141
 		}
142 142
 
143
-		$this->log->trace( 'Getting events [ entity ids :: ' . join( ', ', $ids ) . ' ]' );
143
+		$this->log->trace('Getting events [ entity ids :: '.join(', ', $ids).' ]');
144 144
 
145 145
 		$args = array(
146 146
 			'post__in'       => $ids,
147 147
 			'post_type'      => Wordlift_Entity_Service::valid_entity_post_types(),
148 148
 			'post_status'    => 'publish',
149
-			'posts_per_page' => - 1,
149
+			'posts_per_page' => -1,
150 150
 			'meta_query'     => array(
151 151
 				'relation' => 'AND',
152 152
 				array(
@@ -172,7 +172,7 @@  discard block
 block discarded – undo
172 172
 			'meta_key'       => Wordlift_Schema_Service::FIELD_DATE_START,
173 173
 		);
174 174
 
175
-		return get_posts( $args );
175
+		return get_posts($args);
176 176
 	}
177 177
 
178 178
 	/**
@@ -186,23 +186,23 @@  discard block
 block discarded – undo
186 186
 	 * @since 3.1.0
187 187
 	 *
188 188
 	 */
189
-	public function to_json( $posts ) {
189
+	public function to_json($posts) {
190 190
 
191 191
 		// If there are no events, return empty JSON
192
-		if ( empty( $posts ) || is_null( $posts ) ) {
192
+		if (empty($posts) || is_null($posts)) {
193 193
 			return '';
194 194
 		}
195 195
 
196 196
 		// {media|thumbnail}: if set to 'media' the image is attached to the slide, if set to 'background' the image is set as background.
197
-		$display_images_as = isset( $_REQUEST['display_images_as'] ) ? (string) $_REQUEST['display_images_as'] : 'media';
197
+		$display_images_as = isset($_REQUEST['display_images_as']) ? (string) $_REQUEST['display_images_as'] : 'media';
198 198
 
199 199
 		// The number of words for the excerpt (by default 55, as WordPress).
200
-		$this->excerpt_length = $excerpt_length = isset( $_REQUEST['excerpt_length'] ) && is_numeric( $_REQUEST['excerpt_length'] ) ? $_REQUEST['excerpt_length'] : 55;
201
-		add_filter( 'excerpt_length', array( $this, 'excerpt_length' ) );
200
+		$this->excerpt_length = $excerpt_length = isset($_REQUEST['excerpt_length']) && is_numeric($_REQUEST['excerpt_length']) ? $_REQUEST['excerpt_length'] : 55;
201
+		add_filter('excerpt_length', array($this, 'excerpt_length'));
202 202
 
203 203
 		// Add a filter to remove the [...] after excerpts, since we're adding
204 204
 		// a link to the post itself.
205
-		add_filter( 'excerpt_more', array( $this, 'excerpt_more' ) );
205
+		add_filter('excerpt_more', array($this, 'excerpt_more'));
206 206
 
207 207
 		// Prepare for the starting slide data. The starting slide will be the one where *now* is between *start/end* dates.
208 208
 		$start_at_slide = 0;
@@ -213,28 +213,28 @@  discard block
 block discarded – undo
213 213
 		$timeline = array();
214 214
 
215 215
 		// Populate the arrays.
216
-		$timeline['events'] = array_map( function ( $item ) use ( &$timeline, &$event_index, &$start_at_slide, &$now, $display_images_as, $excerpt_length ) {
216
+		$timeline['events'] = array_map(function($item) use (&$timeline, &$event_index, &$start_at_slide, &$now, $display_images_as, $excerpt_length) {
217 217
 
218 218
 			// Get the start and end dates.
219
-			$start_date = strtotime( get_post_meta( $item->ID, Wordlift_Schema_Service::FIELD_DATE_START, true ) );
220
-			$end_date   = strtotime( get_post_meta( $item->ID, Wordlift_Schema_Service::FIELD_DATE_END, true ) );
219
+			$start_date = strtotime(get_post_meta($item->ID, Wordlift_Schema_Service::FIELD_DATE_START, true));
220
+			$end_date   = strtotime(get_post_meta($item->ID, Wordlift_Schema_Service::FIELD_DATE_END, true));
221 221
 
222 222
 			// Set the starting slide.
223
-			$event_index ++;
224
-			if ( 0 === $start_at_slide && $now >= $start_date && $now <= $end_date ) {
223
+			$event_index++;
224
+			if (0 === $start_at_slide && $now >= $start_date && $now <= $end_date) {
225 225
 				$start_at_slide = $event_index;
226 226
 			}
227 227
 
228 228
 			// Load thumbnail
229
-			$thumbnail_id = get_post_thumbnail_id( $item->ID );
230
-			if ( '' !== $thumbnail_id && 0 !== $thumbnail_id
231
-			     && false !== ( $attachment = wp_get_attachment_image_src( $thumbnail_id ) )
229
+			$thumbnail_id = get_post_thumbnail_id($item->ID);
230
+			if ('' !== $thumbnail_id && 0 !== $thumbnail_id
231
+			     && false !== ($attachment = wp_get_attachment_image_src($thumbnail_id))
232 232
 			) {
233 233
 
234 234
 				// Set the thumbnail URL.
235
-				if ( 'background' === $display_images_as ) {
236
-					$date['background'] = array( 'url' => $attachment[0] );
237
-					$date['media']      = array( 'thumbnail' => $attachment[0] );
235
+				if ('background' === $display_images_as) {
236
+					$date['background'] = array('url' => $attachment[0]);
237
+					$date['media']      = array('thumbnail' => $attachment[0]);
238 238
 				} else {
239 239
 					$date['media'] = array(
240 240
 						'url'       => $attachment[0],
@@ -244,37 +244,37 @@  discard block
 block discarded – undo
244 244
 			}
245 245
 
246 246
 			// Set the start/end dates by converting them to TimelineJS required format.
247
-			$date['start_date'] = Wordlift_Timeline_Service::date( $start_date );
248
-			$date['end_date']   = Wordlift_Timeline_Service::date( $end_date );
247
+			$date['start_date'] = Wordlift_Timeline_Service::date($start_date);
248
+			$date['end_date']   = Wordlift_Timeline_Service::date($end_date);
249 249
 
250
-			setup_postdata( $GLOBALS['post'] = $item );
250
+			setup_postdata($GLOBALS['post'] = $item);
251 251
 
252 252
 			$more_link_text = sprintf(
253 253
 				'<span aria-label="%1$s">%2$s</span>',
254 254
 				sprintf(
255 255
 				/* translators: %s: Name of current post */
256
-					__( 'Continue reading %s' ),
257
-					the_title_attribute( array( 'echo' => false ) )
256
+					__('Continue reading %s'),
257
+					the_title_attribute(array('echo' => false))
258 258
 				),
259
-				__( '(more&hellip;)' )
259
+				__('(more&hellip;)')
260 260
 			);
261 261
 
262 262
 			// Set the event text only with the headline (see https://github.com/insideout10/wordlift-plugin/issues/352).
263 263
 			$date['text'] = array(
264
-				'headline' => '<a href="' . get_permalink( $item->ID ) . '">' . $item->post_title . '</a>',
264
+				'headline' => '<a href="'.get_permalink($item->ID).'">'.$item->post_title.'</a>',
265 265
 			);
266 266
 
267 267
 			// If we have an excerpt, set it.
268
-			if ( 0 < $excerpt_length ) {
269
-				$date['text']['text'] = sprintf( '%s <a href="%s">%s</a>', get_the_excerpt(), get_permalink(), $more_link_text );
268
+			if (0 < $excerpt_length) {
269
+				$date['text']['text'] = sprintf('%s <a href="%s">%s</a>', get_the_excerpt(), get_permalink(), $more_link_text);
270 270
 			}
271 271
 
272 272
 			return $date;
273 273
 
274
-		}, $posts );
274
+		}, $posts);
275 275
 
276 276
 		// Finally remove the excerpt filter.
277
-		remove_filter( 'excerpt_length', array( $this, 'excerpt_length' ) );
277
+		remove_filter('excerpt_length', array($this, 'excerpt_length'));
278 278
 
279 279
 		// The JSON format is defined here: https://timeline.knightlab.com/docs/json-format.html
280 280
 		return array(
@@ -293,7 +293,7 @@  discard block
 block discarded – undo
293 293
 	 * @since 3.7.0
294 294
 	 *
295 295
 	 */
296
-	public function excerpt_more( $excerpt_more ) {
296
+	public function excerpt_more($excerpt_more) {
297 297
 
298 298
 		return '';
299 299
 	}
@@ -308,7 +308,7 @@  discard block
 block discarded – undo
308 308
 	 * @since 3.7.0
309 309
 	 *
310 310
 	 */
311
-	public function excerpt_length( $length ) {
311
+	public function excerpt_length($length) {
312 312
 
313 313
 		return $this->excerpt_length;
314 314
 	}
@@ -323,12 +323,12 @@  discard block
 block discarded – undo
323 323
 	 * @since 3.7.0
324 324
 	 *
325 325
 	 */
326
-	public static function date( $value ) {
326
+	public static function date($value) {
327 327
 
328 328
 		return array(
329
-			'year'  => (int) date( 'Y', $value ),
330
-			'month' => (int) date( 'm', $value ),
331
-			'day'   => (int) date( 'd', $value ),
329
+			'year'  => (int) date('Y', $value),
330
+			'month' => (int) date('m', $value),
331
+			'day'   => (int) date('d', $value),
332 332
 
333 333
 		);
334 334
 	}
@@ -344,7 +344,7 @@  discard block
 block discarded – undo
344 344
 	public function get_all_related_to_last_50_published_posts() {
345 345
 
346 346
 		// Global timeline. Get entities from the latest posts.
347
-		$latest_posts_ids = get_posts( array(
347
+		$latest_posts_ids = get_posts(array(
348 348
 			'numberposts' => 50,
349 349
 			'fields'      => 'ids', //only get post IDs
350 350
 			'post_type'   => Wordlift_Entity_Service::valid_entity_post_types(),
@@ -361,19 +361,19 @@  discard block
 block discarded – undo
361 361
 				),
362 362
 			),
363 363
 			'post_status' => 'publish',
364
-		) );
364
+		));
365 365
 
366
-		if ( empty( $latest_posts_ids ) ) {
366
+		if (empty($latest_posts_ids)) {
367 367
 			// There are no posts.
368 368
 			return array();
369 369
 		}
370 370
 
371 371
 		// Collect entities related to latest posts
372 372
 		$entity_ids = array();
373
-		foreach ( $latest_posts_ids as $id ) {
374
-			$entity_ids = array_merge( $entity_ids, wl_core_get_related_entity_ids( $id, array(
373
+		foreach ($latest_posts_ids as $id) {
374
+			$entity_ids = array_merge($entity_ids, wl_core_get_related_entity_ids($id, array(
375 375
 				'status' => 'publish',
376
-			) ) );
376
+			)));
377 377
 		}
378 378
 
379 379
 		return $entity_ids;
Please login to merge, or discard this patch.
src/includes/class-wordlift-key-validation-service.php 2 patches
Indentation   +181 added lines, -181 removed lines patch added patch discarded remove patch
@@ -20,189 +20,189 @@
 block discarded – undo
20 20
  */
21 21
 class Wordlift_Key_Validation_Service {
22 22
 
23
-	/**
24
-	 * A {@link Wordlift_Log_Service} instance.
25
-	 *
26
-	 * @since  3.14.0
27
-	 * @access private
28
-	 * @var \Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
29
-	 */
30
-	private $log;
31
-
32
-	/**
33
-	 * The {@link Wordlift_Configuration_Service} instance.
34
-	 *
35
-	 * @since  3.14.0
36
-	 * @access private
37
-	 * @var \Wordlift_Configuration_Service $configuration_service The {@link Wordlift_Configuration_Service} instance.
38
-	 */
39
-	private $configuration_service;
40
-
41
-	/**
42
-	 * @var Ttl_Cache
43
-	 */
44
-	private $ttl_cache_service;
45
-
46
-	/**
47
-	 * Create a {@link Wordlift_Key_Validation_Service} instance.
48
-	 *
49
-	 * @param \Wordlift_Configuration_Service $configuration_service The {@link Wordlift_Configuration_Service} instance.
50
-	 *
51
-	 * @since 3.14.0
52
-	 */
53
-	public function __construct( $configuration_service ) {
54
-
55
-		$this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Key_Validation_Service' );
56
-
57
-		$this->configuration_service = $configuration_service;
58
-
59
-		add_action( 'admin_init', array( $this, 'wl_load_plugin' ) );
60
-		/**
61
-		 * Filter: wl_feature__enable__notices.
62
-		 *
63
-		 * @param bool whether the notices needs to be enabled or not.
64
-		 *
65
-		 * @return bool
66
-		 * @since 3.27.6
67
-		 */
68
-		if ( apply_filters( 'wl_feature__enable__notices', true ) ) {
69
-			add_action( 'admin_notices', array( $this, 'wl_key_update_notice' ) );
70
-		}
71
-
72
-		$this->ttl_cache_service = new Ttl_Cache( 'key-validation-notification');
73
-
74
-	}
75
-
76
-	/**
77
-	 * Validate the provided key.
78
-	 *
79
-	 * @param string $key WordLift's key to validate.
80
-	 *
81
-	 * @return WP_Error|array The response or WP_Error on failure.
82
-	 * @since 3.9.0
83
-	 *
84
-	 */
85
-	public function get_account_info( $key ) {
86
-
87
-		$this->log->debug( 'Validating key...' );
88
-
89
-		return Default_Api_Service::get_instance()->get( '/accounts/info', array(
90
-			'Authorization' => "Key $key",
91
-		) )->get_response();
92
-	}
93
-
94
-	/**
95
-	 * Check if key is valid
96
-	 *
97
-	 * @param $key string
98
-	 *
99
-	 * @return bool
100
-	 */
101
-	public function is_key_valid( $key ) {
102
-
103
-		$response = $this->get_account_info( $key );
104
-
105
-		if ( is_wp_error( $response ) || 2 !== (int) $response['response']['code'] / 100 ) {
106
-			return false;
107
-		}
108
-		$res_body = json_decode( wp_remote_retrieve_body( $response ), true );
109
-
110
-		$url = $res_body['url'];
111
-
112
-		// Considering that production URL may be filtered.
113
-		$home_url = get_option( 'home' );
114
-		$site_url = apply_filters( 'wl_production_site_url', untrailingslashit( $home_url ) );
115
-		if ( is_null( $url ) || $url === $site_url ) {
116
-			return true;
117
-		}
118
-
119
-		return false;
120
-	}
121
-
122
-	/**
123
-	 * This function is hooked to the `wl_validate_key` AJAX call.
124
-	 *
125
-	 * @since 3.9.0
126
-	 */
127
-	public function validate_key() {
128
-
129
-		// Ensure we don't have garbage before us.
130
-		ob_clean();
131
-
132
-		// Check if we have a key.
133
-		if ( ! isset( $_POST['key'] ) ) {
134
-			wp_send_json_error( 'The key parameter is required.' );
135
-		}
136
-
137
-		$response = $this->get_account_info( (string) $_POST['key'] );
138
-
139
-		// If we got an error, return invalid.
140
-		if ( is_wp_error( $response ) || 2 !== (int) $response['response']['code'] / 100 ) {
141
-			wp_send_json_success( array( 'valid' => false, 'message' => '' ) );
142
-		}
143
-
144
-		$res_body = json_decode( wp_remote_retrieve_body( $response ), true );
145
-
146
-		// The URL stored in WLS. If this is the initial install the URL may be null.
147
-		$url = $res_body['url'];
148
-
149
-		// Considering that production URL may be filtered.
150
-		$home_url = get_option( 'home' );
151
-		$site_url = apply_filters( 'wl_production_site_url', untrailingslashit( $home_url ) );
152
-
153
-		// If the URL isn't set or matches, then it's valid.
154
-		if ( is_null( $url ) || $url === $site_url ) {
155
-		    // Invalidate the cache key
156
-			$this->ttl_cache_service->delete('is_key_valid' );
157
-			wp_send_json_success( array( 'valid' => true, 'message' => '' ) );
158
-		}
159
-
160
-		// If the URL doesn't match it means that this key has been configured elsewhere already.
161
-		if ( $url !== $site_url ) {
162
-			Wordlift_Configuration_Service::get_instance()->set_key( '' );
163
-			wp_send_json_success( array(
164
-				'valid'   => false,
165
-				'message' => __( 'The key is already used on another site, please contact us at [email protected] to move the key to another site.', 'wordlift' ),
166
-			) );
167
-		}
168
-
169
-		// Set a response with valid set to true or false according to the key validity with message.
170
-		wp_send_json_success( array(
171
-			'valid'   => false,
172
-			'message' => __( 'An error occurred, please contact us at [email protected]', 'wordlift' ),
173
-		) );
174
-	}
175
-
176
-	/**
177
-	 * This function is hooked `admin_init` to check _wl_blog_url.
178
-	 *
179
-	 */
180
-	public function wl_load_plugin() {
181
-
182
-		$wl_blog_url = get_option( '_wl_blog_url' );
183
-		$home_url    = get_option( 'home' );
184
-
185
-		if ( ! $wl_blog_url ) {
186
-			update_option( '_wl_blog_url', $home_url, true );
187
-		} else if ( $wl_blog_url !== $home_url ) {
188
-			update_option( '_wl_blog_url', $home_url, true );
189
-			Wordlift_Configuration_Service::get_instance()->set_key( '' );
190
-			set_transient( 'wl-key-error-msg', __( "Your web site URL has changed. To avoid data corruption, WordLift's key has been removed. Please provide a new key in WordLift Settings. If you believe this to be an error, please contact us at [email protected]", 'wordlift' ), 10 );
191
-		}
192
-
193
-	}
194
-
195
-	/**
196
-	 * This function is hooked to the `admin_notices` to show admin notification.
197
-	 *
198
-	 */
199
-	public function wl_key_update_notice() {
200
-		if ( get_transient( 'wl-key-error-msg' ) ) {
201
-			?>
23
+    /**
24
+     * A {@link Wordlift_Log_Service} instance.
25
+     *
26
+     * @since  3.14.0
27
+     * @access private
28
+     * @var \Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
29
+     */
30
+    private $log;
31
+
32
+    /**
33
+     * The {@link Wordlift_Configuration_Service} instance.
34
+     *
35
+     * @since  3.14.0
36
+     * @access private
37
+     * @var \Wordlift_Configuration_Service $configuration_service The {@link Wordlift_Configuration_Service} instance.
38
+     */
39
+    private $configuration_service;
40
+
41
+    /**
42
+     * @var Ttl_Cache
43
+     */
44
+    private $ttl_cache_service;
45
+
46
+    /**
47
+     * Create a {@link Wordlift_Key_Validation_Service} instance.
48
+     *
49
+     * @param \Wordlift_Configuration_Service $configuration_service The {@link Wordlift_Configuration_Service} instance.
50
+     *
51
+     * @since 3.14.0
52
+     */
53
+    public function __construct( $configuration_service ) {
54
+
55
+        $this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Key_Validation_Service' );
56
+
57
+        $this->configuration_service = $configuration_service;
58
+
59
+        add_action( 'admin_init', array( $this, 'wl_load_plugin' ) );
60
+        /**
61
+         * Filter: wl_feature__enable__notices.
62
+         *
63
+         * @param bool whether the notices needs to be enabled or not.
64
+         *
65
+         * @return bool
66
+         * @since 3.27.6
67
+         */
68
+        if ( apply_filters( 'wl_feature__enable__notices', true ) ) {
69
+            add_action( 'admin_notices', array( $this, 'wl_key_update_notice' ) );
70
+        }
71
+
72
+        $this->ttl_cache_service = new Ttl_Cache( 'key-validation-notification');
73
+
74
+    }
75
+
76
+    /**
77
+     * Validate the provided key.
78
+     *
79
+     * @param string $key WordLift's key to validate.
80
+     *
81
+     * @return WP_Error|array The response or WP_Error on failure.
82
+     * @since 3.9.0
83
+     *
84
+     */
85
+    public function get_account_info( $key ) {
86
+
87
+        $this->log->debug( 'Validating key...' );
88
+
89
+        return Default_Api_Service::get_instance()->get( '/accounts/info', array(
90
+            'Authorization' => "Key $key",
91
+        ) )->get_response();
92
+    }
93
+
94
+    /**
95
+     * Check if key is valid
96
+     *
97
+     * @param $key string
98
+     *
99
+     * @return bool
100
+     */
101
+    public function is_key_valid( $key ) {
102
+
103
+        $response = $this->get_account_info( $key );
104
+
105
+        if ( is_wp_error( $response ) || 2 !== (int) $response['response']['code'] / 100 ) {
106
+            return false;
107
+        }
108
+        $res_body = json_decode( wp_remote_retrieve_body( $response ), true );
109
+
110
+        $url = $res_body['url'];
111
+
112
+        // Considering that production URL may be filtered.
113
+        $home_url = get_option( 'home' );
114
+        $site_url = apply_filters( 'wl_production_site_url', untrailingslashit( $home_url ) );
115
+        if ( is_null( $url ) || $url === $site_url ) {
116
+            return true;
117
+        }
118
+
119
+        return false;
120
+    }
121
+
122
+    /**
123
+     * This function is hooked to the `wl_validate_key` AJAX call.
124
+     *
125
+     * @since 3.9.0
126
+     */
127
+    public function validate_key() {
128
+
129
+        // Ensure we don't have garbage before us.
130
+        ob_clean();
131
+
132
+        // Check if we have a key.
133
+        if ( ! isset( $_POST['key'] ) ) {
134
+            wp_send_json_error( 'The key parameter is required.' );
135
+        }
136
+
137
+        $response = $this->get_account_info( (string) $_POST['key'] );
138
+
139
+        // If we got an error, return invalid.
140
+        if ( is_wp_error( $response ) || 2 !== (int) $response['response']['code'] / 100 ) {
141
+            wp_send_json_success( array( 'valid' => false, 'message' => '' ) );
142
+        }
143
+
144
+        $res_body = json_decode( wp_remote_retrieve_body( $response ), true );
145
+
146
+        // The URL stored in WLS. If this is the initial install the URL may be null.
147
+        $url = $res_body['url'];
148
+
149
+        // Considering that production URL may be filtered.
150
+        $home_url = get_option( 'home' );
151
+        $site_url = apply_filters( 'wl_production_site_url', untrailingslashit( $home_url ) );
152
+
153
+        // If the URL isn't set or matches, then it's valid.
154
+        if ( is_null( $url ) || $url === $site_url ) {
155
+            // Invalidate the cache key
156
+            $this->ttl_cache_service->delete('is_key_valid' );
157
+            wp_send_json_success( array( 'valid' => true, 'message' => '' ) );
158
+        }
159
+
160
+        // If the URL doesn't match it means that this key has been configured elsewhere already.
161
+        if ( $url !== $site_url ) {
162
+            Wordlift_Configuration_Service::get_instance()->set_key( '' );
163
+            wp_send_json_success( array(
164
+                'valid'   => false,
165
+                'message' => __( 'The key is already used on another site, please contact us at [email protected] to move the key to another site.', 'wordlift' ),
166
+            ) );
167
+        }
168
+
169
+        // Set a response with valid set to true or false according to the key validity with message.
170
+        wp_send_json_success( array(
171
+            'valid'   => false,
172
+            'message' => __( 'An error occurred, please contact us at [email protected]', 'wordlift' ),
173
+        ) );
174
+    }
175
+
176
+    /**
177
+     * This function is hooked `admin_init` to check _wl_blog_url.
178
+     *
179
+     */
180
+    public function wl_load_plugin() {
181
+
182
+        $wl_blog_url = get_option( '_wl_blog_url' );
183
+        $home_url    = get_option( 'home' );
184
+
185
+        if ( ! $wl_blog_url ) {
186
+            update_option( '_wl_blog_url', $home_url, true );
187
+        } else if ( $wl_blog_url !== $home_url ) {
188
+            update_option( '_wl_blog_url', $home_url, true );
189
+            Wordlift_Configuration_Service::get_instance()->set_key( '' );
190
+            set_transient( 'wl-key-error-msg', __( "Your web site URL has changed. To avoid data corruption, WordLift's key has been removed. Please provide a new key in WordLift Settings. If you believe this to be an error, please contact us at [email protected]", 'wordlift' ), 10 );
191
+        }
192
+
193
+    }
194
+
195
+    /**
196
+     * This function is hooked to the `admin_notices` to show admin notification.
197
+     *
198
+     */
199
+    public function wl_key_update_notice() {
200
+        if ( get_transient( 'wl-key-error-msg' ) ) {
201
+            ?>
202 202
             <div class="updated notice is-dismissible error">
203 203
                 <p><?php _e( get_transient( 'wl-key-error-msg' ), 'wordlift' ); ?></p>
204 204
             </div>
205 205
 			<?php
206
-		}
207
-	}
206
+        }
207
+    }
208 208
 }
Please login to merge, or discard this patch.
Spacing   +46 added lines, -46 removed lines patch added patch discarded remove patch
@@ -50,13 +50,13 @@  discard block
 block discarded – undo
50 50
 	 *
51 51
 	 * @since 3.14.0
52 52
 	 */
53
-	public function __construct( $configuration_service ) {
53
+	public function __construct($configuration_service) {
54 54
 
55
-		$this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Key_Validation_Service' );
55
+		$this->log = Wordlift_Log_Service::get_logger('Wordlift_Key_Validation_Service');
56 56
 
57 57
 		$this->configuration_service = $configuration_service;
58 58
 
59
-		add_action( 'admin_init', array( $this, 'wl_load_plugin' ) );
59
+		add_action('admin_init', array($this, 'wl_load_plugin'));
60 60
 		/**
61 61
 		 * Filter: wl_feature__enable__notices.
62 62
 		 *
@@ -65,11 +65,11 @@  discard block
 block discarded – undo
65 65
 		 * @return bool
66 66
 		 * @since 3.27.6
67 67
 		 */
68
-		if ( apply_filters( 'wl_feature__enable__notices', true ) ) {
69
-			add_action( 'admin_notices', array( $this, 'wl_key_update_notice' ) );
68
+		if (apply_filters('wl_feature__enable__notices', true)) {
69
+			add_action('admin_notices', array($this, 'wl_key_update_notice'));
70 70
 		}
71 71
 
72
-		$this->ttl_cache_service = new Ttl_Cache( 'key-validation-notification');
72
+		$this->ttl_cache_service = new Ttl_Cache('key-validation-notification');
73 73
 
74 74
 	}
75 75
 
@@ -82,13 +82,13 @@  discard block
 block discarded – undo
82 82
 	 * @since 3.9.0
83 83
 	 *
84 84
 	 */
85
-	public function get_account_info( $key ) {
85
+	public function get_account_info($key) {
86 86
 
87
-		$this->log->debug( 'Validating key...' );
87
+		$this->log->debug('Validating key...');
88 88
 
89
-		return Default_Api_Service::get_instance()->get( '/accounts/info', array(
89
+		return Default_Api_Service::get_instance()->get('/accounts/info', array(
90 90
 			'Authorization' => "Key $key",
91
-		) )->get_response();
91
+		))->get_response();
92 92
 	}
93 93
 
94 94
 	/**
@@ -98,21 +98,21 @@  discard block
 block discarded – undo
98 98
 	 *
99 99
 	 * @return bool
100 100
 	 */
101
-	public function is_key_valid( $key ) {
101
+	public function is_key_valid($key) {
102 102
 
103
-		$response = $this->get_account_info( $key );
103
+		$response = $this->get_account_info($key);
104 104
 
105
-		if ( is_wp_error( $response ) || 2 !== (int) $response['response']['code'] / 100 ) {
105
+		if (is_wp_error($response) || 2 !== (int) $response['response']['code'] / 100) {
106 106
 			return false;
107 107
 		}
108
-		$res_body = json_decode( wp_remote_retrieve_body( $response ), true );
108
+		$res_body = json_decode(wp_remote_retrieve_body($response), true);
109 109
 
110 110
 		$url = $res_body['url'];
111 111
 
112 112
 		// Considering that production URL may be filtered.
113
-		$home_url = get_option( 'home' );
114
-		$site_url = apply_filters( 'wl_production_site_url', untrailingslashit( $home_url ) );
115
-		if ( is_null( $url ) || $url === $site_url ) {
113
+		$home_url = get_option('home');
114
+		$site_url = apply_filters('wl_production_site_url', untrailingslashit($home_url));
115
+		if (is_null($url) || $url === $site_url) {
116 116
 			return true;
117 117
 		}
118 118
 
@@ -130,47 +130,47 @@  discard block
 block discarded – undo
130 130
 		ob_clean();
131 131
 
132 132
 		// Check if we have a key.
133
-		if ( ! isset( $_POST['key'] ) ) {
134
-			wp_send_json_error( 'The key parameter is required.' );
133
+		if ( ! isset($_POST['key'])) {
134
+			wp_send_json_error('The key parameter is required.');
135 135
 		}
136 136
 
137
-		$response = $this->get_account_info( (string) $_POST['key'] );
137
+		$response = $this->get_account_info((string) $_POST['key']);
138 138
 
139 139
 		// If we got an error, return invalid.
140
-		if ( is_wp_error( $response ) || 2 !== (int) $response['response']['code'] / 100 ) {
141
-			wp_send_json_success( array( 'valid' => false, 'message' => '' ) );
140
+		if (is_wp_error($response) || 2 !== (int) $response['response']['code'] / 100) {
141
+			wp_send_json_success(array('valid' => false, 'message' => ''));
142 142
 		}
143 143
 
144
-		$res_body = json_decode( wp_remote_retrieve_body( $response ), true );
144
+		$res_body = json_decode(wp_remote_retrieve_body($response), true);
145 145
 
146 146
 		// The URL stored in WLS. If this is the initial install the URL may be null.
147 147
 		$url = $res_body['url'];
148 148
 
149 149
 		// Considering that production URL may be filtered.
150
-		$home_url = get_option( 'home' );
151
-		$site_url = apply_filters( 'wl_production_site_url', untrailingslashit( $home_url ) );
150
+		$home_url = get_option('home');
151
+		$site_url = apply_filters('wl_production_site_url', untrailingslashit($home_url));
152 152
 
153 153
 		// If the URL isn't set or matches, then it's valid.
154
-		if ( is_null( $url ) || $url === $site_url ) {
154
+		if (is_null($url) || $url === $site_url) {
155 155
 		    // Invalidate the cache key
156
-			$this->ttl_cache_service->delete('is_key_valid' );
157
-			wp_send_json_success( array( 'valid' => true, 'message' => '' ) );
156
+			$this->ttl_cache_service->delete('is_key_valid');
157
+			wp_send_json_success(array('valid' => true, 'message' => ''));
158 158
 		}
159 159
 
160 160
 		// If the URL doesn't match it means that this key has been configured elsewhere already.
161
-		if ( $url !== $site_url ) {
162
-			Wordlift_Configuration_Service::get_instance()->set_key( '' );
163
-			wp_send_json_success( array(
161
+		if ($url !== $site_url) {
162
+			Wordlift_Configuration_Service::get_instance()->set_key('');
163
+			wp_send_json_success(array(
164 164
 				'valid'   => false,
165
-				'message' => __( 'The key is already used on another site, please contact us at [email protected] to move the key to another site.', 'wordlift' ),
166
-			) );
165
+				'message' => __('The key is already used on another site, please contact us at [email protected] to move the key to another site.', 'wordlift'),
166
+			));
167 167
 		}
168 168
 
169 169
 		// Set a response with valid set to true or false according to the key validity with message.
170
-		wp_send_json_success( array(
170
+		wp_send_json_success(array(
171 171
 			'valid'   => false,
172
-			'message' => __( 'An error occurred, please contact us at [email protected]', 'wordlift' ),
173
-		) );
172
+			'message' => __('An error occurred, please contact us at [email protected]', 'wordlift'),
173
+		));
174 174
 	}
175 175
 
176 176
 	/**
@@ -179,15 +179,15 @@  discard block
 block discarded – undo
179 179
 	 */
180 180
 	public function wl_load_plugin() {
181 181
 
182
-		$wl_blog_url = get_option( '_wl_blog_url' );
183
-		$home_url    = get_option( 'home' );
182
+		$wl_blog_url = get_option('_wl_blog_url');
183
+		$home_url    = get_option('home');
184 184
 
185
-		if ( ! $wl_blog_url ) {
186
-			update_option( '_wl_blog_url', $home_url, true );
187
-		} else if ( $wl_blog_url !== $home_url ) {
188
-			update_option( '_wl_blog_url', $home_url, true );
189
-			Wordlift_Configuration_Service::get_instance()->set_key( '' );
190
-			set_transient( 'wl-key-error-msg', __( "Your web site URL has changed. To avoid data corruption, WordLift's key has been removed. Please provide a new key in WordLift Settings. If you believe this to be an error, please contact us at [email protected]", 'wordlift' ), 10 );
185
+		if ( ! $wl_blog_url) {
186
+			update_option('_wl_blog_url', $home_url, true);
187
+		} else if ($wl_blog_url !== $home_url) {
188
+			update_option('_wl_blog_url', $home_url, true);
189
+			Wordlift_Configuration_Service::get_instance()->set_key('');
190
+			set_transient('wl-key-error-msg', __("Your web site URL has changed. To avoid data corruption, WordLift's key has been removed. Please provide a new key in WordLift Settings. If you believe this to be an error, please contact us at [email protected]", 'wordlift'), 10);
191 191
 		}
192 192
 
193 193
 	}
@@ -197,10 +197,10 @@  discard block
 block discarded – undo
197 197
 	 *
198 198
 	 */
199 199
 	public function wl_key_update_notice() {
200
-		if ( get_transient( 'wl-key-error-msg' ) ) {
200
+		if (get_transient('wl-key-error-msg')) {
201 201
 			?>
202 202
             <div class="updated notice is-dismissible error">
203
-                <p><?php _e( get_transient( 'wl-key-error-msg' ), 'wordlift' ); ?></p>
203
+                <p><?php _e(get_transient('wl-key-error-msg'), 'wordlift'); ?></p>
204 204
             </div>
205 205
 			<?php
206 206
 		}
Please login to merge, or discard this patch.
src/includes/class-wordlift-http-api.php 2 patches
Indentation   +171 added lines, -171 removed lines patch added patch discarded remove patch
@@ -16,176 +16,176 @@
 block discarded – undo
16 16
  */
17 17
 class Wordlift_Http_Api {
18 18
 
19
-	/**
20
-	 * A {@link Wordlift_Log_Service} instance.
21
-	 *
22
-	 * @since 3.15.3
23
-	 *
24
-	 * @var \Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
25
-	 */
26
-	private $log;
27
-
28
-	/**
29
-	 * Create a {@link Wordlift_End_Point} instance.
30
-	 *
31
-	 * @since 3.15.3
32
-	 */
33
-	public function __construct() {
34
-
35
-		$this->log = Wordlift_Log_Service::get_logger( get_class() );
36
-
37
-		add_action( 'init', array( $this, 'add_rewrite_endpoint' ) );
38
-		add_action( 'template_redirect', array( $this, 'template_redirect' ) );
39
-
40
-		//region SAMPLE ACTIONS.
41
-		add_action( 'admin_post_wl_hello_world', array(
42
-			$this,
43
-			'hello_world',
44
-		) );
45
-		add_action( 'admin_post_nopriv_wl_hello_world', array(
46
-			$this,
47
-			'nopriv_hello_world',
48
-		) );
49
-		//endregion
50
-
51
-	}
52
-
53
-	/**
54
-	 * Add the `wl-api` rewrite end-point.
55
-	 *
56
-	 * @since 3.15.3
57
-	 */
58
-	public function add_rewrite_endpoint() {
59
-
60
-		add_rewrite_endpoint( 'wl-api', EP_ROOT );
61
-		$this->ensure_rewrite_rules_are_flushed();
62
-
63
-	}
64
-
65
-	/**
66
-	 * Handle `template_redirect` hooks.
67
-	 *
68
-	 * @since 3.15.3
69
-	 */
70
-	public function template_redirect() {
71
-
72
-		global $wp_query;
73
-
74
-		if ( ! isset( $wp_query->query_vars['wl-api'] ) ) {
75
-			$this->log->trace( 'Skipping, not a `wl-api` call.' );
76
-
77
-			return;
78
-		}
79
-
80
-		$this->do_action( (string) $_REQUEST['action'] );
81
-
82
-		exit;
83
-
84
-	}
85
-
86
-	/**
87
-	 * Do the requested action.
88
-	 *
89
-	 * @since 3.15.3
90
-	 *
91
-	 * @param string $action The action to execute.
92
-	 */
93
-	private function do_action( $action ) {
94
-
95
-		if ( empty( $action ) ) {
96
-			return;
97
-		}
98
-
99
-		if ( ! wp_validate_auth_cookie( '', 'logged_in' ) ) {
100
-			/**
101
-			 * Fires on a non-authenticated admin post request for the given action.
102
-			 *
103
-			 * The dynamic portion of the hook name, `$action`, refers to the given
104
-			 * request action.
105
-			 *
106
-			 * @since 2.6.0
107
-			 */
108
-			do_action( "admin_post_nopriv_{$action}" );
109
-		} else {
110
-			/**
111
-			 * Fires on an authenticated admin post request for the given action.
112
-			 *
113
-			 * The dynamic portion of the hook name, `$action`, refers to the given
114
-			 * request action.
115
-			 *
116
-			 * @since 2.6.0
117
-			 */
118
-			do_action( "admin_post_{$action}" );
119
-		}
120
-
121
-	}
122
-
123
-	/**
124
-	 * Test function, anonymous.
125
-	 *
126
-	 * @since 3.15.3
127
-	 */
128
-	public function nopriv_hello_world() {
129
-
130
-		wp_die( 'Hello World! (from anonymous)' );
131
-
132
-	}
133
-
134
-	/**
135
-	 * Test function, authenticated.
136
-	 *
137
-	 * @since 3.15.3
138
-	 */
139
-	public function hello_world() {
140
-
141
-		wp_die( 'Hello World! (from authenticated)' );
142
-
143
-	}
144
-
145
-	/**
146
-	 * Ensure that the rewrite rules are flushed the first time.
147
-	 *
148
-	 * @since 3.16.0 changed the value from 1 to `yes` to avoid type juggling issues.
149
-	 * @since 3.15.3
150
-	 */
151
-	public static function ensure_rewrite_rules_are_flushed() {
152
-
153
-		// See https://github.com/insideout10/wordlift-plugin/issues/698.
154
-		if ( 'yes' !== get_option( 'wl_http_api' ) ) {
155
-			update_option( 'wl_http_api', 'yes' );
156
-			add_action( 'wp_loaded', function () {
157
-				flush_rewrite_rules();
158
-			} );
159
-		}
160
-
161
-	}
162
-
163
-	/**
164
-	 * Called by {@see activate_wordlift}, resets the `wl_http_api` option flag in order to force WordLift to
165
-	 * reinitialize the `wl-api` route.
166
-	 *
167
-	 * @see https://github.com/insideout10/wordlift-plugin/issues/820 related issue.
168
-	 *
169
-	 * @since 3.19.2
170
-	 */
171
-	public static function activate() {
172
-
173
-		// Force the plugin to reinitialize the rewrite rules.
174
-		update_option( 'wl_http_api', 'no' );
175
-
176
-	}
177
-
178
-	/**
179
-	 * Delete the option when the plugin is deactivated.
180
-	 *
181
-	 * @since 3.19.4
182
-	 *
183
-	 * @see https://github.com/insideout10/wordlift-plugin/issues/846
184
-	 */
185
-	public static function deactivate() {
186
-
187
-		delete_option( 'wl_http_api' );
188
-
189
-	}
19
+    /**
20
+     * A {@link Wordlift_Log_Service} instance.
21
+     *
22
+     * @since 3.15.3
23
+     *
24
+     * @var \Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
25
+     */
26
+    private $log;
27
+
28
+    /**
29
+     * Create a {@link Wordlift_End_Point} instance.
30
+     *
31
+     * @since 3.15.3
32
+     */
33
+    public function __construct() {
34
+
35
+        $this->log = Wordlift_Log_Service::get_logger( get_class() );
36
+
37
+        add_action( 'init', array( $this, 'add_rewrite_endpoint' ) );
38
+        add_action( 'template_redirect', array( $this, 'template_redirect' ) );
39
+
40
+        //region SAMPLE ACTIONS.
41
+        add_action( 'admin_post_wl_hello_world', array(
42
+            $this,
43
+            'hello_world',
44
+        ) );
45
+        add_action( 'admin_post_nopriv_wl_hello_world', array(
46
+            $this,
47
+            'nopriv_hello_world',
48
+        ) );
49
+        //endregion
50
+
51
+    }
52
+
53
+    /**
54
+     * Add the `wl-api` rewrite end-point.
55
+     *
56
+     * @since 3.15.3
57
+     */
58
+    public function add_rewrite_endpoint() {
59
+
60
+        add_rewrite_endpoint( 'wl-api', EP_ROOT );
61
+        $this->ensure_rewrite_rules_are_flushed();
62
+
63
+    }
64
+
65
+    /**
66
+     * Handle `template_redirect` hooks.
67
+     *
68
+     * @since 3.15.3
69
+     */
70
+    public function template_redirect() {
71
+
72
+        global $wp_query;
73
+
74
+        if ( ! isset( $wp_query->query_vars['wl-api'] ) ) {
75
+            $this->log->trace( 'Skipping, not a `wl-api` call.' );
76
+
77
+            return;
78
+        }
79
+
80
+        $this->do_action( (string) $_REQUEST['action'] );
81
+
82
+        exit;
83
+
84
+    }
85
+
86
+    /**
87
+     * Do the requested action.
88
+     *
89
+     * @since 3.15.3
90
+     *
91
+     * @param string $action The action to execute.
92
+     */
93
+    private function do_action( $action ) {
94
+
95
+        if ( empty( $action ) ) {
96
+            return;
97
+        }
98
+
99
+        if ( ! wp_validate_auth_cookie( '', 'logged_in' ) ) {
100
+            /**
101
+             * Fires on a non-authenticated admin post request for the given action.
102
+             *
103
+             * The dynamic portion of the hook name, `$action`, refers to the given
104
+             * request action.
105
+             *
106
+             * @since 2.6.0
107
+             */
108
+            do_action( "admin_post_nopriv_{$action}" );
109
+        } else {
110
+            /**
111
+             * Fires on an authenticated admin post request for the given action.
112
+             *
113
+             * The dynamic portion of the hook name, `$action`, refers to the given
114
+             * request action.
115
+             *
116
+             * @since 2.6.0
117
+             */
118
+            do_action( "admin_post_{$action}" );
119
+        }
120
+
121
+    }
122
+
123
+    /**
124
+     * Test function, anonymous.
125
+     *
126
+     * @since 3.15.3
127
+     */
128
+    public function nopriv_hello_world() {
129
+
130
+        wp_die( 'Hello World! (from anonymous)' );
131
+
132
+    }
133
+
134
+    /**
135
+     * Test function, authenticated.
136
+     *
137
+     * @since 3.15.3
138
+     */
139
+    public function hello_world() {
140
+
141
+        wp_die( 'Hello World! (from authenticated)' );
142
+
143
+    }
144
+
145
+    /**
146
+     * Ensure that the rewrite rules are flushed the first time.
147
+     *
148
+     * @since 3.16.0 changed the value from 1 to `yes` to avoid type juggling issues.
149
+     * @since 3.15.3
150
+     */
151
+    public static function ensure_rewrite_rules_are_flushed() {
152
+
153
+        // See https://github.com/insideout10/wordlift-plugin/issues/698.
154
+        if ( 'yes' !== get_option( 'wl_http_api' ) ) {
155
+            update_option( 'wl_http_api', 'yes' );
156
+            add_action( 'wp_loaded', function () {
157
+                flush_rewrite_rules();
158
+            } );
159
+        }
160
+
161
+    }
162
+
163
+    /**
164
+     * Called by {@see activate_wordlift}, resets the `wl_http_api` option flag in order to force WordLift to
165
+     * reinitialize the `wl-api` route.
166
+     *
167
+     * @see https://github.com/insideout10/wordlift-plugin/issues/820 related issue.
168
+     *
169
+     * @since 3.19.2
170
+     */
171
+    public static function activate() {
172
+
173
+        // Force the plugin to reinitialize the rewrite rules.
174
+        update_option( 'wl_http_api', 'no' );
175
+
176
+    }
177
+
178
+    /**
179
+     * Delete the option when the plugin is deactivated.
180
+     *
181
+     * @since 3.19.4
182
+     *
183
+     * @see https://github.com/insideout10/wordlift-plugin/issues/846
184
+     */
185
+    public static function deactivate() {
186
+
187
+        delete_option( 'wl_http_api' );
188
+
189
+    }
190 190
 
191 191
 }
Please login to merge, or discard this patch.
Spacing   +23 added lines, -23 removed lines patch added patch discarded remove patch
@@ -32,20 +32,20 @@  discard block
 block discarded – undo
32 32
 	 */
33 33
 	public function __construct() {
34 34
 
35
-		$this->log = Wordlift_Log_Service::get_logger( get_class() );
35
+		$this->log = Wordlift_Log_Service::get_logger(get_class());
36 36
 
37
-		add_action( 'init', array( $this, 'add_rewrite_endpoint' ) );
38
-		add_action( 'template_redirect', array( $this, 'template_redirect' ) );
37
+		add_action('init', array($this, 'add_rewrite_endpoint'));
38
+		add_action('template_redirect', array($this, 'template_redirect'));
39 39
 
40 40
 		//region SAMPLE ACTIONS.
41
-		add_action( 'admin_post_wl_hello_world', array(
41
+		add_action('admin_post_wl_hello_world', array(
42 42
 			$this,
43 43
 			'hello_world',
44
-		) );
45
-		add_action( 'admin_post_nopriv_wl_hello_world', array(
44
+		));
45
+		add_action('admin_post_nopriv_wl_hello_world', array(
46 46
 			$this,
47 47
 			'nopriv_hello_world',
48
-		) );
48
+		));
49 49
 		//endregion
50 50
 
51 51
 	}
@@ -57,7 +57,7 @@  discard block
 block discarded – undo
57 57
 	 */
58 58
 	public function add_rewrite_endpoint() {
59 59
 
60
-		add_rewrite_endpoint( 'wl-api', EP_ROOT );
60
+		add_rewrite_endpoint('wl-api', EP_ROOT);
61 61
 		$this->ensure_rewrite_rules_are_flushed();
62 62
 
63 63
 	}
@@ -71,13 +71,13 @@  discard block
 block discarded – undo
71 71
 
72 72
 		global $wp_query;
73 73
 
74
-		if ( ! isset( $wp_query->query_vars['wl-api'] ) ) {
75
-			$this->log->trace( 'Skipping, not a `wl-api` call.' );
74
+		if ( ! isset($wp_query->query_vars['wl-api'])) {
75
+			$this->log->trace('Skipping, not a `wl-api` call.');
76 76
 
77 77
 			return;
78 78
 		}
79 79
 
80
-		$this->do_action( (string) $_REQUEST['action'] );
80
+		$this->do_action((string) $_REQUEST['action']);
81 81
 
82 82
 		exit;
83 83
 
@@ -90,13 +90,13 @@  discard block
 block discarded – undo
90 90
 	 *
91 91
 	 * @param string $action The action to execute.
92 92
 	 */
93
-	private function do_action( $action ) {
93
+	private function do_action($action) {
94 94
 
95
-		if ( empty( $action ) ) {
95
+		if (empty($action)) {
96 96
 			return;
97 97
 		}
98 98
 
99
-		if ( ! wp_validate_auth_cookie( '', 'logged_in' ) ) {
99
+		if ( ! wp_validate_auth_cookie('', 'logged_in')) {
100 100
 			/**
101 101
 			 * Fires on a non-authenticated admin post request for the given action.
102 102
 			 *
@@ -105,7 +105,7 @@  discard block
 block discarded – undo
105 105
 			 *
106 106
 			 * @since 2.6.0
107 107
 			 */
108
-			do_action( "admin_post_nopriv_{$action}" );
108
+			do_action("admin_post_nopriv_{$action}");
109 109
 		} else {
110 110
 			/**
111 111
 			 * Fires on an authenticated admin post request for the given action.
@@ -115,7 +115,7 @@  discard block
 block discarded – undo
115 115
 			 *
116 116
 			 * @since 2.6.0
117 117
 			 */
118
-			do_action( "admin_post_{$action}" );
118
+			do_action("admin_post_{$action}");
119 119
 		}
120 120
 
121 121
 	}
@@ -127,7 +127,7 @@  discard block
 block discarded – undo
127 127
 	 */
128 128
 	public function nopriv_hello_world() {
129 129
 
130
-		wp_die( 'Hello World! (from anonymous)' );
130
+		wp_die('Hello World! (from anonymous)');
131 131
 
132 132
 	}
133 133
 
@@ -138,7 +138,7 @@  discard block
 block discarded – undo
138 138
 	 */
139 139
 	public function hello_world() {
140 140
 
141
-		wp_die( 'Hello World! (from authenticated)' );
141
+		wp_die('Hello World! (from authenticated)');
142 142
 
143 143
 	}
144 144
 
@@ -151,9 +151,9 @@  discard block
 block discarded – undo
151 151
 	public static function ensure_rewrite_rules_are_flushed() {
152 152
 
153 153
 		// See https://github.com/insideout10/wordlift-plugin/issues/698.
154
-		if ( 'yes' !== get_option( 'wl_http_api' ) ) {
155
-			update_option( 'wl_http_api', 'yes' );
156
-			add_action( 'wp_loaded', function () {
154
+		if ('yes' !== get_option('wl_http_api')) {
155
+			update_option('wl_http_api', 'yes');
156
+			add_action('wp_loaded', function() {
157 157
 				flush_rewrite_rules();
158 158
 			} );
159 159
 		}
@@ -171,7 +171,7 @@  discard block
 block discarded – undo
171 171
 	public static function activate() {
172 172
 
173 173
 		// Force the plugin to reinitialize the rewrite rules.
174
-		update_option( 'wl_http_api', 'no' );
174
+		update_option('wl_http_api', 'no');
175 175
 
176 176
 	}
177 177
 
@@ -184,7 +184,7 @@  discard block
 block discarded – undo
184 184
 	 */
185 185
 	public static function deactivate() {
186 186
 
187
-		delete_option( 'wl_http_api' );
187
+		delete_option('wl_http_api');
188 188
 
189 189
 	}
190 190
 
Please login to merge, or discard this patch.
src/includes/class-wordlift-publisher-ajax-adapter.php 2 patches
Indentation   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -16,55 +16,55 @@
 block discarded – undo
16 16
  */
17 17
 class Wordlift_Publisher_Ajax_Adapter {
18 18
 
19
-	/**
20
-	 * The {@link Wordlift_Publisher_Service} instance.
21
-	 *
22
-	 * @since  3.11.0
23
-	 * @access private
24
-	 * @var Wordlift_Publisher_Service $publisher_service The {@link Wordlift_Publisher_Service} instance.
25
-	 */
26
-	private $publisher_service;
19
+    /**
20
+     * The {@link Wordlift_Publisher_Service} instance.
21
+     *
22
+     * @since  3.11.0
23
+     * @access private
24
+     * @var Wordlift_Publisher_Service $publisher_service The {@link Wordlift_Publisher_Service} instance.
25
+     */
26
+    private $publisher_service;
27 27
 
28
-	/**
29
-	 * Create a {@link Wordlift_Publisher_Ajax_Adapter} instance.
30
-	 *
31
-	 * @since 3.11.0
32
-	 *
33
-	 * @param \Wordlift_Publisher_Service $publisher_service The {@link Wordlift_Publisher_Service} instance.
34
-	 */
35
-	function __construct( $publisher_service ) {
28
+    /**
29
+     * Create a {@link Wordlift_Publisher_Ajax_Adapter} instance.
30
+     *
31
+     * @since 3.11.0
32
+     *
33
+     * @param \Wordlift_Publisher_Service $publisher_service The {@link Wordlift_Publisher_Service} instance.
34
+     */
35
+    function __construct( $publisher_service ) {
36 36
 
37
-		$this->publisher_service = $publisher_service;
37
+        $this->publisher_service = $publisher_service;
38 38
 
39
-	}
39
+    }
40 40
 
41
-	/**
42
-	 * The publisher AJAX action. This function is hook to the `wl_publisher`
43
-	 * action.
44
-	 *
45
-	 * @since 3.11.0
46
-	 */
47
-	public function publisher() {
41
+    /**
42
+     * The publisher AJAX action. This function is hook to the `wl_publisher`
43
+     * action.
44
+     *
45
+     * @since 3.11.0
46
+     */
47
+    public function publisher() {
48 48
 
49
-		// Ensure we don't have garbage before us.
50
-		ob_clean();
49
+        // Ensure we don't have garbage before us.
50
+        ob_clean();
51 51
 
52
-		// Check if the current user can `manage_options`.
53
-		if ( ! current_user_can( 'manage_options' ) ) {
54
-			wp_send_json_error( 'Access denied.' );
55
-		}
52
+        // Check if the current user can `manage_options`.
53
+        if ( ! current_user_can( 'manage_options' ) ) {
54
+            wp_send_json_error( 'Access denied.' );
55
+        }
56 56
 
57
-		// No actual search parameter was passed, bail out.
58
-		if ( ! isset( $_POST['q'] ) || empty( $_POST['q'] ) ) {
59
-			wp_send_json_error( 'The q parameter is required.' );
60
-		}
57
+        // No actual search parameter was passed, bail out.
58
+        if ( ! isset( $_POST['q'] ) || empty( $_POST['q'] ) ) {
59
+            wp_send_json_error( 'The q parameter is required.' );
60
+        }
61 61
 
62
-		// Get the response.
63
-		$response = $this->publisher_service->query( (string) $_POST['q'] );
62
+        // Get the response.
63
+        $response = $this->publisher_service->query( (string) $_POST['q'] );
64 64
 
65
-		// Finally output the response.
66
-		wp_send_json_success( $response );
65
+        // Finally output the response.
66
+        wp_send_json_success( $response );
67 67
 
68
-	}
68
+    }
69 69
 
70 70
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -32,7 +32,7 @@  discard block
 block discarded – undo
32 32
 	 *
33 33
 	 * @param \Wordlift_Publisher_Service $publisher_service The {@link Wordlift_Publisher_Service} instance.
34 34
 	 */
35
-	function __construct( $publisher_service ) {
35
+	function __construct($publisher_service) {
36 36
 
37 37
 		$this->publisher_service = $publisher_service;
38 38
 
@@ -50,20 +50,20 @@  discard block
 block discarded – undo
50 50
 		ob_clean();
51 51
 
52 52
 		// Check if the current user can `manage_options`.
53
-		if ( ! current_user_can( 'manage_options' ) ) {
54
-			wp_send_json_error( 'Access denied.' );
53
+		if ( ! current_user_can('manage_options')) {
54
+			wp_send_json_error('Access denied.');
55 55
 		}
56 56
 
57 57
 		// No actual search parameter was passed, bail out.
58
-		if ( ! isset( $_POST['q'] ) || empty( $_POST['q'] ) ) {
59
-			wp_send_json_error( 'The q parameter is required.' );
58
+		if ( ! isset($_POST['q']) || empty($_POST['q'])) {
59
+			wp_send_json_error('The q parameter is required.');
60 60
 		}
61 61
 
62 62
 		// Get the response.
63
-		$response = $this->publisher_service->query( (string) $_POST['q'] );
63
+		$response = $this->publisher_service->query((string) $_POST['q']);
64 64
 
65 65
 		// Finally output the response.
66
-		wp_send_json_success( $response );
66
+		wp_send_json_success($response);
67 67
 
68 68
 	}
69 69
 
Please login to merge, or discard this patch.
src/includes/class-wordlift-deactivator-feedback.php 2 patches
Indentation   +157 added lines, -157 removed lines patch added patch discarded remove patch
@@ -21,161 +21,161 @@
 block discarded – undo
21 21
  */
22 22
 class Wordlift_Deactivator_Feedback {
23 23
 
24
-	/**
25
-	 * A {@link Wordlift_Log_Service} instance.
26
-	 *
27
-	 * @since  3.19.0
28
-	 * @access private
29
-	 * @var \Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
30
-	 */
31
-	private $log;
32
-
33
-	/**
34
-	 * The {@link Wordlift_Configuration_Service} instance.
35
-	 *
36
-	 * @since  3.19.0
37
-	 * @access private
38
-	 * @var \Wordlift_Configuration_Service $configuration_service The {@link Wordlift_Configuration_Service} instance.
39
-	 */
40
-	private $configuration_service;
41
-
42
-	/**
43
-	 * Wordlift_Deactivator_Feedback constructor.
44
-	 *
45
-	 * @since 3.19.0
46
-	 *
47
-	 * @param \Wordlift_Configuration_Service $configuration_service The {@link Wordlift_Configuration_Service} instance.
48
-	 */
49
-	public function __construct( $configuration_service ) {
50
-
51
-		$this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Deactivator_Feedback' );
52
-
53
-		$this->configuration_service = $configuration_service;
54
-
55
-	}
56
-	/**
57
-	 * Checks whether we have permissions to show the popup.
58
-	 *
59
-	 * @version 3.19.0
60
-	 *
61
-	 * @return  bool `true` if we have permissions, false otherwise.
62
-	 */
63
-	private function has_permission_to_show_popup() {
64
-		// Get the current page.
65
-		global $pagenow;
66
-
67
-		// Bail if the user doesn't have permissions
68
-		// or if it's not the plugins page.
69
-		if ( 'plugins.php' !== $pagenow ) {
70
-			return false;
71
-		}
72
-
73
-		// Get the user preferences. We shouldn't show the feedback popup
74
-		// if we don't have permissions for that.
75
-		$user_preferences = $this->configuration_service->get_diagnostic_preferences();
76
-
77
-		// Bail. We don't have preferences to show the popup.
78
-		if ( 'yes' !== $user_preferences ) {
79
-			return false;
80
-		}
81
-
82
-		return true;
83
-	}
84
-
85
-	/**
86
-	 * Render the feedback popup in the footer.
87
-	 *
88
-	 * @version 3.19.0
89
-	 *
90
-	 * @return  void
91
-	 */
92
-	public function render_feedback_popup() {
93
-		// Bail if we don't have permissions to show the popup.
94
-		if ( ! $this->has_permission_to_show_popup() ) {
95
-			return;
96
-		}
97
-		// Include the partial.
98
-		include plugin_dir_path( __FILE__ ) . '../admin/partials/wordlift-admin-deactivation-feedback-popup.php';
99
-	}
100
-
101
-	/**
102
-	 * Enqueue required popup scripts and styles.
103
-	 *
104
-	 * @version 3.19.0
105
-	 *
106
-	 * @return  void
107
-	 */
108
-	public function enqueue_popup_scripts() {
109
-		// Bail if we don't have permissions to show the popup.
110
-		if ( ! $this->has_permission_to_show_popup() ) {
111
-			return;
112
-		}
113
-
114
-		wp_enqueue_style( 'wordlift-admin-feedback-popup', plugin_dir_url( dirname( __FILE__ ) ) . 'admin/css/wordlift-admin-feedback-popup.css', array() );
115
-		wp_enqueue_script( 'wordlift-admin-feedback-popup', plugin_dir_url( dirname( __FILE__ ) ) . 'admin/js/wordlift-admin-feedback-popup.js', array( 'jquery' ) );
116
-	}
117
-
118
-	/**
119
-	 * Handle the deactivation ajax call
120
-	 * and perform a request to external server.
121
-	 *
122
-	 * @version 3.19.0
123
-	 *
124
-	 * @return  void
125
-	 */
126
-	public function wl_deactivation_feedback() {
127
-		// Bail if the nonce is not valid.
128
-		if (
129
-			empty( $_POST['wl_deactivation_feedback_nonce'] ) || // The nonce doens't exists.
130
-			! wp_verify_nonce( $_POST['wl_deactivation_feedback_nonce'], 'wl_deactivation_feedback_nonce' ) // The nonce is invalid.
131
-		) {
132
-			wp_send_json_error( __( 'Nonce Security Check Failed!', 'wordlift' ) );
133
-		}
134
-
135
-		// We allow user to deactivate without providing a reason
136
-		// so bail and send success response.
137
-		if ( empty( $_POST['code'] ) ) {
138
-			wp_send_json_success();
139
-		}
140
-
141
-		$plugin_data = get_plugin_data( plugin_dir_path( dirname( __FILE__ ) ) . 'wordlift.php', false, false );
142
-
143
-		// Prepare the options.
144
-		$options = array(
145
-			// The deactivation reason.
146
-			'code'             => (string) $_POST['code'],
147
-			// Additional information if provided.
148
-			'details'          => ( ! empty( $_POST['details'] ) ) ? (string) $_POST['details'] : '',
149
-			// The website url.
150
-			'url'              => get_bloginfo( 'url' ),
151
-			// WP version.
152
-			'wordpressVersion' => get_bloginfo( 'version' ),
153
-			// WL version.
154
-			'wordliftVersion'  => $plugin_data['Version'],
155
-			// The admin email.
156
-			'email'            => get_bloginfo( 'admin_email' ),
157
-		);
158
-
159
-		$response = wp_remote_post(
160
-			$this->configuration_service->get_deactivation_feedback_url(),
161
-			array(
162
-				'method'  => 'POST',
163
-				'body'    => json_encode( $options ),
164
-				'headers' => array( 'Content-Type' => 'application/json; charset=utf-8' ),
165
-			)
166
-		);
167
-
168
-		$code    = wp_remote_retrieve_response_code( $response );
169
-		$message = wp_remote_retrieve_response_message( $response );
170
-
171
-		// Add message to the error log if the response code is not 200.
172
-		if ( 201 !== $code ) {
173
-			// Write the error in the logs.
174
-			$this->log->error( 'An error occurred while requesting a feedback endpoint error_code: ' . $code . ' message: ' . $message );
175
-		}
176
-
177
-		// We should send success message even when the feedback is not
178
-		// send, because otherwise the plugin cannot be deactivated.
179
-		wp_send_json_success();
180
-	}
24
+    /**
25
+     * A {@link Wordlift_Log_Service} instance.
26
+     *
27
+     * @since  3.19.0
28
+     * @access private
29
+     * @var \Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
30
+     */
31
+    private $log;
32
+
33
+    /**
34
+     * The {@link Wordlift_Configuration_Service} instance.
35
+     *
36
+     * @since  3.19.0
37
+     * @access private
38
+     * @var \Wordlift_Configuration_Service $configuration_service The {@link Wordlift_Configuration_Service} instance.
39
+     */
40
+    private $configuration_service;
41
+
42
+    /**
43
+     * Wordlift_Deactivator_Feedback constructor.
44
+     *
45
+     * @since 3.19.0
46
+     *
47
+     * @param \Wordlift_Configuration_Service $configuration_service The {@link Wordlift_Configuration_Service} instance.
48
+     */
49
+    public function __construct( $configuration_service ) {
50
+
51
+        $this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Deactivator_Feedback' );
52
+
53
+        $this->configuration_service = $configuration_service;
54
+
55
+    }
56
+    /**
57
+     * Checks whether we have permissions to show the popup.
58
+     *
59
+     * @version 3.19.0
60
+     *
61
+     * @return  bool `true` if we have permissions, false otherwise.
62
+     */
63
+    private function has_permission_to_show_popup() {
64
+        // Get the current page.
65
+        global $pagenow;
66
+
67
+        // Bail if the user doesn't have permissions
68
+        // or if it's not the plugins page.
69
+        if ( 'plugins.php' !== $pagenow ) {
70
+            return false;
71
+        }
72
+
73
+        // Get the user preferences. We shouldn't show the feedback popup
74
+        // if we don't have permissions for that.
75
+        $user_preferences = $this->configuration_service->get_diagnostic_preferences();
76
+
77
+        // Bail. We don't have preferences to show the popup.
78
+        if ( 'yes' !== $user_preferences ) {
79
+            return false;
80
+        }
81
+
82
+        return true;
83
+    }
84
+
85
+    /**
86
+     * Render the feedback popup in the footer.
87
+     *
88
+     * @version 3.19.0
89
+     *
90
+     * @return  void
91
+     */
92
+    public function render_feedback_popup() {
93
+        // Bail if we don't have permissions to show the popup.
94
+        if ( ! $this->has_permission_to_show_popup() ) {
95
+            return;
96
+        }
97
+        // Include the partial.
98
+        include plugin_dir_path( __FILE__ ) . '../admin/partials/wordlift-admin-deactivation-feedback-popup.php';
99
+    }
100
+
101
+    /**
102
+     * Enqueue required popup scripts and styles.
103
+     *
104
+     * @version 3.19.0
105
+     *
106
+     * @return  void
107
+     */
108
+    public function enqueue_popup_scripts() {
109
+        // Bail if we don't have permissions to show the popup.
110
+        if ( ! $this->has_permission_to_show_popup() ) {
111
+            return;
112
+        }
113
+
114
+        wp_enqueue_style( 'wordlift-admin-feedback-popup', plugin_dir_url( dirname( __FILE__ ) ) . 'admin/css/wordlift-admin-feedback-popup.css', array() );
115
+        wp_enqueue_script( 'wordlift-admin-feedback-popup', plugin_dir_url( dirname( __FILE__ ) ) . 'admin/js/wordlift-admin-feedback-popup.js', array( 'jquery' ) );
116
+    }
117
+
118
+    /**
119
+     * Handle the deactivation ajax call
120
+     * and perform a request to external server.
121
+     *
122
+     * @version 3.19.0
123
+     *
124
+     * @return  void
125
+     */
126
+    public function wl_deactivation_feedback() {
127
+        // Bail if the nonce is not valid.
128
+        if (
129
+            empty( $_POST['wl_deactivation_feedback_nonce'] ) || // The nonce doens't exists.
130
+            ! wp_verify_nonce( $_POST['wl_deactivation_feedback_nonce'], 'wl_deactivation_feedback_nonce' ) // The nonce is invalid.
131
+        ) {
132
+            wp_send_json_error( __( 'Nonce Security Check Failed!', 'wordlift' ) );
133
+        }
134
+
135
+        // We allow user to deactivate without providing a reason
136
+        // so bail and send success response.
137
+        if ( empty( $_POST['code'] ) ) {
138
+            wp_send_json_success();
139
+        }
140
+
141
+        $plugin_data = get_plugin_data( plugin_dir_path( dirname( __FILE__ ) ) . 'wordlift.php', false, false );
142
+
143
+        // Prepare the options.
144
+        $options = array(
145
+            // The deactivation reason.
146
+            'code'             => (string) $_POST['code'],
147
+            // Additional information if provided.
148
+            'details'          => ( ! empty( $_POST['details'] ) ) ? (string) $_POST['details'] : '',
149
+            // The website url.
150
+            'url'              => get_bloginfo( 'url' ),
151
+            // WP version.
152
+            'wordpressVersion' => get_bloginfo( 'version' ),
153
+            // WL version.
154
+            'wordliftVersion'  => $plugin_data['Version'],
155
+            // The admin email.
156
+            'email'            => get_bloginfo( 'admin_email' ),
157
+        );
158
+
159
+        $response = wp_remote_post(
160
+            $this->configuration_service->get_deactivation_feedback_url(),
161
+            array(
162
+                'method'  => 'POST',
163
+                'body'    => json_encode( $options ),
164
+                'headers' => array( 'Content-Type' => 'application/json; charset=utf-8' ),
165
+            )
166
+        );
167
+
168
+        $code    = wp_remote_retrieve_response_code( $response );
169
+        $message = wp_remote_retrieve_response_message( $response );
170
+
171
+        // Add message to the error log if the response code is not 200.
172
+        if ( 201 !== $code ) {
173
+            // Write the error in the logs.
174
+            $this->log->error( 'An error occurred while requesting a feedback endpoint error_code: ' . $code . ' message: ' . $message );
175
+        }
176
+
177
+        // We should send success message even when the feedback is not
178
+        // send, because otherwise the plugin cannot be deactivated.
179
+        wp_send_json_success();
180
+    }
181 181
 }
Please login to merge, or discard this patch.
Spacing   +24 added lines, -24 removed lines patch added patch discarded remove patch
@@ -46,9 +46,9 @@  discard block
 block discarded – undo
46 46
 	 *
47 47
 	 * @param \Wordlift_Configuration_Service $configuration_service The {@link Wordlift_Configuration_Service} instance.
48 48
 	 */
49
-	public function __construct( $configuration_service ) {
49
+	public function __construct($configuration_service) {
50 50
 
51
-		$this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Deactivator_Feedback' );
51
+		$this->log = Wordlift_Log_Service::get_logger('Wordlift_Deactivator_Feedback');
52 52
 
53 53
 		$this->configuration_service = $configuration_service;
54 54
 
@@ -66,7 +66,7 @@  discard block
 block discarded – undo
66 66
 
67 67
 		// Bail if the user doesn't have permissions
68 68
 		// or if it's not the plugins page.
69
-		if ( 'plugins.php' !== $pagenow ) {
69
+		if ('plugins.php' !== $pagenow) {
70 70
 			return false;
71 71
 		}
72 72
 
@@ -75,7 +75,7 @@  discard block
 block discarded – undo
75 75
 		$user_preferences = $this->configuration_service->get_diagnostic_preferences();
76 76
 
77 77
 		// Bail. We don't have preferences to show the popup.
78
-		if ( 'yes' !== $user_preferences ) {
78
+		if ('yes' !== $user_preferences) {
79 79
 			return false;
80 80
 		}
81 81
 
@@ -91,11 +91,11 @@  discard block
 block discarded – undo
91 91
 	 */
92 92
 	public function render_feedback_popup() {
93 93
 		// Bail if we don't have permissions to show the popup.
94
-		if ( ! $this->has_permission_to_show_popup() ) {
94
+		if ( ! $this->has_permission_to_show_popup()) {
95 95
 			return;
96 96
 		}
97 97
 		// Include the partial.
98
-		include plugin_dir_path( __FILE__ ) . '../admin/partials/wordlift-admin-deactivation-feedback-popup.php';
98
+		include plugin_dir_path(__FILE__).'../admin/partials/wordlift-admin-deactivation-feedback-popup.php';
99 99
 	}
100 100
 
101 101
 	/**
@@ -107,12 +107,12 @@  discard block
 block discarded – undo
107 107
 	 */
108 108
 	public function enqueue_popup_scripts() {
109 109
 		// Bail if we don't have permissions to show the popup.
110
-		if ( ! $this->has_permission_to_show_popup() ) {
110
+		if ( ! $this->has_permission_to_show_popup()) {
111 111
 			return;
112 112
 		}
113 113
 
114
-		wp_enqueue_style( 'wordlift-admin-feedback-popup', plugin_dir_url( dirname( __FILE__ ) ) . 'admin/css/wordlift-admin-feedback-popup.css', array() );
115
-		wp_enqueue_script( 'wordlift-admin-feedback-popup', plugin_dir_url( dirname( __FILE__ ) ) . 'admin/js/wordlift-admin-feedback-popup.js', array( 'jquery' ) );
114
+		wp_enqueue_style('wordlift-admin-feedback-popup', plugin_dir_url(dirname(__FILE__)).'admin/css/wordlift-admin-feedback-popup.css', array());
115
+		wp_enqueue_script('wordlift-admin-feedback-popup', plugin_dir_url(dirname(__FILE__)).'admin/js/wordlift-admin-feedback-popup.js', array('jquery'));
116 116
 	}
117 117
 
118 118
 	/**
@@ -126,52 +126,52 @@  discard block
 block discarded – undo
126 126
 	public function wl_deactivation_feedback() {
127 127
 		// Bail if the nonce is not valid.
128 128
 		if (
129
-			empty( $_POST['wl_deactivation_feedback_nonce'] ) || // The nonce doens't exists.
130
-			! wp_verify_nonce( $_POST['wl_deactivation_feedback_nonce'], 'wl_deactivation_feedback_nonce' ) // The nonce is invalid.
129
+			empty($_POST['wl_deactivation_feedback_nonce']) || // The nonce doens't exists.
130
+			! wp_verify_nonce($_POST['wl_deactivation_feedback_nonce'], 'wl_deactivation_feedback_nonce') // The nonce is invalid.
131 131
 		) {
132
-			wp_send_json_error( __( 'Nonce Security Check Failed!', 'wordlift' ) );
132
+			wp_send_json_error(__('Nonce Security Check Failed!', 'wordlift'));
133 133
 		}
134 134
 
135 135
 		// We allow user to deactivate without providing a reason
136 136
 		// so bail and send success response.
137
-		if ( empty( $_POST['code'] ) ) {
137
+		if (empty($_POST['code'])) {
138 138
 			wp_send_json_success();
139 139
 		}
140 140
 
141
-		$plugin_data = get_plugin_data( plugin_dir_path( dirname( __FILE__ ) ) . 'wordlift.php', false, false );
141
+		$plugin_data = get_plugin_data(plugin_dir_path(dirname(__FILE__)).'wordlift.php', false, false);
142 142
 
143 143
 		// Prepare the options.
144 144
 		$options = array(
145 145
 			// The deactivation reason.
146 146
 			'code'             => (string) $_POST['code'],
147 147
 			// Additional information if provided.
148
-			'details'          => ( ! empty( $_POST['details'] ) ) ? (string) $_POST['details'] : '',
148
+			'details'          => ( ! empty($_POST['details'])) ? (string) $_POST['details'] : '',
149 149
 			// The website url.
150
-			'url'              => get_bloginfo( 'url' ),
150
+			'url'              => get_bloginfo('url'),
151 151
 			// WP version.
152
-			'wordpressVersion' => get_bloginfo( 'version' ),
152
+			'wordpressVersion' => get_bloginfo('version'),
153 153
 			// WL version.
154 154
 			'wordliftVersion'  => $plugin_data['Version'],
155 155
 			// The admin email.
156
-			'email'            => get_bloginfo( 'admin_email' ),
156
+			'email'            => get_bloginfo('admin_email'),
157 157
 		);
158 158
 
159 159
 		$response = wp_remote_post(
160 160
 			$this->configuration_service->get_deactivation_feedback_url(),
161 161
 			array(
162 162
 				'method'  => 'POST',
163
-				'body'    => json_encode( $options ),
164
-				'headers' => array( 'Content-Type' => 'application/json; charset=utf-8' ),
163
+				'body'    => json_encode($options),
164
+				'headers' => array('Content-Type' => 'application/json; charset=utf-8'),
165 165
 			)
166 166
 		);
167 167
 
168
-		$code    = wp_remote_retrieve_response_code( $response );
169
-		$message = wp_remote_retrieve_response_message( $response );
168
+		$code    = wp_remote_retrieve_response_code($response);
169
+		$message = wp_remote_retrieve_response_message($response);
170 170
 
171 171
 		// Add message to the error log if the response code is not 200.
172
-		if ( 201 !== $code ) {
172
+		if (201 !== $code) {
173 173
 			// Write the error in the logs.
174
-			$this->log->error( 'An error occurred while requesting a feedback endpoint error_code: ' . $code . ' message: ' . $message );
174
+			$this->log->error('An error occurred while requesting a feedback endpoint error_code: '.$code.' message: '.$message);
175 175
 		}
176 176
 
177 177
 		// We should send success message even when the feedback is not
Please login to merge, or discard this patch.
src/admin/class-wordlift-admin-schemaorg-property-metabox.php 2 patches
Indentation   +302 added lines, -302 removed lines patch added patch discarded remove patch
@@ -16,266 +16,266 @@  discard block
 block discarded – undo
16 16
  */
17 17
 class Wordlift_Admin_Schemaorg_Property_Metabox {
18 18
 
19
-	/**
20
-	 * The action name used for `nonce` checks.
21
-	 *
22
-	 * @since 3.20.0
23
-	 */
24
-	const ACTION_NAME = '_wl_save_schemaorg_props';
25
-
26
-	/**
27
-	 * The `nonce` field name.
28
-	 *
29
-	 * @since 3.20.0
30
-	 */
31
-	const NONCE_NAME = '_wl_save_schemaorg_props_nonce';
32
-
33
-	/**
34
-	 * The following properties are the properties defined by the `Thing` entity type.
35
-	 *
36
-	 * Any change here must be reflected in {@link Wordlift_Entity_Post_To_Jsonld_Converter::convert()}, where
37
-	 * the `Thing` properties are loaded using the entity type's `custom_fields` entry provided by the
38
-	 * {@link Wordlift_Schema_Service}.
39
-	 *
40
-	 * @since 3.20.0
41
-	 */
42
-	private static $unsupported_properties = array(
43
-		'additionalType',
44
-		'alternateName',
45
-		'description',
46
-		'disambiguatingDescription',
47
-		'identifier',
48
-		'image',
49
-		'mainEntityOfPage',
50
-		'name',
51
-		'potentialAction',
52
-		'sameAs',
53
-		'subjectOf',
54
-		'url',
55
-	);
56
-
57
-	/**
58
-	 * The following array defines the ranges currently supported. In particular we currently support only
59
-	 * the basic data types.
60
-	 *
61
-	 * @since 3.20.0
62
-	 */
63
-	private static $supported_ranges = array(
64
-		'Boolean',
65
-		'False',
66
-		'True',
67
-		'Date',
68
-		'DateTime',
69
-		'Number',
70
-		'Float',
71
-		'Integer',
72
-		'Time',
73
-		'Text',
74
-		'URL',
75
-	);
76
-
77
-	/**
78
-	 * The {@link Wordlift_Schemaorg_Property_Service} instance.
79
-	 *
80
-	 * @since 3.20.0
81
-	 * @access private
82
-	 * @var \Wordlift_Schemaorg_Property_Service $schemaorg_property_service The {@link Wordlift_Schemaorg_Property_Service} instance.
83
-	 */
84
-	private $schemaorg_property_service;
85
-
86
-	/**
87
-	 * A {@link Wordlift_Log_Service} instance.
88
-	 *
89
-	 * @since 3.20.0
90
-	 * @access private
91
-	 * @var \Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
92
-	 */
93
-	private $log;
94
-
95
-	/**
96
-	 * Create a {@link Wordlift_Admin_Schemaorg_Property_Metabox} instance.
97
-	 *
98
-	 * @since 3.20.0
99
-	 *
100
-	 * @param \Wordlift_Schemaorg_Property_Service $schemaorg_property_service The {@link Wordlift_Schemaorg_Property_Service} instance.
101
-	 */
102
-	public function __construct( $schemaorg_property_service ) {
103
-
104
-		$this->log = Wordlift_Log_Service::get_logger( get_class() );
105
-
106
-		// Add a hook to display the Schema.org properties metabox.
107
-		add_action( 'add_meta_boxes', array( $this, 'add_meta_boxes' ) );
108
-
109
-		// Add a hook to save the properties.
110
-		add_action( 'save_post', array( $this, 'save_post' ) );
111
-
112
-		// Add a hook to provide an Ajax end-point to load the Schema.org properties.
113
-		add_action( 'wp_ajax_wl_schemaorg_property', array( $this, 'schemaorg_property' ) );
114
-
115
-		$this->schemaorg_property_service = $schemaorg_property_service;
19
+    /**
20
+     * The action name used for `nonce` checks.
21
+     *
22
+     * @since 3.20.0
23
+     */
24
+    const ACTION_NAME = '_wl_save_schemaorg_props';
25
+
26
+    /**
27
+     * The `nonce` field name.
28
+     *
29
+     * @since 3.20.0
30
+     */
31
+    const NONCE_NAME = '_wl_save_schemaorg_props_nonce';
32
+
33
+    /**
34
+     * The following properties are the properties defined by the `Thing` entity type.
35
+     *
36
+     * Any change here must be reflected in {@link Wordlift_Entity_Post_To_Jsonld_Converter::convert()}, where
37
+     * the `Thing` properties are loaded using the entity type's `custom_fields` entry provided by the
38
+     * {@link Wordlift_Schema_Service}.
39
+     *
40
+     * @since 3.20.0
41
+     */
42
+    private static $unsupported_properties = array(
43
+        'additionalType',
44
+        'alternateName',
45
+        'description',
46
+        'disambiguatingDescription',
47
+        'identifier',
48
+        'image',
49
+        'mainEntityOfPage',
50
+        'name',
51
+        'potentialAction',
52
+        'sameAs',
53
+        'subjectOf',
54
+        'url',
55
+    );
56
+
57
+    /**
58
+     * The following array defines the ranges currently supported. In particular we currently support only
59
+     * the basic data types.
60
+     *
61
+     * @since 3.20.0
62
+     */
63
+    private static $supported_ranges = array(
64
+        'Boolean',
65
+        'False',
66
+        'True',
67
+        'Date',
68
+        'DateTime',
69
+        'Number',
70
+        'Float',
71
+        'Integer',
72
+        'Time',
73
+        'Text',
74
+        'URL',
75
+    );
76
+
77
+    /**
78
+     * The {@link Wordlift_Schemaorg_Property_Service} instance.
79
+     *
80
+     * @since 3.20.0
81
+     * @access private
82
+     * @var \Wordlift_Schemaorg_Property_Service $schemaorg_property_service The {@link Wordlift_Schemaorg_Property_Service} instance.
83
+     */
84
+    private $schemaorg_property_service;
85
+
86
+    /**
87
+     * A {@link Wordlift_Log_Service} instance.
88
+     *
89
+     * @since 3.20.0
90
+     * @access private
91
+     * @var \Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
92
+     */
93
+    private $log;
94
+
95
+    /**
96
+     * Create a {@link Wordlift_Admin_Schemaorg_Property_Metabox} instance.
97
+     *
98
+     * @since 3.20.0
99
+     *
100
+     * @param \Wordlift_Schemaorg_Property_Service $schemaorg_property_service The {@link Wordlift_Schemaorg_Property_Service} instance.
101
+     */
102
+    public function __construct( $schemaorg_property_service ) {
103
+
104
+        $this->log = Wordlift_Log_Service::get_logger( get_class() );
105
+
106
+        // Add a hook to display the Schema.org properties metabox.
107
+        add_action( 'add_meta_boxes', array( $this, 'add_meta_boxes' ) );
108
+
109
+        // Add a hook to save the properties.
110
+        add_action( 'save_post', array( $this, 'save_post' ) );
111
+
112
+        // Add a hook to provide an Ajax end-point to load the Schema.org properties.
113
+        add_action( 'wp_ajax_wl_schemaorg_property', array( $this, 'schemaorg_property' ) );
114
+
115
+        $this->schemaorg_property_service = $schemaorg_property_service;
116
+
117
+    }
118
+
119
+    /**
120
+     * Hook `add_meta_boxes`.
121
+     *
122
+     * @since 3.20.0
123
+     *
124
+     * @param string $post_type The current post type.
125
+     */
126
+    public function add_meta_boxes( $post_type ) {
127
+
128
+        // Bail out if the `post_type` isn't a valid entity post type.
129
+        if ( ! Wordlift_Entity_Type_Service::is_valid_entity_post_type( $post_type ) ) {
130
+            return;
131
+        }
116 132
 
117
-	}
133
+        // Add our metabox configuration.
134
+        add_meta_box(
135
+            'wl-schemaorg-property',
136
+            __( 'Schema.org Properties', 'wordlift' ),
137
+            array( $this, 'render' ),
138
+            $post_type,
139
+            'normal',
140
+            'default'
141
+        );
142
+
143
+    }
144
+
145
+    /**
146
+     * Hook `save_post`.
147
+     *
148
+     * The hook will receive the property data in the `$_POST` array.
149
+     *
150
+     * @since 3.20.0
151
+     *
152
+     * @param int $post_id The post id.
153
+     */
154
+    public function save_post( $post_id ) {
155
+
156
+        //region ## CHECKS.
157
+        // Add nonce for security and authentication.
158
+        $nonce_name = isset( $_POST[ self::NONCE_NAME ] ) ? (string) $_POST[ self::NONCE_NAME ] : '';
159
+
160
+        // Check if nonce is set.
161
+        if ( ! isset( $nonce_name ) ) {
162
+            $this->log->warn( '`nonce` not set.' );
163
+
164
+            return;
165
+        }
118 166
 
119
-	/**
120
-	 * Hook `add_meta_boxes`.
121
-	 *
122
-	 * @since 3.20.0
123
-	 *
124
-	 * @param string $post_type The current post type.
125
-	 */
126
-	public function add_meta_boxes( $post_type ) {
127
-
128
-		// Bail out if the `post_type` isn't a valid entity post type.
129
-		if ( ! Wordlift_Entity_Type_Service::is_valid_entity_post_type( $post_type ) ) {
130
-			return;
131
-		}
132
-
133
-		// Add our metabox configuration.
134
-		add_meta_box(
135
-			'wl-schemaorg-property',
136
-			__( 'Schema.org Properties', 'wordlift' ),
137
-			array( $this, 'render' ),
138
-			$post_type,
139
-			'normal',
140
-			'default'
141
-		);
167
+        // Check if nonce is valid.
168
+        if ( ! wp_verify_nonce( $nonce_name, self::ACTION_NAME ) ) {
169
+            $this->log->warn( 'Invalid `nonce`.' );
142 170
 
143
-	}
171
+            return;
172
+        }
144 173
 
145
-	/**
146
-	 * Hook `save_post`.
147
-	 *
148
-	 * The hook will receive the property data in the `$_POST` array.
149
-	 *
150
-	 * @since 3.20.0
151
-	 *
152
-	 * @param int $post_id The post id.
153
-	 */
154
-	public function save_post( $post_id ) {
174
+        // Check if user has permissions to save data.
175
+        if ( ! current_user_can( 'edit_post', $post_id ) ) {
176
+            $this->log->warn( "User can't edit posts." );
155 177
 
156
-		//region ## CHECKS.
157
-		// Add nonce for security and authentication.
158
-		$nonce_name = isset( $_POST[ self::NONCE_NAME ] ) ? (string) $_POST[ self::NONCE_NAME ] : '';
178
+            return;
179
+        }
180
+
181
+        /*
182
+		 * If this is an autosave, our form has not been submitted,
183
+		 * so we don't want to do anything.
184
+		 */
185
+        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
186
+            $this->log->trace( "Doing autosave." );
159 187
 
160
-		// Check if nonce is set.
161
-		if ( ! isset( $nonce_name ) ) {
162
-			$this->log->warn( '`nonce` not set.' );
188
+            return;
189
+        }
163 190
 
164
-			return;
165
-		}
191
+        // Check if not an autosave.
192
+        if ( wp_is_post_autosave( $post_id ) ) {
193
+            $this->log->trace( "It's an autosave." );
166 194
 
167
-		// Check if nonce is valid.
168
-		if ( ! wp_verify_nonce( $nonce_name, self::ACTION_NAME ) ) {
169
-			$this->log->warn( 'Invalid `nonce`.' );
195
+            return;
196
+        }
170 197
 
171
-			return;
172
-		}
198
+        // Check if not a revision.
199
+        if ( wp_is_post_revision( $post_id ) ) {
200
+            $this->log->trace( "It's a revision." );
173 201
 
174
-		// Check if user has permissions to save data.
175
-		if ( ! current_user_can( 'edit_post', $post_id ) ) {
176
-			$this->log->warn( "User can't edit posts." );
202
+            return;
203
+        }
177 204
 
178
-			return;
179
-		}
205
+        // check if there was a multisite switch before
206
+        if ( is_multisite() && ms_is_switched() ) {
207
+            $this->log->trace( "It's multisite and has been switched." );
180 208
 
181
-		/*
182
-		 * If this is an autosave, our form has not been submitted,
183
-		 * so we don't want to do anything.
184
-		 */
185
-		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
186
-			$this->log->trace( "Doing autosave." );
187
-
188
-			return;
189
-		}
190
-
191
-		// Check if not an autosave.
192
-		if ( wp_is_post_autosave( $post_id ) ) {
193
-			$this->log->trace( "It's an autosave." );
194
-
195
-			return;
196
-		}
197
-
198
-		// Check if not a revision.
199
-		if ( wp_is_post_revision( $post_id ) ) {
200
-			$this->log->trace( "It's a revision." );
201
-
202
-			return;
203
-		}
204
-
205
-		// check if there was a multisite switch before
206
-		if ( is_multisite() && ms_is_switched() ) {
207
-			$this->log->trace( "It's multisite and has been switched." );
208
-
209
-			return;
210
-		}
211
-		//endregion
212
-
213
-		// Get only the `_wl_prop` keys.
214
-		$prop_keys = $this->schemaorg_property_service->get_keys( $post_id );
215
-
216
-		// Delete the existing properties.
217
-		foreach ( $prop_keys as $key ) {
218
-			delete_post_meta( $post_id, $key );
219
-		}
220
-
221
-		// Save the new props. The structure is:
222
-		//  - prop name
223
-		//    - instance uuid
224
-		//      - type: the prop data type.
225
-		//      - language: the prop value language.
226
-		//      - value: the prop value.
227
-		//
228
-		// `_wl_prop` is *not* Wordlift_Schemaorg_Property_Service::PREFIX.
229
-		foreach ( $_POST['_wl_prop'] as $name => $instances ) {
230
-			foreach ( $instances as $uuid => $meta ) {
231
-				foreach ( $meta as $meta_key => $meta_value ) {
232
-					if ( ! empty( $meta_value ) ) {
233
-						add_post_meta( $post_id, Wordlift_Schemaorg_Property_Service::PREFIX . "{$name}_{$uuid}_{$meta_key}", $meta_value );
234
-					}
235
-				}
236
-			}
237
-		}
209
+            return;
210
+        }
211
+        //endregion
238 212
 
239
-	}
213
+        // Get only the `_wl_prop` keys.
214
+        $prop_keys = $this->schemaorg_property_service->get_keys( $post_id );
240 215
 
241
-	/**
242
-	 * The Ajax end-point used to retrieve Schema.org properties data.
243
-	 *
244
-	 * @since 3.20.0
245
-	 */
246
-	public function schemaorg_property() {
247
-
248
-		//region ## NONCE VALIDATION.
249
-		// Check nonce, we don't send back a valid nonce if this one isn't valid, of course.
250
-		if ( ! wp_verify_nonce( $_REQUEST['_wpnonce'], 'wl_schemaorg_property' ) ) {
251
-			wp_send_json_error( array(
252
-				'message' => '`nonce` missing or invalid.',
253
-			) );
254
-		}
255
-
256
-		$next_nonce = wp_create_nonce( 'wl_schemaorg_property' );
257
-		//endregion
258
-
259
-		// Check that a `term_id` has been provided.
260
-		if ( empty( $_REQUEST['term_id'] ) ) {
261
-			wp_send_json_error( array(
262
-				'_wpnonce' => $next_nonce,
263
-				'message'  => '`term_id` missing or invalid.',
264
-			) );
265
-		}
266
-
267
-		// Get the class names from the term ids.
268
-		$class_names = array_map( function ( $term_id ) {
269
-			$sanitized = intval( $term_id );
270
-
271
-			return get_term_meta( $sanitized, Wordlift_Schemaorg_Class_Service::NAME_META_KEY, true );
272
-		}, $_REQUEST['term_id'] );
273
-
274
-		// Encode the class names as a json array.
275
-		$class_names_as_json_array = wp_json_encode( $class_names );
276
-
277
-		// Prepare the GraphQL query.
278
-		$query = "query {
216
+        // Delete the existing properties.
217
+        foreach ( $prop_keys as $key ) {
218
+            delete_post_meta( $post_id, $key );
219
+        }
220
+
221
+        // Save the new props. The structure is:
222
+        //  - prop name
223
+        //    - instance uuid
224
+        //      - type: the prop data type.
225
+        //      - language: the prop value language.
226
+        //      - value: the prop value.
227
+        //
228
+        // `_wl_prop` is *not* Wordlift_Schemaorg_Property_Service::PREFIX.
229
+        foreach ( $_POST['_wl_prop'] as $name => $instances ) {
230
+            foreach ( $instances as $uuid => $meta ) {
231
+                foreach ( $meta as $meta_key => $meta_value ) {
232
+                    if ( ! empty( $meta_value ) ) {
233
+                        add_post_meta( $post_id, Wordlift_Schemaorg_Property_Service::PREFIX . "{$name}_{$uuid}_{$meta_key}", $meta_value );
234
+                    }
235
+                }
236
+            }
237
+        }
238
+
239
+    }
240
+
241
+    /**
242
+     * The Ajax end-point used to retrieve Schema.org properties data.
243
+     *
244
+     * @since 3.20.0
245
+     */
246
+    public function schemaorg_property() {
247
+
248
+        //region ## NONCE VALIDATION.
249
+        // Check nonce, we don't send back a valid nonce if this one isn't valid, of course.
250
+        if ( ! wp_verify_nonce( $_REQUEST['_wpnonce'], 'wl_schemaorg_property' ) ) {
251
+            wp_send_json_error( array(
252
+                'message' => '`nonce` missing or invalid.',
253
+            ) );
254
+        }
255
+
256
+        $next_nonce = wp_create_nonce( 'wl_schemaorg_property' );
257
+        //endregion
258
+
259
+        // Check that a `term_id` has been provided.
260
+        if ( empty( $_REQUEST['term_id'] ) ) {
261
+            wp_send_json_error( array(
262
+                '_wpnonce' => $next_nonce,
263
+                'message'  => '`term_id` missing or invalid.',
264
+            ) );
265
+        }
266
+
267
+        // Get the class names from the term ids.
268
+        $class_names = array_map( function ( $term_id ) {
269
+            $sanitized = intval( $term_id );
270
+
271
+            return get_term_meta( $sanitized, Wordlift_Schemaorg_Class_Service::NAME_META_KEY, true );
272
+        }, $_REQUEST['term_id'] );
273
+
274
+        // Encode the class names as a json array.
275
+        $class_names_as_json_array = wp_json_encode( $class_names );
276
+
277
+        // Prepare the GraphQL query.
278
+        $query = "query {
279 279
 	schemaProperties(classes: $class_names_as_json_array) {
280 280
 		name label description weight ranges {
281 281
             name label
@@ -283,66 +283,66 @@  discard block
 block discarded – undo
283 283
 	}
284 284
 }";
285 285
 
286
-		// Send the request to the remote server.
287
-		$reply = wp_remote_post( 'http://turin.wordlift.it:41660/graphql', array(
288
-			'headers' => array(
289
-				'Content-Type' => 'application/json; charset=UTF-8',
290
-			),
291
-			'body'    => wp_json_encode( array(
292
-				'query'     => $query,
293
-				'variables' => null,
294
-			) ),
295
-		) );
296
-
297
-		// If the response is empty return an error.
298
-		if ( empty( $reply['body'] ) ) {
299
-			wp_send_json_error();
300
-		}
301
-
302
-		// Decode the response.
303
-		$json = json_decode( $reply['body'], true );
304
-
305
-		// Remove unsupported ranges.
306
-		$json['schemaProperties'] = array_map( function ( $item ) {
307
-			// Remove unsupported ranges.
308
-			$item['ranges'] = array_values( array_filter( $item['ranges'], function ( $range ) {
309
-				return in_array( $range['name'], Wordlift_Admin_Schemaorg_Property_Metabox::$supported_ranges );
310
-			} ) );
311
-
312
-			return $item;
313
-		}, $json['schemaProperties'] );
314
-
315
-		// Remove unwanted properties (properties from the `Thing` entity type).
316
-		$json['schemaProperties'] = array_values( array_filter( $json['schemaProperties'], function ( $item ) {
317
-			return 0 < count( $item['ranges'] ) && ! in_array( $item['name'], Wordlift_Admin_Schemaorg_Property_Metabox::$unsupported_properties );
318
-		} ) );
319
-
320
-		/**
321
-		 * Filter: wl_schemaorg_properties_for_classes.
322
-		 *
323
-		 * @since 3.20.0
324
-		 *
325
-		 * @param array $json A json instance as array.
326
-		 * @param array $classes An array of Schema.org classes.
327
-		 */
328
-		$properties = apply_filters( 'wl_schemaorg_properties_for_classes', $json, $class_names );
329
-
330
-		// Finally output the response.
331
-		wp_send_json_success( $properties );
332
-
333
-	}
286
+        // Send the request to the remote server.
287
+        $reply = wp_remote_post( 'http://turin.wordlift.it:41660/graphql', array(
288
+            'headers' => array(
289
+                'Content-Type' => 'application/json; charset=UTF-8',
290
+            ),
291
+            'body'    => wp_json_encode( array(
292
+                'query'     => $query,
293
+                'variables' => null,
294
+            ) ),
295
+        ) );
296
+
297
+        // If the response is empty return an error.
298
+        if ( empty( $reply['body'] ) ) {
299
+            wp_send_json_error();
300
+        }
334 301
 
335
-	/**
336
-	 * Render the metabox.
337
-	 *
338
-	 * @since 3.20.0
339
-	 */
340
-	public function render() {
341
-		?>
302
+        // Decode the response.
303
+        $json = json_decode( $reply['body'], true );
304
+
305
+        // Remove unsupported ranges.
306
+        $json['schemaProperties'] = array_map( function ( $item ) {
307
+            // Remove unsupported ranges.
308
+            $item['ranges'] = array_values( array_filter( $item['ranges'], function ( $range ) {
309
+                return in_array( $range['name'], Wordlift_Admin_Schemaorg_Property_Metabox::$supported_ranges );
310
+            } ) );
311
+
312
+            return $item;
313
+        }, $json['schemaProperties'] );
314
+
315
+        // Remove unwanted properties (properties from the `Thing` entity type).
316
+        $json['schemaProperties'] = array_values( array_filter( $json['schemaProperties'], function ( $item ) {
317
+            return 0 < count( $item['ranges'] ) && ! in_array( $item['name'], Wordlift_Admin_Schemaorg_Property_Metabox::$unsupported_properties );
318
+        } ) );
319
+
320
+        /**
321
+         * Filter: wl_schemaorg_properties_for_classes.
322
+         *
323
+         * @since 3.20.0
324
+         *
325
+         * @param array $json A json instance as array.
326
+         * @param array $classes An array of Schema.org classes.
327
+         */
328
+        $properties = apply_filters( 'wl_schemaorg_properties_for_classes', $json, $class_names );
329
+
330
+        // Finally output the response.
331
+        wp_send_json_success( $properties );
332
+
333
+    }
334
+
335
+    /**
336
+     * Render the metabox.
337
+     *
338
+     * @since 3.20.0
339
+     */
340
+    public function render() {
341
+        ?>
342 342
         <input type="hidden" name="<?php echo self::NONCE_NAME; ?>"
343 343
                value="<?php echo wp_create_nonce( self::ACTION_NAME ); ?>"/>
344 344
         <div id="wl-schema-properties-form"></div>
345 345
 		<?php
346
-	}
346
+    }
347 347
 
348 348
 }
Please login to merge, or discard this patch.
Spacing   +62 added lines, -62 removed lines patch added patch discarded remove patch
@@ -99,18 +99,18 @@  discard block
 block discarded – undo
99 99
 	 *
100 100
 	 * @param \Wordlift_Schemaorg_Property_Service $schemaorg_property_service The {@link Wordlift_Schemaorg_Property_Service} instance.
101 101
 	 */
102
-	public function __construct( $schemaorg_property_service ) {
102
+	public function __construct($schemaorg_property_service) {
103 103
 
104
-		$this->log = Wordlift_Log_Service::get_logger( get_class() );
104
+		$this->log = Wordlift_Log_Service::get_logger(get_class());
105 105
 
106 106
 		// Add a hook to display the Schema.org properties metabox.
107
-		add_action( 'add_meta_boxes', array( $this, 'add_meta_boxes' ) );
107
+		add_action('add_meta_boxes', array($this, 'add_meta_boxes'));
108 108
 
109 109
 		// Add a hook to save the properties.
110
-		add_action( 'save_post', array( $this, 'save_post' ) );
110
+		add_action('save_post', array($this, 'save_post'));
111 111
 
112 112
 		// Add a hook to provide an Ajax end-point to load the Schema.org properties.
113
-		add_action( 'wp_ajax_wl_schemaorg_property', array( $this, 'schemaorg_property' ) );
113
+		add_action('wp_ajax_wl_schemaorg_property', array($this, 'schemaorg_property'));
114 114
 
115 115
 		$this->schemaorg_property_service = $schemaorg_property_service;
116 116
 
@@ -123,18 +123,18 @@  discard block
 block discarded – undo
123 123
 	 *
124 124
 	 * @param string $post_type The current post type.
125 125
 	 */
126
-	public function add_meta_boxes( $post_type ) {
126
+	public function add_meta_boxes($post_type) {
127 127
 
128 128
 		// Bail out if the `post_type` isn't a valid entity post type.
129
-		if ( ! Wordlift_Entity_Type_Service::is_valid_entity_post_type( $post_type ) ) {
129
+		if ( ! Wordlift_Entity_Type_Service::is_valid_entity_post_type($post_type)) {
130 130
 			return;
131 131
 		}
132 132
 
133 133
 		// Add our metabox configuration.
134 134
 		add_meta_box(
135 135
 			'wl-schemaorg-property',
136
-			__( 'Schema.org Properties', 'wordlift' ),
137
-			array( $this, 'render' ),
136
+			__('Schema.org Properties', 'wordlift'),
137
+			array($this, 'render'),
138 138
 			$post_type,
139 139
 			'normal',
140 140
 			'default'
@@ -151,29 +151,29 @@  discard block
 block discarded – undo
151 151
 	 *
152 152
 	 * @param int $post_id The post id.
153 153
 	 */
154
-	public function save_post( $post_id ) {
154
+	public function save_post($post_id) {
155 155
 
156 156
 		//region ## CHECKS.
157 157
 		// Add nonce for security and authentication.
158
-		$nonce_name = isset( $_POST[ self::NONCE_NAME ] ) ? (string) $_POST[ self::NONCE_NAME ] : '';
158
+		$nonce_name = isset($_POST[self::NONCE_NAME]) ? (string) $_POST[self::NONCE_NAME] : '';
159 159
 
160 160
 		// Check if nonce is set.
161
-		if ( ! isset( $nonce_name ) ) {
162
-			$this->log->warn( '`nonce` not set.' );
161
+		if ( ! isset($nonce_name)) {
162
+			$this->log->warn('`nonce` not set.');
163 163
 
164 164
 			return;
165 165
 		}
166 166
 
167 167
 		// Check if nonce is valid.
168
-		if ( ! wp_verify_nonce( $nonce_name, self::ACTION_NAME ) ) {
169
-			$this->log->warn( 'Invalid `nonce`.' );
168
+		if ( ! wp_verify_nonce($nonce_name, self::ACTION_NAME)) {
169
+			$this->log->warn('Invalid `nonce`.');
170 170
 
171 171
 			return;
172 172
 		}
173 173
 
174 174
 		// Check if user has permissions to save data.
175
-		if ( ! current_user_can( 'edit_post', $post_id ) ) {
176
-			$this->log->warn( "User can't edit posts." );
175
+		if ( ! current_user_can('edit_post', $post_id)) {
176
+			$this->log->warn("User can't edit posts.");
177 177
 
178 178
 			return;
179 179
 		}
@@ -182,40 +182,40 @@  discard block
 block discarded – undo
182 182
 		 * If this is an autosave, our form has not been submitted,
183 183
 		 * so we don't want to do anything.
184 184
 		 */
185
-		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
186
-			$this->log->trace( "Doing autosave." );
185
+		if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
186
+			$this->log->trace("Doing autosave.");
187 187
 
188 188
 			return;
189 189
 		}
190 190
 
191 191
 		// Check if not an autosave.
192
-		if ( wp_is_post_autosave( $post_id ) ) {
193
-			$this->log->trace( "It's an autosave." );
192
+		if (wp_is_post_autosave($post_id)) {
193
+			$this->log->trace("It's an autosave.");
194 194
 
195 195
 			return;
196 196
 		}
197 197
 
198 198
 		// Check if not a revision.
199
-		if ( wp_is_post_revision( $post_id ) ) {
200
-			$this->log->trace( "It's a revision." );
199
+		if (wp_is_post_revision($post_id)) {
200
+			$this->log->trace("It's a revision.");
201 201
 
202 202
 			return;
203 203
 		}
204 204
 
205 205
 		// check if there was a multisite switch before
206
-		if ( is_multisite() && ms_is_switched() ) {
207
-			$this->log->trace( "It's multisite and has been switched." );
206
+		if (is_multisite() && ms_is_switched()) {
207
+			$this->log->trace("It's multisite and has been switched.");
208 208
 
209 209
 			return;
210 210
 		}
211 211
 		//endregion
212 212
 
213 213
 		// Get only the `_wl_prop` keys.
214
-		$prop_keys = $this->schemaorg_property_service->get_keys( $post_id );
214
+		$prop_keys = $this->schemaorg_property_service->get_keys($post_id);
215 215
 
216 216
 		// Delete the existing properties.
217
-		foreach ( $prop_keys as $key ) {
218
-			delete_post_meta( $post_id, $key );
217
+		foreach ($prop_keys as $key) {
218
+			delete_post_meta($post_id, $key);
219 219
 		}
220 220
 
221 221
 		// Save the new props. The structure is:
@@ -226,11 +226,11 @@  discard block
 block discarded – undo
226 226
 		//      - value: the prop value.
227 227
 		//
228 228
 		// `_wl_prop` is *not* Wordlift_Schemaorg_Property_Service::PREFIX.
229
-		foreach ( $_POST['_wl_prop'] as $name => $instances ) {
230
-			foreach ( $instances as $uuid => $meta ) {
231
-				foreach ( $meta as $meta_key => $meta_value ) {
232
-					if ( ! empty( $meta_value ) ) {
233
-						add_post_meta( $post_id, Wordlift_Schemaorg_Property_Service::PREFIX . "{$name}_{$uuid}_{$meta_key}", $meta_value );
229
+		foreach ($_POST['_wl_prop'] as $name => $instances) {
230
+			foreach ($instances as $uuid => $meta) {
231
+				foreach ($meta as $meta_key => $meta_value) {
232
+					if ( ! empty($meta_value)) {
233
+						add_post_meta($post_id, Wordlift_Schemaorg_Property_Service::PREFIX."{$name}_{$uuid}_{$meta_key}", $meta_value);
234 234
 					}
235 235
 				}
236 236
 			}
@@ -247,32 +247,32 @@  discard block
 block discarded – undo
247 247
 
248 248
 		//region ## NONCE VALIDATION.
249 249
 		// Check nonce, we don't send back a valid nonce if this one isn't valid, of course.
250
-		if ( ! wp_verify_nonce( $_REQUEST['_wpnonce'], 'wl_schemaorg_property' ) ) {
251
-			wp_send_json_error( array(
250
+		if ( ! wp_verify_nonce($_REQUEST['_wpnonce'], 'wl_schemaorg_property')) {
251
+			wp_send_json_error(array(
252 252
 				'message' => '`nonce` missing or invalid.',
253
-			) );
253
+			));
254 254
 		}
255 255
 
256
-		$next_nonce = wp_create_nonce( 'wl_schemaorg_property' );
256
+		$next_nonce = wp_create_nonce('wl_schemaorg_property');
257 257
 		//endregion
258 258
 
259 259
 		// Check that a `term_id` has been provided.
260
-		if ( empty( $_REQUEST['term_id'] ) ) {
261
-			wp_send_json_error( array(
260
+		if (empty($_REQUEST['term_id'])) {
261
+			wp_send_json_error(array(
262 262
 				'_wpnonce' => $next_nonce,
263 263
 				'message'  => '`term_id` missing or invalid.',
264
-			) );
264
+			));
265 265
 		}
266 266
 
267 267
 		// Get the class names from the term ids.
268
-		$class_names = array_map( function ( $term_id ) {
269
-			$sanitized = intval( $term_id );
268
+		$class_names = array_map(function($term_id) {
269
+			$sanitized = intval($term_id);
270 270
 
271
-			return get_term_meta( $sanitized, Wordlift_Schemaorg_Class_Service::NAME_META_KEY, true );
272
-		}, $_REQUEST['term_id'] );
271
+			return get_term_meta($sanitized, Wordlift_Schemaorg_Class_Service::NAME_META_KEY, true);
272
+		}, $_REQUEST['term_id']);
273 273
 
274 274
 		// Encode the class names as a json array.
275
-		$class_names_as_json_array = wp_json_encode( $class_names );
275
+		$class_names_as_json_array = wp_json_encode($class_names);
276 276
 
277 277
 		// Prepare the GraphQL query.
278 278
 		$query = "query {
@@ -284,38 +284,38 @@  discard block
 block discarded – undo
284 284
 }";
285 285
 
286 286
 		// Send the request to the remote server.
287
-		$reply = wp_remote_post( 'http://turin.wordlift.it:41660/graphql', array(
287
+		$reply = wp_remote_post('http://turin.wordlift.it:41660/graphql', array(
288 288
 			'headers' => array(
289 289
 				'Content-Type' => 'application/json; charset=UTF-8',
290 290
 			),
291
-			'body'    => wp_json_encode( array(
291
+			'body'    => wp_json_encode(array(
292 292
 				'query'     => $query,
293 293
 				'variables' => null,
294
-			) ),
295
-		) );
294
+			)),
295
+		));
296 296
 
297 297
 		// If the response is empty return an error.
298
-		if ( empty( $reply['body'] ) ) {
298
+		if (empty($reply['body'])) {
299 299
 			wp_send_json_error();
300 300
 		}
301 301
 
302 302
 		// Decode the response.
303
-		$json = json_decode( $reply['body'], true );
303
+		$json = json_decode($reply['body'], true);
304 304
 
305 305
 		// Remove unsupported ranges.
306
-		$json['schemaProperties'] = array_map( function ( $item ) {
306
+		$json['schemaProperties'] = array_map(function($item) {
307 307
 			// Remove unsupported ranges.
308
-			$item['ranges'] = array_values( array_filter( $item['ranges'], function ( $range ) {
309
-				return in_array( $range['name'], Wordlift_Admin_Schemaorg_Property_Metabox::$supported_ranges );
310
-			} ) );
308
+			$item['ranges'] = array_values(array_filter($item['ranges'], function($range) {
309
+				return in_array($range['name'], Wordlift_Admin_Schemaorg_Property_Metabox::$supported_ranges);
310
+			} ));
311 311
 
312 312
 			return $item;
313
-		}, $json['schemaProperties'] );
313
+		}, $json['schemaProperties']);
314 314
 
315 315
 		// Remove unwanted properties (properties from the `Thing` entity type).
316
-		$json['schemaProperties'] = array_values( array_filter( $json['schemaProperties'], function ( $item ) {
317
-			return 0 < count( $item['ranges'] ) && ! in_array( $item['name'], Wordlift_Admin_Schemaorg_Property_Metabox::$unsupported_properties );
318
-		} ) );
316
+		$json['schemaProperties'] = array_values(array_filter($json['schemaProperties'], function($item) {
317
+			return 0 < count($item['ranges']) && ! in_array($item['name'], Wordlift_Admin_Schemaorg_Property_Metabox::$unsupported_properties);
318
+		} ));
319 319
 
320 320
 		/**
321 321
 		 * Filter: wl_schemaorg_properties_for_classes.
@@ -325,10 +325,10 @@  discard block
 block discarded – undo
325 325
 		 * @param array $json A json instance as array.
326 326
 		 * @param array $classes An array of Schema.org classes.
327 327
 		 */
328
-		$properties = apply_filters( 'wl_schemaorg_properties_for_classes', $json, $class_names );
328
+		$properties = apply_filters('wl_schemaorg_properties_for_classes', $json, $class_names);
329 329
 
330 330
 		// Finally output the response.
331
-		wp_send_json_success( $properties );
331
+		wp_send_json_success($properties);
332 332
 
333 333
 	}
334 334
 
@@ -340,7 +340,7 @@  discard block
 block discarded – undo
340 340
 	public function render() {
341 341
 		?>
342 342
         <input type="hidden" name="<?php echo self::NONCE_NAME; ?>"
343
-               value="<?php echo wp_create_nonce( self::ACTION_NAME ); ?>"/>
343
+               value="<?php echo wp_create_nonce(self::ACTION_NAME); ?>"/>
344 344
         <div id="wl-schema-properties-form"></div>
345 345
 		<?php
346 346
 	}
Please login to merge, or discard this patch.