File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.191: download - view: text, annotated - select for diffs
Mon May 3 16:07:18 2004 UTC (20 years, 2 months ago) by matthew
Branches: MAIN
CVS tags: version_1_1_99_0, HEAD
Modified multiple_select_form to give a value instead of a name to each
option.  Modified it to take a size as input.

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.191 2004/05/03 16:07:18 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,4,%domains);
  911:     } else {
  912: 	return &select_form($name,$value,%domains);
  913:     }
  914: }
  915: 
  916: sub multiple_select_form {
  917:     my ($name,$value,$size,%hash)=@_;
  918:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
  919:     my $output='';
  920:     if (! defined($size)) {
  921:         $size = 4;
  922:         if (scalar(keys(%hash))<4) {
  923:             $size = scalar(keys(%hash));
  924:         }
  925:     }
  926:     $output.="\n<select name='$name' size='$size' multiple='1'>";
  927:     foreach (sort(keys(%hash))) {
  928:         $output.='<option value="'.$_.'" ';
  929:         $output.='selected ' if ($selected{$_});
  930:         $output.='>'.$hash{$_}."</option>\n";
  931:     }
  932:     $output.="</select>\n";
  933:     return $output;
  934: }
  935: 
  936: #-------------------------------------------
  937: 
  938: =pod
  939: 
  940: =item * select_form($defdom,$name,%hash)
  941: 
  942: Returns a string containing a <select name='$name' size='1'> form to 
  943: allow a user to select options from a hash option_name => displayed text.  
  944: See lonrights.pm for an example invocation and use.
  945: 
  946: =cut
  947: 
  948: #-------------------------------------------
  949: sub select_form {
  950:     my ($def,$name,%hash) = @_;
  951:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
  952:     my @keys;
  953:     if (exists($hash{'select_form_order'})) {
  954: 	@keys=@{$hash{'select_form_order'}};
  955:     } else {
  956: 	@keys=sort(keys(%hash));
  957:     }
  958:     foreach (@keys) {
  959:         $selectform.="<option value=\"$_\" ".
  960:             ($_ eq $def ? 'selected' : '').
  961:                 ">".&mt($hash{$_})."</option>\n";
  962:     }
  963:     $selectform.="</select>";
  964:     return $selectform;
  965: }
  966: 
  967: sub gradeleveldescription {
  968:     my $gradelevel=shift;
  969:     my %gradelevels=(0 => 'Not specified',
  970: 		     1 => 'Grade 1',
  971: 		     2 => 'Grade 2',
  972: 		     3 => 'Grade 3',
  973: 		     4 => 'Grade 4',
  974: 		     5 => 'Grade 5',
  975: 		     6 => 'Grade 6',
  976: 		     7 => 'Grade 7',
  977: 		     8 => 'Grade 8',
  978: 		     9 => 'Grade 9',
  979: 		     10 => 'Grade 10',
  980: 		     11 => 'Grade 11',
  981: 		     12 => 'Grade 12',
  982: 		     13 => 'Grade 13',
  983: 		     14 => '100 Level',
  984: 		     15 => '200 Level',
  985: 		     16 => '300 Level',
  986: 		     17 => '400 Level',
  987: 		     18 => 'Graduate Level');
  988:     return &mt($gradelevels{$gradelevel});
  989: }
  990: 
  991: sub select_level_form {
  992:     my ($deflevel,$name)=@_;
  993:     unless ($deflevel) { $deflevel=0; }
  994:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
  995:     for (my $i=0; $i<=18; $i++) {
  996:         $selectform.="<option value=\"$i\" ".
  997:             ($i==$deflevel ? 'selected' : '').
  998:                 ">".&gradeleveldescription($i)."</option>\n";
  999:     }
 1000:     $selectform.="</select>";
 1001:     return $selectform;
 1002: }
 1003: 
 1004: #-------------------------------------------
 1005: 
 1006: =pod
 1007: 
 1008: =item * select_dom_form($defdom,$name,$includeempty)
 1009: 
 1010: Returns a string containing a <select name='$name' size='1'> form to 
 1011: allow a user to select the domain to preform an operation in.  
 1012: See loncreateuser.pm for an example invocation and use.
 1013: 
 1014: If the $includeempty flag is set, it also includes an empty choice ("no domain
 1015: selected");
 1016: 
 1017: =cut
 1018: 
 1019: #-------------------------------------------
 1020: sub select_dom_form {
 1021:     my ($defdom,$name,$includeempty) = @_;
 1022:     my @domains = get_domains();
 1023:     if ($includeempty) { @domains=('',@domains); }
 1024:     my $selectdomain = "<select name=\"$name\" size=\"1\">\n";
 1025:     foreach (@domains) {
 1026:         $selectdomain.="<option value=\"$_\" ".
 1027:             ($_ eq $defdom ? 'selected' : '').
 1028:                 ">$_</option>\n";
 1029:     }
 1030:     $selectdomain.="</select>";
 1031:     return $selectdomain;
 1032: }
 1033: 
 1034: #-------------------------------------------
 1035: 
 1036: =pod
 1037: 
 1038: =item * get_library_servers($domain)
 1039: 
 1040: Returns a hash which contains keys like '103l3' and values like 
 1041: 'kirk.lite.msu.edu'.  All of the keys will be for machines in the
 1042: given $domain.
 1043: 
 1044: =cut
 1045: 
 1046: #-------------------------------------------
 1047: sub get_library_servers {
 1048:     my $domain = shift;
 1049:     my %library_servers;
 1050:     foreach (keys(%Apache::lonnet::libserv)) {
 1051:         if ($Apache::lonnet::hostdom{$_} eq $domain) {
 1052:             $library_servers{$_} = $Apache::lonnet::hostname{$_};
 1053:         }
 1054:     }
 1055:     return %library_servers;
 1056: }
 1057: 
 1058: #-------------------------------------------
 1059: 
 1060: =pod
 1061: 
 1062: =item * home_server_option_list($domain)
 1063: 
 1064: returns a string which contains an <option> list to be used in a 
 1065: <select> form input.  See loncreateuser.pm for an example.
 1066: 
 1067: =cut
 1068: 
 1069: #-------------------------------------------
 1070: sub home_server_option_list {
 1071:     my $domain = shift;
 1072:     my %servers = &get_library_servers($domain);
 1073:     my $result = '';
 1074:     foreach (sort keys(%servers)) {
 1075:         $result.=
 1076:             '<option value="'.$_.'">'.$_.' '.$servers{$_}."</option>\n";
 1077:     }
 1078:     return $result;
 1079: }
 1080: 
 1081: =pod
 1082: 
 1083: =back
 1084: 
 1085: =cut
 1086: 
 1087: ###############################################################
 1088: ##                  Decoding User Agent                      ##
 1089: ###############################################################
 1090: 
 1091: =pod
 1092: 
 1093: =head1 Decoding the User Agent
 1094: 
 1095: =over 4
 1096: 
 1097: =item * &decode_user_agent()
 1098: 
 1099: Inputs: $r
 1100: 
 1101: Outputs:
 1102: 
 1103: =over 4
 1104: 
 1105: =item * $httpbrowser
 1106: 
 1107: =item * $clientbrowser
 1108: 
 1109: =item * $clientversion
 1110: 
 1111: =item * $clientmathml
 1112: 
 1113: =item * $clientunicode
 1114: 
 1115: =item * $clientos
 1116: 
 1117: =back
 1118: 
 1119: =back 
 1120: 
 1121: =cut
 1122: 
 1123: ###############################################################
 1124: ###############################################################
 1125: sub decode_user_agent {
 1126:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 1127:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 1128:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 1129:     my $clientbrowser='unknown';
 1130:     my $clientversion='0';
 1131:     my $clientmathml='';
 1132:     my $clientunicode='0';
 1133:     for (my $i=0;$i<=$#browsertype;$i++) {
 1134:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
 1135: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 1136: 	    $clientbrowser=$bname;
 1137:             $httpbrowser=~/$vreg/i;
 1138: 	    $clientversion=$1;
 1139:             $clientmathml=($clientversion>=$minv);
 1140:             $clientunicode=($clientversion>=$univ);
 1141: 	}
 1142:     }
 1143:     my $clientos='unknown';
 1144:     if (($httpbrowser=~/linux/i) ||
 1145:         ($httpbrowser=~/unix/i) ||
 1146:         ($httpbrowser=~/ux/i) ||
 1147:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 1148:     if (($httpbrowser=~/vax/i) ||
 1149:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 1150:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 1151:     if (($httpbrowser=~/mac/i) ||
 1152:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 1153:     if ($httpbrowser=~/win/i) { $clientos='win'; }
 1154:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 1155:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 1156:             $clientunicode,$clientos,);
 1157: }
 1158: 
 1159: ###############################################################
 1160: ##    Authentication changing form generation subroutines    ##
 1161: ###############################################################
 1162: ##
 1163: ## All of the authform_xxxxxxx subroutines take their inputs in a
 1164: ## hash, and have reasonable default values.
 1165: ##
 1166: ##    formname = the name given in the <form> tag.
 1167: #-------------------------------------------
 1168: 
 1169: =pod
 1170: 
 1171: =head1 Authentication Routines
 1172: 
 1173: =over 4
 1174: 
 1175: =item * authform_xxxxxx
 1176: 
 1177: The authform_xxxxxx subroutines provide javascript and html forms which 
 1178: handle some of the conveniences required for authentication forms.  
 1179: This is not an optimal method, but it works.  
 1180: 
 1181: See loncreateuser.pm for invocation and use examples.
 1182: 
 1183: =over 4
 1184: 
 1185: =item * authform_header
 1186: 
 1187: =item * authform_authorwarning
 1188: 
 1189: =item * authform_nochange
 1190: 
 1191: =item * authform_kerberos
 1192: 
 1193: =item * authform_internal
 1194: 
 1195: =item * authform_filesystem
 1196: 
 1197: =back
 1198: 
 1199: =back 
 1200: 
 1201: =cut
 1202: 
 1203: #-------------------------------------------
 1204: sub authform_header{  
 1205:     my %in = (
 1206:         formname => 'cu',
 1207:         kerb_def_dom => '',
 1208:         @_,
 1209:     );
 1210:     $in{'formname'} = 'document.' . $in{'formname'};
 1211:     my $result='';
 1212: 
 1213: #---------------------------------------------- Code for upper case translation
 1214:     my $Javascript_toUpperCase;
 1215:     unless ($in{kerb_def_dom}) {
 1216:         $Javascript_toUpperCase =<<"END";
 1217:         switch (choice) {
 1218:            case 'krb': currentform.elements[choicearg].value =
 1219:                currentform.elements[choicearg].value.toUpperCase();
 1220:                break;
 1221:            default:
 1222:         }
 1223: END
 1224:     } else {
 1225:         $Javascript_toUpperCase = "";
 1226:     }
 1227: 
 1228:     my $radioval = "'nochange'";
 1229:     if (exists($in{'curr_authtype'}) &&
 1230:         defined($in{'curr_authtype'}) &&
 1231:         $in{'curr_authtype'} ne '') {
 1232:         $radioval = "'$in{'curr_authtype'}arg'";
 1233:     }
 1234:     my $argfield = 'null';
 1235:     if ( grep/^mode$/,(keys %in) ) {
 1236:         if ($in{'mode'} eq 'modifycourse')  {
 1237:             if ( grep/^curr_authtype$/,(keys %in) ) {
 1238:                 $radioval = "'$in{'curr_authtype'}'";
 1239:             }
 1240:             if ( grep/^curr_autharg$/,(keys %in) ) {
 1241:                 unless ($in{'curr_autharg'} eq '') {
 1242:                     $argfield = "'$in{'curr_autharg'}'";
 1243:                 }
 1244:             }
 1245:         }
 1246:     }
 1247: 
 1248:     $result.=<<"END";
 1249: var current = new Object();
 1250: current.radiovalue = $radioval;
 1251: current.argfield = $argfield;
 1252: 
 1253: function changed_radio(choice,currentform) {
 1254:     var choicearg = choice + 'arg';
 1255:     // If a radio button in changed, we need to change the argfield
 1256:     if (current.radiovalue != choice) {
 1257:         current.radiovalue = choice;
 1258:         if (current.argfield != null) {
 1259:             currentform.elements[current.argfield].value = '';
 1260:         }
 1261:         if (choice == 'nochange') {
 1262:             current.argfield = null;
 1263:         } else {
 1264:             current.argfield = choicearg;
 1265:             switch(choice) {
 1266:                 case 'krb': 
 1267:                     currentform.elements[current.argfield].value = 
 1268:                         "$in{'kerb_def_dom'}";
 1269:                 break;
 1270:               default:
 1271:                 break;
 1272:             }
 1273:         }
 1274:     }
 1275:     return;
 1276: }
 1277: 
 1278: function changed_text(choice,currentform) {
 1279:     var choicearg = choice + 'arg';
 1280:     if (currentform.elements[choicearg].value !='') {
 1281:         $Javascript_toUpperCase
 1282:         // clear old field
 1283:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 1284:             currentform.elements[current.argfield].value = '';
 1285:         }
 1286:         current.argfield = choicearg;
 1287:     }
 1288:     set_auth_radio_buttons(choice,currentform);
 1289:     return;
 1290: }
 1291: 
 1292: function set_auth_radio_buttons(newvalue,currentform) {
 1293:     var i=0;
 1294:     while (i < currentform.login.length) {
 1295:         if (currentform.login[i].value == newvalue) { break; }
 1296:         i++;
 1297:     }
 1298:     if (i == currentform.login.length) {
 1299:         return;
 1300:     }
 1301:     current.radiovalue = newvalue;
 1302:     currentform.login[i].checked = true;
 1303:     return;
 1304: }
 1305: END
 1306:     return $result;
 1307: }
 1308: 
 1309: sub authform_authorwarning{
 1310:     my $result='';
 1311:     $result='<i>'.
 1312:         &mt('As a general rule, only authors or co-authors should be '.
 1313:             'filesystem authenticated '.
 1314:             '(which allows access to the server filesystem).')."</i>\n";
 1315:     return $result;
 1316: }
 1317: 
 1318: sub authform_nochange{  
 1319:     my %in = (
 1320:               formname => 'document.cu',
 1321:               kerb_def_dom => 'MSU.EDU',
 1322:               @_,
 1323:           );
 1324:     my $result = &mt('[_1] Do not change login data',
 1325:                      '<input type="radio" name="login" value="nochange" '.
 1326:                      'checked="checked" onclick="'.
 1327:             "javascript:changed_radio('nochange',$in{'formname'});".'" />');
 1328:     return $result;
 1329: }
 1330: 
 1331: sub authform_kerberos{  
 1332:     my %in = (
 1333:               formname => 'document.cu',
 1334:               kerb_def_dom => 'MSU.EDU',
 1335:               kerb_def_auth => 'krb4',
 1336:               @_,
 1337:               );
 1338:     my ($check4,$check5,$krbarg);
 1339:     if ($in{'kerb_def_auth'} eq 'krb5') {
 1340:        $check5 = " checked=\"on\"";
 1341:     } else {
 1342:        $check4 = " checked=\"on\"";
 1343:     }
 1344:     $krbarg = $in{'kerb_def_dom'};
 1345: 
 1346:     my $krbcheck = "";
 1347:     if ( grep/^curr_authtype$/,(keys %in) ) {
 1348:         if ($in{'curr_authtype'} =~ m/^krb/) {
 1349:             $krbcheck = " checked=\"on\"";
 1350:             if ( grep/^curr_autharg$/,(keys %in) ) {
 1351:                 $krbarg = $in{'curr_autharg'};
 1352:             }
 1353:         }
 1354:     }
 1355: 
 1356:     my $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 1357:     my $result .= &mt
 1358:         ('[_1] Kerberos authenticated with domain [_2] '.
 1359:          '[_3] Version 4 [_4] Version 5',
 1360:          '<input type="radio" name="login" value="krb" '.
 1361:              'onclick="'.$jscall.'" onchange="'.$jscall.'"'.$krbcheck.' />',
 1362:          '<input type="text" size="10" name="krbarg" '.
 1363:              'value="'.$krbarg.'" '.
 1364:              'onchange="'.$jscall.'" />',
 1365:          '<input type="radio" name="krbver" value="4" '.$check4.' />',
 1366:          '<input type="radio" name="krbver" value="5" '.$check5.' />');
 1367:     return $result;
 1368: }
 1369: 
 1370: sub authform_internal{  
 1371:     my %args = (
 1372:                 formname => 'document.cu',
 1373:                 kerb_def_dom => 'MSU.EDU',
 1374:                 @_,
 1375:                 );
 1376: 
 1377:     my $intcheck = "";
 1378:     my $intarg = 'value=""';
 1379:     if ( grep/^curr_authtype$/,(keys %args) ) {
 1380:         if ($args{'curr_authtype'} eq 'int') {
 1381:             $intcheck = " checked=\"on\"";
 1382:             if ( grep/^curr_autharg$/,(keys %args) ) {
 1383:                 $intarg = "value=\"$args{'curr_autharg'}\"";
 1384:             }
 1385:         }
 1386:     }
 1387: 
 1388:     my $jscall = "javascript:changed_radio('int',$args{'formname'});";
 1389:     my $result.=&mt
 1390:         ('[_1] Internally authenticated (with initial password [_2])',
 1391:          '<input type="radio" name="login" value="int" '.$intcheck.
 1392:              ' onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 1393:          '<input type="text" size="10" name="intarg" '.$intarg.
 1394:              ' onchange="'.$jscall.'" />');
 1395:     return $result;
 1396: }
 1397: 
 1398: sub authform_local{  
 1399:     my %in = (
 1400:               formname => 'document.cu',
 1401:               kerb_def_dom => 'MSU.EDU',
 1402:               @_,
 1403:               );
 1404: 
 1405:     my $loccheck = "";
 1406:     my $locarg = 'value=""';
 1407:     if ( grep/^curr_authtype$/,(keys %in) ) {
 1408:         if ($in{'curr_authtype'} eq 'loc') {
 1409:             $loccheck = " checked=\"on\"";
 1410:             if ( grep/^curr_autharg$/,(keys %in) ) {
 1411:                 $locarg = "value=\"$in{'curr_autharg'}\"";
 1412:             }
 1413:         }
 1414:     }
 1415: 
 1416:     my $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 1417:     my $result.=&mt('[_1] Local Authentication with argument [_2]',
 1418:                     '<input type="radio" name="login" value="loc" '.$loccheck.
 1419:                         ' onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 1420:                     '<input type="text" size="10" name="locarg" '.$locarg.
 1421:                         ' onchange="'.$jscall.'" />');
 1422:     return $result;
 1423: }
 1424: 
 1425: sub authform_filesystem{  
 1426:     my %in = (
 1427:               formname => 'document.cu',
 1428:               kerb_def_dom => 'MSU.EDU',
 1429:               @_,
 1430:               );
 1431:     my $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 1432:     my $result.= &mt
 1433:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 1434:          '<input type="radio" name="login" value="fsys" '.
 1435:          'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 1436:          '<input type="text" size="10" name="fsysarg" value="" '.
 1437:                   'onchange="'.$jscall.'" />');
 1438:     return $result;
 1439: }
 1440: 
 1441: ###############################################################
 1442: ##    Get Authentication Defaults for Domain                 ##
 1443: ###############################################################
 1444: 
 1445: =pod
 1446: 
 1447: =head1 Domains and Authentication
 1448: 
 1449: Returns default authentication type and an associated argument as
 1450: listed in file 'domain.tab'.
 1451: 
 1452: =over 4
 1453: 
 1454: =item * get_auth_defaults
 1455: 
 1456: get_auth_defaults($target_domain) returns the default authentication
 1457: type and an associated argument (initial password or a kerberos domain).
 1458: These values are stored in lonTabs/domain.tab
 1459: 
 1460: ($def_auth, $def_arg) = &get_auth_defaults($target_domain);
 1461: 
 1462: If target_domain is not found in domain.tab, returns nothing ('').
 1463: 
 1464: =cut
 1465: 
 1466: #-------------------------------------------
 1467: sub get_auth_defaults {
 1468:     my $domain=shift;
 1469:     return ($Apache::lonnet::domain_auth_def{$domain},$Apache::lonnet::domain_auth_arg_def{$domain});
 1470: }
 1471: ###############################################################
 1472: ##   End Get Authentication Defaults for Domain              ##
 1473: ###############################################################
 1474: 
 1475: ###############################################################
 1476: ##    Get Kerberos Defaults for Domain                 ##
 1477: ###############################################################
 1478: ##
 1479: ## Returns default kerberos version and an associated argument
 1480: ## as listed in file domain.tab. If not listed, provides
 1481: ## appropriate default domain and kerberos version.
 1482: ##
 1483: #-------------------------------------------
 1484: 
 1485: =pod
 1486: 
 1487: =item * get_kerberos_defaults
 1488: 
 1489: get_kerberos_defaults($target_domain) returns the default kerberos
 1490: version and domain. If not found in domain.tabs, it defaults to
 1491: version 4 and the domain of the server.
 1492: 
 1493: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 1494: 
 1495: =cut
 1496: 
 1497: #-------------------------------------------
 1498: sub get_kerberos_defaults {
 1499:     my $domain=shift;
 1500:     my ($krbdef,$krbdefdom) =
 1501:         &Apache::loncommon::get_auth_defaults($domain);
 1502:     unless ($krbdef =~/^krb/ && $krbdefdom) {
 1503:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 1504:         my $krbdefdom=$1;
 1505:         $krbdefdom=~tr/a-z/A-Z/;
 1506:         $krbdef = "krb4";
 1507:     }
 1508:     return ($krbdef,$krbdefdom);
 1509: }
 1510: 
 1511: =pod
 1512: 
 1513: =back
 1514: 
 1515: =cut
 1516: 
 1517: ###############################################################
 1518: ##                Thesaurus Functions                        ##
 1519: ###############################################################
 1520: 
 1521: =pod
 1522: 
 1523: =head1 Thesaurus Functions
 1524: 
 1525: =over 4
 1526: 
 1527: =item * initialize_keywords
 1528: 
 1529: Initializes the package variable %Keywords if it is empty.  Uses the
 1530: package variable $thesaurus_db_file.
 1531: 
 1532: =cut
 1533: 
 1534: ###################################################
 1535: 
 1536: sub initialize_keywords {
 1537:     return 1 if (scalar keys(%Keywords));
 1538:     # If we are here, %Keywords is empty, so fill it up
 1539:     #   Make sure the file we need exists...
 1540:     if (! -e $thesaurus_db_file) {
 1541:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 1542:                                  " failed because it does not exist");
 1543:         return 0;
 1544:     }
 1545:     #   Set up the hash as a database
 1546:     my %thesaurus_db;
 1547:     if (! tie(%thesaurus_db,'GDBM_File',
 1548:               $thesaurus_db_file,&GDBM_READER(),0640)){
 1549:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 1550:                                  $thesaurus_db_file);
 1551:         return 0;
 1552:     } 
 1553:     #  Get the average number of appearances of a word.
 1554:     my $avecount = $thesaurus_db{'average.count'};
 1555:     #  Put keywords (those that appear > average) into %Keywords
 1556:     while (my ($word,$data)=each (%thesaurus_db)) {
 1557:         my ($count,undef) = split /:/,$data;
 1558:         $Keywords{$word}++ if ($count > $avecount);
 1559:     }
 1560:     untie %thesaurus_db;
 1561:     # Remove special values from %Keywords.
 1562:     foreach ('total.count','average.count') {
 1563:         delete($Keywords{$_}) if (exists($Keywords{$_}));
 1564:     }
 1565:     return 1;
 1566: }
 1567: 
 1568: ###################################################
 1569: 
 1570: =pod
 1571: 
 1572: =item * keyword($word)
 1573: 
 1574: Returns true if $word is a keyword.  A keyword is a word that appears more 
 1575: than the average number of times in the thesaurus database.  Calls 
 1576: &initialize_keywords
 1577: 
 1578: =cut
 1579: 
 1580: ###################################################
 1581: 
 1582: sub keyword {
 1583:     return if (!&initialize_keywords());
 1584:     my $word=lc(shift());
 1585:     $word=~s/\W//g;
 1586:     return exists($Keywords{$word});
 1587: }
 1588: 
 1589: ###############################################################
 1590: 
 1591: =pod 
 1592: 
 1593: =item * get_related_words
 1594: 
 1595: Look up a word in the thesaurus.  Takes a scalar argument and returns
 1596: an array of words.  If the keyword is not in the thesaurus, an empty array
 1597: will be returned.  The order of the words returned is determined by the
 1598: database which holds them.
 1599: 
 1600: Uses global $thesaurus_db_file.
 1601: 
 1602: =cut
 1603: 
 1604: ###############################################################
 1605: sub get_related_words {
 1606:     my $keyword = shift;
 1607:     my %thesaurus_db;
 1608:     if (! -e $thesaurus_db_file) {
 1609:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 1610:                                  "failed because the file does not exist");
 1611:         return ();
 1612:     }
 1613:     if (! tie(%thesaurus_db,'GDBM_File',
 1614:               $thesaurus_db_file,&GDBM_READER(),0640)){
 1615:         return ();
 1616:     } 
 1617:     my @Words=();
 1618:     if (exists($thesaurus_db{$keyword})) {
 1619:         $_ = $thesaurus_db{$keyword};
 1620:         (undef,@Words) = split/:/;  # The first element is the number of times
 1621:                                     # the word appears.  We do not need it now.
 1622:         for (my $i=0;$i<=$#Words;$i++) {
 1623:             ($Words[$i],undef)= split/\,/,$Words[$i];
 1624:         }
 1625:     }
 1626:     untie %thesaurus_db;
 1627:     return @Words;
 1628: }
 1629: 
 1630: =pod
 1631: 
 1632: =back
 1633: 
 1634: =cut
 1635: 
 1636: # -------------------------------------------------------------- Plaintext name
 1637: =pod
 1638: 
 1639: =head1 User Name Functions
 1640: 
 1641: =over 4
 1642: 
 1643: =item * plainname($uname,$udom)
 1644: 
 1645: Takes a users logon name and returns it as a string in
 1646: "first middle last generation" form
 1647: 
 1648: =cut
 1649: 
 1650: ###############################################################
 1651: sub plainname {
 1652:     my ($uname,$udom)=@_;
 1653:     my %names=&Apache::lonnet::get('environment',
 1654:                     ['firstname','middlename','lastname','generation'],
 1655: 					 $udom,$uname);
 1656:     my $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 1657: 	$names{'lastname'}.' '.$names{'generation'};
 1658:     $name=~s/\s+$//;
 1659:     $name=~s/\s+/ /g;
 1660:     if ($name !~ /\S/) { $name=$uname.'@'.$udom; }
 1661:     return $name;
 1662: }
 1663: 
 1664: # -------------------------------------------------------------------- Nickname
 1665: =pod
 1666: 
 1667: =item * nickname($uname,$udom)
 1668: 
 1669: Gets a users name and returns it as a string as
 1670: 
 1671: "&quot;nickname&quot;"
 1672: 
 1673: if the user has a nickname or
 1674: 
 1675: "first middle last generation"
 1676: 
 1677: if the user does not
 1678: 
 1679: =cut
 1680: 
 1681: sub nickname {
 1682:     my ($uname,$udom)=@_;
 1683:     my %names=&Apache::lonnet::get('environment',
 1684:   ['nickname','firstname','middlename','lastname','generation'],$udom,$uname);
 1685:     my $name=$names{'nickname'};
 1686:     if ($name) {
 1687:        $name='&quot;'.$name.'&quot;'; 
 1688:     } else {
 1689:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 1690: 	     $names{'lastname'}.' '.$names{'generation'};
 1691:        $name=~s/\s+$//;
 1692:        $name=~s/\s+/ /g;
 1693:     }
 1694:     return $name;
 1695: }
 1696: 
 1697: 
 1698: # ------------------------------------------------------------------ Screenname
 1699: 
 1700: =pod
 1701: 
 1702: =item * screenname($uname,$udom)
 1703: 
 1704: Gets a users screenname and returns it as a string
 1705: 
 1706: =cut
 1707: 
 1708: sub screenname {
 1709:     my ($uname,$udom)=@_;
 1710:     my %names=
 1711:  &Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 1712:     return $names{'screenname'};
 1713: }
 1714: 
 1715: # ------------------------------------------------------------- Message Wrapper
 1716: 
 1717: sub messagewrapper {
 1718:     my ($link,$un,$do)=@_;
 1719:     return 
 1720: "<a href='/adm/email?compose=individual&recname=$un&recdom=$do'>$link</a>";
 1721: }
 1722: # --------------------------------------------------------------- Notes Wrapper
 1723: 
 1724: sub noteswrapper {
 1725:     my ($link,$un,$do)=@_;
 1726:     return 
 1727: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
 1728: }
 1729: # ------------------------------------------------------------- Aboutme Wrapper
 1730: 
 1731: sub aboutmewrapper {
 1732:     my ($link,$username,$domain,$target)=@_;
 1733:     return "<a href='/adm/$domain/$username/aboutme'".
 1734: 	($target?" target='$target'":'').">$link</a>";
 1735: }
 1736: 
 1737: # ------------------------------------------------------------ Syllabus Wrapper
 1738: 
 1739: 
 1740: sub syllabuswrapper {
 1741:     my ($linktext,$coursedir,$domain,$fontcolor)=@_;
 1742:     if ($fontcolor) { 
 1743:         $linktext='<font color="'.$fontcolor.'">'.$linktext.'</font>'; 
 1744:     }
 1745:     return "<a href='/public/$domain/$coursedir/syllabus'>$linktext</a>";
 1746: }
 1747: 
 1748: =pod
 1749: 
 1750: =back
 1751: 
 1752: =head1 Access .tab File Data
 1753: 
 1754: =over 4
 1755: 
 1756: =item * languageids() 
 1757: 
 1758: returns list of all language ids
 1759: 
 1760: =cut
 1761: 
 1762: sub languageids {
 1763:     return sort(keys(%language));
 1764: }
 1765: 
 1766: =pod
 1767: 
 1768: =item * languagedescription() 
 1769: 
 1770: returns description of a specified language id
 1771: 
 1772: =cut
 1773: 
 1774: sub languagedescription {
 1775:     my $code=shift;
 1776:     return  ($supported_language{$code}?'* ':'').
 1777:             $language{$code}.
 1778: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 1779: }
 1780: 
 1781: sub plainlanguagedescription {
 1782:     my $code=shift;
 1783:     return $language{$code};
 1784: }
 1785: 
 1786: sub supportedlanguagecode {
 1787:     my $code=shift;
 1788:     return $supported_language{$code};
 1789: }
 1790: 
 1791: =pod
 1792: 
 1793: =item * copyrightids() 
 1794: 
 1795: returns list of all copyrights
 1796: 
 1797: =cut
 1798: 
 1799: sub copyrightids {
 1800:     return sort(keys(%cprtag));
 1801: }
 1802: 
 1803: =pod
 1804: 
 1805: =item * copyrightdescription() 
 1806: 
 1807: returns description of a specified copyright id
 1808: 
 1809: =cut
 1810: 
 1811: sub copyrightdescription {
 1812:     return &mt($cprtag{shift(@_)});
 1813: }
 1814: 
 1815: =pod
 1816: 
 1817: =item * filecategories() 
 1818: 
 1819: returns list of all file categories
 1820: 
 1821: =cut
 1822: 
 1823: sub filecategories {
 1824:     return sort(keys(%category_extensions));
 1825: }
 1826: 
 1827: =pod
 1828: 
 1829: =item * filecategorytypes() 
 1830: 
 1831: returns list of file types belonging to a given file
 1832: category
 1833: 
 1834: =cut
 1835: 
 1836: sub filecategorytypes {
 1837:     return @{$category_extensions{lc($_[0])}};
 1838: }
 1839: 
 1840: =pod
 1841: 
 1842: =item * fileembstyle() 
 1843: 
 1844: returns embedding style for a specified file type
 1845: 
 1846: =cut
 1847: 
 1848: sub fileembstyle {
 1849:     return $fe{lc(shift(@_))};
 1850: }
 1851: 
 1852: 
 1853: sub filecategoryselect {
 1854:     my ($name,$value)=@_;
 1855:     return &select_form($value,$name,
 1856: 			'' => &mt('Any category'),
 1857: 			map { $_,$_ } sort(keys(%category_extensions)));
 1858: }
 1859: 
 1860: =pod
 1861: 
 1862: =item * filedescription() 
 1863: 
 1864: returns description for a specified file type
 1865: 
 1866: =cut
 1867: 
 1868: sub filedescription {
 1869:     my $file_description = $fd{lc(shift())};
 1870:     $file_description =~ s:([\[\]]):~$1:g;
 1871:     return &mt($file_description);
 1872: }
 1873: 
 1874: =pod
 1875: 
 1876: =item * filedescriptionex() 
 1877: 
 1878: returns description for a specified file type with
 1879: extra formatting
 1880: 
 1881: =cut
 1882: 
 1883: sub filedescriptionex {
 1884:     my $ex=shift;
 1885:     my $file_description = $fd{lc($ex)};
 1886:     $file_description =~ s:([\[\]]):~$1:g;
 1887:     return '.'.$ex.' '.&mt($file_description);
 1888: }
 1889: 
 1890: # End of .tab access
 1891: =pod
 1892: 
 1893: =back
 1894: 
 1895: =cut
 1896: 
 1897: # ------------------------------------------------------------------ File Types
 1898: sub fileextensions {
 1899:     return sort(keys(%fe));
 1900: }
 1901: 
 1902: # ----------------------------------------------------------- Display Languages
 1903: # returns a hash with all desired display languages
 1904: #
 1905: 
 1906: sub display_languages {
 1907:     my %languages=();
 1908:     foreach (&preferred_languages()) {
 1909: 	$languages{$_}=1;
 1910:     }
 1911:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 1912:     if ($ENV{'form.displaylanguage'}) {
 1913: 	foreach (split(/\s*(\,|\;|\:)\s*/,$ENV{'form.displaylanguage'})) {
 1914: 	    $languages{$_}=1;
 1915:         }
 1916:     }
 1917:     return %languages;
 1918: }
 1919: 
 1920: sub preferred_languages {
 1921:     my @languages=();
 1922:     if ($ENV{'course.'.$ENV{'request.course.id'}.'.languages'}) {
 1923: 	@languages=(@languages,split(/\s*(\,|\;|\:)\s*/,
 1924: 	         $ENV{'course.'.$ENV{'request.course.id'}.'.languages'}));
 1925:     }
 1926:     if ($ENV{'environment.languages'}) {
 1927: 	@languages=split(/\s*(\,|\;|\:)\s*/,$ENV{'environment.languages'});
 1928:     }
 1929:     my $browser=(split(/\;/,$ENV{'HTTP_ACCEPT_LANGUAGE'}))[0];
 1930:     if ($browser) {
 1931: 	@languages=(@languages,split(/\s*(\,|\;|\:)\s*/,$browser));
 1932:     }
 1933:     if ($Apache::lonnet::domain_lang_def{$ENV{'user.domain'}}) {
 1934: 	@languages=(@languages,
 1935: 		$Apache::lonnet::domain_lang_def{$ENV{'user.domain'}});
 1936:     }
 1937:     if ($Apache::lonnet::domain_lang_def{$ENV{'request.role.domain'}}) {
 1938: 	@languages=(@languages,
 1939: 		$Apache::lonnet::domain_lang_def{$ENV{'request.role.domain'}});
 1940:     }
 1941:     if ($Apache::lonnet::domain_lang_def{
 1942: 	                          $Apache::lonnet::perlvar{'lonDefDomain'}}) {
 1943: 	@languages=(@languages,
 1944: 		$Apache::lonnet::domain_lang_def{
 1945:                                   $Apache::lonnet::perlvar{'lonDefDomain'}});
 1946:     }
 1947: # turn "en-ca" into "en-ca,en"
 1948:     my @genlanguages;
 1949:     foreach (@languages) {
 1950: 	unless ($_=~/\w/) { next; }
 1951: 	push (@genlanguages,$_);
 1952: 	if ($_=~/(\-|\_)/) {
 1953: 	    push (@genlanguages,(split(/(\-|\_)/,$_))[0]);
 1954: 	}
 1955:     }
 1956:     return @genlanguages;
 1957: }
 1958: 
 1959: ###############################################################
 1960: ##               Student Answer Attempts                     ##
 1961: ###############################################################
 1962: 
 1963: =pod
 1964: 
 1965: =head1 Alternate Problem Views
 1966: 
 1967: =over 4
 1968: 
 1969: =item * get_previous_attempt($symb, $username, $domain, $course,
 1970:     $getattempt, $regexp, $gradesub)
 1971: 
 1972: Return string with previous attempt on problem. Arguments:
 1973: 
 1974: =over 4
 1975: 
 1976: =item * $symb: Problem, including path
 1977: 
 1978: =item * $username: username of the desired student
 1979: 
 1980: =item * $domain: domain of the desired student
 1981: 
 1982: =item * $course: Course ID
 1983: 
 1984: =item * $getattempt: Leave blank for all attempts, otherwise put
 1985:     something
 1986: 
 1987: =item * $regexp: if string matches this regexp, the string will be
 1988:     sent to $gradesub
 1989: 
 1990: =item * $gradesub: routine that processes the string if it matches $regexp
 1991: 
 1992: =back
 1993: 
 1994: The output string is a table containing all desired attempts, if any.
 1995: 
 1996: =cut
 1997: 
 1998: sub get_previous_attempt {
 1999:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
 2000:   my $prevattempts='';
 2001:   no strict 'refs';
 2002:   if ($symb) {
 2003:     my (%returnhash)=
 2004:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 2005:     if ($returnhash{'version'}) {
 2006:       my %lasthash=();
 2007:       my $version;
 2008:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 2009:         foreach (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 2010: 	  $lasthash{$_}=$returnhash{$version.':'.$_};
 2011:         }
 2012:       }
 2013:       $prevattempts='<table border="0" width="100%"><tr><td bgcolor="#777777">';
 2014:       $prevattempts.='<table border="0" width="100%"><tr bgcolor="#e6ffff"><td>History</td>';
 2015:       foreach (sort(keys %lasthash)) {
 2016: 	my ($ign,@parts) = split(/\./,$_);
 2017: 	if ($#parts > 0) {
 2018: 	  my $data=$parts[-1];
 2019: 	  pop(@parts);
 2020: 	  $prevattempts.='<td>Part '.join('.',@parts).'<br />'.$data.'&nbsp;</td>';
 2021: 	} else {
 2022: 	  if ($#parts == 0) {
 2023: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 2024: 	  } else {
 2025: 	    $prevattempts.='<th>'.$ign.'</th>';
 2026: 	  }
 2027: 	}
 2028:       }
 2029:       if ($getattempt eq '') {
 2030: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 2031: 	  $prevattempts.='</tr><tr bgcolor="#ffffe6"><td>Transaction '.$version.'</td>';
 2032: 	    foreach (sort(keys %lasthash)) {
 2033: 	       my $value;
 2034: 	       if ($_ =~ /timestamp/) {
 2035: 		  $value=scalar(localtime($returnhash{$version.':'.$_}));
 2036: 	       } else {
 2037: 		  $value=$returnhash{$version.':'.$_};
 2038: 	       }
 2039: 	       $prevattempts.='<td>'.&Apache::lonnet::unescape($value).'&nbsp;</td>';   
 2040: 	    }
 2041: 	 }
 2042:       }
 2043:       $prevattempts.='</tr><tr bgcolor="#ffffe6"><td>Current</td>';
 2044:       foreach (sort(keys %lasthash)) {
 2045: 	my $value;
 2046: 	if ($_ =~ /timestamp/) {
 2047: 	  $value=scalar(localtime($lasthash{$_}));
 2048: 	} else {
 2049: 	  $value=$lasthash{$_};
 2050: 	}
 2051: 	$value=&Apache::lonnet::unescape($value);
 2052: 	if ($_ =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
 2053: 	$prevattempts.='<td>'.$value.'&nbsp;</td>';
 2054:       }
 2055:       $prevattempts.='</tr></table></td></tr></table>';
 2056:     } else {
 2057:       $prevattempts='Nothing submitted - no attempts.';
 2058:     }
 2059:   } else {
 2060:     $prevattempts='No data.';
 2061:   }
 2062: }
 2063: 
 2064: sub relative_to_absolute {
 2065:     my ($url,$output)=@_;
 2066:     my $parser=HTML::TokeParser->new(\$output);
 2067:     my $token;
 2068:     my $thisdir=$url;
 2069:     my @rlinks=();
 2070:     while ($token=$parser->get_token) {
 2071: 	if ($token->[0] eq 'S') {
 2072: 	    if ($token->[1] eq 'a') {
 2073: 		if ($token->[2]->{'href'}) {
 2074: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 2075: 		}
 2076: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 2077: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 2078: 	    } elsif ($token->[1] eq 'base') {
 2079: 		$thisdir=$token->[2]->{'href'};
 2080: 	    }
 2081: 	}
 2082:     }
 2083:     $thisdir=~s-/[^/]*$--;
 2084:     foreach (@rlinks) {
 2085: 	unless (($_=~/^http:\/\//i) ||
 2086: 		($_=~/^\//) ||
 2087: 		($_=~/^javascript:/i) ||
 2088: 		($_=~/^mailto:/i) ||
 2089: 		($_=~/^\#/)) {
 2090: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$_);
 2091: 	    $output=~s/(\"|\'|\=\s*)$_(\"|\'|\s|\>)/$1$newlocation$2/;
 2092: 	}
 2093:     }
 2094: # -------------------------------------------------- Deal with Applet codebases
 2095:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 2096:     return $output;
 2097: }
 2098: 
 2099: =pod
 2100: 
 2101: =item * get_student_view
 2102: 
 2103: show a snapshot of what student was looking at
 2104: 
 2105: =cut
 2106: 
 2107: sub get_student_view {
 2108:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 2109:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 2110:   my (%form);
 2111:   my @elements=('symb','courseid','domain','username');
 2112:   foreach my $element (@elements) {
 2113:       $form{'grade_'.$element}=eval '$'.$element #'
 2114:   }
 2115:   if (defined($moreenv)) {
 2116:       %form=(%form,%{$moreenv});
 2117:   }
 2118:   if ($target eq 'tex') {$form{'grade_target'} = 'tex';}
 2119:   $feedurl=&Apache::lonnet::clutter($feedurl);
 2120:   my $userview=&Apache::lonnet::ssi_body($feedurl,%form);
 2121:   $userview=~s/\<body[^\>]*\>//gi;
 2122:   $userview=~s/\<\/body\>//gi;
 2123:   $userview=~s/\<html\>//gi;
 2124:   $userview=~s/\<\/html\>//gi;
 2125:   $userview=~s/\<head\>//gi;
 2126:   $userview=~s/\<\/head\>//gi;
 2127:   $userview=~s/action\s*\=/would_be_action\=/gi;
 2128:   $userview=&relative_to_absolute($feedurl,$userview);
 2129:   return $userview;
 2130: }
 2131: 
 2132: =pod
 2133: 
 2134: =item * get_student_answers() 
 2135: 
 2136: show a snapshot of how student was answering problem
 2137: 
 2138: =cut
 2139: 
 2140: sub get_student_answers {
 2141:   my ($symb,$username,$domain,$courseid,%form) = @_;
 2142:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 2143:   my (%moreenv);
 2144:   my @elements=('symb','courseid','domain','username');
 2145:   foreach my $element (@elements) {
 2146:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 2147:   }
 2148:   $moreenv{'grade_target'}='answer';
 2149:   %moreenv=(%form,%moreenv);
 2150:   my $userview=&Apache::lonnet::ssi('/res/'.$feedurl,%moreenv);
 2151:   return $userview;
 2152: }
 2153: 
 2154: =pod
 2155: 
 2156: =item * &submlink()
 2157: 
 2158: Inputs: $text $uname $udom $symb
 2159: 
 2160: Returns: A link to grades.pm such as to see the SUBM view of a student
 2161: 
 2162: =cut
 2163: 
 2164: ###############################################
 2165: sub submlink {
 2166:     my ($text,$uname,$udom,$symb)=@_;
 2167:     if (!($uname && $udom)) {
 2168: 	(my $cursymb, my $courseid,$udom,$uname)=
 2169: 	    &Apache::lonxml::whichuser($symb);
 2170: 	if (!$symb) { $symb=$cursymb; }
 2171:     }
 2172:     if (!$symb) { $symb=&symbread(); }
 2173:     return '<a href="/adm/grades?symb='.$symb.'&student='.$uname.
 2174: 	'&userdom='.$udom.'&command=submission">'.$text.'</a>';
 2175: }
 2176: ##############################################
 2177: 
 2178: =pod
 2179: 
 2180: =back
 2181: 
 2182: =cut
 2183: 
 2184: ###############################################
 2185: 
 2186: 
 2187: sub timehash {
 2188:     my @ltime=localtime(shift);
 2189:     return ( 'seconds' => $ltime[0],
 2190:              'minutes' => $ltime[1],
 2191:              'hours'   => $ltime[2],
 2192:              'day'     => $ltime[3],
 2193:              'month'   => $ltime[4]+1,
 2194:              'year'    => $ltime[5]+1900,
 2195:              'weekday' => $ltime[6],
 2196:              'dayyear' => $ltime[7]+1,
 2197:              'dlsav'   => $ltime[8] );
 2198: }
 2199: 
 2200: sub maketime {
 2201:     my %th=@_;
 2202:     return POSIX::mktime(
 2203:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 2204:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,$th{'dlsav'}));
 2205: }
 2206: 
 2207: #########################################
 2208: 
 2209: sub findallcourses {
 2210:     my %courses=();
 2211:     my $now=time;
 2212:     foreach (keys %ENV) {
 2213: 	if ($_=~/^user\.role\.\w+\.\/(\w+)\/(\w+)/) {
 2214: 	    my ($starttime,$endtime)=$ENV{$_};
 2215:             my $active=1;
 2216:             if ($starttime) {
 2217: 		if ($now<$starttime) { $active=0; }
 2218:             }
 2219:             if ($endtime) {
 2220:                 if ($now>$endtime) { $active=0; }
 2221:             }
 2222:             if ($active) { $courses{$1.'_'.$2}=1; }
 2223:         }
 2224:     }
 2225:     return keys %courses;
 2226: }
 2227: 
 2228: ###############################################
 2229: ###############################################
 2230: 
 2231: =pod
 2232: 
 2233: =head1 Domain Template Functions
 2234: 
 2235: =over 4
 2236: 
 2237: =item * &determinedomain()
 2238: 
 2239: Inputs: $domain (usually will be undef)
 2240: 
 2241: Returns: Determines which domain should be used for designs
 2242: 
 2243: =cut
 2244: 
 2245: ###############################################
 2246: sub determinedomain {
 2247:     my $domain=shift;
 2248:    if (! $domain) {
 2249:         # Determine domain if we have not been given one
 2250:         $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
 2251:         if ($ENV{'user.domain'}) { $domain=$ENV{'user.domain'}; }
 2252:         if ($ENV{'request.role.domain'}) { 
 2253:             $domain=$ENV{'request.role.domain'}; 
 2254:         }
 2255:     }
 2256:     return $domain;
 2257: }
 2258: ###############################################
 2259: =pod
 2260: 
 2261: =item * &domainlogo()
 2262: 
 2263: Inputs: $domain (usually will be undef)
 2264: 
 2265: Returns: A link to a domain logo, if the domain logo exists.
 2266: If the domain logo does not exist, a description of the domain.
 2267: 
 2268: =cut
 2269: 
 2270: ###############################################
 2271: sub domainlogo {
 2272:     my $domain = &determinedomain(shift);    
 2273:      # See if there is a logo
 2274:     if (-e '/home/httpd/html/adm/lonDomLogos/'.$domain.'.gif') {
 2275: 	my $lonhttpdPort=$Apache::lonnet::perlvar{'lonhttpdPort'};
 2276: 	if (!defined($lonhttpdPort)) { $lonhttpdPort='8080'; }
 2277:         return '<img src="http://'.$ENV{'HTTP_HOST'}.':'.$lonhttpdPort.
 2278: 	    '/adm/lonDomLogos/'.$domain.'.gif" alt="'.$domain.'" />';
 2279:     } elsif(exists($Apache::lonnet::domaindescription{$domain})) {
 2280:         return $Apache::lonnet::domaindescription{$domain};
 2281:     } else {
 2282:         return '';
 2283:     }
 2284: }
 2285: ##############################################
 2286: 
 2287: =pod
 2288: 
 2289: =item * &designparm()
 2290: 
 2291: Inputs: $which parameter; $domain (usually will be undef)
 2292: 
 2293: Returns: value of designparamter $which
 2294: 
 2295: =cut
 2296: 
 2297: ##############################################
 2298: sub designparm {
 2299:     my ($which,$domain)=@_;
 2300:     if ($ENV{'browser.blackwhite'} eq 'on') {
 2301: 	if ($which=~/\.(font|alink|vlink|link)$/) {
 2302: 	    return '#000000';
 2303: 	}
 2304: 	if ($which=~/\.(pgbg|sidebg)$/) {
 2305: 	    return '#FFFFFF';
 2306: 	}
 2307: 	if ($which=~/\.tabbg$/) {
 2308: 	    return '#CCCCCC';
 2309: 	}
 2310:     }
 2311:     if ($ENV{'environment.color.'.$which}) {
 2312: 	return $ENV{'environment.color.'.$which};
 2313:     }
 2314:     $domain=&determinedomain($domain);
 2315:     if ($designhash{$domain.'.'.$which}) {
 2316: 	return $designhash{$domain.'.'.$which};
 2317:     } else {
 2318:         return $designhash{'default.'.$which};
 2319:     }
 2320: }
 2321: 
 2322: ###############################################
 2323: ###############################################
 2324: 
 2325: =pod
 2326: 
 2327: =back
 2328: 
 2329: =head1 HTTP Helpers
 2330: 
 2331: =over 4
 2332: 
 2333: =item * &bodytag()
 2334: 
 2335: Returns a uniform header for LON-CAPA web pages.
 2336: 
 2337: Inputs: 
 2338: 
 2339: =over 4
 2340: 
 2341: =item * $title, A title to be displayed on the page.
 2342: 
 2343: =item * $function, the current role (can be undef).
 2344: 
 2345: =item * $addentries, extra parameters for the <body> tag.
 2346: 
 2347: =item * $bodyonly, if defined, only return the <body> tag.
 2348: 
 2349: =item * $domain, if defined, force a given domain.
 2350: 
 2351: =item * $forcereg, if page should register as content page (relevant for 
 2352:             text interface only)
 2353: 
 2354: =back
 2355: 
 2356: Returns: A uniform header for LON-CAPA web pages.  
 2357: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 2358: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 2359: other decorations will be returned.
 2360: 
 2361: =cut
 2362: 
 2363: sub bodytag {
 2364:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg)=@_;
 2365:     $title=&mt($title);
 2366:     $function = &get_users_function() if (!$function);
 2367:     my $img=&designparm($function.'.img',$domain);
 2368:     my $pgbg=&designparm($function.'.pgbg',$domain);
 2369:     my $tabbg=&designparm($function.'.tabbg',$domain);
 2370:     my $font=&designparm($function.'.font',$domain);
 2371:     my $link=&designparm($function.'.link',$domain);
 2372:     my $alink=&designparm($function.'.alink',$domain);
 2373:     my $vlink=&designparm($function.'.vlink',$domain);
 2374:     my $sidebg=&designparm($function.'.sidebg',$domain);
 2375: # Accessibility font enhance
 2376:     unless ($addentries) { $addentries=''; }
 2377:     my $addstyle='';
 2378:     if ($ENV{'browser.fontenhance'} eq 'on') {
 2379: 	$addstyle=' font-size: x-large;';
 2380:     }
 2381:  # role and realm
 2382:     my ($role,$realm)
 2383:        =&Apache::lonnet::plaintext((split(/\./,$ENV{'request.role'}))[0]);
 2384: # realm
 2385:     if ($ENV{'request.course.id'}) {
 2386: 	$realm=
 2387:          $ENV{'course.'.$ENV{'request.course.id'}.'.description'};
 2388:     }
 2389:     unless ($realm) { $realm='&nbsp;'; }
 2390: # Set messages
 2391:     my $messages=&domainlogo($domain);
 2392: # Port for miniserver
 2393:     my $lonhttpdPort=$Apache::lonnet::perlvar{'lonhttpdPort'};
 2394:     if (!defined($lonhttpdPort)) { $lonhttpdPort='8080'; }
 2395: # construct main body tag
 2396:     my $bodytag = <<END;
 2397: <style>
 2398: h1, h2, h3, th { font-family: Arial, Helvetica, sans-serif }
 2399: a:focus { color: red; background: yellow } 
 2400: </style>
 2401: <body bgcolor="$pgbg" text="$font" alink="$alink" vlink="$vlink" link="$link"
 2402: style="margin-top: 0px;$addstyle" $addentries>
 2403: END
 2404:     my $upperleft='<img src="http://'.$ENV{'HTTP_HOST'}.':'.
 2405:                    $lonhttpdPort.$img.'" alt="'.$function.'" />';
 2406:     if ($bodyonly) {
 2407:         return $bodytag;
 2408:     } elsif ($ENV{'browser.interface'} eq 'textual') {
 2409: # Accessibility
 2410:         return $bodytag.&Apache::lonmenu::menubuttons($forcereg,'web',
 2411:                                                       $forcereg).
 2412:                '<h1>LON-CAPA: '.$title.'</h1>';
 2413:     } elsif ($ENV{'environment.remote'} eq 'off') {
 2414: # No Remote
 2415:         return $bodytag.&Apache::lonmenu::menubuttons($forcereg,'web',
 2416:                                                       $forcereg).
 2417:       '<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.
 2418: '</b></font></td></tr></table>';
 2419:     }
 2420: 
 2421: #
 2422: # Top frame rendering, Remote is up
 2423: #
 2424:     return(<<ENDBODY);
 2425: $bodytag
 2426: <table width="100%" cellspacing="0" border="0" cellpadding="0">
 2427: <tr><td bgcolor="$sidebg">
 2428: $upperleft</td>
 2429: <td bgcolor="$sidebg" align="right">$messages&nbsp;</td>
 2430: </tr>
 2431: <tr>
 2432: <td rowspan="3" bgcolor="$tabbg">
 2433: &nbsp;<font size="5" face="Arial, Helvetica, sans-serif"><b>$title</b></font>
 2434: <td bgcolor="$tabbg" align="right">
 2435: <font size="2" face="Arial, Helvetica, sans-serif">
 2436:     $ENV{'environment.firstname'}
 2437:     $ENV{'environment.middlename'}
 2438:     $ENV{'environment.lastname'}
 2439:     $ENV{'environment.generation'}
 2440:     </font>&nbsp;
 2441: </td>
 2442: </tr>
 2443: <tr><td bgcolor="$tabbg" align="right">
 2444: <font size="2" face="Arial, Helvetica, sans-serif">$role</font>&nbsp;
 2445: </td></tr>
 2446: <tr>
 2447: <td bgcolor="$tabbg" align="right"><font size="2" face="Arial, Helvetica, sans-serif">$realm</font>&nbsp;</td></tr>
 2448: </table><br>
 2449: ENDBODY
 2450: }
 2451: 
 2452: ###############################################
 2453: 
 2454: =pod
 2455: 
 2456: =item get_users_function
 2457: 
 2458: Used by &bodytag to determine the current users primary role.
 2459: Returns either 'student','coordinator','admin', or 'author'.
 2460: 
 2461: =cut
 2462: 
 2463: ###############################################
 2464: sub get_users_function {
 2465:     my $function = 'student';
 2466:     if ($ENV{'request.role'}=~/^(cc|in|ta|ep)/) {
 2467:         $function='coordinator';
 2468:     }
 2469:     if ($ENV{'request.role'}=~/^(su|dc|ad|li)/) {
 2470:         $function='admin';
 2471:     }
 2472:     if (($ENV{'request.role'}=~/^(au|ca)/) ||
 2473:         ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
 2474:         $function='author';
 2475:     }
 2476:     return $function;
 2477: }
 2478: 
 2479: ###############################################
 2480: 
 2481: sub get_posted_cgi {
 2482:     my $r=shift;
 2483: 
 2484:     my $buffer;
 2485:     
 2486:     $r->read($buffer,$r->header_in('Content-length'),0);
 2487:     unless ($buffer=~/^(\-+\w+)\s+Content\-Disposition\:\s*form\-data/si) {
 2488: 	my @pairs=split(/&/,$buffer);
 2489: 	my $pair;
 2490: 	foreach $pair (@pairs) {
 2491: 	    my ($name,$value) = split(/=/,$pair);
 2492: 	    $value =~ tr/+/ /;
 2493: 	    $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 2494: 	    $name  =~ tr/+/ /;
 2495: 	    $name  =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 2496: 	    &add_to_env("form.$name",$value);
 2497: 	}
 2498:     } else {
 2499: 	my $contentsep=$1;
 2500: 	my @lines = split (/\n/,$buffer);
 2501: 	my $name='';
 2502: 	my $value='';
 2503: 	my $fname='';
 2504: 	my $fmime='';
 2505: 	my $i;
 2506: 	for ($i=0;$i<=$#lines;$i++) {
 2507: 	    if ($lines[$i]=~/^$contentsep/) {
 2508: 		if ($name) {
 2509: 		    chomp($value);
 2510: 		    if ($fname) {
 2511: 			$ENV{"form.$name.filename"}=$fname;
 2512: 			$ENV{"form.$name.mimetype"}=$fmime;
 2513: 		    } else {
 2514: 			$value=~s/\s+$//s;
 2515: 		    }
 2516: 		    &add_to_env("form.$name",$value);
 2517: 		}
 2518: 		if ($i<$#lines) {
 2519: 		    $i++;
 2520: 		    $lines[$i]=~
 2521: 		/Content\-Disposition\:\s*form\-data\;\s*name\=\"([^\"]+)\"/i;
 2522: 		    $name=$1;
 2523: 		    $value='';
 2524: 		    if ($lines[$i]=~/filename\=\"([^\"]+)\"/i) {
 2525: 			$fname=$1;
 2526: 			if 
 2527:                             ($lines[$i+1]=~/Content\-Type\:\s*([\w\-\/]+)/i) {
 2528: 				$fmime=$1;
 2529: 				$i++;
 2530: 			    } else {
 2531: 				$fmime='';
 2532: 			    }
 2533: 		    } else {
 2534: 			$fname='';
 2535: 			$fmime='';
 2536: 		    }
 2537: 		    $i++;
 2538: 		}
 2539: 	    } else {
 2540: 		$value.=$lines[$i]."\n";
 2541: 	    }
 2542: 	}
 2543:     }
 2544:     $ENV{'request.method'}=$ENV{'REQUEST_METHOD'};
 2545:     $r->method_number(M_GET);
 2546:     $r->method('GET');
 2547:     $r->headers_in->unset('Content-length');
 2548: }
 2549: 
 2550: =pod
 2551: 
 2552: =item * get_unprocessed_cgi($query,$possible_names)
 2553: 
 2554: Modify the %ENV hash to contain unprocessed CGI form parameters held in
 2555: $query.  The parameters listed in $possible_names (an array reference),
 2556: will be set in $ENV{'form.name'} if they do not already exist.
 2557: 
 2558: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
 2559: $possible_names is an ref to an array of form element names.  As an example:
 2560: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
 2561: will result in $ENV{'form.uname'} and $ENV{'form.udom'} being set.
 2562: 
 2563: =cut
 2564: 
 2565: sub get_unprocessed_cgi {
 2566:   my ($query,$possible_names)= @_;
 2567:   # $Apache::lonxml::debug=1;
 2568:   foreach (split(/&/,$query)) {
 2569:     my ($name, $value) = split(/=/,$_);
 2570:     $name = &Apache::lonnet::unescape($name);
 2571:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
 2572:       $value =~ tr/+/ /;
 2573:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 2574:       &Apache::lonxml::debug("Seting :$name: to :$value:");
 2575:       unless (defined($ENV{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
 2576:     }
 2577:   }
 2578: }
 2579: 
 2580: =pod
 2581: 
 2582: =item * cacheheader() 
 2583: 
 2584: returns cache-controlling header code
 2585: 
 2586: =cut
 2587: 
 2588: sub cacheheader {
 2589:   unless ($ENV{'request.method'} eq 'GET') { return ''; }
 2590:   my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 2591:   my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
 2592:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
 2593:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
 2594:   return $output;
 2595: }
 2596: 
 2597: =pod
 2598: 
 2599: =item * no_cache($r) 
 2600: 
 2601: specifies header code to not have cache
 2602: 
 2603: =cut
 2604: 
 2605: sub no_cache {
 2606:   my ($r) = @_;
 2607:   unless ($ENV{'request.method'} eq 'GET') { return ''; }
 2608:   #my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 2609:   $r->no_cache(1);
 2610:   $r->header_out("Pragma" => "no-cache");
 2611:   #$r->header_out("Expires" => $date);
 2612: }
 2613: 
 2614: sub content_type {
 2615:     my ($r,$type,$charset) = @_;
 2616:     unless ($charset) {
 2617: 	$charset=&Apache::lonlocal::current_encoding;
 2618:     }
 2619:     if ($charset) { $type.='; charset='.$charset; }
 2620:     if ($r) {
 2621: 	$r->content_type($type);
 2622:     } else {
 2623: 	print("Content-type: $type\n\n");
 2624:     }
 2625: }
 2626: 
 2627: =pod
 2628: 
 2629: =item * add_to_env($name,$value) 
 2630: 
 2631: adds $name to the %ENV hash with value
 2632: $value, if $name already exists, the entry is converted to an array
 2633: reference and $value is added to the array.
 2634: 
 2635: =cut
 2636: 
 2637: sub add_to_env {
 2638:   my ($name,$value)=@_;
 2639:   if (defined($ENV{$name})) {
 2640:     if (ref($ENV{$name})) {
 2641:       #already have multiple values
 2642:       push(@{ $ENV{$name} },$value);
 2643:     } else {
 2644:       #first time seeing multiple values, convert hash entry to an arrayref
 2645:       my $first=$ENV{$name};
 2646:       undef($ENV{$name});
 2647:       push(@{ $ENV{$name} },$first,$value);
 2648:     }
 2649:   } else {
 2650:     $ENV{$name}=$value;
 2651:   }
 2652: }
 2653: 
 2654: =pod
 2655: 
 2656: =item * get_env_multiple($name) 
 2657: 
 2658: gets $name from the %ENV hash, it seemlessly handles the cases where multiple
 2659: values may be defined and end up as an array ref.
 2660: 
 2661: returns an array of values
 2662: 
 2663: =cut
 2664: 
 2665: sub get_env_multiple {
 2666:     my ($name) = @_;
 2667:     my @values;
 2668:     if (defined($ENV{$name})) {
 2669:         # exists is it an array
 2670:         if (ref($ENV{$name})) {
 2671:             @values=@{ $ENV{$name} };
 2672:         } else {
 2673:             $values[0]=$ENV{$name};
 2674:         }
 2675:     }
 2676:     return(@values);
 2677: }
 2678: 
 2679: 
 2680: =pod
 2681: 
 2682: =back 
 2683: 
 2684: =head1 CSV Upload/Handling functions
 2685: 
 2686: =over 4
 2687: 
 2688: =item * upfile_store($r)
 2689: 
 2690: Store uploaded file, $r should be the HTTP Request object,
 2691: needs $ENV{'form.upfile'}
 2692: returns $datatoken to be put into hidden field
 2693: 
 2694: =cut
 2695: 
 2696: sub upfile_store {
 2697:     my $r=shift;
 2698:     $ENV{'form.upfile'}=~s/\r/\n/gs;
 2699:     $ENV{'form.upfile'}=~s/\f/\n/gs;
 2700:     $ENV{'form.upfile'}=~s/\n+/\n/gs;
 2701:     $ENV{'form.upfile'}=~s/\n+$//gs;
 2702: 
 2703:     my $datatoken=$ENV{'user.name'}.'_'.$ENV{'user.domain'}.
 2704: 	'_enroll_'.$ENV{'request.course.id'}.'_'.time.'_'.$$;
 2705:     {
 2706:         my $datafile = $r->dir_config('lonDaemons').
 2707:                            '/tmp/'.$datatoken.'.tmp';
 2708:         if ( open(my $fh,">$datafile") ) {
 2709:             print $fh $ENV{'form.upfile'};
 2710:             close($fh);
 2711:         }
 2712:     }
 2713:     return $datatoken;
 2714: }
 2715: 
 2716: =pod
 2717: 
 2718: =item * load_tmp_file($r)
 2719: 
 2720: Load uploaded file from tmp, $r should be the HTTP Request object,
 2721: needs $ENV{'form.datatoken'},
 2722: sets $ENV{'form.upfile'} to the contents of the file
 2723: 
 2724: =cut
 2725: 
 2726: sub load_tmp_file {
 2727:     my $r=shift;
 2728:     my @studentdata=();
 2729:     {
 2730:         my $studentfile = $r->dir_config('lonDaemons').
 2731:                               '/tmp/'.$ENV{'form.datatoken'}.'.tmp';
 2732:         if ( open(my $fh,"<$studentfile") ) {
 2733:             @studentdata=<$fh>;
 2734:             close($fh);
 2735:         }
 2736:     }
 2737:     $ENV{'form.upfile'}=join('',@studentdata);
 2738: }
 2739: 
 2740: =pod
 2741: 
 2742: =item * upfile_record_sep()
 2743: 
 2744: Separate uploaded file into records
 2745: returns array of records,
 2746: needs $ENV{'form.upfile'} and $ENV{'form.upfiletype'}
 2747: 
 2748: =cut
 2749: 
 2750: sub upfile_record_sep {
 2751:     if ($ENV{'form.upfiletype'} eq 'xml') {
 2752:     } else {
 2753: 	return split(/\n/,$ENV{'form.upfile'});
 2754:     }
 2755: }
 2756: 
 2757: =pod
 2758: 
 2759: =item * record_sep($record)
 2760: 
 2761: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $ENV{'form.upfiletype'}
 2762: 
 2763: =cut
 2764: 
 2765: sub record_sep {
 2766:     my $record=shift;
 2767:     my %components=();
 2768:     if ($ENV{'form.upfiletype'} eq 'xml') {
 2769:     } elsif ($ENV{'form.upfiletype'} eq 'space') {
 2770:         my $i=0;
 2771:         foreach (split(/\s+/,$record)) {
 2772:             my $field=$_;
 2773:             $field=~s/^(\"|\')//;
 2774:             $field=~s/(\"|\')$//;
 2775:             $components{$i}=$field;
 2776:             $i++;
 2777:         }
 2778:     } elsif ($ENV{'form.upfiletype'} eq 'tab') {
 2779:         my $i=0;
 2780:         foreach (split(/\t/,$record)) {
 2781:             my $field=$_;
 2782:             $field=~s/^(\"|\')//;
 2783:             $field=~s/(\"|\')$//;
 2784:             $components{$i}=$field;
 2785:             $i++;
 2786:         }
 2787:     } else {
 2788:         my @allfields=split(/\,/,$record);
 2789:         my $i=0;
 2790:         my $j;
 2791:         for ($j=0;$j<=$#allfields;$j++) {
 2792:             my $field=$allfields[$j];
 2793:             if ($field=~/^\s*(\"|\')/) {
 2794: 		my $delimiter=$1;
 2795:                 while (($field!~/$delimiter$/) && ($j<$#allfields)) {
 2796: 		    $j++;
 2797: 		    $field.=','.$allfields[$j];
 2798: 		}
 2799:                 $field=~s/^\s*$delimiter//;
 2800:                 $field=~s/$delimiter\s*$//;
 2801:             }
 2802:             $components{$i}=$field;
 2803: 	    $i++;
 2804:         }
 2805:     }
 2806:     return %components;
 2807: }
 2808: 
 2809: ######################################################
 2810: ######################################################
 2811: 
 2812: =pod
 2813: 
 2814: =item * upfile_select_html()
 2815: 
 2816: Return HTML code to select a file from the users machine and specify 
 2817: the file type.
 2818: 
 2819: =cut
 2820: 
 2821: ######################################################
 2822: ######################################################
 2823: sub upfile_select_html {
 2824:     my %Types = (
 2825:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
 2826:                  space => &mt('Space separated'),
 2827:                  tab   => &mt('Tabulator separated'),
 2828: #                 xml   => &mt('HTML/XML'),
 2829:                  );
 2830:     my $Str = '<input type="file" name="upfile" size="50" />'.
 2831:         '<br />Type: <select name="upfiletype">';
 2832:     foreach my $type (sort(keys(%Types))) {
 2833:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
 2834:     }
 2835:     $Str .= "</select>\n";
 2836:     return $Str;
 2837: }
 2838: 
 2839: ######################################################
 2840: ######################################################
 2841: 
 2842: =pod
 2843: 
 2844: =item * csv_print_samples($r,$records)
 2845: 
 2846: Prints a table of sample values from each column uploaded $r is an
 2847: Apache Request ref, $records is an arrayref from
 2848: &Apache::loncommon::upfile_record_sep
 2849: 
 2850: =cut
 2851: 
 2852: ######################################################
 2853: ######################################################
 2854: sub csv_print_samples {
 2855:     my ($r,$records) = @_;
 2856:     my (%sone,%stwo,%sthree);
 2857:     %sone=&record_sep($$records[0]);
 2858:     if (defined($$records[1])) {%stwo=&record_sep($$records[1]);}
 2859:     if (defined($$records[2])) {%sthree=&record_sep($$records[2]);}
 2860:     #
 2861:     $r->print(&mt('Samples').'<br /><table border="2"><tr>');
 2862:     foreach (sort({$a <=> $b} keys(%sone))) { 
 2863:         $r->print('<th>'.&mt('Column&nbsp;[_1]',($_+1)).'</th>'); }
 2864:     $r->print('</tr>');
 2865:     foreach my $hash (\%sone,\%stwo,\%sthree) {
 2866: 	$r->print('<tr>');
 2867: 	foreach (sort({$a <=> $b} keys(%sone))) {
 2868: 	    $r->print('<td>');
 2869: 	    if (defined($$hash{$_})) { $r->print($$hash{$_}); }
 2870: 	    $r->print('</td>');
 2871: 	}
 2872: 	$r->print('</tr>');
 2873:     }
 2874:     $r->print('</tr></table><br />'."\n");
 2875: }
 2876: 
 2877: ######################################################
 2878: ######################################################
 2879: 
 2880: =pod
 2881: 
 2882: =item * csv_print_select_table($r,$records,$d)
 2883: 
 2884: Prints a table to create associations between values and table columns.
 2885: 
 2886: $r is an Apache Request ref,
 2887: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 2888: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
 2889: 
 2890: =cut
 2891: 
 2892: ######################################################
 2893: ######################################################
 2894: sub csv_print_select_table {
 2895:     my ($r,$records,$d) = @_;
 2896:     my $i=0;my %sone;
 2897:     %sone=&record_sep($$records[0]);
 2898:     $r->print(&mt('Associate columns with student attributes.')."\n".
 2899: 	     '<table border="2"><tr>'.
 2900:               '<th>'.&mt('Attribute').'</th>'.
 2901:               '<th>'.&mt('Column').'</th></tr>'."\n");
 2902:     foreach (@$d) {
 2903: 	my ($value,$display,$defaultcol)=@{ $_ };
 2904: 	$r->print('<tr><td>'.$display.'</td>');
 2905: 
 2906: 	$r->print('<td><select name=f'.$i.
 2907: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 2908: 	$r->print('<option value="none"></option>');
 2909: 	foreach (sort({$a <=> $b} keys(%sone))) {
 2910: 	    $r->print('<option value="'.$_.'"'.
 2911:                       ($_ eq $defaultcol ? ' selected ' : '').
 2912:                       '>Column '.($_+1).'</option>');
 2913: 	}
 2914: 	$r->print('</select></td></tr>'."\n");
 2915: 	$i++;
 2916:     }
 2917:     $i--;
 2918:     return $i;
 2919: }
 2920: 
 2921: ######################################################
 2922: ######################################################
 2923: 
 2924: =pod
 2925: 
 2926: =item * csv_samples_select_table($r,$records,$d)
 2927: 
 2928: Prints a table of sample values from the upload and can make associate samples to internal names.
 2929: 
 2930: $r is an Apache Request ref,
 2931: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 2932: $d is an array of 2 element arrays (internal name, displayed name)
 2933: 
 2934: =cut
 2935: 
 2936: ######################################################
 2937: ######################################################
 2938: sub csv_samples_select_table {
 2939:     my ($r,$records,$d) = @_;
 2940:     my %sone; my %stwo; my %sthree;
 2941:     my $i=0;
 2942:     #
 2943:     $r->print('<table border=2><tr><th>'.
 2944:               &mt('Field').'</th><th>'.&mt('Samples').'</th></tr>');
 2945:     %sone=&record_sep($$records[0]);
 2946:     if (defined($$records[1])) {%stwo=&record_sep($$records[1]);}
 2947:     if (defined($$records[2])) {%sthree=&record_sep($$records[2]);}
 2948:     #
 2949:     foreach (sort keys %sone) {
 2950: 	$r->print('<tr><td><select name="f'.$i.'"'.
 2951: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 2952: 	foreach (@$d) {
 2953: 	    my ($value,$display,$defaultcol)=@{ $_ };
 2954: 	    $r->print('<option value="'.$value.'"'.
 2955:                       ($i eq $defaultcol ? ' selected ':'').'>'.
 2956:                       $display.'</option>');
 2957: 	}
 2958: 	$r->print('</select></td><td>');
 2959: 	if (defined($sone{$_})) { $r->print($sone{$_}."</br>\n"); }
 2960: 	if (defined($stwo{$_})) { $r->print($stwo{$_}."</br>\n"); }
 2961: 	if (defined($sthree{$_})) { $r->print($sthree{$_}."</br>\n"); }
 2962: 	$r->print('</td></tr>');
 2963: 	$i++;
 2964:     }
 2965:     $i--;
 2966:     return($i);
 2967: }
 2968: 
 2969: ######################################################
 2970: ######################################################
 2971: 
 2972: =pod
 2973: 
 2974: =item clean_excel_name($name)
 2975: 
 2976: Returns a replacement for $name which does not contain any illegal characters.
 2977: 
 2978: =cut
 2979: 
 2980: ######################################################
 2981: ######################################################
 2982: sub clean_excel_name {
 2983:     my ($name) = @_;
 2984:     $name =~ s/[:\*\?\/\\]//g;
 2985:     if (length($name) > 31) {
 2986:         $name = substr($name,0,31);
 2987:     }
 2988:     return $name;
 2989: }
 2990: 
 2991: =pod
 2992: 
 2993: =item * check_if_partid_hidden($id,$symb,$udom,$uname)
 2994: 
 2995: Returns either 1 or undef
 2996: 
 2997: 1 if the part is to be hidden, undef if it is to be shown
 2998: 
 2999: Arguments are:
 3000: 
 3001: $id the id of the part to be checked
 3002: $symb, optional the symb of the resource to check
 3003: $udom, optional the domain of the user to check for
 3004: $uname, optional the username of the user to check for
 3005: 
 3006: =cut
 3007: 
 3008: sub check_if_partid_hidden {
 3009:     my ($id,$symb,$udom,$uname) = @_;
 3010:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
 3011: 					 $symb,$udom,$uname);
 3012:     my $truth=1;
 3013:     #if the string starts with !, then the list is the list to show not hide
 3014:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
 3015:     my @hiddenlist=split(/,/,$hiddenparts);
 3016:     foreach my $checkid (@hiddenlist) {
 3017: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
 3018:     }
 3019:     return !$truth;
 3020: }
 3021: 
 3022: 
 3023: ############################################################
 3024: ############################################################
 3025: 
 3026: =pod
 3027: 
 3028: =back 
 3029: 
 3030: =head1 cgi-bin script and graphing routines
 3031: 
 3032: =over 4
 3033: 
 3034: =item get_cgi_id
 3035: 
 3036: Inputs: none
 3037: 
 3038: Returns an id which can be used to pass environment variables
 3039: to various cgi-bin scripts.  These environment variables will
 3040: be removed from the users environment after a given time by
 3041: the routine &Apache::lonnet::transfer_profile_to_env.
 3042: 
 3043: =cut
 3044: 
 3045: ############################################################
 3046: ############################################################
 3047: my $uniq=0;
 3048: sub get_cgi_id {
 3049:     $uniq=($uniq+1)%100000;
 3050:     return (time.'_'.$uniq);
 3051: }
 3052: 
 3053: ############################################################
 3054: ############################################################
 3055: 
 3056: =pod
 3057: 
 3058: =item DrawBarGraph
 3059: 
 3060: Facilitates the plotting of data in a (stacked) bar graph.
 3061: Puts plot definition data into the users environment in order for 
 3062: graph.png to plot it.  Returns an <img> tag for the plot.
 3063: The bars on the plot are labeled '1','2',...,'n'.
 3064: 
 3065: Inputs:
 3066: 
 3067: =over 4
 3068: 
 3069: =item $Title: string, the title of the plot
 3070: 
 3071: =item $xlabel: string, text describing the X-axis of the plot
 3072: 
 3073: =item $ylabel: string, text describing the Y-axis of the plot
 3074: 
 3075: =item $Max: scalar, the maximum Y value to use in the plot
 3076: If $Max is < any data point, the graph will not be rendered.
 3077: 
 3078: =item $colors: array ref holding the colors to be used for the data sets when
 3079: they are plotted.  If undefined, default values will be used.
 3080: 
 3081: =item $labels: array ref holding the labels to use on the x-axis for the bars.
 3082: 
 3083: =item @Values: An array of array references.  Each array reference holds data
 3084: to be plotted in a stacked bar chart.
 3085: 
 3086: =back
 3087: 
 3088: Returns:
 3089: 
 3090: An <img> tag which references graph.png and the appropriate identifying
 3091: information for the plot.
 3092: 
 3093: =cut
 3094: 
 3095: ############################################################
 3096: ############################################################
 3097: sub DrawBarGraph {
 3098:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
 3099:     #
 3100:     if (! defined($colors)) {
 3101:         $colors = ['#33ff00', 
 3102:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
 3103:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
 3104:                   ]; 
 3105:     }
 3106:     #
 3107:     my $identifier = &get_cgi_id();
 3108:     my $id = 'cgi.'.$identifier;        
 3109:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
 3110:         return '';
 3111:     }
 3112:     my $NumBars = scalar(@{$Values[0]});
 3113:     my %ValuesHash;
 3114:     my $NumSets=1;
 3115:     foreach my $array (@Values) {
 3116:         next if (! ref($array));
 3117:         $ValuesHash{$id.'.data.'.$NumSets++} = 
 3118:             join(',',@$array);
 3119:     }
 3120:     #
 3121:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
 3122:     if ($NumBars < 10) {
 3123:         $width = 120+$NumBars*15;
 3124:         $xskip = 1;
 3125:         $bar_width = 15;
 3126:     } elsif ($NumBars <= 25) {
 3127:         $width = 120+$NumBars*11;
 3128:         $xskip = 5;
 3129:         $bar_width = 8;
 3130:     } elsif ($NumBars <= 50) {
 3131:         $width = 120+$NumBars*8;
 3132:         $xskip = 5;
 3133:         $bar_width = 4;
 3134:     } else {
 3135:         $width = 120+$NumBars*8;
 3136:         $xskip = 5;
 3137:         $bar_width = 4;
 3138:     }
 3139:     #
 3140:     my @Labels;
 3141:     if (defined($labels)) {
 3142:         @Labels = @$labels;
 3143:     } else {
 3144:         for (my $i=0;$i<@{$Values[0]};$i++) {
 3145:             push (@Labels,$i+1);
 3146:         }
 3147:     }
 3148:     #
 3149:     $Max = 1 if ($Max < 1);
 3150:     if ( int($Max) < $Max ) {
 3151:         $Max++;
 3152:         $Max = int($Max);
 3153:     }
 3154:     $Title  = '' if (! defined($Title));
 3155:     $xlabel = '' if (! defined($xlabel));
 3156:     $ylabel = '' if (! defined($ylabel));
 3157:     $ValuesHash{$id.'.title'}    = &Apache::lonnet::escape($Title);
 3158:     $ValuesHash{$id.'.xlabel'}   = &Apache::lonnet::escape($xlabel);
 3159:     $ValuesHash{$id.'.ylabel'}   = &Apache::lonnet::escape($ylabel);
 3160:     $ValuesHash{$id.'.y_max_value'} = $Max;
 3161:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
 3162:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
 3163:     $ValuesHash{$id.'.PlotType'} = 'bar';
 3164:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 3165:     $ValuesHash{$id.'.height'}   = $height;
 3166:     $ValuesHash{$id.'.width'}    = $width;
 3167:     $ValuesHash{$id.'.xskip'}    = $xskip;
 3168:     $ValuesHash{$id.'.bar_width'} = $bar_width;
 3169:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
 3170:     #
 3171:     &Apache::lonnet::appenv(%ValuesHash);
 3172:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 3173: }
 3174: 
 3175: ############################################################
 3176: ############################################################
 3177: 
 3178: =pod
 3179: 
 3180: =item DrawXYGraph
 3181: 
 3182: Facilitates the plotting of data in an XY graph.
 3183: Puts plot definition data into the users environment in order for 
 3184: graph.png to plot it.  Returns an <img> tag for the plot.
 3185: 
 3186: Inputs:
 3187: 
 3188: =over 4
 3189: 
 3190: =item $Title: string, the title of the plot
 3191: 
 3192: =item $xlabel: string, text describing the X-axis of the plot
 3193: 
 3194: =item $ylabel: string, text describing the Y-axis of the plot
 3195: 
 3196: =item $Max: scalar, the maximum Y value to use in the plot
 3197: If $Max is < any data point, the graph will not be rendered.
 3198: 
 3199: =item $colors: Array ref containing the hex color codes for the data to be 
 3200: plotted in.  If undefined, default values will be used.
 3201: 
 3202: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 3203: 
 3204: =item $Ydata: Array ref containing Array refs.  
 3205: Each of the contained arrays will be plotted as a separate curve.
 3206: 
 3207: =item %Values: hash indicating or overriding any default values which are 
 3208: passed to graph.png.  
 3209: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 3210: 
 3211: =back
 3212: 
 3213: Returns:
 3214: 
 3215: An <img> tag which references graph.png and the appropriate identifying
 3216: information for the plot.
 3217: 
 3218: =cut
 3219: 
 3220: ############################################################
 3221: ############################################################
 3222: sub DrawXYGraph {
 3223:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
 3224:     #
 3225:     # Create the identifier for the graph
 3226:     my $identifier = &get_cgi_id();
 3227:     my $id = 'cgi.'.$identifier;
 3228:     #
 3229:     $Title  = '' if (! defined($Title));
 3230:     $xlabel = '' if (! defined($xlabel));
 3231:     $ylabel = '' if (! defined($ylabel));
 3232:     my %ValuesHash = 
 3233:         (
 3234:          $id.'.title'  => &Apache::lonnet::escape($Title),
 3235:          $id.'.xlabel' => &Apache::lonnet::escape($xlabel),
 3236:          $id.'.ylabel' => &Apache::lonnet::escape($ylabel),
 3237:          $id.'.y_max_value'=> $Max,
 3238:          $id.'.labels'     => join(',',@$Xlabels),
 3239:          $id.'.PlotType'   => 'XY',
 3240:          );
 3241:     #
 3242:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 3243:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 3244:     }
 3245:     #
 3246:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
 3247:         return '';
 3248:     }
 3249:     my $NumSets=1;
 3250:     foreach my $array (@{$Ydata}){
 3251:         next if (! ref($array));
 3252:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 3253:     }
 3254:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
 3255:     #
 3256:     # Deal with other parameters
 3257:     while (my ($key,$value) = each(%Values)) {
 3258:         $ValuesHash{$id.'.'.$key} = $value;
 3259:     }
 3260:     #
 3261:     &Apache::lonnet::appenv(%ValuesHash);
 3262:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 3263: }
 3264: 
 3265: ############################################################
 3266: ############################################################
 3267: 
 3268: =pod
 3269: 
 3270: =item DrawXYYGraph
 3271: 
 3272: Facilitates the plotting of data in an XY graph with two Y axes.
 3273: Puts plot definition data into the users environment in order for 
 3274: graph.png to plot it.  Returns an <img> tag for the plot.
 3275: 
 3276: Inputs:
 3277: 
 3278: =over 4
 3279: 
 3280: =item $Title: string, the title of the plot
 3281: 
 3282: =item $xlabel: string, text describing the X-axis of the plot
 3283: 
 3284: =item $ylabel: string, text describing the Y-axis of the plot
 3285: 
 3286: =item $colors: Array ref containing the hex color codes for the data to be 
 3287: plotted in.  If undefined, default values will be used.
 3288: 
 3289: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 3290: 
 3291: =item $Ydata1: The first data set
 3292: 
 3293: =item $Min1: The minimum value of the left Y-axis
 3294: 
 3295: =item $Max1: The maximum value of the left Y-axis
 3296: 
 3297: =item $Ydata2: The second data set
 3298: 
 3299: =item $Min2: The minimum value of the right Y-axis
 3300: 
 3301: =item $Max2: The maximum value of the left Y-axis
 3302: 
 3303: =item %Values: hash indicating or overriding any default values which are 
 3304: passed to graph.png.  
 3305: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 3306: 
 3307: =back
 3308: 
 3309: Returns:
 3310: 
 3311: An <img> tag which references graph.png and the appropriate identifying
 3312: information for the plot.
 3313: 
 3314: =cut
 3315: 
 3316: ############################################################
 3317: ############################################################
 3318: sub DrawXYYGraph {
 3319:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
 3320:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
 3321:     #
 3322:     # Create the identifier for the graph
 3323:     my $identifier = &get_cgi_id();
 3324:     my $id = 'cgi.'.$identifier;
 3325:     #
 3326:     $Title  = '' if (! defined($Title));
 3327:     $xlabel = '' if (! defined($xlabel));
 3328:     $ylabel = '' if (! defined($ylabel));
 3329:     my %ValuesHash = 
 3330:         (
 3331:          $id.'.title'  => &Apache::lonnet::escape($Title),
 3332:          $id.'.xlabel' => &Apache::lonnet::escape($xlabel),
 3333:          $id.'.ylabel' => &Apache::lonnet::escape($ylabel),
 3334:          $id.'.labels' => join(',',@$Xlabels),
 3335:          $id.'.PlotType' => 'XY',
 3336:          $id.'.NumSets' => 2,
 3337:          $id.'.two_axes' => 1,
 3338:          $id.'.y1_max_value' => $Max1,
 3339:          $id.'.y1_min_value' => $Min1,
 3340:          $id.'.y2_max_value' => $Max2,
 3341:          $id.'.y2_min_value' => $Min2,
 3342:          );
 3343:     #
 3344:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 3345:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 3346:     }
 3347:     #
 3348:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
 3349:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
 3350:         return '';
 3351:     }
 3352:     my $NumSets=1;
 3353:     foreach my $array ($Ydata1,$Ydata2){
 3354:         next if (! ref($array));
 3355:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 3356:     }
 3357:     #
 3358:     # Deal with other parameters
 3359:     while (my ($key,$value) = each(%Values)) {
 3360:         $ValuesHash{$id.'.'.$key} = $value;
 3361:     }
 3362:     #
 3363:     &Apache::lonnet::appenv(%ValuesHash);
 3364:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 3365: }
 3366: 
 3367: ############################################################
 3368: ############################################################
 3369: 
 3370: =pod
 3371: 
 3372: =back 
 3373: 
 3374: =head1 Statistics helper routines?  
 3375: 
 3376: Bad place for them but what the hell.
 3377: 
 3378: =over 4
 3379: 
 3380: =item &chartlink
 3381: 
 3382: Returns a link to the chart for a specific student.  
 3383: 
 3384: Inputs:
 3385: 
 3386: =over 4
 3387: 
 3388: =item $linktext: The text of the link
 3389: 
 3390: =item $sname: The students username
 3391: 
 3392: =item $sdomain: The students domain
 3393: 
 3394: =back
 3395: 
 3396: =back
 3397: 
 3398: =cut
 3399: 
 3400: ############################################################
 3401: ############################################################
 3402: sub chartlink {
 3403:     my ($linktext, $sname, $sdomain) = @_;
 3404:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
 3405:         '&SelectedStudent='.&Apache::lonnet::escape($sname.':'.$sdomain).
 3406:         '&chartoutputmode='.HTML::Entities::encode('html, with all links').
 3407:        '">'.$linktext.'</a>';
 3408: }
 3409: 
 3410: #######################################################
 3411: #######################################################
 3412: 
 3413: =pod
 3414: 
 3415: =head1 Course Environment Routines
 3416: 
 3417: =over 4
 3418: 
 3419: =item &restore_course_settings 
 3420: 
 3421: =item &store_course_settings
 3422: 
 3423: Restores/Store indicated form parameters from the course environment.
 3424: Will not overwrite existing values of the form parameters.
 3425: 
 3426: Inputs: 
 3427: a scalar describing the data (e.g. 'chart', 'problem_analysis')
 3428: 
 3429: a hash ref describing the data to be stored.  For example:
 3430:    
 3431: %Save_Parameters = ('Status' => 'scalar',
 3432:     'chartoutputmode' => 'scalar',
 3433:     'chartoutputdata' => 'scalar',
 3434:     'Section' => 'array',
 3435:     'StudentData' => 'array',
 3436:     'Maps' => 'array');
 3437: 
 3438: Returns: both routines return nothing
 3439: 
 3440: =cut
 3441: 
 3442: #######################################################
 3443: #######################################################
 3444: sub store_course_settings {
 3445:     # save to the environment
 3446:     # appenv the same items, just to be safe
 3447:     my $courseid = $ENV{'request.course.id'};
 3448:     my $coursedom = $ENV{'course.'.$courseid.'.domain'};
 3449:     my ($prefix,$Settings) = @_;
 3450:     my %SaveHash;
 3451:     my %AppHash;
 3452:     while (my ($setting,$type) = each(%$Settings)) {
 3453:         my $basename = 'internal.'.$prefix.'.'.$setting;
 3454:         my $envname = 'course.'.$courseid.'.'.$basename;
 3455:         if (exists($ENV{'form.'.$setting})) {
 3456:             # Save this value away
 3457:             if ($type eq 'scalar' &&
 3458:                 (! exists($ENV{$envname}) || 
 3459:                  $ENV{$envname} ne $ENV{'form.'.$setting})) {
 3460:                 $SaveHash{$basename} = $ENV{'form.'.$setting};
 3461:                 $AppHash{$envname}   = $ENV{'form.'.$setting};
 3462:             } elsif ($type eq 'array') {
 3463:                 my $stored_form;
 3464:                 if (ref($ENV{'form.'.$setting})) {
 3465:                     $stored_form = join(',',
 3466:                                         map {
 3467:                                             &Apache::lonnet::escape($_);
 3468:                                         } sort(@{$ENV{'form.'.$setting}}));
 3469:                 } else {
 3470:                     $stored_form = 
 3471:                         &Apache::lonnet::escape($ENV{'form.'.$setting});
 3472:                 }
 3473:                 # Determine if the array contents are the same.
 3474:                 if ($stored_form ne $ENV{$envname}) {
 3475:                     $SaveHash{$basename} = $stored_form;
 3476:                     $AppHash{$envname}   = $stored_form;
 3477:                 }
 3478:             }
 3479:         }
 3480:     }
 3481:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
 3482:                                           $coursedom,
 3483:                                           $ENV{'course.'.$courseid.'.num'});
 3484:     if ($put_result !~ /^(ok|delayed)/) {
 3485:         &Apache::lonnet::logthis('unable to save form parameters, '.
 3486:                                  'got error:'.$put_result);
 3487:     }
 3488:     # Make sure these settings stick around in this session, too
 3489:     &Apache::lonnet::appenv(%AppHash);
 3490:     return;
 3491: }
 3492: 
 3493: sub restore_course_settings {
 3494:     my $courseid = $ENV{'request.course.id'};
 3495:     my ($prefix,$Settings) = @_;
 3496:     while (my ($setting,$type) = each(%$Settings)) {
 3497:         next if (exists($ENV{'form.'.$setting}));
 3498:         my $envname = 'course.'.$courseid.'.internal.'.$prefix.
 3499:             '.'.$setting;
 3500:         if (exists($ENV{$envname})) {
 3501:             if ($type eq 'scalar') {
 3502:                 $ENV{'form.'.$setting} = $ENV{$envname};
 3503:             } elsif ($type eq 'array') {
 3504:                 $ENV{'form.'.$setting} = [ 
 3505:                                            map { 
 3506:                                                &Apache::lonnet::unescape($_); 
 3507:                                            } split(',',$ENV{$envname})
 3508:                                            ];
 3509:             }
 3510:         }
 3511:     }
 3512: }
 3513: 
 3514: ############################################################
 3515: ############################################################
 3516: 
 3517: sub propath {
 3518:     my ($udom,$uname)=@_;
 3519:     $udom=~s/\W//g;
 3520:     $uname=~s/\W//g;
 3521:     my $subdir=$uname.'__';
 3522:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 3523:     my $proname="$Apache::lonnet::perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
 3524:     return $proname;
 3525: } 
 3526: 
 3527: sub icon {
 3528:     my ($file)=@_;
 3529:     my $curfext = (split(/\./,$file))[-1];
 3530:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
 3531:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
 3532:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
 3533: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
 3534: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
 3535: 	            $curfext.".gif") {
 3536: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
 3537: 		$curfext.".gif";
 3538: 	}
 3539:     }
 3540:     return $iconname;
 3541: } 
 3542: 
 3543: =pod
 3544: 
 3545: =back
 3546: 
 3547: =cut
 3548: 
 3549: 1;
 3550: __END__;
 3551: 

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