--- loncom/interface/lonnotify.pm	2005/08/02 05:03:10	1.1
+++ loncom/interface/lonnotify.pm	2008/11/17 17:10:57	1.29
@@ -1,3 +1,7 @@
+# The LearningOnline Network with CAPA
+# Sending messages
+#
+# $Id: lonnotify.pm,v 1.29 2008/11/17 17:10:57 schafran Exp $
 #
 # Copyright Michigan State University Board of Trustees
 #
@@ -27,10 +31,15 @@ package Apache::lonnotify;
 use strict;
 use Apache::lonnet;
 use Apache::loncommon;
-use Apache::lonsupportreq;
+use Apache::courseclassifier;
 use LONCAPA::Enrollment;
 use Apache::Constants qw(:common :http);
 use Apache::lonlocal;
+use Mail::Send;
+use HTML::TokeParser;
+use HTML::Entities;
+use lib '/home/httpd/lib/perl/';
+use LONCAPA;
 
 sub handler {
     my ($r) = @_;
@@ -40,31 +49,319 @@ sub handler {
     if ($r->header_only) {
         return OK;
     }
-#    my $codedom = $env{'request.role.domain'};
-    my $cdom = 'northwood5';
-    unless (&Apache::lonnet::allowed('psa',$env{'request.role.domain'})) {
+    my $cdom = $env{'request.role.domain'};
+    unless (&Apache::lonnet::allowed('psa',$cdom)) {
         # Not allowed to broadcast e-mail system-wide 
         $env{'user.error.msg'}="/adm/notify:psa:0:0:Cannot broadcast e-mail systemwide";
         return HTTP_NOT_ACCEPTABLE;
     }
 
+    &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
+                                            ['command']);
     my $command = $env{'form.command'};
+    my $origin = $env{'form.origin'};
+
     &Apache::lonhtmlcommon::clear_breadcrumbs();
+
     &Apache::lonhtmlcommon::add_breadcrumb
         ({href=>'/adm/notify',
-          text=>"Broadcast e-mail"});
+          text=>"Broadcast E-mail"});
     if ($command eq 'process') {
-        &print_request_receipt($r,$cdom);
+        &print_request_receipt($r,$command,$cdom);
     } elsif ($command eq 'compose') {
-        &print_composition_form($r,$cdom);
+        &print_composition_form($r,$command,$cdom);
+    } elsif ($command eq 'pick_target') {
+        &print_selection_form($r,$command,$cdom);
+    } elsif ($command eq 'pick_display') {
+        &print_display_option_form($r,$command,$cdom);
+    } elsif ($command eq 'display') {
+        &print_display($r,$command,$cdom);
     } else {
-        &print_selection_form($r,$cdom);
+        &print_front_page($r,'front',$cdom);
     }
     return OK;
 }
 
+sub add_script {
+    my ($js) = @_;
+    return '<script type="text/javascript">'."\n".$js."\n".'</script>';
+}
+
+sub start_page {
+    my ($jscript,$bread_title,$formname) = @_;
+
+    my $loadcode;
+    if ((defined($env{'form.origin'})) 
+	&& ($env{'form.command'} eq 'compose' 
+	    || $env{'form.command'} eq 'pick_target' 
+	    || $env{'form.command'} eq 'pick_display')) {
+        if ($env{'form.origin'} ne '') {
+            $loadcode = 'javascript:setFormElements(document.'.$env{'form.command'}.')';
+            if (($env{'form.command'} eq 'pick_target') 
+		&& (($env{'form.origin'} eq 'compose')
+		    || ($env{'form.origin'} eq 'process'))) {
+                if ($env{'form.coursepick'} eq 'category') {
+                    $loadcode .= ';javascript:setCourseCat(document.'.$env{'form.command'}.')';
+                }
+            }
+        }
+    }
+    
+    my $start_page = 
+	&Apache::loncommon::start_page('Broadcast e-mail to users', $jscript,
+				       {'add_entries' => 
+					    {'onload' => $loadcode,},});
+    my $breadcrumbs =
+	&Apache::lonhtmlcommon::breadcrumbs($bread_title,
+					    'Broadcast_system_email');
+    my $output = <<"ENDONE";
+$start_page
+$breadcrumbs
+<br />
+<form name="$formname" method="POST">
+ENDONE
+
+    return $output;
+}
+
+sub end_page {
+    return '</form>'.&Apache::loncommon::end_page();
+}
+
+sub print_front_page {
+    my ($r,$formname,$cdom) = @_;
+
+    my $jscript = qq|
+function next_page(caller) {
+    if (caller == 'view') {
+        document.front.command.value="pick_display"
+    }
+    else {
+        document.front.command.value="pick_target"
+    }
+    document.front.submit()
+}
+    |; 
+
+    my $output = &start_page(&add_script($jscript),
+			     'Broadcast e-mail to Domain', $formname);
+
+    $output .= '<input type="hidden" name="command" />';
+    $output .= '<table class="LC_notify_front_page">'.
+              '<tr><td><a href="javascript:next_page('."'new'".')">'.
+              'Send a new e-mail to selected users from this domain</a></td></tr><tr>'.
+              '<td><a href="javascript:next_page('."'view'".')">'.
+              'Display e-mail sent by Domain Coordinators in this domain'.
+              '</a></td></tr></table>';
+    $output .= &end_page();
+
+    $r->print($output);
+    return;
+}
+
+sub print_display_option_form {
+    my ($r,$formname,$cdom) = @_;
+    &Apache::lonhtmlcommon::add_breadcrumb({text=>"Display options"});
+
+    my $cmd = 'display';
+    my $submit_text = 'Display e-mail';
+    my @roles = ('dc');
+    my $now = time;
+
+    my $startdateform = &Apache::lonhtmlcommon::date_setter($formname,
+                                                            'startdate',
+                                                            $now);
+    my $enddateform = &Apache::lonhtmlcommon::date_setter($formname,
+                                                          'enddate',
+                                                          $now);
+    my %elements = (
+        startdate_month => 'selectbox',
+        startdate_hour => 'selectbox',
+        enddate_month => 'selectbox',
+        enddate_hour => 'selectbox',
+        startdate_day => 'text',
+        startdate_year => 'text',
+        startdate_minute => 'text',
+        startdate_second => 'text',
+        enddate_day => 'text',
+        enddate_year => 'text',
+        enddate_minute => 'text',
+        enddate_second => 'text',
+        sender => 'checkbox',
+    );
+    my $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements);
+
+    my $output = &start_page(&add_script($jscript),
+			     'Broadcast e-mail display options', $formname);
+
+    $output .= &Apache::lonhtmlcommon::start_pick_box();
+    $output .= &Apache::lonhtmlcommon::row_title(&mt('Date range'));
+    $output .= '<table><tr><td>'.&mt('Earliest to display:').' </td><td>'.
+                $startdateform.'</td></tr>';
+    $output .= '<tr><td>'.&mt('Latest to display:').' </td><td>'.$enddateform.
+               '</td></tr></table>';
+    $output .= &Apache::lonhtmlcommon::row_closure();
+    $output .= &Apache::lonhtmlcommon::row_title(&mt('Choose sender(s)'));
+    my %personnel = &Apache::lonnet::get_domain_roles($cdom,\@roles);
+    my @domcc = ();
+    foreach my $server (keys %personnel) {
+        foreach my $user (sort(keys %{$personnel{$server}})) {
+            my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
+            unless (grep/^$uname:$udom$/,@domcc) {
+                my %userinfo = &Apache::lonnet::get('environment',['lastname','firstname'],$udom,$uname);
+                $output .= '<input type="checkbox" name="sender" value="'.$uname.':'.$udom.'" />&nbsp;'.$userinfo{'firstname'}.' '.$userinfo{'lastname'}.'&nbsp;&nbsp;('.$uname.':'.$udom.')';
+                push (@domcc,$uname.':'.$udom);
+            }
+        }
+    }
+    $output .= &Apache::lonhtmlcommon::row_closure();
+    $output .= &Apache::lonhtmlcommon::submit_row(&mt('Submit'),$cmd,$submit_text);
+    $output .= &Apache::lonhtmlcommon::end_pick_box();
+    $output .= qq(<input type="hidden" name="sortby" value="date" />\n).
+	&end_page();
+    $r->print($output);
+    return;
+}
+
+sub print_display {
+    my ($r,$formname,$cdom) = @_;
+    &Apache::lonhtmlcommon::add_breadcrumb
+         ({href=>"javascript:goBack('pick_display')",
+          text=>"Display options"},
+         {text=>"E-mail display"});
+
+    my $msgcount = 0;
+    my $start = &Apache::lonhtmlcommon::get_date_from_form('startdate');
+    my $end = &Apache::lonhtmlcommon::get_date_from_form('enddate');
+    my @senders = &Apache::loncommon::get_env_multiple('form.sender');
+    my %sentmail = &Apache::lonnet::dcmaildump($cdom,$start,$end,\@senders);
+    my %dcmail = ();
+    my %Sortby = ();
+    my $jscript = <<"ENDSCRIPT";
+function changeSort(caller) {
+    document.$formname.command.value = '$formname';
+    document.$formname.sortby.value = caller;
+    document.$formname.submit();
+}
+function goBack(target) {
+    document.$formname.command.value = target;
+    document.$formname.submit();
+}
+
+ENDSCRIPT
+
+    my $output = &start_page(&add_script($jscript),
+			     'Display Broadcast e-mail', $formname);
+
+    foreach my $msgid (keys(%sentmail)) {
+        my %content = &Apache::lonmsg::unpackagemsg($sentmail{$msgid});
+        $msgcount ++;
+        %{$dcmail{$msgid}} = ();
+        foreach my $item (keys(%content)) {
+            if ($item eq 'recipient') {
+                foreach my $user (keys(%{$content{recipient}})) {
+                    $dcmail{$msgid}{recipient}{$user} = $content{recipient}{$user};
+                }
+            } else {
+                $dcmail{$msgid}{$item} = $content{$item};
+            }
+        }
+    }
+    $output .= &Apache::loncommon::start_data_table();
+    if ($msgcount > 0) {
+        $output .= &Apache::loncommon::start_data_table_header_row().
+	    '<th><a href="javascript:changeSort(\'date\')">Date</a></th>'.
+	    '<th><a href="javascript:changeSort(\'subject\')">Subject</a></th>'.
+	    '<th><a href="javascript:changeSort(\'sender\')">Sender</a></th>'.
+	    '<th><a href="javascript:changeSort(\'message\')">Message</a></th>'.
+	    '<th><a href="javascript:changeSort(\'recipients\')">Recipients</a></th>'.
+	    &Apache::loncommon::end_data_table_header_row();
+
+        if (($env{'form.sortby'} eq 'date') || ($env{'form.sortby'} eq '') || (!defined($env{'form.sortby'})) || (($env{'form.sortby'} eq 'sender') && (@senders <= 1))) {
+            foreach my $msgid (sort(keys(%dcmail))) {
+                my $recipients = '';
+                my ($date,undef,$sname,$sdom) =
+                                  &Apache::lonmsg::unpackmsgid($msgid,undef,1);
+                $date = &Apache::lonlocal::locallocaltime($date);
+                foreach my $user (sort(keys(%{$dcmail{$msgid}{recipient}}))) {
+                    $recipients .= $dcmail{$msgid}{recipient}{$user}.', ';
+                }
+                $recipients =~ s/,\s$//;
+                $output .= &Apache::loncommon::start_data_table_row().
+		    '<td><small>'.$date.'</small></td>'.
+		    '<td><small>'.&cr_to_br($dcmail{$msgid}{subject}).'</small></td>'.
+		    '<td><small>'.$sname.':'.$sdom.'</small></td><td><small>'.&cr_to_br($dcmail{$msgid}{message}).'</small></td>'.
+		    '<td><small>'.$recipients.'</small></td>'."\n".
+		    &Apache::loncommon::end_data_table_row();
+            }
+        } else {
+            foreach my $msgid (sort(keys(%dcmail))) {
+                my ($date,undef,$sname,$sdom) =
+                                   &Apache::lonmsg::unpackmsgid($msgid,undef,1);
+                if ($env{'form.sortby'} eq 'subject') {
+                    push @{$Sortby{$dcmail{$msgid}{subject}}},$msgid;
+                } elsif ($env{'form.sortby'} eq 'message') {
+                    push @{$Sortby{$dcmail{$msgid}{message}}},$msgid;
+                } elsif ($env{'form.sortby'} eq 'recipients') {
+                    my $recipients ='';
+                    foreach my $user (sort(keys(%{$dcmail{$msgid}{recipient}}))) {
+                        $recipients .= $dcmail{$msgid}{recipient}{$user}.', ';
+                    }
+                    $recipients =~ s/,\s$//;
+                    push @{$Sortby{$recipients}},$msgid;
+                } elsif ($env{'form.sortby'} eq 'sender') {
+                    if (@senders > 1) {
+                       push @{$Sortby{$sname.':'.$sdom}},$msgid;
+                    }
+                }
+            }
+            foreach my $key (sort(keys(%Sortby))) {
+                foreach my $msgid (@{$Sortby{$key}}) {
+                    my $recipients = '';
+                    if ($env{'form.sortby'} eq 'recipients') {
+                        $recipients = $key;
+                    } else {
+                        foreach my $user (sort(keys(%{$dcmail{$msgid}{recipient}}))) {
+                            $recipients .= $dcmail{$msgid}{recipient}{$user}.', ';
+                        }
+                        $recipients =~ s/,\s$//;
+                    }
+                    my ($date,undef,$sname,$sdom) =
+                                   &Apache::lonmsg::unpackmsgid($msgid,undef,1);
+                    $date = &Apache::lonlocal::locallocaltime($date);
+                    $output .=  &Apache::loncommon::start_data_table_row().
+			'<td><small>'.$date.'</small></td>'.
+			'<td><small>'.&cr_to_br($dcmail{$msgid}{subject}).'</small></td>'.
+			'<td><small>'.$sname.':'.$sdom.'</small></td>'.
+			'<td><small>'.&cr_to_br($dcmail{$msgid}{message}).'</small></td>'.
+			'<td><small>'.$recipients.'</small></td>'."\n".
+			&Apache::loncommon::end_data_table_row();
+                }
+            }
+        }
+    } else {
+        $output .= &Apache::loncommon::start_data_table_empty_row().
+	    '<td>No mail sent matching supplied criteria</td>'.
+	    &Apache::loncommon::end_data_table_empty_row();
+    }
+    $output .= &Apache::loncommon::end_data_table();
+    $output .= &Apache::lonhtmlcommon::echo_form_input(['sortby','command','origin']);
+    my $curr_sortby;
+    if (defined($env{'form.sortby'})) {
+        $curr_sortby = $env{'form.sortby'};
+    } else {
+        $curr_sortby = 'date';
+    }
+    $output .= qq(<input type="hidden" name="origin" value="$formname" />\n);
+    $output .= qq(<input type="hidden" name="command" />\n);
+    $output .= qq(<input type="hidden" name="sortby" value="$curr_sortby" />\n);
+    $output .= &end_page();
+    $r->print($output);
+    return;
+}
+
 sub print_selection_form {
-    my ($r,$cdom) = @_;
+    my ($r,$formname,$cdom) = @_;
     my %coursecodes = ();
     my %codes = ();
     my @codetitles = ();
@@ -77,421 +374,440 @@ sub print_selection_form {
     my $totcodes = 0;
     my $format_reply;
     my $jscript = '';
-    my $loaditems = qq|
-function initialize_codes() {
-    return;
-}
-    |;
-    $totcodes = &Apache::lonsupportreq::retrieve_instcodes(\%coursecodes,$cdom,$totcodes);
+    my %lt=&Apache::lonlocal::texthash(
+               'buil' => 'Building valid e-mail address from username, if missing from preferences:',
+               'kerb' => 'Kerberos: enter default for each realm used in the domain, with comma separation of entries',
+               'infs' => 'Internal, Filesystem and Local authentication: enter single default.',
+               'comp' => 'Compose E-mail'
+           );
+    &Apache::lonhtmlcommon::add_breadcrumb
+          ({text=>"Select Audience"});
+
+    $totcodes = &Apache::courseclassifier::retrieve_instcodes(\%coursecodes,$cdom,$totcodes);
     if ($totcodes > 0) {
         $format_reply = &Apache::lonnet::auto_instcode_format($caller,$cdom,\%coursecodes,\%codes,\@codetitles,\%cat_titles,\%cat_order);
         if ($format_reply eq 'ok') {
             my $numtypes = @codetitles;
-            &Apache::lonsupportreq::build_code_selections(\%codes,\@codetitles,\%cat_titles,\%cat_order,\%idlist,\%idnums,\%idlist_titles);
-            &Apache::lonsupportreq::javascript_code_selections($numtypes,\%cat_titles,\$jscript,\%idlist,\%idnums,\%idlist_titles,\@codetitles);
-            $loaditems = '';
+            &Apache::courseclassifier::build_code_selections(\%codes,\@codetitles,\%cat_titles,\%cat_order,\%idlist,\%idnums,\%idlist_titles);
+            my ($scripttext,$longtitles) = &Apache::courseclassifier::javascript_definitions(\@codetitles,\%idlist,\%idlist_titles,\%idnums,\%cat_titles);
+            my $longtitles_str = join('","',@{$longtitles});
+            my $allidlist = $idlist{$codetitles[0]};
+            $jscript .= &Apache::courseclassifier::courseset_js_start($formname,$longtitles_str,$allidlist);
+            $jscript .= $scripttext;
+            $jscript .= &Apache::courseclassifier::javascript_code_selections($formname,@codetitles);
         }
     }
 
-    my $function = &Apache::loncommon::get_users_function();
-    my $tablecolor = &Apache::loncommon::designparm($function.'.tabbg');
-    my $bodytag = &Apache::loncommon::bodytag('Broadcast e-mail to users');
-    my $html=&Apache::lonxml::xmlbegin();
-    my $breadcrumbs = &Apache::lonhtmlcommon::breadcrumbs
-            (undef,'Broadcast e-mail to users','Broadcast_system_email');
-    $r->print(<<ENDONE);
-$html
-<head>
- <title>LON-CAPA Notification E-mail</title>
-<script type"text/javascript">
-$jscript
-</script>
-</head>
-$bodytag
-$breadcrumbs
-<br />
-<form method="post" name="logproblem">
- <table width="580" border="0" cellpadding="0" cellspacing="0" bgcolor="#000000">
-  <tr>
-   <td>
-    <table width="100%" border="0" cellpadding="0" cellspacing="1" bgcolor="#000000">
-     <tr>
-      <td>
-       <table width="100%" border="0" cellpadding="0" cellspacing="0" bgcolor="#ffffff">
-        <tr>
-         <td>
-          <table width="100%" border="0" cellpadding="0" cellspacing="1" bgcolor="#ffffff">
-           <tr>
-            <td width="140" bgcolor="$tablecolor">
-             <table width="140" border="0" cellpadding="8" cellspacing="0">
-              <tr>
-               <td align="right"><b>Roles:</b>
-               </td>
-              </tr>
-             </table>
-            </td>
-            <td width="100%" valign="top">
-             <table width="100%" border="0" cellpadding="8" cellspacing="0">
-              <tr>
-               <td>
-                <select name="roles" multiple>
-ENDONE
-    foreach  ('cc','in','ta','ep','ad') {
-        my $plrole=&Apache::lonnet::plaintext($_);
-        $r->print('  <option value="'.$_.'">'.$plrole.'</option>');
-    }
-    $r->print(<<ENDTWO);
-                </select>
-               </td>
-              </tr>
-             </table>
-            </td>
-           </tr>
-           <tr>
-            <td width="140" bgcolor="$tablecolor">
-             <table width="140" border="0" cellpadding="8" cellspacing="0">
-              <tr>
-               <td align="right"><b>Courses:</b>
-               </td>
-              </tr>
-             </table>
-            </td>
-            <td width="100%" valign="top">
-             <table width="100%" border="0" cellpadding="8" cellspacing="0">
-              <tr>
-               <td>
-ENDTWO
-    if ($totcodes > 0) {
-        my $numtitles = @codetitles;
-        if ($numtitles == 0) {
-            $r->print('No institutional course code categories found.<br />Can not select courses to receive e-mail.');
-        } else {
-            $r->print('<table><tr><td>'.$codetitles[0].'<br />'."\n".
-               '<select name="'.$codetitles[0].
-               '" onChange="courseSet('."'$codetitles[0]'".')">'."\n".
-               ' <option value="-1" />Select'."\n");
-            my @items = ();
-            my @longitems = ();
-            if ($idlist{$codetitles[0]} =~ /","/) {
-                @items = split/","/,$idlist{$codetitles[0]};
-            } else {
-                $items[0] = $idlist{$codetitles[0]};
-            }
-            if (defined($idlist_titles{$codetitles[0]})) {
-                if ($idlist_titles{$codetitles[0]} =~ /","/) {
-                    @longitems = split/","/,$idlist_titles{$codetitles[0]};
-                } else {
-                    $longitems[0] = $idlist_titles{$codetitles[0]};
-                }
-                for (my $i=0; $i<@longitems; $i++) {
-                    if ($longitems[$i] eq '') {
-                        $longitems[$i] = $items[$i];
-                    }
-                }
-            } else {
-                @longitems = @items;
-            }
-            for (my $i=0; $i<@items; $i++) {
-                $r->print(' <option value="'.$items[$i].'">'.$longitems[$i].'</option>');
-            }
-            $r->print('</select></td>');
-            for (my $i=1; $i<$numtitles; $i++) {
-                $r->print('<td>'.$codetitles[$i].'<br />'."\n".
-                          '<select name="'.$codetitles[$i].
-                          '" onChange="courseSet('."'$codetitles[$i]'".')">'."\n".
-                          '<option value="-1">&lt;-Pick '.$codetitles[$i-1].'</option>'."\n".
-                          '</select>'."\n".
-                          '</td>'
-                );
-            }
-            $r->print('</tr></table>');
-        }
-    }
-    $r->print(<<END);
-               </td>
-              </tr>
-             </table>
-            </td>
-           </tr>
-           <tr>
-            <td width="140" bgcolor="$tablecolor">
-             <table width="140" border="0" cellpadding="8" cellspacing="0">
-              <tr>
-               <td align="right"><b>Submit:</b>
-               </td>
-              </tr>
-             </table>
-            </td>
-            <td width="100%" valign="top" align="right">
-             <br />
-             <input type="hidden" name="command" value="compose" />
-             <input type="submit" value="Compose Message"/> &nbsp;
-             <br /><br />
-            </td>
-           </tr>
-          </table>
-         </td>
-        </tr>
-       </table>
-      </td>
-     </tr>
-    </table>
-   </td>
-  </tr>
- </table>
-</form>
-</body>
-</html>
-END
+    my $cb_jscript = &Apache::loncommon::coursebrowser_javascript($cdom);
+
+    my %elements = (
+                     roles => 'selectbox',
+                     types => 'selectbox',
+                     Year => 'selectbox',
+                     coursepick => 'radio',
+                     coursetotal => 'text',
+                     courselist => 'text',
+                     internal => 'text',
+                     krb4 => 'text',
+                     krb5 => 'text',
+                     localauth => 'text',
+                     unix => 'text',
+                   );
+    $jscript .= &Apache::lonhtmlcommon::set_form_elements(\%elements);
+    if ($env{'form.coursepick'} eq 'category') {
+        $jscript .= qq|
+function setCourseCat(formname) {
+    if (formname.Year.options[formname.Year.selectedIndex].value == -1) {
+        return;
+    }
+    courseSet('Year');
+    for (var j=0; j<formname.Semester.length; j++) {
+        if (formname.Semester.options[j].value == "$env{'form.Semester'}") {
+            formname.Semester.options[j].selected = true;
+        }
+    }
+    if (formname.Semester.options[formname.Semester.selectedIndex].value == -1) {
+        return;
+    }
+    courseSet('Semester');
+    for (var j=0; j<formname.Department.length; j++) {
+        if (formname.Department.options[j].value == "$env{'form.Department'}") {
+            formname.Department.options[j].selected = true;
+        }
+    }
+    if (formname.Department.options[formname.Department.selectedIndex].value == -1) {
+        return;
+    }
+    courseSet('Department');
+    for (var j=0; j<formname.Number.length; j++) {
+        if (formname.Number.options[j].value == "$env{'form.Number'}") {
+            formname.Number.options[j].selected = true;
+        }
+    }
+}
+|; 
+    }
+
+
+    my $output = &start_page(&add_script($jscript).$cb_jscript,
+			     'Choose e-mail audience', $formname);
+
+    $output .= &Apache::lonhtmlcommon::start_pick_box();
+    my @roles = ('ow','cc','in','ta','ep','st','cr');
+    my %longtypes = ();
+    my %authtypes = ();
+    &form_elements(\%longtypes,\%authtypes);
+    my $descrip = $lt{'buil'}.' 
+<ul>
+<li>'.$lt{'kerb'}.'<br />(e.g., MSU.EDU=msu.edu, MSUE.EDU=msue.msu.edu).</li>
+<li>'.$lt{'infs'}.'</li>
+</ul>'."\n";
+    my $submit_text = $lt{'comp'};
+    my $cmd = 'compose';
+    $output .= &Apache::lonhtmlcommon::role_select_row(\@roles,'Roles');
+    $output .= &Apache::lonhtmlcommon::course_select_row('Courses',$formname,$totcodes,\@codetitles,\%idlist,\%idlist_titles);
+    $output .= &Apache::lonhtmlcommon::status_select_row(\%longtypes,&mt('Access status'));
+    $output .= &Apache::lonhtmlcommon::email_default_row(\%authtypes,&mt('Username -> Email conversion'),$descrip);
+    $output .= &Apache::lonhtmlcommon::submit_row(&mt('Submit'),$cmd,$submit_text);
+    $output .= &Apache::lonhtmlcommon::end_pick_box();
+    $output .= &end_page();
+    $r->print($output);
     return;
 }
 
 sub print_composition_form {
-    my ($r,$cdom) = @_;
-    my $function = &Apache::loncommon::get_users_function();
-    my $tablecolor = &Apache::loncommon::designparm($function.'.tabbg');
-    my $bodytag = &Apache::loncommon::bodytag('Broadcast e-mail to users');
-    my $html=&Apache::lonxml::xmlbegin();
+    my ($r,$formname,$cdom) = @_;
     &Apache::lonhtmlcommon::add_breadcrumb
-        ({href=>'/adm/notify?command=compose',
-          text=>"Compose Message"});
-    my $jscript = <<"END";
-function checkAll(field) {
-    if (field.length > 0) {
-        for (i = 0; i < field.length; i++) {
-            field[i].checked = true ;
-        }
-    } else {
-        field.checked = true
-    }
+        ({href=>"javascript:goBack('pick_target')",
+          text=>"Select Audience"},
+         {text=>"Compose E-mail"});
+    my $jscript = &Apache::loncommon::check_uncheck_jscript();
+    $jscript .= qq|
+function goBack(target) {
+    document.$formname.command.value = target;
+    document.$formname.submit();
 }
-                                                                                         
-function uncheckAll(field) {
-    if (field.length > 0) {
-        for (i = 0; i < field.length; i++) {
-            field[i].checked = false ;
-        }     } else {
-        field.checked = false ;
-    }
-}
-END
-    my $breadcrumbs = (&Apache::lonhtmlcommon::breadcrumbs
-        (undef,'Broadcast e-mail to users','Broadcast_system_email'));
-
-    $r->print(<<ENDONE);
-$html
-<head>
- <title>LON-CAPA Notification E-mail</title>
-<script type"text/javascript">
-$jscript
-</script>
-</head>
-$bodytag $breadcrumbs
-<br /> 
-ENDONE
-    my $instcode = '';
-    my @cats = ('Semester','Year','Department','Number');
-    foreach my $category (@cats) {
-        if (defined($env{'form.'.$category})) {
-            unless ($env{'form.'.$category} eq '-1') {
-                $instcode .= $env{'form.'.$category};
+|;
+
+    my %lt=&Apache::lonlocal::texthash(
+                      'nore' => 'No recipients identified',
+                      'emad' => 'e-mail address',
+                   );
+    my %elements = (
+                     subject => 'text',
+                     message => 'text',
+                     sender => 'text',
+                     recipient => 'checkbox',
+                   );
+    $jscript .= &Apache::lonhtmlcommon::set_form_elements(\%elements);
+
+    $r->print(&start_page(&add_script($jscript),
+			  'Broadcast e-mail to users', $formname));
+
+    my $coursefilter = $env{'form.coursepick'};
+    my %courses;
+    if ($coursefilter eq 'all') {
+        %courses = &Apache::lonnet::courseiddump($cdom,'.','.','.','.','.',
+                                                 undef,undef,'Course');
+    } elsif ($coursefilter eq 'category') {
+        my $instcode = '';
+        my @cats = ('Semester','Year','Department','Number');
+        foreach my $category (@cats) {
+            if (defined($env{'form.'.$category})) {
+                unless ($env{'form.'.$category} eq '-1') {
+                    $instcode .= $env{'form.'.$category};
+                }
             }
         }
+        if ($instcode eq '') {
+            $instcode = '.';
+        }
+        %courses = &Apache::lonnet::courseiddump($cdom,'.','.',$instcode,'.','.',
+                                                 undef,undef,'Course');
+    } elsif ($coursefilter eq 'specific') {
+        if ($env{'form.coursetotal'} > 1) {
+            my @course_ids = split(/&&/,$env{'form.courselist'});
+            foreach my $cid (@course_ids) {
+                $courses{$cid} = '';
+            }
+        } else {
+            $courses{$env{'form.courselist'}} = '';
+        }
     }
-    if ($instcode eq '') {
-        $instcode = '.';
-    }
-    my %courses = &Apache::lonnet::courseiddump($cdom,'.','.',$instcode,'.','.');
+
+    my @types = &Apache::loncommon::get_env_multiple('form.types');
     my @roles = &Apache::loncommon::get_env_multiple('form.roles');
+
+    my %longtypes = ();
+    my %authtypes = ();
+    my %email_defaults = ();
+
+    &form_elements(\%longtypes,\%authtypes);
+    foreach my $auth (keys(%authtypes)) {
+        if (exists($env{'form.'.$auth})) {
+             my $default = $env{'form.'.$auth};
+             $default =~ s/^,+//;
+             $default =~ s/,+$//;
+             if ($auth =~ /^krb/) {
+                 %{$email_defaults{$auth}} = ();
+                 if ($default =~ /,/) {
+                     my @items = split(/,/,$default);
+                     foreach my $item (@items) {
+                         my ($realm,$value) = split(/=/,$item);
+                         $email_defaults{$auth}{$realm} = $value;
+                     }
+                 } else {
+                     my ($realm,$value) = split(/=/,$default);
+                     $email_defaults{$auth}{$realm} = $value;
+                 }
+             } else {
+                 $email_defaults{$auth} = $default;
+             }
+         }
+    }
+
+    my $sender = &get_user_info($env{'user.name'},%email_defaults);
+
     my %recipients = ();
-    foreach my $course_id (keys %courses) {
-        &get_active_users($course_id,\@roles,\%recipients);
+    my %users = ();
+    my %access = ();
+    my @sections = ();
+    my $totalrecip = 0;
+    my @unmatched = ();
+    foreach my $role (@roles) {
+        %{$users{$role}} = ();
+    }
+    foreach my $type (@types) {
+        $access{$type} = $type;
+    }
+    foreach my $course_id (keys(%courses)) {
+        my %coursehash = 
+            &Apache::lonnet::coursedescription($course_id,{'one_time' => 1});
+        my $cdom = $coursehash{'domain'};
+        my $cnum = $coursehash{'num'};
+        &Apache::loncommon::get_course_users($cdom,$cnum,\%access,\@roles,\@sections,\%users);
+    }
+    foreach my $role (keys(%users)) {
+        foreach my $user (keys(%{$users{$role}})) {
+            unless (defined($recipients{$user})) {
+                $recipients{$user} = &get_user_info($user,%email_defaults);
+                if ($recipients{$user} eq '') {
+                    push @unmatched, $user;
+                } else {
+                    $totalrecip ++;
+                } 
+            }
+        }
     }
-    if (%recipients) {
-        $r->print('<form name="compose" method="post"> 
-<input type="hidden" command="process" />
- <table width="580" border="0" cellpadding="0" cellspacing="0" bgcolor="#000000">
-  <tr>
-   <td>
-    <table width="100%" border="0" cellpadding="0" cellspacing="1" bgcolor="#000000">
-     <tr>
-      <td>
-       <table width="100%" border="0" cellpadding="0" cellspacing="0" bgcolor="#ffffff">
-        <tr>
-         <td>
-          <table width="100%" border="0" cellpadding="0" cellspacing="1" bgcolor="#ffffff">
-           <tr>
-            <td width="140" bgcolor="'.$tablecolor.'">
-             <table width="140" border="0" cellpadding="8" cellspacing="0">
-              <tr>
-               <td align="right"><b>Subject:</b>
-               </td>
-              </tr>
-             </table>
-            </td>
-            <td width="100%" valign="top">
-             <table width="100%" border="0" cellpadding="8" cellspacing="0">
-              <tr>
-               <td><input type="text" name="subject" size="30" />
-               </td>
-              </tr>
-             </table>
-            </td>
-           </tr>
-           <tr>
-            <td width="140" bgcolor="'.$tablecolor.'">
-             <table width="140" border="0" cellpadding="8" cellspacing="0">
-              <tr>
-               <td align="right">Message:</td>
-               </td>
-              </tr>
-             </table>
-            </td>
-            <td width="100%" valign="top">
-             <table width="100%" border="0" cellpadding="8" cellspacing="0">
-              <tr>
-               <td>
-                  <textarea name="message" id="message"
-                   cols="60" rows="10" wrap="hard"></textarea>
-               </td>
-              </tr>
-             </table>
-            </td>
-           </tr>
-           <tr>
-            <td width="140" bgcolor="'.$tablecolor.'">
-             <table width="140" border="0" cellpadding="8" cellspacing="0">
-              <tr>
-               <td align="right"><b>Recipients:</b>
-               </td>
-              </tr>
-             </table>
-            </td>
-            <td width="100%" valign="top">
-             <table width="100%" border="0" cellpadding="8" cellspacing="0">
-              <tr>
-               <td>
-                <input type="button" value="check all"
-onclick="javascript:checkAll(document.compose.email)" />
-                &nbsp;&nbsp;<input type="button" value="uncheck all"
-onclick="javascript:uncheckAll(document.compose.email)" /><br />
-                <table border="0">');
-        foreach my $username (sort keys %recipients) {
+    my $output;
+  
+    if ($totalrecip > 0) {
+        $output .= &Apache::lonhtmlcommon::start_pick_box();
+        $output .= &Apache::lonhtmlcommon::row_title(&mt('Subject'));
+        $output .= '<input type="text" name="subject" size="30" />';
+        $output .= &Apache::lonhtmlcommon::row_closure();
+        $output .= &Apache::lonhtmlcommon::row_title(&mt('Message'));
+        $output .= '  <textarea name="message" id="message"
+                      cols="60" rows="10" wrap="hard"></textarea>';
+        $output .= &Apache::lonhtmlcommon::row_closure();
+        $output .= &Apache::lonhtmlcommon::row_title(&mt('Recipients'));
+        $output .= '<input type="button" value="check all" 
+                    onclick="javascript:checkAll(document.compose.recipient)" />
+                    &nbsp;&nbsp;<input type="button" value="uncheck all"
+                    onclick="javascript:uncheckAll(document.compose.recipient)" />
+                    <br />';
+	$output .= &Apache::loncommon::start_data_table();
+        if (keys(%recipients) > 0) {
+	    $output .= &Apache::loncommon::start_data_table_header_row();
+            $output .= '<th>&nbsp;<th>username:domain</th><th>'.$lt{'emad'}.'</th>';
+	    $output .= &Apache::loncommon::end_data_table_header_row();
+        }
+        foreach my $username (sort(keys(%recipients))) {
+	    $output .= &Apache::loncommon::start_data_table_row();
             if ($recipients{$username} =~ /\@/) {
-                my $value=&Apache::lonnet::escape($username).':'.&Apache::lonnet::escape($recipients{$username});
-                $r->print('<tr><td><input type="checkbox" name="email" value="'.$value.'" checked="checked" /></td><td>'.$username.'</td><td>'.$recipients{$username}.'</td></tr>');
-                $numrecep ++;
-            }
-        }
-        $r->print('
-                </table>
-               </td>
-              </tr>
-             </table>
-            </td>
-           </tr>
-           <tr>
-            <td width="140" bgcolor="'.$tablecolor.'">
-             <table width="140" border="0" cellpadding="8" cellspacing="0">
-              <tr>
-               <td align="right"><b>Submit:</b>
-               </td>
-              </tr>
-             </table>
-            </td>
-            <td width="100%" valign="top" align="right">
-             <br />
-             <input type="hidden" name="command" value="compose" />
-             <input type="submit" name="sendemail" value="Send Message"/> &nbsp;
-             <br /><br />
-            </td>
-           </tr>
-          </table>
-         </td>
-        </tr>
-       </table>
-      </td>
-     </tr>
-    </table>
-   </td>
-  </tr>
- </table>
-</form>');
+                my $value=&escape($username).':'.&escape($recipients{$username});
+                $output .= '<td><input type="checkbox" name="recipient" value="'.$value.'" /></td><td>'.$username.'</td><td>'.$recipients{$username}.'</td>';
+            }
+	    $output .= &Apache::loncommon::end_data_table_row();
+        }
+        $output .= &Apache::loncommon::end_data_table();
+        if (@unmatched) {
+            $output .= '<br /><br />'.&mt('Could not determine e-mail addresses for the following users:').'<ul>';
+            foreach my $username (sort @unmatched) {
+                $output .= '<li>'.$username.'</li>';
+            }
+            $output .= '</ul>';
+        }
+        $output .= &Apache::lonhtmlcommon::row_closure();
+        $output .= &Apache::lonhtmlcommon::row_title(&mt('Sender e-mail address'));
+        $output .= '<input type="text" name="sender" value="'.$sender.'" />';
+        $output .= &Apache::lonhtmlcommon::row_closure();
+        $output .= &Apache::lonhtmlcommon::submit_row(&mt('Submit'),'process',&mt('Send'));
+        $output .= &Apache::lonhtmlcommon::end_pick_box();
     } else {
-        $r->print('No recipients identified');
+        $output .= $lt{'nore'}."\n".
+                   '<input type="hidden" name="command" value="" />'."\n";
     }
-    $r->print('</body></html>');
+    $output .= '<input type="hidden" name="origin" value="'.$formname.'" />'."\n";
+    $output .= &Apache::lonhtmlcommon::echo_form_input(['command','origin','subject','message','recipient','sender'],);
+    $output .= &end_page();
+    $r->print($output);
     return;
 }
 
 
 sub print_request_receipt {
-    my ($r,$dom) =@_;
-    my @recipients = &Apache::loncommon::get_env_multiple('recipients');
+    my ($r,$formname,$dom) =@_;
+    my @recipients = &Apache::loncommon::get_env_multiple('form.recipient');
     my $subject = $env{'form.subject'};
     my $message = $env{'form.message'};
-    my $function = &Apache::loncommon::get_users_function();
-    my $tablecolor = &Apache::loncommon::designparm($function.'.tabbg');
-    my $bodytag = &Apache::loncommon::bodytag('Broadcast e-mail to users');
-    my $html=&Apache::lonxml::xmlbegin();
-    my $jscript;
-    my $breadcrumbs = &Apache::lonhtmlcommon::breadcrumbs
-            (undef,'Broadcast e-mail to users','Broadcast_system_email');
-    $r->print(<<ENDONE);
-$html
-<head>
- <title>LON-CAPA Notification E-mail</title>
-<script type"text/javascript">
-$jscript
-</script>
-</head>
-$bodytag
-$breadcrumbs
-ENDONE
-    $r->print($subject.'<br /><br />');
-    $r->print($message.'<br /><br />');
-    foreach my $person (@recipients) {
-        my ($username,$email) = split/:/,$person;
-        $r->print('user: '.&Apache::lonnet::unescape($username).' email: '.&Apache::lonnet::unescape($email).'<br />');
+    my $from = $env{'form.sender'};
+    my $jscript = <<ENDSCRIPT;
+function goBack(target) {
+    document.$formname.command.value = target;
+    document.$formname.submit();
+}
+ENDSCRIPT
+
+    &Apache::lonhtmlcommon::add_breadcrumb
+        ({href=>"javascript:goBack('pick_target')",
+          text=>"Select audience"});
+    &Apache::lonhtmlcommon::add_breadcrumb
+        ({href=>"javascript:goBack('compose')",
+          text=>"Compose E-mail"});
+    &Apache::lonhtmlcommon::add_breadcrumb
+        ({href=>"/adm/notify?command=process",
+          text=>"Outcome"});
+
+
+    my $output = &start_page(&add_script($jscript), 'E-mail Delivery',
+			     $formname);
+
+
+    my @deliveries = ();
+    &broadcast_email(\@recipients,$subject,$from,$message,\@deliveries);
+    if (@deliveries > 0) {
+	$output .= &Apache::loncommon::start_data_table();
+        &store_mail($subject,$message,$dom,\@deliveries);
+        $output .= &Apache::loncommon::start_data_table_header_row().
+	    '<th>'.&mt('Status').'</th>'.
+	    '<th>'.&mt('Subject').'</th>'.
+	    '<th>'.&mt('Message').'</th>'.
+	    '<th>'.&mt('Recipents').'</th>'.
+	    &Apache::loncommon::end_data_table_header_row();
+	$output .= &Apache::loncommon::start_data_table_row().
+	    '<td valign="middle">'.&mt('Sent').'</td>'.
+	    '<td valign="middle">'.&cr_to_br($subject).'</td>'.
+	    '<td valign="middle">'.&cr_to_br($message).'</td>'.
+	    '<td>';
+        foreach my $person (@deliveries) {
+            my ($username,$email) = split(/:/,$person);
+            $output .= &unescape($email).'&nbsp;('.&unescape($username).')<br />'."\n";
+        }
+        $output .= '</td>'.
+	    &Apache::loncommon::end_data_table_row().
+	    &Apache::loncommon::end_data_table();
+    } else {
+        $output .= 'No mail sent - no recipients identified'; 
     }
+    $output .= '<br /><a href="/adm/notify">Send another 
+e-mail?</a>'."\n";
+    $output .= '<input type="hidden" name="command" />'."\n".
+               '<input type="hidden" name="origin" value="'.$formname.'" />'."\n";
+    $output .= &Apache::lonhtmlcommon::echo_form_input(['command','origin']);
+    $output .= &end_page();
+    $r->print($output);
     return;
 }
 
-sub get_active_users {
-    my ($course_id,$roles,$recipients) = @_;
-    if (@{$roles} > 0) {
-        my ($cdom,$cnum) = split/_/,$course_id;
-        my @coursepersonnel = &Apache::lonnet::getkeys('nohist_userroles',$cdom,$cnum);
-        foreach my $person (@coursepersonnel) {
-            my ($role,$user) = ($person =~ /^([^:]*):(.+)$/);
-            if (($role) && (grep/^$role$/,@{$roles})) {
-                unless (exists($$recipients{$user})) {
-                    my ($uname,$udom) = split/:/,$user;
-                    if ($uname ne '' && $udom ne '') {
-                        if (&LONCAPA::Enrollment::check_user_status($udom,$uname,$cdom,$cnum,$role) eq 'ok') {
-                            my %userinfo = &Apache::lonnet::get('environment',['permanenetemail','notification','critnotification',],$udom,$uname);
-                            my @emailtypes = ('permanentemail','critnotification','notification');
-                            my $email = '';
-                            foreach (@emailtypes) {
-                                $email = $userinfo{$_};
-                                if ($email =~ /\@/) {
-                                    last;    
-                                }
-                            }
-                            if ($email eq '') {
-                               my $authinfo  = &Apache::lonnet::queryauthenticate($uname,$udom);
-                               my ($authtype,$autharg) = split/:/,$authinfo;
-                               if (($authtype =~ /^krb/) && ($autharg =~ /^MSU/)) {
-                                   $email = $uname.'@msu.edu';
-                               }  
-                            }
-                            $$recipients{$user} = $email;
-                        }
-                    }
-                }
+sub broadcast_email {
+    my ($recipients,$subject,$from,$message,$deliveries)=@_;
+# Should implement staggered delivery for large numbers of recipients?.
+    foreach my $user (@{$recipients}) {
+        my $msg = new Mail::Send;
+        my ($username,$to) = split(/:/,$user);
+        $username = &unescape($username);
+        $to = &unescape($to);
+        $msg->to($to);
+        $msg->subject($subject);
+        $msg->add('From',"$from");
+        if (my $fh = $msg->open()) {
+            print $fh $message;
+            $fh->close;
+            push(@{$deliveries},$user); 
+        }
+    }
+}
+
+sub get_user_info {
+    my ($user,%email_defaults) = @_;
+    my ($uname,$udom) = split(/:/,$user);
+    my @emailtypes = ('permanentemail','critnotification','notification');
+    my %userinfo = &Apache::loncommon::getemails($uname,$udom);
+    my $email = '';
+    foreach my $type (@emailtypes) {
+        $email = $userinfo{$type};
+        if ($email =~ /\@/) {
+            last;
+        }
+    }
+    if ($email eq '') {
+        my $authinfo  = &Apache::lonnet::queryauthenticate($uname,$udom);
+        my ($authtype,$autharg) = split(/:/,$authinfo);
+        if ($authtype =~ /^krb/) {
+            if (defined($email_defaults{$authtype}{$autharg})) {
+                $email = $uname.'@'.$email_defaults{$authtype}{$autharg};
+            }
+        } else {
+            if ((defined($email_defaults{$authtype})) && ($email_defaults{$authtype} ne '')) {
+                $email = $uname.'@'.$email_defaults{$authtype};
             }
         }
     }
+    return $email;
+}
+
+sub form_elements {
+   my ($longtypes,$authtypes) = @_;
+   %{$longtypes} = (
+                   active => 'Currently has access',
+                   previous => 'Previously had access',
+                   future => 'Will have future access',
+                   );
+   %{$authtypes} = (
+                   krb4 => 'Kerberos 4',
+                   krb5 => 'Kerberos 5',
+                   internal => 'Internal (LON-CAPA)',
+                   unix => 'Filesystem (UNIX)',
+                   localauth => 'Local/Customized',
+                   );
+   return;
+}
+
+sub store_mail {
+    my ($subject,$message,$domain,$recipients,$attachmenturl) = @_;
+    my $msgid;
+    ($msgid,$message) = &Apache::lonmsg::packagemsg($subject,$message,undef,undef,
+                        $attachmenturl,$recipients,undef,undef,'dcmail');
+
+# Store in dc email db files on primary library server for domain.
+    my $server = &Apache::lonnet::domain($domain,'primary');
+    if (defined($server)) {
+        unless (&Apache::lonnet::dcmailput($domain,$msgid,$message,$server) 
+                                                            eq 'ok') {
+            &Apache::lonnet::logthis('Storage of dc mail failed for domain'.
+                 $domain.' for server: '. $server.'.  Message ID was '.$msgid);
+        }
+    } else {
+        &Apache::lonnet::logthis('Storage of dc mail failed for domain'.
+           $domain.' as no primary server identified. Message ID was '.$msgid);
+    }
+}
+
+sub cr_to_br {
+    my $incoming = shift;
+    $incoming =~ s/\n/\<br \/\>/g;
+    return $incoming;
 }
 
 1;