File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.157: download - view: text, annotated - select for diffs
Mon Dec 1 14:36:22 2003 UTC (20 years, 7 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
POD changes.

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

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