Completed
Push — master ( bce0b6...fefb31 )
by David
03:27
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
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
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
218
// add allowed post tags.
219
add_action( 'init', 'wordlift_allowed_post_tags' );
220
221
222
/**
223
 * Register additional scripts for the admin UI.
224
 */
225
function wordlift_admin_enqueue_scripts() {
226
227
	// Added for compatibility with WordPress 3.9 (see http://make.wordpress.org/core/2014/04/16/jquery-ui-and-wpdialogs-in-wordpress-3-9/)
228
	wp_enqueue_script( 'wpdialogs' );
229
	wp_enqueue_style( 'wp-jquery-ui-dialog' );
230
231
	wp_enqueue_style( 'wordlift-reloaded', plugin_dir_url( __FILE__ ) . 'css/wordlift-reloaded.min.css' );
232
233
	wp_enqueue_script( 'jquery-ui-autocomplete' );
234
	wp_enqueue_script( 'angularjs', 'https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.11/angular.min.js' );
235
	wp_enqueue_script( 'angularjs-geolocation', plugin_dir_url( __FILE__ ) . '/bower_components/angularjs-geolocation/dist/angularjs-geolocation.min.js' );
236
	wp_enqueue_script( 'angularjs-touch', 'https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.11/angular-touch.min.js' );
237
	wp_enqueue_script( 'angularjs-animate', 'https://code.angularjs.org/1.3.11/angular-animate.min.js' );
238
239
	// Disable auto-save for custom entity posts only
240
	if ( Wordlift_Entity_Service::TYPE_NAME === get_post_type() ) {
241
		wp_dequeue_script( 'autosave' );
242
	}
243
}
244
245
add_action( 'admin_enqueue_scripts', 'wordlift_admin_enqueue_scripts' );
246
247
function wl_enqueue_scripts() {
248
	wp_enqueue_style( 'wordlift-ui', plugin_dir_url( __FILE__ ) . 'css/wordlift-ui.min.css' );
249
}
250
251
add_action( 'wp_enqueue_scripts', 'wl_enqueue_scripts' );
252
253
/**
254
 * Hooked to *wp_kses_allowed_html* filter, adds microdata attributes.
255
 *
256
 * @param array  $allowedtags The array with the currently configured elements and attributes.
257
 * @param string $context     The context.
258
 *
259
 * @return array An array which contains allowed microdata attributes.
260
 */
261
function wordlift_allowed_html( $allowedtags, $context ) {
262
263
	if ( 'post' !== $context ) {
264
		return $allowedtags;
265
	}
266
267
	return array_merge_recursive( $allowedtags, array(
268
		'span' => array(
269
			'itemscope' => true,
270
			'itemtype'  => true,
271
			'itemid'    => true,
272
			'itemprop'  => true,
273
		),
274
	) );
275
}
276
277
add_filter( 'wp_kses_allowed_html', 'wordlift_allowed_html', 10, 2 );
278
279
/**
280
 * Get the coordinates for the specified post ID.
281
 *
282
 * @param int $post_id The post ID.
283
 *
284
 * @return array|null An array of coordinates or null.
285
 */
286
function wl_get_coordinates( $post_id ) {
287
288
	$latitude  = wl_schema_get_value( $post_id, 'latitude' );
289
	$longitude = wl_schema_get_value( $post_id, 'longitude' );
290
291
	// DO NOT set latitude/longitude to 0/0 as default values. It's a specific place on the globe:
292
	// "The zero/zero point of this system is located in the Gulf of Guinea about 625 km (390 mi) south of Tema, Ghana."
293
	return array(
294
		'latitude'  => isset( $latitude[0] ) && is_numeric( $latitude[0] ) ? $latitude[0] : '',
295
		'longitude' => isset( $longitude[0] ) && is_numeric( $longitude[0] ) ? $longitude[0] : '',
296
	);
297
}
298
299
/**
300
 * Get the modified time of the provided post. If the time is negative, return the published date.
301
 *
302
 * @param object $post A post instance.
303
 *
304
 * @return string A datetime.
305
 */
306
function wl_get_post_modified_time( $post ) {
307
308
	$date_modified = get_post_modified_time( 'c', true, $post );
309
310
	if ( '-' === substr( $date_modified, 0, 1 ) ) {
311
		return get_the_time( 'c', $post );
312
	}
313
314
	return $date_modified;
315
}
316
317
/**
318
 * Get all the images bound to a post.
319
 *
320
 * @param int $post_id The post ID.
321
 *
322
 * @return array An array of image URLs.
323
 */
324
function wl_get_image_urls( $post_id ) {
325
326
327
	// If there is a featured image it has the priority
328
	$featured_image_id = get_post_thumbnail_id( $post_id );
329
	if ( is_numeric( $featured_image_id ) ) {
330
		$image_url = wp_get_attachment_url( $featured_image_id );
331
332
		return array( $image_url );
333
	}
334
335
	// 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...
336
337
	$images = get_children( array(
338
		'post_parent'    => $post_id,
339
		'post_type'      => 'attachment',
340
		'post_mime_type' => 'image',
341
	) );
342
343
	// Return an empty array if no image is found.
344
	if ( empty( $images ) ) {
345
		return array();
346
	}
347
348
	// Prepare the return array.
349
	$image_urls = array();
350
351
	// Collect the URLs.
352
	foreach ( $images as $attachment_id => $attachment ) {
353
		$image_url = wp_get_attachment_url( $attachment_id );
354
		// Ensure the URL isn't collected already.
355
		if ( ! in_array( $image_url, $image_urls ) ) {
356
			array_push( $image_urls, $image_url );
357
		}
358
	}
359
360
	// 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...
361
362
	return $image_urls;
363
}
364
365
/**
366
 * Get a SPARQL fragment with schema:image predicates.
367
 *
368
 * @param string $uri     The URI subject of the statements.
369
 * @param int    $post_id The post ID.
370
 *
371
 * @return string The SPARQL fragment.
372
 */
373
function wl_get_sparql_images( $uri, $post_id ) {
374
375
	$sparql = '';
376
377
	// Get the escaped URI.
378
	$uri_e = esc_html( $uri );
379
380
	// Add SPARQL stmts to write the schema:image.
381
	$image_urls = wl_get_image_urls( $post_id );
382
	foreach ( $image_urls as $image_url ) {
383
		$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...
384
		$sparql .= " <$uri_e> schema:image <$image_url_esc> . \n";
385
	}
386
387
	return $sparql;
388
}
389
390
/**
391
 * Get an attachment with the specified parent post ID and source URL.
392
 *
393
 * @param int    $parent_post_id The parent post ID.
394
 * @param string $source_url     The source URL.
395
 *
396
 * @return WP_Post|null A post instance or null if not found.
397
 */
398
function wl_get_attachment_for_source_url( $parent_post_id, $source_url ) {
399
400
	// 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...
401
402
	$posts = get_posts( array(
403
		'post_type'      => 'attachment',
404
		'posts_per_page' => 1,
405
		'post_status'    => 'any',
406
		'post_parent'    => $parent_post_id,
407
		'meta_key'       => 'wl_source_url',
408
		'meta_value'     => $source_url,
409
	) );
410
411
	// Return the found post.
412
	if ( 1 === count( $posts ) ) {
413
		return $posts[0];
414
	}
415
416
	// Return null.
417
	return null;
418
}
419
420
/**
421
 * Set the source URL.
422
 *
423
 * @param int    $post_id    The post ID.
424
 * @param string $source_url The source URL.
425
 */
426
function wl_set_source_url( $post_id, $source_url ) {
427
428
	delete_post_meta( $post_id, 'wl_source_url' );
429
	add_post_meta( $post_id, 'wl_source_url', $source_url );
430
}
431
432
433
/**
434
 * This function is called by the *flush_rewrite_rules_hard* hook. It recalculates the URI for all the posts.
435
 *
436
 * @since 3.0.0
437
 *
438
 * @uses  rl_sparql_prefixes() to get the SPARQL prefixes.
439
 * @uses  wordlift_esc_sparql() to escape the SPARQL query.
440
 * @uses  wl_get_entity_uri() to get an entity URI.
441
 * @uses  rl_execute_sparql_update_query() to post the DELETE and INSERT queries.
442
 *
443
 * @param bool $hard True if the rewrite involves configuration updates in Apache/IIS.
444
 */
445
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...
446
447
	// If WL is not yet configured, we cannot perform any update, so we exit.
448
	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...
449
		return;
450
	}
451
452
	// Set the initial offset and limit each call to 100 posts to avoid memory errors.
453
	$offset = 0;
454
	$limit  = 100;
455
456
	// Get more posts if the number of returned posts matches the limit.
457
	while ( $limit === ( $posts = get_posts( array(
458
			'offset'      => $offset,
459
			'numberposts' => $limit,
460
			'orderby'     => 'ID',
461
			'post_type'   => 'any',
462
			'post_status' => 'publish',
463
		) ) ) ) {
464
465
		// Holds the delete part of the query.
466
		$delete_query = rl_sparql_prefixes();
467
468
		// Holds the insert part of the query.
469
		$insert_query = '';
470
471
		// Cycle in each post to build the query.
472
		foreach ( $posts as $post ) {
473
474
			// Ignore revisions.
475
			if ( wp_is_post_revision( $post->ID ) ) {
476
				continue;
477
			}
478
479
			// Get the entity URI.
480
			$s = Wordlift_Sparql_Service::escape_uri( Wordlift_Entity_Service::get_instance()
481
			                                                                 ->get_uri( $post->ID ) );
482
483
			// Get the post URL.
484
			// $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...
485
486
			// Prepare the DELETE and INSERT commands.
487
			$delete_query .= "DELETE { <$s> schema:url ?u . } WHERE  { <$s> schema:url ?u . };\n";
488
489
			$insert_query .= Wordlift_Schema_Url_Property_Service::get_instance()
490
			                                                     ->get_insert_query( $s, $post->ID );
491
492
		}
493
494
495
		// Execute the query.
496
		rl_execute_sparql_update_query( $delete_query . $insert_query );
497
498
		// Advance to the next posts.
499
		$offset += $limit;
500
501
	}
502
503
//	// 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...
504
//	$posts = get_posts( array(
505
//		'posts_per_page' => - 1,
506
//		'post_type'      => 'any',
507
//		'post_status'    => 'publish'
508
//	) );
509
510
}
511
512
add_filter( 'flush_rewrite_rules_hard', 'wl_flush_rewrite_rules_hard', 10, 1 );
513
514
/**
515
 * Sanitizes an URI path by replacing the non allowed characters with an underscore.
516
 * @uses       sanitize_title() to manage not ASCII chars
517
 * @deprecated use Wordlift_Uri_Service::get_instance()->sanitize_path();
518
 * @see        https://codex.wordpress.org/Function_Reference/sanitize_title
519
 *
520
 * @param string $path The path to sanitize.
521
 * @param string $char The replacement character (by default an underscore).
522
 *
523
 * @return string The sanitized path.
524
 */
525
function wl_sanitize_uri_path( $path, $char = '_' ) {
526
527
	return Wordlift_Uri_Service::get_instance()->sanitize_path( $path, $char );
528
}
529
530
/**
531
 * Utility function to check if a variable is set and force it to be an array
532
 *
533
 * @package mixed $value Any value
534
 *
535
 * @return array Array containing $value (if $value was not an array)
536
 */
537
function wl_force_to_array( $value ) {
538
539
	if ( ! is_array( $value ) ) {
540
		return array( $value );
541
	}
542
543
	return $value;
544
}
545
546
/**
547
 * Schedule the execution of SPARQL Update queries before the WordPress look ends.
548
 */
549
function wl_shutdown() {
550
551
	// Get the filename to the temporary SPARQL file.
552
	$filename = WL_TEMP_DIR . WL_REQUEST_ID . '.sparql';
553
554
	// If WordLift is buffering SPARQL queries, we're admins and a buffer exists, then schedule it.
555
	if ( WL_ENABLE_SPARQL_UPDATE_QUERIES_BUFFERING && is_admin() && file_exists( $filename ) ) {
556
557
		// The request ID.
558
		$args = array( WL_REQUEST_ID );
559
560
		// Schedule the execution of the SPARQL query with the request ID.
561
		wp_schedule_single_event( time(), 'wl_execute_saved_sparql_update_query', $args );
562
563
		// Check that the request is scheduled.
564
		$timestamp = wp_next_scheduled( 'wl_execute_saved_sparql_update_query', $args );
565
566
		// Spawn the cron.
567
		spawn_cron();
568
569
		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...
570
	}
571
}
572
573
add_action( 'shutdown', 'wl_shutdown' );
574
575
/**
576
 * Replaces the *itemid* attributes URIs with the WordLift URIs.
577
 *
578
 * @param string $content The post content.
579
 *
580
 * @return string The updated post content.
581
 */
582
function wl_replace_item_id_with_uri( $content ) {
583
584
	// 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...
585
586
	// Strip slashes, see https://core.trac.wordpress.org/ticket/21767
587
	$content = stripslashes( $content );
588
589
	// If any match are found.
590
	$matches = array();
591
	if ( 0 < preg_match_all( '/ itemid="([^"]+)"/i', $content, $matches, PREG_SET_ORDER ) ) {
592
593
		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...
594
595
			// Get the item ID.
596
			$item_id = $match[1];
597
598
			// Get the post bound to that item ID (looking both in the 'official' URI and in the 'same-as' .
599
			$post = Wordlift_Entity_Service::get_instance()
600
			                               ->get_entity_post_by_uri( $item_id );
601
602
			// If no entity is found, continue to the next one.
603
			if ( null === $post ) {
604
				continue;
605
			}
606
607
			// Get the URI for that post.
608
			$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...
609
610
			// 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...
611
612
			// If the item ID and the URI differ, replace the item ID with the URI saved in WordPress.
613
			if ( $item_id !== $uri ) {
614
				$uri_e   = esc_html( $uri );
615
				$content = str_replace( " itemid=\"$item_id\"", " itemid=\"$uri_e\"", $content );
616
			}
617
		}
618
	}
619
620
	// Reapply slashes.
621
	$content = addslashes( $content );
622
623
	return $content;
624
}
625
626
add_filter( 'content_save_pre', 'wl_replace_item_id_with_uri', 1, 1 );
627
628
require_once( 'wordlift_entity_functions.php' );
629
630
// add editor related methods.
631
require_once( 'wordlift_editor.php' );
632
633
// add the WordLift entity custom type.
634
require_once( 'wordlift_entity_type.php' );
635
require_once( 'wordlift_entity_type_taxonomy.php' );
636
637
// add callbacks on post save to notify data changes from wp to redlink triple store
638
require_once( 'wordlift_to_redlink_data_push_callbacks.php' );
639
640
require_once( 'modules/configuration/wordlift_configuration_settings.php' );
641
642
// Load modules
643
require_once( 'modules/analyzer/wordlift_analyzer.php' );
644
require_once( 'modules/linked_data/wordlift_linked_data.php' );
645
require_once( 'modules/prefixes/wordlift_prefixes.php' );
646
require_once( 'modules/redirector/wordlift_redirector.php' );
647
648
// Shortcodes
649
650
require_once( 'modules/geo_widget/wordlift_geo_widget.php' );
651
require_once( 'shortcodes/wordlift_shortcode_chord.php' );
652
require_once( 'shortcodes/wordlift_shortcode_geomap.php' );
653
require_once( 'shortcodes/wordlift_shortcode_field.php' );
654
require_once( 'shortcodes/wordlift_shortcode_faceted_search.php' );
655
require_once( 'shortcodes/wordlift_shortcode_navigator.php' );
656
657
require_once( 'widgets/wordlift_widget_geo.php' );
658
require_once( 'widgets/wordlift_widget_chord.php' );
659
require_once( 'widgets/wordlift_widget_timeline.php' );
660
661
require_once( 'wordlift_sparql.php' );
662
require_once( 'wordlift_redlink.php' );
663
664
// Add admin functions.
665
// TODO: find a way to make 'admin' UI tests work.
666
//if ( is_admin() ) {
667
668
require_once( 'admin/wordlift_admin.php' );
669
require_once( 'admin/wordlift_admin_edit_post.php' );
670
require_once( 'admin/wordlift_admin_save_post.php' );
671
672
// add the entities meta box.
673
require_once( 'admin/wordlift_admin_meta_box_entities.php' );
674
675
// add the entity creation AJAX.
676
require_once( 'admin/wordlift_admin_ajax_related_posts.php' );
677
678
// Load the wl_chord TinyMCE button and configuration dialog.
679
require_once( 'admin/wordlift_admin_shortcodes.php' );
680
681
// Provide syncing features.
682
require_once( 'admin/wordlift_admin_sync.php' );
683
//}
684
685
// load languages.
686
// TODO: the following call gives for granted that the plugin is in the wordlift directory,
687
//       we're currently doing this because wordlift is symbolic linked.
688
load_plugin_textdomain( 'wordlift', false, '/wordlift/languages' );
689
690
691
/**
692
 * The code that runs during plugin activation.
693
 * This action is documented in includes/class-wordlift-activator.php
694
 */
695
function activate_wordlift() {
696
	require_once plugin_dir_path( __FILE__ ) . 'includes/class-wordlift-activator.php';
697
	Wordlift_Activator::activate();
698
}
699
700
/**
701
 * The code that runs during plugin deactivation.
702
 * This action is documented in includes/class-wordlift-deactivator.php
703
 */
704
function deactivate_wordlift() {
705
	require_once plugin_dir_path( __FILE__ ) . 'includes/class-wordlift-deactivator.php';
706
	Wordlift_Deactivator::deactivate();
707
}
708
709
register_activation_hook( __FILE__, 'activate_wordlift' );
710
register_deactivation_hook( __FILE__, 'deactivate_wordlift' );
711
712
/**
713
 * The core plugin class that is used to define internationalization,
714
 * admin-specific hooks, and public-facing site hooks.
715
 */
716
require plugin_dir_path( __FILE__ ) . 'includes/class-wordlift.php';
717
718
/**
719
 * Begins execution of the plugin.
720
 *
721
 * Since everything within the plugin is registered via hooks,
722
 * then kicking off the plugin from this point in the file does
723
 * not affect the page life cycle.
724
 *
725
 * @since    1.0.0
726
 */
727
function run_wordlift() {
728
729
	$plugin = new Wordlift();
730
	$plugin->run();
731
732
}
733
734
run_wordlift();
735