File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.136: download - view: text, annotated - select for diffs
Mon Oct 27 21:21:08 2003 UTC (20 years, 7 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Complete rewrite of how graph.png works and of the interface routines for
it in loncommon.pm.  Added &DrawXYGraph which occasionally works.

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

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