Jake Vanderwerf
2026-01-01 f0fb57aea8652e4c66290fc34a9b4f5b10cd5530
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
<?php
/*
Plugin Name: JakeVan Base
Plugin URI: https://jakevan.ca
Description: The Base Plugin for JakeVan clients
Author: Jake Vanderwerf
Version: 1.0.0
Author URI: https://jakevan.ca/
Textdomain: jvb
*/
 
use JVBase\JVB;
use JVBase\managers\IconsManager;
use JVBase\utility\Checker;
use JVBase\utility\Features;
 
//security
if (!defined('ABSPATH')) {
    exit;
}
 
/**
 * Track REST API errors by wrapping request execution
 */
add_filter('rest_pre_dispatch', function($result, $server, $request) {
    // Store request details globally for error logging
    $GLOBALS['jvb_rest_request'] = [
        'route' => $request->get_route(),
        'method' => $request->get_method(),
        'params' => $request->get_params(),
        'time' => microtime(true),
    ];
 
    // Set up error handler for this request
    set_error_handler(function($errno, $errstr, $errfile, $errline) {
        if (!(error_reporting() & $errno)) {
            return false;
        }
 
        $context = array_merge($GLOBALS['jvb_rest_request'] ?? [], [
            'error_type' => $errno,
            'error_message' => $errstr,
            'file' => $errfile,
            'line' => $errline,
            'user_id' => get_current_user_id(),
        ]);
 
        error_log('JVB REST Error: ' . json_encode($context));
 
        return false; // Let PHP handle it normally too
    });
 
    return $result;
}, 10, 3);
 
add_filter('rest_post_dispatch', function($result, $server, $request) {
    // Restore default error handler
    restore_error_handler();
 
    // Check for fatal errors that occurred during request
    $error = error_get_last();
    if ($error && in_array($error['type'], [E_ERROR, E_USER_ERROR, E_PARSE, E_COMPILE_ERROR])) {
        $context = array_merge($GLOBALS['jvb_rest_request'] ?? [], [
            'fatal_error' => $error,
            'user_id' => get_current_user_id(),
        ]);
 
        error_log('JVB REST Fatal: ' . json_encode($context));
    }
 
    // Clean up
    unset($GLOBALS['jvb_rest_request']);
 
    return $result;
}, 10, 3);
 
 
const JVB_LOCAL = 'northeh.test';
 
function jvbIgnoredPostTypes():array
{
    return [BASE.'directory', BASE.'dash', 'attachment', 'revision', 'nav_menu_item'];
}
add_filter('show_admin_bar', '__return_false');
const JVB_TESTING = true;
 
const JVB_DIR = WP_PLUGIN_DIR . '/jvb';
define('JVB_URL', plugin_dir_url(__FILE__));
 
// Session Security
define('JVB_SESSION_FINGERPRINT', true);
 
// Login Security
define('JVB_MAX_LOGIN_ATTEMPTS', 5);
define('JVB_LOCKOUT_DURATION', 15 * MINUTE_IN_SECONDS);
 
 
require(JVB_DIR.'/base/_setup.php');
//error_log('###############################################');
//error_log('Registered Base');
//error_log('###############################################');
//error_log('BASE: '.print_r(BASE, true));
//error_log('JVB_SITE: '.print_r(JVB_SITE, true));
//error_log('JVB_OPTIONS: '.print_r(JVB_OPTIONS, true));
//error_log('JVB_CONTENT: '.print_r(JVB_CONTENT, true));
//error_log('JVB_TAXONOMY: '.print_r(JVB_TAXONOMY, true));
//error_log('JVB_LOGIN: '.print_r(JVB_LOGIN, true));
//error_log('JVB_MEMBERSHIP: '.print_r(JVB_MEMBERSHIP, true));
//error_log('JVB_USER: '.print_r(JVB_USER, true));
 
 
if (empty(JVB_SITE)) {
    return;
}
require(JVB_DIR.'/inc/utility/setup.php');
require(JVB_DIR.'/checks.php');
require(JVB_DIR.'/globals.php');
 
$jvb_feed        = jvbGlobalFeedContent();
$jvb_taxonomy_for= jvbGlobalTaxonomyFor();
$jvb_responses     = jvbGlobalResponses();
 
global $jvb_everything;
$jvb_everything = array_merge(JVB_CONTENT, JVB_TAXONOMY);
 
 
require(JVB_DIR . '/inc/registry/_setup.php');
 
require(JVB_DIR . '/activate.php');
 
require(JVB_DIR . '/inc/helpers/all.php');
require(JVB_DIR . '/inc/ui/_setup.php');
require(JVB_DIR . '/inc/meta/_setup.php');
require(JVB_DIR . '/inc/importers/_setup.php');
require(JVB_DIR . '/inc/managers/_setup.php');
 
/**
 * Get an icon element
 *
 * @param string $name Icon name
 * @param array $options Options array:
 *   - 'source' => 'icons'|'dash'|'forms'|etc. (default: 'icons')
 *   - 'style' => 'regular'|'bold'|'fill'|etc.
 *   - 'label' => 'Accessible label'
 *   - 'decorative' => true
 *   - 'class' => 'additional classes'
 *   - 'size' => 24
 * @return string HTML icon element
 */
function jvbIcon(string $name, array $options = []): string
{
    $source = $options['source'] ?? 'icons';
 
    // Remove source from options before passing to IconsManager
    unset($options['source']);
 
    return IconsManager::for($source)->get($name, $options);
}
 
/**
 * Get a CSS data URI for an icon
 *
 * @param string $name Icon name
 * @param array $options Options array:
 *   - 'style' => 'regular'|'bold'|'fill'|etc.
 *   - 'source' => 'icons'|'dash'|'forms'|etc. (for tracking purposes)
 * @return string data:image/svg+xml;base64,... URL
 */
function jvbCSSIcon(string $name, array $options = []): string
{
    $style = $options['style'] ?? null;
    $source = $options['source'] ?? 'icons';
 
    return IconsManager::for($source)->getCSSIcon($name, $style);
}
 
/**
 * Get a dashboard icon
 */
function jvbDashIcon(string $name, array $options = []): string
{
    $options['source'] = 'dash';
    return jvbIcon($name, $options);
}
 
/**
 * Get a form editor icon
 */
function jvbFormIcon(string $name, array $options = []): string
{
    $options['source'] = 'forms';
    return jvbIcon($name, $options);
}
 
require(JVB_DIR . '/inc/integrations/_setup.php');
require(JVB_DIR . '/inc/rest/_setup.php');
 
add_filter( 'cron_schedules', 'jvbCronSchedules');
function jvbCronSchedules($schedules)
{
    $schedules[ 'every-5-minutes' ] = [
        'interval' => 5 * 60,
        'display' => __('Every 5 minutes', 'jvb')
    ];
    $schedules[ 'every-minute' ] = [
        'interval' => 60,
        'display' => __('Every minute', 'jvb')
    ];
    $schedules[ 'monthly' ] = [
        'interval' => 604800 * 4,
        'display' => __('Once Monthly', 'jvb')
    ];
 
    return $schedules;
}
 
register_activation_hook(JVB_DIR.'/jvb.php', 'jvbActivatePlugin');
register_deactivation_hook(JVB_DIR.'/jvb.php', 'jvbDeactivatePlugin');
 
 
 
 
 
 
 
add_action('init', 'jvbUserCheck');
function jvbUserCheck():void
{
    if (is_admin() && isOurPeople()) {
        wp_redirect(get_home_url(null, '/dash'));
        exit;
    }
}
 
require(JVB_DIR . '/inc/users/UserSettings.php');
 
 
require(JVB_DIR . '/inc/templates.php');
 
/**
 * Utilities
 */
require(JVB_DIR . '/cleanup.php');
require(JVB_DIR . '/inc/admin/_setup.php');
 
require(JVB_DIR . '/JVBase.php');
add_action('init', 'jvbLoadBase', 1);
function jvbLoadBase():void
{
    JVB::getInstance();
}
function JVB(): JVB
{
    return JVB::getInstance();
}
 
 
function checkIf(): Checker
{
    return JVBase\utility\Checker::getInstance();
}
 
require(JVB_DIR . '/inc/blocks/_setup.php');
 
 
 
 
 
 
 
add_filter('upload_mimes', function ($mimes) {
    $mimes['webp'] = 'image/webp';
    $mimes['avif'] = 'image/avif';
    return $mimes;
});
 
// And this to ensure WebP is treated as an image
add_filter('file_is_displayable_image', function ($result, $path) {
    if (preg_match('/\.webp$/i', $path)) {
        return true;
    }
    return $result;
}, 10, 2);
 
 
function jvbDump(mixed $array, string $name = 'var'):void
{
    highlight_string("<?php\n\$$name =\n" . var_export($array, true) . ";\n?>");
}
 
 
/**
 * Scripts
 */
add_action('wp_enqueue_scripts', 'jvbScripts', 10);
 
function jvbScripts():void
{
    add_action('wp_head', 'jvbInlineNavStyles');
 
    if (Features::forSite()->has('dashboard')) {
        wp_enqueue_script('jvb-queue');
    }
 
    wp_enqueue_script('jvb-auth');
    wp_enqueue_script('jvb-settings');
    wp_enqueue_script('jvb-navigation');
//    wp_enqueue_script('jvb-ui');
//    wp_enqueue_script('jvb-media');
    wp_enqueue_script('jvb-gallery');
    wp_enqueue_script('jvb-cache');
 
 
    $interactions = [];
    if (Features::forSite()->has('favourites')) {
        $interactions[] = 'favourites';
    }
    if (Features::anyContentHas('karma') ||
        Features::anyTaxonomyHas('karma') ||
        Features::anyUserHas('karma')) {
        $interactions[] = 'karma';
    }
    if (Features::forSite()->has('notifications')) {
        $interactions[] = 'notifications';
    }
 
    if (!empty($interactions)) {
        wp_enqueue_script('jvb-interactions');
        foreach($interactions as $interaction) {
            wp_enqueue_script('jvb-'.$interaction);
        }
    }
 
 
    $queue = [
        'api' => rest_url('jvb/v1/'),
        'redirect' => wp_login_url(home_url(add_query_arg(null, null))),
        'labels' => jvbGetLabels(),
    ];
 
    wp_localize_script('jvb-auth', 'jvbSettings', $queue);
 
 
    $initUserSettings = 'async function initUserItems() {
    if (!jvbSettings.currentUser) return;
 
    window.userFavourites = {};
    window.userVotes = {};
    ';
    if (Features::forSite()->has('favourites')) {
        wp_enqueue_script('jvb-favourites');
        $initUserSettings .= '
        //Fetch user favourites
        try {
            const result = await window.jvbCache.fetchWithCache(
                `${jvbSettings.api}favourites?all=true`,
                {
                    method: \'GET\',
                    headers: {\'X-WP-Nonce\': jvbSettings.nonce}
                }
            );
 
            if (result && result.favourites) {
                for (const key in result.favourites) {
                    window.userFavourites[key] = new Set();
                    result.favourites[key].forEach(id => {
                        window.userFavourites[key].add(parseInt(id));
                    });
                }
            }
        } catch (error) {
            console.error(\'Failed to fetch user favourites:\', error);
        }';
    }
 
    if (Features::anyContentHas('karma') || Features::anyTaxonomyHas('karma') || Features::anyUserHas('karma')) {
        wp_enqueue_script('jvb-votes');
        $initUserSettings .= '// Fetch user votes
        try {
            const result = await window.jvbCache.fetchWithCache(
                `${jvbSettings.api}vote?user=${jvbSettings.currentUser}`,
                {
                    method: \'GET\',
                    headers: {\'X-WP-Nonce\': jvbSettings.nonce}
                },
                {forceRefresh: true}
            );
 
            window.userVotes = {};
            if (result) {
                for (const key in result) {
                    window.userVotes[key] = new Map();
                    for (const [id, vote] of Object.entries(result[key])) {
                        window.userVotes[key].set(parseInt(id), vote);
                    }
                }
            }
        } catch (error) {
            console.error(\'Failed to fetch user votes:\', error);
        }';
    }
 
    $initUserSettings .= '} initUserItems();';
 
//  wp_add_inline_script('jvb-queue', $initUserSettings, 'after');
 
 
    if (is_search() ||
        is_tax(BASE.'shop') ||
        is_singular(BASE.'artist') ||
        jvbIsDirectory()
    ) {
        wp_enqueue_script('jvb-page-nav');
    }
 
        // Only load on single shop pages or other relevant pages
    if (is_tax(BASE.'shop') ||
        is_singular(BASE.'partner')) {
            $ID = get_queried_object_id();
        if (is_tax()) {
            $check = get_term_meta($ID, BASE.'has_map', true);
        } else {
            $check = get_post_meta($ID, BASE.'has_map', true);
        }
 
//        if ($check && $check !== '') {
////            wp_enqueue_script(
////                'google-maps-frontend',
////                'https://maps.googleapis.com/maps/api/js?key=' . GOOGLE_API . '&callback=googleMapsLoaded',
////                [],
////                null,
////                ['strategy' => 'async',
////                 'in_footer' => true]
////            );
//
//            // Add the callback function
//            wp_add_inline_script('google-maps-frontend', '
//            function googleMapsLoaded() {
//                if (window.googleMapsCallbacks && window.googleMapsCallbacks.length) {
//                    window.googleMapsCallbacks.forEach(callback => callback());
//                }
//            }
//        ');
//        }
    }
    if (is_user_logged_in() && Features::forSite()->has('notifications')) {
        wp_enqueue_script('jvb-notifications');
 
        wp_localize_script('jvb-notifications', 'notificationSettings', array(
            'homeUrl' => home_url(),
            'strings' => array(
                'loading' => 'Loading...',
                'error' => 'Failed to load notifications',
                'noNotifications' => 'No new notifications',
                'viewAll' => 'View All Notifications',
                'markRead' => 'Mark as read',
                'review' => 'Review'
            )
        ));
    }
 
    jvbAddScriptDependency('jvb-feed-view-script', 'jvb-queue');
    jvbAddScriptDependency('jvb-feed-view-script', 'jvb-selector');
    jvbAddScriptDependency('jvb-feed-view-script', 'jvb-data-store');
    jvbAddScriptDependency('jvb-feed-view-script', 'jvb-cache');
    jvbAddScriptDependency('jvb-feed-view-script', 'jvb-a11y');
    jvbAddScriptDependency('jvb-feed-view-script', 'jvb-utility');
    jvbAddScriptDependency('jvb-feed-view-script', 'jvb-gallery');
//    jvbAddScriptDependency('jvb-feed-view-script', 'jvb-loading');
    jvbAddScriptDependency('jvb-forms-view-script', 'jvb-queue');
    jvbAddScriptDependency('jvb-forms-view-script', 'jvb-quill');
    jvbAddScriptDependency('jvb-forms-view-script', 'jvb-form');
    jvbAddScriptDependency('jvb-forms-view-script', 'jvb-tabs');
}
 
function jvbAdminMap():void
{
//    wp_enqueue_script(
//        'google-maps',
//        'https://maps.googleapis.com/maps/api/js?key=' . GOOGLE_API . '&libraries=places&callback=googleMapsLoaded',
//        [],
//        null,
//        [
//            'strategy' => 'async',
//            'in_footer' => true
//        ]
//    );
//
//    // Add the callback function
//    wp_add_inline_script('google-maps', '
//        function googleMapsLoaded() {
//            if (window.googleMapsCallbacks && window.googleMapsCallbacks.length) {
//                window.googleMapsCallbacks.forEach(callback => callback());
//            }
//        }
//    ');
}
 
function jvbAddScriptDependency(string $handle, string $dep):bool
{
    global $wp_scripts;
 
    $script = $wp_scripts->query($handle);
    if (!$script) {
        return false;
    }
 
    if (!in_array($dep, $script->deps)) {
        $script->deps[] = $dep;
    }
 
    return true;
}
 
 
add_action('wp_body_open', 'jvbAccessibility');
function jvbAccessibility():void
{
    echo '<div class="screen-reader-text live-region" aria-live="polite" role="status"></div>';
}
 
 
//add_action('wp_head', 'jvbDumpIt');
function jvbDumpIt()
{
}
 
add_action('after_setup_theme', 'jvbImageSize');
function jvbImageSize():void
{
    add_theme_support('post-thumbnails');
    add_image_size( 'tiny', 50, 50, false );
}
 
 
//
//add_action('rest_api_init', function() {
//  error_log('User ' . get_current_user_id() . ' can edit pages: ' . (current_user_can('edit_pages') ? 'yes' : 'no'));
//  error_log('User roles: ' . print_r(wp_get_current_user()->roles, true));
//});
//
//add_filter('rest_pre_dispatch', function($result, $server, $request) {
//  if (strpos($request->get_route(), '/wp/v2/pages') !== false) {
//      error_log('Pages request - User: ' . get_current_user_id());
//      error_log('Can edit pages: ' . (current_user_can('edit_pages') ? 'yes' : 'no'));
//      error_log('Nonce: ' . $request->get_header('X-WP-Nonce'));
//  }
//  return $result;
//}, 10, 3);
 
add_filter('rest_authentication_errors', function($result) {
 
    // Don't override existing authentication
    if (is_wp_error($result) || $result === true) {
        return $result;
    }
 
    // Try to authenticate from cookie
    $cookie_user = wp_validate_auth_cookie('', 'logged_in');
 
    if ($cookie_user) {
        wp_set_current_user($cookie_user);
        return true;
    }
    return $result;
}, 99);