File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.188: download - view: text, annotated - select for diffs
Mon Apr 19 21:28:19 2004 UTC (20 years, 1 month ago) by matthew
Branches: MAIN
CVS tags: HEAD
&filedescription and &filedescriptionex: added regexp processing of
description to 'escape' [ and ] with '~'s prior to localization.

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

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