Wordpress Gutenberg Block for Mobilizon
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

345 lines
10 KiB

<?php
/**
* Blocks Initializer
*
* Enqueue CSS/JS of all the blocks.
*
* @since 1.0.0
* @package CGB
*/
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Enqueue Gutenberg block assets for both frontend + backend.
*
* Assets enqueued:
* 1. blocks.style.build.css - Frontend + Backend.
* 2. blocks.build.js - Backend.
* 3. blocks.editor.build.css - Backend.
*
* @uses {wp-blocks} for block type registration & related functions.
* @uses {wp-element} for WP Element abstraction — structure of blocks.
* @uses {wp-i18n} to internationalize the block's text.
* @uses {wp-editor} for WP editor styles.
* @since 1.0.0
*/
function stripTrailingSlash(&$component) {
$component = rtrim($component, '/');
}
function addhttp($url) {
if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
$url = "https://" . $url;
}
return $url;
}
function mobilizon_query($baseURL, $query) {
// Get API-endpoint from Instance URL
$url_array = array($baseURL, "api");
array_walk_recursive($url_array, 'stripTrailingSlash');
$endpoint = implode('/', $url_array);
$endpoint = addhttp($endpoint);
// Define default GraphQL headers
$headers = ['Content-Type: application/json', 'User-Agent: Minimal GraphQL client'];
$body = array ('query' => $query);
$args = array(
'body' => $body,
'headers' => $headers,
);
// Send HTTP-Query and return the response
return(wp_remote_post($endpoint, $args));
}
function block_render_callback($attributes, $content) {
ob_start();
// var_dump($attributes); // Debugging only
// Check if we are supposed to render anything at all
if (array_key_exists("mobilizonInputFieldIsValid", $attributes) && $attributes["mobilizonInputFieldIsValid"]) {
// Set the string which limits how many events are queriend at maximum
if (isset($attributes['mobilizonEventLimit']) && ($attributes['mobilizonEventLimit'] != 0)) {
$limit = $attributes['mobilizonEventLimit'];
$limit = "(limit: ${limit})";
} else {
$limit = "";
}
}
// Get if we are getting the events of a group only, or not
// This is changes the way we query the events, as well as we parse the reponse array
if (isset($attributes['mobilizonGroupName']) && $attributes['mobilizonGroupName'] != '' ) {
$filter_by_group = True;
} else {
$filter_by_group = False;
}
// Define query string
// The query quite differs, if we query only the events of a certain group
if ($filter_by_group) {
$groupName = $attributes['mobilizonGroupName'];
$query = "query {
group (preferredUsername: \"${groupName}\") {
organizedEvents ${limit} {
elements {
id,
updatedAt,
title,
url,
beginsOn,
endsOn,
description,
attributedTo {
name,
url
},
organizerActor {
name,
url
},
onlineAddress,
picture {
url
},
physicalAddress {
postalCode,
description,
locality,
street
}
},
total
}
}
}
";
}
else {
$query = "query {
events ${limit} {
elements {
id,
updatedAt,
url,
title,
beginsOn,
endsOn,
status,
description,
attributedTo {
name,
url
},
organizerActor {
name,
url
},
onlineAddress,
picture {
url
},
physicalAddress {
postalCode,
description,
locality,
street
}
},
total
}
}
";
}
// Execute the event query to the mobilizon instance
$response = mobilizon_query($attributes['mobilizonBaseURL'], $query);
// Check if the HTTP-Query was successful, if not do nothing?
if ( wp_remote_retrieve_response_code( $response ) != 200 ) {
return ob_get_clean();;
}
// Extract the events as an array from the query's response body
$body = json_decode(wp_remote_retrieve_body( $response ), true);
if ($filter_by_group) {
$events = $body['data']['group']['organizedEvents']['elements'];
} else {
$events = $body['data']['events']['elements'];
}
// Display the event-array in as html list
echo '<ul class="wp-block-cgb-block-mobilizon">';
// Loop through each event
$event_index = 0;
foreach ($events as $event) {
$event_index = $event_index + 1;
echo '<li>';
// start of modal with the description
echo '<a href="#modal-'.$event_index.'">';
echo '<time>';
$start_datetime = strtotime($event['beginsOn']);
echo date_i18n( 'D, d. M. Y, G:i', $start_datetime );
echo '</time>';
echo '<h3>';
echo $event['title'];
echo '</h3>';
if ( !isset( $attributes['mobilizonShowHeaderImage'] ) ) {
if ( isset( $event['picture']['url'] ) ){
$response = wp_remote_get( $event['picture']['url'] );
$http_code = wp_remote_retrieve_response_code( $response );
if ($http_code == 200) {
$imageData = base64_encode( wp_remote_retrieve_body( $response ) );
echo '<img src="data:image/jpeg;base64,'.$imageData.'">';
}
}
}
// Get Details if present
if (isset($event['physicalAddress'])) {
$locality_description = $event['physicalAddress']['description'];
$locality_street = $event['physicalAddress']['street'];
$locality_city = $event['physicalAddress']['postalCode'] . ' ' . $event['physicalAddress']['locality'];;
}
else {
$locality_street = "";
$locality_description = "No location set";
$locality_city = "";
}
$locality = join("<br>",array_filter(array($locality_description,$locality_street,$locality_city)));
if (isset($event['onlineAddress'])) {
$online_adress = $event['onlineAddress'];
$online_addres_host = parse_url($online_adress, PHP_URL_HOST);
}
else {
$online_adress = "";
$online_addres_host = "";
}
if (isset($event['attributedTo'])) {
$organizer_name = $event['attributedTo']['name'];
$organizer_url = $event['attributedTo']['url'];
}
else {
$organizer_name = $event['organizerActor']['name'];
$organizer_url = $event['organizerActor']['url'];
}
$date = date_i18n( 'D, d. M. Y', $start_datetime);
$start = date_i18n(' G:i ', $start_datetime);
$end = date_i18n('G:i', strtotime($event['endsOn']));
$description = $event['description'];
$description_modal = '<div class="modal modal-lg" id="modal-'.$event_index.'">
<a href="#close" class="modal-overlay" aria-label="Close"></a>
<div class="modal-container">
<div class="modal-header">
<a href="#close" class="btn-clear float-right" aria-label="Close"></a>
<h3>'.$event['title'].'</h3>
</div>
<div class="modal-body">
<div class="event-description-wrapper">
<aside class="event-metadata">
<h4>Place</h4>
<div class="eventMetaDataBlock">
'.$locality.'
</div>
<h4>Date and Time</h4>
<div class="eventMetaDataBlock">
'.$date.' from '.$start.' to '.$end.'
</div>
<h4>Organised by</h4>
<div class="eventMetaDataBlock">
<a href="'.$organizer_url.'" target="blank">'.$organizer_name.' </a>
</div>
<h4>Website</h4>
<div class="eventMetaDataBlock">
<a href="'.$online_adress.'" target="blank">'.$online_addres_host.'</a>
</div>
</aside>
<div class="event-description">
'.$event['description'].'
</div>
</div>
</div>
<div class="modal-footer">
<a href="'.$event['url'].'" target=blank">Go to original Mobilizon-Event</a>
</div>
</div>
</div>
';
echo $description_modal;
echo '</a>'; // end of the description modal
echo '</li>';
}
echo '</ul>';
return ob_get_clean();
}
function mobilizon_cgb_block_assets() { // phpcs:ignore
// Register block styles for both frontend + backend.
wp_register_style(
'mobilizon-cgb-style-css', // Handle.
plugins_url( 'dist/blocks.style.build.css', dirname( __FILE__ ) ), // Block style CSS.
is_admin() ? array( 'wp-editor' ) : null, // Dependency to include the CSS after it.
null // filemtime( plugin_dir_path( __DIR__ ) . 'dist/blocks.style.build.css' ) // Version: File modification time.
);
// Register block editor script for backend.
wp_register_script(
'mobilizon-cgb-block-js', // Handle.
plugins_url( '/dist/blocks.build.js', dirname( __FILE__ ) ), // Block.build.js: We register the block here. Built with Webpack.
array( 'wp-blocks', 'wp-i18n', 'wp-element', 'wp-editor' ), // Dependencies, defined above.
null, // filemtime( plugin_dir_path( __DIR__ ) . 'dist/blocks.build.js' ), // Version: filemtime — Gets file modification time.
true // Enqueue the script in the footer.
);
// Register block editor styles for backend.
wp_register_style(
'mobilizon-cgb-block-editor-css', // Handle.
plugins_url( 'dist/blocks.editor.build.css', dirname( __FILE__ ) ), // Block editor CSS.
array( 'wp-edit-blocks' ), // Dependency to include the CSS after it.
null // filemtime( plugin_dir_path( __DIR__ ) . 'dist/blocks.editor.build.css' ) // Version: File modification time.
);
// WP Localized globals. Use dynamic PHP stuff in JavaScript via `cgbGlobal` object.
wp_localize_script(
'mobilizon-cgb-block-js',
'cgbGlobal', // Array containing dynamic data for a JS Global.
[
'pluginDirPath' => plugin_dir_path( __DIR__ ),
'pluginDirUrl' => plugin_dir_url( __DIR__ ),
// Add more data here that you want to access from `cgbGlobal` object.
]
);
/**
* Register Gutenberg block on server-side.
*
* Register the block on server-side to ensure that the block
* scripts and styles for both frontend and backend are
* enqueued when the editor loads.
*
* @link https://wordpress.org/gutenberg/handbook/blocks/writing-your-first-block-type#enqueuing-block-scripts
* @since 1.16.0
*/
register_block_type(
'cgb/block-mobilizon', array(
// Enqueue blocks.style.build.css on both frontend & backend.
'style' => 'mobilizon-cgb-style-css',
// Enqueue blocks.build.js in the editor only.
'editor_script' => 'mobilizon-cgb-block-js',
// Enqueue blocks.editor.build.css in the editor only.
'editor_style' => 'mobilizon-cgb-block-editor-css',
'render_callback' => 'block_render_callback',
)
);
}
// Hook: Block assets.
add_action( 'init', 'mobilizon_cgb_block_assets' );