outsider

Sync email accounts through imap on Plesk 12 Ubuntu/Debian

Feb 18th, 2016
409
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 5.38 KB | None | 0 0
  1. #!/usr/bin/php
  2. <?php
  3.     // Edit this to your needs (only need to change source, as target is your local server)
  4.     $source_connectionstring = "{127.0.0.1:993/imap/ssl/novalidate-cert}";
  5.     $target_connectionstring = "{localhost:143/imap/notls}";
  6.  
  7.     // Basic requirements check
  8.     if (!function_exists('mcrypt_decrypt'))
  9.         die('You need php\'s mcrypt extension in order for this tool to work.'.PHP_EOL);
  10.     if (!function_exists('imap_open'))
  11.         die('You need php\'s imap extension in order for this tool to work.'.PHP_EOL);
  12.     if (!function_exists('mb_convert_encoding'))
  13.         die('You need php\'s multibyte extension in order for this tool to work.'.PHP_EOL);
  14.    
  15.     $mycnf = parse_ini_file('/etc/mysql/debian.cnf');
  16.     $secret = file_get_contents('/etc/psa/private/secret_key');
  17.    
  18.     $db = new mysqli($mycnf['host'], $mycnf['user'], $mycnf['password'], 'psa' );
  19.    
  20.     function connect_imap($con, $ro = false)
  21.     {
  22.         global $user, $password;
  23.         $imap = @imap_open($con, $user, $password, ($ro ? OP_READONLY : OP_HALFOPEN), 10);
  24.         if (!$imap)
  25.         {
  26.             echo 'Unable to connect to ' . $con . ' : ' . imap_last_error() . PHP_EOL;
  27.             return false;
  28.         }
  29.         return $imap;
  30.     }
  31.    
  32.     $result = $db->query("SELECT CONCAT(mail_name,'@',name) as email,accounts.password FROM mail LEFT JOIN domains on domains.id=mail.dom_id LEFT JOIN accounts on accounts.id=mail.account_id");
  33.     while ($row = $result->fetch_assoc())
  34.     {
  35.         // No password? Then it's a forward, no need to sync
  36.         if (empty($row['password']))
  37.             continue;
  38.        
  39.         $user = $row['email'];
  40.         $hash = explode('$', $row['password']);
  41.         $iv = base64_decode($hash[2]);
  42.         $ct = base64_decode($hash[3]);
  43.         $password = str_replace("\0", '', mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $secret, $ct , MCRYPT_MODE_CBC, $iv));
  44.        
  45.         echo 'Syncing account '. $user . PHP_EOL;
  46.        
  47.         $source_imap = connect_imap($source_connectionstring, true);
  48.         if (!$source_imap) continue;
  49.  
  50.         $target_imap = connect_imap($target_connectionstring);
  51.         if (!$target_imap) continue;
  52.        
  53.         $targetfolders = array();
  54.         $target_folders = imap_list($target_imap, $target_connectionstring, '*');
  55.         if ($target_folders !== false)
  56.         {
  57.             foreach($target_folders AS $folder)
  58.                 $targetfolders[] = str_replace($target_connectionstring, '', $folder);
  59.         }
  60.        
  61.         $source_folders = imap_list($source_imap, $source_connectionstring, '*');  
  62.         if ($source_folders !== false)
  63.         {
  64.             $migratedfolders = array();
  65.             foreach ($source_folders as $value)
  66.             {
  67.                 $folderpath = str_replace($source_connectionstring, '', $value);
  68.                 if(in_array($folderpath, $migratedfolders))
  69.                     continue;
  70.                
  71.                 $targetroot = mb_convert_encoding($folderpath, "UTF7-IMAP","ISO-8859-15");
  72.                 echo ' - Folder: ' . $targetroot . PHP_EOL;
  73.                
  74.                 if (!in_array($targetroot, $targetfolders))
  75.                 {
  76.                     echo 'Creating ' . $targetroot . PHP_EOL;
  77.                     if(!imap_createmailbox($target_imap, $target_connectionstring . $targetroot))
  78.                     {
  79.                         echo 'Error creating the targetfolder ' . $folderpath . ':' . imap_last_error() . PHP_EOL;
  80.                         continue;
  81.                     }
  82.                 }
  83.                
  84.                 imap_reopen($source_imap, $source_connectionstring . $targetroot, OP_READONLY);
  85.                 $MC = imap_check($source_imap);
  86.                 $count = intval($MC->Nmsgs);
  87.                 echo ' - Messages: ' . $count . PHP_EOL;
  88.                
  89.                 if ($count)
  90.                 {
  91.                     $src_messages = array();
  92.                     $counter = 0;
  93.                     $fetchresult = imap_fetch_overview($source_imap, '1:' . $count, 0);
  94.                     foreach ($fetchresult as $overview)
  95.                     {
  96.                         $flags = array();
  97.                         if ($overview->flagged) $flags[] = '\Flagged';
  98.                         if ($overview->answered) $flags[] = '\Answered';
  99.                         if ($overview->deleted) $flags[] = '\Deleted';
  100.                         if ($overview->seen) $flags[] = '\Seen';
  101.                         if ($overview->draft) $flags[] = '\Draft';
  102.                        
  103.                         $src_messages[$counter] = $overview;
  104.                         $src_messages[$counter]->flags = implode(' ',$flags);
  105.                         $src_messages[$counter]->internaldate = gmdate('d-M-Y H:i:s O', $overview->udate);
  106.                    
  107.                         if (!isset($overview->message_id))
  108.                             $src_messages[$counter]->message_id = md5($overview->udate . '+' . $overview->size);
  109.                        
  110.                         $counter++;
  111.                     }
  112.                    
  113.                     // Remove messages we already have
  114.                     imap_reopen($target_imap, $target_connectionstring . $targetroot);
  115.                     $MC = imap_check($target_imap);            
  116.                     $fetchresult2 = imap_fetch_overview($target_imap, '1:' . $MC->Nmsgs, 0);
  117.                     foreach ($fetchresult2 as $overview)
  118.                     {
  119.                         foreach(array_keys($src_messages) AS $src)
  120.                         {
  121.                             if (!isset($overview->message_id))
  122.                                 $overview->message_id = md5($overview->udate . '+' . $overview->size);
  123.                            
  124.                             if ($src_messages[$src]->message_id == $overview->message_id)
  125.                             {
  126.                                 unset($src_messages[$src]);
  127.                                 break;
  128.                             }
  129.                         }
  130.                     }
  131.                     echo ' - Need to copy ' . count($src_messages) . ' mails.' . PHP_EOL;
  132.                    
  133.                     if (count($src_messages))
  134.                     {
  135.                         foreach ($src_messages AS $message)
  136.                         {                      
  137.                             echo '   - Transfering ' . $message->message_id . PHP_EOL;
  138.                             $msg = imap_fetchheader($source_imap, $message->msgno) . imap_body($source_imap, $message->msgno);
  139.                             if(!imap_append($target_imap, $target_connectionstring . $targetroot, $msg, $message->flags, $message->internaldate))
  140.                                 echo '     - Unable to migrate the email : ' . imap_last_error() . PHP_EOL;
  141.                         }  
  142.                     }
  143.                 }
  144.                 $migratedfolders[] = $folderpath;
  145.             }
  146.         }
  147.         imap_close($source_imap);
  148.         imap_close($target_imap);
  149.     }
  150. ?>
Add Comment
Please, Sign In to add comment