Consolidate HG WordPress plugins

This commit is contained in:
parkel committed 2026-11-18 01:22:22 +01:00
commit dccb8ed9bd
18 files changed
+1701

No files matched your search

+209
View File
@@ -0,0 +1,209 @@
<?php
if (!defined('ABSPATH')) exit;
HG_Plugin_Admin::register([
'slug' => 'hg-socialfeed',
'label' => 'Social Feed',
'title' => 'HG Social Feed',
'description' => 'Toon berichten en profiellinks van Instagram, Facebook en X.',
'version' => HGSF_VERSION,
'callback' => 'hgsf_admin_page',
]);
function hgsf_admin_page(): void {
if (!current_user_can('manage_options')) {
wp_die('Geen toegang.', '', ['response' => 403]);
}
$notice = match ($_GET['hgsf_notice'] ?? '') {
'saved' => ['success', 'Instellingen opgeslagen.'],
'synced' => ['success', 'Berichten opgehaald.'],
'failed' => ['error', 'Het ophalen is mislukt. Bekijk de status van het platform.'],
'invalid' => ['error', 'Controleer het profiel en het toegangstoken van het platform.'],
'busy' => ['error', 'Er loopt al een synchronisatie voor dit platform. Probeer het zo opnieuw.'],
'disconnected' => ['success', 'Toegangstoken en opgeslagen berichten verwijderd. De profiellink blijft beschikbaar.'],
default => null,
};
?>
<div class="wrap hg-suite">
<header class="hg-suite-header">
<span class="hg-suite-mark" aria-hidden="true">HG</span>
<div><h1>HG Social Feed</h1><p>Beheer de bronnen voor berichten en profieliconen.</p></div>
</header>
<?php if ($notice) : ?>
<div class="notice notice-<?php echo esc_attr($notice[0]); ?>"><p><?php echo esc_html($notice[1]); ?></p></div>
<?php endif; ?>
<div class="hg-suite-grid">
<?php foreach (HGSF_SOURCES as $source => $provider) :
hgsf_admin_source($source, $provider['label']);
endforeach; ?>
</div>
<h2>Plaatsen op de website</h2>
<p><code>[hg_socialfeed]</code> toont de recentste berichten en links naar de profielen.</p>
<p><code>[hg_sociallinks]</code> toont alleen de iconenbalk met links naar de ingestelde profielen.</p>
<p>Beperk desgewenst de bronnen met <code>sources="instagram,facebook"</code>.</p>
</div>
<?php
}
function hgsf_admin_source(string $source, string $label): void {
$connection = hgsf_connection($source);
$snapshot = hgsf_snapshot($connection, $source);
$field = $source === 'facebook' ? 'Pagina-ID' : 'Gebruikersnaam';
$help = match ($source) {
'instagram' => [
'Gebruik een langlevend Instagram-toegangstoken uit het Meta App Dashboard.',
'https://developers.facebook.com/documentation/instagram-platform/instagram-api-with-instagram-login/get-started',
],
'facebook' => [
'Gebruik een paginatoegangstoken voor een Facebook-pagina die je beheert.',
'https://developers.facebook.com/docs/graph-api/reference/page/published_posts',
],
'x' => [
'Gebruik het app-only Bearer Token uit de X Developer Console.',
'https://docs.x.com/x-api/getting-started/pricing',
],
};
$can_sync = $connection['token'] && ($source !== 'x' || $connection['enabled']);
?>
<section class="hg-suite-card">
<h2><?php echo esc_html($label); ?></h2>
<form action="<?php echo esc_url(admin_url('admin-post.php')); ?>" method="post">
<input type="hidden" name="action" value="hgsf_settings">
<input type="hidden" name="source" value="<?php echo esc_attr($source); ?>">
<?php wp_nonce_field('hgsf_settings_' . $source, 'hgsf_nonce_' . $source); ?>
<p>
<label for="hgsf-<?php echo esc_attr($source); ?>-username"><?php echo esc_html($field); ?></label><br>
<input type="text" id="hgsf-<?php echo esc_attr($source); ?>-username" name="username" maxlength="31"
value="<?php echo esc_attr($connection['username']); ?>" autocapitalize="none" spellcheck="false">
</p>
<?php if ($source === 'facebook') : ?>
<p>
<label for="hgsf-facebook-profile">Paginanaam in de URL</label><br>
<input type="text" id="hgsf-facebook-profile" name="profile" maxlength="75"
value="<?php echo esc_attr($connection['profile']); ?>" autocapitalize="none" spellcheck="false">
<br><span class="description">Optioneel voor de profiellink. Bijvoorbeeld mijnbedrijf uit facebook.com/mijnbedrijf.</span>
</p>
<?php endif; ?>
<p>
<label for="hgsf-<?php echo esc_attr($source); ?>-token">Toegangstoken</label><br>
<input type="password" id="hgsf-<?php echo esc_attr($source); ?>-token" name="token" autocomplete="new-password"
maxlength="2048" aria-describedby="hgsf-<?php echo esc_attr($source); ?>-token-help">
<br><span class="description" id="hgsf-<?php echo esc_attr($source); ?>-token-help">
<?php echo esc_html($connection['token'] ? 'Laat leeg om het huidige token voor dit account te behouden.' : $help[0]); ?>
<a href="<?php echo esc_url($help[1]); ?>">Documentatie</a>
</span>
</p>
<?php if ($source === 'x') : ?>
<p><label><input type="checkbox" name="enabled" value="1" <?php checked($connection['enabled']); ?>>
X-berichten automatisch ophalen. X rekent per API-gebruik.</label></p>
<?php endif; ?>
<p>
<button type="submit" name="operation" value="save" class="button button-primary">Opslaan</button>
<?php if ($can_sync) : ?>
<button type="submit" name="operation" value="sync" class="button">Nu synchroniseren</button>
<?php endif; ?>
<?php if ($connection['token']) : ?>
<button type="submit" name="operation" value="disconnect" class="button">Koppeling verwijderen</button>
<?php endif; ?>
</p>
</form>
<?php if (!$can_sync) : ?>
<p>Automatisch ophalen staat uit.</p>
<?php elseif (!empty($snapshot['error'])) : ?>
<p><?php echo esc_html($snapshot['error']); ?></p>
<?php elseif (!empty($snapshot['synced_at'])) : ?>
<p><?php echo esc_html(sprintf('Laatste geslaagde synchronisatie op %s. Opgehaalde berichten: %d.', wp_date('j F Y H:i', $snapshot['synced_at']), count($snapshot['posts']))); ?></p>
<?php else : ?>
<p>De eerste synchronisatie staat nog open.</p>
<?php endif; ?>
<?php if (!empty($snapshot['refresh_failed'])) : ?>
<p>Het token kon nog niet automatisch worden verlengd. WordPress probeert het bij de volgende synchronisatie opnieuw.</p>
<?php endif; ?>
</section>
<?php
}
function hgsf_handle_settings(): void {
if (!current_user_can('manage_options')) {
wp_die('Geen toegang.', '', ['response' => 403]);
}
$source = $_POST['source'] ?? '';
if (!is_string($source) || !isset(HGSF_SOURCES[$source])) {
wp_die('Ongeldig platform.', '', ['response' => 400]);
}
check_admin_referer('hgsf_settings_' . $source, 'hgsf_nonce_' . $source);
$result = hgsf_with_connection_lock(static fn () => hgsf_save_settings($source, $_POST), $source);
$notice = is_wp_error($result) ? 'busy' : $result;
wp_safe_redirect(add_query_arg(['page' => 'hg-socialfeed', 'hgsf_notice' => $notice], admin_url('admin.php')));
exit;
}
function hgsf_save_settings(string $source, array $input): string {
$connection = hgsf_connection($source);
$provider = HGSF_SOURCES[$source];
$operation = $input['operation'] ?? '';
if ($operation === 'disconnect') {
$connection['id'] = wp_generate_uuid4();
$connection['token'] = '';
$connection['saved_at'] = 0;
$connection['enabled'] = false;
update_option($provider['connection'], $connection, false);
delete_option($provider['snapshot']);
return 'disconnected';
}
if ($operation === 'sync') {
return is_wp_error(hgsf_update_snapshot($connection, $source)) ? 'failed' : 'synced';
}
if ($operation !== 'save') {
return 'invalid';
}
$username = $input['username'] ?? '';
$token = $input['token'] ?? '';
$profile = $source === 'facebook' ? ($input['profile'] ?? '') : '';
if (!is_string($username) || !is_string($token) || !is_string($profile)) {
return 'invalid';
}
$username = strtolower(ltrim(trim(wp_unslash($username)), '@'));
$token = trim(wp_unslash($token));
$profile = trim(wp_unslash($profile));
$enabled = $source === 'x' && ($input['enabled'] ?? '') === '1';
$pattern = match ($source) {
'instagram' => '/^[a-z0-9._]{1,30}$/D',
'facebook' => '/^[0-9]{1,30}$/D',
'x' => '/^[a-z0-9_]{1,15}$/D',
};
if (($username !== '' && !preg_match($pattern, $username))
|| ($profile !== '' && !preg_match('/^[a-z0-9.]{1,75}$/iD', $profile))
|| ($token !== '' && ($username === '' || !hgsf_valid_token($token, $source)))) {
return 'invalid';
}
$credentials_changed = $username !== $connection['username'] || $token !== '';
$enable_changed = $enabled !== $connection['enabled'];
if ($enabled && ($username === '' || ($token === '' && ($credentials_changed || !$connection['token'])))) {
return 'invalid';
}
if ($credentials_changed) {
$connection['id'] = wp_generate_uuid4();
$connection['username'] = $username;
$connection['token'] = $token;
$connection['saved_at'] = time();
}
$connection['profile'] = $profile;
$connection['enabled'] = $enabled;
update_option($provider['connection'], $connection, false);
if ($credentials_changed || $enable_changed) {
delete_option($provider['snapshot']);
if ($connection['token'] && ($source !== 'x' || $enabled)) {
return is_wp_error(hgsf_update_snapshot($connection, $source)) ? 'failed' : 'synced';
}
}
return 'saved';
}
add_action('admin_post_hgsf_settings', 'hgsf_handle_settings');
+74
View File
@@ -0,0 +1,74 @@
<?php
if (!defined('ABSPATH')) exit;
const HGSF_FACEBOOK_VERSION = 'v27.0';
function hgsf_facebook_permalink($url): string {
if (!is_string($url)) {
return '';
}
$parts = wp_parse_url(esc_url_raw($url, ['https']));
$path = $parts['path'] ?? '';
if (($parts['scheme'] ?? '') !== 'https'
|| !in_array($parts['host'] ?? '', ['www.facebook.com', 'facebook.com', 'm.facebook.com'], true)
|| !preg_match('~^/(?:[a-z0-9.]+/)?(?:(?:posts|videos|reels?|photos)/[a-z0-9_.-]+|story\.php|permalink\.php|photo(?:\.php)?|watch)/?$~iD', $path)) {
return '';
}
$query = [];
parse_str($parts['query'] ?? '', $query);
$query = array_filter(
array_intersect_key($query, array_flip(['id', 'v', 'story_fbid', 'fbid'])),
static fn ($value): bool => is_string($value) && preg_match('/^[a-z0-9_-]+$/iD', $value) === 1
);
return 'https://www.facebook.com' . $path . ($query ? '?' . http_build_query($query, '', '&', PHP_QUERY_RFC3986) : '');
}
function hgsf_fetch_facebook(array $connection): array|WP_Error {
$token = $connection['token'];
$page = hgsf_http_get('facebook', HGSF_FACEBOOK_VERSION . '/me', [
'fields' => 'id,is_published',
], $token);
if (is_wp_error($page)) {
return $page;
}
$page_id = $page['id'] ?? '';
if ((!is_string($page_id) && !is_int($page_id)) || (string) $page_id !== $connection['username']) {
return new WP_Error('account', 'Het Facebook-paginatoken hoort niet bij het ingestelde pagina-ID.');
}
if (($page['is_published'] ?? null) !== true) {
return new WP_Error('private', 'De Facebook-pagina is niet openbaar gepubliceerd.');
}
$response = hgsf_http_get('facebook', HGSF_FACEBOOK_VERSION . '/' . $connection['username'] . '/published_posts', [
'fields' => 'permalink_url,message,full_picture,created_time,is_hidden,is_published,is_expired',
'limit' => HGSF_POSTS_MAX,
], $token);
if (is_wp_error($response)) {
return $response;
}
if (!is_array($response['data'] ?? null)) {
return new WP_Error('api', 'Facebook heeft geen leesbare berichtenlijst teruggegeven.');
}
$posts = [];
foreach ($response['data'] as $post) {
$link = hgsf_facebook_permalink($post['permalink_url'] ?? null);
if (!$link || !empty($post['is_hidden']) || !empty($post['is_expired']) || ($post['is_published'] ?? true) !== true) {
continue;
}
$image = hgsf_media_url($post['full_picture'] ?? null, '/(?:^|\.)(fbcdn\.net|fbsbx\.com)$/iD');
$message = $post['message'] ?? '';
$timestamp = $post['created_time'] ?? '';
$caption = is_string($message) ? sanitize_text_field($message) : '';
$posts[$link] = [
'link' => $link,
'image' => $image,
'caption' => wp_html_excerpt($caption, 180, '…'),
'type' => $image ? 'IMAGE' : 'TEXT',
'date' => (is_string($timestamp) ? strtotime($timestamp) : false) ?: 0,
];
}
return array_values($posts);
}
+52
View File
@@ -0,0 +1,52 @@
<?php
/**
* HG admin navigation, bundled identically in each standalone HG plugin.
* Shared component version: 1.0.0. Update both copies together.
*/
if (!defined('ABSPATH')) exit;
if (!class_exists('HG_Plugin_Admin', false)) {
final class HG_Plugin_Admin {
private static array $plugins = [];
private static array $hooks = [];
public static function register(array $plugin): void {
self::$plugins[$plugin['slug']] = $plugin;
}
public static function hook(string $slug): string {
return self::$hooks[$slug] ?? '';
}
public static function menu(): void {
if (!self::$plugins) return;
add_menu_page('HG Plugins', 'HG Plugins', 'manage_options', 'hg-plugins', [self::class, 'overview'], 'dashicons-screenoptions', 58);
add_submenu_page('hg-plugins', 'HG Plugins', 'Overzicht', 'manage_options', 'hg-plugins', [self::class, 'overview']);
uasort(self::$plugins, fn($a, $b) => strcasecmp($a['label'], $b['label']));
foreach (self::$plugins as $slug => $plugin) {
self::$hooks[$slug] = (string) add_submenu_page('hg-plugins', $plugin['title'], $plugin['label'], 'manage_options', $slug, $plugin['callback']);
}
}
public static function styles(): void {
if (!self::$plugins || !current_user_can('manage_options')) return;
wp_enqueue_style('hg-admin-menu', plugins_url('../assets/hg-admin-menu.css', __FILE__), [], '1.0.0');
}
public static function overview(): void {
if (!current_user_can('manage_options')) wp_die('Geen toegang.', '', ['response' => 403]);
?>
<div class="wrap hg-suite">
<header class="hg-suite-header"><span class="hg-suite-mark" aria-hidden="true">HG</span><div><h1>HG Plugins</h1><p>De Hippogrief-modules op deze website.</p></div></header>
<div class="hg-suite-grid">
<?php foreach (self::$plugins as $slug => $plugin): ?>
<section class="hg-suite-card"><span class="hg-suite-version">Versie <?php echo esc_html($plugin['version']); ?></span><h2><?php echo esc_html($plugin['title']); ?></h2><p><?php echo esc_html($plugin['description']); ?></p><a class="button button-primary" href="<?php echo esc_url(add_query_arg('page', $slug, admin_url('admin.php'))); ?>">Beheren</a></section>
<?php endforeach; ?>
</div>
</div>
<?php
}
}
add_action('admin_menu', [HG_Plugin_Admin::class, 'menu'], 20);
add_action('admin_enqueue_scripts', [HG_Plugin_Admin::class, 'styles']);
}
+91
View File
@@ -0,0 +1,91 @@
<?php
if (!defined('ABSPATH')) exit;
const HGSF_INSTAGRAM_VERSION = 'v27.0';
function hgsf_instagram_posts(array $media): array {
$posts = [];
foreach ($media as $item) {
if (!is_array($item)) {
continue;
}
$type = $item['media_type'] ?? '';
if (!in_array($type, ['IMAGE', 'CAROUSEL_ALBUM', 'VIDEO'], true)) {
continue;
}
$link = $item['permalink'] ?? '';
$image = $item[$type === 'VIDEO' ? 'thumbnail_url' : 'media_url'] ?? '';
if (!is_string($link) || !is_string($image)) {
continue;
}
$link = esc_url_raw($link, ['https']);
$parts = wp_parse_url($link);
if (($parts['scheme'] ?? '') !== 'https'
|| !in_array($parts['host'] ?? '', ['www.instagram.com', 'instagram.com'], true)
|| !preg_match('~^/(p|reel|tv)/[A-Za-z0-9_-]+/?$~D', $parts['path'] ?? '')) {
continue;
}
$image = hgsf_media_url($image, '/(?:^|\.)(cdninstagram\.com|fbcdn\.net)$/iD');
if (!$image) {
continue;
}
$caption = $item['caption'] ?? '';
$timestamp = $item['timestamp'] ?? '';
// Store the canonical link independently of Instagram's tracking parameters.
$link = 'https://www.instagram.com' . $parts['path'];
$posts[$link] = [
'link' => $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']);
}
+145
View File
@@ -0,0 +1,145 @@
<?php
if (!defined('ABSPATH')) exit;
function hgsf_shortcode_sources(array $attributes): array {
$filter = array_map('trim', explode(',', strtolower($attributes['sources'])));
return array_intersect_key(HGSF_SOURCES, array_flip($filter));
}
function hgsf_shortcode($attributes = []): string {
$attributes = shortcode_atts(['limit' => 8, 'sources' => implode(',', array_keys(HGSF_SOURCES))], (array) $attributes, 'hg_socialfeed');
$limit = max(1, min(HGSF_POSTS_MAX, (int) $attributes['limit']));
$posts = [];
$profiles = [];
foreach (hgsf_shortcode_sources($attributes) as $source => $provider) {
$connection = hgsf_connection($source);
$profile_url = hgsf_profile_url($source, $connection);
if ($profile_url) {
$profiles[$source] = $profile_url;
}
foreach (hgsf_cached_posts($connection, $source) as $post) {
$posts[] = ['source' => $source] + $post;
}
}
if (!$profiles) {
return '';
}
$posts = array_slice(hgsf_sort_posts($posts), 0, HGSF_POSTS_MAX);
hgsf_feed_styles();
if (count($posts) > $limit) {
wp_enqueue_script('hg-socialfeed', plugins_url('assets/feed.js', HGSF_PLUGIN_FILE), [], HGSF_VERSION, ['in_footer' => true]);
}
if (in_array('x', array_column($posts, 'source'), true)) {
wp_enqueue_script('hg-socialfeed-x', 'https://platform.twitter.com/widgets.js', [], null, ['in_footer' => true, 'strategy' => 'async']);
}
$grid_id = wp_unique_id('hgsf-grid-');
ob_start();
?>
<div class="hgsf-feed" data-hgsf-limit="<?php echo esc_attr($limit); ?>">
<?php if ($posts) : ?>
<ul class="hgsf-grid" id="<?php echo esc_attr($grid_id); ?>" aria-label="Recente berichten op sociale media">
<?php foreach ($posts as $post) : ?>
<li tabindex="-1"<?php echo $post['source'] === 'x' ? ' class="hgsf-x-tile"' : ''; ?>>
<?php hgsf_render_post($post, count($profiles) > 1); ?>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
<div class="hgsf-actions">
<?php if (count($posts) > $limit) : ?>
<button type="button" class="hgsf-more" aria-controls="<?php echo esc_attr($grid_id); ?>" hidden>Meer berichten</button>
<?php endif; ?>
<?php foreach ($profiles as $source => $url) : ?>
<a class="hgsf-profile" href="<?php echo esc_url($url); ?>">Volg ons op <?php echo esc_html(HGSF_SOURCES[$source]['label']); ?> <span aria-hidden="true">↗</span></a>
<?php endforeach; ?>
</div>
</div>
<?php
return (string) ob_get_clean();
}
function hgsf_render_post(array $post, bool $show_source): void {
$source = $post['source'];
$platform = HGSF_SOURCES[$source]['label'];
$date = $post['date'] ? wp_date(get_option('date_format'), $post['date']) : '';
if ($source === 'x') : ?>
<blockquote class="twitter-tweet hgsf-x-embed" data-dnt="true" data-lang="<?php echo esc_attr(strtok(get_locale(), '_')); ?>">
<a href="<?php echo esc_url($post['link']); ?>">Bekijk bericht op X<?php echo $date ? esc_html(' · ' . $date) : ''; ?></a>
</blockquote>
<?php
return;
endif;
$label = match ($post['type']) {
'VIDEO' => 'Bekijk de video',
'CAROUSEL_ALBUM' => 'Bekijk de foto’s',
default => 'Bekijk het bericht',
};
$label .= ' op ' . $platform;
$has_image = $post['image'] !== '';
?>
<a class="hgsf-post<?php echo $has_image ? '' : ' hgsf-text-post'; ?>" href="<?php echo esc_url($post['link']); ?>"
<?php if ($has_image) : ?>aria-label="<?php echo esc_attr(trim($label . '. ' . $post['caption'])); ?>"<?php endif; ?>>
<?php if ($has_image) : ?>
<img src="<?php echo esc_url($post['image']); ?>" alt="" width="400" height="400" loading="lazy" decoding="async" referrerpolicy="no-referrer">
<?php if ($post['type'] === 'VIDEO') : ?>
<span class="hgsf-video" aria-hidden="true">&#9654;</span>
<?php endif; ?>
<?php if ($show_source) : ?>
<span class="hgsf-platform" aria-hidden="true"><?php echo esc_html($platform); ?></span>
<?php endif; ?>
<?php else : ?>
<span class="hgsf-text-platform"><?php echo esc_html($platform); ?></span>
<span><?php echo esc_html($post['caption'] ?: $label); ?></span>
<span class="hgsf-text-date"><?php echo esc_html($date); ?></span>
<?php endif; ?>
</a>
<?php
}
function hgsf_feed_styles(): void {
wp_enqueue_style('hg-socialfeed', plugins_url('assets/feed.css', HGSF_PLUGIN_FILE), [], HGSF_VERSION);
}
function hgsf_sociallinks_shortcode($attributes = []): string {
$attributes = shortcode_atts(['sources' => implode(',', array_keys(HGSF_SOURCES))], (array) $attributes, 'hg_sociallinks');
$links = [];
foreach (hgsf_shortcode_sources($attributes) as $source => $provider) {
$url = hgsf_profile_url($source, hgsf_connection($source));
if ($url) {
$links[$source] = $url;
}
}
if (!$links) {
return '';
}
hgsf_feed_styles();
ob_start();
?>
<ul class="hgsf-sociallinks" aria-label="Sociale media">
<?php foreach ($links as $source => $url) : ?>
<li><a href="<?php echo esc_url($url); ?>" aria-label="<?php echo esc_attr(HGSF_SOURCES[$source]['label']); ?>"><?php hgsf_social_icon($source); ?></a></li>
<?php endforeach; ?>
</ul>
<?php
return (string) ob_get_clean();
}
function hgsf_social_icon(string $source): void {
?>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
<?php if ($source === 'instagram') : ?>
<rect x="3" y="3" width="18" height="18" rx="5" fill="none" stroke="currentColor" stroke-width="2"/>
<circle cx="12" cy="12" r="4" fill="none" stroke="currentColor" stroke-width="2"/>
<circle cx="17.5" cy="6.5" r="1.2" fill="currentColor"/>
<?php elseif ($source === 'facebook') : ?>
<path fill="currentColor" d="M24 12a12 12 0 1 0-13.875 11.854v-8.385H7.078V12h3.047V9.356c0-3.007 1.792-4.669 4.532-4.669 1.313 0 2.686.235 2.686.235v2.953H15.83c-1.49 0-1.955.925-1.955 1.874V12h3.328l-.532 3.469h-2.796v8.385A12 12 0 0 0 24 12Z"/>
<?php else : ?>
<path fill="currentColor" d="M18.901 1.153h3.68l-8.04 9.19L24 22.846h-7.406l-5.8-7.584-6.64 7.584H.47l8.6-9.835L0 1.154h7.594l5.243 6.932 6.064-6.933Zm-1.29 19.492h2.039L6.488 3.24H4.3Z"/>
<?php endif; ?>
</svg>
<?php
}
+196
View File
@@ -0,0 +1,196 @@
<?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);
}
}
+53
View File
@@ -0,0 +1,53 @@
<?php
if (!defined('ABSPATH')) exit;
function hgsf_fetch_x(array $connection): array|WP_Error {
$token = $connection['token'];
$handle = $connection['username'];
$response = hgsf_http_get('x', '2/users/by/username/' . rawurlencode($handle), [
'user.fields' => 'protected',
], $token);
if (is_wp_error($response)) {
return $response;
}
$account = $response['data'] ?? [];
$id = $account['id'] ?? '';
$username = $account['username'] ?? '';
if (!is_string($id) || !preg_match('/^[0-9]{1,19}$/D', $id) || !is_string($username) || strcasecmp($username, $handle) !== 0) {
return new WP_Error('account', 'X heeft geen openbaar profiel gevonden voor de ingestelde gebruikersnaam.');
}
if (($account['protected'] ?? null) !== false) {
return new WP_Error('private', 'Het ingestelde X-profiel is afgeschermd.');
}
$response = hgsf_http_get('x', '2/users/' . $id . '/tweets', [
'max_results' => 5,
'exclude' => 'replies,retweets',
'post.fields' => 'created_at,withheld',
], $token);
if (is_wp_error($response)) {
return $response;
}
$data = $response['data'] ?? [];
if (!is_array($data) || (!isset($response['data']) && ($response['meta']['result_count'] ?? null) !== 0)) {
return new WP_Error('api', 'X heeft geen leesbare berichtenlijst teruggegeven.');
}
$posts = [];
foreach ($data as $post) {
$id = $post['id'] ?? '';
$created_at = $post['created_at'] ?? '';
$time = is_string($created_at) ? strtotime($created_at) : false;
if (!is_string($id) || !preg_match('/^[0-9]{1,19}$/D', $id) || !$time || !empty($post['withheld'])) {
continue;
}
$posts[$id] = [
'id' => $id,
'link' => 'https://x.com/' . rawurlencode($handle) . '/status/' . $id,
'type' => 'EMBED',
'date' => $time,
];
}
return array_values($posts);
}