File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.170: download - view: text, annotated - select for diffs
Fri Jan 2 21:00:56 2004 UTC (20 years, 6 months ago) by www
Branches: MAIN
CVS tags: HEAD
Remember where we were in Resource Space

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

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