Jake Vanderwerf
2026-05-01 48721c85ebcfa973ee81719d2467ca80e4253dc9
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
<?php
namespace JVBase\rest;
 
if (!defined('ABSPATH')) {
    exit;
}
use JVBase\meta\Meta;
use WP_Error;
use WP_REST_Request;
use WP_REST_Response;
 
/**
 * @deprecated
 */
class RegisterRoutes extends RestRouteManager {
 
    protected array $config;
    protected array $tables = [];
    protected $wpdb;
    public function __construct(
        string $content,
        array $config
    ) {
        $this->route = $content;
        $this->config = $config;
        $this->cache_name = $content;
 
 
        parent::__construct();
 
        global $wpdb;
        $this->wpdb = $wpdb;
 
        if (jvbCheck('invitable', $this->config)) {
            foreach ($this->config['for_content'] as $c) {
                $this->tables[$c] = BASE .'invitations_'.$c;
            }
        }
 
        $this->action = 'dash-';
        add_filter(BASE.'handle_bulk_operation', [$this, 'processOperation'], 10, 3);
    }
 
    public function registerRoutes()
    {
        register_rest_route($this->namespace, "/{$this->route}", [
            [
                'methods'               => 'GET',
                'callback'              => [$this, 'handleGET'],
                'permission_callback'   => [$this, 'checkPermission'],
            ],
            [
                'methods'               => 'POST',
                'callback'              => [$this, 'handlePOST'],
                'permission_callback'   => [$this, 'checkPermission'],
            ]
        ]);
 
        if (jvbCheck('invitable', $this->config)) {
            register_rest_route($this->namespace, "/{$this->route}/members", [
                [
                    'methods'               => 'GET',
                    'callback'              => [$this, 'getInvitations'],
                    'permission_callback'   => [$this, 'checkPermission'],
                ],
                [
                    'methods'               => 'POST',
                    'callback'              => [$this, 'handleActions'],
                    'permission_callback'   => [$this, 'checkPermission'],
                ]
            ]);
        }
 
        if (jvbCheck('verify_entry', $this->config)) {
            register_rest_Route($this->namespace, "/{$this->route}/requests", [
                [
                    'methods'               => 'POST',
                    'callback'              => [$this, 'handleInvite'],
                    'permission_callback'   => [$this, 'checkPermission']
                ]
            ]);
        }
 
    }
 
    public function checkPermission(WP_REST_Request $request):bool
    {
        if ($this->route === 'options' && !current_user_can('manage_options')) {
            return false;
        } elseif (array_key_exists('is_owned_by', $this->config)) {
            $term = $request->get_param('term_id');
            if (!$this->checkTerm([
                'term_id'   => $term,
                'taxonomy'  => $this->route
            ])) {
                return false;
            }
            if (!current_user_can('manage_'.$this->route.'_'.$term)) {
                return false;
            }
        }
        return parent::checkPermission($request);
    }
 
    public function handleGET(WP_REST_Request $request):WP_REST_Response
    {
 
    }
 
    public function handlePOST(WP_REST_Request $request):WP_REST_Response
    {
        $data = $request->get_params();
        $user = $data['user'];
        if (!$this->checkUser($user) || !$this->userCheck($user)) {
            return new WP_REST_Response([
                'success'   => false,
                'message'   => 'Looks like you may not be who you say you are...'
            ]);
        }
        if ($this->route === 'shop' && !$this->checkTerm([
            'term_id'   => $data['shop'],
            'taxonomy'  => $this->route
        ])) {
            return new WP_REST_Response([
                'success'   => false,
                'message'   => 'This shop doesn\'t exist?'
            ]);
        }
        $queue = JVB()->queue();
        unset($data['user']);
        $operationID = $data['id'];
        unset($data['id']);
 
        $queue->queueOperation(
            $this->route.'_update',
            $user,
            $data,
            [
                'operation_id'  => $operationID,
                'priority'      => 'high',
            ]
        );
        return new WP_REST_Response([
            'success'   => true,
            'message'   => 'Successfully queued for processing'
        ]);
    }
 
    public function processOperation(WP_Error|array $result, object $operation, array $data):WP_Error|array
    {
        switch ($operation->type) {
            case $this->route.'_update':
                return $this->handleUpdateOperation($operation->user_id, $data);
            default:
                return $result;
        }
    }
    protected function handleUpdateOperation(int $userID, array $data):WP_Error|array
    {
        if ($this->route === 'options') {
            if (!user_can($userID, 'manage_options')) {
                return [
                    'success'   => false,
                    'error'     => 'User cannot change options'
                ];
            }
            $meta = Meta::forOptions($this->route);
        } else {
            $termID = (int) $data['term_id'];
            if (!user_can($userID, 'manage_'.$this->route.'_'.$termID)) {
                return [
                    'success'   => false,
                    'error'     => 'User cannot manage this '.$this->route
                ];
            }
            $meta = Meta::forTerm($termID);
        }
 
        $results = [];
 
        $allowed = array_filter($data, function ($v, $k) {
            return array_key_exists($v, $this->config['fields']??[]);
        }, ARRAY_FILTER_USE_BOTH);
 
 
        foreach ($allowed as $name => $value) {
            if (empty($value)) {
                $results[] = $meta->delete($name);
            } else {
                $results[] = $meta->set($name, $value);
            }
        }
        //Allow plugins & themes to process extra data here
        //Example: custom image generation logic
        $results = array_merge($results, apply_filters('jvb_'.$this->route.'_update_extra', [], $data));
 
        return [
            'success'   => true,
            'message'   => $this->route.' successfully updated',
            'results'   => $results
        ];
    }
    public function getInvitations(WP_REST_Request $request):WP_REST_Response
    {
        $termID = (int) $request->get_param('term_id');
        if (!$this->checkTerm(['term_id' => $termID, 'taxonomy' => $this->route])) {
            return new WP_REST_Response([
                'success'   => false,
                'message'   => 'Invalid shop'
            ]);
        }
        $status = $request->get_param('status') ?? 'all';
        $page = $request->get_param('page') ?? 1;
        $role = $request->get_param('content') ?? $this->config['for_content'][0];
        return JVB()->routes('invites')->getTermInvitations(['to_term' => $termID, 'status' => $status, 'page' => $page, 'taxonomy' => $this->route, 'role' => $role]);
    }
 
    public function handleActions(WP_REST_Request $request):WP_REST_Response
    {
        $action = $request->get_param('action');
        $termID = (int)$request->get_param('term_id');
        $userID = (int)$request->get_param('user');
        if (!$this->checkTerm(['term_id' => $termID, 'taxonomy' => $this->route]) || !$this->checkUser($userID)) {
            return new WP_REST_Response([
                'success'   => false,
                'message'   => 'Invalid shop or user'
            ]);
        }
 
        switch ($action) {
            case 'add_user':
                $return = $this->addUserToTerm($userID, $termID);
                break;
            case 'remove_user':
                $return = $this->removeUserFromTerm($userID, $termID);
                break;
            case 'add_invitation':
                $invitation = JVB()->routes('invites')->createInvitation(
                    sanitize_text_field($request->get_param('name')),
                    sanitize_email($request->get_param('email')),
                    $userID,
                    sanitize_text_field($request->get_param('role')) ?? $this->config['for_content'][0],
                    $termID,
                    $this->route
                );
                if (is_wp_error($invitation)) {
                    $return = [
                        'success'   => false,
                        'message'   => $invitation->get_error_message()
                    ];
                }else {
                    $return = [
                        'success'   => true,
                        'message'   => 'Invitation sent successfully'
                    ];
                }
                break;
            case 'remove_invitation':
 
                $targetUser = sanitize_text_field($request->get_param('target_user'));
                $return = $this->removeTermInvite($userID, $termID, $targetUser);
                break;
            case 'process_request':
                $request_id = sanitize_text_field($request->get_param('request_id'));
                $decision = $request->get_param('decision');
                $notes = $request->get_param('notes');
                $return = $this->processTermRequest($request_id, $decision, $notes, $userID);
                break;
            default:
                $return = [
                    'success'   => false,
                    'message'   => 'invalid action'
                ];
        }
        return new WP_REST_Response($return);
    }
 
 
    public function handleInvite(WP_REST_Request $request):WP_REST_Response
    {
 
    }
 
    public function requestEntry(int $userID, string $role, int $termID, string $taxonomy):bool
    {
        if (!$this->checkUser($userID) || !$this->checkTerm(['term_id' => $termID, 'taxonomy' => $taxonomy])) {
            return false;
        }
 
        $tableName = $this->wpdb->prefix . BASE . $role . '_' . $taxonomy . '_requests';
 
        //Check if request already exists
        $existing = $this->wpdb->get_var($this->wpdb->prepare(
            "SELECT id FROM {$tableName} WHERE user_id = %d AND term_id = %d",
            $userID,
            $termID
        ));
 
        if ($existing) {
            return false;
        }
 
        //get the user's profile id
        $profileID = get_user_meta($userID, BASE.'profile_link', true);
        if (!$profileID) {
            return false;
        }
 
        $result = $this->wpdb->insert(
            $tableName,
            [
                'user_id'       => $userID,
                'content_id'    => $profileID,
                'term_id'       => $termID,
                'status'        => 'requested',
                'created_date'  => current_time('mysql')
            ]
        );
 
        if ($result === false) {
            return false;
        }
 
        $this->notifyManagers($termID, $userID, $profileID);
        return true;
    }
 
    protected function notifyManagers(int $termID, int $userID, int $profileID):void
    {
        if (!$this->checkTerm(['term_id' => $termID, 'taxonomy' => $this->route]) || !$this->checkUser($userID)) {
            return;
        }
 
        $termMeta = Meta::forTerm($termID);
        $managers = explode(',', $termMeta->get('managers'));
        $owner = explode(',', $termMeta->get('owner'));
 
        $owners = array_unique(array_merge($managers, $owner));
 
        //Get requester's info
        $userName = get_the_title($profileID);
        $termName = get_term($termID, BASE.$this->route)->name;
 
 
        //Notify managers
        JVB()->notification()->addNotification(
            $owners,
            'entry_request',
            [
                'profile_id'    => $profileID,
                'user_name'     => $userName,
                'user_id'       => $userID,
                'term_id'       => $termID,
                'term_name'     => $termName
            ]
        );
 
    }
}