File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.166: download - view: text, annotated - select for diffs
Mon Dec 29 17:11:53 2003 UTC (20 years, 6 months ago) by www
Branches: MAIN
CVS tags: HEAD
New prettyprint function to produce consistent metadata output.

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

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