| 1 |
<?php |
| 2 |
/** |
| 3 |
* GSuite Block. |
| 4 |
* |
| 5 |
* @since 11.3 |
| 6 |
* |
| 7 |
* @package automattic/jetpack |
| 8 |
*/ |
| 9 |
|
| 10 |
namespace Automattic\Jetpack\Extensions\GoogleDocsEmbed; |
| 11 |
|
| 12 |
use Automattic\Jetpack\Blocks; |
| 13 |
|
| 14 |
if ( ! defined( 'ABSPATH' ) ) { |
| 15 |
exit( 0 ); |
| 16 |
} |
| 17 |
|
| 18 |
/** |
| 19 |
* Registers the blocks for use in Gutenberg |
| 20 |
* This is done via an action so that we can disable |
| 21 |
* registration if we need to. |
| 22 |
*/ |
| 23 |
function register_blocks() { |
| 24 |
|
| 25 |
Blocks::jetpack_register_block( |
| 26 |
__DIR__, |
| 27 |
array( |
| 28 |
'render_callback' => __NAMESPACE__ . '\render_callback', |
| 29 |
) |
| 30 |
); |
| 31 |
} |
| 32 |
add_action( 'init', __NAMESPACE__ . '\register_blocks' ); |
| 33 |
|
| 34 |
/** |
| 35 |
* The block rendering callback. |
| 36 |
* |
| 37 |
* The render implementation lives in render.php and is only loaded when the |
| 38 |
* block is actually rendered, keeping it out of the eager front-end path. |
| 39 |
* |
| 40 |
* @param array $attributes attributes. |
| 41 |
* @return string |
| 42 |
*/ |
| 43 |
function render_callback( $attributes ) { |
| 44 |
require_once __DIR__ . '/render.php'; |
| 45 |
return render_callback_implementation( $attributes ); |
| 46 |
} |
| 47 |
|
| 48 |
/** |
| 49 |
* Convert GSuite URL to a preview URL. |
| 50 |
* |
| 51 |
* @param string $url The URL of the published Doc/Spreadsheet/Presentation. |
| 52 |
* |
| 53 |
* @return string |
| 54 |
*/ |
| 55 |
function map_gsuite_url( $url ) { |
| 56 |
|
| 57 |
// Default regex for all the URLs. |
| 58 |
$gsuite_regex = '/^(http|https):\/\/(docs\.google.com)\/(spreadsheets|document|presentation)\/d\/([A-Za-z0-9_-]+).*?$/i'; |
| 59 |
|
| 60 |
/** |
| 61 |
* Check if the URL is valid. |
| 62 |
* |
| 63 |
* If not, return the original URL as is. |
| 64 |
*/ |
| 65 |
preg_match( $gsuite_regex, $url, $matches ); |
| 66 |
if ( |
| 67 |
empty( $matches ) || |
| 68 |
empty( $matches[1] ) || |
| 69 |
empty( $matches[2] ) || |
| 70 |
empty( $matches[3] ) || |
| 71 |
empty( $matches[4] ) |
| 72 |
) { |
| 73 |
return $url; |
| 74 |
} |
| 75 |
|
| 76 |
return "{$matches[1]}://$matches[2]/$matches[3]/d/$matches[4]/preview"; |
| 77 |
} |
| 78 |
|