File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.112: download - view: text, annotated - select for diffs
Wed Aug 20 18:18:45 2003 UTC (20 years, 9 months ago) by bowersj2
Branches: MAIN
CVS tags: HEAD
Documentation reformatting. A smidge of updating.

I was going to add a couple of routines and there was no good way to
document it, so I fixed this up.

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

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