* Functions to perform snippet operations
use function Code_Snippets\Settings\get_self_option;
use function Code_Snippets\Settings\update_self_option;
* Clean the cache where active snippets are stored.
* @param string $table_name Snippets table name.
* @param array<string>|false $scopes List of scopes. Optional. If not provided, will flush the cache for all scopes.
function clean_active_snippets_cache( string $table_name, $scopes = false ) {
$scope_groups = $scopes ? [ $scopes ] : [
[ 'head-content', 'footer-content' ],
[ 'global', 'single-use', 'front-end' ],
[ 'global', 'single-use', 'admin' ],
foreach ( $scope_groups as $scopes ) {
wp_cache_delete( sprintf( 'active_snippets_%s_%s', sanitize_key( join( '_', $scopes ) ), $table_name ), CACHE_GROUP );
* Flush all snippets caches for a given database table.
* @param string $table_name Snippets table name.
function clean_snippets_cache( string $table_name ) {
wp_cache_delete( "all_snippet_tags_$table_name", CACHE_GROUP );
wp_cache_delete( "all_snippets_$table_name", CACHE_GROUP );
clean_active_snippets_cache( $table_name );
* Retrieve a list of snippets from the database.
* @param array<string> $ids The IDs of the snippets to fetch.
* @param bool|null $network Retrieve multisite-wide snippets (true) or site-wide snippets (false).
* @return array<Snippet> List of Snippet objects.
function get_snippets( array $ids = array(), ?bool $network = null ): array {
// If only one ID has been passed in, defer to the get_snippet() function.
$ids_count = count( $ids );
if ( 1 === $ids_count ) {
return array( get_snippet( $ids[0], $network ) );
$network = DB::validate_network_param( $network );
$table_name = code_snippets()->db->get_table_name( $network );
$snippets = wp_cache_get( "all_snippets_$table_name", CACHE_GROUP );
// Fetch all snippets from the database if none are cached.
if ( ! is_array( $snippets ) ) {
$results = $wpdb->get_results( "SELECT * FROM $table_name", ARRAY_A );
function ( $snippet_data ) use ( $network ) {
$snippet_data['network'] = $network;
return new Snippet( $snippet_data );
$snippets = apply_filters( 'code_snippets/get_snippets', $snippets, $network );
if ( 0 === $ids_count ) {
wp_cache_set( "all_snippets_$table_name", $snippets, CACHE_GROUP );
// If a list of IDs are provided, narrow down the snippets list.
$ids = array_map( 'intval', $ids );
function ( Snippet $snippet ) use ( $ids ) {
return in_array( $snippet->id, $ids, true );
* Gets all used tags from the database.
function get_all_snippet_tags() {
$table_name = code_snippets()->db->get_table_name();
$cache_key = "all_snippet_tags_$table_name";
$tags = wp_cache_get( $cache_key, CACHE_GROUP );
// Grab all tags from the database.
$all_tags = $wpdb->get_col( "SELECT tags FROM $table_name" );
// Merge all tags into a single array.
foreach ( $all_tags as $snippet_tags ) {
$snippet_tags = code_snippets_build_tags_array( $snippet_tags );
$tags = array_merge( $snippet_tags, $tags );
// Remove duplicate tags.
$tags = array_values( array_unique( $tags, SORT_REGULAR ) );
wp_cache_set( $cache_key, $tags, CACHE_GROUP );
* Make sure that the tags are a valid array.
* @param array|string $tags The tags to convert into an array.
* @return array<string> The converted tags.
function code_snippets_build_tags_array( $tags ): array {
/* If there are no tags set, return an empty array. */
/* If the tags are set as a string, convert them into an array. */
if ( is_string( $tags ) ) {
$tags = wp_strip_all_tags( $tags );
$tags = str_replace( ', ', ',', $tags );
$tags = explode( ',', $tags );
/* If we still don't have an array, just convert whatever we do have into one. */
* Retrieve a single snippets from the database.
* Will return empty snippet object if no snippet ID is specified.
* @param int $id The ID of the snippet to retrieve. 0 to build a new snippet.
* @param bool|null $network Retrieve a multisite-wide snippet (true) or site-wide snippet (false).
* @return Snippet A single snippet object.
function get_snippet( int $id = 0, ?bool $network = null ): Snippet {
$network = DB::validate_network_param( $network );
$table_name = code_snippets()->db->get_table_name( $network );
// If an invalid ID is provided, then return an empty snippet object.
$snippet = new Snippet();
$cached_snippets = wp_cache_get( "all_snippets_$table_name", CACHE_GROUP );
// Attempt to fetch snippet from the cached list, if it exists.
if ( is_array( $cached_snippets ) ) {
foreach ( $cached_snippets as $snippet ) {
if ( $snippet->id === $id ) {
return apply_filters( 'code_snippets/get_snippet', $snippet, $id, $network );
// Otherwise, retrieve the snippet from the database.
// phpcs:disable WordPress.DB.DirectDatabaseQuery.NoCaching
$snippet_data = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $table_name WHERE id = %d", $id ) );
$snippet = new Snippet( $snippet_data );
$snippet->network = $network;
return apply_filters( 'code_snippets/get_snippet', $snippet, $id, $network );
* Ensure the list of shared network snippets is correct if one has been recently activated or deactivated.
* @param Snippet[] $snippets Snippets that was recently updated.
* @return boolean Whether an update was performed.
function update_shared_network_snippets( array $snippets ): bool {
if ( ! is_multisite() ) {
foreach ( $snippets as $snippet ) {
if ( $snippet->network ) {
if ( $snippet->shared_network ) {
$shared_ids[] = $snippet->id;
$unshared_ids[] = $snippet->id;
if ( ! $shared_ids && ! $unshared_ids ) {
$existing_shared_ids = get_site_option( 'shared_network_snippets', [] );
$updated_shared_ids = array_values( array_diff( array_merge( $existing_shared_ids, $shared_ids ), $unshared_ids ) );
if ( $existing_shared_ids === $updated_shared_ids ) {
update_site_option( 'shared_network_snippets', $updated_shared_ids );
// Deactivate the snippet on all sites if necessary.
$sites = get_sites( [ 'fields' => 'ids' ] );
foreach ( $sites as $site ) {
$active_shared_ids = get_option( 'active_shared_network_snippets' );
if ( is_array( $active_shared_ids ) ) {
$active_shared_ids = array_diff( $active_shared_ids, $unshared_ids );
update_option( 'active_shared_network_snippets', $active_shared_ids );
clean_active_snippets_cache( code_snippets()->db->ms_table );
* @param int $id ID of the snippet to activate.
* @param bool|null $network Whether the snippets are multisite-wide (true) or site-wide (false).
* @return Snippet|string Snippet object on success, error message on failure.
function activate_snippet( int $id, ?bool $network = null ) {
$network = DB::validate_network_param( $network );
$table_name = code_snippets()->db->get_table_name( $network );
// Retrieve the snippet code from the database for validation before activating.
$snippet = get_snippet( $id, $network );
if ( 0 === $snippet->id ) {
// translators: %d: snippet identifier.
return sprintf( __( 'Could not locate snippet with ID %d.', 'code-snippets' ), $id );
if('php' == $snippet->type ){
$validator = new Validator( $snippet->code );
if ( $validator->validate() ) {
return __( 'Could not activate snippet: code did not pass validation.', 'code-snippets' );
array( 'active' => '1' ),
return __( 'Could not activate snippet.', 'code-snippets' );
update_shared_network_snippets( [ $snippet ] );
do_action( 'code_snippets/activate_snippet', $snippet, $network );
clean_snippets_cache( $table_name );
* Activates multiple snippets.
* @param array<integer> $ids The IDs of the snippets to activate.
* @param bool|null $network Whether the snippets are multisite-wide (true) or site-wide (false).
* @return Snippet[]|null Snippets which were successfully activated, or null on failure.
function activate_snippets( array $ids, ?bool $network = null ): ?array {
$network = DB::validate_network_param( $network );
$table_name = code_snippets()->db->get_table_name( $network );
$snippets = get_snippets( $ids, $network );
// Loop through each snippet code and validate individually.
foreach ( $snippets as $snippet ) {
$validator = new Validator( $snippet->code );
$code_error = $validator->validate();
$valid_ids[] = $snippet->id;
$valid_snippets[] = $snippet;
// If there are no valid snippets, then we're done.
// Build a SQL query containing all IDs, as wpdb::update does not support OR conditionals.
$ids_format = implode( ',', array_fill( 0, count( $valid_ids ), '%d' ) );
// phpcs:disable WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
$rows_updated = $wpdb->query( $wpdb->prepare( "UPDATE $table_name SET active = 1 WHERE id IN ($ids_format)", $valid_ids ) );
update_shared_network_snippets( $valid_snippets );
do_action( 'code_snippets/activate_snippets', $valid_snippets, $table_name );
clean_snippets_cache( $table_name );
* @param int $id ID of the snippet to deactivate.
* @param bool|null $network Whether the snippets are multisite-wide (true) or site-wide (false).
* @return Snippet|null Snippet that was deactivated on success, or null on failure.
function deactivate_snippet( int $id, ?bool $network = null ): ?Snippet {
$network = DB::validate_network_param( $network );
$table = code_snippets()->db->get_table_name( $network );
// Set the snippet to inactive.
array( 'active' => '0' ),
// Update the recently active list.
$snippet = get_snippet( $id );
$recently_active = [ $id => time() ] + get_self_option( $network, 'recently_activated_snippets', [] );
update_self_option( $network, 'recently_activated_snippets', $recently_active );
update_shared_network_snippets( [ $snippet ] );
do_action( 'code_snippets/deactivate_snippet', $id, $network );
clean_snippets_cache( $table );
* Deletes a snippet from the database.
* @param int $id ID of the snippet to delete.
* @param bool|null $network Delete from network-wide (true) or site-wide (false) table.
* @return bool Whether the snippet was deleted successfully.
function delete_snippet( int $id, ?bool $network = null ): bool {
$network = DB::validate_network_param( $network );
$table = code_snippets()->db->get_table_name( $network );
$snippet = get_snippet( $id, $network );
do_action( 'code_snippets/delete_snippet', $snippet, $network );
clean_snippets_cache( $table );
code_snippets()->cloud_api->delete_snippet_from_transient_data( $id );
* Trashes a snippet from the database.
* @param int $id ID of the snippet to trash.
* @param bool|null $network Trash from network-wide (true) or site-wide (false) table.
* @return bool Whether the snippet was trashed successfully.
function trash_snippet( int $id, ?bool $network = null ): bool {
$network = DB::validate_network_param( $network );
$table = code_snippets()->db->get_table_name( $network );
$snippet = get_snippet( $id, $network );
array( 'active' => '-1' ),
do_action( 'code_snippets/trash_snippet', $snippet, $network );
clean_snippets_cache( $table );
code_snippets()->cloud_api->delete_snippet_from_transient_data( $id );
* Restore a trashed snippet by setting its active status back to 0 (inactive).
* @param int $id Snippet ID to restore.
* @param bool|null $network Whether the snippet is multisite-wide (true) or site-wide (false).
* @return bool Whether the restore was successful.