Completed
Push — develop ( 195cb3...f65bd6 )
by David
02:59
created
src/admin/wordlift_admin_meta_box_entities.php 2 patches
Indentation   +84 added lines, -84 removed lines patch added patch discarded remove patch
@@ -10,15 +10,15 @@  discard block
 block discarded – undo
10 10
  */
11 11
 function wl_register_metaboxes() {
12 12
 
13
-	// Load metabox classes
14
-	require_once( 'WL_Metabox/class-wl-metabox.php' );
13
+    // Load metabox classes
14
+    require_once( 'WL_Metabox/class-wl-metabox.php' );
15 15
 
16
-	$wl_metabox = new WL_Metabox();     // Everything is done inside here with the correct timing
16
+    $wl_metabox = new WL_Metabox();     // Everything is done inside here with the correct timing
17 17
 }
18 18
 
19 19
 if ( is_admin() ) {
20
-	add_action( 'load-post.php', 'wl_register_metaboxes' );
21
-	add_action( 'load-post-new.php', 'wl_register_metaboxes' );
20
+    add_action( 'load-post.php', 'wl_register_metaboxes' );
21
+    add_action( 'load-post-new.php', 'wl_register_metaboxes' );
22 22
 }
23 23
 
24 24
 
@@ -29,12 +29,12 @@  discard block
 block discarded – undo
29 29
  */
30 30
 function wl_admin_add_entities_meta_box( $post_type ) {
31 31
 
32
-	// wl_write_log( "wl_admin_add_entities_meta_box [ post type :: $post_type ]" );
32
+    // wl_write_log( "wl_admin_add_entities_meta_box [ post type :: $post_type ]" );
33 33
 
34
-	// Add main meta box for related entities and 4W
35
-	add_meta_box(
36
-		'wordlift_entities_box', __( 'WordLift', 'wordlift' ), 'wl_entities_box_content', $post_type, 'side', 'high'
37
-	);
34
+    // Add main meta box for related entities and 4W
35
+    add_meta_box(
36
+        'wordlift_entities_box', __( 'WordLift', 'wordlift' ), 'wl_entities_box_content', $post_type, 'side', 'high'
37
+    );
38 38
 }
39 39
 
40 40
 add_action( 'add_meta_boxes', 'wl_admin_add_entities_meta_box' );
@@ -46,23 +46,23 @@  discard block
 block discarded – undo
46 46
  */
47 47
 function wl_entities_box_content( $post ) {
48 48
 
49
-	// wl_write_log( "wl_entities_box_content [ post id :: $post->ID ]" );
49
+    // wl_write_log( "wl_entities_box_content [ post id :: $post->ID ]" );
50 50
 
51
-	// Angularjs edit-post widget wrapper
52
-	echo '<div id="wordlift-edit-post-outer-wrapper"></div>';
51
+    // Angularjs edit-post widget wrapper
52
+    echo '<div id="wordlift-edit-post-outer-wrapper"></div>';
53 53
 
54
-	// Angularjs edit-post widget classification boxes configuration
55
-	$classification_boxes = unserialize( WL_CORE_POST_CLASSIFICATION_BOXES );
54
+    // Angularjs edit-post widget classification boxes configuration
55
+    $classification_boxes = unserialize( WL_CORE_POST_CLASSIFICATION_BOXES );
56 56
 
57
-	// Array to store all related entities ids
58
-	$all_referenced_entities_ids = array();
57
+    // Array to store all related entities ids
58
+    $all_referenced_entities_ids = array();
59 59
 
60
-	// Add selected entities to classification_boxes
61
-	foreach ( $classification_boxes as $i => $box ) {
62
-		// Build the proper relation name
63
-		$relation_name = $box['id'];
60
+    // Add selected entities to classification_boxes
61
+    foreach ( $classification_boxes as $i => $box ) {
62
+        // Build the proper relation name
63
+        $relation_name = $box['id'];
64 64
 
65
-		// wl_write_log( "Going to related of $relation_name" );
65
+        // wl_write_log( "Going to related of $relation_name" );
66 66
 //
67 67
 //		// Get entity ids related to the current post for the given relation name (both draft and published entities)
68 68
 //		$draft_entity_ids   = wl_core_get_related_entity_ids( $post->ID, array(
@@ -82,68 +82,68 @@  discard block
 block discarded – undo
82 82
 //			$entity_id = wl_get_entity_uri( $entity_id );
83 83
 //		} );
84 84
 //
85
-		// Get the entity referenced from the post content.
86
-		$entity_uris = Wordlift_Content_Filter_Service::get_instance()->get_entity_uris( $post->post_content );
87
-
88
-		// Enhance current box selected entities.
89
-		$classification_boxes[ $i ]['selectedEntities'] = $entity_uris;
90
-
91
-		// Maps the URIs to entity posts.
92
-		$entity_service = Wordlift_Entity_Service::get_instance();
93
-		$entity_ids     = array_map( function ( $item ) use ( $entity_service ) {
94
-			$post = $entity_service->get_entity_post_by_uri( $item );
95
-
96
-			return $post->ID;
97
-		}, $entity_uris );
98
-		// Store the entity ids for all the 4W
99
-		$all_referenced_entities_ids = array_merge( $all_referenced_entities_ids, $entity_ids );
100
-
101
-	}
102
-	// Json encoding for classification boxes structure
103
-	$classification_boxes = json_encode( $classification_boxes );
104
-
105
-	// Ensure there are no repetitions of the referenced entities
106
-	$all_referenced_entities_ids = array_unique( $all_referenced_entities_ids );
107
-
108
-	// Build the entity storage object
109
-	$referenced_entities_obj = array();
110
-	foreach ( $all_referenced_entities_ids as $referenced_entity ) {
111
-		$entity                                   = wl_serialize_entity( $referenced_entity );
112
-		$referenced_entities_obj[ $entity['id'] ] = $entity;
113
-	}
114
-
115
-	$referenced_entities_obj = empty( $referenced_entities_obj ) ?
116
-		'{}' : json_encode( $referenced_entities_obj );
117
-
118
-	$published_place_id  = get_post_meta(
119
-		$post->ID, Wordlift_Schema_Service::FIELD_LOCATION_CREATED, true
120
-	);
121
-	$published_place_obj = ( $published_place_id ) ?
122
-		json_encode( wl_serialize_entity( $published_place_id ) ) :
123
-		'undefined';
124
-
125
-	$topic_id  = get_post_meta(
126
-		$post->ID, Wordlift_Schema_Service::FIELD_TOPIC, true
127
-	);
128
-	$topic_obj = ( $topic_id ) ?
129
-		json_encode( wl_serialize_entity( $topic_id ) ) :
130
-		'undefined';
131
-
132
-	$configuration_service = Wordlift_Configuration_Service::get_instance();
133
-
134
-	$default_thumbnail_path = WL_DEFAULT_THUMBNAIL_PATH;
135
-	$default_path           = WL_DEFAULT_PATH;
136
-	$dataset_uri            = $configuration_service->get_dataset_uri();
137
-	$current_post_uri       = wl_get_entity_uri( $post->ID );
138
-
139
-	// Retrieve the current post author
140
-	$post_author = get_userdata( $post->post_author )->display_name;
141
-	// Retrive the published date
142
-	$published_date = get_the_time( 'Y-m-d', $post->ID );
143
-	// Current language
144
-	$current_language = $configuration_service->get_language_code();
145
-
146
-	echo <<<EOF
85
+        // Get the entity referenced from the post content.
86
+        $entity_uris = Wordlift_Content_Filter_Service::get_instance()->get_entity_uris( $post->post_content );
87
+
88
+        // Enhance current box selected entities.
89
+        $classification_boxes[ $i ]['selectedEntities'] = $entity_uris;
90
+
91
+        // Maps the URIs to entity posts.
92
+        $entity_service = Wordlift_Entity_Service::get_instance();
93
+        $entity_ids     = array_map( function ( $item ) use ( $entity_service ) {
94
+            $post = $entity_service->get_entity_post_by_uri( $item );
95
+
96
+            return $post->ID;
97
+        }, $entity_uris );
98
+        // Store the entity ids for all the 4W
99
+        $all_referenced_entities_ids = array_merge( $all_referenced_entities_ids, $entity_ids );
100
+
101
+    }
102
+    // Json encoding for classification boxes structure
103
+    $classification_boxes = json_encode( $classification_boxes );
104
+
105
+    // Ensure there are no repetitions of the referenced entities
106
+    $all_referenced_entities_ids = array_unique( $all_referenced_entities_ids );
107
+
108
+    // Build the entity storage object
109
+    $referenced_entities_obj = array();
110
+    foreach ( $all_referenced_entities_ids as $referenced_entity ) {
111
+        $entity                                   = wl_serialize_entity( $referenced_entity );
112
+        $referenced_entities_obj[ $entity['id'] ] = $entity;
113
+    }
114
+
115
+    $referenced_entities_obj = empty( $referenced_entities_obj ) ?
116
+        '{}' : json_encode( $referenced_entities_obj );
117
+
118
+    $published_place_id  = get_post_meta(
119
+        $post->ID, Wordlift_Schema_Service::FIELD_LOCATION_CREATED, true
120
+    );
121
+    $published_place_obj = ( $published_place_id ) ?
122
+        json_encode( wl_serialize_entity( $published_place_id ) ) :
123
+        'undefined';
124
+
125
+    $topic_id  = get_post_meta(
126
+        $post->ID, Wordlift_Schema_Service::FIELD_TOPIC, true
127
+    );
128
+    $topic_obj = ( $topic_id ) ?
129
+        json_encode( wl_serialize_entity( $topic_id ) ) :
130
+        'undefined';
131
+
132
+    $configuration_service = Wordlift_Configuration_Service::get_instance();
133
+
134
+    $default_thumbnail_path = WL_DEFAULT_THUMBNAIL_PATH;
135
+    $default_path           = WL_DEFAULT_PATH;
136
+    $dataset_uri            = $configuration_service->get_dataset_uri();
137
+    $current_post_uri       = wl_get_entity_uri( $post->ID );
138
+
139
+    // Retrieve the current post author
140
+    $post_author = get_userdata( $post->post_author )->display_name;
141
+    // Retrive the published date
142
+    $published_date = get_the_time( 'Y-m-d', $post->ID );
143
+    // Current language
144
+    $current_language = $configuration_service->get_language_code();
145
+
146
+    echo <<<EOF
147 147
     <script type="text/javascript">
148 148
         jQuery( function() {
149 149
 
Please login to merge, or discard this patch.
Spacing   +31 added lines, -33 removed lines patch added patch discarded remove patch
@@ -11,14 +11,14 @@  discard block
 block discarded – undo
11 11
 function wl_register_metaboxes() {
12 12
 
13 13
 	// Load metabox classes
14
-	require_once( 'WL_Metabox/class-wl-metabox.php' );
14
+	require_once('WL_Metabox/class-wl-metabox.php');
15 15
 
16
-	$wl_metabox = new WL_Metabox();     // Everything is done inside here with the correct timing
16
+	$wl_metabox = new WL_Metabox(); // Everything is done inside here with the correct timing
17 17
 }
18 18
 
19
-if ( is_admin() ) {
20
-	add_action( 'load-post.php', 'wl_register_metaboxes' );
21
-	add_action( 'load-post-new.php', 'wl_register_metaboxes' );
19
+if (is_admin()) {
20
+	add_action('load-post.php', 'wl_register_metaboxes');
21
+	add_action('load-post-new.php', 'wl_register_metaboxes');
22 22
 }
23 23
 
24 24
 
@@ -27,24 +27,24 @@  discard block
 block discarded – undo
27 27
  *
28 28
  * @param string $post_type The type of the current open post.
29 29
  */
30
-function wl_admin_add_entities_meta_box( $post_type ) {
30
+function wl_admin_add_entities_meta_box($post_type) {
31 31
 
32 32
 	// wl_write_log( "wl_admin_add_entities_meta_box [ post type :: $post_type ]" );
33 33
 
34 34
 	// Add main meta box for related entities and 4W
35 35
 	add_meta_box(
36
-		'wordlift_entities_box', __( 'WordLift', 'wordlift' ), 'wl_entities_box_content', $post_type, 'side', 'high'
36
+		'wordlift_entities_box', __('WordLift', 'wordlift'), 'wl_entities_box_content', $post_type, 'side', 'high'
37 37
 	);
38 38
 }
39 39
 
40
-add_action( 'add_meta_boxes', 'wl_admin_add_entities_meta_box' );
40
+add_action('add_meta_boxes', 'wl_admin_add_entities_meta_box');
41 41
 
42 42
 /**
43 43
  * Displays the meta box contents (called by *add_meta_box* callback).
44 44
  *
45 45
  * @param WP_Post $post The current post.
46 46
  */
47
-function wl_entities_box_content( $post ) {
47
+function wl_entities_box_content($post) {
48 48
 
49 49
 	// wl_write_log( "wl_entities_box_content [ post id :: $post->ID ]" );
50 50
 
@@ -52,13 +52,13 @@  discard block
 block discarded – undo
52 52
 	echo '<div id="wordlift-edit-post-outer-wrapper"></div>';
53 53
 
54 54
 	// Angularjs edit-post widget classification boxes configuration
55
-	$classification_boxes = unserialize( WL_CORE_POST_CLASSIFICATION_BOXES );
55
+	$classification_boxes = unserialize(WL_CORE_POST_CLASSIFICATION_BOXES);
56 56
 
57 57
 	// Array to store all related entities ids
58 58
 	$all_referenced_entities_ids = array();
59 59
 
60 60
 	// Add selected entities to classification_boxes
61
-	foreach ( $classification_boxes as $i => $box ) {
61
+	foreach ($classification_boxes as $i => $box) {
62 62
 		// Build the proper relation name
63 63
 		$relation_name = $box['id'];
64 64
 
@@ -83,63 +83,61 @@  discard block
 block discarded – undo
83 83
 //		} );
84 84
 //
85 85
 		// Get the entity referenced from the post content.
86
-		$entity_uris = Wordlift_Content_Filter_Service::get_instance()->get_entity_uris( $post->post_content );
86
+		$entity_uris = Wordlift_Content_Filter_Service::get_instance()->get_entity_uris($post->post_content);
87 87
 
88 88
 		// Enhance current box selected entities.
89
-		$classification_boxes[ $i ]['selectedEntities'] = $entity_uris;
89
+		$classification_boxes[$i]['selectedEntities'] = $entity_uris;
90 90
 
91 91
 		// Maps the URIs to entity posts.
92 92
 		$entity_service = Wordlift_Entity_Service::get_instance();
93
-		$entity_ids     = array_map( function ( $item ) use ( $entity_service ) {
94
-			$post = $entity_service->get_entity_post_by_uri( $item );
93
+		$entity_ids     = array_map(function($item) use ($entity_service) {
94
+			$post = $entity_service->get_entity_post_by_uri($item);
95 95
 
96 96
 			return $post->ID;
97
-		}, $entity_uris );
97
+		}, $entity_uris);
98 98
 		// Store the entity ids for all the 4W
99
-		$all_referenced_entities_ids = array_merge( $all_referenced_entities_ids, $entity_ids );
99
+		$all_referenced_entities_ids = array_merge($all_referenced_entities_ids, $entity_ids);
100 100
 
101 101
 	}
102 102
 	// Json encoding for classification boxes structure
103
-	$classification_boxes = json_encode( $classification_boxes );
103
+	$classification_boxes = json_encode($classification_boxes);
104 104
 
105 105
 	// Ensure there are no repetitions of the referenced entities
106
-	$all_referenced_entities_ids = array_unique( $all_referenced_entities_ids );
106
+	$all_referenced_entities_ids = array_unique($all_referenced_entities_ids);
107 107
 
108 108
 	// Build the entity storage object
109 109
 	$referenced_entities_obj = array();
110
-	foreach ( $all_referenced_entities_ids as $referenced_entity ) {
111
-		$entity                                   = wl_serialize_entity( $referenced_entity );
112
-		$referenced_entities_obj[ $entity['id'] ] = $entity;
110
+	foreach ($all_referenced_entities_ids as $referenced_entity) {
111
+		$entity                                   = wl_serialize_entity($referenced_entity);
112
+		$referenced_entities_obj[$entity['id']] = $entity;
113 113
 	}
114 114
 
115
-	$referenced_entities_obj = empty( $referenced_entities_obj ) ?
116
-		'{}' : json_encode( $referenced_entities_obj );
115
+	$referenced_entities_obj = empty($referenced_entities_obj) ?
116
+		'{}' : json_encode($referenced_entities_obj);
117 117
 
118 118
 	$published_place_id  = get_post_meta(
119 119
 		$post->ID, Wordlift_Schema_Service::FIELD_LOCATION_CREATED, true
120 120
 	);
121
-	$published_place_obj = ( $published_place_id ) ?
122
-		json_encode( wl_serialize_entity( $published_place_id ) ) :
123
-		'undefined';
121
+	$published_place_obj = ($published_place_id) ?
122
+		json_encode(wl_serialize_entity($published_place_id)) : 'undefined';
124 123
 
125 124
 	$topic_id  = get_post_meta(
126 125
 		$post->ID, Wordlift_Schema_Service::FIELD_TOPIC, true
127 126
 	);
128
-	$topic_obj = ( $topic_id ) ?
129
-		json_encode( wl_serialize_entity( $topic_id ) ) :
130
-		'undefined';
127
+	$topic_obj = ($topic_id) ?
128
+		json_encode(wl_serialize_entity($topic_id)) : 'undefined';
131 129
 
132 130
 	$configuration_service = Wordlift_Configuration_Service::get_instance();
133 131
 
134 132
 	$default_thumbnail_path = WL_DEFAULT_THUMBNAIL_PATH;
135 133
 	$default_path           = WL_DEFAULT_PATH;
136 134
 	$dataset_uri            = $configuration_service->get_dataset_uri();
137
-	$current_post_uri       = wl_get_entity_uri( $post->ID );
135
+	$current_post_uri       = wl_get_entity_uri($post->ID);
138 136
 
139 137
 	// Retrieve the current post author
140
-	$post_author = get_userdata( $post->post_author )->display_name;
138
+	$post_author = get_userdata($post->post_author)->display_name;
141 139
 	// Retrive the published date
142
-	$published_date = get_the_time( 'Y-m-d', $post->ID );
140
+	$published_date = get_the_time('Y-m-d', $post->ID);
143 141
 	// Current language
144 142
 	$current_language = $configuration_service->get_language_code();
145 143
 
Please login to merge, or discard this patch.
src/admin/partials/wordlift-admin-batch-analysis-page.php 2 patches
Indentation   +43 added lines, -43 removed lines patch added patch discarded remove patch
@@ -11,68 +11,68 @@
 block discarded – undo
11 11
 	<h2><?php esc_html_e( 'WordLift Batch Analyze Monitor', 'wordlift' ) ?></h2>
12 12
 
13 13
 	<?php
14
-	$queue        = $this->batch_analysis_service->waiting_for_analysis();
15
-	$submit_count = count( $queue );
16
-	?>
14
+    $queue        = $this->batch_analysis_service->waiting_for_analysis();
15
+    $submit_count = count( $queue );
16
+    ?>
17 17
 	<h3><?php esc_html_e( 'Posts in queue', 'wordlift' ) ?><?php echo " ($submit_count)"; ?></h3>
18 18
 	<?php
19
-	if ( empty( $queue ) ) {
20
-		esc_html_e( 'Nothing is currently in queue', 'wordlift' );
21
-	} else {
22
-		echo '<ul>';
23
-		foreach ( $queue as $pid ) {
24
-			$cancel_link = admin_url( "admin-ajax.php?action=wl_batch_analysis_cancel&post=$pid" );
25
-			?>
19
+    if ( empty( $queue ) ) {
20
+        esc_html_e( 'Nothing is currently in queue', 'wordlift' );
21
+    } else {
22
+        echo '<ul>';
23
+        foreach ( $queue as $pid ) {
24
+            $cancel_link = admin_url( "admin-ajax.php?action=wl_batch_analysis_cancel&post=$pid" );
25
+            ?>
26 26
 			<li><a href="<?php echo get_edit_post_link( $pid ) ?>"><?php
27
-					echo get_the_title( $pid ) ?></a> [<a
27
+                    echo get_the_title( $pid ) ?></a> [<a
28 28
 					href="<?php echo esc_attr( $cancel_link ); ?> "><?php esc_html_e( 'Cancel', 'wordlift' ); ?></a>]
29 29
 			</li>
30 30
 			<?php
31
-		}
32
-		echo '</ul>';
33
-	}
31
+        }
32
+        echo '</ul>';
33
+    }
34 34
 
35
-	$queue         = $this->batch_analysis_service->waiting_for_response();
36
-	$request_count = count( $queue );
37
-	?>
35
+    $queue         = $this->batch_analysis_service->waiting_for_response();
36
+    $request_count = count( $queue );
37
+    ?>
38 38
 	<h3><?php esc_html_e( 'Posts being processed', 'wordlift' ) ?><?php echo " ($request_count)"; ?></h3>
39 39
 	<?php
40
-	if ( empty( $queue ) ) {
41
-		esc_html_e( 'Nothing is currently being processed', 'wordlift' );
42
-	} else {
43
-		echo '<ul>';
44
-		foreach ( $queue as $pid ) {
45
-			$cancel_link = admin_url( "admin-ajax.php?action=wl_batch_analysis_cancel&post=$pid" );
46
-			?>
40
+    if ( empty( $queue ) ) {
41
+        esc_html_e( 'Nothing is currently being processed', 'wordlift' );
42
+    } else {
43
+        echo '<ul>';
44
+        foreach ( $queue as $pid ) {
45
+            $cancel_link = admin_url( "admin-ajax.php?action=wl_batch_analysis_cancel&post=$pid" );
46
+            ?>
47 47
 			<li><a href="<?php echo get_edit_post_link( $pid ) ?>"><?php
48
-					echo get_the_title( $pid ) ?></a> [<a
48
+                    echo get_the_title( $pid ) ?></a> [<a
49 49
 					href="<?php echo esc_attr( $cancel_link ); ?> "><?php esc_html_e( 'Cancel', 'wordlift' ); ?></a>]
50 50
 			</li>
51 51
 			<?php
52
-		}
53
-		echo '</ul>';
54
-	}
52
+        }
53
+        echo '</ul>';
54
+    }
55 55
 
56
-	$queue         = $this->batch_analysis_service->get_warnings();
57
-	$warning_count = count( $queue );
58
-	?>
56
+    $queue         = $this->batch_analysis_service->get_warnings();
57
+    $warning_count = count( $queue );
58
+    ?>
59 59
 
60 60
 	<h3><?php esc_html_e( 'Posts with warnings', 'wordlift' ) ?><?php echo " ($warning_count)"; ?></h3>
61 61
 	<?php
62
-	if ( empty( $queue ) ) {
63
-		esc_html_e( 'No warnings :-)', 'wordlift' );
64
-	} else {
65
-		echo '<ul>';
66
-		foreach ( $queue as $pid ) {
67
-			$cancel_link = admin_url( "admin-ajax.php?action=wl_batch_analysis_clear_warning&post=$pid" );
68
-			?>
62
+    if ( empty( $queue ) ) {
63
+        esc_html_e( 'No warnings :-)', 'wordlift' );
64
+    } else {
65
+        echo '<ul>';
66
+        foreach ( $queue as $pid ) {
67
+            $cancel_link = admin_url( "admin-ajax.php?action=wl_batch_analysis_clear_warning&post=$pid" );
68
+            ?>
69 69
 			<li><a href="<?php echo get_edit_post_link( $pid ) ?>"><?php
70
-					echo get_the_title( $pid ) ?></a> [<a
70
+                    echo get_the_title( $pid ) ?></a> [<a
71 71
 					href="<?php echo esc_attr( $cancel_link ); ?> "><?php esc_html_e( 'Clear warning', 'wordlift' ); ?></a>]
72 72
 			</li>
73 73
 			<?php
74
-		}
75
-		echo '</ul>';
76
-	}
77
-	?>
74
+        }
75
+        echo '</ul>';
76
+    }
77
+    ?>
78 78
 </div>
Please login to merge, or discard this patch.
Spacing   +28 added lines, -28 removed lines patch added patch discarded remove patch
@@ -8,24 +8,24 @@  discard block
 block discarded – undo
8 8
 ?>
9 9
 
10 10
 <div class="wrap">
11
-	<h2><?php esc_html_e( 'WordLift Batch Analyze Monitor', 'wordlift' ) ?></h2>
11
+	<h2><?php esc_html_e('WordLift Batch Analyze Monitor', 'wordlift') ?></h2>
12 12
 
13 13
 	<?php
14 14
 	$queue        = $this->batch_analysis_service->waiting_for_analysis();
15
-	$submit_count = count( $queue );
15
+	$submit_count = count($queue);
16 16
 	?>
17
-	<h3><?php esc_html_e( 'Posts in queue', 'wordlift' ) ?><?php echo " ($submit_count)"; ?></h3>
17
+	<h3><?php esc_html_e('Posts in queue', 'wordlift') ?><?php echo " ($submit_count)"; ?></h3>
18 18
 	<?php
19
-	if ( empty( $queue ) ) {
20
-		esc_html_e( 'Nothing is currently in queue', 'wordlift' );
19
+	if (empty($queue)) {
20
+		esc_html_e('Nothing is currently in queue', 'wordlift');
21 21
 	} else {
22 22
 		echo '<ul>';
23
-		foreach ( $queue as $pid ) {
24
-			$cancel_link = admin_url( "admin-ajax.php?action=wl_batch_analysis_cancel&post=$pid" );
23
+		foreach ($queue as $pid) {
24
+			$cancel_link = admin_url("admin-ajax.php?action=wl_batch_analysis_cancel&post=$pid");
25 25
 			?>
26
-			<li><a href="<?php echo get_edit_post_link( $pid ) ?>"><?php
27
-					echo get_the_title( $pid ) ?></a> [<a
28
-					href="<?php echo esc_attr( $cancel_link ); ?> "><?php esc_html_e( 'Cancel', 'wordlift' ); ?></a>]
26
+			<li><a href="<?php echo get_edit_post_link($pid) ?>"><?php
27
+					echo get_the_title($pid) ?></a> [<a
28
+					href="<?php echo esc_attr($cancel_link); ?> "><?php esc_html_e('Cancel', 'wordlift'); ?></a>]
29 29
 			</li>
30 30
 			<?php
31 31
 		}
@@ -33,20 +33,20 @@  discard block
 block discarded – undo
33 33
 	}
34 34
 
35 35
 	$queue         = $this->batch_analysis_service->waiting_for_response();
36
-	$request_count = count( $queue );
36
+	$request_count = count($queue);
37 37
 	?>
38
-	<h3><?php esc_html_e( 'Posts being processed', 'wordlift' ) ?><?php echo " ($request_count)"; ?></h3>
38
+	<h3><?php esc_html_e('Posts being processed', 'wordlift') ?><?php echo " ($request_count)"; ?></h3>
39 39
 	<?php
40
-	if ( empty( $queue ) ) {
41
-		esc_html_e( 'Nothing is currently being processed', 'wordlift' );
40
+	if (empty($queue)) {
41
+		esc_html_e('Nothing is currently being processed', 'wordlift');
42 42
 	} else {
43 43
 		echo '<ul>';
44
-		foreach ( $queue as $pid ) {
45
-			$cancel_link = admin_url( "admin-ajax.php?action=wl_batch_analysis_cancel&post=$pid" );
44
+		foreach ($queue as $pid) {
45
+			$cancel_link = admin_url("admin-ajax.php?action=wl_batch_analysis_cancel&post=$pid");
46 46
 			?>
47
-			<li><a href="<?php echo get_edit_post_link( $pid ) ?>"><?php
48
-					echo get_the_title( $pid ) ?></a> [<a
49
-					href="<?php echo esc_attr( $cancel_link ); ?> "><?php esc_html_e( 'Cancel', 'wordlift' ); ?></a>]
47
+			<li><a href="<?php echo get_edit_post_link($pid) ?>"><?php
48
+					echo get_the_title($pid) ?></a> [<a
49
+					href="<?php echo esc_attr($cancel_link); ?> "><?php esc_html_e('Cancel', 'wordlift'); ?></a>]
50 50
 			</li>
51 51
 			<?php
52 52
 		}
@@ -54,21 +54,21 @@  discard block
 block discarded – undo
54 54
 	}
55 55
 
56 56
 	$queue         = $this->batch_analysis_service->get_warnings();
57
-	$warning_count = count( $queue );
57
+	$warning_count = count($queue);
58 58
 	?>
59 59
 
60
-	<h3><?php esc_html_e( 'Posts with warnings', 'wordlift' ) ?><?php echo " ($warning_count)"; ?></h3>
60
+	<h3><?php esc_html_e('Posts with warnings', 'wordlift') ?><?php echo " ($warning_count)"; ?></h3>
61 61
 	<?php
62
-	if ( empty( $queue ) ) {
63
-		esc_html_e( 'No warnings :-)', 'wordlift' );
62
+	if (empty($queue)) {
63
+		esc_html_e('No warnings :-)', 'wordlift');
64 64
 	} else {
65 65
 		echo '<ul>';
66
-		foreach ( $queue as $pid ) {
67
-			$cancel_link = admin_url( "admin-ajax.php?action=wl_batch_analysis_clear_warning&post=$pid" );
66
+		foreach ($queue as $pid) {
67
+			$cancel_link = admin_url("admin-ajax.php?action=wl_batch_analysis_clear_warning&post=$pid");
68 68
 			?>
69
-			<li><a href="<?php echo get_edit_post_link( $pid ) ?>"><?php
70
-					echo get_the_title( $pid ) ?></a> [<a
71
-					href="<?php echo esc_attr( $cancel_link ); ?> "><?php esc_html_e( 'Clear warning', 'wordlift' ); ?></a>]
69
+			<li><a href="<?php echo get_edit_post_link($pid) ?>"><?php
70
+					echo get_the_title($pid) ?></a> [<a
71
+					href="<?php echo esc_attr($cancel_link); ?> "><?php esc_html_e('Clear warning', 'wordlift'); ?></a>]
72 72
 			</li>
73 73
 			<?php
74 74
 		}
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 WP_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( "wp_async_$this->action" );
71
+        // Run the asynchronous action.
72
+        do_action( "wp_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( "wp_async_$this->action" );
72
+		do_action("wp_async_$this->action");
73 73
 
74 74
 	}
75 75
 
Please login to merge, or discard this patch.
src/includes/wp-async-task/wp-async-task.php 2 patches
Indentation   +269 added lines, -269 removed lines patch added patch discarded remove patch
@@ -8,275 +8,275 @@
 block discarded – undo
8 8
  */
9 9
 
10 10
 if ( ! class_exists( 'WP_Async_Task' ) ) {
11
-	abstract class WP_Async_Task {
12
-
13
-		/**
14
-		 * Constant identifier for a task that should be available to logged-in users
15
-		 *
16
-		 * See constructor documentation for more details.
17
-		 */
18
-		const LOGGED_IN = 1;
19
-
20
-		/**
21
-		 * Constant identifier for a task that should be available to logged-out users
22
-		 *
23
-		 * See constructor documentation for more details.
24
-		 */
25
-		const LOGGED_OUT = 2;
26
-
27
-		/**
28
-		 * Constant identifier for a task that should be available to all users regardless of auth status
29
-		 *
30
-		 * See constructor documentation for more details.
31
-		 */
32
-		const BOTH = 3;
33
-
34
-		/**
35
-		 * This is the argument count for the main action set in the constructor. It
36
-		 * is set to an arbitrarily high value of twenty, but can be overridden if
37
-		 * necessary
38
-		 *
39
-		 * @var int
40
-		 */
41
-		protected $argument_count = 20;
42
-
43
-		/**
44
-		 * Priority to fire intermediate action.
45
-		 *
46
-		 * @var int
47
-		 */
48
-		protected $priority = 10;
49
-
50
-		/**
51
-		 * @var string
52
-		 */
53
-		protected $action;
54
-
55
-		/**
56
-		 * @var array
57
-		 */
58
-		protected $_body_data;
59
-
60
-		/**
61
-		 * Constructor to wire up the necessary actions
62
-		 *
63
-		 * Which hooks the asynchronous postback happens on can be set by the
64
-		 * $auth_level parameter. There are essentially three options: logged in users
65
-		 * only, logged out users only, or both. Set this when you instantiate an
66
-		 * object by using one of the three class constants to do so:
67
-		 *  - LOGGED_IN
68
-		 *  - LOGGED_OUT
69
-		 *  - BOTH
70
-		 * $auth_level defaults to BOTH
71
-		 *
72
-		 * @throws Exception If the class' $action value hasn't been set
73
-		 *
74
-		 * @param int $auth_level The authentication level to use (see above)
75
-		 */
76
-		public function __construct( $auth_level = self::BOTH ) {
77
-			if ( empty( $this->action ) ) {
78
-				throw new Exception( 'Action not defined for class ' . __CLASS__ );
79
-			}
80
-			add_action( $this->action, array(
81
-				$this,
82
-				'launch',
83
-			), (int) $this->priority, (int) $this->argument_count );
84
-			if ( $auth_level & self::LOGGED_IN ) {
85
-				add_action( "admin_post_wp_async_$this->action", array(
86
-					$this,
87
-					'handle_postback',
88
-				) );
89
-			}
90
-			if ( $auth_level & self::LOGGED_OUT ) {
91
-				add_action( "admin_post_nopriv_wp_async_$this->action", array(
92
-					$this,
93
-					'handle_postback',
94
-				) );
95
-			}
96
-		}
97
-
98
-		/**
99
-		 * Add the shutdown action for launching the real postback if we don't
100
-		 * get an exception thrown by prepare_data().
101
-		 *
102
-		 * @uses func_get_args() To grab any arguments passed by the action
103
-		 */
104
-		public function launch() {
105
-			$data = func_get_args();
106
-			try {
107
-				$data = $this->prepare_data( $data );
108
-			} catch ( Exception $e ) {
109
-				return;
110
-			}
111
-
112
-			$data['action'] = "wp_async_$this->action";
113
-			$data['_nonce'] = $this->create_async_nonce();
114
-
115
-			$this->_body_data = $data;
116
-
117
-			if ( ! has_action( 'shutdown', array(
118
-				$this,
119
-				'launch_on_shutdown',
120
-			) )
121
-			) {
122
-				add_action( 'shutdown', array( $this, 'launch_on_shutdown' ) );
123
-			}
124
-		}
125
-
126
-		/**
127
-		 * Launch the request on the WordPress shutdown hook
128
-		 *
129
-		 * On VIP we got into data races due to the postback sometimes completing
130
-		 * faster than the data could propogate to the database server cluster.
131
-		 * This made WordPress get empty data sets from the database without
132
-		 * failing. On their advice, we're moving the actual firing of the async
133
-		 * postback to the shutdown hook. Supposedly that will ensure that the
134
-		 * data at least has time to get into the object cache.
135
-		 *
136
-		 * @uses $_COOKIE        To send a cookie header for async postback
137
-		 * @uses apply_filters()
138
-		 * @uses admin_url()
139
-		 * @uses wp_remote_post()
140
-		 */
141
-		public function launch_on_shutdown() {
142
-			if ( ! empty( $this->_body_data ) ) {
143
-				$cookies = array();
144
-				foreach ( $_COOKIE as $name => $value ) {
145
-					$cookies[] = "$name=" . urlencode( is_array( $value ) ? serialize( $value ) : $value );
146
-				}
147
-
148
-				$request_args = array(
149
-					'timeout'   => 0.01,
150
-					'blocking'  => false,
151
-					'sslverify' => apply_filters( 'https_local_ssl_verify', false ),
152
-					'body'      => $this->_body_data,
153
-					'headers'   => array(
154
-						'cookie' => implode( '; ', $cookies ),
155
-					),
156
-				);
157
-
158
-				$url = admin_url( 'admin-post.php' );
159
-
160
-				wp_remote_post( $url, $request_args );
161
-			}
162
-		}
163
-
164
-		/**
165
-		 * Verify the postback is valid, then fire any scheduled events.
166
-		 *
167
-		 * @uses $_POST['_nonce']
168
-		 * @uses is_user_logged_in()
169
-		 * @uses add_filter()
170
-		 * @uses wp_die()
171
-		 */
172
-		public function handle_postback() {
173
-			if ( isset( $_POST['_nonce'] ) && $this->verify_async_nonce( $_POST['_nonce'] ) ) {
174
-				if ( ! is_user_logged_in() ) {
175
-					$this->action = "nopriv_$this->action";
176
-				}
177
-				$this->run_action();
178
-			}
179
-
180
-			add_filter( 'wp_die_handler', function () {
181
-				die();
182
-			} );
183
-			wp_die();
184
-		}
185
-
186
-		/**
187
-		 * Create a random, one time use token.
188
-		 *
189
-		 * Based entirely on wp_create_nonce() but does not tie the nonce to the
190
-		 * current logged-in user.
191
-		 *
192
-		 * @uses wp_nonce_tick()
193
-		 * @uses wp_hash()
194
-		 *
195
-		 * @return string The one-time use token
196
-		 */
197
-		protected function create_async_nonce() {
198
-			$action = $this->get_nonce_action();
199
-			$i      = wp_nonce_tick();
200
-
201
-			return substr( wp_hash( $i . $action . get_class( $this ), 'nonce' ), - 12, 10 );
202
-		}
203
-
204
-		/**
205
-		 * Verify that the correct nonce was used within the time limit.
206
-		 *
207
-		 * @uses wp_nonce_tick()
208
-		 * @uses wp_hash()
209
-		 *
210
-		 * @param string $nonce Nonce to be verified
211
-		 *
212
-		 * @return bool Whether the nonce check passed or failed
213
-		 */
214
-		protected function verify_async_nonce( $nonce ) {
215
-			$action = $this->get_nonce_action();
216
-			$i      = wp_nonce_tick();
217
-
218
-			// Nonce generated 0-12 hours ago
219
-			if ( substr( wp_hash( $i . $action . get_class( $this ), 'nonce' ), - 12, 10 ) == $nonce ) {
220
-				return 1;
221
-			}
222
-
223
-			// Nonce generated 12-24 hours ago
224
-			if ( substr( wp_hash( ( $i - 1 ) . $action . get_class( $this ), 'nonce' ), - 12, 10 ) == $nonce ) {
225
-				return 2;
226
-			}
227
-
228
-			// Invalid nonce
229
-			return false;
230
-		}
231
-
232
-		/**
233
-		 * Get a nonce action based on the $action property of the class
234
-		 *
235
-		 * @return string The nonce action for the current instance
236
-		 */
237
-		protected function get_nonce_action() {
238
-			$action = $this->action;
239
-			if ( substr( $action, 0, 7 ) === 'nopriv_' ) {
240
-				$action = substr( $action, 7 );
241
-			}
242
-			$action = "wp_async_$action";
243
-
244
-			return $action;
245
-		}
246
-
247
-		/**
248
-		 * Prepare any data to be passed to the asynchronous postback
249
-		 *
250
-		 * The array this function receives will be a numerically keyed array from
251
-		 * func_get_args(). It is expected that you will return an associative array
252
-		 * so that the $_POST values used in the asynchronous call will make sense.
253
-		 *
254
-		 * The array you send back may or may not have anything to do with the data
255
-		 * passed into this method. It all depends on the implementation details and
256
-		 * what data is needed in the asynchronous postback.
257
-		 *
258
-		 * Do not set values for 'action' or '_nonce', as those will get overwritten
259
-		 * later in launch().
260
-		 *
261
-		 * @throws Exception If the postback should not occur for any reason
262
-		 *
263
-		 * @param array $data The raw data received by the launch method
264
-		 *
265
-		 * @return array The prepared data
266
-		 */
267
-		abstract protected function prepare_data( $data );
268
-
269
-		/**
270
-		 * Run the do_action function for the asynchronous postback.
271
-		 *
272
-		 * This method needs to fetch and sanitize any and all data from the $_POST
273
-		 * superglobal and provide them to the do_action call.
274
-		 *
275
-		 * The action should be constructed as "wp_async_task_$this->action"
276
-		 */
277
-		abstract protected function run_action();
278
-
279
-	}
11
+    abstract class WP_Async_Task {
12
+
13
+        /**
14
+         * Constant identifier for a task that should be available to logged-in users
15
+         *
16
+         * See constructor documentation for more details.
17
+         */
18
+        const LOGGED_IN = 1;
19
+
20
+        /**
21
+         * Constant identifier for a task that should be available to logged-out users
22
+         *
23
+         * See constructor documentation for more details.
24
+         */
25
+        const LOGGED_OUT = 2;
26
+
27
+        /**
28
+         * Constant identifier for a task that should be available to all users regardless of auth status
29
+         *
30
+         * See constructor documentation for more details.
31
+         */
32
+        const BOTH = 3;
33
+
34
+        /**
35
+         * This is the argument count for the main action set in the constructor. It
36
+         * is set to an arbitrarily high value of twenty, but can be overridden if
37
+         * necessary
38
+         *
39
+         * @var int
40
+         */
41
+        protected $argument_count = 20;
42
+
43
+        /**
44
+         * Priority to fire intermediate action.
45
+         *
46
+         * @var int
47
+         */
48
+        protected $priority = 10;
49
+
50
+        /**
51
+         * @var string
52
+         */
53
+        protected $action;
54
+
55
+        /**
56
+         * @var array
57
+         */
58
+        protected $_body_data;
59
+
60
+        /**
61
+         * Constructor to wire up the necessary actions
62
+         *
63
+         * Which hooks the asynchronous postback happens on can be set by the
64
+         * $auth_level parameter. There are essentially three options: logged in users
65
+         * only, logged out users only, or both. Set this when you instantiate an
66
+         * object by using one of the three class constants to do so:
67
+         *  - LOGGED_IN
68
+         *  - LOGGED_OUT
69
+         *  - BOTH
70
+         * $auth_level defaults to BOTH
71
+         *
72
+         * @throws Exception If the class' $action value hasn't been set
73
+         *
74
+         * @param int $auth_level The authentication level to use (see above)
75
+         */
76
+        public function __construct( $auth_level = self::BOTH ) {
77
+            if ( empty( $this->action ) ) {
78
+                throw new Exception( 'Action not defined for class ' . __CLASS__ );
79
+            }
80
+            add_action( $this->action, array(
81
+                $this,
82
+                'launch',
83
+            ), (int) $this->priority, (int) $this->argument_count );
84
+            if ( $auth_level & self::LOGGED_IN ) {
85
+                add_action( "admin_post_wp_async_$this->action", array(
86
+                    $this,
87
+                    'handle_postback',
88
+                ) );
89
+            }
90
+            if ( $auth_level & self::LOGGED_OUT ) {
91
+                add_action( "admin_post_nopriv_wp_async_$this->action", array(
92
+                    $this,
93
+                    'handle_postback',
94
+                ) );
95
+            }
96
+        }
97
+
98
+        /**
99
+         * Add the shutdown action for launching the real postback if we don't
100
+         * get an exception thrown by prepare_data().
101
+         *
102
+         * @uses func_get_args() To grab any arguments passed by the action
103
+         */
104
+        public function launch() {
105
+            $data = func_get_args();
106
+            try {
107
+                $data = $this->prepare_data( $data );
108
+            } catch ( Exception $e ) {
109
+                return;
110
+            }
111
+
112
+            $data['action'] = "wp_async_$this->action";
113
+            $data['_nonce'] = $this->create_async_nonce();
114
+
115
+            $this->_body_data = $data;
116
+
117
+            if ( ! has_action( 'shutdown', array(
118
+                $this,
119
+                'launch_on_shutdown',
120
+            ) )
121
+            ) {
122
+                add_action( 'shutdown', array( $this, 'launch_on_shutdown' ) );
123
+            }
124
+        }
125
+
126
+        /**
127
+         * Launch the request on the WordPress shutdown hook
128
+         *
129
+         * On VIP we got into data races due to the postback sometimes completing
130
+         * faster than the data could propogate to the database server cluster.
131
+         * This made WordPress get empty data sets from the database without
132
+         * failing. On their advice, we're moving the actual firing of the async
133
+         * postback to the shutdown hook. Supposedly that will ensure that the
134
+         * data at least has time to get into the object cache.
135
+         *
136
+         * @uses $_COOKIE        To send a cookie header for async postback
137
+         * @uses apply_filters()
138
+         * @uses admin_url()
139
+         * @uses wp_remote_post()
140
+         */
141
+        public function launch_on_shutdown() {
142
+            if ( ! empty( $this->_body_data ) ) {
143
+                $cookies = array();
144
+                foreach ( $_COOKIE as $name => $value ) {
145
+                    $cookies[] = "$name=" . urlencode( is_array( $value ) ? serialize( $value ) : $value );
146
+                }
147
+
148
+                $request_args = array(
149
+                    'timeout'   => 0.01,
150
+                    'blocking'  => false,
151
+                    'sslverify' => apply_filters( 'https_local_ssl_verify', false ),
152
+                    'body'      => $this->_body_data,
153
+                    'headers'   => array(
154
+                        'cookie' => implode( '; ', $cookies ),
155
+                    ),
156
+                );
157
+
158
+                $url = admin_url( 'admin-post.php' );
159
+
160
+                wp_remote_post( $url, $request_args );
161
+            }
162
+        }
163
+
164
+        /**
165
+         * Verify the postback is valid, then fire any scheduled events.
166
+         *
167
+         * @uses $_POST['_nonce']
168
+         * @uses is_user_logged_in()
169
+         * @uses add_filter()
170
+         * @uses wp_die()
171
+         */
172
+        public function handle_postback() {
173
+            if ( isset( $_POST['_nonce'] ) && $this->verify_async_nonce( $_POST['_nonce'] ) ) {
174
+                if ( ! is_user_logged_in() ) {
175
+                    $this->action = "nopriv_$this->action";
176
+                }
177
+                $this->run_action();
178
+            }
179
+
180
+            add_filter( 'wp_die_handler', function () {
181
+                die();
182
+            } );
183
+            wp_die();
184
+        }
185
+
186
+        /**
187
+         * Create a random, one time use token.
188
+         *
189
+         * Based entirely on wp_create_nonce() but does not tie the nonce to the
190
+         * current logged-in user.
191
+         *
192
+         * @uses wp_nonce_tick()
193
+         * @uses wp_hash()
194
+         *
195
+         * @return string The one-time use token
196
+         */
197
+        protected function create_async_nonce() {
198
+            $action = $this->get_nonce_action();
199
+            $i      = wp_nonce_tick();
200
+
201
+            return substr( wp_hash( $i . $action . get_class( $this ), 'nonce' ), - 12, 10 );
202
+        }
203
+
204
+        /**
205
+         * Verify that the correct nonce was used within the time limit.
206
+         *
207
+         * @uses wp_nonce_tick()
208
+         * @uses wp_hash()
209
+         *
210
+         * @param string $nonce Nonce to be verified
211
+         *
212
+         * @return bool Whether the nonce check passed or failed
213
+         */
214
+        protected function verify_async_nonce( $nonce ) {
215
+            $action = $this->get_nonce_action();
216
+            $i      = wp_nonce_tick();
217
+
218
+            // Nonce generated 0-12 hours ago
219
+            if ( substr( wp_hash( $i . $action . get_class( $this ), 'nonce' ), - 12, 10 ) == $nonce ) {
220
+                return 1;
221
+            }
222
+
223
+            // Nonce generated 12-24 hours ago
224
+            if ( substr( wp_hash( ( $i - 1 ) . $action . get_class( $this ), 'nonce' ), - 12, 10 ) == $nonce ) {
225
+                return 2;
226
+            }
227
+
228
+            // Invalid nonce
229
+            return false;
230
+        }
231
+
232
+        /**
233
+         * Get a nonce action based on the $action property of the class
234
+         *
235
+         * @return string The nonce action for the current instance
236
+         */
237
+        protected function get_nonce_action() {
238
+            $action = $this->action;
239
+            if ( substr( $action, 0, 7 ) === 'nopriv_' ) {
240
+                $action = substr( $action, 7 );
241
+            }
242
+            $action = "wp_async_$action";
243
+
244
+            return $action;
245
+        }
246
+
247
+        /**
248
+         * Prepare any data to be passed to the asynchronous postback
249
+         *
250
+         * The array this function receives will be a numerically keyed array from
251
+         * func_get_args(). It is expected that you will return an associative array
252
+         * so that the $_POST values used in the asynchronous call will make sense.
253
+         *
254
+         * The array you send back may or may not have anything to do with the data
255
+         * passed into this method. It all depends on the implementation details and
256
+         * what data is needed in the asynchronous postback.
257
+         *
258
+         * Do not set values for 'action' or '_nonce', as those will get overwritten
259
+         * later in launch().
260
+         *
261
+         * @throws Exception If the postback should not occur for any reason
262
+         *
263
+         * @param array $data The raw data received by the launch method
264
+         *
265
+         * @return array The prepared data
266
+         */
267
+        abstract protected function prepare_data( $data );
268
+
269
+        /**
270
+         * Run the do_action function for the asynchronous postback.
271
+         *
272
+         * This method needs to fetch and sanitize any and all data from the $_POST
273
+         * superglobal and provide them to the do_action call.
274
+         *
275
+         * The action should be constructed as "wp_async_task_$this->action"
276
+         */
277
+        abstract protected function run_action();
278
+
279
+    }
280 280
 
281 281
 }
282 282
 
Please login to merge, or discard this patch.
Spacing   +34 added lines, -34 removed lines patch added patch discarded remove patch
@@ -7,7 +7,7 @@  discard block
 block discarded – undo
7 7
  * License: MIT
8 8
  */
9 9
 
10
-if ( ! class_exists( 'WP_Async_Task' ) ) {
10
+if ( ! class_exists('WP_Async_Task')) {
11 11
 	abstract class WP_Async_Task {
12 12
 
13 13
 		/**
@@ -73,25 +73,25 @@  discard block
 block discarded – undo
73 73
 		 *
74 74
 		 * @param int $auth_level The authentication level to use (see above)
75 75
 		 */
76
-		public function __construct( $auth_level = self::BOTH ) {
77
-			if ( empty( $this->action ) ) {
78
-				throw new Exception( 'Action not defined for class ' . __CLASS__ );
76
+		public function __construct($auth_level = self::BOTH) {
77
+			if (empty($this->action)) {
78
+				throw new Exception('Action not defined for class '.__CLASS__);
79 79
 			}
80
-			add_action( $this->action, array(
80
+			add_action($this->action, array(
81 81
 				$this,
82 82
 				'launch',
83
-			), (int) $this->priority, (int) $this->argument_count );
84
-			if ( $auth_level & self::LOGGED_IN ) {
85
-				add_action( "admin_post_wp_async_$this->action", array(
83
+			), (int) $this->priority, (int) $this->argument_count);
84
+			if ($auth_level & self::LOGGED_IN) {
85
+				add_action("admin_post_wp_async_$this->action", array(
86 86
 					$this,
87 87
 					'handle_postback',
88
-				) );
88
+				));
89 89
 			}
90
-			if ( $auth_level & self::LOGGED_OUT ) {
91
-				add_action( "admin_post_nopriv_wp_async_$this->action", array(
90
+			if ($auth_level & self::LOGGED_OUT) {
91
+				add_action("admin_post_nopriv_wp_async_$this->action", array(
92 92
 					$this,
93 93
 					'handle_postback',
94
-				) );
94
+				));
95 95
 			}
96 96
 		}
97 97
 
@@ -104,8 +104,8 @@  discard block
 block discarded – undo
104 104
 		public function launch() {
105 105
 			$data = func_get_args();
106 106
 			try {
107
-				$data = $this->prepare_data( $data );
108
-			} catch ( Exception $e ) {
107
+				$data = $this->prepare_data($data);
108
+			} catch (Exception $e) {
109 109
 				return;
110 110
 			}
111 111
 
@@ -114,12 +114,12 @@  discard block
 block discarded – undo
114 114
 
115 115
 			$this->_body_data = $data;
116 116
 
117
-			if ( ! has_action( 'shutdown', array(
117
+			if ( ! has_action('shutdown', array(
118 118
 				$this,
119 119
 				'launch_on_shutdown',
120
-			) )
120
+			))
121 121
 			) {
122
-				add_action( 'shutdown', array( $this, 'launch_on_shutdown' ) );
122
+				add_action('shutdown', array($this, 'launch_on_shutdown'));
123 123
 			}
124 124
 		}
125 125
 
@@ -139,25 +139,25 @@  discard block
 block discarded – undo
139 139
 		 * @uses wp_remote_post()
140 140
 		 */
141 141
 		public function launch_on_shutdown() {
142
-			if ( ! empty( $this->_body_data ) ) {
142
+			if ( ! empty($this->_body_data)) {
143 143
 				$cookies = array();
144
-				foreach ( $_COOKIE as $name => $value ) {
145
-					$cookies[] = "$name=" . urlencode( is_array( $value ) ? serialize( $value ) : $value );
144
+				foreach ($_COOKIE as $name => $value) {
145
+					$cookies[] = "$name=".urlencode(is_array($value) ? serialize($value) : $value);
146 146
 				}
147 147
 
148 148
 				$request_args = array(
149 149
 					'timeout'   => 0.01,
150 150
 					'blocking'  => false,
151
-					'sslverify' => apply_filters( 'https_local_ssl_verify', false ),
151
+					'sslverify' => apply_filters('https_local_ssl_verify', false),
152 152
 					'body'      => $this->_body_data,
153 153
 					'headers'   => array(
154
-						'cookie' => implode( '; ', $cookies ),
154
+						'cookie' => implode('; ', $cookies),
155 155
 					),
156 156
 				);
157 157
 
158
-				$url = admin_url( 'admin-post.php' );
158
+				$url = admin_url('admin-post.php');
159 159
 
160
-				wp_remote_post( $url, $request_args );
160
+				wp_remote_post($url, $request_args);
161 161
 			}
162 162
 		}
163 163
 
@@ -170,14 +170,14 @@  discard block
 block discarded – undo
170 170
 		 * @uses wp_die()
171 171
 		 */
172 172
 		public function handle_postback() {
173
-			if ( isset( $_POST['_nonce'] ) && $this->verify_async_nonce( $_POST['_nonce'] ) ) {
174
-				if ( ! is_user_logged_in() ) {
173
+			if (isset($_POST['_nonce']) && $this->verify_async_nonce($_POST['_nonce'])) {
174
+				if ( ! is_user_logged_in()) {
175 175
 					$this->action = "nopriv_$this->action";
176 176
 				}
177 177
 				$this->run_action();
178 178
 			}
179 179
 
180
-			add_filter( 'wp_die_handler', function () {
180
+			add_filter('wp_die_handler', function() {
181 181
 				die();
182 182
 			} );
183 183
 			wp_die();
@@ -198,7 +198,7 @@  discard block
 block discarded – undo
198 198
 			$action = $this->get_nonce_action();
199 199
 			$i      = wp_nonce_tick();
200 200
 
201
-			return substr( wp_hash( $i . $action . get_class( $this ), 'nonce' ), - 12, 10 );
201
+			return substr(wp_hash($i.$action.get_class($this), 'nonce'), - 12, 10);
202 202
 		}
203 203
 
204 204
 		/**
@@ -211,17 +211,17 @@  discard block
 block discarded – undo
211 211
 		 *
212 212
 		 * @return bool Whether the nonce check passed or failed
213 213
 		 */
214
-		protected function verify_async_nonce( $nonce ) {
214
+		protected function verify_async_nonce($nonce) {
215 215
 			$action = $this->get_nonce_action();
216 216
 			$i      = wp_nonce_tick();
217 217
 
218 218
 			// Nonce generated 0-12 hours ago
219
-			if ( substr( wp_hash( $i . $action . get_class( $this ), 'nonce' ), - 12, 10 ) == $nonce ) {
219
+			if (substr(wp_hash($i.$action.get_class($this), 'nonce'), - 12, 10) == $nonce) {
220 220
 				return 1;
221 221
 			}
222 222
 
223 223
 			// Nonce generated 12-24 hours ago
224
-			if ( substr( wp_hash( ( $i - 1 ) . $action . get_class( $this ), 'nonce' ), - 12, 10 ) == $nonce ) {
224
+			if (substr(wp_hash(($i - 1).$action.get_class($this), 'nonce'), - 12, 10) == $nonce) {
225 225
 				return 2;
226 226
 			}
227 227
 
@@ -236,8 +236,8 @@  discard block
 block discarded – undo
236 236
 		 */
237 237
 		protected function get_nonce_action() {
238 238
 			$action = $this->action;
239
-			if ( substr( $action, 0, 7 ) === 'nopriv_' ) {
240
-				$action = substr( $action, 7 );
239
+			if (substr($action, 0, 7) === 'nopriv_') {
240
+				$action = substr($action, 7);
241 241
 			}
242 242
 			$action = "wp_async_$action";
243 243
 
@@ -264,7 +264,7 @@  discard block
 block discarded – undo
264 264
 		 *
265 265
 		 * @return array The prepared data
266 266
 		 */
267
-		abstract protected function prepare_data( $data );
267
+		abstract protected function prepare_data($data);
268 268
 
269 269
 		/**
270 270
 		 * 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 WP_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( "wp_async_$this->action" );
71
+        // Run the asynchronous action.
72
+        do_action( "wp_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( "wp_async_$this->action" );
72
+		do_action("wp_async_$this->action");
73 73
 
74 74
 	}
75 75
 
Please login to merge, or discard this patch.
src/includes/class-wordlift-content-filter-service.php 2 patches
Indentation   +156 added lines, -156 removed lines patch added patch discarded remove patch
@@ -18,161 +18,161 @@
 block discarded – undo
18 18
  */
19 19
 class Wordlift_Content_Filter_Service {
20 20
 
21
-	/**
22
-	 * The pattern to find entities in text.
23
-	 *
24
-	 * @since 3.8.0
25
-	 */
26
-	const PATTERN = '/<(\\w+)[^<]*class="([^"]*)"\\sitemid=\"([^"]+)\"[^>]*>([^<]*)<\\/\\1>/i';
27
-
28
-	/**
29
-	 * A {@link Wordlift_Entity_Service} instance.
30
-	 *
31
-	 * @since  3.8.0
32
-	 * @access private
33
-	 * @var \Wordlift_Entity_Service $entity_service A {@link Wordlift_Entity_Service} instance.
34
-	 */
35
-	private $entity_service;
36
-
37
-	/**
38
-	 * The {@link Wordlift_Configuration_Service} instance.
39
-	 *
40
-	 * @since  3.13.0
41
-	 * @access private
42
-	 * @var \Wordlift_Configuration_Service $configuration_service The {@link Wordlift_Configuration_Service} instance.
43
-	 */
44
-	private $configuration_service;
45
-
46
-	/**
47
-	 * The `link by default` setting.
48
-	 *
49
-	 * @since  3.13.0
50
-	 * @access private
51
-	 * @var bool True if link by default is enabled otherwise false.
52
-	 */
53
-	private $is_link_by_default;
54
-
55
-	/**
56
-	 * The {@link Wordlift_Content_Filter_Service} singleton instance.
57
-	 *
58
-	 * @since  3.14.2
59
-	 * @access private
60
-	 * @var \Wordlift_Content_Filter_Service $instance The {@link Wordlift_Content_Filter_Service} singleton instance.
61
-	 */
62
-	private static $instance;
63
-
64
-	/**
65
-	 * Create a {@link Wordlift_Content_Filter_Service} instance.
66
-	 *
67
-	 * @since 3.8.0
68
-	 *
69
-	 * @param \Wordlift_Entity_Service        $entity_service        The {@link Wordlift_Entity_Service} instance.
70
-	 * @param \Wordlift_Configuration_Service $configuration_service The {@link Wordlift_Configuration_Service} instance.
71
-	 */
72
-	public function __construct( $entity_service, $configuration_service ) {
73
-
74
-		$this->entity_service        = $entity_service;
75
-		$this->configuration_service = $configuration_service;
76
-
77
-		self::$instance = $this;
78
-
79
-	}
80
-
81
-	/**
82
-	 * Get the {@link Wordlift_Content_Filter_Service} singleton instance.
83
-	 *
84
-	 * @since 3.14.2
85
-	 * @return \Wordlift_Content_Filter_Service The {@link Wordlift_Content_Filter_Service} singleton instance.
86
-	 */
87
-	public static function get_instance() {
88
-
89
-		return self::$instance;
90
-	}
91
-
92
-	/**
93
-	 * Mangle the content by adding links to the entity pages. This function is
94
-	 * hooked to the 'the_content' WP's filter.
95
-	 *
96
-	 * @since 3.8.0
97
-	 *
98
-	 * @param string $content The content being filtered.
99
-	 *
100
-	 * @return string The filtered content.
101
-	 */
102
-	public function the_content( $content ) {
103
-
104
-		// Preload the `link by default` setting.
105
-		$this->is_link_by_default = $this->configuration_service->is_link_by_default();
106
-
107
-		// Replace each match of the entity tag with the entity link. If an error
108
-		// occurs fail silently returning the original content.
109
-		return preg_replace_callback( self::PATTERN, array(
110
-			$this,
111
-			'link',
112
-		), $content ) ?: $content;
113
-	}
114
-
115
-	/**
116
-	 * Get the entity match and replace it with a page link.
117
-	 *
118
-	 * @since 3.8.0
119
-	 *
120
-	 * @param array $matches An array of matches.
121
-	 *
122
-	 * @return string The replaced text with the link to the entity page.
123
-	 */
124
-	private function link( $matches ) {
125
-
126
-		// Get the entity itemid URI and label.
127
-		$css_class = $matches[2];
128
-		$uri       = $matches[3];
129
-		$label     = $matches[4];
130
-
131
-		// Get the entity post by URI.
132
-		if ( null === ( $post = $this->entity_service->get_entity_post_by_uri( $uri ) ) ) {
133
-
134
-			// If the entity post is not found return the label w/o the markup
135
-			// around it.
136
-			//
137
-			// See https://github.com/insideout10/wordlift-plugin/issues/461
138
-			return $label;
139
-		}
140
-
141
-		$no_link = - 1 < strpos( $css_class, 'wl-no-link' );
142
-		$link    = - 1 < strpos( $css_class, 'wl-link' );
143
-
144
-		// Don't link if links are disabled and the entity is not link or the
145
-		// entity is do not link.
146
-		$dont_link = ( ! $this->is_link_by_default && ! $link ) || $no_link;
147
-
148
-		// Return the label if it's don't link.
149
-		if ( $dont_link ) {
150
-			return $label;
151
-		}
152
-
153
-		// Get the link.
154
-		$href = get_permalink( $post );
155
-
156
-		// Return the link.
157
-		return "<a class='wl-entity-page-link' href='$href'>$label</a>";
158
-	}
159
-
160
-	/**
161
-	 * Get the entity URIs (configured in the `itemid` attribute) contained in
162
-	 * the provided content.
163
-	 *
164
-	 * @since 3.14.2
165
-	 *
166
-	 * @param string $content The content.
167
-	 *
168
-	 * @return array An array of URIs.
169
-	 */
170
-	public function get_entity_uris( $content ) {
171
-
172
-		$matches = array();
173
-		preg_match_all( Wordlift_Content_Filter_Service::PATTERN, $content, $matches );
174
-
175
-		return array_unique( $matches[3] );
176
-	}
21
+    /**
22
+     * The pattern to find entities in text.
23
+     *
24
+     * @since 3.8.0
25
+     */
26
+    const PATTERN = '/<(\\w+)[^<]*class="([^"]*)"\\sitemid=\"([^"]+)\"[^>]*>([^<]*)<\\/\\1>/i';
27
+
28
+    /**
29
+     * A {@link Wordlift_Entity_Service} instance.
30
+     *
31
+     * @since  3.8.0
32
+     * @access private
33
+     * @var \Wordlift_Entity_Service $entity_service A {@link Wordlift_Entity_Service} instance.
34
+     */
35
+    private $entity_service;
36
+
37
+    /**
38
+     * The {@link Wordlift_Configuration_Service} instance.
39
+     *
40
+     * @since  3.13.0
41
+     * @access private
42
+     * @var \Wordlift_Configuration_Service $configuration_service The {@link Wordlift_Configuration_Service} instance.
43
+     */
44
+    private $configuration_service;
45
+
46
+    /**
47
+     * The `link by default` setting.
48
+     *
49
+     * @since  3.13.0
50
+     * @access private
51
+     * @var bool True if link by default is enabled otherwise false.
52
+     */
53
+    private $is_link_by_default;
54
+
55
+    /**
56
+     * The {@link Wordlift_Content_Filter_Service} singleton instance.
57
+     *
58
+     * @since  3.14.2
59
+     * @access private
60
+     * @var \Wordlift_Content_Filter_Service $instance The {@link Wordlift_Content_Filter_Service} singleton instance.
61
+     */
62
+    private static $instance;
63
+
64
+    /**
65
+     * Create a {@link Wordlift_Content_Filter_Service} instance.
66
+     *
67
+     * @since 3.8.0
68
+     *
69
+     * @param \Wordlift_Entity_Service        $entity_service        The {@link Wordlift_Entity_Service} instance.
70
+     * @param \Wordlift_Configuration_Service $configuration_service The {@link Wordlift_Configuration_Service} instance.
71
+     */
72
+    public function __construct( $entity_service, $configuration_service ) {
73
+
74
+        $this->entity_service        = $entity_service;
75
+        $this->configuration_service = $configuration_service;
76
+
77
+        self::$instance = $this;
78
+
79
+    }
80
+
81
+    /**
82
+     * Get the {@link Wordlift_Content_Filter_Service} singleton instance.
83
+     *
84
+     * @since 3.14.2
85
+     * @return \Wordlift_Content_Filter_Service The {@link Wordlift_Content_Filter_Service} singleton instance.
86
+     */
87
+    public static function get_instance() {
88
+
89
+        return self::$instance;
90
+    }
91
+
92
+    /**
93
+     * Mangle the content by adding links to the entity pages. This function is
94
+     * hooked to the 'the_content' WP's filter.
95
+     *
96
+     * @since 3.8.0
97
+     *
98
+     * @param string $content The content being filtered.
99
+     *
100
+     * @return string The filtered content.
101
+     */
102
+    public function the_content( $content ) {
103
+
104
+        // Preload the `link by default` setting.
105
+        $this->is_link_by_default = $this->configuration_service->is_link_by_default();
106
+
107
+        // Replace each match of the entity tag with the entity link. If an error
108
+        // occurs fail silently returning the original content.
109
+        return preg_replace_callback( self::PATTERN, array(
110
+            $this,
111
+            'link',
112
+        ), $content ) ?: $content;
113
+    }
114
+
115
+    /**
116
+     * Get the entity match and replace it with a page link.
117
+     *
118
+     * @since 3.8.0
119
+     *
120
+     * @param array $matches An array of matches.
121
+     *
122
+     * @return string The replaced text with the link to the entity page.
123
+     */
124
+    private function link( $matches ) {
125
+
126
+        // Get the entity itemid URI and label.
127
+        $css_class = $matches[2];
128
+        $uri       = $matches[3];
129
+        $label     = $matches[4];
130
+
131
+        // Get the entity post by URI.
132
+        if ( null === ( $post = $this->entity_service->get_entity_post_by_uri( $uri ) ) ) {
133
+
134
+            // If the entity post is not found return the label w/o the markup
135
+            // around it.
136
+            //
137
+            // See https://github.com/insideout10/wordlift-plugin/issues/461
138
+            return $label;
139
+        }
140
+
141
+        $no_link = - 1 < strpos( $css_class, 'wl-no-link' );
142
+        $link    = - 1 < strpos( $css_class, 'wl-link' );
143
+
144
+        // Don't link if links are disabled and the entity is not link or the
145
+        // entity is do not link.
146
+        $dont_link = ( ! $this->is_link_by_default && ! $link ) || $no_link;
147
+
148
+        // Return the label if it's don't link.
149
+        if ( $dont_link ) {
150
+            return $label;
151
+        }
152
+
153
+        // Get the link.
154
+        $href = get_permalink( $post );
155
+
156
+        // Return the link.
157
+        return "<a class='wl-entity-page-link' href='$href'>$label</a>";
158
+    }
159
+
160
+    /**
161
+     * Get the entity URIs (configured in the `itemid` attribute) contained in
162
+     * the provided content.
163
+     *
164
+     * @since 3.14.2
165
+     *
166
+     * @param string $content The content.
167
+     *
168
+     * @return array An array of URIs.
169
+     */
170
+    public function get_entity_uris( $content ) {
171
+
172
+        $matches = array();
173
+        preg_match_all( Wordlift_Content_Filter_Service::PATTERN, $content, $matches );
174
+
175
+        return array_unique( $matches[3] );
176
+    }
177 177
 
178 178
 }
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -69,7 +69,7 @@  discard block
 block discarded – undo
69 69
 	 * @param \Wordlift_Entity_Service        $entity_service        The {@link Wordlift_Entity_Service} instance.
70 70
 	 * @param \Wordlift_Configuration_Service $configuration_service The {@link Wordlift_Configuration_Service} instance.
71 71
 	 */
72
-	public function __construct( $entity_service, $configuration_service ) {
72
+	public function __construct($entity_service, $configuration_service) {
73 73
 
74 74
 		$this->entity_service        = $entity_service;
75 75
 		$this->configuration_service = $configuration_service;
@@ -99,17 +99,17 @@  discard block
 block discarded – undo
99 99
 	 *
100 100
 	 * @return string The filtered content.
101 101
 	 */
102
-	public function the_content( $content ) {
102
+	public function the_content($content) {
103 103
 
104 104
 		// Preload the `link by default` setting.
105 105
 		$this->is_link_by_default = $this->configuration_service->is_link_by_default();
106 106
 
107 107
 		// Replace each match of the entity tag with the entity link. If an error
108 108
 		// occurs fail silently returning the original content.
109
-		return preg_replace_callback( self::PATTERN, array(
109
+		return preg_replace_callback(self::PATTERN, array(
110 110
 			$this,
111 111
 			'link',
112
-		), $content ) ?: $content;
112
+		), $content) ?: $content;
113 113
 	}
114 114
 
115 115
 	/**
@@ -121,7 +121,7 @@  discard block
 block discarded – undo
121 121
 	 *
122 122
 	 * @return string The replaced text with the link to the entity page.
123 123
 	 */
124
-	private function link( $matches ) {
124
+	private function link($matches) {
125 125
 
126 126
 		// Get the entity itemid URI and label.
127 127
 		$css_class = $matches[2];
@@ -129,7 +129,7 @@  discard block
 block discarded – undo
129 129
 		$label     = $matches[4];
130 130
 
131 131
 		// Get the entity post by URI.
132
-		if ( null === ( $post = $this->entity_service->get_entity_post_by_uri( $uri ) ) ) {
132
+		if (null === ($post = $this->entity_service->get_entity_post_by_uri($uri))) {
133 133
 
134 134
 			// If the entity post is not found return the label w/o the markup
135 135
 			// around it.
@@ -138,20 +138,20 @@  discard block
 block discarded – undo
138 138
 			return $label;
139 139
 		}
140 140
 
141
-		$no_link = - 1 < strpos( $css_class, 'wl-no-link' );
142
-		$link    = - 1 < strpos( $css_class, 'wl-link' );
141
+		$no_link = - 1 < strpos($css_class, 'wl-no-link');
142
+		$link    = - 1 < strpos($css_class, 'wl-link');
143 143
 
144 144
 		// Don't link if links are disabled and the entity is not link or the
145 145
 		// entity is do not link.
146
-		$dont_link = ( ! $this->is_link_by_default && ! $link ) || $no_link;
146
+		$dont_link = ( ! $this->is_link_by_default && ! $link) || $no_link;
147 147
 
148 148
 		// Return the label if it's don't link.
149
-		if ( $dont_link ) {
149
+		if ($dont_link) {
150 150
 			return $label;
151 151
 		}
152 152
 
153 153
 		// Get the link.
154
-		$href = get_permalink( $post );
154
+		$href = get_permalink($post);
155 155
 
156 156
 		// Return the link.
157 157
 		return "<a class='wl-entity-page-link' href='$href'>$label</a>";
@@ -167,12 +167,12 @@  discard block
 block discarded – undo
167 167
 	 *
168 168
 	 * @return array An array of URIs.
169 169
 	 */
170
-	public function get_entity_uris( $content ) {
170
+	public function get_entity_uris($content) {
171 171
 
172 172
 		$matches = array();
173
-		preg_match_all( Wordlift_Content_Filter_Service::PATTERN, $content, $matches );
173
+		preg_match_all(Wordlift_Content_Filter_Service::PATTERN, $content, $matches);
174 174
 
175
-		return array_unique( $matches[3] );
175
+		return array_unique($matches[3]);
176 176
 	}
177 177
 
178 178
 }
Please login to merge, or discard this patch.
src/includes/class-wordlift-batch-analysis-adapter.php 2 patches
Indentation   +54 added lines, -54 removed lines patch added patch discarded remove patch
@@ -16,87 +16,87 @@
 block discarded – undo
16 16
  */
17 17
 class Wordlift_Batch_Analysis_Adapter {
18 18
 
19
-	/**
20
-	 * @var Wordlift_Batch_Analysis_Service
21
-	 */
22
-	private $batch_analysis_service;
19
+    /**
20
+     * @var Wordlift_Batch_Analysis_Service
21
+     */
22
+    private $batch_analysis_service;
23 23
 
24 24
 
25
-	/**
26
-	 * Wordlift_Batch_Analysis_Adapter constructor.
27
-	 *
28
-	 * @since 3.14.2
29
-	 *
30
-	 * @param \Wordlift_Batch_Analysis_Service $batch_analysis_service
31
-	 */
32
-	public function __construct( $batch_analysis_service ) {
25
+    /**
26
+     * Wordlift_Batch_Analysis_Adapter constructor.
27
+     *
28
+     * @since 3.14.2
29
+     *
30
+     * @param \Wordlift_Batch_Analysis_Service $batch_analysis_service
31
+     */
32
+    public function __construct( $batch_analysis_service ) {
33 33
 
34
-		$this->batch_analysis_service = $batch_analysis_service;
34
+        $this->batch_analysis_service = $batch_analysis_service;
35 35
 
36
-	}
36
+    }
37 37
 
38
-	public function submit_auto_selected_posts() {
38
+    public function submit_auto_selected_posts() {
39 39
 
40
-		if ( ! isset( $_REQUEST['link'] ) ) {
41
-			wp_die( 'The `link` parameter is required.' );
42
-		}
40
+        if ( ! isset( $_REQUEST['link'] ) ) {
41
+            wp_die( 'The `link` parameter is required.' );
42
+        }
43 43
 
44
-		$count = $this->batch_analysis_service->submit_auto_selected_posts( $_REQUEST['link'] );
44
+        $count = $this->batch_analysis_service->submit_auto_selected_posts( $_REQUEST['link'] );
45 45
 
46
-		// Clear any buffer.
47
-		ob_clean();
46
+        // Clear any buffer.
47
+        ob_clean();
48 48
 
49
-		// Send the response.
50
-		wp_send_json_success( array( 'count' => $count ) );
49
+        // Send the response.
50
+        wp_send_json_success( array( 'count' => $count ) );
51 51
 
52
-	}
52
+    }
53 53
 
54
-	public function submit() {
54
+    public function submit() {
55 55
 
56
-		if ( ! isset( $_REQUEST['link'] ) || ! isset( $_REQUEST['post'] ) ) {
57
-			wp_die( 'The `link` and `post` parameters are required.' );
58
-		}
56
+        if ( ! isset( $_REQUEST['link'] ) || ! isset( $_REQUEST['post'] ) ) {
57
+            wp_die( 'The `link` and `post` parameters are required.' );
58
+        }
59 59
 
60
-		$count = $this->batch_analysis_service->submit( (array) $_REQUEST['post'], $_REQUEST['link'] );
60
+        $count = $this->batch_analysis_service->submit( (array) $_REQUEST['post'], $_REQUEST['link'] );
61 61
 
62
-		// Clear any buffer.
63
-		ob_clean();
62
+        // Clear any buffer.
63
+        ob_clean();
64 64
 
65
-		// Send the response.
66
-		wp_send_json_success( array( 'count' => $count ) );
65
+        // Send the response.
66
+        wp_send_json_success( array( 'count' => $count ) );
67 67
 
68
-	}
68
+    }
69 69
 
70
-	public function cancel() {
70
+    public function cancel() {
71 71
 
72
-		if ( ! isset( $_REQUEST['post'] ) ) {
73
-			wp_die( 'The `post` parameter is required.' );
74
-		}
72
+        if ( ! isset( $_REQUEST['post'] ) ) {
73
+            wp_die( 'The `post` parameter is required.' );
74
+        }
75 75
 
76
-		$count = $this->batch_analysis_service->cancel( (array) $_REQUEST['post'] );
76
+        $count = $this->batch_analysis_service->cancel( (array) $_REQUEST['post'] );
77 77
 
78
-		// Clear any buffer.
79
-		ob_clean();
78
+        // Clear any buffer.
79
+        ob_clean();
80 80
 
81
-		// Send the response.
82
-		wp_send_json_success( array( 'count' => $count ) );
81
+        // Send the response.
82
+        wp_send_json_success( array( 'count' => $count ) );
83 83
 
84
-	}
84
+    }
85 85
 
86
-	public function clear_warning() {
86
+    public function clear_warning() {
87 87
 
88
-		if ( ! isset( $_REQUEST['post'] ) ) {
89
-			wp_die( 'The `post` parameter is required.' );
90
-		}
88
+        if ( ! isset( $_REQUEST['post'] ) ) {
89
+            wp_die( 'The `post` parameter is required.' );
90
+        }
91 91
 
92
-		$this->batch_analysis_service->clear_warning( (array) $_REQUEST['post'] );
92
+        $this->batch_analysis_service->clear_warning( (array) $_REQUEST['post'] );
93 93
 
94
-		// Clear any buffer.
95
-		ob_clean();
94
+        // Clear any buffer.
95
+        ob_clean();
96 96
 
97
-		// Send the response.
98
-		wp_send_json_success();
97
+        // Send the response.
98
+        wp_send_json_success();
99 99
 
100
-	}
100
+    }
101 101
 
102 102
 }
Please login to merge, or discard this patch.
Spacing   +16 added lines, -16 removed lines patch added patch discarded remove patch
@@ -29,7 +29,7 @@  discard block
 block discarded – undo
29 29
 	 *
30 30
 	 * @param \Wordlift_Batch_Analysis_Service $batch_analysis_service
31 31
 	 */
32
-	public function __construct( $batch_analysis_service ) {
32
+	public function __construct($batch_analysis_service) {
33 33
 
34 34
 		$this->batch_analysis_service = $batch_analysis_service;
35 35
 
@@ -37,59 +37,59 @@  discard block
 block discarded – undo
37 37
 
38 38
 	public function submit_auto_selected_posts() {
39 39
 
40
-		if ( ! isset( $_REQUEST['link'] ) ) {
41
-			wp_die( 'The `link` parameter is required.' );
40
+		if ( ! isset($_REQUEST['link'])) {
41
+			wp_die('The `link` parameter is required.');
42 42
 		}
43 43
 
44
-		$count = $this->batch_analysis_service->submit_auto_selected_posts( $_REQUEST['link'] );
44
+		$count = $this->batch_analysis_service->submit_auto_selected_posts($_REQUEST['link']);
45 45
 
46 46
 		// Clear any buffer.
47 47
 		ob_clean();
48 48
 
49 49
 		// Send the response.
50
-		wp_send_json_success( array( 'count' => $count ) );
50
+		wp_send_json_success(array('count' => $count));
51 51
 
52 52
 	}
53 53
 
54 54
 	public function submit() {
55 55
 
56
-		if ( ! isset( $_REQUEST['link'] ) || ! isset( $_REQUEST['post'] ) ) {
57
-			wp_die( 'The `link` and `post` parameters are required.' );
56
+		if ( ! isset($_REQUEST['link']) || ! isset($_REQUEST['post'])) {
57
+			wp_die('The `link` and `post` parameters are required.');
58 58
 		}
59 59
 
60
-		$count = $this->batch_analysis_service->submit( (array) $_REQUEST['post'], $_REQUEST['link'] );
60
+		$count = $this->batch_analysis_service->submit((array) $_REQUEST['post'], $_REQUEST['link']);
61 61
 
62 62
 		// Clear any buffer.
63 63
 		ob_clean();
64 64
 
65 65
 		// Send the response.
66
-		wp_send_json_success( array( 'count' => $count ) );
66
+		wp_send_json_success(array('count' => $count));
67 67
 
68 68
 	}
69 69
 
70 70
 	public function cancel() {
71 71
 
72
-		if ( ! isset( $_REQUEST['post'] ) ) {
73
-			wp_die( 'The `post` parameter is required.' );
72
+		if ( ! isset($_REQUEST['post'])) {
73
+			wp_die('The `post` parameter is required.');
74 74
 		}
75 75
 
76
-		$count = $this->batch_analysis_service->cancel( (array) $_REQUEST['post'] );
76
+		$count = $this->batch_analysis_service->cancel((array) $_REQUEST['post']);
77 77
 
78 78
 		// Clear any buffer.
79 79
 		ob_clean();
80 80
 
81 81
 		// Send the response.
82
-		wp_send_json_success( array( 'count' => $count ) );
82
+		wp_send_json_success(array('count' => $count));
83 83
 
84 84
 	}
85 85
 
86 86
 	public function clear_warning() {
87 87
 
88
-		if ( ! isset( $_REQUEST['post'] ) ) {
89
-			wp_die( 'The `post` parameter is required.' );
88
+		if ( ! isset($_REQUEST['post'])) {
89
+			wp_die('The `post` parameter is required.');
90 90
 		}
91 91
 
92
-		$this->batch_analysis_service->clear_warning( (array) $_REQUEST['post'] );
92
+		$this->batch_analysis_service->clear_warning((array) $_REQUEST['post']);
93 93
 
94 94
 		// Clear any buffer.
95 95
 		ob_clean();
Please login to merge, or discard this patch.
src/includes/class-wordlift-batch-analysis-service.php 2 patches
Indentation   +603 added lines, -603 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( 'wp_async_wl_batch_analysis_request', array(
171
-			$this,
172
-			'request',
173
-		) );
174
-		add_action( 'wp_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( 'wp_async_wl_batch_analysis_request', array(
171
+            $this,
172
+            'request',
173
+        ) );
174
+        add_action( 'wp_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,492 +218,492 @@  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 the provided list of {@link WP_Post}s' ids for Batch Analysis.
264
-	 *
265
-	 * @since 3.14.2
266
-	 *
267
-	 * @param int|array $post_ids A single {@link WP_Post}'s id or an array of
268
-	 *                            {@link WP_Post}s' ids.
269
-	 * @param string    $link     The link setting.
270
-	 *
271
-	 * @return int The number of submitted {@link WP_Post}s or false on error.
272
-	 */
273
-	public function submit( $post_ids, $link ) {
274
-		global $wpdb;
275
-
276
-		// Submit the posts/pages and return the number of affected results.
277
-		// We're using a SQL query here because we could have potentially
278
-		// thousands of rows.
279
-		$count = $wpdb->query(
280
-			$this->get_sql( $link ) .
281
-			' AND p.ID IN ( ' . implode( ',', wp_parse_id_list( $post_ids ) ) . ' )'
282
-		);
283
-
284
-		// Request Batch Analysis (the operation is handled asynchronously).
285
-		do_action( 'wl_batch_analysis_request' );
286
-
287
-		// Divide the count by 3 to get the number of posts/pages queued.
288
-		return $count / 3;
289
-	}
290
-
291
-	/**
292
-	 * Cancel the Batch Analysis request for the specified {@link WP_Post}s.
293
-	 *
294
-	 * @since 3.14.2
295
-	 *
296
-	 * @param int|array $post_ids A single {@link WP_Post}'s id or an array of
297
-	 *                            {@link WP_Post}s' ids.
298
-	 *
299
-	 * @return false|int The number of cancelled {@link WP_Post}s or false on
300
-	 *                   error.
301
-	 */
302
-	public function cancel( $post_ids ) {
303
-		global $wpdb;
304
-
305
-		return $wpdb->query( $wpdb->prepare(
306
-			"
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 the provided list of {@link WP_Post}s' ids for Batch Analysis.
264
+     *
265
+     * @since 3.14.2
266
+     *
267
+     * @param int|array $post_ids A single {@link WP_Post}'s id or an array of
268
+     *                            {@link WP_Post}s' ids.
269
+     * @param string    $link     The link setting.
270
+     *
271
+     * @return int The number of submitted {@link WP_Post}s or false on error.
272
+     */
273
+    public function submit( $post_ids, $link ) {
274
+        global $wpdb;
275
+
276
+        // Submit the posts/pages and return the number of affected results.
277
+        // We're using a SQL query here because we could have potentially
278
+        // thousands of rows.
279
+        $count = $wpdb->query(
280
+            $this->get_sql( $link ) .
281
+            ' AND p.ID IN ( ' . implode( ',', wp_parse_id_list( $post_ids ) ) . ' )'
282
+        );
283
+
284
+        // Request Batch Analysis (the operation is handled asynchronously).
285
+        do_action( 'wl_batch_analysis_request' );
286
+
287
+        // Divide the count by 3 to get the number of posts/pages queued.
288
+        return $count / 3;
289
+    }
290
+
291
+    /**
292
+     * Cancel the Batch Analysis request for the specified {@link WP_Post}s.
293
+     *
294
+     * @since 3.14.2
295
+     *
296
+     * @param int|array $post_ids A single {@link WP_Post}'s id or an array of
297
+     *                            {@link WP_Post}s' ids.
298
+     *
299
+     * @return false|int The number of cancelled {@link WP_Post}s or false on
300
+     *                   error.
301
+     */
302
+    public function cancel( $post_ids ) {
303
+        global $wpdb;
304
+
305
+        return $wpdb->query( $wpdb->prepare(
306
+            "
307 307
 			DELETE FROM $wpdb->postmeta
308 308
 			WHERE meta_key = %s
309 309
 				AND meta_value = %s
310 310
 				AND post_id IN ( " . implode( ',', wp_parse_id_list( $post_ids ) ) . " )
311 311
 			",
312
-			self::STATE_META_KEY,
313
-			self::STATE_REQUEST
314
-		) );
312
+            self::STATE_META_KEY,
313
+            self::STATE_REQUEST
314
+        ) );
315 315
 
316
-	}
316
+    }
317 317
 
318
-	/**
319
-	 * Request the batch analysis for submitted posts.
320
-	 *
321
-	 * @since 3.14.2
322
-	 */
323
-	public function request() {
318
+    /**
319
+     * Request the batch analysis for submitted posts.
320
+     *
321
+     * @since 3.14.2
322
+     */
323
+    public function request() {
324 324
 
325
-		$this->log->debug( "Requesting analysis..." );
325
+        $this->log->debug( "Requesting analysis..." );
326 326
 
327
-		// By default 5 posts of any post type are returned.
328
-		$posts = get_posts( array(
329
-			'fields'     => 'ids',
330
-			'meta_key'   => self::STATE_META_KEY,
331
-			'meta_value' => self::STATE_SUBMIT,
332
-			'orderby'    => 'ID',
333
-		) );
327
+        // By default 5 posts of any post type are returned.
328
+        $posts = get_posts( array(
329
+            'fields'     => 'ids',
330
+            'meta_key'   => self::STATE_META_KEY,
331
+            'meta_value' => self::STATE_SUBMIT,
332
+            'orderby'    => 'ID',
333
+        ) );
334 334
 
335
-		// Bail out if there are no submitted posts.
336
-		if ( empty( $posts ) ) {
337
-			$this->log->debug( 'No posts to submit found, checking for completed requests...' );
335
+        // Bail out if there are no submitted posts.
336
+        if ( empty( $posts ) ) {
337
+            $this->log->debug( 'No posts to submit found, checking for completed requests...' );
338 338
 
339
-			do_action( 'wl_batch_analysis_complete' );
339
+            do_action( 'wl_batch_analysis_complete' );
340 340
 
341
-			return;
342
-		}
341
+            return;
342
+        }
343 343
 
344
-		// Send a request for each post.
345
-		foreach ( $posts as $id ) {
346
-			$this->log->debug( "Requesting analysis for post $id..." );
344
+        // Send a request for each post.
345
+        foreach ( $posts as $id ) {
346
+            $this->log->debug( "Requesting analysis for post $id..." );
347 347
 
348
-			// Change the state to `REQUEST`.
349
-			$this->set_state( $id, self::STATE_REQUEST );
348
+            // Change the state to `REQUEST`.
349
+            $this->set_state( $id, self::STATE_REQUEST );
350 350
 
351
-			// Send the actual request to the remote service.
352
-			$result = $this->do_request( $id );
351
+            // Send the actual request to the remote service.
352
+            $result = $this->do_request( $id );
353 353
 
354
-			$this->log->debug( "Analysis requested for post $id." );
354
+            $this->log->debug( "Analysis requested for post $id." );
355 355
 
356
-			// Set an error if we received an error.
357
-			if ( is_wp_error( $result ) ) {
358
-				$this->log->error( "Analysis request for post $id returned {$result->get_error_message()}." );
356
+            // Set an error if we received an error.
357
+            if ( is_wp_error( $result ) ) {
358
+                $this->log->error( "Analysis request for post $id returned {$result->get_error_message()}." );
359 359
 
360
-				$this->set_state( $id, self::STATE_ERROR );
361
-			}
360
+                $this->set_state( $id, self::STATE_ERROR );
361
+            }
362 362
 
363
-		}
363
+        }
364 364
 
365
-		// Call the `wl_batch_analysis_request` action again. This is going
366
-		// to be handled by the async task.
367
-		do_action( 'wl_batch_analysis_request' );
365
+        // Call the `wl_batch_analysis_request` action again. This is going
366
+        // to be handled by the async task.
367
+        do_action( 'wl_batch_analysis_request' );
368 368
 
369
-	}
369
+    }
370 370
 
371
-	/**
372
-	 * Get the results for the Batch Analysis.
373
-	 *
374
-	 * @since 3.14.2
375
-	 */
376
-	public function complete() {
371
+    /**
372
+     * Get the results for the Batch Analysis.
373
+     *
374
+     * @since 3.14.2
375
+     */
376
+    public function complete() {
377 377
 
378
-		$this->log->debug( "Requesting results..." );
378
+        $this->log->debug( "Requesting results..." );
379 379
 
380
-		// By default 5 posts of any post type are returned.
381
-		$posts = get_posts( array(
382
-			'fields'     => 'ids',
383
-			'meta_key'   => self::STATE_META_KEY,
384
-			'meta_value' => self::STATE_REQUEST,
385
-			'orderby'    => 'ID',
386
-		) );
380
+        // By default 5 posts of any post type are returned.
381
+        $posts = get_posts( array(
382
+            'fields'     => 'ids',
383
+            'meta_key'   => self::STATE_META_KEY,
384
+            'meta_value' => self::STATE_REQUEST,
385
+            'orderby'    => 'ID',
386
+        ) );
387 387
 
388
-		// Bail out if there are no submitted posts.
389
-		if ( empty( $posts ) ) {
390
-			$this->log->debug( 'No posts in request state found.' );
388
+        // Bail out if there are no submitted posts.
389
+        if ( empty( $posts ) ) {
390
+            $this->log->debug( 'No posts in request state found.' );
391 391
 
392
-			return;
393
-		}
392
+            return;
393
+        }
394 394
 
395
-		// Send a request for each post.
396
-		foreach ( $posts as $id ) {
397
-			$this->log->debug( "Requesting results for post $id..." );
395
+        // Send a request for each post.
396
+        foreach ( $posts as $id ) {
397
+            $this->log->debug( "Requesting results for post $id..." );
398 398
 
399
-			// Send the actual request to the remote service.
400
-			$response = $this->do_complete( $id );
399
+            // Send the actual request to the remote service.
400
+            $response = $this->do_complete( $id );
401 401
 
402
-			$this->log->debug( "Results requested for post $id." );
402
+            $this->log->debug( "Results requested for post $id." );
403 403
 
404
-			// Set an error if we received an error.
405
-			if ( ! is_wp_error( $response ) && isset( $response['body'] ) ) {
404
+            // Set an error if we received an error.
405
+            if ( ! is_wp_error( $response ) && isset( $response['body'] ) ) {
406 406
 
407
-				$this->log->debug( "Results received for post $id." );
407
+                $this->log->debug( "Results received for post $id." );
408 408
 
409
-				// Save the returned content as new revision.
410
-				$json = json_decode( $response['body'] );
411
-
412
-				// Continue if the content isn't set.
413
-				if ( ! isset( $json->content ) || empty( $json->content ) ) {
414
-					continue;
415
-				}
409
+                // Save the returned content as new revision.
410
+                $json = json_decode( $response['body'] );
411
+
412
+                // Continue if the content isn't set.
413
+                if ( ! isset( $json->content ) || empty( $json->content ) ) {
414
+                    continue;
415
+                }
416 416
 
417
-				$this->set_warning_based_on_content( $id, $json->content );
418
-
419
-				$content = wp_slash( $json->content );
420
-
421
-				wp_update_post( array(
422
-					'ID'           => $id,
423
-					'post_content' => $content,
424
-				) );
425
-
426
-				// Update the status.
427
-				$this->set_state( $id, self::STATE_SUCCESS );
428
-
429
-				$this->log->debug( "Post $id updated with batch analysis results." );
430
-
431
-				continue;
432
-			}
433
-
434
-			// @todo: implement a kind of timeout that sets an error if the
435
-			// results haven't been received after a long time.
436
-
437
-		}
438
-
439
-		// Call the `wl_batch_analysis_request` action again. This is going
440
-		// to be handled by the async task.
441
-		do_action( 'wl_batch_analysis_complete' );
442
-
443
-	}
444
-
445
-	/**
446
-	 * Set a warning flag on the {@link WP_Post} if its content has suspicious
447
-	 * interpolations.
448
-	 *
449
-	 * @since 3.14.2
450
-	 *
451
-	 * @param int    $post_id The {@link WP_Post}'s id.
452
-	 * @param string $content The {@link WP_Post}'s content.
453
-	 *
454
-	 * @return string The content (for chaining operations).
455
-	 */
456
-	private function set_warning_based_on_content( $post_id, $content ) {
457
-
458
-		$matches = array();
459
-
460
-		// Check for suspicious interpolations.
461
-		$warning = 0 < preg_match_all( '/\w<[a-z]+ id="urn:enhancement-[^"]+" class="[^"]+" itemid="[^"]+">/', $content, $matches )
462
-		           || 0 < preg_match_all( '/<[a-z]+ id="urn:enhancement-[^"]+" class="[^"]+" itemid="[^"]+">\s/', $content, $matches );
463
-
464
-		// Set the warning flag accordingly.
465
-		$this->set_warning( $post_id, $warning );
466
-
467
-		return $content;
468
-	}
469
-
470
-	/**
471
-	 * Clear the warning flag for the specified {@link WP_Post}s.
472
-	 *
473
-	 * @since 3.14.2
474
-	 *
475
-	 * @param int|array $post_ids A single {@link WP_Post}'s id or an array of
476
-	 *                            {@link WP_Post}s' ids.
477
-	 */
478
-	public function clear_warning( $post_ids ) {
479
-
480
-		foreach ( (array) $post_ids as $post_id ) {
481
-			delete_post_meta( $post_id, self::WARNING_META_KEY );
482
-		}
483
-
484
-	}
485
-
486
-	/**
487
-	 * Set the warning flag for the specified {@link WP_Post}.
488
-	 *
489
-	 * @since 3.14.2
490
-	 *
491
-	 * @param int  $post_id The {@link WP_Post}'s id.
492
-	 * @param bool $value   The flag's value.
493
-	 *
494
-	 * @return int|bool Meta ID if the key didn't exist, true on successful update,
495
-	 *                  false on failure.
496
-	 */
497
-	private function set_warning( $post_id, $value ) {
498
-
499
-		return update_post_meta( $post_id, self::WARNING_META_KEY, ( true === $value ? 'yes' : 'no' ) );
500
-	}
501
-
502
-	/**
503
-	 * Get the post/page batch analysis state.
504
-	 *
505
-	 * @since 3.14.2
506
-	 *
507
-	 * @param int $post_id The {@link WP_Post}'s id.
508
-	 *
509
-	 * @return int|string The post state or an empty string if not set.
510
-	 */
511
-	public function get_state( $post_id ) {
512
-
513
-		return get_post_meta( $post_id, self::STATE_META_KEY, true );
514
-	}
515
-
516
-	/**
517
-	 * Set the post/page batch analysis state.
518
-	 *
519
-	 * @since 3.14.2
520
-	 *
521
-	 * @param int $post_id The {@link WP_Post}'s id.
522
-	 * @param int $value   The new state.
523
-	 *
524
-	 * @return int|bool Meta ID if the key didn't exist, true on successful update,
525
-	 *                  false on failure.
526
-	 */
527
-	public function set_state( $post_id, $value ) {
528
-
529
-		// Update the state.
530
-		$result = update_post_meta( $post_id, self::STATE_META_KEY, $value );
531
-
532
-		// Update timestamps as required.
533
-		switch ( $value ) {
534
-
535
-			//### REQUEST state.
536
-			case self::STATE_REQUEST:
537
-				add_post_meta( $post_id, self::REQUEST_TIMESTAMP_META_KEY, current_time( 'mysql', true ) );
538
-				break;
539
-
540
-			//### SUCCESS/ERROR state.
541
-			case self::STATE_SUCCESS:
542
-			case self::STATE_ERROR:
543
-				add_post_meta( $post_id, self::COMPLETE_TIMESTAMP_META_KEY, current_time( 'mysql', true ) );
544
-				break;
545
-		}
546
-
547
-		// Finally return the result.
548
-		return $result;
549
-	}
550
-
551
-	/**
552
-	 * Get the link setting for a {@link WP_Post}.
553
-	 *
554
-	 * If there are multiple link settings, only the last one is returned.
555
-	 *
556
-	 * @since 3.14.2
557
-	 *
558
-	 * @param int $post_id The {@link WP_Post}'s id.
559
-	 *
560
-	 * @return string The link setting or `default` if not set.
561
-	 */
562
-	public function get_link( $post_id ) {
563
-
564
-		$values = get_post_meta( $post_id, self::LINK_META_KEY );
565
-
566
-		return end( $values ) ?: 'default';
567
-	}
568
-
569
-	/**
570
-	 * Get the array of post IDS waiting in the queue to start processing.
571
-	 *
572
-	 * @since 3.14.0
573
-	 *
574
-	 * @return array The waiting to be processed post ids queue.
575
-	 */
576
-	public function waiting_for_analysis() {
577
-
578
-		return get_posts( array(
579
-			'posts_per_page' => - 1,
580
-			'fields'         => 'ids',
581
-			'post_status'    => 'any',
582
-			'meta_key'       => self::STATE_META_KEY,
583
-			'meta_value'     => self::STATE_SUBMIT,
584
-			'orderby'        => 'ID',
585
-		) );
586
-	}
587
-
588
-	/**
589
-	 * Get the array of post IDS waiting for response.
590
-	 *
591
-	 * @deprecated
592
-	 * @since 3.14.0
593
-	 *
594
-	 * @return array The waiting for response post ids queue.
595
-	 */
596
-	public function waiting_for_response() {
597
-
598
-		return get_posts( array(
599
-			'posts_per_page' => - 1,
600
-			'fields'         => 'ids',
601
-			'post_status'    => 'any',
602
-			'meta_key'       => self::STATE_META_KEY,
603
-			'meta_value'     => self::STATE_REQUEST,
604
-			'orderby'        => 'ID',
605
-		) );
606
-	}
607
-
608
-	/**
609
-	 * Request the analysis for the specified {@link WP_Post}.
610
-	 *
611
-	 * @since 3.14.2
612
-	 *
613
-	 * @param int $post_id The {@link WP_Post}'s id.
614
-	 *
615
-	 * @return WP_Error|array The response or WP_Error on failure.
616
-	 */
617
-	private function do_request( $post_id ) {
618
-
619
-		// Get the post.
620
-		$post = get_post( $post_id );
621
-
622
-		// Bail out if the post isn't found.
623
-		if ( null === $post ) {
624
-			$this->log->warn( "Post $post_id not found." );
625
-
626
-			return new WP_Error( 0, "Cannot find post $post_id." );
627
-		}
628
-
629
-		// Get the link setting.
630
-		$link = $this->get_link( $post_id );
631
-
632
-		$this->log->debug( "Sending analysis request for post $post_id [ link :: $link ]..." );
633
-
634
-		// Get the batch analysis URL.
635
-		$url = $this->configuration_service->get_batch_analysis_url();
636
-
637
-		// Prepare the POST parameters.
638
-		$param = array(
639
-			'id'              => $post->ID,
640
-			'key'             => $this->configuration_service->get_key(),
641
-			'content'         => $post->post_content,
642
-			'contentLanguage' => $this->configuration_service->get_language_code(),
643
-			'version'         => $this->plugin->get_version(),
644
-			'links'           => $link,
645
-			'scope'           => 'local',
646
-		);
647
-
648
-		// Get the HTTP options.
649
-		$args = array_merge_recursive( unserialize( WL_REDLINK_API_HTTP_OPTIONS ), array(
650
-			'method'      => 'POST',
651
-			'headers'     => array(
652
-				'Accept'       => 'application/json',
653
-				'Content-type' => 'application/json; charset=UTF-8',
654
-			),
655
-			// we need to downgrade the HTTP version in this case since chunked encoding is dumping numbers in the response.
656
-			'httpversion' => '1.0',
657
-			'body'        => wp_json_encode( $param ),
658
-		) );
659
-
660
-		$this->log->debug( "Posting analysis request for post $post_id to $url..." );
661
-
662
-		// Post the parameter.
663
-		return wp_remote_post( $url, $args );
664
-	}
665
-
666
-	/**
667
-	 * Get the Batch Analysis results for the specified {@link WP_Post}.
668
-	 *
669
-	 * @since 3.14.2
670
-	 *
671
-	 * @param int $post_id The {@link WP_Post}'s id.
672
-	 *
673
-	 * @return WP_Error|array The response or WP_Error on failure.
674
-	 */
675
-	private function do_complete( $post_id ) {
676
-
677
-		$post = get_post( $post_id );
678
-
679
-		if ( null === $post ) {
680
-			// Post was possibly deleted, just bailout.
681
-			return new WP_Error( 0, "Post $post_id not found." );
682
-		}
683
-
684
-		$url = $this->configuration_service->get_batch_analysis_url();
685
-		$key = $this->configuration_service->get_key();
686
-		$url = $url . '/' . $post->ID . '?key=' . $key;
687
-
688
-		return wp_remote_get( $url, unserialize( WL_REDLINK_API_HTTP_OPTIONS ) );
689
-	}
690
-
691
-	/**
692
-	 * Get the {@link WP_Post}s' ids flagged with warnings.
693
-	 *
694
-	 * @since 3.14.2
695
-	 *
696
-	 * @return array An array of {@link WP_Post}s' ids.
697
-	 */
698
-	public function get_warnings() {
699
-
700
-		return get_posts( array(
701
-			'fields'      => 'ids',
702
-			'numberposts' => - 1,
703
-			'post_status' => 'any',
704
-			'meta_key'    => self::WARNING_META_KEY,
705
-			'meta_value'  => 'yes',
706
-		) );
707
-	}
417
+                $this->set_warning_based_on_content( $id, $json->content );
418
+
419
+                $content = wp_slash( $json->content );
420
+
421
+                wp_update_post( array(
422
+                    'ID'           => $id,
423
+                    'post_content' => $content,
424
+                ) );
425
+
426
+                // Update the status.
427
+                $this->set_state( $id, self::STATE_SUCCESS );
428
+
429
+                $this->log->debug( "Post $id updated with batch analysis results." );
430
+
431
+                continue;
432
+            }
433
+
434
+            // @todo: implement a kind of timeout that sets an error if the
435
+            // results haven't been received after a long time.
436
+
437
+        }
438
+
439
+        // Call the `wl_batch_analysis_request` action again. This is going
440
+        // to be handled by the async task.
441
+        do_action( 'wl_batch_analysis_complete' );
442
+
443
+    }
444
+
445
+    /**
446
+     * Set a warning flag on the {@link WP_Post} if its content has suspicious
447
+     * interpolations.
448
+     *
449
+     * @since 3.14.2
450
+     *
451
+     * @param int    $post_id The {@link WP_Post}'s id.
452
+     * @param string $content The {@link WP_Post}'s content.
453
+     *
454
+     * @return string The content (for chaining operations).
455
+     */
456
+    private function set_warning_based_on_content( $post_id, $content ) {
457
+
458
+        $matches = array();
459
+
460
+        // Check for suspicious interpolations.
461
+        $warning = 0 < preg_match_all( '/\w<[a-z]+ id="urn:enhancement-[^"]+" class="[^"]+" itemid="[^"]+">/', $content, $matches )
462
+                   || 0 < preg_match_all( '/<[a-z]+ id="urn:enhancement-[^"]+" class="[^"]+" itemid="[^"]+">\s/', $content, $matches );
463
+
464
+        // Set the warning flag accordingly.
465
+        $this->set_warning( $post_id, $warning );
466
+
467
+        return $content;
468
+    }
469
+
470
+    /**
471
+     * Clear the warning flag for the specified {@link WP_Post}s.
472
+     *
473
+     * @since 3.14.2
474
+     *
475
+     * @param int|array $post_ids A single {@link WP_Post}'s id or an array of
476
+     *                            {@link WP_Post}s' ids.
477
+     */
478
+    public function clear_warning( $post_ids ) {
479
+
480
+        foreach ( (array) $post_ids as $post_id ) {
481
+            delete_post_meta( $post_id, self::WARNING_META_KEY );
482
+        }
483
+
484
+    }
485
+
486
+    /**
487
+     * Set the warning flag for the specified {@link WP_Post}.
488
+     *
489
+     * @since 3.14.2
490
+     *
491
+     * @param int  $post_id The {@link WP_Post}'s id.
492
+     * @param bool $value   The flag's value.
493
+     *
494
+     * @return int|bool Meta ID if the key didn't exist, true on successful update,
495
+     *                  false on failure.
496
+     */
497
+    private function set_warning( $post_id, $value ) {
498
+
499
+        return update_post_meta( $post_id, self::WARNING_META_KEY, ( true === $value ? 'yes' : 'no' ) );
500
+    }
501
+
502
+    /**
503
+     * Get the post/page batch analysis state.
504
+     *
505
+     * @since 3.14.2
506
+     *
507
+     * @param int $post_id The {@link WP_Post}'s id.
508
+     *
509
+     * @return int|string The post state or an empty string if not set.
510
+     */
511
+    public function get_state( $post_id ) {
512
+
513
+        return get_post_meta( $post_id, self::STATE_META_KEY, true );
514
+    }
515
+
516
+    /**
517
+     * Set the post/page batch analysis state.
518
+     *
519
+     * @since 3.14.2
520
+     *
521
+     * @param int $post_id The {@link WP_Post}'s id.
522
+     * @param int $value   The new state.
523
+     *
524
+     * @return int|bool Meta ID if the key didn't exist, true on successful update,
525
+     *                  false on failure.
526
+     */
527
+    public function set_state( $post_id, $value ) {
528
+
529
+        // Update the state.
530
+        $result = update_post_meta( $post_id, self::STATE_META_KEY, $value );
531
+
532
+        // Update timestamps as required.
533
+        switch ( $value ) {
534
+
535
+            //### REQUEST state.
536
+            case self::STATE_REQUEST:
537
+                add_post_meta( $post_id, self::REQUEST_TIMESTAMP_META_KEY, current_time( 'mysql', true ) );
538
+                break;
539
+
540
+            //### SUCCESS/ERROR state.
541
+            case self::STATE_SUCCESS:
542
+            case self::STATE_ERROR:
543
+                add_post_meta( $post_id, self::COMPLETE_TIMESTAMP_META_KEY, current_time( 'mysql', true ) );
544
+                break;
545
+        }
546
+
547
+        // Finally return the result.
548
+        return $result;
549
+    }
550
+
551
+    /**
552
+     * Get the link setting for a {@link WP_Post}.
553
+     *
554
+     * If there are multiple link settings, only the last one is returned.
555
+     *
556
+     * @since 3.14.2
557
+     *
558
+     * @param int $post_id The {@link WP_Post}'s id.
559
+     *
560
+     * @return string The link setting or `default` if not set.
561
+     */
562
+    public function get_link( $post_id ) {
563
+
564
+        $values = get_post_meta( $post_id, self::LINK_META_KEY );
565
+
566
+        return end( $values ) ?: 'default';
567
+    }
568
+
569
+    /**
570
+     * Get the array of post IDS waiting in the queue to start processing.
571
+     *
572
+     * @since 3.14.0
573
+     *
574
+     * @return array The waiting to be processed post ids queue.
575
+     */
576
+    public function waiting_for_analysis() {
577
+
578
+        return get_posts( array(
579
+            'posts_per_page' => - 1,
580
+            'fields'         => 'ids',
581
+            'post_status'    => 'any',
582
+            'meta_key'       => self::STATE_META_KEY,
583
+            'meta_value'     => self::STATE_SUBMIT,
584
+            'orderby'        => 'ID',
585
+        ) );
586
+    }
587
+
588
+    /**
589
+     * Get the array of post IDS waiting for response.
590
+     *
591
+     * @deprecated
592
+     * @since 3.14.0
593
+     *
594
+     * @return array The waiting for response post ids queue.
595
+     */
596
+    public function waiting_for_response() {
597
+
598
+        return get_posts( array(
599
+            'posts_per_page' => - 1,
600
+            'fields'         => 'ids',
601
+            'post_status'    => 'any',
602
+            'meta_key'       => self::STATE_META_KEY,
603
+            'meta_value'     => self::STATE_REQUEST,
604
+            'orderby'        => 'ID',
605
+        ) );
606
+    }
607
+
608
+    /**
609
+     * Request the analysis for the specified {@link WP_Post}.
610
+     *
611
+     * @since 3.14.2
612
+     *
613
+     * @param int $post_id The {@link WP_Post}'s id.
614
+     *
615
+     * @return WP_Error|array The response or WP_Error on failure.
616
+     */
617
+    private function do_request( $post_id ) {
618
+
619
+        // Get the post.
620
+        $post = get_post( $post_id );
621
+
622
+        // Bail out if the post isn't found.
623
+        if ( null === $post ) {
624
+            $this->log->warn( "Post $post_id not found." );
625
+
626
+            return new WP_Error( 0, "Cannot find post $post_id." );
627
+        }
628
+
629
+        // Get the link setting.
630
+        $link = $this->get_link( $post_id );
631
+
632
+        $this->log->debug( "Sending analysis request for post $post_id [ link :: $link ]..." );
633
+
634
+        // Get the batch analysis URL.
635
+        $url = $this->configuration_service->get_batch_analysis_url();
636
+
637
+        // Prepare the POST parameters.
638
+        $param = array(
639
+            'id'              => $post->ID,
640
+            'key'             => $this->configuration_service->get_key(),
641
+            'content'         => $post->post_content,
642
+            'contentLanguage' => $this->configuration_service->get_language_code(),
643
+            'version'         => $this->plugin->get_version(),
644
+            'links'           => $link,
645
+            'scope'           => 'local',
646
+        );
647
+
648
+        // Get the HTTP options.
649
+        $args = array_merge_recursive( unserialize( WL_REDLINK_API_HTTP_OPTIONS ), array(
650
+            'method'      => 'POST',
651
+            'headers'     => array(
652
+                'Accept'       => 'application/json',
653
+                'Content-type' => 'application/json; charset=UTF-8',
654
+            ),
655
+            // we need to downgrade the HTTP version in this case since chunked encoding is dumping numbers in the response.
656
+            'httpversion' => '1.0',
657
+            'body'        => wp_json_encode( $param ),
658
+        ) );
659
+
660
+        $this->log->debug( "Posting analysis request for post $post_id to $url..." );
661
+
662
+        // Post the parameter.
663
+        return wp_remote_post( $url, $args );
664
+    }
665
+
666
+    /**
667
+     * Get the Batch Analysis results for the specified {@link WP_Post}.
668
+     *
669
+     * @since 3.14.2
670
+     *
671
+     * @param int $post_id The {@link WP_Post}'s id.
672
+     *
673
+     * @return WP_Error|array The response or WP_Error on failure.
674
+     */
675
+    private function do_complete( $post_id ) {
676
+
677
+        $post = get_post( $post_id );
678
+
679
+        if ( null === $post ) {
680
+            // Post was possibly deleted, just bailout.
681
+            return new WP_Error( 0, "Post $post_id not found." );
682
+        }
683
+
684
+        $url = $this->configuration_service->get_batch_analysis_url();
685
+        $key = $this->configuration_service->get_key();
686
+        $url = $url . '/' . $post->ID . '?key=' . $key;
687
+
688
+        return wp_remote_get( $url, unserialize( WL_REDLINK_API_HTTP_OPTIONS ) );
689
+    }
690
+
691
+    /**
692
+     * Get the {@link WP_Post}s' ids flagged with warnings.
693
+     *
694
+     * @since 3.14.2
695
+     *
696
+     * @return array An array of {@link WP_Post}s' ids.
697
+     */
698
+    public function get_warnings() {
699
+
700
+        return get_posts( array(
701
+            'fields'      => 'ids',
702
+            'numberposts' => - 1,
703
+            'post_status' => 'any',
704
+            'meta_key'    => self::WARNING_META_KEY,
705
+            'meta_value'  => 'yes',
706
+        ) );
707
+    }
708 708
 
709 709
 }
Please login to merge, or discard this patch.
Spacing   +101 added lines, -101 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( 'wp_async_wl_batch_analysis_request', array(
170
+		add_action('wp_async_wl_batch_analysis_request', array(
171 171
 			$this,
172 172
 			'request',
173
-		) );
174
-		add_action( 'wp_async_wl_batch_analysis_complete', array(
173
+		));
174
+		add_action('wp_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;
@@ -270,19 +270,19 @@  discard block
 block discarded – undo
270 270
 	 *
271 271
 	 * @return int The number of submitted {@link WP_Post}s or false on error.
272 272
 	 */
273
-	public function submit( $post_ids, $link ) {
273
+	public function submit($post_ids, $link) {
274 274
 		global $wpdb;
275 275
 
276 276
 		// Submit the posts/pages and return the number of affected results.
277 277
 		// We're using a SQL query here because we could have potentially
278 278
 		// thousands of rows.
279 279
 		$count = $wpdb->query(
280
-			$this->get_sql( $link ) .
281
-			' AND p.ID IN ( ' . implode( ',', wp_parse_id_list( $post_ids ) ) . ' )'
280
+			$this->get_sql($link).
281
+			' AND p.ID IN ( '.implode(',', wp_parse_id_list($post_ids)).' )'
282 282
 		);
283 283
 
284 284
 		// Request Batch Analysis (the operation is handled asynchronously).
285
-		do_action( 'wl_batch_analysis_request' );
285
+		do_action('wl_batch_analysis_request');
286 286
 
287 287
 		// Divide the count by 3 to get the number of posts/pages queued.
288 288
 		return $count / 3;
@@ -299,19 +299,19 @@  discard block
 block discarded – undo
299 299
 	 * @return false|int The number of cancelled {@link WP_Post}s or false on
300 300
 	 *                   error.
301 301
 	 */
302
-	public function cancel( $post_ids ) {
302
+	public function cancel($post_ids) {
303 303
 		global $wpdb;
304 304
 
305
-		return $wpdb->query( $wpdb->prepare(
305
+		return $wpdb->query($wpdb->prepare(
306 306
 			"
307 307
 			DELETE FROM $wpdb->postmeta
308 308
 			WHERE meta_key = %s
309 309
 				AND meta_value = %s
310
-				AND post_id IN ( " . implode( ',', wp_parse_id_list( $post_ids ) ) . " )
310
+				AND post_id IN ( ".implode(',', wp_parse_id_list($post_ids))." )
311 311
 			",
312 312
 			self::STATE_META_KEY,
313 313
 			self::STATE_REQUEST
314
-		) );
314
+		));
315 315
 
316 316
 	}
317 317
 
@@ -322,49 +322,49 @@  discard block
 block discarded – undo
322 322
 	 */
323 323
 	public function request() {
324 324
 
325
-		$this->log->debug( "Requesting analysis..." );
325
+		$this->log->debug("Requesting analysis...");
326 326
 
327 327
 		// By default 5 posts of any post type are returned.
328
-		$posts = get_posts( array(
328
+		$posts = get_posts(array(
329 329
 			'fields'     => 'ids',
330 330
 			'meta_key'   => self::STATE_META_KEY,
331 331
 			'meta_value' => self::STATE_SUBMIT,
332 332
 			'orderby'    => 'ID',
333
-		) );
333
+		));
334 334
 
335 335
 		// Bail out if there are no submitted posts.
336
-		if ( empty( $posts ) ) {
337
-			$this->log->debug( 'No posts to submit found, checking for completed requests...' );
336
+		if (empty($posts)) {
337
+			$this->log->debug('No posts to submit found, checking for completed requests...');
338 338
 
339
-			do_action( 'wl_batch_analysis_complete' );
339
+			do_action('wl_batch_analysis_complete');
340 340
 
341 341
 			return;
342 342
 		}
343 343
 
344 344
 		// Send a request for each post.
345
-		foreach ( $posts as $id ) {
346
-			$this->log->debug( "Requesting analysis for post $id..." );
345
+		foreach ($posts as $id) {
346
+			$this->log->debug("Requesting analysis for post $id...");
347 347
 
348 348
 			// Change the state to `REQUEST`.
349
-			$this->set_state( $id, self::STATE_REQUEST );
349
+			$this->set_state($id, self::STATE_REQUEST);
350 350
 
351 351
 			// Send the actual request to the remote service.
352
-			$result = $this->do_request( $id );
352
+			$result = $this->do_request($id);
353 353
 
354
-			$this->log->debug( "Analysis requested for post $id." );
354
+			$this->log->debug("Analysis requested for post $id.");
355 355
 
356 356
 			// Set an error if we received an error.
357
-			if ( is_wp_error( $result ) ) {
358
-				$this->log->error( "Analysis request for post $id returned {$result->get_error_message()}." );
357
+			if (is_wp_error($result)) {
358
+				$this->log->error("Analysis request for post $id returned {$result->get_error_message()}.");
359 359
 
360
-				$this->set_state( $id, self::STATE_ERROR );
360
+				$this->set_state($id, self::STATE_ERROR);
361 361
 			}
362 362
 
363 363
 		}
364 364
 
365 365
 		// Call the `wl_batch_analysis_request` action again. This is going
366 366
 		// to be handled by the async task.
367
-		do_action( 'wl_batch_analysis_request' );
367
+		do_action('wl_batch_analysis_request');
368 368
 
369 369
 	}
370 370
 
@@ -375,58 +375,58 @@  discard block
 block discarded – undo
375 375
 	 */
376 376
 	public function complete() {
377 377
 
378
-		$this->log->debug( "Requesting results..." );
378
+		$this->log->debug("Requesting results...");
379 379
 
380 380
 		// By default 5 posts of any post type are returned.
381
-		$posts = get_posts( array(
381
+		$posts = get_posts(array(
382 382
 			'fields'     => 'ids',
383 383
 			'meta_key'   => self::STATE_META_KEY,
384 384
 			'meta_value' => self::STATE_REQUEST,
385 385
 			'orderby'    => 'ID',
386
-		) );
386
+		));
387 387
 
388 388
 		// Bail out if there are no submitted posts.
389
-		if ( empty( $posts ) ) {
390
-			$this->log->debug( 'No posts in request state found.' );
389
+		if (empty($posts)) {
390
+			$this->log->debug('No posts in request state found.');
391 391
 
392 392
 			return;
393 393
 		}
394 394
 
395 395
 		// Send a request for each post.
396
-		foreach ( $posts as $id ) {
397
-			$this->log->debug( "Requesting results for post $id..." );
396
+		foreach ($posts as $id) {
397
+			$this->log->debug("Requesting results for post $id...");
398 398
 
399 399
 			// Send the actual request to the remote service.
400
-			$response = $this->do_complete( $id );
400
+			$response = $this->do_complete($id);
401 401
 
402
-			$this->log->debug( "Results requested for post $id." );
402
+			$this->log->debug("Results requested for post $id.");
403 403
 
404 404
 			// Set an error if we received an error.
405
-			if ( ! is_wp_error( $response ) && isset( $response['body'] ) ) {
405
+			if ( ! is_wp_error($response) && isset($response['body'])) {
406 406
 
407
-				$this->log->debug( "Results received for post $id." );
407
+				$this->log->debug("Results received for post $id.");
408 408
 
409 409
 				// Save the returned content as new revision.
410
-				$json = json_decode( $response['body'] );
410
+				$json = json_decode($response['body']);
411 411
 
412 412
 				// Continue if the content isn't set.
413
-				if ( ! isset( $json->content ) || empty( $json->content ) ) {
413
+				if ( ! isset($json->content) || empty($json->content)) {
414 414
 					continue;
415 415
 				}
416 416
 
417
-				$this->set_warning_based_on_content( $id, $json->content );
417
+				$this->set_warning_based_on_content($id, $json->content);
418 418
 
419
-				$content = wp_slash( $json->content );
419
+				$content = wp_slash($json->content);
420 420
 
421
-				wp_update_post( array(
421
+				wp_update_post(array(
422 422
 					'ID'           => $id,
423 423
 					'post_content' => $content,
424
-				) );
424
+				));
425 425
 
426 426
 				// Update the status.
427
-				$this->set_state( $id, self::STATE_SUCCESS );
427
+				$this->set_state($id, self::STATE_SUCCESS);
428 428
 
429
-				$this->log->debug( "Post $id updated with batch analysis results." );
429
+				$this->log->debug("Post $id updated with batch analysis results.");
430 430
 
431 431
 				continue;
432 432
 			}
@@ -438,7 +438,7 @@  discard block
 block discarded – undo
438 438
 
439 439
 		// Call the `wl_batch_analysis_request` action again. This is going
440 440
 		// to be handled by the async task.
441
-		do_action( 'wl_batch_analysis_complete' );
441
+		do_action('wl_batch_analysis_complete');
442 442
 
443 443
 	}
444 444
 
@@ -453,16 +453,16 @@  discard block
 block discarded – undo
453 453
 	 *
454 454
 	 * @return string The content (for chaining operations).
455 455
 	 */
456
-	private function set_warning_based_on_content( $post_id, $content ) {
456
+	private function set_warning_based_on_content($post_id, $content) {
457 457
 
458 458
 		$matches = array();
459 459
 
460 460
 		// Check for suspicious interpolations.
461
-		$warning = 0 < preg_match_all( '/\w<[a-z]+ id="urn:enhancement-[^"]+" class="[^"]+" itemid="[^"]+">/', $content, $matches )
462
-		           || 0 < preg_match_all( '/<[a-z]+ id="urn:enhancement-[^"]+" class="[^"]+" itemid="[^"]+">\s/', $content, $matches );
461
+		$warning = 0 < preg_match_all('/\w<[a-z]+ id="urn:enhancement-[^"]+" class="[^"]+" itemid="[^"]+">/', $content, $matches)
462
+		           || 0 < preg_match_all('/<[a-z]+ id="urn:enhancement-[^"]+" class="[^"]+" itemid="[^"]+">\s/', $content, $matches);
463 463
 
464 464
 		// Set the warning flag accordingly.
465
-		$this->set_warning( $post_id, $warning );
465
+		$this->set_warning($post_id, $warning);
466 466
 
467 467
 		return $content;
468 468
 	}
@@ -475,10 +475,10 @@  discard block
 block discarded – undo
475 475
 	 * @param int|array $post_ids A single {@link WP_Post}'s id or an array of
476 476
 	 *                            {@link WP_Post}s' ids.
477 477
 	 */
478
-	public function clear_warning( $post_ids ) {
478
+	public function clear_warning($post_ids) {
479 479
 
480
-		foreach ( (array) $post_ids as $post_id ) {
481
-			delete_post_meta( $post_id, self::WARNING_META_KEY );
480
+		foreach ((array) $post_ids as $post_id) {
481
+			delete_post_meta($post_id, self::WARNING_META_KEY);
482 482
 		}
483 483
 
484 484
 	}
@@ -494,9 +494,9 @@  discard block
 block discarded – undo
494 494
 	 * @return int|bool Meta ID if the key didn't exist, true on successful update,
495 495
 	 *                  false on failure.
496 496
 	 */
497
-	private function set_warning( $post_id, $value ) {
497
+	private function set_warning($post_id, $value) {
498 498
 
499
-		return update_post_meta( $post_id, self::WARNING_META_KEY, ( true === $value ? 'yes' : 'no' ) );
499
+		return update_post_meta($post_id, self::WARNING_META_KEY, (true === $value ? 'yes' : 'no'));
500 500
 	}
501 501
 
502 502
 	/**
@@ -508,9 +508,9 @@  discard block
 block discarded – undo
508 508
 	 *
509 509
 	 * @return int|string The post state or an empty string if not set.
510 510
 	 */
511
-	public function get_state( $post_id ) {
511
+	public function get_state($post_id) {
512 512
 
513
-		return get_post_meta( $post_id, self::STATE_META_KEY, true );
513
+		return get_post_meta($post_id, self::STATE_META_KEY, true);
514 514
 	}
515 515
 
516 516
 	/**
@@ -524,23 +524,23 @@  discard block
 block discarded – undo
524 524
 	 * @return int|bool Meta ID if the key didn't exist, true on successful update,
525 525
 	 *                  false on failure.
526 526
 	 */
527
-	public function set_state( $post_id, $value ) {
527
+	public function set_state($post_id, $value) {
528 528
 
529 529
 		// Update the state.
530
-		$result = update_post_meta( $post_id, self::STATE_META_KEY, $value );
530
+		$result = update_post_meta($post_id, self::STATE_META_KEY, $value);
531 531
 
532 532
 		// Update timestamps as required.
533
-		switch ( $value ) {
533
+		switch ($value) {
534 534
 
535 535
 			//### REQUEST state.
536 536
 			case self::STATE_REQUEST:
537
-				add_post_meta( $post_id, self::REQUEST_TIMESTAMP_META_KEY, current_time( 'mysql', true ) );
537
+				add_post_meta($post_id, self::REQUEST_TIMESTAMP_META_KEY, current_time('mysql', true));
538 538
 				break;
539 539
 
540 540
 			//### SUCCESS/ERROR state.
541 541
 			case self::STATE_SUCCESS:
542 542
 			case self::STATE_ERROR:
543
-				add_post_meta( $post_id, self::COMPLETE_TIMESTAMP_META_KEY, current_time( 'mysql', true ) );
543
+				add_post_meta($post_id, self::COMPLETE_TIMESTAMP_META_KEY, current_time('mysql', true));
544 544
 				break;
545 545
 		}
546 546
 
@@ -559,11 +559,11 @@  discard block
 block discarded – undo
559 559
 	 *
560 560
 	 * @return string The link setting or `default` if not set.
561 561
 	 */
562
-	public function get_link( $post_id ) {
562
+	public function get_link($post_id) {
563 563
 
564
-		$values = get_post_meta( $post_id, self::LINK_META_KEY );
564
+		$values = get_post_meta($post_id, self::LINK_META_KEY);
565 565
 
566
-		return end( $values ) ?: 'default';
566
+		return end($values) ?: 'default';
567 567
 	}
568 568
 
569 569
 	/**
@@ -575,14 +575,14 @@  discard block
 block discarded – undo
575 575
 	 */
576 576
 	public function waiting_for_analysis() {
577 577
 
578
-		return get_posts( array(
579
-			'posts_per_page' => - 1,
578
+		return get_posts(array(
579
+			'posts_per_page' => -1,
580 580
 			'fields'         => 'ids',
581 581
 			'post_status'    => 'any',
582 582
 			'meta_key'       => self::STATE_META_KEY,
583 583
 			'meta_value'     => self::STATE_SUBMIT,
584 584
 			'orderby'        => 'ID',
585
-		) );
585
+		));
586 586
 	}
587 587
 
588 588
 	/**
@@ -595,14 +595,14 @@  discard block
 block discarded – undo
595 595
 	 */
596 596
 	public function waiting_for_response() {
597 597
 
598
-		return get_posts( array(
599
-			'posts_per_page' => - 1,
598
+		return get_posts(array(
599
+			'posts_per_page' => -1,
600 600
 			'fields'         => 'ids',
601 601
 			'post_status'    => 'any',
602 602
 			'meta_key'       => self::STATE_META_KEY,
603 603
 			'meta_value'     => self::STATE_REQUEST,
604 604
 			'orderby'        => 'ID',
605
-		) );
605
+		));
606 606
 	}
607 607
 
608 608
 	/**
@@ -614,22 +614,22 @@  discard block
 block discarded – undo
614 614
 	 *
615 615
 	 * @return WP_Error|array The response or WP_Error on failure.
616 616
 	 */
617
-	private function do_request( $post_id ) {
617
+	private function do_request($post_id) {
618 618
 
619 619
 		// Get the post.
620
-		$post = get_post( $post_id );
620
+		$post = get_post($post_id);
621 621
 
622 622
 		// Bail out if the post isn't found.
623
-		if ( null === $post ) {
624
-			$this->log->warn( "Post $post_id not found." );
623
+		if (null === $post) {
624
+			$this->log->warn("Post $post_id not found.");
625 625
 
626
-			return new WP_Error( 0, "Cannot find post $post_id." );
626
+			return new WP_Error(0, "Cannot find post $post_id.");
627 627
 		}
628 628
 
629 629
 		// Get the link setting.
630
-		$link = $this->get_link( $post_id );
630
+		$link = $this->get_link($post_id);
631 631
 
632
-		$this->log->debug( "Sending analysis request for post $post_id [ link :: $link ]..." );
632
+		$this->log->debug("Sending analysis request for post $post_id [ link :: $link ]...");
633 633
 
634 634
 		// Get the batch analysis URL.
635 635
 		$url = $this->configuration_service->get_batch_analysis_url();
@@ -646,7 +646,7 @@  discard block
 block discarded – undo
646 646
 		);
647 647
 
648 648
 		// Get the HTTP options.
649
-		$args = array_merge_recursive( unserialize( WL_REDLINK_API_HTTP_OPTIONS ), array(
649
+		$args = array_merge_recursive(unserialize(WL_REDLINK_API_HTTP_OPTIONS), array(
650 650
 			'method'      => 'POST',
651 651
 			'headers'     => array(
652 652
 				'Accept'       => 'application/json',
@@ -654,13 +654,13 @@  discard block
 block discarded – undo
654 654
 			),
655 655
 			// we need to downgrade the HTTP version in this case since chunked encoding is dumping numbers in the response.
656 656
 			'httpversion' => '1.0',
657
-			'body'        => wp_json_encode( $param ),
658
-		) );
657
+			'body'        => wp_json_encode($param),
658
+		));
659 659
 
660
-		$this->log->debug( "Posting analysis request for post $post_id to $url..." );
660
+		$this->log->debug("Posting analysis request for post $post_id to $url...");
661 661
 
662 662
 		// Post the parameter.
663
-		return wp_remote_post( $url, $args );
663
+		return wp_remote_post($url, $args);
664 664
 	}
665 665
 
666 666
 	/**
@@ -672,20 +672,20 @@  discard block
 block discarded – undo
672 672
 	 *
673 673
 	 * @return WP_Error|array The response or WP_Error on failure.
674 674
 	 */
675
-	private function do_complete( $post_id ) {
675
+	private function do_complete($post_id) {
676 676
 
677
-		$post = get_post( $post_id );
677
+		$post = get_post($post_id);
678 678
 
679
-		if ( null === $post ) {
679
+		if (null === $post) {
680 680
 			// Post was possibly deleted, just bailout.
681
-			return new WP_Error( 0, "Post $post_id not found." );
681
+			return new WP_Error(0, "Post $post_id not found.");
682 682
 		}
683 683
 
684 684
 		$url = $this->configuration_service->get_batch_analysis_url();
685 685
 		$key = $this->configuration_service->get_key();
686
-		$url = $url . '/' . $post->ID . '?key=' . $key;
686
+		$url = $url.'/'.$post->ID.'?key='.$key;
687 687
 
688
-		return wp_remote_get( $url, unserialize( WL_REDLINK_API_HTTP_OPTIONS ) );
688
+		return wp_remote_get($url, unserialize(WL_REDLINK_API_HTTP_OPTIONS));
689 689
 	}
690 690
 
691 691
 	/**
@@ -697,13 +697,13 @@  discard block
 block discarded – undo
697 697
 	 */
698 698
 	public function get_warnings() {
699 699
 
700
-		return get_posts( array(
700
+		return get_posts(array(
701 701
 			'fields'      => 'ids',
702
-			'numberposts' => - 1,
702
+			'numberposts' => -1,
703 703
 			'post_status' => 'any',
704 704
 			'meta_key'    => self::WARNING_META_KEY,
705 705
 			'meta_value'  => 'yes',
706
-		) );
706
+		));
707 707
 	}
708 708
 
709 709
 }
Please login to merge, or discard this patch.
src/includes/class-wordlift-relation-rebuild-adapter.php 2 patches
Indentation   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -1,31 +1,31 @@
 block discarded – undo
1 1
 <?php
2 2
 
3 3
 class Wordlift_Relation_Rebuild_Adapter {
4
-	/**
5
-	 * @var Wordlift_Relation_Rebuild_Service
6
-	 */
7
-	private $relation_rebuild_service;
4
+    /**
5
+     * @var Wordlift_Relation_Rebuild_Service
6
+     */
7
+    private $relation_rebuild_service;
8 8
 
9 9
 
10
-	/**
11
-	 * Wordlift_Relation_Rebuild_Adapter constructor.
12
-	 *
13
-	 * @param \Wordlift_Relation_Rebuild_Service $relation_rebuild_service
14
-	 */
15
-	public function __construct( $relation_rebuild_service ) {
16
-		$this->relation_rebuild_service = $relation_rebuild_service;
17
-	}
10
+    /**
11
+     * Wordlift_Relation_Rebuild_Adapter constructor.
12
+     *
13
+     * @param \Wordlift_Relation_Rebuild_Service $relation_rebuild_service
14
+     */
15
+    public function __construct( $relation_rebuild_service ) {
16
+        $this->relation_rebuild_service = $relation_rebuild_service;
17
+    }
18 18
 
19
-	public function process_all() {
19
+    public function process_all() {
20 20
 
21
-		$this->relation_rebuild_service->process_all();
21
+        $this->relation_rebuild_service->process_all();
22 22
 
23
-		ob_clean();
23
+        ob_clean();
24 24
 
25
-		wp_send_json_success( array(
26
-			'count' => $this->relation_rebuild_service->get_count(),
27
-		) );
25
+        wp_send_json_success( array(
26
+            'count' => $this->relation_rebuild_service->get_count(),
27
+        ) );
28 28
 
29
-	}
29
+    }
30 30
 
31 31
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -12,7 +12,7 @@  discard block
 block discarded – undo
12 12
 	 *
13 13
 	 * @param \Wordlift_Relation_Rebuild_Service $relation_rebuild_service
14 14
 	 */
15
-	public function __construct( $relation_rebuild_service ) {
15
+	public function __construct($relation_rebuild_service) {
16 16
 		$this->relation_rebuild_service = $relation_rebuild_service;
17 17
 	}
18 18
 
@@ -22,9 +22,9 @@  discard block
 block discarded – undo
22 22
 
23 23
 		ob_clean();
24 24
 
25
-		wp_send_json_success( array(
25
+		wp_send_json_success(array(
26 26
 			'count' => $this->relation_rebuild_service->get_count(),
27
-		) );
27
+		));
28 28
 
29 29
 	}
30 30
 
Please login to merge, or discard this patch.