Completed
Pull Request — develop (#1237)
by Naveen
03:26
created
src/wordlift.php 2 patches
Indentation   +231 added lines, -231 removed lines patch added patch discarded remove patch
@@ -49,7 +49,7 @@  discard block
 block discarded – undo
49 49
 
50 50
 // If this file is called directly, abort.
51 51
 if ( ! defined( 'WPINC' ) ) {
52
-	die;
52
+    die;
53 53
 }
54 54
 
55 55
 require_once plugin_dir_path( __FILE__ ) . 'vendor/autoload.php';
@@ -72,7 +72,7 @@  discard block
 block discarded – undo
72 72
  */
73 73
 function wl_write_log( $log ) {
74 74
 
75
-	Wordlift_Log_Service::get_instance()->debug( $log );
75
+    Wordlift_Log_Service::get_instance()->debug( $log );
76 76
 
77 77
 }
78 78
 
@@ -89,7 +89,7 @@  discard block
 block discarded – undo
89 89
  */
90 90
 function wl_write_log_hide_key( $text ) {
91 91
 
92
-	return str_ireplace( wl_configuration_get_key(), '<hidden>', $text );
92
+    return str_ireplace( wl_configuration_get_key(), '<hidden>', $text );
93 93
 }
94 94
 
95 95
 /**
@@ -97,21 +97,21 @@  discard block
 block discarded – undo
97 97
  * see http://vip.wordpress.com/documentation/register-additional-html-attributes-for-tinymce-and-wp-kses/
98 98
  */
99 99
 function wordlift_allowed_post_tags() {
100
-	global $allowedposttags;
101
-
102
-	$tags           = array( 'span' );
103
-	$new_attributes = array(
104
-		'itemscope' => array(),
105
-		'itemtype'  => array(),
106
-		'itemprop'  => array(),
107
-		'itemid'    => array(),
108
-	);
109
-
110
-	foreach ( $tags as $tag ) {
111
-		if ( isset( $allowedposttags[ $tag ] ) && is_array( $allowedposttags[ $tag ] ) ) {
112
-			$allowedposttags[ $tag ] = array_merge( $allowedposttags[ $tag ], $new_attributes );
113
-		}
114
-	}
100
+    global $allowedposttags;
101
+
102
+    $tags           = array( 'span' );
103
+    $new_attributes = array(
104
+        'itemscope' => array(),
105
+        'itemtype'  => array(),
106
+        'itemprop'  => array(),
107
+        'itemid'    => array(),
108
+    );
109
+
110
+    foreach ( $tags as $tag ) {
111
+        if ( isset( $allowedposttags[ $tag ] ) && is_array( $allowedposttags[ $tag ] ) ) {
112
+            $allowedposttags[ $tag ] = array_merge( $allowedposttags[ $tag ], $new_attributes );
113
+        }
114
+    }
115 115
 }
116 116
 
117 117
 // add allowed post tags.
@@ -122,18 +122,18 @@  discard block
 block discarded – undo
122 122
  */
123 123
 function wordlift_admin_enqueue_scripts() {
124 124
 
125
-	// Added for compatibility with WordPress 3.9 (see http://make.wordpress.org/core/2014/04/16/jquery-ui-and-wpdialogs-in-wordpress-3-9/)
126
-	wp_enqueue_script( 'wpdialogs' );
127
-	wp_enqueue_style( 'wp-jquery-ui-dialog' );
125
+    // Added for compatibility with WordPress 3.9 (see http://make.wordpress.org/core/2014/04/16/jquery-ui-and-wpdialogs-in-wordpress-3-9/)
126
+    wp_enqueue_script( 'wpdialogs' );
127
+    wp_enqueue_style( 'wp-jquery-ui-dialog' );
128 128
 
129
-	wp_enqueue_style( 'wordlift-reloaded', plugin_dir_url( __FILE__ ) . 'css/wordlift-reloaded.min.css' );
129
+    wp_enqueue_style( 'wordlift-reloaded', plugin_dir_url( __FILE__ ) . 'css/wordlift-reloaded.min.css' );
130 130
 
131
-	wp_enqueue_script( 'jquery-ui-autocomplete' );
131
+    wp_enqueue_script( 'jquery-ui-autocomplete' );
132 132
 
133
-	// Disable auto-save for custom entity posts only
134
-	if ( Wordlift_Entity_Service::TYPE_NAME === get_post_type() ) {
135
-		wp_dequeue_script( 'autosave' );
136
-	}
133
+    // Disable auto-save for custom entity posts only
134
+    if ( Wordlift_Entity_Service::TYPE_NAME === get_post_type() ) {
135
+        wp_dequeue_script( 'autosave' );
136
+    }
137 137
 
138 138
 }
139 139
 
@@ -149,18 +149,18 @@  discard block
 block discarded – undo
149 149
  */
150 150
 function wordlift_allowed_html( $allowedtags, $context ) {
151 151
 
152
-	if ( 'post' !== $context ) {
153
-		return $allowedtags;
154
-	}
155
-
156
-	return array_merge_recursive( $allowedtags, array(
157
-		'span' => array(
158
-			'itemscope' => true,
159
-			'itemtype'  => true,
160
-			'itemid'    => true,
161
-			'itemprop'  => true,
162
-		),
163
-	) );
152
+    if ( 'post' !== $context ) {
153
+        return $allowedtags;
154
+    }
155
+
156
+    return array_merge_recursive( $allowedtags, array(
157
+        'span' => array(
158
+            'itemscope' => true,
159
+            'itemtype'  => true,
160
+            'itemid'    => true,
161
+            'itemprop'  => true,
162
+        ),
163
+    ) );
164 164
 }
165 165
 
166 166
 add_filter( 'wp_kses_allowed_html', 'wordlift_allowed_html', 10, 2 );
@@ -174,16 +174,16 @@  discard block
 block discarded – undo
174 174
  */
175 175
 function wl_get_coordinates( $post_id ) {
176 176
 
177
-	$latitude  = wl_schema_get_value( $post_id, 'latitude' );
178
-	$longitude = wl_schema_get_value( $post_id, 'longitude' );
177
+    $latitude  = wl_schema_get_value( $post_id, 'latitude' );
178
+    $longitude = wl_schema_get_value( $post_id, 'longitude' );
179 179
 
180
-	// DO NOT set latitude/longitude to 0/0 as default values. It's a specific
181
-	// place on the globe:"The zero/zero point of this system is located in the
182
-	// Gulf of Guinea about 625 km (390 mi) south of Tema, Ghana."
183
-	return array(
184
-		'latitude'  => isset( $latitude[0] ) && is_numeric( $latitude[0] ) ? $latitude[0] : '',
185
-		'longitude' => isset( $longitude[0] ) && is_numeric( $longitude[0] ) ? $longitude[0] : '',
186
-	);
180
+    // DO NOT set latitude/longitude to 0/0 as default values. It's a specific
181
+    // place on the globe:"The zero/zero point of this system is located in the
182
+    // Gulf of Guinea about 625 km (390 mi) south of Tema, Ghana."
183
+    return array(
184
+        'latitude'  => isset( $latitude[0] ) && is_numeric( $latitude[0] ) ? $latitude[0] : '',
185
+        'longitude' => isset( $longitude[0] ) && is_numeric( $longitude[0] ) ? $longitude[0] : '',
186
+    );
187 187
 }
188 188
 
189 189
 /**
@@ -197,9 +197,9 @@  discard block
 block discarded – undo
197 197
  */
198 198
 function wl_get_image_urls( $post_id ) {
199 199
 
200
-	return Wordlift_Storage_Factory::get_instance()
201
-	                               ->post_images()
202
-	                               ->get( $post_id );
200
+    return Wordlift_Storage_Factory::get_instance()
201
+                                    ->post_images()
202
+                                    ->get( $post_id );
203 203
 
204 204
 }
205 205
 
@@ -213,24 +213,24 @@  discard block
 block discarded – undo
213 213
  */
214 214
 function wl_get_attachment_for_source_url( $parent_post_id, $source_url ) {
215 215
 
216
-	// wl_write_log( "wl_get_attachment_for_source_url [ parent post id :: $parent_post_id ][ source url :: $source_url ]" );
216
+    // wl_write_log( "wl_get_attachment_for_source_url [ parent post id :: $parent_post_id ][ source url :: $source_url ]" );
217 217
 
218
-	$posts = get_posts( array(
219
-		'post_type'      => 'attachment',
220
-		'posts_per_page' => 1,
221
-		'post_status'    => 'any',
222
-		'post_parent'    => $parent_post_id,
223
-		'meta_key'       => 'wl_source_url',
224
-		'meta_value'     => $source_url,
225
-	) );
218
+    $posts = get_posts( array(
219
+        'post_type'      => 'attachment',
220
+        'posts_per_page' => 1,
221
+        'post_status'    => 'any',
222
+        'post_parent'    => $parent_post_id,
223
+        'meta_key'       => 'wl_source_url',
224
+        'meta_value'     => $source_url,
225
+    ) );
226 226
 
227
-	// Return the found post.
228
-	if ( 1 === count( $posts ) ) {
229
-		return $posts[0];
230
-	}
227
+    // Return the found post.
228
+    if ( 1 === count( $posts ) ) {
229
+        return $posts[0];
230
+    }
231 231
 
232
-	// Return null.
233
-	return null;
232
+    // Return null.
233
+    return null;
234 234
 }
235 235
 
236 236
 /**
@@ -241,8 +241,8 @@  discard block
 block discarded – undo
241 241
  */
242 242
 function wl_set_source_url( $post_id, $source_url ) {
243 243
 
244
-	delete_post_meta( $post_id, 'wl_source_url' );
245
-	add_post_meta( $post_id, 'wl_source_url', $source_url );
244
+    delete_post_meta( $post_id, 'wl_source_url' );
245
+    add_post_meta( $post_id, 'wl_source_url', $source_url );
246 246
 }
247 247
 
248 248
 /**
@@ -259,7 +259,7 @@  discard block
 block discarded – undo
259 259
  */
260 260
 function wl_sanitize_uri_path( $path, $char = '_' ) {
261 261
 
262
-	return Wordlift_Uri_Service::get_instance()->sanitize_path( $path, $char );
262
+    return Wordlift_Uri_Service::get_instance()->sanitize_path( $path, $char );
263 263
 }
264 264
 
265 265
 /**
@@ -271,47 +271,47 @@  discard block
 block discarded – undo
271 271
  */
272 272
 function wl_replace_item_id_with_uri( $content ) {
273 273
 
274
-	$log = Wordlift_Log_Service::get_logger( 'wl_replace_item_id_with_uri' );
275
-	$log->trace( 'Replacing item IDs with URIs...' );
274
+    $log = Wordlift_Log_Service::get_logger( 'wl_replace_item_id_with_uri' );
275
+    $log->trace( 'Replacing item IDs with URIs...' );
276 276
 
277
-	// Strip slashes, see https://core.trac.wordpress.org/ticket/21767
278
-	$content = stripslashes( $content );
277
+    // Strip slashes, see https://core.trac.wordpress.org/ticket/21767
278
+    $content = stripslashes( $content );
279 279
 
280
-	// If any match are found.
281
-	$matches = array();
282
-	if ( 0 < preg_match_all( '/ itemid="([^"]+)"/i', $content, $matches, PREG_SET_ORDER ) ) {
280
+    // If any match are found.
281
+    $matches = array();
282
+    if ( 0 < preg_match_all( '/ itemid="([^"]+)"/i', $content, $matches, PREG_SET_ORDER ) ) {
283 283
 
284
-		foreach ( $matches as $match ) {
284
+        foreach ( $matches as $match ) {
285 285
 
286
-			// Get the item ID.
287
-			$item_id = $match[1];
286
+            // Get the item ID.
287
+            $item_id = $match[1];
288 288
 
289
-			// Get the post bound to that item ID (looking both in the 'official' URI and in the 'same-as' .
290
-			$post = Wordlift_Entity_Service::get_instance()
291
-			                               ->get_entity_post_by_uri( $item_id );
289
+            // Get the post bound to that item ID (looking both in the 'official' URI and in the 'same-as' .
290
+            $post = Wordlift_Entity_Service::get_instance()
291
+                                            ->get_entity_post_by_uri( $item_id );
292 292
 
293
-			// If no entity is found, continue to the next one.
294
-			if ( null === $post ) {
295
-				continue;
296
-			}
293
+            // If no entity is found, continue to the next one.
294
+            if ( null === $post ) {
295
+                continue;
296
+            }
297 297
 
298
-			// Get the URI for that post.
299
-			$uri = wl_get_entity_uri( $post->ID );
298
+            // Get the URI for that post.
299
+            $uri = wl_get_entity_uri( $post->ID );
300 300
 
301
-			// wl_write_log( "wl_replace_item_id_with_uri [ item id :: $item_id ][ uri :: $uri ]" );
301
+            // wl_write_log( "wl_replace_item_id_with_uri [ item id :: $item_id ][ uri :: $uri ]" );
302 302
 
303
-			// If the item ID and the URI differ, replace the item ID with the URI saved in WordPress.
304
-			if ( ! empty( $uri ) && $item_id !== $uri ) {
305
-				$uri_e   = esc_html( $uri );
306
-				$content = str_replace( " itemid=\"$item_id\"", " itemid=\"$uri_e\"", $content );
307
-			}
308
-		}
309
-	}
303
+            // If the item ID and the URI differ, replace the item ID with the URI saved in WordPress.
304
+            if ( ! empty( $uri ) && $item_id !== $uri ) {
305
+                $uri_e   = esc_html( $uri );
306
+                $content = str_replace( " itemid=\"$item_id\"", " itemid=\"$uri_e\"", $content );
307
+            }
308
+        }
309
+    }
310 310
 
311
-	// Reapply slashes.
312
-	$content = addslashes( $content );
311
+    // Reapply slashes.
312
+    $content = addslashes( $content );
313 313
 
314
-	return $content;
314
+    return $content;
315 315
 }
316 316
 
317 317
 add_filter( 'content_save_pre', 'wl_replace_item_id_with_uri', 1, 1 );
@@ -374,29 +374,29 @@  discard block
 block discarded – undo
374 374
  */
375 375
 function activate_wordlift() {
376 376
 
377
-	$log = Wordlift_Log_Service::get_logger( 'activate_wordlift' );
378
-
379
-	$log->info( 'Activating WordLift...' );
380
-
381
-	require_once plugin_dir_path( __FILE__ ) . 'includes/class-wordlift-activator.php';
382
-	Wordlift_Activator::activate();
383
-
384
-	/**
385
-	 * Tell the {@link Wordlift_Http_Api} class that we're activating, to let it run activation tasks.
386
-	 *
387
-	 * @see https://github.com/insideout10/wordlift-plugin/issues/820 related issue.
388
-	 * @since 3.19.2
389
-	 */
390
-	Wordlift_Http_Api::activate();
391
-
392
-	// Ensure the post type is registered before flushing the rewrite rules.
393
-	Wordlift_Entity_Post_Type_Service::get_instance()->register();
394
-	flush_rewrite_rules();
395
-	/**
396
-	 * @since 3.27.7
397
-	 * @see https://github.com/insideout10/wordlift-plugin/issues/1214
398
-	 */
399
-	Top_Entities::activate();
377
+    $log = Wordlift_Log_Service::get_logger( 'activate_wordlift' );
378
+
379
+    $log->info( 'Activating WordLift...' );
380
+
381
+    require_once plugin_dir_path( __FILE__ ) . 'includes/class-wordlift-activator.php';
382
+    Wordlift_Activator::activate();
383
+
384
+    /**
385
+     * Tell the {@link Wordlift_Http_Api} class that we're activating, to let it run activation tasks.
386
+     *
387
+     * @see https://github.com/insideout10/wordlift-plugin/issues/820 related issue.
388
+     * @since 3.19.2
389
+     */
390
+    Wordlift_Http_Api::activate();
391
+
392
+    // Ensure the post type is registered before flushing the rewrite rules.
393
+    Wordlift_Entity_Post_Type_Service::get_instance()->register();
394
+    flush_rewrite_rules();
395
+    /**
396
+     * @since 3.27.7
397
+     * @see https://github.com/insideout10/wordlift-plugin/issues/1214
398
+     */
399
+    Top_Entities::activate();
400 400
 }
401 401
 
402 402
 /**
@@ -405,16 +405,16 @@  discard block
 block discarded – undo
405 405
  */
406 406
 function deactivate_wordlift() {
407 407
 
408
-	require_once plugin_dir_path( __FILE__ ) . 'includes/class-wordlift-deactivator.php';
409
-	Wordlift_Deactivator::deactivate();
410
-	Wordlift_Http_Api::deactivate();
411
-	Ttl_Cache_Cleaner::deactivate();
412
-	/**
413
-	 * @since 3.27.7
414
-	 * @see https://github.com/insideout10/wordlift-plugin/issues/1214
415
-	 */
416
-	Top_Entities::deactivate();
417
-	flush_rewrite_rules();
408
+    require_once plugin_dir_path( __FILE__ ) . 'includes/class-wordlift-deactivator.php';
409
+    Wordlift_Deactivator::deactivate();
410
+    Wordlift_Http_Api::deactivate();
411
+    Ttl_Cache_Cleaner::deactivate();
412
+    /**
413
+     * @since 3.27.7
414
+     * @see https://github.com/insideout10/wordlift-plugin/issues/1214
415
+     */
416
+    Top_Entities::deactivate();
417
+    flush_rewrite_rules();
418 418
 
419 419
 }
420 420
 
@@ -437,98 +437,98 @@  discard block
 block discarded – undo
437 437
  * @since    1.0.0
438 438
  */
439 439
 function run_wordlift() {
440
-	/**
441
-	 * Filter: wl_feature__enable__widgets.
442
-	 *
443
-	 * @param bool whether the widgets needed to be registered, defaults to true.
444
-	 *
445
-	 * @return bool
446
-	 * @since 3.27.6
447
-	 */
448
-	if ( apply_filters( 'wl_feature__enable__widgets', true ) ) {
449
-		add_action( 'widgets_init', 'wl_register_chord_widget' );
450
-		add_action( 'widgets_init', 'wl_register_geo_widget' );
451
-		add_action( 'widgets_init', 'wl_register_timeline_widget' );
452
-	}
453
-	add_filter( 'widget_text', 'do_shortcode' );
454
-
455
-
456
-	/**
457
-	 * Filter: wl_feature__enable__analysis
458
-	 *
459
-	 * @param bool Whether to send api request to analysis or not
460
-	 *
461
-	 * @return bool
462
-	 * @since 3.27.6
463
-	 */
464
-	if ( apply_filters( 'wl_feature__enable__analysis', true ) ) {
465
-		add_action( 'wp_ajax_wl_analyze', 'wl_ajax_analyze_action' );
466
-	} else {
467
-		add_action( 'wp_ajax_wl_analyze', 'wl_ajax_analyze_disabled_action' );
468
-	}
469
-
470
-	/*
440
+    /**
441
+     * Filter: wl_feature__enable__widgets.
442
+     *
443
+     * @param bool whether the widgets needed to be registered, defaults to true.
444
+     *
445
+     * @return bool
446
+     * @since 3.27.6
447
+     */
448
+    if ( apply_filters( 'wl_feature__enable__widgets', true ) ) {
449
+        add_action( 'widgets_init', 'wl_register_chord_widget' );
450
+        add_action( 'widgets_init', 'wl_register_geo_widget' );
451
+        add_action( 'widgets_init', 'wl_register_timeline_widget' );
452
+    }
453
+    add_filter( 'widget_text', 'do_shortcode' );
454
+
455
+
456
+    /**
457
+     * Filter: wl_feature__enable__analysis
458
+     *
459
+     * @param bool Whether to send api request to analysis or not
460
+     *
461
+     * @return bool
462
+     * @since 3.27.6
463
+     */
464
+    if ( apply_filters( 'wl_feature__enable__analysis', true ) ) {
465
+        add_action( 'wp_ajax_wl_analyze', 'wl_ajax_analyze_action' );
466
+    } else {
467
+        add_action( 'wp_ajax_wl_analyze', 'wl_ajax_analyze_disabled_action' );
468
+    }
469
+
470
+    /*
471 471
 	 * We introduce the WordLift autoloader, since we start using classes in namespaces, i.e. Wordlift\Http.
472 472
 	 *
473 473
 	 * @since 3.21.2
474 474
 	 */
475
-	wordlift_plugin_autoload_register();
475
+    wordlift_plugin_autoload_register();
476 476
 
477
-	$plugin = new Wordlift();
478
-	$plugin->run();
477
+    $plugin = new Wordlift();
478
+    $plugin->run();
479 479
 
480
-	// Initialize the TTL Cache Cleaner.
481
-	new Ttl_Cache_Cleaner();
480
+    // Initialize the TTL Cache Cleaner.
481
+    new Ttl_Cache_Cleaner();
482 482
 
483
-	// Load the new Post Adapter.
484
-	new Post_Adapter();
483
+    // Load the new Post Adapter.
484
+    new Post_Adapter();
485 485
 
486
-	// Load the API Data Hooks.
487
-	new Api_Data_Hooks();
486
+    // Load the API Data Hooks.
487
+    new Api_Data_Hooks();
488 488
 
489
-	add_action( 'plugins_loaded', function () use ( $plugin ) {
490
-		// Load early. **PLEASE NOTE** that features are applied only to calls that happen **AFTER** the `plugins_loaded`
491
-		// action.
492
-		require_once plugin_dir_path( __FILE__ ) . 'wordlift/features/index.php';
489
+    add_action( 'plugins_loaded', function () use ( $plugin ) {
490
+        // Load early. **PLEASE NOTE** that features are applied only to calls that happen **AFTER** the `plugins_loaded`
491
+        // action.
492
+        require_once plugin_dir_path( __FILE__ ) . 'wordlift/features/index.php';
493 493
 
494
-		// Licenses Images.
495
-		$user_agent                   = User_Agent::get_user_agent();
496
-		$wordlift_key                 = Wordlift_Configuration_Service::get_instance()->get_key();
497
-		$api_service                  = new Default_Api_Service( apply_filters( 'wl_api_base_url', WL_CONFIG_WORDLIFT_API_URL_DEFAULT_VALUE ), 60, $user_agent, $wordlift_key );
498
-		$image_license_factory        = new Image_License_Factory();
499
-		$image_license_service        = new Image_License_Service( $api_service, $image_license_factory );
500
-		$image_license_cache          = new Ttl_Cache( 'image-license', 86400 * 30 ); // 30 days.
501
-		$cached_image_license_service = new Cached_Image_License_Service( $image_license_service, $image_license_cache );
494
+        // Licenses Images.
495
+        $user_agent                   = User_Agent::get_user_agent();
496
+        $wordlift_key                 = Wordlift_Configuration_Service::get_instance()->get_key();
497
+        $api_service                  = new Default_Api_Service( apply_filters( 'wl_api_base_url', WL_CONFIG_WORDLIFT_API_URL_DEFAULT_VALUE ), 60, $user_agent, $wordlift_key );
498
+        $image_license_factory        = new Image_License_Factory();
499
+        $image_license_service        = new Image_License_Service( $api_service, $image_license_factory );
500
+        $image_license_cache          = new Ttl_Cache( 'image-license', 86400 * 30 ); // 30 days.
501
+        $cached_image_license_service = new Cached_Image_License_Service( $image_license_service, $image_license_cache );
502 502
 
503
-		$image_license_scheduler       = new Image_License_Scheduler( $image_license_service, $image_license_cache );
504
-		$image_license_cleanup_service = new Image_License_Cleanup_Service();
503
+        $image_license_scheduler       = new Image_License_Scheduler( $image_license_service, $image_license_cache );
504
+        $image_license_cleanup_service = new Image_License_Cleanup_Service();
505 505
 
506
-		// Get the cached data. If we have cached data, we load the notifier.
507
-		$image_license_data = $image_license_cache->get( Cached_Image_License_Service::GET_NON_PUBLIC_DOMAIN_IMAGES );
508
-		if ( null !== $image_license_data ) {
509
-			$image_license_page = new Image_License_Page( $image_license_data, Wordlift::get_instance()->get_version() );
510
-			new Image_License_Notifier( $image_license_data, $image_license_page );
511
-		}
506
+        // Get the cached data. If we have cached data, we load the notifier.
507
+        $image_license_data = $image_license_cache->get( Cached_Image_License_Service::GET_NON_PUBLIC_DOMAIN_IMAGES );
508
+        if ( null !== $image_license_data ) {
509
+            $image_license_page = new Image_License_Page( $image_license_data, Wordlift::get_instance()->get_version() );
510
+            new Image_License_Notifier( $image_license_data, $image_license_page );
511
+        }
512 512
 
513
-		$remove_all_images_task         = new Remove_All_Images_Task( $cached_image_license_service );
514
-		$remove_all_images_task_adapter = new Task_Ajax_Adapter( $remove_all_images_task );
513
+        $remove_all_images_task         = new Remove_All_Images_Task( $cached_image_license_service );
514
+        $remove_all_images_task_adapter = new Task_Ajax_Adapter( $remove_all_images_task );
515 515
 
516
-		$reload_data_task         = new Reload_Data_Task();
517
-		$reload_data_task_adapter = new Task_Ajax_Adapter( $reload_data_task );
516
+        $reload_data_task         = new Reload_Data_Task();
517
+        $reload_data_task_adapter = new Task_Ajax_Adapter( $reload_data_task );
518 518
 
519
-		$add_license_caption_or_remove_task         = new Add_License_Caption_Or_Remove_Task( $cached_image_license_service );
520
-		$add_license_caption_or_remove_task_adapter = new Task_Ajax_Adapter( $add_license_caption_or_remove_task );
519
+        $add_license_caption_or_remove_task         = new Add_License_Caption_Or_Remove_Task( $cached_image_license_service );
520
+        $add_license_caption_or_remove_task_adapter = new Task_Ajax_Adapter( $add_license_caption_or_remove_task );
521 521
 
522
-		$remove_all_images_task_page             = new Remove_All_Images_Page( new Task_Ajax_Adapters_Registry( $remove_all_images_task_adapter ), $plugin->get_version() );
523
-		$reload_data_task_page                   = new Reload_Data_Page( new Task_Ajax_Adapters_Registry( $reload_data_task_adapter ), $plugin->get_version() );
524
-		$add_license_caption_or_remove_task_page = new Add_License_Caption_Or_Remove_Page( new Task_Ajax_Adapters_Registry( $add_license_caption_or_remove_task_adapter ), $plugin->get_version() );
522
+        $remove_all_images_task_page             = new Remove_All_Images_Page( new Task_Ajax_Adapters_Registry( $remove_all_images_task_adapter ), $plugin->get_version() );
523
+        $reload_data_task_page                   = new Reload_Data_Page( new Task_Ajax_Adapters_Registry( $reload_data_task_adapter ), $plugin->get_version() );
524
+        $add_license_caption_or_remove_task_page = new Add_License_Caption_Or_Remove_Page( new Task_Ajax_Adapters_Registry( $add_license_caption_or_remove_task_adapter ), $plugin->get_version() );
525 525
 
526
-		new Wordlift_Products_Navigator_Shortcode_REST();
526
+        new Wordlift_Products_Navigator_Shortcode_REST();
527 527
 
528
-		// Register the Dataset module, requires `$api_service`.
529
-		require_once plugin_dir_path( __FILE__ ) . 'wordlift/dataset/index.php';
528
+        // Register the Dataset module, requires `$api_service`.
529
+        require_once plugin_dir_path( __FILE__ ) . 'wordlift/dataset/index.php';
530 530
 
531
-	} );
531
+    } );
532 532
 
533 533
 }
534 534
 
@@ -542,45 +542,45 @@  discard block
 block discarded – undo
542 542
  */
543 543
 function wordlift_plugin_autoload_register() {
544 544
 
545
-	spl_autoload_register( function ( $class_name ) {
545
+    spl_autoload_register( function ( $class_name ) {
546 546
 
547
-		// Bail out if these are not our classes.
548
-		if ( 0 !== strpos( $class_name, 'Wordlift\\' ) ) {
549
-			return false;
550
-		}
547
+        // Bail out if these are not our classes.
548
+        if ( 0 !== strpos( $class_name, 'Wordlift\\' ) ) {
549
+            return false;
550
+        }
551 551
 
552
-		$class_name_lc = strtolower( str_replace( '_', '-', $class_name ) );
552
+        $class_name_lc = strtolower( str_replace( '_', '-', $class_name ) );
553 553
 
554
-		preg_match( '|^(?:(.*)\\\\)?(.+?)$|', $class_name_lc, $matches );
554
+        preg_match( '|^(?:(.*)\\\\)?(.+?)$|', $class_name_lc, $matches );
555 555
 
556
-		$path = str_replace( '\\', DIRECTORY_SEPARATOR, $matches[1] );
557
-		$file = 'class-' . $matches[2] . '.php';
556
+        $path = str_replace( '\\', DIRECTORY_SEPARATOR, $matches[1] );
557
+        $file = 'class-' . $matches[2] . '.php';
558 558
 
559
-		$full_path = plugin_dir_path( __FILE__ ) . $path . DIRECTORY_SEPARATOR . $file;
559
+        $full_path = plugin_dir_path( __FILE__ ) . $path . DIRECTORY_SEPARATOR . $file;
560 560
 
561
-		if ( ! file_exists( $full_path ) ) {
562
-			echo( "Class $class_name not found at $full_path." );
561
+        if ( ! file_exists( $full_path ) ) {
562
+            echo( "Class $class_name not found at $full_path." );
563 563
 
564
-			return false;
565
-		}
564
+            return false;
565
+        }
566 566
 
567
-		require_once $full_path;
567
+        require_once $full_path;
568 568
 
569
-		return true;
570
-	} );
569
+        return true;
570
+    } );
571 571
 
572 572
 }
573 573
 
574 574
 function wl_block_categories( $categories, $post ) {
575
-	return array_merge(
576
-		$categories,
577
-		array(
578
-			array(
579
-				'slug'  => 'wordlift',
580
-				'title' => __( 'WordLift', 'wordlift' ),
581
-			),
582
-		)
583
-	);
575
+    return array_merge(
576
+        $categories,
577
+        array(
578
+            array(
579
+                'slug'  => 'wordlift',
580
+                'title' => __( 'WordLift', 'wordlift' ),
581
+            ),
582
+        )
583
+    );
584 584
 }
585 585
 
586 586
 add_filter( 'block_categories', 'wl_block_categories', 10, 2 );
Please login to merge, or discard this patch.
Spacing   +128 added lines, -128 removed lines patch added patch discarded remove patch
@@ -48,17 +48,17 @@  discard block
 block discarded – undo
48 48
 use Wordlift\Tasks\Task_Ajax_Adapters_Registry;
49 49
 
50 50
 // If this file is called directly, abort.
51
-if ( ! defined( 'WPINC' ) ) {
51
+if ( ! defined('WPINC')) {
52 52
 	die;
53 53
 }
54 54
 
55
-require_once plugin_dir_path( __FILE__ ) . 'vendor/autoload.php';
55
+require_once plugin_dir_path(__FILE__).'vendor/autoload.php';
56 56
 
57 57
 // Include WordLift constants.
58
-require_once( 'wordlift_constants.php' );
58
+require_once('wordlift_constants.php');
59 59
 
60 60
 // Load modules.
61
-require_once( 'modules/core/wordlift_core.php' );
61
+require_once('modules/core/wordlift_core.php');
62 62
 
63 63
 /**
64 64
  * Log to the debug.log file.
@@ -70,9 +70,9 @@  discard block
 block discarded – undo
70 70
  * @deprecated use Wordlift_Log_Service::get_instance()->info( $log );
71 71
  *
72 72
  */
73
-function wl_write_log( $log ) {
73
+function wl_write_log($log) {
74 74
 
75
-	Wordlift_Log_Service::get_instance()->debug( $log );
75
+	Wordlift_Log_Service::get_instance()->debug($log);
76 76
 
77 77
 }
78 78
 
@@ -87,9 +87,9 @@  discard block
 block discarded – undo
87 87
  * @since 3.0.0
88 88
  *
89 89
  */
90
-function wl_write_log_hide_key( $text ) {
90
+function wl_write_log_hide_key($text) {
91 91
 
92
-	return str_ireplace( wl_configuration_get_key(), '<hidden>', $text );
92
+	return str_ireplace(wl_configuration_get_key(), '<hidden>', $text);
93 93
 }
94 94
 
95 95
 /**
@@ -99,7 +99,7 @@  discard block
 block discarded – undo
99 99
 function wordlift_allowed_post_tags() {
100 100
 	global $allowedposttags;
101 101
 
102
-	$tags           = array( 'span' );
102
+	$tags           = array('span');
103 103
 	$new_attributes = array(
104 104
 		'itemscope' => array(),
105 105
 		'itemtype'  => array(),
@@ -107,15 +107,15 @@  discard block
 block discarded – undo
107 107
 		'itemid'    => array(),
108 108
 	);
109 109
 
110
-	foreach ( $tags as $tag ) {
111
-		if ( isset( $allowedposttags[ $tag ] ) && is_array( $allowedposttags[ $tag ] ) ) {
112
-			$allowedposttags[ $tag ] = array_merge( $allowedposttags[ $tag ], $new_attributes );
110
+	foreach ($tags as $tag) {
111
+		if (isset($allowedposttags[$tag]) && is_array($allowedposttags[$tag])) {
112
+			$allowedposttags[$tag] = array_merge($allowedposttags[$tag], $new_attributes);
113 113
 		}
114 114
 	}
115 115
 }
116 116
 
117 117
 // add allowed post tags.
118
-add_action( 'init', 'wordlift_allowed_post_tags' );
118
+add_action('init', 'wordlift_allowed_post_tags');
119 119
 
120 120
 /**
121 121
  * Register additional scripts for the admin UI.
@@ -123,21 +123,21 @@  discard block
 block discarded – undo
123 123
 function wordlift_admin_enqueue_scripts() {
124 124
 
125 125
 	// Added for compatibility with WordPress 3.9 (see http://make.wordpress.org/core/2014/04/16/jquery-ui-and-wpdialogs-in-wordpress-3-9/)
126
-	wp_enqueue_script( 'wpdialogs' );
127
-	wp_enqueue_style( 'wp-jquery-ui-dialog' );
126
+	wp_enqueue_script('wpdialogs');
127
+	wp_enqueue_style('wp-jquery-ui-dialog');
128 128
 
129
-	wp_enqueue_style( 'wordlift-reloaded', plugin_dir_url( __FILE__ ) . 'css/wordlift-reloaded.min.css' );
129
+	wp_enqueue_style('wordlift-reloaded', plugin_dir_url(__FILE__).'css/wordlift-reloaded.min.css');
130 130
 
131
-	wp_enqueue_script( 'jquery-ui-autocomplete' );
131
+	wp_enqueue_script('jquery-ui-autocomplete');
132 132
 
133 133
 	// Disable auto-save for custom entity posts only
134
-	if ( Wordlift_Entity_Service::TYPE_NAME === get_post_type() ) {
135
-		wp_dequeue_script( 'autosave' );
134
+	if (Wordlift_Entity_Service::TYPE_NAME === get_post_type()) {
135
+		wp_dequeue_script('autosave');
136 136
 	}
137 137
 
138 138
 }
139 139
 
140
-add_action( 'admin_enqueue_scripts', 'wordlift_admin_enqueue_scripts' );
140
+add_action('admin_enqueue_scripts', 'wordlift_admin_enqueue_scripts');
141 141
 
142 142
 /**
143 143
  * Hooked to *wp_kses_allowed_html* filter, adds microdata attributes.
@@ -147,23 +147,23 @@  discard block
 block discarded – undo
147 147
  *
148 148
  * @return array An array which contains allowed microdata attributes.
149 149
  */
150
-function wordlift_allowed_html( $allowedtags, $context ) {
150
+function wordlift_allowed_html($allowedtags, $context) {
151 151
 
152
-	if ( 'post' !== $context ) {
152
+	if ('post' !== $context) {
153 153
 		return $allowedtags;
154 154
 	}
155 155
 
156
-	return array_merge_recursive( $allowedtags, array(
156
+	return array_merge_recursive($allowedtags, array(
157 157
 		'span' => array(
158 158
 			'itemscope' => true,
159 159
 			'itemtype'  => true,
160 160
 			'itemid'    => true,
161 161
 			'itemprop'  => true,
162 162
 		),
163
-	) );
163
+	));
164 164
 }
165 165
 
166
-add_filter( 'wp_kses_allowed_html', 'wordlift_allowed_html', 10, 2 );
166
+add_filter('wp_kses_allowed_html', 'wordlift_allowed_html', 10, 2);
167 167
 
168 168
 /**
169 169
  * Get the coordinates for the specified post ID.
@@ -172,17 +172,17 @@  discard block
 block discarded – undo
172 172
  *
173 173
  * @return array|null An array of coordinates or null.
174 174
  */
175
-function wl_get_coordinates( $post_id ) {
175
+function wl_get_coordinates($post_id) {
176 176
 
177
-	$latitude  = wl_schema_get_value( $post_id, 'latitude' );
178
-	$longitude = wl_schema_get_value( $post_id, 'longitude' );
177
+	$latitude  = wl_schema_get_value($post_id, 'latitude');
178
+	$longitude = wl_schema_get_value($post_id, 'longitude');
179 179
 
180 180
 	// DO NOT set latitude/longitude to 0/0 as default values. It's a specific
181 181
 	// place on the globe:"The zero/zero point of this system is located in the
182 182
 	// Gulf of Guinea about 625 km (390 mi) south of Tema, Ghana."
183 183
 	return array(
184
-		'latitude'  => isset( $latitude[0] ) && is_numeric( $latitude[0] ) ? $latitude[0] : '',
185
-		'longitude' => isset( $longitude[0] ) && is_numeric( $longitude[0] ) ? $longitude[0] : '',
184
+		'latitude'  => isset($latitude[0]) && is_numeric($latitude[0]) ? $latitude[0] : '',
185
+		'longitude' => isset($longitude[0]) && is_numeric($longitude[0]) ? $longitude[0] : '',
186 186
 	);
187 187
 }
188 188
 
@@ -195,11 +195,11 @@  discard block
 block discarded – undo
195 195
  * @deprecated use Wordlift_Storage_Factory::get_instance()->post_images()->get( $post_id )
196 196
  *
197 197
  */
198
-function wl_get_image_urls( $post_id ) {
198
+function wl_get_image_urls($post_id) {
199 199
 
200 200
 	return Wordlift_Storage_Factory::get_instance()
201 201
 	                               ->post_images()
202
-	                               ->get( $post_id );
202
+	                               ->get($post_id);
203 203
 
204 204
 }
205 205
 
@@ -211,21 +211,21 @@  discard block
 block discarded – undo
211 211
  *
212 212
  * @return WP_Post|null A post instance or null if not found.
213 213
  */
214
-function wl_get_attachment_for_source_url( $parent_post_id, $source_url ) {
214
+function wl_get_attachment_for_source_url($parent_post_id, $source_url) {
215 215
 
216 216
 	// wl_write_log( "wl_get_attachment_for_source_url [ parent post id :: $parent_post_id ][ source url :: $source_url ]" );
217 217
 
218
-	$posts = get_posts( array(
218
+	$posts = get_posts(array(
219 219
 		'post_type'      => 'attachment',
220 220
 		'posts_per_page' => 1,
221 221
 		'post_status'    => 'any',
222 222
 		'post_parent'    => $parent_post_id,
223 223
 		'meta_key'       => 'wl_source_url',
224 224
 		'meta_value'     => $source_url,
225
-	) );
225
+	));
226 226
 
227 227
 	// Return the found post.
228
-	if ( 1 === count( $posts ) ) {
228
+	if (1 === count($posts)) {
229 229
 		return $posts[0];
230 230
 	}
231 231
 
@@ -239,10 +239,10 @@  discard block
 block discarded – undo
239 239
  * @param int $post_id The post ID.
240 240
  * @param string $source_url The source URL.
241 241
  */
242
-function wl_set_source_url( $post_id, $source_url ) {
242
+function wl_set_source_url($post_id, $source_url) {
243 243
 
244
-	delete_post_meta( $post_id, 'wl_source_url' );
245
-	add_post_meta( $post_id, 'wl_source_url', $source_url );
244
+	delete_post_meta($post_id, 'wl_source_url');
245
+	add_post_meta($post_id, 'wl_source_url', $source_url);
246 246
 }
247 247
 
248 248
 /**
@@ -257,9 +257,9 @@  discard block
 block discarded – undo
257 257
  * @see        https://codex.wordpress.org/Function_Reference/sanitize_title
258 258
  *
259 259
  */
260
-function wl_sanitize_uri_path( $path, $char = '_' ) {
260
+function wl_sanitize_uri_path($path, $char = '_') {
261 261
 
262
-	return Wordlift_Uri_Service::get_instance()->sanitize_path( $path, $char );
262
+	return Wordlift_Uri_Service::get_instance()->sanitize_path($path, $char);
263 263
 }
264 264
 
265 265
 /**
@@ -269,104 +269,104 @@  discard block
 block discarded – undo
269 269
  *
270 270
  * @return string The updated post content.
271 271
  */
272
-function wl_replace_item_id_with_uri( $content ) {
272
+function wl_replace_item_id_with_uri($content) {
273 273
 
274
-	$log = Wordlift_Log_Service::get_logger( 'wl_replace_item_id_with_uri' );
275
-	$log->trace( 'Replacing item IDs with URIs...' );
274
+	$log = Wordlift_Log_Service::get_logger('wl_replace_item_id_with_uri');
275
+	$log->trace('Replacing item IDs with URIs...');
276 276
 
277 277
 	// Strip slashes, see https://core.trac.wordpress.org/ticket/21767
278
-	$content = stripslashes( $content );
278
+	$content = stripslashes($content);
279 279
 
280 280
 	// If any match are found.
281 281
 	$matches = array();
282
-	if ( 0 < preg_match_all( '/ itemid="([^"]+)"/i', $content, $matches, PREG_SET_ORDER ) ) {
282
+	if (0 < preg_match_all('/ itemid="([^"]+)"/i', $content, $matches, PREG_SET_ORDER)) {
283 283
 
284
-		foreach ( $matches as $match ) {
284
+		foreach ($matches as $match) {
285 285
 
286 286
 			// Get the item ID.
287 287
 			$item_id = $match[1];
288 288
 
289 289
 			// Get the post bound to that item ID (looking both in the 'official' URI and in the 'same-as' .
290 290
 			$post = Wordlift_Entity_Service::get_instance()
291
-			                               ->get_entity_post_by_uri( $item_id );
291
+			                               ->get_entity_post_by_uri($item_id);
292 292
 
293 293
 			// If no entity is found, continue to the next one.
294
-			if ( null === $post ) {
294
+			if (null === $post) {
295 295
 				continue;
296 296
 			}
297 297
 
298 298
 			// Get the URI for that post.
299
-			$uri = wl_get_entity_uri( $post->ID );
299
+			$uri = wl_get_entity_uri($post->ID);
300 300
 
301 301
 			// wl_write_log( "wl_replace_item_id_with_uri [ item id :: $item_id ][ uri :: $uri ]" );
302 302
 
303 303
 			// If the item ID and the URI differ, replace the item ID with the URI saved in WordPress.
304
-			if ( ! empty( $uri ) && $item_id !== $uri ) {
305
-				$uri_e   = esc_html( $uri );
306
-				$content = str_replace( " itemid=\"$item_id\"", " itemid=\"$uri_e\"", $content );
304
+			if ( ! empty($uri) && $item_id !== $uri) {
305
+				$uri_e   = esc_html($uri);
306
+				$content = str_replace(" itemid=\"$item_id\"", " itemid=\"$uri_e\"", $content);
307 307
 			}
308 308
 		}
309 309
 	}
310 310
 
311 311
 	// Reapply slashes.
312
-	$content = addslashes( $content );
312
+	$content = addslashes($content);
313 313
 
314 314
 	return $content;
315 315
 }
316 316
 
317
-add_filter( 'content_save_pre', 'wl_replace_item_id_with_uri', 1, 1 );
317
+add_filter('content_save_pre', 'wl_replace_item_id_with_uri', 1, 1);
318 318
 
319
-require_once( 'wordlift_entity_functions.php' );
319
+require_once('wordlift_entity_functions.php');
320 320
 
321 321
 // add editor related methods.
322
-require_once( 'wordlift_editor.php' );
322
+require_once('wordlift_editor.php');
323 323
 
324 324
 // add the WordLift entity custom type.
325
-require_once( 'wordlift_entity_type.php' );
325
+require_once('wordlift_entity_type.php');
326 326
 
327 327
 // add callbacks on post save to notify data changes from wp to redlink triple store
328
-require_once( 'wordlift_to_redlink_data_push_callbacks.php' );
328
+require_once('wordlift_to_redlink_data_push_callbacks.php');
329 329
 
330
-require_once( 'modules/configuration/wordlift_configuration_settings.php' );
330
+require_once('modules/configuration/wordlift_configuration_settings.php');
331 331
 
332 332
 // Load modules
333
-require_once( 'modules/analyzer/wordlift_analyzer.php' );
334
-require_once( 'modules/linked_data/wordlift_linked_data.php' );
335
-require_once( 'modules/prefixes/wordlift_prefixes.php' );
333
+require_once('modules/analyzer/wordlift_analyzer.php');
334
+require_once('modules/linked_data/wordlift_linked_data.php');
335
+require_once('modules/prefixes/wordlift_prefixes.php');
336 336
 
337 337
 // Shortcodes
338 338
 
339
-require_once( 'modules/geo_widget/wordlift_geo_widget.php' );
340
-require_once( 'shortcodes/class-wordlift-shortcode-rest.php' );
341
-require_once( 'shortcodes/wordlift_shortcode_chord.php' );
342
-require_once( 'shortcodes/wordlift_shortcode_geomap.php' );
343
-require_once( 'shortcodes/wordlift_shortcode_field.php' );
344
-require_once( 'shortcodes/wordlift_shortcode_faceted_search.php' );
345
-require_once( 'shortcodes/wordlift_shortcode_navigator.php' );
346
-require_once( 'shortcodes/class-wordlift-products-navigator-shortcode-rest.php' );
339
+require_once('modules/geo_widget/wordlift_geo_widget.php');
340
+require_once('shortcodes/class-wordlift-shortcode-rest.php');
341
+require_once('shortcodes/wordlift_shortcode_chord.php');
342
+require_once('shortcodes/wordlift_shortcode_geomap.php');
343
+require_once('shortcodes/wordlift_shortcode_field.php');
344
+require_once('shortcodes/wordlift_shortcode_faceted_search.php');
345
+require_once('shortcodes/wordlift_shortcode_navigator.php');
346
+require_once('shortcodes/class-wordlift-products-navigator-shortcode-rest.php');
347 347
 
348
-require_once( 'widgets/wordlift_widget_geo.php' );
349
-require_once( 'widgets/class-wordlift-chord-widget.php' );
350
-require_once( 'widgets/wordlift_widget_timeline.php' );
348
+require_once('widgets/wordlift_widget_geo.php');
349
+require_once('widgets/class-wordlift-chord-widget.php');
350
+require_once('widgets/wordlift_widget_timeline.php');
351 351
 
352
-require_once( 'wordlift_redlink.php' );
352
+require_once('wordlift_redlink.php');
353 353
 
354 354
 // Add admin functions.
355 355
 // TODO: find a way to make 'admin' UI tests work.
356 356
 //if ( is_admin() ) {
357 357
 
358
-require_once( 'admin/wordlift_admin.php' );
359
-require_once( 'admin/wordlift_admin_edit_post.php' );
360
-require_once( 'admin/wordlift_admin_save_post.php' );
358
+require_once('admin/wordlift_admin.php');
359
+require_once('admin/wordlift_admin_edit_post.php');
360
+require_once('admin/wordlift_admin_save_post.php');
361 361
 
362 362
 // add the entities meta box.
363
-require_once( 'admin/wordlift_admin_meta_box_entities.php' );
363
+require_once('admin/wordlift_admin_meta_box_entities.php');
364 364
 
365 365
 // add the entity creation AJAX.
366
-require_once( 'admin/wordlift_admin_ajax_related_posts.php' );
366
+require_once('admin/wordlift_admin_ajax_related_posts.php');
367 367
 
368 368
 // Load the wl_chord TinyMCE button and configuration dialog.
369
-require_once( 'admin/wordlift_admin_shortcodes.php' );
369
+require_once('admin/wordlift_admin_shortcodes.php');
370 370
 
371 371
 /**
372 372
  * The code that runs during plugin activation.
@@ -374,11 +374,11 @@  discard block
 block discarded – undo
374 374
  */
375 375
 function activate_wordlift() {
376 376
 
377
-	$log = Wordlift_Log_Service::get_logger( 'activate_wordlift' );
377
+	$log = Wordlift_Log_Service::get_logger('activate_wordlift');
378 378
 
379
-	$log->info( 'Activating WordLift...' );
379
+	$log->info('Activating WordLift...');
380 380
 
381
-	require_once plugin_dir_path( __FILE__ ) . 'includes/class-wordlift-activator.php';
381
+	require_once plugin_dir_path(__FILE__).'includes/class-wordlift-activator.php';
382 382
 	Wordlift_Activator::activate();
383 383
 
384 384
 	/**
@@ -405,7 +405,7 @@  discard block
 block discarded – undo
405 405
  */
406 406
 function deactivate_wordlift() {
407 407
 
408
-	require_once plugin_dir_path( __FILE__ ) . 'includes/class-wordlift-deactivator.php';
408
+	require_once plugin_dir_path(__FILE__).'includes/class-wordlift-deactivator.php';
409 409
 	Wordlift_Deactivator::deactivate();
410 410
 	Wordlift_Http_Api::deactivate();
411 411
 	Ttl_Cache_Cleaner::deactivate();
@@ -418,14 +418,14 @@  discard block
 block discarded – undo
418 418
 
419 419
 }
420 420
 
421
-register_activation_hook( __FILE__, 'activate_wordlift' );
422
-register_deactivation_hook( __FILE__, 'deactivate_wordlift' );
421
+register_activation_hook(__FILE__, 'activate_wordlift');
422
+register_deactivation_hook(__FILE__, 'deactivate_wordlift');
423 423
 
424 424
 /**
425 425
  * The core plugin class that is used to define internationalization,
426 426
  * admin-specific hooks, and public-facing site hooks.
427 427
  */
428
-require plugin_dir_path( __FILE__ ) . 'includes/class-wordlift.php';
428
+require plugin_dir_path(__FILE__).'includes/class-wordlift.php';
429 429
 
430 430
 /**
431 431
  * Begins execution of the plugin.
@@ -445,12 +445,12 @@  discard block
 block discarded – undo
445 445
 	 * @return bool
446 446
 	 * @since 3.27.6
447 447
 	 */
448
-	if ( apply_filters( 'wl_feature__enable__widgets', true ) ) {
449
-		add_action( 'widgets_init', 'wl_register_chord_widget' );
450
-		add_action( 'widgets_init', 'wl_register_geo_widget' );
451
-		add_action( 'widgets_init', 'wl_register_timeline_widget' );
448
+	if (apply_filters('wl_feature__enable__widgets', true)) {
449
+		add_action('widgets_init', 'wl_register_chord_widget');
450
+		add_action('widgets_init', 'wl_register_geo_widget');
451
+		add_action('widgets_init', 'wl_register_timeline_widget');
452 452
 	}
453
-	add_filter( 'widget_text', 'do_shortcode' );
453
+	add_filter('widget_text', 'do_shortcode');
454 454
 
455 455
 
456 456
 	/**
@@ -461,10 +461,10 @@  discard block
 block discarded – undo
461 461
 	 * @return bool
462 462
 	 * @since 3.27.6
463 463
 	 */
464
-	if ( apply_filters( 'wl_feature__enable__analysis', true ) ) {
465
-		add_action( 'wp_ajax_wl_analyze', 'wl_ajax_analyze_action' );
464
+	if (apply_filters('wl_feature__enable__analysis', true)) {
465
+		add_action('wp_ajax_wl_analyze', 'wl_ajax_analyze_action');
466 466
 	} else {
467
-		add_action( 'wp_ajax_wl_analyze', 'wl_ajax_analyze_disabled_action' );
467
+		add_action('wp_ajax_wl_analyze', 'wl_ajax_analyze_disabled_action');
468 468
 	}
469 469
 
470 470
 	/*
@@ -486,47 +486,47 @@  discard block
 block discarded – undo
486 486
 	// Load the API Data Hooks.
487 487
 	new Api_Data_Hooks();
488 488
 
489
-	add_action( 'plugins_loaded', function () use ( $plugin ) {
489
+	add_action('plugins_loaded', function() use ($plugin) {
490 490
 		// Load early. **PLEASE NOTE** that features are applied only to calls that happen **AFTER** the `plugins_loaded`
491 491
 		// action.
492
-		require_once plugin_dir_path( __FILE__ ) . 'wordlift/features/index.php';
492
+		require_once plugin_dir_path(__FILE__).'wordlift/features/index.php';
493 493
 
494 494
 		// Licenses Images.
495 495
 		$user_agent                   = User_Agent::get_user_agent();
496 496
 		$wordlift_key                 = Wordlift_Configuration_Service::get_instance()->get_key();
497
-		$api_service                  = new Default_Api_Service( apply_filters( 'wl_api_base_url', WL_CONFIG_WORDLIFT_API_URL_DEFAULT_VALUE ), 60, $user_agent, $wordlift_key );
497
+		$api_service                  = new Default_Api_Service(apply_filters('wl_api_base_url', WL_CONFIG_WORDLIFT_API_URL_DEFAULT_VALUE), 60, $user_agent, $wordlift_key);
498 498
 		$image_license_factory        = new Image_License_Factory();
499
-		$image_license_service        = new Image_License_Service( $api_service, $image_license_factory );
500
-		$image_license_cache          = new Ttl_Cache( 'image-license', 86400 * 30 ); // 30 days.
501
-		$cached_image_license_service = new Cached_Image_License_Service( $image_license_service, $image_license_cache );
499
+		$image_license_service        = new Image_License_Service($api_service, $image_license_factory);
500
+		$image_license_cache          = new Ttl_Cache('image-license', 86400 * 30); // 30 days.
501
+		$cached_image_license_service = new Cached_Image_License_Service($image_license_service, $image_license_cache);
502 502
 
503
-		$image_license_scheduler       = new Image_License_Scheduler( $image_license_service, $image_license_cache );
503
+		$image_license_scheduler       = new Image_License_Scheduler($image_license_service, $image_license_cache);
504 504
 		$image_license_cleanup_service = new Image_License_Cleanup_Service();
505 505
 
506 506
 		// Get the cached data. If we have cached data, we load the notifier.
507
-		$image_license_data = $image_license_cache->get( Cached_Image_License_Service::GET_NON_PUBLIC_DOMAIN_IMAGES );
508
-		if ( null !== $image_license_data ) {
509
-			$image_license_page = new Image_License_Page( $image_license_data, Wordlift::get_instance()->get_version() );
510
-			new Image_License_Notifier( $image_license_data, $image_license_page );
507
+		$image_license_data = $image_license_cache->get(Cached_Image_License_Service::GET_NON_PUBLIC_DOMAIN_IMAGES);
508
+		if (null !== $image_license_data) {
509
+			$image_license_page = new Image_License_Page($image_license_data, Wordlift::get_instance()->get_version());
510
+			new Image_License_Notifier($image_license_data, $image_license_page);
511 511
 		}
512 512
 
513
-		$remove_all_images_task         = new Remove_All_Images_Task( $cached_image_license_service );
514
-		$remove_all_images_task_adapter = new Task_Ajax_Adapter( $remove_all_images_task );
513
+		$remove_all_images_task         = new Remove_All_Images_Task($cached_image_license_service);
514
+		$remove_all_images_task_adapter = new Task_Ajax_Adapter($remove_all_images_task);
515 515
 
516 516
 		$reload_data_task         = new Reload_Data_Task();
517
-		$reload_data_task_adapter = new Task_Ajax_Adapter( $reload_data_task );
517
+		$reload_data_task_adapter = new Task_Ajax_Adapter($reload_data_task);
518 518
 
519
-		$add_license_caption_or_remove_task         = new Add_License_Caption_Or_Remove_Task( $cached_image_license_service );
520
-		$add_license_caption_or_remove_task_adapter = new Task_Ajax_Adapter( $add_license_caption_or_remove_task );
519
+		$add_license_caption_or_remove_task         = new Add_License_Caption_Or_Remove_Task($cached_image_license_service);
520
+		$add_license_caption_or_remove_task_adapter = new Task_Ajax_Adapter($add_license_caption_or_remove_task);
521 521
 
522
-		$remove_all_images_task_page             = new Remove_All_Images_Page( new Task_Ajax_Adapters_Registry( $remove_all_images_task_adapter ), $plugin->get_version() );
523
-		$reload_data_task_page                   = new Reload_Data_Page( new Task_Ajax_Adapters_Registry( $reload_data_task_adapter ), $plugin->get_version() );
524
-		$add_license_caption_or_remove_task_page = new Add_License_Caption_Or_Remove_Page( new Task_Ajax_Adapters_Registry( $add_license_caption_or_remove_task_adapter ), $plugin->get_version() );
522
+		$remove_all_images_task_page             = new Remove_All_Images_Page(new Task_Ajax_Adapters_Registry($remove_all_images_task_adapter), $plugin->get_version());
523
+		$reload_data_task_page                   = new Reload_Data_Page(new Task_Ajax_Adapters_Registry($reload_data_task_adapter), $plugin->get_version());
524
+		$add_license_caption_or_remove_task_page = new Add_License_Caption_Or_Remove_Page(new Task_Ajax_Adapters_Registry($add_license_caption_or_remove_task_adapter), $plugin->get_version());
525 525
 
526 526
 		new Wordlift_Products_Navigator_Shortcode_REST();
527 527
 
528 528
 		// Register the Dataset module, requires `$api_service`.
529
-		require_once plugin_dir_path( __FILE__ ) . 'wordlift/dataset/index.php';
529
+		require_once plugin_dir_path(__FILE__).'wordlift/dataset/index.php';
530 530
 
531 531
 	} );
532 532
 
@@ -542,24 +542,24 @@  discard block
 block discarded – undo
542 542
  */
543 543
 function wordlift_plugin_autoload_register() {
544 544
 
545
-	spl_autoload_register( function ( $class_name ) {
545
+	spl_autoload_register(function($class_name) {
546 546
 
547 547
 		// Bail out if these are not our classes.
548
-		if ( 0 !== strpos( $class_name, 'Wordlift\\' ) ) {
548
+		if (0 !== strpos($class_name, 'Wordlift\\')) {
549 549
 			return false;
550 550
 		}
551 551
 
552
-		$class_name_lc = strtolower( str_replace( '_', '-', $class_name ) );
552
+		$class_name_lc = strtolower(str_replace('_', '-', $class_name));
553 553
 
554
-		preg_match( '|^(?:(.*)\\\\)?(.+?)$|', $class_name_lc, $matches );
554
+		preg_match('|^(?:(.*)\\\\)?(.+?)$|', $class_name_lc, $matches);
555 555
 
556
-		$path = str_replace( '\\', DIRECTORY_SEPARATOR, $matches[1] );
557
-		$file = 'class-' . $matches[2] . '.php';
556
+		$path = str_replace('\\', DIRECTORY_SEPARATOR, $matches[1]);
557
+		$file = 'class-'.$matches[2].'.php';
558 558
 
559
-		$full_path = plugin_dir_path( __FILE__ ) . $path . DIRECTORY_SEPARATOR . $file;
559
+		$full_path = plugin_dir_path(__FILE__).$path.DIRECTORY_SEPARATOR.$file;
560 560
 
561
-		if ( ! file_exists( $full_path ) ) {
562
-			echo( "Class $class_name not found at $full_path." );
561
+		if ( ! file_exists($full_path)) {
562
+			echo("Class $class_name not found at $full_path.");
563 563
 
564 564
 			return false;
565 565
 		}
@@ -571,16 +571,16 @@  discard block
 block discarded – undo
571 571
 
572 572
 }
573 573
 
574
-function wl_block_categories( $categories, $post ) {
574
+function wl_block_categories($categories, $post) {
575 575
 	return array_merge(
576 576
 		$categories,
577 577
 		array(
578 578
 			array(
579 579
 				'slug'  => 'wordlift',
580
-				'title' => __( 'WordLift', 'wordlift' ),
580
+				'title' => __('WordLift', 'wordlift'),
581 581
 			),
582 582
 		)
583 583
 	);
584 584
 }
585 585
 
586
-add_filter( 'block_categories', 'wl_block_categories', 10, 2 );
586
+add_filter('block_categories', 'wl_block_categories', 10, 2);
Please login to merge, or discard this patch.
src/includes/class-wordlift-languages.php 1 patch
Indentation   +282 added lines, -282 removed lines patch added patch discarded remove patch
@@ -11,7 +11,7 @@  discard block
 block discarded – undo
11 11
  */
12 12
 
13 13
 if ( ! defined( 'ABSPATH' ) ) {
14
-	exit;
14
+    exit;
15 15
 }
16 16
 
17 17
 /**
@@ -21,295 +21,295 @@  discard block
 block discarded – undo
21 21
  */
22 22
 class Wordlift_Languages {
23 23
 
24
-	/**
25
-	 * An array that will contain language codes => language names pairs. It gets lazily loaded the first time by the
26
-	 * `get_languages` function.
27
-	 *
28
-	 * @since 3.9.0
29
-	 * @var array|null An array of language codes => language names pairs or NULL if not initialized yet.
30
-	 */
31
-	private static $languages = null;
24
+    /**
25
+     * An array that will contain language codes => language names pairs. It gets lazily loaded the first time by the
26
+     * `get_languages` function.
27
+     *
28
+     * @since 3.9.0
29
+     * @var array|null An array of language codes => language names pairs or NULL if not initialized yet.
30
+     */
31
+    private static $languages = null;
32 32
 
33
-	/**
34
-	 * The list of supported language codes.
35
-	 *
36
-	 * @since 3.9.0
37
-	 *
38
-	 * @var array An array of language codes.
39
-	 */
40
-	private static $codes = array(
41
-		'ar',
42
-		'be',
43
-		'bg',
44
-		'ca',
45
-		'cs',
46
-		'da',
47
-		'de',
48
-		'el',
49
-		'en',
50
-		'es',
51
-		'et',
52
-		'fi',
53
-		'fr',
54
-		'he',
55
-		'hr',
56
-		'hu',
57
-		'id',
58
-		'is',
59
-		'it',
60
-		'lt',
61
-		'lv',
62
-		'nl',
63
-		'no',
64
-		'pl',
65
-		'pt',
66
-		'ro',
67
-		'ru',
68
-		'sk',
69
-		'sl',
70
-		'sq',
71
-		'sr',
72
-		'sv',
73
-		'tr',
74
-		'uk',
75
-		'zh-cn',
76
-	);
33
+    /**
34
+     * The list of supported language codes.
35
+     *
36
+     * @since 3.9.0
37
+     *
38
+     * @var array An array of language codes.
39
+     */
40
+    private static $codes = array(
41
+        'ar',
42
+        'be',
43
+        'bg',
44
+        'ca',
45
+        'cs',
46
+        'da',
47
+        'de',
48
+        'el',
49
+        'en',
50
+        'es',
51
+        'et',
52
+        'fi',
53
+        'fr',
54
+        'he',
55
+        'hr',
56
+        'hu',
57
+        'id',
58
+        'is',
59
+        'it',
60
+        'lt',
61
+        'lv',
62
+        'nl',
63
+        'no',
64
+        'pl',
65
+        'pt',
66
+        'ro',
67
+        'ru',
68
+        'sk',
69
+        'sl',
70
+        'sq',
71
+        'sr',
72
+        'sv',
73
+        'tr',
74
+        'uk',
75
+        'zh-cn',
76
+    );
77 77
 
78
-	/**
79
-	 * Get the list of WordLift's supported languages in an array with language code => language name pairs.
80
-	 *
81
-	 * @since 3.9.0
82
-	 *
83
-	 * @return array An array with language code => language name pairs.
84
-	 */
85
-	public static function get_languages() {
78
+    /**
79
+     * Get the list of WordLift's supported languages in an array with language code => language name pairs.
80
+     *
81
+     * @since 3.9.0
82
+     *
83
+     * @return array An array with language code => language name pairs.
84
+     */
85
+    public static function get_languages() {
86 86
 
87
-		// Lazily load the languages.
88
-		if ( null === self::$languages ) {
87
+        // Lazily load the languages.
88
+        if ( null === self::$languages ) {
89 89
 
90
-			// Get the language names from WP's own (multisite) function.
91
-			foreach ( self::$codes as $key ) {
92
-				self::$languages[ $key ] = self::format_code_lang( $key );
93
-			}
90
+            // Get the language names from WP's own (multisite) function.
91
+            foreach ( self::$codes as $key ) {
92
+                self::$languages[ $key ] = self::format_code_lang( $key );
93
+            }
94 94
 
95
-			// Sort by language name.
96
-			asort( self::$languages );
97
-		}
95
+            // Sort by language name.
96
+            asort( self::$languages );
97
+        }
98 98
 
99
-		return self::$languages;
100
-	}
99
+        return self::$languages;
100
+    }
101 101
 
102
-	/**
103
-	 * Returns the language for a language code. This function is a clone of WP's function provided in `ms.php`.
104
-	 *
105
-	 * @since 3.9.3
106
-	 *
107
-	 * @param string $code Optional. The two-letter language code. Default empty.
108
-	 *
109
-	 * @return string The language corresponding to $code if it exists. If it does not exist,
110
-	 *                then the first two letters of $code is returned.
111
-	 */
112
-	private static function format_code_lang( $code = '' ) {
113
-		$code       = strtolower( substr( $code, 0, 2 ) );
114
-		$lang_codes = array(
115
-			'aa' => 'Afar',
116
-			'ab' => 'Abkhazian',
117
-			'af' => 'Afrikaans',
118
-			'ak' => 'Akan',
119
-			'sq' => 'Albanian',
120
-			'am' => 'Amharic',
121
-			'ar' => 'Arabic',
122
-			'an' => 'Aragonese',
123
-			'hy' => 'Armenian',
124
-			'as' => 'Assamese',
125
-			'av' => 'Avaric',
126
-			'ae' => 'Avestan',
127
-			'ay' => 'Aymara',
128
-			'az' => 'Azerbaijani',
129
-			'ba' => 'Bashkir',
130
-			'bm' => 'Bambara',
131
-			'eu' => 'Basque',
132
-			'be' => 'Belarusian',
133
-			'bn' => 'Bengali',
134
-			'bh' => 'Bihari',
135
-			'bi' => 'Bislama',
136
-			'bs' => 'Bosnian',
137
-			'br' => 'Breton',
138
-			'bg' => 'Bulgarian',
139
-			'my' => 'Burmese',
140
-			'ca' => 'Catalan; Valencian',
141
-			'ch' => 'Chamorro',
142
-			'ce' => 'Chechen',
143
-			'zh' => 'Chinese',
144
-			'cu' => 'Church Slavic; Old Slavonic; Church Slavonic; Old Bulgarian; Old Church Slavonic',
145
-			'cv' => 'Chuvash',
146
-			'kw' => 'Cornish',
147
-			'co' => 'Corsican',
148
-			'cr' => 'Cree',
149
-			'cs' => 'Czech',
150
-			'da' => 'Danish',
151
-			'dv' => 'Divehi; Dhivehi; Maldivian',
152
-			'nl' => 'Dutch; Flemish',
153
-			'dz' => 'Dzongkha',
154
-			'en' => 'English',
155
-			'eo' => 'Esperanto',
156
-			'et' => 'Estonian',
157
-			'ee' => 'Ewe',
158
-			'fo' => 'Faroese',
159
-			'fj' => 'Fijjian',
160
-			'fi' => 'Finnish',
161
-			'fr' => 'French',
162
-			'fy' => 'Western Frisian',
163
-			'ff' => 'Fulah',
164
-			'ka' => 'Georgian',
165
-			'de' => 'German',
166
-			'gd' => 'Gaelic; Scottish Gaelic',
167
-			'ga' => 'Irish',
168
-			'gl' => 'Galician',
169
-			'gv' => 'Manx',
170
-			'el' => 'Greek, Modern',
171
-			'gn' => 'Guarani',
172
-			'gu' => 'Gujarati',
173
-			'ht' => 'Haitian; Haitian Creole',
174
-			'ha' => 'Hausa',
175
-			'he' => 'Hebrew',
176
-			'hz' => 'Herero',
177
-			'hi' => 'Hindi',
178
-			'ho' => 'Hiri Motu',
179
-			'hu' => 'Hungarian',
180
-			'ig' => 'Igbo',
181
-			'is' => 'Icelandic',
182
-			'io' => 'Ido',
183
-			'ii' => 'Sichuan Yi',
184
-			'iu' => 'Inuktitut',
185
-			'ie' => 'Interlingue',
186
-			'ia' => 'Interlingua (International Auxiliary Language Association)',
187
-			'id' => 'Indonesian',
188
-			'ik' => 'Inupiaq',
189
-			'it' => 'Italian',
190
-			'jv' => 'Javanese',
191
-			'ja' => 'Japanese',
192
-			'kl' => 'Kalaallisut; Greenlandic',
193
-			'kn' => 'Kannada',
194
-			'ks' => 'Kashmiri',
195
-			'kr' => 'Kanuri',
196
-			'kk' => 'Kazakh',
197
-			'km' => 'Central Khmer',
198
-			'ki' => 'Kikuyu; Gikuyu',
199
-			'rw' => 'Kinyarwanda',
200
-			'ky' => 'Kirghiz; Kyrgyz',
201
-			'kv' => 'Komi',
202
-			'kg' => 'Kongo',
203
-			'ko' => 'Korean',
204
-			'kj' => 'Kuanyama; Kwanyama',
205
-			'ku' => 'Kurdish',
206
-			'lo' => 'Lao',
207
-			'la' => 'Latin',
208
-			'lv' => 'Latvian',
209
-			'li' => 'Limburgan; Limburger; Limburgish',
210
-			'ln' => 'Lingala',
211
-			'lt' => 'Lithuanian',
212
-			'lb' => 'Luxembourgish; Letzeburgesch',
213
-			'lu' => 'Luba-Katanga',
214
-			'lg' => 'Ganda',
215
-			'mk' => 'Macedonian',
216
-			'mh' => 'Marshallese',
217
-			'ml' => 'Malayalam',
218
-			'mi' => 'Maori',
219
-			'mr' => 'Marathi',
220
-			'ms' => 'Malay',
221
-			'mg' => 'Malagasy',
222
-			'mt' => 'Maltese',
223
-			'mo' => 'Moldavian',
224
-			'mn' => 'Mongolian',
225
-			'na' => 'Nauru',
226
-			'nv' => 'Navajo; Navaho',
227
-			'nr' => 'Ndebele, South; South Ndebele',
228
-			'nd' => 'Ndebele, North; North Ndebele',
229
-			'ng' => 'Ndonga',
230
-			'ne' => 'Nepali',
231
-			'nn' => 'Norwegian Nynorsk; Nynorsk, Norwegian',
232
-			'nb' => 'Bokmål, Norwegian, Norwegian Bokmål',
233
-			'no' => 'Norwegian',
234
-			'ny' => 'Chichewa; Chewa; Nyanja',
235
-			'oc' => 'Occitan, Provençal',
236
-			'oj' => 'Ojibwa',
237
-			'or' => 'Oriya',
238
-			'om' => 'Oromo',
239
-			'os' => 'Ossetian; Ossetic',
240
-			'pa' => 'Panjabi; Punjabi',
241
-			'fa' => 'Persian',
242
-			'pi' => 'Pali',
243
-			'pl' => 'Polish',
244
-			'pt' => 'Portuguese',
245
-			'ps' => 'Pushto',
246
-			'qu' => 'Quechua',
247
-			'rm' => 'Romansh',
248
-			'ro' => 'Romanian',
249
-			'rn' => 'Rundi',
250
-			'ru' => 'Russian',
251
-			'sg' => 'Sango',
252
-			'sa' => 'Sanskrit',
253
-			'sr' => 'Serbian',
254
-			'hr' => 'Croatian',
255
-			'si' => 'Sinhala; Sinhalese',
256
-			'sk' => 'Slovak',
257
-			'sl' => 'Slovenian',
258
-			'se' => 'Northern Sami',
259
-			'sm' => 'Samoan',
260
-			'sn' => 'Shona',
261
-			'sd' => 'Sindhi',
262
-			'so' => 'Somali',
263
-			'st' => 'Sotho, Southern',
264
-			'es' => 'Spanish; Castilian',
265
-			'sc' => 'Sardinian',
266
-			'ss' => 'Swati',
267
-			'su' => 'Sundanese',
268
-			'sw' => 'Swahili',
269
-			'sv' => 'Swedish',
270
-			'ty' => 'Tahitian',
271
-			'ta' => 'Tamil',
272
-			'tt' => 'Tatar',
273
-			'te' => 'Telugu',
274
-			'tg' => 'Tajik',
275
-			'tl' => 'Tagalog',
276
-			'th' => 'Thai',
277
-			'bo' => 'Tibetan',
278
-			'ti' => 'Tigrinya',
279
-			'to' => 'Tonga (Tonga Islands)',
280
-			'tn' => 'Tswana',
281
-			'ts' => 'Tsonga',
282
-			'tk' => 'Turkmen',
283
-			'tr' => 'Turkish',
284
-			'tw' => 'Twi',
285
-			'ug' => 'Uighur; Uyghur',
286
-			'uk' => 'Ukrainian',
287
-			'ur' => 'Urdu',
288
-			'uz' => 'Uzbek',
289
-			've' => 'Venda',
290
-			'vi' => 'Vietnamese',
291
-			'vo' => 'Volapük',
292
-			'cy' => 'Welsh',
293
-			'wa' => 'Walloon',
294
-			'wo' => 'Wolof',
295
-			'xh' => 'Xhosa',
296
-			'yi' => 'Yiddish',
297
-			'yo' => 'Yoruba',
298
-			'za' => 'Zhuang; Chuang',
299
-			'zu' => 'Zulu'
300
-		);
102
+    /**
103
+     * Returns the language for a language code. This function is a clone of WP's function provided in `ms.php`.
104
+     *
105
+     * @since 3.9.3
106
+     *
107
+     * @param string $code Optional. The two-letter language code. Default empty.
108
+     *
109
+     * @return string The language corresponding to $code if it exists. If it does not exist,
110
+     *                then the first two letters of $code is returned.
111
+     */
112
+    private static function format_code_lang( $code = '' ) {
113
+        $code       = strtolower( substr( $code, 0, 2 ) );
114
+        $lang_codes = array(
115
+            'aa' => 'Afar',
116
+            'ab' => 'Abkhazian',
117
+            'af' => 'Afrikaans',
118
+            'ak' => 'Akan',
119
+            'sq' => 'Albanian',
120
+            'am' => 'Amharic',
121
+            'ar' => 'Arabic',
122
+            'an' => 'Aragonese',
123
+            'hy' => 'Armenian',
124
+            'as' => 'Assamese',
125
+            'av' => 'Avaric',
126
+            'ae' => 'Avestan',
127
+            'ay' => 'Aymara',
128
+            'az' => 'Azerbaijani',
129
+            'ba' => 'Bashkir',
130
+            'bm' => 'Bambara',
131
+            'eu' => 'Basque',
132
+            'be' => 'Belarusian',
133
+            'bn' => 'Bengali',
134
+            'bh' => 'Bihari',
135
+            'bi' => 'Bislama',
136
+            'bs' => 'Bosnian',
137
+            'br' => 'Breton',
138
+            'bg' => 'Bulgarian',
139
+            'my' => 'Burmese',
140
+            'ca' => 'Catalan; Valencian',
141
+            'ch' => 'Chamorro',
142
+            'ce' => 'Chechen',
143
+            'zh' => 'Chinese',
144
+            'cu' => 'Church Slavic; Old Slavonic; Church Slavonic; Old Bulgarian; Old Church Slavonic',
145
+            'cv' => 'Chuvash',
146
+            'kw' => 'Cornish',
147
+            'co' => 'Corsican',
148
+            'cr' => 'Cree',
149
+            'cs' => 'Czech',
150
+            'da' => 'Danish',
151
+            'dv' => 'Divehi; Dhivehi; Maldivian',
152
+            'nl' => 'Dutch; Flemish',
153
+            'dz' => 'Dzongkha',
154
+            'en' => 'English',
155
+            'eo' => 'Esperanto',
156
+            'et' => 'Estonian',
157
+            'ee' => 'Ewe',
158
+            'fo' => 'Faroese',
159
+            'fj' => 'Fijjian',
160
+            'fi' => 'Finnish',
161
+            'fr' => 'French',
162
+            'fy' => 'Western Frisian',
163
+            'ff' => 'Fulah',
164
+            'ka' => 'Georgian',
165
+            'de' => 'German',
166
+            'gd' => 'Gaelic; Scottish Gaelic',
167
+            'ga' => 'Irish',
168
+            'gl' => 'Galician',
169
+            'gv' => 'Manx',
170
+            'el' => 'Greek, Modern',
171
+            'gn' => 'Guarani',
172
+            'gu' => 'Gujarati',
173
+            'ht' => 'Haitian; Haitian Creole',
174
+            'ha' => 'Hausa',
175
+            'he' => 'Hebrew',
176
+            'hz' => 'Herero',
177
+            'hi' => 'Hindi',
178
+            'ho' => 'Hiri Motu',
179
+            'hu' => 'Hungarian',
180
+            'ig' => 'Igbo',
181
+            'is' => 'Icelandic',
182
+            'io' => 'Ido',
183
+            'ii' => 'Sichuan Yi',
184
+            'iu' => 'Inuktitut',
185
+            'ie' => 'Interlingue',
186
+            'ia' => 'Interlingua (International Auxiliary Language Association)',
187
+            'id' => 'Indonesian',
188
+            'ik' => 'Inupiaq',
189
+            'it' => 'Italian',
190
+            'jv' => 'Javanese',
191
+            'ja' => 'Japanese',
192
+            'kl' => 'Kalaallisut; Greenlandic',
193
+            'kn' => 'Kannada',
194
+            'ks' => 'Kashmiri',
195
+            'kr' => 'Kanuri',
196
+            'kk' => 'Kazakh',
197
+            'km' => 'Central Khmer',
198
+            'ki' => 'Kikuyu; Gikuyu',
199
+            'rw' => 'Kinyarwanda',
200
+            'ky' => 'Kirghiz; Kyrgyz',
201
+            'kv' => 'Komi',
202
+            'kg' => 'Kongo',
203
+            'ko' => 'Korean',
204
+            'kj' => 'Kuanyama; Kwanyama',
205
+            'ku' => 'Kurdish',
206
+            'lo' => 'Lao',
207
+            'la' => 'Latin',
208
+            'lv' => 'Latvian',
209
+            'li' => 'Limburgan; Limburger; Limburgish',
210
+            'ln' => 'Lingala',
211
+            'lt' => 'Lithuanian',
212
+            'lb' => 'Luxembourgish; Letzeburgesch',
213
+            'lu' => 'Luba-Katanga',
214
+            'lg' => 'Ganda',
215
+            'mk' => 'Macedonian',
216
+            'mh' => 'Marshallese',
217
+            'ml' => 'Malayalam',
218
+            'mi' => 'Maori',
219
+            'mr' => 'Marathi',
220
+            'ms' => 'Malay',
221
+            'mg' => 'Malagasy',
222
+            'mt' => 'Maltese',
223
+            'mo' => 'Moldavian',
224
+            'mn' => 'Mongolian',
225
+            'na' => 'Nauru',
226
+            'nv' => 'Navajo; Navaho',
227
+            'nr' => 'Ndebele, South; South Ndebele',
228
+            'nd' => 'Ndebele, North; North Ndebele',
229
+            'ng' => 'Ndonga',
230
+            'ne' => 'Nepali',
231
+            'nn' => 'Norwegian Nynorsk; Nynorsk, Norwegian',
232
+            'nb' => 'Bokmål, Norwegian, Norwegian Bokmål',
233
+            'no' => 'Norwegian',
234
+            'ny' => 'Chichewa; Chewa; Nyanja',
235
+            'oc' => 'Occitan, Provençal',
236
+            'oj' => 'Ojibwa',
237
+            'or' => 'Oriya',
238
+            'om' => 'Oromo',
239
+            'os' => 'Ossetian; Ossetic',
240
+            'pa' => 'Panjabi; Punjabi',
241
+            'fa' => 'Persian',
242
+            'pi' => 'Pali',
243
+            'pl' => 'Polish',
244
+            'pt' => 'Portuguese',
245
+            'ps' => 'Pushto',
246
+            'qu' => 'Quechua',
247
+            'rm' => 'Romansh',
248
+            'ro' => 'Romanian',
249
+            'rn' => 'Rundi',
250
+            'ru' => 'Russian',
251
+            'sg' => 'Sango',
252
+            'sa' => 'Sanskrit',
253
+            'sr' => 'Serbian',
254
+            'hr' => 'Croatian',
255
+            'si' => 'Sinhala; Sinhalese',
256
+            'sk' => 'Slovak',
257
+            'sl' => 'Slovenian',
258
+            'se' => 'Northern Sami',
259
+            'sm' => 'Samoan',
260
+            'sn' => 'Shona',
261
+            'sd' => 'Sindhi',
262
+            'so' => 'Somali',
263
+            'st' => 'Sotho, Southern',
264
+            'es' => 'Spanish; Castilian',
265
+            'sc' => 'Sardinian',
266
+            'ss' => 'Swati',
267
+            'su' => 'Sundanese',
268
+            'sw' => 'Swahili',
269
+            'sv' => 'Swedish',
270
+            'ty' => 'Tahitian',
271
+            'ta' => 'Tamil',
272
+            'tt' => 'Tatar',
273
+            'te' => 'Telugu',
274
+            'tg' => 'Tajik',
275
+            'tl' => 'Tagalog',
276
+            'th' => 'Thai',
277
+            'bo' => 'Tibetan',
278
+            'ti' => 'Tigrinya',
279
+            'to' => 'Tonga (Tonga Islands)',
280
+            'tn' => 'Tswana',
281
+            'ts' => 'Tsonga',
282
+            'tk' => 'Turkmen',
283
+            'tr' => 'Turkish',
284
+            'tw' => 'Twi',
285
+            'ug' => 'Uighur; Uyghur',
286
+            'uk' => 'Ukrainian',
287
+            'ur' => 'Urdu',
288
+            'uz' => 'Uzbek',
289
+            've' => 'Venda',
290
+            'vi' => 'Vietnamese',
291
+            'vo' => 'Volapük',
292
+            'cy' => 'Welsh',
293
+            'wa' => 'Walloon',
294
+            'wo' => 'Wolof',
295
+            'xh' => 'Xhosa',
296
+            'yi' => 'Yiddish',
297
+            'yo' => 'Yoruba',
298
+            'za' => 'Zhuang; Chuang',
299
+            'zu' => 'Zulu'
300
+        );
301 301
 
302
-		/**
303
-		 * Filters the language codes.
304
-		 *
305
-		 * @since MU
306
-		 *
307
-		 * @param array $lang_codes Key/value pair of language codes where key is the short version.
308
-		 * @param string $code A two-letter designation of the language.
309
-		 */
310
-		$lang_codes = apply_filters( 'lang_codes', $lang_codes, $code );
302
+        /**
303
+         * Filters the language codes.
304
+         *
305
+         * @since MU
306
+         *
307
+         * @param array $lang_codes Key/value pair of language codes where key is the short version.
308
+         * @param string $code A two-letter designation of the language.
309
+         */
310
+        $lang_codes = apply_filters( 'lang_codes', $lang_codes, $code );
311 311
 
312
-		return strtr( $code, $lang_codes );
313
-	}
312
+        return strtr( $code, $lang_codes );
313
+    }
314 314
 
315 315
 }
Please login to merge, or discard this patch.
src/includes/class-wordlift-entity-uri-service.php 2 patches
Indentation   +275 added lines, -275 removed lines patch added patch discarded remove patch
@@ -17,280 +17,280 @@
 block discarded – undo
17 17
  */
18 18
 class Wordlift_Entity_Uri_Service {
19 19
 
20
-	/**
21
-	 * Holds the {@link Wordlift_Entity_Uri_Service} instance.
22
-	 *
23
-	 * @since 3.21.5
24
-	 * @access private
25
-	 * @var Wordlift_Entity_Uri_Service $instance The {@link Wordlift_Entity_Uri_Service} singleton.
26
-	 */
27
-	private static $instance;
28
-
29
-	/**
30
-	 * A {@link Wordlift_Log_Service} instance.
31
-	 *
32
-	 * @since  3.16.3
33
-	 * @access private
34
-	 * @var \Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
35
-	 */
36
-	private $log;
37
-
38
-	/**
39
-	 * The {@link Wordlift_Configuration_Service} instance.
40
-	 *
41
-	 * @since  3.16.3
42
-	 * @access private
43
-	 * @var \Wordlift_Configuration_Service $configuration_service The {@link Wordlift_Configuration_Service} instance.
44
-	 */
45
-	private $configuration_service;
46
-
47
-	/**
48
-	 * An array of URIs to post ID valid for the current request.
49
-	 *
50
-	 * @since  3.16.3
51
-	 * @access private
52
-	 * @var array $uri_to_post An array of URIs to post ID valid for the current request.
53
-	 */
54
-	protected $uri_to_post;
55
-
56
-	/**
57
-	 * Create a {@link Wordlift_Entity_Uri_Service} instance.
58
-	 *
59
-	 * @param \Wordlift_Configuration_Service $configuration_service The {@link Wordlift_Configuration_Service} instance.
60
-	 *
61
-	 * @since 3.16.3
62
-	 *
63
-	 */
64
-	public function __construct( $configuration_service ) {
65
-
66
-		$this->log = Wordlift_Log_Service::get_logger( get_class() );
67
-
68
-		$this->configuration_service = $configuration_service;
69
-
70
-		// Add a filter to the `rest_post_dispatch` filter to add the wl_entity_url meta as `wl:entity_url`.
71
-		add_filter( 'rest_post_dispatch', array( $this, 'rest_post_dispatch' ) );
72
-
73
-		self::$instance = $this;
74
-
75
-	}
76
-
77
-	/**
78
-	 * Get the singleton.
79
-	 *
80
-	 * @return Wordlift_Entity_Uri_Service The singleton instance.
81
-	 * @since 3.21.5
82
-	 */
83
-	public static function get_instance() {
84
-
85
-		return self::$instance;
86
-	}
87
-
88
-	/**
89
-	 * Preload the provided URIs in the local cache.
90
-	 *
91
-	 * This function will populate the local `$uri_to_post` array by running a
92
-	 * single query with all the URIs and returning the mappings in the array.
93
-	 *
94
-	 * @param array $uris An array of URIs.
95
-	 *
96
-	 * @since 3.16.3
97
-	 *
98
-	 */
99
-	public function preload_uris( $uris ) {
100
-
101
-		// Bail out if there are no URIs.
102
-		if ( 0 === count( $uris ) ) {
103
-			return;
104
-		}
105
-
106
-		$this->log->trace( 'Preloading ' . count( $uris ) . ' URI(s)...' );
107
-
108
-		$that          = $this;
109
-		$external_uris = array_filter( $uris, function ( $item ) use ( $that ) {
110
-			return ! $that->is_internal( $item );
111
-		} );
112
-
113
-		$query_args = array(
114
-			// See https://github.com/insideout10/wordlift-plugin/issues/654.
115
-			'ignore_sticky_posts' => 1,
116
-			'cache_results'       => false,
117
-			'numberposts'         => - 1,
118
-			'post_status'         => array( 'publish', 'draft', 'private', 'future' ),
119
-			'post_type'           => Wordlift_Entity_Service::valid_entity_post_types(),
120
-			'meta_query'          => array(
121
-				array(
122
-					'key'     => WL_ENTITY_URL_META_NAME,
123
-					'value'   => $uris,
124
-					'compare' => 'IN',
125
-				),
126
-			),
127
-		);
128
-
129
-		// Only if the current uri is not an internal uri, entity search is
130
-		// performed also looking at sameAs values.
131
-		//
132
-		// This solve issues like https://github.com/insideout10/wordlift-plugin/issues/237
133
-		if ( 0 < count( $external_uris ) ) {
134
-
135
-			$query_args['meta_query']['relation'] = 'OR';
136
-			$query_args['meta_query'][]           = array(
137
-				'key'     => Wordlift_Schema_Service::FIELD_SAME_AS,
138
-				'value'   => $external_uris,
139
-				'compare' => 'IN',
140
-			);
141
-
142
-		}
143
-
144
-		// Get the posts.
145
-		$posts = get_posts( $query_args );
146
-
147
-		// Populate the array. We reinitialize the array on purpose because
148
-		// we don't want these data to long live.
149
-		$this->uri_to_post = array_reduce( $posts, function ( $carry, $item ) use ( $that ) {
150
-			$uris = array_merge(
151
-				get_post_meta( $item->ID, WL_ENTITY_URL_META_NAME ),
152
-				get_post_meta( $item->ID, Wordlift_Schema_Service::FIELD_SAME_AS )
153
-			);
154
-
155
-			return $carry
156
-			       // Get the URI related to the post and fill them with the item id.
157
-			       + array_fill_keys( $uris, $item );
158
-		}, array() );
159
-
160
-		// Add the not found URIs.
161
-		$this->uri_to_post += array_fill_keys( $uris, null );
162
-
163
-		$this->log->debug( count( $this->uri_to_post ) . " URI(s) preloaded." );
164
-
165
-	}
166
-
167
-	/**
168
-	 * Reset the URI to post local cache.
169
-	 *
170
-	 * @since 3.16.3
171
-	 */
172
-	public function reset_uris() {
173
-
174
-		$this->uri_to_post = array();
175
-
176
-	}
177
-
178
-	/**
179
-	 * Find entity posts by the entity URI. Entity as searched by their entity URI or same as.
180
-	 *
181
-	 * @param string $uri The entity URI.
182
-	 *
183
-	 * @return WP_Post|null A WP_Post instance or null if not found.
184
-	 * @since 3.2.0
185
-	 *
186
-	 */
187
-	public function get_entity( $uri ) {
188
-
189
-		$this->log->trace( "Getting an entity post for URI $uri..." );
190
-
191
-		// Check if we've been provided with a value otherwise return null.
192
-		if ( empty( $uri ) ) {
193
-			return null;
194
-		}
195
-
196
-		$this->log->debug( "Querying post for $uri..." );
197
-
198
-		$query_args = array(
199
-			// See https://github.com/insideout10/wordlift-plugin/issues/654.
200
-			'ignore_sticky_posts' => 1,
201
-			'posts_per_page'      => 1,
202
-			'post_status'         => 'any',
203
-			'post_type'           => Wordlift_Entity_Service::valid_entity_post_types(),
204
-			'meta_query'          => array(
205
-				array(
206
-					'key'     => WL_ENTITY_URL_META_NAME,
207
-					'value'   => $uri,
208
-					'compare' => '=',
209
-				),
210
-			),
211
-		);
212
-
213
-		// Only if the current uri is not an internal uri, entity search is
214
-		// performed also looking at sameAs values.
215
-		//
216
-		// This solve issues like https://github.com/insideout10/wordlift-plugin/issues/237
217
-		if ( ! $this->is_internal( $uri ) ) {
218
-
219
-			$query_args['meta_query']['relation'] = 'OR';
220
-			$query_args['meta_query'][]           = array(
221
-				'key'     => Wordlift_Schema_Service::FIELD_SAME_AS,
222
-				'value'   => $uri,
223
-				'compare' => '=',
224
-			);
225
-		}
226
-
227
-		$posts = get_posts( $query_args );
228
-
229
-		// Attempt to find post by URI (only for local entity URLs)
230
-		if ( empty( $posts ) ) {
231
-
232
-			$this->log->debug( "Finding post by $uri..." );
233
-			$postid = url_to_postid( $uri );
234
-			if ( $postid !== 0 ) {
235
-				$this->log->trace( "Found post $postid by URL" );
236
-
237
-				return get_post( $postid );
238
-			}
239
-
240
-		}
241
-
242
-		// Return null if no post is found.
243
-		if ( empty( $posts ) ) {
244
-			$this->log->warn( "No post for URI $uri." );
245
-
246
-			return null;
247
-		}
248
-
249
-		// Return the found post.
250
-		return current( $posts );
251
-	}
252
-
253
-	/**
254
-	 * Determines whether a given uri is an internal uri or not.
255
-	 *
256
-	 * @param string $uri An uri.
257
-	 *
258
-	 * @return true if the uri internal to the current dataset otherwise false.
259
-	 * @since 3.16.3
260
-	 *
261
-	 */
262
-	public function is_internal( $uri ) {
263
-
264
-		return ( 0 === strrpos( $uri, (string) $this->configuration_service->get_dataset_uri() ) );
265
-	}
266
-
267
-	/**
268
-	 * Hook to `rest_post_dispatch` to alter the response and add the `wl_entity_url` post meta as `wl:entity_url`.
269
-	 *
270
-	 * We're using this filter instead of the well known `register_meta` / `register_rest_field` because we still need
271
-	 * to provide full compatibility with WordPress 4.4+.
272
-	 *
273
-	 * @param WP_HTTP_Response $result Result to send to the client. Usually a WP_REST_Response.
274
-	 *
275
-	 * @return WP_HTTP_Response The result to send to the client.
276
-	 *
277
-	 * @since 3.23.0
278
-	 */
279
-	public function rest_post_dispatch( $result ) {
280
-
281
-		// Get a reference to the actual data.
282
-		$data = &$result->data;
283
-
284
-		// Bail out if we don't have the required parameters, or if the type is not a valid entity.
285
-		if ( ! is_array( $data ) || ! isset( $data['id'] ) || ! isset( $data['type'] )
286
-		     || ! Wordlift_Entity_Type_Service::is_valid_entity_post_type( $data['type'] ) ) {
287
-			return $result;
288
-		}
289
-
290
-		// Add the `wl:entity_url`.
291
-		$data['wl:entity_url'] = Wordlift_Entity_Service::get_instance()->get_uri( $data['id'] );
292
-
293
-		return $result;
294
-	}
20
+    /**
21
+     * Holds the {@link Wordlift_Entity_Uri_Service} instance.
22
+     *
23
+     * @since 3.21.5
24
+     * @access private
25
+     * @var Wordlift_Entity_Uri_Service $instance The {@link Wordlift_Entity_Uri_Service} singleton.
26
+     */
27
+    private static $instance;
28
+
29
+    /**
30
+     * A {@link Wordlift_Log_Service} instance.
31
+     *
32
+     * @since  3.16.3
33
+     * @access private
34
+     * @var \Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
35
+     */
36
+    private $log;
37
+
38
+    /**
39
+     * The {@link Wordlift_Configuration_Service} instance.
40
+     *
41
+     * @since  3.16.3
42
+     * @access private
43
+     * @var \Wordlift_Configuration_Service $configuration_service The {@link Wordlift_Configuration_Service} instance.
44
+     */
45
+    private $configuration_service;
46
+
47
+    /**
48
+     * An array of URIs to post ID valid for the current request.
49
+     *
50
+     * @since  3.16.3
51
+     * @access private
52
+     * @var array $uri_to_post An array of URIs to post ID valid for the current request.
53
+     */
54
+    protected $uri_to_post;
55
+
56
+    /**
57
+     * Create a {@link Wordlift_Entity_Uri_Service} instance.
58
+     *
59
+     * @param \Wordlift_Configuration_Service $configuration_service The {@link Wordlift_Configuration_Service} instance.
60
+     *
61
+     * @since 3.16.3
62
+     *
63
+     */
64
+    public function __construct( $configuration_service ) {
65
+
66
+        $this->log = Wordlift_Log_Service::get_logger( get_class() );
67
+
68
+        $this->configuration_service = $configuration_service;
69
+
70
+        // Add a filter to the `rest_post_dispatch` filter to add the wl_entity_url meta as `wl:entity_url`.
71
+        add_filter( 'rest_post_dispatch', array( $this, 'rest_post_dispatch' ) );
72
+
73
+        self::$instance = $this;
74
+
75
+    }
76
+
77
+    /**
78
+     * Get the singleton.
79
+     *
80
+     * @return Wordlift_Entity_Uri_Service The singleton instance.
81
+     * @since 3.21.5
82
+     */
83
+    public static function get_instance() {
84
+
85
+        return self::$instance;
86
+    }
87
+
88
+    /**
89
+     * Preload the provided URIs in the local cache.
90
+     *
91
+     * This function will populate the local `$uri_to_post` array by running a
92
+     * single query with all the URIs and returning the mappings in the array.
93
+     *
94
+     * @param array $uris An array of URIs.
95
+     *
96
+     * @since 3.16.3
97
+     *
98
+     */
99
+    public function preload_uris( $uris ) {
100
+
101
+        // Bail out if there are no URIs.
102
+        if ( 0 === count( $uris ) ) {
103
+            return;
104
+        }
105
+
106
+        $this->log->trace( 'Preloading ' . count( $uris ) . ' URI(s)...' );
107
+
108
+        $that          = $this;
109
+        $external_uris = array_filter( $uris, function ( $item ) use ( $that ) {
110
+            return ! $that->is_internal( $item );
111
+        } );
112
+
113
+        $query_args = array(
114
+            // See https://github.com/insideout10/wordlift-plugin/issues/654.
115
+            'ignore_sticky_posts' => 1,
116
+            'cache_results'       => false,
117
+            'numberposts'         => - 1,
118
+            'post_status'         => array( 'publish', 'draft', 'private', 'future' ),
119
+            'post_type'           => Wordlift_Entity_Service::valid_entity_post_types(),
120
+            'meta_query'          => array(
121
+                array(
122
+                    'key'     => WL_ENTITY_URL_META_NAME,
123
+                    'value'   => $uris,
124
+                    'compare' => 'IN',
125
+                ),
126
+            ),
127
+        );
128
+
129
+        // Only if the current uri is not an internal uri, entity search is
130
+        // performed also looking at sameAs values.
131
+        //
132
+        // This solve issues like https://github.com/insideout10/wordlift-plugin/issues/237
133
+        if ( 0 < count( $external_uris ) ) {
134
+
135
+            $query_args['meta_query']['relation'] = 'OR';
136
+            $query_args['meta_query'][]           = array(
137
+                'key'     => Wordlift_Schema_Service::FIELD_SAME_AS,
138
+                'value'   => $external_uris,
139
+                'compare' => 'IN',
140
+            );
141
+
142
+        }
143
+
144
+        // Get the posts.
145
+        $posts = get_posts( $query_args );
146
+
147
+        // Populate the array. We reinitialize the array on purpose because
148
+        // we don't want these data to long live.
149
+        $this->uri_to_post = array_reduce( $posts, function ( $carry, $item ) use ( $that ) {
150
+            $uris = array_merge(
151
+                get_post_meta( $item->ID, WL_ENTITY_URL_META_NAME ),
152
+                get_post_meta( $item->ID, Wordlift_Schema_Service::FIELD_SAME_AS )
153
+            );
154
+
155
+            return $carry
156
+                    // Get the URI related to the post and fill them with the item id.
157
+                   + array_fill_keys( $uris, $item );
158
+        }, array() );
159
+
160
+        // Add the not found URIs.
161
+        $this->uri_to_post += array_fill_keys( $uris, null );
162
+
163
+        $this->log->debug( count( $this->uri_to_post ) . " URI(s) preloaded." );
164
+
165
+    }
166
+
167
+    /**
168
+     * Reset the URI to post local cache.
169
+     *
170
+     * @since 3.16.3
171
+     */
172
+    public function reset_uris() {
173
+
174
+        $this->uri_to_post = array();
175
+
176
+    }
177
+
178
+    /**
179
+     * Find entity posts by the entity URI. Entity as searched by their entity URI or same as.
180
+     *
181
+     * @param string $uri The entity URI.
182
+     *
183
+     * @return WP_Post|null A WP_Post instance or null if not found.
184
+     * @since 3.2.0
185
+     *
186
+     */
187
+    public function get_entity( $uri ) {
188
+
189
+        $this->log->trace( "Getting an entity post for URI $uri..." );
190
+
191
+        // Check if we've been provided with a value otherwise return null.
192
+        if ( empty( $uri ) ) {
193
+            return null;
194
+        }
195
+
196
+        $this->log->debug( "Querying post for $uri..." );
197
+
198
+        $query_args = array(
199
+            // See https://github.com/insideout10/wordlift-plugin/issues/654.
200
+            'ignore_sticky_posts' => 1,
201
+            'posts_per_page'      => 1,
202
+            'post_status'         => 'any',
203
+            'post_type'           => Wordlift_Entity_Service::valid_entity_post_types(),
204
+            'meta_query'          => array(
205
+                array(
206
+                    'key'     => WL_ENTITY_URL_META_NAME,
207
+                    'value'   => $uri,
208
+                    'compare' => '=',
209
+                ),
210
+            ),
211
+        );
212
+
213
+        // Only if the current uri is not an internal uri, entity search is
214
+        // performed also looking at sameAs values.
215
+        //
216
+        // This solve issues like https://github.com/insideout10/wordlift-plugin/issues/237
217
+        if ( ! $this->is_internal( $uri ) ) {
218
+
219
+            $query_args['meta_query']['relation'] = 'OR';
220
+            $query_args['meta_query'][]           = array(
221
+                'key'     => Wordlift_Schema_Service::FIELD_SAME_AS,
222
+                'value'   => $uri,
223
+                'compare' => '=',
224
+            );
225
+        }
226
+
227
+        $posts = get_posts( $query_args );
228
+
229
+        // Attempt to find post by URI (only for local entity URLs)
230
+        if ( empty( $posts ) ) {
231
+
232
+            $this->log->debug( "Finding post by $uri..." );
233
+            $postid = url_to_postid( $uri );
234
+            if ( $postid !== 0 ) {
235
+                $this->log->trace( "Found post $postid by URL" );
236
+
237
+                return get_post( $postid );
238
+            }
239
+
240
+        }
241
+
242
+        // Return null if no post is found.
243
+        if ( empty( $posts ) ) {
244
+            $this->log->warn( "No post for URI $uri." );
245
+
246
+            return null;
247
+        }
248
+
249
+        // Return the found post.
250
+        return current( $posts );
251
+    }
252
+
253
+    /**
254
+     * Determines whether a given uri is an internal uri or not.
255
+     *
256
+     * @param string $uri An uri.
257
+     *
258
+     * @return true if the uri internal to the current dataset otherwise false.
259
+     * @since 3.16.3
260
+     *
261
+     */
262
+    public function is_internal( $uri ) {
263
+
264
+        return ( 0 === strrpos( $uri, (string) $this->configuration_service->get_dataset_uri() ) );
265
+    }
266
+
267
+    /**
268
+     * Hook to `rest_post_dispatch` to alter the response and add the `wl_entity_url` post meta as `wl:entity_url`.
269
+     *
270
+     * We're using this filter instead of the well known `register_meta` / `register_rest_field` because we still need
271
+     * to provide full compatibility with WordPress 4.4+.
272
+     *
273
+     * @param WP_HTTP_Response $result Result to send to the client. Usually a WP_REST_Response.
274
+     *
275
+     * @return WP_HTTP_Response The result to send to the client.
276
+     *
277
+     * @since 3.23.0
278
+     */
279
+    public function rest_post_dispatch( $result ) {
280
+
281
+        // Get a reference to the actual data.
282
+        $data = &$result->data;
283
+
284
+        // Bail out if we don't have the required parameters, or if the type is not a valid entity.
285
+        if ( ! is_array( $data ) || ! isset( $data['id'] ) || ! isset( $data['type'] )
286
+             || ! Wordlift_Entity_Type_Service::is_valid_entity_post_type( $data['type'] ) ) {
287
+            return $result;
288
+        }
289
+
290
+        // Add the `wl:entity_url`.
291
+        $data['wl:entity_url'] = Wordlift_Entity_Service::get_instance()->get_uri( $data['id'] );
292
+
293
+        return $result;
294
+    }
295 295
 
296 296
 }
Please login to merge, or discard this patch.
Spacing   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -61,14 +61,14 @@  discard block
 block discarded – undo
61 61
 	 * @since 3.16.3
62 62
 	 *
63 63
 	 */
64
-	public function __construct( $configuration_service ) {
64
+	public function __construct($configuration_service) {
65 65
 
66
-		$this->log = Wordlift_Log_Service::get_logger( get_class() );
66
+		$this->log = Wordlift_Log_Service::get_logger(get_class());
67 67
 
68 68
 		$this->configuration_service = $configuration_service;
69 69
 
70 70
 		// Add a filter to the `rest_post_dispatch` filter to add the wl_entity_url meta as `wl:entity_url`.
71
-		add_filter( 'rest_post_dispatch', array( $this, 'rest_post_dispatch' ) );
71
+		add_filter('rest_post_dispatch', array($this, 'rest_post_dispatch'));
72 72
 
73 73
 		self::$instance = $this;
74 74
 
@@ -96,26 +96,26 @@  discard block
 block discarded – undo
96 96
 	 * @since 3.16.3
97 97
 	 *
98 98
 	 */
99
-	public function preload_uris( $uris ) {
99
+	public function preload_uris($uris) {
100 100
 
101 101
 		// Bail out if there are no URIs.
102
-		if ( 0 === count( $uris ) ) {
102
+		if (0 === count($uris)) {
103 103
 			return;
104 104
 		}
105 105
 
106
-		$this->log->trace( 'Preloading ' . count( $uris ) . ' URI(s)...' );
106
+		$this->log->trace('Preloading '.count($uris).' URI(s)...');
107 107
 
108 108
 		$that          = $this;
109
-		$external_uris = array_filter( $uris, function ( $item ) use ( $that ) {
110
-			return ! $that->is_internal( $item );
109
+		$external_uris = array_filter($uris, function($item) use ($that) {
110
+			return ! $that->is_internal($item);
111 111
 		} );
112 112
 
113 113
 		$query_args = array(
114 114
 			// See https://github.com/insideout10/wordlift-plugin/issues/654.
115 115
 			'ignore_sticky_posts' => 1,
116 116
 			'cache_results'       => false,
117
-			'numberposts'         => - 1,
118
-			'post_status'         => array( 'publish', 'draft', 'private', 'future' ),
117
+			'numberposts'         => -1,
118
+			'post_status'         => array('publish', 'draft', 'private', 'future'),
119 119
 			'post_type'           => Wordlift_Entity_Service::valid_entity_post_types(),
120 120
 			'meta_query'          => array(
121 121
 				array(
@@ -130,7 +130,7 @@  discard block
 block discarded – undo
130 130
 		// performed also looking at sameAs values.
131 131
 		//
132 132
 		// This solve issues like https://github.com/insideout10/wordlift-plugin/issues/237
133
-		if ( 0 < count( $external_uris ) ) {
133
+		if (0 < count($external_uris)) {
134 134
 
135 135
 			$query_args['meta_query']['relation'] = 'OR';
136 136
 			$query_args['meta_query'][]           = array(
@@ -142,25 +142,25 @@  discard block
 block discarded – undo
142 142
 		}
143 143
 
144 144
 		// Get the posts.
145
-		$posts = get_posts( $query_args );
145
+		$posts = get_posts($query_args);
146 146
 
147 147
 		// Populate the array. We reinitialize the array on purpose because
148 148
 		// we don't want these data to long live.
149
-		$this->uri_to_post = array_reduce( $posts, function ( $carry, $item ) use ( $that ) {
149
+		$this->uri_to_post = array_reduce($posts, function($carry, $item) use ($that) {
150 150
 			$uris = array_merge(
151
-				get_post_meta( $item->ID, WL_ENTITY_URL_META_NAME ),
152
-				get_post_meta( $item->ID, Wordlift_Schema_Service::FIELD_SAME_AS )
151
+				get_post_meta($item->ID, WL_ENTITY_URL_META_NAME),
152
+				get_post_meta($item->ID, Wordlift_Schema_Service::FIELD_SAME_AS)
153 153
 			);
154 154
 
155 155
 			return $carry
156 156
 			       // Get the URI related to the post and fill them with the item id.
157
-			       + array_fill_keys( $uris, $item );
158
-		}, array() );
157
+			       + array_fill_keys($uris, $item);
158
+		}, array());
159 159
 
160 160
 		// Add the not found URIs.
161
-		$this->uri_to_post += array_fill_keys( $uris, null );
161
+		$this->uri_to_post += array_fill_keys($uris, null);
162 162
 
163
-		$this->log->debug( count( $this->uri_to_post ) . " URI(s) preloaded." );
163
+		$this->log->debug(count($this->uri_to_post)." URI(s) preloaded.");
164 164
 
165 165
 	}
166 166
 
@@ -184,16 +184,16 @@  discard block
 block discarded – undo
184 184
 	 * @since 3.2.0
185 185
 	 *
186 186
 	 */
187
-	public function get_entity( $uri ) {
187
+	public function get_entity($uri) {
188 188
 
189
-		$this->log->trace( "Getting an entity post for URI $uri..." );
189
+		$this->log->trace("Getting an entity post for URI $uri...");
190 190
 
191 191
 		// Check if we've been provided with a value otherwise return null.
192
-		if ( empty( $uri ) ) {
192
+		if (empty($uri)) {
193 193
 			return null;
194 194
 		}
195 195
 
196
-		$this->log->debug( "Querying post for $uri..." );
196
+		$this->log->debug("Querying post for $uri...");
197 197
 
198 198
 		$query_args = array(
199 199
 			// See https://github.com/insideout10/wordlift-plugin/issues/654.
@@ -214,7 +214,7 @@  discard block
 block discarded – undo
214 214
 		// performed also looking at sameAs values.
215 215
 		//
216 216
 		// This solve issues like https://github.com/insideout10/wordlift-plugin/issues/237
217
-		if ( ! $this->is_internal( $uri ) ) {
217
+		if ( ! $this->is_internal($uri)) {
218 218
 
219 219
 			$query_args['meta_query']['relation'] = 'OR';
220 220
 			$query_args['meta_query'][]           = array(
@@ -224,30 +224,30 @@  discard block
 block discarded – undo
224 224
 			);
225 225
 		}
226 226
 
227
-		$posts = get_posts( $query_args );
227
+		$posts = get_posts($query_args);
228 228
 
229 229
 		// Attempt to find post by URI (only for local entity URLs)
230
-		if ( empty( $posts ) ) {
230
+		if (empty($posts)) {
231 231
 
232
-			$this->log->debug( "Finding post by $uri..." );
233
-			$postid = url_to_postid( $uri );
234
-			if ( $postid !== 0 ) {
235
-				$this->log->trace( "Found post $postid by URL" );
232
+			$this->log->debug("Finding post by $uri...");
233
+			$postid = url_to_postid($uri);
234
+			if ($postid !== 0) {
235
+				$this->log->trace("Found post $postid by URL");
236 236
 
237
-				return get_post( $postid );
237
+				return get_post($postid);
238 238
 			}
239 239
 
240 240
 		}
241 241
 
242 242
 		// Return null if no post is found.
243
-		if ( empty( $posts ) ) {
244
-			$this->log->warn( "No post for URI $uri." );
243
+		if (empty($posts)) {
244
+			$this->log->warn("No post for URI $uri.");
245 245
 
246 246
 			return null;
247 247
 		}
248 248
 
249 249
 		// Return the found post.
250
-		return current( $posts );
250
+		return current($posts);
251 251
 	}
252 252
 
253 253
 	/**
@@ -259,9 +259,9 @@  discard block
 block discarded – undo
259 259
 	 * @since 3.16.3
260 260
 	 *
261 261
 	 */
262
-	public function is_internal( $uri ) {
262
+	public function is_internal($uri) {
263 263
 
264
-		return ( 0 === strrpos( $uri, (string) $this->configuration_service->get_dataset_uri() ) );
264
+		return (0 === strrpos($uri, (string) $this->configuration_service->get_dataset_uri()));
265 265
 	}
266 266
 
267 267
 	/**
@@ -276,19 +276,19 @@  discard block
 block discarded – undo
276 276
 	 *
277 277
 	 * @since 3.23.0
278 278
 	 */
279
-	public function rest_post_dispatch( $result ) {
279
+	public function rest_post_dispatch($result) {
280 280
 
281 281
 		// Get a reference to the actual data.
282 282
 		$data = &$result->data;
283 283
 
284 284
 		// Bail out if we don't have the required parameters, or if the type is not a valid entity.
285
-		if ( ! is_array( $data ) || ! isset( $data['id'] ) || ! isset( $data['type'] )
286
-		     || ! Wordlift_Entity_Type_Service::is_valid_entity_post_type( $data['type'] ) ) {
285
+		if ( ! is_array($data) || ! isset($data['id']) || ! isset($data['type'])
286
+		     || ! Wordlift_Entity_Type_Service::is_valid_entity_post_type($data['type'])) {
287 287
 			return $result;
288 288
 		}
289 289
 
290 290
 		// Add the `wl:entity_url`.
291
-		$data['wl:entity_url'] = Wordlift_Entity_Service::get_instance()->get_uri( $data['id'] );
291
+		$data['wl:entity_url'] = Wordlift_Entity_Service::get_instance()->get_uri($data['id']);
292 292
 
293 293
 		return $result;
294 294
 	}
Please login to merge, or discard this patch.
src/wordlift/jsonld/class-jsonld-user-service.php 2 patches
Indentation   +71 added lines, -71 removed lines patch added patch discarded remove patch
@@ -6,76 +6,76 @@
 block discarded – undo
6 6
 
7 7
 class Jsonld_User_Service {
8 8
 
9
-	/**
10
-	 * @var \Wordlift_User_Service $user_service
11
-	 */
12
-	private $user_service;
13
-
14
-	/**
15
-	 * @var Jsonld_Service
16
-	 */
17
-	private $jsonld_service;
18
-
19
-	/**
20
-	 * Jsonld_User_Service constructor.
21
-	 *
22
-	 * @param \Wordlift_User_Service $user_service
23
-	 */
24
-	function __construct( $user_service ) {
25
-		$this->user_service = $user_service;
26
-	}
27
-
28
-	/**
29
-	 * @param Jsonld_Service $jsonld_service
30
-	 */
31
-	function set_jsonld_service( $jsonld_service ) {
32
-		$this->jsonld_service = $jsonld_service;
33
-	}
34
-
35
-	function get( $user_id ) {
36
-		$userdata = get_userdata( $user_id );
37
-
38
-		// Bail out if user not found.
39
-		if ( ! ( $userdata instanceof \WP_User ) ) {
40
-			return array();
41
-		}
42
-
43
-		// Return the post JSON-LD if a post has been bound to this user.
44
-		$post_id = $this->user_service->get_entity( $user_id );
45
-		if ( ! empty( $post_id ) && isset( $this->jsonld_service ) ) {
46
-			return $this->jsonld_service->get( Object_Type_Enum::POST, $post_id );
47
-		}
48
-
49
-		// Bail out if the user doesn't have a valid URI.
50
-		$uri = $this->user_service->get_uri( $user_id );
51
-		if ( empty( $uri ) ) {
52
-			return array();
53
-		}
54
-
55
-		// Finally return the user's JSON-LD.
56
-		$data = array(
57
-			'@context' => 'http://schema.org',
58
-			'@id'      => $uri,
59
-			'@type'    => 'Person',
60
-		);
61
-
62
-		if ( ! empty( $userdata->display_name ) ) {
63
-			$data['name'] = $userdata->display_name;
64
-		}
65
-
66
-		if ( ! empty( $userdata->first_name ) ) {
67
-			$data['givenName'] = $userdata->first_name;
68
-		}
69
-
70
-		if ( ! empty( $userdata->last_name ) ) {
71
-			$data['familyName'] = $userdata->last_name;
72
-		}
73
-
74
-		if ( ! empty( $userdata->user_url ) ) {
75
-			$data['url'] = $userdata->user_url;
76
-		}
77
-
78
-		return array( $data );
79
-	}
9
+    /**
10
+     * @var \Wordlift_User_Service $user_service
11
+     */
12
+    private $user_service;
13
+
14
+    /**
15
+     * @var Jsonld_Service
16
+     */
17
+    private $jsonld_service;
18
+
19
+    /**
20
+     * Jsonld_User_Service constructor.
21
+     *
22
+     * @param \Wordlift_User_Service $user_service
23
+     */
24
+    function __construct( $user_service ) {
25
+        $this->user_service = $user_service;
26
+    }
27
+
28
+    /**
29
+     * @param Jsonld_Service $jsonld_service
30
+     */
31
+    function set_jsonld_service( $jsonld_service ) {
32
+        $this->jsonld_service = $jsonld_service;
33
+    }
34
+
35
+    function get( $user_id ) {
36
+        $userdata = get_userdata( $user_id );
37
+
38
+        // Bail out if user not found.
39
+        if ( ! ( $userdata instanceof \WP_User ) ) {
40
+            return array();
41
+        }
42
+
43
+        // Return the post JSON-LD if a post has been bound to this user.
44
+        $post_id = $this->user_service->get_entity( $user_id );
45
+        if ( ! empty( $post_id ) && isset( $this->jsonld_service ) ) {
46
+            return $this->jsonld_service->get( Object_Type_Enum::POST, $post_id );
47
+        }
48
+
49
+        // Bail out if the user doesn't have a valid URI.
50
+        $uri = $this->user_service->get_uri( $user_id );
51
+        if ( empty( $uri ) ) {
52
+            return array();
53
+        }
54
+
55
+        // Finally return the user's JSON-LD.
56
+        $data = array(
57
+            '@context' => 'http://schema.org',
58
+            '@id'      => $uri,
59
+            '@type'    => 'Person',
60
+        );
61
+
62
+        if ( ! empty( $userdata->display_name ) ) {
63
+            $data['name'] = $userdata->display_name;
64
+        }
65
+
66
+        if ( ! empty( $userdata->first_name ) ) {
67
+            $data['givenName'] = $userdata->first_name;
68
+        }
69
+
70
+        if ( ! empty( $userdata->last_name ) ) {
71
+            $data['familyName'] = $userdata->last_name;
72
+        }
73
+
74
+        if ( ! empty( $userdata->user_url ) ) {
75
+            $data['url'] = $userdata->user_url;
76
+        }
77
+
78
+        return array( $data );
79
+    }
80 80
 
81 81
 }
Please login to merge, or discard this patch.
Spacing   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -21,34 +21,34 @@  discard block
 block discarded – undo
21 21
 	 *
22 22
 	 * @param \Wordlift_User_Service $user_service
23 23
 	 */
24
-	function __construct( $user_service ) {
24
+	function __construct($user_service) {
25 25
 		$this->user_service = $user_service;
26 26
 	}
27 27
 
28 28
 	/**
29 29
 	 * @param Jsonld_Service $jsonld_service
30 30
 	 */
31
-	function set_jsonld_service( $jsonld_service ) {
31
+	function set_jsonld_service($jsonld_service) {
32 32
 		$this->jsonld_service = $jsonld_service;
33 33
 	}
34 34
 
35
-	function get( $user_id ) {
36
-		$userdata = get_userdata( $user_id );
35
+	function get($user_id) {
36
+		$userdata = get_userdata($user_id);
37 37
 
38 38
 		// Bail out if user not found.
39
-		if ( ! ( $userdata instanceof \WP_User ) ) {
39
+		if ( ! ($userdata instanceof \WP_User)) {
40 40
 			return array();
41 41
 		}
42 42
 
43 43
 		// Return the post JSON-LD if a post has been bound to this user.
44
-		$post_id = $this->user_service->get_entity( $user_id );
45
-		if ( ! empty( $post_id ) && isset( $this->jsonld_service ) ) {
46
-			return $this->jsonld_service->get( Object_Type_Enum::POST, $post_id );
44
+		$post_id = $this->user_service->get_entity($user_id);
45
+		if ( ! empty($post_id) && isset($this->jsonld_service)) {
46
+			return $this->jsonld_service->get(Object_Type_Enum::POST, $post_id);
47 47
 		}
48 48
 
49 49
 		// Bail out if the user doesn't have a valid URI.
50
-		$uri = $this->user_service->get_uri( $user_id );
51
-		if ( empty( $uri ) ) {
50
+		$uri = $this->user_service->get_uri($user_id);
51
+		if (empty($uri)) {
52 52
 			return array();
53 53
 		}
54 54
 
@@ -59,23 +59,23 @@  discard block
 block discarded – undo
59 59
 			'@type'    => 'Person',
60 60
 		);
61 61
 
62
-		if ( ! empty( $userdata->display_name ) ) {
62
+		if ( ! empty($userdata->display_name)) {
63 63
 			$data['name'] = $userdata->display_name;
64 64
 		}
65 65
 
66
-		if ( ! empty( $userdata->first_name ) ) {
66
+		if ( ! empty($userdata->first_name)) {
67 67
 			$data['givenName'] = $userdata->first_name;
68 68
 		}
69 69
 
70
-		if ( ! empty( $userdata->last_name ) ) {
70
+		if ( ! empty($userdata->last_name)) {
71 71
 			$data['familyName'] = $userdata->last_name;
72 72
 		}
73 73
 
74
-		if ( ! empty( $userdata->user_url ) ) {
74
+		if ( ! empty($userdata->user_url)) {
75 75
 			$data['url'] = $userdata->user_url;
76 76
 		}
77 77
 
78
-		return array( $data );
78
+		return array($data);
79 79
 	}
80 80
 
81 81
 }
Please login to merge, or discard this patch.
src/wordlift/autocomplete/class-local-autocomplete-service.php 2 patches
Indentation   +51 added lines, -51 removed lines patch added patch discarded remove patch
@@ -15,62 +15,62 @@
 block discarded – undo
15 15
 
16 16
 class Local_Autocomplete_Service extends Abstract_Autocomplete_Service {
17 17
 
18
-	/**
19
-	 * @inheritDoc
20
-	 */
21
-	public function query( $query, $scope, $excludes ) {
22
-		global $wpdb;
18
+    /**
19
+     * @inheritDoc
20
+     */
21
+    public function query( $query, $scope, $excludes ) {
22
+        global $wpdb;
23 23
 
24
-		$posts = $wpdb->get_results( $wpdb->prepare(
25
-			"SELECT * FROM {$wpdb->posts} p"
26
-			. " INNER JOIN {$wpdb->term_relationships} tr"
27
-			. "  ON tr.object_id = p.ID"
28
-			. " INNER JOIN {$wpdb->term_taxonomy} tt"
29
-			. "  ON tt.taxonomy = %s AND tt.term_taxonomy_id = tr.term_taxonomy_id"
30
-			. " INNER JOIN {$wpdb->terms} t"
31
-			. "  ON t.term_id = tt.term_id AND t.name != %s"
32
-			. " LEFT OUTER JOIN {$wpdb->postmeta} pm"
33
-			. "  ON pm.meta_key = %s AND pm.post_id = p.ID"
34
-			. " WHERE p.post_type IN ( '" . implode( "', '", array_map( 'esc_sql', Wordlift_Entity_Service::valid_entity_post_types() ) ) . "' )"
35
-			. "  AND p.post_status IN ( 'publish', 'draft', 'private', 'future' ) "
36
-			. "  AND ( p.post_title LIKE %s OR pm.meta_value LIKE %s )"
37
-			. " LIMIT %d",
38
-			Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME,
39
-			'article',
40
-			Wordlift_Entity_Service::ALTERNATIVE_LABEL_META_KEY,
41
-			// `prepare` doesn't support argument number, hence we must repeat the query.
42
-			'%' . $wpdb->esc_like( $query ) . '%',
43
-			'%' . $wpdb->esc_like( $query ) . '%',
44
-			50
45
-		) );
24
+        $posts = $wpdb->get_results( $wpdb->prepare(
25
+            "SELECT * FROM {$wpdb->posts} p"
26
+            . " INNER JOIN {$wpdb->term_relationships} tr"
27
+            . "  ON tr.object_id = p.ID"
28
+            . " INNER JOIN {$wpdb->term_taxonomy} tt"
29
+            . "  ON tt.taxonomy = %s AND tt.term_taxonomy_id = tr.term_taxonomy_id"
30
+            . " INNER JOIN {$wpdb->terms} t"
31
+            . "  ON t.term_id = tt.term_id AND t.name != %s"
32
+            . " LEFT OUTER JOIN {$wpdb->postmeta} pm"
33
+            . "  ON pm.meta_key = %s AND pm.post_id = p.ID"
34
+            . " WHERE p.post_type IN ( '" . implode( "', '", array_map( 'esc_sql', Wordlift_Entity_Service::valid_entity_post_types() ) ) . "' )"
35
+            . "  AND p.post_status IN ( 'publish', 'draft', 'private', 'future' ) "
36
+            . "  AND ( p.post_title LIKE %s OR pm.meta_value LIKE %s )"
37
+            . " LIMIT %d",
38
+            Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME,
39
+            'article',
40
+            Wordlift_Entity_Service::ALTERNATIVE_LABEL_META_KEY,
41
+            // `prepare` doesn't support argument number, hence we must repeat the query.
42
+            '%' . $wpdb->esc_like( $query ) . '%',
43
+            '%' . $wpdb->esc_like( $query ) . '%',
44
+            50
45
+        ) );
46 46
 
47
-		$results = array_map( function ( $item ) {
47
+        $results = array_map( function ( $item ) {
48 48
 
49
-			$entity_service = Wordlift_Entity_Service::get_instance();
50
-			$uri            = $entity_service->get_uri( $item->ID );
49
+            $entity_service = Wordlift_Entity_Service::get_instance();
50
+            $uri            = $entity_service->get_uri( $item->ID );
51 51
 
52
-			return array(
53
-				// see #1074: The value property is needed for autocomplete in category page
54
-				// to function correctly, if value is not provided, then the entity
55
-				// wont be correctly saved.
56
-				'value'        => $uri,
57
-				'id'           => $uri,
58
-				'label'        => array( $item->post_title ),
59
-				'labels'       => $entity_service->get_alternative_labels( $item->ID ),
60
-				'descriptions' => array( Wordlift_Post_Excerpt_Helper::get_text_excerpt( $item ) ),
61
-				'scope'        => 'local',
62
-				'sameAss'      => get_post_meta( $item->ID, \Wordlift_Schema_Service::FIELD_SAME_AS ),
63
-				// The following properties are less relevant because we're linking entities that exist already in the
64
-				// vocabulary. That's why we don't make an effort to load the real data.
65
-				'types'        => array( 'http://schema.org/Thing' ),
66
-				'urls'         => array(),
67
-				'images'       => array(),
68
-			);
69
-		}, $posts );
52
+            return array(
53
+                // see #1074: The value property is needed for autocomplete in category page
54
+                // to function correctly, if value is not provided, then the entity
55
+                // wont be correctly saved.
56
+                'value'        => $uri,
57
+                'id'           => $uri,
58
+                'label'        => array( $item->post_title ),
59
+                'labels'       => $entity_service->get_alternative_labels( $item->ID ),
60
+                'descriptions' => array( Wordlift_Post_Excerpt_Helper::get_text_excerpt( $item ) ),
61
+                'scope'        => 'local',
62
+                'sameAss'      => get_post_meta( $item->ID, \Wordlift_Schema_Service::FIELD_SAME_AS ),
63
+                // The following properties are less relevant because we're linking entities that exist already in the
64
+                // vocabulary. That's why we don't make an effort to load the real data.
65
+                'types'        => array( 'http://schema.org/Thing' ),
66
+                'urls'         => array(),
67
+                'images'       => array(),
68
+            );
69
+        }, $posts );
70 70
 
71
-		$results = array_unique( $results, SORT_REGULAR );
71
+        $results = array_unique( $results, SORT_REGULAR );
72 72
 
73
-		return $this->filter( $results, $excludes );
74
-	}
73
+        return $this->filter( $results, $excludes );
74
+    }
75 75
 
76 76
 }
Please login to merge, or discard this patch.
Spacing   +16 added lines, -16 removed lines patch added patch discarded remove patch
@@ -18,10 +18,10 @@  discard block
 block discarded – undo
18 18
 	/**
19 19
 	 * @inheritDoc
20 20
 	 */
21
-	public function query( $query, $scope, $excludes ) {
21
+	public function query($query, $scope, $excludes) {
22 22
 		global $wpdb;
23 23
 
24
-		$posts = $wpdb->get_results( $wpdb->prepare(
24
+		$posts = $wpdb->get_results($wpdb->prepare(
25 25
 			"SELECT * FROM {$wpdb->posts} p"
26 26
 			. " INNER JOIN {$wpdb->term_relationships} tr"
27 27
 			. "  ON tr.object_id = p.ID"
@@ -31,7 +31,7 @@  discard block
 block discarded – undo
31 31
 			. "  ON t.term_id = tt.term_id AND t.name != %s"
32 32
 			. " LEFT OUTER JOIN {$wpdb->postmeta} pm"
33 33
 			. "  ON pm.meta_key = %s AND pm.post_id = p.ID"
34
-			. " WHERE p.post_type IN ( '" . implode( "', '", array_map( 'esc_sql', Wordlift_Entity_Service::valid_entity_post_types() ) ) . "' )"
34
+			. " WHERE p.post_type IN ( '".implode("', '", array_map('esc_sql', Wordlift_Entity_Service::valid_entity_post_types()))."' )"
35 35
 			. "  AND p.post_status IN ( 'publish', 'draft', 'private', 'future' ) "
36 36
 			. "  AND ( p.post_title LIKE %s OR pm.meta_value LIKE %s )"
37 37
 			. " LIMIT %d",
@@ -39,15 +39,15 @@  discard block
 block discarded – undo
39 39
 			'article',
40 40
 			Wordlift_Entity_Service::ALTERNATIVE_LABEL_META_KEY,
41 41
 			// `prepare` doesn't support argument number, hence we must repeat the query.
42
-			'%' . $wpdb->esc_like( $query ) . '%',
43
-			'%' . $wpdb->esc_like( $query ) . '%',
42
+			'%'.$wpdb->esc_like($query).'%',
43
+			'%'.$wpdb->esc_like($query).'%',
44 44
 			50
45
-		) );
45
+		));
46 46
 
47
-		$results = array_map( function ( $item ) {
47
+		$results = array_map(function($item) {
48 48
 
49 49
 			$entity_service = Wordlift_Entity_Service::get_instance();
50
-			$uri            = $entity_service->get_uri( $item->ID );
50
+			$uri            = $entity_service->get_uri($item->ID);
51 51
 
52 52
 			return array(
53 53
 				// see #1074: The value property is needed for autocomplete in category page
@@ -55,22 +55,22 @@  discard block
 block discarded – undo
55 55
 				// wont be correctly saved.
56 56
 				'value'        => $uri,
57 57
 				'id'           => $uri,
58
-				'label'        => array( $item->post_title ),
59
-				'labels'       => $entity_service->get_alternative_labels( $item->ID ),
60
-				'descriptions' => array( Wordlift_Post_Excerpt_Helper::get_text_excerpt( $item ) ),
58
+				'label'        => array($item->post_title),
59
+				'labels'       => $entity_service->get_alternative_labels($item->ID),
60
+				'descriptions' => array(Wordlift_Post_Excerpt_Helper::get_text_excerpt($item)),
61 61
 				'scope'        => 'local',
62
-				'sameAss'      => get_post_meta( $item->ID, \Wordlift_Schema_Service::FIELD_SAME_AS ),
62
+				'sameAss'      => get_post_meta($item->ID, \Wordlift_Schema_Service::FIELD_SAME_AS),
63 63
 				// The following properties are less relevant because we're linking entities that exist already in the
64 64
 				// vocabulary. That's why we don't make an effort to load the real data.
65
-				'types'        => array( 'http://schema.org/Thing' ),
65
+				'types'        => array('http://schema.org/Thing'),
66 66
 				'urls'         => array(),
67 67
 				'images'       => array(),
68 68
 			);
69
-		}, $posts );
69
+		}, $posts);
70 70
 
71
-		$results = array_unique( $results, SORT_REGULAR );
71
+		$results = array_unique($results, SORT_REGULAR);
72 72
 
73
-		return $this->filter( $results, $excludes );
73
+		return $this->filter($results, $excludes);
74 74
 	}
75 75
 
76 76
 }
Please login to merge, or discard this patch.
src/wordlift/post/class-post-adapter.php 2 patches
Indentation   +320 added lines, -320 removed lines patch added patch discarded remove patch
@@ -18,326 +18,326 @@
 block discarded – undo
18 18
 
19 19
 class Post_Adapter {
20 20
 
21
-	/**
22
-	 * A {@link Wordlift_Log_Service} logging instance.
23
-	 *
24
-	 * @access private
25
-	 * @var \Wordlift_Log_Service A {@link Wordlift_Log_Service} logging instance.
26
-	 */
27
-	private $log;
28
-
29
-	/**
30
-	 * A {@link Wordlift_Entity_Service} instance.
31
-	 *
32
-	 * @access private
33
-	 * @var \Wordlift_Entity_Service A {@link Wordlift_Entity_Service} instance.
34
-	 */
35
-	private $entity_service;
36
-
37
-	/**
38
-	 * A {@link Entity_Store} instance.
39
-	 *
40
-	 * @access private
41
-	 * @var Entity_Store $entity_store A {@link Entity_Store} instance.
42
-	 */
43
-	private $entity_store;
44
-
45
-	public function __construct() {
46
-
47
-		// Bail out if block editor's functions aren't available.
48
-		if ( ! function_exists( 'register_block_type' ) || ! function_exists( 'parse_blocks' ) ) {
49
-			return;
50
-		}
51
-
52
-		$this->log = \Wordlift_Log_Service::get_logger( get_class() );
53
-
54
-		$this->entity_service = \Wordlift_Entity_Service::get_instance();
55
-		$this->entity_store   = Entity_Store::get_instance();
56
-
57
-		add_action( 'init', array( $this, 'init' ) );
58
-		add_filter( 'wp_insert_post_data', array( $this, 'wp_insert_post_data' ), 10, 2 );
59
-
60
-	}
61
-
62
-	/**
63
-	 * Initialize by registering our block type `wordlift/classification`, required for {@link parse_blocks) to work
64
-	 * correctly.
65
-	 */
66
-	public function init() {
67
-
68
-		register_block_type( 'wordlift/classification', array(
69
-			'editor_script' => 'wl-block-editor',
70
-			'attributes'    => array(
71
-				'entities' => array( 'type' => 'array' ),
72
-			),
73
-		) );
74
-
75
-	}
76
-
77
-	/**
78
-	 * A sample structure:
79
-	 *
80
-	 * {
81
-	 *   "entities": [
82
-	 *     {
83
-	 *       "annotations": {
84
-	 *         "urn:enhancement-7e8e66fc": {
85
-	 *           "start": 3480,
86
-	 *           "end": 3486,
87
-	 *           "text": "libero"
88
-	 *         }
89
-	 *       },
90
-	 *       "description": "Le libero ou libéro est un poste défensif du volley-ball. Des règles particulières le concernant ont été introduites à la fin des années 1990. De par sa spécificité, le libéro a un statut à part au sein d’une équipe de volley-ball. Pour être identifié, il doit porter un uniforme qui contraste avec ceux des autres membres de son équipe, titulaires ou remplaçants.",
91
-	 *       "id": "http://fr.dbpedia.org/resource/Libero_(volley-ball)",
92
-	 *       "label": "Libero (volley-ball)",
93
-	 *       "mainType": "other",
94
-	 *       "occurrences": ["urn:enhancement-7e8e66fc"],
95
-	 *       "sameAs": null,
96
-	 *       "synonyms": [],
97
-	 *       "types": ["other"]
98
-	 *     }
99
-	 *   ]
100
-	 * }
101
-	 *
102
-	 * @param array $data An array of slashed post data.
103
-	 * @param array $postarr An array of sanitized, but otherwise unmodified post data.
104
-	 *
105
-	 * @return array The data array.
106
-	 * @throws \Exception
107
-	 */
108
-	public function wp_insert_post_data( $data, $postarr ) {
109
-
110
-		//
111
-		$post_status = $data['post_status'];
112
-		if ( 'auto-draft' === $post_status || 'inherit' === $post_status ) {
113
-			return $data;
114
-		}
115
-
116
-		$this->log->trace( "The following data has been received by `wp_insert_post_data`:\n"
117
-		                   . var_export( $data, true ) );
118
-
119
-		try {
120
-			$entities = $this->parse_content( wp_unslash( $data['post_content'] ) );
121
-
122
-			foreach ( $entities as $entity ) {
123
-				$this->create_or_update_entity( $entity, $data['post_status'] );
124
-			}
125
-
126
-		} catch ( \Exception $e ) {
127
-			$this->log->error( $e->getMessage() );
128
-		}
129
-
130
-		return $data;
131
-	}
132
-
133
-	/**
134
-	 * Parse the post content to find the `wordlift/classification` block and return the entities' data.
135
-	 *
136
-	 * @param string $post_content The post content.
137
-	 *
138
-	 * @return array An array of entities' structures.
139
-	 * @throws \Exception
140
-	 */
141
-	private function parse_content( $post_content ) {
142
-
143
-		$all_blocks = parse_blocks( $post_content );
144
-		$this->log->trace( "The following blocks have been parsed while in `wp_insert_post`:\n"
145
-		                   . var_export( $all_blocks, true ) );
146
-
147
-		$blocks = array_filter( $all_blocks, function ( $item ) {
148
-			return ! empty( $item['blockName'] ) && 'wordlift/classification' === $item['blockName'];
149
-		} );
150
-
151
-		// Bail out if the blocks' array is empty.
152
-		if ( empty( $blocks ) ) {
153
-			return array();
154
-		}
155
-
156
-		$block = current( $blocks );
157
-		$this->log->trace( "The following block has been found while in `wp_insert_post`:\n"
158
-		                   . var_export( $block, true ) );
159
-
160
-		// Bail out if the entities array is empty.
161
-		if ( empty( $block['attrs'] ) && empty( $block['attrs']['entities'] ) ) {
162
-			return array();
163
-		}
164
-
165
-		return $block['attrs']['entities'];
166
-	}
167
-
168
-	/**
169
-	 * Collect entity labels from the entity array.
170
-	 *
171
-	 * This function expects an array with the following keys:
172
-	 *
173
-	 * array(
174
-	 *   'label'       => ...,
175
-	 *   'synonyms'    => array( ... ),
176
-	 *   'annotations' => array(
177
-	 *     ...id...      => array( text => ... ),
178
-	 *   ),
179
-	 *   'occurrences' => array( ... ),
180
-	 * )
181
-	 *
182
-	 * and it is going to output an array with all the labels, keeping the `label` at first position:
183
-	 *
184
-	 * array(
185
-	 *   ...label...,
186
-	 *   ...synonyms...,
187
-	 *   ...texts...,
188
-	 * )
189
-	 *
190
-	 * This function is going to collect the label from the `label` property, from the `synonyms` property and from
191
-	 * `annotations` property. Since the `annotations` property contains all the annotations including those that
192
-	 * haven't been selected, this function is going to only get the `text` for the annotations property listed in
193
-	 * `occurrences`.
194
-	 *
195
-	 * @param array $entity {
196
-	 *  The entity data.
197
-	 *
198
-	 * @type string $label The entity label.
199
-	 * @type array $synonyms The entity synonyms.
200
-	 * @type array $occurrences The selected occurrences.
201
-	 * @type array $annotations The annotations.
202
-	 * }
203
-	 *
204
-	 * @return array An array of labels.
205
-	 */
206
-	public function get_labels( $entity ) {
207
-
208
-		$args = wp_parse_args( $entity, array(
209
-			'label'       => array(),
210
-			'synonyms'    => array(),
211
-			'annotations' => array(),
212
-			'occurrences' => array(),
213
-		) );
214
-
215
-		// We gather all the labels, occurrences texts and synonyms into one array.
216
-		$initial = array_merge(
217
-			(array) $args['label'],
218
-			(array) $args['synonyms']
219
-		);
220
-
221
-		$annotations = $args['annotations'];
222
-
223
-		return array_reduce( $args['occurrences'], function ( $carry, $item ) use ( $annotations ) {
224
-
225
-			// Bail out if occurrences->$item->text isn't set or its contents are already
226
-			// in `$carry`.
227
-			if ( ! isset( $annotations[ $item ]['text'] )
228
-			     || in_array( $annotations[ $item ]['text'], $carry ) ) {
229
-				return $carry;
230
-			}
231
-
232
-			// Push the label.
233
-			$carry[] = $annotations[ $item ]['text'];
234
-
235
-			return $carry;
236
-		}, $initial );
237
-	}
238
-
239
-	/**
240
-	 * Create or update the entity.
241
-	 *
242
-	 * An entity lookup is performed on the local vocabulary using the `id` and `sameAs` URIs. If an entity is found
243
-	 * the {@link Entity_Store} update function is called to update the `labels` and the `sameAs` values.
244
-	 *
245
-	 * If an entity is not found the {@link Entity_Store} create function is called to create a new entity.
246
-	 *
247
-	 * @param array $entity {
248
-	 * The entity parameters.
249
-	 *
250
-	 * @type string The entity item id URI.
251
-	 * @type string|array The entity sameAs URI(s).
252
-	 * @type string $description The entity description.
253
-	 * }
254
-	 *
255
-	 * @param       $string $post_status The post status, default 'draft'.
256
-	 *
257
-	 * @return int|\WP_Error
258
-	 * @throws \Exception
259
-	 */
260
-	private function create_or_update_entity( $entity, $post_status = 'draft' ) {
261
-
262
-		// Get only valid IDs.
263
-		$ids = array_filter( (array) $entity['id'], function ( $id ) {
264
-			return preg_match( '|^https?://|', $id );
265
-		} );
266
-
267
-		$uris = array_merge(
268
-			(array) $ids,
269
-			(array) $entity['sameAs']
270
-		);
271
-
272
-		$post = $this->get_first_matching_entity_by_uri( $uris );
273
-
274
-		$this->log->trace( 'Entity' . ( empty( $post ) ? ' not' : '' ) . " found with the following URIs:\n"
275
-		                   . var_export( $uris, true ) );
276
-
277
-		// Get the labels.
278
-		$labels = $this->get_labels( $entity );
279
-
280
-		if ( empty( $post ) ) {
281
-			// Create the entity if it doesn't exist.
282
-			$post_id = $this->entity_store->create( array(
283
-				'labels'      => $labels,
284
-				'description' => $entity['description'],
285
-				'same_as'     => $uris,
286
-			), $post_status );
287
-
288
-			// Return the WP_Error if we got one.
289
-			if ( is_wp_error( $post_id ) ) {
290
-				return $post_id;
291
-			}
292
-
293
-			// Add the entity type.
294
-			if ( isset( $entity['mainType'] ) ) {
295
-				wp_set_object_terms( $post_id, $entity['mainType'], \Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME );
296
-			}
297
-
298
-			if ( isset( $entity['properties'] ) && isset( $entity['properties']['latitude'] ) && isset( $entity['properties']['longitude'] ) ) {
299
-				add_post_meta( $post_id, \Wordlift_Schema_Service::FIELD_GEO_LATITUDE, $entity['properties']['latitude'] );
300
-				add_post_meta( $post_id, \Wordlift_Schema_Service::FIELD_GEO_LONGITUDE, $entity['properties']['longitude'] );
301
-			}
302
-		} else {
303
-			// Update the entity otherwise.
304
-			$post_id = $this->entity_store->update( array(
305
-				'ID'      => $post->ID,
306
-				'labels'  => $labels,
307
-				'same_as' => $uris,
308
-			) );
309
-
310
-			// Add the entity type.
311
-			if ( isset( $entity['mainType'] ) ) {
312
-				wp_add_object_terms( $post_id, $entity['mainType'], \Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME );
313
-			}
314
-		}
315
-
316
-		return $post_id;
317
-	}
318
-
319
-	/**
320
-	 * Get the first matching entity for the provided URI array.
321
-	 *
322
-	 * Entities IDs and sameAs are searched.
323
-	 *
324
-	 * @param array $uris An array of URIs.
325
-	 *
326
-	 * @return \WP_Post|null The entity WP_Post if found or null if not found.
327
-	 */
328
-	private function get_first_matching_entity_by_uri( $uris ) {
329
-
330
-		foreach ( $uris as $uri ) {
331
-			$existing_entity = $this->entity_service->get_entity_post_by_uri( $uri );
332
-			if ( isset( $existing_entity ) ) {
333
-				return $existing_entity;
334
-			}
335
-		}
336
-
337
-		return null;
338
-	}
339
-
340
-	//	/**
21
+    /**
22
+     * A {@link Wordlift_Log_Service} logging instance.
23
+     *
24
+     * @access private
25
+     * @var \Wordlift_Log_Service A {@link Wordlift_Log_Service} logging instance.
26
+     */
27
+    private $log;
28
+
29
+    /**
30
+     * A {@link Wordlift_Entity_Service} instance.
31
+     *
32
+     * @access private
33
+     * @var \Wordlift_Entity_Service A {@link Wordlift_Entity_Service} instance.
34
+     */
35
+    private $entity_service;
36
+
37
+    /**
38
+     * A {@link Entity_Store} instance.
39
+     *
40
+     * @access private
41
+     * @var Entity_Store $entity_store A {@link Entity_Store} instance.
42
+     */
43
+    private $entity_store;
44
+
45
+    public function __construct() {
46
+
47
+        // Bail out if block editor's functions aren't available.
48
+        if ( ! function_exists( 'register_block_type' ) || ! function_exists( 'parse_blocks' ) ) {
49
+            return;
50
+        }
51
+
52
+        $this->log = \Wordlift_Log_Service::get_logger( get_class() );
53
+
54
+        $this->entity_service = \Wordlift_Entity_Service::get_instance();
55
+        $this->entity_store   = Entity_Store::get_instance();
56
+
57
+        add_action( 'init', array( $this, 'init' ) );
58
+        add_filter( 'wp_insert_post_data', array( $this, 'wp_insert_post_data' ), 10, 2 );
59
+
60
+    }
61
+
62
+    /**
63
+     * Initialize by registering our block type `wordlift/classification`, required for {@link parse_blocks) to work
64
+     * correctly.
65
+     */
66
+    public function init() {
67
+
68
+        register_block_type( 'wordlift/classification', array(
69
+            'editor_script' => 'wl-block-editor',
70
+            'attributes'    => array(
71
+                'entities' => array( 'type' => 'array' ),
72
+            ),
73
+        ) );
74
+
75
+    }
76
+
77
+    /**
78
+     * A sample structure:
79
+     *
80
+     * {
81
+     *   "entities": [
82
+     *     {
83
+     *       "annotations": {
84
+     *         "urn:enhancement-7e8e66fc": {
85
+     *           "start": 3480,
86
+     *           "end": 3486,
87
+     *           "text": "libero"
88
+     *         }
89
+     *       },
90
+     *       "description": "Le libero ou libéro est un poste défensif du volley-ball. Des règles particulières le concernant ont été introduites à la fin des années 1990. De par sa spécificité, le libéro a un statut à part au sein d’une équipe de volley-ball. Pour être identifié, il doit porter un uniforme qui contraste avec ceux des autres membres de son équipe, titulaires ou remplaçants.",
91
+     *       "id": "http://fr.dbpedia.org/resource/Libero_(volley-ball)",
92
+     *       "label": "Libero (volley-ball)",
93
+     *       "mainType": "other",
94
+     *       "occurrences": ["urn:enhancement-7e8e66fc"],
95
+     *       "sameAs": null,
96
+     *       "synonyms": [],
97
+     *       "types": ["other"]
98
+     *     }
99
+     *   ]
100
+     * }
101
+     *
102
+     * @param array $data An array of slashed post data.
103
+     * @param array $postarr An array of sanitized, but otherwise unmodified post data.
104
+     *
105
+     * @return array The data array.
106
+     * @throws \Exception
107
+     */
108
+    public function wp_insert_post_data( $data, $postarr ) {
109
+
110
+        //
111
+        $post_status = $data['post_status'];
112
+        if ( 'auto-draft' === $post_status || 'inherit' === $post_status ) {
113
+            return $data;
114
+        }
115
+
116
+        $this->log->trace( "The following data has been received by `wp_insert_post_data`:\n"
117
+                            . var_export( $data, true ) );
118
+
119
+        try {
120
+            $entities = $this->parse_content( wp_unslash( $data['post_content'] ) );
121
+
122
+            foreach ( $entities as $entity ) {
123
+                $this->create_or_update_entity( $entity, $data['post_status'] );
124
+            }
125
+
126
+        } catch ( \Exception $e ) {
127
+            $this->log->error( $e->getMessage() );
128
+        }
129
+
130
+        return $data;
131
+    }
132
+
133
+    /**
134
+     * Parse the post content to find the `wordlift/classification` block and return the entities' data.
135
+     *
136
+     * @param string $post_content The post content.
137
+     *
138
+     * @return array An array of entities' structures.
139
+     * @throws \Exception
140
+     */
141
+    private function parse_content( $post_content ) {
142
+
143
+        $all_blocks = parse_blocks( $post_content );
144
+        $this->log->trace( "The following blocks have been parsed while in `wp_insert_post`:\n"
145
+                            . var_export( $all_blocks, true ) );
146
+
147
+        $blocks = array_filter( $all_blocks, function ( $item ) {
148
+            return ! empty( $item['blockName'] ) && 'wordlift/classification' === $item['blockName'];
149
+        } );
150
+
151
+        // Bail out if the blocks' array is empty.
152
+        if ( empty( $blocks ) ) {
153
+            return array();
154
+        }
155
+
156
+        $block = current( $blocks );
157
+        $this->log->trace( "The following block has been found while in `wp_insert_post`:\n"
158
+                            . var_export( $block, true ) );
159
+
160
+        // Bail out if the entities array is empty.
161
+        if ( empty( $block['attrs'] ) && empty( $block['attrs']['entities'] ) ) {
162
+            return array();
163
+        }
164
+
165
+        return $block['attrs']['entities'];
166
+    }
167
+
168
+    /**
169
+     * Collect entity labels from the entity array.
170
+     *
171
+     * This function expects an array with the following keys:
172
+     *
173
+     * array(
174
+     *   'label'       => ...,
175
+     *   'synonyms'    => array( ... ),
176
+     *   'annotations' => array(
177
+     *     ...id...      => array( text => ... ),
178
+     *   ),
179
+     *   'occurrences' => array( ... ),
180
+     * )
181
+     *
182
+     * and it is going to output an array with all the labels, keeping the `label` at first position:
183
+     *
184
+     * array(
185
+     *   ...label...,
186
+     *   ...synonyms...,
187
+     *   ...texts...,
188
+     * )
189
+     *
190
+     * This function is going to collect the label from the `label` property, from the `synonyms` property and from
191
+     * `annotations` property. Since the `annotations` property contains all the annotations including those that
192
+     * haven't been selected, this function is going to only get the `text` for the annotations property listed in
193
+     * `occurrences`.
194
+     *
195
+     * @param array $entity {
196
+     *  The entity data.
197
+     *
198
+     * @type string $label The entity label.
199
+     * @type array $synonyms The entity synonyms.
200
+     * @type array $occurrences The selected occurrences.
201
+     * @type array $annotations The annotations.
202
+     * }
203
+     *
204
+     * @return array An array of labels.
205
+     */
206
+    public function get_labels( $entity ) {
207
+
208
+        $args = wp_parse_args( $entity, array(
209
+            'label'       => array(),
210
+            'synonyms'    => array(),
211
+            'annotations' => array(),
212
+            'occurrences' => array(),
213
+        ) );
214
+
215
+        // We gather all the labels, occurrences texts and synonyms into one array.
216
+        $initial = array_merge(
217
+            (array) $args['label'],
218
+            (array) $args['synonyms']
219
+        );
220
+
221
+        $annotations = $args['annotations'];
222
+
223
+        return array_reduce( $args['occurrences'], function ( $carry, $item ) use ( $annotations ) {
224
+
225
+            // Bail out if occurrences->$item->text isn't set or its contents are already
226
+            // in `$carry`.
227
+            if ( ! isset( $annotations[ $item ]['text'] )
228
+                 || in_array( $annotations[ $item ]['text'], $carry ) ) {
229
+                return $carry;
230
+            }
231
+
232
+            // Push the label.
233
+            $carry[] = $annotations[ $item ]['text'];
234
+
235
+            return $carry;
236
+        }, $initial );
237
+    }
238
+
239
+    /**
240
+     * Create or update the entity.
241
+     *
242
+     * An entity lookup is performed on the local vocabulary using the `id` and `sameAs` URIs. If an entity is found
243
+     * the {@link Entity_Store} update function is called to update the `labels` and the `sameAs` values.
244
+     *
245
+     * If an entity is not found the {@link Entity_Store} create function is called to create a new entity.
246
+     *
247
+     * @param array $entity {
248
+     * The entity parameters.
249
+     *
250
+     * @type string The entity item id URI.
251
+     * @type string|array The entity sameAs URI(s).
252
+     * @type string $description The entity description.
253
+     * }
254
+     *
255
+     * @param       $string $post_status The post status, default 'draft'.
256
+     *
257
+     * @return int|\WP_Error
258
+     * @throws \Exception
259
+     */
260
+    private function create_or_update_entity( $entity, $post_status = 'draft' ) {
261
+
262
+        // Get only valid IDs.
263
+        $ids = array_filter( (array) $entity['id'], function ( $id ) {
264
+            return preg_match( '|^https?://|', $id );
265
+        } );
266
+
267
+        $uris = array_merge(
268
+            (array) $ids,
269
+            (array) $entity['sameAs']
270
+        );
271
+
272
+        $post = $this->get_first_matching_entity_by_uri( $uris );
273
+
274
+        $this->log->trace( 'Entity' . ( empty( $post ) ? ' not' : '' ) . " found with the following URIs:\n"
275
+                            . var_export( $uris, true ) );
276
+
277
+        // Get the labels.
278
+        $labels = $this->get_labels( $entity );
279
+
280
+        if ( empty( $post ) ) {
281
+            // Create the entity if it doesn't exist.
282
+            $post_id = $this->entity_store->create( array(
283
+                'labels'      => $labels,
284
+                'description' => $entity['description'],
285
+                'same_as'     => $uris,
286
+            ), $post_status );
287
+
288
+            // Return the WP_Error if we got one.
289
+            if ( is_wp_error( $post_id ) ) {
290
+                return $post_id;
291
+            }
292
+
293
+            // Add the entity type.
294
+            if ( isset( $entity['mainType'] ) ) {
295
+                wp_set_object_terms( $post_id, $entity['mainType'], \Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME );
296
+            }
297
+
298
+            if ( isset( $entity['properties'] ) && isset( $entity['properties']['latitude'] ) && isset( $entity['properties']['longitude'] ) ) {
299
+                add_post_meta( $post_id, \Wordlift_Schema_Service::FIELD_GEO_LATITUDE, $entity['properties']['latitude'] );
300
+                add_post_meta( $post_id, \Wordlift_Schema_Service::FIELD_GEO_LONGITUDE, $entity['properties']['longitude'] );
301
+            }
302
+        } else {
303
+            // Update the entity otherwise.
304
+            $post_id = $this->entity_store->update( array(
305
+                'ID'      => $post->ID,
306
+                'labels'  => $labels,
307
+                'same_as' => $uris,
308
+            ) );
309
+
310
+            // Add the entity type.
311
+            if ( isset( $entity['mainType'] ) ) {
312
+                wp_add_object_terms( $post_id, $entity['mainType'], \Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME );
313
+            }
314
+        }
315
+
316
+        return $post_id;
317
+    }
318
+
319
+    /**
320
+     * Get the first matching entity for the provided URI array.
321
+     *
322
+     * Entities IDs and sameAs are searched.
323
+     *
324
+     * @param array $uris An array of URIs.
325
+     *
326
+     * @return \WP_Post|null The entity WP_Post if found or null if not found.
327
+     */
328
+    private function get_first_matching_entity_by_uri( $uris ) {
329
+
330
+        foreach ( $uris as $uri ) {
331
+            $existing_entity = $this->entity_service->get_entity_post_by_uri( $uri );
332
+            if ( isset( $existing_entity ) ) {
333
+                return $existing_entity;
334
+            }
335
+        }
336
+
337
+        return null;
338
+    }
339
+
340
+    //	/**
341 341
 //	 * @param int      $post_ID Post ID.
342 342
 //	 * @param \WP_Post $post Post object.
343 343
 //	 * @param bool     $update Whether this is an existing post being updated or not.
Please login to merge, or discard this patch.
Spacing   +59 added lines, -59 removed lines patch added patch discarded remove patch
@@ -45,17 +45,17 @@  discard block
 block discarded – undo
45 45
 	public function __construct() {
46 46
 
47 47
 		// Bail out if block editor's functions aren't available.
48
-		if ( ! function_exists( 'register_block_type' ) || ! function_exists( 'parse_blocks' ) ) {
48
+		if ( ! function_exists('register_block_type') || ! function_exists('parse_blocks')) {
49 49
 			return;
50 50
 		}
51 51
 
52
-		$this->log = \Wordlift_Log_Service::get_logger( get_class() );
52
+		$this->log = \Wordlift_Log_Service::get_logger(get_class());
53 53
 
54 54
 		$this->entity_service = \Wordlift_Entity_Service::get_instance();
55 55
 		$this->entity_store   = Entity_Store::get_instance();
56 56
 
57
-		add_action( 'init', array( $this, 'init' ) );
58
-		add_filter( 'wp_insert_post_data', array( $this, 'wp_insert_post_data' ), 10, 2 );
57
+		add_action('init', array($this, 'init'));
58
+		add_filter('wp_insert_post_data', array($this, 'wp_insert_post_data'), 10, 2);
59 59
 
60 60
 	}
61 61
 
@@ -65,12 +65,12 @@  discard block
 block discarded – undo
65 65
 	 */
66 66
 	public function init() {
67 67
 
68
-		register_block_type( 'wordlift/classification', array(
68
+		register_block_type('wordlift/classification', array(
69 69
 			'editor_script' => 'wl-block-editor',
70 70
 			'attributes'    => array(
71
-				'entities' => array( 'type' => 'array' ),
71
+				'entities' => array('type' => 'array'),
72 72
 			),
73
-		) );
73
+		));
74 74
 
75 75
 	}
76 76
 
@@ -105,26 +105,26 @@  discard block
 block discarded – undo
105 105
 	 * @return array The data array.
106 106
 	 * @throws \Exception
107 107
 	 */
108
-	public function wp_insert_post_data( $data, $postarr ) {
108
+	public function wp_insert_post_data($data, $postarr) {
109 109
 
110 110
 		//
111 111
 		$post_status = $data['post_status'];
112
-		if ( 'auto-draft' === $post_status || 'inherit' === $post_status ) {
112
+		if ('auto-draft' === $post_status || 'inherit' === $post_status) {
113 113
 			return $data;
114 114
 		}
115 115
 
116
-		$this->log->trace( "The following data has been received by `wp_insert_post_data`:\n"
117
-		                   . var_export( $data, true ) );
116
+		$this->log->trace("The following data has been received by `wp_insert_post_data`:\n"
117
+		                   . var_export($data, true));
118 118
 
119 119
 		try {
120
-			$entities = $this->parse_content( wp_unslash( $data['post_content'] ) );
120
+			$entities = $this->parse_content(wp_unslash($data['post_content']));
121 121
 
122
-			foreach ( $entities as $entity ) {
123
-				$this->create_or_update_entity( $entity, $data['post_status'] );
122
+			foreach ($entities as $entity) {
123
+				$this->create_or_update_entity($entity, $data['post_status']);
124 124
 			}
125 125
 
126
-		} catch ( \Exception $e ) {
127
-			$this->log->error( $e->getMessage() );
126
+		} catch (\Exception $e) {
127
+			$this->log->error($e->getMessage());
128 128
 		}
129 129
 
130 130
 		return $data;
@@ -138,27 +138,27 @@  discard block
 block discarded – undo
138 138
 	 * @return array An array of entities' structures.
139 139
 	 * @throws \Exception
140 140
 	 */
141
-	private function parse_content( $post_content ) {
141
+	private function parse_content($post_content) {
142 142
 
143
-		$all_blocks = parse_blocks( $post_content );
144
-		$this->log->trace( "The following blocks have been parsed while in `wp_insert_post`:\n"
145
-		                   . var_export( $all_blocks, true ) );
143
+		$all_blocks = parse_blocks($post_content);
144
+		$this->log->trace("The following blocks have been parsed while in `wp_insert_post`:\n"
145
+		                   . var_export($all_blocks, true));
146 146
 
147
-		$blocks = array_filter( $all_blocks, function ( $item ) {
148
-			return ! empty( $item['blockName'] ) && 'wordlift/classification' === $item['blockName'];
147
+		$blocks = array_filter($all_blocks, function($item) {
148
+			return ! empty($item['blockName']) && 'wordlift/classification' === $item['blockName'];
149 149
 		} );
150 150
 
151 151
 		// Bail out if the blocks' array is empty.
152
-		if ( empty( $blocks ) ) {
152
+		if (empty($blocks)) {
153 153
 			return array();
154 154
 		}
155 155
 
156
-		$block = current( $blocks );
157
-		$this->log->trace( "The following block has been found while in `wp_insert_post`:\n"
158
-		                   . var_export( $block, true ) );
156
+		$block = current($blocks);
157
+		$this->log->trace("The following block has been found while in `wp_insert_post`:\n"
158
+		                   . var_export($block, true));
159 159
 
160 160
 		// Bail out if the entities array is empty.
161
-		if ( empty( $block['attrs'] ) && empty( $block['attrs']['entities'] ) ) {
161
+		if (empty($block['attrs']) && empty($block['attrs']['entities'])) {
162 162
 			return array();
163 163
 		}
164 164
 
@@ -203,14 +203,14 @@  discard block
 block discarded – undo
203 203
 	 *
204 204
 	 * @return array An array of labels.
205 205
 	 */
206
-	public function get_labels( $entity ) {
206
+	public function get_labels($entity) {
207 207
 
208
-		$args = wp_parse_args( $entity, array(
208
+		$args = wp_parse_args($entity, array(
209 209
 			'label'       => array(),
210 210
 			'synonyms'    => array(),
211 211
 			'annotations' => array(),
212 212
 			'occurrences' => array(),
213
-		) );
213
+		));
214 214
 
215 215
 		// We gather all the labels, occurrences texts and synonyms into one array.
216 216
 		$initial = array_merge(
@@ -220,20 +220,20 @@  discard block
 block discarded – undo
220 220
 
221 221
 		$annotations = $args['annotations'];
222 222
 
223
-		return array_reduce( $args['occurrences'], function ( $carry, $item ) use ( $annotations ) {
223
+		return array_reduce($args['occurrences'], function($carry, $item) use ($annotations) {
224 224
 
225 225
 			// Bail out if occurrences->$item->text isn't set or its contents are already
226 226
 			// in `$carry`.
227
-			if ( ! isset( $annotations[ $item ]['text'] )
228
-			     || in_array( $annotations[ $item ]['text'], $carry ) ) {
227
+			if ( ! isset($annotations[$item]['text'])
228
+			     || in_array($annotations[$item]['text'], $carry)) {
229 229
 				return $carry;
230 230
 			}
231 231
 
232 232
 			// Push the label.
233
-			$carry[] = $annotations[ $item ]['text'];
233
+			$carry[] = $annotations[$item]['text'];
234 234
 
235 235
 			return $carry;
236
-		}, $initial );
236
+		}, $initial);
237 237
 	}
238 238
 
239 239
 	/**
@@ -257,11 +257,11 @@  discard block
 block discarded – undo
257 257
 	 * @return int|\WP_Error
258 258
 	 * @throws \Exception
259 259
 	 */
260
-	private function create_or_update_entity( $entity, $post_status = 'draft' ) {
260
+	private function create_or_update_entity($entity, $post_status = 'draft') {
261 261
 
262 262
 		// Get only valid IDs.
263
-		$ids = array_filter( (array) $entity['id'], function ( $id ) {
264
-			return preg_match( '|^https?://|', $id );
263
+		$ids = array_filter((array) $entity['id'], function($id) {
264
+			return preg_match('|^https?://|', $id);
265 265
 		} );
266 266
 
267 267
 		$uris = array_merge(
@@ -269,47 +269,47 @@  discard block
 block discarded – undo
269 269
 			(array) $entity['sameAs']
270 270
 		);
271 271
 
272
-		$post = $this->get_first_matching_entity_by_uri( $uris );
272
+		$post = $this->get_first_matching_entity_by_uri($uris);
273 273
 
274
-		$this->log->trace( 'Entity' . ( empty( $post ) ? ' not' : '' ) . " found with the following URIs:\n"
275
-		                   . var_export( $uris, true ) );
274
+		$this->log->trace('Entity'.(empty($post) ? ' not' : '')." found with the following URIs:\n"
275
+		                   . var_export($uris, true));
276 276
 
277 277
 		// Get the labels.
278
-		$labels = $this->get_labels( $entity );
278
+		$labels = $this->get_labels($entity);
279 279
 
280
-		if ( empty( $post ) ) {
280
+		if (empty($post)) {
281 281
 			// Create the entity if it doesn't exist.
282
-			$post_id = $this->entity_store->create( array(
282
+			$post_id = $this->entity_store->create(array(
283 283
 				'labels'      => $labels,
284 284
 				'description' => $entity['description'],
285 285
 				'same_as'     => $uris,
286
-			), $post_status );
286
+			), $post_status);
287 287
 
288 288
 			// Return the WP_Error if we got one.
289
-			if ( is_wp_error( $post_id ) ) {
289
+			if (is_wp_error($post_id)) {
290 290
 				return $post_id;
291 291
 			}
292 292
 
293 293
 			// Add the entity type.
294
-			if ( isset( $entity['mainType'] ) ) {
295
-				wp_set_object_terms( $post_id, $entity['mainType'], \Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME );
294
+			if (isset($entity['mainType'])) {
295
+				wp_set_object_terms($post_id, $entity['mainType'], \Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME);
296 296
 			}
297 297
 
298
-			if ( isset( $entity['properties'] ) && isset( $entity['properties']['latitude'] ) && isset( $entity['properties']['longitude'] ) ) {
299
-				add_post_meta( $post_id, \Wordlift_Schema_Service::FIELD_GEO_LATITUDE, $entity['properties']['latitude'] );
300
-				add_post_meta( $post_id, \Wordlift_Schema_Service::FIELD_GEO_LONGITUDE, $entity['properties']['longitude'] );
298
+			if (isset($entity['properties']) && isset($entity['properties']['latitude']) && isset($entity['properties']['longitude'])) {
299
+				add_post_meta($post_id, \Wordlift_Schema_Service::FIELD_GEO_LATITUDE, $entity['properties']['latitude']);
300
+				add_post_meta($post_id, \Wordlift_Schema_Service::FIELD_GEO_LONGITUDE, $entity['properties']['longitude']);
301 301
 			}
302 302
 		} else {
303 303
 			// Update the entity otherwise.
304
-			$post_id = $this->entity_store->update( array(
304
+			$post_id = $this->entity_store->update(array(
305 305
 				'ID'      => $post->ID,
306 306
 				'labels'  => $labels,
307 307
 				'same_as' => $uris,
308
-			) );
308
+			));
309 309
 
310 310
 			// Add the entity type.
311
-			if ( isset( $entity['mainType'] ) ) {
312
-				wp_add_object_terms( $post_id, $entity['mainType'], \Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME );
311
+			if (isset($entity['mainType'])) {
312
+				wp_add_object_terms($post_id, $entity['mainType'], \Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME);
313 313
 			}
314 314
 		}
315 315
 
@@ -325,11 +325,11 @@  discard block
 block discarded – undo
325 325
 	 *
326 326
 	 * @return \WP_Post|null The entity WP_Post if found or null if not found.
327 327
 	 */
328
-	private function get_first_matching_entity_by_uri( $uris ) {
328
+	private function get_first_matching_entity_by_uri($uris) {
329 329
 
330
-		foreach ( $uris as $uri ) {
331
-			$existing_entity = $this->entity_service->get_entity_post_by_uri( $uri );
332
-			if ( isset( $existing_entity ) ) {
330
+		foreach ($uris as $uri) {
331
+			$existing_entity = $this->entity_service->get_entity_post_by_uri($uri);
332
+			if (isset($existing_entity)) {
333 333
 				return $existing_entity;
334 334
 			}
335 335
 		}
Please login to merge, or discard this patch.