File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.197: download - view: text, annotated - select for diffs
Tue Jul 6 15:48:30 2004 UTC (19 years, 10 months ago) by matthew
Branches: MAIN
CVS tags: version_1_1_99_2, HEAD
pod fix.

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

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