Skip to content

Instantly share code, notes, and snippets.

@leda-ferreira
Created January 19, 2017 13:38
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save leda-ferreira/60efee6a8b73cc118f521f89ccb22957 to your computer and use it in GitHub Desktop.
Save leda-ferreira/60efee6a8b73cc118f521f89ccb22957 to your computer and use it in GitHub Desktop.
Roundcube - Import mbox backup file from Gmail
<?php
/* Usage: php import.php EMAIL PASSWORD /path/to/file.mbox */
$argv = $_SERVER['argv'];
array_shift($argv); // script name
$user = array_shift($argv);
if (!$user) {
die("EMAIL IS MISSING.\n");
}
$pass = array_shift($argv);
if (!$pass) {
die("PASSWORD IS MISSING.\n");
}
$file = array_shift($argv);
if (!$file) {
die("FILENAME IS MISSING.\n");
} elseif (!(file_exists($file) && is_file($file))) {
die("INVALID FILE.\n");
}
$destinationFolder = 'RECUPERADAS';
// <editor-fold defaultstate="collapsed" desc="1.) BOOTSTRAP DO ROUNDCUBE">
require_once 'program/include/iniset.php';
// init application, start session, init output class, etc.
$RCMAIL = rcmail::get_instance(0, $GLOBALS['env']);
// check if config files had errors
if ($err_str = $RCMAIL->config->get_error()) {
echo "CONFIG ERROR\n";
rcmail::raise_error(array(
'code' => 601,
'type' => 'php',
'message' => $err_str), false, true);
}
// check DB connections and exit on failure
if ($err_str = $RCMAIL->db->is_error()) {
echo "DATABASE ERROR\n";
rcmail::raise_error(array(
'code' => 603,
'type' => 'db',
'message' => $err_str), false, true);
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="2.) AUTENTICAÇÃO DO USUÁRIO">
$RCMAIL->kill_session();
$auth = $RCMAIL->plugins->exec_hook('authenticate', array(
'host' => $RCMAIL->autoselect_host(),
'user' => $user,
'pass' => $pass,
'cookiecheck' => false,
'valid' => true,
));
if ($auth['valid'] && !$auth['abort'] && $RCMAIL->login($auth['user'], $auth['pass'], $auth['host'], $auth['cookiecheck'])
) {
echo "LOGIN OK\n";
} else {
die("ERRO NO LOGIN\n");
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="3.) ABRIR ARQUIVO">
$imported = 0;
// read the first few lines to detect header-like structure
$fp = fopen($file, 'r');
do {
$line = fgets($fp);
} while ($line !== false && trim($line) == '');
if (!preg_match('/^From .+/', $line) && !preg_match('/^[a-z-_]+:\s+.+/i', $line)) {
die("ERRO NO preg_match\n");
}
// </editor-fold>
ini_set('display_errors', 1);
error_reporting(E_ALL & ~E_NOTICE);
set_time_limit(0);
$folder = array(
'name' => $destinationFolder,
'oldname' => null,
'class' => '',
'options' => array(),
'settings' => array('view_mode' => 0, 'sort_column' => null, 'sort_order' => null,),
'subscribe' => true,
);
$STORAGE = $RCMAIL->get_storage();
$RCMAIL->plugins->exec_hook('folder_create', array('record' => $folder));
$created = $STORAGE->create_folder($folder['name'], $folder['subscribe']);
$folders = array();
// <editor-fold defaultstate="collapsed" desc="4.) IMPORTAR MENSAGENS">
$message = $lastline = $folderName = $date = '';
fseek($fp, 0);
while (($line = fgets($fp)) !== false) {
$line = utf8_decode($line);
// importing mbox file, split by From - lines
if (strncmp($line, 'X-Gmail-Labels: ', 16) === 0 && strlen($line) > 16) {
$folderName = trim(substr($line, 16));
$folder['name'] = "{$destinationFolder}." . $folderName;
if (!array_key_exists($folderName, $folders)) {
$RCMAIL->plugins->exec_hook('folder_create', array('record' => $folder));
$created = $STORAGE->create_folder($folder['name'], $folder['subscribe']);
$folders[$folderName] = $folderName;
}
}
if ($lastline === '' && strncmp($line, 'From ', 5) === 0 && strlen($line) > 5) {
if (!$date) {
$exp = explode(' ', $line);
$date = implode(' ', array_slice($exp, 2));
}
if (!empty($message)) {
// unquote ">From " lines in message body
$message = rtrim(preg_replace('/\n>([>]*)From /', "\n\\1From ", $message));
if ($RCMAIL->storage->save_message($folder['name'], $message, '', false, array(), $date)) {
$imported++;
echo $imported, PHP_EOL;
} else {
rcube::raise_error("Failed to import message to " . $RCMAIL->storage->get_folder(), false, true);
}
$message = '';
$date = '';
$folder['name'] = $destinationFolder;
}
continue;
}
$message .= $line;
$lastline = rtrim($line);
}
$message = rtrim($message);
if (!empty($message) && $RCMAIL->storage->save_message($folder['name'], $message, '', false, array(), $date)) {
$imported++;
echo 'end ' . $imported . PHP_EOL;
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="5.) FIM">
if ($imported) {
echo "FORAM IMPORTADAS {$imported} mensagens.\n";
$OUTPUT->command('command', 'list');
} else {
echo "ERRO AO IMPORTAR AS MENSAGENS.\n";
}
// </editor-fold>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment