Jake Vanderwerf
2026-08-07 a8ff85042ffbfe94b678fd818c02deb613bfd116
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
<?php
/**
 * Facebook Integration
 * Handles Facebook posts, page information, events, and OAuth authentication
 */
 
namespace JVBase\integrations\services;
use Exception;
use JVBase\integrations\Admin;
use JVBase\integrations\Instance;
use JVBase\integrations\Integrations;
use JVBase\integrations\OAuth;
use JVBase\integrations\OAuthCredentials;
use JVBase\integrations\OAuthURLs;
use JVBase\integrations\Requests;
use JVBase\integrations\SyncDefaults;
use JVBase\integrations\SyncFrom;
use JVBase\integrations\SyncTo;
use JVBase\integrations\UserConnection;
use WP_Error;
 
if (!defined('ABSPATH')) {
    exit;
}
 
class Facebook extends Integrations
{
    use Admin,
        Instance,
        OAuth,
        UserConnection,
        Requests,
        SyncFrom,
        SyncTo,
        SyncDefaults;
 
    protected function __construct()
    {
        $this->service_name = 'facebook';
        $this->title = 'Facebook';
        $this->icon = 'facebook-logo';
 
        $this->apiVersion = 'v25.0';
 
        $this->canSync = [
            'create'    => true,
            'update'    => true,
            'delete'    => true
        ];
 
        $this->defineFields();
        $this->defineInstructions();
        $this->defineOAuth();
        $this->defineActions();
 
        $this->baseUrl = 'https://graph.facebook.com/'.$this->apiVersion;
        $this->baseOAuthUrl = 'https://www.facebook.com/'.$this->apiVersion;
 
        parent::__construct();
    }
 
        protected function defineFields():void
        {
            $client_id = $this->addField(
                'client_id',
                'App ID',
                'text',
                'manage_options'
            );
                $client_id->setRequired();
                $client_id->setHint('Your Facebook App ID from developers.facebook.com');
 
            $client_secret = $this->addField(
                'client_secret',
                'App Secret',
                'text',
                'manage_options'
            );
                $client_secret->setRequired();
                $client_secret->setSubType('password');
 
            $pages = $this->addField('pages', 'Pages', 'select', [$this, 'testUserCanConnect']);
                $pages->setHidden();
                $pages->setOptions($this->getPageOptions());
 
            $page = $this->addField('page_id', 'Connect to Page', 'select', [$this, 'testUserCanConnect']);
                $page->setOptions($this->loadCredentials()['pages']??[]);
                $page->setHint('Select the page you want to connect this site to.');
        }
            public function testUserCanConnect():bool
            {
                $user = get_current_user_id();
                return $this->userCanConnect($user);
            }
            protected function getPageOptions():array
            {
                return $this->loadCredentials()['pages']??[];
            }
        protected function defineInstructions():void
        {
 
        }
        protected function defineActions():void
        {
            $this->addAction(
                'Select Page',
                [$this, 'handleSelectPage'],
                'select_page',
                'plugs-connected'
            );
 
            $this->addAction(
                'Fetch Pages',
                [$this, 'getPages'],
                'fetch_pages',
                'download-simple'
            );
        }
        public function defineOAuth():void
        {
            $this->oauth = new OAuthURLs(
                'https://www.facebook.com/'.$this->apiVersion.'/dialog/oauth',
                'https://graph.facebook.com/'.$this->apiVersion.'/oauth/access_token',
                'https://graph.facebook.com/'.$this->apiVersion.'/me/permissions'
            );
            $this->oathScopes = [
                'pages_show_list',
                'business_management',
                'pages_manage_metadata',
                'pages_manage_posts'
            ];
        }
        public function getServiceDescription():string
        {
            return 'Connect your Facebook Page to share posts, events, and engage with your audience.';
        }
    protected function initialize(): void
    {
        // TODO: Implement initialize() method.
    }
 
    protected function refreshAccessToken(OAuthCredentials $credentials): array
    {
        return $this->response(false, 'Not set up yet');
    }
 
    protected function getRequestHeaders(): array
    {
        return [
            'Content-Type' => 'application/json',
            'Accept' => 'application/json'
        ];
    }
 
 
    protected function handleResponse(\WP_Error|array $response, string $method, string $endpoint): array
    {
        if (is_wp_error($response) && $response->get_error_message() === 'rate_limit_exceeded') {
            return $this->response(false, 'Rate limit exceeded');
        }
 
        $endpoint = str_replace($this->baseUrl, '', $endpoint);
        return match ($endpoint) {
            '/me/accounts?access_token='.$this->getAccessToken()    => $this->handleGetPagesResponse($response, $method),
            default => $this->response(false, 'Unhandled Response for ' . $endpoint . ' endpoint, with method: ' . $method),
        };
    }
    /************************************************************
     * UTILITY METHODS
    ************************************************************/
    protected function getPageID():string|false
    {
        return $this->loadCredentials()['page_id']??false;
    }
    protected function getClientID():string|false
    {
        return $this->loadCredentials()['client_id']??false;
    }
    protected function getClientSecret():string|false
    {
        return $this->loadCredentials()['client_secret']??false;
    }
 
    protected function getFBUserID():string|false
    {
        $cred = $this->loadCredentials();
        if ($this->isSetUp() && !array_key_exists('user_id', $cred)) {
            $resp = $this->getRequest(
                $this->baseUrl.'/me?access_token='.$cred['access_token'],
            );
            if ($resp && !is_wp_error($resp)) {
                $tmp['user_id'] = $resp['id'];
                $tmp['user_name'] = $resp['name'];
 
                $this->saveCredentials($tmp, false);
            }
            $cred = array_merge($cred, $tmp);
        }
        return $cred['user_id']??false;
    }
    public function getPages():array|false
    {
        if (!$this->getAccessToken()) {
            return false;
        }
 
        try {
            return $this->getRequest(
                $this->apiBase.'/me/accounts?access_token='.$this->getAccessToken(),
            );
        } catch (Exception $e) {
            $this->logError(
                'getPages',
                'Failed to load pages',
                [
                    'error' => $e->getMessage(),
                ]
            );
        }
        return [];
    }
        protected function handleGetPagesResponse(WP_Error|array $response, string $method):array
        {
            $options = [];
            foreach ($response as $page) {
                if (array_key_exists('id', $page) && array_key_exists('name', $page)) {
                    $options[$page['id']] = $page['name'];
                }
            }
            if (!empty($options)) {
                $this->saveCredentials(['pages' => $options]);
            }
            return $this->response(true, 'Found pages', $options);
        }
 
    /************************************************************
     * ACTIONS
    ************************************************************/
    public function handleSelectPage(array $data):array
    {
        if (empty($data['page_id']??'')) {
            return $this->response(false, 'No page selected.');
        }
 
        $cred = [
            'page_id'   => sanitize_text_field($data['page_id']),
        ];
        return $this->saveCredentials($cred, false);
    }
 
    public function handleFetchPages():array
    {
        try {
            $pages = $this->getPages();
            if (!$pages) {
                return $this->response(false, 'No pages found');
            }
 
            return $this->response(
                true,
                sprintf('Found %d page(s)', count($pages)),
                $pages
            );
        } catch (Exception $e) {
            return $this->response(false, 'Failed to fetch pages: '.$e->getMessage());
        }
    }
 
    protected function setContentTypes(): void
    {
        // TODO: Implement setContentTypes() method.
    }
 
    protected function formatForService(int $itemID, string $type = 'post'): array
    {
        return [];
    }
}