Files
wp-plugin-socialfeed/includes/sources.php
T

197 lines
7.3 KiB
PHP

<?php
if (!defined('ABSPATH')) exit;
const HGSF_POSTS_MAX = 24;
const HGSF_CACHE_LIFETIME = 2 * DAY_IN_SECONDS;
const HGSF_SOURCES = [
'instagram' => [
'label' => 'Instagram',
'connection' => 'hgsf_connection',
'snapshot' => 'hgsf_instagram_snapshot',
'schedule' => 'twicedaily',
'fetch' => 'hgsf_fetch_instagram',
],
'facebook' => [
'label' => 'Facebook',
'connection' => 'hgsf_facebook_connection',
'snapshot' => 'hgsf_facebook_snapshot',
'schedule' => 'twicedaily',
'fetch' => 'hgsf_fetch_facebook',
],
'x' => [
'label' => 'X',
'connection' => 'hgsf_x_connection',
'snapshot' => 'hgsf_x_snapshot',
'schedule' => 'daily',
'fetch' => 'hgsf_fetch_x',
],
];
function hgsf_connection(string $source = 'instagram'): array {
$stored = get_option(HGSF_SOURCES[$source]['connection'], []);
return (is_array($stored) ? $stored : []) + [
'id' => '',
'username' => '',
'token' => '',
'saved_at' => 0,
'enabled' => false,
'profile' => '',
];
}
function hgsf_snapshot(array $connection, string $source = 'instagram'): array {
$snapshot = get_option(HGSF_SOURCES[$source]['snapshot'], []);
return $connection['id'] && ($snapshot['connection_id'] ?? '') === $connection['id'] ? $snapshot : [];
}
function hgsf_cached_posts(array $connection, string $source = 'instagram'): array {
if ($source === 'x' && !$connection['enabled']) {
return [];
}
$snapshot = hgsf_snapshot($connection, $source);
$lifetime = $source === 'x' ? DAY_IN_SECONDS + HOUR_IN_SECONDS : HGSF_CACHE_LIFETIME;
return time() - ($snapshot['synced_at'] ?? 0) < $lifetime ? ($snapshot['posts'] ?? []) : [];
}
function hgsf_profile_url(string $source, array $connection): string {
$username = $connection['username'];
if ($source === 'facebook' && $connection['profile'] !== '') {
$username = $connection['profile'];
}
if ($username === '') {
return '';
}
return match ($source) {
'instagram' => 'https://www.instagram.com/' . rawurlencode($username) . '/',
'facebook' => 'https://www.facebook.com/' . rawurlencode($username),
'x' => 'https://x.com/' . rawurlencode($username),
};
}
function hgsf_with_connection_lock(callable $operation, string $source = 'instagram'): mixed {
global $wpdb;
// Serialize credential changes with WP-Cron for each source.
$name = 'hgsf_' . md5(DB_NAME . '/' . $wpdb->options . ($source === 'instagram' ? '' : '/' . $source));
$acquired = $wpdb->get_var($wpdb->prepare('SELECT GET_LOCK(%s, 0)', $name));
if ((int) $acquired !== 1) {
return new WP_Error('busy', 'Er loopt al een synchronisatie voor dit platform. Probeer het zo opnieuw.');
}
try {
return $operation();
} finally {
$wpdb->get_var($wpdb->prepare('SELECT RELEASE_LOCK(%s)', $name));
}
}
function hgsf_http_get(string $source, string $path, array $query, string $token): array|WP_Error {
$host = match ($source) {
'instagram' => 'graph.instagram.com',
'facebook' => 'graph.facebook.com',
'x' => 'api.x.com',
};
$headers = ['Accept' => 'application/json'];
if ($source === 'instagram') {
$query['access_token'] = $token;
} else {
$headers['Authorization'] = 'Bearer ' . $token;
}
$url = 'https://' . $host . '/' . $path . '?' . http_build_query($query, '', '&', PHP_QUERY_RFC3986);
$response = wp_safe_remote_get($url, [
'headers' => $headers,
'timeout' => 7,
'redirection' => 0,
'limit_response_size' => 256 * KB_IN_BYTES,
]);
$label = HGSF_SOURCES[$source]['label'];
if (is_wp_error($response)) {
return new WP_Error('unavailable', sprintf('%s is tijdelijk niet bereikbaar.', $label));
}
$status = (int) wp_remote_retrieve_response_code($response);
$data = json_decode(wp_remote_retrieve_body($response), true, 512, JSON_BIGINT_AS_STRING);
if ($status === 401 || (int) ($data['error']['code'] ?? 0) === 190) {
return new WP_Error('token', sprintf('%s heeft het toegangstoken geweigerd. Controleer of het nog geldig is.', $label));
}
if ($source === 'x' && $status === 402) {
return new WP_Error('credits', 'Controleer het beschikbare API-tegoed in de X Developer Console.');
}
if ($status === 429) {
return new WP_Error('rate_limit', sprintf('%s heeft de API-limiet bereikt. WordPress probeert het bij de volgende synchronisatie opnieuw.', $label));
}
if ($status !== 200 || !is_array($data) || isset($data['error']) || (!isset($data['data']) && !empty($data['errors']))) {
return new WP_Error('api', sprintf('%s heeft het verzoek geweigerd. Controleer de accounttoegang.', $label));
}
return $data;
}
function hgsf_valid_token($token, string $source = 'instagram'): bool {
$pattern = $source === 'x' ? '~^[A-Za-z0-9._\~+/%-]+=*$~D' : '~^[A-Za-z0-9._\~+/-]+=*$~D';
return is_string($token) && strlen($token) <= 2048 && preg_match($pattern, $token) === 1;
}
function hgsf_media_url($url, string $suffix_pattern): string {
if (!is_string($url)) {
return '';
}
$url = esc_url_raw($url, ['https']);
$parts = wp_parse_url($url);
if (($parts['scheme'] ?? '') !== 'https'
|| isset($parts['user']) || isset($parts['pass']) || isset($parts['port'])
|| !preg_match($suffix_pattern, $parts['host'] ?? '')) {
return '';
}
return $url;
}
function hgsf_sort_posts(array $posts): array {
usort($posts, static fn (array $a, array $b): int => $b['date'] <=> $a['date']);
return $posts;
}
function hgsf_sync_source(string $source): bool|WP_Error {
return hgsf_with_connection_lock(static fn () => hgsf_update_snapshot(hgsf_connection($source), $source), $source);
}
function hgsf_update_snapshot(array $connection, string $source = 'instagram'): bool|WP_Error {
if (!$connection['token'] || ($source === 'x' && !$connection['enabled'])) {
return new WP_Error('disconnected', 'Voor dit platform is synchronisatie niet ingeschakeld.');
}
$snapshot = hgsf_snapshot($connection, $source);
$now = time();
$fetch = HGSF_SOURCES[$source]['fetch'];
$result = $fetch($connection, $snapshot, $now);
$snapshot['connection_id'] = $connection['id'];
$snapshot['attempted_at'] = $now;
$snapshot['error'] = '';
if (is_wp_error($result)) {
$snapshot['error'] = $result->get_error_message();
if (in_array($result->get_error_code(), ['private', 'account'], true)) {
unset($snapshot['posts'], $snapshot['synced_at']);
}
} else {
$snapshot['posts'] = array_slice(hgsf_sort_posts($result), 0, HGSF_POSTS_MAX);
$snapshot['synced_at'] = $now;
}
update_option(HGSF_SOURCES[$source]['snapshot'], $snapshot, false);
return is_wp_error($result) ? $result : true;
}
function hgsf_schedule_events(): void {
$ready = true;
foreach (HGSF_SOURCES as $source => $provider) {
$hook = 'hgsf_sync_' . $source;
if (!wp_next_scheduled($hook) && !wp_schedule_event(time() + MINUTE_IN_SECONDS, $provider['schedule'], $hook)) {
$ready = false;
}
}
if ($ready) {
update_option('hgsf_cron_version', HGSF_VERSION, false);
}
}