Completed
Push — develop ( 7a04bf...706ddd )
by David
02:47
created
src/wordlift.php 2 patches
Indentation   +161 added lines, -161 removed lines patch added patch discarded remove patch
@@ -26,7 +26,7 @@  discard block
 block discarded – undo
26 26
 
27 27
 // If this file is called directly, abort.
28 28
 if ( ! defined( 'WPINC' ) ) {
29
-	die;
29
+    die;
30 30
 }
31 31
 
32 32
 // Include WordLift constants.
@@ -48,7 +48,7 @@  discard block
 block discarded – undo
48 48
  */
49 49
 function wl_write_log( $log ) {
50 50
 
51
-	Wordlift_Log_Service::get_instance()->debug( $log );
51
+    Wordlift_Log_Service::get_instance()->debug( $log );
52 52
 
53 53
 }
54 54
 
@@ -64,20 +64,20 @@  discard block
 block discarded – undo
64 64
  */
65 65
 function wl_write_log_handler( $log, $caller = null ) {
66 66
 
67
-	global $wl_logger;
67
+    global $wl_logger;
68 68
 
69
-	if ( true === WP_DEBUG ) {
69
+    if ( true === WP_DEBUG ) {
70 70
 
71
-		$message = ( isset( $caller ) ? sprintf( '[%-40.40s] ', $caller ) : '' ) .
72
-		           ( is_array( $log ) || is_object( $log ) ? print_r( $log, true ) : wl_write_log_hide_key( $log ) );
71
+        $message = ( isset( $caller ) ? sprintf( '[%-40.40s] ', $caller ) : '' ) .
72
+                    ( is_array( $log ) || is_object( $log ) ? print_r( $log, true ) : wl_write_log_hide_key( $log ) );
73 73
 
74
-		if ( isset( $wl_logger ) ) {
75
-			$wl_logger->info( $message );
76
-		} else {
77
-			error_log( $message );
78
-		}
74
+        if ( isset( $wl_logger ) ) {
75
+            $wl_logger->info( $message );
76
+        } else {
77
+            error_log( $message );
78
+        }
79 79
 
80
-	}
80
+    }
81 81
 
82 82
 }
83 83
 
@@ -94,7 +94,7 @@  discard block
 block discarded – undo
94 94
  */
95 95
 function wl_write_log_hide_key( $text ) {
96 96
 
97
-	return str_ireplace( wl_configuration_get_key(), '<hidden>', $text );
97
+    return str_ireplace( wl_configuration_get_key(), '<hidden>', $text );
98 98
 }
99 99
 
100 100
 /**
@@ -102,21 +102,21 @@  discard block
 block discarded – undo
102 102
  * see http://vip.wordpress.com/documentation/register-additional-html-attributes-for-tinymce-and-wp-kses/
103 103
  */
104 104
 function wordlift_allowed_post_tags() {
105
-	global $allowedposttags;
106
-
107
-	$tags           = array( 'span' );
108
-	$new_attributes = array(
109
-		'itemscope' => array(),
110
-		'itemtype'  => array(),
111
-		'itemprop'  => array(),
112
-		'itemid'    => array(),
113
-	);
114
-
115
-	foreach ( $tags as $tag ) {
116
-		if ( isset( $allowedposttags[ $tag ] ) && is_array( $allowedposttags[ $tag ] ) ) {
117
-			$allowedposttags[ $tag ] = array_merge( $allowedposttags[ $tag ], $new_attributes );
118
-		}
119
-	}
105
+    global $allowedposttags;
106
+
107
+    $tags           = array( 'span' );
108
+    $new_attributes = array(
109
+        'itemscope' => array(),
110
+        'itemtype'  => array(),
111
+        'itemprop'  => array(),
112
+        'itemid'    => array(),
113
+    );
114
+
115
+    foreach ( $tags as $tag ) {
116
+        if ( isset( $allowedposttags[ $tag ] ) && is_array( $allowedposttags[ $tag ] ) ) {
117
+            $allowedposttags[ $tag ] = array_merge( $allowedposttags[ $tag ], $new_attributes );
118
+        }
119
+    }
120 120
 }
121 121
 
122 122
 // add allowed post tags.
@@ -127,28 +127,28 @@  discard block
 block discarded – undo
127 127
  */
128 128
 function wordlift_admin_enqueue_scripts() {
129 129
 
130
-	// Added for compatibility with WordPress 3.9 (see http://make.wordpress.org/core/2014/04/16/jquery-ui-and-wpdialogs-in-wordpress-3-9/)
131
-	wp_enqueue_script( 'wpdialogs' );
132
-	wp_enqueue_style( 'wp-jquery-ui-dialog' );
130
+    // Added for compatibility with WordPress 3.9 (see http://make.wordpress.org/core/2014/04/16/jquery-ui-and-wpdialogs-in-wordpress-3-9/)
131
+    wp_enqueue_script( 'wpdialogs' );
132
+    wp_enqueue_style( 'wp-jquery-ui-dialog' );
133 133
 
134
-	wp_enqueue_style( 'wordlift-reloaded', plugin_dir_url( __FILE__ ) . 'css/wordlift-reloaded.min.css' );
134
+    wp_enqueue_style( 'wordlift-reloaded', plugin_dir_url( __FILE__ ) . 'css/wordlift-reloaded.min.css' );
135 135
 
136
-	wp_enqueue_script( 'jquery-ui-autocomplete' );
137
-	wp_enqueue_script( 'angularjs', 'https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.11/angular.min.js' );
138
-	wp_enqueue_script( 'angularjs-geolocation', plugin_dir_url( __FILE__ ) . 'bower_components/angularjs-geolocation/dist/angularjs-geolocation.min.js' );
139
-	wp_enqueue_script( 'angularjs-touch', 'https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.11/angular-touch.min.js' );
140
-	wp_enqueue_script( 'angularjs-animate', 'https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.11/angular-animate.min.js' );
136
+    wp_enqueue_script( 'jquery-ui-autocomplete' );
137
+    wp_enqueue_script( 'angularjs', 'https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.11/angular.min.js' );
138
+    wp_enqueue_script( 'angularjs-geolocation', plugin_dir_url( __FILE__ ) . 'bower_components/angularjs-geolocation/dist/angularjs-geolocation.min.js' );
139
+    wp_enqueue_script( 'angularjs-touch', 'https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.11/angular-touch.min.js' );
140
+    wp_enqueue_script( 'angularjs-animate', 'https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.11/angular-animate.min.js' );
141 141
 
142
-	// Disable auto-save for custom entity posts only
143
-	if ( Wordlift_Entity_Service::TYPE_NAME === get_post_type() ) {
144
-		wp_dequeue_script( 'autosave' );
145
-	}
142
+    // Disable auto-save for custom entity posts only
143
+    if ( Wordlift_Entity_Service::TYPE_NAME === get_post_type() ) {
144
+        wp_dequeue_script( 'autosave' );
145
+    }
146 146
 }
147 147
 
148 148
 add_action( 'admin_enqueue_scripts', 'wordlift_admin_enqueue_scripts' );
149 149
 
150 150
 function wl_enqueue_scripts() {
151
-	wp_enqueue_style( 'wordlift-ui', plugin_dir_url( __FILE__ ) . 'css/wordlift-ui.min.css' );
151
+    wp_enqueue_style( 'wordlift-ui', plugin_dir_url( __FILE__ ) . 'css/wordlift-ui.min.css' );
152 152
 }
153 153
 
154 154
 add_action( 'wp_enqueue_scripts', 'wl_enqueue_scripts' );
@@ -163,18 +163,18 @@  discard block
 block discarded – undo
163 163
  */
164 164
 function wordlift_allowed_html( $allowedtags, $context ) {
165 165
 
166
-	if ( 'post' !== $context ) {
167
-		return $allowedtags;
168
-	}
169
-
170
-	return array_merge_recursive( $allowedtags, array(
171
-		'span' => array(
172
-			'itemscope' => true,
173
-			'itemtype'  => true,
174
-			'itemid'    => true,
175
-			'itemprop'  => true,
176
-		),
177
-	) );
166
+    if ( 'post' !== $context ) {
167
+        return $allowedtags;
168
+    }
169
+
170
+    return array_merge_recursive( $allowedtags, array(
171
+        'span' => array(
172
+            'itemscope' => true,
173
+            'itemtype'  => true,
174
+            'itemid'    => true,
175
+            'itemprop'  => true,
176
+        ),
177
+    ) );
178 178
 }
179 179
 
180 180
 add_filter( 'wp_kses_allowed_html', 'wordlift_allowed_html', 10, 2 );
@@ -188,16 +188,16 @@  discard block
 block discarded – undo
188 188
  */
189 189
 function wl_get_coordinates( $post_id ) {
190 190
 
191
-	$latitude  = wl_schema_get_value( $post_id, 'latitude' );
192
-	$longitude = wl_schema_get_value( $post_id, 'longitude' );
191
+    $latitude  = wl_schema_get_value( $post_id, 'latitude' );
192
+    $longitude = wl_schema_get_value( $post_id, 'longitude' );
193 193
 
194
-	// DO NOT set latitude/longitude to 0/0 as default values. It's a specific
195
-	// place on the globe:"The zero/zero point of this system is located in the
196
-	// Gulf of Guinea about 625 km (390 mi) south of Tema, Ghana."
197
-	return array(
198
-		'latitude'  => isset( $latitude[0] ) && is_numeric( $latitude[0] ) ? $latitude[0] : '',
199
-		'longitude' => isset( $longitude[0] ) && is_numeric( $longitude[0] ) ? $longitude[0] : '',
200
-	);
194
+    // DO NOT set latitude/longitude to 0/0 as default values. It's a specific
195
+    // place on the globe:"The zero/zero point of this system is located in the
196
+    // Gulf of Guinea about 625 km (390 mi) south of Tema, Ghana."
197
+    return array(
198
+        'latitude'  => isset( $latitude[0] ) && is_numeric( $latitude[0] ) ? $latitude[0] : '',
199
+        'longitude' => isset( $longitude[0] ) && is_numeric( $longitude[0] ) ? $longitude[0] : '',
200
+    );
201 201
 }
202 202
 
203 203
 /**
@@ -211,9 +211,9 @@  discard block
 block discarded – undo
211 211
  */
212 212
 function wl_get_image_urls( $post_id ) {
213 213
 
214
-	return Wordlift_Storage_Factory::get_instance()
215
-	                               ->post_images()
216
-	                               ->get( $post_id );
214
+    return Wordlift_Storage_Factory::get_instance()
215
+                                    ->post_images()
216
+                                    ->get( $post_id );
217 217
 
218 218
 //	// If there is a featured image it has the priority.
219 219
 //	$featured_image_id = get_post_thumbnail_id( $post_id );
@@ -261,24 +261,24 @@  discard block
 block discarded – undo
261 261
  */
262 262
 function wl_get_attachment_for_source_url( $parent_post_id, $source_url ) {
263 263
 
264
-	// wl_write_log( "wl_get_attachment_for_source_url [ parent post id :: $parent_post_id ][ source url :: $source_url ]" );
264
+    // wl_write_log( "wl_get_attachment_for_source_url [ parent post id :: $parent_post_id ][ source url :: $source_url ]" );
265 265
 
266
-	$posts = get_posts( array(
267
-		'post_type'      => 'attachment',
268
-		'posts_per_page' => 1,
269
-		'post_status'    => 'any',
270
-		'post_parent'    => $parent_post_id,
271
-		'meta_key'       => 'wl_source_url',
272
-		'meta_value'     => $source_url,
273
-	) );
266
+    $posts = get_posts( array(
267
+        'post_type'      => 'attachment',
268
+        'posts_per_page' => 1,
269
+        'post_status'    => 'any',
270
+        'post_parent'    => $parent_post_id,
271
+        'meta_key'       => 'wl_source_url',
272
+        'meta_value'     => $source_url,
273
+    ) );
274 274
 
275
-	// Return the found post.
276
-	if ( 1 === count( $posts ) ) {
277
-		return $posts[0];
278
-	}
275
+    // Return the found post.
276
+    if ( 1 === count( $posts ) ) {
277
+        return $posts[0];
278
+    }
279 279
 
280
-	// Return null.
281
-	return null;
280
+    // Return null.
281
+    return null;
282 282
 }
283 283
 
284 284
 /**
@@ -289,8 +289,8 @@  discard block
 block discarded – undo
289 289
  */
290 290
 function wl_set_source_url( $post_id, $source_url ) {
291 291
 
292
-	delete_post_meta( $post_id, 'wl_source_url' );
293
-	add_post_meta( $post_id, 'wl_source_url', $source_url );
292
+    delete_post_meta( $post_id, 'wl_source_url' );
293
+    add_post_meta( $post_id, 'wl_source_url', $source_url );
294 294
 }
295 295
 
296 296
 
@@ -307,61 +307,61 @@  discard block
 block discarded – undo
307 307
  */
308 308
 function wl_flush_rewrite_rules_hard( $hard ) {
309 309
 
310
-	// If WL is not yet configured, we cannot perform any update, so we exit.
311
-	if ( '' === wl_configuration_get_key() ) {
312
-		return;
313
-	}
310
+    // If WL is not yet configured, we cannot perform any update, so we exit.
311
+    if ( '' === wl_configuration_get_key() ) {
312
+        return;
313
+    }
314 314
 
315
-	// Set the initial offset and limit each call to 100 posts to avoid memory errors.
316
-	$offset = 0;
317
-	$limit  = 100;
315
+    // Set the initial offset and limit each call to 100 posts to avoid memory errors.
316
+    $offset = 0;
317
+    $limit  = 100;
318 318
 
319
-	// Get more posts if the number of returned posts matches the limit.
320
-	while ( $limit === ( $posts = get_posts( array(
321
-			'offset'      => $offset,
322
-			'numberposts' => $limit,
323
-			'orderby'     => 'ID',
324
-			'post_type'   => 'any',
325
-			'post_status' => 'publish',
326
-		) ) ) ) {
319
+    // Get more posts if the number of returned posts matches the limit.
320
+    while ( $limit === ( $posts = get_posts( array(
321
+            'offset'      => $offset,
322
+            'numberposts' => $limit,
323
+            'orderby'     => 'ID',
324
+            'post_type'   => 'any',
325
+            'post_status' => 'publish',
326
+        ) ) ) ) {
327 327
 
328
-		// Holds the delete part of the query.
329
-		$delete_query = rl_sparql_prefixes();
328
+        // Holds the delete part of the query.
329
+        $delete_query = rl_sparql_prefixes();
330 330
 
331
-		// Holds the insert part of the query.
332
-		$insert_query = '';
331
+        // Holds the insert part of the query.
332
+        $insert_query = '';
333 333
 
334
-		// Cycle in each post to build the query.
335
-		foreach ( $posts as $post ) {
334
+        // Cycle in each post to build the query.
335
+        foreach ( $posts as $post ) {
336 336
 
337
-			// Ignore revisions.
338
-			if ( wp_is_post_revision( $post->ID ) ) {
339
-				continue;
340
-			}
337
+            // Ignore revisions.
338
+            if ( wp_is_post_revision( $post->ID ) ) {
339
+                continue;
340
+            }
341 341
 
342
-			// Get the entity URI.
343
-			$s = Wordlift_Sparql_Service::escape_uri( Wordlift_Entity_Service::get_instance()
344
-			                                                                 ->get_uri( $post->ID ) );
342
+            // Get the entity URI.
343
+            $s = Wordlift_Sparql_Service::escape_uri( Wordlift_Entity_Service::get_instance()
344
+                                                                                ->get_uri( $post->ID ) );
345 345
 
346
-			// Get the post URL.
347
-			// $url = wl_sparql_escape_uri( get_permalink( $post->ID ) );
346
+            // Get the post URL.
347
+            // $url = wl_sparql_escape_uri( get_permalink( $post->ID ) );
348 348
 
349
-			// Prepare the DELETE and INSERT commands.
350
-			$delete_query .= "DELETE { <$s> schema:url ?u . } WHERE  { <$s> schema:url ?u . };\n";
349
+            // Prepare the DELETE and INSERT commands.
350
+            $delete_query .= "DELETE { <$s> schema:url ?u . } WHERE  { <$s> schema:url ?u . };\n";
351 351
 
352
-			$insert_query .= Wordlift_Schema_Url_Property_Service::get_instance()
353
-			                                                     ->get_insert_query( $s, $post->ID );
352
+            $insert_query .= Wordlift_Schema_Url_Property_Service::get_instance()
353
+                                                                    ->get_insert_query( $s, $post->ID );
354 354
 
355
-		}
355
+        }
356 356
 
357 357
 
358
-		// Execute the query.
359
-		rl_execute_sparql_update_query( $delete_query . $insert_query );
358
+        // Execute the query.
359
+        rl_execute_sparql_update_query( $delete_query . $insert_query );
360 360
 
361
-		// Advance to the next posts.
362
-		$offset += $limit;
361
+        // Advance to the next posts.
362
+        $offset += $limit;
363 363
 
364
-	}
364
+    }
365 365
 
366 366
 }
367 367
 
@@ -380,7 +380,7 @@  discard block
 block discarded – undo
380 380
  */
381 381
 function wl_sanitize_uri_path( $path, $char = '_' ) {
382 382
 
383
-	return Wordlift_Uri_Service::get_instance()->sanitize_path( $path, $char );
383
+    return Wordlift_Uri_Service::get_instance()->sanitize_path( $path, $char );
384 384
 }
385 385
 
386 386
 ///**
@@ -421,46 +421,46 @@  discard block
 block discarded – undo
421 421
  */
422 422
 function wl_replace_item_id_with_uri( $content ) {
423 423
 
424
-	// wl_write_log( "wl_replace_item_id_with_uri" );
424
+    // wl_write_log( "wl_replace_item_id_with_uri" );
425 425
 
426
-	// Strip slashes, see https://core.trac.wordpress.org/ticket/21767
427
-	$content = stripslashes( $content );
426
+    // Strip slashes, see https://core.trac.wordpress.org/ticket/21767
427
+    $content = stripslashes( $content );
428 428
 
429
-	// If any match are found.
430
-	$matches = array();
431
-	if ( 0 < preg_match_all( '/ itemid="([^"]+)"/i', $content, $matches, PREG_SET_ORDER ) ) {
429
+    // If any match are found.
430
+    $matches = array();
431
+    if ( 0 < preg_match_all( '/ itemid="([^"]+)"/i', $content, $matches, PREG_SET_ORDER ) ) {
432 432
 
433
-		foreach ( $matches as $match ) {
433
+        foreach ( $matches as $match ) {
434 434
 
435
-			// Get the item ID.
436
-			$item_id = $match[1];
435
+            // Get the item ID.
436
+            $item_id = $match[1];
437 437
 
438
-			// Get the post bound to that item ID (looking both in the 'official' URI and in the 'same-as' .
439
-			$post = Wordlift_Entity_Service::get_instance()
440
-			                               ->get_entity_post_by_uri( $item_id );
438
+            // Get the post bound to that item ID (looking both in the 'official' URI and in the 'same-as' .
439
+            $post = Wordlift_Entity_Service::get_instance()
440
+                                            ->get_entity_post_by_uri( $item_id );
441 441
 
442
-			// If no entity is found, continue to the next one.
443
-			if ( null === $post ) {
444
-				continue;
445
-			}
442
+            // If no entity is found, continue to the next one.
443
+            if ( null === $post ) {
444
+                continue;
445
+            }
446 446
 
447
-			// Get the URI for that post.
448
-			$uri = wl_get_entity_uri( $post->ID );
447
+            // Get the URI for that post.
448
+            $uri = wl_get_entity_uri( $post->ID );
449 449
 
450
-			// wl_write_log( "wl_replace_item_id_with_uri [ item id :: $item_id ][ uri :: $uri ]" );
450
+            // wl_write_log( "wl_replace_item_id_with_uri [ item id :: $item_id ][ uri :: $uri ]" );
451 451
 
452
-			// If the item ID and the URI differ, replace the item ID with the URI saved in WordPress.
453
-			if ( $item_id !== $uri ) {
454
-				$uri_e   = esc_html( $uri );
455
-				$content = str_replace( " itemid=\"$item_id\"", " itemid=\"$uri_e\"", $content );
456
-			}
457
-		}
458
-	}
452
+            // If the item ID and the URI differ, replace the item ID with the URI saved in WordPress.
453
+            if ( $item_id !== $uri ) {
454
+                $uri_e   = esc_html( $uri );
455
+                $content = str_replace( " itemid=\"$item_id\"", " itemid=\"$uri_e\"", $content );
456
+            }
457
+        }
458
+    }
459 459
 
460
-	// Reapply slashes.
461
-	$content = addslashes( $content );
460
+    // Reapply slashes.
461
+    $content = addslashes( $content );
462 462
 
463
-	return $content;
463
+    return $content;
464 464
 }
465 465
 
466 466
 add_filter( 'content_save_pre', 'wl_replace_item_id_with_uri', 1, 1 );
@@ -528,9 +528,9 @@  discard block
 block discarded – undo
528 528
  */
529 529
 function activate_wordlift() {
530 530
 
531
-	require_once plugin_dir_path( __FILE__ ) . 'includes/class-wordlift-activator.php';
532
-	Wordlift_Activator::activate();
533
-	flush_rewrite_rules();
531
+    require_once plugin_dir_path( __FILE__ ) . 'includes/class-wordlift-activator.php';
532
+    Wordlift_Activator::activate();
533
+    flush_rewrite_rules();
534 534
 
535 535
 }
536 536
 
@@ -540,9 +540,9 @@  discard block
 block discarded – undo
540 540
  */
541 541
 function deactivate_wordlift() {
542 542
 
543
-	require_once plugin_dir_path( __FILE__ ) . 'includes/class-wordlift-deactivator.php';
544
-	Wordlift_Deactivator::deactivate();
545
-	flush_rewrite_rules();
543
+    require_once plugin_dir_path( __FILE__ ) . 'includes/class-wordlift-deactivator.php';
544
+    Wordlift_Deactivator::deactivate();
545
+    flush_rewrite_rules();
546 546
 
547 547
 }
548 548
 
@@ -566,8 +566,8 @@  discard block
 block discarded – undo
566 566
  */
567 567
 function run_wordlift() {
568 568
 
569
-	$plugin = new Wordlift();
570
-	$plugin->run();
569
+    $plugin = new Wordlift();
570
+    $plugin->run();
571 571
 
572 572
 }
573 573
 
Please login to merge, or discard this patch.
Spacing   +107 added lines, -107 removed lines patch added patch discarded remove patch
@@ -25,15 +25,15 @@  discard block
 block discarded – undo
25 25
  */
26 26
 
27 27
 // If this file is called directly, abort.
28
-if ( ! defined( 'WPINC' ) ) {
28
+if ( ! defined('WPINC')) {
29 29
 	die;
30 30
 }
31 31
 
32 32
 // Include WordLift constants.
33
-require_once( 'wordlift_constants.php' );
33
+require_once('wordlift_constants.php');
34 34
 
35 35
 // Load modules.
36
-require_once( 'modules/core/wordlift_core.php' );
36
+require_once('modules/core/wordlift_core.php');
37 37
 
38 38
 /**
39 39
  * Log to the debug.log file.
@@ -46,9 +46,9 @@  discard block
 block discarded – undo
46 46
  *
47 47
  * @param string|mixed $log The log data.
48 48
  */
49
-function wl_write_log( $log ) {
49
+function wl_write_log($log) {
50 50
 
51
-	Wordlift_Log_Service::get_instance()->debug( $log );
51
+	Wordlift_Log_Service::get_instance()->debug($log);
52 52
 
53 53
 }
54 54
 
@@ -62,19 +62,19 @@  discard block
 block discarded – undo
62 62
  * @param string|array $log    The log data.
63 63
  * @param string       $caller The calling function.
64 64
  */
65
-function wl_write_log_handler( $log, $caller = null ) {
65
+function wl_write_log_handler($log, $caller = null) {
66 66
 
67 67
 	global $wl_logger;
68 68
 
69
-	if ( true === WP_DEBUG ) {
69
+	if (true === WP_DEBUG) {
70 70
 
71
-		$message = ( isset( $caller ) ? sprintf( '[%-40.40s] ', $caller ) : '' ) .
72
-		           ( is_array( $log ) || is_object( $log ) ? print_r( $log, true ) : wl_write_log_hide_key( $log ) );
71
+		$message = (isset($caller) ? sprintf('[%-40.40s] ', $caller) : '').
72
+		           (is_array($log) || is_object($log) ? print_r($log, true) : wl_write_log_hide_key($log));
73 73
 
74
-		if ( isset( $wl_logger ) ) {
75
-			$wl_logger->info( $message );
74
+		if (isset($wl_logger)) {
75
+			$wl_logger->info($message);
76 76
 		} else {
77
-			error_log( $message );
77
+			error_log($message);
78 78
 		}
79 79
 
80 80
 	}
@@ -92,9 +92,9 @@  discard block
 block discarded – undo
92 92
  *
93 93
  * @return string A text with the key hidden.
94 94
  */
95
-function wl_write_log_hide_key( $text ) {
95
+function wl_write_log_hide_key($text) {
96 96
 
97
-	return str_ireplace( wl_configuration_get_key(), '<hidden>', $text );
97
+	return str_ireplace(wl_configuration_get_key(), '<hidden>', $text);
98 98
 }
99 99
 
100 100
 /**
@@ -104,7 +104,7 @@  discard block
 block discarded – undo
104 104
 function wordlift_allowed_post_tags() {
105 105
 	global $allowedposttags;
106 106
 
107
-	$tags           = array( 'span' );
107
+	$tags           = array('span');
108 108
 	$new_attributes = array(
109 109
 		'itemscope' => array(),
110 110
 		'itemtype'  => array(),
@@ -112,15 +112,15 @@  discard block
 block discarded – undo
112 112
 		'itemid'    => array(),
113 113
 	);
114 114
 
115
-	foreach ( $tags as $tag ) {
116
-		if ( isset( $allowedposttags[ $tag ] ) && is_array( $allowedposttags[ $tag ] ) ) {
117
-			$allowedposttags[ $tag ] = array_merge( $allowedposttags[ $tag ], $new_attributes );
115
+	foreach ($tags as $tag) {
116
+		if (isset($allowedposttags[$tag]) && is_array($allowedposttags[$tag])) {
117
+			$allowedposttags[$tag] = array_merge($allowedposttags[$tag], $new_attributes);
118 118
 		}
119 119
 	}
120 120
 }
121 121
 
122 122
 // add allowed post tags.
123
-add_action( 'init', 'wordlift_allowed_post_tags' );
123
+add_action('init', 'wordlift_allowed_post_tags');
124 124
 
125 125
 /**
126 126
  * Register additional scripts for the admin UI.
@@ -128,30 +128,30 @@  discard block
 block discarded – undo
128 128
 function wordlift_admin_enqueue_scripts() {
129 129
 
130 130
 	// Added for compatibility with WordPress 3.9 (see http://make.wordpress.org/core/2014/04/16/jquery-ui-and-wpdialogs-in-wordpress-3-9/)
131
-	wp_enqueue_script( 'wpdialogs' );
132
-	wp_enqueue_style( 'wp-jquery-ui-dialog' );
131
+	wp_enqueue_script('wpdialogs');
132
+	wp_enqueue_style('wp-jquery-ui-dialog');
133 133
 
134
-	wp_enqueue_style( 'wordlift-reloaded', plugin_dir_url( __FILE__ ) . 'css/wordlift-reloaded.min.css' );
134
+	wp_enqueue_style('wordlift-reloaded', plugin_dir_url(__FILE__).'css/wordlift-reloaded.min.css');
135 135
 
136
-	wp_enqueue_script( 'jquery-ui-autocomplete' );
137
-	wp_enqueue_script( 'angularjs', 'https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.11/angular.min.js' );
138
-	wp_enqueue_script( 'angularjs-geolocation', plugin_dir_url( __FILE__ ) . 'bower_components/angularjs-geolocation/dist/angularjs-geolocation.min.js' );
139
-	wp_enqueue_script( 'angularjs-touch', 'https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.11/angular-touch.min.js' );
140
-	wp_enqueue_script( 'angularjs-animate', 'https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.11/angular-animate.min.js' );
136
+	wp_enqueue_script('jquery-ui-autocomplete');
137
+	wp_enqueue_script('angularjs', 'https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.11/angular.min.js');
138
+	wp_enqueue_script('angularjs-geolocation', plugin_dir_url(__FILE__).'bower_components/angularjs-geolocation/dist/angularjs-geolocation.min.js');
139
+	wp_enqueue_script('angularjs-touch', 'https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.11/angular-touch.min.js');
140
+	wp_enqueue_script('angularjs-animate', 'https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.11/angular-animate.min.js');
141 141
 
142 142
 	// Disable auto-save for custom entity posts only
143
-	if ( Wordlift_Entity_Service::TYPE_NAME === get_post_type() ) {
144
-		wp_dequeue_script( 'autosave' );
143
+	if (Wordlift_Entity_Service::TYPE_NAME === get_post_type()) {
144
+		wp_dequeue_script('autosave');
145 145
 	}
146 146
 }
147 147
 
148
-add_action( 'admin_enqueue_scripts', 'wordlift_admin_enqueue_scripts' );
148
+add_action('admin_enqueue_scripts', 'wordlift_admin_enqueue_scripts');
149 149
 
150 150
 function wl_enqueue_scripts() {
151
-	wp_enqueue_style( 'wordlift-ui', plugin_dir_url( __FILE__ ) . 'css/wordlift-ui.min.css' );
151
+	wp_enqueue_style('wordlift-ui', plugin_dir_url(__FILE__).'css/wordlift-ui.min.css');
152 152
 }
153 153
 
154
-add_action( 'wp_enqueue_scripts', 'wl_enqueue_scripts' );
154
+add_action('wp_enqueue_scripts', 'wl_enqueue_scripts');
155 155
 
156 156
 /**
157 157
  * Hooked to *wp_kses_allowed_html* filter, adds microdata attributes.
@@ -161,23 +161,23 @@  discard block
 block discarded – undo
161 161
  *
162 162
  * @return array An array which contains allowed microdata attributes.
163 163
  */
164
-function wordlift_allowed_html( $allowedtags, $context ) {
164
+function wordlift_allowed_html($allowedtags, $context) {
165 165
 
166
-	if ( 'post' !== $context ) {
166
+	if ('post' !== $context) {
167 167
 		return $allowedtags;
168 168
 	}
169 169
 
170
-	return array_merge_recursive( $allowedtags, array(
170
+	return array_merge_recursive($allowedtags, array(
171 171
 		'span' => array(
172 172
 			'itemscope' => true,
173 173
 			'itemtype'  => true,
174 174
 			'itemid'    => true,
175 175
 			'itemprop'  => true,
176 176
 		),
177
-	) );
177
+	));
178 178
 }
179 179
 
180
-add_filter( 'wp_kses_allowed_html', 'wordlift_allowed_html', 10, 2 );
180
+add_filter('wp_kses_allowed_html', 'wordlift_allowed_html', 10, 2);
181 181
 
182 182
 /**
183 183
  * Get the coordinates for the specified post ID.
@@ -186,17 +186,17 @@  discard block
 block discarded – undo
186 186
  *
187 187
  * @return array|null An array of coordinates or null.
188 188
  */
189
-function wl_get_coordinates( $post_id ) {
189
+function wl_get_coordinates($post_id) {
190 190
 
191
-	$latitude  = wl_schema_get_value( $post_id, 'latitude' );
192
-	$longitude = wl_schema_get_value( $post_id, 'longitude' );
191
+	$latitude  = wl_schema_get_value($post_id, 'latitude');
192
+	$longitude = wl_schema_get_value($post_id, 'longitude');
193 193
 
194 194
 	// DO NOT set latitude/longitude to 0/0 as default values. It's a specific
195 195
 	// place on the globe:"The zero/zero point of this system is located in the
196 196
 	// Gulf of Guinea about 625 km (390 mi) south of Tema, Ghana."
197 197
 	return array(
198
-		'latitude'  => isset( $latitude[0] ) && is_numeric( $latitude[0] ) ? $latitude[0] : '',
199
-		'longitude' => isset( $longitude[0] ) && is_numeric( $longitude[0] ) ? $longitude[0] : '',
198
+		'latitude'  => isset($latitude[0]) && is_numeric($latitude[0]) ? $latitude[0] : '',
199
+		'longitude' => isset($longitude[0]) && is_numeric($longitude[0]) ? $longitude[0] : '',
200 200
 	);
201 201
 }
202 202
 
@@ -209,11 +209,11 @@  discard block
 block discarded – undo
209 209
  *
210 210
  * @return array An array of image URLs.
211 211
  */
212
-function wl_get_image_urls( $post_id ) {
212
+function wl_get_image_urls($post_id) {
213 213
 
214 214
 	return Wordlift_Storage_Factory::get_instance()
215 215
 	                               ->post_images()
216
-	                               ->get( $post_id );
216
+	                               ->get($post_id);
217 217
 
218 218
 //	// If there is a featured image it has the priority.
219 219
 //	$featured_image_id = get_post_thumbnail_id( $post_id );
@@ -259,21 +259,21 @@  discard block
 block discarded – undo
259 259
  *
260 260
  * @return WP_Post|null A post instance or null if not found.
261 261
  */
262
-function wl_get_attachment_for_source_url( $parent_post_id, $source_url ) {
262
+function wl_get_attachment_for_source_url($parent_post_id, $source_url) {
263 263
 
264 264
 	// wl_write_log( "wl_get_attachment_for_source_url [ parent post id :: $parent_post_id ][ source url :: $source_url ]" );
265 265
 
266
-	$posts = get_posts( array(
266
+	$posts = get_posts(array(
267 267
 		'post_type'      => 'attachment',
268 268
 		'posts_per_page' => 1,
269 269
 		'post_status'    => 'any',
270 270
 		'post_parent'    => $parent_post_id,
271 271
 		'meta_key'       => 'wl_source_url',
272 272
 		'meta_value'     => $source_url,
273
-	) );
273
+	));
274 274
 
275 275
 	// Return the found post.
276
-	if ( 1 === count( $posts ) ) {
276
+	if (1 === count($posts)) {
277 277
 		return $posts[0];
278 278
 	}
279 279
 
@@ -287,10 +287,10 @@  discard block
 block discarded – undo
287 287
  * @param int    $post_id    The post ID.
288 288
  * @param string $source_url The source URL.
289 289
  */
290
-function wl_set_source_url( $post_id, $source_url ) {
290
+function wl_set_source_url($post_id, $source_url) {
291 291
 
292
-	delete_post_meta( $post_id, 'wl_source_url' );
293
-	add_post_meta( $post_id, 'wl_source_url', $source_url );
292
+	delete_post_meta($post_id, 'wl_source_url');
293
+	add_post_meta($post_id, 'wl_source_url', $source_url);
294 294
 }
295 295
 
296 296
 
@@ -305,10 +305,10 @@  discard block
 block discarded – undo
305 305
  *
306 306
  * @param bool $hard True if the rewrite involves configuration updates in Apache/IIS.
307 307
  */
308
-function wl_flush_rewrite_rules_hard( $hard ) {
308
+function wl_flush_rewrite_rules_hard($hard) {
309 309
 
310 310
 	// If WL is not yet configured, we cannot perform any update, so we exit.
311
-	if ( '' === wl_configuration_get_key() ) {
311
+	if ('' === wl_configuration_get_key()) {
312 312
 		return;
313 313
 	}
314 314
 
@@ -317,13 +317,13 @@  discard block
 block discarded – undo
317 317
 	$limit  = 100;
318 318
 
319 319
 	// Get more posts if the number of returned posts matches the limit.
320
-	while ( $limit === ( $posts = get_posts( array(
320
+	while ($limit === ($posts = get_posts(array(
321 321
 			'offset'      => $offset,
322 322
 			'numberposts' => $limit,
323 323
 			'orderby'     => 'ID',
324 324
 			'post_type'   => 'any',
325 325
 			'post_status' => 'publish',
326
-		) ) ) ) {
326
+		)))) {
327 327
 
328 328
 		// Holds the delete part of the query.
329 329
 		$delete_query = rl_sparql_prefixes();
@@ -332,16 +332,16 @@  discard block
 block discarded – undo
332 332
 		$insert_query = '';
333 333
 
334 334
 		// Cycle in each post to build the query.
335
-		foreach ( $posts as $post ) {
335
+		foreach ($posts as $post) {
336 336
 
337 337
 			// Ignore revisions.
338
-			if ( wp_is_post_revision( $post->ID ) ) {
338
+			if (wp_is_post_revision($post->ID)) {
339 339
 				continue;
340 340
 			}
341 341
 
342 342
 			// Get the entity URI.
343
-			$s = Wordlift_Sparql_Service::escape_uri( Wordlift_Entity_Service::get_instance()
344
-			                                                                 ->get_uri( $post->ID ) );
343
+			$s = Wordlift_Sparql_Service::escape_uri(Wordlift_Entity_Service::get_instance()
344
+			                                                                 ->get_uri($post->ID));
345 345
 
346 346
 			// Get the post URL.
347 347
 			// $url = wl_sparql_escape_uri( get_permalink( $post->ID ) );
@@ -350,13 +350,13 @@  discard block
 block discarded – undo
350 350
 			$delete_query .= "DELETE { <$s> schema:url ?u . } WHERE  { <$s> schema:url ?u . };\n";
351 351
 
352 352
 			$insert_query .= Wordlift_Schema_Url_Property_Service::get_instance()
353
-			                                                     ->get_insert_query( $s, $post->ID );
353
+			                                                     ->get_insert_query($s, $post->ID);
354 354
 
355 355
 		}
356 356
 
357 357
 
358 358
 		// Execute the query.
359
-		rl_execute_sparql_update_query( $delete_query . $insert_query );
359
+		rl_execute_sparql_update_query($delete_query.$insert_query);
360 360
 
361 361
 		// Advance to the next posts.
362 362
 		$offset += $limit;
@@ -365,7 +365,7 @@  discard block
 block discarded – undo
365 365
 
366 366
 }
367 367
 
368
-add_filter( 'flush_rewrite_rules_hard', 'wl_flush_rewrite_rules_hard', 10, 1 );
368
+add_filter('flush_rewrite_rules_hard', 'wl_flush_rewrite_rules_hard', 10, 1);
369 369
 
370 370
 /**
371 371
  * Sanitizes an URI path by replacing the non allowed characters with an underscore.
@@ -378,9 +378,9 @@  discard block
 block discarded – undo
378 378
  *
379 379
  * @return string The sanitized path.
380 380
  */
381
-function wl_sanitize_uri_path( $path, $char = '_' ) {
381
+function wl_sanitize_uri_path($path, $char = '_') {
382 382
 
383
-	return Wordlift_Uri_Service::get_instance()->sanitize_path( $path, $char );
383
+	return Wordlift_Uri_Service::get_instance()->sanitize_path($path, $char);
384 384
 }
385 385
 
386 386
 ///**
@@ -419,107 +419,107 @@  discard block
 block discarded – undo
419 419
  *
420 420
  * @return string The updated post content.
421 421
  */
422
-function wl_replace_item_id_with_uri( $content ) {
422
+function wl_replace_item_id_with_uri($content) {
423 423
 
424 424
 	// wl_write_log( "wl_replace_item_id_with_uri" );
425 425
 
426 426
 	// Strip slashes, see https://core.trac.wordpress.org/ticket/21767
427
-	$content = stripslashes( $content );
427
+	$content = stripslashes($content);
428 428
 
429 429
 	// If any match are found.
430 430
 	$matches = array();
431
-	if ( 0 < preg_match_all( '/ itemid="([^"]+)"/i', $content, $matches, PREG_SET_ORDER ) ) {
431
+	if (0 < preg_match_all('/ itemid="([^"]+)"/i', $content, $matches, PREG_SET_ORDER)) {
432 432
 
433
-		foreach ( $matches as $match ) {
433
+		foreach ($matches as $match) {
434 434
 
435 435
 			// Get the item ID.
436 436
 			$item_id = $match[1];
437 437
 
438 438
 			// Get the post bound to that item ID (looking both in the 'official' URI and in the 'same-as' .
439 439
 			$post = Wordlift_Entity_Service::get_instance()
440
-			                               ->get_entity_post_by_uri( $item_id );
440
+			                               ->get_entity_post_by_uri($item_id);
441 441
 
442 442
 			// If no entity is found, continue to the next one.
443
-			if ( null === $post ) {
443
+			if (null === $post) {
444 444
 				continue;
445 445
 			}
446 446
 
447 447
 			// Get the URI for that post.
448
-			$uri = wl_get_entity_uri( $post->ID );
448
+			$uri = wl_get_entity_uri($post->ID);
449 449
 
450 450
 			// wl_write_log( "wl_replace_item_id_with_uri [ item id :: $item_id ][ uri :: $uri ]" );
451 451
 
452 452
 			// If the item ID and the URI differ, replace the item ID with the URI saved in WordPress.
453
-			if ( $item_id !== $uri ) {
454
-				$uri_e   = esc_html( $uri );
455
-				$content = str_replace( " itemid=\"$item_id\"", " itemid=\"$uri_e\"", $content );
453
+			if ($item_id !== $uri) {
454
+				$uri_e   = esc_html($uri);
455
+				$content = str_replace(" itemid=\"$item_id\"", " itemid=\"$uri_e\"", $content);
456 456
 			}
457 457
 		}
458 458
 	}
459 459
 
460 460
 	// Reapply slashes.
461
-	$content = addslashes( $content );
461
+	$content = addslashes($content);
462 462
 
463 463
 	return $content;
464 464
 }
465 465
 
466
-add_filter( 'content_save_pre', 'wl_replace_item_id_with_uri', 1, 1 );
466
+add_filter('content_save_pre', 'wl_replace_item_id_with_uri', 1, 1);
467 467
 
468
-require_once( 'wordlift_entity_functions.php' );
468
+require_once('wordlift_entity_functions.php');
469 469
 
470 470
 // add editor related methods.
471
-require_once( 'wordlift_editor.php' );
471
+require_once('wordlift_editor.php');
472 472
 
473 473
 // add the WordLift entity custom type.
474
-require_once( 'wordlift_entity_type.php' );
475
-require_once( 'wordlift_entity_type_taxonomy.php' );
474
+require_once('wordlift_entity_type.php');
475
+require_once('wordlift_entity_type_taxonomy.php');
476 476
 
477 477
 // add callbacks on post save to notify data changes from wp to redlink triple store
478
-require_once( 'wordlift_to_redlink_data_push_callbacks.php' );
478
+require_once('wordlift_to_redlink_data_push_callbacks.php');
479 479
 
480
-require_once( 'modules/configuration/wordlift_configuration_settings.php' );
480
+require_once('modules/configuration/wordlift_configuration_settings.php');
481 481
 
482 482
 // Load modules
483
-require_once( 'modules/analyzer/wordlift_analyzer.php' );
484
-require_once( 'modules/linked_data/wordlift_linked_data.php' );
485
-require_once( 'modules/prefixes/wordlift_prefixes.php' );
483
+require_once('modules/analyzer/wordlift_analyzer.php');
484
+require_once('modules/linked_data/wordlift_linked_data.php');
485
+require_once('modules/prefixes/wordlift_prefixes.php');
486 486
 
487 487
 // Shortcodes
488 488
 
489
-require_once( 'modules/geo_widget/wordlift_geo_widget.php' );
490
-require_once( 'shortcodes/wordlift_shortcode_chord.php' );
491
-require_once( 'shortcodes/wordlift_shortcode_geomap.php' );
492
-require_once( 'shortcodes/wordlift_shortcode_field.php' );
493
-require_once( 'shortcodes/wordlift_shortcode_faceted_search.php' );
494
-require_once( 'shortcodes/wordlift_shortcode_navigator.php' );
489
+require_once('modules/geo_widget/wordlift_geo_widget.php');
490
+require_once('shortcodes/wordlift_shortcode_chord.php');
491
+require_once('shortcodes/wordlift_shortcode_geomap.php');
492
+require_once('shortcodes/wordlift_shortcode_field.php');
493
+require_once('shortcodes/wordlift_shortcode_faceted_search.php');
494
+require_once('shortcodes/wordlift_shortcode_navigator.php');
495 495
 
496
-require_once( 'widgets/wordlift_widget_geo.php' );
497
-require_once( 'widgets/wordlift_widget_chord.php' );
498
-require_once( 'widgets/wordlift_widget_timeline.php' );
496
+require_once('widgets/wordlift_widget_geo.php');
497
+require_once('widgets/wordlift_widget_chord.php');
498
+require_once('widgets/wordlift_widget_timeline.php');
499 499
 
500
-require_once( 'wordlift_redlink.php' );
500
+require_once('wordlift_redlink.php');
501 501
 
502 502
 // Add admin functions.
503 503
 // TODO: find a way to make 'admin' UI tests work.
504 504
 //if ( is_admin() ) {
505 505
 
506
-require_once( 'admin/wordlift_admin.php' );
507
-require_once( 'admin/wordlift_admin_edit_post.php' );
508
-require_once( 'admin/wordlift_admin_save_post.php' );
506
+require_once('admin/wordlift_admin.php');
507
+require_once('admin/wordlift_admin_edit_post.php');
508
+require_once('admin/wordlift_admin_save_post.php');
509 509
 
510 510
 // add the entities meta box.
511
-require_once( 'admin/wordlift_admin_meta_box_entities.php' );
511
+require_once('admin/wordlift_admin_meta_box_entities.php');
512 512
 
513 513
 // add the entity creation AJAX.
514
-require_once( 'admin/wordlift_admin_ajax_related_posts.php' );
514
+require_once('admin/wordlift_admin_ajax_related_posts.php');
515 515
 
516 516
 // Load the wl_chord TinyMCE button and configuration dialog.
517
-require_once( 'admin/wordlift_admin_shortcodes.php' );
517
+require_once('admin/wordlift_admin_shortcodes.php');
518 518
 
519 519
 // load languages.
520 520
 // TODO: the following call gives for granted that the plugin is in the wordlift directory,
521 521
 //       we're currently doing this because wordlift is symbolic linked.
522
-load_plugin_textdomain( 'wordlift', false, '/wordlift/languages' );
522
+load_plugin_textdomain('wordlift', false, '/wordlift/languages');
523 523
 
524 524
 
525 525
 /**
@@ -528,7 +528,7 @@  discard block
 block discarded – undo
528 528
  */
529 529
 function activate_wordlift() {
530 530
 
531
-	require_once plugin_dir_path( __FILE__ ) . 'includes/class-wordlift-activator.php';
531
+	require_once plugin_dir_path(__FILE__).'includes/class-wordlift-activator.php';
532 532
 	Wordlift_Activator::activate();
533 533
 	flush_rewrite_rules();
534 534
 
@@ -540,20 +540,20 @@  discard block
 block discarded – undo
540 540
  */
541 541
 function deactivate_wordlift() {
542 542
 
543
-	require_once plugin_dir_path( __FILE__ ) . 'includes/class-wordlift-deactivator.php';
543
+	require_once plugin_dir_path(__FILE__).'includes/class-wordlift-deactivator.php';
544 544
 	Wordlift_Deactivator::deactivate();
545 545
 	flush_rewrite_rules();
546 546
 
547 547
 }
548 548
 
549
-register_activation_hook( __FILE__, 'activate_wordlift' );
550
-register_deactivation_hook( __FILE__, 'deactivate_wordlift' );
549
+register_activation_hook(__FILE__, 'activate_wordlift');
550
+register_deactivation_hook(__FILE__, 'deactivate_wordlift');
551 551
 
552 552
 /**
553 553
  * The core plugin class that is used to define internationalization,
554 554
  * admin-specific hooks, and public-facing site hooks.
555 555
  */
556
-require plugin_dir_path( __FILE__ ) . 'includes/class-wordlift.php';
556
+require plugin_dir_path(__FILE__).'includes/class-wordlift.php';
557 557
 
558 558
 /**
559 559
  * Begins execution of the plugin.
Please login to merge, or discard this patch.
src/wordlift_constants.php 2 patches
Indentation   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -5,14 +5,14 @@  discard block
 block discarded – undo
5 5
 
6 6
 // Define the basic options for HTTP calls to REDLINK.
7 7
 define( 'WL_REDLINK_API_HTTP_OPTIONS', serialize( array(
8
-	'timeout'         => 300,
9
-	'redirection'     => 5,
10
-	'httpversion'     => '1.1',
11
-	'blocking'        => true,
12
-	'cookies'         => array(),
13
-	'sslverify'       => ( 'false' === getenv( 'WL_SSL_VERIFY_ENABLED' ) ) ? false : true,
14
-	'sslcertificates' => dirname( __FILE__ ) . '/ssl/ca-bundle.crt',
15
-	'decompress'      => false,
8
+    'timeout'         => 300,
9
+    'redirection'     => 5,
10
+    'httpversion'     => '1.1',
11
+    'blocking'        => true,
12
+    'cookies'         => array(),
13
+    'sslverify'       => ( 'false' === getenv( 'WL_SSL_VERIFY_ENABLED' ) ) ? false : true,
14
+    'sslcertificates' => dirname( __FILE__ ) . '/ssl/ca-bundle.crt',
15
+    'decompress'      => false,
16 16
 ) ) );
17 17
 
18 18
 // Create a unique ID for this request, useful to hook async HTTP requests.
@@ -25,11 +25,11 @@  discard block
 block discarded – undo
25 25
 
26 26
 function wl_is_sparql_update_queries_buffering_enabled() {
27 27
 
28
-	if ( isset( $_REQUEST['wl-async'] ) && 'false' === $_REQUEST['wl-async'] ) {
29
-		return false;
30
-	}
28
+    if ( isset( $_REQUEST['wl-async'] ) && 'false' === $_REQUEST['wl-async'] ) {
29
+        return false;
30
+    }
31 31
 
32
-	return 'true' !== getenv( 'WL_DISABLE_SPARQL_UPDATE_QUERIES_BUFFERING' );
32
+    return 'true' !== getenv( 'WL_DISABLE_SPARQL_UPDATE_QUERIES_BUFFERING' );
33 33
 }
34 34
 
35 35
 // Define the meta name used to store the entity URL.
@@ -52,13 +52,13 @@  discard block
 block discarded – undo
52 52
  */
53 53
 function wl_prefixes() {
54 54
 
55
-	$items    = wl_prefixes_list();
56
-	$prefixes = array();
55
+    $items    = wl_prefixes_list();
56
+    $prefixes = array();
57 57
 
58
-	foreach ( $items as $item ) {
59
-		$prefixes[ $item['prefix'] ] = $item['namespace'];
60
-	}
58
+    foreach ( $items as $item ) {
59
+        $prefixes[ $item['prefix'] ] = $item['namespace'];
60
+    }
61 61
 
62
-	return $prefixes;
62
+    return $prefixes;
63 63
 
64 64
 }
Please login to merge, or discard this patch.
Spacing   +16 added lines, -16 removed lines patch added patch discarded remove patch
@@ -6,49 +6,49 @@  discard block
 block discarded – undo
6 6
  */
7 7
 
8 8
 // Define the basic options for HTTP calls to REDLINK.
9
-define( 'WL_REDLINK_API_HTTP_OPTIONS', serialize( array(
9
+define('WL_REDLINK_API_HTTP_OPTIONS', serialize(array(
10 10
 	'timeout'         => 300,
11 11
 	'redirection'     => 5,
12 12
 	'httpversion'     => '1.1',
13 13
 	'blocking'        => true,
14 14
 	'cookies'         => array(),
15
-	'sslverify'       => ( 'false' === getenv( 'WL_SSL_VERIFY_ENABLED' ) ) ? false : true,
16
-	'sslcertificates' => dirname( __FILE__ ) . '/ssl/ca-bundle.crt',
15
+	'sslverify'       => ('false' === getenv('WL_SSL_VERIFY_ENABLED')) ? false : true,
16
+	'sslcertificates' => dirname(__FILE__).'/ssl/ca-bundle.crt',
17 17
 	'decompress'      => false,
18
-) ) );
18
+)));
19 19
 
20 20
 // Create a unique ID for this request, useful to hook async HTTP requests.
21
-define( 'WL_REQUEST_ID', uniqid( true ) );
21
+define('WL_REQUEST_ID', uniqid(true));
22 22
 
23 23
 // Set the temporary files folder.
24
-defined( 'WL_TEMP_DIR' ) || define( 'WL_TEMP_DIR', get_temp_dir() );
24
+defined('WL_TEMP_DIR') || define('WL_TEMP_DIR', get_temp_dir());
25 25
 
26
-define( 'WL_ENABLE_SPARQL_UPDATE_QUERIES_BUFFERING', wl_is_sparql_update_queries_buffering_enabled() );
26
+define('WL_ENABLE_SPARQL_UPDATE_QUERIES_BUFFERING', wl_is_sparql_update_queries_buffering_enabled());
27 27
 
28 28
 function wl_is_sparql_update_queries_buffering_enabled() {
29 29
 
30
-	if ( isset( $_REQUEST['wl-async'] ) && 'false' === $_REQUEST['wl-async'] ) {
30
+	if (isset($_REQUEST['wl-async']) && 'false' === $_REQUEST['wl-async']) {
31 31
 		return false;
32 32
 	}
33 33
 
34
-	return 'true' !== getenv( 'WL_DISABLE_SPARQL_UPDATE_QUERIES_BUFFERING' );
34
+	return 'true' !== getenv('WL_DISABLE_SPARQL_UPDATE_QUERIES_BUFFERING');
35 35
 }
36 36
 
37 37
 // Define the meta name used to store the entity URL.
38
-define( 'WL_ENTITY_URL_META_NAME', 'entity_url' );
38
+define('WL_ENTITY_URL_META_NAME', 'entity_url');
39 39
 
40 40
 // Max number of recursions when printing microdata.
41
-define( 'WL_RECURSION_DEPTH_ON_ENTITY_METADATA_PRINTING', 3 );
41
+define('WL_RECURSION_DEPTH_ON_ENTITY_METADATA_PRINTING', 3);
42 42
 
43 43
 // 3.13.0, we use by default WLS 1.11 which provides us with the new, faster
44 44
 // chunked analysis.
45
-define( 'WL_CONFIG_WORDLIFT_API_URL_DEFAULT_VALUE', defined( 'WORDLIFT_API_URL' ) ? WORDLIFT_API_URL . '/' : 'https://api.wordlift.it/' );
45
+define('WL_CONFIG_WORDLIFT_API_URL_DEFAULT_VALUE', defined('WORDLIFT_API_URL') ? WORDLIFT_API_URL . '/' : 'https://api.wordlift.it/');
46 46
 
47
-define( 'WL_CONFIG_TEST_GOOGLE_RICH_SNIPPETS_URL', 'https://developers.google.com/structured-data/testing-tool/?url=' );
47
+define('WL_CONFIG_TEST_GOOGLE_RICH_SNIPPETS_URL', 'https://developers.google.com/structured-data/testing-tool/?url=');
48 48
 
49 49
 // If is set to true, there will be additional button in 'Download Your Data' page
50 50
 // that will allow users to download their data in JSON-LD format.
51
-defined( 'WL_CONFIG_DOWNLOAD_GA_CONTENT_DATA' ) || define( 'WL_CONFIG_DOWNLOAD_GA_CONTENT_DATA', false );
51
+defined('WL_CONFIG_DOWNLOAD_GA_CONTENT_DATA') || define('WL_CONFIG_DOWNLOAD_GA_CONTENT_DATA', false);
52 52
 
53 53
 
54 54
 /**
@@ -61,8 +61,8 @@  discard block
 block discarded – undo
61 61
 	$items    = wl_prefixes_list();
62 62
 	$prefixes = array();
63 63
 
64
-	foreach ( $items as $item ) {
65
-		$prefixes[ $item['prefix'] ] = $item['namespace'];
64
+	foreach ($items as $item) {
65
+		$prefixes[$item['prefix']] = $item['namespace'];
66 66
 	}
67 67
 
68 68
 	return $prefixes;
Please login to merge, or discard this patch.
src/wordlift_redlink.php 2 patches
Indentation   +38 added lines, -38 removed lines patch added patch discarded remove patch
@@ -19,56 +19,56 @@
 block discarded – undo
19 19
  */
20 20
 function rl_execute_sparql_update_query( $query, $queue = WL_ENABLE_SPARQL_UPDATE_QUERIES_BUFFERING ) {
21 21
 
22
-	$log = Wordlift_Log_Service::get_logger( 'rl_execute_sparql_update_query' );
22
+    $log = Wordlift_Log_Service::get_logger( 'rl_execute_sparql_update_query' );
23 23
 
24
-	if ( get_transient( 'DISABLE_ENTITY_PUSH' ) ) {
25
-		$log->info('Entity push is disabled.');
24
+    if ( get_transient( 'DISABLE_ENTITY_PUSH' ) ) {
25
+        $log->info('Entity push is disabled.');
26 26
 
27
-		return true;
28
-	}
27
+        return true;
28
+    }
29 29
 
30
-	// Queue the update query.
31
-	if ( $queue ) {
32
-		$log->debug( 'Queueing query...' );
30
+    // Queue the update query.
31
+    if ( $queue ) {
32
+        $log->debug( 'Queueing query...' );
33 33
 
34
-		Wordlift_Sparql_Service::get_instance()->queue( $query );
34
+        Wordlift_Sparql_Service::get_instance()->queue( $query );
35 35
 
36
-		return true;
37
-	}
36
+        return true;
37
+    }
38 38
 
39
-	// Get the update end-point.
40
-	$url = wl_configuration_get_query_update_url();
39
+    // Get the update end-point.
40
+    $url = wl_configuration_get_query_update_url();
41 41
 
42
-	// Prepare the request.
43
-	$args = array_merge_recursive( unserialize( WL_REDLINK_API_HTTP_OPTIONS ), array(
44
-		'method'  => 'POST',
45
-		'headers' => array(
46
-			'Accept'       => 'application/json',
47
-			'Content-type' => 'application/sparql-update; charset=utf-8',
48
-		),
49
-		'body'    => $query,
50
-	) );
42
+    // Prepare the request.
43
+    $args = array_merge_recursive( unserialize( WL_REDLINK_API_HTTP_OPTIONS ), array(
44
+        'method'  => 'POST',
45
+        'headers' => array(
46
+            'Accept'       => 'application/json',
47
+            'Content-type' => 'application/sparql-update; charset=utf-8',
48
+        ),
49
+        'body'    => $query,
50
+    ) );
51 51
 
52
-	// Send the request.
53
-	$response = wp_remote_post( $url, $args );
52
+    // Send the request.
53
+    $response = wp_remote_post( $url, $args );
54 54
 
55
-	// If an error has been raised, return the error.
56
-	if ( is_wp_error( $response ) || 200 !== (int) $response['response']['code'] ) {
55
+    // If an error has been raised, return the error.
56
+    if ( is_wp_error( $response ) || 200 !== (int) $response['response']['code'] ) {
57 57
 
58
-		$body = ( is_wp_error( $response ) ? $response->get_error_message() : $response['body'] );
58
+        $body = ( is_wp_error( $response ) ? $response->get_error_message() : $response['body'] );
59 59
 
60
-		$log->warn( "rl_execute_sparql_update_query : error [ url :: $url ][ args :: " );
61
-		$log->warn( "\n" . var_export( $args, true ) );
62
-		$log->warn( "[ response :: " );
63
-		$log->warn( "\n" . var_export( $response, true ) );
64
-		$log->warn( "][ body :: " );
65
-		$log->warn( "\n" . $body );
66
-		$log->warn( "]" );
60
+        $log->warn( "rl_execute_sparql_update_query : error [ url :: $url ][ args :: " );
61
+        $log->warn( "\n" . var_export( $args, true ) );
62
+        $log->warn( "[ response :: " );
63
+        $log->warn( "\n" . var_export( $response, true ) );
64
+        $log->warn( "][ body :: " );
65
+        $log->warn( "\n" . $body );
66
+        $log->warn( "]" );
67 67
 
68
-		return false;
69
-	}
68
+        return false;
69
+    }
70 70
 
71
-	$log->debug( "Query executed successfully [ query :: $query ]" );
71
+    $log->debug( "Query executed successfully [ query :: $query ]" );
72 72
 
73
-	return true;
73
+    return true;
74 74
 }
Please login to merge, or discard this patch.
Spacing   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -17,21 +17,21 @@  discard block
 block discarded – undo
17 17
  *
18 18
  * @return bool True if successful otherwise false.
19 19
  */
20
-function rl_execute_sparql_update_query( $query, $queue = WL_ENABLE_SPARQL_UPDATE_QUERIES_BUFFERING ) {
20
+function rl_execute_sparql_update_query($query, $queue = WL_ENABLE_SPARQL_UPDATE_QUERIES_BUFFERING) {
21 21
 
22
-	$log = Wordlift_Log_Service::get_logger( 'rl_execute_sparql_update_query' );
22
+	$log = Wordlift_Log_Service::get_logger('rl_execute_sparql_update_query');
23 23
 
24
-	if ( get_transient( 'DISABLE_ENTITY_PUSH' ) ) {
24
+	if (get_transient('DISABLE_ENTITY_PUSH')) {
25 25
 		$log->info('Entity push is disabled.');
26 26
 
27 27
 		return true;
28 28
 	}
29 29
 
30 30
 	// Queue the update query.
31
-	if ( $queue ) {
32
-		$log->debug( 'Queueing query...' );
31
+	if ($queue) {
32
+		$log->debug('Queueing query...');
33 33
 
34
-		Wordlift_Sparql_Service::get_instance()->queue( $query );
34
+		Wordlift_Sparql_Service::get_instance()->queue($query);
35 35
 
36 36
 		return true;
37 37
 	}
@@ -40,35 +40,35 @@  discard block
 block discarded – undo
40 40
 	$url = wl_configuration_get_query_update_url();
41 41
 
42 42
 	// Prepare the request.
43
-	$args = array_merge_recursive( unserialize( WL_REDLINK_API_HTTP_OPTIONS ), array(
43
+	$args = array_merge_recursive(unserialize(WL_REDLINK_API_HTTP_OPTIONS), array(
44 44
 		'method'  => 'POST',
45 45
 		'headers' => array(
46 46
 			'Accept'       => 'application/json',
47 47
 			'Content-type' => 'application/sparql-update; charset=utf-8',
48 48
 		),
49 49
 		'body'    => $query,
50
-	) );
50
+	));
51 51
 
52 52
 	// Send the request.
53
-	$response = wp_remote_post( $url, $args );
53
+	$response = wp_remote_post($url, $args);
54 54
 
55 55
 	// If an error has been raised, return the error.
56
-	if ( is_wp_error( $response ) || 200 !== (int) $response['response']['code'] ) {
56
+	if (is_wp_error($response) || 200 !== (int) $response['response']['code']) {
57 57
 
58
-		$body = ( is_wp_error( $response ) ? $response->get_error_message() : $response['body'] );
58
+		$body = (is_wp_error($response) ? $response->get_error_message() : $response['body']);
59 59
 
60
-		$log->warn( "rl_execute_sparql_update_query : error [ url :: $url ][ args :: " );
61
-		$log->warn( "\n" . var_export( $args, true ) );
62
-		$log->warn( "[ response :: " );
63
-		$log->warn( "\n" . var_export( $response, true ) );
64
-		$log->warn( "][ body :: " );
65
-		$log->warn( "\n" . $body );
66
-		$log->warn( "]" );
60
+		$log->warn("rl_execute_sparql_update_query : error [ url :: $url ][ args :: ");
61
+		$log->warn("\n".var_export($args, true));
62
+		$log->warn("[ response :: ");
63
+		$log->warn("\n".var_export($response, true));
64
+		$log->warn("][ body :: ");
65
+		$log->warn("\n".$body);
66
+		$log->warn("]");
67 67
 
68 68
 		return false;
69 69
 	}
70 70
 
71
-	$log->debug( "Query executed successfully [ query :: $query ]" );
71
+	$log->debug("Query executed successfully [ query :: $query ]");
72 72
 
73 73
 	return true;
74 74
 }
Please login to merge, or discard this patch.
src/includes/class-wordlift-relation-service.php 2 patches
Indentation   +371 added lines, -371 removed lines patch added patch discarded remove patch
@@ -18,371 +18,371 @@  discard block
 block discarded – undo
18 18
  */
19 19
 class Wordlift_Relation_Service {
20 20
 
21
-	/**
22
-	 * The singleton instance.
23
-	 *
24
-	 * @since  3.15.0
25
-	 * @access private
26
-	 * @var \Wordlift_Relation_Service $instance The singleton instance.
27
-	 */
28
-	private static $instance;
29
-
30
-	/**
31
-	 * The relation table name in MySQL, set during instantiation.
32
-	 *
33
-	 * @since  3.15.0
34
-	 * @access private
35
-	 * @var string $relation_table The relation table name.
36
-	 */
37
-	private $relation_table;
38
-
39
-	/**
40
-	 * A {@link Wordlift_Log_Service} instance.
41
-	 *
42
-	 * @since 3.15.3
43
-	 *
44
-	 * @var Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
45
-	 */
46
-	private $log;
47
-
48
-	/**
49
-	 * Create a {@link Wordlift_Relation_Service} instance.
50
-	 *
51
-	 * @since 3.15.0
52
-	 */
53
-	public function __construct() {
54
-
55
-		$this->log = Wordlift_Log_Service::get_logger( get_class() );
56
-
57
-		global $wpdb;
58
-
59
-		// The relations table.
60
-		$this->relation_table = "{$wpdb->prefix}wl_relation_instances";
61
-
62
-		self::$instance = $this;
63
-
64
-	}
65
-
66
-	/**
67
-	 * Get the singleton instance.
68
-	 *
69
-	 * @since  3.15.0
70
-	 * @access public
71
-	 * @return \Wordlift_Relation_Service The {@link Wordlift_Relation_Service}
72
-	 *                                    singleton instance.
73
-	 */
74
-	public static function get_instance() {
75
-
76
-		return self::$instance;
77
-	}
78
-
79
-	/**
80
-	 * Get the articles referencing the specified entity {@link WP_Post}.
81
-	 *
82
-	 * @since 3.15.0
83
-	 *
84
-	 * @param int|array   $object_id The entity {@link WP_Post}'s id.
85
-	 * @param string      $fields    The fields to return, 'ids' to only return ids or
86
-	 *                               '*' to return all fields, by default '*'.
87
-	 * @param null|string $predicate The predicate (who|what|...), by default all.
88
-	 * @param null|string $status    The status, by default all.
89
-	 * @param array       $excludes  An array of ids to exclude from the results.
90
-	 * @param null|int    $limit     The maximum number of results, by default
91
-	 *                               no limit.
92
-	 * @param null|array  $include   The {@link WP_Post}s' ids to include.
93
-	 *
94
-	 * @return array|object|null Database query results
95
-	 */
96
-	public function get_article_subjects( $object_id, $fields = '*', $predicate = null, $status = null, $excludes = array(), $limit = null, $include = null ) {
97
-		global $wpdb;
98
-
99
-		// The output fields.
100
-		$actual_fields = self::fields( $fields );
101
-
102
-		$this->log->trace( 'Getting article subjects for object ' . implode( ', ', (array) $object_id ) . '...' );
103
-
104
-		$objects = $this->article_id_to_entity_id( $object_id );
105
-
106
-		// If there are no related objects, return an empty array.
107
-		if ( empty( $objects ) ) {
108
-			$this->log->debug( 'No entities found for object ' . implode( ', ', (array) $object_id ) . '.' );
109
-
110
-			return array();
111
-		}
112
-
113
-		$this->log->debug( count( $objects ) . ' entity id(s) found for object ' . implode( ', ', (array) $object_id ) . '.' );
114
-
115
-		$sql =
116
-			"
21
+    /**
22
+     * The singleton instance.
23
+     *
24
+     * @since  3.15.0
25
+     * @access private
26
+     * @var \Wordlift_Relation_Service $instance The singleton instance.
27
+     */
28
+    private static $instance;
29
+
30
+    /**
31
+     * The relation table name in MySQL, set during instantiation.
32
+     *
33
+     * @since  3.15.0
34
+     * @access private
35
+     * @var string $relation_table The relation table name.
36
+     */
37
+    private $relation_table;
38
+
39
+    /**
40
+     * A {@link Wordlift_Log_Service} instance.
41
+     *
42
+     * @since 3.15.3
43
+     *
44
+     * @var Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
45
+     */
46
+    private $log;
47
+
48
+    /**
49
+     * Create a {@link Wordlift_Relation_Service} instance.
50
+     *
51
+     * @since 3.15.0
52
+     */
53
+    public function __construct() {
54
+
55
+        $this->log = Wordlift_Log_Service::get_logger( get_class() );
56
+
57
+        global $wpdb;
58
+
59
+        // The relations table.
60
+        $this->relation_table = "{$wpdb->prefix}wl_relation_instances";
61
+
62
+        self::$instance = $this;
63
+
64
+    }
65
+
66
+    /**
67
+     * Get the singleton instance.
68
+     *
69
+     * @since  3.15.0
70
+     * @access public
71
+     * @return \Wordlift_Relation_Service The {@link Wordlift_Relation_Service}
72
+     *                                    singleton instance.
73
+     */
74
+    public static function get_instance() {
75
+
76
+        return self::$instance;
77
+    }
78
+
79
+    /**
80
+     * Get the articles referencing the specified entity {@link WP_Post}.
81
+     *
82
+     * @since 3.15.0
83
+     *
84
+     * @param int|array   $object_id The entity {@link WP_Post}'s id.
85
+     * @param string      $fields    The fields to return, 'ids' to only return ids or
86
+     *                               '*' to return all fields, by default '*'.
87
+     * @param null|string $predicate The predicate (who|what|...), by default all.
88
+     * @param null|string $status    The status, by default all.
89
+     * @param array       $excludes  An array of ids to exclude from the results.
90
+     * @param null|int    $limit     The maximum number of results, by default
91
+     *                               no limit.
92
+     * @param null|array  $include   The {@link WP_Post}s' ids to include.
93
+     *
94
+     * @return array|object|null Database query results
95
+     */
96
+    public function get_article_subjects( $object_id, $fields = '*', $predicate = null, $status = null, $excludes = array(), $limit = null, $include = null ) {
97
+        global $wpdb;
98
+
99
+        // The output fields.
100
+        $actual_fields = self::fields( $fields );
101
+
102
+        $this->log->trace( 'Getting article subjects for object ' . implode( ', ', (array) $object_id ) . '...' );
103
+
104
+        $objects = $this->article_id_to_entity_id( $object_id );
105
+
106
+        // If there are no related objects, return an empty array.
107
+        if ( empty( $objects ) ) {
108
+            $this->log->debug( 'No entities found for object ' . implode( ', ', (array) $object_id ) . '.' );
109
+
110
+            return array();
111
+        }
112
+
113
+        $this->log->debug( count( $objects ) . ' entity id(s) found for object ' . implode( ', ', (array) $object_id ) . '.' );
114
+
115
+        $sql =
116
+            "
117 117
 			SELECT DISTINCT p.$actual_fields
118 118
 			FROM {$this->relation_table} r
119 119
 			INNER JOIN $wpdb->posts p
120 120
 				ON p.id = r.subject_id
121 121
 			"
122
-			// Add the status clause.
123
-			. self::and_status( $status )
124
-			. self::inner_join_is_article()
125
-			. self::where_object_id( $objects )
126
-			// Since `object_id` can be an article ID we need to exclude it from
127
-			// the results.
128
-			. self::and_article_not_in( array_merge( $excludes, (array) $object_id ) )
129
-			. self::and_article_in( $include )
130
-			. self::and_post_type_in()
131
-			. self::and_predicate( $predicate )
132
-			. self::limit( $limit );
133
-
134
-
135
-		return '*' === $actual_fields ? $wpdb->get_results( $sql ) : $wpdb->get_col( $sql );
136
-	}
137
-
138
-	/**
139
-	 * The `post_type IN` clause.
140
-	 *
141
-	 * @since 3.15.3
142
-	 *
143
-	 * @return string The `post_type IN` clause.
144
-	 */
145
-	private static function and_post_type_in() {
146
-
147
-		return " AND p.post_type IN ( '"
148
-			   . implode(
149
-				   "','",
150
-				   array_map( 'esc_sql', Wordlift_Entity_Service::valid_entity_post_types() )
151
-			   )
152
-			   . "' )";
153
-	}
154
-
155
-	/**
156
-	 * Add the limit clause if specified.
157
-	 *
158
-	 * @since 3.15.0
159
-	 *
160
-	 * @param null|int $limit The maximum number of results.
161
-	 *
162
-	 * @return string The limit clause (empty if no limit has been specified).
163
-	 */
164
-	private static function limit( $limit = null ) {
165
-
166
-		if ( null === $limit ) {
167
-			return '';
168
-		}
169
-
170
-		return "LIMIT $limit";
171
-	}
172
-
173
-	/**
174
-	 * Map the provided ids into entities (i.e. return the id if it's an entity
175
-	 * or get the entities if it's a post).
176
-	 *
177
-	 * @since 3.15.0
178
-	 *
179
-	 * @param int|array $object_id An array of posts/entities' ids.
180
-	 *
181
-	 * @return array An array of entities' ids.
182
-	 */
183
-	private function article_id_to_entity_id( $object_id ) {
184
-
185
-		$entity_service = Wordlift_Entity_Service::get_instance();
186
-
187
-		$relation_service = $this;
188
-
189
-		return array_reduce( (array) $object_id, function ( $carry, $item ) use ( $entity_service, $relation_service ) {
190
-			if ( $entity_service->is_entity( $item ) ) {
191
-				return array_merge( $carry, (array) $item );
192
-			}
193
-
194
-			return array_merge( $carry, $relation_service->get_objects( $item, 'ids' ) );
195
-		}, array() );
196
-
197
-	}
198
-
199
-	/**
200
-	 * Add the WHERE clause.
201
-	 *
202
-	 * @since 3.15.0
203
-	 *
204
-	 * @param int|array $object_id An array of {@link WP_Post}s' ids.
205
-	 *
206
-	 * @return string The WHERE clause.
207
-	 */
208
-	private static function where_object_id( $object_id ) {
209
-
210
-		return ' WHERE r.object_id IN ( ' . implode( ',', wp_parse_id_list( (array) $object_id ) ) . ' )';
211
-	}
212
-
213
-	/**
214
-	 * Add the exclude clause.
215
-	 *
216
-	 * @since 3.15.0
217
-	 *
218
-	 * @param int|array $exclude An array of {@link WP_Post}s' ids to exclude.
219
-	 *
220
-	 * @return string The exclude clause.
221
-	 */
222
-	private static function and_article_not_in( $exclude ) {
223
-
224
-		return ' AND NOT p.ID IN ( ' . implode( ',', wp_parse_id_list( (array) $exclude ) ) . ' )';
225
-	}
226
-
227
-	/**
228
-	 * Add the include clause.
229
-	 *
230
-	 * @since 3.15.0
231
-	 *
232
-	 * @param null|int|array $include An array of {@link WP_Post}s' ids.
233
-	 *
234
-	 * @return string An empty string if $include is null otherwise the include
235
-	 *                clause.
236
-	 */
237
-	private static function and_article_in( $include = null ) {
238
-
239
-		if ( null === $include ) {
240
-			return '';
241
-		}
242
-
243
-		return ' AND p.ID IN ( ' . implode( ',', wp_parse_id_list( (array) $include ) ) . ' )';
244
-	}
245
-
246
-	/**
247
-	 * Get the entities' {@link WP_Post}s' ids referencing the specified {@link WP_Post}.
248
-	 *
249
-	 * @since 3.15.0
250
-	 *
251
-	 * @param int         $object_id The object {@link WP_Post}'s id.
252
-	 * @param string      $fields    The fields to return, 'ids' to only return ids or
253
-	 *                               '*' to return all fields, by default '*'.
254
-	 * @param null|string $status    The status, by default all.
255
-	 *
256
-	 * @return array|object|null Database query results
257
-	 */
258
-	public function get_non_article_subjects( $object_id, $fields = '*', $status = null ) {
259
-		global $wpdb;
260
-
261
-		// The output fields.
262
-		$actual_fields = self::fields( $fields );
263
-
264
-		$sql = $wpdb->prepare(
265
-			"
122
+            // Add the status clause.
123
+            . self::and_status( $status )
124
+            . self::inner_join_is_article()
125
+            . self::where_object_id( $objects )
126
+            // Since `object_id` can be an article ID we need to exclude it from
127
+            // the results.
128
+            . self::and_article_not_in( array_merge( $excludes, (array) $object_id ) )
129
+            . self::and_article_in( $include )
130
+            . self::and_post_type_in()
131
+            . self::and_predicate( $predicate )
132
+            . self::limit( $limit );
133
+
134
+
135
+        return '*' === $actual_fields ? $wpdb->get_results( $sql ) : $wpdb->get_col( $sql );
136
+    }
137
+
138
+    /**
139
+     * The `post_type IN` clause.
140
+     *
141
+     * @since 3.15.3
142
+     *
143
+     * @return string The `post_type IN` clause.
144
+     */
145
+    private static function and_post_type_in() {
146
+
147
+        return " AND p.post_type IN ( '"
148
+                . implode(
149
+                    "','",
150
+                    array_map( 'esc_sql', Wordlift_Entity_Service::valid_entity_post_types() )
151
+                )
152
+                . "' )";
153
+    }
154
+
155
+    /**
156
+     * Add the limit clause if specified.
157
+     *
158
+     * @since 3.15.0
159
+     *
160
+     * @param null|int $limit The maximum number of results.
161
+     *
162
+     * @return string The limit clause (empty if no limit has been specified).
163
+     */
164
+    private static function limit( $limit = null ) {
165
+
166
+        if ( null === $limit ) {
167
+            return '';
168
+        }
169
+
170
+        return "LIMIT $limit";
171
+    }
172
+
173
+    /**
174
+     * Map the provided ids into entities (i.e. return the id if it's an entity
175
+     * or get the entities if it's a post).
176
+     *
177
+     * @since 3.15.0
178
+     *
179
+     * @param int|array $object_id An array of posts/entities' ids.
180
+     *
181
+     * @return array An array of entities' ids.
182
+     */
183
+    private function article_id_to_entity_id( $object_id ) {
184
+
185
+        $entity_service = Wordlift_Entity_Service::get_instance();
186
+
187
+        $relation_service = $this;
188
+
189
+        return array_reduce( (array) $object_id, function ( $carry, $item ) use ( $entity_service, $relation_service ) {
190
+            if ( $entity_service->is_entity( $item ) ) {
191
+                return array_merge( $carry, (array) $item );
192
+            }
193
+
194
+            return array_merge( $carry, $relation_service->get_objects( $item, 'ids' ) );
195
+        }, array() );
196
+
197
+    }
198
+
199
+    /**
200
+     * Add the WHERE clause.
201
+     *
202
+     * @since 3.15.0
203
+     *
204
+     * @param int|array $object_id An array of {@link WP_Post}s' ids.
205
+     *
206
+     * @return string The WHERE clause.
207
+     */
208
+    private static function where_object_id( $object_id ) {
209
+
210
+        return ' WHERE r.object_id IN ( ' . implode( ',', wp_parse_id_list( (array) $object_id ) ) . ' )';
211
+    }
212
+
213
+    /**
214
+     * Add the exclude clause.
215
+     *
216
+     * @since 3.15.0
217
+     *
218
+     * @param int|array $exclude An array of {@link WP_Post}s' ids to exclude.
219
+     *
220
+     * @return string The exclude clause.
221
+     */
222
+    private static function and_article_not_in( $exclude ) {
223
+
224
+        return ' AND NOT p.ID IN ( ' . implode( ',', wp_parse_id_list( (array) $exclude ) ) . ' )';
225
+    }
226
+
227
+    /**
228
+     * Add the include clause.
229
+     *
230
+     * @since 3.15.0
231
+     *
232
+     * @param null|int|array $include An array of {@link WP_Post}s' ids.
233
+     *
234
+     * @return string An empty string if $include is null otherwise the include
235
+     *                clause.
236
+     */
237
+    private static function and_article_in( $include = null ) {
238
+
239
+        if ( null === $include ) {
240
+            return '';
241
+        }
242
+
243
+        return ' AND p.ID IN ( ' . implode( ',', wp_parse_id_list( (array) $include ) ) . ' )';
244
+    }
245
+
246
+    /**
247
+     * Get the entities' {@link WP_Post}s' ids referencing the specified {@link WP_Post}.
248
+     *
249
+     * @since 3.15.0
250
+     *
251
+     * @param int         $object_id The object {@link WP_Post}'s id.
252
+     * @param string      $fields    The fields to return, 'ids' to only return ids or
253
+     *                               '*' to return all fields, by default '*'.
254
+     * @param null|string $status    The status, by default all.
255
+     *
256
+     * @return array|object|null Database query results
257
+     */
258
+    public function get_non_article_subjects( $object_id, $fields = '*', $status = null ) {
259
+        global $wpdb;
260
+
261
+        // The output fields.
262
+        $actual_fields = self::fields( $fields );
263
+
264
+        $sql = $wpdb->prepare(
265
+            "
266 266
 			SELECT p.$actual_fields
267 267
 			FROM {$this->relation_table} r
268 268
 			INNER JOIN $wpdb->posts p
269 269
 				ON p.id = r.subject_id
270 270
 			"
271
-			// Add the status clause.
272
-			. self::and_status( $status )
273
-			. self::inner_join_is_not_article()
274
-			. " WHERE r.object_id = %d "
275
-			. self::and_post_type_in()
276
-			,
277
-			$object_id
278
-		);
279
-
280
-		return '*' === $actual_fields ? $wpdb->get_results( $sql ) : $wpdb->get_col( $sql );
281
-	}
282
-
283
-	/**
284
-	 * Get the entities referenced by the specified {@link WP_Post}.
285
-	 *
286
-	 * @since 3.15.0
287
-	 *
288
-	 * @param int         $subject_id The {@link WP_Post}'s id.
289
-	 * @param string      $fields     The fields to return, 'ids' to only return ids or
290
-	 *                                '*' to return all fields, by default '*'.
291
-	 * @param null|string $predicate  The predicate (who|what|...), by default all.
292
-	 * @param null|string $status     The status, by default all.
293
-	 *
294
-	 * @return array|object|null Database query results
295
-	 */
296
-	public function get_objects( $subject_id, $fields = '*', $predicate = null, $status = null ) {
297
-		global $wpdb;
298
-
299
-		// The output fields.
300
-		$actual_fields = self::fields( $fields );
301
-
302
-		$sql = $wpdb->prepare(
303
-			"
271
+            // Add the status clause.
272
+            . self::and_status( $status )
273
+            . self::inner_join_is_not_article()
274
+            . " WHERE r.object_id = %d "
275
+            . self::and_post_type_in()
276
+            ,
277
+            $object_id
278
+        );
279
+
280
+        return '*' === $actual_fields ? $wpdb->get_results( $sql ) : $wpdb->get_col( $sql );
281
+    }
282
+
283
+    /**
284
+     * Get the entities referenced by the specified {@link WP_Post}.
285
+     *
286
+     * @since 3.15.0
287
+     *
288
+     * @param int         $subject_id The {@link WP_Post}'s id.
289
+     * @param string      $fields     The fields to return, 'ids' to only return ids or
290
+     *                                '*' to return all fields, by default '*'.
291
+     * @param null|string $predicate  The predicate (who|what|...), by default all.
292
+     * @param null|string $status     The status, by default all.
293
+     *
294
+     * @return array|object|null Database query results
295
+     */
296
+    public function get_objects( $subject_id, $fields = '*', $predicate = null, $status = null ) {
297
+        global $wpdb;
298
+
299
+        // The output fields.
300
+        $actual_fields = self::fields( $fields );
301
+
302
+        $sql = $wpdb->prepare(
303
+            "
304 304
 			SELECT p.$actual_fields
305 305
 			FROM {$this->relation_table} r
306 306
 			INNER JOIN $wpdb->posts p
307 307
 				ON p.id = r.object_id
308 308
 			"
309
-			// Add the status clause.
310
-			. self::and_status( $status )
311
-			. self::inner_join_is_not_article()
312
-			. " WHERE r.subject_id = %d "
313
-			. self::and_post_type_in()
314
-			. self::and_predicate( $predicate )
315
-			,
316
-			$subject_id
317
-		);
318
-
319
-		return '*' === $actual_fields ? $wpdb->get_results( $sql ) : $wpdb->get_col( $sql );
320
-	}
321
-
322
-	/**
323
-	 * Add the `post_status` clause.
324
-	 *
325
-	 * @since 3.15.0
326
-	 *
327
-	 * @param null|string|array $status The status values.
328
-	 *
329
-	 * @return string An empty string if $status is null, otherwise the status clause.
330
-	 */
331
-	private static function and_status( $status = null ) {
332
-
333
-		if ( null === $status ) {
334
-			return '';
335
-		}
336
-
337
-		return " AND p.post_status IN ('" . implode( "', '", array_map( 'esc_sql', (array) $status ) ) . "')";
338
-	}
339
-
340
-	/**
341
-	 * Add the `predicate` clause.
342
-	 *
343
-	 * @since 3.15.0
344
-	 *
345
-	 * @param null|string|array $predicate An array of predicates.
346
-	 *
347
-	 * @return string An empty string if $predicate is null otherwise the predicate
348
-	 *                clause.
349
-	 */
350
-	private static function and_predicate( $predicate = null ) {
351
-
352
-		if ( null === $predicate ) {
353
-			return '';
354
-		}
355
-
356
-		return " AND r.predicate IN ('" . implode( "', '", array_map( 'esc_sql', (array) $predicate ) ) . "')";
357
-	}
358
-
359
-	/**
360
-	 * The select fields.
361
-	 *
362
-	 * @since 3.15.0
363
-	 *
364
-	 * @param string $fields Either 'ids' or '*', by default '*'.
365
-	 *
366
-	 * @return string The `id` field if `ids` otherwise `*`.
367
-	 */
368
-	private static function fields( $fields = '*' ) {
369
-
370
-		// The output fields.
371
-		return 'ids' === $fields ? 'id' : '*';
372
-	}
373
-
374
-	/**
375
-	 * The inner join clause for articles.
376
-	 *
377
-	 * @since 3.15.0
378
-	 *
379
-	 * @return string The articles inner join clause.
380
-	 */
381
-	private static function inner_join_is_article() {
382
-		global $wpdb;
383
-
384
-		return $wpdb->prepare(
385
-			"
309
+            // Add the status clause.
310
+            . self::and_status( $status )
311
+            . self::inner_join_is_not_article()
312
+            . " WHERE r.subject_id = %d "
313
+            . self::and_post_type_in()
314
+            . self::and_predicate( $predicate )
315
+            ,
316
+            $subject_id
317
+        );
318
+
319
+        return '*' === $actual_fields ? $wpdb->get_results( $sql ) : $wpdb->get_col( $sql );
320
+    }
321
+
322
+    /**
323
+     * Add the `post_status` clause.
324
+     *
325
+     * @since 3.15.0
326
+     *
327
+     * @param null|string|array $status The status values.
328
+     *
329
+     * @return string An empty string if $status is null, otherwise the status clause.
330
+     */
331
+    private static function and_status( $status = null ) {
332
+
333
+        if ( null === $status ) {
334
+            return '';
335
+        }
336
+
337
+        return " AND p.post_status IN ('" . implode( "', '", array_map( 'esc_sql', (array) $status ) ) . "')";
338
+    }
339
+
340
+    /**
341
+     * Add the `predicate` clause.
342
+     *
343
+     * @since 3.15.0
344
+     *
345
+     * @param null|string|array $predicate An array of predicates.
346
+     *
347
+     * @return string An empty string if $predicate is null otherwise the predicate
348
+     *                clause.
349
+     */
350
+    private static function and_predicate( $predicate = null ) {
351
+
352
+        if ( null === $predicate ) {
353
+            return '';
354
+        }
355
+
356
+        return " AND r.predicate IN ('" . implode( "', '", array_map( 'esc_sql', (array) $predicate ) ) . "')";
357
+    }
358
+
359
+    /**
360
+     * The select fields.
361
+     *
362
+     * @since 3.15.0
363
+     *
364
+     * @param string $fields Either 'ids' or '*', by default '*'.
365
+     *
366
+     * @return string The `id` field if `ids` otherwise `*`.
367
+     */
368
+    private static function fields( $fields = '*' ) {
369
+
370
+        // The output fields.
371
+        return 'ids' === $fields ? 'id' : '*';
372
+    }
373
+
374
+    /**
375
+     * The inner join clause for articles.
376
+     *
377
+     * @since 3.15.0
378
+     *
379
+     * @return string The articles inner join clause.
380
+     */
381
+    private static function inner_join_is_article() {
382
+        global $wpdb;
383
+
384
+        return $wpdb->prepare(
385
+            "
386 386
 			INNER JOIN $wpdb->term_relationships tr
387 387
 			 ON p.id = tr.object_id
388 388
 			INNER JOIN $wpdb->term_taxonomy tt
@@ -392,23 +392,23 @@  discard block
 block discarded – undo
392 392
 			 ON t.term_id = tt.term_id
393 393
 			  AND t.slug = %s
394 394
 			",
395
-			'wl_entity_type',
396
-			'article'
397
-		);
398
-	}
399
-
400
-	/**
401
-	 * The inner join clause for non-articles.
402
-	 *
403
-	 * @since 3.15.0
404
-	 *
405
-	 * @return string The non-articles inner join clause.
406
-	 */
407
-	private static function inner_join_is_not_article() {
408
-		global $wpdb;
409
-
410
-		return $wpdb->prepare(
411
-			"
395
+            'wl_entity_type',
396
+            'article'
397
+        );
398
+    }
399
+
400
+    /**
401
+     * The inner join clause for non-articles.
402
+     *
403
+     * @since 3.15.0
404
+     *
405
+     * @return string The non-articles inner join clause.
406
+     */
407
+    private static function inner_join_is_not_article() {
408
+        global $wpdb;
409
+
410
+        return $wpdb->prepare(
411
+            "
412 412
 			INNER JOIN $wpdb->term_relationships tr
413 413
 			 ON p.id = tr.object_id
414 414
 			INNER JOIN $wpdb->term_taxonomy tt
@@ -418,9 +418,9 @@  discard block
 block discarded – undo
418 418
 			 ON t.term_id = tt.term_id
419 419
 			  AND NOT t.slug = %s
420 420
 			",
421
-			'wl_entity_type',
422
-			'article'
423
-		);
424
-	}
421
+            'wl_entity_type',
422
+            'article'
423
+        );
424
+    }
425 425
 
426 426
 }
Please login to merge, or discard this patch.
Spacing   +47 added lines, -47 removed lines patch added patch discarded remove patch
@@ -52,7 +52,7 @@  discard block
 block discarded – undo
52 52
 	 */
53 53
 	public function __construct() {
54 54
 
55
-		$this->log = Wordlift_Log_Service::get_logger( get_class() );
55
+		$this->log = Wordlift_Log_Service::get_logger(get_class());
56 56
 
57 57
 		global $wpdb;
58 58
 
@@ -93,24 +93,24 @@  discard block
 block discarded – undo
93 93
 	 *
94 94
 	 * @return array|object|null Database query results
95 95
 	 */
96
-	public function get_article_subjects( $object_id, $fields = '*', $predicate = null, $status = null, $excludes = array(), $limit = null, $include = null ) {
96
+	public function get_article_subjects($object_id, $fields = '*', $predicate = null, $status = null, $excludes = array(), $limit = null, $include = null) {
97 97
 		global $wpdb;
98 98
 
99 99
 		// The output fields.
100
-		$actual_fields = self::fields( $fields );
100
+		$actual_fields = self::fields($fields);
101 101
 
102
-		$this->log->trace( 'Getting article subjects for object ' . implode( ', ', (array) $object_id ) . '...' );
102
+		$this->log->trace('Getting article subjects for object '.implode(', ', (array) $object_id).'...');
103 103
 
104
-		$objects = $this->article_id_to_entity_id( $object_id );
104
+		$objects = $this->article_id_to_entity_id($object_id);
105 105
 
106 106
 		// If there are no related objects, return an empty array.
107
-		if ( empty( $objects ) ) {
108
-			$this->log->debug( 'No entities found for object ' . implode( ', ', (array) $object_id ) . '.' );
107
+		if (empty($objects)) {
108
+			$this->log->debug('No entities found for object '.implode(', ', (array) $object_id).'.');
109 109
 
110 110
 			return array();
111 111
 		}
112 112
 
113
-		$this->log->debug( count( $objects ) . ' entity id(s) found for object ' . implode( ', ', (array) $object_id ) . '.' );
113
+		$this->log->debug(count($objects).' entity id(s) found for object '.implode(', ', (array) $object_id).'.');
114 114
 
115 115
 		$sql =
116 116
 			"
@@ -120,19 +120,19 @@  discard block
 block discarded – undo
120 120
 				ON p.id = r.subject_id
121 121
 			"
122 122
 			// Add the status clause.
123
-			. self::and_status( $status )
123
+			. self::and_status($status)
124 124
 			. self::inner_join_is_article()
125
-			. self::where_object_id( $objects )
125
+			. self::where_object_id($objects)
126 126
 			// Since `object_id` can be an article ID we need to exclude it from
127 127
 			// the results.
128
-			. self::and_article_not_in( array_merge( $excludes, (array) $object_id ) )
129
-			. self::and_article_in( $include )
128
+			. self::and_article_not_in(array_merge($excludes, (array) $object_id))
129
+			. self::and_article_in($include)
130 130
 			. self::and_post_type_in()
131
-			. self::and_predicate( $predicate )
132
-			. self::limit( $limit );
131
+			. self::and_predicate($predicate)
132
+			. self::limit($limit);
133 133
 
134 134
 
135
-		return '*' === $actual_fields ? $wpdb->get_results( $sql ) : $wpdb->get_col( $sql );
135
+		return '*' === $actual_fields ? $wpdb->get_results($sql) : $wpdb->get_col($sql);
136 136
 	}
137 137
 
138 138
 	/**
@@ -147,7 +147,7 @@  discard block
 block discarded – undo
147 147
 		return " AND p.post_type IN ( '"
148 148
 			   . implode(
149 149
 				   "','",
150
-				   array_map( 'esc_sql', Wordlift_Entity_Service::valid_entity_post_types() )
150
+				   array_map('esc_sql', Wordlift_Entity_Service::valid_entity_post_types())
151 151
 			   )
152 152
 			   . "' )";
153 153
 	}
@@ -161,9 +161,9 @@  discard block
 block discarded – undo
161 161
 	 *
162 162
 	 * @return string The limit clause (empty if no limit has been specified).
163 163
 	 */
164
-	private static function limit( $limit = null ) {
164
+	private static function limit($limit = null) {
165 165
 
166
-		if ( null === $limit ) {
166
+		if (null === $limit) {
167 167
 			return '';
168 168
 		}
169 169
 
@@ -180,19 +180,19 @@  discard block
 block discarded – undo
180 180
 	 *
181 181
 	 * @return array An array of entities' ids.
182 182
 	 */
183
-	private function article_id_to_entity_id( $object_id ) {
183
+	private function article_id_to_entity_id($object_id) {
184 184
 
185 185
 		$entity_service = Wordlift_Entity_Service::get_instance();
186 186
 
187 187
 		$relation_service = $this;
188 188
 
189
-		return array_reduce( (array) $object_id, function ( $carry, $item ) use ( $entity_service, $relation_service ) {
190
-			if ( $entity_service->is_entity( $item ) ) {
191
-				return array_merge( $carry, (array) $item );
189
+		return array_reduce((array) $object_id, function($carry, $item) use ($entity_service, $relation_service) {
190
+			if ($entity_service->is_entity($item)) {
191
+				return array_merge($carry, (array) $item);
192 192
 			}
193 193
 
194
-			return array_merge( $carry, $relation_service->get_objects( $item, 'ids' ) );
195
-		}, array() );
194
+			return array_merge($carry, $relation_service->get_objects($item, 'ids'));
195
+		}, array());
196 196
 
197 197
 	}
198 198
 
@@ -205,9 +205,9 @@  discard block
 block discarded – undo
205 205
 	 *
206 206
 	 * @return string The WHERE clause.
207 207
 	 */
208
-	private static function where_object_id( $object_id ) {
208
+	private static function where_object_id($object_id) {
209 209
 
210
-		return ' WHERE r.object_id IN ( ' . implode( ',', wp_parse_id_list( (array) $object_id ) ) . ' )';
210
+		return ' WHERE r.object_id IN ( '.implode(',', wp_parse_id_list((array) $object_id)).' )';
211 211
 	}
212 212
 
213 213
 	/**
@@ -219,9 +219,9 @@  discard block
 block discarded – undo
219 219
 	 *
220 220
 	 * @return string The exclude clause.
221 221
 	 */
222
-	private static function and_article_not_in( $exclude ) {
222
+	private static function and_article_not_in($exclude) {
223 223
 
224
-		return ' AND NOT p.ID IN ( ' . implode( ',', wp_parse_id_list( (array) $exclude ) ) . ' )';
224
+		return ' AND NOT p.ID IN ( '.implode(',', wp_parse_id_list((array) $exclude)).' )';
225 225
 	}
226 226
 
227 227
 	/**
@@ -234,13 +234,13 @@  discard block
 block discarded – undo
234 234
 	 * @return string An empty string if $include is null otherwise the include
235 235
 	 *                clause.
236 236
 	 */
237
-	private static function and_article_in( $include = null ) {
237
+	private static function and_article_in($include = null) {
238 238
 
239
-		if ( null === $include ) {
239
+		if (null === $include) {
240 240
 			return '';
241 241
 		}
242 242
 
243
-		return ' AND p.ID IN ( ' . implode( ',', wp_parse_id_list( (array) $include ) ) . ' )';
243
+		return ' AND p.ID IN ( '.implode(',', wp_parse_id_list((array) $include)).' )';
244 244
 	}
245 245
 
246 246
 	/**
@@ -255,11 +255,11 @@  discard block
 block discarded – undo
255 255
 	 *
256 256
 	 * @return array|object|null Database query results
257 257
 	 */
258
-	public function get_non_article_subjects( $object_id, $fields = '*', $status = null ) {
258
+	public function get_non_article_subjects($object_id, $fields = '*', $status = null) {
259 259
 		global $wpdb;
260 260
 
261 261
 		// The output fields.
262
-		$actual_fields = self::fields( $fields );
262
+		$actual_fields = self::fields($fields);
263 263
 
264 264
 		$sql = $wpdb->prepare(
265 265
 			"
@@ -269,7 +269,7 @@  discard block
 block discarded – undo
269 269
 				ON p.id = r.subject_id
270 270
 			"
271 271
 			// Add the status clause.
272
-			. self::and_status( $status )
272
+			. self::and_status($status)
273 273
 			. self::inner_join_is_not_article()
274 274
 			. " WHERE r.object_id = %d "
275 275
 			. self::and_post_type_in()
@@ -277,7 +277,7 @@  discard block
 block discarded – undo
277 277
 			$object_id
278 278
 		);
279 279
 
280
-		return '*' === $actual_fields ? $wpdb->get_results( $sql ) : $wpdb->get_col( $sql );
280
+		return '*' === $actual_fields ? $wpdb->get_results($sql) : $wpdb->get_col($sql);
281 281
 	}
282 282
 
283 283
 	/**
@@ -293,11 +293,11 @@  discard block
 block discarded – undo
293 293
 	 *
294 294
 	 * @return array|object|null Database query results
295 295
 	 */
296
-	public function get_objects( $subject_id, $fields = '*', $predicate = null, $status = null ) {
296
+	public function get_objects($subject_id, $fields = '*', $predicate = null, $status = null) {
297 297
 		global $wpdb;
298 298
 
299 299
 		// The output fields.
300
-		$actual_fields = self::fields( $fields );
300
+		$actual_fields = self::fields($fields);
301 301
 
302 302
 		$sql = $wpdb->prepare(
303 303
 			"
@@ -307,16 +307,16 @@  discard block
 block discarded – undo
307 307
 				ON p.id = r.object_id
308 308
 			"
309 309
 			// Add the status clause.
310
-			. self::and_status( $status )
310
+			. self::and_status($status)
311 311
 			. self::inner_join_is_not_article()
312 312
 			. " WHERE r.subject_id = %d "
313 313
 			. self::and_post_type_in()
314
-			. self::and_predicate( $predicate )
314
+			. self::and_predicate($predicate)
315 315
 			,
316 316
 			$subject_id
317 317
 		);
318 318
 
319
-		return '*' === $actual_fields ? $wpdb->get_results( $sql ) : $wpdb->get_col( $sql );
319
+		return '*' === $actual_fields ? $wpdb->get_results($sql) : $wpdb->get_col($sql);
320 320
 	}
321 321
 
322 322
 	/**
@@ -328,13 +328,13 @@  discard block
 block discarded – undo
328 328
 	 *
329 329
 	 * @return string An empty string if $status is null, otherwise the status clause.
330 330
 	 */
331
-	private static function and_status( $status = null ) {
331
+	private static function and_status($status = null) {
332 332
 
333
-		if ( null === $status ) {
333
+		if (null === $status) {
334 334
 			return '';
335 335
 		}
336 336
 
337
-		return " AND p.post_status IN ('" . implode( "', '", array_map( 'esc_sql', (array) $status ) ) . "')";
337
+		return " AND p.post_status IN ('".implode("', '", array_map('esc_sql', (array) $status))."')";
338 338
 	}
339 339
 
340 340
 	/**
@@ -347,13 +347,13 @@  discard block
 block discarded – undo
347 347
 	 * @return string An empty string if $predicate is null otherwise the predicate
348 348
 	 *                clause.
349 349
 	 */
350
-	private static function and_predicate( $predicate = null ) {
350
+	private static function and_predicate($predicate = null) {
351 351
 
352
-		if ( null === $predicate ) {
352
+		if (null === $predicate) {
353 353
 			return '';
354 354
 		}
355 355
 
356
-		return " AND r.predicate IN ('" . implode( "', '", array_map( 'esc_sql', (array) $predicate ) ) . "')";
356
+		return " AND r.predicate IN ('".implode("', '", array_map('esc_sql', (array) $predicate))."')";
357 357
 	}
358 358
 
359 359
 	/**
@@ -365,7 +365,7 @@  discard block
 block discarded – undo
365 365
 	 *
366 366
 	 * @return string The `id` field if `ids` otherwise `*`.
367 367
 	 */
368
-	private static function fields( $fields = '*' ) {
368
+	private static function fields($fields = '*') {
369 369
 
370 370
 		// The output fields.
371 371
 		return 'ids' === $fields ? 'id' : '*';
Please login to merge, or discard this patch.
src/includes/class-wordlift-batch-analysis-service.php 2 patches
Indentation   +628 added lines, -628 removed lines patch added patch discarded remove patch
@@ -51,158 +51,158 @@  discard block
 block discarded – undo
51 51
  */
52 52
 class Wordlift_Batch_Analysis_Service {
53 53
 
54
-	/**
55
-	 * The list of states for the Batch Analysis:
56
-	 *  - STATE_META_KEY: the batch analysis state meta key,
57
-	 *  - STATE_SUBMIT: a post/page has been submitted for analysis,
58
-	 *  - STATE_REQUEST: the plugin requested an analysis for the submitted
59
-	 *      post/page,
60
-	 *  - STATE_SUCCESS: the analysis has completed successfully,
61
-	 *  - STATE_ERROR: the analysis returned an error.
62
-	 *
63
-	 * @since 3.14.2
64
-	 */
65
-	const STATE_META_KEY = '_wl_batch_analysis_state';
66
-	const STATE_SUBMIT = 0;
67
-	const STATE_REQUEST = 1;
68
-	// ### COMPLETE states.
69
-	const STATE_SUCCESS = 2;
70
-	const STATE_ERROR = 2;
71
-
72
-	/**
73
-	 * The submit timestamp meta key. A post may have more than one timestamp.
74
-	 *
75
-	 * @since 3.14.2
76
-	 */
77
-	const SUBMIT_TIMESTAMP_META_KEY = '_wl_batch_analysis_submit_timestamp';
78
-
79
-	/**
80
-	 * The request timestamp meta key. A post may have more than one timestamp.
81
-	 *
82
-	 * @since 3.14.2
83
-	 */
84
-	const REQUEST_TIMESTAMP_META_KEY = '_wl_batch_analysis_request_timestamp';
85
-
86
-	/**
87
-	 * The complete (success or error) timestamp meta key. A post may have more
88
-	 * than one timestamp.
89
-	 *
90
-	 * @since 3.14.2
91
-	 */
92
-	const COMPLETE_TIMESTAMP_META_KEY = '_wl_batch_analysis_complete_timestamp';
93
-
94
-	/**
95
-	 * The link setting meta key. A post may have more than one setting.
96
-	 *
97
-	 * @since 3.14.2
98
-	 */
99
-	const LINK_META_KEY = '_wl_batch_analysis_link';
100
-
101
-	/**
102
-	 * The warning timestamp meta key. A post has only zero/one value.
103
-	 *
104
-	 * @since 3.14.2
105
-	 */
106
-	const WARNING_META_KEY = '_wl_batch_analysis_warning';
107
-
108
-	/**
109
-	 * Option name.
110
-	 *
111
-	 * @since  3.14.0
112
-	 */
113
-	const OPTION_NAME = 'wl_analyze_batch';
114
-
115
-	/**
116
-	 * Name of waiting to be processed queue array inside the option.
117
-	 *
118
-	 * @since  3.14.0
119
-	 */
120
-	const ANALYZE_QUEUE = 'queue';
121
-
122
-	/**
123
-	 * Name of waiting for response queue array inside the option.
124
-	 *
125
-	 * @since  3.14.0
126
-	 */
127
-	const RESPONSE_QUEUE = 'processing';
128
-
129
-	/**
130
-	 * The {@link Wordlift} plugin instance.
131
-	 *
132
-	 * @since  3.14.0
133
-	 * @access private
134
-	 * @var \Wordlift $plugin The {@link Wordlift} plugin instance.
135
-	 */
136
-	private $plugin;
137
-
138
-	/**
139
-	 * The {@link Wordlift_Configuration_Service} instance.
140
-	 *
141
-	 * @since  3.14.0
142
-	 * @access private
143
-	 * @var \Wordlift_Configuration_Service $configuration_service The {@link Wordlift_Configuration_Service} instance.
144
-	 */
145
-	private $configuration_service;
146
-
147
-	/**
148
-	 * A {@link Wordlift_Log_Service} instance.
149
-	 *
150
-	 * @since  3.14.2
151
-	 * @access private
152
-	 * @var \Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
153
-	 */
154
-	private $log;
155
-
156
-	/**
157
-	 * The {@link Class_Wordlift_Batch_Analys_Service} instance.
158
-	 *
159
-	 * @since 3.14.0
160
-	 *
161
-	 * @param \Wordlift                       $plugin                The {@link Wordlift} plugin instance.
162
-	 * @param \Wordlift_Configuration_Service $configuration_service The {@link Wordlift_Configuration_Service} instance.
163
-	 */
164
-	public function __construct( $plugin, $configuration_service ) {
165
-
166
-		$this->plugin                = $plugin;
167
-		$this->configuration_service = $configuration_service;
168
-		$this->log                   = Wordlift_Log_Service::get_logger( 'Wordlift_Batch_Analysis_Service' );
169
-
170
-		add_action( 'wl_async_wl_batch_analysis_request', array(
171
-			$this,
172
-			'request',
173
-		) );
174
-		add_action( 'wl_async_wl_batch_analysis_complete', array(
175
-			$this,
176
-			'complete',
177
-		) );
178
-
179
-	}
180
-
181
-	/**
182
-	 * Get the base SQL statement to submit a post for Batch Analysis.
183
-	 *
184
-	 * Functions may use this base SQL and add their own filters.
185
-	 *
186
-	 * @since 3.14.2
187
-	 *
188
-	 * @param string $link The link setting ('yes'/'no').
189
-	 *
190
-	 * @return string The base SQL.
191
-	 */
192
-	private function get_sql( $link ) {
193
-		global $wpdb;
194
-
195
-		// Prepare the statement:
196
-		//  1. Insert into `postmeta` the meta keys and values:
197
-		//    a) state meta, with value of SUBMIT (0),
198
-		//    b) submit timestamp, with value of UTC timestamp,
199
-		//    c) link meta, with the provided value.
200
-		//  2. Join the current state value, can be used for filters by other
201
-		//     functions.
202
-		//  3. Filter by `post`/`page` types.
203
-		//  4. Filter by `publish` status.
204
-		return $wpdb->prepare(
205
-			"
54
+    /**
55
+     * The list of states for the Batch Analysis:
56
+     *  - STATE_META_KEY: the batch analysis state meta key,
57
+     *  - STATE_SUBMIT: a post/page has been submitted for analysis,
58
+     *  - STATE_REQUEST: the plugin requested an analysis for the submitted
59
+     *      post/page,
60
+     *  - STATE_SUCCESS: the analysis has completed successfully,
61
+     *  - STATE_ERROR: the analysis returned an error.
62
+     *
63
+     * @since 3.14.2
64
+     */
65
+    const STATE_META_KEY = '_wl_batch_analysis_state';
66
+    const STATE_SUBMIT = 0;
67
+    const STATE_REQUEST = 1;
68
+    // ### COMPLETE states.
69
+    const STATE_SUCCESS = 2;
70
+    const STATE_ERROR = 2;
71
+
72
+    /**
73
+     * The submit timestamp meta key. A post may have more than one timestamp.
74
+     *
75
+     * @since 3.14.2
76
+     */
77
+    const SUBMIT_TIMESTAMP_META_KEY = '_wl_batch_analysis_submit_timestamp';
78
+
79
+    /**
80
+     * The request timestamp meta key. A post may have more than one timestamp.
81
+     *
82
+     * @since 3.14.2
83
+     */
84
+    const REQUEST_TIMESTAMP_META_KEY = '_wl_batch_analysis_request_timestamp';
85
+
86
+    /**
87
+     * The complete (success or error) timestamp meta key. A post may have more
88
+     * than one timestamp.
89
+     *
90
+     * @since 3.14.2
91
+     */
92
+    const COMPLETE_TIMESTAMP_META_KEY = '_wl_batch_analysis_complete_timestamp';
93
+
94
+    /**
95
+     * The link setting meta key. A post may have more than one setting.
96
+     *
97
+     * @since 3.14.2
98
+     */
99
+    const LINK_META_KEY = '_wl_batch_analysis_link';
100
+
101
+    /**
102
+     * The warning timestamp meta key. A post has only zero/one value.
103
+     *
104
+     * @since 3.14.2
105
+     */
106
+    const WARNING_META_KEY = '_wl_batch_analysis_warning';
107
+
108
+    /**
109
+     * Option name.
110
+     *
111
+     * @since  3.14.0
112
+     */
113
+    const OPTION_NAME = 'wl_analyze_batch';
114
+
115
+    /**
116
+     * Name of waiting to be processed queue array inside the option.
117
+     *
118
+     * @since  3.14.0
119
+     */
120
+    const ANALYZE_QUEUE = 'queue';
121
+
122
+    /**
123
+     * Name of waiting for response queue array inside the option.
124
+     *
125
+     * @since  3.14.0
126
+     */
127
+    const RESPONSE_QUEUE = 'processing';
128
+
129
+    /**
130
+     * The {@link Wordlift} plugin instance.
131
+     *
132
+     * @since  3.14.0
133
+     * @access private
134
+     * @var \Wordlift $plugin The {@link Wordlift} plugin instance.
135
+     */
136
+    private $plugin;
137
+
138
+    /**
139
+     * The {@link Wordlift_Configuration_Service} instance.
140
+     *
141
+     * @since  3.14.0
142
+     * @access private
143
+     * @var \Wordlift_Configuration_Service $configuration_service The {@link Wordlift_Configuration_Service} instance.
144
+     */
145
+    private $configuration_service;
146
+
147
+    /**
148
+     * A {@link Wordlift_Log_Service} instance.
149
+     *
150
+     * @since  3.14.2
151
+     * @access private
152
+     * @var \Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
153
+     */
154
+    private $log;
155
+
156
+    /**
157
+     * The {@link Class_Wordlift_Batch_Analys_Service} instance.
158
+     *
159
+     * @since 3.14.0
160
+     *
161
+     * @param \Wordlift                       $plugin                The {@link Wordlift} plugin instance.
162
+     * @param \Wordlift_Configuration_Service $configuration_service The {@link Wordlift_Configuration_Service} instance.
163
+     */
164
+    public function __construct( $plugin, $configuration_service ) {
165
+
166
+        $this->plugin                = $plugin;
167
+        $this->configuration_service = $configuration_service;
168
+        $this->log                   = Wordlift_Log_Service::get_logger( 'Wordlift_Batch_Analysis_Service' );
169
+
170
+        add_action( 'wl_async_wl_batch_analysis_request', array(
171
+            $this,
172
+            'request',
173
+        ) );
174
+        add_action( 'wl_async_wl_batch_analysis_complete', array(
175
+            $this,
176
+            'complete',
177
+        ) );
178
+
179
+    }
180
+
181
+    /**
182
+     * Get the base SQL statement to submit a post for Batch Analysis.
183
+     *
184
+     * Functions may use this base SQL and add their own filters.
185
+     *
186
+     * @since 3.14.2
187
+     *
188
+     * @param string $link The link setting ('yes'/'no').
189
+     *
190
+     * @return string The base SQL.
191
+     */
192
+    private function get_sql( $link ) {
193
+        global $wpdb;
194
+
195
+        // Prepare the statement:
196
+        //  1. Insert into `postmeta` the meta keys and values:
197
+        //    a) state meta, with value of SUBMIT (0),
198
+        //    b) submit timestamp, with value of UTC timestamp,
199
+        //    c) link meta, with the provided value.
200
+        //  2. Join the current state value, can be used for filters by other
201
+        //     functions.
202
+        //  3. Filter by `post`/`page` types.
203
+        //  4. Filter by `publish` status.
204
+        return $wpdb->prepare(
205
+            "
206 206
 			INSERT INTO $wpdb->postmeta ( post_id, meta_key, meta_value )
207 207
 			SELECT p.ID, metas.*
208 208
 			FROM (
@@ -218,517 +218,517 @@  discard block
 block discarded – undo
218 218
 			WHERE p.post_type IN ('post', 'page')
219 219
 				AND p.post_status = 'publish'
220 220
 			",
221
-			self::STATE_META_KEY,
222
-			self::SUBMIT_TIMESTAMP_META_KEY,
223
-			self::LINK_META_KEY,
224
-			$link,
225
-			self::STATE_META_KEY
226
-		);
227
-	}
228
-
229
-	/**
230
-	 * Submit for analysis all the posts/pages which do not have annotations
231
-	 * and haven't been analyzed before.
232
-	 *
233
-	 * @since 3.14.2
234
-	 *
235
-	 * @param string $link The link setting.
236
-	 *
237
-	 * @return false|int The number of submitted {@link WP_Post}s or false on
238
-	 *                   error.
239
-	 */
240
-	public function submit_auto_selected_posts( $link ) {
241
-		global $wpdb;
242
-
243
-		// Submit the posts/pages and return the number of affected results.
244
-		// We're using a SQL query here because we could have potentially
245
-		// thousands of rows.
246
-		$count = $wpdb->query( $wpdb->prepare(
247
-			$this->get_sql( $link ) .
248
-			"
221
+            self::STATE_META_KEY,
222
+            self::SUBMIT_TIMESTAMP_META_KEY,
223
+            self::LINK_META_KEY,
224
+            $link,
225
+            self::STATE_META_KEY
226
+        );
227
+    }
228
+
229
+    /**
230
+     * Submit for analysis all the posts/pages which do not have annotations
231
+     * and haven't been analyzed before.
232
+     *
233
+     * @since 3.14.2
234
+     *
235
+     * @param string $link The link setting.
236
+     *
237
+     * @return false|int The number of submitted {@link WP_Post}s or false on
238
+     *                   error.
239
+     */
240
+    public function submit_auto_selected_posts( $link ) {
241
+        global $wpdb;
242
+
243
+        // Submit the posts/pages and return the number of affected results.
244
+        // We're using a SQL query here because we could have potentially
245
+        // thousands of rows.
246
+        $count = $wpdb->query( $wpdb->prepare(
247
+            $this->get_sql( $link ) .
248
+            "
249 249
 				AND batch_analysis_state.meta_value IS NULL
250 250
 				AND p.post_content NOT REGEXP %s;
251 251
 			",
252
-			'<[a-z]+ id="urn:[^"]+" class="[^"]+" itemid="[^"]+">'
253
-		) );
254
-
255
-		// Request Batch Analysis (the operation is handled asynchronously).
256
-		do_action( 'wl_batch_analysis_request' );
257
-
258
-		// Divide the count by 3 to get the number of posts/pages queued.
259
-		return $count / 3;
260
-	}
261
-
262
-	/**
263
-	 * Submit all posts for analysis.
264
-	 *
265
-	 * @since 3.14.5
266
-	 *
267
-	 * @param string $link The link setting.
268
-	 *
269
-	 * @return false|int The number of submitted {@link WP_Post}s or false on
270
-	 *                   error.
271
-	 */
272
-	public function submit_all_posts( $link ) {
273
-		global $wpdb;
274
-
275
-		// Submit the posts/pages and return the number of affected results.
276
-		// We're using a SQL query here because we could have potentially
277
-		// thousands of rows.
278
-		$count = $wpdb->query( $this->get_sql( $link ) );
279
-
280
-		// Request Batch Analysis (the operation is handled asynchronously).
281
-		do_action( 'wl_batch_analysis_request' );
282
-
283
-		// Divide the count by 3 to get the number of posts/pages queued.
284
-		return $count / 3;
285
-	}
286
-
287
-	/**
288
-	 * Submit the provided list of {@link WP_Post}s' ids for Batch Analysis.
289
-	 *
290
-	 * @since 3.14.2
291
-	 *
292
-	 * @param int|array $post_ids A single {@link WP_Post}'s id or an array of
293
-	 *                            {@link WP_Post}s' ids.
294
-	 * @param string    $link     The link setting.
295
-	 *
296
-	 * @return int The number of submitted {@link WP_Post}s or false on error.
297
-	 */
298
-	public function submit( $post_ids, $link ) {
299
-		global $wpdb;
300
-
301
-		// Submit the posts/pages and return the number of affected results.
302
-		// We're using a SQL query here because we could have potentially
303
-		// thousands of rows.
304
-		$count = $wpdb->query(
305
-			$this->get_sql( $link ) .
306
-			' AND p.ID IN ( ' . implode( ',', wp_parse_id_list( $post_ids ) ) . ' )'
307
-		);
308
-
309
-		// Request Batch Analysis (the operation is handled asynchronously).
310
-		do_action( 'wl_batch_analysis_request' );
311
-
312
-		// Divide the count by 3 to get the number of posts/pages queued.
313
-		return $count / 3;
314
-	}
315
-
316
-	/**
317
-	 * Cancel the Batch Analysis request for the specified {@link WP_Post}s.
318
-	 *
319
-	 * @since 3.14.2
320
-	 *
321
-	 * @param int|array $post_ids A single {@link WP_Post}'s id or an array of
322
-	 *                            {@link WP_Post}s' ids.
323
-	 *
324
-	 * @return false|int The number of cancelled {@link WP_Post}s or false on
325
-	 *                   error.
326
-	 */
327
-	public function cancel( $post_ids ) {
328
-		global $wpdb;
329
-
330
-		return $wpdb->query( $wpdb->prepare(
331
-			"
252
+            '<[a-z]+ id="urn:[^"]+" class="[^"]+" itemid="[^"]+">'
253
+        ) );
254
+
255
+        // Request Batch Analysis (the operation is handled asynchronously).
256
+        do_action( 'wl_batch_analysis_request' );
257
+
258
+        // Divide the count by 3 to get the number of posts/pages queued.
259
+        return $count / 3;
260
+    }
261
+
262
+    /**
263
+     * Submit all posts for analysis.
264
+     *
265
+     * @since 3.14.5
266
+     *
267
+     * @param string $link The link setting.
268
+     *
269
+     * @return false|int The number of submitted {@link WP_Post}s or false on
270
+     *                   error.
271
+     */
272
+    public function submit_all_posts( $link ) {
273
+        global $wpdb;
274
+
275
+        // Submit the posts/pages and return the number of affected results.
276
+        // We're using a SQL query here because we could have potentially
277
+        // thousands of rows.
278
+        $count = $wpdb->query( $this->get_sql( $link ) );
279
+
280
+        // Request Batch Analysis (the operation is handled asynchronously).
281
+        do_action( 'wl_batch_analysis_request' );
282
+
283
+        // Divide the count by 3 to get the number of posts/pages queued.
284
+        return $count / 3;
285
+    }
286
+
287
+    /**
288
+     * Submit the provided list of {@link WP_Post}s' ids for Batch Analysis.
289
+     *
290
+     * @since 3.14.2
291
+     *
292
+     * @param int|array $post_ids A single {@link WP_Post}'s id or an array of
293
+     *                            {@link WP_Post}s' ids.
294
+     * @param string    $link     The link setting.
295
+     *
296
+     * @return int The number of submitted {@link WP_Post}s or false on error.
297
+     */
298
+    public function submit( $post_ids, $link ) {
299
+        global $wpdb;
300
+
301
+        // Submit the posts/pages and return the number of affected results.
302
+        // We're using a SQL query here because we could have potentially
303
+        // thousands of rows.
304
+        $count = $wpdb->query(
305
+            $this->get_sql( $link ) .
306
+            ' AND p.ID IN ( ' . implode( ',', wp_parse_id_list( $post_ids ) ) . ' )'
307
+        );
308
+
309
+        // Request Batch Analysis (the operation is handled asynchronously).
310
+        do_action( 'wl_batch_analysis_request' );
311
+
312
+        // Divide the count by 3 to get the number of posts/pages queued.
313
+        return $count / 3;
314
+    }
315
+
316
+    /**
317
+     * Cancel the Batch Analysis request for the specified {@link WP_Post}s.
318
+     *
319
+     * @since 3.14.2
320
+     *
321
+     * @param int|array $post_ids A single {@link WP_Post}'s id or an array of
322
+     *                            {@link WP_Post}s' ids.
323
+     *
324
+     * @return false|int The number of cancelled {@link WP_Post}s or false on
325
+     *                   error.
326
+     */
327
+    public function cancel( $post_ids ) {
328
+        global $wpdb;
329
+
330
+        return $wpdb->query( $wpdb->prepare(
331
+            "
332 332
 			DELETE FROM $wpdb->postmeta
333 333
 			WHERE meta_key = %s
334 334
 				AND meta_value = %s
335 335
 				AND post_id IN ( " . implode( ',', wp_parse_id_list( $post_ids ) ) . " )
336 336
 			",
337
-			self::STATE_META_KEY,
338
-			self::STATE_REQUEST
339
-		) );
337
+            self::STATE_META_KEY,
338
+            self::STATE_REQUEST
339
+        ) );
340 340
 
341
-	}
341
+    }
342 342
 
343
-	/**
344
-	 * Request the batch analysis for submitted posts.
345
-	 *
346
-	 * @since 3.14.2
347
-	 */
348
-	public function request() {
343
+    /**
344
+     * Request the batch analysis for submitted posts.
345
+     *
346
+     * @since 3.14.2
347
+     */
348
+    public function request() {
349 349
 
350
-		$this->log->debug( "Requesting analysis..." );
350
+        $this->log->debug( "Requesting analysis..." );
351 351
 
352
-		// By default 5 posts of any post type are returned.
353
-		$posts = get_posts( array(
354
-			'fields'     => 'ids',
355
-			'meta_key'   => self::STATE_META_KEY,
356
-			'meta_value' => self::STATE_SUBMIT,
357
-			'orderby'    => 'ID',
358
-		) );
352
+        // By default 5 posts of any post type are returned.
353
+        $posts = get_posts( array(
354
+            'fields'     => 'ids',
355
+            'meta_key'   => self::STATE_META_KEY,
356
+            'meta_value' => self::STATE_SUBMIT,
357
+            'orderby'    => 'ID',
358
+        ) );
359 359
 
360
-		// Bail out if there are no submitted posts.
361
-		if ( empty( $posts ) ) {
362
-			$this->log->debug( 'No posts to submit found, checking for completed requests...' );
360
+        // Bail out if there are no submitted posts.
361
+        if ( empty( $posts ) ) {
362
+            $this->log->debug( 'No posts to submit found, checking for completed requests...' );
363 363
 
364
-			do_action( 'wl_batch_analysis_complete' );
364
+            do_action( 'wl_batch_analysis_complete' );
365 365
 
366
-			return;
367
-		}
366
+            return;
367
+        }
368 368
 
369
-		// Send a request for each post.
370
-		foreach ( $posts as $id ) {
371
-			$this->log->debug( "Requesting analysis for post $id..." );
369
+        // Send a request for each post.
370
+        foreach ( $posts as $id ) {
371
+            $this->log->debug( "Requesting analysis for post $id..." );
372 372
 
373
-			// Change the state to `REQUEST`.
374
-			$this->set_state( $id, self::STATE_REQUEST );
373
+            // Change the state to `REQUEST`.
374
+            $this->set_state( $id, self::STATE_REQUEST );
375 375
 
376
-			// Send the actual request to the remote service.
377
-			$result = $this->do_request( $id );
376
+            // Send the actual request to the remote service.
377
+            $result = $this->do_request( $id );
378 378
 
379
-			$this->log->debug( "Analysis requested for post $id." );
379
+            $this->log->debug( "Analysis requested for post $id." );
380 380
 
381
-			// Set an error if we received an error.
382
-			if ( is_wp_error( $result ) ) {
383
-				$this->log->error( "Analysis request for post $id returned {$result->get_error_message()}." );
381
+            // Set an error if we received an error.
382
+            if ( is_wp_error( $result ) ) {
383
+                $this->log->error( "Analysis request for post $id returned {$result->get_error_message()}." );
384 384
 
385
-				$this->set_state( $id, self::STATE_ERROR );
386
-			}
385
+                $this->set_state( $id, self::STATE_ERROR );
386
+            }
387 387
 
388
-		}
388
+        }
389 389
 
390
-		// Call the `wl_batch_analysis_request` action again. This is going
391
-		// to be handled by the async task.
392
-		do_action( 'wl_batch_analysis_request' );
390
+        // Call the `wl_batch_analysis_request` action again. This is going
391
+        // to be handled by the async task.
392
+        do_action( 'wl_batch_analysis_request' );
393 393
 
394
-	}
394
+    }
395 395
 
396
-	/**
397
-	 * Get the results for the Batch Analysis.
398
-	 *
399
-	 * @since 3.14.2
400
-	 */
401
-	public function complete() {
396
+    /**
397
+     * Get the results for the Batch Analysis.
398
+     *
399
+     * @since 3.14.2
400
+     */
401
+    public function complete() {
402 402
 
403
-		$this->log->debug( "Requesting results..." );
403
+        $this->log->debug( "Requesting results..." );
404 404
 
405
-		// By default 5 posts of any post type are returned.
406
-		$posts = get_posts( array(
407
-			'fields'     => 'ids',
408
-			'meta_key'   => self::STATE_META_KEY,
409
-			'meta_value' => self::STATE_REQUEST,
410
-			'orderby'    => 'ID',
411
-		) );
405
+        // By default 5 posts of any post type are returned.
406
+        $posts = get_posts( array(
407
+            'fields'     => 'ids',
408
+            'meta_key'   => self::STATE_META_KEY,
409
+            'meta_value' => self::STATE_REQUEST,
410
+            'orderby'    => 'ID',
411
+        ) );
412 412
 
413
-		// Bail out if there are no submitted posts.
414
-		if ( empty( $posts ) ) {
415
-			$this->log->debug( 'No posts in request state found.' );
413
+        // Bail out if there are no submitted posts.
414
+        if ( empty( $posts ) ) {
415
+            $this->log->debug( 'No posts in request state found.' );
416 416
 
417
-			return;
418
-		}
417
+            return;
418
+        }
419 419
 
420
-		// Send a request for each post.
421
-		foreach ( $posts as $id ) {
422
-			$this->log->debug( "Requesting results for post $id..." );
420
+        // Send a request for each post.
421
+        foreach ( $posts as $id ) {
422
+            $this->log->debug( "Requesting results for post $id..." );
423 423
 
424
-			// Send the actual request to the remote service.
425
-			$response = $this->do_complete( $id );
424
+            // Send the actual request to the remote service.
425
+            $response = $this->do_complete( $id );
426 426
 
427
-			$this->log->debug( "Results requested for post $id." );
427
+            $this->log->debug( "Results requested for post $id." );
428 428
 
429
-			// Set an error if we received an error.
430
-			if ( ! is_wp_error( $response ) && isset( $response['body'] ) ) {
429
+            // Set an error if we received an error.
430
+            if ( ! is_wp_error( $response ) && isset( $response['body'] ) ) {
431 431
 
432
-				$this->log->debug( "Results received for post $id." );
432
+                $this->log->debug( "Results received for post $id." );
433 433
 
434
-				// Save the returned content as new revision.
435
-				$json = json_decode( $response['body'] );
436
-
437
-				// Continue if the content isn't set.
438
-				if ( ! isset( $json->content ) || empty( $json->content ) ) {
439
-					continue;
440
-				}
434
+                // Save the returned content as new revision.
435
+                $json = json_decode( $response['body'] );
436
+
437
+                // Continue if the content isn't set.
438
+                if ( ! isset( $json->content ) || empty( $json->content ) ) {
439
+                    continue;
440
+                }
441 441
 
442
-				$this->set_warning_based_on_content( $id, $json->content );
443
-
444
-				$content = wp_slash( $json->content );
445
-
446
-				wp_update_post( array(
447
-					'ID'           => $id,
448
-					'post_content' => $content,
449
-				) );
450
-
451
-				// Update the status.
452
-				$this->set_state( $id, self::STATE_SUCCESS );
453
-
454
-				$this->log->debug( "Post $id updated with batch analysis results." );
455
-
456
-				continue;
457
-			}
458
-
459
-			// @todo: implement a kind of timeout that sets an error if the
460
-			// results haven't been received after a long time.
461
-
462
-		}
463
-
464
-		// Call the `wl_batch_analysis_request` action again. This is going
465
-		// to be handled by the async task.
466
-		do_action( 'wl_batch_analysis_complete' );
467
-
468
-	}
469
-
470
-	/**
471
-	 * Set a warning flag on the {@link WP_Post} if its content has suspicious
472
-	 * interpolations.
473
-	 *
474
-	 * @since 3.14.2
475
-	 *
476
-	 * @param int    $post_id The {@link WP_Post}'s id.
477
-	 * @param string $content The {@link WP_Post}'s content.
478
-	 *
479
-	 * @return string The content (for chaining operations).
480
-	 */
481
-	private function set_warning_based_on_content( $post_id, $content ) {
482
-
483
-		$matches = array();
484
-
485
-		// Check for suspicious interpolations.
486
-		$warning = 0 < preg_match_all( '/\w<[a-z]+ id="urn:enhancement-[^"]+" class="[^"]+" itemid="[^"]+">/', $content, $matches )
487
-				   || 0 < preg_match_all( '/<[a-z]+ id="urn:enhancement-[^"]+" class="[^"]+" itemid="[^"]+">\s/', $content, $matches );
488
-
489
-		// Set the warning flag accordingly.
490
-		$this->set_warning( $post_id, $warning );
491
-
492
-		return $content;
493
-	}
494
-
495
-	/**
496
-	 * Clear the warning flag for the specified {@link WP_Post}s.
497
-	 *
498
-	 * @since 3.14.2
499
-	 *
500
-	 * @param int|array $post_ids A single {@link WP_Post}'s id or an array of
501
-	 *                            {@link WP_Post}s' ids.
502
-	 */
503
-	public function clear_warning( $post_ids ) {
504
-
505
-		foreach ( (array) $post_ids as $post_id ) {
506
-			delete_post_meta( $post_id, self::WARNING_META_KEY );
507
-		}
508
-
509
-	}
510
-
511
-	/**
512
-	 * Set the warning flag for the specified {@link WP_Post}.
513
-	 *
514
-	 * @since 3.14.2
515
-	 *
516
-	 * @param int  $post_id The {@link WP_Post}'s id.
517
-	 * @param bool $value   The flag's value.
518
-	 *
519
-	 * @return int|bool Meta ID if the key didn't exist, true on successful update,
520
-	 *                  false on failure.
521
-	 */
522
-	private function set_warning( $post_id, $value ) {
523
-
524
-		return update_post_meta( $post_id, self::WARNING_META_KEY, ( true === $value ? 'yes' : 'no' ) );
525
-	}
526
-
527
-	/**
528
-	 * Get the post/page batch analysis state.
529
-	 *
530
-	 * @since 3.14.2
531
-	 *
532
-	 * @param int $post_id The {@link WP_Post}'s id.
533
-	 *
534
-	 * @return int|string The post state or an empty string if not set.
535
-	 */
536
-	public function get_state( $post_id ) {
537
-
538
-		return get_post_meta( $post_id, self::STATE_META_KEY, true );
539
-	}
540
-
541
-	/**
542
-	 * Set the post/page batch analysis state.
543
-	 *
544
-	 * @since 3.14.2
545
-	 *
546
-	 * @param int $post_id The {@link WP_Post}'s id.
547
-	 * @param int $value   The new state.
548
-	 *
549
-	 * @return int|bool Meta ID if the key didn't exist, true on successful update,
550
-	 *                  false on failure.
551
-	 */
552
-	public function set_state( $post_id, $value ) {
553
-
554
-		// Update the state.
555
-		$result = update_post_meta( $post_id, self::STATE_META_KEY, $value );
556
-
557
-		// Update timestamps as required.
558
-		switch ( $value ) {
559
-
560
-			// ### REQUEST state.
561
-			case self::STATE_REQUEST:
562
-				add_post_meta( $post_id, self::REQUEST_TIMESTAMP_META_KEY, current_time( 'mysql', true ) );
563
-				break;
564
-
565
-			// ### SUCCESS/ERROR state.
566
-			case self::STATE_SUCCESS:
567
-			case self::STATE_ERROR:
568
-				add_post_meta( $post_id, self::COMPLETE_TIMESTAMP_META_KEY, current_time( 'mysql', true ) );
569
-				break;
570
-		}
571
-
572
-		// Finally return the result.
573
-		return $result;
574
-	}
575
-
576
-	/**
577
-	 * Get the link setting for a {@link WP_Post}.
578
-	 *
579
-	 * If there are multiple link settings, only the last one is returned.
580
-	 *
581
-	 * @since 3.14.2
582
-	 *
583
-	 * @param int $post_id The {@link WP_Post}'s id.
584
-	 *
585
-	 * @return string The link setting or `default` if not set.
586
-	 */
587
-	public function get_link( $post_id ) {
588
-
589
-		$values = get_post_meta( $post_id, self::LINK_META_KEY );
590
-
591
-		return end( $values ) ?: 'default';
592
-	}
593
-
594
-	/**
595
-	 * Get the array of post IDS waiting in the queue to start processing.
596
-	 *
597
-	 * @since 3.14.0
598
-	 *
599
-	 * @return array The waiting to be processed post ids queue.
600
-	 */
601
-	public function waiting_for_analysis() {
602
-
603
-		return get_posts( array(
604
-			'posts_per_page' => - 1,
605
-			'fields'         => 'ids',
606
-			'post_status'    => 'any',
607
-			'meta_key'       => self::STATE_META_KEY,
608
-			'meta_value'     => self::STATE_SUBMIT,
609
-			'orderby'        => 'ID',
610
-		) );
611
-	}
612
-
613
-	/**
614
-	 * Get the array of post IDS waiting for response.
615
-	 *
616
-	 * @deprecated
617
-	 * @since 3.14.0
618
-	 *
619
-	 * @return array The waiting for response post ids queue.
620
-	 */
621
-	public function waiting_for_response() {
622
-
623
-		return get_posts( array(
624
-			'posts_per_page' => - 1,
625
-			'fields'         => 'ids',
626
-			'post_status'    => 'any',
627
-			'meta_key'       => self::STATE_META_KEY,
628
-			'meta_value'     => self::STATE_REQUEST,
629
-			'orderby'        => 'ID',
630
-		) );
631
-	}
632
-
633
-	/**
634
-	 * Request the analysis for the specified {@link WP_Post}.
635
-	 *
636
-	 * @since 3.14.2
637
-	 *
638
-	 * @param int $post_id The {@link WP_Post}'s id.
639
-	 *
640
-	 * @return WP_Error|array The response or WP_Error on failure.
641
-	 */
642
-	private function do_request( $post_id ) {
643
-
644
-		// Get the post.
645
-		$post = get_post( $post_id );
646
-
647
-		// Bail out if the post isn't found.
648
-		if ( null === $post ) {
649
-			$this->log->warn( "Post $post_id not found." );
650
-
651
-			return new WP_Error( 0, "Cannot find post $post_id." );
652
-		}
653
-
654
-		// Get the link setting.
655
-		$link = $this->get_link( $post_id );
656
-
657
-		$this->log->debug( "Sending analysis request for post $post_id [ link :: $link ]..." );
658
-
659
-		// Get the batch analysis URL.
660
-		$url = $this->configuration_service->get_batch_analysis_url();
661
-
662
-		// Prepare the POST parameters.
663
-		$param = array(
664
-			'id'              => $post->ID,
665
-			'key'             => $this->configuration_service->get_key(),
666
-			'content'         => $post->post_content,
667
-			'contentLanguage' => $this->configuration_service->get_language_code(),
668
-			'version'         => $this->plugin->get_version(),
669
-			'links'           => $link,
670
-			'scope'           => 'local',
671
-		);
672
-
673
-		// Get the HTTP options.
674
-		$args = array_merge_recursive( unserialize( WL_REDLINK_API_HTTP_OPTIONS ), array(
675
-			'method'      => 'POST',
676
-			'headers'     => array(
677
-				'Accept'       => 'application/json',
678
-				'Content-type' => 'application/json; charset=UTF-8',
679
-			),
680
-			// we need to downgrade the HTTP version in this case since chunked encoding is dumping numbers in the response.
681
-			'httpversion' => '1.0',
682
-			'body'        => wp_json_encode( $param ),
683
-		) );
684
-
685
-		$this->log->debug( "Posting analysis request for post $post_id to $url..." );
686
-
687
-		// Post the parameter.
688
-		return wp_remote_post( $url, $args );
689
-	}
690
-
691
-	/**
692
-	 * Get the Batch Analysis results for the specified {@link WP_Post}.
693
-	 *
694
-	 * @since 3.14.2
695
-	 *
696
-	 * @param int $post_id The {@link WP_Post}'s id.
697
-	 *
698
-	 * @return WP_Error|array The response or WP_Error on failure.
699
-	 */
700
-	private function do_complete( $post_id ) {
701
-
702
-		$post = get_post( $post_id );
703
-
704
-		if ( null === $post ) {
705
-			// Post was possibly deleted, just bailout.
706
-			return new WP_Error( 0, "Post $post_id not found." );
707
-		}
708
-
709
-		$url = $this->configuration_service->get_batch_analysis_url();
710
-		$key = $this->configuration_service->get_key();
711
-		$url = $url . '/' . $post->ID . '?key=' . $key;
712
-
713
-		return wp_remote_get( $url, unserialize( WL_REDLINK_API_HTTP_OPTIONS ) );
714
-	}
715
-
716
-	/**
717
-	 * Get the {@link WP_Post}s' ids flagged with warnings.
718
-	 *
719
-	 * @since 3.14.2
720
-	 *
721
-	 * @return array An array of {@link WP_Post}s' ids.
722
-	 */
723
-	public function get_warnings() {
724
-
725
-		return get_posts( array(
726
-			'fields'      => 'ids',
727
-			'numberposts' => - 1,
728
-			'post_status' => 'any',
729
-			'meta_key'    => self::WARNING_META_KEY,
730
-			'meta_value'  => 'yes',
731
-		) );
732
-	}
442
+                $this->set_warning_based_on_content( $id, $json->content );
443
+
444
+                $content = wp_slash( $json->content );
445
+
446
+                wp_update_post( array(
447
+                    'ID'           => $id,
448
+                    'post_content' => $content,
449
+                ) );
450
+
451
+                // Update the status.
452
+                $this->set_state( $id, self::STATE_SUCCESS );
453
+
454
+                $this->log->debug( "Post $id updated with batch analysis results." );
455
+
456
+                continue;
457
+            }
458
+
459
+            // @todo: implement a kind of timeout that sets an error if the
460
+            // results haven't been received after a long time.
461
+
462
+        }
463
+
464
+        // Call the `wl_batch_analysis_request` action again. This is going
465
+        // to be handled by the async task.
466
+        do_action( 'wl_batch_analysis_complete' );
467
+
468
+    }
469
+
470
+    /**
471
+     * Set a warning flag on the {@link WP_Post} if its content has suspicious
472
+     * interpolations.
473
+     *
474
+     * @since 3.14.2
475
+     *
476
+     * @param int    $post_id The {@link WP_Post}'s id.
477
+     * @param string $content The {@link WP_Post}'s content.
478
+     *
479
+     * @return string The content (for chaining operations).
480
+     */
481
+    private function set_warning_based_on_content( $post_id, $content ) {
482
+
483
+        $matches = array();
484
+
485
+        // Check for suspicious interpolations.
486
+        $warning = 0 < preg_match_all( '/\w<[a-z]+ id="urn:enhancement-[^"]+" class="[^"]+" itemid="[^"]+">/', $content, $matches )
487
+                   || 0 < preg_match_all( '/<[a-z]+ id="urn:enhancement-[^"]+" class="[^"]+" itemid="[^"]+">\s/', $content, $matches );
488
+
489
+        // Set the warning flag accordingly.
490
+        $this->set_warning( $post_id, $warning );
491
+
492
+        return $content;
493
+    }
494
+
495
+    /**
496
+     * Clear the warning flag for the specified {@link WP_Post}s.
497
+     *
498
+     * @since 3.14.2
499
+     *
500
+     * @param int|array $post_ids A single {@link WP_Post}'s id or an array of
501
+     *                            {@link WP_Post}s' ids.
502
+     */
503
+    public function clear_warning( $post_ids ) {
504
+
505
+        foreach ( (array) $post_ids as $post_id ) {
506
+            delete_post_meta( $post_id, self::WARNING_META_KEY );
507
+        }
508
+
509
+    }
510
+
511
+    /**
512
+     * Set the warning flag for the specified {@link WP_Post}.
513
+     *
514
+     * @since 3.14.2
515
+     *
516
+     * @param int  $post_id The {@link WP_Post}'s id.
517
+     * @param bool $value   The flag's value.
518
+     *
519
+     * @return int|bool Meta ID if the key didn't exist, true on successful update,
520
+     *                  false on failure.
521
+     */
522
+    private function set_warning( $post_id, $value ) {
523
+
524
+        return update_post_meta( $post_id, self::WARNING_META_KEY, ( true === $value ? 'yes' : 'no' ) );
525
+    }
526
+
527
+    /**
528
+     * Get the post/page batch analysis state.
529
+     *
530
+     * @since 3.14.2
531
+     *
532
+     * @param int $post_id The {@link WP_Post}'s id.
533
+     *
534
+     * @return int|string The post state or an empty string if not set.
535
+     */
536
+    public function get_state( $post_id ) {
537
+
538
+        return get_post_meta( $post_id, self::STATE_META_KEY, true );
539
+    }
540
+
541
+    /**
542
+     * Set the post/page batch analysis state.
543
+     *
544
+     * @since 3.14.2
545
+     *
546
+     * @param int $post_id The {@link WP_Post}'s id.
547
+     * @param int $value   The new state.
548
+     *
549
+     * @return int|bool Meta ID if the key didn't exist, true on successful update,
550
+     *                  false on failure.
551
+     */
552
+    public function set_state( $post_id, $value ) {
553
+
554
+        // Update the state.
555
+        $result = update_post_meta( $post_id, self::STATE_META_KEY, $value );
556
+
557
+        // Update timestamps as required.
558
+        switch ( $value ) {
559
+
560
+            // ### REQUEST state.
561
+            case self::STATE_REQUEST:
562
+                add_post_meta( $post_id, self::REQUEST_TIMESTAMP_META_KEY, current_time( 'mysql', true ) );
563
+                break;
564
+
565
+            // ### SUCCESS/ERROR state.
566
+            case self::STATE_SUCCESS:
567
+            case self::STATE_ERROR:
568
+                add_post_meta( $post_id, self::COMPLETE_TIMESTAMP_META_KEY, current_time( 'mysql', true ) );
569
+                break;
570
+        }
571
+
572
+        // Finally return the result.
573
+        return $result;
574
+    }
575
+
576
+    /**
577
+     * Get the link setting for a {@link WP_Post}.
578
+     *
579
+     * If there are multiple link settings, only the last one is returned.
580
+     *
581
+     * @since 3.14.2
582
+     *
583
+     * @param int $post_id The {@link WP_Post}'s id.
584
+     *
585
+     * @return string The link setting or `default` if not set.
586
+     */
587
+    public function get_link( $post_id ) {
588
+
589
+        $values = get_post_meta( $post_id, self::LINK_META_KEY );
590
+
591
+        return end( $values ) ?: 'default';
592
+    }
593
+
594
+    /**
595
+     * Get the array of post IDS waiting in the queue to start processing.
596
+     *
597
+     * @since 3.14.0
598
+     *
599
+     * @return array The waiting to be processed post ids queue.
600
+     */
601
+    public function waiting_for_analysis() {
602
+
603
+        return get_posts( array(
604
+            'posts_per_page' => - 1,
605
+            'fields'         => 'ids',
606
+            'post_status'    => 'any',
607
+            'meta_key'       => self::STATE_META_KEY,
608
+            'meta_value'     => self::STATE_SUBMIT,
609
+            'orderby'        => 'ID',
610
+        ) );
611
+    }
612
+
613
+    /**
614
+     * Get the array of post IDS waiting for response.
615
+     *
616
+     * @deprecated
617
+     * @since 3.14.0
618
+     *
619
+     * @return array The waiting for response post ids queue.
620
+     */
621
+    public function waiting_for_response() {
622
+
623
+        return get_posts( array(
624
+            'posts_per_page' => - 1,
625
+            'fields'         => 'ids',
626
+            'post_status'    => 'any',
627
+            'meta_key'       => self::STATE_META_KEY,
628
+            'meta_value'     => self::STATE_REQUEST,
629
+            'orderby'        => 'ID',
630
+        ) );
631
+    }
632
+
633
+    /**
634
+     * Request the analysis for the specified {@link WP_Post}.
635
+     *
636
+     * @since 3.14.2
637
+     *
638
+     * @param int $post_id The {@link WP_Post}'s id.
639
+     *
640
+     * @return WP_Error|array The response or WP_Error on failure.
641
+     */
642
+    private function do_request( $post_id ) {
643
+
644
+        // Get the post.
645
+        $post = get_post( $post_id );
646
+
647
+        // Bail out if the post isn't found.
648
+        if ( null === $post ) {
649
+            $this->log->warn( "Post $post_id not found." );
650
+
651
+            return new WP_Error( 0, "Cannot find post $post_id." );
652
+        }
653
+
654
+        // Get the link setting.
655
+        $link = $this->get_link( $post_id );
656
+
657
+        $this->log->debug( "Sending analysis request for post $post_id [ link :: $link ]..." );
658
+
659
+        // Get the batch analysis URL.
660
+        $url = $this->configuration_service->get_batch_analysis_url();
661
+
662
+        // Prepare the POST parameters.
663
+        $param = array(
664
+            'id'              => $post->ID,
665
+            'key'             => $this->configuration_service->get_key(),
666
+            'content'         => $post->post_content,
667
+            'contentLanguage' => $this->configuration_service->get_language_code(),
668
+            'version'         => $this->plugin->get_version(),
669
+            'links'           => $link,
670
+            'scope'           => 'local',
671
+        );
672
+
673
+        // Get the HTTP options.
674
+        $args = array_merge_recursive( unserialize( WL_REDLINK_API_HTTP_OPTIONS ), array(
675
+            'method'      => 'POST',
676
+            'headers'     => array(
677
+                'Accept'       => 'application/json',
678
+                'Content-type' => 'application/json; charset=UTF-8',
679
+            ),
680
+            // we need to downgrade the HTTP version in this case since chunked encoding is dumping numbers in the response.
681
+            'httpversion' => '1.0',
682
+            'body'        => wp_json_encode( $param ),
683
+        ) );
684
+
685
+        $this->log->debug( "Posting analysis request for post $post_id to $url..." );
686
+
687
+        // Post the parameter.
688
+        return wp_remote_post( $url, $args );
689
+    }
690
+
691
+    /**
692
+     * Get the Batch Analysis results for the specified {@link WP_Post}.
693
+     *
694
+     * @since 3.14.2
695
+     *
696
+     * @param int $post_id The {@link WP_Post}'s id.
697
+     *
698
+     * @return WP_Error|array The response or WP_Error on failure.
699
+     */
700
+    private function do_complete( $post_id ) {
701
+
702
+        $post = get_post( $post_id );
703
+
704
+        if ( null === $post ) {
705
+            // Post was possibly deleted, just bailout.
706
+            return new WP_Error( 0, "Post $post_id not found." );
707
+        }
708
+
709
+        $url = $this->configuration_service->get_batch_analysis_url();
710
+        $key = $this->configuration_service->get_key();
711
+        $url = $url . '/' . $post->ID . '?key=' . $key;
712
+
713
+        return wp_remote_get( $url, unserialize( WL_REDLINK_API_HTTP_OPTIONS ) );
714
+    }
715
+
716
+    /**
717
+     * Get the {@link WP_Post}s' ids flagged with warnings.
718
+     *
719
+     * @since 3.14.2
720
+     *
721
+     * @return array An array of {@link WP_Post}s' ids.
722
+     */
723
+    public function get_warnings() {
724
+
725
+        return get_posts( array(
726
+            'fields'      => 'ids',
727
+            'numberposts' => - 1,
728
+            'post_status' => 'any',
729
+            'meta_key'    => self::WARNING_META_KEY,
730
+            'meta_value'  => 'yes',
731
+        ) );
732
+    }
733 733
 
734 734
 }
Please login to merge, or discard this patch.
Spacing   +104 added lines, -104 removed lines patch added patch discarded remove patch
@@ -161,20 +161,20 @@  discard block
 block discarded – undo
161 161
 	 * @param \Wordlift                       $plugin                The {@link Wordlift} plugin instance.
162 162
 	 * @param \Wordlift_Configuration_Service $configuration_service The {@link Wordlift_Configuration_Service} instance.
163 163
 	 */
164
-	public function __construct( $plugin, $configuration_service ) {
164
+	public function __construct($plugin, $configuration_service) {
165 165
 
166 166
 		$this->plugin                = $plugin;
167 167
 		$this->configuration_service = $configuration_service;
168
-		$this->log                   = Wordlift_Log_Service::get_logger( 'Wordlift_Batch_Analysis_Service' );
168
+		$this->log                   = Wordlift_Log_Service::get_logger('Wordlift_Batch_Analysis_Service');
169 169
 
170
-		add_action( 'wl_async_wl_batch_analysis_request', array(
170
+		add_action('wl_async_wl_batch_analysis_request', array(
171 171
 			$this,
172 172
 			'request',
173
-		) );
174
-		add_action( 'wl_async_wl_batch_analysis_complete', array(
173
+		));
174
+		add_action('wl_async_wl_batch_analysis_complete', array(
175 175
 			$this,
176 176
 			'complete',
177
-		) );
177
+		));
178 178
 
179 179
 	}
180 180
 
@@ -189,7 +189,7 @@  discard block
 block discarded – undo
189 189
 	 *
190 190
 	 * @return string The base SQL.
191 191
 	 */
192
-	private function get_sql( $link ) {
192
+	private function get_sql($link) {
193 193
 		global $wpdb;
194 194
 
195 195
 		// Prepare the statement:
@@ -237,23 +237,23 @@  discard block
 block discarded – undo
237 237
 	 * @return false|int The number of submitted {@link WP_Post}s or false on
238 238
 	 *                   error.
239 239
 	 */
240
-	public function submit_auto_selected_posts( $link ) {
240
+	public function submit_auto_selected_posts($link) {
241 241
 		global $wpdb;
242 242
 
243 243
 		// Submit the posts/pages and return the number of affected results.
244 244
 		// We're using a SQL query here because we could have potentially
245 245
 		// thousands of rows.
246
-		$count = $wpdb->query( $wpdb->prepare(
247
-			$this->get_sql( $link ) .
246
+		$count = $wpdb->query($wpdb->prepare(
247
+			$this->get_sql($link).
248 248
 			"
249 249
 				AND batch_analysis_state.meta_value IS NULL
250 250
 				AND p.post_content NOT REGEXP %s;
251 251
 			",
252 252
 			'<[a-z]+ id="urn:[^"]+" class="[^"]+" itemid="[^"]+">'
253
-		) );
253
+		));
254 254
 
255 255
 		// Request Batch Analysis (the operation is handled asynchronously).
256
-		do_action( 'wl_batch_analysis_request' );
256
+		do_action('wl_batch_analysis_request');
257 257
 
258 258
 		// Divide the count by 3 to get the number of posts/pages queued.
259 259
 		return $count / 3;
@@ -269,16 +269,16 @@  discard block
 block discarded – undo
269 269
 	 * @return false|int The number of submitted {@link WP_Post}s or false on
270 270
 	 *                   error.
271 271
 	 */
272
-	public function submit_all_posts( $link ) {
272
+	public function submit_all_posts($link) {
273 273
 		global $wpdb;
274 274
 
275 275
 		// Submit the posts/pages and return the number of affected results.
276 276
 		// We're using a SQL query here because we could have potentially
277 277
 		// thousands of rows.
278
-		$count = $wpdb->query( $this->get_sql( $link ) );
278
+		$count = $wpdb->query($this->get_sql($link));
279 279
 
280 280
 		// Request Batch Analysis (the operation is handled asynchronously).
281
-		do_action( 'wl_batch_analysis_request' );
281
+		do_action('wl_batch_analysis_request');
282 282
 
283 283
 		// Divide the count by 3 to get the number of posts/pages queued.
284 284
 		return $count / 3;
@@ -295,19 +295,19 @@  discard block
 block discarded – undo
295 295
 	 *
296 296
 	 * @return int The number of submitted {@link WP_Post}s or false on error.
297 297
 	 */
298
-	public function submit( $post_ids, $link ) {
298
+	public function submit($post_ids, $link) {
299 299
 		global $wpdb;
300 300
 
301 301
 		// Submit the posts/pages and return the number of affected results.
302 302
 		// We're using a SQL query here because we could have potentially
303 303
 		// thousands of rows.
304 304
 		$count = $wpdb->query(
305
-			$this->get_sql( $link ) .
306
-			' AND p.ID IN ( ' . implode( ',', wp_parse_id_list( $post_ids ) ) . ' )'
305
+			$this->get_sql($link).
306
+			' AND p.ID IN ( '.implode(',', wp_parse_id_list($post_ids)).' )'
307 307
 		);
308 308
 
309 309
 		// Request Batch Analysis (the operation is handled asynchronously).
310
-		do_action( 'wl_batch_analysis_request' );
310
+		do_action('wl_batch_analysis_request');
311 311
 
312 312
 		// Divide the count by 3 to get the number of posts/pages queued.
313 313
 		return $count / 3;
@@ -324,19 +324,19 @@  discard block
 block discarded – undo
324 324
 	 * @return false|int The number of cancelled {@link WP_Post}s or false on
325 325
 	 *                   error.
326 326
 	 */
327
-	public function cancel( $post_ids ) {
327
+	public function cancel($post_ids) {
328 328
 		global $wpdb;
329 329
 
330
-		return $wpdb->query( $wpdb->prepare(
330
+		return $wpdb->query($wpdb->prepare(
331 331
 			"
332 332
 			DELETE FROM $wpdb->postmeta
333 333
 			WHERE meta_key = %s
334 334
 				AND meta_value = %s
335
-				AND post_id IN ( " . implode( ',', wp_parse_id_list( $post_ids ) ) . " )
335
+				AND post_id IN ( ".implode(',', wp_parse_id_list($post_ids))." )
336 336
 			",
337 337
 			self::STATE_META_KEY,
338 338
 			self::STATE_REQUEST
339
-		) );
339
+		));
340 340
 
341 341
 	}
342 342
 
@@ -347,49 +347,49 @@  discard block
 block discarded – undo
347 347
 	 */
348 348
 	public function request() {
349 349
 
350
-		$this->log->debug( "Requesting analysis..." );
350
+		$this->log->debug("Requesting analysis...");
351 351
 
352 352
 		// By default 5 posts of any post type are returned.
353
-		$posts = get_posts( array(
353
+		$posts = get_posts(array(
354 354
 			'fields'     => 'ids',
355 355
 			'meta_key'   => self::STATE_META_KEY,
356 356
 			'meta_value' => self::STATE_SUBMIT,
357 357
 			'orderby'    => 'ID',
358
-		) );
358
+		));
359 359
 
360 360
 		// Bail out if there are no submitted posts.
361
-		if ( empty( $posts ) ) {
362
-			$this->log->debug( 'No posts to submit found, checking for completed requests...' );
361
+		if (empty($posts)) {
362
+			$this->log->debug('No posts to submit found, checking for completed requests...');
363 363
 
364
-			do_action( 'wl_batch_analysis_complete' );
364
+			do_action('wl_batch_analysis_complete');
365 365
 
366 366
 			return;
367 367
 		}
368 368
 
369 369
 		// Send a request for each post.
370
-		foreach ( $posts as $id ) {
371
-			$this->log->debug( "Requesting analysis for post $id..." );
370
+		foreach ($posts as $id) {
371
+			$this->log->debug("Requesting analysis for post $id...");
372 372
 
373 373
 			// Change the state to `REQUEST`.
374
-			$this->set_state( $id, self::STATE_REQUEST );
374
+			$this->set_state($id, self::STATE_REQUEST);
375 375
 
376 376
 			// Send the actual request to the remote service.
377
-			$result = $this->do_request( $id );
377
+			$result = $this->do_request($id);
378 378
 
379
-			$this->log->debug( "Analysis requested for post $id." );
379
+			$this->log->debug("Analysis requested for post $id.");
380 380
 
381 381
 			// Set an error if we received an error.
382
-			if ( is_wp_error( $result ) ) {
383
-				$this->log->error( "Analysis request for post $id returned {$result->get_error_message()}." );
382
+			if (is_wp_error($result)) {
383
+				$this->log->error("Analysis request for post $id returned {$result->get_error_message()}.");
384 384
 
385
-				$this->set_state( $id, self::STATE_ERROR );
385
+				$this->set_state($id, self::STATE_ERROR);
386 386
 			}
387 387
 
388 388
 		}
389 389
 
390 390
 		// Call the `wl_batch_analysis_request` action again. This is going
391 391
 		// to be handled by the async task.
392
-		do_action( 'wl_batch_analysis_request' );
392
+		do_action('wl_batch_analysis_request');
393 393
 
394 394
 	}
395 395
 
@@ -400,58 +400,58 @@  discard block
 block discarded – undo
400 400
 	 */
401 401
 	public function complete() {
402 402
 
403
-		$this->log->debug( "Requesting results..." );
403
+		$this->log->debug("Requesting results...");
404 404
 
405 405
 		// By default 5 posts of any post type are returned.
406
-		$posts = get_posts( array(
406
+		$posts = get_posts(array(
407 407
 			'fields'     => 'ids',
408 408
 			'meta_key'   => self::STATE_META_KEY,
409 409
 			'meta_value' => self::STATE_REQUEST,
410 410
 			'orderby'    => 'ID',
411
-		) );
411
+		));
412 412
 
413 413
 		// Bail out if there are no submitted posts.
414
-		if ( empty( $posts ) ) {
415
-			$this->log->debug( 'No posts in request state found.' );
414
+		if (empty($posts)) {
415
+			$this->log->debug('No posts in request state found.');
416 416
 
417 417
 			return;
418 418
 		}
419 419
 
420 420
 		// Send a request for each post.
421
-		foreach ( $posts as $id ) {
422
-			$this->log->debug( "Requesting results for post $id..." );
421
+		foreach ($posts as $id) {
422
+			$this->log->debug("Requesting results for post $id...");
423 423
 
424 424
 			// Send the actual request to the remote service.
425
-			$response = $this->do_complete( $id );
425
+			$response = $this->do_complete($id);
426 426
 
427
-			$this->log->debug( "Results requested for post $id." );
427
+			$this->log->debug("Results requested for post $id.");
428 428
 
429 429
 			// Set an error if we received an error.
430
-			if ( ! is_wp_error( $response ) && isset( $response['body'] ) ) {
430
+			if ( ! is_wp_error($response) && isset($response['body'])) {
431 431
 
432
-				$this->log->debug( "Results received for post $id." );
432
+				$this->log->debug("Results received for post $id.");
433 433
 
434 434
 				// Save the returned content as new revision.
435
-				$json = json_decode( $response['body'] );
435
+				$json = json_decode($response['body']);
436 436
 
437 437
 				// Continue if the content isn't set.
438
-				if ( ! isset( $json->content ) || empty( $json->content ) ) {
438
+				if ( ! isset($json->content) || empty($json->content)) {
439 439
 					continue;
440 440
 				}
441 441
 
442
-				$this->set_warning_based_on_content( $id, $json->content );
442
+				$this->set_warning_based_on_content($id, $json->content);
443 443
 
444
-				$content = wp_slash( $json->content );
444
+				$content = wp_slash($json->content);
445 445
 
446
-				wp_update_post( array(
446
+				wp_update_post(array(
447 447
 					'ID'           => $id,
448 448
 					'post_content' => $content,
449
-				) );
449
+				));
450 450
 
451 451
 				// Update the status.
452
-				$this->set_state( $id, self::STATE_SUCCESS );
452
+				$this->set_state($id, self::STATE_SUCCESS);
453 453
 
454
-				$this->log->debug( "Post $id updated with batch analysis results." );
454
+				$this->log->debug("Post $id updated with batch analysis results.");
455 455
 
456 456
 				continue;
457 457
 			}
@@ -463,7 +463,7 @@  discard block
 block discarded – undo
463 463
 
464 464
 		// Call the `wl_batch_analysis_request` action again. This is going
465 465
 		// to be handled by the async task.
466
-		do_action( 'wl_batch_analysis_complete' );
466
+		do_action('wl_batch_analysis_complete');
467 467
 
468 468
 	}
469 469
 
@@ -478,16 +478,16 @@  discard block
 block discarded – undo
478 478
 	 *
479 479
 	 * @return string The content (for chaining operations).
480 480
 	 */
481
-	private function set_warning_based_on_content( $post_id, $content ) {
481
+	private function set_warning_based_on_content($post_id, $content) {
482 482
 
483 483
 		$matches = array();
484 484
 
485 485
 		// Check for suspicious interpolations.
486
-		$warning = 0 < preg_match_all( '/\w<[a-z]+ id="urn:enhancement-[^"]+" class="[^"]+" itemid="[^"]+">/', $content, $matches )
487
-				   || 0 < preg_match_all( '/<[a-z]+ id="urn:enhancement-[^"]+" class="[^"]+" itemid="[^"]+">\s/', $content, $matches );
486
+		$warning = 0 < preg_match_all('/\w<[a-z]+ id="urn:enhancement-[^"]+" class="[^"]+" itemid="[^"]+">/', $content, $matches)
487
+				   || 0 < preg_match_all('/<[a-z]+ id="urn:enhancement-[^"]+" class="[^"]+" itemid="[^"]+">\s/', $content, $matches);
488 488
 
489 489
 		// Set the warning flag accordingly.
490
-		$this->set_warning( $post_id, $warning );
490
+		$this->set_warning($post_id, $warning);
491 491
 
492 492
 		return $content;
493 493
 	}
@@ -500,10 +500,10 @@  discard block
 block discarded – undo
500 500
 	 * @param int|array $post_ids A single {@link WP_Post}'s id or an array of
501 501
 	 *                            {@link WP_Post}s' ids.
502 502
 	 */
503
-	public function clear_warning( $post_ids ) {
503
+	public function clear_warning($post_ids) {
504 504
 
505
-		foreach ( (array) $post_ids as $post_id ) {
506
-			delete_post_meta( $post_id, self::WARNING_META_KEY );
505
+		foreach ((array) $post_ids as $post_id) {
506
+			delete_post_meta($post_id, self::WARNING_META_KEY);
507 507
 		}
508 508
 
509 509
 	}
@@ -519,9 +519,9 @@  discard block
 block discarded – undo
519 519
 	 * @return int|bool Meta ID if the key didn't exist, true on successful update,
520 520
 	 *                  false on failure.
521 521
 	 */
522
-	private function set_warning( $post_id, $value ) {
522
+	private function set_warning($post_id, $value) {
523 523
 
524
-		return update_post_meta( $post_id, self::WARNING_META_KEY, ( true === $value ? 'yes' : 'no' ) );
524
+		return update_post_meta($post_id, self::WARNING_META_KEY, (true === $value ? 'yes' : 'no'));
525 525
 	}
526 526
 
527 527
 	/**
@@ -533,9 +533,9 @@  discard block
 block discarded – undo
533 533
 	 *
534 534
 	 * @return int|string The post state or an empty string if not set.
535 535
 	 */
536
-	public function get_state( $post_id ) {
536
+	public function get_state($post_id) {
537 537
 
538
-		return get_post_meta( $post_id, self::STATE_META_KEY, true );
538
+		return get_post_meta($post_id, self::STATE_META_KEY, true);
539 539
 	}
540 540
 
541 541
 	/**
@@ -549,23 +549,23 @@  discard block
 block discarded – undo
549 549
 	 * @return int|bool Meta ID if the key didn't exist, true on successful update,
550 550
 	 *                  false on failure.
551 551
 	 */
552
-	public function set_state( $post_id, $value ) {
552
+	public function set_state($post_id, $value) {
553 553
 
554 554
 		// Update the state.
555
-		$result = update_post_meta( $post_id, self::STATE_META_KEY, $value );
555
+		$result = update_post_meta($post_id, self::STATE_META_KEY, $value);
556 556
 
557 557
 		// Update timestamps as required.
558
-		switch ( $value ) {
558
+		switch ($value) {
559 559
 
560 560
 			// ### REQUEST state.
561 561
 			case self::STATE_REQUEST:
562
-				add_post_meta( $post_id, self::REQUEST_TIMESTAMP_META_KEY, current_time( 'mysql', true ) );
562
+				add_post_meta($post_id, self::REQUEST_TIMESTAMP_META_KEY, current_time('mysql', true));
563 563
 				break;
564 564
 
565 565
 			// ### SUCCESS/ERROR state.
566 566
 			case self::STATE_SUCCESS:
567 567
 			case self::STATE_ERROR:
568
-				add_post_meta( $post_id, self::COMPLETE_TIMESTAMP_META_KEY, current_time( 'mysql', true ) );
568
+				add_post_meta($post_id, self::COMPLETE_TIMESTAMP_META_KEY, current_time('mysql', true));
569 569
 				break;
570 570
 		}
571 571
 
@@ -584,11 +584,11 @@  discard block
 block discarded – undo
584 584
 	 *
585 585
 	 * @return string The link setting or `default` if not set.
586 586
 	 */
587
-	public function get_link( $post_id ) {
587
+	public function get_link($post_id) {
588 588
 
589
-		$values = get_post_meta( $post_id, self::LINK_META_KEY );
589
+		$values = get_post_meta($post_id, self::LINK_META_KEY);
590 590
 
591
-		return end( $values ) ?: 'default';
591
+		return end($values) ?: 'default';
592 592
 	}
593 593
 
594 594
 	/**
@@ -600,14 +600,14 @@  discard block
 block discarded – undo
600 600
 	 */
601 601
 	public function waiting_for_analysis() {
602 602
 
603
-		return get_posts( array(
604
-			'posts_per_page' => - 1,
603
+		return get_posts(array(
604
+			'posts_per_page' => -1,
605 605
 			'fields'         => 'ids',
606 606
 			'post_status'    => 'any',
607 607
 			'meta_key'       => self::STATE_META_KEY,
608 608
 			'meta_value'     => self::STATE_SUBMIT,
609 609
 			'orderby'        => 'ID',
610
-		) );
610
+		));
611 611
 	}
612 612
 
613 613
 	/**
@@ -620,14 +620,14 @@  discard block
 block discarded – undo
620 620
 	 */
621 621
 	public function waiting_for_response() {
622 622
 
623
-		return get_posts( array(
624
-			'posts_per_page' => - 1,
623
+		return get_posts(array(
624
+			'posts_per_page' => -1,
625 625
 			'fields'         => 'ids',
626 626
 			'post_status'    => 'any',
627 627
 			'meta_key'       => self::STATE_META_KEY,
628 628
 			'meta_value'     => self::STATE_REQUEST,
629 629
 			'orderby'        => 'ID',
630
-		) );
630
+		));
631 631
 	}
632 632
 
633 633
 	/**
@@ -639,22 +639,22 @@  discard block
 block discarded – undo
639 639
 	 *
640 640
 	 * @return WP_Error|array The response or WP_Error on failure.
641 641
 	 */
642
-	private function do_request( $post_id ) {
642
+	private function do_request($post_id) {
643 643
 
644 644
 		// Get the post.
645
-		$post = get_post( $post_id );
645
+		$post = get_post($post_id);
646 646
 
647 647
 		// Bail out if the post isn't found.
648
-		if ( null === $post ) {
649
-			$this->log->warn( "Post $post_id not found." );
648
+		if (null === $post) {
649
+			$this->log->warn("Post $post_id not found.");
650 650
 
651
-			return new WP_Error( 0, "Cannot find post $post_id." );
651
+			return new WP_Error(0, "Cannot find post $post_id.");
652 652
 		}
653 653
 
654 654
 		// Get the link setting.
655
-		$link = $this->get_link( $post_id );
655
+		$link = $this->get_link($post_id);
656 656
 
657
-		$this->log->debug( "Sending analysis request for post $post_id [ link :: $link ]..." );
657
+		$this->log->debug("Sending analysis request for post $post_id [ link :: $link ]...");
658 658
 
659 659
 		// Get the batch analysis URL.
660 660
 		$url = $this->configuration_service->get_batch_analysis_url();
@@ -671,7 +671,7 @@  discard block
 block discarded – undo
671 671
 		);
672 672
 
673 673
 		// Get the HTTP options.
674
-		$args = array_merge_recursive( unserialize( WL_REDLINK_API_HTTP_OPTIONS ), array(
674
+		$args = array_merge_recursive(unserialize(WL_REDLINK_API_HTTP_OPTIONS), array(
675 675
 			'method'      => 'POST',
676 676
 			'headers'     => array(
677 677
 				'Accept'       => 'application/json',
@@ -679,13 +679,13 @@  discard block
 block discarded – undo
679 679
 			),
680 680
 			// we need to downgrade the HTTP version in this case since chunked encoding is dumping numbers in the response.
681 681
 			'httpversion' => '1.0',
682
-			'body'        => wp_json_encode( $param ),
683
-		) );
682
+			'body'        => wp_json_encode($param),
683
+		));
684 684
 
685
-		$this->log->debug( "Posting analysis request for post $post_id to $url..." );
685
+		$this->log->debug("Posting analysis request for post $post_id to $url...");
686 686
 
687 687
 		// Post the parameter.
688
-		return wp_remote_post( $url, $args );
688
+		return wp_remote_post($url, $args);
689 689
 	}
690 690
 
691 691
 	/**
@@ -697,20 +697,20 @@  discard block
 block discarded – undo
697 697
 	 *
698 698
 	 * @return WP_Error|array The response or WP_Error on failure.
699 699
 	 */
700
-	private function do_complete( $post_id ) {
700
+	private function do_complete($post_id) {
701 701
 
702
-		$post = get_post( $post_id );
702
+		$post = get_post($post_id);
703 703
 
704
-		if ( null === $post ) {
704
+		if (null === $post) {
705 705
 			// Post was possibly deleted, just bailout.
706
-			return new WP_Error( 0, "Post $post_id not found." );
706
+			return new WP_Error(0, "Post $post_id not found.");
707 707
 		}
708 708
 
709 709
 		$url = $this->configuration_service->get_batch_analysis_url();
710 710
 		$key = $this->configuration_service->get_key();
711
-		$url = $url . '/' . $post->ID . '?key=' . $key;
711
+		$url = $url.'/'.$post->ID.'?key='.$key;
712 712
 
713
-		return wp_remote_get( $url, unserialize( WL_REDLINK_API_HTTP_OPTIONS ) );
713
+		return wp_remote_get($url, unserialize(WL_REDLINK_API_HTTP_OPTIONS));
714 714
 	}
715 715
 
716 716
 	/**
@@ -722,13 +722,13 @@  discard block
 block discarded – undo
722 722
 	 */
723 723
 	public function get_warnings() {
724 724
 
725
-		return get_posts( array(
725
+		return get_posts(array(
726 726
 			'fields'      => 'ids',
727
-			'numberposts' => - 1,
727
+			'numberposts' => -1,
728 728
 			'post_status' => 'any',
729 729
 			'meta_key'    => self::WARNING_META_KEY,
730 730
 			'meta_value'  => 'yes',
731
-		) );
731
+		));
732 732
 	}
733 733
 
734 734
 }
Please login to merge, or discard this patch.
wp-async-task/class-wordlift-batch-analysis-complete-async-task.php 2 patches
Indentation   +45 added lines, -45 removed lines patch added patch discarded remove patch
@@ -18,59 +18,59 @@
 block discarded – undo
18 18
  */
19 19
 class Wordlift_Batch_Analysis_Complete_Async_Task extends Wordlift_Async_Task {
20 20
 
21
-	/**
22
-	 * The protected $action property should be set to the action to which you
23
-	 * wish to attach the asynchronous task. For example, if you want to spin
24
-	 * off an asynchronous task whenever a post gets saved, you would set this
25
-	 * to save_post.
26
-	 *
27
-	 * @since  3.14.2
28
-	 * @access protected
29
-	 * @var string $action The action to which you wish to attach the
30
-	 *                     asynchronous task.
31
-	 */
32
-	protected $action = 'wl_batch_analysis_complete';
21
+    /**
22
+     * The protected $action property should be set to the action to which you
23
+     * wish to attach the asynchronous task. For example, if you want to spin
24
+     * off an asynchronous task whenever a post gets saved, you would set this
25
+     * to save_post.
26
+     *
27
+     * @since  3.14.2
28
+     * @access protected
29
+     * @var string $action The action to which you wish to attach the
30
+     *                     asynchronous task.
31
+     */
32
+    protected $action = 'wl_batch_analysis_complete';
33 33
 
34
-	/**
35
-	 * A {@link Wordlift_Log_Service} instance.
36
-	 *
37
-	 * @since  3.14.2
38
-	 * @access private
39
-	 * @var \Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
40
-	 */
41
-	private $log;
34
+    /**
35
+     * A {@link Wordlift_Log_Service} instance.
36
+     *
37
+     * @since  3.14.2
38
+     * @access private
39
+     * @var \Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
40
+     */
41
+    private $log;
42 42
 
43
-	/**
44
-	 * Create a {@link Wordlift_Sparql_Query_Async_Task} instance.
45
-	 *
46
-	 * @since 3.14.2
47
-	 *
48
-	 * @param int $auth_level The authentication level to use (see above)
49
-	 */
50
-	public function __construct( $auth_level = self::BOTH ) {
51
-		parent::__construct( $auth_level );
43
+    /**
44
+     * Create a {@link Wordlift_Sparql_Query_Async_Task} instance.
45
+     *
46
+     * @since 3.14.2
47
+     *
48
+     * @param int $auth_level The authentication level to use (see above)
49
+     */
50
+    public function __construct( $auth_level = self::BOTH ) {
51
+        parent::__construct( $auth_level );
52 52
 
53
-		$this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Batch_Analysis_Complete_Async_Task' );
53
+        $this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Batch_Analysis_Complete_Async_Task' );
54 54
 
55
-	}
55
+    }
56 56
 
57
-	/**
58
-	 * @inheritdoc
59
-	 */
60
-	protected function prepare_data( $data ) {
57
+    /**
58
+     * @inheritdoc
59
+     */
60
+    protected function prepare_data( $data ) {
61 61
 
62
-		// Return the link setting.
63
-		return array();
64
-	}
62
+        // Return the link setting.
63
+        return array();
64
+    }
65 65
 
66
-	/**
67
-	 * @inheritdoc
68
-	 */
69
-	protected function run_action() {
66
+    /**
67
+     * @inheritdoc
68
+     */
69
+    protected function run_action() {
70 70
 
71
-		// Run the asynchronous action.
72
-		do_action( "wl_async_$this->action" );
71
+        // Run the asynchronous action.
72
+        do_action( "wl_async_$this->action" );
73 73
 
74
-	}
74
+    }
75 75
 
76 76
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -47,17 +47,17 @@  discard block
 block discarded – undo
47 47
 	 *
48 48
 	 * @param int $auth_level The authentication level to use (see above)
49 49
 	 */
50
-	public function __construct( $auth_level = self::BOTH ) {
51
-		parent::__construct( $auth_level );
50
+	public function __construct($auth_level = self::BOTH) {
51
+		parent::__construct($auth_level);
52 52
 
53
-		$this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Batch_Analysis_Complete_Async_Task' );
53
+		$this->log = Wordlift_Log_Service::get_logger('Wordlift_Batch_Analysis_Complete_Async_Task');
54 54
 
55 55
 	}
56 56
 
57 57
 	/**
58 58
 	 * @inheritdoc
59 59
 	 */
60
-	protected function prepare_data( $data ) {
60
+	protected function prepare_data($data) {
61 61
 
62 62
 		// Return the link setting.
63 63
 		return array();
@@ -69,7 +69,7 @@  discard block
 block discarded – undo
69 69
 	protected function run_action() {
70 70
 
71 71
 		// Run the asynchronous action.
72
-		do_action( "wl_async_$this->action" );
72
+		do_action("wl_async_$this->action");
73 73
 
74 74
 	}
75 75
 
Please login to merge, or discard this patch.
src/includes/wp-async-task/class-wordlift-sparql-query-async-task.php 2 patches
Indentation   +51 added lines, -51 removed lines patch added patch discarded remove patch
@@ -18,68 +18,68 @@
 block discarded – undo
18 18
  */
19 19
 class Wordlift_Sparql_Query_Async_Task extends Wordlift_Async_Task {
20 20
 
21
-	/**
22
-	 * The protected $action property should be set to the action to which you
23
-	 * wish to attach the asynchronous task. For example, if you want to spin
24
-	 * off an asynchronous task whenever a post gets saved, you would set this
25
-	 * to save_post.
26
-	 *
27
-	 * @since  3.13.2
28
-	 * @access protected
29
-	 * @var string $action The action to which you wish to attach the
30
-	 *                     asynchronous task.
31
-	 */
32
-	protected $action = 'wl_run_sparql_query';
21
+    /**
22
+     * The protected $action property should be set to the action to which you
23
+     * wish to attach the asynchronous task. For example, if you want to spin
24
+     * off an asynchronous task whenever a post gets saved, you would set this
25
+     * to save_post.
26
+     *
27
+     * @since  3.13.2
28
+     * @access protected
29
+     * @var string $action The action to which you wish to attach the
30
+     *                     asynchronous task.
31
+     */
32
+    protected $action = 'wl_run_sparql_query';
33 33
 
34
-	/**
35
-	 * A {@link Wordlift_Log_Service} instance.
36
-	 *
37
-	 * @since  3.13.2
38
-	 * @access private
39
-	 * @var \Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
40
-	 */
41
-	private $log;
34
+    /**
35
+     * A {@link Wordlift_Log_Service} instance.
36
+     *
37
+     * @since  3.13.2
38
+     * @access private
39
+     * @var \Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
40
+     */
41
+    private $log;
42 42
 
43
-	/**
44
-	 * Create a {@link Wordlift_Sparql_Query_Async_Task} instance.
45
-	 *
46
-	 * @since 3.13.2
47
-	 *
48
-	 * @param int $auth_level The authentication level to use (see above)
49
-	 */
50
-	public function __construct( $auth_level = self::BOTH ) {
51
-		parent::__construct( $auth_level );
43
+    /**
44
+     * Create a {@link Wordlift_Sparql_Query_Async_Task} instance.
45
+     *
46
+     * @since 3.13.2
47
+     *
48
+     * @param int $auth_level The authentication level to use (see above)
49
+     */
50
+    public function __construct( $auth_level = self::BOTH ) {
51
+        parent::__construct( $auth_level );
52 52
 
53
-		$this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Sparql_Query_Async_Task' );
53
+        $this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Sparql_Query_Async_Task' );
54 54
 
55
-	}
55
+    }
56 56
 
57 57
 
58
-	/**
59
-	 * @inheritdoc
60
-	 */
61
-	protected function prepare_data( $data ) {
58
+    /**
59
+     * @inheritdoc
60
+     */
61
+    protected function prepare_data( $data ) {
62 62
 
63
-		// Return the request id, which is used to get the sparql queries stored
64
-		// in the temporary files.
65
-		return array( 'request_id' => $data[0] );
66
-	}
63
+        // Return the request id, which is used to get the sparql queries stored
64
+        // in the temporary files.
65
+        return array( 'request_id' => $data[0] );
66
+    }
67 67
 
68
-	/**
69
-	 * @inheritdoc
70
-	 */
71
-	protected function run_action() {
68
+    /**
69
+     * @inheritdoc
70
+     */
71
+    protected function run_action() {
72 72
 
73
-		// Bail out if there's no request id.
74
-		if ( ! isset( $_POST['request_id'] ) ) {
75
-			$this->log->warn( 'Request Id not found.' );
73
+        // Bail out if there's no request id.
74
+        if ( ! isset( $_POST['request_id'] ) ) {
75
+            $this->log->warn( 'Request Id not found.' );
76 76
 
77
-			return;
78
-		}
77
+            return;
78
+        }
79 79
 
80
-		// Run the asynchronous action.
81
-		do_action( "wl_async_$this->action", $_POST['request_id'] );
80
+        // Run the asynchronous action.
81
+        do_action( "wl_async_$this->action", $_POST['request_id'] );
82 82
 
83
-	}
83
+    }
84 84
 
85 85
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -47,10 +47,10 @@  discard block
 block discarded – undo
47 47
 	 *
48 48
 	 * @param int $auth_level The authentication level to use (see above)
49 49
 	 */
50
-	public function __construct( $auth_level = self::BOTH ) {
51
-		parent::__construct( $auth_level );
50
+	public function __construct($auth_level = self::BOTH) {
51
+		parent::__construct($auth_level);
52 52
 
53
-		$this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Sparql_Query_Async_Task' );
53
+		$this->log = Wordlift_Log_Service::get_logger('Wordlift_Sparql_Query_Async_Task');
54 54
 
55 55
 	}
56 56
 
@@ -58,11 +58,11 @@  discard block
 block discarded – undo
58 58
 	/**
59 59
 	 * @inheritdoc
60 60
 	 */
61
-	protected function prepare_data( $data ) {
61
+	protected function prepare_data($data) {
62 62
 
63 63
 		// Return the request id, which is used to get the sparql queries stored
64 64
 		// in the temporary files.
65
-		return array( 'request_id' => $data[0] );
65
+		return array('request_id' => $data[0]);
66 66
 	}
67 67
 
68 68
 	/**
@@ -71,14 +71,14 @@  discard block
 block discarded – undo
71 71
 	protected function run_action() {
72 72
 
73 73
 		// Bail out if there's no request id.
74
-		if ( ! isset( $_POST['request_id'] ) ) {
75
-			$this->log->warn( 'Request Id not found.' );
74
+		if ( ! isset($_POST['request_id'])) {
75
+			$this->log->warn('Request Id not found.');
76 76
 
77 77
 			return;
78 78
 		}
79 79
 
80 80
 		// Run the asynchronous action.
81
-		do_action( "wl_async_$this->action", $_POST['request_id'] );
81
+		do_action("wl_async_$this->action", $_POST['request_id']);
82 82
 
83 83
 	}
84 84
 
Please login to merge, or discard this patch.
src/includes/wp-async-task/class-wordlift-async-task.php 2 patches
Indentation   +286 added lines, -286 removed lines patch added patch discarded remove patch
@@ -9,292 +9,292 @@
 block discarded – undo
9 9
 
10 10
 abstract class Wordlift_Async_Task {
11 11
 
12
-	/**
13
-	 * Constant identifier for a task that should be available to logged-in users
14
-	 *
15
-	 * See constructor documentation for more details.
16
-	 */
17
-	const LOGGED_IN = 1;
18
-
19
-	/**
20
-	 * Constant identifier for a task that should be available to logged-out users
21
-	 *
22
-	 * See constructor documentation for more details.
23
-	 */
24
-	const LOGGED_OUT = 2;
25
-
26
-	/**
27
-	 * Constant identifier for a task that should be available to all users regardless of auth status
28
-	 *
29
-	 * See constructor documentation for more details.
30
-	 */
31
-	const BOTH = 3;
32
-
33
-	/**
34
-	 * This is the argument count for the main action set in the constructor. It
35
-	 * is set to an arbitrarily high value of twenty, but can be overridden if
36
-	 * necessary
37
-	 *
38
-	 * @var int
39
-	 */
40
-	protected $argument_count = 20;
41
-
42
-	/**
43
-	 * Priority to fire intermediate action.
44
-	 *
45
-	 * @var int
46
-	 */
47
-	protected $priority = 10;
48
-
49
-	/**
50
-	 * @var string
51
-	 */
52
-	protected $action;
53
-
54
-	/**
55
-	 * @var array
56
-	 */
57
-	protected $_body_data;
58
-
59
-	/**
60
-	 * A {@link Wordlift_Log_Service} instance.
61
-	 *
62
-	 * @since  3.15.0
63
-	 * @access private
64
-	 * @var \Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
65
-	 */
66
-	private $log;
67
-
68
-	/**
69
-	 * Constructor to wire up the necessary actions
70
-	 *
71
-	 * Which hooks the asynchronous postback happens on can be set by the
72
-	 * $auth_level parameter. There are essentially three options: logged in users
73
-	 * only, logged out users only, or both. Set this when you instantiate an
74
-	 * object by using one of the three class constants to do so:
75
-	 *  - LOGGED_IN
76
-	 *  - LOGGED_OUT
77
-	 *  - BOTH
78
-	 * $auth_level defaults to BOTH
79
-	 *
80
-	 * @throws Exception If the class' $action value hasn't been set
81
-	 *
82
-	 * @param int $auth_level The authentication level to use (see above)
83
-	 */
84
-	public function __construct( $auth_level = self::BOTH ) {
85
-
86
-		$this->log = Wordlift_Log_Service::get_logger( get_class() );
87
-
88
-		if ( empty( $this->action ) ) {
89
-			throw new Exception( 'Action not defined for class ' . __CLASS__ );
90
-		}
91
-		add_action( $this->action, array(
92
-			$this,
93
-			'launch',
94
-		), (int) $this->priority, (int) $this->argument_count );
95
-		if ( $auth_level & self::LOGGED_IN ) {
96
-			add_action( "admin_post_wl_async_$this->action", array(
97
-				$this,
98
-				'handle_postback',
99
-			) );
100
-		}
101
-		if ( $auth_level & self::LOGGED_OUT ) {
102
-			add_action( "admin_post_nopriv_wl_async_$this->action", array(
103
-				$this,
104
-				'handle_postback',
105
-			) );
106
-		}
107
-	}
108
-
109
-	/**
110
-	 * Add the shutdown action for launching the real postback if we don't
111
-	 * get an exception thrown by prepare_data().
112
-	 *
113
-	 * @uses func_get_args() To grab any arguments passed by the action
114
-	 */
115
-	public function launch() {
116
-		$data = func_get_args();
117
-		try {
118
-			$data = $this->prepare_data( $data );
119
-		} catch ( Exception $e ) {
120
-			return;
121
-		}
122
-
123
-		$data['action'] = "wl_async_$this->action";
124
-		$data['_nonce'] = $this->create_async_nonce();
125
-
126
-		$this->_body_data = $data;
127
-
128
-		if ( ! has_action( 'shutdown', array(
129
-			$this,
130
-			'launch_on_shutdown',
131
-		) )
132
-		) {
133
-			add_action( 'shutdown', array( $this, 'launch_on_shutdown' ) );
134
-		}
135
-	}
136
-
137
-	/**
138
-	 * Launch the request on the WordPress shutdown hook
139
-	 *
140
-	 * On VIP we got into data races due to the postback sometimes completing
141
-	 * faster than the data could propogate to the database server cluster.
142
-	 * This made WordPress get empty data sets from the database without
143
-	 * failing. On their advice, we're moving the actual firing of the async
144
-	 * postback to the shutdown hook. Supposedly that will ensure that the
145
-	 * data at least has time to get into the object cache.
146
-	 *
147
-	 * @uses $_COOKIE        To send a cookie header for async postback
148
-	 * @uses apply_filters()
149
-	 * @uses admin_url()
150
-	 * @uses wp_remote_post()
151
-	 */
152
-	public function launch_on_shutdown() {
153
-
154
-		$this->log->debug( 'Launching Async Task...' );
155
-
156
-		if ( ! empty( $this->_body_data ) ) {
157
-			$cookies = array();
158
-			foreach ( $_COOKIE as $name => $value ) {
159
-				$cookies[] = "$name=" . urlencode( is_array( $value ) ? serialize( $value ) : $value );
160
-			}
161
-
162
-			$request_args = array(
163
-				'timeout'   => 0.01,
164
-				'blocking'  => false,
165
-				'sslverify' => apply_filters( 'https_local_ssl_verify', false ),
166
-				'body'      => $this->_body_data,
167
-				'headers'   => array(
168
-					'cookie' => implode( '; ', $cookies ),
169
-				),
170
-			);
171
-
172
-			$url = get_site_url( null, 'wl-api' );
173
-
174
-			$this->log->debug( "Posting URL $url..." );
175
-
176
-			$result = wp_remote_post( $url, $request_args );
177
-
178
-			if ( is_wp_error( $result ) ) {
179
-				$this->log->error( 'Posting URL returned an error: ' . $result->get_error_message() );
180
-			}
181
-		}
182
-	}
183
-
184
-	/**
185
-	 * Verify the postback is valid, then fire any scheduled events.
186
-	 *
187
-	 * @uses $_POST['_nonce']
188
-	 * @uses is_user_logged_in()
189
-	 * @uses add_filter()
190
-	 * @uses wp_die()
191
-	 */
192
-	public function handle_postback() {
193
-		if ( isset( $_POST['_nonce'] ) && $this->verify_async_nonce( $_POST['_nonce'] ) ) {
194
-			if ( ! is_user_logged_in() ) {
195
-				$this->action = "nopriv_$this->action";
196
-			}
197
-			$this->run_action();
198
-		}
199
-
200
-		add_filter( 'wp_die_handler', function () {
201
-			die();
202
-		} );
203
-		wp_die();
204
-	}
205
-
206
-	/**
207
-	 * Create a random, one time use token.
208
-	 *
209
-	 * Based entirely on wp_create_nonce() but does not tie the nonce to the
210
-	 * current logged-in user.
211
-	 *
212
-	 * @uses wp_nonce_tick()
213
-	 * @uses wp_hash()
214
-	 *
215
-	 * @return string The one-time use token
216
-	 */
217
-	protected function create_async_nonce() {
218
-		$action = $this->get_nonce_action();
219
-		$i      = wp_nonce_tick();
220
-
221
-		return substr( wp_hash( $i . $action . get_class( $this ), 'nonce' ), - 12, 10 );
222
-	}
223
-
224
-	/**
225
-	 * Verify that the correct nonce was used within the time limit.
226
-	 *
227
-	 * @uses wp_nonce_tick()
228
-	 * @uses wp_hash()
229
-	 *
230
-	 * @param string $nonce Nonce to be verified
231
-	 *
232
-	 * @return bool Whether the nonce check passed or failed
233
-	 */
234
-	protected function verify_async_nonce( $nonce ) {
235
-		$action = $this->get_nonce_action();
236
-		$i      = wp_nonce_tick();
237
-
238
-		// Nonce generated 0-12 hours ago
239
-		if ( substr( wp_hash( $i . $action . get_class( $this ), 'nonce' ), - 12, 10 ) == $nonce ) {
240
-			return 1;
241
-		}
242
-
243
-		// Nonce generated 12-24 hours ago
244
-		if ( substr( wp_hash( ( $i - 1 ) . $action . get_class( $this ), 'nonce' ), - 12, 10 ) == $nonce ) {
245
-			return 2;
246
-		}
247
-
248
-		// Invalid nonce
249
-		return false;
250
-	}
251
-
252
-	/**
253
-	 * Get a nonce action based on the $action property of the class
254
-	 *
255
-	 * @return string The nonce action for the current instance
256
-	 */
257
-	protected function get_nonce_action() {
258
-		$action = $this->action;
259
-		if ( substr( $action, 0, 7 ) === 'nopriv_' ) {
260
-			$action = substr( $action, 7 );
261
-		}
262
-		$action = "wl_async_$action";
263
-
264
-		return $action;
265
-	}
266
-
267
-	/**
268
-	 * Prepare any data to be passed to the asynchronous postback
269
-	 *
270
-	 * The array this function receives will be a numerically keyed array from
271
-	 * func_get_args(). It is expected that you will return an associative array
272
-	 * so that the $_POST values used in the asynchronous call will make sense.
273
-	 *
274
-	 * The array you send back may or may not have anything to do with the data
275
-	 * passed into this method. It all depends on the implementation details and
276
-	 * what data is needed in the asynchronous postback.
277
-	 *
278
-	 * Do not set values for 'action' or '_nonce', as those will get overwritten
279
-	 * later in launch().
280
-	 *
281
-	 * @throws Exception If the postback should not occur for any reason
282
-	 *
283
-	 * @param array $data The raw data received by the launch method
284
-	 *
285
-	 * @return array The prepared data
286
-	 */
287
-	abstract protected function prepare_data( $data );
288
-
289
-	/**
290
-	 * Run the do_action function for the asynchronous postback.
291
-	 *
292
-	 * This method needs to fetch and sanitize any and all data from the $_POST
293
-	 * superglobal and provide them to the do_action call.
294
-	 *
295
-	 * The action should be constructed as "wl_async_task_$this->action"
296
-	 */
297
-	abstract protected function run_action();
12
+    /**
13
+     * Constant identifier for a task that should be available to logged-in users
14
+     *
15
+     * See constructor documentation for more details.
16
+     */
17
+    const LOGGED_IN = 1;
18
+
19
+    /**
20
+     * Constant identifier for a task that should be available to logged-out users
21
+     *
22
+     * See constructor documentation for more details.
23
+     */
24
+    const LOGGED_OUT = 2;
25
+
26
+    /**
27
+     * Constant identifier for a task that should be available to all users regardless of auth status
28
+     *
29
+     * See constructor documentation for more details.
30
+     */
31
+    const BOTH = 3;
32
+
33
+    /**
34
+     * This is the argument count for the main action set in the constructor. It
35
+     * is set to an arbitrarily high value of twenty, but can be overridden if
36
+     * necessary
37
+     *
38
+     * @var int
39
+     */
40
+    protected $argument_count = 20;
41
+
42
+    /**
43
+     * Priority to fire intermediate action.
44
+     *
45
+     * @var int
46
+     */
47
+    protected $priority = 10;
48
+
49
+    /**
50
+     * @var string
51
+     */
52
+    protected $action;
53
+
54
+    /**
55
+     * @var array
56
+     */
57
+    protected $_body_data;
58
+
59
+    /**
60
+     * A {@link Wordlift_Log_Service} instance.
61
+     *
62
+     * @since  3.15.0
63
+     * @access private
64
+     * @var \Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
65
+     */
66
+    private $log;
67
+
68
+    /**
69
+     * Constructor to wire up the necessary actions
70
+     *
71
+     * Which hooks the asynchronous postback happens on can be set by the
72
+     * $auth_level parameter. There are essentially three options: logged in users
73
+     * only, logged out users only, or both. Set this when you instantiate an
74
+     * object by using one of the three class constants to do so:
75
+     *  - LOGGED_IN
76
+     *  - LOGGED_OUT
77
+     *  - BOTH
78
+     * $auth_level defaults to BOTH
79
+     *
80
+     * @throws Exception If the class' $action value hasn't been set
81
+     *
82
+     * @param int $auth_level The authentication level to use (see above)
83
+     */
84
+    public function __construct( $auth_level = self::BOTH ) {
85
+
86
+        $this->log = Wordlift_Log_Service::get_logger( get_class() );
87
+
88
+        if ( empty( $this->action ) ) {
89
+            throw new Exception( 'Action not defined for class ' . __CLASS__ );
90
+        }
91
+        add_action( $this->action, array(
92
+            $this,
93
+            'launch',
94
+        ), (int) $this->priority, (int) $this->argument_count );
95
+        if ( $auth_level & self::LOGGED_IN ) {
96
+            add_action( "admin_post_wl_async_$this->action", array(
97
+                $this,
98
+                'handle_postback',
99
+            ) );
100
+        }
101
+        if ( $auth_level & self::LOGGED_OUT ) {
102
+            add_action( "admin_post_nopriv_wl_async_$this->action", array(
103
+                $this,
104
+                'handle_postback',
105
+            ) );
106
+        }
107
+    }
108
+
109
+    /**
110
+     * Add the shutdown action for launching the real postback if we don't
111
+     * get an exception thrown by prepare_data().
112
+     *
113
+     * @uses func_get_args() To grab any arguments passed by the action
114
+     */
115
+    public function launch() {
116
+        $data = func_get_args();
117
+        try {
118
+            $data = $this->prepare_data( $data );
119
+        } catch ( Exception $e ) {
120
+            return;
121
+        }
122
+
123
+        $data['action'] = "wl_async_$this->action";
124
+        $data['_nonce'] = $this->create_async_nonce();
125
+
126
+        $this->_body_data = $data;
127
+
128
+        if ( ! has_action( 'shutdown', array(
129
+            $this,
130
+            'launch_on_shutdown',
131
+        ) )
132
+        ) {
133
+            add_action( 'shutdown', array( $this, 'launch_on_shutdown' ) );
134
+        }
135
+    }
136
+
137
+    /**
138
+     * Launch the request on the WordPress shutdown hook
139
+     *
140
+     * On VIP we got into data races due to the postback sometimes completing
141
+     * faster than the data could propogate to the database server cluster.
142
+     * This made WordPress get empty data sets from the database without
143
+     * failing. On their advice, we're moving the actual firing of the async
144
+     * postback to the shutdown hook. Supposedly that will ensure that the
145
+     * data at least has time to get into the object cache.
146
+     *
147
+     * @uses $_COOKIE        To send a cookie header for async postback
148
+     * @uses apply_filters()
149
+     * @uses admin_url()
150
+     * @uses wp_remote_post()
151
+     */
152
+    public function launch_on_shutdown() {
153
+
154
+        $this->log->debug( 'Launching Async Task...' );
155
+
156
+        if ( ! empty( $this->_body_data ) ) {
157
+            $cookies = array();
158
+            foreach ( $_COOKIE as $name => $value ) {
159
+                $cookies[] = "$name=" . urlencode( is_array( $value ) ? serialize( $value ) : $value );
160
+            }
161
+
162
+            $request_args = array(
163
+                'timeout'   => 0.01,
164
+                'blocking'  => false,
165
+                'sslverify' => apply_filters( 'https_local_ssl_verify', false ),
166
+                'body'      => $this->_body_data,
167
+                'headers'   => array(
168
+                    'cookie' => implode( '; ', $cookies ),
169
+                ),
170
+            );
171
+
172
+            $url = get_site_url( null, 'wl-api' );
173
+
174
+            $this->log->debug( "Posting URL $url..." );
175
+
176
+            $result = wp_remote_post( $url, $request_args );
177
+
178
+            if ( is_wp_error( $result ) ) {
179
+                $this->log->error( 'Posting URL returned an error: ' . $result->get_error_message() );
180
+            }
181
+        }
182
+    }
183
+
184
+    /**
185
+     * Verify the postback is valid, then fire any scheduled events.
186
+     *
187
+     * @uses $_POST['_nonce']
188
+     * @uses is_user_logged_in()
189
+     * @uses add_filter()
190
+     * @uses wp_die()
191
+     */
192
+    public function handle_postback() {
193
+        if ( isset( $_POST['_nonce'] ) && $this->verify_async_nonce( $_POST['_nonce'] ) ) {
194
+            if ( ! is_user_logged_in() ) {
195
+                $this->action = "nopriv_$this->action";
196
+            }
197
+            $this->run_action();
198
+        }
199
+
200
+        add_filter( 'wp_die_handler', function () {
201
+            die();
202
+        } );
203
+        wp_die();
204
+    }
205
+
206
+    /**
207
+     * Create a random, one time use token.
208
+     *
209
+     * Based entirely on wp_create_nonce() but does not tie the nonce to the
210
+     * current logged-in user.
211
+     *
212
+     * @uses wp_nonce_tick()
213
+     * @uses wp_hash()
214
+     *
215
+     * @return string The one-time use token
216
+     */
217
+    protected function create_async_nonce() {
218
+        $action = $this->get_nonce_action();
219
+        $i      = wp_nonce_tick();
220
+
221
+        return substr( wp_hash( $i . $action . get_class( $this ), 'nonce' ), - 12, 10 );
222
+    }
223
+
224
+    /**
225
+     * Verify that the correct nonce was used within the time limit.
226
+     *
227
+     * @uses wp_nonce_tick()
228
+     * @uses wp_hash()
229
+     *
230
+     * @param string $nonce Nonce to be verified
231
+     *
232
+     * @return bool Whether the nonce check passed or failed
233
+     */
234
+    protected function verify_async_nonce( $nonce ) {
235
+        $action = $this->get_nonce_action();
236
+        $i      = wp_nonce_tick();
237
+
238
+        // Nonce generated 0-12 hours ago
239
+        if ( substr( wp_hash( $i . $action . get_class( $this ), 'nonce' ), - 12, 10 ) == $nonce ) {
240
+            return 1;
241
+        }
242
+
243
+        // Nonce generated 12-24 hours ago
244
+        if ( substr( wp_hash( ( $i - 1 ) . $action . get_class( $this ), 'nonce' ), - 12, 10 ) == $nonce ) {
245
+            return 2;
246
+        }
247
+
248
+        // Invalid nonce
249
+        return false;
250
+    }
251
+
252
+    /**
253
+     * Get a nonce action based on the $action property of the class
254
+     *
255
+     * @return string The nonce action for the current instance
256
+     */
257
+    protected function get_nonce_action() {
258
+        $action = $this->action;
259
+        if ( substr( $action, 0, 7 ) === 'nopriv_' ) {
260
+            $action = substr( $action, 7 );
261
+        }
262
+        $action = "wl_async_$action";
263
+
264
+        return $action;
265
+    }
266
+
267
+    /**
268
+     * Prepare any data to be passed to the asynchronous postback
269
+     *
270
+     * The array this function receives will be a numerically keyed array from
271
+     * func_get_args(). It is expected that you will return an associative array
272
+     * so that the $_POST values used in the asynchronous call will make sense.
273
+     *
274
+     * The array you send back may or may not have anything to do with the data
275
+     * passed into this method. It all depends on the implementation details and
276
+     * what data is needed in the asynchronous postback.
277
+     *
278
+     * Do not set values for 'action' or '_nonce', as those will get overwritten
279
+     * later in launch().
280
+     *
281
+     * @throws Exception If the postback should not occur for any reason
282
+     *
283
+     * @param array $data The raw data received by the launch method
284
+     *
285
+     * @return array The prepared data
286
+     */
287
+    abstract protected function prepare_data( $data );
288
+
289
+    /**
290
+     * Run the do_action function for the asynchronous postback.
291
+     *
292
+     * This method needs to fetch and sanitize any and all data from the $_POST
293
+     * superglobal and provide them to the do_action call.
294
+     *
295
+     * The action should be constructed as "wl_async_task_$this->action"
296
+     */
297
+    abstract protected function run_action();
298 298
 
299 299
 }
300 300
 
Please login to merge, or discard this patch.
Spacing   +38 added lines, -38 removed lines patch added patch discarded remove patch
@@ -81,28 +81,28 @@  discard block
 block discarded – undo
81 81
 	 *
82 82
 	 * @param int $auth_level The authentication level to use (see above)
83 83
 	 */
84
-	public function __construct( $auth_level = self::BOTH ) {
84
+	public function __construct($auth_level = self::BOTH) {
85 85
 
86
-		$this->log = Wordlift_Log_Service::get_logger( get_class() );
86
+		$this->log = Wordlift_Log_Service::get_logger(get_class());
87 87
 
88
-		if ( empty( $this->action ) ) {
89
-			throw new Exception( 'Action not defined for class ' . __CLASS__ );
88
+		if (empty($this->action)) {
89
+			throw new Exception('Action not defined for class '.__CLASS__);
90 90
 		}
91
-		add_action( $this->action, array(
91
+		add_action($this->action, array(
92 92
 			$this,
93 93
 			'launch',
94
-		), (int) $this->priority, (int) $this->argument_count );
95
-		if ( $auth_level & self::LOGGED_IN ) {
96
-			add_action( "admin_post_wl_async_$this->action", array(
94
+		), (int) $this->priority, (int) $this->argument_count);
95
+		if ($auth_level & self::LOGGED_IN) {
96
+			add_action("admin_post_wl_async_$this->action", array(
97 97
 				$this,
98 98
 				'handle_postback',
99
-			) );
99
+			));
100 100
 		}
101
-		if ( $auth_level & self::LOGGED_OUT ) {
102
-			add_action( "admin_post_nopriv_wl_async_$this->action", array(
101
+		if ($auth_level & self::LOGGED_OUT) {
102
+			add_action("admin_post_nopriv_wl_async_$this->action", array(
103 103
 				$this,
104 104
 				'handle_postback',
105
-			) );
105
+			));
106 106
 		}
107 107
 	}
108 108
 
@@ -115,8 +115,8 @@  discard block
 block discarded – undo
115 115
 	public function launch() {
116 116
 		$data = func_get_args();
117 117
 		try {
118
-			$data = $this->prepare_data( $data );
119
-		} catch ( Exception $e ) {
118
+			$data = $this->prepare_data($data);
119
+		} catch (Exception $e) {
120 120
 			return;
121 121
 		}
122 122
 
@@ -125,12 +125,12 @@  discard block
 block discarded – undo
125 125
 
126 126
 		$this->_body_data = $data;
127 127
 
128
-		if ( ! has_action( 'shutdown', array(
128
+		if ( ! has_action('shutdown', array(
129 129
 			$this,
130 130
 			'launch_on_shutdown',
131
-		) )
131
+		))
132 132
 		) {
133
-			add_action( 'shutdown', array( $this, 'launch_on_shutdown' ) );
133
+			add_action('shutdown', array($this, 'launch_on_shutdown'));
134 134
 		}
135 135
 	}
136 136
 
@@ -151,32 +151,32 @@  discard block
 block discarded – undo
151 151
 	 */
152 152
 	public function launch_on_shutdown() {
153 153
 
154
-		$this->log->debug( 'Launching Async Task...' );
154
+		$this->log->debug('Launching Async Task...');
155 155
 
156
-		if ( ! empty( $this->_body_data ) ) {
156
+		if ( ! empty($this->_body_data)) {
157 157
 			$cookies = array();
158
-			foreach ( $_COOKIE as $name => $value ) {
159
-				$cookies[] = "$name=" . urlencode( is_array( $value ) ? serialize( $value ) : $value );
158
+			foreach ($_COOKIE as $name => $value) {
159
+				$cookies[] = "$name=".urlencode(is_array($value) ? serialize($value) : $value);
160 160
 			}
161 161
 
162 162
 			$request_args = array(
163 163
 				'timeout'   => 0.01,
164 164
 				'blocking'  => false,
165
-				'sslverify' => apply_filters( 'https_local_ssl_verify', false ),
165
+				'sslverify' => apply_filters('https_local_ssl_verify', false),
166 166
 				'body'      => $this->_body_data,
167 167
 				'headers'   => array(
168
-					'cookie' => implode( '; ', $cookies ),
168
+					'cookie' => implode('; ', $cookies),
169 169
 				),
170 170
 			);
171 171
 
172
-			$url = get_site_url( null, 'wl-api' );
172
+			$url = get_site_url(null, 'wl-api');
173 173
 
174
-			$this->log->debug( "Posting URL $url..." );
174
+			$this->log->debug("Posting URL $url...");
175 175
 
176
-			$result = wp_remote_post( $url, $request_args );
176
+			$result = wp_remote_post($url, $request_args);
177 177
 
178
-			if ( is_wp_error( $result ) ) {
179
-				$this->log->error( 'Posting URL returned an error: ' . $result->get_error_message() );
178
+			if (is_wp_error($result)) {
179
+				$this->log->error('Posting URL returned an error: '.$result->get_error_message());
180 180
 			}
181 181
 		}
182 182
 	}
@@ -190,14 +190,14 @@  discard block
 block discarded – undo
190 190
 	 * @uses wp_die()
191 191
 	 */
192 192
 	public function handle_postback() {
193
-		if ( isset( $_POST['_nonce'] ) && $this->verify_async_nonce( $_POST['_nonce'] ) ) {
194
-			if ( ! is_user_logged_in() ) {
193
+		if (isset($_POST['_nonce']) && $this->verify_async_nonce($_POST['_nonce'])) {
194
+			if ( ! is_user_logged_in()) {
195 195
 				$this->action = "nopriv_$this->action";
196 196
 			}
197 197
 			$this->run_action();
198 198
 		}
199 199
 
200
-		add_filter( 'wp_die_handler', function () {
200
+		add_filter('wp_die_handler', function() {
201 201
 			die();
202 202
 		} );
203 203
 		wp_die();
@@ -218,7 +218,7 @@  discard block
 block discarded – undo
218 218
 		$action = $this->get_nonce_action();
219 219
 		$i      = wp_nonce_tick();
220 220
 
221
-		return substr( wp_hash( $i . $action . get_class( $this ), 'nonce' ), - 12, 10 );
221
+		return substr(wp_hash($i.$action.get_class($this), 'nonce'), - 12, 10);
222 222
 	}
223 223
 
224 224
 	/**
@@ -231,17 +231,17 @@  discard block
 block discarded – undo
231 231
 	 *
232 232
 	 * @return bool Whether the nonce check passed or failed
233 233
 	 */
234
-	protected function verify_async_nonce( $nonce ) {
234
+	protected function verify_async_nonce($nonce) {
235 235
 		$action = $this->get_nonce_action();
236 236
 		$i      = wp_nonce_tick();
237 237
 
238 238
 		// Nonce generated 0-12 hours ago
239
-		if ( substr( wp_hash( $i . $action . get_class( $this ), 'nonce' ), - 12, 10 ) == $nonce ) {
239
+		if (substr(wp_hash($i.$action.get_class($this), 'nonce'), - 12, 10) == $nonce) {
240 240
 			return 1;
241 241
 		}
242 242
 
243 243
 		// Nonce generated 12-24 hours ago
244
-		if ( substr( wp_hash( ( $i - 1 ) . $action . get_class( $this ), 'nonce' ), - 12, 10 ) == $nonce ) {
244
+		if (substr(wp_hash(($i - 1).$action.get_class($this), 'nonce'), - 12, 10) == $nonce) {
245 245
 			return 2;
246 246
 		}
247 247
 
@@ -256,8 +256,8 @@  discard block
 block discarded – undo
256 256
 	 */
257 257
 	protected function get_nonce_action() {
258 258
 		$action = $this->action;
259
-		if ( substr( $action, 0, 7 ) === 'nopriv_' ) {
260
-			$action = substr( $action, 7 );
259
+		if (substr($action, 0, 7) === 'nopriv_') {
260
+			$action = substr($action, 7);
261 261
 		}
262 262
 		$action = "wl_async_$action";
263 263
 
@@ -284,7 +284,7 @@  discard block
 block discarded – undo
284 284
 	 *
285 285
 	 * @return array The prepared data
286 286
 	 */
287
-	abstract protected function prepare_data( $data );
287
+	abstract protected function prepare_data($data);
288 288
 
289 289
 	/**
290 290
 	 * Run the do_action function for the asynchronous postback.
Please login to merge, or discard this patch.
includes/wp-async-task/class-wordlift-batch-analysis-request-async-task.php 2 patches
Indentation   +45 added lines, -45 removed lines patch added patch discarded remove patch
@@ -18,59 +18,59 @@
 block discarded – undo
18 18
  */
19 19
 class Wordlift_Batch_Analysis_Request_Async_Task extends Wordlift_Async_Task {
20 20
 
21
-	/**
22
-	 * The protected $action property should be set to the action to which you
23
-	 * wish to attach the asynchronous task. For example, if you want to spin
24
-	 * off an asynchronous task whenever a post gets saved, you would set this
25
-	 * to save_post.
26
-	 *
27
-	 * @since  3.14.2
28
-	 * @access protected
29
-	 * @var string $action The action to which you wish to attach the
30
-	 *                     asynchronous task.
31
-	 */
32
-	protected $action = 'wl_batch_analysis_request';
21
+    /**
22
+     * The protected $action property should be set to the action to which you
23
+     * wish to attach the asynchronous task. For example, if you want to spin
24
+     * off an asynchronous task whenever a post gets saved, you would set this
25
+     * to save_post.
26
+     *
27
+     * @since  3.14.2
28
+     * @access protected
29
+     * @var string $action The action to which you wish to attach the
30
+     *                     asynchronous task.
31
+     */
32
+    protected $action = 'wl_batch_analysis_request';
33 33
 
34
-	/**
35
-	 * A {@link Wordlift_Log_Service} instance.
36
-	 *
37
-	 * @since  3.14.2
38
-	 * @access private
39
-	 * @var \Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
40
-	 */
41
-	private $log;
34
+    /**
35
+     * A {@link Wordlift_Log_Service} instance.
36
+     *
37
+     * @since  3.14.2
38
+     * @access private
39
+     * @var \Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
40
+     */
41
+    private $log;
42 42
 
43
-	/**
44
-	 * Create a {@link Wordlift_Sparql_Query_Async_Task} instance.
45
-	 *
46
-	 * @since 3.14.2
47
-	 *
48
-	 * @param int $auth_level The authentication level to use (see above)
49
-	 */
50
-	public function __construct( $auth_level = self::BOTH ) {
51
-		parent::__construct( $auth_level );
43
+    /**
44
+     * Create a {@link Wordlift_Sparql_Query_Async_Task} instance.
45
+     *
46
+     * @since 3.14.2
47
+     *
48
+     * @param int $auth_level The authentication level to use (see above)
49
+     */
50
+    public function __construct( $auth_level = self::BOTH ) {
51
+        parent::__construct( $auth_level );
52 52
 
53
-		$this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Batch_Analysis_Request_Async_Task' );
53
+        $this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Batch_Analysis_Request_Async_Task' );
54 54
 
55
-	}
55
+    }
56 56
 
57
-	/**
58
-	 * @inheritdoc
59
-	 */
60
-	protected function prepare_data( $data ) {
57
+    /**
58
+     * @inheritdoc
59
+     */
60
+    protected function prepare_data( $data ) {
61 61
 
62
-		// Return the link setting.
63
-		return array();
64
-	}
62
+        // Return the link setting.
63
+        return array();
64
+    }
65 65
 
66
-	/**
67
-	 * @inheritdoc
68
-	 */
69
-	protected function run_action() {
66
+    /**
67
+     * @inheritdoc
68
+     */
69
+    protected function run_action() {
70 70
 
71
-		// Run the asynchronous action.
72
-		do_action( "wl_async_$this->action" );
71
+        // Run the asynchronous action.
72
+        do_action( "wl_async_$this->action" );
73 73
 
74
-	}
74
+    }
75 75
 
76 76
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -47,17 +47,17 @@  discard block
 block discarded – undo
47 47
 	 *
48 48
 	 * @param int $auth_level The authentication level to use (see above)
49 49
 	 */
50
-	public function __construct( $auth_level = self::BOTH ) {
51
-		parent::__construct( $auth_level );
50
+	public function __construct($auth_level = self::BOTH) {
51
+		parent::__construct($auth_level);
52 52
 
53
-		$this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Batch_Analysis_Request_Async_Task' );
53
+		$this->log = Wordlift_Log_Service::get_logger('Wordlift_Batch_Analysis_Request_Async_Task');
54 54
 
55 55
 	}
56 56
 
57 57
 	/**
58 58
 	 * @inheritdoc
59 59
 	 */
60
-	protected function prepare_data( $data ) {
60
+	protected function prepare_data($data) {
61 61
 
62 62
 		// Return the link setting.
63 63
 		return array();
@@ -69,7 +69,7 @@  discard block
 block discarded – undo
69 69
 	protected function run_action() {
70 70
 
71 71
 		// Run the asynchronous action.
72
-		do_action( "wl_async_$this->action" );
72
+		do_action("wl_async_$this->action");
73 73
 
74 74
 	}
75 75
 
Please login to merge, or discard this patch.