File:  [LON-CAPA] / loncom / interface / lonnotify.pm
Revision 1.44: download - view: text, annotated - select for diffs
Sat Mar 6 13:41:46 2021 UTC (3 years, 2 months ago) by raeburn
Branches: MAIN
CVS tags: version_2_12_X, version_2_11_X, version_2_11_4_uiuc, version_2_11_4_msu, version_2_11_4, version_2_11_3_uiuc, version_2_11_3_msu, version_2_11_3, HEAD
 - Missing localization call added.

    1: # The LearningOnline Network with CAPA
    2: # Sending messages
    3: #
    4: # $Id: lonnotify.pm,v 1.44 2021/03/06 13:41:46 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28:                                                                                 
   29: package Apache::lonnotify;
   30:                                                                                 
   31: use strict;
   32: use Apache::lonnet;
   33: use Apache::loncommon;
   34: use Apache::courseclassifier;
   35: use LONCAPA::Enrollment;
   36: use Apache::Constants qw(:common :http);
   37: use Apache::lonlocal;
   38: use Mail::Send;
   39: use HTML::TokeParser;
   40: use HTML::Entities;
   41: use lib '/home/httpd/lib/perl/';
   42: use LONCAPA;
   43: 
   44: sub handler {
   45:     my ($r) = @_;
   46:     &Apache::loncommon::content_type($r,'text/html');
   47:     $r->send_http_header;
   48: 
   49:     if ($r->header_only) {
   50:         return OK;
   51:     }
   52:     my $cdom = $env{'request.role.domain'};
   53:     unless (&Apache::lonnet::allowed('psa',$cdom)) {
   54:         # Not allowed to broadcast e-mail system-wide 
   55:         $env{'user.error.msg'}="/adm/notify:psa:0:0:Cannot broadcast e-mail systemwide";
   56:         return HTTP_NOT_ACCEPTABLE;
   57:     }
   58: 
   59:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
   60:                                             ['command']);
   61:     my $command = $env{'form.command'};
   62:     my $origin = $env{'form.origin'};
   63: 
   64:     &Apache::lonhtmlcommon::clear_breadcrumbs();
   65: 
   66:     &Apache::lonhtmlcommon::add_breadcrumb
   67:         ({href=>'/adm/notify',
   68:           text=>"Broadcast E-mail"});
   69:     if ($command eq 'process') {
   70:         &print_request_receipt($r,$command,$cdom);
   71:     } elsif ($command eq 'compose') {
   72:         &print_composition_form($r,$command,$cdom);
   73:     } elsif ($command eq 'pick_target') {
   74:         &print_selection_form($r,$command,$cdom);
   75:     } elsif ($command eq 'pick_display') {
   76:         &print_display_option_form($r,$command,$cdom);
   77:     } elsif ($command eq 'display') {
   78:         &print_display($r,$command,$cdom);
   79:     } else {
   80:         &print_front_page($r,'front',$cdom);
   81:     }
   82:     return OK;
   83: }
   84: 
   85: sub add_script {
   86:     my ($js) = @_;
   87:     return '<script type="text/javascript">'."\n".$js."\n".'</script>';
   88: }
   89: 
   90: sub start_page {
   91:     my ($jscript,$bread_title,$formname) = @_;
   92: 
   93:     my $loadcode;
   94:     if ((defined($env{'form.origin'})) 
   95: 	&& ($env{'form.command'} eq 'compose' 
   96: 	    || $env{'form.command'} eq 'pick_target' 
   97: 	    || $env{'form.command'} eq 'pick_display')) {
   98:         if ($env{'form.origin'} ne '') {
   99:             $loadcode = 'javascript:setFormElements(document.'.$env{'form.command'}.')';
  100:             if (($env{'form.command'} eq 'pick_target') 
  101: 		&& (($env{'form.origin'} eq 'compose')
  102: 		    || ($env{'form.origin'} eq 'process'))) {
  103:                 if ($env{'form.coursepick'} eq 'category') {
  104:                     $loadcode .= ';javascript:setCourseCat(document.'.$env{'form.command'}.')';
  105:                 }
  106:             }
  107:         }
  108:     }
  109:     
  110:     my $start_page = 
  111: 	&Apache::loncommon::start_page('Broadcast e-mail to users', $jscript,
  112: 				       {'add_entries' => 
  113: 					    {'onload' => $loadcode,},});
  114:     my $breadcrumbs =
  115: 	&Apache::lonhtmlcommon::breadcrumbs($bread_title,
  116: 					    'Broadcast_system_email');
  117:     my $output = <<"ENDONE";
  118: $start_page
  119: $breadcrumbs
  120: <br />
  121: <form name="$formname" method="post" action="">
  122: ENDONE
  123: 
  124:     return $output;
  125: }
  126: 
  127: sub end_page {
  128:     return '</form>'.&Apache::loncommon::end_page();
  129: }
  130: 
  131: sub print_front_page {
  132:     my ($r,$formname,$cdom) = @_;
  133: 
  134:     my $jscript = qq|
  135: function next_page(caller) {
  136:     if (caller == 'view') {
  137:         document.front.command.value="pick_display"
  138:     }
  139:     else {
  140:         document.front.command.value="pick_target"
  141:     }
  142:     document.front.submit()
  143: }
  144:     |; 
  145: 
  146: 
  147:     my @menu=
  148:         ({  categorytitle=>'Broadcast e-mail to Domain',
  149:         items =>[
  150:             {   linktext => 'Send e-mail to selected users',
  151:                 url => 'javascript:next_page('."'new'".')',
  152:                 permission => 1,
  153:                 #help => '',
  154:                 icon => 'mail-reply-all.png',
  155:                 linktitle => 'Send a new e-mail to selected users from this domain'
  156:             },
  157:             {   linktext => 'Display sent e-mails',
  158:                 url => 'javascript:next_page('."'view'".')',
  159:                 permission => 1,
  160:                 #help => '',
  161:                 icon => 'messalog.png',
  162:                 linktitle => 'Display e-mail sent by Domain Coordinators in this domain'
  163:             },
  164:         ]
  165:         },
  166:         );
  167: 
  168:     $r->print(
  169:         &start_page(&add_script($jscript),
  170:             'Broadcast e-mail to Domain', $formname)
  171:        .'<input type="hidden" name="command" />'
  172:        .&Apache::lonhtmlcommon::generate_menu(@menu)
  173:        .&end_page()
  174:     );
  175:     return;
  176: }
  177: 
  178: sub print_display_option_form {
  179:     my ($r,$formname,$cdom) = @_;
  180:     &Apache::lonhtmlcommon::add_breadcrumb({text=>"Display options"});
  181: 
  182:     my $cmd = 'display';
  183:     my $submit_text = &mt('Display e-mail');
  184:     my @roles = ('dc');
  185:     my $now = time;
  186: 
  187:     my $startdateform = &Apache::lonhtmlcommon::date_setter($formname,
  188:                                                             'startdate',
  189:                                                             $now);
  190:     my $enddateform = &Apache::lonhtmlcommon::date_setter($formname,
  191:                                                           'enddate',
  192:                                                           $now);
  193:     my %elements = (
  194:         startdate_month => 'selectbox',
  195:         startdate_hour => 'selectbox',
  196:         enddate_month => 'selectbox',
  197:         enddate_hour => 'selectbox',
  198:         startdate_day => 'text',
  199:         startdate_year => 'text',
  200:         startdate_minute => 'text',
  201:         startdate_second => 'text',
  202:         enddate_day => 'text',
  203:         enddate_year => 'text',
  204:         enddate_minute => 'text',
  205:         enddate_second => 'text',
  206:         sender => 'checkbox',
  207:     );
  208:     my $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements);
  209: 
  210:     my $output = &start_page(&add_script($jscript),
  211: 			     'Broadcast e-mail display options', $formname);
  212: 
  213:     $output .= &Apache::lonhtmlcommon::start_pick_box();
  214:     $output .= &Apache::lonhtmlcommon::row_title(&mt('Date range'));
  215:     $output .= '<table><tr><td>'.&mt('Earliest to display:').' </td><td>'.
  216:                 $startdateform.'</td></tr>';
  217:     $output .= '<tr><td>'.&mt('Latest to display:').' </td><td>'.$enddateform.
  218:                '</td></tr></table>';
  219:     $output .= &Apache::lonhtmlcommon::row_closure();
  220:     $output .= &Apache::lonhtmlcommon::row_title(&mt('Choose sender(s)'));
  221:     my %personnel = &Apache::lonnet::get_domain_roles($cdom,\@roles);
  222:     my @domcc = ();
  223:     foreach my $server (keys(%personnel)) {
  224:         foreach my $user (sort(keys(%{$personnel{$server}}))) {
  225:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
  226:             unless (grep/^$uname:$udom$/,@domcc) {
  227:                 my %userinfo = &Apache::lonnet::get('environment',['lastname','firstname'],$udom,$uname);
  228:                 $output .= '<input type="checkbox" name="sender" value="'.$uname.':'.$udom.'" />&nbsp;'.$userinfo{'firstname'}.' '.$userinfo{'lastname'}.'&nbsp;&nbsp;('.$uname.':'.$udom.')';
  229:                 push (@domcc,$uname.':'.$udom);
  230:             }
  231:         }
  232:     }
  233:     $output .= &Apache::lonhtmlcommon::row_closure();
  234:     $output .= &Apache::lonhtmlcommon::submit_row(&mt('Submit'),$cmd,$submit_text);
  235:     $output .= &Apache::lonhtmlcommon::end_pick_box();
  236:     $output .= qq(<input type="hidden" name="sortby" value="date" />\n).
  237: 	&end_page();
  238:     $r->print($output);
  239:     return;
  240: }
  241: 
  242: sub print_display {
  243:     my ($r,$formname,$cdom) = @_;
  244:     &Apache::lonhtmlcommon::add_breadcrumb
  245:          ({href=>"javascript:goBack('pick_display')",
  246:           text=>"Display options"},
  247:          {text=>"E-mail display"});
  248: 
  249:     my $msgcount = 0;
  250:     my $start = &Apache::lonhtmlcommon::get_date_from_form('startdate');
  251:     my $end = &Apache::lonhtmlcommon::get_date_from_form('enddate');
  252:     my @senders = &Apache::loncommon::get_env_multiple('form.sender');
  253:     my %sentmail = &Apache::lonnet::dcmaildump($cdom,$start,$end,\@senders);
  254:     my %dcmail = ();
  255:     my %Sortby = ();
  256:     my $jscript = <<"ENDSCRIPT";
  257: function changeSort(caller) {
  258:     document.$formname.command.value = '$formname';
  259:     document.$formname.sortby.value = caller;
  260:     document.$formname.submit();
  261: }
  262: function goBack(target) {
  263:     document.$formname.command.value = target;
  264:     document.$formname.submit();
  265: }
  266: 
  267: ENDSCRIPT
  268: 
  269:     my $output = &start_page(&add_script($jscript),
  270: 			     'Display Broadcast e-mail', $formname);
  271: 
  272:     foreach my $msgid (keys(%sentmail)) {
  273:         my %content = &Apache::lonmsg::unpackagemsg($sentmail{$msgid});
  274:         $msgcount ++;
  275:         %{$dcmail{$msgid}} = ();
  276:         foreach my $item (keys(%content)) {
  277:             if ($item eq 'recipient') {
  278:                 foreach my $user (keys(%{$content{recipient}})) {
  279:                     $dcmail{$msgid}{recipient}{$user} = $content{recipient}{$user};
  280:                 }
  281:             } else {
  282:                 $dcmail{$msgid}{$item} = $content{$item};
  283:             }
  284:         }
  285:     }
  286:     $output .= &Apache::loncommon::start_data_table();
  287:     if ($msgcount > 0) {
  288:         $output .= &Apache::loncommon::start_data_table_header_row().
  289: 	    '<th><a href="javascript:changeSort(\'date\')">'.&mt('Date').'</a></th>'.
  290: 	    '<th><a href="javascript:changeSort(\'subject\')">'.&mt('Subject').'</a></th>'.
  291: 	    '<th><a href="javascript:changeSort(\'sender\')">'.&mt('Sender').'</a></th>'.
  292: 	    '<th><a href="javascript:changeSort(\'message\')">'.&mt('Message').'</a></th>'.
  293: 	    '<th><a href="javascript:changeSort(\'recipients\')">'.&mt('Recipients').'</a></th>'.
  294: 	    &Apache::loncommon::end_data_table_header_row();
  295: 
  296:         if (($env{'form.sortby'} eq 'date') || ($env{'form.sortby'} eq '') || (!defined($env{'form.sortby'})) || (($env{'form.sortby'} eq 'sender') && (@senders <= 1))) {
  297:             foreach my $msgid (sort(keys(%dcmail))) {
  298:                 my $recipients = '';
  299:                 my ($date,undef,$sname,$sdom) =
  300:                                   &Apache::lonmsg::unpackmsgid($msgid,undef,1);
  301:                 $date = &Apache::lonlocal::locallocaltime($date);
  302:                 foreach my $user (sort(keys(%{$dcmail{$msgid}{recipient}}))) {
  303:                     $recipients .= $dcmail{$msgid}{recipient}{$user}.', ';
  304:                 }
  305:                 $recipients =~ s/,\s$//;
  306:                 $output .= &Apache::loncommon::start_data_table_row().
  307: 		    '<td><small>'.$date.'</small></td>'.
  308: 		    '<td><small>'.&cr_to_br($dcmail{$msgid}{subject}).'</small></td>'.
  309: 		    '<td><small>'.$sname.':'.$sdom.'</small></td><td><small>'.&cr_to_br($dcmail{$msgid}{message}).'</small></td>'.
  310: 		    '<td><small>'.$recipients.'</small></td>'."\n".
  311: 		    &Apache::loncommon::end_data_table_row();
  312:             }
  313:         } else {
  314:             foreach my $msgid (sort(keys(%dcmail))) {
  315:                 my ($date,undef,$sname,$sdom) =
  316:                                    &Apache::lonmsg::unpackmsgid($msgid,undef,1);
  317:                 if ($env{'form.sortby'} eq 'subject') {
  318:                     push @{$Sortby{$dcmail{$msgid}{subject}}},$msgid;
  319:                 } elsif ($env{'form.sortby'} eq 'message') {
  320:                     push @{$Sortby{$dcmail{$msgid}{message}}},$msgid;
  321:                 } elsif ($env{'form.sortby'} eq 'recipients') {
  322:                     my $recipients ='';
  323:                     foreach my $user (sort(keys(%{$dcmail{$msgid}{recipient}}))) {
  324:                         $recipients .= $dcmail{$msgid}{recipient}{$user}.', ';
  325:                     }
  326:                     $recipients =~ s/,\s$//;
  327:                     push @{$Sortby{$recipients}},$msgid;
  328:                 } elsif ($env{'form.sortby'} eq 'sender') {
  329:                     if (@senders > 1) {
  330:                        push @{$Sortby{$sname.':'.$sdom}},$msgid;
  331:                     }
  332:                 }
  333:             }
  334:             foreach my $key (sort(keys(%Sortby))) {
  335:                 foreach my $msgid (@{$Sortby{$key}}) {
  336:                     my $recipients = '';
  337:                     if ($env{'form.sortby'} eq 'recipients') {
  338:                         $recipients = $key;
  339:                     } else {
  340:                         foreach my $user (sort(keys(%{$dcmail{$msgid}{recipient}}))) {
  341:                             $recipients .= $dcmail{$msgid}{recipient}{$user}.', ';
  342:                         }
  343:                         $recipients =~ s/,\s$//;
  344:                     }
  345:                     my ($date,undef,$sname,$sdom) =
  346:                                    &Apache::lonmsg::unpackmsgid($msgid,undef,1);
  347:                     $date = &Apache::lonlocal::locallocaltime($date);
  348:                     $output .=  &Apache::loncommon::start_data_table_row().
  349: 			'<td><small>'.$date.'</small></td>'.
  350: 			'<td><small>'.&cr_to_br($dcmail{$msgid}{subject}).'</small></td>'.
  351: 			'<td><small>'.$sname.':'.$sdom.'</small></td>'.
  352: 			'<td><small>'.&cr_to_br($dcmail{$msgid}{message}).'</small></td>'.
  353: 			'<td><small>'.$recipients.'</small></td>'."\n".
  354: 			&Apache::loncommon::end_data_table_row();
  355:                 }
  356:             }
  357:         }
  358:     } else {
  359:         $output .= &Apache::loncommon::start_data_table_empty_row().
  360: 	    '<td>'.&mt('No mail sent matching supplied criteria').'</td>'.
  361: 	    &Apache::loncommon::end_data_table_empty_row();
  362:     }
  363:     $output .= &Apache::loncommon::end_data_table();
  364:     $output .= &Apache::lonhtmlcommon::echo_form_input(['sortby','command','origin']);
  365:     my $curr_sortby;
  366:     if (defined($env{'form.sortby'})) {
  367:         $curr_sortby = $env{'form.sortby'};
  368:     } else {
  369:         $curr_sortby = 'date';
  370:     }
  371:     $output .= qq(<input type="hidden" name="origin" value="$formname" />\n);
  372:     $output .= qq(<input type="hidden" name="command" />\n);
  373:     $output .= qq(<input type="hidden" name="sortby" value="$curr_sortby" />\n);
  374:     $output .= &end_page();
  375:     $r->print($output);
  376:     return;
  377: }
  378: 
  379: sub print_selection_form {
  380:     my ($r,$formname,$cdom) = @_;
  381:     my %codes = ();
  382:     my @codetitles = ();
  383:     my %cat_titles = ();
  384:     my %cat_order = ();
  385:     my %idlist = ();
  386:     my %idnums = ();
  387:     my %idlist_titles = ();
  388:     my $totcodes = 0;
  389:     my $jscript = '';
  390:     my %lt=&Apache::lonlocal::texthash(
  391:                'buil' => 'Building valid e-mail address from username, if missing from preferences:',
  392:                'kerb' => 'Kerberos: enter default for each realm used in the domain, with comma separation of entries',
  393:                'infs' => 'Internal, Filesystem and Local authentication: enter single default.',
  394:                'comp' => 'Compose E-mail'
  395:            );
  396:     &Apache::lonhtmlcommon::add_breadcrumb
  397:           ({text=>"Select Audience"});
  398: 
  399:     my $instcats = &Apache::lonnet::get_dom_instcats($cdom);
  400:     if (ref($instcats) eq 'HASH') {
  401:         if ((ref($instcats->{'codetitles'}) eq 'ARRAY') && (ref($instcats->{'codes'}) eq 'HASH') &&
  402:             (ref($instcats->{'cat_titles'}) eq 'HASH') && (ref($instcats->{'cat_order'}) eq 'HASH')) {
  403:             %codes = %{$instcats->{'codes'}};
  404:             @codetitles = @{$instcats->{'codetitles'}};
  405:             %cat_titles = %{$instcats->{'cat_titles'}};
  406:             %cat_order = %{$instcats->{'cat_order'}};
  407:             $totcodes = scalar(keys(%codes));
  408:             my $numtypes = @codetitles;
  409:             &Apache::courseclassifier::build_code_selections(\%codes,\@codetitles,\%cat_titles,\%cat_order,\%idlist,\%idnums,\%idlist_titles);
  410:             my ($scripttext,$longtitles) = &Apache::courseclassifier::javascript_definitions(\@codetitles,\%idlist,\%idlist_titles,\%idnums,\%cat_titles);
  411:             my $longtitles_str = join('","',@{$longtitles});
  412:             my $allidlist = $idlist{$codetitles[0]};
  413:             $jscript .= &Apache::courseclassifier::courseset_js_start($formname,$longtitles_str,$allidlist);
  414:             $jscript .= $scripttext;
  415:             $jscript .= &Apache::courseclassifier::javascript_code_selections($formname,\@codetitles);
  416:         }
  417:     }
  418:     my @standardnames = &Apache::loncommon::get_standard_codeitems();
  419: 
  420:     my $cb_jscript = &Apache::loncommon::coursebrowser_javascript($cdom);
  421: 
  422:     my %elements = (
  423:                      roles => 'selectbox',
  424:                      types => 'selectbox',
  425:                      Year => 'selectbox',
  426:                      coursepick => 'radio',
  427:                      coursetotal => 'text',
  428:                      courselist => 'text',
  429:                      internal => 'text',
  430:                      krb4 => 'text',
  431:                      krb5 => 'text',
  432:                      localauth => 'text',
  433:                      unix => 'text',
  434:                    );
  435:     $jscript .= &Apache::lonhtmlcommon::set_form_elements(\%elements);
  436:     if ($env{'form.coursepick'} eq 'category') {
  437:         $jscript .= qq|
  438: function setCourseCat(formname) {
  439:     if (formname.Year.options[formname.Year.selectedIndex].value == -1) {
  440:         return;
  441:     }
  442:     courseSet('$codetitles[0]');
  443:     for (var j=0; j<formname.Semester.length; j++) {
  444:         if (formname.Semester.options[j].value == "$env{'form.Semester'}") {
  445:             formname.Semester.options[j].selected = true;
  446:         }
  447:     }
  448:     if (formname.Semester.options[formname.Semester.selectedIndex].value == -1) {
  449:         return;
  450:     }
  451:     courseSet('$codetitles[1]');
  452:     for (var j=0; j<formname.Department.length; j++) {
  453:         if (formname.Department.options[j].value == "$env{'form.Department'}") {
  454:             formname.Department.options[j].selected = true;
  455:         }
  456:     }
  457:     if (formname.Department.options[formname.Department.selectedIndex].value == -1) {
  458:         return;
  459:     }
  460:     courseSet('$codetitles[2]');
  461:     for (var j=0; j<formname.Number.length; j++) {
  462:         if (formname.Number.options[j].value == "$env{'form.Number'}") {
  463:             formname.Number.options[j].selected = true;
  464:         }
  465:     }
  466: }
  467: |; 
  468:     }
  469: 
  470: 
  471:     my $output = &start_page(&add_script($jscript).$cb_jscript,
  472: 			     'Choose e-mail audience', $formname);
  473: 
  474:     $output .= &Apache::lonhtmlcommon::start_pick_box();
  475:     my @roles = ('ow','cc','in','ta','ep','st','cr');
  476:     my %longtypes = ();
  477:     my %authtypes = ();
  478:     &form_elements(\%longtypes,\%authtypes);
  479:     my $descrip = $lt{'buil'}.' 
  480: <ul>
  481: <li>'.$lt{'kerb'}.'<br />(e.g., MSU.EDU=msu.edu, MSUE.EDU=msue.msu.edu).</li>
  482: <li>'.$lt{'infs'}.'</li>
  483: </ul>'."\n";
  484:     my $submit_text = $lt{'comp'};
  485:     my $cmd = 'compose';
  486:     $output .= &Apache::lonhtmlcommon::role_select_row(\@roles,&mt('Roles'));
  487:     $output .= &Apache::lonhtmlcommon::course_select_row(&mt('Courses'),$formname,$totcodes,\@codetitles,\%idlist,\%idlist_titles,undef,undef,\@standardnames);
  488:     $output .= &Apache::lonhtmlcommon::status_select_row(\%longtypes,&mt('Access status'));
  489:     $output .= &Apache::lonhtmlcommon::email_default_row(\%authtypes,&mt('Username -> E-mail conversion'),$descrip);
  490:     $output .= &Apache::lonhtmlcommon::submit_row(&mt('Submit'),$cmd,$submit_text);
  491:     $output .= &Apache::lonhtmlcommon::end_pick_box();
  492:     $output .= &end_page();
  493:     $r->print($output);
  494:     return;
  495: }
  496: 
  497: sub print_composition_form {
  498:     my ($r,$formname,$cdom) = @_;
  499:     &Apache::lonhtmlcommon::add_breadcrumb
  500:         ({href=>"javascript:goBack('pick_target')",
  501:           text=>"Select Audience"},
  502:          {text=>"Compose E-mail"});
  503:     my $jscript = &Apache::loncommon::check_uncheck_jscript();
  504:     $jscript .= qq|
  505: function goBack(target) {
  506:     document.$formname.command.value = target;
  507:     document.$formname.submit();
  508: }
  509: |;
  510: 
  511:     my %lt=&Apache::lonlocal::texthash(
  512:                       'nore' => 'No recipients identified',
  513:                       'emad' => 'e-mail address',
  514:                    );
  515:     my %elements = (
  516:                      subject => 'text',
  517:                      message => 'text',
  518:                      sender => 'text',
  519:                      recipient => 'checkbox',
  520:                    );
  521:     $jscript .= &Apache::lonhtmlcommon::set_form_elements(\%elements);
  522: 
  523:     $r->print(&start_page(&add_script($jscript),
  524: 			  'Broadcast e-mail to users', $formname));
  525: 
  526:     my $coursefilter = $env{'form.coursepick'};
  527:     my %courses;
  528:     if ($coursefilter eq 'all') {
  529:         %courses = &Apache::lonnet::courseiddump($cdom,'.','.','.','.','.',
  530:                                                  undef,undef,'Course');
  531:     } elsif ($coursefilter eq 'category') {
  532:         my $instcode = &Apache::courseclassifier::instcode_from_selectors($cdom);
  533:         my $regexp = '';
  534:         if ($instcode eq '') {
  535:             $instcode = '.';
  536:         } else {
  537:             $regexp = 1;
  538:         }
  539:         %courses = &Apache::lonnet::courseiddump($cdom,'.','.',$instcode,'.','.',
  540:                                                  undef,undef,'Course',$regexp);
  541:     } elsif ($coursefilter eq 'specific') {
  542:         if ($env{'form.coursetotal'} > 1) {
  543:             my @course_ids = split(/&&/,$env{'form.courselist'});
  544:             foreach my $cid (@course_ids) {
  545:                 $courses{$cid} = '';
  546:             }
  547:         } else {
  548:             $courses{$env{'form.courselist'}} = '';
  549:         }
  550:     }
  551: 
  552:     my @types = &Apache::loncommon::get_env_multiple('form.types');
  553:     my @roles = &Apache::loncommon::get_env_multiple('form.roles');
  554: 
  555:     my %longtypes = ();
  556:     my %authtypes = ();
  557:     my %email_defaults = ();
  558: 
  559:     &form_elements(\%longtypes,\%authtypes);
  560:     foreach my $auth (keys(%authtypes)) {
  561:         if (exists($env{'form.'.$auth})) {
  562:              my $default = $env{'form.'.$auth};
  563:              $default =~ s/^,+//;
  564:              $default =~ s/,+$//;
  565:              if ($auth =~ /^krb/) {
  566:                  %{$email_defaults{$auth}} = ();
  567:                  if ($default =~ /,/) {
  568:                      my @items = split(/,/,$default);
  569:                      foreach my $item (@items) {
  570:                          my ($realm,$value) = split(/=/,$item);
  571:                          $email_defaults{$auth}{$realm} = $value;
  572:                      }
  573:                  } else {
  574:                      my ($realm,$value) = split(/=/,$default);
  575:                      $email_defaults{$auth}{$realm} = $value;
  576:                  }
  577:              } else {
  578:                  $email_defaults{$auth} = $default;
  579:              }
  580:          }
  581:     }
  582: 
  583:     my $sender = &get_user_info($env{'user.name'},%email_defaults);
  584: 
  585:     my %recipients = ();
  586:     my %users = ();
  587:     my %access = ();
  588:     my @sections = ();
  589:     my $totalrecip = 0;
  590:     my @unmatched = ();
  591:     foreach my $role (@roles) {
  592:         %{$users{$role}} = ();
  593:     }
  594:     foreach my $type (@types) {
  595:         $access{$type} = $type;
  596:     }
  597:     foreach my $course_id (keys(%courses)) {
  598:         my %coursehash = 
  599:             &Apache::lonnet::coursedescription($course_id,{'one_time' => 1});
  600:         my $cdom = $coursehash{'domain'};
  601:         my $cnum = $coursehash{'num'};
  602:         &Apache::loncommon::get_course_users($cdom,$cnum,\%access,\@roles,\@sections,\%users);
  603:     }
  604:     foreach my $role (keys(%users)) {
  605:         foreach my $user (keys(%{$users{$role}})) {
  606:             unless (defined($recipients{$user})) {
  607:                 $recipients{$user} = &get_user_info($user,%email_defaults);
  608:                 if ($recipients{$user} eq '') {
  609:                     push @unmatched, $user;
  610:                 } else {
  611:                     $totalrecip ++;
  612:                 } 
  613:             }
  614:         }
  615:     }
  616:     my $output;
  617:   
  618:     if ($totalrecip > 0) {
  619:         $output .= &Apache::lonhtmlcommon::start_pick_box();
  620:         $output .= &Apache::lonhtmlcommon::row_title(&mt('Subject'));
  621:         $output .= '<input type="text" name="subject" size="30" />';
  622:         $output .= &Apache::lonhtmlcommon::row_closure();
  623:         $output .= &Apache::lonhtmlcommon::row_title(&mt('Message'));
  624:         $output .= '  <textarea name="message" id="message"
  625:                       cols="60" rows="10" wrap="hard"></textarea>';
  626:         $output .= &Apache::lonhtmlcommon::row_closure();
  627:         $output .= &Apache::lonhtmlcommon::row_title(&mt('Recipients'));
  628:         $output .= '<input type="button" value="check all" 
  629:                     onclick="javascript:checkAll(document.compose.recipient)" />
  630:                     &nbsp;&nbsp;<input type="button" value="uncheck all"
  631:                     onclick="javascript:uncheckAll(document.compose.recipient)" />
  632:                     <br />';
  633: 	$output .= &Apache::loncommon::start_data_table();
  634:         if (keys(%recipients) > 0) {
  635: 	    $output .= &Apache::loncommon::start_data_table_header_row();
  636:             $output .= '<th>&nbsp;<th>username:domain</th><th>'.$lt{'emad'}.'</th>';
  637: 	    $output .= &Apache::loncommon::end_data_table_header_row();
  638:         }
  639:         foreach my $username (sort(keys(%recipients))) {
  640: 	    $output .= &Apache::loncommon::start_data_table_row();
  641:             if ($recipients{$username} =~ /\@/) {
  642:                 my $value=&escape($username).':'.&escape($recipients{$username});
  643:                 $output .= '<td><input type="checkbox" name="recipient" value="'.$value.'" /></td><td>'.$username.'</td><td>'.$recipients{$username}.'</td>';
  644:             }
  645: 	    $output .= &Apache::loncommon::end_data_table_row();
  646:         }
  647:         $output .= &Apache::loncommon::end_data_table();
  648:         if (@unmatched) {
  649:             $output .= '<br /><br />'.&mt('Could not determine e-mail addresses for the following users:').'<ul>';
  650:             foreach my $username (sort(@unmatched)) {
  651:                 $output .= '<li>'.$username.'</li>';
  652:             }
  653:             $output .= '</ul>';
  654:         }
  655:         $output .= &Apache::lonhtmlcommon::row_closure();
  656:         $output .= &Apache::lonhtmlcommon::row_title(&mt('Sender e-mail address'));
  657:         $output .= '<input type="text" name="sender" value="'.$sender.'" />';
  658:         $output .= &Apache::lonhtmlcommon::row_closure();
  659:         $output .= &Apache::lonhtmlcommon::submit_row(&mt('Submit'),'process',&mt('Send'));
  660:         $output .= &Apache::lonhtmlcommon::end_pick_box();
  661:     } else {
  662:         $output .= $lt{'nore'}."\n".
  663:                    '<input type="hidden" name="command" value="" />'."\n";
  664:     }
  665:     $output .= '<input type="hidden" name="origin" value="'.$formname.'" />'."\n";
  666:     $output .= &Apache::lonhtmlcommon::echo_form_input(['command','origin','subject','message','recipient','sender'],);
  667:     $output .= &end_page();
  668:     $r->print($output);
  669:     return;
  670: }
  671: 
  672: 
  673: sub print_request_receipt {
  674:     my ($r,$formname,$dom) =@_;
  675:     my @recipients = &Apache::loncommon::get_env_multiple('form.recipient');
  676:     my $subject = $env{'form.subject'};
  677:     my $message = $env{'form.message'};
  678:     my $from = $env{'form.sender'};
  679:     my $jscript = <<ENDSCRIPT;
  680: function goBack(target) {
  681:     document.$formname.command.value = target;
  682:     document.$formname.submit();
  683: }
  684: ENDSCRIPT
  685: 
  686:     &Apache::lonhtmlcommon::add_breadcrumb
  687:         ({href=>"javascript:goBack('pick_target')",
  688:           text=>"Select audience"});
  689:     &Apache::lonhtmlcommon::add_breadcrumb
  690:         ({href=>"javascript:goBack('compose')",
  691:           text=>"Compose E-mail"});
  692:     &Apache::lonhtmlcommon::add_breadcrumb
  693:         ({href=>"/adm/notify?command=process",
  694:           text=>"Outcome"});
  695: 
  696: 
  697:     my $output = &start_page(&add_script($jscript), 'E-mail Delivery',
  698: 			     $formname);
  699: 
  700: 
  701:     my @deliveries = ();
  702:     &broadcast_email(\@recipients,$subject,$from,$message,\@deliveries);
  703:     if (@deliveries > 0) {
  704: 	$output .= &Apache::loncommon::start_data_table();
  705:         &store_mail($subject,$message,$dom,\@deliveries);
  706:         $output .= &Apache::loncommon::start_data_table_header_row().
  707: 	    '<th>'.&mt('Status').'</th>'.
  708: 	    '<th>'.&mt('Subject').'</th>'.
  709: 	    '<th>'.&mt('Message').'</th>'.
  710: 	    '<th>'.&mt('Recipients').'</th>'.
  711: 	    &Apache::loncommon::end_data_table_header_row();
  712: 	$output .= &Apache::loncommon::start_data_table_row().
  713: 	    '<td valign="middle">'.&mt('Sent').'</td>'.
  714: 	    '<td valign="middle">'.&cr_to_br($subject).'</td>'.
  715: 	    '<td valign="middle">'.&cr_to_br($message).'</td>'.
  716: 	    '<td>';
  717:         foreach my $person (@deliveries) {
  718:             my ($username,$email) = split(/:/,$person);
  719:             $output .= &unescape($email).'&nbsp;('.&unescape($username).')<br />'."\n";
  720:         }
  721:         $output .= '</td>'.
  722: 	    &Apache::loncommon::end_data_table_row().
  723: 	    &Apache::loncommon::end_data_table();
  724:     } else {
  725:         $output .= &mt('No mail sent - no recipients identified'); 
  726:     }
  727:     $output .= '<br /><a href="/adm/notify">'.&mt('Send another e-mail').'</a>'."\n";
  728:     $output .= '<input type="hidden" name="command" />'."\n".
  729:                '<input type="hidden" name="origin" value="'.$formname.'" />'."\n";
  730:     $output .= &Apache::lonhtmlcommon::echo_form_input(['command','origin']);
  731:     $output .= &end_page();
  732:     $r->print($output);
  733:     return;
  734: }
  735: 
  736: sub broadcast_email {
  737:     my ($recipients,$subject,$from,$message,$deliveries)=@_;
  738: # Should implement staggered delivery for large numbers of recipients?.
  739:     foreach my $user (@{$recipients}) {
  740:         my $msg = new Mail::Send;
  741:         my ($username,$to) = split(/:/,$user);
  742:         $username = &unescape($username);
  743:         $to = &unescape($to);
  744:         $msg->to($to);
  745:         $msg->subject($subject);
  746:         $msg->add('From',"$from");
  747:         $msg->add('Content-type','text/plain; charset=UTF-8');
  748:         if (my $fh = $msg->open()) {
  749:             print $fh $message;
  750:             $fh->close;
  751:             push(@{$deliveries},$user); 
  752:         }
  753:     }
  754: }
  755: 
  756: sub get_user_info {
  757:     my ($user,%email_defaults) = @_;
  758:     my ($uname,$udom) = split(/:/,$user);
  759:     my @emailtypes = ('permanentemail','critnotification','notification');
  760:     my %userinfo = &Apache::loncommon::getemails($uname,$udom);
  761:     my $email = '';
  762:     foreach my $type (@emailtypes) {
  763:         $email = $userinfo{$type};
  764:         if ($email =~ /\@/) {
  765:             last;
  766:         }
  767:     }
  768:     if ($email eq '') {
  769:         my $authinfo  = &Apache::lonnet::queryauthenticate($uname,$udom);
  770:         my ($authtype,$autharg) = split(/:/,$authinfo);
  771:         if ($authtype =~ /^krb/) {
  772:             if (defined($email_defaults{$authtype}{$autharg})) {
  773:                 $email = $uname.'@'.$email_defaults{$authtype}{$autharg};
  774:             }
  775:         } else {
  776:             if ((defined($email_defaults{$authtype})) && ($email_defaults{$authtype} ne '')) {
  777:                 $email = $uname.'@'.$email_defaults{$authtype};
  778:             }
  779:         }
  780:     }
  781:     return $email;
  782: }
  783: 
  784: sub form_elements {
  785:    my ($longtypes,$authtypes) = @_;
  786:    %{$longtypes} = (
  787:                    active => &mt('Currently has access'),
  788:                    previous => &mt('Previously had access'),
  789:                    future => &mt('Will have future access'),
  790:                    );
  791:    %{$authtypes} = &Apache::lonlocal::texthash (
  792:                    krb4 => 'Kerberos 4',
  793:                    krb5 => 'Kerberos 5',
  794:                    internal => 'Internal (LON-CAPA)',
  795:                    unix => 'Filesystem (UNIX)',
  796:                    localauth => 'Local/Customized',
  797:                    );
  798:    return;
  799: }
  800: 
  801: sub store_mail {
  802:     my ($subject,$message,$domain,$recipients,$attachmenturl) = @_;
  803:     my $msgid;
  804:     ($msgid,$message) = &Apache::lonmsg::packagemsg($subject,$message,undef,undef,
  805:                         $attachmenturl,$recipients,undef,undef,'dcmail');
  806: 
  807: # Store in dc email db files on primary library server for domain.
  808:     my $server = &Apache::lonnet::domain($domain,'primary');
  809:     if (defined($server)) {
  810:         unless (&Apache::lonnet::dcmailput($domain,$msgid,$message,$server) 
  811:                                                             eq 'ok') {
  812:             &Apache::lonnet::logthis('Storage of dc mail failed for domain'.
  813:                  $domain.' for server: '. $server.'.  Message ID was '.$msgid);
  814:         }
  815:     } else {
  816:         &Apache::lonnet::logthis('Storage of dc mail failed for domain'.
  817:            $domain.' as no primary server identified. Message ID was '.$msgid);
  818:     }
  819: }
  820: 
  821: sub cr_to_br {
  822:     my $incoming = shift;
  823:     $incoming =~ s/\n/\<br \/\>/g;
  824:     return $incoming;
  825: }
  826: 
  827: 1;

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>