| 1 |
<?php |
| 2 |
/** |
| 3 |
* Bootstraps synchronization (collaborative editing). |
| 4 |
* |
| 5 |
* @package gutenberg |
| 6 |
*/ |
| 7 |
|
| 8 |
/** |
| 9 |
* Initializes the collaborative editing secret. |
| 10 |
*/ |
| 11 |
function gutenberg_rest_api_init_collaborative_editing() { |
| 12 |
$gutenberg_experiments = get_option( 'gutenberg-experiments' ); |
| 13 |
if ( ! $gutenberg_experiments || ! array_key_exists( 'gutenberg-sync-collaboration', $gutenberg_experiments ) ) { |
| 14 |
return; |
| 15 |
} |
| 16 |
$collaborative_editing_secret = get_site_option( 'collaborative_editing_secret' ); |
| 17 |
if ( ! $collaborative_editing_secret ) { |
| 18 |
$collaborative_editing_secret = wp_generate_password( 64, false ); |
| 19 |
} |
| 20 |
add_site_option( 'collaborative_editing_secret', $collaborative_editing_secret ); |
| 21 |
|
| 22 |
wp_add_inline_script( 'wp-sync', 'window.__experimentalCollaborativeEditingSecret = "' . $collaborative_editing_secret . '";', 'before' ); |
| 23 |
} |
| 24 |
add_action( 'admin_init', 'gutenberg_rest_api_init_collaborative_editing' ); |
| 25 |
|
| 26 |
/** |
| 27 |
* Registers post meta for persisting CRDT documents. |
| 28 |
*/ |
| 29 |
function gutenberg_rest_api_crdt_post_meta() { |
| 30 |
$gutenberg_experiments = get_option( 'gutenberg-experiments' ); |
| 31 |
if ( ! $gutenberg_experiments || ! array_key_exists( 'gutenberg-sync-collaboration', $gutenberg_experiments ) ) { |
| 32 |
return; |
| 33 |
} |
| 34 |
|
| 35 |
// This string must match WORDPRESS_META_KEY_FOR_CRDT_DOC_PERSISTENCE in @wordpress/sync. |
| 36 |
$persisted_crdt_post_meta_key = '_crdt_document'; |
| 37 |
|
| 38 |
register_meta( |
| 39 |
'post', |
| 40 |
$persisted_crdt_post_meta_key, |
| 41 |
array( |
| 42 |
'auth_callback' => function ( bool $_allowed, string $_meta_key, int $object_id, int $user_id ): bool { |
| 43 |
return user_can( $user_id, 'edit_post', $object_id ); |
| 44 |
}, |
| 45 |
// IMPORTANT: Revisions must be disabled because we always want to preserve |
| 46 |
// the latest persisted CRDT document, even when a revision is restored. |
| 47 |
// This ensures that we can continue to apply updates to a shared document |
| 48 |
// and peers can simply merge the restored revision like any other incoming |
| 49 |
// update. |
| 50 |
// |
| 51 |
// If we want to persist CRDT documents alongisde revisions in the |
| 52 |
// future, we should do so in a separate meta key. |
| 53 |
'revisions_enabled' => false, |
| 54 |
'show_in_rest' => true, |
| 55 |
'single' => true, |
| 56 |
'type' => 'string', |
| 57 |
) |
| 58 |
); |
| 59 |
} |
| 60 |
add_action( 'init', 'gutenberg_rest_api_crdt_post_meta' ); |
| 61 |
|