OMGF | GDPR/DSVGO Compliant, Faster Google Fonts. Easy. - Version 2.1.6

Version Description

Fixed bug where tables weren't created upon installation. Moved logic to plugin activation, instead of 'plugins_loaded'.

Download this release

Release Info

Developer DaanvandenBergh
Plugin Icon 128x128 OMGF | GDPR/DSVGO Compliant, Faster Google Fonts. Easy.
Version 2.1.6
Comparing to
See all releases

Code changes from version 2.0.8 to 2.1.6

host-webfonts-local.php CHANGED
@@ -4,7 +4,7 @@
4
  * Plugin Name: OMGF
5
  * Plugin URI: https://daan.dev/wordpress-plugins/host-google-fonts-locally
6
  * Description: Minimize DNS requests and leverage browser cache by easily saving Google Fonts to your server and removing the external Google Fonts.
7
- * Version: 2.0.8
8
  * Author: Daan van den Bergh
9
  * Author URI: https://daan.dev
10
  * License: GPL2v2 or later
@@ -12,576 +12,66 @@
12
  * @formatter:on
13
  */
14
 
15
- // Exit if accessed directly
16
- if (!defined('ABSPATH')) {
17
- exit;
18
- }
19
-
20
- global $wpdb;
21
 
22
  /**
23
  * Define constants.
24
  */
 
 
25
  define('OMGF_DB_VERSION', '1.8.3');
26
- define('OMGF_STATIC_VERSION', '2.0.2');
27
  define('OMGF_WEB_FONT_LOADER_VERSION', '1.6.26');
28
- define('OMGF_SITE_URL', 'https://daan.dev');
29
- define('OMGF_DB_TABLENAME', $wpdb->prefix . 'caos_webfonts');
30
- define('OMGF_DB_CHARSET', $wpdb->get_charset_collate());
31
- define('OMGF_HELPER_URL', 'https://google-webfonts-helper.herokuapp.com/api/fonts/');
32
- define('OMGF_FILENAME', 'fonts.css');
33
- define('OMGF_CACHE_DIR', esc_attr(get_option('caos_webfonts_cache_dir')) ?: '/cache/omgf-webfonts');
34
- define('OMGF_CDN_URL', esc_attr(get_option('caos_webfonts_cdn_url')));
35
- define('OMGF_WEB_FONT_LOADER', esc_attr(get_option('omgf_web_font_loader')));
36
- define('OMGF_REMOVE_VERSION', esc_attr(get_option('caos_webfonts_remove_version')));
37
- define('OMGF_CURRENT_BLOG_ID', get_current_blog_id());
38
- define('OMGF_UPLOAD_DIR', WP_CONTENT_DIR . OMGF_CACHE_DIR);
39
- define('OMGF_UPLOAD_URL', hwlGetUploadUrl());
40
- define('OMGF_DISPLAY_OPTION', esc_attr(get_option('caos_webfonts_display_option')) ?: 'auto');
41
- define('OMGF_REMOVE_GFONTS', esc_attr(get_option('caos_webfonts_remove_gfonts')));
42
- define('OMGF_PRELOAD', esc_attr(get_option('caos_webfonts_preload')));
43
-
44
- /**
45
- * Register settings
46
- */
47
- function hwlRegisterSettings()
48
- {
49
- register_setting(
50
- 'caos-webfonts-basic-settings',
51
- 'caos_webfonts_cache_dir'
52
- );
53
- register_setting(
54
- 'caos-webfonts-basic-settings',
55
- 'caos_webfonts_cdn_url'
56
- );
57
- register_setting(
58
- 'caos-webfonts-basic-settings',
59
- 'omgf_web_font_loader'
60
- );
61
- register_setting(
62
- 'caos-webfonts-basic-settings',
63
- 'caos_webfonts_remove_version'
64
- );
65
- register_setting(
66
- 'caos-webfonts-basic-settings',
67
- 'caos_webfonts_display_option'
68
- );
69
- register_setting(
70
- 'caos-webfonts-basic-settings',
71
- 'caos_webfonts_remove_gfonts'
72
- );
73
- register_setting(
74
- 'caos-webfonts-basic-settings',
75
- 'caos_webfonts_preload'
76
- );
77
- }
78
 
79
  /**
80
- * Create the Admin menu-item
81
- */
82
- function hwlCreateMenu()
83
- {
84
- add_options_page(
85
- 'OMGF',
86
- 'Optimize Webfonts',
87
- 'manage_options',
88
- 'optimize-webfonts',
89
- 'hwlSettingsPage'
90
- );
91
- add_action(
92
- 'admin_init',
93
- 'hwlRegisterSettings'
94
- );
95
- }
96
-
97
- add_action('admin_menu', 'hwlCreateMenu');
98
-
99
- /**
100
- * Returns the configured name of WordPress' content directory.
101
  *
102
- * @return mixed
103
- */
104
- function hwlGetContentDirName()
105
- {
106
- preg_match('/[^\/]+$/u', WP_CONTENT_DIR, $match);
107
-
108
- return $match[0];
109
- }
110
-
111
- /**
112
- * @return string
113
- */
114
- function hwlGetUploadUrl()
115
- {
116
- if (OMGF_CDN_URL) {
117
- $uploadUrl = '//' . OMGF_CDN_URL . '/' . hwlGetContentDirName() . OMGF_CACHE_DIR;
118
- } else {
119
- $uploadUrl = get_site_url(OMGF_CURRENT_BLOG_ID, hwlGetContentDirName() . OMGF_CACHE_DIR);
120
- }
121
-
122
- return $uploadUrl;
123
- }
124
-
125
- /**
126
- * Create table to store downloaded fonts in version 1.6.1.
127
- */
128
- function hwlCreateWebfontsTable()
129
- {
130
- global $wpdb;
131
- $sql = "CREATE TABLE IF NOT EXISTS " . OMGF_DB_TABLENAME . " (
132
- font_id varchar(191) NOT NULL,
133
- font_family varchar(191) NOT NULL,
134
- font_weight mediumint(5) NOT NULL,
135
- font_style varchar(191) NOT NULL,
136
- downloaded tinyint(1) DEFAULT 0,
137
- url_ttf varchar(191) NULL,
138
- url_woff varchar(191) NULL,
139
- url_woff2 varchar(191) NULL,
140
- url_eot varchar(191) NULL,
141
- UNIQUE KEY (font_id)
142
- ) " . OMGF_DB_CHARSET . ";";
143
- $wpdb->query($sql);
144
-
145
- add_option('caos_webfonts_db_version', '1.6.1');
146
- }
147
-
148
- /**
149
- * Create table to store selected subsets in version 1.7.0.
150
- */
151
- function hwlCreateSubsetsTable()
152
- {
153
- global $wpdb;
154
- $sql = "CREATE TABLE IF NOT EXISTS " . OMGF_DB_TABLENAME . '_subsets' . " (
155
- subset_font varchar(32) NOT NULL,
156
- subset_family varchar(191) NOT NULL,
157
- available_subsets varchar(191) NOT NULL,
158
- selected_subsets varchar(191) NOT NULL,
159
- UNIQUE KEY (subset_font)
160
- ) " . OMGF_DB_CHARSET . ";";
161
- $wpdb->query($sql);
162
-
163
- update_option('caos_webfonts_db_version', '1.7.0');
164
- }
165
-
166
- /**
167
- * Adds the 'local' column in version 1.8.3
168
- */
169
- function hwlAddLocalColumn()
170
- {
171
- global $wpdb;
172
-
173
- $sql = "ALTER TABLE " . OMGF_DB_TABLENAME . " " .
174
- "ADD COLUMN local varchar(128) AFTER font_style;";
175
- $wpdb->query($sql);
176
-
177
- update_option('caos_webfonts_db_version', '1.8.3');
178
- }
179
-
180
- /**
181
- * Check current version and execute required db updates.
182
- */
183
- function hwlRunDbUpdates()
184
- {
185
- $currentVersion = get_option('caos_webfonts_db_version') ?: '1.0.0';
186
- if (version_compare($currentVersion, '1.6.1') < 0) {
187
- hwlCreateWebfontsTable();
188
- }
189
- if (version_compare($currentVersion, '1.7.0') < 0) {
190
- hwlCreateSubsetsTable();
191
- }
192
- if (version_compare($currentVersion, OMGF_DB_VERSION) < 0) {
193
- hwlAddLocalColumn();
194
- }
195
- }
196
-
197
- add_action('plugins_loaded', 'hwlRunDbUpdates');
198
-
199
- /**
200
- * @param $links
201
- *
202
- * @return mixed
203
- */
204
- function hwlSettingsLink($links)
205
- {
206
- $adminUrl = admin_url() . 'options-general.php?page=optimize-webfonts';
207
- $settingsLink = "<a href='$adminUrl'>" . __('Settings') . "</a>";
208
- array_push($links, $settingsLink);
209
-
210
- return $links;
211
- }
212
-
213
- $caosLink = plugin_basename(__FILE__);
214
-
215
- add_filter("plugin_action_links_$caosLink", 'hwlSettingsLink');
216
-
217
- /**
218
- * Render the settings page.
219
- */
220
- function hwlSettingsPage()
221
- {
222
- if (!current_user_can('manage_options')) {
223
- wp_die(__("You're not cool enough to access this page."));
224
- }
225
- ?>
226
- <div class="wrap">
227
- <h1><?php _e('OMGF | Optimize My Google Fonts', 'host-webfonts-local'); ?></h1>
228
- <p>
229
- <?php _e('Developed by: ', 'host-webfonts-local'); ?>
230
- <a title="Buy me a beer!" href="<?php echo OMGF_SITE_URL; ?>/donate/">Daan van den Bergh</a>.
231
- </p>
232
-
233
- <div id="hwl-admin-notices"></div>
234
-
235
- <?php require_once(dirname(__FILE__) . '/includes/templates/settings-welcome.phtml'); ?>
236
-
237
- <form id="hwl-options-form" class="settings-column left" name="hwl-options-form" method="post">
238
- <div class="">
239
- <?php require_once(dirname(__FILE__) . '/includes/templates/settings-generate-stylesheet.phtml'); ?>
240
- </div>
241
- </form>
242
-
243
- <form id="hwl-settings-form" class="settings-column right" name="hwl-settings-form" method="post" action="options.php">
244
- <?php
245
- settings_fields('caos-webfonts-basic-settings');
246
- do_settings_sections('caos-webfonts-basic-settings');
247
-
248
- require_once(dirname(__FILE__) . '/includes/templates/settings-basic-settings.phtml');
249
-
250
- do_action('hwl_after_settings_form_settings');
251
-
252
- submit_button();
253
- ?>
254
- </form>
255
- </div>
256
- <?php
257
- }
258
-
259
- /**
260
- * @return array|\Exception
261
- */
262
- function hwlGetTotalFonts()
263
- {
264
- global $wpdb;
265
-
266
- try {
267
- return $wpdb->get_results("SELECT * FROM " . OMGF_DB_TABLENAME);
268
- } catch (\Exception $e) {
269
- return $e;
270
- }
271
- }
272
-
273
- /**
274
- * @return array|\Exception
275
- */
276
- function hwlGetDownloadedFonts()
277
- {
278
- global $wpdb;
279
-
280
- try {
281
- return $wpdb->get_results("SELECT * FROM " . OMGF_DB_TABLENAME . " WHERE downloaded = 1");
282
- } catch (\Exception $e) {
283
- return $e;
284
- }
285
- }
286
-
287
- /**
288
- * @return array
289
- */
290
- function hwlGetDownloadStatus()
291
- {
292
- return array(
293
- "downloaded" => count(hwlGetDownloadedFonts()),
294
- "total" => count(hwlGetTotalFonts())
295
- );
296
- }
297
-
298
- /**
299
- * @return array|\Exception|null|object
300
- */
301
- function hwlGetSubsets()
302
- {
303
- global $wpdb;
304
-
305
- try {
306
- return $wpdb->get_results("SELECT * FROM " . OMGF_DB_TABLENAME . "_subsets");
307
- } catch (\Exception $e) {
308
- return $e;
309
- }
310
- }
311
-
312
- function hwlGetFontsByFamily($family)
313
- {
314
- global $wpdb;
315
-
316
- try {
317
- return $wpdb->get_results("SELECT * FROM " . OMGF_DB_TABLENAME . " WHERE font_family = '$family'");
318
- } catch (\Exception $e) {
319
- return $e;
320
- }
321
- }
322
-
323
- /**
324
- * @return \Exception|void
325
- */
326
- function hwlCleanQueue()
327
- {
328
- global $wpdb;
329
-
330
- try {
331
- $wpdb->query("TRUNCATE TABLE " . OMGF_DB_TABLENAME);
332
- $wpdb->query("TRUNCATE TABLE " . OMGF_DB_TABLENAME . "_subsets");
333
- } catch (\Exception $e) {
334
- return $e;
335
- }
336
- }
337
-
338
- /**
339
- * AJAX-wrapper for hwlGetDownloadStatus()
340
- */
341
- function hwlAjaxGetDownloadStatus()
342
- {
343
- return wp_die(
344
- json_encode(
345
- hwlGetDownloadStatus()
346
- )
347
- );
348
- }
349
-
350
- add_action('wp_ajax_hwlAjaxGetDownloadStatus', 'hwlAjaxGetDownloadStatus');
351
-
352
- /**
353
- * AJAX-wrapper for hwlCleanQueue()
354
- */
355
- function hwlAjaxCleanQueue()
356
- {
357
- return wp_die(hwlCleanQueue());
358
- }
359
-
360
- add_action('wp_ajax_hwlAjaxCleanQueue', 'hwlAjaxCleanQueue');
361
-
362
- /**
363
- * AJAX-wrapper for hwlEmptyDir()
364
  *
365
- * @return array
366
  */
367
- function hwlAjaxEmptyDir()
368
  {
369
- return array_map('unlink', array_filter((array) glob(OMGF_UPLOAD_DIR . '/*')));
370
- }
371
-
372
- add_action('wp_ajax_hwlAjaxEmptyDir', 'hwlAjaxEmptyDir');
373
 
374
- /**
375
- * Search Subsets in Google Webfonts Helper
376
- */
377
- function hwlAjaxSearchFontSubsets()
378
- {
379
- try {
380
- $searchQueries = explode(',', sanitize_text_field($_POST['search_query']));
381
-
382
- foreach ($searchQueries as $searchQuery) {
383
- $request = curl_init();
384
- curl_setopt($request, CURLOPT_URL, OMGF_HELPER_URL . $searchQuery);
385
- curl_setopt($request, CURLOPT_RETURNTRANSFER, 1);
386
- $result = curl_exec($request);
387
- curl_close($request);
388
-
389
- $result = json_decode($result);
390
- $response[] = array(
391
- 'family' => $result->family,
392
- 'id' => $result->id,
393
- 'subsets' => $result->subsets
394
- );
395
- }
396
- wp_die(json_encode($response));
397
- } catch (\Exception $e) {
398
- wp_die($e);
399
- }
400
- }
401
-
402
- add_action('wp_ajax_hwlAjaxSearchFontSubsets', 'hwlAjaxSearchFontSubsets');
403
-
404
- /**
405
- * Search Fonts in Google Webfonts Helper
406
- */
407
- function hwlAjaxSearchGoogleFonts()
408
- {
409
- try {
410
- $request = curl_init();
411
- $searchQuery = sanitize_text_field($_POST['search_query']);
412
- $subsets = implode($_POST['search_subsets'], ',');
413
-
414
- curl_setopt($request, CURLOPT_URL, OMGF_HELPER_URL . $searchQuery . '?subsets=' . $subsets);
415
- curl_setopt($request, CURLOPT_RETURNTRANSFER, 1);
416
-
417
- $result = curl_exec($request);
418
-
419
- curl_close($request);
420
- wp_die($result);
421
- } catch (\Exception $e) {
422
- wp_die($e);
423
  }
424
- }
425
-
426
- add_action('wp_ajax_hwlAjaxSearchGoogleFonts', 'hwlAjaxSearchGoogleFonts');
427
 
428
- /**
429
- * Create cache dir upon plugin (re-)activation.
430
- */
431
- function hwlCreateCacheDir()
432
- {
433
- $uploadDir = OMGF_UPLOAD_DIR;
434
- if (!is_dir($uploadDir)) {
435
- wp_mkdir_p($uploadDir);
436
- }
437
- }
438
 
439
- register_activation_hook(__FILE__, 'hwlCreateCacheDir');
440
-
441
- /**
442
- * @return array
443
- */
444
- function hwlFontDisplayOptions()
445
- {
446
- $fontDisplay = array(
447
- __('Auto (default)', 'host-webfonts-local') => 'auto',
448
- __('Block', 'host-webfonts-local') => 'block',
449
- __('Swap', 'host-webfonts-local') => 'swap',
450
- __('Fallback', 'host-webfonts-local') => 'fallback',
451
- __('Optional', 'host-webfonts-local') => 'optional'
452
- );
453
-
454
- return $fontDisplay;
455
- }
456
-
457
- /**
458
- * The function for generating the stylesheet and saving it to the upload-dir.
459
- */
460
- function hwlAjaxGenerateStyles()
461
- {
462
- require_once(dirname(__FILE__) . '/includes/ajax/class-generate-styles.php');
463
- }
464
-
465
- add_action('wp_ajax_hwlAjaxGenerateStyles', 'hwlAjaxGenerateStyles');
466
-
467
- /**
468
- * Saves the chosen webfonts to the database for further processing.
469
- */
470
- function hwlAjaxDownloadFonts()
471
- {
472
- require_once(dirname(__FILE__) . '/includes/ajax/class-download-fonts.php');
473
- }
474
-
475
- add_action('wp_ajax_hwlAjaxDownloadFonts', 'hwlAjaxDownloadFonts');
476
-
477
- /**
478
- * Once the stylesheet is generated. We can enqueue it.
479
- */
480
- function hwlEnqueueStylesheet()
481
- {
482
- if (OMGF_WEB_FONT_LOADER) {
483
- require_once(dirname(__FILE__) . '/includes/templates/script-web-font-loader.phtml');
484
  } else {
485
- wp_enqueue_style('omgf-fonts', OMGF_UPLOAD_URL . '/' . OMGF_FILENAME, array(), (OMGF_REMOVE_VERSION ? null : OMGF_STATIC_VERSION));
486
- }
487
- }
488
 
489
- add_action('wp_enqueue_scripts', 'hwlEnqueueStylesheet');
 
 
 
490
 
491
- /**
492
- * Stylesheet and Javascript needed in Admin
493
- */
494
- function hwlEnqueueAdminJs($hook)
495
- {
496
- if ($hook == 'settings_page_optimize-webfonts') {
497
- wp_enqueue_script('hwl-admin-js', plugin_dir_url(__FILE__) . 'js/hwl-admin.js', array('jquery'), OMGF_STATIC_VERSION, true);
498
- wp_enqueue_style('hwl-admin-css', plugin_dir_url(__FILE__) . 'css/hwl-admin.css', array(), OMGF_STATIC_VERSION);
499
  }
500
- }
501
-
502
- add_action('admin_enqueue_scripts', 'hwlEnqueueAdminJs');
503
-
504
- /**
505
- * When plugin is deactivated. Remove all CSS and JS.
506
- */
507
- function hwlDequeueJsCss()
508
- {
509
- wp_dequeue_script('hwl-admin-js');
510
- wp_dequeue_style('hwl-admin-css');
511
- wp_dequeue_style('omgf-fonts');
512
- }
513
-
514
- register_deactivation_hook(__FILE__, 'hwlDequeueJsCss');
515
 
516
- /**
517
- * Prioritize the loading of fonts by adding a resource hint to the document head.
518
- */
519
- function hwlAddLinkPreload()
520
- {
521
- global $wp_styles;
522
 
523
- $handle = 'omgf-fonts';
524
- $style = $wp_styles->registered[$handle];
525
-
526
- /** Do not add 'preload' if Minification plugins are enabled. */
527
- if ($style) {
528
- $source = $style->src . ($style->ver ? "?ver={$style->ver}" : "");
529
- echo "<link rel='preload' href='{$source}' as='style' />\n";
530
- }
531
- }
532
-
533
- function hwlIsPreloadEnabled()
534
- {
535
- if (OMGF_PRELOAD == 'on') {
536
- add_action('wp_head', 'hwlAddLinkPreload', 1);
537
- }
538
  }
539
 
540
- add_action('init', 'hwlIsPreloadEnabled');
541
 
542
  /**
543
- * Automatically dequeues any stylesheets loaded from fonts.gstatic.com or
544
- * fonts.googleapis.com. Also checks for stylesheets dependant on Google Fonts and
545
- * re-enqueues and registers them.
546
  */
547
- function hwlRemoveGoogleFonts()
548
  {
549
- global $wp_styles;
550
-
551
- $registered = $wp_styles->registered;
552
- $fonts = array_filter(
553
- $registered, function ($contents) {
554
- return strpos($contents->src, 'fonts.googleapis.com') !== false
555
- || strpos($contents->src, 'fonts.gstatic.com') !== false;
556
- }
557
- );
558
- $dependencies = array_filter(
559
- $registered, function ($contents) use ($fonts) {
560
- return !empty(array_intersect(array_keys($fonts), $contents->deps));
561
- }
562
- );
563
-
564
- foreach ($fonts as $font) {
565
- wp_deregister_style($font->handle);
566
- wp_dequeue_style($font->handle);
567
- }
568
-
569
- foreach ($dependencies as $dependency) {
570
- wp_register_style('omgf-dep-' . $dependency->handle, $dependency->src);
571
- wp_enqueue_style('omgf-dep-' . $dependency->handle, $dependency->src);
572
- }
573
- }
574
-
575
- function hwlIsRemoveGoogleFontsEnabled()
576
- {
577
- if (OMGF_REMOVE_GFONTS == 'on' && !is_admin()) {
578
- add_action('wp_print_styles', 'hwlRemoveGoogleFonts', PHP_INT_MAX);
579
-
580
- // Enfold compatibility.
581
- add_filter('avf_output_google_webfonts_script', function() {
582
- return false;
583
- });
584
- }
585
  }
586
 
587
- add_action('init', 'hwlIsRemoveGoogleFontsEnabled');
4
  * Plugin Name: OMGF
5
  * Plugin URI: https://daan.dev/wordpress-plugins/host-google-fonts-locally
6
  * Description: Minimize DNS requests and leverage browser cache by easily saving Google Fonts to your server and removing the external Google Fonts.
7
+ * Version: 2.1.6
8
  * Author: Daan van den Bergh
9
  * Author URI: https://daan.dev
10
  * License: GPL2v2 or later
12
  * @formatter:on
13
  */
14
 
15
+ defined('ABSPATH') || exit;
 
 
 
 
 
16
 
17
  /**
18
  * Define constants.
19
  */
20
+ define('OMGF_PLUGIN_DIR', plugin_dir_path(__FILE__));
21
+ define('OMGF_PLUGIN_FILE', __FILE__);
22
  define('OMGF_DB_VERSION', '1.8.3');
23
+ define('OMGF_STATIC_VERSION', '2.1.4');
24
  define('OMGF_WEB_FONT_LOADER_VERSION', '1.6.26');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
  /**
27
+ * Takes care of loading classes on demand.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  *
29
+ * @param $class
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  *
31
+ * @return mixed|void
32
  */
33
+ function omgf_autoload($class)
34
  {
35
+ $path = explode('_', $class);
 
 
 
36
 
37
+ if ($path[0] != 'OMGF') {
38
+ return;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  }
 
 
 
40
 
41
+ $filename = '';
 
 
 
 
 
 
 
 
 
42
 
43
+ if (count($path) == 1) {
44
+ $filename = 'class-' . strtolower(str_replace('_', '-', $class)) . '.php';
45
+ } elseif (count($path) == 2) {
46
+ array_shift($path);
47
+ $filename = 'class-' . strtolower($path[0]) . '.php';
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  } else {
49
+ array_shift($path);
50
+ end($path);
51
+ $i = 0;
52
 
53
+ while ($i < key($path)) {
54
+ $filename .= strtolower($path[$i]) . '/';
55
+ $i++;
56
+ }
57
 
58
+ $filename .= 'class-' . strtolower($path[$i]) . '.php';
 
 
 
 
 
 
 
59
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
 
61
+ return include OMGF_PLUGIN_DIR . 'includes/' . $filename;
 
 
 
 
 
62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  }
64
 
65
+ spl_autoload_register('omgf_autoload');
66
 
67
  /**
68
+ * All systems GO!!!
69
+ *
70
+ * @return OMGF
71
  */
72
+ function omgf_init()
73
  {
74
+ return new OMGF();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
  }
76
 
77
+ add_action('plugins_loaded', 'omgf_init', PHP_INT_MAX);
includes/admin/class-settings.php ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * @package : OMGF
4
+ * @author : Daan van den Bergh
5
+ * @copyright: (c) 2019 Daan van den Bergh
6
+ * @url : https://daan.dev
7
+ */
8
+
9
+ defined('ABSPATH') || exit;
10
+
11
+ class OMGF_Admin_Settings extends OMGF_Admin
12
+ {
13
+ const OMGF_FONT_DISPLAY_OPTIONS = array(
14
+ 'Auto (default)' => 'auto',
15
+ 'Block' => 'block',
16
+ 'Swap' => 'swap',
17
+ 'Fallback' => 'fallback',
18
+ 'Optional' => 'optional'
19
+ );
20
+ const OMGF_AUTO_DETECTION_ENABLED_LABEL = 'omgf_auto_detection_enabled';
21
+ const OMGF_DETECTED_FONTS_LABEL = 'omgf_detected_fonts';
22
+
23
+ /**
24
+ * OMGF_Admin_Settings constructor.
25
+ */
26
+ public function __construct()
27
+ {
28
+ // @formatter:off
29
+ add_action('admin_menu', array($this, 'create_menu'));
30
+
31
+ $caosLink = plugin_basename(OMGF_PLUGIN_FILE);
32
+
33
+ add_filter("plugin_action_links_$caosLink", array($this, 'create_settings_link'));
34
+ // @formatter:on
35
+
36
+ parent::__construct();
37
+ }
38
+
39
+ /**
40
+ * Creates the menu item.
41
+ */
42
+ public function create_menu()
43
+ {
44
+ add_options_page(
45
+ 'OMGF',
46
+ 'Optimize Webfonts',
47
+ 'manage_options',
48
+ 'optimize-webfonts',
49
+ array(
50
+ $this,
51
+ 'create_settings_page'
52
+ )
53
+ );
54
+ // @formatter:off
55
+ add_action('admin_init', array($this, 'register_settings'));
56
+ // @formatter:on
57
+ }
58
+
59
+ /**
60
+ * Display the settings page.
61
+ */
62
+ public function create_settings_page()
63
+ {
64
+ if (!current_user_can('manage_options')) {
65
+ wp_die(__("You're not cool enough to access this page."));
66
+ }
67
+ ?>
68
+ <div class="wrap">
69
+ <h1><?php _e('OMGF | Optimize My Google Fonts', 'host-webfonts-local'); ?></h1>
70
+
71
+ <div id="hwl-admin-notices"></div>
72
+
73
+ <?php $this->get_template('welcome'); ?>
74
+
75
+ <form id="hwl-options-form" class="settings-column left" name="hwl-options-form" method="post">
76
+ <div class="">
77
+ <?php $this->get_template('generate-stylesheet'); ?>
78
+ </div>
79
+ </form>
80
+
81
+ <form id="hwl-settings-form" class="settings-column right" name="hwl-settings-form" method="post" action="options.php">
82
+ <?php
83
+ settings_fields('caos-webfonts-basic-settings');
84
+ do_settings_sections('caos-webfonts-basic-settings');
85
+
86
+ $this->get_template('basic-settings');
87
+
88
+ do_action('hwl_after_settings_form_settings');
89
+
90
+ submit_button();
91
+ ?>
92
+ </form>
93
+ </div>
94
+ <?php
95
+ }
96
+
97
+ /**
98
+ * Register our settings.
99
+ */
100
+ public function register_settings()
101
+ {
102
+ register_setting(
103
+ 'caos-webfonts-basic-settings',
104
+ self::OMGF_AUTO_DETECTION_ENABLED_LABEL
105
+ );
106
+ register_setting(
107
+ 'caos-webfonts-basic-settings',
108
+ self::OMGF_DETECTED_FONTS_LABEL
109
+ );
110
+ register_setting(
111
+ 'caos-webfonts-basic-settings',
112
+ 'caos_webfonts_cache_dir'
113
+ );
114
+ register_setting(
115
+ 'caos-webfonts-basic-settings',
116
+ 'caos_webfonts_cdn_url'
117
+ );
118
+ register_setting(
119
+ 'caos-webfonts-basic-settings',
120
+ 'omgf_web_font_loader'
121
+ );
122
+ register_setting(
123
+ 'caos-webfonts-basic-settings',
124
+ 'caos_webfonts_remove_version'
125
+ );
126
+ register_setting(
127
+ 'caos-webfonts-basic-settings',
128
+ 'caos_webfonts_display_option'
129
+ );
130
+ register_setting(
131
+ 'caos-webfonts-basic-settings',
132
+ 'caos_webfonts_remove_gfonts'
133
+ );
134
+ register_setting(
135
+ 'caos-webfonts-basic-settings',
136
+ 'caos_webfonts_preload'
137
+ );
138
+ }
139
+
140
+ /**
141
+ * Adds the 'settings' link to the Plugin overview.
142
+ *
143
+ * @return mixed
144
+ */
145
+ public function create_settings_link($links)
146
+ {
147
+ $adminUrl = admin_url() . 'options-general.php?page=optimize-webfonts';
148
+ $settingsLink = "<a href='$adminUrl'>" . __('Settings') . "</a>";
149
+ array_push($links, $settingsLink);
150
+
151
+ return $links;
152
+ }
153
+ }
includes/ajax/class-detect.php ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * @package : OMGF
4
+ * @author : Daan van den Bergh
5
+ * @copyright: (c) 2019 Daan van den Bergh
6
+ * @url : https://daan.dev
7
+ */
8
+
9
+ defined('ABSPATH') || exit;
10
+
11
+ class OMGF_AJAX_Detect
12
+ {
13
+ public function __construct(
14
+ $fonts
15
+ ) {
16
+ $this->save_detected_fonts($fonts);
17
+ }
18
+
19
+ /**
20
+ *
21
+ */
22
+ public function save_detected_fonts($used_fonts)
23
+ {
24
+ $font_properties = $this->extract_font_properties($used_fonts);
25
+
26
+ $fonts = $this->build_subsets_array($font_properties);
27
+
28
+ /** It only needs to run once. */
29
+ update_option(OMGF_Admin_Settings::OMGF_AUTO_DETECTION_ENABLED_LABEL, false);
30
+
31
+ wp_die(json_encode($fonts));
32
+ }
33
+
34
+ /**
35
+ * @param $fontSource
36
+ *
37
+ * @return array
38
+ */
39
+ private function extract_font_properties($fontSource)
40
+ {
41
+ $font_properties = array();
42
+
43
+ $i = 0;
44
+
45
+ foreach ($fontSource as $source) {
46
+ $parts = parse_url($source);
47
+
48
+ parse_str($parts['query'], $font_properties[]);
49
+
50
+ /**
51
+ * Some themes (like Twenty Sixteen) do chained requests using a pipe (|).
52
+ * This function explodes these requests and adds them to the query.
53
+ */
54
+ if (strpos($font_properties[$i]['family'], '|') !== false) {
55
+ $parts_parts = explode('|', $font_properties[$i]['family']);
56
+ $font_property_subset = $font_properties[$i]['subset'];
57
+
58
+ foreach ($parts_parts as $part) {
59
+ $font_properties[$i]['family'] = $part;
60
+ $font_properties[$i]['subset'] = $font_property_subset;
61
+ $i++;
62
+ }
63
+ }
64
+
65
+ $i++;
66
+ }
67
+
68
+ return $font_properties;
69
+ }
70
+
71
+ /**
72
+ * @param $font_properties
73
+ *
74
+ * @return array
75
+ */
76
+ private function build_subsets_array($font_properties)
77
+ {
78
+ $i = 0;
79
+
80
+ foreach ($font_properties as $properties) {
81
+ $parts = explode(':', $properties['family']);
82
+ $subsets = isset($properties['subset']) ? explode(',', $properties['subset']) : null;
83
+
84
+ if (!empty($parts)) {
85
+ $font_family = $parts[0];
86
+ $styles = explode(',', $parts[1]);
87
+ }
88
+
89
+ $fonts['subsets'][$i]['family'] = $font_family;
90
+ $fonts['subsets'][$i]['id'] = str_replace(' ', '-', strtolower($font_family));
91
+ $fonts['subsets'][$i]['subsets'] = $subsets;
92
+ $fonts['subsets'][$i]['used_styles'] = $styles;
93
+
94
+ $i++;
95
+ }
96
+
97
+ $fonts['auto-detect'] = true;
98
+
99
+ return $fonts;
100
+ }
101
+ }
includes/ajax/{class-download-fonts.php → class-download.php} RENAMED
@@ -6,14 +6,9 @@
6
  * @url : https://daan.dev
7
  */
8
 
9
- // Exit if accessed directly
10
- if (!defined('ABSPATH')) {
11
- exit;
12
- }
13
-
14
- require_once(dirname(dirname(__FILE__)) . '/class-ajax.php');
15
 
16
- class OMGF_AJAX_Download_Fonts extends OMGF_AJAX
17
  {
18
  /** @var $fonts */
19
  private $fonts;
@@ -21,11 +16,23 @@ class OMGF_AJAX_Download_Fonts extends OMGF_AJAX
21
  /** @var $subsets */
22
  private $subsets;
23
 
 
 
 
 
 
 
24
  /**
25
  * OMGF_Download_Fonts constructor.
26
  */
27
  public function __construct()
28
  {
 
 
 
 
 
 
29
  $this->init();
30
  }
31
 
@@ -40,7 +47,7 @@ class OMGF_AJAX_Download_Fonts extends OMGF_AJAX
40
  * To match the current queue of fonts. We need to truncate the table first.
41
  */
42
  try {
43
- hwlCleanQueue();
44
  } catch (\Exception $e) {
45
  $this->throw_error($e->getCode(), $e->getMessage());
46
  }
@@ -58,7 +65,7 @@ class OMGF_AJAX_Download_Fonts extends OMGF_AJAX
58
  $this->save_subsets_to_db();
59
  $this->save_fonts_to_db();
60
 
61
- $this->download_fonts();
62
  }
63
 
64
  /**
@@ -77,13 +84,11 @@ class OMGF_AJAX_Download_Fonts extends OMGF_AJAX
77
  */
78
  private function save_subsets_to_db()
79
  {
80
- global $wpdb;
81
-
82
  foreach ($this->subsets as $id => $subset) {
83
  $availableSubsets = implode($subset['available'], ',');
84
- $selectedSubsets = implode($subset['selected'], ',');
85
 
86
- $wpdb->insert(
87
  OMGF_DB_TABLENAME . '_subsets',
88
  array(
89
  'subset_font' => $id,
@@ -100,10 +105,13 @@ class OMGF_AJAX_Download_Fonts extends OMGF_AJAX
100
  */
101
  private function save_fonts_to_db()
102
  {
103
- global $wpdb;
104
-
105
  foreach ($this->fonts as $id => $font) {
106
- $wpdb->insert(
 
 
 
 
 
107
  OMGF_DB_TABLENAME,
108
  array(
109
  'font_id' => sanitize_text_field($id),
@@ -112,23 +120,21 @@ class OMGF_AJAX_Download_Fonts extends OMGF_AJAX
112
  'font_style' => sanitize_text_field($font['font-style']),
113
  'local' => sanitize_text_field($font['local']),
114
  'downloaded' => 0,
115
- 'url_ttf' => esc_url_raw($font['url']['ttf']),
116
- 'url_woff' => esc_url_raw($font['url']['woff']),
117
- 'url_woff2' => esc_url_raw($font['url']['woff2']),
118
- 'url_eot' => esc_url_raw($font['url']['eot'])
119
  )
120
  );
121
  }
122
  }
123
 
124
  /**
125
- *
126
  */
127
- private function download_fonts()
128
  {
129
- global $wpdb;
130
-
131
- $selectedFonts = hwlGetTotalFonts();
132
 
133
  foreach ($selectedFonts as $id => $font) {
134
  // If font is marked as downloaded. Skip it.
@@ -142,6 +148,10 @@ class OMGF_AJAX_Download_Fonts extends OMGF_AJAX
142
  $urls['url_eot'] = $font->url_eot;
143
 
144
  foreach ($urls as $type => $url) {
 
 
 
 
145
  $remoteFile = esc_url_raw($url);
146
 
147
  /**
@@ -151,8 +161,8 @@ class OMGF_AJAX_Download_Fonts extends OMGF_AJAX
151
  continue;
152
  }
153
 
154
- $filename = basename($remoteFile);
155
- $localFile = OMGF_UPLOAD_DIR . '/' . $filename;
156
 
157
  try {
158
  $this->download_file_curl($localFile, $remoteFile);
@@ -171,7 +181,7 @@ class OMGF_AJAX_Download_Fonts extends OMGF_AJAX
171
  * If it fails, we can still fall back to the external URL and nothing breaks.
172
  */
173
  $localFileUrl = OMGF_UPLOAD_URL . '/' . $filename;
174
- $wpdb->update(
175
  OMGF_DB_TABLENAME,
176
  array(
177
  $type => $localFileUrl
@@ -185,7 +195,7 @@ class OMGF_AJAX_Download_Fonts extends OMGF_AJAX
185
  /**
186
  * After all files are downloaded, set the 'downloaded'-field to 1.
187
  */
188
- $wpdb->update(
189
  OMGF_DB_TABLENAME,
190
  array(
191
  'downloaded' => 1
@@ -241,5 +251,3 @@ class OMGF_AJAX_Download_Fonts extends OMGF_AJAX
241
  file_put_contents($localFile, file_get_contents($remoteFile));
242
  }
243
  }
244
-
245
- new OMGF_AJAX_Download_Fonts();
6
  * @url : https://daan.dev
7
  */
8
 
9
+ defined('ABSPATH') || exit;
 
 
 
 
 
10
 
11
+ class OMGF_AJAX_Download extends OMGF_AJAX
12
  {
13
  /** @var $fonts */
14
  private $fonts;
16
  /** @var $subsets */
17
  private $subsets;
18
 
19
+ /** @var QM_DB $wpdb */
20
+ private $wpdb;
21
+
22
+ /** @var OMGF_DB $db */
23
+ protected $db;
24
+
25
  /**
26
  * OMGF_Download_Fonts constructor.
27
  */
28
  public function __construct()
29
  {
30
+ global $wpdb;
31
+
32
+ $this->wpdb = $wpdb;
33
+
34
+ parent::__construct();
35
+
36
  $this->init();
37
  }
38
 
47
  * To match the current queue of fonts. We need to truncate the table first.
48
  */
49
  try {
50
+ $this->db->clean_queue();
51
  } catch (\Exception $e) {
52
  $this->throw_error($e->getCode(), $e->getMessage());
53
  }
65
  $this->save_subsets_to_db();
66
  $this->save_fonts_to_db();
67
 
68
+ $this->download();
69
  }
70
 
71
  /**
84
  */
85
  private function save_subsets_to_db()
86
  {
 
 
87
  foreach ($this->subsets as $id => $subset) {
88
  $availableSubsets = implode($subset['available'], ',');
89
+ $selectedSubsets = implode(isset($subset['selected']) ? $subset['selected'] : array(), ',');
90
 
91
+ $this->wpdb->insert(
92
  OMGF_DB_TABLENAME . '_subsets',
93
  array(
94
  'subset_font' => $id,
105
  */
106
  private function save_fonts_to_db()
107
  {
 
 
108
  foreach ($this->fonts as $id => $font) {
109
+ $urlTtf = $font['url']['ttf'] !== 'undefined' ? $font['url']['ttf'] : null;
110
+ $urlWoff = $font['url']['woff'] !== 'undefined' ? $font['url']['woff'] : null;
111
+ $urlWoffTwo = $font['url']['woff2'] !== 'undefined' ? $font['url']['woff2'] : null;
112
+ $urlEot = $font['url']['eot'] !== 'undefined' ? $font['url']['eot'] : null;
113
+
114
+ $this->wpdb->insert(
115
  OMGF_DB_TABLENAME,
116
  array(
117
  'font_id' => sanitize_text_field($id),
120
  'font_style' => sanitize_text_field($font['font-style']),
121
  'local' => sanitize_text_field($font['local']),
122
  'downloaded' => 0,
123
+ 'url_ttf' => esc_url_raw($urlTtf),
124
+ 'url_woff' => esc_url_raw($urlWoff),
125
+ 'url_woff2' => esc_url_raw($urlWoffTwo),
126
+ 'url_eot' => esc_url_raw($urlEot)
127
  )
128
  );
129
  }
130
  }
131
 
132
  /**
133
+ * Download the fonts and write them to the database.
134
  */
135
+ private function download()
136
  {
137
+ $selectedFonts = $this->db->get_total_fonts();
 
 
138
 
139
  foreach ($selectedFonts as $id => $font) {
140
  // If font is marked as downloaded. Skip it.
148
  $urls['url_eot'] = $font->url_eot;
149
 
150
  foreach ($urls as $type => $url) {
151
+ if (!$url) {
152
+ continue;
153
+ }
154
+
155
  $remoteFile = esc_url_raw($url);
156
 
157
  /**
161
  continue;
162
  }
163
 
164
+ $filename = basename($remoteFile);
165
+ $localFile = OMGF_UPLOAD_DIR . '/' . $filename;
166
 
167
  try {
168
  $this->download_file_curl($localFile, $remoteFile);
181
  * If it fails, we can still fall back to the external URL and nothing breaks.
182
  */
183
  $localFileUrl = OMGF_UPLOAD_URL . '/' . $filename;
184
+ $this->wpdb->update(
185
  OMGF_DB_TABLENAME,
186
  array(
187
  $type => $localFileUrl
195
  /**
196
  * After all files are downloaded, set the 'downloaded'-field to 1.
197
  */
198
+ $this->wpdb->update(
199
  OMGF_DB_TABLENAME,
200
  array(
201
  'downloaded' => 1
251
  file_put_contents($localFile, file_get_contents($remoteFile));
252
  }
253
  }
 
 
includes/ajax/class-generate-styles.php DELETED
@@ -1,111 +0,0 @@
1
- <?php
2
- /**
3
- * @package : OMGF
4
- * @author : Daan van den Bergh
5
- * @copyright: (c) 2019 Daan van den Bergh
6
- * @url : https://daan.dev
7
- */
8
-
9
- // Exit if accessed directly
10
- if (!defined('ABSPATH')) {
11
- exit;
12
- }
13
-
14
- require_once(dirname(dirname(__FILE__)) . '/class-ajax.php');
15
-
16
- class OMGF_AJAX_Generate_Styles extends OMGF_AJAX
17
- {
18
- /** @var array $fonts */
19
- private $fonts = [];
20
-
21
- /**
22
- * OMGF_AJAX_Generate_Styles constructor.
23
- */
24
- public function __construct()
25
- {
26
- $this->init();
27
- }
28
-
29
- /**
30
- * Generate the Stylesheet
31
- */
32
- private function init()
33
- {
34
- header("Content-type: text/css");
35
-
36
- $this->insert_promo();
37
-
38
- $selectedFonts = hwlGetTotalFonts();
39
-
40
- $this->process_fonts($selectedFonts);
41
-
42
- $fonts = implode("\n", $this->fonts);
43
- $file = OMGF_UPLOAD_DIR . '/' . OMGF_FILENAME;
44
-
45
- /**
46
- * If the file can be created and uploaded. Let's try to write it.
47
- */
48
- try {
49
- $stylesheet = fopen($file, 'w') or $this->throw_error(400, "Cannot create file {$file}");
50
- fwrite($stylesheet, $fonts);
51
- fclose($stylesheet);
52
- wp_die(__('Stylesheet was successfully generated and added to your theme\'s header.'));
53
- } catch (Exception $e) {
54
- $this->throw_error($e->getCode(), __("Stylesheet could not be generated: $e"));
55
- }
56
- }
57
-
58
- /**
59
- * Insert promo material :)
60
- *
61
- * The alignment is crooked, so it'll look nice in the stylesheet.
62
- */
63
- private function insert_promo()
64
- {
65
- $this->fonts[] = "/**
66
- * This file is automagically generated by OMGF
67
- *
68
- * @author: Daan van den Bergh
69
- * @copyright: (c) 2019 Daan van den Bergh
70
- * @url: " . OMGF_SITE_URL . "
71
- */";
72
- }
73
-
74
- /**
75
- * Prepare fonts for generation.
76
- */
77
- private function process_fonts($fonts)
78
- {
79
- $fontDisplay = OMGF_DISPLAY_OPTION;
80
-
81
- foreach ($fonts as $font) {
82
- $fontFamily = sanitize_text_field($font->font_family);
83
- $fontStyle = sanitize_text_field($font->font_style);
84
- $fontWeight = sanitize_text_field($font->font_weight);
85
- $fontUrlEot = esc_url_raw($font->url_eot);
86
- $fontUrlWoffTwo = esc_url_raw($font->url_woff2);
87
- $fontUrlWoff = esc_url_raw($font->url_woff);
88
- $fontUrlTtf = esc_url_raw($font->url_ttf);
89
- $locals = explode(',', sanitize_text_field($font->local));
90
- $fontLocal = isset($locals[0]) ? $locals[0] : $fontFamily . " " . ucfirst($fontStyle);
91
- $fontLocalDash = isset($locals[1]) ? $locals[1] : $fontFamily . "-" . ucfirst($fontStyle);
92
-
93
- /**
94
- * The alignment is crooked, so it'll look nice in the stylesheet.
95
- */
96
- $this->fonts[] = "@font-face {
97
- font-family: '$fontFamily';
98
- font-display: $fontDisplay;
99
- font-style: $fontStyle;
100
- font-weight: $fontWeight;
101
- src: url('$fontUrlEot'); /* IE9 Compatible */
102
- src: local('$fontLocal'), local('$fontLocalDash'),
103
- url('$fontUrlWoffTwo') format('woff2'), /* Super Modern Browsers */
104
- url('$fontUrlWoff') format('woff'), /* Modern Browsers */
105
- url('$fontUrlTtf') format('truetype'); /* Safari, Android, iOS */
106
- }";
107
- }
108
- }
109
- }
110
-
111
- new OMGF_AJAX_Generate_Styles();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
includes/ajax/class-generate.php ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * @package : OMGF
4
+ * @author : Daan van den Bergh
5
+ * @copyright: (c) 2019 Daan van den Bergh
6
+ * @url : https://daan.dev
7
+ */
8
+
9
+ defined('ABSPATH') || exit;
10
+
11
+ class OMGF_AJAX_Generate extends OMGF_AJAX
12
+ {
13
+ /** @var array $fonts */
14
+ private $fonts = [];
15
+
16
+ /**
17
+ * OMGF_AJAX_Generate_Styles constructor.
18
+ */
19
+ public function __construct()
20
+ {
21
+ parent::__construct();
22
+
23
+ $this->init();
24
+ }
25
+
26
+ /**
27
+ * Generate the Stylesheet
28
+ */
29
+ private function init()
30
+ {
31
+ header("Content-type: text/css");
32
+
33
+ $this->insert_promo();
34
+
35
+ $selectedFonts = $this->db->get_total_fonts();
36
+
37
+ $this->process_fonts($selectedFonts);
38
+
39
+ $fonts = implode("\n", $this->fonts);
40
+ $file = OMGF_UPLOAD_DIR . '/' . OMGF_FILENAME;
41
+
42
+ /**
43
+ * If the file can be created and uploaded. Let's try to write it.
44
+ */
45
+ try {
46
+ $stylesheet = fopen($file, 'w') or $this->throw_error(400, "Cannot create file {$file}");
47
+ fwrite($stylesheet, $fonts);
48
+ fclose($stylesheet);
49
+ wp_die(__('Stylesheet was successfully generated and added to your theme\'s header.'));
50
+ } catch (Exception $e) {
51
+ $this->throw_error($e->getCode(), __("Stylesheet could not be generated: $e"));
52
+ }
53
+ }
54
+
55
+ /**
56
+ * Insert promo material :)
57
+ *
58
+ * The alignment is crooked, so it'll look nice in the stylesheet.
59
+ */
60
+ private function insert_promo()
61
+ {
62
+ $this->fonts[] = "/**
63
+ * This file is automagically generated by OMGF
64
+ *
65
+ * @author: Daan van den Bergh
66
+ * @copyright: (c) 2019 Daan van den Bergh
67
+ * @url: " . OMGF_SITE_URL . "
68
+ */";
69
+ }
70
+
71
+ /**
72
+ * Prepare fonts for generation.
73
+ */
74
+ private function process_fonts($fonts)
75
+ {
76
+ $fontDisplay = OMGF_DISPLAY_OPTION;
77
+
78
+ $i = 1;
79
+
80
+ foreach ($fonts as $font) {
81
+ $fontUrlEot = isset($font->url_eot) ? array(0 => esc_url_raw($font->url_eot)) : array();
82
+ $fontSources = isset($font->url_woff2) ? array('woff2' => esc_url_raw($font->url_woff2)) : array();
83
+ $fontSources = $fontSources + (isset($font->url_woff) ? array('woff' => esc_url_raw($font->url_woff)) : array());
84
+ $fontSources = $fontSources + (isset($font->url_ttf) ? array('truetype' => esc_url_raw($font->url_ttf)) : array());
85
+ $locals = explode(',', sanitize_text_field($font->local));
86
+
87
+ $this->fonts[$i] = "@font-face { \n";
88
+ $this->fonts[$i] .= $this->build_property('font-family', $font->font_family);
89
+ $this->fonts[$i] .= $this->build_property('font-display', $fontDisplay);
90
+ $this->fonts[$i] .= $this->build_property('font-style', $font->font_style);
91
+ $this->fonts[$i] .= $this->build_property('font-weight', $font->font_weight);
92
+ $this->fonts[$i] .= isset($fontUrlEot) ? " src: " . $this->build_source_string($fontUrlEot) : '';
93
+ $this->fonts[$i] .= " src: " . $this->build_source_string($locals, 'local', false);
94
+ // There'll always be at least one font available, so no need to check here if $fontSources is set.
95
+ $this->fonts[$i] .= $this->build_source_string($fontSources);
96
+ $this->fonts[$i] .= "}";
97
+
98
+ $i++;
99
+ }
100
+ }
101
+
102
+ /**
103
+ * @param $property
104
+ * @param $value
105
+ *
106
+ * @return string
107
+ */
108
+ private function build_property($property, $value)
109
+ {
110
+ $value = sanitize_text_field($value);
111
+
112
+ return " $property: $value;\n";
113
+ }
114
+
115
+ /**
116
+ * @param $sources
117
+ * @param string $type
118
+ * @param bool $endSemiColon
119
+ *
120
+ * @return string
121
+ */
122
+ private function build_source_string($sources, $type = 'url', $endSemiColon = true)
123
+ {
124
+ $lastSrc = end($sources);
125
+ $source = '';
126
+
127
+ foreach ($sources as $format => $url) {
128
+ $source .= " $type('$url')" . (!is_numeric($format) ? " format('$format')" : '');
129
+
130
+ if ($url === $lastSrc && $endSemiColon) {
131
+ $source .= ";\n";
132
+ } else {
133
+ $source .= ",\n";
134
+ }
135
+ }
136
+
137
+ return $source;
138
+ }
139
+ }
includes/class-admin.php ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * @package : OMGF
4
+ * @author : Daan van den Bergh
5
+ * @copyright: (c) 2019 Daan van den Bergh
6
+ * @url : https://daan.dev
7
+ */
8
+
9
+ defined('ABSPATH') || exit;
10
+
11
+ class OMGF_Admin
12
+ {
13
+ const OMGF_ADMIN_JS_HANDLE = 'omgf-admin-js';
14
+ const OMGF_ADMIN_CSS_HANDLE = 'omgf-admin-css';
15
+
16
+ public function __construct()
17
+ {
18
+ // @formatter:off
19
+ add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_js'));
20
+ // @formatter:on
21
+ }
22
+
23
+ /**
24
+ * Enqueues the necessary JS and CSS and passes options as a JS object.
25
+ *
26
+ * @param $hook
27
+ */
28
+ public function enqueue_admin_js($hook)
29
+ {
30
+ if ($hook == 'settings_page_optimize-webfonts') {
31
+ wp_enqueue_script(self::OMGF_ADMIN_JS_HANDLE, plugin_dir_url(OMGF_PLUGIN_FILE) . 'js/hwl-admin.js', array('jquery'), OMGF_STATIC_VERSION, true);
32
+ wp_enqueue_style(self::OMGF_ADMIN_CSS_HANDLE, plugin_dir_url(OMGF_PLUGIN_FILE) . 'css/hwl-admin.css', array(), OMGF_STATIC_VERSION);
33
+
34
+ $options = array(
35
+ 'auto_detect_enabled' => OMGF_AUTO_DETECT_ENABLED,
36
+ 'detected_fonts' => get_option('omgf_detected_fonts')
37
+ );
38
+
39
+ wp_localize_script(self::OMGF_ADMIN_JS_HANDLE, 'omgf', $options);
40
+ }
41
+ }
42
+
43
+ protected function get_template($name)
44
+ {
45
+ return include OMGF_PLUGIN_DIR . 'templates/admin/block-' . $name . '.phtml';
46
+ }
47
+ }
includes/class-ajax.php CHANGED
@@ -6,8 +6,193 @@
6
  * @url : https://daan.dev
7
  */
8
 
 
 
9
  class OMGF_AJAX
10
  {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  /**
12
  * @param $code
13
  * @param $message
@@ -17,5 +202,3 @@ class OMGF_AJAX
17
  wp_send_json_error(__($message, 'host-webfonts-local'), (int) $code);
18
  }
19
  }
20
-
21
- new OMGF_AJAX();
6
  * @url : https://daan.dev
7
  */
8
 
9
+ defined('ABSPATH') || exit;
10
+
11
  class OMGF_AJAX
12
  {
13
+ protected $db;
14
+
15
+ /**
16
+ * OMGF_AJAX constructor.
17
+ */
18
+ public function __construct()
19
+ {
20
+ $this->db = new OMGF_DB();
21
+
22
+ // @formatter:off
23
+ add_action('wp_ajax_omgf_ajax_download_fonts', array($this, 'download_fonts'));
24
+ add_action('wp_ajax_omgf_ajax_generate_styles', array($this, 'generate_styles'));
25
+ add_action('wp_ajax_omgf_ajax_get_download_status', array($this, 'get_download_status'));
26
+ add_action('wp_ajax_omgf_ajax_clean_queue', array($this, 'clean_queue'));
27
+ add_action('wp_ajax_omgf_ajax_empty_dir', array($this, 'empty_directory'));
28
+ add_action('wp_ajax_omgf_ajax_search_font_subsets', array($this, 'search_font_subsets'));
29
+ add_action('wp_ajax_omgf_ajax_search_google_fonts', array($this, 'search_fonts'));
30
+ add_action('wp_ajax_omgf_ajax_auto_detect', array($this, 'auto_detect'));
31
+ // @formatter:on
32
+ }
33
+
34
+ /**
35
+ * @return OMGF_AJAX_Download
36
+ */
37
+ public function download_fonts()
38
+ {
39
+ return new OMGF_AJAX_Download();
40
+ }
41
+
42
+ /**
43
+ * @return OMGF_AJAX_Generate
44
+ */
45
+ public function generate_styles()
46
+ {
47
+ return new OMGF_AJAX_Generate();
48
+ }
49
+
50
+ /**
51
+ * Get download status from DB.
52
+ */
53
+ public function get_download_status()
54
+ {
55
+ $status = json_encode($this->db->get_download_status());
56
+
57
+ wp_die($status);
58
+ }
59
+
60
+ /**
61
+ * AJAX-wrapper for hwlCleanQueue()
62
+ */
63
+ public function clean_queue()
64
+ {
65
+ update_option(OMGF_Admin_Settings::OMGF_DETECTED_FONTS_LABEL, '');
66
+ update_option(OMGF_Admin_Settings::OMGF_AUTO_DETECTION_ENABLED_LABEL, '');
67
+
68
+ wp_die($this->db->clean_queue());
69
+ }
70
+
71
+ /**
72
+ * Empty cache directory.
73
+ *
74
+ * @return array
75
+ */
76
+ public function empty_directory()
77
+ {
78
+ update_option(OMGF_Admin_Settings::OMGF_DETECTED_FONTS_LABEL, '');
79
+ update_option(OMGF_Admin_Settings::OMGF_AUTO_DETECTION_ENABLED_LABEL, '');
80
+
81
+ return array_map('unlink', array_filter((array) glob(OMGF_UPLOAD_DIR . '/*')));
82
+ }
83
+
84
+ /**
85
+ * Search the API for the requested fonts and return the available subsets.
86
+ */
87
+ public function search_font_subsets()
88
+ {
89
+ try {
90
+ $searchQueries = explode(',', sanitize_text_field($_POST['search_query']));
91
+
92
+ foreach ($searchQueries as $searchQuery) {
93
+ $request = curl_init();
94
+ curl_setopt($request, CURLOPT_URL, OMGF_HELPER_URL . $searchQuery);
95
+ curl_setopt($request, CURLOPT_RETURNTRANSFER, 1);
96
+ $result = curl_exec($request);
97
+ curl_close($request);
98
+
99
+ $result = json_decode($result);
100
+ $response[] = array(
101
+ 'family' => $result->family,
102
+ 'id' => $result->id,
103
+ 'subsets' => $result->subsets
104
+ );
105
+ }
106
+ wp_die(json_encode($response));
107
+ } catch (\Exception $e) {
108
+ wp_die($e);
109
+ }
110
+ }
111
+
112
+ /**
113
+ * Return the available fonts for the selected subset(s) from the API.
114
+ */
115
+ public function search_fonts()
116
+ {
117
+ try {
118
+ $request = curl_init();
119
+ $searchQuery = sanitize_text_field($_POST['search_query']);
120
+ $subsets = implode(isset($_POST['search_subsets']) ? $_POST['search_subsets'] : array(), ',');
121
+
122
+ curl_setopt($request, CURLOPT_URL, OMGF_HELPER_URL . $searchQuery . '?subsets=' . $subsets);
123
+ curl_setopt($request, CURLOPT_RETURNTRANSFER, 1);
124
+
125
+ $result = curl_exec($request);
126
+ curl_close($request);
127
+
128
+ if (!empty($_POST['used_styles'])) {
129
+ $used_styles['variants'] = array_values($this->process_used_styles($_POST['used_styles'], json_decode($result)->variants));
130
+
131
+ wp_die(json_encode($used_styles));
132
+ }
133
+
134
+ wp_die($result);
135
+ } catch (\Exception $e) {
136
+ wp_die($e);
137
+ }
138
+ }
139
+
140
+ /**
141
+ * @param $usedStyles
142
+ * @param $availableStyles
143
+ *
144
+ * @return array
145
+ */
146
+ private function process_used_styles($usedStyles, $availableStyles)
147
+ {
148
+ foreach ($usedStyles as &$style) {
149
+ $fontWeight = preg_replace('/[^0-9]/', '', $style);
150
+ $fontStyle = preg_replace('/[^a-zA-Z]/', '', $style);
151
+
152
+ if ($fontStyle == 'i') {
153
+ $fontStyle = 'italic';
154
+ }
155
+
156
+ $style = $fontWeight . $fontStyle;
157
+ }
158
+
159
+ return array_filter(
160
+ $availableStyles,
161
+ function ($style) use ($usedStyles) {
162
+ $fontStyle = $style->fontWeight . ($style->fontStyle !== 'normal' ? $style->fontStyle : '');
163
+
164
+ return in_array($fontStyle, $usedStyles);
165
+ }
166
+ );
167
+ }
168
+
169
+ /**
170
+ *
171
+ */
172
+ public function auto_detect()
173
+ {
174
+ $used_fonts = json_decode(get_option(OMGF_Admin_Settings::OMGF_DETECTED_FONTS_LABEL));
175
+ $auto_detect = get_option(OMGF_Admin_Settings::OMGF_AUTO_DETECTION_ENABLED_LABEL);
176
+
177
+ if ($used_fonts && $auto_detect) {
178
+ new OMGF_AJAX_Detect($used_fonts);
179
+ }
180
+
181
+ $this->enable_auto_detect();
182
+
183
+ $url = get_permalink(get_posts()[0]->ID);
184
+
185
+ wp_die(__("Auto-detection mode enabled. Open any page on your frontend (e.g. your <a href='$url' target='_blank'>latest post</a>). After the page is fully loaded, return here and <a href='javascript:location.reload()'>click here</a> to refresh this page. Then click 'Load fonts'."));
186
+ }
187
+
188
+ /**
189
+ *
190
+ */
191
+ private function enable_auto_detect()
192
+ {
193
+ update_option(OMGF_Admin_Settings::OMGF_AUTO_DETECTION_ENABLED_LABEL, true);
194
+ }
195
+
196
  /**
197
  * @param $code
198
  * @param $message
202
  wp_send_json_error(__($message, 'host-webfonts-local'), (int) $code);
203
  }
204
  }
 
 
includes/class-db.php ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * @package : OMGF
4
+ * @author : Daan van den Bergh
5
+ * @copyright: (c) 2019 Daan van den Bergh
6
+ * @url : https://daan.dev
7
+ */
8
+
9
+ defined('ABSPATH') || exit;
10
+
11
+ class OMGF_DB
12
+ {
13
+ /** @var QM_DB $wpdb */
14
+ private $wpdb;
15
+
16
+ /**
17
+ * OMGF_DB constructor.
18
+ */
19
+ public function __construct()
20
+ {
21
+ global $wpdb;
22
+
23
+ $this->wpdb = $wpdb;
24
+ }
25
+
26
+ /**
27
+ * @return array
28
+ */
29
+ public function get_download_status()
30
+ {
31
+ return array(
32
+ "downloaded" => count($this->get_downloaded_fonts()),
33
+ "total" => count($this->get_total_fonts())
34
+ );
35
+ }
36
+
37
+ /**
38
+ * @return array|\Exception
39
+ */
40
+ public function get_downloaded_fonts()
41
+ {
42
+ try {
43
+ return $this->wpdb->get_results("SELECT * FROM " . OMGF_DB_TABLENAME . " WHERE downloaded = 1");
44
+ } catch (\Exception $e) {
45
+ return $e;
46
+ }
47
+ }
48
+
49
+ /**
50
+ * @return array|\Exception
51
+ */
52
+ public function get_total_fonts()
53
+ {
54
+ try {
55
+ return $this->wpdb->get_results("SELECT * FROM " . OMGF_DB_TABLENAME);
56
+ } catch (\Exception $e) {
57
+ return $e;
58
+ }
59
+ }
60
+
61
+ /**
62
+ * @return array|\Exception|null|object
63
+ */
64
+ public function get_subsets()
65
+ {
66
+ try {
67
+ return $this->wpdb->get_results("SELECT * FROM " . OMGF_DB_TABLENAME . "_subsets");
68
+ } catch (\Exception $e) {
69
+ return $e;
70
+ }
71
+ }
72
+
73
+ /**
74
+ * @param $family
75
+ *
76
+ * @return array|Exception|object|null
77
+ */
78
+ public function get_fonts_by_family($family)
79
+ {
80
+ try {
81
+ return $this->wpdb->get_results("SELECT * FROM " . OMGF_DB_TABLENAME . " WHERE font_family = '$family'");
82
+ } catch (\Exception $e) {
83
+ return $e;
84
+ }
85
+ }
86
+
87
+ /**
88
+ * @return Exception|void
89
+ */
90
+ public function clean_queue()
91
+ {
92
+ try {
93
+ $this->wpdb->query("TRUNCATE TABLE " . OMGF_DB_TABLENAME);
94
+ $this->wpdb->query("TRUNCATE TABLE " . OMGF_DB_TABLENAME . "_subsets");
95
+ } catch (\Exception $e) {
96
+ return $e;
97
+ }
98
+ }
99
+ }
includes/class-omgf.php ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * @package : OMGF
4
+ * @author : Daan van den Bergh
5
+ * @copyright: (c) 2019 Daan van den Bergh
6
+ * @url : https://daan.dev
7
+ */
8
+
9
+ defined('ABSPATH') || exit;
10
+
11
+ class OMGF
12
+ {
13
+ /**
14
+ * OMGF constructor.
15
+ */
16
+ public function __construct()
17
+ {
18
+ $this->define_constants();
19
+
20
+ if (is_admin()) {
21
+ $this->do_setup();
22
+ $this->do_settings();
23
+ $this->add_ajax_hooks();
24
+ }
25
+
26
+ if (!is_admin()) {
27
+ $this->do_frontend();
28
+ }
29
+
30
+ // @formatter:off
31
+ register_activation_hook(OMGF_PLUGIN_FILE, array($this, 'create_cache_dir'));
32
+ register_activation_hook(OMGF_PLUGIN_FILE, array($this, 'do_setup'));
33
+ register_deactivation_hook(OMGF_PLUGIN_FILE, array($this, 'dequeue_css_js'));
34
+ // @formatter:on
35
+ }
36
+
37
+ /**
38
+ * Define constants.
39
+ */
40
+ public function define_constants()
41
+ {
42
+ global $wpdb;
43
+
44
+ define('OMGF_SITE_URL', 'https://daan.dev');
45
+ define('OMGF_DB_TABLENAME', $wpdb->prefix . 'caos_webfonts');
46
+ define('OMGF_DB_CHARSET', $wpdb->get_charset_collate());
47
+ define('OMGF_HELPER_URL', 'https://google-webfonts-helper.herokuapp.com/api/fonts/');
48
+ define('OMGF_FILENAME', 'fonts.css');
49
+ define('OMGF_AUTO_DETECT_ENABLED', esc_attr(get_option(OMGF_Admin_Settings::OMGF_AUTO_DETECTION_ENABLED_LABEL, false)));
50
+ define('OMGF_CACHE_DIR', esc_attr(get_option('caos_webfonts_cache_dir')) ?: '/cache/omgf-webfonts');
51
+ define('OMGF_CDN_URL', esc_attr(get_option('caos_webfonts_cdn_url')));
52
+ define('OMGF_WEB_FONT_LOADER', esc_attr(get_option('omgf_web_font_loader')));
53
+ define('OMGF_REMOVE_VERSION', esc_attr(get_option('caos_webfonts_remove_version')));
54
+ define('OMGF_CURRENT_BLOG_ID', get_current_blog_id());
55
+ define('OMGF_UPLOAD_DIR', WP_CONTENT_DIR . OMGF_CACHE_DIR);
56
+ define('OMGF_UPLOAD_URL', $this->get_upload_url());
57
+ define('OMGF_DISPLAY_OPTION', esc_attr(get_option('caos_webfonts_display_option')) ?: 'auto');
58
+ define('OMGF_REMOVE_GFONTS', esc_attr(get_option('caos_webfonts_remove_gfonts')));
59
+ define('OMGF_PRELOAD', esc_attr(get_option('caos_webfonts_preload')));
60
+ }
61
+
62
+ /**
63
+ * @return OMGF_Setup
64
+ */
65
+ private function do_setup()
66
+ {
67
+ return new OMGF_Setup();
68
+ }
69
+
70
+ /**
71
+ * @return OMGF_Admin_Settings
72
+ */
73
+ private function do_settings()
74
+ {
75
+ return new OMGF_Admin_Settings();
76
+ }
77
+
78
+ /**
79
+ * @return OMGF_AJAX
80
+ */
81
+ private function add_ajax_hooks()
82
+ {
83
+ return new OMGF_AJAX();
84
+ }
85
+
86
+ /**
87
+ * @return OMGF_Frontend_Functions
88
+ */
89
+ private function do_frontend()
90
+ {
91
+ return new OMGF_Frontend_Functions();
92
+ }
93
+
94
+ /**
95
+ * Create cache dir upon plugin (re-)activation.
96
+ */
97
+ public function create_cache_dir()
98
+ {
99
+ $uploadDir = OMGF_UPLOAD_DIR;
100
+ if (!is_dir($uploadDir)) {
101
+ wp_mkdir_p($uploadDir);
102
+ }
103
+ }
104
+
105
+ /**
106
+ * Returns the configured name of WordPress' content directory.
107
+ *
108
+ * @return mixed
109
+ */
110
+ public function get_content_dir()
111
+ {
112
+ preg_match('/[^\/]+$/u', WP_CONTENT_DIR, $match);
113
+
114
+ return $match[0];
115
+ }
116
+
117
+ /**
118
+ * @return string
119
+ */
120
+ public function get_upload_url()
121
+ {
122
+ if (OMGF_CDN_URL) {
123
+ $uploadUrl = '//' . OMGF_CDN_URL . '/' . $this->get_content_dir() . OMGF_CACHE_DIR;
124
+ } else {
125
+ $uploadUrl = get_site_url(OMGF_CURRENT_BLOG_ID, $this->get_content_dir() . OMGF_CACHE_DIR);
126
+ }
127
+
128
+ return $uploadUrl;
129
+ }
130
+
131
+ /**
132
+ * Removes all static files upon plugin deactivation.
133
+ */
134
+ public function dequeue_css_js()
135
+ {
136
+ wp_dequeue_script(OMGF_Admin::OMGF_ADMIN_JS_HANDLE);
137
+ wp_dequeue_style(OMGF_Admin::OMGF_ADMIN_CSS_HANDLE);
138
+ wp_dequeue_style(OMGF_Frontend_Functions::OMGF_STYLE_HANDLE);
139
+ }
140
+ }
includes/class-setup.php ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * @package : OMGF
4
+ * @author : Daan van den Bergh
5
+ * @copyright: (c) 2019 Daan van den Bergh
6
+ * @url : https://daan.dev
7
+ */
8
+
9
+ defined('ABSPATH') || exit;
10
+
11
+ class OMGF_Setup
12
+ {
13
+ /** @var QM_DB $wpdb */
14
+ private $wpdb;
15
+
16
+ /**
17
+ * OMGF_Admin_Setup constructor.
18
+ */
19
+ public function __construct()
20
+ {
21
+ global $wpdb;
22
+
23
+ $this->wpdb = $wpdb;
24
+
25
+ $this->run_db_updates();
26
+ }
27
+
28
+ /**
29
+ * Run initial database updates.
30
+ */
31
+ public function run_db_updates()
32
+ {
33
+ $currentVersion = get_option('caos_webfonts_db_version') ?: '1.0.0';
34
+ if (version_compare($currentVersion, '1.6.1') < 0) {
35
+ $this->create_webfonts_table();
36
+ }
37
+ if (version_compare($currentVersion, '1.7.0') < 0) {
38
+ $this->create_subsets_table();
39
+ }
40
+ if (version_compare($currentVersion, OMGF_DB_VERSION) < 0) {
41
+ $this->add_local_column();
42
+ }
43
+ }
44
+
45
+ /**
46
+ * Create the table where downloaded webfonts are registered.
47
+ */
48
+ private function create_webfonts_table()
49
+ {
50
+ $sql = "CREATE TABLE IF NOT EXISTS " . OMGF_DB_TABLENAME . " (
51
+ font_id varchar(191) NOT NULL,
52
+ font_family varchar(191) NOT NULL,
53
+ font_weight mediumint(5) NOT NULL,
54
+ font_style varchar(191) NOT NULL,
55
+ downloaded tinyint(1) DEFAULT 0,
56
+ url_ttf varchar(191) NULL,
57
+ url_woff varchar(191) NULL,
58
+ url_woff2 varchar(191) NULL,
59
+ url_eot varchar(191) NULL,
60
+ UNIQUE KEY (font_id)
61
+ ) " . OMGF_DB_CHARSET . ";";
62
+ $this->wpdb->query($sql);
63
+
64
+ add_option('caos_webfonts_db_version', '1.6.1');
65
+ }
66
+
67
+ /**
68
+ * Creates the subsets table.
69
+ */
70
+ private function create_subsets_table()
71
+ {
72
+ $sql = "CREATE TABLE IF NOT EXISTS " . OMGF_DB_TABLENAME . '_subsets' . " (
73
+ subset_font varchar(32) NOT NULL,
74
+ subset_family varchar(191) NOT NULL,
75
+ available_subsets varchar(191) NOT NULL,
76
+ selected_subsets varchar(191) NOT NULL,
77
+ UNIQUE KEY (subset_font)
78
+ ) " . OMGF_DB_CHARSET . ";";
79
+ $this->wpdb->query($sql);
80
+
81
+ update_option('caos_webfonts_db_version', '1.7.0');
82
+ }
83
+
84
+ /**
85
+ * Adds 'local' column.
86
+ */
87
+ private function add_local_column()
88
+ {
89
+ $sql = "ALTER TABLE " . OMGF_DB_TABLENAME . " " .
90
+ "ADD COLUMN local varchar(128) AFTER font_style;";
91
+ $this->wpdb->query($sql);
92
+
93
+ update_option('caos_webfonts_db_version', '1.8.3');
94
+ }
95
+ }
includes/frontend/class-functions.php ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * @package : OMGF
4
+ * @author : Daan van den Bergh
5
+ * @copyright: (c) 2019 Daan van den Bergh
6
+ * @url : https://daan.dev
7
+ */
8
+
9
+ defined('ABSPATH') || exit;
10
+
11
+ class OMGF_Frontend_Functions
12
+ {
13
+ const OMGF_STYLE_HANDLE = 'omgf-fonts';
14
+
15
+ /**
16
+ * OMGF_Frontend_Functions constructor.
17
+ */
18
+ public function __construct()
19
+ {
20
+ // @formatter:off
21
+ add_action('wp_enqueue_scripts', array($this, 'enqueue_stylesheet'), PHP_INT_MAX);
22
+ add_action('wp_print_styles', array($this, 'is_remove_google_fonts_enabled'), 100);
23
+
24
+ if (OMGF_AUTO_DETECT_ENABLED) {
25
+ add_action('wp_enqueue_scripts', array($this, 'auto_detect_fonts'), PHP_INT_MAX);
26
+ }
27
+
28
+ if (!OMGF_WEB_FONT_LOADER) {
29
+ add_action('init', array($this, 'is_preload_enabled'));
30
+ }
31
+ // @formatter:on
32
+ }
33
+
34
+ /**
35
+ * Once the stylesheet is generated. We can enqueue it.
36
+ */
37
+ public function enqueue_stylesheet()
38
+ {
39
+ if (OMGF_WEB_FONT_LOADER) {
40
+ $this->get_template('web-font-loader');
41
+ } else {
42
+ wp_enqueue_style(self::OMGF_STYLE_HANDLE, OMGF_UPLOAD_URL . '/' . OMGF_FILENAME, array(), (OMGF_REMOVE_VERSION ? null : OMGF_STATIC_VERSION));
43
+ }
44
+ }
45
+
46
+ /**
47
+ * @param $name
48
+ */
49
+ public function get_template($name)
50
+ {
51
+ include OMGF_PLUGIN_DIR . 'templates/frontend-' . $name . '.phtml';
52
+ }
53
+
54
+ /**
55
+ * Check if the Remove Google Fonts option is enabled.
56
+ */
57
+ public function is_remove_google_fonts_enabled()
58
+ {
59
+ if (OMGF_REMOVE_GFONTS == 'on' && !is_admin()) {
60
+ // @formatter:off
61
+ add_action('wp_print_styles', array($this, 'remove_google_fonts'), PHP_INT_MAX);
62
+ // Theme: Enfold
63
+ add_filter('avf_output_google_webfonts_script', function() { return false; });
64
+ // @formatter:on
65
+ }
66
+ }
67
+
68
+ /**
69
+ * Check if the Preload option is enabled.
70
+ */
71
+ public function is_preload_enabled()
72
+ {
73
+ if (OMGF_PRELOAD == 'on') {
74
+ // @formatter:off
75
+ add_action('wp_head', array($this, 'add_link_preload'), 1);
76
+ // @formatter:on
77
+ }
78
+ }
79
+
80
+ /**
81
+ * Automatically dequeues any stylesheets loaded from fonts.gstatic.com or
82
+ * fonts.googleapis.com. Also checks for stylesheets dependant on Google Fonts and
83
+ * re-enqueues and registers them.
84
+ */
85
+ public function remove_google_fonts()
86
+ {
87
+ global $wp_styles;
88
+
89
+ $registered = $wp_styles->registered;
90
+
91
+ $fonts = $this->detect_registered_google_fonts($registered);
92
+
93
+ $dependencies = array_filter(
94
+ $registered, function ($contents) use ($fonts) {
95
+ return !empty(array_intersect(array_keys($fonts), $contents->deps));
96
+ }
97
+ );
98
+
99
+ foreach ($fonts as $font) {
100
+ wp_deregister_style($font->handle);
101
+ wp_dequeue_style($font->handle);
102
+ }
103
+
104
+ foreach ($dependencies as $dependency) {
105
+ wp_register_style('omgf-dep-' . $dependency->handle, $dependency->src);
106
+ wp_enqueue_style('omgf-dep-' . $dependency->handle, $dependency->src);
107
+ }
108
+ }
109
+
110
+ private function detect_registered_google_fonts($registered_styles)
111
+ {
112
+ return array_filter(
113
+ $registered_styles,
114
+ function ($contents) {
115
+ return strpos($contents->src, 'fonts.googleapis.com') !== false
116
+ || strpos($contents->src, 'fonts.gstatic.com') !== false;
117
+ }
118
+ );
119
+ }
120
+
121
+ /**
122
+ * Prioritize the loading of fonts by adding a resource hint to the document head.
123
+ *
124
+ * Does not work with Web Font Loader enabled.
125
+ */
126
+ public function add_link_preload()
127
+ {
128
+ global $wp_styles;
129
+
130
+ $style = $wp_styles->registered[self::OMGF_STYLE_HANDLE];
131
+
132
+ /** Do not add 'preload' if Minification plugins are enabled. */
133
+ if ($style) {
134
+ $source = $style->src . ($style->ver ? "?ver={$style->ver}" : "");
135
+ echo "<link rel='preload' href='{$source}' as='style' />\n";
136
+ }
137
+ }
138
+
139
+ /**
140
+ * Saves the used Google Fonts in the database, so it can be used by auto-detection.
141
+ */
142
+ public function auto_detect_fonts()
143
+ {
144
+ global $wp_styles;
145
+
146
+ $registered = $wp_styles->registered;
147
+
148
+ $fonts = $this->detect_registered_google_fonts($registered);
149
+
150
+ foreach ($fonts as $font) {
151
+ $google_fonts_src[] = $font->src;
152
+ }
153
+
154
+ update_option(OMGF_Admin_Settings::OMGF_DETECTED_FONTS_LABEL, json_encode($google_fonts_src));
155
+ }
156
+ }
js/hwl-admin.js CHANGED
@@ -10,8 +10,8 @@
10
  */
11
  function hwlClickSearch()
12
  {
13
- let input = jQuery('#search-field')
14
- searchQuery = input.val().replace(/\s/g, '-').toLowerCase()
15
  hwlSearchFontSubsets(searchQuery)
16
  }
17
 
@@ -29,7 +29,7 @@ function hwlSearchFontSubsets(queriedFonts)
29
  type: 'POST',
30
  url: ajaxurl,
31
  data: {
32
- action: 'hwlAjaxSearchFontSubsets',
33
  search_query: queriedFonts
34
  },
35
  dataType: 'json',
@@ -44,6 +44,47 @@ function hwlSearchFontSubsets(queriedFonts)
44
  })
45
  }
46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  /**
48
  * Print available subsets
49
  *
@@ -51,31 +92,50 @@ function hwlSearchFontSubsets(queriedFonts)
51
  */
52
  function hwlRenderAvailableSubsets(response)
53
  {
54
- let data = response['responseJSON'];
55
- dataLength = data.length;
 
 
 
 
 
 
 
 
 
 
56
 
57
- for (let ii = 0; ii < dataLength; ii++) {
58
- subsets = data[ii]['subsets']
59
- family = data[ii]['family'];
60
- id = data[ii]['id'];
61
  length = subsets.length;
62
  renderedSubsets = [];
63
 
64
  for (let iii = 0; iii < length; iii++) {
65
- renderedSubsets[iii] = `<td><label><input name="${id}" value="${subsets[iii]}" type="checkbox" onclick="hwlGenerateSearchQuery('${id}')" />${subsets[iii]}</label></td>`;
66
  }
67
 
68
  jQuery('#hwl-subsets').append('<tr valign="top" id="' + id + '"><td><input type="text" class="hwl-subset-font-family" value="' + family + '" readonly/></td>' + renderedSubsets + '</tr>');
69
  jQuery('#hwl-results').append("<tbody id='" + 'hwl-section-' + id + "'></tbody>");
70
  }
 
 
 
 
 
 
 
 
 
 
 
 
71
  }
72
 
73
  /**
74
  * Generate search query for selected subsets
75
  *
76
  * @param id
 
77
  */
78
- function hwlGenerateSearchQuery(id)
79
  {
80
  let subsets = [];
81
  checked = jQuery("input[name='" + id + "']:checked");
@@ -84,8 +144,8 @@ function hwlGenerateSearchQuery(id)
84
  subsets.push(jQuery(this).val());
85
  });
86
 
87
- subsets.join()
88
- hwlSearchGoogleFonts(id, subsets);
89
  }
90
 
91
  /**
@@ -93,18 +153,20 @@ function hwlGenerateSearchQuery(id)
93
  *
94
  * @param id
95
  * @param subsets
 
96
  */
97
- function hwlSearchGoogleFonts(id, subsets)
98
  {
99
- let loadingDiv = jQuery('#hwl-warning .loading')
100
- let errorDiv = jQuery('#hwl-warning .error')
101
  jQuery.ajax({
102
  type: 'POST',
103
  url: ajaxurl,
104
  data: {
105
- action: 'hwlAjaxSearchGoogleFonts',
106
  search_query: id,
107
- search_subsets: subsets
 
108
  },
109
  dataType: 'json',
110
  beforeSend: function() {
@@ -114,12 +176,12 @@ function hwlSearchGoogleFonts(id, subsets)
114
  errorDiv.show()
115
  },
116
  complete: function(response) {
117
- loadingDiv.hide()
118
- errorDiv.hide()
119
  if(response['responseText'] !== 'Not found') {
120
- hwlRenderAvailableFonts(response)
121
  } else {
122
- errorDiv.show()
123
  }
124
  }
125
  })
@@ -132,17 +194,17 @@ function hwlSearchGoogleFonts(id, subsets)
132
  */
133
  function hwlRenderAvailableFonts(results)
134
  {
135
- let response = JSON.parse(results['responseText'])
136
- variants = response['variants']
137
- length = variants.length
138
- renderedFonts = []
139
  for(iii = 0; iii < length; iii++) {
140
- fontFamily = variants[iii].fontFamily.replace(/'/g, '')
141
- fontId = variants[iii].id
142
- font = fontFamily.replace(/\s+/g, '-').toLowerCase() + '-' + variants[iii].id
143
- fontWeight = variants[iii].fontWeight
144
- fontStyle = variants[iii].fontStyle
145
- fontLocal = variants[iii].local
146
  renderedFonts[iii] = `<tr id="row-${font}" valign="top">
147
  <td>
148
  <input readonly type="text" value="${fontFamily}" name="caos_webfonts_array][${font}][font-family]" />
@@ -189,13 +251,13 @@ function hwlGatherSelectedSubsets()
189
  jQuery.each(checked, function() {
190
  selectedSubsets.push(jQuery(this).val());
191
  });
192
- selectedSubsets.join()
193
 
194
  availableSubsets = [];
195
  jQuery.each(checkboxes, function() {
196
  availableSubsets.push(jQuery(this).val());
197
  });
198
- availableSubsets.join()
199
 
200
  family = jQuery(this).find('.hwl-subset-font-family').val();
201
 
@@ -223,7 +285,7 @@ function hwlDownloadFonts()
223
  type: 'POST',
224
  url: ajaxurl,
225
  data: {
226
- action: 'hwlAjaxDownloadFonts',
227
  subsets: hwlSubsets,
228
  fonts: hwlFonts,
229
  },
@@ -267,7 +329,7 @@ function hwlGetDownloadStatus()
267
  type: 'POST',
268
  url: ajaxurl,
269
  data: {
270
- action: 'hwlAjaxGetDownloadStatus'
271
  },
272
  dataType: 'text json',
273
  success: function(response) {
@@ -304,7 +366,7 @@ function hwlGenerateStylesheet()
304
  type: 'POST',
305
  url: ajaxurl,
306
  data: {
307
- action: 'hwlAjaxGenerateStyles',
308
  selected_fonts: hwlFonts
309
  },
310
  beforeSend: function() {
@@ -320,7 +382,7 @@ function hwlGenerateStylesheet()
320
  hwlScrollTop();
321
  jQuery('#hwl-admin-notices').append(
322
  `<div class="notice notice-error is-dismissible">
323
- <p>The stylesheet could not be created: ${response}</p>
324
  </div>`
325
  );
326
  hwlUpdateInputValue(generateButton, 'Generate Stylesheet');
@@ -350,13 +412,13 @@ function hwlEmptyDir()
350
  type: 'POST',
351
  url: ajaxurl,
352
  data: {
353
- action: 'hwlAjaxEmptyDir'
354
  },
355
  success: function() {
356
- hwlCleanQueue()
357
  hwlUpdateStatusBar(0)
358
  }
359
- })
360
  }
361
 
362
  /**
@@ -368,7 +430,7 @@ function hwlCleanQueue()
368
  type: 'POST',
369
  url: ajaxurl,
370
  data: {
371
- action: 'hwlAjaxCleanQueue'
372
  },
373
  success: function() {
374
  jQuery('.caos-status-progress-percentage').html('0%')
@@ -394,14 +456,14 @@ function hwlScrollTop()
394
  */
395
  function hwlSerializeArray(data)
396
  {
397
- let result = []
398
  data.each(function() {
399
- fields = {}
400
  jQuery.each(jQuery(this).serializeArray(), function() {
401
  fields[this.name] = this.value
402
- })
403
  result.push(fields)
404
- })
405
  return result
406
  }
407
 
@@ -412,5 +474,16 @@ function hwlSerializeArray(data)
412
  */
413
  function hwlRemoveRow(rowId)
414
  {
415
- jQuery('#' + rowId).remove()
416
  }
 
 
 
 
 
 
 
 
 
 
 
10
  */
11
  function hwlClickSearch()
12
  {
13
+ let input = jQuery('#search-field');
14
+ searchQuery = input.val().replace(/\s/g, '-').toLowerCase();
15
  hwlSearchFontSubsets(searchQuery)
16
  }
17
 
29
  type: 'POST',
30
  url: ajaxurl,
31
  data: {
32
+ action: 'omgf_ajax_search_font_subsets',
33
  search_query: queriedFonts
34
  },
35
  dataType: 'json',
44
  })
45
  }
46
 
47
+ function hwlAutoDetectFonts()
48
+ {
49
+ let detectButton = jQuery('#detect-btn');
50
+
51
+ jQuery.ajax({
52
+ type: 'POST',
53
+ url: ajaxurl,
54
+ data: {
55
+ action: 'omgf_ajax_auto_detect'
56
+ },
57
+ dataType: 'json',
58
+ beforeSend: function() {
59
+ if (omgf.auto_detect_enabled === '' && omgf.detected_fonts === '') {
60
+ hwlCleanQueue();
61
+ }
62
+ },
63
+ complete: function(response) {
64
+ if (omgf.auto_detect_enabled === '' && omgf.detected_fonts === '') {
65
+ hwlScrollTop();
66
+ jQuery('#hwl-admin-notices').append("<div class='notice notice-success is-dismissible'><p>" + response['responseText'] + "</p></div>");
67
+ hwlUpdateInputValue(detectButton, 'Enabled', '0 38px 1px');
68
+ } else {
69
+ try {
70
+ hwlUpdateInputValue(detectButton, 'Auto-detect', '0 36px 1px');
71
+ hwlRenderAvailableSubsets(response);
72
+ } catch(error) {
73
+ hwlScrollTop();
74
+ jQuery('#hwl-admin-notices').append("<div class='notice notice-success is-dismissible'><p>Oops! Something went wrong. " + error + ". Refresh the page and try again. If all else fails, click 'Clean Queue' and start over.");
75
+ }
76
+ }
77
+ }
78
+ })
79
+ }
80
+
81
+ /**
82
+ * Run this after refresh when both statements return true.
83
+ */
84
+ if (omgf.auto_detect_enabled !== '' && omgf.detected_fonts !== '') {
85
+ hwlAutoDetectFonts();
86
+ }
87
+
88
  /**
89
  * Print available subsets
90
  *
92
  */
93
  function hwlRenderAvailableSubsets(response)
94
  {
95
+ let data = response['responseJSON'];
96
+ let subsetArray = data['subsets'] === undefined ? data : data['subsets'];
97
+
98
+ for (let ii = 0; ii < subsetArray.length; ii++) {
99
+ subsets = subsetArray[ii]['subsets'];
100
+ family = subsetArray[ii]['family'];
101
+ id = subsetArray[ii]['id'];
102
+ usedStyles = subsetArray[ii]['used_styles'];
103
+
104
+ if (subsets === null) {
105
+ subsets = ['latin'];
106
+ }
107
 
 
 
 
 
108
  length = subsets.length;
109
  renderedSubsets = [];
110
 
111
  for (let iii = 0; iii < length; iii++) {
112
+ renderedSubsets[iii] = `<td><label><input name="${id}" value="${subsets[iii]}" type="checkbox" onclick='hwlGenerateSearchQuery("${id}", ${JSON.stringify(usedStyles)})' />${subsets[iii]}</label></td>`;
113
  }
114
 
115
  jQuery('#hwl-subsets').append('<tr valign="top" id="' + id + '"><td><input type="text" class="hwl-subset-font-family" value="' + family + '" readonly/></td>' + renderedSubsets + '</tr>');
116
  jQuery('#hwl-results').append("<tbody id='" + 'hwl-section-' + id + "'></tbody>");
117
  }
118
+
119
+ if (data['auto-detect'] === true) {
120
+ jQuery('#hwl-subsets input[type="checkbox"]').each(function() {
121
+ /**
122
+ * These fonts are used by WP Admin. But might be used by front-end as well.
123
+ * That's why we do return them, but do not trigger a search by default.
124
+ */
125
+ if (this.getAttribute('name') !== 'open-sans' && this.getAttribute('name') !== 'noto-serif') {
126
+ this.click();
127
+ }
128
+ });
129
+ }
130
  }
131
 
132
  /**
133
  * Generate search query for selected subsets
134
  *
135
  * @param id
136
+ * @param usedStyles
137
  */
138
+ function hwlGenerateSearchQuery(id, usedStyles = null)
139
  {
140
  let subsets = [];
141
  checked = jQuery("input[name='" + id + "']:checked");
144
  subsets.push(jQuery(this).val());
145
  });
146
 
147
+ subsets.join();
148
+ hwlSearchGoogleFonts(id, subsets, usedStyles);
149
  }
150
 
151
  /**
153
  *
154
  * @param id
155
  * @param subsets
156
+ * @param usedStyles
157
  */
158
+ function hwlSearchGoogleFonts(id, subsets, usedStyles = null)
159
  {
160
+ let loadingDiv = jQuery('#hwl-warning .loading');
161
+ let errorDiv = jQuery('#hwl-warning .error');
162
  jQuery.ajax({
163
  type: 'POST',
164
  url: ajaxurl,
165
  data: {
166
+ action: 'omgf_ajax_search_google_fonts',
167
  search_query: id,
168
+ search_subsets: subsets,
169
+ used_styles: usedStyles
170
  },
171
  dataType: 'json',
172
  beforeSend: function() {
176
  errorDiv.show()
177
  },
178
  complete: function(response) {
179
+ loadingDiv.hide();
180
+ errorDiv.hide();
181
  if(response['responseText'] !== 'Not found') {
182
+ hwlRenderAvailableFonts(response);
183
  } else {
184
+ errorDiv.show();
185
  }
186
  }
187
  })
194
  */
195
  function hwlRenderAvailableFonts(results)
196
  {
197
+ let response = JSON.parse(results['responseText']);
198
+ variants = response['variants'];
199
+ length = variants.length;
200
+ renderedFonts = [];
201
  for(iii = 0; iii < length; iii++) {
202
+ fontFamily = variants[iii].fontFamily.replace(/'/g, '');
203
+ fontId = variants[iii].id;
204
+ font = fontFamily.replace(/\s+/g, '-').toLowerCase() + '-' + variants[iii].id;
205
+ fontWeight = variants[iii].fontWeight;
206
+ fontStyle = variants[iii].fontStyle;
207
+ fontLocal = variants[iii].local;
208
  renderedFonts[iii] = `<tr id="row-${font}" valign="top">
209
  <td>
210
  <input readonly type="text" value="${fontFamily}" name="caos_webfonts_array][${font}][font-family]" />
251
  jQuery.each(checked, function() {
252
  selectedSubsets.push(jQuery(this).val());
253
  });
254
+ selectedSubsets.join();
255
 
256
  availableSubsets = [];
257
  jQuery.each(checkboxes, function() {
258
  availableSubsets.push(jQuery(this).val());
259
  });
260
+ availableSubsets.join();
261
 
262
  family = jQuery(this).find('.hwl-subset-font-family').val();
263
 
285
  type: 'POST',
286
  url: ajaxurl,
287
  data: {
288
+ action: 'omgf_ajax_download_fonts',
289
  subsets: hwlSubsets,
290
  fonts: hwlFonts,
291
  },
329
  type: 'POST',
330
  url: ajaxurl,
331
  data: {
332
+ action: 'omgf_ajax_get_download_status'
333
  },
334
  dataType: 'text json',
335
  success: function(response) {
366
  type: 'POST',
367
  url: ajaxurl,
368
  data: {
369
+ action: 'omgf_ajax_generate_styles',
370
  selected_fonts: hwlFonts
371
  },
372
  beforeSend: function() {
382
  hwlScrollTop();
383
  jQuery('#hwl-admin-notices').append(
384
  `<div class="notice notice-error is-dismissible">
385
+ <p>The stylesheet could not be created: ${response.responseText}</p>
386
  </div>`
387
  );
388
  hwlUpdateInputValue(generateButton, 'Generate Stylesheet');
412
  type: 'POST',
413
  url: ajaxurl,
414
  data: {
415
+ action: 'omgf_ajax_empty_dir'
416
  },
417
  success: function() {
418
+ hwlCleanQueue();
419
  hwlUpdateStatusBar(0)
420
  }
421
+ });
422
  }
423
 
424
  /**
430
  type: 'POST',
431
  url: ajaxurl,
432
  data: {
433
+ action: 'omgf_ajax_clean_queue'
434
  },
435
  success: function() {
436
  jQuery('.caos-status-progress-percentage').html('0%')
456
  */
457
  function hwlSerializeArray(data)
458
  {
459
+ let result = [];
460
  data.each(function() {
461
+ fields = {};
462
  jQuery.each(jQuery(this).serializeArray(), function() {
463
  fields[this.name] = this.value
464
+ });
465
  result.push(fields)
466
+ });
467
  return result
468
  }
469
 
474
  */
475
  function hwlRemoveRow(rowId)
476
  {
477
+ jQuery('#' + rowId).remove();
478
  }
479
+
480
+
481
+ jQuery('#omgf_web_font_loader, #caos_webfonts_preload').click(function () {
482
+ if (this.className === 'omgf_web_font_loader' && this.checked === true) {
483
+ jQuery('#caos_webfonts_preload').attr('checked', false);
484
+ }
485
+
486
+ if (this.className === 'caos_webfonts_preload' && this.checked === true) {
487
+ jQuery('#omgf_web_font_loader').attr('checked', false);
488
+ }
489
+ });
{includes → js}/libraries/webfont.js RENAMED
File without changes
readme.txt CHANGED
@@ -4,7 +4,7 @@ Donate link: https://daan.dev/donate/
4
  Tags: google, fonts, host, save, local, locally, webfonts, update, minimize, external, requests, leverage, browser, cache
5
  Requires at least: 4.6
6
  Tested up to: 5.3
7
- Stable tag: 2.0.8
8
  License: GPLv2 or later
9
  License URI: http://www.gnu.org/licenses/gpl-2.0.html
10
 
@@ -21,8 +21,9 @@ That's it. You're done!
21
  This will *decrease your pageload times*, *leverage browser cache*, *minimize DNS requests* and effectively bring you a perfect score on *Pagespeed Insights* and *Pingdom*, without taking toll on the performance of your webserver.
22
 
23
  = Features =
24
- - Easily find and download your fonts in multiple subsets,
25
- - Generate a stylesheet, which is automatically added to your header using WordPress' wp_head()-function,
 
26
  - Change the caching path (where the fonts and stylesheet are saved) for increased compatibility with Multisite environments and Caching- and Security-plugins, such as WP Super Cache, Autoptimize and WordFence,
27
  - Serve your fonts from your CDN,
28
  - Enable Typekit's [Web Font Loader](https://github.com/typekit/webfontloader) to load your fonts asynchronously and further increase your Pagespeed Insights score (!),
@@ -114,6 +115,27 @@ N/A
114
 
115
  == Changelog ==
116
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
  = 2.0.8 =
118
  Fixed 400-error when re-downloading fonts. Added compatibility for Enfold-theme.
119
 
4
  Tags: google, fonts, host, save, local, locally, webfonts, update, minimize, external, requests, leverage, browser, cache
5
  Requires at least: 4.6
6
  Tested up to: 5.3
7
+ Stable tag: 2.1.6
8
  License: GPLv2 or later
9
  License URI: http://www.gnu.org/licenses/gpl-2.0.html
10
 
21
  This will *decrease your pageload times*, *leverage browser cache*, *minimize DNS requests* and effectively bring you a perfect score on *Pagespeed Insights* and *Pingdom*, without taking toll on the performance of your webserver.
22
 
23
  = Features =
24
+ - *Automatically detect* which Google Fonts your theme is using or,
25
+ - Easily find additional fonts in any/multiple subsets,
26
+ - Download them and generate a stylesheet, which is automatically added to your header using WordPress' wp_head()-function,
27
  - Change the caching path (where the fonts and stylesheet are saved) for increased compatibility with Multisite environments and Caching- and Security-plugins, such as WP Super Cache, Autoptimize and WordFence,
28
  - Serve your fonts from your CDN,
29
  - Enable Typekit's [Web Font Loader](https://github.com/typekit/webfontloader) to load your fonts asynchronously and further increase your Pagespeed Insights score (!),
115
 
116
  == Changelog ==
117
 
118
+ = 2.1.6 =
119
+ Fixed bug where tables weren't created upon installation. Moved logic to plugin activation, instead of 'plugins_loaded'.
120
+
121
+ = 2.1.5 =
122
+ No new features or bugfixes. Just a re-arrangement of the support tab to be more in line with the new feature set.
123
+
124
+ = 2.1.4 =
125
+ Code clean-up in Generate-script. Improved error-handling.
126
+
127
+ = 2.1.3 =
128
+ Added error handling for when certain URLs return 'undefined' from Google Fonts API. Auto-detect now loads detected fonts immediately after settings page refresh. Code optimizations.
129
+
130
+ = 2.1.2 =
131
+ Added compatibility for (more efficient) chained requests to Google Fonts (separated by a pipe (|)) to the Auto-detect feature. Some themes (like Twenty Sixteen) use this feature.
132
+
133
+ = 2.1.1 =
134
+ Bugfix where Auto-detect would retrieve the fonts used by WordPress' Administrator area, instead of the frontend.
135
+
136
+ = 2.1.0 =
137
+ Complete overhaul of code. Major performance upgrades. Added Auto-detect feature.
138
+
139
  = 2.0.8 =
140
  Fixed 400-error when re-downloading fonts. Added compatibility for Enfold-theme.
141
 
includes/templates/settings-basic-settings.phtml → templates/admin/block-basic-settings.phtml RENAMED
@@ -1,36 +1,36 @@
1
  <?php
2
  /**
3
- * @package: OMGF
4
- * @author: Daan van den Bergh
5
  * @copyright: (c) 2019 Daan van den Bergh
6
- * @url: https://daan.dev
7
  */
8
 
9
  // Exit if accessed directly
10
- if (!defined( 'ABSPATH')) exit;
 
 
 
11
  ?>
12
  <div class="">
13
- <h3><?php _e('Basic Settings', 'host-webfonts-local'); ?></h3>
14
- <p class="description">
15
- <?php _e('Do not forget to re-generate the stylesheet after changing settings.', 'host-webfonts-local'); ?>
16
- </p>
17
  <p class="description">
18
  <?php _e('* Empty Cache Directory, Download Fonts and Generate Stylesheet after changing this setting.', 'host-webfonts-local'); ?>
19
  </p>
20
- <table class="form-table">
21
- <tr valign="top">
22
- <th scope="row">
23
  <label for="caos_webfonts_cache_dir">
24
  <?php _e('Save webfonts to...', 'host-webfonts-local'); ?> *
25
  </label>
26
  </th>
27
- <td>
28
- <input id="caos_webfonts_cache_dir" class="caos_webfonts_cache_dir" type="text" name="caos_webfonts_cache_dir" placeholder="<?= __('e.g. /cache/omgf-webfonts', 'host-webfonts-local'); ?>" value="<?= OMGF_CACHE_DIR; ?>" />
29
- <p class="description">
30
- <?php _e("Changes the path where webfonts are cached inside WordPress' content directory (usually <code>wp-content</code>). If you're using Multisite, give each site a unique cache directory path. Defaults to <code>/cache/caos-webfonts</code>.", 'host-webfonts-local'); ?>
31
- </p>
32
- </td>
33
- </tr>
34
  <tr valign="top">
35
  <th scope="row">
36
  <label for="caos_webfonts_cdn_url">
@@ -38,7 +38,7 @@ if (!defined( 'ABSPATH')) exit;
38
  </label>
39
  </th>
40
  <td>
41
- <input id="caos_webfonts_cdn_url" class="caos_webfonts_cdn_url" type="text" name="caos_webfonts_cdn_url" placeholder="<?= __('e.g. cdn.mydomain.com', 'host-webfonts-local'); ?>" value="<?= OMGF_CDN_URL; ?>" />
42
  <p class="description">
43
  <?php _e("Are you using a CDN? Then enter the URL here.", 'host-webfonts-local'); ?>
44
  </p>
@@ -77,15 +77,14 @@ if (!defined( 'ABSPATH')) exit;
77
  </label>
78
  </th>
79
  <td>
80
- <?php $fontDisplay = hwlFontDisplayOptions(); ?>
81
- <select id="caos_webfonts_display_option" name="caos_webfonts_display_option">
82
- <?php foreach ($fontDisplay as $label => $value): ?>
83
  <option value="<?= $value; ?>" <?= $value == OMGF_DISPLAY_OPTION ? 'selected' : ''; ?>><?php _e($label, 'host-webfonts-local'); ?></option>
84
- <?php endforeach; ?>
85
- </select>
86
- <br/>
87
  <p class="description">
88
- <?php _e('Select which font-display strategy to use. Defaults to \'Auto\'.', 'host-webfonts-local'); ?>
89
  <a target="_blank" href="https://developers.google.com/web/updates/2016/02/font-display"><?php _e('Read more', 'host-webfonts-local'); ?></a>
90
  </p>
91
  </td>
@@ -99,7 +98,7 @@ if (!defined( 'ABSPATH')) exit;
99
  <td>
100
  <input class="caos_webfonts_remove_gfonts" id="caos_webfonts_remove_gfonts" type="checkbox" name="caos_webfonts_remove_gfonts" <?= OMGF_REMOVE_GFONTS == 'on' ? 'checked = "checked"' : ''; ?> />
101
  <p class="description">
102
- <?= sprintf(__('Enabling this option will attempt to remove any externally hosted Google Fonts-stylesheets from your WordPress-blog. If it doesn\'t work for you, click %shere%s for a more comprehensive guide.', 'host-webfonts-local'), '<a target="_blank" href="' . OMGF_SITE_URL . '/how-to/remove-google-fonts-wordpress">', '</a>'); ?>
103
  </p>
104
  </td>
105
  </tr>
@@ -112,9 +111,10 @@ if (!defined( 'ABSPATH')) exit;
112
  <td>
113
  <input class="caos_webfonts_preload" id="caos_webfonts_preload" type="checkbox" name="caos_webfonts_preload" <?= OMGF_PRELOAD == 'on' ? 'checked = "checked"' : ''; ?> />
114
  <p class="description">
115
- <?php _e('Leave this disabled if you\'re using a CSS minification plugin, such as Autoptimize or W3 Total Cache.', 'host-webfonts-local'); ?> <a target="_blank" href="https://developers.google.com/web/fundamentals/performance/resource-prioritization#preload"><?php _e('Read more', 'host-webfonts-local'); ?></a>
 
116
  </p>
117
  </td>
118
  </tr>
119
- </table>
120
  </div>
1
  <?php
2
  /**
3
+ * @package : OMGF
4
+ * @author : Daan van den Bergh
5
  * @copyright: (c) 2019 Daan van den Bergh
6
+ * @url : https://daan.dev
7
  */
8
 
9
  // Exit if accessed directly
10
+ if (!defined('ABSPATH')) {
11
+ exit;
12
+ }
13
+ $utmTags = '?utm_source=omgf&utm_medium=plugin&utm_campaign=settings';
14
  ?>
15
  <div class="">
16
+ <h3><?php _e('Basic Settings', 'host-webfonts-local'); ?></h3>
 
 
 
17
  <p class="description">
18
  <?php _e('* Empty Cache Directory, Download Fonts and Generate Stylesheet after changing this setting.', 'host-webfonts-local'); ?>
19
  </p>
20
+ <table class="form-table">
21
+ <tr valign="top">
22
+ <th scope="row">
23
  <label for="caos_webfonts_cache_dir">
24
  <?php _e('Save webfonts to...', 'host-webfonts-local'); ?> *
25
  </label>
26
  </th>
27
+ <td>
28
+ <input id="caos_webfonts_cache_dir" class="caos_webfonts_cache_dir" type="text" name="caos_webfonts_cache_dir" placeholder="<?= __('e.g. /cache/omgf-webfonts', 'host-webfonts-local'); ?>" value="<?= OMGF_CACHE_DIR; ?>"/>
29
+ <p class="description">
30
+ <?php _e("Changes the path where webfonts are cached inside WordPress' content directory (usually <code>wp-content</code>). If you're using Multisite, give each site a unique cache directory path. Defaults to <code>/cache/caos-webfonts</code>.", 'host-webfonts-local'); ?>
31
+ </p>
32
+ </td>
33
+ </tr>
34
  <tr valign="top">
35
  <th scope="row">
36
  <label for="caos_webfonts_cdn_url">
38
  </label>
39
  </th>
40
  <td>
41
+ <input id="caos_webfonts_cdn_url" class="caos_webfonts_cdn_url" type="text" name="caos_webfonts_cdn_url" placeholder="<?= __('e.g. cdn.mydomain.com', 'host-webfonts-local'); ?>" value="<?= OMGF_CDN_URL; ?>"/>
42
  <p class="description">
43
  <?php _e("Are you using a CDN? Then enter the URL here.", 'host-webfonts-local'); ?>
44
  </p>
77
  </label>
78
  </th>
79
  <td>
80
+ <select id="caos_webfonts_display_option" name="caos_webfonts_display_option">
81
+ <?php foreach (OMGF_Admin_Settings::OMGF_FONT_DISPLAY_OPTIONS as $label => $value): ?>
 
82
  <option value="<?= $value; ?>" <?= $value == OMGF_DISPLAY_OPTION ? 'selected' : ''; ?>><?php _e($label, 'host-webfonts-local'); ?></option>
83
+ <?php endforeach; ?>
84
+ </select>
85
+ <br/>
86
  <p class="description">
87
+ <?php _e('Select which font-display strategy to use. Defaults to \'Auto\'.', 'host-webfonts-local'); ?>
88
  <a target="_blank" href="https://developers.google.com/web/updates/2016/02/font-display"><?php _e('Read more', 'host-webfonts-local'); ?></a>
89
  </p>
90
  </td>
98
  <td>
99
  <input class="caos_webfonts_remove_gfonts" id="caos_webfonts_remove_gfonts" type="checkbox" name="caos_webfonts_remove_gfonts" <?= OMGF_REMOVE_GFONTS == 'on' ? 'checked = "checked"' : ''; ?> />
100
  <p class="description">
101
+ <?= sprintf(__('Enabling this option will attempt to remove any externally hosted Google Fonts-stylesheets from your WordPress-blog. If it doesn\'t work for you, click %shere%s for a more comprehensive guide.', 'host-webfonts-local'), '<a target="_blank" href="' . OMGF_SITE_URL . '/how-to/remove-google-fonts-wordpress/' . $utmTags . '">', '</a>'); ?>
102
  </p>
103
  </td>
104
  </tr>
111
  <td>
112
  <input class="caos_webfonts_preload" id="caos_webfonts_preload" type="checkbox" name="caos_webfonts_preload" <?= OMGF_PRELOAD == 'on' ? 'checked = "checked"' : ''; ?> />
113
  <p class="description">
114
+ <?php _e('Leave this disabled if you\'re using a CSS minification plugin, such as Autoptimize or W3 Total Cache, or when using Web Font Loader.', 'host-webfonts-local'); ?>
115
+ <a target="_blank" href="https://developers.google.com/web/fundamentals/performance/resource-prioritization#preload"><?php _e('Read more', 'host-webfonts-local'); ?></a>
116
  </p>
117
  </td>
118
  </tr>
119
+ </table>
120
  </div>
includes/templates/settings-generate-stylesheet.phtml → templates/admin/block-generate-stylesheet.phtml RENAMED
@@ -10,17 +10,18 @@
10
  if (!defined('ABSPATH')) {
11
  exit;
12
  }
 
 
13
  ?>
14
  <div class="">
15
  <h3><?php _e('Generate Stylesheet', 'host-webfonts-local'); ?></h3>
16
- <p class="description">
17
- <?php _e('Search for fonts using a comma-separated list (e.g. Open Sans,Roboto,Poppins) and click \'Search\'.', 'host-webfonts-local'); ?>
18
- </p>
19
  <div class="hwl-search-box">
20
  <input type="text" name="search-field"
21
  id="search-field" class="form-input-tip ui-autocomplete-input" placeholder="<?php _e('Search... (e.g. Roboto,Open Sans)', 'host-webfonts-local'); ?>"/>
22
  <input type="button" onclick="hwlClickSearch()" name="search-btn"
23
  id="search-btn" class="button button-primary button-hero" value="<?php _e('Search', 'host-webfonts-local'); ?>"/>
 
24
  </div>
25
  <table>
26
  <tr id="row" valign="top">
@@ -28,25 +29,26 @@ if (!defined('ABSPATH')) {
28
  </tr>
29
  <tbody id="hwl-subsets">
30
  <?php
31
- $subsetFonts = hwlGetSubsets();
32
  ?>
33
  <?php if ($subsetFonts): ?>
34
  <?php foreach ($subsetFonts as $subsetFont): ?>
35
  <?php
36
  $availableSubsets = explode(',', $subsetFont->available_subsets);
37
  $selectedSubsets = explode(',', $subsetFont->selected_subsets);
 
38
  ?>
39
  <tr valign="top" id="<?= $subsetFont->subset_font; ?>">
40
  <td>
41
  <label>
42
- <input readonly type="text" class="hwl-subset-font-family" value="<?= $subsetFont->subset_family; ?>"/>
43
  </label>
44
  </td>
45
  <?php foreach ($availableSubsets as $availableSubset): ?>
46
  <td>
47
  <label>
48
  <?php $checked = in_array($availableSubset, $selectedSubsets) ? 'checked="checked"' : ''; ?>
49
- <input name="<?= $subsetFont->subset_font; ?>" value="<?= $availableSubset; ?>" type="checkbox" onclick="hwlGenerateSearchQuery('<?= $subsetFont->subset_font; ?>')" <?= $checked; ?>/>
50
  <?= $availableSubset; ?>
51
  </label>
52
  </td>
@@ -63,13 +65,13 @@ if (!defined('ABSPATH')) {
63
  </table>
64
  <table align="left" id="hwl-results">
65
  <?php
66
- $savedFonts = hwlGetTotalFonts();
67
  ?>
68
  <?php if ($savedFonts && $subsetFonts): ?>
69
  <?php foreach ($subsetFonts as $subsetFont): ?>
70
  <tbody id="hwl-section-<?= $subsetFont->subset_font; ?>">
71
  <?php
72
- $fonts = hwlGetFontsByFamily($subsetFont->subset_family);
73
  ?>
74
  <?php foreach ($fonts as $font):
75
  $fontId = $font->font_id;
@@ -138,8 +140,8 @@ if (!defined('ABSPATH')) {
138
  </tr>
139
  <tr valign="center">
140
  <?php
141
- $downloaded = hwlGetDownloadStatus()['downloaded'];
142
- $total = hwlGetDownloadStatus()['total'];
143
  $width = $downloaded && $total ? (100 / $total) * $downloaded : 0;
144
  ?>
145
  <td colspan="5">
10
  if (!defined('ABSPATH')) {
11
  exit;
12
  }
13
+
14
+ $db = new OMGF_DB();
15
  ?>
16
  <div class="">
17
  <h3><?php _e('Generate Stylesheet', 'host-webfonts-local'); ?></h3>
18
+ <p class="description">* Default WordPress font.</p>
 
 
19
  <div class="hwl-search-box">
20
  <input type="text" name="search-field"
21
  id="search-field" class="form-input-tip ui-autocomplete-input" placeholder="<?php _e('Search... (e.g. Roboto,Open Sans)', 'host-webfonts-local'); ?>"/>
22
  <input type="button" onclick="hwlClickSearch()" name="search-btn"
23
  id="search-btn" class="button button-primary button-hero" value="<?php _e('Search', 'host-webfonts-local'); ?>"/>
24
+ <input type="button" onclick="hwlAutoDetectFonts()" name="detect-btn" id="detect-btn" class="button button-secondary button-hero" value="<?= __('Auto-detect', 'host-webfonts-local'); ?>" />
25
  </div>
26
  <table>
27
  <tr id="row" valign="top">
29
  </tr>
30
  <tbody id="hwl-subsets">
31
  <?php
32
+ $subsetFonts = $db->get_subsets();
33
  ?>
34
  <?php if ($subsetFonts): ?>
35
  <?php foreach ($subsetFonts as $subsetFont): ?>
36
  <?php
37
  $availableSubsets = explode(',', $subsetFont->available_subsets);
38
  $selectedSubsets = explode(',', $subsetFont->selected_subsets);
39
+ $defaultSubsets = array('open-sans', 'noto-serif');
40
  ?>
41
  <tr valign="top" id="<?= $subsetFont->subset_font; ?>">
42
  <td>
43
  <label>
44
+ <input readonly type="text" class="hwl-subset-font-family" value="<?= $subsetFont->subset_family; ?> <?= in_array($subsetFont->subset_font, $defaultSubsets) ? '*' : ''; ?>" />
45
  </label>
46
  </td>
47
  <?php foreach ($availableSubsets as $availableSubset): ?>
48
  <td>
49
  <label>
50
  <?php $checked = in_array($availableSubset, $selectedSubsets) ? 'checked="checked"' : ''; ?>
51
+ <input name="<?= $subsetFont->subset_font; ?>" value="<?= $availableSubset; ?>" type="checkbox" onclick="hwlGenerateSearchQuery('<?= $subsetFont->subset_font; ?>')" <?= $checked; ?> />
52
  <?= $availableSubset; ?>
53
  </label>
54
  </td>
65
  </table>
66
  <table align="left" id="hwl-results">
67
  <?php
68
+ $savedFonts = $db->get_total_fonts();
69
  ?>
70
  <?php if ($savedFonts && $subsetFonts): ?>
71
  <?php foreach ($subsetFonts as $subsetFont): ?>
72
  <tbody id="hwl-section-<?= $subsetFont->subset_font; ?>">
73
  <?php
74
+ $fonts = $db->get_fonts_by_family($subsetFont->subset_family);
75
  ?>
76
  <?php foreach ($fonts as $font):
77
  $fontId = $font->font_id;
140
  </tr>
141
  <tr valign="center">
142
  <?php
143
+ $downloaded = $db->get_download_status()['downloaded'];
144
+ $total = $db->get_download_status()['total'];
145
  $width = $downloaded && $total ? (100 / $total) * $downloaded : 0;
146
  ?>
147
  <td colspan="5">
includes/templates/settings-welcome.phtml → templates/admin/block-welcome.phtml RENAMED
@@ -10,24 +10,18 @@
10
  if (!defined('ABSPATH')) {
11
  exit;
12
  }
 
13
  ?>
14
  <div id="welcome-panel" class="welcome-panel">
15
  <div class="welcome-panel-content">
16
- <h2><?php _e('Thank you for using OMGF!', 'host-webfonts-local'); ?></h2>
17
  <p class="about-description">
18
- <?php _e(
19
- 'OMGF automagically downloads and saves the fonts you want to use inside Wordpress\' content-folder, generates a stylesheet for them and enqueues it in your theme\'s header. This will decrease your pageload times, leverage your browser cache, minimize external requests and effectively bring you a perfect score on Pagespeed Insights and Pingdom.',
20
- 'host-webfonts-local'
21
- ); ?>
22
  </p>
23
  <div class="welcome-panel-column-container">
24
  <div class="welcome-panel-column" style="width: 32%;">
25
  <h3><?php _e( 'Quickstart', 'host-webfonts-local') ;?></h3>
26
  <ul>
27
- <li class="welcome-icon dashicons-before dashicons-editor-bold"><?= sprintf(__('For all available fonts, check out %sGoogle Fonts%s', 'host-webfonts-local'), '<a href="https://fonts.google.com/" target="_blank">','</a>'); ?></li>
28
- <li class="welcome-icon dashicons-before dashicons-cloud"><?php _e('Search for for your fonts', 'host-webfonts-local'); ?></li>
29
- <li class="welcome-icon dashicons-before dashicons-admin-settings"><?php _e('Select the subsets you need', 'host-webfonts-local'); ?></li>
30
- <li class="welcome-icon dashicons-before dashicons-admin-tools"><?php _e('Modify the list by removing the fonts you don\'t use', 'host-webfonts-local'); ?></li>
31
  <li class="welcome-icon dashicons-before dashicons-update"><?php _e('Click \'Download Fonts\' and wait for the download to complete', 'host-webfonts-local'); ?></li>
32
  <li class="welcome-icon dashicons-before dashicons-art"><?php _e('Click \'Generate Stylesheet\' and wait for the process to complete', 'host-webfonts-local'); ?></li>
33
  <li class="welcome-icon dashicons-before dashicons-media-text"><?php _e('The stylesheet is generated and added to your theme\'s header', 'host-webfonts-local'); ?></li>
@@ -35,43 +29,30 @@ if (!defined('ABSPATH')) {
35
  <li class="welcome-icon dashicons-before dashicons-smiley"><?php _e('Done!', 'host-webfonts-local'); ?></li>
36
  </ul>
37
  <p>
38
- <?= sprintf(__('%sClick here%s for a more comprehensive guide.', 'host-webfonts-local'), '<a target="_blank" href="' . OMGF_SITE_URL . '/wordpress/host-google-fonts-locally/">', '</a>'); ?>
39
  </p>
40
  </div>
41
  <div class="welcome-panel-column" style="width: 32%;">
42
- <h3><?php _e('Get a Perfect Score on Pagespeed & Pingdom!', 'host-webfonts-local'); ?></h3>
43
- <p><?= sprintf(__('%sLeverage your browser cache%s and
44
- %slower pageload times%s by hosting analytics.js locally with
45
- %sCAOS%s.', 'host-webfonts-local'), '<strong>', '</strong>', '<strong>', '</strong>', '<a href="' . OMGF_SITE_URL . '/wordpress-plugins/optimize-analytics-wordpress/" target="_blank">', '</a>'); ?>
46
- </p>
47
- <p>
48
- <a target="_blank" href="https://wordpress.org/plugins/host-analyticsjs-local"><?php _e('Download now', 'host-webfonts-local'); ?></a>
49
- </p>
50
- <h3><?php _e('Want to Host other Files Locally?', 'host-webfonts-local'); ?></h3>
51
- <p><?php _e('Unleash your site\'s true potential by locally hosting as many files as possible.', 'host-webfonts-local'); ?></p>
52
  <p>
53
- <a target="_blank" href="<?= OMGF_SITE_URL; ?>/how-to/host-js-locally-crontab/"><?php _e('Read more', 'host-webfonts-local'); ?></a>
 
54
  </p>
55
  </div>
56
  <div class="welcome-panel-column welcome-panel-last" style="width: 34%;">
57
  <h3>
58
- <?php _e('Need Help?', 'host-webfonts-local'); ?>
59
  </h3>
60
  <p>
61
- <?php _e('Thank you for using OMGF.', 'host-webfonts-local'); ?>
62
- </p>
63
- <p>
64
- <?= sprintf(__('I am convinced that knowledge should be free. That\'s why I will never charge you for the plugins I create and I will help you to succeed in your projects through the %stutorials%s on my blog.', 'host-webfonts-local'), '<a href="' . OMGF_SITE_URL . '/how-to/" target="_blank">', '</a>'); ?>
65
  </p>
66
  <p>
67
  <?= sprintf(__('However, my time is just as valuable as yours. Consider supporting me by either %sdonating%s or leaving a %s5-star review%s on Wordpress.org.', 'host-webfonts-local'), '<a href="' . OMGF_SITE_URL . '/donate" target="_blank">', '</a>', '<a target="_blank" href="https://wordpress.org/support/plugin/host-analyticsjs-local/reviews/?rate=5#new-post">', '</a>'); ?>
68
  </p>
69
  <p>
70
-
71
- <?= sprintf(__('If you\'re running into any issues, please make sure you\'ve read %sthe manual%s thoroughly. Visit the %sFAQ%s and %sSupport Forum%s to see if your question has already been answered. If not, ask a question on the Support Forum.', 'host-webfonts-local'), '<a href="' . OMGF_SITE_URL . '/wordpress/host-google-fonts-locally/" target="_blank">', '</a>', '<a href="https://wordpress.org/plugins/host-webfonts-local/#description" target="_blank">', '</a>', '<a href="https://wordpress.org/support/plugin/host-webfonts-local">', '</a>'); ?>
72
- </p>
73
- <p>
74
- <a target="_blank" class="button button-primary button-hero" href="<?= OMGF_SITE_URL; ?>/donate/"><span class="dashicons-before dashicons-heart"> <?php _e('Donate', 'host-webfonts-local'); ?></span></a>
75
  <a target="_blank" class="button button-secondary button-hero" href="https://wordpress.org/support/plugin/host-webfonts-local/reviews/?rate=5#new-post"><span class="dashicons-before dashicons-star-filled"> <?php _e('Review', 'host-webfonts-local'); ?></span></a>
76
  <a target="_blank" class="button button-secondary button-hero" href="https://twitter.com/Dan0sz"><span class="dashicons-before dashicons-twitter"> <?php _e('Follow', 'host-webfonts-local'); ?></span></a>
77
  </p>
10
  if (!defined('ABSPATH')) {
11
  exit;
12
  }
13
+ $utmTags = '?utm_source=omgf&utm_medium=plugin&utm_campaign=support_tab';
14
  ?>
15
  <div id="welcome-panel" class="welcome-panel">
16
  <div class="welcome-panel-content">
 
17
  <p class="about-description">
18
+ <?= get_plugin_data(OMGF_PLUGIN_FILE)['Description']; ?>
 
 
 
19
  </p>
20
  <div class="welcome-panel-column-container">
21
  <div class="welcome-panel-column" style="width: 32%;">
22
  <h3><?php _e( 'Quickstart', 'host-webfonts-local') ;?></h3>
23
  <ul>
24
+ <li class="welcome-icon dashicons-before dashicons-admin-settings"><?php _e('Click Auto-detect and wait for the on-screen instructions', 'host-webfonts-local'); ?></li>
 
 
 
25
  <li class="welcome-icon dashicons-before dashicons-update"><?php _e('Click \'Download Fonts\' and wait for the download to complete', 'host-webfonts-local'); ?></li>
26
  <li class="welcome-icon dashicons-before dashicons-art"><?php _e('Click \'Generate Stylesheet\' and wait for the process to complete', 'host-webfonts-local'); ?></li>
27
  <li class="welcome-icon dashicons-before dashicons-media-text"><?php _e('The stylesheet is generated and added to your theme\'s header', 'host-webfonts-local'); ?></li>
29
  <li class="welcome-icon dashicons-before dashicons-smiley"><?php _e('Done!', 'host-webfonts-local'); ?></li>
30
  </ul>
31
  <p>
32
+ <?= sprintf(__('%sClick here%s for a more comprehensive guide.', 'host-webfonts-local'), '<a target="_blank" href="' . OMGF_SITE_URL . '/wordpress/host-google-fonts-locally/' . $utmTags . '">', '</a>'); ?>
33
  </p>
34
  </div>
35
  <div class="welcome-panel-column" style="width: 32%;">
36
+ <h3>
37
+ <?php _e('Need Help?', 'host-webfonts-local'); ?>
38
+ </h3>
 
 
 
 
 
 
 
39
  <p>
40
+ <?= sprintf(__('If you\'re running into any issues, please make sure you\'ve read %sthe manual%s thoroughly. Visit the %sFAQ%s and %sSupport Forum%s to see if your question has already been answered. If not, ask a question on the Support Forum.', 'host-webfonts-local'), '<a href="' . OMGF_SITE_URL . '/wordpress/host-google-fonts-locally/' . $utmTags . '" target="_blank">', '</a>', '<a href="https://wordpress.org/plugins/host-webfonts-local/#description" target="_blank">', '</a>', '<a href="https://wordpress.org/support/plugin/host-webfonts-local">', '</a>'); ?>
41
+
42
  </p>
43
  </div>
44
  <div class="welcome-panel-column welcome-panel-last" style="width: 34%;">
45
  <h3>
46
+ <?php _e('Support OMGF', 'host-webfonts-local'); ?>
47
  </h3>
48
  <p>
49
+ <?= sprintf(__('I am convinced that knowledge should be free. That\'s why I will never charge you for the plugins I create and I will help you to succeed in your projects through the %stutorials%s on my blog.', 'host-webfonts-local'), '<a href="' . OMGF_SITE_URL . '/how-to/' . $utmTags . '" target="_blank">', '</a>'); ?>
 
 
 
50
  </p>
51
  <p>
52
  <?= sprintf(__('However, my time is just as valuable as yours. Consider supporting me by either %sdonating%s or leaving a %s5-star review%s on Wordpress.org.', 'host-webfonts-local'), '<a href="' . OMGF_SITE_URL . '/donate" target="_blank">', '</a>', '<a target="_blank" href="https://wordpress.org/support/plugin/host-analyticsjs-local/reviews/?rate=5#new-post">', '</a>'); ?>
53
  </p>
54
  <p>
55
+ <a target="_blank" class="button button-primary button-hero" href="<?= OMGF_SITE_URL; ?>/donate/?utm_source=omgf&utm_medium=plugin&utm_campaign=donate_button"><span class="dashicons-before dashicons-heart"> <?php _e('Donate', 'host-webfonts-local'); ?></span></a>
 
 
 
 
56
  <a target="_blank" class="button button-secondary button-hero" href="https://wordpress.org/support/plugin/host-webfonts-local/reviews/?rate=5#new-post"><span class="dashicons-before dashicons-star-filled"> <?php _e('Review', 'host-webfonts-local'); ?></span></a>
57
  <a target="_blank" class="button button-secondary button-hero" href="https://twitter.com/Dan0sz"><span class="dashicons-before dashicons-twitter"> <?php _e('Follow', 'host-webfonts-local'); ?></span></a>
58
  </p>
includes/templates/script-web-font-loader.phtml → templates/frontend-web-font-loader.phtml RENAMED
@@ -6,12 +6,10 @@
6
  * @url : https://daan.dev
7
  */
8
 
9
- // Exit if accessed directly
10
- if (!defined('ABSPATH')) {
11
- exit;
12
- }
13
 
14
- $fonts = hwlGetDownloadedFonts();
 
15
  $families = array_unique(
16
  array_map(
17
  function ($i) {
@@ -23,7 +21,7 @@ $families = array_unique(
23
  $omgfStaticVersion = '?ver=' . OMGF_STATIC_VERSION;
24
  $omgfSrcUrl = OMGF_UPLOAD_URL . '/' . OMGF_FILENAME . (OMGF_REMOVE_VERSION ? null : $omgfStaticVersion);
25
  $wflVersion = '?ver=' . OMGF_WEB_FONT_LOADER_VERSION;
26
- $wflSrcUrl = plugin_dir_url(dirname(__FILE__)) . 'libraries/webfont.js' . (OMGF_REMOVE_VERSION ? null : $wflVersion);
27
  ?>
28
  <?php if ($fonts && $families): ?>
29
  <script type="text/javascript">
6
  * @url : https://daan.dev
7
  */
8
 
9
+ defined('ABSPATH') || exit;
 
 
 
10
 
11
+ $db = new OMGF_DB();
12
+ $fonts = $db->get_downloaded_fonts();
13
  $families = array_unique(
14
  array_map(
15
  function ($i) {
21
  $omgfStaticVersion = '?ver=' . OMGF_STATIC_VERSION;
22
  $omgfSrcUrl = OMGF_UPLOAD_URL . '/' . OMGF_FILENAME . (OMGF_REMOVE_VERSION ? null : $omgfStaticVersion);
23
  $wflVersion = '?ver=' . OMGF_WEB_FONT_LOADER_VERSION;
24
+ $wflSrcUrl = plugin_dir_url(OMGF_PLUGIN_FILE) . 'js/libraries/webfont.js' . (OMGF_REMOVE_VERSION ? null : $wflVersion);
25
  ?>
26
  <?php if ($fonts && $families): ?>
27
  <script type="text/javascript">