Skip to main content

GravityKit\GravityMigrate\Import

Gravity Forms import class.

Source: src/Import.php:31

Details​

  • Kind: class
  • Namespace: GravityKit\GravityMigrate

Properties​

PropertyTypeDescription
$chunk_sizeintLines of the SQL dump processed per request.
$data_chunk_sizesarrayChunks sizes for migrating data types.
$temp_prefixstringTemp prefix for imported tables.
$known_temp_table_names_build_countintCount of \self::get_known_temp_table_names() cache misses (rebuilds).
$import_infoarrayImport information from JSON file.

Methods​

MethodDescription
__construct()Constructor.
get_instance()Returns class instance.
get_file_object()Returns the SplFileObject for the provided file.
get_num_chunks_in_file()Returns the number of chunks in an SQL file.
import_chunk()Imports a chunk of a provided SQL file into the database
is_safe_remote_url()Whether $url is safe to fetch: http(s) scheme, host resolves to one or more addresses,
sanitize_form_id_list()Reduces a form-id list to positive integers, joined for direct use in an IN(...)
get_uploads_data()Creates a query to get upload meta fields attached to gravity form entries.
import_lock_check()Takes the import lock for this run, reclaiming a stale one left by an interrupted import.
import_is_live()Whether ANY import currently owns the staged bundle and the temp tables.
background_import_is_active()Whether a background import still legitimately owns the staged bundle, the temp tables
release_lock_if_token_matches()Releases the import lock if, and only if, $token matches the token stored on it. The entry
submissions_block_check()Check if Gravity Forms is currently upgrading the database.
ajax_routes()Registers the import's AJAX routes with Foundation.
renumber_post_meta_sql()Moves one staged post's meta onto the id that post was given on this site.
cancel_import()Cancels the crashed import request.
abandon_import()Frees the import lock held by a browser-driven run whose tab has gone.
reset_state()Clears migration state so a fresh import starts clean: drops the temporary tables,
get_skipped_statement_count()
delete_all_temp_tables()Deletes all migration temporary tables.
remove_ansi_quotes()Removes ANSI quotes from a given string and replaces them with backticks.
convert_to_temp_query()Converts a query to run on temporary tables.
is_safe_temp_query()Gate run after {@see self::convert_to_temp_query()} and before any query from
has_single_top_level_statement()Whether $sql is exactly one statement: a quote-aware scan (honoring the
str_replace_first()Replaces first instance of a string.
process_import_file()Processes the imported file.
update_gravity_forms_gutenberg_blocks()Updates the form ID in Gravity Forms Gutenberg blocks, including innerBlocks.
update_inner_blocks()Recursively updates form IDs within innerBlocks.
update_gravity_forms_classic_shortcodes()Updates the form ID in Gravity Forms classic shortcodes.
get_attr_name()Returns the attribute name.
update_gravity_forms_ids_in_content()Updates the form IDs in Post content (Gutenberg blocks and classic shortcodes).
remap_ids_in_content_using_map()Updates the ids in Post content (Gutenberg blocks and classic
remap_ids_in_content()Updates ids in Post content (Gutenberg blocks and classic shortcodes)
update_gravity_ids_in_array()Updates the form IDs in Array (Gutenberg blocks and classic shortcodes).
update_gravity_ids_in_array_using_map()Map-based counterpart to {@see update_gravity_ids_in_array()}: applies
update_gravity_post_ids_in_metas()Updates the form IDs in Post metas (Gutenberg blocks and classic shortcodes).

Method Reference​

__construct()​

public function __construct()

Constructor.

Since: 1.0.0

Source: src/Import.php:509

get_instance()​

public static function get_instance(): Import

Returns class instance.

Returns​

  • Import

Since: 1.0.0

Source: src/Import.php:536

get_file_object()​

public function get_file_object( $file, $line=0, $byte_offset=null )

Returns the SplFileObject for the provided file.

Parameters​

NameTypeDefaultDescription
$filestringDump file.
$lineint0Line number. Ignored when $byte_offset is given.
$byte_offsetint | nullnullWhen given, seeks directly to this byte position (O(1)) instead of $line's line-based \self::seek_spl(), which reads every line from the start of the file.

Returns​

Since:

  • 1.0.0
  • 1.3.0 (Accepts an optional byte offset for O(1) resume seeking; see $byte_offset.)

Source: src/Import.php:613

get_num_chunks_in_file()​

public function get_num_chunks_in_file( $file )

Returns the number of chunks in an SQL file.

Parameters​

NameTypeDefaultDescription
$fileSplFileObjectSPL File.

Returns​

Since:

  • 1.0.0
  • 1.3.0 (Refuses to scan a dump file larger than {@see self::MAX_DUMP_FILE_SIZE_BYTES}.)

Source: src/Import.php:683

import_chunk()​

public function import_chunk( $file, $info_file_path, $chunk=0, $current_query='', $byte_offset=null )

Imports a chunk of a provided SQL file into the database

Parameters​

NameTypeDefaultDescription
$filestringSQL File.
$info_file_pathstringPath of the info file.
$chunkint0Chunk of the SQL file.
$current_querystring''Remaining query.
$byte_offsetint | nullnullByte position to resume reading from; when null, seeks by line instead using $chunk.

Returns​

Since:

  • 1.0.0
  • 1.3.0 (Refuses to read a dump file larger than {@see self::MAX_DUMP_FILE_SIZE_BYTES}.)
  • 1.3.0 (Accepts an optional byte offset to resume from ($byte_offset) and returns the byte offset reached, avoiding a full re-read from the start of the file.)

Source: src/Import.php:747

is_safe_remote_url()​

public function is_safe_remote_url( $url )

Whether $url is safe to fetch: http(s) scheme, host resolves to one or more addresses,

passes WordPress' own wp_http_validate_url() checks, AND every resolved address is public (not loopback, private, link-local, or otherwise reserved). Resolution happens immediately before this returns, keeping the gap between validating an address and connecting to it as small as possible.

A host that resolves to nothing at all fails closed rather than falling back to a syntax-only check: an unresolvable host cannot be fetched from anyway, so refusing it costs a legitimate migration nothing.

Parameters​

NameTypeDefaultDescription
$urlstring

Returns​

  • bool

Since: 1.3.0

Source: src/Import.php:1162

sanitize_form_id_list()​

public static function sanitize_form_id_list( $forms )

Reduces a form-id list to positive integers, joined for direct use in an IN(...)

clause. Form ids reach these clauses unquoted, where escaping protects nothing, so anything that is not an id is discarded rather than escaped. An empty result yields 0, which matches no form, rather than the IN() syntax error an empty list would produce.

Parameters​

NameTypeDefaultDescription
$formsstring | arrayComma-separated ids, or an array of them.

Returns​

  • string

Since: 1.3.0

Source: src/Import.php:1567

get_uploads_data()​

public function get_uploads_data( $table, $where, &$uploads_data=[] )

Creates a query to get upload meta fields attached to gravity form entries.

Parameters​

NameTypeDefaultDescription
$tablestringUploads meta table name.
$wherearrayArray of where statements for all tables.
&$uploads_dataarray[]Field-map cache. Populated in place on a cache miss (empty array in); reused as-is otherwise.

Returns​

  • string

Since:

  • 1.0.0
  • 1.3.0 ($uploads_data is taken by reference and populated in place, so repeat calls reuse the field map instead of re-querying and re-decoding it.)

Source: src/Import.php:1667

import_lock_check()​

public function import_lock_check( $chunk, $token='' )

Takes the import lock for this run, reclaiming a stale one left by an interrupted import.

Only the first request of a run claims it; every request refreshes the last-request time the staleness check reads.

Parameters​

NameTypeDefaultDescription
$chunkstringChunk number of this request. Only chunk 0 claims the lock.
$tokenstring''The lock token this run carries, threaded through every request after the first. Empty on the request that claims the lock.

Returns​

  • void

Throws​

  • Exception — If another import already holds the lock.

Since: 1.0.0

Source: src/Import.php:2032

import_is_live()​

public function import_is_live(): bool

Whether ANY import currently owns the staged bundle and the temp tables.

Broader than \self::background_import_is_active(), which answers only for the scheduler. A browser-driven run holds the same lock over the same files and is just as destroyed by having them replaced or deleted underneath it, so anything that would touch them has to ask this rather than the narrower question.

A lock whose last request is older than the timeout is not live: that run was interrupted, and \self::import_lock_check() is free to reclaim it.

Returns​

  • bool

Since: %ver%

Source: src/Import.php:2145

background_import_is_active()​

public function background_import_is_active(): bool

Whether a background import still legitimately owns the staged bundle, the temp tables

and \Options::IMPORT_LOCK().

A background job's steps are spaced by the scheduler's dispatch cadence rather than a browser's continuous polling, so it can look stale by the clock while very much alive. Anything that would reclaim the lock, or delete what the job is using, must consult this first. Paused counts as active: a paused job's data is still live.

Never true for a background import's own lock-acquiring request, which runs while \Options::IMPORT_LOCK() is still free.

Returns​

  • bool

Since: %ver%

Source: src/Import.php:2175

release_lock_if_token_matches()​

public function release_lock_if_token_matches( string $token ): void

Releases the import lock if, and only if, $token matches the token stored on it. The entry

point for code outside this class that holds a run's recorded token.

Parameters​

NameTypeDefaultDescription
$tokenstringLock token to match before releasing.

Returns​

  • void

Since: %ver%

Source: src/Import.php:2237

submissions_block_check()​

public function submissions_block_check()

Check if Gravity Forms is currently upgrading the database.

Returns​

  • void

Throws​

  • Exception

Since: 1.0.0

Source: src/Import.php:2250

ajax_routes()​

public function ajax_routes( $routes )

Registers the import's AJAX routes with Foundation.

Parameters​

NameTypeDefaultDescription
$routesarrayRoutes registered so far.

Returns​

  • array

Since: 1.0.0

Source: src/Import.php:2268

renumber_post_meta_sql()​

public static function renumber_post_meta_sql( $manipulation_table, $staged_table, $new_post_id, $imported_post_id )

Moves one staged post's meta onto the id that post was given on this site.

Matched on meta_id as well as post_id, because the manipulation table is never truncated between posts: it accumulates rows already renumbered to their new ids. New ids start above the destination's highest post, so as soon as one of them equals a later source post's id -- routine whenever the destination forces renumbering -- a post_id-only match drags the earlier post's rows along too, landing its View configuration on whatever post is being written now. Restricting to the meta rows that belong to this post in the staged table is what keeps them apart.

Parameters​

NameTypeDefaultDescription
$manipulation_tablestringThe table holding posts renumbered so far.
$staged_tablestringThe staged postmeta table, still on source ids.
$new_post_idintThe id this post was given here.
$imported_post_idintThe id it had on the source site.

Returns​

  • string

Since: %ver%

Source: src/Import.php:5583

cancel_import()​

public function cancel_import()

Cancels the crashed import request.

Returns​

  • void

Source: src/Import.php:5902

abandon_import()​

public function abandon_import(): array

Frees the import lock held by a browser-driven run whose tab has gone.

A synchronous import only advances while the tab that started it is asking for the next chunk, so a closed tab ends the run -- but the lock it took at chunk 0 outlives it until \self::LOCK_TIMEOUT_IN_SECONDS() elapses, and the operator who comes back before then is refused with "Import already in progress" for a run that stopped when they left.

Deliberately not a cancel: the temp tables are rebuilt by the next run at chunk 0 and the staged bundle is left alone, so returning and pressing Import again costs nothing. A background job is refused outright -- the scheduler owns it, and it keeps running whatever this tab does.

Returns​

  • array{abandoned: — bool}

Since: %ver%

Source: src/Import.php:5925

reset_state()​

public function reset_state()

Clears migration state so a fresh import starts clean: drops the temporary tables,

clears the crashed-import record, frees the import lock, and only then deletes the staged import files. Import-only by design (does not touch export state).

The order is the contract. Anything a concurrent import could start against or inherit is cleared while the lock is held; the lock is freed before the directory deletion, which is the only step here that is both slow and killable, and a request killed mid-deletion runs no finally. Freed last, that death stranded the lock for \self::LOCK_TIMEOUT_IN_SECONDS(); freed first, it costs only files, which the clear-imports cron collects.

The window this leaves: a second import can claim the lock (\self::import_lock_check()) while these lines are still unlinking, and fail to read the bundle. Nothing is damaged -- its temp tables are its own.

Returns​

  • void

Since:

  • 1.2.0
  • %ver% Frees the lock before deleting the staged files rather than after.

Source: src/Import.php:5963

get_skipped_statement_count()​

public function get_skipped_statement_count(): int

Returns​

  • int — Count of dump statements {@see self::is_safe_temp_query()} rejected (logged and skipped rather than executed) on this instance so far.

Since: 1.3.0

Source: src/Import.php:6048

delete_all_temp_tables()​

public function delete_all_temp_tables()

Deletes all migration temporary tables.

Returns​

  • void

Since: 1.0.0

Source: src/Import.php:6285

remove_ansi_quotes()​

public function remove_ansi_quotes( $string )

Removes ANSI quotes from a given string and replaces them with backticks.

Parameters​

NameTypeDefaultDescription
$stringstringString to remove ANSI quotes from.

Returns​

  • string

Since: 1.0.0

Source: src/Import.php:6313

convert_to_temp_query()​

public function convert_to_temp_query( $query, $export_db_prefix )

Converts a query to run on temporary tables.

The source site's table prefix is rewritten to this site's ONLY inside the statement's target table identifier, never across the whole statement: an exported row's own data can legitimately contain the source prefix as text (a path, a support note, a serialized option), and a statement-wide replacement silently rewrites that text on every migration between two sites whose prefixes differ.

Parameters​

NameTypeDefaultDescription
$querystringSQL query.
$export_db_prefixstringTable prefix the bundle was exported with.

Returns​

  • string

Since:

  • 1.0.0
  • 1.3.0 (Rewrites the source table prefix only within the target table identifier.)

Source: src/Import.php:6369

is_safe_temp_query()​

public function is_safe_temp_query( $query ): bool

Gate run after {@see self::convert_to_temp_query()} and before any query from

an import bundle reaches the database. A query is safe only if it is one of the 3 statement shapes a legitimate export ever emits (see Export.php's write() call sites: a lone DROP TABLE IF EXISTS per table, the raw SHOW CREATE TABLE output, and INSERT INTO \table` (cols) VALUES (...)), targets exactly one of \self::get_known_temp_table_names() with NO second table reference of any kind (\self::has_single_validated_table_reference()), and is a single top-level statement (\self::has_single_top_level_statement()`).

LOCK TABLES and ALTER TABLE are rejected outright: a legitimate export emits neither, so recognizing them only widens what a bundle can ask for.

Parameters​

NameTypeDefaultDescription
$querystringA single statement, already temp-prefixed.

Returns​

  • bool

Since: 1.3.0

Source: src/Import.php:6477

has_single_top_level_statement()​

public function has_single_top_level_statement( $sql ): bool

Whether $sql is exactly one statement: a quote-aware scan (honoring the

backslash-escaping \Export::mysql_escape_mimic() uses, and doubled-backtick escaping inside identifiers) confirming there is exactly one ; outside a quoted region, and it is the final non-whitespace character.

Parameters​

NameTypeDefaultDescription
$sqlstring

Returns​

  • bool

Since:

  • 1.3.0
  • 1.3.0 (Rejects a query carrying more than one top-level ; instead of only checking the position of the last one.)

Source: src/Import.php:6665

str_replace_first()​

public static function str_replace_first( $search, $replace, $string )

Replaces first instance of a string.

Parameters​

NameTypeDefaultDescription
$searchstring
$replacestring
$stringstring

Returns​

  • string — replaced string.

Since: 1.0.0

Source: src/Import.php:6744

process_import_file()​

public function process_import_file( $file_path, $password )

Processes the imported file.

Extract the zip file and return the info.json file.

Parameters​

NameTypeDefaultDescription
$file_pathstringZIP File path.
$passwordstringOptional password.

Returns​

Since:

  • 1.0.0
  • 1.3.0 (Refuses to extract an entry whose uncompressed size exceeds {@see self::MAX_DUMP_FILE_SIZE_BYTES}.)

Source: src/Import.php:7078

update_gravity_forms_gutenberg_blocks()​

public function update_gravity_forms_gutenberg_blocks( $content, $old_id, $new_id, $id_type )

Updates the form ID in Gravity Forms Gutenberg blocks, including innerBlocks.

Parameters​

NameTypeDefaultDescription
$contentstringPost content to search for form IDs.
$old_idstringThe old form ID to replace.
$new_idstringThe new form ID to set.
$id_typestringID type the attribute is matched by.

Returns​

  • string

Since: 1.0.0

Source: src/Import.php:7730

update_inner_blocks()​

public function update_inner_blocks( &$blocks, $old_id, $new_id, $id_type )

Recursively updates form IDs within innerBlocks.

Parameters​

NameTypeDefaultDescription
&$blocksarrayAn array of Gutenberg blocks.
$old_idstringThe old form ID to replace.
$new_idstringThe new form ID to set.
$id_typestringID type the attribute is matched by.

Since: 1.0.0

Source: src/Import.php:7750

update_gravity_forms_classic_shortcodes()​

public function update_gravity_forms_classic_shortcodes( $content, $old_id, $new_id, $id_type )

Updates the form ID in Gravity Forms classic shortcodes.

Parameters​

NameTypeDefaultDescription
$contentstringPost content to search for form IDs.
$old_idstringThe old form ID to replace.
$new_idstringThe new form ID to set.
$id_typestringID type the attribute is matched by.

Returns​

  • string

Since: 1.0.0

Source: src/Import.php:7780

get_attr_name()​

public function get_attr_name( $id_type, $to_sync )

Returns the attribute name.

Parameters​

NameTypeDefaultDescription
$id_typestringID type.
$to_syncarrayAttributes to sync.

Returns​

  • string

Since: 1.0.0

Source: src/Import.php:7826

update_gravity_forms_ids_in_content()​

public function update_gravity_forms_ids_in_content( $content, $old_id, $new_id, $id_type )

Updates the form IDs in Post content (Gutenberg blocks and classic shortcodes).

Parameters​

NameTypeDefaultDescription
$contentstringPost content to search for form IDs.
$old_idstringThe old form ID to replace.
$new_idstringThe new form ID to set.
$id_typestringID type the attribute is matched by.

Returns​

  • string

Since: 1.0.0

Source: src/Import.php:7856

remap_ids_in_content_using_map()​

public function remap_ids_in_content_using_map( $content, array $id_map, $id_type )

Updates the ids in Post content (Gutenberg blocks and classic

shortcodes) for a single id type, given the full old-id-to-new-id map at once, instead of one old/new pair per call.

Applying pairs one at a time to the same content (\update_gravity_forms_ids_in_content) cascades when the id spaces overlap: rewriting old id 1 to new id 2 can leave a "2" in the content that a later pair (old id 2 -> new id 9) then matches and rewrites again. Looking every id up in the full map in a single pass guarantees each reference is rewritten at most once.

Parameters​

NameTypeDefaultDescription
$contentstringPost content to search for ids.
$id_maparrayMap of old id (int|string) => new id.
$id_typestringID type (e.g. 'form_id', 'entry_id', 'view_id', 'view-id').

Returns​

  • string

Since: 1.3.0

Source: src/Import.php:7883

remap_ids_in_content()​

public function remap_ids_in_content( $content, array $mappings_by_id_type )

Updates ids in Post content (Gutenberg blocks and classic shortcodes)

for ALL applicable id types in a single parse + serialize pass.

\remap_ids_in_content_using_map handles one id type per call, so a post referencing several id types (e.g. a form, an entry, and a View) would otherwise be parsed and re-serialized once per id type -- an O(posts x id_types) cost. This walks the block tree once, applying every non-empty map to the attribute its id type resolves to, then serializes once; the shortcode pass mirrors this with one loop over the shortcode list checking every applicable id type per shortcode.

Each attribute is scoped to exactly one id type (\Util::get_blocks_list() / \Util::get_shortcodes_list(): no block or shortcode maps two id types to the same attribute), so applying every map in one pass cannot double-remap a single attribute -- the single-hop, non-cascading guarantee \remap_ids_in_content_using_map establishes for one id type holds here across all of them at once.

Parameters​

NameTypeDefaultDescription
$contentstringPost content to search for ids.
$mappings_by_id_typearrayMap of id_type (e.g. 'form_id', 'entry_id', 'view_id', 'view-id') => (map of old id => new id). Id types with an empty or absent map are ignored entirely (no parse cost).

Returns​

  • string

Since: 1.3.0

Source: src/Import.php:8017

update_gravity_ids_in_array()​

public function update_gravity_ids_in_array( $array, $old_id, $new_id, $id_type )

Updates the form IDs in Array (Gutenberg blocks and classic shortcodes).

Parameters​

NameTypeDefaultDescription
$arrayarray | stringArray to search for IDs.
$old_idstringThe old ID to replace.
$new_idstringThe new ID to set.
$id_typestringID type the attribute is matched by.

Returns​

  • array | string

Since: 1.0.0

Source: src/Import.php:8173

update_gravity_ids_in_array_using_map()​

public function update_gravity_ids_in_array_using_map( $array, array $id_map, $id_type )

Map-based counterpart to {@see update_gravity_ids_in_array()}: applies

the full old-id-to-new-id map to every scalar leaf in a single pass (via \remap_ids_in_content_using_map), instead of one old/new pair at a time. An overlapping map (an old id that equals another pair's new id) applied pair-by-pair to the same value would otherwise cascade -- a freshly rewritten id matching and being rewritten again by a later pair.

Parameters​

NameTypeDefaultDescription
$arrayarray | stringArray (or scalar) to search for ids.
$id_maparrayMap of old id (int|string) => new id.
$id_typestringID type.

Returns​

  • array | string

Since: 1.3.0

Source: src/Import.php:8205

update_gravity_post_ids_in_metas()​

public function update_gravity_post_ids_in_metas( $updated_post_ids )

Updates the form IDs in Post metas (Gutenberg blocks and classic shortcodes).

Parameters​

NameTypeDefaultDescription
$updated_post_idsarrayMap of old post id => new post id.

Returns​

  • bool | void

Since: 1.0.0

Source: src/Import.php:8228