File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.201: download - view: text, annotated - select for diffs
Mon Jul 19 21:00:53 2004 UTC (19 years, 10 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
Fix bug #3224

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

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