@@ -859,4 +859,71 @@ public static function get_extensions_preset_for_variation( $preset_extensions_m
859859
860860 return $ preset_extensions ;
861861 }
862+
863+ /**
864+ * Validate a URL used in a SSR block.
865+ *
866+ * @since 8.3.0
867+ *
868+ * @param string $url URL saved as an attribute in block.
869+ * @param array $allowed Array of allowed hosts for that block, or regexes to check against.
870+ * @param bool $is_regex Array of regexes matching the URL that could be used in block.
871+ *
872+ * @return bool|string
873+ */
874+ public static function validate_block_embed_url ( $ url , $ allowed = array (), $ is_regex = false ) {
875+ if (
876+ empty ( $ url )
877+ || ! is_array ( $ allowed )
878+ || empty ( $ allowed )
879+ ) {
880+ return false ;
881+ }
882+
883+ $ url_components = wp_parse_url ( $ url );
884+
885+ // Bail early if we cannot find a host.
886+ if ( empty ( $ url_components ['host ' ] ) ) {
887+ return false ;
888+ }
889+
890+ // Normalize URL.
891+ $ url = sprintf (
892+ '%s://%s%s%s ' ,
893+ $ url_components ['scheme ' ],
894+ $ url_components ['host ' ],
895+ $ url_components ['path ' ] ? $ url_components ['path ' ] : '/ ' ,
896+ $ url_components ['query ' ] ? '? ' . $ url_components ['query ' ] : ''
897+ );
898+
899+ if ( ! empty ( $ url_components ['fragment ' ] ) ) {
900+ $ url = $ url . '# ' . rawurlencode ( $ url_components ['fragment ' ] );
901+ }
902+
903+ /*
904+ * If we're using a whitelist of hosts,
905+ * check if the URL belongs to one of the domains allowed for that block.
906+ */
907+ if (
908+ false === $ is_regex
909+ && in_array ( $ url_components ['host ' ], $ allowed , true )
910+ ) {
911+ return $ url ;
912+ }
913+
914+ /*
915+ * If we are using an array of regexes to check against,
916+ * loop through that.
917+ */
918+ if ( true === $ is_regex ) {
919+ foreach ( $ allowed as $ regex ) {
920+ if ( 1 === preg_match ( $ regex , $ url ) ) {
921+ return $ url ;
922+ }
923+ }
924+ }
925+
926+ return false ;
927+ }
928+
862929}
0 commit comments