Passed
Push — master ( 51c804...1c8cf7 )
by Brian
05:30
created

WP_Font_Awesome_Settings::extract_package()   C

Complexity

Conditions 15
Paths 70

Size

Total Lines 57
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 15
eloc 30
nc 70
nop 3
dl 0
loc 57
rs 5.9166
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * A class for adjusting font awesome settings on WordPress
4
 *
5
 * This class can be added to any plugin or theme and will add a settings screen to WordPress to control Font Awesome settings.
6
 *
7
 * @link https://github.com/AyeCode/wp-font-awesome-settings
8
 *
9
 * @internal This file should not be edited directly but pulled from the github repo above.
10
 */
11
12
/**
13
 * Bail if we are not in WP.
14
 */
15
if ( ! defined( 'ABSPATH' ) ) {
16
	exit;
17
}
18
19
/**
20
 * Only add if the class does not already exist.
21
 */
22
if ( ! class_exists( 'WP_Font_Awesome_Settings' ) ) {
23
24
	/**
25
	 * A Class to be able to change settings for Font Awesome.
26
	 *
27
	 * Class WP_Font_Awesome_Settings
28
	 * @since 1.0.10 Now able to pass wp.org theme check.
29
	 * @since 1.0.11 Font Awesome Pro now supported.
30
	 * @since 1.0.11 Font Awesome Kits now supported.
31
	 * @since 1.0.13 RTL language support added.
32
	 * @since 1.0.14 Warning added for v6 pro requires kit and will now not work if official FA plugin installed.
33
	 * @since 1.0.15 Font Awesome will now load in the FSE if enable din the backend.
34
	 * @since 1.1.0 Option added to load FontAwesome locally.
35
	 * @ver 1.0.15
36
	 * @todo decide how to implement textdomain
37
	 */
38
	class WP_Font_Awesome_Settings {
39
40
		/**
41
		 * Class version version.
42
		 *
43
		 * @var string
44
		 */
45
		public $version = '1.0.15';
46
47
		/**
48
		 * Class textdomain.
49
		 *
50
		 * @var string
51
		 */
52
		public $textdomain = 'font-awesome-settings';
53
54
		/**
55
		 * Latest version of Font Awesome at time of publish published.
56
		 *
57
		 * @var string
58
		 */
59
		public $latest = "5.8.2";
60
61
		/**
62
		 * The title.
63
		 *
64
		 * @var string
65
		 */
66
		public $name = 'Font Awesome';
67
68
		/**
69
		 * Holds the settings values.
70
		 *
71
		 * @var array
72
		 */
73
		private $settings;
74
75
		/**
76
		 * WP_Font_Awesome_Settings instance.
77
		 *
78
		 * @access private
79
		 * @since  1.0.0
80
		 * @var    WP_Font_Awesome_Settings There can be only one!
81
		 */
82
		private static $instance = null;
83
84
		/**
85
		 * Main WP_Font_Awesome_Settings Instance.
86
		 *
87
		 * Ensures only one instance of WP_Font_Awesome_Settings is loaded or can be loaded.
88
		 *
89
		 * @since 1.0.0
90
		 * @static
91
		 * @return WP_Font_Awesome_Settings - Main instance.
92
		 */
93
		public static function instance() {
94
			if ( ! isset( self::$instance ) && ! ( self::$instance instanceof WP_Font_Awesome_Settings ) ) {
95
				self::$instance = new WP_Font_Awesome_Settings;
96
97
				add_action( 'init', array( self::$instance, 'init' ) ); // set settings
98
99
				if ( is_admin() ) {
100
					add_action( 'admin_menu', array( self::$instance, 'menu_item' ) );
101
					add_action( 'admin_init', array( self::$instance, 'register_settings' ) );
102
					add_action( 'admin_notices', array( self::$instance, 'admin_notices' ) );
103
				}
104
105
				do_action( 'wp_font_awesome_settings_loaded' );
106
			}
107
108
			return self::$instance;
109
		}
110
111
		/**
112
		 * Initiate the settings and add the required action hooks.
113
		 *
114
		 * @since 1.0.8 Settings name wrong - FIXED
115
		 */
116
		public function init() {
117
			// Download fontawesome locally.
118
			add_action( 'update_option_wp-font-awesome-settings', array( $this, 'update_option_wp_font_awesome_settings' ), 10, 2 );
119
120
			$this->settings = $this->get_settings();
121
122
			// check if the official plugin is active and use that instead if so.
123
			if ( ! defined( 'FONTAWESOME_PLUGIN_FILE' ) ) {
124
125
				if ( $this->settings['type'] == 'CSS' ) {
126
127
					if ( $this->settings['enqueue'] == '' || $this->settings['enqueue'] == 'frontend' ) {
128
						add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_style' ), 5000 );
129
					}
130
131
					if ( $this->settings['enqueue'] == '' || $this->settings['enqueue'] == 'backend' ) {
132
						add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_style' ), 5000 );
133
						add_filter( 'block_editor_settings_all', array( $this, 'enqueue_editor_styles' ), 10, 2 );
134
					}
135
136
				} else {
137
138
					if ( $this->settings['enqueue'] == '' || $this->settings['enqueue'] == 'frontend' ) {
139
						add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ), 5000 );
140
					}
141
142
					if ( $this->settings['enqueue'] == '' || $this->settings['enqueue'] == 'backend' ) {
143
						add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ), 5000 );
144
						add_filter( 'block_editor_settings_all', array( $this, 'enqueue_editor_scripts' ), 10, 2 );
145
					}
146
				}
147
148
				// remove font awesome if set to do so
149
				if ( $this->settings['dequeue'] == '1' ) {
150
					add_action( 'clean_url', array( $this, 'remove_font_awesome' ), 5000, 3 );
151
				}
152
			}
153
154
		}
155
156
		/**
157
		 * Add FA to the FSE.
158
		 *
159
		 * @param $editor_settings
160
		 * @param $block_editor_context
161
		 *
162
		 * @return array
163
		 */
164
		public function enqueue_editor_styles( $editor_settings, $block_editor_context ){
0 ignored issues
show
Unused Code introduced by
The parameter $block_editor_context is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

164
		public function enqueue_editor_styles( $editor_settings, /** @scrutinizer ignore-unused */ $block_editor_context ){

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

Loading history...
165
166
			if ( ! empty( $editor_settings['__unstableResolvedAssets']['styles'] ) ) {
167
				$url = $this->get_url();
168
				$editor_settings['__unstableResolvedAssets']['styles'] .= "<link rel='stylesheet' id='font-awesome-css'  href='$url' media='all' />";
169
			}
170
171
			return $editor_settings;
172
		}
173
174
		/**
175
		 * Add FA to the FSE.
176
		 *
177
		 * @param $editor_settings
178
		 * @param $block_editor_context
179
		 *
180
		 * @return array
181
		 */
182
		public function enqueue_editor_scripts( $editor_settings, $block_editor_context ){
0 ignored issues
show
Unused Code introduced by
The parameter $block_editor_context is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

182
		public function enqueue_editor_scripts( $editor_settings, /** @scrutinizer ignore-unused */ $block_editor_context ){

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

Loading history...
183
184
			$url = $this->get_url();
185
			$editor_settings['__unstableResolvedAssets']['scripts'] .= "<script src='$url' id='font-awesome-js'></script>";
186
187
			return $editor_settings;
188
		}
189
190
		/**
191
		 * Adds the Font Awesome styles.
192
		 */
193
		public function enqueue_style() {
194
			// build url
195
			$url = $this->get_url();
196
			$version = ! empty( $this->settings['local'] ) && empty( $this->settings['pro'] ) ? strip_tags( $this->settings['local_version'] ) : null;
197
198
			wp_deregister_style( 'font-awesome' ); // deregister in case its already there
199
			wp_register_style( 'font-awesome', $url, array(), $version );
200
			wp_enqueue_style( 'font-awesome' );
201
202
			// RTL language support CSS.
203
			if ( is_rtl() ) {
204
				wp_add_inline_style( 'font-awesome', $this->rtl_inline_css() );
205
			}
206
207
			if ( $this->settings['shims'] ) {
208
				$url = $this->get_url( true );
209
				wp_deregister_style( 'font-awesome-shims' ); // deregister in case its already there
210
				wp_register_style( 'font-awesome-shims', $url, array(), $version );
211
				wp_enqueue_style( 'font-awesome-shims' );
212
			}
213
		}
214
215
		/**
216
		 * Adds the Font Awesome JS.
217
		 */
218
		public function enqueue_scripts() {
219
			// build url
220
			$url = $this->get_url();
221
222
			$deregister_function = 'wp' . '_' . 'deregister' . '_' . 'script';
223
			call_user_func( $deregister_function, 'font-awesome' ); // deregister in case its already there
224
			wp_register_script( 'font-awesome', $url, array(), null );
225
			wp_enqueue_script( 'font-awesome' );
226
227
			if ( $this->settings['shims'] ) {
228
				$url = $this->get_url( true );
229
				call_user_func( $deregister_function, 'font-awesome-shims' ); // deregister in case its already there
230
				wp_register_script( 'font-awesome-shims', $url, array(), null );
231
				wp_enqueue_script( 'font-awesome-shims' );
232
			}
233
		}
234
235
		/**
236
		 * Get the url of the Font Awesome files.
237
		 *
238
		 * @param bool $shims If this is a shim file or not.
239
		 * @param bool $local Load locally if allowed.
240
		 *
241
		 * @return string The url to the file.
242
		 */
243
		public function get_url( $shims = false, $local = true ) {
244
			$script  = $shims ? 'v4-shims' : 'all';
245
			$sub     = $this->settings['pro'] ? 'pro' : 'use';
246
			$type    = $this->settings['type'];
247
			$version = $this->settings['version'];
248
			$kit_url = $this->settings['kit-url'] ? esc_url( $this->settings['kit-url'] ) : '';
249
			$url     = '';
250
251
			if ( $type == 'KIT' && $kit_url ) {
252
				if ( $shims ) {
253
					// if its a kit then we don't add shims here
254
					return '';
255
				}
256
				$url .= $kit_url; // CDN
257
				$url .= "?wpfas=true"; // set our var so our version is not removed
258
			} else {
259
				$v = '';
260
				// Check and load locally.
261
				if ( $local && $this->has_local() ) {
262
					$script .= ".min";
263
					$v .= '&ver=' . strip_tags( $this->settings['local_version'] );
264
					$url .= $this->get_fonts_url(); // Local fonts url.
265
				} else {
266
					$url .= "https://$sub.fontawesome.com/releases/"; // CDN
267
					$url .= ! empty( $version ) ? "v" . $version . '/' : "v" . $this->get_latest_version() . '/'; // version
268
				}
269
				$url .= $type == 'CSS' ? 'css/' : 'js/'; // type
270
				$url .= $type == 'CSS' ? $script . '.css' : $script . '.js'; // type
271
				$url .= "?wpfas=true" . $v; // set our var so our version is not removed
272
			}
273
274
			return $url;
275
		}
276
277
		/**
278
		 * Try and remove any other versions of Font Awesome added by other plugins/themes.
279
		 *
280
		 * Uses the clean_url filter to try and remove any other Font Awesome files added, it can also add pseudo-elements flag for the JS version.
281
		 *
282
		 * @param $url
283
		 * @param $original_url
284
		 * @param $_context
285
		 *
286
		 * @return string The filtered url.
287
		 */
288
		public function remove_font_awesome( $url, $original_url, $_context ) {
289
290
			if ( $_context == 'display'
291
			     && ( strstr( $url, "fontawesome" ) !== false || strstr( $url, "font-awesome" ) !== false )
292
			     && ( strstr( $url, ".js" ) !== false || strstr( $url, ".css" ) !== false )
293
			) {// it's a font-awesome-url (probably)
294
295
				if ( strstr( $url, "wpfas=true" ) !== false ) {
296
					if ( $this->settings['type'] == 'JS' ) {
297
						if ( $this->settings['js-pseudo'] ) {
298
							$url .= "' data-search-pseudo-elements defer='defer";
299
						} else {
300
							$url .= "' defer='defer";
301
						}
302
					}
303
				} else {
304
					$url = ''; // removing the url removes the file
305
				}
306
307
			}
308
309
			return $url;
310
		}
311
312
		/**
313
		 * Register the database settings with WordPress.
314
		 */
315
		public function register_settings() {
316
			register_setting( 'wp-font-awesome-settings', 'wp-font-awesome-settings' );
317
		}
318
319
		/**
320
		 * Add the WordPress settings menu item.
321
		 * @since 1.0.10 Calling function name direct will fail theme check so we don't.
322
		 */
323
		public function menu_item() {
324
			$menu_function = 'add' . '_' . 'options' . '_' . 'page'; // won't pass theme check if function name present in theme
325
			call_user_func( $menu_function, $this->name, $this->name, 'manage_options', 'wp-font-awesome-settings', array(
326
				$this,
327
				'settings_page'
328
			) );
329
		}
330
331
		/**
332
		 * Get the current Font Awesome output settings.
333
		 *
334
		 * @return array The array of settings.
335
		 */
336
		public function get_settings() {
337
			$db_settings = get_option( 'wp-font-awesome-settings' );
338
339
			$defaults = array(
340
				'type'      => 'CSS', // type to use, CSS or JS or KIT
341
				'version'   => '', // latest
342
				'enqueue'   => '', // front and backend
343
				'shims'     => '0', // default OFF now in 2020
344
				'js-pseudo' => '0', // if the pseudo elements flag should be set (CPU intensive)
345
				'dequeue'   => '0', // if we should try to remove other versions added by other plugins/themes
346
				'pro'       => '0', // if pro CDN url should be used
347
				'local'     => '0', // Store fonts locally.
348
				'local_version' => '', // Local fonts version.
349
				'kit-url'   => '', // the kit url
350
			);
351
352
			$settings = wp_parse_args( $db_settings, $defaults );
0 ignored issues
show
Bug introduced by
It seems like $db_settings can also be of type false; however, parameter $args of wp_parse_args() does only seem to accept array|object|string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

352
			$settings = wp_parse_args( /** @scrutinizer ignore-type */ $db_settings, $defaults );
Loading history...
353
354
			/**
355
			 * Filter the Font Awesome settings.
356
			 *
357
			 * @todo if we add this filer people might use it and then it defeates the purpose of this class :/
358
			 */
359
			return $this->settings = apply_filters( 'wp-font-awesome-settings', $settings, $db_settings, $defaults );
360
		}
361
362
		/**
363
		 * The settings page html output.
364
		 */
365
		public function settings_page() {
366
			if ( ! current_user_can( 'manage_options' ) ) {
367
				wp_die( __( 'You do not have sufficient permissions to access this page.', 'font-awesome-settings' ) );
368
			}
369
370
			// a hidden way to force the update of the version number via api instead of waiting the 48 hours
371
			if ( isset( $_REQUEST['force-version-check'] ) ) {
372
				$this->get_latest_version( $force_api = true );
373
			}
374
375
			if ( ! defined( 'FONTAWESOME_PLUGIN_FILE' ) ) {
376
				?>
377
                <style>
378
                    .wpfas-kit-show {
379
                        display: none;
380
                    }
381
                    .wpfas-kit-set .wpfas-kit-hide,.wpfas-has-pro .wpfas-hide-pro {
382
                        display: none;
383
                    }
384
                    .wpfas-kit-set .wpfas-kit-show {
385
                        display: table-row;
386
                    }
387
                    .fas-settings-form .submit{
388
                        display: inline;
389
                        padding-right: 5px;
390
                    }
391
                    .fas-settings-form .fas-buttons{
392
                        margin: 15px 0;
393
                    }
394
                    #wpfas-version{
395
                        color: #646970;
396
                    }
397
                </style>
398
                <div class="wrap">
399
                    <h1><?php echo $this->name; ?></h1>
400
                    <form method="post" action="options.php" class="fas-settings-form">
401
						<?php
402
						settings_fields( 'wp-font-awesome-settings' );
403
						do_settings_sections( 'wp-font-awesome-settings' );
404
						$table_class = '';
405
						if ( $this->settings['type'] ) {
406
							$table_class .= 'wpfas-' . sanitize_html_class( strtolower( $this->settings['type'] ) ) . '-set';
407
						}
408
						if ( ! empty( $this->settings['pro'] ) ) {
409
							$table_class .= ' wpfas-has-pro';
410
						}
411
						?>
412
						<?php if ( $this->settings['type'] != 'KIT' && ! empty( $this->settings['local'] ) && empty( $this->settings['pro'] ) ) { ?>
413
							<?php if ( $this->has_local() ) { ?>
414
							<div class="notice notice-info"><p><strong><?php _e( 'Font Awesome fonts are loading locally.', 'font-awesome-settings' ); ?></strong></p></div>
415
							<?php } else { ?>
416
							<div class="notice notice-error"><p><strong><?php _e( 'Font Awesome fonts are not loading locally!', 'font-awesome-settings' ); ?></strong></p></div>
417
							<?php } ?>
418
						<?php } ?>
419
                        <table class="form-table wpfas-table-settings <?php echo esc_attr( $table_class ); ?>">
420
                            <tr valign="top">
421
                                <th scope="row"><label for="wpfas-type"><?php _e( 'Type', 'font-awesome-settings' ); ?></label></th>
422
                                <td>
423
                                    <select name="wp-font-awesome-settings[type]" id="wpfas-type" onchange="if(this.value=='KIT'){jQuery('.wpfas-table-settings').addClass('wpfas-kit-set');}else{jQuery('.wpfas-table-settings').removeClass('wpfas-kit-set');}">
424
                                        <option value="CSS" <?php selected( $this->settings['type'], 'CSS' ); ?>><?php _e( 'CSS (default)', 'font-awesome-settings' ); ?></option>
425
                                        <option value="JS" <?php selected( $this->settings['type'], 'JS' ); ?>>JS</option>
426
                                        <option value="KIT" <?php selected( $this->settings['type'], 'KIT' ); ?>><?php _e( 'Kits (settings managed on fontawesome.com)', 'font-awesome-settings' ); ?></option>
427
                                    </select>
428
                                </td>
429
                            </tr>
430
431
                            <tr valign="top" class="wpfas-kit-show">
432
                                <th scope="row"><label for="wpfas-kit-url"><?php _e( 'Kit URL', 'font-awesome-settings' ); ?></label></th>
433
                                <td>
434
                                    <input class="regular-text" id="wpfas-kit-url" type="url" name="wp-font-awesome-settings[kit-url]" value="<?php echo esc_attr( $this->settings['kit-url'] ); ?>" placeholder="<?php echo 'https://kit.font';echo 'awesome.com/123abc.js'; // this won't pass theme check :(?>"/>
435
                                    <span><?php
436
										echo sprintf(
437
											__( 'Requires a free account with Font Awesome. %sGet kit url%s', 'font-awesome-settings' ),
438
											'<a rel="noopener noreferrer" target="_blank" href="https://fontawesome.com/kits"><i class="fas fa-external-link-alt"></i>',
439
											'</a>'
440
										);
441
										?></span>
442
                                </td>
443
                            </tr>
444
445
                            <tr valign="top" class="wpfas-kit-hide">
446
                                <th scope="row"><label for="wpfas-version"><?php _e( 'Version', 'font-awesome-settings' ); ?></label></th>
447
                                <td>
448
                                    <select name="wp-font-awesome-settings[version]" id="wpfas-version">
449
                                        <option value="" <?php selected( $this->settings['version'], '' ); ?>><?php echo sprintf( __( 'Latest - %s (default)', 'font-awesome-settings' ), $this->get_latest_version() ); ?></option>
450
                                        <option value="6.1.0" <?php selected( $this->settings['version'], '6.1.0' ); ?>>6.1.0</option>
451
                                        <option value="6.0.0" <?php selected( $this->settings['version'], '6.0.0' ); ?>>6.0.0</option>
452
                                        <option value="5.15.4" <?php selected( $this->settings['version'], '5.15.4' ); ?>>5.15.4</option>
453
                                        <option value="5.6.0" <?php selected( $this->settings['version'], '5.6.0' ); ?>>5.6.0</option>
454
                                        <option value="5.5.0" <?php selected( $this->settings['version'], '5.5.0' ); ?>>5.5.0</option>
455
                                        <option value="5.4.0" <?php selected( $this->settings['version'], '5.4.0' ); ?>>5.4.0</option>
456
                                        <option value="5.3.0" <?php selected( $this->settings['version'], '5.3.0' ); ?>>5.3.0</option>
457
                                        <option value="5.2.0" <?php selected( $this->settings['version'], '5.2.0' ); ?>>5.2.0</option>
458
                                        <option value="5.1.0" <?php selected( $this->settings['version'], '5.1.0' ); ?>>5.1.0</option>
459
                                        <option value="4.7.0" <?php selected( $this->settings['version'], '4.7.0' ); ?>>4.7.1 (CSS only)</option>
460
                                    </select>
461
                                </td>
462
                            </tr>
463
464
                            <tr valign="top">
465
                                <th scope="row"><label for="wpfas-enqueue"><?php _e( 'Enqueue', 'font-awesome-settings' ); ?></label></th>
466
                                <td>
467
                                    <select name="wp-font-awesome-settings[enqueue]" id="wpfas-enqueue">
468
                                        <option value="" <?php selected( $this->settings['enqueue'], '' ); ?>><?php _e( 'Frontend + Backend (default)', 'font-awesome-settings' ); ?></option>
469
                                        <option value="frontend" <?php selected( $this->settings['enqueue'], 'frontend' ); ?>><?php _e( 'Frontend', 'font-awesome-settings' ); ?></option>
470
                                        <option value="backend" <?php selected( $this->settings['enqueue'], 'backend' ); ?>><?php _e( 'Backend', 'font-awesome-settings' ); ?></option>
471
                                    </select>
472
                                </td>
473
                            </tr>
474
475
                            <tr valign="top" class="wpfas-kit-hide">
476
                                <th scope="row"><label
477
                                            for="wpfas-pro"><?php _e( 'Enable pro', 'font-awesome-settings' ); ?></label></th>
478
                                <td>
479
                                    <input type="hidden" name="wp-font-awesome-settings[pro]" value="0"/>
480
                                    <input type="checkbox" name="wp-font-awesome-settings[pro]" value="1" <?php checked( $this->settings['pro'], '1' ); ?> id="wpfas-pro" onchange="if(jQuery(this).is(':checked')){jQuery('.wpfas-table-settings').addClass('wpfas-has-pro')}else{jQuery('.wpfas-table-settings').removeClass('wpfas-has-pro')}"/>
481
                                    <span><?php
482
										echo wp_sprintf(
483
											__( 'Requires a subscription. %sLearn more%s  %sManage my allowed domains%s', 'font-awesome-settings' ),
484
											'<a rel="noopener noreferrer" target="_blank" href="https://fontawesome.com/referral?a=c9b89e1418">',
485
											' <i class="fas fa-external-link-alt"></i></a>',
486
											'<a rel="noopener noreferrer" target="_blank" href="https://fontawesome.com/account/cdn">',
487
											' <i class="fas fa-external-link-alt"></i></a>'
488
										);
489
										?></span>
490
                                </td>
491
                            </tr>
492
493
							<tr valign="top" class="wpfas-kit-hide wpfas-hide-pro">
494
								<th scope="row"><label for="wpfas-local"><?php _e( 'Load Fonts Locally', 'font-awesome-settings' ); ?></label></th>
495
								<td>
496
									<input type="hidden" name="wp-font-awesome-settings[local]" value="0"/>
497
									<input type="hidden" name="wp-font-awesome-settings[local_version]" value="<?php echo esc_attr( $this->settings['local_version'] ); ?>"/>
498
									<input type="checkbox" name="wp-font-awesome-settings[local]" value="1" <?php checked( $this->settings['local'], '1' ); ?> id="wpfas-local"/>
499
									<span><?php _e( '(For free version only) Load FontAwesome fonts from locally. This downloads FontAwesome fonts from fontawesome.com & stores at the local site.', 'font-awesome-settings' ); ?></span>
500
								</td>
501
							</tr>
502
503
                            <tr valign="top" class="wpfas-kit-hide">
504
                                <th scope="row"><label
505
                                            for="wpfas-shims"><?php _e( 'Enable v4 shims compatibility', 'font-awesome-settings' ); ?></label>
506
                                </th>
507
                                <td>
508
                                    <input type="hidden" name="wp-font-awesome-settings[shims]" value="0"/>
509
                                    <input type="checkbox" name="wp-font-awesome-settings[shims]"
510
                                           value="1" <?php checked( $this->settings['shims'], '1' ); ?> id="wpfas-shims"/>
511
                                    <span><?php _e( 'This enables v4 classes to work with v5, sort of like a band-aid until everyone has updated everything to v5.', 'font-awesome-settings' ); ?></span>
512
                                </td>
513
                            </tr>
514
515
                            <tr valign="top" class="wpfas-kit-hide">
516
                                <th scope="row"><label
517
                                            for="wpfas-js-pseudo"><?php _e( 'Enable JS pseudo elements (not recommended)', 'font-awesome-settings' ); ?></label>
518
                                </th>
519
                                <td>
520
                                    <input type="hidden" name="wp-font-awesome-settings[js-pseudo]" value="0"/>
521
                                    <input type="checkbox" name="wp-font-awesome-settings[js-pseudo]"
522
                                           value="1" <?php checked( $this->settings['js-pseudo'], '1' ); ?>
523
                                           id="wpfas-js-pseudo"/>
524
                                    <span><?php _e( 'Used only with the JS version, this will make pseudo-elements work but can be CPU intensive on some sites.', 'font-awesome-settings' ); ?></span>
525
                                </td>
526
                            </tr>
527
528
                            <tr valign="top">
529
                                <th scope="row"><label
530
                                            for="wpfas-dequeue"><?php _e( 'Dequeue', 'font-awesome-settings' ); ?></label></th>
531
                                <td>
532
                                    <input type="hidden" name="wp-font-awesome-settings[dequeue]" value="0"/>
533
                                    <input type="checkbox" name="wp-font-awesome-settings[dequeue]"
534
                                           value="1" <?php checked( $this->settings['dequeue'], '1' ); ?>
535
                                           id="wpfas-dequeue"/>
536
                                    <span><?php _e( 'This will try to dequeue any other Font Awesome versions loaded by other sources if they are added with `font-awesome` or `fontawesome` in the name.', 'font-awesome-settings' ); ?></span>
537
                                </td>
538
                            </tr>
539
540
                        </table>
541
                        <div class="fas-buttons">
542
							<?php
543
							submit_button();
544
							?>
545
                            <p class="submit"><a href="https://fontawesome.com/referral?a=c9b89e1418" class="button button-secondary"><?php _e('Get 14,000+ more icons with Font Awesome Pro','font-awesome-settings'); ?> <i class="fas fa-external-link-alt"></i></a></p>
546
547
                        </div>
548
                    </form>
549
550
                    <div id="wpfas-version"><?php echo sprintf(__( 'Version: %s (affiliate links provided)', 'font-awesome-settings' ), $this->version ); ?></div>
551
                </div>
552
				<?php
553
			}
554
		}
555
556
		/**
557
		 * Check a version number is valid and if so return it or else return an empty string.
558
		 *
559
		 * @param $version string The version number to check.
560
		 *
561
		 * @since 1.0.6
562
		 *
563
		 * @return string Either a valid version number or an empty string.
564
		 */
565
		public function validate_version_number( $version ) {
566
567
			if ( version_compare( $version, '0.0.1', '>=' ) >= 0 ) {
568
				// valid
569
			} else {
570
				$version = '';// not validated
571
			}
572
573
			return $version;
574
		}
575
576
577
		/**
578
		 * Get the latest version of Font Awesome.
579
		 *
580
		 * We check for a cached version and if none we will check for a live version via API and then cache it for 48 hours.
581
		 *
582
		 * @since 1.0.7
583
		 * @return mixed|string The latest version number found.
584
		 */
585
		public function get_latest_version( $force_api = false ) {
586
			$latest_version = $this->latest;
587
588
			$cache = get_transient( 'wp-font-awesome-settings-version' );
589
590
			if ( $cache === false || $force_api ) { // its not set
591
				$api_ver = $this->get_latest_version_from_api();
592
				if ( version_compare( $api_ver, $this->latest, '>=' ) >= 0 ) {
593
					$latest_version = $api_ver;
594
					set_transient( 'wp-font-awesome-settings-version', $api_ver, 48 * HOUR_IN_SECONDS );
595
				}
596
			} elseif ( $this->validate_version_number( $cache ) ) {
597
				if ( version_compare( $cache, $this->latest, '>=' ) >= 0 ) {
598
					$latest_version = $cache;
599
				}
600
			}
601
602
			// Check and auto download fonts locally.
603
			if ( empty( $this->settings['pro'] ) && empty( $this->settings['version'] ) && $this->settings['type'] != 'KIT' && ! empty( $this->settings['local'] ) && ! empty( $this->settings['local_version'] ) && ! empty( $latest_version ) ) {
604
				if ( version_compare( $latest_version, $this->settings['local_version'], '>' ) && is_admin() && ! wp_doing_ajax() ) {
605
					$this->download_package( $latest_version );
606
				}
607
			}
608
609
			return $latest_version;
610
		}
611
612
		/**
613
		 * Get the latest Font Awesome version from the github API.
614
		 *
615
		 * @since 1.0.7
616
		 * @return string The latest version number or `0` on API fail.
617
		 */
618
		public function get_latest_version_from_api() {
619
			$version  = "0";
620
			$response = wp_remote_get( "https://api.github.com/repos/FortAwesome/Font-Awesome/releases/latest" );
621
			if ( ! is_wp_error( $response ) && is_array( $response ) ) {
622
				$api_response = json_decode( wp_remote_retrieve_body( $response ), true );
623
				if ( isset( $api_response['tag_name'] ) && version_compare( $api_response['tag_name'], $this->latest, '>=' ) >= 0 && empty( $api_response['prerelease'] ) ) {
624
					$version = $api_response['tag_name'];
625
				}
626
			}
627
628
			return $version;
629
		}
630
631
		/**
632
		 * Inline CSS for RTL language support.
633
		 *
634
		 * @since 1.0.13
635
		 * @return string Inline CSS.
636
		 */
637
		public function rtl_inline_css() {
638
			$inline_css = '[dir=rtl] .fa-address,[dir=rtl] .fa-address-card,[dir=rtl] .fa-adjust,[dir=rtl] .fa-alarm-clock,[dir=rtl] .fa-align-left,[dir=rtl] .fa-align-right,[dir=rtl] .fa-analytics,[dir=rtl] .fa-angle-double-left,[dir=rtl] .fa-angle-double-right,[dir=rtl] .fa-angle-left,[dir=rtl] .fa-angle-right,[dir=rtl] .fa-arrow-alt-circle-left,[dir=rtl] .fa-arrow-alt-circle-right,[dir=rtl] .fa-arrow-alt-from-left,[dir=rtl] .fa-arrow-alt-from-right,[dir=rtl] .fa-arrow-alt-left,[dir=rtl] .fa-arrow-alt-right,[dir=rtl] .fa-arrow-alt-square-left,[dir=rtl] .fa-arrow-alt-square-right,[dir=rtl] .fa-arrow-alt-to-left,[dir=rtl] .fa-arrow-alt-to-right,[dir=rtl] .fa-arrow-circle-left,[dir=rtl] .fa-arrow-circle-right,[dir=rtl] .fa-arrow-from-left,[dir=rtl] .fa-arrow-from-right,[dir=rtl] .fa-arrow-left,[dir=rtl] .fa-arrow-right,[dir=rtl] .fa-arrow-square-left,[dir=rtl] .fa-arrow-square-right,[dir=rtl] .fa-arrow-to-left,[dir=rtl] .fa-arrow-to-right,[dir=rtl] .fa-balance-scale-left,[dir=rtl] .fa-balance-scale-right,[dir=rtl] .fa-bed,[dir=rtl] .fa-bed-bunk,[dir=rtl] .fa-bed-empty,[dir=rtl] .fa-border-left,[dir=rtl] .fa-border-right,[dir=rtl] .fa-calendar-check,[dir=rtl] .fa-caret-circle-left,[dir=rtl] .fa-caret-circle-right,[dir=rtl] .fa-caret-left,[dir=rtl] .fa-caret-right,[dir=rtl] .fa-caret-square-left,[dir=rtl] .fa-caret-square-right,[dir=rtl] .fa-cart-arrow-down,[dir=rtl] .fa-cart-plus,[dir=rtl] .fa-chart-area,[dir=rtl] .fa-chart-bar,[dir=rtl] .fa-chart-line,[dir=rtl] .fa-chart-line-down,[dir=rtl] .fa-chart-network,[dir=rtl] .fa-chart-pie,[dir=rtl] .fa-chart-pie-alt,[dir=rtl] .fa-chart-scatter,[dir=rtl] .fa-check-circle,[dir=rtl] .fa-check-square,[dir=rtl] .fa-chevron-circle-left,[dir=rtl] .fa-chevron-circle-right,[dir=rtl] .fa-chevron-double-left,[dir=rtl] .fa-chevron-double-right,[dir=rtl] .fa-chevron-left,[dir=rtl] .fa-chevron-right,[dir=rtl] .fa-chevron-square-left,[dir=rtl] .fa-chevron-square-right,[dir=rtl] .fa-clock,[dir=rtl] .fa-file,[dir=rtl] .fa-file-alt,[dir=rtl] .fa-file-archive,[dir=rtl] .fa-file-audio,[dir=rtl] .fa-file-chart-line,[dir=rtl] .fa-file-chart-pie,[dir=rtl] .fa-file-code,[dir=rtl] .fa-file-excel,[dir=rtl] .fa-file-image,[dir=rtl] .fa-file-pdf,[dir=rtl] .fa-file-powerpoint,[dir=rtl] .fa-file-video,[dir=rtl] .fa-file-word,[dir=rtl] .fa-flag,[dir=rtl] .fa-folder,[dir=rtl] .fa-folder-open,[dir=rtl] .fa-hand-lizard,[dir=rtl] .fa-hand-point-down,[dir=rtl] .fa-hand-point-left,[dir=rtl] .fa-hand-point-right,[dir=rtl] .fa-hand-point-up,[dir=rtl] .fa-hand-scissors,[dir=rtl] .fa-image,[dir=rtl] .fa-long-arrow-alt-left,[dir=rtl] .fa-long-arrow-alt-right,[dir=rtl] .fa-long-arrow-left,[dir=rtl] .fa-long-arrow-right,[dir=rtl] .fa-luggage-cart,[dir=rtl] .fa-moon,[dir=rtl] .fa-pencil,[dir=rtl] .fa-pencil-alt,[dir=rtl] .fa-play-circle,[dir=rtl] .fa-project-diagram,[dir=rtl] .fa-quote-left,[dir=rtl] .fa-quote-right,[dir=rtl] .fa-shopping-cart,[dir=rtl] .fa-thumbs-down,[dir=rtl] .fa-thumbs-up,[dir=rtl] .fa-user-chart{filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=0, mirror=1);transform:scale(-1,1)}[dir=rtl] .fa-spin{animation-direction:reverse}';
639
640
			return $inline_css;
641
		}
642
643
		/**
644
		 * Show any warnings as an admin notice.
645
		 *
646
		 * @return void
647
		 */
648
		public function admin_notices() {
649
			$settings = $this->settings;
650
651
			if ( defined( 'FONTAWESOME_PLUGIN_FILE' ) ) {
652
				if ( ! empty( $_REQUEST['page'] ) && $_REQUEST['page'] == 'wp-font-awesome-settings' ) {
653
					?>
654
                    <div class="notice  notice-error is-dismissible">
655
                        <p><?php _e( 'The Official Font Awesome Plugin is active, please adjust your settings there.', 'font-awesome-settings' ); ?></p>
656
                    </div>
657
					<?php
658
				}
659
			} else {
660
				if ( ! empty( $settings ) ) {
661
					if ( $settings['type'] != 'KIT' && $settings['pro'] && ( $settings['version'] == '' || version_compare( $settings['version'], '6', '>=' ) ) ) {
662
						$link = admin_url('options-general.php?page=wp-font-awesome-settings');
663
						?>
664
                        <div class="notice  notice-error is-dismissible">
665
                            <p><?php echo sprintf( __( 'Font Awesome Pro v6 requires the use of a kit, please setup your kit in %ssettings.%s', 'font-awesome-settings' ),"<a href='". esc_url_raw( $link )."'>","</a>" ); ?></p>
666
                        </div>
667
						<?php
668
					}
669
				}
670
			}
671
		}
672
673
		/**
674
		 * Handle fontawesome save settings to download fontawesome to store locally.
675
		 *
676
		 * @since 1.1.0
677
		 *
678
		 * @param mixed $old_value The old option value.
679
		 * @param mixed $value     The new option value.
680
		 */
681
		public function update_option_wp_font_awesome_settings( $old_value, $new_value ) {
682
			// Do nothing if WordPress is being installed.
683
			if ( wp_installing() ) {
684
				return;
685
			}
686
687
			if ( ! empty( $new_value['local'] ) && empty( $new_value['pro'] ) ) {
688
				// Old values
689
				$old_version = isset( $old_value['version'] ) && $old_value['version'] ? $old_value['version'] : ( isset( $old_value['local_version'] ) ? $old_value['local_version'] : '' );
690
				$old_local = isset( $old_value['local'] ) ? (int) $old_value['local'] : 0;
691
692
				// New values
693
				$new_version = isset( $new_value['version'] ) && $new_value['version'] ? $new_value['version'] : $this->get_latest_version();
694
695
				if ( empty( $old_local ) || $old_version !== $new_version ) {
696
					$response = $this->download_package( $new_version, $new_value );
697
698
					if ( is_wp_error( $response ) ) {
699
						add_settings_error( 'general', 'fontawesome_download', __( 'ERROR:', 'font-awesome-settings' ) . ' ' . $response->get_error_message(), 'error' );
700
					}
701
				}
702
			}
703
		}
704
705
		/**
706
		 * Get the fonts directory local path.
707
		 *
708
		 * @since 1.1.0
709
		 *
710
		 * @param string Fonts directory local path.
0 ignored issues
show
Bug introduced by
The type Fonts was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
711
		 */
712
		public function get_fonts_dir() {
713
			$upload_dir = wp_upload_dir( null, false );
714
715
			return $upload_dir['basedir'] . DIRECTORY_SEPARATOR .  'ayefonts' . DIRECTORY_SEPARATOR . 'fa' . DIRECTORY_SEPARATOR;
716
		}
717
718
		/**
719
		 * Get the fonts directory local url.
720
		 *
721
		 * @since 1.1.0
722
		 *
723
		 * @param string Fonts directory local url.
724
		 */
725
		public function get_fonts_url() {
726
			$upload_dir = wp_upload_dir( null, false );
727
728
			return $upload_dir['baseurl'] .  '/ayefonts/fa/';
729
		}
730
731
		/**
732
		 * Check whether load locally active.
733
		 *
734
		 * @since 1.1.0
735
		 *
736
		 * @return bool True if active else false.
737
		 */
738
		public function has_local() {
739
			if ( ! empty( $this->settings['local'] ) && empty( $this->settings['pro'] ) && file_exists( $this->get_fonts_dir() . 'css' . DIRECTORY_SEPARATOR . 'all.css' ) ) {
740
				return true;
741
			}
742
743
			return false;
744
		}
745
746
		/**
747
		 * Get the WP Filesystem access.
748
		 *
749
		 * @since 1.1.0
750
		 *
751
		 * @return object The WP Filesystem.
752
		 */
753
		public function get_wp_filesystem() {
754
			if ( ! function_exists( 'get_filesystem_method' ) ) {
755
				require_once( ABSPATH . "/wp-admin/includes/file.php" );
756
			}
757
758
			$access_type = get_filesystem_method();
759
760
			if ( $access_type === 'direct' ) {
761
				/* You can safely run request_filesystem_credentials() without any issues and don't need to worry about passing in a URL */
762
				$creds = request_filesystem_credentials( trailingslashit( site_url() ) . 'wp-admin/', '', false, false, array() );
0 ignored issues
show
Bug introduced by
false of type false is incompatible with the type string expected by parameter $context of request_filesystem_credentials(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

762
				$creds = request_filesystem_credentials( trailingslashit( site_url() ) . 'wp-admin/', '', false, /** @scrutinizer ignore-type */ false, array() );
Loading history...
763
764
				/* Initialize the API */
765
				if ( ! WP_Filesystem( $creds ) ) {
766
					/* Any problems and we exit */
767
					return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type object.
Loading history...
768
				}
769
770
				global $wp_filesystem;
771
772
				return $wp_filesystem;
773
				/* Do our file manipulations below */
774
			} else if ( defined( 'FTP_USER' ) ) {
775
				$creds = request_filesystem_credentials( trailingslashit( site_url() ) . 'wp-admin/', '', false, false, array() );
776
777
				/* Initialize the API */
778
				if ( ! WP_Filesystem( $creds ) ) {
779
					/* Any problems and we exit */
780
					return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type object.
Loading history...
781
				}
782
783
				global $wp_filesystem;
784
785
				return $wp_filesystem;
786
			} else {
787
				/* Don't have direct write access. Prompt user with our notice */
788
				return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type object.
Loading history...
789
			}
790
		}
791
792
		/**
793
		 * Download the fontawesome package file.
794
		 *
795
		 * @since 1.1.0
796
		 *
797
		 * @param mixed $version The font awesome.
798
		 * @param array $option Fontawesome settings.
799
		 * @return WP_ERROR|bool Error on fail and true on success.
800
		 */
801
		public function download_package( $version, $option = array() ) {
802
			$filename = 'fontawesome-free-' . $version . '-web';
803
			$url = 'https://use.fontawesome.com/releases/v' . $version . '/' . $filename . '.zip';
804
805
			if ( ! function_exists( 'wp_handle_upload' ) ) {
806
				require_once ABSPATH . 'wp-admin/includes/file.php';
807
			}
808
809
			$download_file = download_url( esc_url_raw( $url ) );
810
811
			if ( is_wp_error( $download_file ) ) {
812
				return new WP_Error( 'fontawesome_download_failed', __( $download_file->get_error_message(), 'font-awesome-settings' ) );
813
			} else if ( empty( $download_file ) ) {
814
				return new WP_Error( 'fontawesome_download_failed', __( 'Something went wrong in downloading the font awesome to store locally.', 'font-awesome-settings' ) );
815
			}
816
817
			$response = $this->extract_package( $download_file, $filename, true );
0 ignored issues
show
Bug introduced by
$download_file of type WP_Error is incompatible with the type string expected by parameter $package of WP_Font_Awesome_Settings::extract_package(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

817
			$response = $this->extract_package( /** @scrutinizer ignore-type */ $download_file, $filename, true );
Loading history...
818
819
			// Update local version.
820
			if ( is_wp_error( $response ) ) {
821
				return $response;
822
			} else if ( $response ) {
823
				if ( empty( $option ) ) {
824
					$option = get_option( 'wp-font-awesome-settings' );
825
				}
826
827
				$option['local_version'] = $version;
828
829
				// Remove action to prevent looping.
830
				remove_action( 'update_option_wp-font-awesome-settings', array( $this, 'update_option_wp_font_awesome_settings' ), 10, 2 );
0 ignored issues
show
Unused Code introduced by
The call to remove_action() has too many arguments starting with 2. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

830
				/** @scrutinizer ignore-call */ 
831
    remove_action( 'update_option_wp-font-awesome-settings', array( $this, 'update_option_wp_font_awesome_settings' ), 10, 2 );

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
831
832
				update_option( 'wp-font-awesome-settings', $option );
833
834
				return true;
835
			}
836
837
			return false;
838
		}
839
840
		/**
841
		 * Extract the fontawesome package file.
842
		 *
843
		 * @since 1.1.0
844
		 *
845
		 * @param string $package The package file path.
846
		 * @param string $dirname Package file name.
847
		 * @param bool   $delete_package Delete temp file or not.
848
		 * @return WP_Error|bool True on success WP_Error on fail.
849
		 */
850
		public function extract_package( $package, $dirname = '', $delete_package = false ) {
851
			global $wp_filesystem;
852
853
			$wp_filesystem = $this->get_wp_filesystem();
854
855
			if ( empty( $wp_filesystem ) && isset( $wp_filesystem->errors ) && is_wp_error( $wp_filesystem->errors ) && $wp_filesystem->errors->get_error_code() ) {
856
				return new WP_Error( 'fontawesome_filesystem_error', __( $wp_filesystem->errors->get_error_message(), 'font-awesome-settings' ) );
857
			} else if ( empty( $wp_filesystem ) ) {
858
				return new WP_Error( 'fontawesome_filesystem_error', __( 'Failed to initialise WP_Filesystem while trying to download the Font Awesome package.', 'font-awesome-settings' ) );
859
			}
860
861
			$fonts_dir = $this->get_fonts_dir();
862
			$fonts_tmp_dir = dirname( $fonts_dir ) . DIRECTORY_SEPARATOR . 'fa-tmp' . DIRECTORY_SEPARATOR;
863
864
			if ( $wp_filesystem->is_dir( $fonts_tmp_dir ) ) {
865
				$wp_filesystem->delete( $fonts_tmp_dir, true );
866
			}
867
868
			// Unzip package to working directory.
869
			$result = unzip_file( $package, $fonts_tmp_dir );
870
871
			if ( is_wp_error( $result ) ) {
872
				$wp_filesystem->delete( $fonts_tmp_dir, true );
873
874
				if ( 'incompatible_archive' === $result->get_error_code() ) {
875
					return new WP_Error( 'fontawesome_incompatible_archive', __( $result->get_error_message(), 'font-awesome-settings' ) );
876
				}
877
878
				return $result;
879
			}
880
881
			if ( $wp_filesystem->is_dir( $fonts_dir ) ) {
882
				$wp_filesystem->delete( $fonts_dir, true );
883
			}
884
885
			$extract_dir = $fonts_tmp_dir;
886
887
			if ( $dirname && $wp_filesystem->is_dir( $extract_dir . $dirname . DIRECTORY_SEPARATOR ) ) {
888
				$extract_dir .= $dirname . DIRECTORY_SEPARATOR;
889
			}
890
891
			try {
892
				$return = $wp_filesystem->move( $extract_dir, $fonts_dir, true );
893
			} catch ( Exception $e ) {
894
				$return = new WP_Error( 'fontawesome_move_package', __( 'Fail to move font awesome package!', 'font-awesome-settings' ) );
895
			}
896
897
			if ( $wp_filesystem->is_dir( $fonts_tmp_dir ) ) {
898
				$wp_filesystem->delete( $fonts_tmp_dir, true );
899
			}
900
901
			// Once extracted, delete the package if required.
902
			if ( $delete_package ) {
903
				unlink( $package );
904
			}
905
906
			return $return;
907
		}
908
	}
909
910
	/**
911
	 * Run the class if found.
912
	 */
913
	WP_Font_Awesome_Settings::instance();
914
}
915