File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.113: download - view: text, annotated - select for diffs
Tue Aug 26 17:20:45 2003 UTC (20 years, 8 months ago) by bowersj2
Branches: MAIN
CVS tags: HEAD
Changable line support added.

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.113 2003/08/26 17:20: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: =cut
  628: 
  629: sub csv_translate {
  630:     my $text = shift;
  631:     $text =~ s/\"/\"\"/g;
  632:     $text =~ s/\n//g;
  633:     return $text;
  634: }
  635: 
  636: =pod
  637: 
  638: =item * change_content_javascript():
  639: 
  640: This and the next function allow you to create small sections of an
  641: otherwise static HTML page that you can update on the fly with
  642: Javascript, even in Netscape 4.
  643: 
  644: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
  645: must be written to the HTML page once. It will prove the Javascript
  646: function "change(name, content)". Calling the change function with the
  647: name of the section 
  648: you want to update, matching the name passed to C<changable_area>, and
  649: the new content you want to put in there, will put the content into
  650: that area.
  651: 
  652: B<Note>: Netscape 4 only reserves enough space for the changable area
  653: to contain room for the original contents. You need to "make space"
  654: for whatever changes you wish to make, and be B<sure> to check your
  655: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
  656: it's adequate for updating a one-line status display, but little more.
  657: This script will set the space to 100% width, so you only need to
  658: worry about height in Netscape 4.
  659: 
  660: Modern browsers are much less limiting, and if you can commit to the
  661: user not using Netscape 4, this feature may be used freely with
  662: pretty much any HTML.
  663: 
  664: =cut
  665: 
  666: sub change_content_javascript {
  667:     # If we're on Netscape 4, we need to use Layer-based code
  668:     if ($ENV{'browser.type'} eq 'netscape' &&
  669: 	$ENV{'browser.version'} =~ /^4\./) {
  670: 	return (<<NETSCAPE4);
  671: 	function change(name, content) {
  672: 	    doc = document.layers[name+"___escape"].layers[0].document;
  673: 	    doc.open();
  674: 	    doc.write(content);
  675: 	    doc.close();
  676: 	}
  677: NETSCAPE4
  678:     } else {
  679: 	# Otherwise, we need to use semi-standards-compliant code
  680: 	# (technically, "innerHTML" isn't standard but the equivalent
  681: 	# is really scary, and every useful browser supports it
  682: 	return (<<DOMBASED);
  683: 	function change(name, content) {
  684: 	    element = document.getElementById(name);
  685: 	    element.innerHTML = content;
  686: 	}
  687: DOMBASED
  688:     }
  689: }
  690: 
  691: =pod
  692: 
  693: =item * changable_area($name, $origContent):
  694: 
  695: This provides a "changable area" that can be modified on the fly via
  696: the Javascript code provided in C<change_content_javascript>. $name is
  697: the name you will use to reference the area later; do not repeat the
  698: same name on a given HTML page more then once. $origContent is what
  699: the area will originally contain, which can be left blank.
  700: 
  701: =cut
  702: 
  703: sub changable_area {
  704:     my ($name, $origContent) = @_;
  705: 
  706:     if ($ENV{'browser.type'} eq 'netscape' &&
  707: 	$ENV{'browser.version'} =~ /^4\./) {
  708: 	# If this is netscape 4, we need to use the Layer tag
  709: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
  710:     } else {
  711: 	return "<span id='$name'>$origContent</span>";
  712:     }
  713: }
  714: 
  715: =pod
  716: 
  717: =back
  718: 
  719: =cut
  720: 
  721: ###############################################################
  722: ##        Home server <option> list generating code          ##
  723: ###############################################################
  724: 
  725: =pod
  726: 
  727: =head1 Home Server option list generating code
  728: 
  729: =over 4
  730: 
  731: =item * get_domains()
  732: 
  733: Returns an array containing each of the domains listed in the hosts.tab
  734: file.
  735: 
  736: =cut
  737: 
  738: #-------------------------------------------
  739: sub get_domains {
  740:     # The code below was stolen from "The Perl Cookbook", p 102, 1st ed.
  741:     my @domains;
  742:     my %seen;
  743:     foreach (sort values(%Apache::lonnet::hostdom)) {
  744:         push (@domains,$_) unless $seen{$_}++;
  745:     }
  746:     return @domains;
  747: }
  748: 
  749: #-------------------------------------------
  750: 
  751: =pod
  752: 
  753: =item * select_form($defdom,$name,%hash)
  754: 
  755: Returns a string containing a <select name='$name' size='1'> form to 
  756: allow a user to select options from a hash option_name => displayed text.  
  757: See lonrights.pm for an example invocation and use.
  758: 
  759: =cut
  760: 
  761: #-------------------------------------------
  762: sub select_form {
  763:     my ($def,$name,%hash) = @_;
  764:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
  765:     foreach (sort keys %hash) {
  766:         $selectform.="<option value=\"$_\" ".
  767:             ($_ eq $def ? 'selected' : '').
  768:                 ">".$hash{$_}."</option>\n";
  769:     }
  770:     $selectform.="</select>";
  771:     return $selectform;
  772: }
  773: 
  774: 
  775: #-------------------------------------------
  776: 
  777: =pod
  778: 
  779: =item * select_dom_form($defdom,$name,$includeempty)
  780: 
  781: Returns a string containing a <select name='$name' size='1'> form to 
  782: allow a user to select the domain to preform an operation in.  
  783: See loncreateuser.pm for an example invocation and use.
  784: 
  785: If the $includeempty flag is set, it also includes an empty choice ("no domain
  786: selected");
  787: 
  788: =cut
  789: 
  790: #-------------------------------------------
  791: sub select_dom_form {
  792:     my ($defdom,$name,$includeempty) = @_;
  793:     my @domains = get_domains();
  794:     if ($includeempty) { @domains=('',@domains); }
  795:     my $selectdomain = "<select name=\"$name\" size=\"1\">\n";
  796:     foreach (@domains) {
  797:         $selectdomain.="<option value=\"$_\" ".
  798:             ($_ eq $defdom ? 'selected' : '').
  799:                 ">$_</option>\n";
  800:     }
  801:     $selectdomain.="</select>";
  802:     return $selectdomain;
  803: }
  804: 
  805: #-------------------------------------------
  806: 
  807: =pod
  808: 
  809: =item * get_library_servers($domain)
  810: 
  811: Returns a hash which contains keys like '103l3' and values like 
  812: 'kirk.lite.msu.edu'.  All of the keys will be for machines in the
  813: given $domain.
  814: 
  815: =cut
  816: 
  817: #-------------------------------------------
  818: sub get_library_servers {
  819:     my $domain = shift;
  820:     my %library_servers;
  821:     foreach (keys(%Apache::lonnet::libserv)) {
  822:         if ($Apache::lonnet::hostdom{$_} eq $domain) {
  823:             $library_servers{$_} = $Apache::lonnet::hostname{$_};
  824:         }
  825:     }
  826:     return %library_servers;
  827: }
  828: 
  829: #-------------------------------------------
  830: 
  831: =pod
  832: 
  833: =item * home_server_option_list($domain)
  834: 
  835: returns a string which contains an <option> list to be used in a 
  836: <select> form input.  See loncreateuser.pm for an example.
  837: 
  838: =cut
  839: 
  840: #-------------------------------------------
  841: sub home_server_option_list {
  842:     my $domain = shift;
  843:     my %servers = &get_library_servers($domain);
  844:     my $result = '';
  845:     foreach (sort keys(%servers)) {
  846:         $result.=
  847:             '<option value="'.$_.'">'.$_.' '.$servers{$_}."</option>\n";
  848:     }
  849:     return $result;
  850: }
  851: 
  852: =pod
  853: 
  854: =back
  855: 
  856: =cut
  857: 
  858: ###############################################################
  859: ##                  Decoding User Agent                      ##
  860: ###############################################################
  861: 
  862: =pod
  863: 
  864: =head1 Decoding the User Agent
  865: 
  866: =over 4
  867: 
  868: =item * &decode_user_agent()
  869: 
  870: Inputs: $r
  871: 
  872: Outputs:
  873: 
  874: =over 4
  875: 
  876: =item * $httpbrowser
  877: 
  878: =item * $clientbrowser
  879: 
  880: =item * $clientversion
  881: 
  882: =item * $clientmathml
  883: 
  884: =item * $clientunicode
  885: 
  886: =item * $clientos
  887: 
  888: =back
  889: 
  890: =cut
  891: 
  892: ###############################################################
  893: ###############################################################
  894: sub decode_user_agent {
  895:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
  896:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
  897:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
  898:     my $clientbrowser='unknown';
  899:     my $clientversion='0';
  900:     my $clientmathml='';
  901:     my $clientunicode='0';
  902:     for (my $i=0;$i<=$#browsertype;$i++) {
  903:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
  904: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
  905: 	    $clientbrowser=$bname;
  906:             $httpbrowser=~/$vreg/i;
  907: 	    $clientversion=$1;
  908:             $clientmathml=($clientversion>=$minv);
  909:             $clientunicode=($clientversion>=$univ);
  910: 	}
  911:     }
  912:     my $clientos='unknown';
  913:     if (($httpbrowser=~/linux/i) ||
  914:         ($httpbrowser=~/unix/i) ||
  915:         ($httpbrowser=~/ux/i) ||
  916:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
  917:     if (($httpbrowser=~/vax/i) ||
  918:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
  919:     if ($httpbrowser=~/next/i) { $clientos='next'; }
  920:     if (($httpbrowser=~/mac/i) ||
  921:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
  922:     if ($httpbrowser=~/win/i) { $clientos='win'; }
  923:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
  924:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
  925:             $clientunicode,$clientos,);
  926: }
  927: 
  928: =pod
  929: 
  930: =back
  931: 
  932: =cut
  933: 
  934: ###############################################################
  935: ##    Authentication changing form generation subroutines    ##
  936: ###############################################################
  937: ##
  938: ## All of the authform_xxxxxxx subroutines take their inputs in a
  939: ## hash, and have reasonable default values.
  940: ##
  941: ##    formname = the name given in the <form> tag.
  942: #-------------------------------------------
  943: 
  944: =pod
  945: 
  946: =head1 Authentication Routines
  947: 
  948: =over 4
  949: 
  950: =item * authform_xxxxxx
  951: 
  952: The authform_xxxxxx subroutines provide javascript and html forms which 
  953: handle some of the conveniences required for authentication forms.  
  954: This is not an optimal method, but it works.  
  955: 
  956: See loncreateuser.pm for invocation and use examples.
  957: 
  958: =over 4
  959: 
  960: =item * authform_header
  961: 
  962: =item * authform_authorwarning
  963: 
  964: =item * authform_nochange
  965: 
  966: =item * authform_kerberos
  967: 
  968: =item * authform_internal
  969: 
  970: =item * authform_filesystem
  971: 
  972: =back
  973: 
  974: =cut
  975: 
  976: #-------------------------------------------
  977: sub authform_header{  
  978:     my %in = (
  979:         formname => 'cu',
  980:         kerb_def_dom => '',
  981:         @_,
  982:     );
  983:     $in{'formname'} = 'document.' . $in{'formname'};
  984:     my $result='';
  985: 
  986: #---------------------------------------------- Code for upper case translation
  987:     my $Javascript_toUpperCase;
  988:     unless ($in{kerb_def_dom}) {
  989:         $Javascript_toUpperCase =<<"END";
  990:         switch (choice) {
  991:            case 'krb': currentform.elements[choicearg].value =
  992:                currentform.elements[choicearg].value.toUpperCase();
  993:                break;
  994:            default:
  995:         }
  996: END
  997:     } else {
  998:         $Javascript_toUpperCase = "";
  999:     }
 1000: 
 1001:     $result.=<<"END";
 1002: var current = new Object();
 1003: current.radiovalue = 'nochange';
 1004: current.argfield = null;
 1005: 
 1006: function changed_radio(choice,currentform) {
 1007:     var choicearg = choice + 'arg';
 1008:     // If a radio button in changed, we need to change the argfield
 1009:     if (current.radiovalue != choice) {
 1010:         current.radiovalue = choice;
 1011:         if (current.argfield != null) {
 1012:             currentform.elements[current.argfield].value = '';
 1013:         }
 1014:         if (choice == 'nochange') {
 1015:             current.argfield = null;
 1016:         } else {
 1017:             current.argfield = choicearg;
 1018:             switch(choice) {
 1019:                 case 'krb': 
 1020:                     currentform.elements[current.argfield].value = 
 1021:                         "$in{'kerb_def_dom'}";
 1022:                 break;
 1023:               default:
 1024:                 break;
 1025:             }
 1026:         }
 1027:     }
 1028:     return;
 1029: }
 1030: 
 1031: function changed_text(choice,currentform) {
 1032:     var choicearg = choice + 'arg';
 1033:     if (currentform.elements[choicearg].value !='') {
 1034:         $Javascript_toUpperCase
 1035:         // clear old field
 1036:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 1037:             currentform.elements[current.argfield].value = '';
 1038:         }
 1039:         current.argfield = choicearg;
 1040:     }
 1041:     set_auth_radio_buttons(choice,currentform);
 1042:     return;
 1043: }
 1044: 
 1045: function set_auth_radio_buttons(newvalue,currentform) {
 1046:     var i=0;
 1047:     while (i < currentform.login.length) {
 1048:         if (currentform.login[i].value == newvalue) { break; }
 1049:         i++;
 1050:     }
 1051:     if (i == currentform.login.length) {
 1052:         return;
 1053:     }
 1054:     current.radiovalue = newvalue;
 1055:     currentform.login[i].checked = true;
 1056:     return;
 1057: }
 1058: END
 1059:     return $result;
 1060: }
 1061: 
 1062: sub authform_authorwarning{
 1063:     my $result='';
 1064:     $result=<<"END";
 1065: <i>As a general rule, only authors or co-authors should be filesystem
 1066: authenticated (which allows access to the server filesystem).</i>
 1067: END
 1068:     return $result;
 1069: }
 1070: 
 1071: sub authform_nochange{  
 1072:     my %in = (
 1073:               formname => 'document.cu',
 1074:               kerb_def_dom => 'MSU.EDU',
 1075:               @_,
 1076:           );
 1077:     my $result='';
 1078:     $result.=<<"END";
 1079: <input type="radio" name="login" value="nochange" checked="checked"
 1080:        onclick="javascript:changed_radio('nochange',$in{'formname'});" />
 1081: Do not change login data
 1082: END
 1083:     return $result;
 1084: }
 1085: 
 1086: sub authform_kerberos{  
 1087:     my %in = (
 1088:               formname => 'document.cu',
 1089:               kerb_def_dom => 'MSU.EDU',
 1090:               kerb_def_auth => 'krb4',
 1091:               @_,
 1092:               );
 1093:     my $result='';
 1094:     my $check4;
 1095:     my $check5;
 1096:     if ($in{'kerb_def_auth'} eq 'krb5') {
 1097:        $check5 = " checked=\"on\"";
 1098:     } else {
 1099:        $check4 = " checked=\"on\"";
 1100:     }
 1101:     $result.=<<"END";
 1102: <input type="radio" name="login" value="krb" 
 1103:        onclick="javascript:changed_radio('krb',$in{'formname'});"
 1104:        onchange="javascript:changed_radio('krb',$in{'formname'});" />
 1105: Kerberos authenticated with domain
 1106: <input type="text" size="10" name="krbarg" value="$in{'kerb_def_dom'}"
 1107:        onchange="javascript:changed_text('krb',$in{'formname'});" />
 1108: <input type="radio" name="krbver" value="4" $check4 />Version 4
 1109: <input type="radio" name="krbver" value="5" $check5 />Version 5
 1110: END
 1111:     return $result;
 1112: }
 1113: 
 1114: sub authform_internal{  
 1115:     my %args = (
 1116:                 formname => 'document.cu',
 1117:                 kerb_def_dom => 'MSU.EDU',
 1118:                 @_,
 1119:                 );
 1120:     my $result='';
 1121:     $result.=<<"END";
 1122: <input type="radio" name="login" value="int"
 1123:        onchange="javascript:changed_radio('int',$args{'formname'});"
 1124:        onclick="javascript:changed_radio('int',$args{'formname'});" />
 1125: Internally authenticated (with initial password 
 1126: <input type="text" size="10" name="intarg" value=""
 1127:        onchange="javascript:changed_text('int',$args{'formname'});" />)
 1128: END
 1129:     return $result;
 1130: }
 1131: 
 1132: sub authform_local{  
 1133:     my %in = (
 1134:               formname => 'document.cu',
 1135:               kerb_def_dom => 'MSU.EDU',
 1136:               @_,
 1137:               );
 1138:     my $result='';
 1139:     $result.=<<"END";
 1140: <input type="radio" name="login" value="loc"
 1141:        onchange="javascript:changed_radio('loc',$in{'formname'});"
 1142:        onclick="javascript:changed_radio('loc',$in{'formname'});" />
 1143: Local Authentication with argument
 1144: <input type="text" size="10" name="locarg" value=""
 1145:        onchange="javascript:changed_text('loc',$in{'formname'});" />
 1146: END
 1147:     return $result;
 1148: }
 1149: 
 1150: sub authform_filesystem{  
 1151:     my %in = (
 1152:               formname => 'document.cu',
 1153:               kerb_def_dom => 'MSU.EDU',
 1154:               @_,
 1155:               );
 1156:     my $result='';
 1157:     $result.=<<"END";
 1158: <input type="radio" name="login" value="fsys" 
 1159:        onchange="javascript:changed_radio('fsys',$in{'formname'});"
 1160:        onclick="javascript:changed_radio('fsys',$in{'formname'});" />
 1161: Filesystem authenticated (with initial password 
 1162: <input type="text" size="10" name="fsysarg" value=""
 1163:        onchange="javascript:changed_text('fsys',$in{'formname'});">)
 1164: END
 1165:     return $result;
 1166: }
 1167: 
 1168: =pod
 1169: 
 1170: =back
 1171: 
 1172: =cut
 1173: 
 1174: ###############################################################
 1175: ##    Get Authentication Defaults for Domain                 ##
 1176: ###############################################################
 1177: 
 1178: =pod
 1179: 
 1180: =head1 Domains and Authentication
 1181: 
 1182: Returns default authentication type and an associated argument as
 1183: listed in file 'domain.tab'.
 1184: 
 1185: =over 4
 1186: 
 1187: =item * get_auth_defaults
 1188: 
 1189: get_auth_defaults($target_domain) returns the default authentication
 1190: type and an associated argument (initial password or a kerberos domain).
 1191: These values are stored in lonTabs/domain.tab
 1192: 
 1193: ($def_auth, $def_arg) = &get_auth_defaults($target_domain);
 1194: 
 1195: If target_domain is not found in domain.tab, returns nothing ('').
 1196: 
 1197: =cut
 1198: 
 1199: #-------------------------------------------
 1200: sub get_auth_defaults {
 1201:     my $domain=shift;
 1202:     return ($Apache::lonnet::domain_auth_def{$domain},$Apache::lonnet::domain_auth_arg_def{$domain});
 1203: }
 1204: ###############################################################
 1205: ##   End Get Authentication Defaults for Domain              ##
 1206: ###############################################################
 1207: 
 1208: ###############################################################
 1209: ##    Get Kerberos Defaults for Domain                 ##
 1210: ###############################################################
 1211: ##
 1212: ## Returns default kerberos version and an associated argument
 1213: ## as listed in file domain.tab. If not listed, provides
 1214: ## appropriate default domain and kerberos version.
 1215: ##
 1216: #-------------------------------------------
 1217: 
 1218: =pod
 1219: 
 1220: =item * get_kerberos_defaults
 1221: 
 1222: get_kerberos_defaults($target_domain) returns the default kerberos
 1223: version and domain. If not found in domain.tabs, it defaults to
 1224: version 4 and the domain of the server.
 1225: 
 1226: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 1227: 
 1228: =cut
 1229: 
 1230: #-------------------------------------------
 1231: sub get_kerberos_defaults {
 1232:     my $domain=shift;
 1233:     my ($krbdef,$krbdefdom) =
 1234:         &Apache::loncommon::get_auth_defaults($domain);
 1235:     unless ($krbdef =~/^krb/ && $krbdefdom) {
 1236:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 1237:         my $krbdefdom=$1;
 1238:         $krbdefdom=~tr/a-z/A-Z/;
 1239:         $krbdef = "krb4";
 1240:     }
 1241:     return ($krbdef,$krbdefdom);
 1242: }
 1243: 
 1244: =pod
 1245: 
 1246: =back
 1247: 
 1248: =cut
 1249: 
 1250: ###############################################################
 1251: ##                Thesaurus Functions                        ##
 1252: ###############################################################
 1253: 
 1254: =pod
 1255: 
 1256: =head1 Thesaurus Functions
 1257: 
 1258: =over 4
 1259: 
 1260: =item * initialize_keywords
 1261: 
 1262: Initializes the package variable %Keywords if it is empty.  Uses the
 1263: package variable $thesaurus_db_file.
 1264: 
 1265: =cut
 1266: 
 1267: ###################################################
 1268: 
 1269: sub initialize_keywords {
 1270:     return 1 if (scalar keys(%Keywords));
 1271:     # If we are here, %Keywords is empty, so fill it up
 1272:     #   Make sure the file we need exists...
 1273:     if (! -e $thesaurus_db_file) {
 1274:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 1275:                                  " failed because it does not exist");
 1276:         return 0;
 1277:     }
 1278:     #   Set up the hash as a database
 1279:     my %thesaurus_db;
 1280:     if (! tie(%thesaurus_db,'GDBM_File',
 1281:               $thesaurus_db_file,&GDBM_READER(),0640)){
 1282:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 1283:                                  $thesaurus_db_file);
 1284:         return 0;
 1285:     } 
 1286:     #  Get the average number of appearances of a word.
 1287:     my $avecount = $thesaurus_db{'average.count'};
 1288:     #  Put keywords (those that appear > average) into %Keywords
 1289:     while (my ($word,$data)=each (%thesaurus_db)) {
 1290:         my ($count,undef) = split /:/,$data;
 1291:         $Keywords{$word}++ if ($count > $avecount);
 1292:     }
 1293:     untie %thesaurus_db;
 1294:     # Remove special values from %Keywords.
 1295:     foreach ('total.count','average.count') {
 1296:         delete($Keywords{$_}) if (exists($Keywords{$_}));
 1297:     }
 1298:     return 1;
 1299: }
 1300: 
 1301: ###################################################
 1302: 
 1303: =pod
 1304: 
 1305: =item * keyword($word)
 1306: 
 1307: Returns true if $word is a keyword.  A keyword is a word that appears more 
 1308: than the average number of times in the thesaurus database.  Calls 
 1309: &initialize_keywords
 1310: 
 1311: =cut
 1312: 
 1313: ###################################################
 1314: 
 1315: sub keyword {
 1316:     return if (!&initialize_keywords());
 1317:     my $word=lc(shift());
 1318:     $word=~s/\W//g;
 1319:     return exists($Keywords{$word});
 1320: }
 1321: 
 1322: ###############################################################
 1323: 
 1324: =pod 
 1325: 
 1326: =item * get_related_words
 1327: 
 1328: Look up a word in the thesaurus.  Takes a scalar arguement and returns
 1329: an array of words.  If the keyword is not in the thesaurus, an empty array
 1330: will be returned.  The order of the words returned is determined by the
 1331: database which holds them.
 1332: 
 1333: Uses global $thesaurus_db_file.
 1334: 
 1335: =cut
 1336: 
 1337: ###############################################################
 1338: sub get_related_words {
 1339:     my $keyword = shift;
 1340:     my %thesaurus_db;
 1341:     if (! -e $thesaurus_db_file) {
 1342:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 1343:                                  "failed because the file does not exist");
 1344:         return ();
 1345:     }
 1346:     if (! tie(%thesaurus_db,'GDBM_File',
 1347:               $thesaurus_db_file,&GDBM_READER(),0640)){
 1348:         return ();
 1349:     } 
 1350:     my @Words=();
 1351:     if (exists($thesaurus_db{$keyword})) {
 1352:         $_ = $thesaurus_db{$keyword};
 1353:         (undef,@Words) = split/:/;  # The first element is the number of times
 1354:                                     # the word appears.  We do not need it now.
 1355:         for (my $i=0;$i<=$#Words;$i++) {
 1356:             ($Words[$i],undef)= split/\,/,$Words[$i];
 1357:         }
 1358:     }
 1359:     untie %thesaurus_db;
 1360:     return @Words;
 1361: }
 1362: 
 1363: =pod
 1364: 
 1365: =back
 1366: 
 1367: =cut
 1368: 
 1369: # -------------------------------------------------------------- Plaintext name
 1370: =pod
 1371: 
 1372: =head1 User Name Functions
 1373: 
 1374: =over 4
 1375: 
 1376: =item * plainname($uname,$udom)
 1377: 
 1378: Takes a users logon name and returns it as a string in
 1379: "first middle last generation" form
 1380: 
 1381: =cut
 1382: 
 1383: ###############################################################
 1384: sub plainname {
 1385:     my ($uname,$udom)=@_;
 1386:     my %names=&Apache::lonnet::get('environment',
 1387:                     ['firstname','middlename','lastname','generation'],
 1388: 					 $udom,$uname);
 1389:     my $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 1390: 	$names{'lastname'}.' '.$names{'generation'};
 1391:     $name=~s/\s+$//;
 1392:     $name=~s/\s+/ /g;
 1393:     return $name;
 1394: }
 1395: 
 1396: # -------------------------------------------------------------------- Nickname
 1397: =pod
 1398: 
 1399: =item * nickname($uname,$udom)
 1400: 
 1401: Gets a users name and returns it as a string as
 1402: 
 1403: "&quot;nickname&quot;"
 1404: 
 1405: if the user has a nickname or
 1406: 
 1407: "first middle last generation"
 1408: 
 1409: if the user does not
 1410: 
 1411: =cut
 1412: 
 1413: sub nickname {
 1414:     my ($uname,$udom)=@_;
 1415:     my %names=&Apache::lonnet::get('environment',
 1416:   ['nickname','firstname','middlename','lastname','generation'],$udom,$uname);
 1417:     my $name=$names{'nickname'};
 1418:     if ($name) {
 1419:        $name='&quot;'.$name.'&quot;'; 
 1420:     } else {
 1421:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 1422: 	     $names{'lastname'}.' '.$names{'generation'};
 1423:        $name=~s/\s+$//;
 1424:        $name=~s/\s+/ /g;
 1425:     }
 1426:     return $name;
 1427: }
 1428: 
 1429: 
 1430: # ------------------------------------------------------------------ Screenname
 1431: 
 1432: =pod
 1433: 
 1434: =item * screenname($uname,$udom)
 1435: 
 1436: Gets a users screenname and returns it as a string
 1437: 
 1438: =cut
 1439: 
 1440: sub screenname {
 1441:     my ($uname,$udom)=@_;
 1442:     my %names=
 1443:  &Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 1444:     return $names{'screenname'};
 1445: }
 1446: 
 1447: # ------------------------------------------------------------- Message Wrapper
 1448: 
 1449: sub messagewrapper {
 1450:     my ($link,$un,$do)=@_;
 1451:     return 
 1452: "<a href='/adm/email?compose=individual&recname=$un&recdom=$do'>$link</a>";
 1453: }
 1454: # --------------------------------------------------------------- Notes Wrapper
 1455: 
 1456: sub noteswrapper {
 1457:     my ($link,$un,$do)=@_;
 1458:     return 
 1459: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
 1460: }
 1461: # ------------------------------------------------------------- Aboutme Wrapper
 1462: 
 1463: sub aboutmewrapper {
 1464:     my ($link,$username,$domain)=@_;
 1465:     return "<a href='/adm/$domain/$username/aboutme'>$link</a>";
 1466: }
 1467: 
 1468: # ------------------------------------------------------------ Syllabus Wrapper
 1469: 
 1470: 
 1471: sub syllabuswrapper {
 1472:     my ($linktext,$coursedir,$domain,$fontcolor)=@_;
 1473:     if ($fontcolor) { 
 1474:         $linktext='<font color="'.$fontcolor.'">'.$linktext.'</font>'; 
 1475:     }
 1476:     return "<a href='/public/$domain/$coursedir/syllabus'>$linktext</a>";
 1477: }
 1478: 
 1479: =pod
 1480: 
 1481: =back
 1482: 
 1483: =head1 Access .tab File Data
 1484: 
 1485: =over 4
 1486: 
 1487: =item * languageids() 
 1488: 
 1489: returns list of all language ids
 1490: 
 1491: =cut
 1492: 
 1493: sub languageids {
 1494:     return sort(keys(%language));
 1495: }
 1496: 
 1497: =pod
 1498: 
 1499: =item * languagedescription() 
 1500: 
 1501: returns description of a specified language id
 1502: 
 1503: =cut
 1504: 
 1505: sub languagedescription {
 1506:     return $language{shift(@_)};
 1507: }
 1508: 
 1509: =pod
 1510: 
 1511: =item * copyrightids() 
 1512: 
 1513: returns list of all copyrights
 1514: 
 1515: =cut
 1516: 
 1517: sub copyrightids {
 1518:     return sort(keys(%cprtag));
 1519: }
 1520: 
 1521: =pod
 1522: 
 1523: =item * copyrightdescription() 
 1524: 
 1525: returns description of a specified copyright id
 1526: 
 1527: =cut
 1528: 
 1529: sub copyrightdescription {
 1530:     return $cprtag{shift(@_)};
 1531: }
 1532: 
 1533: =pod
 1534: 
 1535: =item * filecategories() 
 1536: 
 1537: returns list of all file categories
 1538: 
 1539: =cut
 1540: 
 1541: sub filecategories {
 1542:     return sort(keys(%category_extensions));
 1543: }
 1544: 
 1545: =pod
 1546: 
 1547: =item * filecategorytypes() 
 1548: 
 1549: returns list of file types belonging to a given file
 1550: category
 1551: 
 1552: =cut
 1553: 
 1554: sub filecategorytypes {
 1555:     return @{$category_extensions{lc($_[0])}};
 1556: }
 1557: 
 1558: =pod
 1559: 
 1560: =item * fileembstyle() 
 1561: 
 1562: returns embedding style for a specified file type
 1563: 
 1564: =cut
 1565: 
 1566: sub fileembstyle {
 1567:     return $fe{lc(shift(@_))};
 1568: }
 1569: 
 1570: =pod
 1571: 
 1572: =item * filedescription() 
 1573: 
 1574: returns description for a specified file type
 1575: 
 1576: =cut
 1577: 
 1578: sub filedescription {
 1579:     return $fd{lc(shift(@_))};
 1580: }
 1581: 
 1582: =pod
 1583: 
 1584: =item * filedescriptionex() 
 1585: 
 1586: returns description for a specified file type with
 1587: extra formatting
 1588: 
 1589: =cut
 1590: 
 1591: sub filedescriptionex {
 1592:     my $ex=shift;
 1593:     return '.'.$ex.' '.$fd{lc($ex)};
 1594: }
 1595: 
 1596: # End of .tab access
 1597: =pod
 1598: 
 1599: =back
 1600: 
 1601: =cut
 1602: 
 1603: # ------------------------------------------------------------------ File Types
 1604: sub fileextensions {
 1605:     return sort(keys(%fe));
 1606: }
 1607: 
 1608: # ----------------------------------------------------------- Display Languages
 1609: # returns a hash with all desired display languages
 1610: #
 1611: 
 1612: sub display_languages {
 1613:     my %languages=();
 1614:     if ($ENV{'environment.languages'}) {
 1615: 	foreach (split(/\s*(\,|\;|\:)\s*/,$ENV{'environment.languages'})) {
 1616: 	    $languages{$_}=1;
 1617:         }
 1618:     }
 1619:     if ($ENV{'course.'.$ENV{'request.course.id'}.'.languages'}) {
 1620: 	foreach (split(/\s*(\,|\;|\:)\s*/,
 1621: 	$ENV{'course.'.$ENV{'request.course.id'}.'.languages'})) {
 1622: 	    $languages{$_}=1;
 1623:         }
 1624:     }
 1625:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 1626:     if ($ENV{'form.displaylanguage'}) {
 1627: 	foreach (split(/\s*(\,|\;|\:)\s*/,$ENV{'form.displaylanguage'})) {
 1628: 	    $languages{$_}=1;
 1629:         }
 1630:     }
 1631:     return %languages;
 1632: }
 1633: 
 1634: ###############################################################
 1635: ##               Student Answer Attempts                     ##
 1636: ###############################################################
 1637: 
 1638: =pod
 1639: 
 1640: =head1 Alternate Problem Views
 1641: 
 1642: =over 4
 1643: 
 1644: =item * get_previous_attempt($symb, $username, $domain, $course,
 1645:     $getattempt, $regexp, $gradesub)
 1646: 
 1647: Return string with previous attempt on problem. Arguments:
 1648: 
 1649: =over 4
 1650: 
 1651: =item * $symb: Problem, including path
 1652: 
 1653: =item * $username: username of the desired student
 1654: 
 1655: =item * $domain: domain of the desired student
 1656: 
 1657: =item * $course: Course ID
 1658: 
 1659: =item * $getattempt: Leave blank for all attempts, otherwise put
 1660:     something
 1661: 
 1662: =item * $regexp: if string matches this regexp, the string will be
 1663:     sent to $gradesub
 1664: 
 1665: =item * $gradesub: routine that processes the string if it matches $regexp
 1666: 
 1667: =back
 1668: 
 1669: The output string is a table containing all desired attempts, if any.
 1670: 
 1671: =cut
 1672: 
 1673: sub get_previous_attempt {
 1674:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
 1675:   my $prevattempts='';
 1676:   no strict 'refs';
 1677:   if ($symb) {
 1678:     my (%returnhash)=
 1679:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 1680:     if ($returnhash{'version'}) {
 1681:       my %lasthash=();
 1682:       my $version;
 1683:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 1684:         foreach (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 1685: 	  $lasthash{$_}=$returnhash{$version.':'.$_};
 1686:         }
 1687:       }
 1688:       $prevattempts='<table border="0" width="100%"><tr><td bgcolor="#777777">';
 1689:       $prevattempts.='<table border="0" width="100%"><tr bgcolor="#e6ffff"><td>History</td>';
 1690:       foreach (sort(keys %lasthash)) {
 1691: 	my ($ign,@parts) = split(/\./,$_);
 1692: 	if ($#parts > 0) {
 1693: 	  my $data=$parts[-1];
 1694: 	  pop(@parts);
 1695: 	  $prevattempts.='<td>Part '.join('.',@parts).'<br />'.$data.'&nbsp;</td>';
 1696: 	} else {
 1697: 	  if ($#parts == 0) {
 1698: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 1699: 	  } else {
 1700: 	    $prevattempts.='<th>'.$ign.'</th>';
 1701: 	  }
 1702: 	}
 1703:       }
 1704:       if ($getattempt eq '') {
 1705: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 1706: 	  $prevattempts.='</tr><tr bgcolor="#ffffe6"><td>Transaction '.$version.'</td>';
 1707: 	    foreach (sort(keys %lasthash)) {
 1708: 	       my $value;
 1709: 	       if ($_ =~ /timestamp/) {
 1710: 		  $value=scalar(localtime($returnhash{$version.':'.$_}));
 1711: 	       } else {
 1712: 		  $value=$returnhash{$version.':'.$_};
 1713: 	       }
 1714: 	       $prevattempts.='<td>'.$value.'&nbsp;</td>';   
 1715: 	    }
 1716: 	 }
 1717:       }
 1718:       $prevattempts.='</tr><tr bgcolor="#ffffe6"><td>Current</td>';
 1719:       foreach (sort(keys %lasthash)) {
 1720: 	my $value;
 1721: 	if ($_ =~ /timestamp/) {
 1722: 	  $value=scalar(localtime($lasthash{$_}));
 1723: 	} else {
 1724: 	  $value=$lasthash{$_};
 1725: 	}
 1726: 	if ($_ =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
 1727: 	$prevattempts.='<td>'.$value.'&nbsp;</td>';
 1728:       }
 1729:       $prevattempts.='</tr></table></td></tr></table>';
 1730:     } else {
 1731:       $prevattempts='Nothing submitted - no attempts.';
 1732:     }
 1733:   } else {
 1734:     $prevattempts='No data.';
 1735:   }
 1736: }
 1737: 
 1738: sub relative_to_absolute {
 1739:     my ($url,$output)=@_;
 1740:     my $parser=HTML::TokeParser->new(\$output);
 1741:     my $token;
 1742:     my $thisdir=$url;
 1743:     my @rlinks=();
 1744:     while ($token=$parser->get_token) {
 1745: 	if ($token->[0] eq 'S') {
 1746: 	    if ($token->[1] eq 'a') {
 1747: 		if ($token->[2]->{'href'}) {
 1748: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 1749: 		}
 1750: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 1751: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 1752: 	    } elsif ($token->[1] eq 'base') {
 1753: 		$thisdir=$token->[2]->{'href'};
 1754: 	    }
 1755: 	}
 1756:     }
 1757:     $thisdir=~s-/[^/]*$--;
 1758:     foreach (@rlinks) {
 1759: 	unless (($_=~/^http:\/\//i) ||
 1760: 		($_=~/^\//) ||
 1761: 		($_=~/^javascript:/i) ||
 1762: 		($_=~/^mailto:/i) ||
 1763: 		($_=~/^\#/)) {
 1764: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$_);
 1765: 	    $output=~s/(\"|\'|\=\s*)$_(\"|\'|\s|\>)/$1$newlocation$2/;
 1766: 	}
 1767:     }
 1768: # -------------------------------------------------- Deal with Applet codebases
 1769:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 1770:     return $output;
 1771: }
 1772: 
 1773: =pod
 1774: 
 1775: =item * get_student_view
 1776: 
 1777: show a snapshot of what student was looking at
 1778: 
 1779: =cut
 1780: 
 1781: sub get_student_view {
 1782:   my ($symb,$username,$domain,$courseid,$target) = @_;
 1783:   my ($map,$id,$feedurl) = split(/___/,$symb);
 1784:   my (%old,%moreenv);
 1785:   my @elements=('symb','courseid','domain','username');
 1786:   foreach my $element (@elements) {
 1787:     $old{$element}=$ENV{'form.grade_'.$element};
 1788:     $moreenv{'form.grade_'.$element}=eval '$'.$element #'
 1789:   }
 1790:   if ($target eq 'tex') {$moreenv{'form.grade_target'} = 'tex';}
 1791:   &Apache::lonnet::appenv(%moreenv);
 1792:   $feedurl=&Apache::lonnet::clutter($feedurl);
 1793:   my $userview=&Apache::lonnet::ssi_body($feedurl);
 1794:   &Apache::lonnet::delenv('form.grade_');
 1795:   foreach my $element (@elements) {
 1796:     $ENV{'form.grade_'.$element}=$old{$element};
 1797:   }
 1798:   $userview=~s/\<body[^\>]*\>//gi;
 1799:   $userview=~s/\<\/body\>//gi;
 1800:   $userview=~s/\<html\>//gi;
 1801:   $userview=~s/\<\/html\>//gi;
 1802:   $userview=~s/\<head\>//gi;
 1803:   $userview=~s/\<\/head\>//gi;
 1804:   $userview=~s/action\s*\=/would_be_action\=/gi;
 1805:   $userview=&relative_to_absolute($feedurl,$userview);
 1806:   return $userview;
 1807: }
 1808: 
 1809: =pod
 1810: 
 1811: =item * get_student_answers() 
 1812: 
 1813: show a snapshot of how student was answering problem
 1814: 
 1815: =cut
 1816: 
 1817: sub get_student_answers {
 1818:   my ($symb,$username,$domain,$courseid,%form) = @_;
 1819:   my ($map,$id,$feedurl) = split(/___/,$symb);
 1820:   my (%old,%moreenv);
 1821:   my @elements=('symb','courseid','domain','username');
 1822:   foreach my $element (@elements) {
 1823:     $old{$element}=$ENV{'form.grade_'.$element};
 1824:     $moreenv{'form.grade_'.$element}=eval '$'.$element #'
 1825:   }
 1826:   $moreenv{'form.grade_target'}='answer';
 1827:   &Apache::lonnet::appenv(%moreenv);
 1828:   my $userview=&Apache::lonnet::ssi('/res/'.$feedurl,%form);
 1829:   &Apache::lonnet::delenv('form.grade_');
 1830:   foreach my $element (@elements) {
 1831:     $ENV{'form.grade_'.$element}=$old{$element};
 1832:   }
 1833:   return $userview;
 1834: }
 1835: 
 1836: =pod
 1837: 
 1838: =back
 1839: 
 1840: =cut
 1841: 
 1842: ###############################################
 1843: 
 1844: 
 1845: sub timehash {
 1846:     my @ltime=localtime(shift);
 1847:     return ( 'seconds' => $ltime[0],
 1848:              'minutes' => $ltime[1],
 1849:              'hours'   => $ltime[2],
 1850:              'day'     => $ltime[3],
 1851:              'month'   => $ltime[4]+1,
 1852:              'year'    => $ltime[5]+1900,
 1853:              'weekday' => $ltime[6],
 1854:              'dayyear' => $ltime[7]+1,
 1855:              'dlsav'   => $ltime[8] );
 1856: }
 1857: 
 1858: sub maketime {
 1859:     my %th=@_;
 1860:     return POSIX::mktime(
 1861:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 1862:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,$th{'dlsav'}));
 1863: }
 1864: 
 1865: 
 1866: #########################################
 1867: #
 1868: # Retro-fixing of un-backward-compatible time format
 1869: 
 1870: sub unsqltime {
 1871:     my $timestamp=shift;
 1872:     if ($timestamp=~/^(\d+)\-(\d+)\-(\d+)\s+(\d+)\:(\d+)\:(\d+)$/) {
 1873:        $timestamp=&maketime(
 1874: 	   'year'=>$1,'month'=>$2,'day'=>$3,
 1875:            'hours'=>$4,'minutes'=>$5,'seconds'=>$6);
 1876:     }
 1877:     return $timestamp;
 1878: }
 1879: 
 1880: #########################################
 1881: 
 1882: sub findallcourses {
 1883:     my %courses=();
 1884:     my $now=time;
 1885:     foreach (keys %ENV) {
 1886: 	if ($_=~/^user\.role\.\w+\.\/(\w+)\/(\w+)/) {
 1887: 	    my ($starttime,$endtime)=$ENV{$_};
 1888:             my $active=1;
 1889:             if ($starttime) {
 1890: 		if ($now<$starttime) { $active=0; }
 1891:             }
 1892:             if ($endtime) {
 1893:                 if ($now>$endtime) { $active=0; }
 1894:             }
 1895:             if ($active) { $courses{$1.'_'.$2}=1; }
 1896:         }
 1897:     }
 1898:     return keys %courses;
 1899: }
 1900: 
 1901: ###############################################
 1902: ###############################################
 1903: 
 1904: =pod
 1905: 
 1906: =head1 Domain Template Functions
 1907: 
 1908: =over 4
 1909: 
 1910: =item * &determinedomain()
 1911: 
 1912: Inputs: $domain (usually will be undef)
 1913: 
 1914: Returns: Determines which domain should be used for designs
 1915: 
 1916: =cut
 1917: 
 1918: ###############################################
 1919: sub determinedomain {
 1920:     my $domain=shift;
 1921:    if (! $domain) {
 1922:         # Determine domain if we have not been given one
 1923:         $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
 1924:         if ($ENV{'user.domain'}) { $domain=$ENV{'user.domain'}; }
 1925:         if ($ENV{'request.role.domain'}) { 
 1926:             $domain=$ENV{'request.role.domain'}; 
 1927:         }
 1928:     }
 1929:     return $domain;
 1930: }
 1931: ###############################################
 1932: =pod
 1933: 
 1934: =item * &domainlogo()
 1935: 
 1936: Inputs: $domain (usually will be undef)
 1937: 
 1938: Returns: A link to a domain logo, if the domain logo exists.
 1939: If the domain logo does not exist, a description of the domain.
 1940: 
 1941: =cut
 1942: 
 1943: ###############################################
 1944: sub domainlogo {
 1945:     my $domain = &determinedomain(shift);    
 1946:      # See if there is a logo
 1947:     if (-e '/home/httpd/html/adm/lonDomLogos/'.$domain.'.gif') {
 1948: 	my $lonhttpdPort=$Apache::lonnet::perlvar{'lonhttpdPort'};
 1949: 	if (!defined($lonhttpdPort)) { $lonhttpdPort='8080'; }
 1950:         return '<img src="http://'.$ENV{'HTTP_HOST'}.':'.$lonhttpdPort.
 1951: 	    '/adm/lonDomLogos/'.$domain.'.gif" />';
 1952:     } elsif(exists($Apache::lonnet::domaindescription{$domain})) {
 1953:         return $Apache::lonnet::domaindescription{$domain};
 1954:     } else {
 1955:         return '';
 1956:     }
 1957: }
 1958: ##############################################
 1959: 
 1960: =pod
 1961: 
 1962: =item * &designparm()
 1963: 
 1964: Inputs: $which parameter; $domain (usually will be undef)
 1965: 
 1966: Returns: value of designparamter $which
 1967: 
 1968: =cut
 1969: 
 1970: ##############################################
 1971: sub designparm {
 1972:     my ($which,$domain)=@_;
 1973:     if ($ENV{'browser.blackwhite'} eq 'on') {
 1974: 	if ($which=~/\.(font|alink|vlink|link)$/) {
 1975: 	    return '#000000';
 1976: 	}
 1977: 	if ($which=~/\.(pgbg|sidebg)$/) {
 1978: 	    return '#FFFFFF';
 1979: 	}
 1980: 	if ($which=~/\.tabbg$/) {
 1981: 	    return '#CCCCCC';
 1982: 	}
 1983:     }
 1984:     if ($ENV{'environment.color.'.$which}) {
 1985: 	return $ENV{'environment.color.'.$which};
 1986:     }
 1987:     $domain=&determinedomain($domain);
 1988:     if ($designhash{$domain.'.'.$which}) {
 1989: 	return $designhash{$domain.'.'.$which};
 1990:     } else {
 1991:         return $designhash{'default.'.$which};
 1992:     }
 1993: }
 1994: 
 1995: ###############################################
 1996: ###############################################
 1997: 
 1998: =pod
 1999: 
 2000: =back
 2001: 
 2002: =head1 HTTP Helpers
 2003: 
 2004: =over 4
 2005: 
 2006: =item * &bodytag()
 2007: 
 2008: Returns a uniform header for LON-CAPA web pages.
 2009: 
 2010: Inputs: 
 2011: 
 2012: =over 4
 2013: 
 2014: =item * $title, A title to be displayed on the page.
 2015: 
 2016: =item * $function, the current role (can be undef).
 2017: 
 2018: =item * $addentries, extra parameters for the <body> tag.
 2019: 
 2020: =item * $bodyonly, if defined, only return the <body> tag.
 2021: 
 2022: =item * $domain, if defined, force a given domain.
 2023: 
 2024: =item * $forcereg, if page should register as content page (relevant for 
 2025:             text interface only)
 2026: 
 2027: =back
 2028: 
 2029: Returns: A uniform header for LON-CAPA web pages.  
 2030: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 2031: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 2032: other decorations will be returned.
 2033: 
 2034: =cut
 2035: 
 2036: sub bodytag {
 2037:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg)=@_;
 2038:     unless ($function) {
 2039: 	$function='student';
 2040:         if ($ENV{'request.role'}=~/^(cc|in|ta|ep)/) {
 2041: 	    $function='coordinator';
 2042:         }
 2043: 	if ($ENV{'request.role'}=~/^(su|dc|ad|li)/) {
 2044:             $function='admin';
 2045:         }
 2046:         if (($ENV{'request.role'}=~/^(au|ca)/) ||
 2047:             ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
 2048:             $function='author';
 2049:         }
 2050:     }
 2051:     my $img=&designparm($function.'.img',$domain);
 2052:     my $pgbg=&designparm($function.'.pgbg',$domain);
 2053:     my $tabbg=&designparm($function.'.tabbg',$domain);
 2054:     my $font=&designparm($function.'.font',$domain);
 2055:     my $link=&designparm($function.'.link',$domain);
 2056:     my $alink=&designparm($function.'.alink',$domain);
 2057:     my $vlink=&designparm($function.'.vlink',$domain);
 2058:     my $sidebg=&designparm($function.'.sidebg',$domain);
 2059: # Accessibility font enhance
 2060:     unless ($addentries) { $addentries=''; }
 2061:     if ($ENV{'browser.fontenhance'} eq 'on') {
 2062: 	$addentries.=' style="font-size: x-large"';
 2063:     }
 2064:  # role and realm
 2065:     my ($role,$realm)
 2066:        =&Apache::lonnet::plaintext((split(/\./,$ENV{'request.role'}))[0]);
 2067: # realm
 2068:     if ($ENV{'request.course.id'}) {
 2069: 	$realm=
 2070:          $ENV{'course.'.$ENV{'request.course.id'}.'.description'};
 2071:     }
 2072:     unless ($realm) { $realm='&nbsp;'; }
 2073: # Set messages
 2074:     my $messages=&domainlogo($domain);
 2075: # Port for miniserver
 2076:     my $lonhttpdPort=$Apache::lonnet::perlvar{'lonhttpdPort'};
 2077:     if (!defined($lonhttpdPort)) { $lonhttpdPort='8080'; }
 2078: # construct main body tag
 2079:     my $bodytag = <<END;
 2080: <body bgcolor="$pgbg" text="$font" alink="$alink" vlink="$vlink" link="$link"
 2081: $addentries>
 2082: END
 2083:     my $upperleft='<img src="http://'.$ENV{'HTTP_HOST'}.':'.
 2084:                    $lonhttpdPort.$img.'" />';
 2085:     if ($bodyonly) {
 2086:         return $bodytag;
 2087:     } elsif ($ENV{'browser.interface'} eq 'textual') {
 2088: # Accessibility
 2089:         return $bodytag.&Apache::lonmenu::menubuttons($forcereg,'web',
 2090:                                                       $forcereg).
 2091:                '<h1>LON-CAPA: '.$title.'</h1>';
 2092:     } elsif ($ENV{'environment.remote'} eq 'off') {
 2093: # No Remote
 2094:         return $bodytag.&Apache::lonmenu::menubuttons($forcereg,'web',
 2095:                                                       $forcereg).
 2096:                '<table bgcolor="'.$pgbg.'" width="100%" border="0" cellspacing="3" cellpadding="3"><tr><td bgcolor="'.$tabbg.'"><font size="+3" color="'.$font.'"><b>'.$title.
 2097: '</b></font></td></tr></table>';
 2098:     }
 2099: 
 2100: #
 2101: # Top frame rendering, Remote is up
 2102: #
 2103:     return(<<ENDBODY);
 2104: $bodytag
 2105: <table width="100%" cellspacing="0" border="0" cellpadding="0">
 2106: <tr><td bgcolor="$sidebg">
 2107: $upperleft</td>
 2108: <td bgcolor="$sidebg" align="right">$messages&nbsp;</td>
 2109: </tr>
 2110: <tr>
 2111: <td rowspan="3" bgcolor="$tabbg">
 2112: &nbsp;<font size="5"><b>$title</b></font>
 2113: <td bgcolor="$tabbg"  align="right">
 2114: <font size="2">
 2115:     $ENV{'environment.firstname'}
 2116:     $ENV{'environment.middlename'}
 2117:     $ENV{'environment.lastname'}
 2118:     $ENV{'environment.generation'}
 2119:     </font>&nbsp;
 2120: </td>
 2121: </tr>
 2122: <tr><td bgcolor="$tabbg" align="right">
 2123: <font size="2">$role</font>&nbsp;
 2124: </td></tr>
 2125: <tr>
 2126: <td bgcolor="$tabbg" align="right"><font size="2">$realm</font>&nbsp;</td></tr>
 2127: </table><br>
 2128: ENDBODY
 2129: }
 2130: 
 2131: ###############################################
 2132: 
 2133: sub get_posted_cgi {
 2134:     my $r=shift;
 2135: 
 2136:     my $buffer;
 2137:     
 2138:     $r->read($buffer,$r->header_in('Content-length'),0);
 2139:     unless ($buffer=~/^(\-+\w+)\s+Content\-Disposition\:\s*form\-data/si) {
 2140: 	my @pairs=split(/&/,$buffer);
 2141: 	my $pair;
 2142: 	foreach $pair (@pairs) {
 2143: 	    my ($name,$value) = split(/=/,$pair);
 2144: 	    $value =~ tr/+/ /;
 2145: 	    $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 2146: 	    $name  =~ tr/+/ /;
 2147: 	    $name  =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 2148: 	    &add_to_env("form.$name",$value);
 2149: 	}
 2150:     } else {
 2151: 	my $contentsep=$1;
 2152: 	my @lines = split (/\n/,$buffer);
 2153: 	my $name='';
 2154: 	my $value='';
 2155: 	my $fname='';
 2156: 	my $fmime='';
 2157: 	my $i;
 2158: 	for ($i=0;$i<=$#lines;$i++) {
 2159: 	    if ($lines[$i]=~/^$contentsep/) {
 2160: 		if ($name) {
 2161: 		    chomp($value);
 2162: 		    if ($fname) {
 2163: 			$ENV{"form.$name.filename"}=$fname;
 2164: 			$ENV{"form.$name.mimetype"}=$fmime;
 2165: 		    } else {
 2166: 			$value=~s/\s+$//s;
 2167: 		    }
 2168: 		    &add_to_env("form.$name",$value);
 2169: 		}
 2170: 		if ($i<$#lines) {
 2171: 		    $i++;
 2172: 		    $lines[$i]=~
 2173: 		/Content\-Disposition\:\s*form\-data\;\s*name\=\"([^\"]+)\"/i;
 2174: 		    $name=$1;
 2175: 		    $value='';
 2176: 		    if ($lines[$i]=~/filename\=\"([^\"]+)\"/i) {
 2177: 			$fname=$1;
 2178: 			if 
 2179:                             ($lines[$i+1]=~/Content\-Type\:\s*([\w\-\/]+)/i) {
 2180: 				$fmime=$1;
 2181: 				$i++;
 2182: 			    } else {
 2183: 				$fmime='';
 2184: 			    }
 2185: 		    } else {
 2186: 			$fname='';
 2187: 			$fmime='';
 2188: 		    }
 2189: 		    $i++;
 2190: 		}
 2191: 	    } else {
 2192: 		$value.=$lines[$i]."\n";
 2193: 	    }
 2194: 	}
 2195:     }
 2196:     $ENV{'request.method'}=$ENV{'REQUEST_METHOD'};
 2197:     $r->method_number(M_GET);
 2198:     $r->method('GET');
 2199:     $r->headers_in->unset('Content-length');
 2200: }
 2201: 
 2202: =pod
 2203: 
 2204: =item * get_unprocessed_cgi($query,$possible_names)
 2205: 
 2206: Modify the %ENV hash to contain unprocessed CGI form parameters held in
 2207: $query.  The parameters listed in $possible_names (an array reference),
 2208: will be set in $ENV{'form.name'} if they do not already exist.
 2209: 
 2210: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
 2211: $possible_names is an ref to an array of form element names.  As an example:
 2212: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
 2213: will result in $ENV{'form.uname'} and $ENV{'form.udom'} being set.
 2214: 
 2215: =cut
 2216: 
 2217: sub get_unprocessed_cgi {
 2218:   my ($query,$possible_names)= @_;
 2219:   # $Apache::lonxml::debug=1;
 2220:   foreach (split(/&/,$query)) {
 2221:     my ($name, $value) = split(/=/,$_);
 2222:     $name = &Apache::lonnet::unescape($name);
 2223:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
 2224:       $value =~ tr/+/ /;
 2225:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 2226:       &Apache::lonxml::debug("Seting :$name: to :$value:");
 2227:       unless (defined($ENV{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
 2228:     }
 2229:   }
 2230: }
 2231: 
 2232: =pod
 2233: 
 2234: =item * cacheheader() 
 2235: 
 2236: returns cache-controlling header code
 2237: 
 2238: =cut
 2239: 
 2240: sub cacheheader {
 2241:   unless ($ENV{'request.method'} eq 'GET') { return ''; }
 2242:   my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 2243:   my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
 2244:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
 2245:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
 2246:   return $output;
 2247: }
 2248: 
 2249: =pod
 2250: 
 2251: =item * no_cache($r) 
 2252: 
 2253: specifies header code to not have cache
 2254: 
 2255: =cut
 2256: 
 2257: sub no_cache {
 2258:   my ($r) = @_;
 2259:   unless ($ENV{'request.method'} eq 'GET') { return ''; }
 2260:   #my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 2261:   $r->no_cache(1);
 2262:   $r->header_out("Pragma" => "no-cache");
 2263:   #$r->header_out("Expires" => $date);
 2264: }
 2265: 
 2266: =pod
 2267: 
 2268: =item * add_to_env($name,$value) 
 2269: 
 2270: adds $name to the %ENV hash with value
 2271: $value, if $name already exists, the entry is converted to an array
 2272: reference and $value is added to the array.
 2273: 
 2274: =cut
 2275: 
 2276: sub add_to_env {
 2277:   my ($name,$value)=@_;
 2278:   if (defined($ENV{$name})) {
 2279:     if (ref($ENV{$name})) {
 2280:       #already have multiple values
 2281:       push(@{ $ENV{$name} },$value);
 2282:     } else {
 2283:       #first time seeing multiple values, convert hash entry to an arrayref
 2284:       my $first=$ENV{$name};
 2285:       undef($ENV{$name});
 2286:       push(@{ $ENV{$name} },$first,$value);
 2287:     }
 2288:   } else {
 2289:     $ENV{$name}=$value;
 2290:   }
 2291: }
 2292: 
 2293: =pod
 2294: 
 2295: =back 
 2296: 
 2297: =head1 CSV Upload/Handling functions
 2298: 
 2299: =over 4
 2300: 
 2301: =item * upfile_store($r)
 2302: 
 2303: Store uploaded file, $r should be the HTTP Request object,
 2304: needs $ENV{'form.upfile'}
 2305: returns $datatoken to be put into hidden field
 2306: 
 2307: =cut
 2308: 
 2309: sub upfile_store {
 2310:     my $r=shift;
 2311:     $ENV{'form.upfile'}=~s/\r/\n/gs;
 2312:     $ENV{'form.upfile'}=~s/\f/\n/gs;
 2313:     $ENV{'form.upfile'}=~s/\n+/\n/gs;
 2314:     $ENV{'form.upfile'}=~s/\n+$//gs;
 2315: 
 2316:     my $datatoken=$ENV{'user.name'}.'_'.$ENV{'user.domain'}.
 2317: 	'_enroll_'.$ENV{'request.course.id'}.'_'.time.'_'.$$;
 2318:     {
 2319: 	my $fh=Apache::File->new('>'.$r->dir_config('lonDaemons').
 2320: 				 '/tmp/'.$datatoken.'.tmp');
 2321: 	print $fh $ENV{'form.upfile'};
 2322:     }
 2323:     return $datatoken;
 2324: }
 2325: 
 2326: =pod
 2327: 
 2328: =item * load_tmp_file($r)
 2329: 
 2330: Load uploaded file from tmp, $r should be the HTTP Request object,
 2331: needs $ENV{'form.datatoken'},
 2332: sets $ENV{'form.upfile'} to the contents of the file
 2333: 
 2334: =cut
 2335: 
 2336: sub load_tmp_file {
 2337:     my $r=shift;
 2338:     my @studentdata=();
 2339:     {
 2340: 	my $fh;
 2341: 	if ($fh=Apache::File->new($r->dir_config('lonDaemons').
 2342: 				  '/tmp/'.$ENV{'form.datatoken'}.'.tmp')) {
 2343: 	    @studentdata=<$fh>;
 2344: 	}
 2345:     }
 2346:     $ENV{'form.upfile'}=join('',@studentdata);
 2347: }
 2348: 
 2349: =pod
 2350: 
 2351: =item * upfile_record_sep()
 2352: 
 2353: Separate uploaded file into records
 2354: returns array of records,
 2355: needs $ENV{'form.upfile'} and $ENV{'form.upfiletype'}
 2356: 
 2357: =cut
 2358: 
 2359: sub upfile_record_sep {
 2360:     if ($ENV{'form.upfiletype'} eq 'xml') {
 2361:     } else {
 2362: 	return split(/\n/,$ENV{'form.upfile'});
 2363:     }
 2364: }
 2365: 
 2366: =pod
 2367: 
 2368: =item * record_sep($record)
 2369: 
 2370: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $ENV{'form.upfiletype'}
 2371: 
 2372: =cut
 2373: 
 2374: sub record_sep {
 2375:     my $record=shift;
 2376:     my %components=();
 2377:     if ($ENV{'form.upfiletype'} eq 'xml') {
 2378:     } elsif ($ENV{'form.upfiletype'} eq 'space') {
 2379:         my $i=0;
 2380:         foreach (split(/\s+/,$record)) {
 2381:             my $field=$_;
 2382:             $field=~s/^(\"|\')//;
 2383:             $field=~s/(\"|\')$//;
 2384:             $components{$i}=$field;
 2385:             $i++;
 2386:         }
 2387:     } elsif ($ENV{'form.upfiletype'} eq 'tab') {
 2388:         my $i=0;
 2389:         foreach (split(/\t+/,$record)) {
 2390:             my $field=$_;
 2391:             $field=~s/^(\"|\')//;
 2392:             $field=~s/(\"|\')$//;
 2393:             $components{$i}=$field;
 2394:             $i++;
 2395:         }
 2396:     } else {
 2397:         my @allfields=split(/\,/,$record);
 2398:         my $i=0;
 2399:         my $j;
 2400:         for ($j=0;$j<=$#allfields;$j++) {
 2401:             my $field=$allfields[$j];
 2402:             if ($field=~/^\s*(\"|\')/) {
 2403: 		my $delimiter=$1;
 2404:                 while (($field!~/$delimiter$/) && ($j<$#allfields)) {
 2405: 		    $j++;
 2406: 		    $field.=','.$allfields[$j];
 2407: 		}
 2408:                 $field=~s/^\s*$delimiter//;
 2409:                 $field=~s/$delimiter\s*$//;
 2410:             }
 2411:             $components{$i}=$field;
 2412: 	    $i++;
 2413:         }
 2414:     }
 2415:     return %components;
 2416: }
 2417: 
 2418: =pod
 2419: 
 2420: =item * upfile_select_html()
 2421: 
 2422: return HTML code to select file and specify its type
 2423: 
 2424: =cut
 2425: 
 2426: sub upfile_select_html {
 2427:     return (<<'ENDUPFORM');
 2428: <input type="file" name="upfile" size="50" />
 2429: <br />Type: <select name="upfiletype">
 2430: <option value="csv">CSV (comma separated values, spreadsheet)</option>
 2431: <option value="space">Space separated</option>
 2432: <option value="tab">Tabulator separated</option>
 2433: <option value="xml">HTML/XML</option>
 2434: </select>
 2435: ENDUPFORM
 2436: }
 2437: 
 2438: =pod
 2439: 
 2440: =item * csv_print_samples($r,$records)
 2441: 
 2442: Prints a table of sample values from each column uploaded $r is an
 2443: Apache Request ref, $records is an arrayref from
 2444: &Apache::loncommon::upfile_record_sep
 2445: 
 2446: =cut
 2447: 
 2448: sub csv_print_samples {
 2449:     my ($r,$records) = @_;
 2450:     my (%sone,%stwo,%sthree);
 2451:     %sone=&record_sep($$records[0]);
 2452:     if (defined($$records[1])) {%stwo=&record_sep($$records[1]);}
 2453:     if (defined($$records[2])) {%sthree=&record_sep($$records[2]);}
 2454: 
 2455:     $r->print('Samples<br /><table border="2"><tr>');
 2456:     foreach (sort({$a <=> $b} keys(%sone))) { $r->print('<th>Column&nbsp;'.($_+1).'</th>'); }
 2457:     $r->print('</tr>');
 2458:     foreach my $hash (\%sone,\%stwo,\%sthree) {
 2459: 	$r->print('<tr>');
 2460: 	foreach (sort({$a <=> $b} keys(%sone))) {
 2461: 	    $r->print('<td>');
 2462: 	    if (defined($$hash{$_})) { $r->print($$hash{$_}); }
 2463: 	    $r->print('</td>');
 2464: 	}
 2465: 	$r->print('</tr>');
 2466:     }
 2467:     $r->print('</tr></table><br />'."\n");
 2468: }
 2469: 
 2470: =pod
 2471: 
 2472: =item * csv_print_select_table($r,$records,$d)
 2473: 
 2474: Prints a table to create associations between values and table columns.
 2475: $r is an Apache Request ref,
 2476: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 2477: $d is an array of 2 element arrays (internal name, displayed name)
 2478: 
 2479: =cut
 2480: 
 2481: sub csv_print_select_table {
 2482:     my ($r,$records,$d) = @_;
 2483:     my $i=0;my %sone;
 2484:     %sone=&record_sep($$records[0]);
 2485:     $r->print('Associate columns with student attributes.'."\n".
 2486: 	     '<table border="2"><tr><th>Attribute</th><th>Column</th></tr>'."\n");
 2487:     foreach (@$d) {
 2488: 	my ($value,$display)=@{ $_ };
 2489: 	$r->print('<tr><td>'.$display.'</td>');
 2490: 
 2491: 	$r->print('<td><select name=f'.$i.
 2492: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 2493: 	$r->print('<option value="none"></option>');
 2494: 	foreach (sort({$a <=> $b} keys(%sone))) {
 2495: 	    $r->print('<option value="'.$_.'">Column '.($_+1).'</option>');
 2496: 	}
 2497: 	$r->print('</select></td></tr>'."\n");
 2498: 	$i++;
 2499:     }
 2500:     $i--;
 2501:     return $i;
 2502: }
 2503: 
 2504: =pod
 2505: 
 2506: =item * csv_samples_select_table($r,$records,$d)
 2507: 
 2508: Prints a table of sample values from the upload and can make associate samples to internal names.
 2509: 
 2510: $r is an Apache Request ref,
 2511: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 2512: $d is an array of 2 element arrays (internal name, displayed name)
 2513: 
 2514: =cut
 2515: 
 2516: sub csv_samples_select_table {
 2517:     my ($r,$records,$d) = @_;
 2518:     my %sone; my %stwo; my %sthree;
 2519:     my $i=0;
 2520: 
 2521:     $r->print('<table border=2><tr><th>Field</th><th>Samples</th></tr>');
 2522:     %sone=&record_sep($$records[0]);
 2523:     if (defined($$records[1])) {%stwo=&record_sep($$records[1]);}
 2524:     if (defined($$records[2])) {%sthree=&record_sep($$records[2]);}
 2525: 
 2526:     foreach (sort keys %sone) {
 2527: 	$r->print('<tr><td><select name=f'.$i.
 2528: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 2529: 	foreach (@$d) {
 2530: 	    my ($value,$display)=@{ $_ };
 2531: 	    $r->print('<option value='.$value.'>'.$display.'</option>');
 2532: 	}
 2533: 	$r->print('</select></td><td>');
 2534: 	if (defined($sone{$_})) { $r->print($sone{$_}."</br>\n"); }
 2535: 	if (defined($stwo{$_})) { $r->print($stwo{$_}."</br>\n"); }
 2536: 	if (defined($sthree{$_})) { $r->print($sthree{$_}."</br>\n"); }
 2537: 	$r->print('</td></tr>');
 2538: 	$i++;
 2539:     }
 2540:     $i--;
 2541:     return($i);
 2542: }
 2543: 
 2544: =pod
 2545: 
 2546: =item * check_if_partid_hidden($id,$symb,$udom,$uname)
 2547: 
 2548: Returns either 1 or undef
 2549: 
 2550: 1 if the part is to be hidden, undef if it is to be shown
 2551: 
 2552: Arguments are:
 2553: 
 2554: $id the id of the part to be checked
 2555: $symb, optional the symb of the resource to check
 2556: $udom, optional the domain of the user to check for
 2557: $uname, optional the username of the user to check for
 2558: 
 2559: =cut
 2560: 
 2561: sub check_if_partid_hidden {
 2562:     my ($id,$symb,$udom,$uname) = @_;
 2563:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.parameter_hiddenparts',
 2564: 					 $symb,$udom,$uname);
 2565:     my @hiddenlist=split(/,/,$hiddenparts);
 2566:     foreach my $checkid (@hiddenlist) {
 2567: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return 1; }
 2568:     }
 2569:     return undef;
 2570: }
 2571: 
 2572: =pod
 2573: 
 2574: =back
 2575: 
 2576: =cut
 2577: 
 2578: 1;
 2579: __END__;
 2580: 

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