$link, 'image' => $image, 'type' => $type, 'caption' => is_string($caption) ? wp_html_excerpt(sanitize_text_field($caption), 140, '…') : '', 'date' => (is_string($timestamp) ? strtotime($timestamp) : false) ?: 0, ]; } return array_values($posts); } function hgsf_sync_instagram(): bool|WP_Error { return hgsf_sync_source('instagram'); } function hgsf_fetch_instagram(array $connection, array &$snapshot, int $now): array|WP_Error { $token = $snapshot['refreshed_token'] ?? $connection['token']; // Meta accepts a renewal once the token is at least one day old. $refresh_at = $snapshot['refresh_at'] ?? ($connection['saved_at'] + DAY_IN_SECONDS); if ($now >= $refresh_at) { $renewed = hgsf_http_get('instagram', 'refresh_access_token', ['grant_type' => 'ig_refresh_token'], $token); $snapshot['refresh_failed'] = true; if (!is_wp_error($renewed) && hgsf_valid_token($renewed['access_token'] ?? null) && (int) ($renewed['expires_in'] ?? 0) > DAY_IN_SECONDS) { $token = $renewed['access_token']; $snapshot['refreshed_token'] = $token; $snapshot['expires_at'] = $now + (int) $renewed['expires_in']; $snapshot['refresh_at'] = max($now + DAY_IN_SECONDS, $snapshot['expires_at'] - 14 * DAY_IN_SECONDS); $snapshot['refresh_failed'] = false; } } $profile = hgsf_http_get('instagram', HGSF_INSTAGRAM_VERSION . '/me', ['fields' => 'user_id,username'], $token); $result = $profile; if (!is_wp_error($profile)) { $account = $profile['data'][0] ?? $profile; $user_id = $account['user_id'] ?? ''; $username = $account['username'] ?? ''; if (!is_string($username) || strcasecmp($username, $connection['username']) !== 0 || (!is_int($user_id) && !is_string($user_id)) || !ctype_digit((string) $user_id)) { $result = new WP_Error('account', 'Het toegangstoken hoort niet bij de ingestelde Instagram-gebruikersnaam.'); } else { $result = hgsf_http_get('instagram', HGSF_INSTAGRAM_VERSION . '/' . $user_id . '/media', [ 'fields' => 'id,media_type,media_url,thumbnail_url,permalink,caption,timestamp', 'limit' => HGSF_POSTS_MAX, ], $token); if (!is_wp_error($result) && !is_array($result['data'] ?? null)) { $result = new WP_Error('api', 'Instagram heeft geen leesbare berichtenlijst teruggegeven.'); } } } return is_wp_error($result) ? $result : hgsf_instagram_posts($result['data']); }