'GET', 'callback' => 'layers_doc_embed_rest_templates', 'permission_callback' => function () { return current_user_can( 'edit_posts' ); }, ) ); } /** * Fetches the public catalog once per 12 hours. * * @return array|WP_Error */ function layers_doc_embed_catalog() { $cached = get_transient( 'layers_doc_embed_catalog' ); if ( is_array( $cached ) ) { return $cached; } $response = wp_remote_get( LAYERS_DOC_EMBED_APP . '/v1/public/templates', array( 'timeout' => 10, 'headers' => array( 'Accept' => 'application/json' ), ) ); if ( is_wp_error( $response ) ) { return $response; } if ( 200 !== wp_remote_retrieve_response_code( $response ) ) { return new WP_Error( 'layers_doc_embed_catalog', __( 'The Layers template catalog is not reachable right now.', 'layers-doc-embed' ) ); } $body = json_decode( wp_remote_retrieve_body( $response ), true ); $list = array(); if ( is_array( $body ) && isset( $body['templates'] ) && is_array( $body['templates'] ) ) { foreach ( $body['templates'] as $t ) { $slug = layers_doc_embed_clean_slug( isset( $t['slug'] ) ? $t['slug'] : '' ); if ( '' === $slug ) { continue; } $list[] = array( 'slug' => $slug, 'title' => isset( $t['title'] ) ? sanitize_text_field( $t['title'] ) : $slug, 'kind' => isset( $t['kind'] ) ? sanitize_key( $t['kind'] ) : '', 'lang' => isset( $t['lang'] ) ? sanitize_key( $t['lang'] ) : '', 'hasPage' => isset( $t['formats'] ) && is_array( $t['formats'] ) && in_array( 'page', $t['formats'], true ), ); } } set_transient( 'layers_doc_embed_catalog', $list, 12 * HOUR_IN_SECONDS ); return $list; } /** * REST callback. * * @return WP_REST_Response|WP_Error */ function layers_doc_embed_rest_templates() { $list = layers_doc_embed_catalog(); if ( is_wp_error( $list ) ) { return $list; } return rest_ensure_response( array( 'templates' => $list, 'lang' => layers_doc_embed_options()['lang'], ) ); }