4 define('INSTALL_PATH', preg_replace('/bin\/$/', '', getcwd()) . '/');
5 ini_set('memory_limit', -1);
7 require_once INSTALL_PATH.'program/include/iniset.php';
10 * Parse commandline arguments into a hash array
12 function get_opt($aliases=array())
15 for ($i=1; $i<count($_SERVER['argv']); $i++)
17 $arg = $_SERVER['argv'][$i];
18 if (substr($arg, 0, 2) == '--')
20 $sp = strpos($arg, '=');
21 $key = substr($arg, 2, $sp - 2);
22 $value = substr($arg, $sp+1);
24 else if ($arg{0} == '-')
26 $key = substr($arg, 1);
27 $value = $_SERVER['argv'][++$i];
32 $args[$key] = preg_replace(array('/^["\']/', '/["\']$/'), '', $value);
34 if ($alias = $aliases[$key])
35 $args[$alias] = $args[$key];
41 function print_usage()
43 print "Usage: msgexport -h imap-host -u user-name -m mailbox name\n";
44 print "--host IMAP host\n";
45 print "--user IMAP user name\n";
46 print "--mbox Mailbox/folder name\n";
47 print "--file Mailbox/folder name\n";
52 $out = $GLOBALS['args']['file'] ? STDOUT : STDERR;
56 function progress_update($pos, $max)
58 $percent = round(100 * $pos / $max);
59 vputs(sprintf("%3d%% [%-51s] %d/%d\033[K\r", $percent, @str_repeat('=', $percent / 2) . '>', $pos, $max));
64 $args = get_opt(array('h' => 'host', 'u' => 'user', 'p' => 'pass', 'm' => 'mbox', 'f' => 'file')) + array('host' => 'localhost', 'mbox' => 'INBOX');
66 if ($_SERVER['argv'][1] == 'help')
71 else if (!$args['host'])
73 vputs("Missing required parameters.\n");
78 // prompt for username if not set
79 if (empty($args['user']))
82 $args['user'] = trim(fgets(STDIN));
85 // prompt for password
87 $args['pass'] = trim(fgets(STDIN));
91 $a_host = parse_url($args['host']);
94 $host = $a_host['host'];
95 $imap_ssl = (isset($a_host['scheme']) && in_array($a_host['scheme'], array('ssl','imaps','tls'))) ? TRUE : FALSE;
96 $imap_port = isset($a_host['port']) ? $a_host['port'] : ($imap_ssl ? 993 : 143);
100 $host = $args['host'];
104 // instantiate IMAP class
105 $IMAP = new rcube_imap(null);
107 // try to connect to IMAP server
108 if ($IMAP->connect($host, $args['user'], $args['pass'], $imap_port, $imap_ssl))
110 vputs("IMAP login successful.\n");
112 $IMAP->set_mailbox($args['mbox']);
114 vputs("Getting message list of {$args['mbox']}...");
115 vputs($IMAP->messagecount()." messages\n");
119 if (!($out = fopen($args['file'], 'w')))
121 vputs("Cannot write to output file\n");
128 for ($count = $IMAP->messagecount(), $i=1; $i <= $count; $i++)
130 $headers = $IMAP->get_headers($i, null, false);
131 $from = current($IMAP->decode_address_list($headers->from, 1, false));
133 fwrite($out, sprintf("From %s %s UID %d\n", $from['mailto'], $headers->date, $headers->uid));
134 fwrite($out, iil_C_FetchPartHeader($IMAP->conn, $IMAP->mailbox, $i, null));
135 fwrite($out, iil_C_HandlePartBody($IMAP->conn, $IMAP->mailbox, $i, null, 1));
136 fwrite($out, "\n\n\n");
138 progress_update($i, $count);
140 vputs("\ncomplete.\n");
144 vputs("IMAP login failed.\n");