File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.192: download - view: text, annotated - select for diffs
Fri Jun 11 02:21:45 2004 UTC (20 years, 1 month ago) by taceyjo1
Branches: MAIN
CVS tags: HEAD
Well <puts on stylepolice repellent> here is the beginning of
opensource, you can now publish things, and it will go into the
metafile.

BUG: #78

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

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