Batch export of contacts
The code provided here will allow you to export contacts for the users. It can be very helpful if you need to backup user data.
To use the code, you will need to supply the following parameters:
- $aDomains
Contacts will only be exported for users in these domains. - $sStorePath
Filesystem path contacts will be saved to.
For each exported user, contacts are saved to file with their email as filename and .csv
extension.
<?php
$aDomains=array("mydomain.com", "anotherdomain.com");
$sStorePath="/var/www/files/backup/";
include __DIR__.'./system/autoload.php';
\Aurora\System\Api::Init(true);
$oCoreModule = \Aurora\System\Api::GetModule("Core");
$oContactsDecorator = \Aurora\System\Api::GetModuleDecorator('Contacts');
$oSync = new Aurora\Modules\Contacts\Classes\Csv\Sync();
$ul = $oCoreModule->getUserList();
$ulItems = $ul["Items"];
foreach ($ulItems as $key=>$item) {
$sEmail = $item["PublicId"];
$oUser = $oCoreModule->GetUserByPublicId($sEmail);
$iUserId = $oUser->EntityId;
$sDomain = \MailSo\Base\Utils::GetDomainFromEmail($sEmail);
if (in_array($sDomain,$aDomains)) {
$aContactsList = $oContactsDecorator->GetContacts($iUserId, 'personal', 0,0, \Aurora\Modules\Contacts\Enums\SortField::Name, \Aurora\System\Enums\SortOrder::ASC);
$aContacts = array();
foreach ($aContactsList["List"] as $aContactsEntry) {
$aContacts[]=$oContactsDecorator->GetContact($aContactsEntry["UUID"],$iUserId);
}
file_put_contents($sStorePath."/".$sEmail.".csv", $oSync->Export($aContacts));
}
}
Now let's solve the opposite task - importing the data we have exported. It is assumed the data are imported into a blank installation; if you attempt to import contacts into accounts which already has contacts, there may be duplicates.
<?php
$sStorePath="/var/www/html/files/backup/";
include __DIR__.'/system/autoload.php';
\Aurora\System\Api::Init(true);
$oCoreDecorator = \Aurora\System\Api::GetModuleDecorator('Core');
$oContactsDecorator = \Aurora\System\Api::GetModuleDecorator('Contacts');
$oSync = new Aurora\Modules\Contacts\Classes\Csv\Sync();
$dirs = array_filter(glob($sStorePath.'*'), 'is_dir');
foreach ($dirs as $dir) {
$sEmail = basename($dir);
$UserId = \Aurora\System\Api::getUserIdByPublicId($sEmail);
$files = array_filter(glob($sStorePath.$sEmail.'/*'), 'is_file');
foreach ($files as $file) {
$ffile = basename($file);
$fname = pathinfo($ffile, PATHINFO_FILENAME);
$fext = strtolower(pathinfo($ffile, PATHINFO_EXTENSION));
if ($fext === "csv") {
$oSync->Import($UserId, $file, "", "personal");
}
}
}