#!/usr/bin/perl
#
# getOWAnames2.pl
#
#####################################################################
#    m0j0.j0j0 getOWAnames2
#
#####################################################################
#
#
# This script retrieves all names from the "Find Names" feature in OWA 
#
# updated for new (old?) version of Exchange... blah... need beer.
#

use LWP::UserAgent;
use HTTP::Cookies;

$ua = new LWP::UserAgent;

$username = "foo";
$password = "bar";
$host = "mail.foo.com";

# Creating initial connection to OWA
$req = new HTTP::Request GET => "http://$host/exchange/";
$req->authorization_basic($username, $password);
my $jar = HTTP::Cookies->new();
$ua->cookie_jar($jar);
my $res = $ua->request($req);
$jar->extract_cookies($res);

print "Connecting to OWA: ";
if ($res->is_success) { print "Success\n"; }
else { print $res->status_line, "\n"; }  

# Retrieve all user accounts
print "Retrieving OWA user names:\n";

getNames('a'..'z');

# a little recursion to get all those names...
sub getNames {
   my @letters = @_;
   foreach $letter (@letters) {
      if ( ! printNames($letter) ) { 
         foreach ('a'..'z') {
            getNames($letter . $_); 
         } 
      }
   }
}

# connect to OWA and grab the users
sub printNames {
   my $LastName = shift @_;
   $req = new HTTP::Request GET => "http://$host/exchange/$username/Inbox/?Cmd=galfind&DN=&LN=$LastName&FN=&TL=&AN=&CP=&DP=&OF=&CY=";
   $req->authorization_basic($username, $password);
   $jar->add_cookie_header($req);
   my $res = $ua->request($req);

   @results = split /\n/, $res->content;

   if (grep /This query would return too many addresses!/, @results) { return 0; }
   else {
      for (my $i=0; $i <= $#results; $i++) { 
         next unless $results[$i] =~ /<tr><td><font SIZE="2">/;

         my @row = split /<\/tr><tr>/, $results[$i];
         foreach(@row) {
             chomp;
             my @col = split /<\/td><td>/;
             my ($name) = $col[0] =~ /<td><font SIZE="2">(.*)<\/font>/;
             my ($phone) = $col[1] =~ /<font SIZE="2">(.*)<\/font>/; 
             my ($office) = $col[2] =~ /<font SIZE="2">(.*)<\/font>/; 
             my ($title) = $col[3] =~ /<font SIZE="2">(.*)<\/font>/; 
             my ($company) = $col[4] =~ /<font SIZE="2">(.*)<\/font>/; 
             my ($userid) = $col[5] =~ /<font SIZE="2">(.*)<\/font>/; 
             print $name, "::", $phone, "::", $office, "::", $title, "::", $company, "::", $userid, "\n";
         }
         last;
      }
      return 1;
   }
}
