File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.168: download - view: text, annotated - select for diffs
Tue Dec 30 20:47:23 2003 UTC (20 years, 5 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- was getting broken images on .rights files
- now all of the icons are genetarted in the same place &Apache::loncommon::icon($file or $url)
- BUG#2531

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

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