Completed
Push — develop ( a29dde...546ddf )
by David
04:13
created
src/includes/batch-analysis/class-wordlift-batch-analysis-service.php 2 patches
Indentation   +715 added lines, -715 removed lines patch added patch discarded remove patch
@@ -51,522 +51,522 @@  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 options setting meta key. A post may have more than one setting.
96
-	 *
97
-	 * @since 3.14.2
98
-	 */
99
-	const BATCH_ANALYSIS_OPTIONS_META_KEY = '_wl_batch_analysis_options';
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
-	 * Regular expressions that match interpolation errors.
131
-	 *
132
-	 * @since  3.17.0
133
-	 */
134
-	private static $interpolation_patterns = array(
135
-		// Matches word before the annotation.
136
-		'~(\w)<[a-z]+ id="urn:[^"]+" class="[^"]+" itemid="[^"]+">(.*?)<\/[a-z]+>~',
137
-		// Matches word after the annotation.
138
-		'~<[a-z]+ id="urn:[^"]+" class="[^"]+" itemid="[^"]+">(.*?)<\/[a-z]+>(\w)~',
139
-		// Matches space in the beginning of annotation name.
140
-		'~<[a-z]+ id="urn:[^"]+" class="[^"]+" itemid="[^"]+">(\s)(.*?)<\/[a-z]+>~',
141
-	);
142
-
143
-	/**
144
-	 * The {@link Wordlift} plugin instance.
145
-	 *
146
-	 * @since  3.14.0
147
-	 * @access private
148
-	 * @var \Wordlift $plugin The {@link Wordlift} plugin instance.
149
-	 */
150
-	private $plugin;
151
-
152
-	/**
153
-	 * The {@link Wordlift_Configuration_Service} instance.
154
-	 *
155
-	 * @since  3.14.0
156
-	 * @access private
157
-	 * @var \Wordlift_Configuration_Service $configuration_service The {@link Wordlift_Configuration_Service} instance.
158
-	 */
159
-	private $configuration_service;
160
-
161
-	/**
162
-	 * The {@link Wordlift_Cache_Service} instance.
163
-	 *
164
-	 * @since  3.17.0
165
-	 * @access protected
166
-	 * @var \Wordlift_Cache_Service $cache_service The {@link Wordlift_Cache_Service} instance.
167
-	 */
168
-	private $cache_service;
169
-
170
-	/**
171
-	 * A {@link Wordlift_Log_Service} instance.
172
-	 *
173
-	 * @since  3.14.2
174
-	 * @access private
175
-	 * @var \Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
176
-	 */
177
-	private $log;
178
-
179
-	/**
180
-	 * The {@link Class_Wordlift_Batch_Analys_Service} instance.
181
-	 *
182
-	 * @since 3.14.0
183
-	 *
184
-	 * @param \Wordlift                       $plugin                The {@link Wordlift} plugin instance.
185
-	 * @param \Wordlift_Configuration_Service $configuration_service The {@link Wordlift_Configuration_Service} instance.
186
-	 * @param \Wordlift_Cache_Service         $cache_service         The {@link Wordlift_Cache_Service} instance.
187
-	 */
188
-	public function __construct( $plugin, $configuration_service, $cache_service ) {
189
-
190
-		$this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Batch_Analysis_Service' );
191
-
192
-		$this->plugin                = $plugin;
193
-		$this->configuration_service = $configuration_service;
194
-		$this->cache_service         = $cache_service;
195
-
196
-		add_action( 'wl_async_wl_batch_analysis_request', array(
197
-			$this,
198
-			'request',
199
-		) );
200
-		add_action( 'wl_async_wl_batch_analysis_complete', array(
201
-			$this,
202
-			'complete',
203
-		) );
204
-
205
-	}
206
-
207
-	/**
208
-	 * Submit posts for Batch Analysis.
209
-	 *
210
-	 * @since 3.14.2
211
-	 *
212
-	 * @param array       $args               {
213
-	 *                                        A list of options for the Batch Analysis.
214
-	 *
215
-	 * @type string       $link               Either `default`, `no` or `yes` (`default` is used if not specified):
216
-	 *                                        * `default` doesn't set the link option - entities
217
-	 *                                           will be linked if configured so in WordLift settings.
218
-	 *                                        * `yes` links the entities.
219
-	 *                                        * `no` doesn't link the entities.
220
-	 *                                        This value is forwarded to WLS' Batch Analysis end-point.
221
-	 * @type int          $min_occurrences    The minimum number of occurrences to select
222
-	 *                                        an entity. Default `1`.
223
-	 * @type bool         $include_annotated  Whether to include annotated posts in selection.
224
-	 *                                        Default `false`.
225
-	 * @type array|int    $include            Explicitly include the specified {@link WP_Post}s.
226
-	 * @type array|int    $exclude            Explicitly exclude the specified {@link WP_Post}s.
227
-	 * @type string|null  $from               An optional date from filter (used in `post_date_gmt`).
228
-	 * @type string|null  $to                 An optional date from filter (used in `post_date_gmt`).
229
-	 * @type array|string $post_type          Specify the post type(s), by default only `post`.
230
-	 *                      }
231
-	 *
232
-	 * @return int The number of submitted {@link WP_Post}s or false on error.
233
-	 */
234
-	public function submit( $args ) {
235
-		global $wpdb;
236
-
237
-		// Parse the parameters.
238
-		$params = wp_parse_args( $args, array(
239
-			'links'             => 'default',
240
-			'min_occurrences'   => 1,
241
-			'include_annotated' => false,
242
-			'exclude'           => array(),
243
-			'from'              => null,
244
-			'to'                => null,
245
-			'post_type'         => 'post',
246
-		) );
247
-
248
-		// Validation.
249
-		if ( ! in_array( $params['links'], array( 'default', 'yes', 'no' ) ) ) {
250
-			wp_die( '`link` must be one of the following: `default`, `yes` or `no`.' );
251
-		}
252
-
253
-		if ( ! is_numeric( $params['min_occurrences'] ) || 1 > $params['min_occurrences'] ) {
254
-			wp_die( '`min_occurrences` must greater or equal 1.' );
255
-		}
256
-
257
-		// Submit the posts/pages and return the number of affected results.
258
-		// We're using a SQL query here because we could have potentially
259
-		// thousands of rows.
260
-		$count = $wpdb->query( Wordlift_Batch_Analysis_Sql_Helper::get_sql( $params ) ); // WPCS: cache ok, db call ok.
261
-
262
-		// Request Batch Analysis (the operation is handled asynchronously).
263
-		do_action( 'wl_batch_analysis_request' );
264
-
265
-		// Divide the count by 3 to get the number of posts/pages queued.
266
-		return $count / 3;
267
-	}
268
-
269
-	/**
270
-	 * Submit one or more {@link WP_Posts} for Batch Analysis.
271
-	 *
272
-	 * @param array    $args            {
273
-	 *                                  An array of arguments.
274
-	 *
275
-	 * @type string    $link            The link option: `default`, `yes` or
276
-	 *                                  `no`. If not set `default`.
277
-	 * @type int       $min_occurrences The minimum number of occurrences. If
278
-	 *                                  not set `1`.
279
-	 * @type array|int $ids             An array of {@link WP_Post}s' ids or one
280
-	 *                                  single numeric {@link WP_Post} id.
281
-	 *                    }
282
-	 *
283
-	 * @return float|int
284
-	 */
285
-	public function submit_posts( $args ) {
286
-		global $wpdb;
287
-
288
-		// Parse the parameters.
289
-		$params = wp_parse_args( $args, array(
290
-			'links'           => 'default',
291
-			'min_occurrences' => 1,
292
-			'ids'             => array(),
293
-		) );
294
-
295
-		// Validation.
296
-		if ( empty( $params['ids'] ) ) {
297
-			wp_die( '`ids` cannot be empty.' );
298
-		}
299
-
300
-		// Submit the posts/pages and return the number of affected results.
301
-		// We're using a SQL query here because we could have potentially
302
-		// thousands of rows.
303
-		$count = $wpdb->query( Wordlift_Batch_Analysis_Sql_Helper::get_sql_for_ids( $params ) ); // WPCS: cache ok, db call ok.
304
-
305
-		// Request Batch Analysis (the operation is handled asynchronously).
306
-		do_action( 'wl_batch_analysis_request' );
307
-
308
-		// Divide the count by 3 to get the number of posts/pages queued.
309
-		return $count / 3;
310
-	}
311
-
312
-	/**
313
-	 * Cancel the Batch Analysis request for the specified {@link WP_Post}s.
314
-	 *
315
-	 * @since 3.14.2
316
-	 *
317
-	 * @param int|array $post_ids A single {@link WP_Post}'s id or an array of
318
-	 *                            {@link WP_Post}s' ids.
319
-	 *
320
-	 * @return false|int The number of cancelled {@link WP_Post}s or false on
321
-	 *                   error.
322
-	 */
323
-	public function cancel( $post_ids ) {
324
-		global $wpdb;
325
-
326
-		return $wpdb->query( $wpdb->prepare(
327
-			"
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 options setting meta key. A post may have more than one setting.
96
+     *
97
+     * @since 3.14.2
98
+     */
99
+    const BATCH_ANALYSIS_OPTIONS_META_KEY = '_wl_batch_analysis_options';
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
+     * Regular expressions that match interpolation errors.
131
+     *
132
+     * @since  3.17.0
133
+     */
134
+    private static $interpolation_patterns = array(
135
+        // Matches word before the annotation.
136
+        '~(\w)<[a-z]+ id="urn:[^"]+" class="[^"]+" itemid="[^"]+">(.*?)<\/[a-z]+>~',
137
+        // Matches word after the annotation.
138
+        '~<[a-z]+ id="urn:[^"]+" class="[^"]+" itemid="[^"]+">(.*?)<\/[a-z]+>(\w)~',
139
+        // Matches space in the beginning of annotation name.
140
+        '~<[a-z]+ id="urn:[^"]+" class="[^"]+" itemid="[^"]+">(\s)(.*?)<\/[a-z]+>~',
141
+    );
142
+
143
+    /**
144
+     * The {@link Wordlift} plugin instance.
145
+     *
146
+     * @since  3.14.0
147
+     * @access private
148
+     * @var \Wordlift $plugin The {@link Wordlift} plugin instance.
149
+     */
150
+    private $plugin;
151
+
152
+    /**
153
+     * The {@link Wordlift_Configuration_Service} instance.
154
+     *
155
+     * @since  3.14.0
156
+     * @access private
157
+     * @var \Wordlift_Configuration_Service $configuration_service The {@link Wordlift_Configuration_Service} instance.
158
+     */
159
+    private $configuration_service;
160
+
161
+    /**
162
+     * The {@link Wordlift_Cache_Service} instance.
163
+     *
164
+     * @since  3.17.0
165
+     * @access protected
166
+     * @var \Wordlift_Cache_Service $cache_service The {@link Wordlift_Cache_Service} instance.
167
+     */
168
+    private $cache_service;
169
+
170
+    /**
171
+     * A {@link Wordlift_Log_Service} instance.
172
+     *
173
+     * @since  3.14.2
174
+     * @access private
175
+     * @var \Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
176
+     */
177
+    private $log;
178
+
179
+    /**
180
+     * The {@link Class_Wordlift_Batch_Analys_Service} instance.
181
+     *
182
+     * @since 3.14.0
183
+     *
184
+     * @param \Wordlift                       $plugin                The {@link Wordlift} plugin instance.
185
+     * @param \Wordlift_Configuration_Service $configuration_service The {@link Wordlift_Configuration_Service} instance.
186
+     * @param \Wordlift_Cache_Service         $cache_service         The {@link Wordlift_Cache_Service} instance.
187
+     */
188
+    public function __construct( $plugin, $configuration_service, $cache_service ) {
189
+
190
+        $this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Batch_Analysis_Service' );
191
+
192
+        $this->plugin                = $plugin;
193
+        $this->configuration_service = $configuration_service;
194
+        $this->cache_service         = $cache_service;
195
+
196
+        add_action( 'wl_async_wl_batch_analysis_request', array(
197
+            $this,
198
+            'request',
199
+        ) );
200
+        add_action( 'wl_async_wl_batch_analysis_complete', array(
201
+            $this,
202
+            'complete',
203
+        ) );
204
+
205
+    }
206
+
207
+    /**
208
+     * Submit posts for Batch Analysis.
209
+     *
210
+     * @since 3.14.2
211
+     *
212
+     * @param array       $args               {
213
+     *                                        A list of options for the Batch Analysis.
214
+     *
215
+     * @type string       $link               Either `default`, `no` or `yes` (`default` is used if not specified):
216
+     *                                        * `default` doesn't set the link option - entities
217
+     *                                           will be linked if configured so in WordLift settings.
218
+     *                                        * `yes` links the entities.
219
+     *                                        * `no` doesn't link the entities.
220
+     *                                        This value is forwarded to WLS' Batch Analysis end-point.
221
+     * @type int          $min_occurrences    The minimum number of occurrences to select
222
+     *                                        an entity. Default `1`.
223
+     * @type bool         $include_annotated  Whether to include annotated posts in selection.
224
+     *                                        Default `false`.
225
+     * @type array|int    $include            Explicitly include the specified {@link WP_Post}s.
226
+     * @type array|int    $exclude            Explicitly exclude the specified {@link WP_Post}s.
227
+     * @type string|null  $from               An optional date from filter (used in `post_date_gmt`).
228
+     * @type string|null  $to                 An optional date from filter (used in `post_date_gmt`).
229
+     * @type array|string $post_type          Specify the post type(s), by default only `post`.
230
+     *                      }
231
+     *
232
+     * @return int The number of submitted {@link WP_Post}s or false on error.
233
+     */
234
+    public function submit( $args ) {
235
+        global $wpdb;
236
+
237
+        // Parse the parameters.
238
+        $params = wp_parse_args( $args, array(
239
+            'links'             => 'default',
240
+            'min_occurrences'   => 1,
241
+            'include_annotated' => false,
242
+            'exclude'           => array(),
243
+            'from'              => null,
244
+            'to'                => null,
245
+            'post_type'         => 'post',
246
+        ) );
247
+
248
+        // Validation.
249
+        if ( ! in_array( $params['links'], array( 'default', 'yes', 'no' ) ) ) {
250
+            wp_die( '`link` must be one of the following: `default`, `yes` or `no`.' );
251
+        }
252
+
253
+        if ( ! is_numeric( $params['min_occurrences'] ) || 1 > $params['min_occurrences'] ) {
254
+            wp_die( '`min_occurrences` must greater or equal 1.' );
255
+        }
256
+
257
+        // Submit the posts/pages and return the number of affected results.
258
+        // We're using a SQL query here because we could have potentially
259
+        // thousands of rows.
260
+        $count = $wpdb->query( Wordlift_Batch_Analysis_Sql_Helper::get_sql( $params ) ); // WPCS: cache ok, db call ok.
261
+
262
+        // Request Batch Analysis (the operation is handled asynchronously).
263
+        do_action( 'wl_batch_analysis_request' );
264
+
265
+        // Divide the count by 3 to get the number of posts/pages queued.
266
+        return $count / 3;
267
+    }
268
+
269
+    /**
270
+     * Submit one or more {@link WP_Posts} for Batch Analysis.
271
+     *
272
+     * @param array    $args            {
273
+     *                                  An array of arguments.
274
+     *
275
+     * @type string    $link            The link option: `default`, `yes` or
276
+     *                                  `no`. If not set `default`.
277
+     * @type int       $min_occurrences The minimum number of occurrences. If
278
+     *                                  not set `1`.
279
+     * @type array|int $ids             An array of {@link WP_Post}s' ids or one
280
+     *                                  single numeric {@link WP_Post} id.
281
+     *                    }
282
+     *
283
+     * @return float|int
284
+     */
285
+    public function submit_posts( $args ) {
286
+        global $wpdb;
287
+
288
+        // Parse the parameters.
289
+        $params = wp_parse_args( $args, array(
290
+            'links'           => 'default',
291
+            'min_occurrences' => 1,
292
+            'ids'             => array(),
293
+        ) );
294
+
295
+        // Validation.
296
+        if ( empty( $params['ids'] ) ) {
297
+            wp_die( '`ids` cannot be empty.' );
298
+        }
299
+
300
+        // Submit the posts/pages and return the number of affected results.
301
+        // We're using a SQL query here because we could have potentially
302
+        // thousands of rows.
303
+        $count = $wpdb->query( Wordlift_Batch_Analysis_Sql_Helper::get_sql_for_ids( $params ) ); // WPCS: cache ok, db call ok.
304
+
305
+        // Request Batch Analysis (the operation is handled asynchronously).
306
+        do_action( 'wl_batch_analysis_request' );
307
+
308
+        // Divide the count by 3 to get the number of posts/pages queued.
309
+        return $count / 3;
310
+    }
311
+
312
+    /**
313
+     * Cancel the Batch Analysis request for the specified {@link WP_Post}s.
314
+     *
315
+     * @since 3.14.2
316
+     *
317
+     * @param int|array $post_ids A single {@link WP_Post}'s id or an array of
318
+     *                            {@link WP_Post}s' ids.
319
+     *
320
+     * @return false|int The number of cancelled {@link WP_Post}s or false on
321
+     *                   error.
322
+     */
323
+    public function cancel( $post_ids ) {
324
+        global $wpdb;
325
+
326
+        return $wpdb->query( $wpdb->prepare(
327
+            "
328 328
 			DELETE FROM $wpdb->postmeta
329 329
 			WHERE meta_key = %s
330 330
 				AND meta_value IN ( %d, %d )
331 331
 				AND post_id IN( " . implode( ',', wp_parse_id_list( $post_ids ) ) . " )
332 332
 			",
333
-			self::STATE_META_KEY,
334
-			self::STATE_SUBMIT,
335
-			self::STATE_REQUEST
336
-		) ); // WPCS: cache ok, db call ok.
333
+            self::STATE_META_KEY,
334
+            self::STATE_SUBMIT,
335
+            self::STATE_REQUEST
336
+        ) ); // WPCS: cache ok, db call ok.
337 337
 
338
-	}
338
+    }
339 339
 
340
-	/**
341
-	 * Request the batch analysis for submitted posts.
342
-	 *
343
-	 * @since 3.14.2
344
-	 */
345
-	public function request() {
340
+    /**
341
+     * Request the batch analysis for submitted posts.
342
+     *
343
+     * @since 3.14.2
344
+     */
345
+    public function request() {
346 346
 
347
-		$this->log->debug( 'Requesting analysis...' );
347
+        $this->log->debug( 'Requesting analysis...' );
348 348
 
349
-		// By default 5 posts of any post type are returned.
350
-		$posts = get_posts( array(
351
-			'fields'     => 'ids',
352
-			'meta_key'   => self::STATE_META_KEY,
353
-			'meta_value' => self::STATE_SUBMIT,
354
-			'orderby'    => 'ID',
355
-			'post_type'  => 'any',
356
-		) );
349
+        // By default 5 posts of any post type are returned.
350
+        $posts = get_posts( array(
351
+            'fields'     => 'ids',
352
+            'meta_key'   => self::STATE_META_KEY,
353
+            'meta_value' => self::STATE_SUBMIT,
354
+            'orderby'    => 'ID',
355
+            'post_type'  => 'any',
356
+        ) );
357 357
 
358
-		// Bail out if there are no submitted posts.
359
-		if ( empty( $posts ) ) {
360
-			$this->log->debug( 'No posts to submit found, checking for completed requests...' );
361
-
362
-			do_action( 'wl_batch_analysis_complete' );
358
+        // Bail out if there are no submitted posts.
359
+        if ( empty( $posts ) ) {
360
+            $this->log->debug( 'No posts to submit found, checking for completed requests...' );
361
+
362
+            do_action( 'wl_batch_analysis_complete' );
363 363
 
364
-			return;
365
-		}
364
+            return;
365
+        }
366 366
 
367
-		// Send a request for each post.
368
-		foreach ( $posts as $id ) {
367
+        // Send a request for each post.
368
+        foreach ( $posts as $id ) {
369 369
 
370
-			$this->log->debug( "Requesting analysis for post $id..." );
370
+            $this->log->debug( "Requesting analysis for post $id..." );
371 371
 
372
-			// Send the actual request to the remote service.
373
-			$result = $this->do_request( $id );
372
+            // Send the actual request to the remote service.
373
+            $result = $this->do_request( $id );
374 374
 
375
-			// Set an error if we received an error.
376
-			if ( is_wp_error( $result ) ) {
377
-				$this->log->error( "An error occurred while requesting a batch analysis for post $id: " . $result->get_error_message() );
375
+            // Set an error if we received an error.
376
+            if ( is_wp_error( $result ) ) {
377
+                $this->log->error( "An error occurred while requesting a batch analysis for post $id: " . $result->get_error_message() );
378 378
 
379
-				$this->set_state( $id, self::STATE_ERROR );
380
-			}
379
+                $this->set_state( $id, self::STATE_ERROR );
380
+            }
381 381
 
382
-		}
382
+        }
383 383
 
384
-		// Call the `wl_batch_analysis_request` action again. This is going
385
-		// to be handled by the async task.
386
-		do_action( 'wl_batch_analysis_request' );
384
+        // Call the `wl_batch_analysis_request` action again. This is going
385
+        // to be handled by the async task.
386
+        do_action( 'wl_batch_analysis_request' );
387 387
 
388
-	}
388
+    }
389 389
 
390
-	/**
391
-	 * Get the results for the Batch Analysis.
392
-	 *
393
-	 * @since 3.14.2
394
-	 */
395
-	public function complete() {
396
-
397
-		$this->log->debug( 'Requesting results...' );
390
+    /**
391
+     * Get the results for the Batch Analysis.
392
+     *
393
+     * @since 3.14.2
394
+     */
395
+    public function complete() {
396
+
397
+        $this->log->debug( 'Requesting results...' );
398 398
 
399
-		// By default 5 posts of any post type are returned.
400
-		$posts = get_posts( array(
401
-			'fields'     => 'ids',
402
-			'meta_key'   => self::STATE_META_KEY,
403
-			'meta_value' => self::STATE_REQUEST,
404
-			'orderby'    => 'ID',
405
-			'post_type'  => 'any',
406
-		) );
399
+        // By default 5 posts of any post type are returned.
400
+        $posts = get_posts( array(
401
+            'fields'     => 'ids',
402
+            'meta_key'   => self::STATE_META_KEY,
403
+            'meta_value' => self::STATE_REQUEST,
404
+            'orderby'    => 'ID',
405
+            'post_type'  => 'any',
406
+        ) );
407 407
 
408
-		// Bail out if there are no submitted posts.
409
-		if ( empty( $posts ) ) {
410
-			$this->log->debug( 'No posts in request state found.' );
408
+        // Bail out if there are no submitted posts.
409
+        if ( empty( $posts ) ) {
410
+            $this->log->debug( 'No posts in request state found.' );
411 411
 
412
-			return;
413
-		}
412
+            return;
413
+        }
414 414
 
415
-		// Send a request for each post.
416
-		foreach ( $posts as $id ) {
417
-			$this->log->debug( "Requesting results for post $id..." );
415
+        // Send a request for each post.
416
+        foreach ( $posts as $id ) {
417
+            $this->log->debug( "Requesting results for post $id..." );
418 418
 
419
-			// Send the actual request to the remote service.
420
-			$response = $this->do_complete( $id );
421
-
422
-			// Move to the next item if we don't have a reply for this one.
423
-			if ( is_wp_error( $response ) || 200 !== (int) $response['response']['code'] || ! isset( $response['body'] ) ) {
424
-				continue;
425
-			}
426
-
427
-			$this->log->debug( "Results received for post $id." );
428
-
429
-			// Save the returned content as new revision.
430
-			$json = json_decode( $response['body'] );
431
-
432
-			// Continue if the content isn't set.
433
-			if ( empty( $json->content ) ) {
434
-				// The post content is empty, so is should be marked as completed.
435
-				$this->log->error( "An error occurred while decoding the batch analysis response for post $id: {$response['body']}" );
419
+            // Send the actual request to the remote service.
420
+            $response = $this->do_complete( $id );
421
+
422
+            // Move to the next item if we don't have a reply for this one.
423
+            if ( is_wp_error( $response ) || 200 !== (int) $response['response']['code'] || ! isset( $response['body'] ) ) {
424
+                continue;
425
+            }
426
+
427
+            $this->log->debug( "Results received for post $id." );
428
+
429
+            // Save the returned content as new revision.
430
+            $json = json_decode( $response['body'] );
431
+
432
+            // Continue if the content isn't set.
433
+            if ( empty( $json->content ) ) {
434
+                // The post content is empty, so is should be marked as completed.
435
+                $this->log->error( "An error occurred while decoding the batch analysis response for post $id: {$response['body']}" );
436 436
 
437
-				$this->set_state( $id, self::STATE_ERROR );
438
-				continue;
439
-			}
440
-
441
-			// Set the warning flag if needed.
442
-			$this->set_warning_based_on_content( $json->content, $id );
443
-
444
-			// Get the content, cleaned up if there are interpolation errors.
445
-			$pre_content = $this->fix_interpolation_errors( $json->content, $id );
446
-
447
-			/**
448
-			 * Filter: 'wl_batch_analysis_update_post_content' - Allow third
449
-			 * parties to perform additional actions when the post content is
450
-			 * updated.
451
-			 *
452
-			 * @since  3.17.0
453
-			 * @api    string $data The {@link WP_Post}'s content.
454
-			 * @api    int    $id   The {@link WP_Post}'s id.
455
-			 */
456
-			$content = apply_filters( 'wl_batch_analysis_update_post_content', $pre_content, $id );
437
+                $this->set_state( $id, self::STATE_ERROR );
438
+                continue;
439
+            }
440
+
441
+            // Set the warning flag if needed.
442
+            $this->set_warning_based_on_content( $json->content, $id );
443
+
444
+            // Get the content, cleaned up if there are interpolation errors.
445
+            $pre_content = $this->fix_interpolation_errors( $json->content, $id );
446
+
447
+            /**
448
+             * Filter: 'wl_batch_analysis_update_post_content' - Allow third
449
+             * parties to perform additional actions when the post content is
450
+             * updated.
451
+             *
452
+             * @since  3.17.0
453
+             * @api    string $data The {@link WP_Post}'s content.
454
+             * @api    int    $id   The {@link WP_Post}'s id.
455
+             */
456
+            $content = apply_filters( 'wl_batch_analysis_update_post_content', $pre_content, $id );
457 457
 
458
-			// Update the post content.
459
-			wp_update_post( array(
460
-				'ID'           => $id,
461
-				'post_content' => wp_slash( $content ),
462
-			) );
463
-
464
-			// Update the status.
465
-			$this->set_state( $id, self::STATE_SUCCESS );
466
-
467
-			// Invalidating the cache for the current post.
468
-			$this->cache_service->delete_cache( $id );
469
-
470
-			$this->log->debug( "Post $id updated with batch analysis results." );
471
-
472
-			// Set default entity type term for posts that didn't have any.
473
-			$this->maybe_set_default_term( $id );
474
-
475
-			// @todo: implement a kind of timeout that sets an error if the
476
-			// results haven't been received after a long time.
477
-		}
478
-
479
-		// Call the `wl_batch_analysis_request` action again. This is going
480
-		// to be handled by the async task.
481
-		do_action( 'wl_batch_analysis_complete' );
482
-
483
-	}
484
-
485
-	/**
486
-	 * Set a warning flag on the {@link WP_Post} if its content has suspicious
487
-	 * interpolations.
488
-	 *
489
-	 * @since 3.14.2
490
-	 *
491
-	 * @param string $content The {@link WP_Post}'s content.
492
-	 * @param int    $post_id The {@link WP_Post}'s id.
493
-	 */
494
-	protected function set_warning_based_on_content( $content, $post_id ) {
495
-
496
-		// Check for suspicious interpolations.
497
-		$is_warning = $this->has_interpolation_errors( $content );
498
-
499
-		// Set the warning flag accordingly.
500
-		$this->set_warning( $post_id, $is_warning );
501
-
502
-	}
503
-
504
-	private function has_interpolation_errors( $content ) {
505
-		$matches = array();
506
-
507
-		// eg:
508
-		// r-pro<span id="urn:local-text-annotation-oxbgy6139gnjgk1n0oxnq9zg62py29pf" class="textannotation disambiguated wl-thing" itemid="http://data.wordlift.it/be2/entity/developing_country">ne region, has shoul</span>dere
509
-
510
-		return 0 < preg_match_all( '/\w<[a-z]+ id="urn:[^"]+" class="[^"]+" itemid="[^"]+">/', $content, $matches )
511
-			   || 0 < preg_match_all( ' /<[a-z]+ id="urn:[^"]+ " class="[^"]+" itemid="[^"]+">\s/', $content, $matches );
512
-	}
513
-
514
-	/**
515
-	 * Fix interpolation errors raised by Batch Analysis
516
-	 *
517
-	 * @param string $content The {@link WP_Post}'s content.
518
-	 * @param int    $id      The {@link WP_Post}'s id.
519
-	 *
520
-	 * @since 3.17.0
521
-	 *
522
-	 * @return string Post content without interpolations.
523
-	 */
524
-	private function fix_interpolation_errors( $content, $id ) {
525
-
526
-		// Bail out if there are no interpolation errors.
527
-		if ( ! $this->has_interpolation_errors( $content ) ) {
528
-			$this->log->trace( "No interpolation errors found for post $id." );
529
-
530
-			return $content;
531
-		}
532
-
533
-		$this->log->debug( "Fixing post $id interpolations..." );
534
-
535
-		// Remove all interpolations from the content.
536
-		return preg_replace( self::$interpolation_patterns, '$1$2', $content );
537
-	}
538
-
539
-	/**
540
-	 * Clear the warning flag for the specified {@link WP_Post}s.
541
-	 *
542
-	 * @since 3.14.2
543
-	 *
544
-	 * @param int|array $post_ids A single {@link WP_Post}'s id or an array of
545
-	 *                            {@link WP_Post}s' ids.
546
-	 */
547
-	public function clear_warning( $post_ids ) {
548
-
549
-		foreach ( (array) $post_ids as $post_id ) {
550
-			delete_post_meta( $post_id, self::WARNING_META_KEY );
551
-		}
552
-
553
-	}
554
-
555
-	/**
556
-	 * Set the warning flag for the specified {@link WP_Post}.
557
-	 *
558
-	 * @since 3.14.2
559
-	 *
560
-	 * @param int  $post_id The {@link WP_Post}'s id.
561
-	 * @param bool $value   The flag's value.
562
-	 *
563
-	 * @return int|bool Meta ID if the key didn't exist, true on successful update,
564
-	 *                  false on failure.
565
-	 */
566
-	private function set_warning( $post_id, $value ) {
567
-
568
-		return update_post_meta( $post_id, self::WARNING_META_KEY, ( true === $value ? 'yes' : 'no' ) );
569
-	}
458
+            // Update the post content.
459
+            wp_update_post( array(
460
+                'ID'           => $id,
461
+                'post_content' => wp_slash( $content ),
462
+            ) );
463
+
464
+            // Update the status.
465
+            $this->set_state( $id, self::STATE_SUCCESS );
466
+
467
+            // Invalidating the cache for the current post.
468
+            $this->cache_service->delete_cache( $id );
469
+
470
+            $this->log->debug( "Post $id updated with batch analysis results." );
471
+
472
+            // Set default entity type term for posts that didn't have any.
473
+            $this->maybe_set_default_term( $id );
474
+
475
+            // @todo: implement a kind of timeout that sets an error if the
476
+            // results haven't been received after a long time.
477
+        }
478
+
479
+        // Call the `wl_batch_analysis_request` action again. This is going
480
+        // to be handled by the async task.
481
+        do_action( 'wl_batch_analysis_complete' );
482
+
483
+    }
484
+
485
+    /**
486
+     * Set a warning flag on the {@link WP_Post} if its content has suspicious
487
+     * interpolations.
488
+     *
489
+     * @since 3.14.2
490
+     *
491
+     * @param string $content The {@link WP_Post}'s content.
492
+     * @param int    $post_id The {@link WP_Post}'s id.
493
+     */
494
+    protected function set_warning_based_on_content( $content, $post_id ) {
495
+
496
+        // Check for suspicious interpolations.
497
+        $is_warning = $this->has_interpolation_errors( $content );
498
+
499
+        // Set the warning flag accordingly.
500
+        $this->set_warning( $post_id, $is_warning );
501
+
502
+    }
503
+
504
+    private function has_interpolation_errors( $content ) {
505
+        $matches = array();
506
+
507
+        // eg:
508
+        // r-pro<span id="urn:local-text-annotation-oxbgy6139gnjgk1n0oxnq9zg62py29pf" class="textannotation disambiguated wl-thing" itemid="http://data.wordlift.it/be2/entity/developing_country">ne region, has shoul</span>dere
509
+
510
+        return 0 < preg_match_all( '/\w<[a-z]+ id="urn:[^"]+" class="[^"]+" itemid="[^"]+">/', $content, $matches )
511
+               || 0 < preg_match_all( ' /<[a-z]+ id="urn:[^"]+ " class="[^"]+" itemid="[^"]+">\s/', $content, $matches );
512
+    }
513
+
514
+    /**
515
+     * Fix interpolation errors raised by Batch Analysis
516
+     *
517
+     * @param string $content The {@link WP_Post}'s content.
518
+     * @param int    $id      The {@link WP_Post}'s id.
519
+     *
520
+     * @since 3.17.0
521
+     *
522
+     * @return string Post content without interpolations.
523
+     */
524
+    private function fix_interpolation_errors( $content, $id ) {
525
+
526
+        // Bail out if there are no interpolation errors.
527
+        if ( ! $this->has_interpolation_errors( $content ) ) {
528
+            $this->log->trace( "No interpolation errors found for post $id." );
529
+
530
+            return $content;
531
+        }
532
+
533
+        $this->log->debug( "Fixing post $id interpolations..." );
534
+
535
+        // Remove all interpolations from the content.
536
+        return preg_replace( self::$interpolation_patterns, '$1$2', $content );
537
+    }
538
+
539
+    /**
540
+     * Clear the warning flag for the specified {@link WP_Post}s.
541
+     *
542
+     * @since 3.14.2
543
+     *
544
+     * @param int|array $post_ids A single {@link WP_Post}'s id or an array of
545
+     *                            {@link WP_Post}s' ids.
546
+     */
547
+    public function clear_warning( $post_ids ) {
548
+
549
+        foreach ( (array) $post_ids as $post_id ) {
550
+            delete_post_meta( $post_id, self::WARNING_META_KEY );
551
+        }
552
+
553
+    }
554
+
555
+    /**
556
+     * Set the warning flag for the specified {@link WP_Post}.
557
+     *
558
+     * @since 3.14.2
559
+     *
560
+     * @param int  $post_id The {@link WP_Post}'s id.
561
+     * @param bool $value   The flag's value.
562
+     *
563
+     * @return int|bool Meta ID if the key didn't exist, true on successful update,
564
+     *                  false on failure.
565
+     */
566
+    private function set_warning( $post_id, $value ) {
567
+
568
+        return update_post_meta( $post_id, self::WARNING_META_KEY, ( true === $value ? 'yes' : 'no' ) );
569
+    }
570 570
 
571 571
 //	/**
572 572
 //	 * Get the post/page batch analysis state.
@@ -582,231 +582,231 @@  discard block
 block discarded – undo
582 582
 //		return get_post_meta( $post_id, self::STATE_META_KEY, true );
583 583
 //	}
584 584
 
585
-	/**
586
-	 * Set the post/page batch analysis state.
587
-	 *
588
-	 * @since 3.14.2
589
-	 *
590
-	 * @param int $post_id The {@link WP_Post}'s id.
591
-	 * @param int $value   The new state.
592
-	 *
593
-	 * @return int|bool Meta ID if the key didn't exist, true on successful update,
594
-	 *                  false on failure.
595
-	 */
596
-	private function set_state( $post_id, $value ) {
597
-
598
-		// Update the state.
599
-		$result = update_post_meta( $post_id, self::STATE_META_KEY, $value );
600
-
601
-		// Update timestamps as required.
602
-		switch ( $value ) {
603
-
604
-			// ### REQUEST state.
605
-			case self::STATE_REQUEST:
606
-				add_post_meta( $post_id, self::REQUEST_TIMESTAMP_META_KEY, current_time( 'mysql', true ) );
607
-				break;
608
-
609
-			// ### SUCCESS/ERROR state.
610
-			case self::STATE_SUCCESS:
611
-			case self::STATE_ERROR:
612
-				add_post_meta( $post_id, self::COMPLETE_TIMESTAMP_META_KEY, current_time( 'mysql', true ) );
613
-				break;
614
-		}
615
-
616
-		// Finally return the result.
617
-		return $result;
618
-	}
619
-
620
-	/**
621
-	 * Get the options setting for a {@link WP_Post}.
622
-	 *
623
-	 * If there are multiple link settings, only the last one is returned.
624
-	 *
625
-	 * @since 3.14.2
626
-	 *
627
-	 * @param int $post_id The {@link WP_Post}'s id.
628
-	 *
629
-	 * @return array The link settings.
630
-	 */
631
-	private function get_options( $post_id ) {
632
-
633
-		$values = get_post_meta( $post_id, self::BATCH_ANALYSIS_OPTIONS_META_KEY );
634
-
635
-		return end( $values ) ?: array(
636
-			'links'           => 'default',
637
-			'min_occurrences' => 1,
638
-		);
639
-	}
640
-
641
-	/**
642
-	 * Get the array of post IDS waiting in the queue to start processing.
643
-	 *
644
-	 * @since 3.14.0
645
-	 *
646
-	 * @return array The waiting to be processed post ids queue.
647
-	 */
648
-	public function waiting_for_analysis() {
649
-
650
-		return get_posts( array(
651
-			'posts_per_page' => - 1,
652
-			'fields'         => 'ids',
653
-			'post_status'    => 'any',
654
-			'meta_key'       => self::STATE_META_KEY,
655
-			'meta_value'     => self::STATE_SUBMIT,
656
-			'orderby'        => 'ID',
657
-			'post_type'      => 'any',
658
-			// Add any because posts from multiple posts types may be waiting.
659
-		) );
660
-	}
661
-
662
-	/**
663
-	 * Get the array of post IDS waiting for response.
664
-	 *
665
-	 * @deprecated
666
-	 * @since 3.14.0
667
-	 *
668
-	 * @return array The waiting for response post ids queue.
669
-	 */
670
-	public function waiting_for_response() {
671
-
672
-		return get_posts( array(
673
-			'posts_per_page' => - 1,
674
-			'fields'         => 'ids',
675
-			'post_status'    => 'any',
676
-			'meta_key'       => self::STATE_META_KEY,
677
-			'meta_value'     => self::STATE_REQUEST,
678
-			'orderby'        => 'ID',
679
-			'post_type'      => 'any',
680
-			// Add any because posts from multiple posts types may be waiting.
681
-		) );
682
-	}
683
-
684
-	/**
685
-	 * Request the analysis for the specified {@link WP_Post}.
686
-	 *
687
-	 * @since 3.14.2
688
-	 *
689
-	 * @param int $post_id The {@link WP_Post}'s id.
690
-	 *
691
-	 * @return WP_Error|array The response or WP_Error on failure.
692
-	 */
693
-	private function do_request( $post_id ) {
694
-
695
-		// Change the state to `REQUEST`.
696
-		$this->set_state( $post_id, self::STATE_REQUEST );
697
-
698
-		// Get the post.
699
-		$post = get_post( $post_id );
700
-
701
-		// Bail out if the post isn't found.
702
-		if ( null === $post ) {
703
-			$this->log->warn( "Post $post_id not found." );
704
-
705
-			return new WP_Error( 0, "Cannot find post $post_id." );
706
-		}
707
-
708
-		// Get the link setting.
709
-		$options = $this->get_options( $post_id );
710
-
711
-		$this->log->debug( 'Sending analysis request for post $post_id [ links :: ' . $options['links'] . ', min_occurrences :: ' . $options['min_occurrences'] . ' ] ...' );
712
-
713
-		// Get the batch analysis URL.
714
-		$url = $this->configuration_service->get_batch_analysis_url();
715
-
716
-		// Prepare the POST parameters.
717
-		$params = array(
718
-			'id'              => $post->ID,
719
-			'key'             => $this->configuration_service->get_key(),
720
-			'content'         => $post->post_content,
721
-			'contentLanguage' => $this->configuration_service->get_language_code(),
722
-			'version'         => $this->plugin->get_version(),
723
-			'scope'           => 'local',
724
-			'links'           => $options['links'],
725
-			'minOccurrences'  => $options['min_occurrences'],
726
-		);
727
-
728
-		// Get the HTTP options.
729
-		$args = array_merge_recursive( unserialize( WL_REDLINK_API_HTTP_OPTIONS ), array(
730
-			'method'      => 'POST',
731
-			'headers'     => array(
732
-				'Accept'       => 'application/json',
733
-				'Content-type' => 'application/json; charset=UTF-8',
734
-			),
735
-			// we need to downgrade the HTTP version in this case since chunked encoding is dumping numbers in the response.
736
-			'httpversion' => '1.0',
737
-			'body'        => wp_json_encode( $params ),
738
-		) );
739
-
740
-		$this->log->debug( "Posting analysis request for post $post_id to $url..." );
741
-
742
-		// Post the parameter.
743
-		return wp_remote_post( $url, $args );
744
-	}
745
-
746
-	/**
747
-	 * Get the Batch Analysis results for the specified {@link WP_Post}.
748
-	 *
749
-	 * @since 3.14.2
750
-	 *
751
-	 * @param int $post_id The {@link WP_Post}'s id.
752
-	 *
753
-	 * @return WP_Error|array The response or WP_Error on failure.
754
-	 */
755
-	private function do_complete( $post_id ) {
756
-
757
-		$post = get_post( $post_id );
758
-
759
-		if ( null === $post ) {
760
-			// Post was possibly deleted, just bailout.
761
-			return new WP_Error( 0, "Post $post_id not found . " );
762
-		}
763
-
764
-		$url = $this->configuration_service->get_batch_analysis_url();
765
-		$key = $this->configuration_service->get_key();
766
-		$url = $url . '/' . $post->ID . '?key=' . $key;
767
-
768
-		return wp_remote_get( $url, unserialize( WL_REDLINK_API_HTTP_OPTIONS ) );
769
-	}
770
-
771
-	/**
772
-	 * Get the {@link WP_Post}s' ids flagged with warnings.
773
-	 *
774
-	 * @since 3.14.2
775
-	 *
776
-	 * @return array An array of {@link WP_Post}s' ids.
777
-	 */
778
-	public function get_warnings() {
779
-
780
-		return get_posts( array(
781
-			'fields'      => 'ids',
782
-			'numberposts' => - 1,
783
-			'post_status' => 'any',
784
-			'meta_key'    => self::WARNING_META_KEY,
785
-			'meta_value'  => 'yes',
786
-			'post_type'   => 'any',
787
-			// Add any because posts from multiple posts types may be waiting.
788
-		) );
789
-	}
790
-
791
-	/**
792
-	 * Check whether the term has entity type associated and set default term if it hasn't.
793
-	 *
794
-	 * @since 3.17.0
795
-	 *
796
-	 * @param int $id The {@link WP_Post}'s id.
797
-	 */
798
-	private function maybe_set_default_term( $id ) {
799
-		// Check whether the post has any of the WordLift entity types.
800
-		$has_term = has_term( '', Wordlift_Entity_Types_Taxonomy_Service::TAXONOMY_NAME, $id );
801
-
802
-		// Bail if the term is associated with entity types already.
803
-		if ( ! empty( $has_term ) ) {
804
-			return;
805
-		}
806
-
807
-		// Set the default `article` term.
808
-		wp_set_object_terms( $id, 'article', Wordlift_Entity_Types_Taxonomy_Service::TAXONOMY_NAME );
809
-
810
-	}
585
+    /**
586
+     * Set the post/page batch analysis state.
587
+     *
588
+     * @since 3.14.2
589
+     *
590
+     * @param int $post_id The {@link WP_Post}'s id.
591
+     * @param int $value   The new state.
592
+     *
593
+     * @return int|bool Meta ID if the key didn't exist, true on successful update,
594
+     *                  false on failure.
595
+     */
596
+    private function set_state( $post_id, $value ) {
597
+
598
+        // Update the state.
599
+        $result = update_post_meta( $post_id, self::STATE_META_KEY, $value );
600
+
601
+        // Update timestamps as required.
602
+        switch ( $value ) {
603
+
604
+            // ### REQUEST state.
605
+            case self::STATE_REQUEST:
606
+                add_post_meta( $post_id, self::REQUEST_TIMESTAMP_META_KEY, current_time( 'mysql', true ) );
607
+                break;
608
+
609
+            // ### SUCCESS/ERROR state.
610
+            case self::STATE_SUCCESS:
611
+            case self::STATE_ERROR:
612
+                add_post_meta( $post_id, self::COMPLETE_TIMESTAMP_META_KEY, current_time( 'mysql', true ) );
613
+                break;
614
+        }
615
+
616
+        // Finally return the result.
617
+        return $result;
618
+    }
619
+
620
+    /**
621
+     * Get the options setting for a {@link WP_Post}.
622
+     *
623
+     * If there are multiple link settings, only the last one is returned.
624
+     *
625
+     * @since 3.14.2
626
+     *
627
+     * @param int $post_id The {@link WP_Post}'s id.
628
+     *
629
+     * @return array The link settings.
630
+     */
631
+    private function get_options( $post_id ) {
632
+
633
+        $values = get_post_meta( $post_id, self::BATCH_ANALYSIS_OPTIONS_META_KEY );
634
+
635
+        return end( $values ) ?: array(
636
+            'links'           => 'default',
637
+            'min_occurrences' => 1,
638
+        );
639
+    }
640
+
641
+    /**
642
+     * Get the array of post IDS waiting in the queue to start processing.
643
+     *
644
+     * @since 3.14.0
645
+     *
646
+     * @return array The waiting to be processed post ids queue.
647
+     */
648
+    public function waiting_for_analysis() {
649
+
650
+        return get_posts( array(
651
+            'posts_per_page' => - 1,
652
+            'fields'         => 'ids',
653
+            'post_status'    => 'any',
654
+            'meta_key'       => self::STATE_META_KEY,
655
+            'meta_value'     => self::STATE_SUBMIT,
656
+            'orderby'        => 'ID',
657
+            'post_type'      => 'any',
658
+            // Add any because posts from multiple posts types may be waiting.
659
+        ) );
660
+    }
661
+
662
+    /**
663
+     * Get the array of post IDS waiting for response.
664
+     *
665
+     * @deprecated
666
+     * @since 3.14.0
667
+     *
668
+     * @return array The waiting for response post ids queue.
669
+     */
670
+    public function waiting_for_response() {
671
+
672
+        return get_posts( array(
673
+            'posts_per_page' => - 1,
674
+            'fields'         => 'ids',
675
+            'post_status'    => 'any',
676
+            'meta_key'       => self::STATE_META_KEY,
677
+            'meta_value'     => self::STATE_REQUEST,
678
+            'orderby'        => 'ID',
679
+            'post_type'      => 'any',
680
+            // Add any because posts from multiple posts types may be waiting.
681
+        ) );
682
+    }
683
+
684
+    /**
685
+     * Request the analysis for the specified {@link WP_Post}.
686
+     *
687
+     * @since 3.14.2
688
+     *
689
+     * @param int $post_id The {@link WP_Post}'s id.
690
+     *
691
+     * @return WP_Error|array The response or WP_Error on failure.
692
+     */
693
+    private function do_request( $post_id ) {
694
+
695
+        // Change the state to `REQUEST`.
696
+        $this->set_state( $post_id, self::STATE_REQUEST );
697
+
698
+        // Get the post.
699
+        $post = get_post( $post_id );
700
+
701
+        // Bail out if the post isn't found.
702
+        if ( null === $post ) {
703
+            $this->log->warn( "Post $post_id not found." );
704
+
705
+            return new WP_Error( 0, "Cannot find post $post_id." );
706
+        }
707
+
708
+        // Get the link setting.
709
+        $options = $this->get_options( $post_id );
710
+
711
+        $this->log->debug( 'Sending analysis request for post $post_id [ links :: ' . $options['links'] . ', min_occurrences :: ' . $options['min_occurrences'] . ' ] ...' );
712
+
713
+        // Get the batch analysis URL.
714
+        $url = $this->configuration_service->get_batch_analysis_url();
715
+
716
+        // Prepare the POST parameters.
717
+        $params = array(
718
+            'id'              => $post->ID,
719
+            'key'             => $this->configuration_service->get_key(),
720
+            'content'         => $post->post_content,
721
+            'contentLanguage' => $this->configuration_service->get_language_code(),
722
+            'version'         => $this->plugin->get_version(),
723
+            'scope'           => 'local',
724
+            'links'           => $options['links'],
725
+            'minOccurrences'  => $options['min_occurrences'],
726
+        );
727
+
728
+        // Get the HTTP options.
729
+        $args = array_merge_recursive( unserialize( WL_REDLINK_API_HTTP_OPTIONS ), array(
730
+            'method'      => 'POST',
731
+            'headers'     => array(
732
+                'Accept'       => 'application/json',
733
+                'Content-type' => 'application/json; charset=UTF-8',
734
+            ),
735
+            // we need to downgrade the HTTP version in this case since chunked encoding is dumping numbers in the response.
736
+            'httpversion' => '1.0',
737
+            'body'        => wp_json_encode( $params ),
738
+        ) );
739
+
740
+        $this->log->debug( "Posting analysis request for post $post_id to $url..." );
741
+
742
+        // Post the parameter.
743
+        return wp_remote_post( $url, $args );
744
+    }
745
+
746
+    /**
747
+     * Get the Batch Analysis results for the specified {@link WP_Post}.
748
+     *
749
+     * @since 3.14.2
750
+     *
751
+     * @param int $post_id The {@link WP_Post}'s id.
752
+     *
753
+     * @return WP_Error|array The response or WP_Error on failure.
754
+     */
755
+    private function do_complete( $post_id ) {
756
+
757
+        $post = get_post( $post_id );
758
+
759
+        if ( null === $post ) {
760
+            // Post was possibly deleted, just bailout.
761
+            return new WP_Error( 0, "Post $post_id not found . " );
762
+        }
763
+
764
+        $url = $this->configuration_service->get_batch_analysis_url();
765
+        $key = $this->configuration_service->get_key();
766
+        $url = $url . '/' . $post->ID . '?key=' . $key;
767
+
768
+        return wp_remote_get( $url, unserialize( WL_REDLINK_API_HTTP_OPTIONS ) );
769
+    }
770
+
771
+    /**
772
+     * Get the {@link WP_Post}s' ids flagged with warnings.
773
+     *
774
+     * @since 3.14.2
775
+     *
776
+     * @return array An array of {@link WP_Post}s' ids.
777
+     */
778
+    public function get_warnings() {
779
+
780
+        return get_posts( array(
781
+            'fields'      => 'ids',
782
+            'numberposts' => - 1,
783
+            'post_status' => 'any',
784
+            'meta_key'    => self::WARNING_META_KEY,
785
+            'meta_value'  => 'yes',
786
+            'post_type'   => 'any',
787
+            // Add any because posts from multiple posts types may be waiting.
788
+        ) );
789
+    }
790
+
791
+    /**
792
+     * Check whether the term has entity type associated and set default term if it hasn't.
793
+     *
794
+     * @since 3.17.0
795
+     *
796
+     * @param int $id The {@link WP_Post}'s id.
797
+     */
798
+    private function maybe_set_default_term( $id ) {
799
+        // Check whether the post has any of the WordLift entity types.
800
+        $has_term = has_term( '', Wordlift_Entity_Types_Taxonomy_Service::TAXONOMY_NAME, $id );
801
+
802
+        // Bail if the term is associated with entity types already.
803
+        if ( ! empty( $has_term ) ) {
804
+            return;
805
+        }
806
+
807
+        // Set the default `article` term.
808
+        wp_set_object_terms( $id, 'article', Wordlift_Entity_Types_Taxonomy_Service::TAXONOMY_NAME );
809
+
810
+    }
811 811
 
812 812
 }
Please login to merge, or discard this patch.
Spacing   +120 added lines, -120 removed lines patch added patch discarded remove patch
@@ -185,22 +185,22 @@  discard block
 block discarded – undo
185 185
 	 * @param \Wordlift_Configuration_Service $configuration_service The {@link Wordlift_Configuration_Service} instance.
186 186
 	 * @param \Wordlift_Cache_Service         $cache_service         The {@link Wordlift_Cache_Service} instance.
187 187
 	 */
188
-	public function __construct( $plugin, $configuration_service, $cache_service ) {
188
+	public function __construct($plugin, $configuration_service, $cache_service) {
189 189
 
190
-		$this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Batch_Analysis_Service' );
190
+		$this->log = Wordlift_Log_Service::get_logger('Wordlift_Batch_Analysis_Service');
191 191
 
192 192
 		$this->plugin                = $plugin;
193 193
 		$this->configuration_service = $configuration_service;
194 194
 		$this->cache_service         = $cache_service;
195 195
 
196
-		add_action( 'wl_async_wl_batch_analysis_request', array(
196
+		add_action('wl_async_wl_batch_analysis_request', array(
197 197
 			$this,
198 198
 			'request',
199
-		) );
200
-		add_action( 'wl_async_wl_batch_analysis_complete', array(
199
+		));
200
+		add_action('wl_async_wl_batch_analysis_complete', array(
201 201
 			$this,
202 202
 			'complete',
203
-		) );
203
+		));
204 204
 
205 205
 	}
206 206
 
@@ -231,11 +231,11 @@  discard block
 block discarded – undo
231 231
 	 *
232 232
 	 * @return int The number of submitted {@link WP_Post}s or false on error.
233 233
 	 */
234
-	public function submit( $args ) {
234
+	public function submit($args) {
235 235
 		global $wpdb;
236 236
 
237 237
 		// Parse the parameters.
238
-		$params = wp_parse_args( $args, array(
238
+		$params = wp_parse_args($args, array(
239 239
 			'links'             => 'default',
240 240
 			'min_occurrences'   => 1,
241 241
 			'include_annotated' => false,
@@ -243,24 +243,24 @@  discard block
 block discarded – undo
243 243
 			'from'              => null,
244 244
 			'to'                => null,
245 245
 			'post_type'         => 'post',
246
-		) );
246
+		));
247 247
 
248 248
 		// Validation.
249
-		if ( ! in_array( $params['links'], array( 'default', 'yes', 'no' ) ) ) {
250
-			wp_die( '`link` must be one of the following: `default`, `yes` or `no`.' );
249
+		if ( ! in_array($params['links'], array('default', 'yes', 'no'))) {
250
+			wp_die('`link` must be one of the following: `default`, `yes` or `no`.');
251 251
 		}
252 252
 
253
-		if ( ! is_numeric( $params['min_occurrences'] ) || 1 > $params['min_occurrences'] ) {
254
-			wp_die( '`min_occurrences` must greater or equal 1.' );
253
+		if ( ! is_numeric($params['min_occurrences']) || 1 > $params['min_occurrences']) {
254
+			wp_die('`min_occurrences` must greater or equal 1.');
255 255
 		}
256 256
 
257 257
 		// Submit the posts/pages and return the number of affected results.
258 258
 		// We're using a SQL query here because we could have potentially
259 259
 		// thousands of rows.
260
-		$count = $wpdb->query( Wordlift_Batch_Analysis_Sql_Helper::get_sql( $params ) ); // WPCS: cache ok, db call ok.
260
+		$count = $wpdb->query(Wordlift_Batch_Analysis_Sql_Helper::get_sql($params)); // WPCS: cache ok, db call ok.
261 261
 
262 262
 		// Request Batch Analysis (the operation is handled asynchronously).
263
-		do_action( 'wl_batch_analysis_request' );
263
+		do_action('wl_batch_analysis_request');
264 264
 
265 265
 		// Divide the count by 3 to get the number of posts/pages queued.
266 266
 		return $count / 3;
@@ -282,28 +282,28 @@  discard block
 block discarded – undo
282 282
 	 *
283 283
 	 * @return float|int
284 284
 	 */
285
-	public function submit_posts( $args ) {
285
+	public function submit_posts($args) {
286 286
 		global $wpdb;
287 287
 
288 288
 		// Parse the parameters.
289
-		$params = wp_parse_args( $args, array(
289
+		$params = wp_parse_args($args, array(
290 290
 			'links'           => 'default',
291 291
 			'min_occurrences' => 1,
292 292
 			'ids'             => array(),
293
-		) );
293
+		));
294 294
 
295 295
 		// Validation.
296
-		if ( empty( $params['ids'] ) ) {
297
-			wp_die( '`ids` cannot be empty.' );
296
+		if (empty($params['ids'])) {
297
+			wp_die('`ids` cannot be empty.');
298 298
 		}
299 299
 
300 300
 		// Submit the posts/pages and return the number of affected results.
301 301
 		// We're using a SQL query here because we could have potentially
302 302
 		// thousands of rows.
303
-		$count = $wpdb->query( Wordlift_Batch_Analysis_Sql_Helper::get_sql_for_ids( $params ) ); // WPCS: cache ok, db call ok.
303
+		$count = $wpdb->query(Wordlift_Batch_Analysis_Sql_Helper::get_sql_for_ids($params)); // WPCS: cache ok, db call ok.
304 304
 
305 305
 		// Request Batch Analysis (the operation is handled asynchronously).
306
-		do_action( 'wl_batch_analysis_request' );
306
+		do_action('wl_batch_analysis_request');
307 307
 
308 308
 		// Divide the count by 3 to get the number of posts/pages queued.
309 309
 		return $count / 3;
@@ -320,20 +320,20 @@  discard block
 block discarded – undo
320 320
 	 * @return false|int The number of cancelled {@link WP_Post}s or false on
321 321
 	 *                   error.
322 322
 	 */
323
-	public function cancel( $post_ids ) {
323
+	public function cancel($post_ids) {
324 324
 		global $wpdb;
325 325
 
326
-		return $wpdb->query( $wpdb->prepare(
326
+		return $wpdb->query($wpdb->prepare(
327 327
 			"
328 328
 			DELETE FROM $wpdb->postmeta
329 329
 			WHERE meta_key = %s
330 330
 				AND meta_value IN ( %d, %d )
331
-				AND post_id IN( " . implode( ',', wp_parse_id_list( $post_ids ) ) . " )
331
+				AND post_id IN( ".implode(',', wp_parse_id_list($post_ids))." )
332 332
 			",
333 333
 			self::STATE_META_KEY,
334 334
 			self::STATE_SUBMIT,
335 335
 			self::STATE_REQUEST
336
-		) ); // WPCS: cache ok, db call ok.
336
+		)); // WPCS: cache ok, db call ok.
337 337
 
338 338
 	}
339 339
 
@@ -344,46 +344,46 @@  discard block
 block discarded – undo
344 344
 	 */
345 345
 	public function request() {
346 346
 
347
-		$this->log->debug( 'Requesting analysis...' );
347
+		$this->log->debug('Requesting analysis...');
348 348
 
349 349
 		// By default 5 posts of any post type are returned.
350
-		$posts = get_posts( array(
350
+		$posts = get_posts(array(
351 351
 			'fields'     => 'ids',
352 352
 			'meta_key'   => self::STATE_META_KEY,
353 353
 			'meta_value' => self::STATE_SUBMIT,
354 354
 			'orderby'    => 'ID',
355 355
 			'post_type'  => 'any',
356
-		) );
356
+		));
357 357
 
358 358
 		// Bail out if there are no submitted posts.
359
-		if ( empty( $posts ) ) {
360
-			$this->log->debug( 'No posts to submit found, checking for completed requests...' );
359
+		if (empty($posts)) {
360
+			$this->log->debug('No posts to submit found, checking for completed requests...');
361 361
 
362
-			do_action( 'wl_batch_analysis_complete' );
362
+			do_action('wl_batch_analysis_complete');
363 363
 
364 364
 			return;
365 365
 		}
366 366
 
367 367
 		// Send a request for each post.
368
-		foreach ( $posts as $id ) {
368
+		foreach ($posts as $id) {
369 369
 
370
-			$this->log->debug( "Requesting analysis for post $id..." );
370
+			$this->log->debug("Requesting analysis for post $id...");
371 371
 
372 372
 			// Send the actual request to the remote service.
373
-			$result = $this->do_request( $id );
373
+			$result = $this->do_request($id);
374 374
 
375 375
 			// Set an error if we received an error.
376
-			if ( is_wp_error( $result ) ) {
377
-				$this->log->error( "An error occurred while requesting a batch analysis for post $id: " . $result->get_error_message() );
376
+			if (is_wp_error($result)) {
377
+				$this->log->error("An error occurred while requesting a batch analysis for post $id: ".$result->get_error_message());
378 378
 
379
-				$this->set_state( $id, self::STATE_ERROR );
379
+				$this->set_state($id, self::STATE_ERROR);
380 380
 			}
381 381
 
382 382
 		}
383 383
 
384 384
 		// Call the `wl_batch_analysis_request` action again. This is going
385 385
 		// to be handled by the async task.
386
-		do_action( 'wl_batch_analysis_request' );
386
+		do_action('wl_batch_analysis_request');
387 387
 
388 388
 	}
389 389
 
@@ -394,55 +394,55 @@  discard block
 block discarded – undo
394 394
 	 */
395 395
 	public function complete() {
396 396
 
397
-		$this->log->debug( 'Requesting results...' );
397
+		$this->log->debug('Requesting results...');
398 398
 
399 399
 		// By default 5 posts of any post type are returned.
400
-		$posts = get_posts( array(
400
+		$posts = get_posts(array(
401 401
 			'fields'     => 'ids',
402 402
 			'meta_key'   => self::STATE_META_KEY,
403 403
 			'meta_value' => self::STATE_REQUEST,
404 404
 			'orderby'    => 'ID',
405 405
 			'post_type'  => 'any',
406
-		) );
406
+		));
407 407
 
408 408
 		// Bail out if there are no submitted posts.
409
-		if ( empty( $posts ) ) {
410
-			$this->log->debug( 'No posts in request state found.' );
409
+		if (empty($posts)) {
410
+			$this->log->debug('No posts in request state found.');
411 411
 
412 412
 			return;
413 413
 		}
414 414
 
415 415
 		// Send a request for each post.
416
-		foreach ( $posts as $id ) {
417
-			$this->log->debug( "Requesting results for post $id..." );
416
+		foreach ($posts as $id) {
417
+			$this->log->debug("Requesting results for post $id...");
418 418
 
419 419
 			// Send the actual request to the remote service.
420
-			$response = $this->do_complete( $id );
420
+			$response = $this->do_complete($id);
421 421
 
422 422
 			// Move to the next item if we don't have a reply for this one.
423
-			if ( is_wp_error( $response ) || 200 !== (int) $response['response']['code'] || ! isset( $response['body'] ) ) {
423
+			if (is_wp_error($response) || 200 !== (int) $response['response']['code'] || ! isset($response['body'])) {
424 424
 				continue;
425 425
 			}
426 426
 
427
-			$this->log->debug( "Results received for post $id." );
427
+			$this->log->debug("Results received for post $id.");
428 428
 
429 429
 			// Save the returned content as new revision.
430
-			$json = json_decode( $response['body'] );
430
+			$json = json_decode($response['body']);
431 431
 
432 432
 			// Continue if the content isn't set.
433
-			if ( empty( $json->content ) ) {
433
+			if (empty($json->content)) {
434 434
 				// The post content is empty, so is should be marked as completed.
435
-				$this->log->error( "An error occurred while decoding the batch analysis response for post $id: {$response['body']}" );
435
+				$this->log->error("An error occurred while decoding the batch analysis response for post $id: {$response['body']}");
436 436
 
437
-				$this->set_state( $id, self::STATE_ERROR );
437
+				$this->set_state($id, self::STATE_ERROR);
438 438
 				continue;
439 439
 			}
440 440
 
441 441
 			// Set the warning flag if needed.
442
-			$this->set_warning_based_on_content( $json->content, $id );
442
+			$this->set_warning_based_on_content($json->content, $id);
443 443
 
444 444
 			// Get the content, cleaned up if there are interpolation errors.
445
-			$pre_content = $this->fix_interpolation_errors( $json->content, $id );
445
+			$pre_content = $this->fix_interpolation_errors($json->content, $id);
446 446
 
447 447
 			/**
448 448
 			 * Filter: 'wl_batch_analysis_update_post_content' - Allow third
@@ -453,24 +453,24 @@  discard block
 block discarded – undo
453 453
 			 * @api    string $data The {@link WP_Post}'s content.
454 454
 			 * @api    int    $id   The {@link WP_Post}'s id.
455 455
 			 */
456
-			$content = apply_filters( 'wl_batch_analysis_update_post_content', $pre_content, $id );
456
+			$content = apply_filters('wl_batch_analysis_update_post_content', $pre_content, $id);
457 457
 
458 458
 			// Update the post content.
459
-			wp_update_post( array(
459
+			wp_update_post(array(
460 460
 				'ID'           => $id,
461
-				'post_content' => wp_slash( $content ),
462
-			) );
461
+				'post_content' => wp_slash($content),
462
+			));
463 463
 
464 464
 			// Update the status.
465
-			$this->set_state( $id, self::STATE_SUCCESS );
465
+			$this->set_state($id, self::STATE_SUCCESS);
466 466
 
467 467
 			// Invalidating the cache for the current post.
468
-			$this->cache_service->delete_cache( $id );
468
+			$this->cache_service->delete_cache($id);
469 469
 
470
-			$this->log->debug( "Post $id updated with batch analysis results." );
470
+			$this->log->debug("Post $id updated with batch analysis results.");
471 471
 
472 472
 			// Set default entity type term for posts that didn't have any.
473
-			$this->maybe_set_default_term( $id );
473
+			$this->maybe_set_default_term($id);
474 474
 
475 475
 			// @todo: implement a kind of timeout that sets an error if the
476 476
 			// results haven't been received after a long time.
@@ -478,7 +478,7 @@  discard block
 block discarded – undo
478 478
 
479 479
 		// Call the `wl_batch_analysis_request` action again. This is going
480 480
 		// to be handled by the async task.
481
-		do_action( 'wl_batch_analysis_complete' );
481
+		do_action('wl_batch_analysis_complete');
482 482
 
483 483
 	}
484 484
 
@@ -491,24 +491,24 @@  discard block
 block discarded – undo
491 491
 	 * @param string $content The {@link WP_Post}'s content.
492 492
 	 * @param int    $post_id The {@link WP_Post}'s id.
493 493
 	 */
494
-	protected function set_warning_based_on_content( $content, $post_id ) {
494
+	protected function set_warning_based_on_content($content, $post_id) {
495 495
 
496 496
 		// Check for suspicious interpolations.
497
-		$is_warning = $this->has_interpolation_errors( $content );
497
+		$is_warning = $this->has_interpolation_errors($content);
498 498
 
499 499
 		// Set the warning flag accordingly.
500
-		$this->set_warning( $post_id, $is_warning );
500
+		$this->set_warning($post_id, $is_warning);
501 501
 
502 502
 	}
503 503
 
504
-	private function has_interpolation_errors( $content ) {
504
+	private function has_interpolation_errors($content) {
505 505
 		$matches = array();
506 506
 
507 507
 		// eg:
508 508
 		// r-pro<span id="urn:local-text-annotation-oxbgy6139gnjgk1n0oxnq9zg62py29pf" class="textannotation disambiguated wl-thing" itemid="http://data.wordlift.it/be2/entity/developing_country">ne region, has shoul</span>dere
509 509
 
510
-		return 0 < preg_match_all( '/\w<[a-z]+ id="urn:[^"]+" class="[^"]+" itemid="[^"]+">/', $content, $matches )
511
-			   || 0 < preg_match_all( ' /<[a-z]+ id="urn:[^"]+ " class="[^"]+" itemid="[^"]+">\s/', $content, $matches );
510
+		return 0 < preg_match_all('/\w<[a-z]+ id="urn:[^"]+" class="[^"]+" itemid="[^"]+">/', $content, $matches)
511
+			   || 0 < preg_match_all(' /<[a-z]+ id="urn:[^"]+ " class="[^"]+" itemid="[^"]+">\s/', $content, $matches);
512 512
 	}
513 513
 
514 514
 	/**
@@ -521,19 +521,19 @@  discard block
 block discarded – undo
521 521
 	 *
522 522
 	 * @return string Post content without interpolations.
523 523
 	 */
524
-	private function fix_interpolation_errors( $content, $id ) {
524
+	private function fix_interpolation_errors($content, $id) {
525 525
 
526 526
 		// Bail out if there are no interpolation errors.
527
-		if ( ! $this->has_interpolation_errors( $content ) ) {
528
-			$this->log->trace( "No interpolation errors found for post $id." );
527
+		if ( ! $this->has_interpolation_errors($content)) {
528
+			$this->log->trace("No interpolation errors found for post $id.");
529 529
 
530 530
 			return $content;
531 531
 		}
532 532
 
533
-		$this->log->debug( "Fixing post $id interpolations..." );
533
+		$this->log->debug("Fixing post $id interpolations...");
534 534
 
535 535
 		// Remove all interpolations from the content.
536
-		return preg_replace( self::$interpolation_patterns, '$1$2', $content );
536
+		return preg_replace(self::$interpolation_patterns, '$1$2', $content);
537 537
 	}
538 538
 
539 539
 	/**
@@ -544,10 +544,10 @@  discard block
 block discarded – undo
544 544
 	 * @param int|array $post_ids A single {@link WP_Post}'s id or an array of
545 545
 	 *                            {@link WP_Post}s' ids.
546 546
 	 */
547
-	public function clear_warning( $post_ids ) {
547
+	public function clear_warning($post_ids) {
548 548
 
549
-		foreach ( (array) $post_ids as $post_id ) {
550
-			delete_post_meta( $post_id, self::WARNING_META_KEY );
549
+		foreach ((array) $post_ids as $post_id) {
550
+			delete_post_meta($post_id, self::WARNING_META_KEY);
551 551
 		}
552 552
 
553 553
 	}
@@ -563,9 +563,9 @@  discard block
 block discarded – undo
563 563
 	 * @return int|bool Meta ID if the key didn't exist, true on successful update,
564 564
 	 *                  false on failure.
565 565
 	 */
566
-	private function set_warning( $post_id, $value ) {
566
+	private function set_warning($post_id, $value) {
567 567
 
568
-		return update_post_meta( $post_id, self::WARNING_META_KEY, ( true === $value ? 'yes' : 'no' ) );
568
+		return update_post_meta($post_id, self::WARNING_META_KEY, (true === $value ? 'yes' : 'no'));
569 569
 	}
570 570
 
571 571
 //	/**
@@ -593,23 +593,23 @@  discard block
 block discarded – undo
593 593
 	 * @return int|bool Meta ID if the key didn't exist, true on successful update,
594 594
 	 *                  false on failure.
595 595
 	 */
596
-	private function set_state( $post_id, $value ) {
596
+	private function set_state($post_id, $value) {
597 597
 
598 598
 		// Update the state.
599
-		$result = update_post_meta( $post_id, self::STATE_META_KEY, $value );
599
+		$result = update_post_meta($post_id, self::STATE_META_KEY, $value);
600 600
 
601 601
 		// Update timestamps as required.
602
-		switch ( $value ) {
602
+		switch ($value) {
603 603
 
604 604
 			// ### REQUEST state.
605 605
 			case self::STATE_REQUEST:
606
-				add_post_meta( $post_id, self::REQUEST_TIMESTAMP_META_KEY, current_time( 'mysql', true ) );
606
+				add_post_meta($post_id, self::REQUEST_TIMESTAMP_META_KEY, current_time('mysql', true));
607 607
 				break;
608 608
 
609 609
 			// ### SUCCESS/ERROR state.
610 610
 			case self::STATE_SUCCESS:
611 611
 			case self::STATE_ERROR:
612
-				add_post_meta( $post_id, self::COMPLETE_TIMESTAMP_META_KEY, current_time( 'mysql', true ) );
612
+				add_post_meta($post_id, self::COMPLETE_TIMESTAMP_META_KEY, current_time('mysql', true));
613 613
 				break;
614 614
 		}
615 615
 
@@ -628,11 +628,11 @@  discard block
 block discarded – undo
628 628
 	 *
629 629
 	 * @return array The link settings.
630 630
 	 */
631
-	private function get_options( $post_id ) {
631
+	private function get_options($post_id) {
632 632
 
633
-		$values = get_post_meta( $post_id, self::BATCH_ANALYSIS_OPTIONS_META_KEY );
633
+		$values = get_post_meta($post_id, self::BATCH_ANALYSIS_OPTIONS_META_KEY);
634 634
 
635
-		return end( $values ) ?: array(
635
+		return end($values) ?: array(
636 636
 			'links'           => 'default',
637 637
 			'min_occurrences' => 1,
638 638
 		);
@@ -647,8 +647,8 @@  discard block
 block discarded – undo
647 647
 	 */
648 648
 	public function waiting_for_analysis() {
649 649
 
650
-		return get_posts( array(
651
-			'posts_per_page' => - 1,
650
+		return get_posts(array(
651
+			'posts_per_page' => -1,
652 652
 			'fields'         => 'ids',
653 653
 			'post_status'    => 'any',
654 654
 			'meta_key'       => self::STATE_META_KEY,
@@ -656,7 +656,7 @@  discard block
 block discarded – undo
656 656
 			'orderby'        => 'ID',
657 657
 			'post_type'      => 'any',
658 658
 			// Add any because posts from multiple posts types may be waiting.
659
-		) );
659
+		));
660 660
 	}
661 661
 
662 662
 	/**
@@ -669,8 +669,8 @@  discard block
 block discarded – undo
669 669
 	 */
670 670
 	public function waiting_for_response() {
671 671
 
672
-		return get_posts( array(
673
-			'posts_per_page' => - 1,
672
+		return get_posts(array(
673
+			'posts_per_page' => -1,
674 674
 			'fields'         => 'ids',
675 675
 			'post_status'    => 'any',
676 676
 			'meta_key'       => self::STATE_META_KEY,
@@ -678,7 +678,7 @@  discard block
 block discarded – undo
678 678
 			'orderby'        => 'ID',
679 679
 			'post_type'      => 'any',
680 680
 			// Add any because posts from multiple posts types may be waiting.
681
-		) );
681
+		));
682 682
 	}
683 683
 
684 684
 	/**
@@ -690,25 +690,25 @@  discard block
 block discarded – undo
690 690
 	 *
691 691
 	 * @return WP_Error|array The response or WP_Error on failure.
692 692
 	 */
693
-	private function do_request( $post_id ) {
693
+	private function do_request($post_id) {
694 694
 
695 695
 		// Change the state to `REQUEST`.
696
-		$this->set_state( $post_id, self::STATE_REQUEST );
696
+		$this->set_state($post_id, self::STATE_REQUEST);
697 697
 
698 698
 		// Get the post.
699
-		$post = get_post( $post_id );
699
+		$post = get_post($post_id);
700 700
 
701 701
 		// Bail out if the post isn't found.
702
-		if ( null === $post ) {
703
-			$this->log->warn( "Post $post_id not found." );
702
+		if (null === $post) {
703
+			$this->log->warn("Post $post_id not found.");
704 704
 
705
-			return new WP_Error( 0, "Cannot find post $post_id." );
705
+			return new WP_Error(0, "Cannot find post $post_id.");
706 706
 		}
707 707
 
708 708
 		// Get the link setting.
709
-		$options = $this->get_options( $post_id );
709
+		$options = $this->get_options($post_id);
710 710
 
711
-		$this->log->debug( 'Sending analysis request for post $post_id [ links :: ' . $options['links'] . ', min_occurrences :: ' . $options['min_occurrences'] . ' ] ...' );
711
+		$this->log->debug('Sending analysis request for post $post_id [ links :: '.$options['links'].', min_occurrences :: '.$options['min_occurrences'].' ] ...');
712 712
 
713 713
 		// Get the batch analysis URL.
714 714
 		$url = $this->configuration_service->get_batch_analysis_url();
@@ -726,7 +726,7 @@  discard block
 block discarded – undo
726 726
 		);
727 727
 
728 728
 		// Get the HTTP options.
729
-		$args = array_merge_recursive( unserialize( WL_REDLINK_API_HTTP_OPTIONS ), array(
729
+		$args = array_merge_recursive(unserialize(WL_REDLINK_API_HTTP_OPTIONS), array(
730 730
 			'method'      => 'POST',
731 731
 			'headers'     => array(
732 732
 				'Accept'       => 'application/json',
@@ -734,13 +734,13 @@  discard block
 block discarded – undo
734 734
 			),
735 735
 			// we need to downgrade the HTTP version in this case since chunked encoding is dumping numbers in the response.
736 736
 			'httpversion' => '1.0',
737
-			'body'        => wp_json_encode( $params ),
738
-		) );
737
+			'body'        => wp_json_encode($params),
738
+		));
739 739
 
740
-		$this->log->debug( "Posting analysis request for post $post_id to $url..." );
740
+		$this->log->debug("Posting analysis request for post $post_id to $url...");
741 741
 
742 742
 		// Post the parameter.
743
-		return wp_remote_post( $url, $args );
743
+		return wp_remote_post($url, $args);
744 744
 	}
745 745
 
746 746
 	/**
@@ -752,20 +752,20 @@  discard block
 block discarded – undo
752 752
 	 *
753 753
 	 * @return WP_Error|array The response or WP_Error on failure.
754 754
 	 */
755
-	private function do_complete( $post_id ) {
755
+	private function do_complete($post_id) {
756 756
 
757
-		$post = get_post( $post_id );
757
+		$post = get_post($post_id);
758 758
 
759
-		if ( null === $post ) {
759
+		if (null === $post) {
760 760
 			// Post was possibly deleted, just bailout.
761
-			return new WP_Error( 0, "Post $post_id not found . " );
761
+			return new WP_Error(0, "Post $post_id not found . ");
762 762
 		}
763 763
 
764 764
 		$url = $this->configuration_service->get_batch_analysis_url();
765 765
 		$key = $this->configuration_service->get_key();
766
-		$url = $url . '/' . $post->ID . '?key=' . $key;
766
+		$url = $url.'/'.$post->ID.'?key='.$key;
767 767
 
768
-		return wp_remote_get( $url, unserialize( WL_REDLINK_API_HTTP_OPTIONS ) );
768
+		return wp_remote_get($url, unserialize(WL_REDLINK_API_HTTP_OPTIONS));
769 769
 	}
770 770
 
771 771
 	/**
@@ -777,15 +777,15 @@  discard block
 block discarded – undo
777 777
 	 */
778 778
 	public function get_warnings() {
779 779
 
780
-		return get_posts( array(
780
+		return get_posts(array(
781 781
 			'fields'      => 'ids',
782
-			'numberposts' => - 1,
782
+			'numberposts' => -1,
783 783
 			'post_status' => 'any',
784 784
 			'meta_key'    => self::WARNING_META_KEY,
785 785
 			'meta_value'  => 'yes',
786 786
 			'post_type'   => 'any',
787 787
 			// Add any because posts from multiple posts types may be waiting.
788
-		) );
788
+		));
789 789
 	}
790 790
 
791 791
 	/**
@@ -795,17 +795,17 @@  discard block
 block discarded – undo
795 795
 	 *
796 796
 	 * @param int $id The {@link WP_Post}'s id.
797 797
 	 */
798
-	private function maybe_set_default_term( $id ) {
798
+	private function maybe_set_default_term($id) {
799 799
 		// Check whether the post has any of the WordLift entity types.
800
-		$has_term = has_term( '', Wordlift_Entity_Types_Taxonomy_Service::TAXONOMY_NAME, $id );
800
+		$has_term = has_term('', Wordlift_Entity_Types_Taxonomy_Service::TAXONOMY_NAME, $id);
801 801
 
802 802
 		// Bail if the term is associated with entity types already.
803
-		if ( ! empty( $has_term ) ) {
803
+		if ( ! empty($has_term)) {
804 804
 			return;
805 805
 		}
806 806
 
807 807
 		// Set the default `article` term.
808
-		wp_set_object_terms( $id, 'article', Wordlift_Entity_Types_Taxonomy_Service::TAXONOMY_NAME );
808
+		wp_set_object_terms($id, 'article', Wordlift_Entity_Types_Taxonomy_Service::TAXONOMY_NAME);
809 809
 
810 810
 	}
811 811
 
Please login to merge, or discard this patch.