Importexport
Tags
- class
-
Importexport
Import / export of module content, driven by a description array.
A module that stores content describes its data as a tree of nodes and hands the SAME description to this library in both directions: with the id of the starting record to export, with that id at 0 to import (the ids of an import come from the archive, never from the description). Nothing here knows about documents, decos or hierarchies - a module follows a new linked table by adding a node, not by touching this file.
Example, the description of a document:
$desc = [ 'table' => 'document_data', // root node, table name without prefix 'id' => $id, 'translations' => true, 'files' => 'auto', 'import' => ['unique' => ['route']], 'children' => [ ['table' => 'document_blocks', 'key' => 'id_document_data', 'order' => 'sort_order', 'files' => false, 'import' => ['fk' => 'id_document_data', 'link' => 'id_block'], 'expand' => ['table' => 'block_{blockname}', 'id' => '{id_block}', 'translations' => 'block_{blockname}', 'files' => 'auto', 'import' => ['drop' => ['creadate']]]], ], 'attach' => ['css-public.css' => $path_of_the_compiled_css], // export only ]; $zip = (new Importexport())->export($desc, 'document-'.$id);
NODE KEYS
- table: table name without the DB prefix, DB->table() is applied on both sides.
Placeholders are substituted here (block_{blockname}). Required on the root node;
a wrong name surfaces as "record not found in
" on export and as an insert failure on import.
- id: ONE record, read with WHERE id=?. The root is always a single record: a root built on 'key' exports a rows list that import() refuses as a root ("malformed node in the manifest"). Ignored by the import.
- key: MANY records, read with WHERE
=?. The searched value comes from the parent record, or from an explicit 'key_value'. The node is exported as ['table' => ..., 'rows' => [...]]. Ignored by the import, where the relation is set by 'fk'. - key_value: the searched value. Written by hand when the parent field alone cannot express it - a text column holding a composed value ('document¤{id}') - otherwise it defaults to the field of the parent named by key_field. Placeholders are substituted like everywhere else. It is bound with the type of the column it is compared to (read from the table model), so a varchar key is never cast to a number: an int cast turns 'document¤12' into 0 and the node silently exports zero rows. Export only: the import strips 'key', 'key_value', 'key_field', 'filter', 'order' and 'files' from a child node before resolving it, so an unresolved placeholder here can never break an import.
- key_field: which field of the PARENT carries the value (default 'id').
- filter: array field => value, appended as AND field=? (bound as a string). Child nodes only. It is ANDed with 'key', never a replacement for it: repeating the key column in a filter can never match.
- order: ORDER BY clause, child nodes only: identifiers, optional ASC/DESC, commas. No expression, and never built from user input.
- translations: false (default), true (field_identifier prefix = table), or the explicit prefix as a string ('block_{blockname}'). Reads languages_long / languages_short on field_identifier LIKE '
-%' and id_item = , and carries the iso code of each language so an import can map the ids of another instance. A language missing on the target is logged and skipped, the import goes on. - files: false (default), 'auto' (every media_use row matching
-%¤
, i.e. the columns flagged COMMENT 'file' in the table) or an explicit list of usage suffixes ( -
%¤ , which is not necessarily a column of the record). Export only: the import rebuilds media_data / media_use from the manifest. - children: list of nodes; in the manifest, a map table => node.
- expand: ONE linked record whose id is computed from the fields of the current line, root node included; omitted when the id resolves to 0. This is how the dynamic block_{blockname} tables are followed. The parent row keeps the reference column (id_block): the import inserts the sub-node first and writes its new id through 'link'.
- recursive: the node repeats itself on its own table, with 'id', 'filter' and 'expand' removed, 'key' defaulting to 'id_parent'. Depth is capped by the $max_depth argument of export(), max_depth (512) when the caller passes none. A description that loops is broken by the branch registry, never by this limit: the record already open higher on the branch is not expanded again, and it is already in the archive at that position.
- import: rules applied on insertion (see below). Empty by default, which means the copy is faithful, column for column.
THE 'attach' KEY (export only)
- attach: array entry name => absolute path. The files go into the archive under attach/, as-is: no media_data, no media_use, no manifest entry, nothing linked to a record. This is for a module that GENERATES its payload rather than storing it - the compiled .css of a document, the theme.css of a theme - so the importer can re-parse it with the code that already knows the format instead of recopying rows whose ids mean nothing elsewhere. The entry is a plain file name; a missing file follows the same rule as a missing media ($allow_incomplete). On the importing side, attached_files() returns entry => extracted path, valid until cleanup_extract().
IMPORT RULES ('import' array of a node)
- drop: columns not to copy (creadate, creation_date...).
- set: imposed values (['active' => 0]).
- fk: column receiving the id of the parent - 0 for a root, which is what a tree id_parent expects. A join column that is neither in 'fk', 'set' nor 'drop' is copied verbatim, so the imported child points at the SOURCE parent.
- link: column of the parent receiving the id of the 'expand' sub-node. The sub-node is inserted BEFORE the parent, its id is written into the data, never patched afterwards by an UPDATE. Without 'link', the expanded record is silently not inserted at all.
- unique: columns whose already used value is suffixed -1, -2 ... (text columns only). The rename is logged, the import goes on.
- rewrite: templates using {root_id} / {parent_id}; the column is overwritten even when it is absent from the data. {root_id} is only reliable in child nodes: a root that also carries 'expand' + 'link' gets the id of the sub-node, inserted first.
ORDER OF OPERATIONS
Export, per node: placeholders resolved, record read (id, or key + filter + order), data = the whole row, translations, media, expand, children, recursive.
Import, per node: id removed, drop, set, fk, expand inserted and link written, unique, rewrite, INSERT, translations, media, children. There is no transaction: whatever was inserted before a failure stays in the database.
PLACEHOLDERS
{field} is substituted in the scalar values of a node, with the scalar fields of the parent record. The substitution does not descend into sub-arrays: children, filter and import are resolved in turn, with the fields of the same parent, when the walk reaches them. An unresolved placeholder fails the export, which is why 'drop' on a field used by a placeholder (id_block) breaks the 'expand' that needs it.
MANIFEST
The archive holds manifest.json (format, version, created, base_url, root, files, missing) and files/... with the media at their path relative to the instance files/ folder. Name collisions are resolved by a -1, -2 ... suffix and recorded in the manifest, so the import can copy the file under its final name. version is compared to format_version: an archive produced by a newer toolkit is refused.
Both directions go through Filesystem::pack() and Filesystem::unpack(), that is the 7z binary, not ext-zip: a host without 7z cannot exchange archives, and pack() runs a child process (blocking, the archive exists when it returns). The export lays the tree out in <HOME_FOLDER>temp/export-.../, media hard linked so a 60 MB export costs no copy, and hands pack() the CONTENTS of that folder - 7z names an entry after the base name of the path it receives. The result stays a standard zip: an instance that cannot pack can still be read with any unzip tool.
On import, the table name of a node is read FROM THE MANIFEST (insert_node() writes into $mnode['table']); the description only tells the shape of the tree and the rules. 'key', the field names of 'filter' and 'order' are validated as plain identifiers before they reach the SELECT, but the table name of a manifest is still interpolated as it comes: a description is trusted code, an archive is not.
ERRORS
export() and import() return false, and every reason is written once with Error::log(), prefixed 'Importexport - '. There is no local error stack: the caller has nothing to relay, it only has to tell the user with Error::message() once the return value says the operation failed.
AN EXPORT IS COMPLETE, OR IT SAYS WHAT IT LACKS. Depth is not a content policy: a description that loops is broken by the branch registry (a record already open higher on the branch is not expanded again, and it is already in the archive at that position, so nothing is lost). A broken description - a node without id or key, both at once, a record the description announces but the database does not have, an unresolved placeholder, the max_depth safety net - is refused outright: export() returns false and writes nothing, whatever $allow_incomplete says. The tree is still walked to the end so the log lists every problem at once.
Missing DATA is a judgement call left to the caller: a media the instance does not have on disk, or a file that cannot be staged, is collected in missing_files(). By default export() refuses the archive over it, which is what a module does on the first click: it then shows the list and asks the admin whether to go on. $allow_incomplete = true is the 'yes' of that question, passed on the second click; the archive is then written with the list in the manifest under 'missing', so the user can weigh what is absent - the archive never loses something silently.
Note that pack() only reports the paths it refused, never a 7z failure, so export() checks the archive exists and is not empty; unpack() answers 'ok', 'password' or 'check_path'.
- author
INRAI
Table of Contents
Constants
- attach_folder : mixed = 'attach'
- Folder inside the archive holding the files the description attaches as-is.
- files_folder : mixed = 'files'
- Folder inside the archive holding the media files.
- format_name : mixed = 'helphp-import-export'
- Identifies the archive format in manifest.json.
- format_version : mixed = 1
- Bumped when the manifest structure changes (an old archive must be refused).
- manifest_name : mixed = 'manifest.json'
- max_depth : mixed = 512
- Last-resort depth limit applied when the caller passes none to export().
Properties
- $last_extract : string
- Folder the last archive was extracted to, empty when there is nothing to clean.
Methods
- __construct() : mixed
- attached_files() : array<string|int, mixed>
- Files attached to the archive that was just imported, entry => absolute path.
- cleanup_extract() : void
- Deletes the folder the archive was extracted to (see self::$last_extract).
- export() : string|false
- Export the described tree to a zip archive.
- import() : int|false
- Import an archive produced by export().
- missing_files() : array<string|int, mixed>
- Files the last export could not include, empty when it was complete.
Constants
attach_folder
Folder inside the archive holding the files the description attaches as-is.
public mixed attach_folder = 'attach'Not media: no media_data / media_use row is written for them, nothing links them to a record. They exist for the payload of a module that generates a file instead of storing one - the compiled .css of a document, the theme.css of a theme - so the importer can re-parse it with the code that already knows the format.
files_folder
Folder inside the archive holding the media files.
public mixed files_folder = 'files'format_name
Identifies the archive format in manifest.json.
public mixed format_name = 'helphp-import-export'format_version
Bumped when the manifest structure changes (an old archive must be refused).
public mixed format_version = 1manifest_name
public mixed manifest_name = 'manifest.json'max_depth
Last-resort depth limit applied when the caller passes none to export().
public mixed max_depth = 512A description that loops is already caught by the branch registry (see describe_record()), so this is only a memory guard against a pathological tree: it must never be reached by real content. Counted per node walked, one step per expand, per children entry and per recursive level. Reaching it aborts the export, it never truncates the archive; a caller that wants another ceiling passes it to export().
Properties
$last_extract
Folder the last archive was extracted to, empty when there is nothing to clean.
public string $last_extract = ''Methods
__construct()
public __construct() : mixedattached_files()
Files attached to the archive that was just imported, entry => absolute path.
public attached_files() : array<string|int, mixed>The archive carries them under attach/ (see the 'attach' key of the description and self::attach_folder): they come from the exporter's disk, not from a record, and the library does nothing with them — it only hands them back. The paths live in the extraction folder, so they are only valid until cleanup_extract(): read the files you need first, then clean up.
Return values
array<string|int, mixed>cleanup_extract()
Deletes the folder the archive was extracted to (see self::$last_extract).
public cleanup_extract() : voidCalled by the modules once the import is finished, whatever its result.
export()
Export the described tree to a zip archive.
public export(array<string|int, mixed> $description[, string $zip_name = 'export' ][, string $output_dir = '' ][, int $max_depth = self::max_depth ][, bool $allow_incomplete = false ]) : string|falseThe tree is walked from the root node, every node read with its own conditions, translations, media and children, then laid out in a staging folder and compressed by Filesystem::pack() (7z must be on the PATH). A looping description is broken at the repeated record; any other failure makes the call return false with no archive at all, so a returned path always means a complete tree (see the class doc).
Parameters
- $description : array<string|int, mixed>
-
the tree description, see the class doc for every node key
- $zip_name : string = 'export'
-
archive base name without extension, filtered to [a-zA-Z0-9_.-] (default 'export')
- $output_dir : string = ''
-
folder receiving the archive, with its trailing slash optional (default <HOME_FOLDER>temp/)
- $max_depth : int = self::max_depth
-
safety net for the depth of this export, one step per expand, per children entry and per recursive level (default: the max_depth constant, 512); loops are broken by the branch registry, this only bounds a pathological tree and aborting on it is a refusal, never a truncation
- $allow_incomplete : bool = false
-
accept an archive with holes (default false). This flag is the SECOND CLICK of the export confirmation: the module calls export() once with false, gets false plus the list from missing_files(), shows that list to the admin and offers 'export anyway'. True is only passed when the admin takes that option. Nothing is built on the first call (no staging, no 7z run), so a refused export costs one walk. False: a media the instance does not have refuses the whole export, and missing_files() lists what was missing. True: the archive is written, the same list goes into the manifest under 'missing', and the caller is expected to show it to the user before they keep the file. A broken description is refused whatever this flag says.
Return values
string|false —absolute path of the zip file, false when nothing was written
import()
Import an archive produced by export().
public import(string $zip_path, array<string|int, mixed> $description[, string $work_dir = '' ]) : int|falseThe description is the same array as for the export, except that the root id is 0 or absent: the ids come from the archive. Each node may carry an 'import' section describing how to insert it, empty by default (faithful copy):
'import' => [ 'drop' => ['creation_date'], // columns not copied 'set' => ['active' => 0], // imposed values 'fk' => 'id_document_data', // receives the parent id 'link' => 'id_block', // receives the 'expand' sub-node id 'unique' => ['route'], // already used => suffixed -1, -2 ... 'rewrite' => ['type' => 'document¤{root_id}', 'module_param' => '{root_id}'], ]
Every record is inserted as a NEW record (no id is reused); files are copied into the instance files/ folder, renamed when the name is already taken, and media_data / media_use rows are rebuilt accordingly. The table written is the one named in the manifest, not the one named in the description.
The archive is extracted with Filesystem::unpack() (7z) under $work_dir and left there: the caller removes it with cleanup_extract(), in every case, success or failure - last_extract is recorded as soon as the folder exists, so an extraction that fails half way does not leak it. Nothing is rolled back on error, so a partial tree stays in the database, and the reason is in the log (Error::log), never in a return array.
Parameters
- $zip_path : string
-
archive to import
- $description : array<string|int, mixed>
-
tree description, same shape as for export, root id at 0
- $work_dir : string = ''
-
where the archive is extracted (default <HOME_FOLDER>temp/)
Return values
int|false —id of the imported root record, false on failure
missing_files()
Files the last export could not include, empty when it was complete.
public missing_files() : array<string|int, mixed>Filled with the physical paths a record references but the instance does not have, or that could not be staged. export() refuses the archive when the list is not empty, unless the caller passed $allow_incomplete = true; the list is then written in the manifest under 'missing', so the archive says what it lacks.
Return values
array<string|int, mixed>On this page - Table Of Contents
- Constants
- Properties
- Methods
Search results
- table: table name without the DB prefix, DB->table() is applied on both sides.
Placeholders are substituted here (block_{blockname}). Required on the root node;
a wrong name surfaces as "record not found in