File:  [LON-CAPA] / loncom / interface / lonsupportreq.pm
Revision 1.61: download - view: text, annotated - select for diffs
Thu Dec 2 23:05:42 2010 UTC (13 years, 11 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Eliminate duplicate declaration.

#
# $Id: lonsupportreq.pm,v 1.61 2010/12/02 23:05:42 raeburn Exp $
#
# Copyright Michigan State University Board of Trustees
#
# This file is part of the LearningOnline Network with CAPA (LON-CAPA).
#
# LON-CAPA is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# LON-CAPA is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with LON-CAPA; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# /home/httpd/html/adm/gpl.txt
#
# http://www.lon-capa.org/
#

package Apache::lonsupportreq;

use strict;
use MIME::Types;
use MIME::Lite;
use CGI::Cookie();
use Apache::Constants qw(:common);
use Apache::loncommon();
use Apache::lonhtmlcommon;
use Apache::lonnet;
use Apache::lonlocal;
use Apache::lonacc();
use Apache::courseclassifier;
use LONCAPA qw(:DEFAULT :match);
 

sub handler {
    my ($r) = @_;
    &Apache::loncommon::content_type($r,'text/html');
    $r->send_http_header;

    if ($r->header_only) {
        return OK;
    }
    if ($r->uri eq '/adm/helpdesk') {
	&Apache::lonlocal::get_language_handle($r);
    }

    &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['origurl','function']);
    if ($r->uri eq '/adm/helpdesk') {
        &Apache::lonacc::get_posted_cgi($r);
    }
    my $function = $env{'form.function'};
    my $origurl = $env{'form.origurl'};
    my $command = $env{'form.command'};

    if ($command eq 'process') {
        &print_request_receipt($r,$origurl,$function);
    } else {
        &print_request_form($r,$origurl,$function);
    }
    return OK;
}
    
sub print_request_form {
    my ($r,$origurl,$function) = @_;
    my ($os,$browser,$bversion,$uhost,$uname,$udom,$uhome,$urole,$usec,$email,$cid,
        $cdom,$cnum,$ctitle,$ccode,$sectionlist,$lastname,$firstname,$server,
        $formname,$public);
    $function = &Apache::loncommon::get_users_function() if (!$function);
    $ccode = '';
    $os = $env{'browser.os'};
    $browser = $env{'browser.type'};
    $bversion = $env{'browser.version'};
    $uhost = $env{'request.host'};
    if (($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')) {
        $public = 1;
    } else {
        $uname = $env{'user.name'};
        $udom = $env{'user.domain'};
    }
    $uhome = $env{'user.home'};
    $urole = $env{'request.role'};
    $usec = $env{'request.course.sec'};
    $cid = $env{'request.course.id'};
    $formname = 'logproblem';
    my $machine = &Apache::lonnet::absolute_url();
    if ($origurl =~ m-^https?://-) {
        $server = $origurl;
    } else {
        $server = $machine.$origurl;
    }
    my $showserver = $server;
    $showserver =~ s/\?.*$//;
    my %lt = &Apache::lonlocal::texthash (
                  email => 'The e-mail address you entered',
                  notv => 'is not a valid e-mail address',
                  rsub => 'You must include a subject',
                  rdes => 'You must include a description',
                  name => 'Name',
                  subm => 'Submit Request',
                  emad => 'Your e-mail address',
                  emac => 'Cc', 
                  unme => 'username',
                  doma => 'domain',
                  entu => 'Enter the username you use to log-in to LON-CAPA',
                  chdo => 'Choose your LON-CAPA domain',
                  entr => 'Enter the username you use to log-in to LON-CAPA, and your domain.',
                  urlp => 'URL of page',
                  phon => 'Phone',
                  crsd => 'Course Details',
                  enin => 'Enter institutional course code',
                  pick => 'Pick',
                  enct => 'Enter course title',
                  secn => 'Section Number',
                  sele => 'Select',
                  titl => 'Title',
                  lsec => 'LON-CAPA sec',
                  subj => 'Subject',
                  detd => 'Detailed Description',
                  opfi => 'Optional file upload',
                  uplf => 'Upload a file (e.g., a screenshot) relevant to your help request (128 KB max.)',
                  fini => 'Finish',
                  clfm => 'Clear Form',
    );
    my $scripttag = (<<"END");
function validate() {
    if (validmail(document.logproblem.email) == false) {
        alert("$lt{'email'}: "+document.logproblem.email.value+" $lt{'notv'}.");
        return;
    }
    if (document.logproblem.subject.value == '') {
        alert("$lt{'rsub'}.");
        return;
    }
    if (document.logproblem.description.value == '') {
        alert("$lt{'rdes'}.");
        return;
    }
    document.logproblem.submit();
}

END
    $scripttag .= &Apache::lonhtmlcommon::javascript_valid_email();
    if ($cid) {
        $cdom = $env{'course.'.$cid.'.domain'};
        $cnum = $env{'course.'.$cid.'.num'};
    }
    if ($cdom && $cnum) {
        my %csettings = &Apache::lonnet::get('environment',['description','internal.coursecode','internal.sectionnums'],$cdom,$cnum);
        $ctitle = $csettings{'description'};
        $ccode = $csettings{'internal.coursecode'};
        $sectionlist = $csettings{'internal.sectionnums'};
    }

    if ($env{'environment.permanentemail'}) {
        $email = $env{'environment.permanentemail'};
    } elsif ($env{'environment.critnotification'}) {
        $email = $env{'environment.critnotification'};
    } elsif ($env{'environment.notification'}) {
        $email = $env{'environment.notification'};
    }
    if ($env{'environment.lastname'}) {
        $lastname = $env{'environment.lastname'};
    }
    if ($env{'environment.firstname'}) {
        $firstname = $env{'environment.firstname'};
    }
    my @sections = split(/,/,$sectionlist);
    my %groupid;
    foreach my $section (@sections) {
        my ($sec,$grp) = split(/:/,$section);
        $groupid{$sec} = $grp;
    }
    &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['codedom',
                                                 'useremail','useraccount']);
    if ($env{'form.origurl'} eq '/adm/createaccount') {
        if ($email eq '') {
            if ($env{'form.useremail'} =~ /^[^\@]+\@[^\@]+$/) {
                $email = &HTML::Entities::encode($env{'form.useremail'},'"<>&');
            }
        }
        if ($uname eq '') {
            if ($env{'form.useraccount'} =~ /^$match_username$/) {
                $uname = &HTML::Entities::encode($env{'form.useraccount'},'"<>&');
            }
        }
    }
    my $codedom = &get_domain();
    my $details_title;
    if ($codedom) {
        $details_title = '<br />('.$codedom.')';
    }
    my %coursecodes;
    my %codes;
    my @codetitles;
    my %cat_titles;
    my %cat_order;
    my %idlist;
    my %idnums;
    my %idlist_titles;
    my $caller = 'global';
    my $totcodes = 0;
    my $format_reply;
    my $jscript = '';
    my $loaditems = qq|
function initialize_codes() {
    return;
}
    |;
    if ($cnum) {
        $coursecodes{$cnum} = $ccode;
        if ($ccode eq '') {
            $totcodes = &Apache::courseclassifier::retrieve_instcodes(\%coursecodes,$codedom,$totcodes);
        } else {
            $coursecodes{$cnum} = $ccode;
            $caller = $cnum;
            $totcodes ++;
        }
    } else { 
        $totcodes = &Apache::courseclassifier::retrieve_instcodes(\%coursecodes,$codedom,$totcodes);
    }
    if ($totcodes > 0) {
        if ($ccode eq '') {
            $format_reply = &Apache::lonnet::auto_instcode_format($caller,$codedom,\%coursecodes,\%codes,\@codetitles,\%cat_titles,\%cat_order);
            if ($format_reply eq 'ok') {
                my $numtypes = @codetitles;
                &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);
                $loaditems = '';
            }
        }
    }
	
    my $js = '<script type="text/javascript">'."\n$scripttag\n$jscript\n".
	'</script>';
    my %add_entries = (topmargin    => "0",
		       marginheight => "0",
		       onLoad       =>"initialize_codes()",);

    
    $r->print(&Apache::loncommon::start_page('Support Request',$js,
				       { 'function'    => $function,
					 'add_entries' => \%add_entries,
					 'only_body'   => 1,}));
    if ($r->uri eq '/adm/helpdesk') {
        &print_header($r,$origurl);
    }
    my @css = ('LC_evenrow_value','LC_oddrow_value');
    my $num = 1;
    my $i = $num%2;
    $r->print('<form method="post" name="logproblem" enctype="multipart/form-data">'."\n");
    my $output = &Apache::lonhtmlcommon::start_pick_box().
                 &Apache::lonhtmlcommon::row_title($lt{'name'},undef,$css[$num])."\n";
    my $fullname = '';
    if ((defined($lastname) && $lastname ne '') && (defined($firstname) && $firstname ne '')) {
        $fullname = "$firstname $lastname"; 
        $output .= $fullname.'<input type="hidden" name="username" value="'.&HTML::Entities::encode($fullname,'"<>&').'" />';
    } else {
        if (defined($firstname) && $firstname ne '') {
            $fullname = $firstname;
        } elsif (defined($lastname) && $lastname ne '') {
            $fullname = " $lastname";
        }
        $output .= '<input type="text" size="20" name="username" value="'.&HTML::Entities::encode($fullname,'"<>&').'" />';
    }
    $output .= '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="button" value="'.$lt{'subm'}.'" onclick="validate()" />&nbsp;'.
                &Apache::lonhtmlcommon::row_closure()."\n";
    $num ++;
    $i = $num%2;
    $output .= &Apache::lonhtmlcommon::row_title($lt{'emad'},undef,$css[$i]).
               '<input type="text" size="20" name="email" value="'.
               &HTML::Entities::encode($email,'"<>&').'" /><br />'."\n".
               &Apache::lonhtmlcommon::row_closure();
    $num ++;
    $i = $num%2;
    if (($env{'user.name'} =~ /^$match_username$/) && (!$public)) {
        $output .= &Apache::lonhtmlcommon::row_title($lt{'emac'},undef,$css[$i]).
                   '<input type="text" size="50" name="cc" value="" /><br />'."\n".
                   &Apache::lonhtmlcommon::row_closure();
        $num ++;
        $i = $num%2;
    }
    $output .= &Apache::lonhtmlcommon::row_title("$lt{'unme'}/$lt{'doma'}",undef,$css[$i]);
    my $udom_input = '<input type="hidden" name="udom" value="'.
                     &HTML::Entities::encode($udom,'"<>&').'" />';
    my $uname_input = '<input type="hidden" name="uname" value="'.
                      &HTML::Entities::encode($uname,'"<>&').'" />'; 
    if (($env{'user.name'} =~ /^$match_username$/) && 
        ($env{'user.domain'} =~ /^$match_domain$/) && (!$public)) {
        $output .= '<i>'.$lt{'unme'}.'</i>:&nbsp;'.$uname.'&nbsp;&nbsp;<i>'.$lt{'doma'}.'</i>:&nbsp;'.$udom.$udom_input.$uname_input;
    } else {
        my $udomform = '';
        my $unameform = '';
        if (($env{'user.domain'} =~ /^$match_domain$/) && (!$public)) {
            $output .= $lt{'entu'};
        } elsif (($env{'user.name'} =~ /^$match_username$/) && (!$public)) { 
            $output .= $lt{'chdo'};
        } else {
            $output .= $lt{'entr'};
        }
        $output .= '<br />';
        if (!$public) {
            if ($env{'user.domain'} =~ /^$match_domain$/) {
                $udomform = '<i>'.$lt{'doma'}.'</i>:&nbsp;'.$udom.$udom_input;
            } elsif ($env{'user.name'} =~ /^$match_username$/) {
                $unameform = '<i>'.$lt{'unme'}.'</i>:&nbsp;'.$uname.'&nbsp;&nbsp;'.$uname_input;
            }
        }
        if ($udomform eq '') {
            $udomform = '<i>'.$lt{'doma'}.'</i>:&nbsp;';
            $udomform .= &Apache::loncommon::select_dom_form($codedom,'udom');
        }
        if ($unameform eq '') {
            $unameform= '<i>'.$lt{'unme'}.'</i>:&nbsp;<input type="text" size="20" name="uname" value="'.$uname.'" />&nbsp;&nbsp;';
        }
        $output .= $unameform.$udomform;
    }
    $output .= &Apache::lonhtmlcommon::row_closure();
    $num ++;
    $i = $num%2;
    $output .= &Apache::lonhtmlcommon::row_title("$lt{'urlp'}",undef,$css[$i]).
               $showserver.'<input type="hidden" name="sourceurl" value="'.
               &HTML::Entities::encode($server,'"<>&').'" />'.
               &Apache::lonhtmlcommon::row_closure().
               &Apache::lonhtmlcommon::row_title("$lt{'phon'}",undef,'LC_evenrow_value').
               '<input type="text" size="15" name="phone" /><br />'.
               &Apache::lonhtmlcommon::row_closure();
    $num ++;
    $i = $num%2; 
    $output .= &Apache::lonhtmlcommon::row_title("$lt{'crsd'}$details_title",undef,$css[$i]);
    if ($cnum) {
        if ($coursecodes{$cnum}) {
            foreach my $item (@codetitles) {
                $output .= '<i>'.$item.'</i>:&nbsp;'.$codes{$cnum}{$item}.';&nbsp;';
            }
            $output .= '&nbsp;<input type="hidden" name="coursecode" value="'.&HTML::Entities::encode($coursecodes{$cnum},'"<>&').'" />';
        } else {
            $output .= $lt{'enin'}.':&nbsp;
                  <input type="text" name="coursecode" size="15" value="" />';
        }
    } else {
        if ($totcodes > 0) {
            my $numtitles = @codetitles;
            if ($numtitles == 0) {
                $output .= $lt{'enin'}.':&nbsp;
                  <input type="text" name="coursecode" size="15" value="" />';
            } else {
                my @standardnames = &Apache::loncommon::get_standard_codeitems();
                my $lasttitle = $numtitles;
                if ($numtitles > 4) {
                    $lasttitle = 4;
                } 
                $output .= '<table><tr><td>'.$codetitles[0].'<br />'."\n".
                      '<select name="'.$standardnames[0].'" onchange="courseSet('."'$codetitles[0]'".')">'."\n".
                      ' <option value="-1" />'.$lt{'sele'}."\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++) {
                    $output .= ' <option value="'.$items[$i].'">'.$longitems[$i].'</option>'."\n";
                }
                $output .= '</select></td>';
                for (my $i=1; $i<$numtitles; $i++) {
                    $output .= '<td>'.$codetitles[$i].'<br />'."\n".
                     '<select name="'.$standardnames[$i].'" onchange="courseSet('."'$codetitles[$i]'".')">'."\n".
                     '<option value="-1">&lt;-'.$lt{'pick'}.' '.$codetitles[$i-1].'</option>'."\n".
                     '</select>'."\n".
                     '</td>'."\n";
                }
                $output .= '</tr></table>';
                if ($numtitles > 4) {
                    $output .= '<br /><br />'.$codetitles[$numtitles].'<br />'."\n".
                          '<select name="'.$standardnames[$numtitles].'" onchange="courseSet('."'$codetitles[$numtitles]'".')">'."\n".
                          '<option value="-1">&lt;-'.$lt{'pick'}.' '.$codetitles[$numtitles-1].'</option>'."\n".
                          '</select>'."\n";
                }
            }
        } else {
            $output .= $lt{'enin'}.':&nbsp;
                  <input type="text" name="coursecode" size="15" value="" />';
        }
    }
    if ($ctitle) {
        $output .= '<br /><i>'.$lt{'titl'}.'</i>:&nbsp;'.$ctitle.
                   '<input type="hidden" name="title" value="'.
                   &HTML::Entities::encode($ctitle,'"<>&').'" />'."\n";
    } else {
        $output .= '<br />'.$lt{'enct'}.':&nbsp;
                 <input type="text" name="title" size="25" value="" />'."\n";
    }
    $output .= &Apache::lonhtmlcommon::row_closure();
    $num ++;
    $i = $num%2;
    $output .= &Apache::lonhtmlcommon::row_title($lt{'secn'},undef,$css[$i]);
    if ($sectionlist) {
        $output .= "<select name=\"section\"\n>".
                   "  <option value=\"\" selected=\"selected\">$lt{'sele'}</option>\n";
        foreach my $id (sort(keys(%groupid))) {
            if ($id eq $groupid{$id} || $groupid{$id} eq '') {
                $output .= "  <option value=".
                           &HTML::Entities::encode($id,'"<>&').
                           " >$id</option>\n";
            } else {
                $output .= "  <option value=".
                           &HTML::Entities::encode($id,'"<>&').
                           " >$id - ($lt{'lsec'}: $groupid{$id})</option>\n";
            }
        }
        $output .= "</select>";
    } else {
        $output .= '<input type="text" name="section" size="10" />';
    }
    $output .= &Apache::lonhtmlcommon::row_closure();
    $num ++;
    $i = $num%2; 
    $output .= &Apache::lonhtmlcommon::row_title($lt{'subj'},undef,'LC_oddrow_value').
               '  <input type="text" size="40" name="subject" />'."\n".
               &Apache::lonhtmlcommon::row_closure().
               &Apache::lonhtmlcommon::row_title($lt{'detd'},undef,'LC_evenrow_value').
               '  <textarea rows="10" cols="45" name="description" wrap="virtual"></textarea>'.
               &Apache::lonhtmlcommon::row_closure();
    $num ++;
    $i = $num%2; 
    if (($env{'user.name'} =~ /^$match_username$/) && (!$public)) {
        $output .= &Apache::lonhtmlcommon::row_title($lt{'opfi'},undef,$css[$i]).
                   ' <input type="file" name="screenshot" size="20" /><br />'.$lt{'uplf'}."\n".
        &Apache::lonhtmlcommon::row_closure();
        $num ++;
        $i = $num%2; 
    }
    $output .= &Apache::lonhtmlcommon::row_title($lt{'fini'},undef,$css[$i]);
    $output .= <<END;
             <table border="0" cellpadding="8" cellspacing="0">
              <tr>
               <td>
                <input type="hidden" name="command" value="process" />
                <input type="button" value="$lt{'subm'}" onclick="validate()" /> &nbsp;
               </td>
               <td>&nbsp;</td>
               <td>
                <input type="reset" value="$lt{'clfm'}" />
               </td>
              </tr>
             </table>
END
    $output .= &Apache::lonhtmlcommon::row_closure(1);
    $output .= &Apache::lonhtmlcommon::end_pick_box();
    $r->print(<<END);
$output
</form>
<br />
END
    $r->print(&Apache::loncommon::end_page());
    return;
}

sub print_request_receipt {
    my ($r,$url,$function) = @_;
    my @ENVvars = ('HTTP_HOST','HTTP_USER_AGENT','REMOTE_ADDR','SERVER_ADDR','SERVER_NAME');
    my @envvars = ('browser.os','browser.type','browser.version','user.home','request.role');
    my @loncvars = ('user.name','user.domain','request.course.sec','request.course.id');
    my @cookievars = ('lonID');

    my $admin = $Apache::lonnet::perlvar{'lonAdminMail'};
    my $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};
    my $defdom = &get_domain();
    my $to = &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',
                                                      $defdom,$origmail);
    my $from = $admin;
    my $bcc;
    my %domconfig =
         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
    if (ref($domconfig{'contacts'}) eq 'HASH') {
        if (exists($domconfig{'contacts'}{'helpdeskmail'})) {
            if (ref($domconfig{'contacts'}{'helpdeskmail'}) eq 'HASH') {
                my $bccmail = $domconfig{'contacts'}{'helpdeskmail'}{'bcc'};
                if ($bccmail ne '') {
                    my @bccs = split(/,/,$bccmail);
                    my @ok_bccs;
                    foreach my $bcc (@bccs) {
                        $bcc =~ s/^\s+//g;
                        $bcc =~ s/\s+$//g;
                        if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                            if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                                push(@ok_bccs,$bcc);
                            }
                        }
                    }
                    if (@ok_bccs > 0) {
                        $bcc = join(', ',@ok_bccs);
                    }
                }
            }
        }
    }
    my $reporttime = &Apache::lonlocal::locallocaltime(time);
    my @formvars = ('username','email','uname','udom','sourceurl','phone','section','coursecode','title','subject','description','screenshot');

    &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},\@formvars);
    my $coursecode = $env{'form.coursecode'};
    if ($coursecode eq '') {
        my $totcodes = 0;
        my %coursecodes;
        $totcodes = &Apache::courseclassifier::retrieve_instcodes(\%coursecodes,$defdom,$totcodes);
        my $coursecode;
        my @standardnames = &Apache::loncommon::get_standard_codeitems();
        if ($totcodes > 0) {
            $coursecode = &Apache::courseclassifier::instcode_from_selectors($defdom); 
        } 
        if ($coursecode eq '') {
            foreach my $item (@standardnames) {
                if ((defined($env{'form.'.$item})) && ($env{'form.'.$item} ne '-1')) {
                    $coursecode .= $env{'form.'.$item};
                }
            }
        }
    }
    my %lt = &Apache::lonlocal::texthash (
                 username    => 'Name',
                 email       => 'E-mail',
                 cc          => 'Cc',
                 user        => 'Username/domain',
                 phone       => 'Phone',
                 crsi        => 'Course Information',
                 subject     => 'Subject',
                 description => 'Description',
                 sourceurl   => 'URL',
                 date        => 'Date/Time',
                 secn        => 'Section',
                 asup        => 'A support request has been sent to',
                 warn        => 'Warning: Problem with support e-mail address',
                 your        => 'Your support request contained the following information',
                 sect        => 'section',
                 info        => 'Information supplied',
                 adin        => 'Additional information recorded',
    );

    my (@ok_ccs,@bad_ccs,$badccmsg,$okcclist);
    if ((defined($env{'user.name'})) && (defined($env{'form.cc'}))) {
        my @ccs;
        if ($env{'form.cc'} =~ /,/) {
            @ccs = split(/,/,$env{'form.cc'});
        } else {
            $env{'form.cc'} =~ s/^\s+//;
            $env{'form.cc'} =~ s/\s+$//;
            @ccs = $env{'form.cc'};
        }
        foreach my $cc (@ccs) {
            $cc =~ s/^\s+//g;
            $cc =~ s/\s+$//g;
            if ($cc =~ m/^[^\@]+\@[^\@]+$/) {
                if (!(grep(/^\Q$cc\E$/,@ok_ccs))) {
                    push(@ok_ccs,$cc);
                }
            } elsif ($cc ne '') {
                if (!(grep(/^\Q$cc\E$/,@bad_ccs))) {
                    push(@bad_ccs,$cc);
                }
            }
        }
        if (@ok_ccs > 0) {
           $okcclist = join(', ',@ok_ccs); 
        } 
        if (@bad_ccs == 1) {
            $badccmsg .= '<br />'.&mt('The following Cc e-mail address is invalid: ').$bad_ccs[0];
        } elsif (@bad_ccs > 1) {
            my $bad_cc_string = join(', ',@bad_ccs);
            $badccmsg .= '<br />'.&mt('The following Cc e-mail addresses are invalid: ').$bad_cc_string;
        }
    }
    $env{'form.user'} = "'".$env{'form.uname'}.':'.$env{'form.udom'}."'";
    $env{'form.crsi'} = $env{'form.title'}.' - '.$coursecode.' - '.$lt{'sect'}.': '.$env{'form.section'};
    my $supportmsg = <<END;
$lt{'username'}: $env{'form.username'}
$lt{'email'}: $env{'form.email'}
$lt{'cc'}: $okcclist
$lt{'user'}: $env{'form.user'}
$lt{'phone'}: $env{'form.phone'}
$lt{'crsi'}: $env{'form.crsi'}
$lt{'subject'}: $env{'form.subject'}
$lt{'description'}: $env{'form.description'}
$lt{'sourceurl'}: $env{'form.sourceurl'}
$lt{'date'}: $reporttime

END
    my $displaymsg;
    foreach my $item ('username','email','cc','user','phone','crsi','subject','description','sourceurl') {
        if ($env{'form.'.$item} ne '') {
            if ($item eq 'description') {
                my $descrip = $env{'form.description'};
                $descrip =  &cleanup_html($descrip);
                $descrip =~ s|[\n\r\f]|<br />|g;
                $displaymsg .= 
                    '<span class="LC_helpform_receipt_cat">'.
                    "$lt{$item}</span>: $descrip<br />\n";
            } elsif ($item eq 'sourceurl') {
                my $showurl = $env{'form.sourceurl'};
                $showurl =~ s/\?.*$//;
                $showurl =  &cleanup_html($showurl);
                $displaymsg .= 
                    '<span class="LC_helpform_receipt_cat">'.
                    "$lt{$item}</span>: $showurl<br />\n";
            } elsif ($item eq 'cc') {
                $displaymsg .=
                    '<span class="LC_helpform_receipt_cat">'.
                    "$lt{$item}</span>: $okcclist<br />\n";
            } else {
                my $showitem = $env{'form.'.$item};
                $showitem = &cleanup_html($showitem);
                $displaymsg .= 
                    '<span class="LC_helpform_receipt_cat">'.
                    "$lt{$item}</span>: $showitem<br />\n";
            }
        }
    }
    $displaymsg .= '<span class="LC_helpform_receipt_cat">'.
                   $lt{'date'}.'</span>: '.$reporttime.'<br />'."\n";

    my $start_page = 
	&Apache::loncommon::start_page('Support request recorded',undef,
				       {'function'    => $function,
					'add_entries' => {
					    topmargin    => "0",
					    marginheight => "0",
					},
					'only_body'   => 1,});

    $r->print(<<"END");
$start_page
<form name="logproblem">
<input type="hidden" name="command" value="result" />
</form>
END
    if ($r->uri eq '/adm/helpdesk') {
        &print_header($r,$url,'process');
    }
    my $bad_email = 0;
    if ($to =~ /,/) {
        my @ok_email; 
        foreach my $email (split(/,/,$to)) {
            if ($email =~ m/^[^\@]+\@[^\@]+$/) {
                if (!grep(/^\Q$email\E$/,@ok_email)) {
                    push(@ok_email,$email);
                }
            }
        }
        if (@ok_email > 0) {
            $to = join(',',@ok_email);
        } elsif ($admin =~ m/^[^\@]+\@[^\@]+$/) {
            $to = $admin;
        } else {
            $bad_email = 1;
        }
    } elsif ($to !~ m/^[^\@]+\@[^\@]+$/) {
        if ($admin =~ m/^[^\@]+\@[^\@]+$/) {
            $to = $admin;
        } else {
            $bad_email = 1;
        }
    }
    if ($bad_email) {
        $r->print('
 <h3>'.$lt{'warn'}.'</h3>'.
&mt('As the e-mail address provided for this LON-CAPA server ([_1]) does not appear to be a valid e-mail address, your support request has <b>not</b> been sent to the LON-CAPA support staff or administrator at your institution.',$to).' '.&mt('Instead a copy has been sent to the LON-CAPA support team at Michigan State University.')); 
            $to = 'helpdesk@lon-capa.org';
    } else {
        $r->print('<h3>'.$lt{'asup'}.' '.$to.'</h3>');
    }
    if (defined($env{'form.email'})) {
        $env{'form.email'} =~ s/^\s+//;
        $env{'form.email'} =~ s/\s+$//;
        if ($env{'form.email'} =~ m/^[^\@]+\@[^\@]+$/) {
            $from = $env{'form.email'};
        }
    }

    if (defined($env{'form.cc'})) {
        if ($badccmsg) {
            $displaymsg .= $badccmsg;
        }
    }

    my $subject = $env{'form.subject'};
    $subject =~ s/(`)/'/g;
    $subject =~ s/\$/\(\$\)/g;
    $supportmsg =~ s/(`)/'/g;
    $supportmsg =~ s/\$/\(\$\)/g;
    $displaymsg =~ s/(`)/'/g;
    $displaymsg =~ s/\$/\(\$\)/g;
    my $fname;

    my $attachmentpath = '';
    my $attachmentsize = '';
    if ((defined($env{'user.name'})) && ($env{'user.name'} ne 'public')
        && ($env{'user.domain'} ne 'public')) {
        if ($env{'form.screenshot.filename'}) {
            $attachmentsize = length($env{'form.screenshot'});
            if ($attachmentsize > 131072) {
                $displaymsg .= '<br />'.&mt('The uploaded screenshot file ([_1] bytes) included with your request exceeded the maximum allowed size - 128 KB, and has therefore been discarded.',$attachmentsize);
            } else {
                $attachmentpath=&Apache::lonnet::userfileupload('screenshot',undef,'helprequests');
            }
        }
    }

    my %cookies;
    my $cookie=CGI::Cookie->parse($r->header_in('Cookie'));
    if ($$cookie{'lonID'} =~ /lonID=($LONCAPA::handle_re);/) {
        $cookies{'lonID'} = $1;
    }

    if ($attachmentpath =~ m-/([^/]+)$-) {
        $fname = $1;
        $displaymsg .= '<br />'
                      .&mt('An uploaded screenshot file [_1] ([_2] bytes) was included in the request sent by [_3].'
                          ,'<span class="LC_filename">'.$fname.'<span>'
                          ,$attachmentsize
                          ,$env{'user.name'}.':'.$env{'user.domain'}
                       );
        $supportmsg .= "\n";
        foreach my $var (@cookievars) {
            $supportmsg .= "$var: $cookies{$var}\n";
        }
        foreach my $var(@ENVvars) {
            $supportmsg .= "$var: $ENV{$var}\n";
        }
        foreach my $var (@envvars) {
            $supportmsg .= "$var: $env{$var}\n";
        }
    }
 
    my $msg = MIME::Lite->new(
                 From    => $from,
                 To      => $to,
                 Subject => $subject,
                 Type    =>'TEXT',
                 Data    => $supportmsg,
                 );
    if (@ok_ccs > 0) {
        my $cc_string = join(', ',@ok_ccs);
        $msg->add("Cc" => $cc_string);
    }
    if ($bcc ne '') {
        $msg->add("Bcc" => $bcc);
    }
    $msg->add('Content-type','text/plain; charset=UTF-8');

    if ($attachmentpath) {
        my ($type, $encoding) = MIME::Types::by_suffix($attachmentpath);
        $msg->attach(Type     => $type,
                     Path     => $attachmentpath,
                     Filename => $fname
                     );

    } else {
        my $envdata = '';
        foreach my $var (@cookievars) {
            $envdata .= "$var: $cookies{$var}\n";
        }
        foreach my $var (@ENVvars) {
            $envdata .= "$var: $ENV{$var}\n";
        }
        foreach my $var (@envvars) {
            $envdata .= "$var: $env{$var}\n";
        }
        foreach my $var (@loncvars) {
            $envdata .= "$var: $env{$var}\n";
        }
        $msg->attach(Type => 'TEXT',
                     Data => $envdata);
    }

### Send it:
    $msg->send('sendmail');

    if ($attachmentpath =~ m|$Apache::lonnet::perlvar{'lonDaemons'}/tmp/helprequests/(\d+)/[^/]+|) {
        unlink($attachmentpath);
    }
    $r->print('<b>'.$lt{'your'}.'</b>:<br /><br />'."\n");
    $r->print('<div style="width:620px;">'.
              &Apache::lonhtmlcommon::start_pick_box().
              &Apache::lonhtmlcommon::row_title($lt{'info'},undef,'LC_oddrow_value')."\n".$displaymsg."\n".
              &Apache::lonhtmlcommon::row_closure().
              &Apache::lonhtmlcommon::row_title($lt{'adin'},undef,'LC_evenrow_value'));
    my $envmsg;
    foreach my $var (@cookievars) {
        if ($cookies{$var} ne '') {
            $envmsg.= '<span class="LC_helpform_receipt_cat">'.
                      $var.'</span>:&nbsp;'.$cookies{$var}.', ';
        }
    }
    foreach my $var (@ENVvars) {
        if ($ENV{$var} ne '') {
            $envmsg .= '<span class="LC_helpform_receipt_cat">'.
                       $var.'</span>:&nbsp;'.$ENV{$var}.', ';
        }
    }
    foreach my $var (@envvars) {
        if ($env{$var} ne '') { 
            $envmsg .= '<span class="LC_helpform_receipt_cat">'.
                       $var.'</span>:&nbsp;'.$env{$var}.', ';
        }
    }
    $envmsg =~ s/, $//;
    $r->print($envmsg."\n".
              &Apache::lonhtmlcommon::row_closure(1)."\n".
              &Apache::lonhtmlcommon::end_pick_box().
              "</div>\n".
              &Apache::loncommon::end_page());
}

sub print_header {
    my ($r,$origurl,$command) = @_;
    my $location=&Apache::loncommon::lonhttpdurl("/adm");
    my ($component_url);
    my $helpdesk_link = '<a href="javascript:validate()">';
    if ($command eq 'process') {
        $helpdesk_link = '<a href="/adm/helpdesk">';
    }
    my %lt = &Apache::lonlocal::texthash (
                                           login => 'Log-in help',
                                           ask   => 'Ask helpdesk',
                                           getst => 'Getting started guide',
                                           back =>  'Back to last location',
                                           headline => 'help/support',
                                         );
    my ($getstartlink,$reviewtext);
    if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/gettingstarted.html') {
        $getstartlink = qq|<td align="center">&nbsp;<b><a href="/adm/gettingstarted.html">$lt{'getst'}</a></td>|;
        $reviewtext = &mt('Please review the information in "Log-in help" and the "Getting started" guide if you are unable to log-in.');
    } else {
        $reviewtext = &mt('Please review the information in "Log-in help" if you are unable to log-in.');
    }
    if ($origurl eq '') {
        $origurl = 'javascript:history.go(-1)';
    }
    $r->print(<<END);
<table width="620" border="0" cellspacing="0" cellpadding="0" height="55">   <tr height="50">    <td width='5'>&nbsp;</td>
   <td>
    <fieldset>
      <legend>
        <img src="$location/lonIcons/minilogo.gif" height="20" width="29" valign="bottom" />
        LON-CAPA $lt{'headline'}
      </legend>
 <table id="LC_helpmenu_links">
   <tr>
    <td align="center"><span class="LC_nobreak"><img src="$location/help/help.png" border="0" alt="($lt{'login'})" valign="middle" />&nbsp;<b><a href="/adm/loginproblems.html">$lt{'login'}</a></b>&nbsp;</span></td>
    <td align="center"><span class="LC_nobreak">&nbsp;<b>$helpdesk_link<img src="$location/lonIcons/helpdesk.gif" border="0" alt="($lt{'ask'})" valign="middle" />&nbsp;$lt{'ask'}</a></b>&nbsp;</span></td>$getstartlink
    <td align="center"><span class="LC_nobreak">&nbsp;<b><a href="$origurl" target="_top"><img src="$location/lonIcons/move_up.gif" border="0" alt="($lt{'back'})" valign="middle" />&nbsp;$lt{'back'}</a></b>&nbsp;</span></td>
   </tr>
 </table>
</fieldset>
  </td>
  <td width='5'>&nbsp;</td>
 </tr>
 <tr height='5'>
  <td colspan='3' height='5'>&nbsp;</td>
 </tr>
END
    if  ($command ne 'process') {
        $r->print('
 <tr>
  <td colspan="3">'.$reviewtext.' '
.&mt('If your problem is still unresolved, the form below can be used to send a question to the LON-CAPA helpdesk.').'<br />'
.'<font size="-1"><b>'.&mt('Students').'</b>: '.&mt('Do <b>not</b> use this form to ask questions about course content.').' '
.&mt('Contact your instructor instead.')
.'</font><br /><br />
  </td>
 </tr>');
    }
    $r->print('
</table>');
    return;
}

sub get_domain {
    my $codedom;
    if (exists($env{'form.codedom'})) {
        $codedom = $env{'form.codedom'};
    } elsif ($env{'request.course.id'}) {
        $codedom = $env{'course.'.$env{'request.course.id'}.'.domain'};
    } elsif ($env{'request.role.domain'}) {
        $codedom = $env{'request.role.domain'};
    } else {
        $codedom = &Apache::lonnet::default_login_domain();
    }
    return $codedom;
}

sub cleanup_html {
    my ($incoming) = @_;
    my $outgoing;
    if ($incoming ne '') {
        $outgoing = $incoming;
        $outgoing =~ s/\#/&#035;/g;
        $outgoing =~ s/\&/&#038;/g;
        $outgoing =~ s/</&#060;/g;
        $outgoing =~ s/>/&#062;/g;
        $outgoing =~ s/\(/&#040/g;
        $outgoing =~ s/\)/&#041;/g;
        $outgoing =~ s/"/&#034;/g;
        $outgoing =~ s/'/&#039;/g;
        $outgoing =~ s/\$/&#036;/g;
    }
    return $outgoing;
}

1;

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