Search by

d3yii2 / d3backupmodules

uldisn

There is no license information available for the latest version (dev-master) of this package.

Package info

github.com/d3yii2/d3backupmodules

pkg:composer/d3yii2/d3backupmodules

Statistics

Installs: 59

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

dev-master 2026-11-26 21:50 UTC

This package is auto-updated.

Last update: 2026-11-26 21:50:25 UTC


README

##Features

  • Creates compressed backup of preferred module data with it's attachments. (run from console with cron)
  • Sends out an email of process completion with link (depends on view)
  • Checks expire parameter to delete old compressed files.

Installation

The preferred way to install this extension is through composer.

Either run

$ composer require d3yii2/d3backupmodules "*"

or add

"d3yii2/d3backupmodules": "*"

to the require section of your composer.json file.

Configuration

change console.php

    'components' =>
        [
            'd3backupmodules' => [
                'class' => 'd3yii2\d3backupmodules\components\ModuleBackupBase',
                'modelComponents' => [2 => 'd3modules\d3invoices\components\InvInvoiceBackup'],
                'emailFrom' => 'Irēķini sistēma',
                'emailBody' => '<a href="{$link}" target="_blank">Lejuplādēt arhīvu</a>',
            ]
        ]

change main.php/web.php

    'modules' => [
        'd3backupmodules' => [
            'class' => 'd3yii2\d3backupmodules\Module',
            'backupDirectory' => $basePath . '/runtime/backups/'
        ]
    ]

SQL data backup

One user can be set as the data backup user (main.php / web.php):

    'modules' => [
        'd3backupmodules' => [
            'class' => 'd3yii2\d3backupmodules\Module',
            'backupDirectory' => 'archives',
            'dataBackupUsername' => 'backup.user',   // user.username; empty - switched off
        ]
    ]

When this user creates an archive:

  • D3BackupModule::createEntry() saves user_id, username and dataBackup = true in the data column;
  • CommandRunner opens the SQL dump before compile() and writes the company data (CompanySqlDump: own company, all partners, users - password hash and auth key are not exported); the component adds the module data to the same dump; the zip gets it as data.sql (INSERT statements, no mysqldump needed);
  • no "archive ready" e-mail is sent;
  • a line is written to the data backup log @runtime/logs/d3backup_data.log (CommandRunner dataBackupLogFile) and Yii log category d3backupmodules.dataBackup:
    2026-11-03 21:40:00 | backup_id=62 | sys_company_id=5 | company=SIA Firma | user=backup.user | component=...InvInvoiceBackup | records=120 | sql_rows=3450 | sql_errors=0 | DONE | zip=.../archives/....zip
    

For other users archives are created as before.

Zips are deleted after backupExpireDays (default 5 days) - copy data backups in time.

Component implementation (see InvInvoiceBackup::createSqlBackup()):

if ($module->isDataBackup()) {
    $dump = $this->createSqlDump();   // dump opened by CommandRunner, company data already in it
    try {
        $dump->table('inv_invoice', ['id' => $ids]);
    } finally {
        $this->finishSqlDump($dump);
    }
}

Restorable attachments (d3files)

By default attachments are added to the zip as attachments/{recordId}_{nr}_{fileName} (readable names for index.html). For a restorable data backup the component can store the files with the d3files storage path and add the d3files rows to data.sql:

if ($module->isDataBackup()) {
    $this->attachmentsDir = self::ATTACHMENTS_DIR_STORAGE;   // 'd3files'
}
foreach ($ids as $id) {
    $this->addRecordAttachments(InvInvoice::class, (int)$id);   // fills $attachments and $attachmentNames
}
...
$dump = $this->createSqlDump();
try {
    ...
} finally {
    $this->finishSqlDump($dump);   // also adds d3files_* rows of the added attachments
}

In the view (pass 'backup' => $this):

echo '<a href="' . Html::encode($backup->getAttachmentHref($a)) . '">' . Html::encode($backup->getAttachmentLabel($a)) . '</a>';

Zip: d3files/<ModelShortName>/<d3files_id>.<ext> - <ModelShortName> is the model of the base link (d3files_model.is_file = 1), the same directory as in the d3files upload directory. A file linked to many records is added once. finishSqlDump() adds to data.sql the rows the storage path is built from, for exactly the files added with addRecordAttachments(): d3files, d3files_model (links of the archived records, not deleted, and all base links of the files - also a deleted base link, like D3files::fileListForWidget()) and d3files_model_name. One file can be linked to many models; links to records outside the archive are not added. Do not dump d3files_* tables in the component. Restore: load data.sql, copy d3files/* into the company d3files upload directory.

Company data - components/CompanySqlDump::dump($dump, $sysCompanyId): own company, partners, branches, addresses, settings, users (secrets blanked), profiles and persons. Called by CommandRunner::run() once per data backup before compile() - do not call it in the components. It does not add module tables - e.g. inv_* tables are added by d3modules\d3invoices\components\InvCompanySqlDump.

SQL dump extensions

Rows that depend on the rows written by any component (e.g. labels of every record) are added by extensions - classes implementing SqlDumpExtensionInterface, configured in CommandRunner:

'sqlDumpExtensions' => [
    'd3yii2\d3labels\components\D3LabelsBackup',   // labels of all written records
],

For every data backup begin(SqlDump $dump, int $sysCompanyId) is called after the dump is opened and end() before it is closed. In begin() set SqlDump::$trackTables; SqlDump::table() then keeps the conditions of the written rows and SqlDump::getWrittenQuery($table) returns SELECT <pk> FROM <table> WHERE <cond1> OR <cond2> to use as sub query in end() (no id lists). BackupBase::sqlDumpCompanyData() is deprecated - for old components; it does nothing when the dump is the one opened by CommandRunner (BackupBase::$sqlDump).

Full company backup

All data of one system company in one zip: index.html (record and row counts), data.sql (company data, shared SQL parts, module data, d3files_* rows) and d3files/<Model>/<d3files_id>.<ext>.

Console config (console.php):

    'controllerMap' => [
        'company-backup' => 'd3yii2\d3backupmodules\commands\CompanyBackupController',
    ],
    'components' => [
        'd3backupmodules' => [
            'class' => 'd3yii2\d3backupmodules\components\CommandRunner',
            // ...
            /** module backup components, run in this order */
            'companyBackupComponents' => [
                'd3modules\d3invoices\components\InvInvoiceBackup',
                'd3modules\lietvediba\components\RkInvoiceBackup',
                'd3modules\lietvediba\components\RkContractBackup',
                'yii2d3\d3emails\components\EmailBackup',
            ],
            /** shared SQL parts, each called once: function (SqlDump $dump, int $sysCompanyId) */
            'companySqlDumps' => [
                ['d3modules\d3invoices\components\InvCompanySqlDump', 'dump'],
            ],
        ],
    ],

Run:

yii company-backup <sysCompanyId>                     # creates the request (D3BackupModule::createCompanyEntry())
yii d3system/d3-component-command d3backupmodules     # builds the zip (as the other archives)

components/CompanyBackup (always a data backup, no e-mail): CommandRunner writes the company data (CompanySqlDump), CompanyBackup calls companySqlDumps once and compileCompany() of every component.

A component for the full backup extends BackupBase and implements CompanyBackupInterface:

public function compileCompany(SqlDump $dump, int $sysCompanyId): int
// all company records: addRecordAttachments() + module tables; returns records count

It must not dump the company data, the shared parts (companySqlDumps) or rows another configured component dumps (e.g. contracts are dumped only by RkContractBackup) - every row once per data.sql.

Usage

After configuration, need to create custom component (see example bellow) in preferred module with view.

Important

Data column in database should be json format keyed with "id", "error", "date_from", "date_to"

Methods

Create custom filename by passing variables with an additional 8 char random string and returns it.

public function createFileName(string $sys_company_name, string $list_name, string $date_from, string $date_to):string

Creates a directory by passed name and generates first index.html from given $html string.

public function createFile(string $fileName, string $html):string

Attached files of one record: [fullPath => '{recordId}_{nr}_{fileName}'] (zip dir attachments/).

public static function getRecordFiles(string $className, int $recordId): array

Attached files of one record with the storage path: [fullPath => '<ModelShortName>/<d3files_id>.<ext>'] (use with $attachmentsDir = BackupBase::ATTACHMENTS_DIR_STORAGE).

public static function getRecordStorageFiles(string $className, int $recordId): array

Adds the attached files of one record to $attachments by $attachmentsDir (readable names or storage paths) and registers them for the SQL data backup (finishSqlDump() writes their d3files_* rows). Can be called for several model classes of the same record - files are added, numbering continues, a file already added is skipped.

public function addRecordAttachments(string $className, int $recordId): void

Link and original file name of an attachment for index.html.

public function getAttachmentHref(string $name): string
public function getAttachmentLabel(string $name): string

Zip directory for $attachments - property BackupBase::$attachmentsDir, default attachments.

Creates compressed file.

public function createZip(string $backUpFolder, string $fileNameFullPath, string $fileName, array $addFiles = [], D3BackupModule $model)

Examples of Custom component example :

public function compile(array $backupData, D3BackupModule $model)
{
   $moduleBackup = new ModuleBackupBase();
   $fileName = $moduleBackup->createFileName('Company', 'Invoices', $model->getDataValue('date_from'), $model->getDataValue('date_to'));
   $html = \Yii::$app->view->render('@vendor/d3modules/d3invoices/views/d3yii2-backup/index', ['backupData' => $backupData]);
   $backupFolder = $moduleBackup->createFile($fileName, $html);
   $moduleBackup->createZip($backupFolder, $moduleBackup->backupDirectory.$fileName, $fileName, [], $model);
}