File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.195: download - view: text, annotated - select for diffs
Sat Jul 3 19:12:41 2004 UTC (20 years ago) by albertel
Branches: MAIN
CVS tags: HEAD
- discussion has occured, no

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

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