Completed
Push — develop ( 558e95...0accb6 )
by David
04:03
created

wordlift.php ➔ wordlift_buttonhooks()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 3
nc 2
nop 0
dl 0
loc 7
rs 9.2
c 0
b 0
f 0
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 49 and the first side effect is on line 29.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
/**
3
 * The plugin bootstrap file
4
 *
5
 * This file is read by WordPress to generate the plugin information in the plugin
6
 * admin area. This file also includes all of the dependencies used by the plugin,
7
 * registers the activation and deactivation functions, and defines a function
8
 * that starts the plugin.
9
 *
10
 * @link              https://wordlift.io
11
 * @since             1.0.0
12
 * @package           Wordlift
13
 *
14
 * @wordpress-plugin
15
 * Plugin Name:       WordLift
16
 * Plugin URI:        https://wordlift.io
17
 * Description:       WordLift brings the power of AI to organize content, attract new readers and get their attention. To activate the plugin ​<a href="https://wordlift.io/">visit our website</a>.
18
 * Version:           3.12.0-dev
19
 * Author:            WordLift, Insideout10
20
 * Author URI:        https://wordlift.io
21
 * License:           GPL-2.0+
22
 * License URI:       http://www.gnu.org/licenses/gpl-2.0.txt
23
 * Text Domain:       wordlift
24
 * Domain Path:       /languages
25
 */
26
27
// If this file is called directly, abort.
28
if ( ! defined( 'WPINC' ) ) {
29
	die;
30
}
31
32
// Include WordLift constants.
33
require_once( 'wordlift_constants.php' );
34
35
// Load modules
36
require_once( 'modules/core/wordlift_core.php' );
37
38
/**
39
 * Log to the debug.log file.
40
 *
41
 * @deprecated use Wordlift_Log_Service::get_instance()->info( $log );
42
 *
43
 * @since      3.0.0
44
 *
45
 * @uses       wl_write_log_handler() to write the log output.
46
 *
47
 * @param string|mixed $log The log data.
48
 */
49
function wl_write_log( $log ) {
50
51
	Wordlift_Log_Service::get_instance()->info( $log );
52
53
//	$handler = apply_filters( 'wl_write_log_handler', null );
0 ignored issues
show
Unused Code Comprehensibility introduced by
48% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
54
//
55
//	$callers         = debug_backtrace();
56
//	$caller_function = $callers[1]['function'];
57
//
58
//	if ( is_null( $handler ) ) {
59
//		wl_write_log_handler( $log, $caller_function );
60
//
61
//		return;
62
//	}
63
//
64
//	call_user_func( $handler, $log, $caller_function );
65
}
66
67
/**
68
 * The default log handler prints out the log.
69
 *
70
 * @deprecated
71
 *
72
 * @since 3.0.0
73
 *
74
 * @param string|array $log    The log data.
75
 * @param string       $caller The calling function.
76
 */
77
function wl_write_log_handler( $log, $caller = null ) {
78
79
	global $wl_logger;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
80
81
	if ( true === WP_DEBUG ) {
82
83
		$message = ( isset( $caller ) ? sprintf( '[%-40.40s] ', $caller ) : '' ) .
84
		           ( is_array( $log ) || is_object( $log ) ? print_r( $log, true ) : wl_write_log_hide_key( $log ) );
0 ignored issues
show
Deprecated Code introduced by
The function wl_write_log_hide_key() has been deprecated.

This function has been deprecated.

Loading history...
85
86
		if ( isset( $wl_logger ) ) {
87
			$wl_logger->info( $message );
88
		} else {
89
			error_log( $message );
90
		}
91
92
	}
93
94
}
95
96
/**
97
 * Hide the WordLift Key from the provided text.
98
 *
99
 * @deprecated
100
 *
101
 * @since 3.0.0
102
 *
103
 * @param $text string A text that may potentially contain a WL key.
104
 *
105
 * @return string A text with the key hidden.
106
 */
107
function wl_write_log_hide_key( $text ) {
108
109
	return str_ireplace( wl_configuration_get_key(), '<hidden>', $text );
0 ignored issues
show
Deprecated Code introduced by
The function wl_configuration_get_key() has been deprecated with message: use Wordlift_Configuration_Service::get_instance()->get_key()

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
110
}
111
112
/**
113
 * Write the query to the buffer file.
114
 *
115
 * @since 3.0.0
116
 *
117
 * @param string $query A SPARQL query.
118
 */
119
function wl_queue_sparql_update_query( $query ) {
120
121
	$filename = WL_TEMP_DIR . WL_REQUEST_ID . '.sparql';
122
	file_put_contents( $filename, $query . "\n", FILE_APPEND );
123
124
	wl_write_log( "wl_queue_sparql_update_query [ filename :: $filename ]" );
0 ignored issues
show
Deprecated Code introduced by
The function wl_write_log() has been deprecated with message: use Wordlift_Log_Service::get_instance()->info( $log );

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
125
}
126
127
/**
128
 * Execute the SPARQL query from the buffer saved for the specified request id.
129
 *
130
 * @param int $request_id The request ID.
131
 */
132
function wl_execute_saved_sparql_update_query( $request_id ) {
133
134
	$filename = WL_TEMP_DIR . $request_id . '.sparql';
135
136
	// If the file doesn't exist, exit.
137
	if ( ! file_exists( $filename ) ) {
138
		wl_write_log( "wl_execute_saved_sparql_update_query : file doesn't exist [ filename :: $filename ]" );
0 ignored issues
show
Deprecated Code introduced by
The function wl_write_log() has been deprecated with message: use Wordlift_Log_Service::get_instance()->info( $log );

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
139
140
		return;
141
	}
142
143
	wl_write_log( "wl_execute_saved_sparql_update_query [ filename :: $filename ]" );
0 ignored issues
show
Deprecated Code introduced by
The function wl_write_log() has been deprecated with message: use Wordlift_Log_Service::get_instance()->info( $log );

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
144
145
	// Get the query saved in the file.
146
	$query = file_get_contents( $filename );
147
148
	// Execute the SPARQL query.
149
	rl_execute_sparql_update_query( $query, false );
150
151
	// Reindex the triple store.
152
	wordlift_reindex_triple_store();
153
154
	// Delete the temporary file.
155
	unlink( $filename );
156
}
157
158
add_action( 'wl_execute_saved_sparql_update_query', 'wl_execute_saved_sparql_update_query', 10, 1 );
159
160
///**
161
// * Add buttons hook for the TinyMCE editor. This method is called by the WP init hook.
162
// */
163
//function wordlift_buttonhooks() {
164
//
165
//	// Only add hooks when the current user has permissions AND is in Rich Text editor mode
166
//	if ( ( current_user_can( 'edit_posts' ) || current_user_can( 'edit_pages' ) ) && get_user_option( 'rich_editing' ) ) {
167
//		add_filter( 'mce_external_plugins', 'wordlift_register_tinymce_javascript' );
168
//	}
169
//}
170
171
///**
172
// * Load the TinyMCE plugin. This method is called by the WP mce_external_plugins hook.
173
// *
174
// * @param array $plugin_array The existing plugins array.
175
// *
176
// * @return array The modified plugins array.
177
// */
178
//function wordlift_register_tinymce_javascript( $plugin_array ) {
179
//
180
//	// add the wordlift plugin.
181
//	// We can't use the minified version here.
182
//
183
//	// Get WordLift's version as a cache killer.
184
//	$version = Wordlift::get_instance()->get_version();
185
//
186
//	// Add our own JavaScript file to TinyMCE's extensions.
187
//	$plugin_array['wordlift']   = plugin_dir_url( __FILE__ ) . 'js/wordlift-reloaded.js?ver=' . $version;
188
//	$plugin_array['wl_tinymce'] = plugin_dir_url( __FILE__ ) . 'js/wordlift-admin-tinymce.bundle.js?ver=' . $version;
189
//
190
//	return $plugin_array;
191
//}
192
193
/**
194
 * Enable microdata schema.org tagging.
195
 * see http://vip.wordpress.com/documentation/register-additional-html-attributes-for-tinymce-and-wp-kses/
196
 */
197
function wordlift_allowed_post_tags() {
198
	global $allowedposttags;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
199
200
	$tags           = array( 'span' );
201
	$new_attributes = array(
202
		'itemscope' => array(),
203
		'itemtype'  => array(),
204
		'itemprop'  => array(),
205
		'itemid'    => array(),
206
	);
207
208
	foreach ( $tags as $tag ) {
209
		if ( isset( $allowedposttags[ $tag ] ) && is_array( $allowedposttags[ $tag ] ) ) {
210
			$allowedposttags[ $tag ] = array_merge( $allowedposttags[ $tag ], $new_attributes );
211
		}
212
	}
213
}
214
215
// init process for button control
216
add_action( 'init', 'wordlift_buttonhooks' );
217
// add allowed post tags.
218
add_action( 'init', 'wordlift_allowed_post_tags' );
219
220
221
/**
222
 * Register additional scripts for the admin UI.
223
 */
224
function wordlift_admin_enqueue_scripts() {
225
226
	// Added for compatibility with WordPress 3.9 (see http://make.wordpress.org/core/2014/04/16/jquery-ui-and-wpdialogs-in-wordpress-3-9/)
227
	wp_enqueue_script( 'wpdialogs' );
228
	wp_enqueue_style( 'wp-jquery-ui-dialog' );
229
230
	wp_enqueue_style( 'wordlift-reloaded', plugin_dir_url( __FILE__ ) . 'css/wordlift-reloaded.min.css' );
231
232
	wp_enqueue_script( 'jquery-ui-autocomplete' );
233
	wp_enqueue_script( 'angularjs', 'https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.11/angular.min.js' );
234
	wp_enqueue_script( 'angularjs-geolocation', plugin_dir_url( __FILE__ ) . '/bower_components/angularjs-geolocation/dist/angularjs-geolocation.min.js' );
235
	wp_enqueue_script( 'angularjs-touch', 'https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.11/angular-touch.min.js' );
236
	wp_enqueue_script( 'angularjs-animate', 'https://code.angularjs.org/1.3.11/angular-animate.min.js' );
237
238
	// Disable auto-save for custom entity posts only
239
	if ( Wordlift_Entity_Service::TYPE_NAME === get_post_type() ) {
240
		wp_dequeue_script( 'autosave' );
241
	}
242
}
243
244
add_action( 'admin_enqueue_scripts', 'wordlift_admin_enqueue_scripts' );
245
246
function wl_enqueue_scripts() {
247
	wp_enqueue_style( 'wordlift-ui', plugin_dir_url( __FILE__ ) . 'css/wordlift-ui.min.css' );
248
}
249
250
add_action( 'wp_enqueue_scripts', 'wl_enqueue_scripts' );
251
252
/**
253
 * Hooked to *wp_kses_allowed_html* filter, adds microdata attributes.
254
 *
255
 * @param array  $allowedtags The array with the currently configured elements and attributes.
256
 * @param string $context     The context.
257
 *
258
 * @return array An array which contains allowed microdata attributes.
259
 */
260
function wordlift_allowed_html( $allowedtags, $context ) {
261
262
	if ( 'post' !== $context ) {
263
		return $allowedtags;
264
	}
265
266
	return array_merge_recursive( $allowedtags, array(
267
		'span' => array(
268
			'itemscope' => true,
269
			'itemtype'  => true,
270
			'itemid'    => true,
271
			'itemprop'  => true,
272
		),
273
	) );
274
}
275
276
add_filter( 'wp_kses_allowed_html', 'wordlift_allowed_html', 10, 2 );
277
278
/**
279
 * Get the coordinates for the specified post ID.
280
 *
281
 * @param int $post_id The post ID.
282
 *
283
 * @return array|null An array of coordinates or null.
284
 */
285
function wl_get_coordinates( $post_id ) {
286
287
	$latitude  = wl_schema_get_value( $post_id, 'latitude' );
288
	$longitude = wl_schema_get_value( $post_id, 'longitude' );
289
290
	// DO NOT set latitude/longitude to 0/0 as default values. It's a specific place on the globe:
291
	// "The zero/zero point of this system is located in the Gulf of Guinea about 625 km (390 mi) south of Tema, Ghana."
292
	return array(
293
		'latitude'  => isset( $latitude[0] ) && is_numeric( $latitude[0] ) ? $latitude[0] : '',
294
		'longitude' => isset( $longitude[0] ) && is_numeric( $longitude[0] ) ? $longitude[0] : '',
295
	);
296
}
297
298
/**
299
 * Get the modified time of the provided post. If the time is negative, return the published date.
300
 *
301
 * @param object $post A post instance.
302
 *
303
 * @return string A datetime.
304
 */
305
function wl_get_post_modified_time( $post ) {
306
307
	$date_modified = get_post_modified_time( 'c', true, $post );
308
309
	if ( '-' === substr( $date_modified, 0, 1 ) ) {
310
		return get_the_time( 'c', $post );
311
	}
312
313
	return $date_modified;
314
}
315
316
/**
317
 * Get all the images bound to a post.
318
 *
319
 * @param int $post_id The post ID.
320
 *
321
 * @return array An array of image URLs.
322
 */
323
function wl_get_image_urls( $post_id ) {
324
325
326
	// If there is a featured image it has the priority
327
	$featured_image_id = get_post_thumbnail_id( $post_id );
328
	if ( is_numeric( $featured_image_id ) ) {
329
		$image_url = wp_get_attachment_url( $featured_image_id );
330
331
		return array( $image_url );
332
	}
333
334
	// wl_write_log( "wl_get_image_urls [ post id :: $post_id ]" );
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
335
336
	$images = get_children( array(
337
		'post_parent'    => $post_id,
338
		'post_type'      => 'attachment',
339
		'post_mime_type' => 'image',
340
	) );
341
342
	// Return an empty array if no image is found.
343
	if ( empty( $images ) ) {
344
		return array();
345
	}
346
347
	// Prepare the return array.
348
	$image_urls = array();
349
350
	// Collect the URLs.
351
	foreach ( $images as $attachment_id => $attachment ) {
352
		$image_url = wp_get_attachment_url( $attachment_id );
353
		// Ensure the URL isn't collected already.
354
		if ( ! in_array( $image_url, $image_urls ) ) {
355
			array_push( $image_urls, $image_url );
356
		}
357
	}
358
359
	// wl_write_log( "wl_get_image_urls [ post id :: $post_id ][ image urls count :: " . count( $image_urls ) . " ]" );
0 ignored issues
show
Unused Code Comprehensibility introduced by
39% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
360
361
	return $image_urls;
362
}
363
364
/**
365
 * Get a SPARQL fragment with schema:image predicates.
366
 *
367
 * @param string $uri     The URI subject of the statements.
368
 * @param int    $post_id The post ID.
369
 *
370
 * @return string The SPARQL fragment.
371
 */
372
function wl_get_sparql_images( $uri, $post_id ) {
373
374
	$sparql = '';
375
376
	// Get the escaped URI.
377
	$uri_e = esc_html( $uri );
378
379
	// Add SPARQL stmts to write the schema:image.
380
	$image_urls = wl_get_image_urls( $post_id );
381
	foreach ( $image_urls as $image_url ) {
382
		$image_url_esc = wl_sparql_escape_uri( $image_url );
0 ignored issues
show
Deprecated Code introduced by
The function wl_sparql_escape_uri() has been deprecated with message: use return Wordlift_Sparql_Service::get_instance()->escape_uri($string)

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
383
		$sparql .= " <$uri_e> schema:image <$image_url_esc> . \n";
384
	}
385
386
	return $sparql;
387
}
388
389
/**
390
 * Get an attachment with the specified parent post ID and source URL.
391
 *
392
 * @param int    $parent_post_id The parent post ID.
393
 * @param string $source_url     The source URL.
394
 *
395
 * @return WP_Post|null A post instance or null if not found.
396
 */
397
function wl_get_attachment_for_source_url( $parent_post_id, $source_url ) {
398
399
	// wl_write_log( "wl_get_attachment_for_source_url [ parent post id :: $parent_post_id ][ source url :: $source_url ]" );
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
400
401
	$posts = get_posts( array(
402
		'post_type'      => 'attachment',
403
		'posts_per_page' => 1,
404
		'post_status'    => 'any',
405
		'post_parent'    => $parent_post_id,
406
		'meta_key'       => 'wl_source_url',
407
		'meta_value'     => $source_url,
408
	) );
409
410
	// Return the found post.
411
	if ( 1 === count( $posts ) ) {
412
		return $posts[0];
413
	}
414
415
	// Return null.
416
	return null;
417
}
418
419
/**
420
 * Set the source URL.
421
 *
422
 * @param int    $post_id    The post ID.
423
 * @param string $source_url The source URL.
424
 */
425
function wl_set_source_url( $post_id, $source_url ) {
426
427
	delete_post_meta( $post_id, 'wl_source_url' );
428
	add_post_meta( $post_id, 'wl_source_url', $source_url );
429
}
430
431
432
/**
433
 * This function is called by the *flush_rewrite_rules_hard* hook. It recalculates the URI for all the posts.
434
 *
435
 * @since 3.0.0
436
 *
437
 * @uses  rl_sparql_prefixes() to get the SPARQL prefixes.
438
 * @uses  wordlift_esc_sparql() to escape the SPARQL query.
439
 * @uses  wl_get_entity_uri() to get an entity URI.
440
 * @uses  rl_execute_sparql_update_query() to post the DELETE and INSERT queries.
441
 *
442
 * @param bool $hard True if the rewrite involves configuration updates in Apache/IIS.
443
 */
444
function wl_flush_rewrite_rules_hard( $hard ) {
0 ignored issues
show
Unused Code introduced by
The parameter $hard is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
445
446
	// If WL is not yet configured, we cannot perform any update, so we exit.
447
	if ( '' === wl_configuration_get_key() ) {
0 ignored issues
show
Deprecated Code introduced by
The function wl_configuration_get_key() has been deprecated with message: use Wordlift_Configuration_Service::get_instance()->get_key()

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
448
		return;
449
	}
450
451
	// Set the initial offset and limit each call to 100 posts to avoid memory errors.
452
	$offset = 0;
453
	$limit  = 100;
454
455
	// Get more posts if the number of returned posts matches the limit.
456
	while ( $limit === ( $posts = get_posts( array(
457
			'offset'      => $offset,
458
			'numberposts' => $limit,
459
			'orderby'     => 'ID',
460
			'post_type'   => 'any',
461
			'post_status' => 'publish',
462
		) ) ) ) {
463
464
		// Holds the delete part of the query.
465
		$delete_query = rl_sparql_prefixes();
466
467
		// Holds the insert part of the query.
468
		$insert_query = '';
469
470
		// Cycle in each post to build the query.
471
		foreach ( $posts as $post ) {
472
473
			// Ignore revisions.
474
			if ( wp_is_post_revision( $post->ID ) ) {
475
				continue;
476
			}
477
478
			// Get the entity URI.
479
			$s = Wordlift_Sparql_Service::escape_uri( Wordlift_Entity_Service::get_instance()
480
			                                                                 ->get_uri( $post->ID ) );
481
482
			// Get the post URL.
483
			// $url = wl_sparql_escape_uri( get_permalink( $post->ID ) );
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
484
485
			// Prepare the DELETE and INSERT commands.
486
			$delete_query .= "DELETE { <$s> schema:url ?u . } WHERE  { <$s> schema:url ?u . };\n";
487
488
			$insert_query .= Wordlift_Schema_Url_Property_Service::get_instance()
489
			                                                     ->get_insert_query( $s, $post->ID );
490
491
		}
492
493
494
		// Execute the query.
495
		rl_execute_sparql_update_query( $delete_query . $insert_query );
496
497
		// Advance to the next posts.
498
		$offset += $limit;
499
500
	}
501
502
//	// Get all published posts.
0 ignored issues
show
Unused Code Comprehensibility introduced by
42% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
503
//	$posts = get_posts( array(
504
//		'posts_per_page' => - 1,
505
//		'post_type'      => 'any',
506
//		'post_status'    => 'publish'
507
//	) );
508
509
}
510
511
add_filter( 'flush_rewrite_rules_hard', 'wl_flush_rewrite_rules_hard', 10, 1 );
512
513
/**
514
 * Sanitizes an URI path by replacing the non allowed characters with an underscore.
515
 * @uses       sanitize_title() to manage not ASCII chars
516
 * @deprecated use Wordlift_Uri_Service::get_instance()->sanitize_path();
517
 * @see        https://codex.wordpress.org/Function_Reference/sanitize_title
518
 *
519
 * @param string $path The path to sanitize.
520
 * @param string $char The replacement character (by default an underscore).
521
 *
522
 * @return string The sanitized path.
523
 */
524
function wl_sanitize_uri_path( $path, $char = '_' ) {
525
526
	return Wordlift_Uri_Service::get_instance()->sanitize_path( $path, $char );
527
}
528
529
/**
530
 * Utility function to check if a variable is set and force it to be an array
531
 *
532
 * @package mixed $value Any value
533
 *
534
 * @return array Array containing $value (if $value was not an array)
535
 */
536
function wl_force_to_array( $value ) {
537
538
	if ( ! is_array( $value ) ) {
539
		return array( $value );
540
	}
541
542
	return $value;
543
}
544
545
/**
546
 * Schedule the execution of SPARQL Update queries before the WordPress look ends.
547
 */
548
function wl_shutdown() {
549
550
	// Get the filename to the temporary SPARQL file.
551
	$filename = WL_TEMP_DIR . WL_REQUEST_ID . '.sparql';
552
553
	// If WordLift is buffering SPARQL queries, we're admins and a buffer exists, then schedule it.
554
	if ( WL_ENABLE_SPARQL_UPDATE_QUERIES_BUFFERING && is_admin() && file_exists( $filename ) ) {
555
556
		// The request ID.
557
		$args = array( WL_REQUEST_ID );
558
559
		// Schedule the execution of the SPARQL query with the request ID.
560
		wp_schedule_single_event( time(), 'wl_execute_saved_sparql_update_query', $args );
561
562
		// Check that the request is scheduled.
563
		$timestamp = wp_next_scheduled( 'wl_execute_saved_sparql_update_query', $args );
564
565
		// Spawn the cron.
566
		spawn_cron();
567
568
		wl_write_log( "wl_shutdown [ request id :: " . WL_REQUEST_ID . " ][ timestamp :: $timestamp ]" );
0 ignored issues
show
Deprecated Code introduced by
The function wl_write_log() has been deprecated with message: use Wordlift_Log_Service::get_instance()->info( $log );

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
569
	}
570
}
571
572
add_action( 'shutdown', 'wl_shutdown' );
573
574
/**
575
 * Replaces the *itemid* attributes URIs with the WordLift URIs.
576
 *
577
 * @param string $content The post content.
578
 *
579
 * @return string The updated post content.
580
 */
581
function wl_replace_item_id_with_uri( $content ) {
582
583
	// wl_write_log( "wl_replace_item_id_with_uri" );
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
584
585
	// Strip slashes, see https://core.trac.wordpress.org/ticket/21767
586
	$content = stripslashes( $content );
587
588
	// If any match are found.
589
	$matches = array();
590
	if ( 0 < preg_match_all( '/ itemid="([^"]+)"/i', $content, $matches, PREG_SET_ORDER ) ) {
591
592
		foreach ( $matches as $match ) {
0 ignored issues
show
Bug introduced by
The expression $matches of type null|array<integer,array<integer,string>> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
593
594
			// Get the item ID.
595
			$item_id = $match[1];
596
597
			// Get the post bound to that item ID (looking both in the 'official' URI and in the 'same-as' .
598
			$post = Wordlift_Entity_Service::get_instance()
599
			                               ->get_entity_post_by_uri( $item_id );
600
601
			// If no entity is found, continue to the next one.
602
			if ( null === $post ) {
603
				continue;
604
			}
605
606
			// Get the URI for that post.
607
			$uri = wl_get_entity_uri( $post->ID );
0 ignored issues
show
Deprecated Code introduced by
The function wl_get_entity_uri() has been deprecated with message: use Wordlift_Entity_Service::get_instance()->get_uri( $post_id )

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
608
609
			// wl_write_log( "wl_replace_item_id_with_uri [ item id :: $item_id ][ uri :: $uri ]" );
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
610
611
			// If the item ID and the URI differ, replace the item ID with the URI saved in WordPress.
612
			if ( $item_id !== $uri ) {
613
				$uri_e   = esc_html( $uri );
614
				$content = str_replace( " itemid=\"$item_id\"", " itemid=\"$uri_e\"", $content );
615
			}
616
		}
617
	}
618
619
	// Reapply slashes.
620
	$content = addslashes( $content );
621
622
	return $content;
623
}
624
625
add_filter( 'content_save_pre', 'wl_replace_item_id_with_uri', 1, 1 );
626
627
require_once( 'wordlift_entity_functions.php' );
628
629
// add editor related methods.
630
require_once( 'wordlift_editor.php' );
631
632
// add the WordLift entity custom type.
633
require_once( 'wordlift_entity_type.php' );
634
require_once( 'wordlift_entity_type_taxonomy.php' );
635
636
// add callbacks on post save to notify data changes from wp to redlink triple store
637
require_once( 'wordlift_to_redlink_data_push_callbacks.php' );
638
639
require_once( 'modules/configuration/wordlift_configuration_settings.php' );
640
641
// Load modules
642
require_once( 'modules/analyzer/wordlift_analyzer.php' );
643
require_once( 'modules/linked_data/wordlift_linked_data.php' );
644
require_once( 'modules/prefixes/wordlift_prefixes.php' );
645
require_once( 'modules/redirector/wordlift_redirector.php' );
646
647
// Shortcodes
648
649
require_once( 'modules/geo_widget/wordlift_geo_widget.php' );
650
require_once( 'shortcodes/wordlift_shortcode_chord.php' );
651
require_once( 'shortcodes/wordlift_shortcode_geomap.php' );
652
require_once( 'shortcodes/wordlift_shortcode_field.php' );
653
require_once( 'shortcodes/wordlift_shortcode_faceted_search.php' );
654
require_once( 'shortcodes/wordlift_shortcode_navigator.php' );
655
656
require_once( 'widgets/wordlift_widget_geo.php' );
657
require_once( 'widgets/wordlift_widget_chord.php' );
658
require_once( 'widgets/wordlift_widget_timeline.php' );
659
660
require_once( 'wordlift_sparql.php' );
661
require_once( 'wordlift_redlink.php' );
662
663
// Add admin functions.
664
// TODO: find a way to make 'admin' UI tests work.
665
//if ( is_admin() ) {
666
667
require_once( 'admin/wordlift_admin.php' );
668
require_once( 'admin/wordlift_admin_edit_post.php' );
669
require_once( 'admin/wordlift_admin_save_post.php' );
670
671
// add the entities meta box.
672
require_once( 'admin/wordlift_admin_meta_box_entities.php' );
673
674
// add the entity creation AJAX.
675
require_once( 'admin/wordlift_admin_ajax_related_posts.php' );
676
677
// Load the wl_chord TinyMCE button and configuration dialog.
678
require_once( 'admin/wordlift_admin_shortcodes.php' );
679
680
// Provide syncing features.
681
require_once( 'admin/wordlift_admin_sync.php' );
682
//}
683
684
// load languages.
685
// TODO: the following call gives for granted that the plugin is in the wordlift directory,
686
//       we're currently doing this because wordlift is symbolic linked.
687
load_plugin_textdomain( 'wordlift', false, '/wordlift/languages' );
688
689
690
/**
691
 * The code that runs during plugin activation.
692
 * This action is documented in includes/class-wordlift-activator.php
693
 */
694
function activate_wordlift() {
695
	require_once plugin_dir_path( __FILE__ ) . 'includes/class-wordlift-activator.php';
696
	Wordlift_Activator::activate();
697
}
698
699
/**
700
 * The code that runs during plugin deactivation.
701
 * This action is documented in includes/class-wordlift-deactivator.php
702
 */
703
function deactivate_wordlift() {
704
	require_once plugin_dir_path( __FILE__ ) . 'includes/class-wordlift-deactivator.php';
705
	Wordlift_Deactivator::deactivate();
706
}
707
708
register_activation_hook( __FILE__, 'activate_wordlift' );
709
register_deactivation_hook( __FILE__, 'deactivate_wordlift' );
710
711
/**
712
 * The core plugin class that is used to define internationalization,
713
 * admin-specific hooks, and public-facing site hooks.
714
 */
715
require plugin_dir_path( __FILE__ ) . 'includes/class-wordlift.php';
716
717
/**
718
 * Begins execution of the plugin.
719
 *
720
 * Since everything within the plugin is registered via hooks,
721
 * then kicking off the plugin from this point in the file does
722
 * not affect the page life cycle.
723
 *
724
 * @since    1.0.0
725
 */
726
function run_wordlift() {
727
728
	$plugin = new Wordlift();
729
	$plugin->run();
730
731
}
732
733
run_wordlift();
734