File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.172: download - view: text, annotated - select for diffs
Thu Jan 15 01:43:43 2004 UTC (20 years, 5 months ago) by www
Branches: MAIN
CVS tags: HEAD
Bugzilla and FAQ links

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.172 2004/01/15 01:43:43 www 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: # Makes a table out of the previous attempts
   30: # Inputs result_from_symbread, user, domain, course_id
   31: # Reads in non-network-related .tab files
   32: 
   33: # POD header:
   34: 
   35: =pod
   36: 
   37: =head1 NAME
   38: 
   39: Apache::loncommon - pile of common routines
   40: 
   41: =head1 SYNOPSIS
   42: 
   43: Common routines for manipulating connections, student answers,
   44:     domains, common Javascript fragments, etc.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: A collection of commonly used subroutines that don't have a natural
   49: home anywhere else. This collection helps remove
   50: redundancy from other modules and increase efficiency of memory usage.
   51: 
   52: =cut 
   53: 
   54: # End of POD header
   55: package Apache::loncommon;
   56: 
   57: use strict;
   58: use Apache::lonnet();
   59: use GDBM_File;
   60: use POSIX qw(strftime mktime);
   61: use Apache::Constants qw(:common :http :methods);
   62: use Apache::lonmsg();
   63: use Apache::lonmenu();
   64: use Apache::lonlocal;
   65: use HTML::Entities;
   66: 
   67: my $readit;
   68: 
   69: ##
   70: ## Global Variables
   71: ##
   72: 
   73: # ----------------------------------------------- Filetypes/Languages/Copyright
   74: my %language;
   75: my %supported_language;
   76: my %cprtag;
   77: my %fe; my %fd;
   78: my %category_extensions;
   79: 
   80: # ---------------------------------------------- Designs
   81: 
   82: my %designhash;
   83: 
   84: # ---------------------------------------------- Thesaurus variables
   85: #
   86: # %Keywords:
   87: #      A hash used by &keyword to determine if a word is considered a keyword.
   88: # $thesaurus_db_file 
   89: #      Scalar containing the full path to the thesaurus database.
   90: 
   91: my %Keywords;
   92: my $thesaurus_db_file;
   93: 
   94: #
   95: # Initialize values from language.tab, copyright.tab, filetypes.tab,
   96: # thesaurus.tab, and filecategories.tab.
   97: #
   98: BEGIN {
   99:     # Variable initialization
  100:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  101:     #
  102:     unless ($readit) {
  103: # ------------------------------------------------------------------- languages
  104:     {
  105:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  106:                                    '/language.tab';
  107:         if ( open(my $fh,"<$langtabfile") ) {
  108:             while (<$fh>) {
  109:                 next if /^\#/;
  110:                 chomp;
  111:                 my ($key,$two,$country,$three,$enc,$val,$sup)=(split(/\t/,$_));
  112:                 $language{$key}=$val.' - '.$enc;
  113:                 if ($sup) {
  114:                     $supported_language{$key}=$sup;
  115:                 }
  116:             }
  117:             close($fh);
  118:         }
  119:     }
  120: # ------------------------------------------------------------------ copyrights
  121:     {
  122:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  123:                                   '/copyright.tab';
  124:         if ( open (my $fh,"<$copyrightfile") ) {
  125:             while (<$fh>) {
  126:                 next if /^\#/;
  127:                 chomp;
  128:                 my ($key,$val)=(split(/\s+/,$_,2));
  129:                 $cprtag{$key}=$val;
  130:             }
  131:             close($fh);
  132:         }
  133:     }
  134: 
  135: # -------------------------------------------------------------- domain designs
  136: 
  137:     my $filename;
  138:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  139:     opendir(DIR,$designdir);
  140:     while ($filename=readdir(DIR)) {
  141: 	my ($domain)=($filename=~/^(\w+)\./);
  142:     {
  143:         my $designfile = $designdir.'/'.$filename;
  144:         if ( open (my $fh,"<$designfile") ) {
  145:             while (<$fh>) {
  146:                 next if /^\#/;
  147:                 chomp;
  148:                 my ($key,$val)=(split(/\=/,$_));
  149:                 if ($val) { $designhash{$domain.'.'.$key}=$val; }
  150:             }
  151:             close($fh);
  152:         }
  153:     }
  154: 
  155:     }
  156:     closedir(DIR);
  157: 
  158: 
  159: # ------------------------------------------------------------- file categories
  160:     {
  161:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  162:                                   '/filecategories.tab';
  163:         if ( open (my $fh,"<$categoryfile") ) {
  164:             while (<$fh>) {
  165:                 next if /^\#/;
  166:                 chomp;
  167:                 my ($extension,$category)=(split(/\s+/,$_,2));
  168:                 push @{$category_extensions{lc($category)}},$extension;
  169:             }
  170:             close($fh);
  171:         }
  172: 
  173:     }
  174: # ------------------------------------------------------------------ file types
  175:     {
  176:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  177:                '/filetypes.tab';
  178:         if ( open (my $fh,"<$typesfile") ) {
  179:             while (<$fh>) {
  180:                 next if (/^\#/);
  181:                 chomp;
  182:                 my ($ending,$emb,$descr)=split(/\s+/,$_,3);
  183:                 if ($descr ne '') {
  184:                     $fe{$ending}=lc($emb);
  185:                     $fd{$ending}=$descr;
  186:                 }
  187:             }
  188:             close($fh);
  189:         }
  190:     }
  191:     &Apache::lonnet::logthis(
  192:               "<font color=yellow>INFO: Read file types</font>");
  193:     $readit=1;
  194:     }  # end of unless($readit) 
  195:     
  196: }
  197: 
  198: ###############################################################
  199: ##           HTML and Javascript Helper Functions            ##
  200: ###############################################################
  201: 
  202: =pod 
  203: 
  204: =head1 HTML and Javascript Functions
  205: 
  206: =over 4
  207: 
  208: =item * browser_and_searcher_javascript ()
  209: 
  210: X<browsing, javascript>X<searching, javascript>Returns a string
  211: containing javascript with two functions, C<openbrowser> and
  212: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  213: tags.
  214: 
  215: =item * openbrowser(formname,elementname,only,omit) [javascript]
  216: 
  217: inputs: formname, elementname, only, omit
  218: 
  219: formname and elementname indicate the name of the html form and name of
  220: the element that the results of the browsing selection are to be placed in. 
  221: 
  222: Specifying 'only' will restrict the browser to displaying only files
  223: with the given extension.  Can be a comma seperated list.
  224: 
  225: Specifying 'omit' will restrict the browser to NOT displaying files
  226: with the given extension.  Can be a comma seperated list.
  227: 
  228: =item * opensearcher(formname, elementname) [javascript]
  229: 
  230: Inputs: formname, elementname
  231: 
  232: formname and elementname specify the name of the html form and the name
  233: of the element the selection from the search results will be placed in.
  234: 
  235: =cut
  236: 
  237: sub browser_and_searcher_javascript {
  238:     my $resurl=&lastresurl();
  239:     return <<END;
  240:     var editbrowser = null;
  241:     function openbrowser(formname,elementname,only,omit,titleelement) {
  242:         var url = '$resurl/?';
  243:         if (editbrowser == null) {
  244:             url += 'launch=1&';
  245:         }
  246:         url += 'catalogmode=interactive&';
  247:         url += 'mode=edit&';
  248:         url += 'form=' + formname + '&';
  249:         if (only != null) {
  250:             url += 'only=' + only + '&';
  251:         } 
  252:         if (omit != null) {
  253:             url += 'omit=' + omit + '&';
  254:         }
  255:         if (titleelement != null) {
  256:             url += 'titleelement=' + titleelement + '&';
  257:         }
  258:         url += 'element=' + elementname + '';
  259:         var title = 'Browser';
  260:         var options = 'scrollbars=1,resizable=1,menubar=0';
  261:         options += ',width=700,height=600';
  262:         editbrowser = open(url,title,options,'1');
  263:         editbrowser.focus();
  264:     }
  265:     var editsearcher;
  266:     function opensearcher(formname,elementname,titleelement) {
  267:         var url = '/adm/searchcat?';
  268:         if (editsearcher == null) {
  269:             url += 'launch=1&';
  270:         }
  271:         url += 'catalogmode=interactive&';
  272:         url += 'mode=edit&';
  273:         url += 'form=' + formname + '&';
  274:         if (titleelement != null) {
  275:             url += 'titleelement=' + titleelement + '&';
  276:         }
  277:         url += 'element=' + elementname + '';
  278:         var title = 'Search';
  279:         var options = 'scrollbars=1,resizable=1,menubar=0';
  280:         options += ',width=700,height=600';
  281:         editsearcher = open(url,title,options,'1');
  282:         editsearcher.focus();
  283:     }
  284: END
  285: }
  286: 
  287: sub lastresurl {
  288:     if ($ENV{'environment.lastresurl'}) {
  289: 	return $ENV{'environment.lastresurl'}
  290:     } else {
  291: 	return '/res';
  292:     }
  293: }
  294: 
  295: sub storeresurl {
  296:     my $resurl=&Apache::lonnet::clutter(shift);
  297:     unless ($resurl=~/^\/res/) { return 0; }
  298:     $resurl=~s/\/$//;
  299:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  300:     &Apache::lonnet::appenv('environment.lastresurl' => $resurl);
  301:     return 1;
  302: }
  303: 
  304: sub studentbrowser_javascript {
  305:    unless (
  306:             (($ENV{'request.course.id'}) && 
  307:              (&Apache::lonnet::allowed('srm',$ENV{'request.course.id'})))
  308:          || ($ENV{'request.role'}=~/^(au|dc|su)/)
  309:           ) { return ''; }  
  310:    return (<<'ENDSTDBRW');
  311: <script type="text/javascript" language="Javascript" >
  312:     var stdeditbrowser;
  313:     function openstdbrowser(formname,uname,udom,roleflag) {
  314:         var url = '/adm/pickstudent?';
  315:         var filter;
  316:         eval('filter=document.'+formname+'.'+uname+'.value;');
  317:         if (filter != null) {
  318:            if (filter != '') {
  319:                url += 'filter='+filter+'&';
  320: 	   }
  321:         }
  322:         url += 'form=' + formname + '&unameelement='+uname+
  323:                                     '&udomelement='+udom;
  324: 	if (roleflag) { url+="&roles=1"; }
  325:         var title = 'Student_Browser';
  326:         var options = 'scrollbars=1,resizable=1,menubar=0';
  327:         options += ',width=700,height=600';
  328:         stdeditbrowser = open(url,title,options,'1');
  329:         stdeditbrowser.focus();
  330:     }
  331: </script>
  332: ENDSTDBRW
  333: }
  334: 
  335: sub selectstudent_link {
  336:    my ($form,$unameele,$udomele)=@_;
  337:    if ($ENV{'request.course.id'}) {  
  338:        unless (&Apache::lonnet::allowed('srm',$ENV{'request.course.id'})) {
  339: 	   return '';
  340:        }
  341:        return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
  342:         '","'.$udomele.'");'."'>".&mt('Select User')."</a>";
  343:    }
  344:    if ($ENV{'request.role'}=~/^(au|dc|su)/) {
  345:        return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
  346:         '","'.$udomele.'",1);'."'>".&mt('Select User')."</a>";
  347:    }
  348:    return '';
  349: }
  350: 
  351: sub coursebrowser_javascript {
  352:     my ($domainfilter)=@_;
  353:    return (<<ENDSTDBRW);
  354: <script type="text/javascript" language="Javascript" >
  355:     var stdeditbrowser;
  356:     function opencrsbrowser(formname,uname,udom) {
  357:         var url = '/adm/pickcourse?';
  358:         var filter;
  359:         if (filter != null) {
  360:            if (filter != '') {
  361:                url += 'filter='+filter+'&';
  362: 	   }
  363:         }
  364:         var domainfilter='$domainfilter';
  365:         if (domainfilter != null) {
  366:            if (domainfilter != '') {
  367:                url += 'domainfilter='+domainfilter+'&';
  368: 	   }
  369:         }
  370:         url += 'form=' + formname + '&cnumelement='+uname+
  371:                                     '&cdomelement='+udom;
  372:         var title = 'Course_Browser';
  373:         var options = 'scrollbars=1,resizable=1,menubar=0';
  374:         options += ',width=700,height=600';
  375:         stdeditbrowser = open(url,title,options,'1');
  376:         stdeditbrowser.focus();
  377:     }
  378: </script>
  379: ENDSTDBRW
  380: }
  381: 
  382: sub selectcourse_link {
  383:    my ($form,$unameele,$udomele)=@_;
  384:     return "<a href='".'javascript:opencrsbrowser("'.$form.'","'.$unameele.
  385:         '","'.$udomele.'");'."'>".&mt('Select Course')."</a>";
  386: }
  387: 
  388: =pod
  389: 
  390: =item * linked_select_forms(...)
  391: 
  392: linked_select_forms returns a string containing a <script></script> block
  393: and html for two <select> menus.  The select menus will be linked in that
  394: changing the value of the first menu will result in new values being placed
  395: in the second menu.  The values in the select menu will appear in alphabetical
  396: order.
  397: 
  398: linked_select_forms takes the following ordered inputs:
  399: 
  400: =over 4
  401: 
  402: =item * $formname, the name of the <form> tag
  403: 
  404: =item * $middletext, the text which appears between the <select> tags
  405: 
  406: =item * $firstdefault, the default value for the first menu
  407: 
  408: =item * $firstselectname, the name of the first <select> tag
  409: 
  410: =item * $secondselectname, the name of the second <select> tag
  411: 
  412: =item * $hashref, a reference to a hash containing the data for the menus.
  413: 
  414: =back 
  415: 
  416: Below is an example of such a hash.  Only the 'text', 'default', and 
  417: 'select2' keys must appear as stated.  keys(%menu) are the possible 
  418: values for the first select menu.  The text that coincides with the 
  419: first menu value is given in $menu{$choice1}->{'text'}.  The values 
  420: and text for the second menu are given in the hash pointed to by 
  421: $menu{$choice1}->{'select2'}.  
  422: 
  423:  my %menu = ( A1 => { text =>"Choice A1" ,
  424:                        default => "B3",
  425:                        select2 => { 
  426:                            B1 => "Choice B1",
  427:                            B2 => "Choice B2",
  428:                            B3 => "Choice B3",
  429:                            B4 => "Choice B4"
  430:                            }
  431:                    },
  432:                A2 => { text =>"Choice A2" ,
  433:                        default => "C2",
  434:                        select2 => { 
  435:                            C1 => "Choice C1",
  436:                            C2 => "Choice C2",
  437:                            C3 => "Choice C3"
  438:                            }
  439:                    },
  440:                A3 => { text =>"Choice A3" ,
  441:                        default => "D6",
  442:                        select2 => { 
  443:                            D1 => "Choice D1",
  444:                            D2 => "Choice D2",
  445:                            D3 => "Choice D3",
  446:                            D4 => "Choice D4",
  447:                            D5 => "Choice D5",
  448:                            D6 => "Choice D6",
  449:                            D7 => "Choice D7"
  450:                            }
  451:                    }
  452:                );
  453: 
  454: =cut
  455: 
  456: sub linked_select_forms {
  457:     my ($formname,
  458:         $middletext,
  459:         $firstdefault,
  460:         $firstselectname,
  461:         $secondselectname, 
  462:         $hashref
  463:         ) = @_;
  464:     my $second = "document.$formname.$secondselectname";
  465:     my $first = "document.$formname.$firstselectname";
  466:     # output the javascript to do the changing
  467:     my $result = '';
  468:     $result.="<script>\n";
  469:     $result.="var select2data = new Object();\n";
  470:     $" = '","';
  471:     my $debug = '';
  472:     foreach my $s1 (sort(keys(%$hashref))) {
  473:         $result.="select2data.d_$s1 = new Object();\n";        
  474:         $result.="select2data.d_$s1.def = new String('".
  475:             $hashref->{$s1}->{'default'}."');\n";
  476:         $result.="select2data.d_$s1.values = new Array(";        
  477:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
  478:         $result.="\"@s2values\");\n";
  479:         $result.="select2data.d_$s1.texts = new Array(";        
  480:         my @s2texts;
  481:         foreach my $value (@s2values) {
  482:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
  483:         }
  484:         $result.="\"@s2texts\");\n";
  485:     }
  486:     $"=' ';
  487:     $result.= <<"END";
  488: 
  489: function select1_changed() {
  490:     // Determine new choice
  491:     var newvalue = "d_" + $first.value;
  492:     // update select2
  493:     var values     = select2data[newvalue].values;
  494:     var texts      = select2data[newvalue].texts;
  495:     var select2def = select2data[newvalue].def;
  496:     var i;
  497:     // out with the old
  498:     for (i = 0; i < $second.options.length; i++) {
  499:         $second.options[i] = null;
  500:     }
  501:     // in with the nuclear
  502:     for (i=0;i<values.length; i++) {
  503:         $second.options[i] = new Option(values[i]);
  504:         $second.options[i].value = values[i];
  505:         $second.options[i].text = texts[i];
  506:         if (values[i] == select2def) {
  507:             $second.options[i].selected = true;
  508:         }
  509:     }
  510: }
  511: </script>
  512: END
  513:     # output the initial values for the selection lists
  514:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
  515:     foreach my $value (sort(keys(%$hashref))) {
  516:         $result.="    <option value=\"$value\" ";
  517:         $result.=" selected=\"true\" " if ($value eq $firstdefault);
  518:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
  519:     }
  520:     $result .= "</select>\n";
  521:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
  522:     $result .= $middletext;
  523:     $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
  524:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
  525:     foreach my $value (sort(keys(%select2))) {
  526:         $result.="    <option value=\"$value\" ";        
  527:         $result.=" selected=\"true\" " if ($value eq $seconddefault);
  528:         $result.=">".&mt($select2{$value})."</option>\n";
  529:     }
  530:     $result .= "</select>\n";
  531:     #    return $debug;
  532:     return $result;
  533: }   #  end of sub linked_select_forms {
  534: 
  535: =pod
  536: 
  537: =item * help_open_topic($topic, $text, $stayOnPage, $width, $height)
  538: 
  539: Returns a string corresponding to an HTML link to the given help
  540: $topic, where $topic corresponds to the name of a .tex file in
  541: /home/httpd/html/adm/help/tex, with underscores replaced by
  542: spaces. 
  543: 
  544: $text will optionally be linked to the same topic, allowing you to
  545: link text in addition to the graphic. If you do not want to link
  546: text, but wish to specify one of the later parameters, pass an
  547: empty string. 
  548: 
  549: $stayOnPage is a value that will be interpreted as a boolean. If true,
  550: the link will not open a new window. If false, the link will open
  551: a new window using Javascript. (Default is false.) 
  552: 
  553: $width and $height are optional numerical parameters that will
  554: override the width and height of the popped up window, which may
  555: be useful for certain help topics with big pictures included. 
  556: 
  557: =cut
  558: 
  559: sub help_open_topic {
  560:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
  561:     $text = "" if (not defined $text);
  562:     $stayOnPage = 0 if (not defined $stayOnPage);
  563:     if ($ENV{'browser.interface'} eq 'textual' ||
  564: 	$ENV{'environment.remote'} eq 'off' ) {
  565: 	$stayOnPage=1;
  566:     }
  567:     $width = 350 if (not defined $width);
  568:     $height = 400 if (not defined $height);
  569:     my $filename = $topic;
  570:     $filename =~ s/ /_/g;
  571: 
  572:     my $template = "";
  573:     my $link;
  574: 
  575:     $topic=~s/\W/\_/g;
  576: 
  577:     if (!$stayOnPage)
  578:     {
  579: 	$link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
  580:     }
  581:     else
  582:     {
  583: 	$link = "/adm/help/${filename}.hlp";
  584:     }
  585: 
  586:     # Add the text
  587:     if ($text ne "")
  588:     {
  589: 	$template .= 
  590:   "<table bgcolor='#3333AA' cellspacing='1' cellpadding='1' border='0'><tr>".
  591:   "<td bgcolor='#5555FF'><a href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
  592:     }
  593: 
  594:     # Add the graphic
  595:     $template .= <<"ENDTEMPLATE";
  596:  <a href="$link"><image src="/adm/help/gif/smallHelp.gif" border="0" alt="(Help: $topic)" /></a>
  597: ENDTEMPLATE
  598:     if ($text ne '') { $template.='</td></tr></table>' };
  599:     return $template;
  600: 
  601: }
  602: 
  603: # This is a quicky function for Latex cheatsheet editing, since it 
  604: # appears in at least four places
  605: sub helpLatexCheatsheet {
  606:     my $other = shift;
  607:     my $addOther = '';
  608:     if ($other) {
  609: 	$addOther = Apache::loncommon::help_open_topic($other, shift,
  610: 						       undef, undef, 600) .
  611: 							   '</td><td>';
  612:     }
  613:     return '<table><tr><td>'.
  614: 	$addOther .
  615: 	&Apache::loncommon::help_open_topic("Greek_Symbols",'Greek Symbols',
  616: 					    undef,undef,600)
  617: 	.'</td><td>'.
  618: 	&Apache::loncommon::help_open_topic("Other_Symbols",'Other Symbols',
  619: 					    undef,undef,600)
  620: 	.'</td></tr></table>';
  621: }
  622: 
  623: sub help_open_bug {
  624:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
  625:     unless ($ENV{'user.adv'}) { return ''; }
  626:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
  627:     $text = "" if (not defined $text);
  628:     $stayOnPage = 0 if (not defined $stayOnPage);
  629:     if ($ENV{'browser.interface'} eq 'textual' ||
  630: 	$ENV{'environment.remote'} eq 'off' ) {
  631: 	$stayOnPage=1;
  632:     }
  633:     $width = 350 if (not defined $width);
  634:     $height = 400 if (not defined $height);
  635: 
  636:     $topic=~s/\W+/\+/g;
  637:     my $link='';
  638:     my $template='';
  639:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&bug_file_loc='.
  640: 	&Apache::lonnet::escape($ENV{'REQUEST_URI'}).'&component='.$topic;
  641:     if (!$stayOnPage)
  642:     {
  643: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
  644:     }
  645:     else
  646:     {
  647: 	$link = $url;
  648:     }
  649: 
  650:     # Add the text
  651:     if ($text ne "")
  652:     {
  653: 	$template .= 
  654:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
  655:   "<td bgcolor='#FF5555'><a href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
  656:     }
  657: 
  658:     # Add the graphic
  659:     $template .= <<"ENDTEMPLATE";
  660:  <a href="$link"><image src="/adm/lonMisc/smallBug.gif" border="0" alt="(Bug: $topic)" /></a>
  661: ENDTEMPLATE
  662:     if ($text ne '') { $template.='</td></tr></table>' };
  663:     return $template;
  664: 
  665: }
  666: 
  667: sub help_open_faq {
  668:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
  669:     unless ($ENV{'user.adv'}) { return ''; }
  670:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
  671:     $text = "" if (not defined $text);
  672:     $stayOnPage = 0 if (not defined $stayOnPage);
  673:     if ($ENV{'browser.interface'} eq 'textual' ||
  674: 	$ENV{'environment.remote'} eq 'off' ) {
  675: 	$stayOnPage=1;
  676:     }
  677:     $width = 350 if (not defined $width);
  678:     $height = 400 if (not defined $height);
  679: 
  680:     $topic=~s/\W+/\+/g;
  681:     my $link='';
  682:     my $template='';
  683:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
  684:     if (!$stayOnPage)
  685:     {
  686: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
  687:     }
  688:     else
  689:     {
  690: 	$link = $url;
  691:     }
  692: 
  693:     # Add the text
  694:     if ($text ne "")
  695:     {
  696: 	$template .= 
  697:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
  698:   "<td bgcolor='#FF5555'><a href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
  699:     }
  700: 
  701:     # Add the graphic
  702:     $template .= <<"ENDTEMPLATE";
  703:  <a href="$link"><image src="/adm/lonMisc/smallFAQ.gif" border="0" alt="(FAQ: $topic)" /></a>
  704: ENDTEMPLATE
  705:     if ($text ne '') { $template.='</td></tr></table>' };
  706:     return $template;
  707: 
  708: }
  709: 
  710: =pod
  711: 
  712: =item * csv_translate($text) 
  713: 
  714: Translate $text to allow it to be output as a 'comma seperated values' 
  715: format.
  716: 
  717: =cut
  718: 
  719: sub csv_translate {
  720:     my $text = shift;
  721:     $text =~ s/\"/\"\"/g;
  722:     $text =~ s/\n//g;
  723:     return $text;
  724: }
  725: 
  726: =pod
  727: 
  728: =item * change_content_javascript():
  729: 
  730: This and the next function allow you to create small sections of an
  731: otherwise static HTML page that you can update on the fly with
  732: Javascript, even in Netscape 4.
  733: 
  734: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
  735: must be written to the HTML page once. It will prove the Javascript
  736: function "change(name, content)". Calling the change function with the
  737: name of the section 
  738: you want to update, matching the name passed to C<changable_area>, and
  739: the new content you want to put in there, will put the content into
  740: that area.
  741: 
  742: B<Note>: Netscape 4 only reserves enough space for the changable area
  743: to contain room for the original contents. You need to "make space"
  744: for whatever changes you wish to make, and be B<sure> to check your
  745: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
  746: it's adequate for updating a one-line status display, but little more.
  747: This script will set the space to 100% width, so you only need to
  748: worry about height in Netscape 4.
  749: 
  750: Modern browsers are much less limiting, and if you can commit to the
  751: user not using Netscape 4, this feature may be used freely with
  752: pretty much any HTML.
  753: 
  754: =cut
  755: 
  756: sub change_content_javascript {
  757:     # If we're on Netscape 4, we need to use Layer-based code
  758:     if ($ENV{'browser.type'} eq 'netscape' &&
  759: 	$ENV{'browser.version'} =~ /^4\./) {
  760: 	return (<<NETSCAPE4);
  761: 	function change(name, content) {
  762: 	    doc = document.layers[name+"___escape"].layers[0].document;
  763: 	    doc.open();
  764: 	    doc.write(content);
  765: 	    doc.close();
  766: 	}
  767: NETSCAPE4
  768:     } else {
  769: 	# Otherwise, we need to use semi-standards-compliant code
  770: 	# (technically, "innerHTML" isn't standard but the equivalent
  771: 	# is really scary, and every useful browser supports it
  772: 	return (<<DOMBASED);
  773: 	function change(name, content) {
  774: 	    element = document.getElementById(name);
  775: 	    element.innerHTML = content;
  776: 	}
  777: DOMBASED
  778:     }
  779: }
  780: 
  781: =pod
  782: 
  783: =item * changable_area($name, $origContent):
  784: 
  785: This provides a "changable area" that can be modified on the fly via
  786: the Javascript code provided in C<change_content_javascript>. $name is
  787: the name you will use to reference the area later; do not repeat the
  788: same name on a given HTML page more then once. $origContent is what
  789: the area will originally contain, which can be left blank.
  790: 
  791: =cut
  792: 
  793: sub changable_area {
  794:     my ($name, $origContent) = @_;
  795: 
  796:     if ($ENV{'browser.type'} eq 'netscape' &&
  797: 	$ENV{'browser.version'} =~ /^4\./) {
  798: 	# If this is netscape 4, we need to use the Layer tag
  799: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
  800:     } else {
  801: 	return "<span id='$name'>$origContent</span>";
  802:     }
  803: }
  804: 
  805: =pod
  806: 
  807: =back
  808: 
  809: =cut
  810: 
  811: ###############################################################
  812: ##        Home server <option> list generating code          ##
  813: ###############################################################
  814: 
  815: =pod
  816: 
  817: =head1 Home Server option list generating code
  818: 
  819: =over 4
  820: 
  821: =item * get_domains()
  822: 
  823: Returns an array containing each of the domains listed in the hosts.tab
  824: file.
  825: 
  826: =cut
  827: 
  828: #-------------------------------------------
  829: sub get_domains {
  830:     # The code below was stolen from "The Perl Cookbook", p 102, 1st ed.
  831:     my @domains;
  832:     my %seen;
  833:     foreach (sort values(%Apache::lonnet::hostdom)) {
  834: 	push (@domains,$_) unless $seen{$_}++;
  835:     }
  836:     return @domains;
  837: }
  838: 
  839: # ------------------------------------------
  840: 
  841: sub domain_select {
  842:     my ($name,$value,$multiple)=@_;
  843:     my %domains=map { 
  844: 	$_ => $_.' '.$Apache::lonnet::domaindescription{$_} 
  845:     } &get_domains;
  846:     if ($multiple) {
  847: 	$domains{''}=&mt('Any domain');
  848: 	return &multiple_select_form($name,$value,%domains);
  849:     } else {
  850: 	return &select_form($name,$value,%domains);
  851:     }
  852: }
  853: 
  854: sub multiple_select_form {
  855:     my ($name,$value,%hash)=@_;
  856:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
  857:     my $output='';
  858:     my $size =(scalar keys %hash<4?scalar keys %hash:4);
  859:     $output.="\n<select name='$name' size='$size' multiple='1'>";
  860:     foreach (sort keys %hash) {
  861:         $output.="<option name='$_'".
  862:             ($selected{$_}?' selected="1"' :'').">$hash{$_}</option>\n";
  863:     }
  864:     $output.="</select>\n";
  865:     return $output;
  866: }
  867: 
  868: #-------------------------------------------
  869: 
  870: =pod
  871: 
  872: =item * select_form($defdom,$name,%hash)
  873: 
  874: Returns a string containing a <select name='$name' size='1'> form to 
  875: allow a user to select options from a hash option_name => displayed text.  
  876: See lonrights.pm for an example invocation and use.
  877: 
  878: =cut
  879: 
  880: #-------------------------------------------
  881: sub select_form {
  882:     my ($def,$name,%hash) = @_;
  883:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
  884:     my @keys;
  885:     if (exists($hash{'select_form_order'})) {
  886: 	@keys=@{$hash{'select_form_order'}};
  887:     } else {
  888: 	@keys=sort(keys(%hash));
  889:     }
  890:     foreach (@keys) {
  891:         $selectform.="<option value=\"$_\" ".
  892:             ($_ eq $def ? 'selected' : '').
  893:                 ">".&mt($hash{$_})."</option>\n";
  894:     }
  895:     $selectform.="</select>";
  896:     return $selectform;
  897: }
  898: 
  899: sub gradeleveldescription {
  900:     my $gradelevel=shift;
  901:     my %gradelevels=(0 => 'Not specified',
  902: 		     1 => 'Grade 1',
  903: 		     2 => 'Grade 2',
  904: 		     3 => 'Grade 3',
  905: 		     4 => 'Grade 4',
  906: 		     5 => 'Grade 5',
  907: 		     6 => 'Grade 6',
  908: 		     7 => 'Grade 7',
  909: 		     8 => 'Grade 8',
  910: 		     9 => 'Grade 9',
  911: 		     10 => 'Grade 10',
  912: 		     11 => 'Grade 11',
  913: 		     12 => 'Grade 12',
  914: 		     13 => 'Grade 13',
  915: 		     14 => '100 Level',
  916: 		     15 => '200 Level',
  917: 		     16 => '300 Level',
  918: 		     17 => '400 Level',
  919: 		     18 => 'Graduate Level');
  920:     return &mt($gradelevels{$gradelevel});
  921: }
  922: 
  923: sub select_level_form {
  924:     my ($deflevel,$name)=@_;
  925:     unless ($deflevel) { $deflevel=0; }
  926:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
  927:     for (my $i=0; $i<=18; $i++) {
  928:         $selectform.="<option value=\"$i\" ".
  929:             ($i==$deflevel ? 'selected' : '').
  930:                 ">".&gradeleveldescription($i)."</option>\n";
  931:     }
  932:     $selectform.="</select>";
  933:     return $selectform;
  934: }
  935: 
  936: #-------------------------------------------
  937: 
  938: =pod
  939: 
  940: =item * select_dom_form($defdom,$name,$includeempty)
  941: 
  942: Returns a string containing a <select name='$name' size='1'> form to 
  943: allow a user to select the domain to preform an operation in.  
  944: See loncreateuser.pm for an example invocation and use.
  945: 
  946: If the $includeempty flag is set, it also includes an empty choice ("no domain
  947: selected");
  948: 
  949: =cut
  950: 
  951: #-------------------------------------------
  952: sub select_dom_form {
  953:     my ($defdom,$name,$includeempty) = @_;
  954:     my @domains = get_domains();
  955:     if ($includeempty) { @domains=('',@domains); }
  956:     my $selectdomain = "<select name=\"$name\" size=\"1\">\n";
  957:     foreach (@domains) {
  958:         $selectdomain.="<option value=\"$_\" ".
  959:             ($_ eq $defdom ? 'selected' : '').
  960:                 ">$_</option>\n";
  961:     }
  962:     $selectdomain.="</select>";
  963:     return $selectdomain;
  964: }
  965: 
  966: #-------------------------------------------
  967: 
  968: =pod
  969: 
  970: =item * get_library_servers($domain)
  971: 
  972: Returns a hash which contains keys like '103l3' and values like 
  973: 'kirk.lite.msu.edu'.  All of the keys will be for machines in the
  974: given $domain.
  975: 
  976: =cut
  977: 
  978: #-------------------------------------------
  979: sub get_library_servers {
  980:     my $domain = shift;
  981:     my %library_servers;
  982:     foreach (keys(%Apache::lonnet::libserv)) {
  983:         if ($Apache::lonnet::hostdom{$_} eq $domain) {
  984:             $library_servers{$_} = $Apache::lonnet::hostname{$_};
  985:         }
  986:     }
  987:     return %library_servers;
  988: }
  989: 
  990: #-------------------------------------------
  991: 
  992: =pod
  993: 
  994: =item * home_server_option_list($domain)
  995: 
  996: returns a string which contains an <option> list to be used in a 
  997: <select> form input.  See loncreateuser.pm for an example.
  998: 
  999: =cut
 1000: 
 1001: #-------------------------------------------
 1002: sub home_server_option_list {
 1003:     my $domain = shift;
 1004:     my %servers = &get_library_servers($domain);
 1005:     my $result = '';
 1006:     foreach (sort keys(%servers)) {
 1007:         $result.=
 1008:             '<option value="'.$_.'">'.$_.' '.$servers{$_}."</option>\n";
 1009:     }
 1010:     return $result;
 1011: }
 1012: 
 1013: =pod
 1014: 
 1015: =back
 1016: 
 1017: =cut
 1018: 
 1019: ###############################################################
 1020: ##                  Decoding User Agent                      ##
 1021: ###############################################################
 1022: 
 1023: =pod
 1024: 
 1025: =head1 Decoding the User Agent
 1026: 
 1027: =over 4
 1028: 
 1029: =item * &decode_user_agent()
 1030: 
 1031: Inputs: $r
 1032: 
 1033: Outputs:
 1034: 
 1035: =over 4
 1036: 
 1037: =item * $httpbrowser
 1038: 
 1039: =item * $clientbrowser
 1040: 
 1041: =item * $clientversion
 1042: 
 1043: =item * $clientmathml
 1044: 
 1045: =item * $clientunicode
 1046: 
 1047: =item * $clientos
 1048: 
 1049: =back
 1050: 
 1051: =back 
 1052: 
 1053: =cut
 1054: 
 1055: ###############################################################
 1056: ###############################################################
 1057: sub decode_user_agent {
 1058:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 1059:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 1060:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 1061:     my $clientbrowser='unknown';
 1062:     my $clientversion='0';
 1063:     my $clientmathml='';
 1064:     my $clientunicode='0';
 1065:     for (my $i=0;$i<=$#browsertype;$i++) {
 1066:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
 1067: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 1068: 	    $clientbrowser=$bname;
 1069:             $httpbrowser=~/$vreg/i;
 1070: 	    $clientversion=$1;
 1071:             $clientmathml=($clientversion>=$minv);
 1072:             $clientunicode=($clientversion>=$univ);
 1073: 	}
 1074:     }
 1075:     my $clientos='unknown';
 1076:     if (($httpbrowser=~/linux/i) ||
 1077:         ($httpbrowser=~/unix/i) ||
 1078:         ($httpbrowser=~/ux/i) ||
 1079:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 1080:     if (($httpbrowser=~/vax/i) ||
 1081:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 1082:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 1083:     if (($httpbrowser=~/mac/i) ||
 1084:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 1085:     if ($httpbrowser=~/win/i) { $clientos='win'; }
 1086:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 1087:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 1088:             $clientunicode,$clientos,);
 1089: }
 1090: 
 1091: ###############################################################
 1092: ##    Authentication changing form generation subroutines    ##
 1093: ###############################################################
 1094: ##
 1095: ## All of the authform_xxxxxxx subroutines take their inputs in a
 1096: ## hash, and have reasonable default values.
 1097: ##
 1098: ##    formname = the name given in the <form> tag.
 1099: #-------------------------------------------
 1100: 
 1101: =pod
 1102: 
 1103: =head1 Authentication Routines
 1104: 
 1105: =over 4
 1106: 
 1107: =item * authform_xxxxxx
 1108: 
 1109: The authform_xxxxxx subroutines provide javascript and html forms which 
 1110: handle some of the conveniences required for authentication forms.  
 1111: This is not an optimal method, but it works.  
 1112: 
 1113: See loncreateuser.pm for invocation and use examples.
 1114: 
 1115: =over 4
 1116: 
 1117: =item * authform_header
 1118: 
 1119: =item * authform_authorwarning
 1120: 
 1121: =item * authform_nochange
 1122: 
 1123: =item * authform_kerberos
 1124: 
 1125: =item * authform_internal
 1126: 
 1127: =item * authform_filesystem
 1128: 
 1129: =back
 1130: 
 1131: =back 
 1132: 
 1133: =cut
 1134: 
 1135: #-------------------------------------------
 1136: sub authform_header{  
 1137:     my %in = (
 1138:         formname => 'cu',
 1139:         kerb_def_dom => '',
 1140:         @_,
 1141:     );
 1142:     $in{'formname'} = 'document.' . $in{'formname'};
 1143:     my $result='';
 1144: 
 1145: #---------------------------------------------- Code for upper case translation
 1146:     my $Javascript_toUpperCase;
 1147:     unless ($in{kerb_def_dom}) {
 1148:         $Javascript_toUpperCase =<<"END";
 1149:         switch (choice) {
 1150:            case 'krb': currentform.elements[choicearg].value =
 1151:                currentform.elements[choicearg].value.toUpperCase();
 1152:                break;
 1153:            default:
 1154:         }
 1155: END
 1156:     } else {
 1157:         $Javascript_toUpperCase = "";
 1158:     }
 1159: 
 1160:     my $radioval = "'nochange'";
 1161:     my $argfield = 'null';
 1162:     if ( grep/^mode$/,(keys %in) ) {
 1163:         if ($in{'mode'} eq 'modifycourse')  {
 1164:             if ( grep/^curr_authtype$/,(keys %in) ) {
 1165:                 $radioval = "'$in{'curr_authtype'}'";
 1166:             }
 1167:             if ( grep/^curr_autharg$/,(keys %in) ) {
 1168:                 unless ($in{'curr_autharg'} eq '') {
 1169:                     $argfield = "'$in{'curr_autharg'}'";
 1170:                 }
 1171:             }
 1172:         }
 1173:     }
 1174: 
 1175:     $result.=<<"END";
 1176: var current = new Object();
 1177: current.radiovalue = $radioval;
 1178: current.argfield = $argfield;
 1179: 
 1180: function changed_radio(choice,currentform) {
 1181:     var choicearg = choice + 'arg';
 1182:     // If a radio button in changed, we need to change the argfield
 1183:     if (current.radiovalue != choice) {
 1184:         current.radiovalue = choice;
 1185:         if (current.argfield != null) {
 1186:             currentform.elements[current.argfield].value = '';
 1187:         }
 1188:         if (choice == 'nochange') {
 1189:             current.argfield = null;
 1190:         } else {
 1191:             current.argfield = choicearg;
 1192:             switch(choice) {
 1193:                 case 'krb': 
 1194:                     currentform.elements[current.argfield].value = 
 1195:                         "$in{'kerb_def_dom'}";
 1196:                 break;
 1197:               default:
 1198:                 break;
 1199:             }
 1200:         }
 1201:     }
 1202:     return;
 1203: }
 1204: 
 1205: function changed_text(choice,currentform) {
 1206:     var choicearg = choice + 'arg';
 1207:     if (currentform.elements[choicearg].value !='') {
 1208:         $Javascript_toUpperCase
 1209:         // clear old field
 1210:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 1211:             currentform.elements[current.argfield].value = '';
 1212:         }
 1213:         current.argfield = choicearg;
 1214:     }
 1215:     set_auth_radio_buttons(choice,currentform);
 1216:     return;
 1217: }
 1218: 
 1219: function set_auth_radio_buttons(newvalue,currentform) {
 1220:     var i=0;
 1221:     while (i < currentform.login.length) {
 1222:         if (currentform.login[i].value == newvalue) { break; }
 1223:         i++;
 1224:     }
 1225:     if (i == currentform.login.length) {
 1226:         return;
 1227:     }
 1228:     current.radiovalue = newvalue;
 1229:     currentform.login[i].checked = true;
 1230:     return;
 1231: }
 1232: END
 1233:     return $result;
 1234: }
 1235: 
 1236: sub authform_authorwarning{
 1237:     my $result='';
 1238:     $result='<i>'.
 1239:         &mt('As a general rule, only authors or co-authors should be '.
 1240:             'filesystem authenticated '.
 1241:             '(which allows access to the server filesystem).')."</i>\n";
 1242:     return $result;
 1243: }
 1244: 
 1245: sub authform_nochange{  
 1246:     my %in = (
 1247:               formname => 'document.cu',
 1248:               kerb_def_dom => 'MSU.EDU',
 1249:               @_,
 1250:           );
 1251:     my $result = &mt('[_1] Do not change login data',
 1252:                      '<input type="radio" name="login" value="nochange" '.
 1253:                      'checked="checked" onclick="'.
 1254:             "javascript:changed_radio('nochange',$in{'formname'});".'" />');
 1255:     return $result;
 1256: }
 1257: 
 1258: sub authform_kerberos{  
 1259:     my %in = (
 1260:               formname => 'document.cu',
 1261:               kerb_def_dom => 'MSU.EDU',
 1262:               kerb_def_auth => 'krb4',
 1263:               @_,
 1264:               );
 1265:     my ($check4,$check5,$krbarg);
 1266:     if ($in{'kerb_def_auth'} eq 'krb5') {
 1267:        $check5 = " checked=\"on\"";
 1268:     } else {
 1269:        $check4 = " checked=\"on\"";
 1270:     }
 1271:     $krbarg = $in{'kerb_def_dom'};
 1272: 
 1273:     my $krbcheck = "";
 1274:     if ( grep/^curr_authtype$/,(keys %in) ) {
 1275:         if ($in{'curr_authtype'} =~ m/^krb/) {
 1276:             $krbcheck = " checked=\"on\"";
 1277:             if ( grep/^curr_autharg$/,(keys %in) ) {
 1278:                 $krbarg = $in{'curr_autharg'};
 1279:             }
 1280:         }
 1281:     }
 1282: 
 1283:     my $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 1284:     my $result .= &mt
 1285:         ('[_1] Kerberos authenticated with domain [_2] '.
 1286:          '[_3] Version 4 [_4] Version 5',
 1287:          '<input type="radio" name="login" value="krb" '.
 1288:              'onclick="'.$jscall.'" onchange="'.$jscall.'"'.$krbcheck.' />',
 1289:          '<input type="text" size="10" name="krbarg" '.
 1290:              'value="'.$krbarg.'" '.
 1291:              'onchange="'.$jscall.'" />',
 1292:          '<input type="radio" name="krbver" value="4" '.$check4.' />',
 1293:          '<input type="radio" name="krbver" value="5" '.$check5.' />');
 1294:     return $result;
 1295: }
 1296: 
 1297: sub authform_internal{  
 1298:     my %args = (
 1299:                 formname => 'document.cu',
 1300:                 kerb_def_dom => 'MSU.EDU',
 1301:                 @_,
 1302:                 );
 1303: 
 1304:     my $intcheck = "";
 1305:     my $intarg = 'value=""';
 1306:     if ( grep/^curr_authtype$/,(keys %args) ) {
 1307:         if ($args{'curr_authtype'} eq 'int') {
 1308:             $intcheck = " checked=\"on\"";
 1309:             if ( grep/^curr_autharg$/,(keys %args) ) {
 1310:                 $intarg = "value=\"$args{'curr_autharg'}\"";
 1311:             }
 1312:         }
 1313:     }
 1314: 
 1315:     my $jscall = "javascript:changed_radio('int',$args{'formname'});";
 1316:     my $result.=&mt
 1317:         ('[_1] Internally authenticated (with initial password [_2])',
 1318:          '<input type="radio" name="login" value="int" '.$intcheck.
 1319:              ' onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 1320:          '<input type="text" size="10" name="intarg" '.$intarg.
 1321:              ' onchange="'.$jscall.'" />');
 1322:     return $result;
 1323: }
 1324: 
 1325: sub authform_local{  
 1326:     my %in = (
 1327:               formname => 'document.cu',
 1328:               kerb_def_dom => 'MSU.EDU',
 1329:               @_,
 1330:               );
 1331: 
 1332:     my $loccheck = "";
 1333:     my $locarg = 'value=""';
 1334:     if ( grep/^curr_authtype$/,(keys %in) ) {
 1335:         if ($in{'curr_authtype'} eq 'loc') {
 1336:             $loccheck = " checked=\"on\"";
 1337:             if ( grep/^curr_autharg$/,(keys %in) ) {
 1338:                 $locarg = "value=\"$in{'curr_autharg'}\"";
 1339:             }
 1340:         }
 1341:     }
 1342: 
 1343:     my $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 1344:     my $result.=&mt('[_1] Local Authentication with argument [_2]',
 1345:                     '<input type="radio" name="login" value="loc" '.$loccheck.
 1346:                         ' onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 1347:                     '<input type="text" size="10" name="locarg" '.$locarg.
 1348:                         ' onchange="'.$jscall.'" />');
 1349:     return $result;
 1350: }
 1351: 
 1352: sub authform_filesystem{  
 1353:     my %in = (
 1354:               formname => 'document.cu',
 1355:               kerb_def_dom => 'MSU.EDU',
 1356:               @_,
 1357:               );
 1358:     my $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 1359:     my $result.= &mt
 1360:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 1361:          '<input type="radio" name="login" value="fsys" '.
 1362:          'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 1363:          '<input type="text" size="10" name="fsysarg" value="" '.
 1364:                   'onchange="'.$jscall.'" />');
 1365:     return $result;
 1366: }
 1367: 
 1368: ###############################################################
 1369: ##    Get Authentication Defaults for Domain                 ##
 1370: ###############################################################
 1371: 
 1372: =pod
 1373: 
 1374: =head1 Domains and Authentication
 1375: 
 1376: Returns default authentication type and an associated argument as
 1377: listed in file 'domain.tab'.
 1378: 
 1379: =over 4
 1380: 
 1381: =item * get_auth_defaults
 1382: 
 1383: get_auth_defaults($target_domain) returns the default authentication
 1384: type and an associated argument (initial password or a kerberos domain).
 1385: These values are stored in lonTabs/domain.tab
 1386: 
 1387: ($def_auth, $def_arg) = &get_auth_defaults($target_domain);
 1388: 
 1389: If target_domain is not found in domain.tab, returns nothing ('').
 1390: 
 1391: =cut
 1392: 
 1393: #-------------------------------------------
 1394: sub get_auth_defaults {
 1395:     my $domain=shift;
 1396:     return ($Apache::lonnet::domain_auth_def{$domain},$Apache::lonnet::domain_auth_arg_def{$domain});
 1397: }
 1398: ###############################################################
 1399: ##   End Get Authentication Defaults for Domain              ##
 1400: ###############################################################
 1401: 
 1402: ###############################################################
 1403: ##    Get Kerberos Defaults for Domain                 ##
 1404: ###############################################################
 1405: ##
 1406: ## Returns default kerberos version and an associated argument
 1407: ## as listed in file domain.tab. If not listed, provides
 1408: ## appropriate default domain and kerberos version.
 1409: ##
 1410: #-------------------------------------------
 1411: 
 1412: =pod
 1413: 
 1414: =item * get_kerberos_defaults
 1415: 
 1416: get_kerberos_defaults($target_domain) returns the default kerberos
 1417: version and domain. If not found in domain.tabs, it defaults to
 1418: version 4 and the domain of the server.
 1419: 
 1420: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 1421: 
 1422: =cut
 1423: 
 1424: #-------------------------------------------
 1425: sub get_kerberos_defaults {
 1426:     my $domain=shift;
 1427:     my ($krbdef,$krbdefdom) =
 1428:         &Apache::loncommon::get_auth_defaults($domain);
 1429:     unless ($krbdef =~/^krb/ && $krbdefdom) {
 1430:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 1431:         my $krbdefdom=$1;
 1432:         $krbdefdom=~tr/a-z/A-Z/;
 1433:         $krbdef = "krb4";
 1434:     }
 1435:     return ($krbdef,$krbdefdom);
 1436: }
 1437: 
 1438: =pod
 1439: 
 1440: =back
 1441: 
 1442: =cut
 1443: 
 1444: ###############################################################
 1445: ##                Thesaurus Functions                        ##
 1446: ###############################################################
 1447: 
 1448: =pod
 1449: 
 1450: =head1 Thesaurus Functions
 1451: 
 1452: =over 4
 1453: 
 1454: =item * initialize_keywords
 1455: 
 1456: Initializes the package variable %Keywords if it is empty.  Uses the
 1457: package variable $thesaurus_db_file.
 1458: 
 1459: =cut
 1460: 
 1461: ###################################################
 1462: 
 1463: sub initialize_keywords {
 1464:     return 1 if (scalar keys(%Keywords));
 1465:     # If we are here, %Keywords is empty, so fill it up
 1466:     #   Make sure the file we need exists...
 1467:     if (! -e $thesaurus_db_file) {
 1468:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 1469:                                  " failed because it does not exist");
 1470:         return 0;
 1471:     }
 1472:     #   Set up the hash as a database
 1473:     my %thesaurus_db;
 1474:     if (! tie(%thesaurus_db,'GDBM_File',
 1475:               $thesaurus_db_file,&GDBM_READER(),0640)){
 1476:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 1477:                                  $thesaurus_db_file);
 1478:         return 0;
 1479:     } 
 1480:     #  Get the average number of appearances of a word.
 1481:     my $avecount = $thesaurus_db{'average.count'};
 1482:     #  Put keywords (those that appear > average) into %Keywords
 1483:     while (my ($word,$data)=each (%thesaurus_db)) {
 1484:         my ($count,undef) = split /:/,$data;
 1485:         $Keywords{$word}++ if ($count > $avecount);
 1486:     }
 1487:     untie %thesaurus_db;
 1488:     # Remove special values from %Keywords.
 1489:     foreach ('total.count','average.count') {
 1490:         delete($Keywords{$_}) if (exists($Keywords{$_}));
 1491:     }
 1492:     return 1;
 1493: }
 1494: 
 1495: ###################################################
 1496: 
 1497: =pod
 1498: 
 1499: =item * keyword($word)
 1500: 
 1501: Returns true if $word is a keyword.  A keyword is a word that appears more 
 1502: than the average number of times in the thesaurus database.  Calls 
 1503: &initialize_keywords
 1504: 
 1505: =cut
 1506: 
 1507: ###################################################
 1508: 
 1509: sub keyword {
 1510:     return if (!&initialize_keywords());
 1511:     my $word=lc(shift());
 1512:     $word=~s/\W//g;
 1513:     return exists($Keywords{$word});
 1514: }
 1515: 
 1516: ###############################################################
 1517: 
 1518: =pod 
 1519: 
 1520: =item * get_related_words
 1521: 
 1522: Look up a word in the thesaurus.  Takes a scalar argument and returns
 1523: an array of words.  If the keyword is not in the thesaurus, an empty array
 1524: will be returned.  The order of the words returned is determined by the
 1525: database which holds them.
 1526: 
 1527: Uses global $thesaurus_db_file.
 1528: 
 1529: =cut
 1530: 
 1531: ###############################################################
 1532: sub get_related_words {
 1533:     my $keyword = shift;
 1534:     my %thesaurus_db;
 1535:     if (! -e $thesaurus_db_file) {
 1536:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 1537:                                  "failed because the file does not exist");
 1538:         return ();
 1539:     }
 1540:     if (! tie(%thesaurus_db,'GDBM_File',
 1541:               $thesaurus_db_file,&GDBM_READER(),0640)){
 1542:         return ();
 1543:     } 
 1544:     my @Words=();
 1545:     if (exists($thesaurus_db{$keyword})) {
 1546:         $_ = $thesaurus_db{$keyword};
 1547:         (undef,@Words) = split/:/;  # The first element is the number of times
 1548:                                     # the word appears.  We do not need it now.
 1549:         for (my $i=0;$i<=$#Words;$i++) {
 1550:             ($Words[$i],undef)= split/\,/,$Words[$i];
 1551:         }
 1552:     }
 1553:     untie %thesaurus_db;
 1554:     return @Words;
 1555: }
 1556: 
 1557: =pod
 1558: 
 1559: =back
 1560: 
 1561: =cut
 1562: 
 1563: # -------------------------------------------------------------- Plaintext name
 1564: =pod
 1565: 
 1566: =head1 User Name Functions
 1567: 
 1568: =over 4
 1569: 
 1570: =item * plainname($uname,$udom)
 1571: 
 1572: Takes a users logon name and returns it as a string in
 1573: "first middle last generation" form
 1574: 
 1575: =cut
 1576: 
 1577: ###############################################################
 1578: sub plainname {
 1579:     my ($uname,$udom)=@_;
 1580:     my %names=&Apache::lonnet::get('environment',
 1581:                     ['firstname','middlename','lastname','generation'],
 1582: 					 $udom,$uname);
 1583:     my $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 1584: 	$names{'lastname'}.' '.$names{'generation'};
 1585:     $name=~s/\s+$//;
 1586:     $name=~s/\s+/ /g;
 1587:     return $name;
 1588: }
 1589: 
 1590: # -------------------------------------------------------------------- Nickname
 1591: =pod
 1592: 
 1593: =item * nickname($uname,$udom)
 1594: 
 1595: Gets a users name and returns it as a string as
 1596: 
 1597: "&quot;nickname&quot;"
 1598: 
 1599: if the user has a nickname or
 1600: 
 1601: "first middle last generation"
 1602: 
 1603: if the user does not
 1604: 
 1605: =cut
 1606: 
 1607: sub nickname {
 1608:     my ($uname,$udom)=@_;
 1609:     my %names=&Apache::lonnet::get('environment',
 1610:   ['nickname','firstname','middlename','lastname','generation'],$udom,$uname);
 1611:     my $name=$names{'nickname'};
 1612:     if ($name) {
 1613:        $name='&quot;'.$name.'&quot;'; 
 1614:     } else {
 1615:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 1616: 	     $names{'lastname'}.' '.$names{'generation'};
 1617:        $name=~s/\s+$//;
 1618:        $name=~s/\s+/ /g;
 1619:     }
 1620:     return $name;
 1621: }
 1622: 
 1623: 
 1624: # ------------------------------------------------------------------ Screenname
 1625: 
 1626: =pod
 1627: 
 1628: =item * screenname($uname,$udom)
 1629: 
 1630: Gets a users screenname and returns it as a string
 1631: 
 1632: =cut
 1633: 
 1634: sub screenname {
 1635:     my ($uname,$udom)=@_;
 1636:     my %names=
 1637:  &Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 1638:     return $names{'screenname'};
 1639: }
 1640: 
 1641: # ------------------------------------------------------------- Message Wrapper
 1642: 
 1643: sub messagewrapper {
 1644:     my ($link,$un,$do)=@_;
 1645:     return 
 1646: "<a href='/adm/email?compose=individual&recname=$un&recdom=$do'>$link</a>";
 1647: }
 1648: # --------------------------------------------------------------- Notes Wrapper
 1649: 
 1650: sub noteswrapper {
 1651:     my ($link,$un,$do)=@_;
 1652:     return 
 1653: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
 1654: }
 1655: # ------------------------------------------------------------- Aboutme Wrapper
 1656: 
 1657: sub aboutmewrapper {
 1658:     my ($link,$username,$domain,$target)=@_;
 1659:     return "<a href='/adm/$domain/$username/aboutme'".
 1660: 	($target?" target='$target'":'').">$link</a>";
 1661: }
 1662: 
 1663: # ------------------------------------------------------------ Syllabus Wrapper
 1664: 
 1665: 
 1666: sub syllabuswrapper {
 1667:     my ($linktext,$coursedir,$domain,$fontcolor)=@_;
 1668:     if ($fontcolor) { 
 1669:         $linktext='<font color="'.$fontcolor.'">'.$linktext.'</font>'; 
 1670:     }
 1671:     return "<a href='/public/$domain/$coursedir/syllabus'>$linktext</a>";
 1672: }
 1673: 
 1674: =pod
 1675: 
 1676: =back
 1677: 
 1678: =head1 Access .tab File Data
 1679: 
 1680: =over 4
 1681: 
 1682: =item * languageids() 
 1683: 
 1684: returns list of all language ids
 1685: 
 1686: =cut
 1687: 
 1688: sub languageids {
 1689:     return sort(keys(%language));
 1690: }
 1691: 
 1692: =pod
 1693: 
 1694: =item * languagedescription() 
 1695: 
 1696: returns description of a specified language id
 1697: 
 1698: =cut
 1699: 
 1700: sub languagedescription {
 1701:     my $code=shift;
 1702:     return  ($supported_language{$code}?'* ':'').
 1703:             $language{$code}.
 1704: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 1705: }
 1706: 
 1707: sub plainlanguagedescription {
 1708:     my $code=shift;
 1709:     return $language{$code};
 1710: }
 1711: 
 1712: sub supportedlanguagecode {
 1713:     my $code=shift;
 1714:     return $supported_language{$code};
 1715: }
 1716: 
 1717: =pod
 1718: 
 1719: =item * copyrightids() 
 1720: 
 1721: returns list of all copyrights
 1722: 
 1723: =cut
 1724: 
 1725: sub copyrightids {
 1726:     return sort(keys(%cprtag));
 1727: }
 1728: 
 1729: =pod
 1730: 
 1731: =item * copyrightdescription() 
 1732: 
 1733: returns description of a specified copyright id
 1734: 
 1735: =cut
 1736: 
 1737: sub copyrightdescription {
 1738:     return &mt($cprtag{shift(@_)});
 1739: }
 1740: 
 1741: =pod
 1742: 
 1743: =item * filecategories() 
 1744: 
 1745: returns list of all file categories
 1746: 
 1747: =cut
 1748: 
 1749: sub filecategories {
 1750:     return sort(keys(%category_extensions));
 1751: }
 1752: 
 1753: =pod
 1754: 
 1755: =item * filecategorytypes() 
 1756: 
 1757: returns list of file types belonging to a given file
 1758: category
 1759: 
 1760: =cut
 1761: 
 1762: sub filecategorytypes {
 1763:     return @{$category_extensions{lc($_[0])}};
 1764: }
 1765: 
 1766: =pod
 1767: 
 1768: =item * fileembstyle() 
 1769: 
 1770: returns embedding style for a specified file type
 1771: 
 1772: =cut
 1773: 
 1774: sub fileembstyle {
 1775:     return $fe{lc(shift(@_))};
 1776: }
 1777: 
 1778: 
 1779: sub filecategoryselect {
 1780:     my ($name,$value)=@_;
 1781:     return &select_form($name,$value,
 1782: 			'' => &mt('Any category'),
 1783: 			map { $_,$_ } sort(keys(%category_extensions)));
 1784: }
 1785: 
 1786: =pod
 1787: 
 1788: =item * filedescription() 
 1789: 
 1790: returns description for a specified file type
 1791: 
 1792: =cut
 1793: 
 1794: sub filedescription {
 1795:     return &mt($fd{lc(shift(@_))});
 1796: }
 1797: 
 1798: =pod
 1799: 
 1800: =item * filedescriptionex() 
 1801: 
 1802: returns description for a specified file type with
 1803: extra formatting
 1804: 
 1805: =cut
 1806: 
 1807: sub filedescriptionex {
 1808:     my $ex=shift;
 1809:     return '.'.$ex.' '.&mt($fd{lc($ex)});
 1810: }
 1811: 
 1812: # End of .tab access
 1813: =pod
 1814: 
 1815: =back
 1816: 
 1817: =cut
 1818: 
 1819: # ------------------------------------------------------------------ File Types
 1820: sub fileextensions {
 1821:     return sort(keys(%fe));
 1822: }
 1823: 
 1824: # ----------------------------------------------------------- Display Languages
 1825: # returns a hash with all desired display languages
 1826: #
 1827: 
 1828: sub display_languages {
 1829:     my %languages=();
 1830:     foreach (&preferred_languages()) {
 1831: 	$languages{$_}=1;
 1832:     }
 1833:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 1834:     if ($ENV{'form.displaylanguage'}) {
 1835: 	foreach (split(/\s*(\,|\;|\:)\s*/,$ENV{'form.displaylanguage'})) {
 1836: 	    $languages{$_}=1;
 1837:         }
 1838:     }
 1839:     return %languages;
 1840: }
 1841: 
 1842: sub preferred_languages {
 1843:     my @languages=();
 1844:     if ($ENV{'environment.languages'}) {
 1845: 	@languages=split(/\s*(\,|\;|\:)\s*/,$ENV{'environment.languages'});
 1846:     }
 1847:     if ($ENV{'course.'.$ENV{'request.course.id'}.'.languages'}) {
 1848: 	@languages=(@languages,split(/\s*(\,|\;|\:)\s*/,
 1849: 	         $ENV{'course.'.$ENV{'request.course.id'}.'.languages'}));
 1850:     }
 1851:     my $browser=(split(/\;/,$ENV{'HTTP_ACCEPT_LANGUAGE'}))[0];
 1852:     if ($browser) {
 1853: 	@languages=(@languages,split(/\s*(\,|\;|\:)\s*/,$browser));
 1854:     }
 1855:     if ($Apache::lonnet::domain_lang_def{$ENV{'user.domain'}}) {
 1856: 	@languages=(@languages,
 1857: 		$Apache::lonnet::domain_lang_def{$ENV{'user.domain'}});
 1858:     }
 1859:     if ($Apache::lonnet::domain_lang_def{$ENV{'request.role.domain'}}) {
 1860: 	@languages=(@languages,
 1861: 		$Apache::lonnet::domain_lang_def{$ENV{'request.role.domain'}});
 1862:     }
 1863:     if ($Apache::lonnet::domain_lang_def{
 1864: 	                          $Apache::lonnet::perlvar{'lonDefDomain'}}) {
 1865: 	@languages=(@languages,
 1866: 		$Apache::lonnet::domain_lang_def{
 1867:                                   $Apache::lonnet::perlvar{'lonDefDomain'}});
 1868:     }
 1869: # turn "en-ca" into "en-ca,en"
 1870:     my @genlanguages;
 1871:     foreach (@languages) {
 1872: 	unless ($_=~/\w/) { next; }
 1873: 	push (@genlanguages,$_);
 1874: 	if ($_=~/(\-|\_)/) {
 1875: 	    push (@genlanguages,(split(/(\-|\_)/,$_))[0]);
 1876: 	}
 1877:     }
 1878:     return @genlanguages;
 1879: }
 1880: 
 1881: ###############################################################
 1882: ##               Student Answer Attempts                     ##
 1883: ###############################################################
 1884: 
 1885: =pod
 1886: 
 1887: =head1 Alternate Problem Views
 1888: 
 1889: =over 4
 1890: 
 1891: =item * get_previous_attempt($symb, $username, $domain, $course,
 1892:     $getattempt, $regexp, $gradesub)
 1893: 
 1894: Return string with previous attempt on problem. Arguments:
 1895: 
 1896: =over 4
 1897: 
 1898: =item * $symb: Problem, including path
 1899: 
 1900: =item * $username: username of the desired student
 1901: 
 1902: =item * $domain: domain of the desired student
 1903: 
 1904: =item * $course: Course ID
 1905: 
 1906: =item * $getattempt: Leave blank for all attempts, otherwise put
 1907:     something
 1908: 
 1909: =item * $regexp: if string matches this regexp, the string will be
 1910:     sent to $gradesub
 1911: 
 1912: =item * $gradesub: routine that processes the string if it matches $regexp
 1913: 
 1914: =back
 1915: 
 1916: The output string is a table containing all desired attempts, if any.
 1917: 
 1918: =cut
 1919: 
 1920: sub get_previous_attempt {
 1921:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
 1922:   my $prevattempts='';
 1923:   no strict 'refs';
 1924:   if ($symb) {
 1925:     my (%returnhash)=
 1926:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 1927:     if ($returnhash{'version'}) {
 1928:       my %lasthash=();
 1929:       my $version;
 1930:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 1931:         foreach (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 1932: 	  $lasthash{$_}=$returnhash{$version.':'.$_};
 1933:         }
 1934:       }
 1935:       $prevattempts='<table border="0" width="100%"><tr><td bgcolor="#777777">';
 1936:       $prevattempts.='<table border="0" width="100%"><tr bgcolor="#e6ffff"><td>History</td>';
 1937:       foreach (sort(keys %lasthash)) {
 1938: 	my ($ign,@parts) = split(/\./,$_);
 1939: 	if ($#parts > 0) {
 1940: 	  my $data=$parts[-1];
 1941: 	  pop(@parts);
 1942: 	  $prevattempts.='<td>Part '.join('.',@parts).'<br />'.$data.'&nbsp;</td>';
 1943: 	} else {
 1944: 	  if ($#parts == 0) {
 1945: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 1946: 	  } else {
 1947: 	    $prevattempts.='<th>'.$ign.'</th>';
 1948: 	  }
 1949: 	}
 1950:       }
 1951:       if ($getattempt eq '') {
 1952: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 1953: 	  $prevattempts.='</tr><tr bgcolor="#ffffe6"><td>Transaction '.$version.'</td>';
 1954: 	    foreach (sort(keys %lasthash)) {
 1955: 	       my $value;
 1956: 	       if ($_ =~ /timestamp/) {
 1957: 		  $value=scalar(localtime($returnhash{$version.':'.$_}));
 1958: 	       } else {
 1959: 		  $value=$returnhash{$version.':'.$_};
 1960: 	       }
 1961: 	       $prevattempts.='<td>'.&Apache::lonnet::unescape($value).'&nbsp;</td>';   
 1962: 	    }
 1963: 	 }
 1964:       }
 1965:       $prevattempts.='</tr><tr bgcolor="#ffffe6"><td>Current</td>';
 1966:       foreach (sort(keys %lasthash)) {
 1967: 	my $value;
 1968: 	if ($_ =~ /timestamp/) {
 1969: 	  $value=scalar(localtime($lasthash{$_}));
 1970: 	} else {
 1971: 	  $value=$lasthash{$_};
 1972: 	}
 1973: 	$value=&Apache::lonnet::unescape($value);
 1974: 	if ($_ =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
 1975: 	$prevattempts.='<td>'.$value.'&nbsp;</td>';
 1976:       }
 1977:       $prevattempts.='</tr></table></td></tr></table>';
 1978:     } else {
 1979:       $prevattempts='Nothing submitted - no attempts.';
 1980:     }
 1981:   } else {
 1982:     $prevattempts='No data.';
 1983:   }
 1984: }
 1985: 
 1986: sub relative_to_absolute {
 1987:     my ($url,$output)=@_;
 1988:     my $parser=HTML::TokeParser->new(\$output);
 1989:     my $token;
 1990:     my $thisdir=$url;
 1991:     my @rlinks=();
 1992:     while ($token=$parser->get_token) {
 1993: 	if ($token->[0] eq 'S') {
 1994: 	    if ($token->[1] eq 'a') {
 1995: 		if ($token->[2]->{'href'}) {
 1996: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 1997: 		}
 1998: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 1999: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 2000: 	    } elsif ($token->[1] eq 'base') {
 2001: 		$thisdir=$token->[2]->{'href'};
 2002: 	    }
 2003: 	}
 2004:     }
 2005:     $thisdir=~s-/[^/]*$--;
 2006:     foreach (@rlinks) {
 2007: 	unless (($_=~/^http:\/\//i) ||
 2008: 		($_=~/^\//) ||
 2009: 		($_=~/^javascript:/i) ||
 2010: 		($_=~/^mailto:/i) ||
 2011: 		($_=~/^\#/)) {
 2012: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$_);
 2013: 	    $output=~s/(\"|\'|\=\s*)$_(\"|\'|\s|\>)/$1$newlocation$2/;
 2014: 	}
 2015:     }
 2016: # -------------------------------------------------- Deal with Applet codebases
 2017:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 2018:     return $output;
 2019: }
 2020: 
 2021: =pod
 2022: 
 2023: =item * get_student_view
 2024: 
 2025: show a snapshot of what student was looking at
 2026: 
 2027: =cut
 2028: 
 2029: sub get_student_view {
 2030:   my ($symb,$username,$domain,$courseid,$target) = @_;
 2031:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 2032:   my (%old,%moreenv);
 2033:   my @elements=('symb','courseid','domain','username');
 2034:   foreach my $element (@elements) {
 2035:     $old{$element}=$ENV{'form.grade_'.$element};
 2036:     $moreenv{'form.grade_'.$element}=eval '$'.$element #'
 2037:   }
 2038:   if ($target eq 'tex') {$moreenv{'form.grade_target'} = 'tex';}
 2039:   &Apache::lonnet::appenv(%moreenv);
 2040:   $feedurl=&Apache::lonnet::clutter($feedurl);
 2041:   my $userview=&Apache::lonnet::ssi_body($feedurl);
 2042:   &Apache::lonnet::delenv('form.grade_');
 2043:   foreach my $element (@elements) {
 2044:     $ENV{'form.grade_'.$element}=$old{$element};
 2045:   }
 2046:   $userview=~s/\<body[^\>]*\>//gi;
 2047:   $userview=~s/\<\/body\>//gi;
 2048:   $userview=~s/\<html\>//gi;
 2049:   $userview=~s/\<\/html\>//gi;
 2050:   $userview=~s/\<head\>//gi;
 2051:   $userview=~s/\<\/head\>//gi;
 2052:   $userview=~s/action\s*\=/would_be_action\=/gi;
 2053:   $userview=&relative_to_absolute($feedurl,$userview);
 2054:   return $userview;
 2055: }
 2056: 
 2057: =pod
 2058: 
 2059: =item * get_student_answers() 
 2060: 
 2061: show a snapshot of how student was answering problem
 2062: 
 2063: =cut
 2064: 
 2065: sub get_student_answers {
 2066:   my ($symb,$username,$domain,$courseid,%form) = @_;
 2067:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 2068:   my (%old,%moreenv);
 2069:   my @elements=('symb','courseid','domain','username');
 2070:   foreach my $element (@elements) {
 2071:     $old{$element}=$ENV{'form.grade_'.$element};
 2072:     $moreenv{'form.grade_'.$element}=eval '$'.$element #'
 2073:   }
 2074:   $moreenv{'form.grade_target'}='answer';
 2075:   &Apache::lonnet::appenv(%moreenv);
 2076:   my $userview=&Apache::lonnet::ssi('/res/'.$feedurl,%form);
 2077:   &Apache::lonnet::delenv('form.grade_');
 2078:   foreach my $element (@elements) {
 2079:     $ENV{'form.grade_'.$element}=$old{$element};
 2080:   }
 2081:   return $userview;
 2082: }
 2083: 
 2084: =pod
 2085: 
 2086: =item * &submlink()
 2087: 
 2088: Inputs: $text $uname $udom $symb
 2089: 
 2090: Returns: A link to grades.pm such as to see the SUBM view of a student
 2091: 
 2092: =cut
 2093: 
 2094: ###############################################
 2095: sub submlink {
 2096:     my ($text,$uname,$udom,$symb)=@_;
 2097:     if (!($uname && $udom)) {
 2098: 	(my $cursymb, my $courseid,$udom,$uname)=
 2099: 	    &Apache::lonxml::whichuser($symb);
 2100: 	if (!$symb) { $symb=$cursymb; }
 2101:     }
 2102:     if (!$symb) { $symb=&symbread(); }
 2103:     return '<a href="/adm/grades?symb='.$symb.'&student='.$uname.
 2104: 	'&userdom='.$udom.'&command=submission">'.$text.'</a>';
 2105: }
 2106: ##############################################
 2107: 
 2108: =pod
 2109: 
 2110: =back
 2111: 
 2112: =cut
 2113: 
 2114: ###############################################
 2115: 
 2116: 
 2117: sub timehash {
 2118:     my @ltime=localtime(shift);
 2119:     return ( 'seconds' => $ltime[0],
 2120:              'minutes' => $ltime[1],
 2121:              'hours'   => $ltime[2],
 2122:              'day'     => $ltime[3],
 2123:              'month'   => $ltime[4]+1,
 2124:              'year'    => $ltime[5]+1900,
 2125:              'weekday' => $ltime[6],
 2126:              'dayyear' => $ltime[7]+1,
 2127:              'dlsav'   => $ltime[8] );
 2128: }
 2129: 
 2130: sub maketime {
 2131:     my %th=@_;
 2132:     return POSIX::mktime(
 2133:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 2134:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,$th{'dlsav'}));
 2135: }
 2136: 
 2137: #########################################
 2138: 
 2139: sub findallcourses {
 2140:     my %courses=();
 2141:     my $now=time;
 2142:     foreach (keys %ENV) {
 2143: 	if ($_=~/^user\.role\.\w+\.\/(\w+)\/(\w+)/) {
 2144: 	    my ($starttime,$endtime)=$ENV{$_};
 2145:             my $active=1;
 2146:             if ($starttime) {
 2147: 		if ($now<$starttime) { $active=0; }
 2148:             }
 2149:             if ($endtime) {
 2150:                 if ($now>$endtime) { $active=0; }
 2151:             }
 2152:             if ($active) { $courses{$1.'_'.$2}=1; }
 2153:         }
 2154:     }
 2155:     return keys %courses;
 2156: }
 2157: 
 2158: ###############################################
 2159: ###############################################
 2160: 
 2161: =pod
 2162: 
 2163: =head1 Domain Template Functions
 2164: 
 2165: =over 4
 2166: 
 2167: =item * &determinedomain()
 2168: 
 2169: Inputs: $domain (usually will be undef)
 2170: 
 2171: Returns: Determines which domain should be used for designs
 2172: 
 2173: =cut
 2174: 
 2175: ###############################################
 2176: sub determinedomain {
 2177:     my $domain=shift;
 2178:    if (! $domain) {
 2179:         # Determine domain if we have not been given one
 2180:         $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
 2181:         if ($ENV{'user.domain'}) { $domain=$ENV{'user.domain'}; }
 2182:         if ($ENV{'request.role.domain'}) { 
 2183:             $domain=$ENV{'request.role.domain'}; 
 2184:         }
 2185:     }
 2186:     return $domain;
 2187: }
 2188: ###############################################
 2189: =pod
 2190: 
 2191: =item * &domainlogo()
 2192: 
 2193: Inputs: $domain (usually will be undef)
 2194: 
 2195: Returns: A link to a domain logo, if the domain logo exists.
 2196: If the domain logo does not exist, a description of the domain.
 2197: 
 2198: =cut
 2199: 
 2200: ###############################################
 2201: sub domainlogo {
 2202:     my $domain = &determinedomain(shift);    
 2203:      # See if there is a logo
 2204:     if (-e '/home/httpd/html/adm/lonDomLogos/'.$domain.'.gif') {
 2205: 	my $lonhttpdPort=$Apache::lonnet::perlvar{'lonhttpdPort'};
 2206: 	if (!defined($lonhttpdPort)) { $lonhttpdPort='8080'; }
 2207:         return '<img src="http://'.$ENV{'HTTP_HOST'}.':'.$lonhttpdPort.
 2208: 	    '/adm/lonDomLogos/'.$domain.'.gif" alt="'.$domain.'" />';
 2209:     } elsif(exists($Apache::lonnet::domaindescription{$domain})) {
 2210:         return $Apache::lonnet::domaindescription{$domain};
 2211:     } else {
 2212:         return '';
 2213:     }
 2214: }
 2215: ##############################################
 2216: 
 2217: =pod
 2218: 
 2219: =item * &designparm()
 2220: 
 2221: Inputs: $which parameter; $domain (usually will be undef)
 2222: 
 2223: Returns: value of designparamter $which
 2224: 
 2225: =cut
 2226: 
 2227: ##############################################
 2228: sub designparm {
 2229:     my ($which,$domain)=@_;
 2230:     if ($ENV{'browser.blackwhite'} eq 'on') {
 2231: 	if ($which=~/\.(font|alink|vlink|link)$/) {
 2232: 	    return '#000000';
 2233: 	}
 2234: 	if ($which=~/\.(pgbg|sidebg)$/) {
 2235: 	    return '#FFFFFF';
 2236: 	}
 2237: 	if ($which=~/\.tabbg$/) {
 2238: 	    return '#CCCCCC';
 2239: 	}
 2240:     }
 2241:     if ($ENV{'environment.color.'.$which}) {
 2242: 	return $ENV{'environment.color.'.$which};
 2243:     }
 2244:     $domain=&determinedomain($domain);
 2245:     if ($designhash{$domain.'.'.$which}) {
 2246: 	return $designhash{$domain.'.'.$which};
 2247:     } else {
 2248:         return $designhash{'default.'.$which};
 2249:     }
 2250: }
 2251: 
 2252: ###############################################
 2253: ###############################################
 2254: 
 2255: =pod
 2256: 
 2257: =back
 2258: 
 2259: =head1 HTTP Helpers
 2260: 
 2261: =over 4
 2262: 
 2263: =item * &bodytag()
 2264: 
 2265: Returns a uniform header for LON-CAPA web pages.
 2266: 
 2267: Inputs: 
 2268: 
 2269: =over 4
 2270: 
 2271: =item * $title, A title to be displayed on the page.
 2272: 
 2273: =item * $function, the current role (can be undef).
 2274: 
 2275: =item * $addentries, extra parameters for the <body> tag.
 2276: 
 2277: =item * $bodyonly, if defined, only return the <body> tag.
 2278: 
 2279: =item * $domain, if defined, force a given domain.
 2280: 
 2281: =item * $forcereg, if page should register as content page (relevant for 
 2282:             text interface only)
 2283: 
 2284: =back
 2285: 
 2286: Returns: A uniform header for LON-CAPA web pages.  
 2287: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 2288: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 2289: other decorations will be returned.
 2290: 
 2291: =cut
 2292: 
 2293: sub bodytag {
 2294:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg)=@_;
 2295:     $title=&mt($title);
 2296:     unless ($function) {
 2297: 	$function='student';
 2298:         if ($ENV{'request.role'}=~/^(cc|in|ta|ep)/) {
 2299: 	    $function='coordinator';
 2300:         }
 2301: 	if ($ENV{'request.role'}=~/^(su|dc|ad|li)/) {
 2302:             $function='admin';
 2303:         }
 2304:         if (($ENV{'request.role'}=~/^(au|ca)/) ||
 2305:             ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
 2306:             $function='author';
 2307:         }
 2308:     }
 2309:     my $img=&designparm($function.'.img',$domain);
 2310:     my $pgbg=&designparm($function.'.pgbg',$domain);
 2311:     my $tabbg=&designparm($function.'.tabbg',$domain);
 2312:     my $font=&designparm($function.'.font',$domain);
 2313:     my $link=&designparm($function.'.link',$domain);
 2314:     my $alink=&designparm($function.'.alink',$domain);
 2315:     my $vlink=&designparm($function.'.vlink',$domain);
 2316:     my $sidebg=&designparm($function.'.sidebg',$domain);
 2317: # Accessibility font enhance
 2318:     unless ($addentries) { $addentries=''; }
 2319:     my $addstyle='';
 2320:     if ($ENV{'browser.fontenhance'} eq 'on') {
 2321: 	$addstyle=' font-size: x-large;';
 2322:     }
 2323:  # role and realm
 2324:     my ($role,$realm)
 2325:        =&Apache::lonnet::plaintext((split(/\./,$ENV{'request.role'}))[0]);
 2326: # realm
 2327:     if ($ENV{'request.course.id'}) {
 2328: 	$realm=
 2329:          $ENV{'course.'.$ENV{'request.course.id'}.'.description'};
 2330:     }
 2331:     unless ($realm) { $realm='&nbsp;'; }
 2332: # Set messages
 2333:     my $messages=&domainlogo($domain);
 2334: # Port for miniserver
 2335:     my $lonhttpdPort=$Apache::lonnet::perlvar{'lonhttpdPort'};
 2336:     if (!defined($lonhttpdPort)) { $lonhttpdPort='8080'; }
 2337: # construct main body tag
 2338:     my $bodytag = <<END;
 2339: <style>
 2340: h1, h2, h3, th { font-family: Arial, Helvetica, sans-serif }
 2341: a:focus { color: red; background: yellow } 
 2342: </style>
 2343: <body bgcolor="$pgbg" text="$font" alink="$alink" vlink="$vlink" link="$link"
 2344: style="margin-top: 0px;$addstyle" $addentries>
 2345: END
 2346:     my $upperleft='<img src="http://'.$ENV{'HTTP_HOST'}.':'.
 2347:                    $lonhttpdPort.$img.'" alt="'.$function.'" />';
 2348:     if ($bodyonly) {
 2349:         return $bodytag;
 2350:     } elsif ($ENV{'browser.interface'} eq 'textual') {
 2351: # Accessibility
 2352:         return $bodytag.&Apache::lonmenu::menubuttons($forcereg,'web',
 2353:                                                       $forcereg).
 2354:                '<h1>LON-CAPA: '.$title.'</h1>';
 2355:     } elsif ($ENV{'environment.remote'} eq 'off') {
 2356: # No Remote
 2357:         return $bodytag.&Apache::lonmenu::menubuttons($forcereg,'web',
 2358:                                                       $forcereg).
 2359:       '<table bgcolor="'.$pgbg.'" width="100%" border="0" cellspacing="3" cellpadding="3"><tr><td bgcolor="'.$tabbg.'"><font face="Arial, Helvetica, sans-serif" size="+3" color="'.$font.'"><b>'.$title.
 2360: '</b></font></td></tr></table>';
 2361:     }
 2362: 
 2363: #
 2364: # Top frame rendering, Remote is up
 2365: #
 2366:     return(<<ENDBODY);
 2367: $bodytag
 2368: <table width="100%" cellspacing="0" border="0" cellpadding="0">
 2369: <tr><td bgcolor="$sidebg">
 2370: $upperleft</td>
 2371: <td bgcolor="$sidebg" align="right">$messages&nbsp;</td>
 2372: </tr>
 2373: <tr>
 2374: <td rowspan="3" bgcolor="$tabbg">
 2375: &nbsp;<font size="5" face="Arial, Helvetica, sans-serif"><b>$title</b></font>
 2376: <td bgcolor="$tabbg" align="right">
 2377: <font size="2" face="Arial, Helvetica, sans-serif">
 2378:     $ENV{'environment.firstname'}
 2379:     $ENV{'environment.middlename'}
 2380:     $ENV{'environment.lastname'}
 2381:     $ENV{'environment.generation'}
 2382:     </font>&nbsp;
 2383: </td>
 2384: </tr>
 2385: <tr><td bgcolor="$tabbg" align="right">
 2386: <font size="2" face="Arial, Helvetica, sans-serif">$role</font>&nbsp;
 2387: </td></tr>
 2388: <tr>
 2389: <td bgcolor="$tabbg" align="right"><font size="2" face="Arial, Helvetica, sans-serif">$realm</font>&nbsp;</td></tr>
 2390: </table><br>
 2391: ENDBODY
 2392: }
 2393: 
 2394: ###############################################
 2395: 
 2396: sub get_posted_cgi {
 2397:     my $r=shift;
 2398: 
 2399:     my $buffer;
 2400:     
 2401:     $r->read($buffer,$r->header_in('Content-length'),0);
 2402:     unless ($buffer=~/^(\-+\w+)\s+Content\-Disposition\:\s*form\-data/si) {
 2403: 	my @pairs=split(/&/,$buffer);
 2404: 	my $pair;
 2405: 	foreach $pair (@pairs) {
 2406: 	    my ($name,$value) = split(/=/,$pair);
 2407: 	    $value =~ tr/+/ /;
 2408: 	    $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 2409: 	    $name  =~ tr/+/ /;
 2410: 	    $name  =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 2411: 	    &add_to_env("form.$name",$value);
 2412: 	}
 2413:     } else {
 2414: 	my $contentsep=$1;
 2415: 	my @lines = split (/\n/,$buffer);
 2416: 	my $name='';
 2417: 	my $value='';
 2418: 	my $fname='';
 2419: 	my $fmime='';
 2420: 	my $i;
 2421: 	for ($i=0;$i<=$#lines;$i++) {
 2422: 	    if ($lines[$i]=~/^$contentsep/) {
 2423: 		if ($name) {
 2424: 		    chomp($value);
 2425: 		    if ($fname) {
 2426: 			$ENV{"form.$name.filename"}=$fname;
 2427: 			$ENV{"form.$name.mimetype"}=$fmime;
 2428: 		    } else {
 2429: 			$value=~s/\s+$//s;
 2430: 		    }
 2431: 		    &add_to_env("form.$name",$value);
 2432: 		}
 2433: 		if ($i<$#lines) {
 2434: 		    $i++;
 2435: 		    $lines[$i]=~
 2436: 		/Content\-Disposition\:\s*form\-data\;\s*name\=\"([^\"]+)\"/i;
 2437: 		    $name=$1;
 2438: 		    $value='';
 2439: 		    if ($lines[$i]=~/filename\=\"([^\"]+)\"/i) {
 2440: 			$fname=$1;
 2441: 			if 
 2442:                             ($lines[$i+1]=~/Content\-Type\:\s*([\w\-\/]+)/i) {
 2443: 				$fmime=$1;
 2444: 				$i++;
 2445: 			    } else {
 2446: 				$fmime='';
 2447: 			    }
 2448: 		    } else {
 2449: 			$fname='';
 2450: 			$fmime='';
 2451: 		    }
 2452: 		    $i++;
 2453: 		}
 2454: 	    } else {
 2455: 		$value.=$lines[$i]."\n";
 2456: 	    }
 2457: 	}
 2458:     }
 2459:     $ENV{'request.method'}=$ENV{'REQUEST_METHOD'};
 2460:     $r->method_number(M_GET);
 2461:     $r->method('GET');
 2462:     $r->headers_in->unset('Content-length');
 2463: }
 2464: 
 2465: =pod
 2466: 
 2467: =item * get_unprocessed_cgi($query,$possible_names)
 2468: 
 2469: Modify the %ENV hash to contain unprocessed CGI form parameters held in
 2470: $query.  The parameters listed in $possible_names (an array reference),
 2471: will be set in $ENV{'form.name'} if they do not already exist.
 2472: 
 2473: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
 2474: $possible_names is an ref to an array of form element names.  As an example:
 2475: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
 2476: will result in $ENV{'form.uname'} and $ENV{'form.udom'} being set.
 2477: 
 2478: =cut
 2479: 
 2480: sub get_unprocessed_cgi {
 2481:   my ($query,$possible_names)= @_;
 2482:   # $Apache::lonxml::debug=1;
 2483:   foreach (split(/&/,$query)) {
 2484:     my ($name, $value) = split(/=/,$_);
 2485:     $name = &Apache::lonnet::unescape($name);
 2486:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
 2487:       $value =~ tr/+/ /;
 2488:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 2489:       &Apache::lonxml::debug("Seting :$name: to :$value:");
 2490:       unless (defined($ENV{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
 2491:     }
 2492:   }
 2493: }
 2494: 
 2495: =pod
 2496: 
 2497: =item * cacheheader() 
 2498: 
 2499: returns cache-controlling header code
 2500: 
 2501: =cut
 2502: 
 2503: sub cacheheader {
 2504:   unless ($ENV{'request.method'} eq 'GET') { return ''; }
 2505:   my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 2506:   my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
 2507:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
 2508:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
 2509:   return $output;
 2510: }
 2511: 
 2512: =pod
 2513: 
 2514: =item * no_cache($r) 
 2515: 
 2516: specifies header code to not have cache
 2517: 
 2518: =cut
 2519: 
 2520: sub no_cache {
 2521:   my ($r) = @_;
 2522:   unless ($ENV{'request.method'} eq 'GET') { return ''; }
 2523:   #my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 2524:   $r->no_cache(1);
 2525:   $r->header_out("Pragma" => "no-cache");
 2526:   #$r->header_out("Expires" => $date);
 2527: }
 2528: 
 2529: sub content_type {
 2530:   my ($r,$type,$charset) = @_;
 2531:   unless ($charset) {
 2532:       $charset=&Apache::lonlocal::current_encoding;
 2533:   }
 2534:   $r->content_type($type.($charset?'; charset='.$charset:''));
 2535: }
 2536: 
 2537: =pod
 2538: 
 2539: =item * add_to_env($name,$value) 
 2540: 
 2541: adds $name to the %ENV hash with value
 2542: $value, if $name already exists, the entry is converted to an array
 2543: reference and $value is added to the array.
 2544: 
 2545: =cut
 2546: 
 2547: sub add_to_env {
 2548:   my ($name,$value)=@_;
 2549:   if (defined($ENV{$name})) {
 2550:     if (ref($ENV{$name})) {
 2551:       #already have multiple values
 2552:       push(@{ $ENV{$name} },$value);
 2553:     } else {
 2554:       #first time seeing multiple values, convert hash entry to an arrayref
 2555:       my $first=$ENV{$name};
 2556:       undef($ENV{$name});
 2557:       push(@{ $ENV{$name} },$first,$value);
 2558:     }
 2559:   } else {
 2560:     $ENV{$name}=$value;
 2561:   }
 2562: }
 2563: 
 2564: =pod
 2565: 
 2566: =item * get_env_multiple($name) 
 2567: 
 2568: gets $name from the %ENV hash, it seemlessly handles the cases where multiple
 2569: values may be defined and end up as an array ref.
 2570: 
 2571: returns an array of values
 2572: 
 2573: =cut
 2574: 
 2575: sub get_env_multiple {
 2576:     my ($name) = @_;
 2577:     my @values;
 2578:     if (defined($ENV{$name})) {
 2579:         # exists is it an array
 2580:         if (ref($ENV{$name})) {
 2581:             @values=@{ $ENV{$name} };
 2582:         } else {
 2583:             $values[0]=$ENV{$name};
 2584:         }
 2585:     }
 2586:     return(@values);
 2587: }
 2588: 
 2589: 
 2590: =pod
 2591: 
 2592: =back 
 2593: 
 2594: =head1 CSV Upload/Handling functions
 2595: 
 2596: =over 4
 2597: 
 2598: =item * upfile_store($r)
 2599: 
 2600: Store uploaded file, $r should be the HTTP Request object,
 2601: needs $ENV{'form.upfile'}
 2602: returns $datatoken to be put into hidden field
 2603: 
 2604: =cut
 2605: 
 2606: sub upfile_store {
 2607:     my $r=shift;
 2608:     $ENV{'form.upfile'}=~s/\r/\n/gs;
 2609:     $ENV{'form.upfile'}=~s/\f/\n/gs;
 2610:     $ENV{'form.upfile'}=~s/\n+/\n/gs;
 2611:     $ENV{'form.upfile'}=~s/\n+$//gs;
 2612: 
 2613:     my $datatoken=$ENV{'user.name'}.'_'.$ENV{'user.domain'}.
 2614: 	'_enroll_'.$ENV{'request.course.id'}.'_'.time.'_'.$$;
 2615:     {
 2616:         my $datafile = $r->dir_config('lonDaemons').
 2617:                            '/tmp/'.$datatoken.'.tmp';
 2618:         if ( open(my $fh,">$datafile") ) {
 2619:             print $fh $ENV{'form.upfile'};
 2620:             close($fh);
 2621:         }
 2622:     }
 2623:     return $datatoken;
 2624: }
 2625: 
 2626: =pod
 2627: 
 2628: =item * load_tmp_file($r)
 2629: 
 2630: Load uploaded file from tmp, $r should be the HTTP Request object,
 2631: needs $ENV{'form.datatoken'},
 2632: sets $ENV{'form.upfile'} to the contents of the file
 2633: 
 2634: =cut
 2635: 
 2636: sub load_tmp_file {
 2637:     my $r=shift;
 2638:     my @studentdata=();
 2639:     {
 2640:         my $studentfile = $r->dir_config('lonDaemons').
 2641:                               '/tmp/'.$ENV{'form.datatoken'}.'.tmp';
 2642:         if ( open(my $fh,"<$studentfile") ) {
 2643:             @studentdata=<$fh>;
 2644:             close($fh);
 2645:         }
 2646:     }
 2647:     $ENV{'form.upfile'}=join('',@studentdata);
 2648: }
 2649: 
 2650: =pod
 2651: 
 2652: =item * upfile_record_sep()
 2653: 
 2654: Separate uploaded file into records
 2655: returns array of records,
 2656: needs $ENV{'form.upfile'} and $ENV{'form.upfiletype'}
 2657: 
 2658: =cut
 2659: 
 2660: sub upfile_record_sep {
 2661:     if ($ENV{'form.upfiletype'} eq 'xml') {
 2662:     } else {
 2663: 	return split(/\n/,$ENV{'form.upfile'});
 2664:     }
 2665: }
 2666: 
 2667: =pod
 2668: 
 2669: =item * record_sep($record)
 2670: 
 2671: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $ENV{'form.upfiletype'}
 2672: 
 2673: =cut
 2674: 
 2675: sub record_sep {
 2676:     my $record=shift;
 2677:     my %components=();
 2678:     if ($ENV{'form.upfiletype'} eq 'xml') {
 2679:     } elsif ($ENV{'form.upfiletype'} eq 'space') {
 2680:         my $i=0;
 2681:         foreach (split(/\s+/,$record)) {
 2682:             my $field=$_;
 2683:             $field=~s/^(\"|\')//;
 2684:             $field=~s/(\"|\')$//;
 2685:             $components{$i}=$field;
 2686:             $i++;
 2687:         }
 2688:     } elsif ($ENV{'form.upfiletype'} eq 'tab') {
 2689:         my $i=0;
 2690:         foreach (split(/\t/,$record)) {
 2691:             my $field=$_;
 2692:             $field=~s/^(\"|\')//;
 2693:             $field=~s/(\"|\')$//;
 2694:             $components{$i}=$field;
 2695:             $i++;
 2696:         }
 2697:     } else {
 2698:         my @allfields=split(/\,/,$record);
 2699:         my $i=0;
 2700:         my $j;
 2701:         for ($j=0;$j<=$#allfields;$j++) {
 2702:             my $field=$allfields[$j];
 2703:             if ($field=~/^\s*(\"|\')/) {
 2704: 		my $delimiter=$1;
 2705:                 while (($field!~/$delimiter$/) && ($j<$#allfields)) {
 2706: 		    $j++;
 2707: 		    $field.=','.$allfields[$j];
 2708: 		}
 2709:                 $field=~s/^\s*$delimiter//;
 2710:                 $field=~s/$delimiter\s*$//;
 2711:             }
 2712:             $components{$i}=$field;
 2713: 	    $i++;
 2714:         }
 2715:     }
 2716:     return %components;
 2717: }
 2718: 
 2719: ######################################################
 2720: ######################################################
 2721: 
 2722: =pod
 2723: 
 2724: =item * upfile_select_html()
 2725: 
 2726: Return HTML code to select a file from the users machine and specify 
 2727: the file type.
 2728: 
 2729: =cut
 2730: 
 2731: ######################################################
 2732: ######################################################
 2733: sub upfile_select_html {
 2734:     my %Types = (
 2735:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
 2736:                  space => &mt('Space separated'),
 2737:                  tab   => &mt('Tabulator separated'),
 2738: #                 xml   => &mt('HTML/XML'),
 2739:                  );
 2740:     my $Str = '<input type="file" name="upfile" size="50" />'.
 2741:         '<br />Type: <select name="upfiletype">';
 2742:     foreach my $type (sort(keys(%Types))) {
 2743:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
 2744:     }
 2745:     $Str .= "</select>\n";
 2746:     return $Str;
 2747: }
 2748: 
 2749: ######################################################
 2750: ######################################################
 2751: 
 2752: =pod
 2753: 
 2754: =item * csv_print_samples($r,$records)
 2755: 
 2756: Prints a table of sample values from each column uploaded $r is an
 2757: Apache Request ref, $records is an arrayref from
 2758: &Apache::loncommon::upfile_record_sep
 2759: 
 2760: =cut
 2761: 
 2762: ######################################################
 2763: ######################################################
 2764: sub csv_print_samples {
 2765:     my ($r,$records) = @_;
 2766:     my (%sone,%stwo,%sthree);
 2767:     %sone=&record_sep($$records[0]);
 2768:     if (defined($$records[1])) {%stwo=&record_sep($$records[1]);}
 2769:     if (defined($$records[2])) {%sthree=&record_sep($$records[2]);}
 2770:     #
 2771:     $r->print(&mt('Samples').'<br /><table border="2"><tr>');
 2772:     foreach (sort({$a <=> $b} keys(%sone))) { 
 2773:         $r->print('<th>'.&mt('Column&nbsp;[_1]',($_+1)).'</th>'); }
 2774:     $r->print('</tr>');
 2775:     foreach my $hash (\%sone,\%stwo,\%sthree) {
 2776: 	$r->print('<tr>');
 2777: 	foreach (sort({$a <=> $b} keys(%sone))) {
 2778: 	    $r->print('<td>');
 2779: 	    if (defined($$hash{$_})) { $r->print($$hash{$_}); }
 2780: 	    $r->print('</td>');
 2781: 	}
 2782: 	$r->print('</tr>');
 2783:     }
 2784:     $r->print('</tr></table><br />'."\n");
 2785: }
 2786: 
 2787: ######################################################
 2788: ######################################################
 2789: 
 2790: =pod
 2791: 
 2792: =item * csv_print_select_table($r,$records,$d)
 2793: 
 2794: Prints a table to create associations between values and table columns.
 2795: 
 2796: $r is an Apache Request ref,
 2797: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 2798: $d is an array of 2 element arrays (internal name, displayed name)
 2799: 
 2800: =cut
 2801: 
 2802: ######################################################
 2803: ######################################################
 2804: sub csv_print_select_table {
 2805:     my ($r,$records,$d) = @_;
 2806:     my $i=0;my %sone;
 2807:     %sone=&record_sep($$records[0]);
 2808:     $r->print(&mt('Associate columns with student attributes.')."\n".
 2809: 	     '<table border="2"><tr>'.
 2810:               '<th>'.&mt('Attribute').'</th>'.
 2811:               '<th>'.&mt('Column').'</th></tr>'."\n");
 2812:     foreach (@$d) {
 2813: 	my ($value,$display)=@{ $_ };
 2814: 	$r->print('<tr><td>'.$display.'</td>');
 2815: 
 2816: 	$r->print('<td><select name=f'.$i.
 2817: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 2818: 	$r->print('<option value="none"></option>');
 2819: 	foreach (sort({$a <=> $b} keys(%sone))) {
 2820: 	    $r->print('<option value="'.$_.'">Column '.($_+1).'</option>');
 2821: 	}
 2822: 	$r->print('</select></td></tr>'."\n");
 2823: 	$i++;
 2824:     }
 2825:     $i--;
 2826:     return $i;
 2827: }
 2828: 
 2829: ######################################################
 2830: ######################################################
 2831: 
 2832: =pod
 2833: 
 2834: =item * csv_samples_select_table($r,$records,$d)
 2835: 
 2836: Prints a table of sample values from the upload and can make associate samples to internal names.
 2837: 
 2838: $r is an Apache Request ref,
 2839: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 2840: $d is an array of 2 element arrays (internal name, displayed name)
 2841: 
 2842: =cut
 2843: 
 2844: ######################################################
 2845: ######################################################
 2846: sub csv_samples_select_table {
 2847:     my ($r,$records,$d) = @_;
 2848:     my %sone; my %stwo; my %sthree;
 2849:     my $i=0;
 2850:     #
 2851:     $r->print('<table border=2><tr><th>'.
 2852:               &mt('Field').'</th><th>'.&mt('Samples').'</th></tr>');
 2853:     %sone=&record_sep($$records[0]);
 2854:     if (defined($$records[1])) {%stwo=&record_sep($$records[1]);}
 2855:     if (defined($$records[2])) {%sthree=&record_sep($$records[2]);}
 2856:     #
 2857:     foreach (sort keys %sone) {
 2858: 	$r->print('<tr><td><select name="f'.$i.'"'.
 2859: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 2860: 	foreach (@$d) {
 2861: 	    my ($value,$display)=@{ $_ };
 2862: 	    $r->print('<option value="'.$value.'">'.$display.'</option>');
 2863: 	}
 2864: 	$r->print('</select></td><td>');
 2865: 	if (defined($sone{$_})) { $r->print($sone{$_}."</br>\n"); }
 2866: 	if (defined($stwo{$_})) { $r->print($stwo{$_}."</br>\n"); }
 2867: 	if (defined($sthree{$_})) { $r->print($sthree{$_}."</br>\n"); }
 2868: 	$r->print('</td></tr>');
 2869: 	$i++;
 2870:     }
 2871:     $i--;
 2872:     return($i);
 2873: }
 2874: 
 2875: ######################################################
 2876: ######################################################
 2877: 
 2878: =pod
 2879: 
 2880: =item clean_excel_name($name)
 2881: 
 2882: Returns a replacement for $name which does not contain any illegal characters.
 2883: 
 2884: =cut
 2885: 
 2886: ######################################################
 2887: ######################################################
 2888: sub clean_excel_name {
 2889:     my ($name) = @_;
 2890:     $name =~ s/[:\*\?\/\\]//g;
 2891:     if (length($name) > 31) {
 2892:         $name = substr($name,0,31);
 2893:     }
 2894:     return $name;
 2895: }
 2896: 
 2897: =pod
 2898: 
 2899: =item * check_if_partid_hidden($id,$symb,$udom,$uname)
 2900: 
 2901: Returns either 1 or undef
 2902: 
 2903: 1 if the part is to be hidden, undef if it is to be shown
 2904: 
 2905: Arguments are:
 2906: 
 2907: $id the id of the part to be checked
 2908: $symb, optional the symb of the resource to check
 2909: $udom, optional the domain of the user to check for
 2910: $uname, optional the username of the user to check for
 2911: 
 2912: =cut
 2913: 
 2914: sub check_if_partid_hidden {
 2915:     my ($id,$symb,$udom,$uname) = @_;
 2916:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
 2917: 					 $symb,$udom,$uname);
 2918:     my $truth=1;
 2919:     #if the string starts with !, then the list is the list to show not hide
 2920:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
 2921:     my @hiddenlist=split(/,/,$hiddenparts);
 2922:     foreach my $checkid (@hiddenlist) {
 2923: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
 2924:     }
 2925:     return !$truth;
 2926: }
 2927: 
 2928: 
 2929: ############################################################
 2930: ############################################################
 2931: 
 2932: =pod
 2933: 
 2934: =back 
 2935: 
 2936: =head1 cgi-bin script and graphing routines
 2937: 
 2938: =over 4
 2939: 
 2940: =item get_cgi_id
 2941: 
 2942: Inputs: none
 2943: 
 2944: Returns an id which can be used to pass environment variables
 2945: to various cgi-bin scripts.  These environment variables will
 2946: be removed from the users environment after a given time by
 2947: the routine &Apache::lonnet::transfer_profile_to_env.
 2948: 
 2949: =cut
 2950: 
 2951: ############################################################
 2952: ############################################################
 2953: my $uniq=0;
 2954: sub get_cgi_id {
 2955:     $uniq=($uniq+1)%100000;
 2956:     return (time.'_'.$uniq);
 2957: }
 2958: 
 2959: ############################################################
 2960: ############################################################
 2961: 
 2962: =pod
 2963: 
 2964: =item DrawBarGraph
 2965: 
 2966: Facilitates the plotting of data in a (stacked) bar graph.
 2967: Puts plot definition data into the users environment in order for 
 2968: graph.png to plot it.  Returns an <img> tag for the plot.
 2969: The bars on the plot are labeled '1','2',...,'n'.
 2970: 
 2971: Inputs:
 2972: 
 2973: =over 4
 2974: 
 2975: =item $Title: string, the title of the plot
 2976: 
 2977: =item $xlabel: string, text describing the X-axis of the plot
 2978: 
 2979: =item $ylabel: string, text describing the Y-axis of the plot
 2980: 
 2981: =item $Max: scalar, the maximum Y value to use in the plot
 2982: If $Max is < any data point, the graph will not be rendered.
 2983: 
 2984: =item $colors: array ref holding the colors to be used for the data sets when
 2985: they are plotted.  If undefined, default values will be used.
 2986: 
 2987: =item @Values: An array of array references.  Each array reference holds data
 2988: to be plotted in a stacked bar chart.
 2989: 
 2990: =back
 2991: 
 2992: Returns:
 2993: 
 2994: An <img> tag which references graph.png and the appropriate identifying
 2995: information for the plot.
 2996: 
 2997: =cut
 2998: 
 2999: ############################################################
 3000: ############################################################
 3001: sub DrawBarGraph {
 3002:     my ($Title,$xlabel,$ylabel,$Max,$colors,@Values)=@_;
 3003:     #
 3004:     if (! defined($colors)) {
 3005:         $colors = ['#33ff00', 
 3006:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
 3007:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
 3008:                   ]; 
 3009:     }
 3010:     #
 3011:     my $identifier = &get_cgi_id();
 3012:     my $id = 'cgi.'.$identifier;        
 3013:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
 3014:         return '';
 3015:     }
 3016:     my $NumBars = scalar(@{$Values[0]});
 3017:     my %ValuesHash;
 3018:     my $NumSets=1;
 3019:     foreach my $array (@Values) {
 3020:         next if (! ref($array));
 3021:         $ValuesHash{$id.'.data.'.$NumSets++} = 
 3022:             join(',',@$array);
 3023:     }
 3024:     #
 3025:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
 3026:     if ($NumBars < 10) {
 3027:         $width = 120+$NumBars*15;
 3028:         $xskip = 1;
 3029:         $bar_width = 15;
 3030:     } elsif ($NumBars <= 25) {
 3031:         $width = 120+$NumBars*11;
 3032:         $xskip = 5;
 3033:         $bar_width = 8;
 3034:     } elsif ($NumBars <= 50) {
 3035:         $width = 120+$NumBars*8;
 3036:         $xskip = 5;
 3037:         $bar_width = 4;
 3038:     } else {
 3039:         $width = 120+$NumBars*8;
 3040:         $xskip = 5;
 3041:         $bar_width = 4;
 3042:     }
 3043:     #
 3044:     my @Labels;
 3045:     for (my $i=0;$i<@{$Values[0]};$i++) {
 3046:         push (@Labels,$i+1);
 3047:     }
 3048:     #
 3049:     $Max = 1 if ($Max < 1);
 3050:     if ( int($Max) < $Max ) {
 3051:         $Max++;
 3052:         $Max = int($Max);
 3053:     }
 3054:     $Title  = '' if (! defined($Title));
 3055:     $xlabel = '' if (! defined($xlabel));
 3056:     $ylabel = '' if (! defined($ylabel));
 3057:     $ValuesHash{$id.'.title'}    = &Apache::lonnet::escape($Title);
 3058:     $ValuesHash{$id.'.xlabel'}   = &Apache::lonnet::escape($xlabel);
 3059:     $ValuesHash{$id.'.ylabel'}   = &Apache::lonnet::escape($ylabel);
 3060:     $ValuesHash{$id.'.y_max_value'} = $Max;
 3061:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
 3062:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
 3063:     $ValuesHash{$id.'.PlotType'} = 'bar';
 3064:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 3065:     $ValuesHash{$id.'.height'}   = $height;
 3066:     $ValuesHash{$id.'.width'}    = $width;
 3067:     $ValuesHash{$id.'.xskip'}    = $xskip;
 3068:     $ValuesHash{$id.'.bar_width'} = $bar_width;
 3069:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
 3070:     #
 3071:     &Apache::lonnet::appenv(%ValuesHash);
 3072:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 3073: }
 3074: 
 3075: ############################################################
 3076: ############################################################
 3077: 
 3078: =pod
 3079: 
 3080: =item DrawXYGraph
 3081: 
 3082: Facilitates the plotting of data in an XY graph.
 3083: Puts plot definition data into the users environment in order for 
 3084: graph.png to plot it.  Returns an <img> tag for the plot.
 3085: 
 3086: Inputs:
 3087: 
 3088: =over 4
 3089: 
 3090: =item $Title: string, the title of the plot
 3091: 
 3092: =item $xlabel: string, text describing the X-axis of the plot
 3093: 
 3094: =item $ylabel: string, text describing the Y-axis of the plot
 3095: 
 3096: =item $Max: scalar, the maximum Y value to use in the plot
 3097: If $Max is < any data point, the graph will not be rendered.
 3098: 
 3099: =item $colors: Array ref containing the hex color codes for the data to be 
 3100: plotted in.  If undefined, default values will be used.
 3101: 
 3102: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 3103: 
 3104: =item $Ydata: Array ref containing Array refs.  
 3105: Each of the contained arrays will be plotted as a seperate curve.
 3106: 
 3107: =item %Values: hash indicating or overriding any default values which are 
 3108: passed to graph.png.  
 3109: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 3110: 
 3111: =back
 3112: 
 3113: Returns:
 3114: 
 3115: An <img> tag which references graph.png and the appropriate identifying
 3116: information for the plot.
 3117: 
 3118: =cut
 3119: 
 3120: ############################################################
 3121: ############################################################
 3122: sub DrawXYGraph {
 3123:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
 3124:     #
 3125:     # Create the identifier for the graph
 3126:     my $identifier = &get_cgi_id();
 3127:     my $id = 'cgi.'.$identifier;
 3128:     #
 3129:     $Title  = '' if (! defined($Title));
 3130:     $xlabel = '' if (! defined($xlabel));
 3131:     $ylabel = '' if (! defined($ylabel));
 3132:     my %ValuesHash = 
 3133:         (
 3134:          $id.'.title'  => &Apache::lonnet::escape($Title),
 3135:          $id.'.xlabel' => &Apache::lonnet::escape($xlabel),
 3136:          $id.'.ylabel' => &Apache::lonnet::escape($ylabel),
 3137:          $id.'.y_max_value'=> $Max,
 3138:          $id.'.labels'     => join(',',@$Xlabels),
 3139:          $id.'.PlotType'   => 'XY',
 3140:          );
 3141:     #
 3142:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 3143:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 3144:     }
 3145:     #
 3146:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
 3147:         return '';
 3148:     }
 3149:     my $NumSets=1;
 3150:     foreach my $array (@{$Ydata}){
 3151:         next if (! ref($array));
 3152:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 3153:     }
 3154:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
 3155:     #
 3156:     # Deal with other parameters
 3157:     while (my ($key,$value) = each(%Values)) {
 3158:         $ValuesHash{$id.'.'.$key} = $value;
 3159:     }
 3160:     #
 3161:     &Apache::lonnet::appenv(%ValuesHash);
 3162:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 3163: }
 3164: 
 3165: ############################################################
 3166: ############################################################
 3167: 
 3168: =pod
 3169: 
 3170: =item DrawXYYGraph
 3171: 
 3172: Facilitates the plotting of data in an XY graph with two Y axes.
 3173: Puts plot definition data into the users environment in order for 
 3174: graph.png to plot it.  Returns an <img> tag for the plot.
 3175: 
 3176: Inputs:
 3177: 
 3178: =over 4
 3179: 
 3180: =item $Title: string, the title of the plot
 3181: 
 3182: =item $xlabel: string, text describing the X-axis of the plot
 3183: 
 3184: =item $ylabel: string, text describing the Y-axis of the plot
 3185: 
 3186: =item $colors: Array ref containing the hex color codes for the data to be 
 3187: plotted in.  If undefined, default values will be used.
 3188: 
 3189: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 3190: 
 3191: =item $Ydata1: The first data set
 3192: 
 3193: =item $Min1: The minimum value of the left Y-axis
 3194: 
 3195: =item $Max1: The maximum value of the left Y-axis
 3196: 
 3197: =item $Ydata2: The second data set
 3198: 
 3199: =item $Min2: The minimum value of the right Y-axis
 3200: 
 3201: =item $Max2: The maximum value of the left Y-axis
 3202: 
 3203: =item %Values: hash indicating or overriding any default values which are 
 3204: passed to graph.png.  
 3205: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 3206: 
 3207: =back
 3208: 
 3209: Returns:
 3210: 
 3211: An <img> tag which references graph.png and the appropriate identifying
 3212: information for the plot.
 3213: 
 3214: =cut
 3215: 
 3216: ############################################################
 3217: ############################################################
 3218: sub DrawXYYGraph {
 3219:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
 3220:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
 3221:     #
 3222:     # Create the identifier for the graph
 3223:     my $identifier = &get_cgi_id();
 3224:     my $id = 'cgi.'.$identifier;
 3225:     #
 3226:     $Title  = '' if (! defined($Title));
 3227:     $xlabel = '' if (! defined($xlabel));
 3228:     $ylabel = '' if (! defined($ylabel));
 3229:     my %ValuesHash = 
 3230:         (
 3231:          $id.'.title'  => &Apache::lonnet::escape($Title),
 3232:          $id.'.xlabel' => &Apache::lonnet::escape($xlabel),
 3233:          $id.'.ylabel' => &Apache::lonnet::escape($ylabel),
 3234:          $id.'.labels' => join(',',@$Xlabels),
 3235:          $id.'.PlotType' => 'XY',
 3236:          $id.'.NumSets' => 2,
 3237:          $id.'.two_axes' => 1,
 3238:          $id.'.y1_max_value' => $Max1,
 3239:          $id.'.y1_min_value' => $Min1,
 3240:          $id.'.y2_max_value' => $Max2,
 3241:          $id.'.y2_min_value' => $Min2,
 3242:          );
 3243:     #
 3244:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 3245:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 3246:     }
 3247:     #
 3248:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
 3249:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
 3250:         return '';
 3251:     }
 3252:     my $NumSets=1;
 3253:     foreach my $array ($Ydata1,$Ydata2){
 3254:         next if (! ref($array));
 3255:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 3256:     }
 3257:     #
 3258:     # Deal with other parameters
 3259:     while (my ($key,$value) = each(%Values)) {
 3260:         $ValuesHash{$id.'.'.$key} = $value;
 3261:     }
 3262:     #
 3263:     &Apache::lonnet::appenv(%ValuesHash);
 3264:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 3265: }
 3266: 
 3267: ############################################################
 3268: ############################################################
 3269: 
 3270: =pod
 3271: 
 3272: =back 
 3273: 
 3274: =head1 Statistics helper routines?  
 3275: 
 3276: Bad place for them but what the hell.
 3277: 
 3278: =over 4
 3279: 
 3280: =item &chartlink
 3281: 
 3282: Returns a link to the chart for a specific student.  
 3283: 
 3284: Inputs:
 3285: 
 3286: =over 4
 3287: 
 3288: =item $linktext: The text of the link
 3289: 
 3290: =item $sname: The students username
 3291: 
 3292: =item $sdomain: The students domain
 3293: 
 3294: =back
 3295: 
 3296: =back
 3297: 
 3298: =cut
 3299: 
 3300: ############################################################
 3301: ############################################################
 3302: sub chartlink {
 3303:     my ($linktext, $sname, $sdomain) = @_;
 3304:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
 3305:         '&SelectedStudent='.&Apache::lonnet::escape($sname.':'.$sdomain).
 3306:         '&chartoutputmode='.HTML::Entities::encode('html, with all links').
 3307:        '">'.$linktext.'</a>';
 3308: }
 3309: 
 3310: #######################################################
 3311: #######################################################
 3312: 
 3313: =pod
 3314: 
 3315: =head1 Course Environment Routines
 3316: 
 3317: =over 4
 3318: 
 3319: =item &restore_course_settings 
 3320: 
 3321: =item &store_course_settings
 3322: 
 3323: Restores/Store indicated form parameters from the course environment.
 3324: Will not overwrite existing values of the form parameters.
 3325: 
 3326: Inputs: 
 3327: a scalar describing the data (e.g. 'chart', 'problem_analysis')
 3328: 
 3329: a hash ref describing the data to be stored.  For example:
 3330:    
 3331: %Save_Parameters = ('Status' => 'scalar',
 3332:     'chartoutputmode' => 'scalar',
 3333:     'chartoutputdata' => 'scalar',
 3334:     'Section' => 'array',
 3335:     'StudentData' => 'array',
 3336:     'Maps' => 'array');
 3337: 
 3338: Returns: both routines return nothing
 3339: 
 3340: =cut
 3341: 
 3342: #######################################################
 3343: #######################################################
 3344: sub store_course_settings {
 3345:     # save to the environment
 3346:     # appenv the same items, just to be safe
 3347:     my $courseid = $ENV{'request.course.id'};
 3348:     my $coursedom = $ENV{'course.'.$courseid.'.domain'};
 3349:     my ($prefix,$Settings) = @_;
 3350:     my %SaveHash;
 3351:     my %AppHash;
 3352:     while (my ($setting,$type) = each(%$Settings)) {
 3353:         my $basename = 'env.internal.'.$prefix.'.'.$setting;
 3354:         my $envname = 'course.'.$courseid.'.'.$basename;
 3355:         if (exists($ENV{'form.'.$setting})) {
 3356:             # Save this value away
 3357:             if ($type eq 'scalar' &&
 3358:                 (! exists($ENV{$envname}) || 
 3359:                  $ENV{$envname} ne $ENV{'form.'.$setting})) {
 3360:                 $SaveHash{$basename} = $ENV{'form.'.$setting};
 3361:                 $AppHash{$envname}   = $ENV{'form.'.$setting};
 3362:             } elsif ($type eq 'array') {
 3363:                 my $stored_form;
 3364:                 if (ref($ENV{'form.'.$setting})) {
 3365:                     $stored_form = join(',',
 3366:                                         map {
 3367:                                             &Apache::lonnet::escape($_);
 3368:                                         } sort(@{$ENV{'form.'.$setting}}));
 3369:                 } else {
 3370:                     $stored_form = 
 3371:                         &Apache::lonnet::escape($ENV{'form.'.$setting});
 3372:                 }
 3373:                 # Determine if the array contents are the same.
 3374:                 if ($stored_form ne $ENV{$envname}) {
 3375:                     $SaveHash{$basename} = $stored_form;
 3376:                     $AppHash{$envname}   = $stored_form;
 3377:                 }
 3378:             }
 3379:         }
 3380:     }
 3381:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
 3382:                                           $coursedom,
 3383:                                           $ENV{'course.'.$courseid.'.num'});
 3384:     if ($put_result !~ /^(ok|delayed)/) {
 3385:         &Apache::lonnet::logthis('unable to save form parameters, '.
 3386:                                  'got error:'.$put_result);
 3387:     }
 3388:     # Make sure these settings stick around in this session, too
 3389:     &Apache::lonnet::appenv(%AppHash);
 3390:     return;
 3391: }
 3392: 
 3393: sub restore_course_settings {
 3394:     my $courseid = $ENV{'request.course.id'};
 3395:     my ($prefix,$Settings) = @_;
 3396:     while (my ($setting,$type) = each(%$Settings)) {
 3397:         next if (exists($ENV{'form.'.$setting}));
 3398:         my $envname = 'course.'.$courseid.'.env.internal.'.$prefix.
 3399:             '.'.$setting;
 3400:         if (exists($ENV{$envname})) {
 3401:             if ($type eq 'scalar') {
 3402:                 $ENV{'form.'.$setting} = $ENV{$envname};
 3403:             } elsif ($type eq 'array') {
 3404:                 $ENV{'form.'.$setting} = [ 
 3405:                                            map { 
 3406:                                                &Apache::lonnet::unescape($_); 
 3407:                                            } split(',',$ENV{$envname})
 3408:                                            ];
 3409:             }
 3410:         }
 3411:     }
 3412: }
 3413: 
 3414: ############################################################
 3415: ############################################################
 3416: 
 3417: sub propath {
 3418:     my ($udom,$uname)=@_;
 3419:     $udom=~s/\W//g;
 3420:     $uname=~s/\W//g;
 3421:     my $subdir=$uname.'__';
 3422:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 3423:     my $proname="$Apache::lonnet::perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
 3424:     return $proname;
 3425: } 
 3426: 
 3427: sub icon {
 3428:     my ($file)=@_;
 3429:     my $curfext = (split(/\./,$file))[-1];
 3430:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
 3431:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
 3432:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
 3433: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
 3434: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
 3435: 	            $curfext.".gif") {
 3436: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
 3437: 		$curfext.".gif";
 3438: 	}
 3439:     }
 3440:     return $iconname;
 3441: } 
 3442: 
 3443: =pod
 3444: 
 3445: =back
 3446: 
 3447: =cut
 3448: 
 3449: 1;
 3450: __END__;
 3451: 

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