File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.62: download - view: text, annotated - select for diffs
Wed Aug 28 14:11:27 2002 UTC (21 years, 9 months ago) by www
Branches: MAIN
CVS tags: HEAD
Convenience links to about-me page, syllabus, and email.

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.62 2002/08/28 14:11:27 www 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/11,12/12,12/17 Scott Harrison
   31: # 12/21 Gerd Kortemeyer
   32: # 12/21 Scott Harrison
   33: # 12/25,12/28 Gerd Kortemeyer
   34: # YEAR=2002
   35: # 1/4 Gerd Kortemeyer
   36: # 6/24,7/2 H. K. Ng
   37: 
   38: # Makes a table out of the previous attempts
   39: # Inputs result_from_symbread, user, domain, course_id
   40: # Reads in non-network-related .tab files
   41: 
   42: # POD header:
   43: 
   44: =pod
   45: 
   46: =head1 NAME
   47: 
   48: Apache::loncommon - pile of common routines
   49: 
   50: =head1 SYNOPSIS
   51: 
   52: Referenced by other mod_perl Apache modules.
   53: 
   54: Invocation:
   55:  &Apache::loncommon::SUBROUTINENAME(ARGUMENTS);
   56: 
   57: =head1 INTRODUCTION
   58: 
   59: Common collection of used subroutines.  This collection helps remove
   60: redundancy from other modules and increase efficiency of memory usage.
   61: 
   62: Current things done:
   63: 
   64:  Makes a table out of the previous homework attempts
   65:  Inputs result_from_symbread, user, domain, course_id
   66:  Reads in non-network-related .tab files
   67: 
   68: This is part of the LearningOnline Network with CAPA project
   69: described at http://www.lon-capa.org.
   70: 
   71: =head2 General Subroutines
   72: 
   73: =over 4
   74: 
   75: =cut 
   76: 
   77: # End of POD header
   78: package Apache::loncommon;
   79: 
   80: use strict;
   81: use Apache::lonnet();
   82: use GDBM_File;
   83: use POSIX qw(strftime mktime);
   84: use Apache::Constants qw(:common);
   85: use Apache::lonmsg();
   86: my $readit;
   87: 
   88: =pod 
   89: 
   90: =item Global Variables
   91: 
   92: =over 4
   93: 
   94: =cut
   95: # ----------------------------------------------- Filetypes/Languages/Copyright
   96: my %language;
   97: my %cprtag;
   98: my %fe; my %fd;
   99: my %category_extensions;
  100: 
  101: # ---------------------------------------------- Thesaurus variables
  102: 
  103: =pod
  104: 
  105: =item %Keywords  
  106: 
  107: A hash used by &keyword to determine if a word is considered a keyword.
  108: 
  109: =item $thesaurus_db_file
  110: 
  111: Scalar containing the full path to the thesaurus database.                 
  112: 
  113: =cut
  114: 
  115: my %Keywords;
  116: my $thesaurus_db_file;
  117: 
  118: 
  119: =pod
  120: 
  121: =back
  122: 
  123: =cut
  124: 
  125: # ----------------------------------------------------------------------- BEGIN
  126: 
  127: =pod
  128: 
  129: =item BEGIN() 
  130: 
  131: Initialize values from language.tab, copyright.tab, filetypes.tab,
  132: thesaurus.tab, and filecategories.tab.
  133: 
  134: =cut
  135: 
  136: # ----------------------------------------------------------------------- BEGIN
  137: 
  138: BEGIN {
  139:     # Variable initialization
  140:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  141:     #
  142:     unless ($readit) {
  143: # ------------------------------------------------------------------- languages
  144:     {
  145: 	my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.
  146: 				 '/language.tab');
  147: 	if ($fh) {
  148: 	    while (<$fh>) {
  149: 		next if /^\#/;
  150: 		chomp;
  151: 		my ($key,$val)=(split(/\s+/,$_,2));
  152: 		$language{$key}=$val;
  153: 	    }
  154: 	}
  155:     }
  156: # ------------------------------------------------------------------ copyrights
  157:     {
  158: 	my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonIncludes'}.
  159: 				  '/copyright.tab');
  160: 	if ($fh) {
  161: 	    while (<$fh>) {
  162: 		next if /^\#/;
  163: 		chomp;
  164: 		my ($key,$val)=(split(/\s+/,$_,2));
  165: 		$cprtag{$key}=$val;
  166: 	    }
  167: 	}
  168:     }
  169: # ------------------------------------------------------------- file categories
  170:     {
  171: 	my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.
  172: 				  '/filecategories.tab');
  173: 	if ($fh) {
  174: 	    while (<$fh>) {
  175: 		next if /^\#/;
  176: 		chomp;
  177: 		my ($extension,$category)=(split(/\s+/,$_,2));
  178: 		push @{$category_extensions{lc($category)}},$extension;
  179: 	    }
  180: 	}
  181:     }
  182: # ------------------------------------------------------------------ file types
  183:     {
  184: 	my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.
  185: 	       '/filetypes.tab');
  186: 	if ($fh) {
  187:             while (<$fh>) {
  188: 		next if (/^\#/);
  189: 		chomp;
  190: 		my ($ending,$emb,$descr)=split(/\s+/,$_,3);
  191: 		if ($descr ne '') { 
  192: 		    $fe{$ending}=lc($emb);
  193: 		    $fd{$ending}=$descr;
  194: 		}
  195: 	    }
  196: 	}
  197:     }
  198:     &Apache::lonnet::logthis(
  199:               "<font color=yellow>INFO: Read file types</font>");
  200:     $readit=1;
  201:     }  # end of unless($readit) 
  202:     
  203: }
  204: # ============================================================= END BEGIN BLOCK
  205: ###############################################################
  206: ##           HTML and Javascript Helper Functions            ##
  207: ###############################################################
  208: 
  209: =pod 
  210: 
  211: =item browser_and_searcher_javascript 
  212: 
  213: Returns scalar containing javascript to open a browser window
  214: or a searcher window.  Also creates 
  215: 
  216: =over 4
  217: 
  218: =item openbrowser(formname,elementname,only,omit) [javascript]
  219: 
  220: inputs: formname, elementname, only, omit
  221: 
  222: formname and elementname indicate the name of the html form and name of
  223: the element that the results of the browsing selection are to be placed in. 
  224: 
  225: Specifying 'only' will restrict the browser to displaying only files
  226: with the given extension.  Can be a comma seperated list.
  227: 
  228: Specifying 'omit' will restrict the browser to NOT displaying files
  229: with the given extension.  Can be a comma seperated list.
  230: 
  231: =item opensearcher(formname, elementname) [javascript]
  232: 
  233: Inputs: formname, elementname
  234: 
  235: formname and elementname specify the name of the html form and the name
  236: of the element the selection from the search results will be placed in.
  237: 
  238: =back
  239: 
  240: =cut
  241: 
  242: ###############################################################
  243: sub browser_and_searcher_javascript {
  244:     return <<END;
  245:     var editbrowser = null;
  246:     function openbrowser(formname,elementname,only,omit) {
  247:         var url = '/res/?';
  248:         if (editbrowser == null) {
  249:             url += 'launch=1&';
  250:         }
  251:         url += 'catalogmode=interactive&';
  252:         url += 'mode=edit&';
  253:         url += 'form=' + formname + '&';
  254:         if (only != null) {
  255:             url += 'only=' + only + '&';
  256:         } 
  257:         if (omit != null) {
  258:             url += 'omit=' + omit + '&';
  259:         }
  260:         url += 'element=' + elementname + '';
  261:         var title = 'Browser';
  262:         var options = 'scrollbars=1,resizable=1,menubar=0';
  263:         options += ',width=700,height=600';
  264:         editbrowser = open(url,title,options,'1');
  265:         editbrowser.focus();
  266:     }
  267:     var editsearcher;
  268:     function opensearcher(formname,elementname) {
  269:         var url = '/adm/searchcat?';
  270:         if (editsearcher == null) {
  271:             url += 'launch=1&';
  272:         }
  273:         url += 'catalogmode=interactive&';
  274:         url += 'mode=edit&';
  275:         url += 'form=' + formname + '&';
  276:         url += 'element=' + elementname + '';
  277:         var title = 'Search';
  278:         var options = 'scrollbars=1,resizable=1,menubar=0';
  279:         options += ',width=700,height=600';
  280:         editsearcher = open(url,title,options,'1');
  281:         editsearcher.focus();
  282:     }
  283: END
  284: }
  285: 
  286: 
  287: 
  288: ###############################################################
  289: 
  290: =pod
  291: 
  292: =item linked_select_forms(...)
  293: 
  294: linked_select_forms returns a string containing a <script></script> block
  295: and html for two <select> menus.  The select menus will be linked in that
  296: changing the value of the first menu will result in new values being placed
  297: in the second menu.  The values in the select menu will appear in alphabetical
  298: order.
  299: 
  300: linked_select_forms takes the following ordered inputs:
  301: 
  302: =over 4
  303: 
  304: =item $formname, the name of the <form> tag
  305: 
  306: =item $middletext, the text which appears between the <select> tags
  307: 
  308: =item $firstdefault, the default value for the first menu
  309: 
  310: =item $firstselectname, the name of the first <select> tag
  311: 
  312: =item $secondselectname, the name of the second <select> tag
  313: 
  314: =item $hashref, a reference to a hash containing the data for the menus.
  315: 
  316: =back 
  317: 
  318: Below is an example of such a hash.  Only the 'text', 'default', and 
  319: 'select2' keys must appear as stated.  keys(%menu) are the possible 
  320: values for the first select menu.  The text that coincides with the 
  321: first menu value is given in $menu{$choice1}->{'text'}.  The values 
  322: and text for the second menu are given in the hash pointed to by 
  323: $menu{$choice1}->{'select2'}.  
  324: 
  325: my %menu = ( A1 => { text =>"Choice A1" ,
  326:                       default => "B3",
  327:                       select2 => { 
  328:                           B1 => "Choice B1",
  329:                           B2 => "Choice B2",
  330:                           B3 => "Choice B3",
  331:                           B4 => "Choice B4"
  332:                           }
  333:                   },
  334:               A2 => { text =>"Choice A2" ,
  335:                       default => "C2",
  336:                       select2 => { 
  337:                           C1 => "Choice C1",
  338:                           C2 => "Choice C2",
  339:                           C3 => "Choice C3"
  340:                           }
  341:                   },
  342:               A3 => { text =>"Choice A3" ,
  343:                       default => "D6",
  344:                       select2 => { 
  345:                           D1 => "Choice D1",
  346:                           D2 => "Choice D2",
  347:                           D3 => "Choice D3",
  348:                           D4 => "Choice D4",
  349:                           D5 => "Choice D5",
  350:                           D6 => "Choice D6",
  351:                           D7 => "Choice D7"
  352:                           }
  353:                   }
  354:               );
  355: 
  356: =cut
  357: 
  358: # ------------------------------------------------
  359: 
  360: sub linked_select_forms {
  361:     my ($formname,
  362:         $middletext,
  363:         $firstdefault,
  364:         $firstselectname,
  365:         $secondselectname, 
  366:         $hashref
  367:         ) = @_;
  368:     my $second = "document.$formname.$secondselectname";
  369:     my $first = "document.$formname.$firstselectname";
  370:     # output the javascript to do the changing
  371:     my $result = '';
  372:     $result.="<script>\n";
  373:     $result.="var select2data = new Object();\n";
  374:     $" = '","';
  375:     my $debug = '';
  376:     foreach my $s1 (sort(keys(%$hashref))) {
  377:         $result.="select2data.d_$s1 = new Object();\n";        
  378:         $result.="select2data.d_$s1.def = new String('".
  379:             $hashref->{$s1}->{'default'}."');\n";
  380:         $result.="select2data.d_$s1.values = new Array(";        
  381:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
  382:         $result.="\"@s2values\");\n";
  383:         $result.="select2data.d_$s1.texts = new Array(";        
  384:         my @s2texts;
  385:         foreach my $value (@s2values) {
  386:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
  387:         }
  388:         $result.="\"@s2texts\");\n";
  389:     }
  390:     $"=' ';
  391:     $result.= <<"END";
  392: 
  393: function select1_changed() {
  394:     // Determine new choice
  395:     var newvalue = "d_" + $first.value;
  396:     // update select2
  397:     var values     = select2data[newvalue].values;
  398:     var texts      = select2data[newvalue].texts;
  399:     var select2def = select2data[newvalue].def;
  400:     var i;
  401:     // out with the old
  402:     for (i = 0; i < $second.options.length; i++) {
  403:         $second.options[i] = null;
  404:     }
  405:     // in with the nuclear
  406:     for (i=0;i<values.length; i++) {
  407:         $second.options[i] = new Option(values[i]);
  408:         $second.options[i].text = texts[i];
  409:         if (values[i] == select2def) {
  410:             $second.options[i].selected = true;
  411:         }
  412:     }
  413: }
  414: </script>
  415: END
  416:     # output the initial values for the selection lists
  417:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
  418:     foreach my $value (sort(keys(%$hashref))) {
  419:         $result.="    <option value=\"$value\" ";
  420:         $result.=" selected=\"true\" " if ($value eq $firstdefault);
  421:         $result.=">$hashref->{$value}->{'text'}</option>\n";
  422:     }
  423:     $result .= "</select>\n";
  424:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
  425:     $result .= $middletext;
  426:     $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
  427:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
  428:     foreach my $value (sort(keys(%select2))) {
  429:         $result.="    <option value=\"$value\" ";        
  430:         $result.=" selected=\"true\" " if ($value eq $seconddefault);
  431:         $result.=">$select2{$value}</option>\n";
  432:     }
  433:     $result .= "</select>\n";
  434:     #    return $debug;
  435:     return $result;
  436: }   #  end of sub linked_select_forms {
  437: 
  438: ###############################################################
  439: 
  440: =pod
  441: 
  442: =item help_open_topic($topic, $text, $stayOnPage, $width, $height)
  443: 
  444: Returns a string corresponding to an HTML link to the given help $topic, where $topic corresponds to the name of a .tex file in /home/httpd/html/adm/help/tex, with underscores replaced by spaces.
  445: 
  446: $text will optionally be linked to the same topic, allowing you to link text in addition to the graphic. If you do not want to link text, but wish to specify one of the later parameters, pass an empty string.
  447: 
  448: $stayOnPage is a value that will be interpreted as a boolean. If true, the link will not open a new window. If false, the link will open a new window using Javascript. (Default is false.)
  449: 
  450: $width and $height are optional numerical parameters that will override the width and height of the popped up window, which may be useful for certain help topics with big pictures included.
  451: 
  452: =cut
  453: 
  454: sub help_open_topic {
  455:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
  456:     $text = "" if (not defined $text);
  457:     $stayOnPage = 0 if (not defined $stayOnPage);
  458:     $width = 350 if (not defined $width);
  459:     $height = 400 if (not defined $height);
  460:     my $filename = $topic;
  461:     $filename =~ s/ /_/g;
  462: 
  463:     my $template = "";
  464:     my $link;
  465: 
  466:     if (!$stayOnPage)
  467:     {
  468: 	$link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height'))";
  469:     }
  470:     else
  471:     {
  472: 	$link = "/adm/help/${filename}.hlp";
  473:     }
  474: 
  475:     # Add the text
  476:     if ($text ne "")
  477:     {
  478: 	$template .= "<a href=\"$link\">$text</a> ";
  479:     }
  480: 
  481:     # Add the graphic
  482:     $template .= <<"ENDTEMPLATE";
  483: <a href="$link"><image src="/adm/help/gif/smallHelp.gif" border="0" alt="(Help: $topic)" /></a>
  484: ENDTEMPLATE
  485: 
  486:     return $template;
  487: 
  488: }
  489: 
  490: =pod
  491: 
  492: =item csv_translate($text) 
  493: 
  494: Translate $text to allow it to be output as a 'comma seperated values' 
  495: format.
  496: 
  497: =cut
  498: 
  499: sub csv_translate {
  500:     my $text = shift;
  501:     $text =~ s/\"/\"\"/g;
  502:     $text =~ s/\n//g;
  503:     return $text;
  504: }
  505: 
  506: ###############################################################
  507: ##        Home server <option> list generating code          ##
  508: ###############################################################
  509: #-------------------------------------------
  510: 
  511: =pod
  512: 
  513: =item get_domains()
  514: 
  515: Returns an array containing each of the domains listed in the hosts.tab
  516: file.
  517: 
  518: =cut
  519: 
  520: #-------------------------------------------
  521: sub get_domains {
  522:     # The code below was stolen from "The Perl Cookbook", p 102, 1st ed.
  523:     my @domains;
  524:     my %seen;
  525:     foreach (sort values(%Apache::lonnet::hostdom)) {
  526:         push (@domains,$_) unless $seen{$_}++;
  527:     }
  528:     return @domains;
  529: }
  530: 
  531: #-------------------------------------------
  532: 
  533: =pod
  534: 
  535: =item select_dom_form($defdom,$name)
  536: 
  537: Returns a string containing a <select name='$name' size='1'> form to 
  538: allow a user to select the domain to preform an operation in.  
  539: See loncreateuser.pm for an example invocation and use.
  540: 
  541: =cut
  542: 
  543: #-------------------------------------------
  544: sub select_dom_form {
  545:     my ($defdom,$name) = @_;
  546:     my @domains = get_domains();
  547:     my $selectdomain = "<select name=\"$name\" size=\"1\">\n";
  548:     foreach (@domains) {
  549:         $selectdomain.="<option value=\"$_\" ".
  550:             ($_ eq $defdom ? 'selected' : '').
  551:                 ">$_</option>\n";
  552:     }
  553:     $selectdomain.="</select>";
  554:     return $selectdomain;
  555: }
  556: 
  557: #-------------------------------------------
  558: 
  559: =pod
  560: 
  561: =item get_library_servers($domain)
  562: 
  563: Returns a hash which contains keys like '103l3' and values like 
  564: 'kirk.lite.msu.edu'.  All of the keys will be for machines in the
  565: given $domain.
  566: 
  567: =cut
  568: 
  569: #-------------------------------------------
  570: sub get_library_servers {
  571:     my $domain = shift;
  572:     my %library_servers;
  573:     foreach (keys(%Apache::lonnet::libserv)) {
  574:         if ($Apache::lonnet::hostdom{$_} eq $domain) {
  575:             $library_servers{$_} = $Apache::lonnet::hostname{$_};
  576:         }
  577:     }
  578:     return %library_servers;
  579: }
  580: 
  581: #-------------------------------------------
  582: 
  583: =pod
  584: 
  585: =item home_server_option_list($domain)
  586: 
  587: returns a string which contains an <option> list to be used in a 
  588: <select> form input.  See loncreateuser.pm for an example.
  589: 
  590: =cut
  591: 
  592: #-------------------------------------------
  593: sub home_server_option_list {
  594:     my $domain = shift;
  595:     my %servers = &get_library_servers($domain);
  596:     my $result = '';
  597:     foreach (sort keys(%servers)) {
  598:         $result.=
  599:             '<option value="'.$_.'">'.$_.' '.$servers{$_}."</option>\n";
  600:     }
  601:     return $result;
  602: }
  603: ###############################################################
  604: ##    End of home server <option> list generating code       ##
  605: ###############################################################
  606: 
  607: ###############################################################
  608: ##    Authentication changing form generation subroutines    ##
  609: ###############################################################
  610: ##
  611: ## All of the authform_xxxxxxx subroutines take their inputs in a
  612: ## hash, and have reasonable default values.
  613: ##
  614: ##    formname = the name given in the <form> tag.
  615: #-------------------------------------------
  616: 
  617: =pod
  618: 
  619: =item authform_xxxxxx
  620: 
  621: The authform_xxxxxx subroutines provide javascript and html forms which 
  622: handle some of the conveniences required for authentication forms.  
  623: This is not an optimal method, but it works.  
  624: 
  625: See loncreateuser.pm for invocation and use examples.
  626: 
  627: =over 4
  628: 
  629: =item authform_header
  630: 
  631: =item authform_authorwarning
  632: 
  633: =item authform_nochange
  634: 
  635: =item authform_kerberos
  636: 
  637: =item authform_internal
  638: 
  639: =item authform_filesystem
  640: 
  641: =back
  642: 
  643: =cut
  644: 
  645: #-------------------------------------------
  646: sub authform_header{  
  647:     my %in = (
  648:         formname => 'cu',
  649:         kerb_def_dom => 'MSU.EDU',
  650:         @_,
  651:     );
  652:     $in{'formname'} = 'document.' . $in{'formname'};
  653:     my $result='';
  654:     $result.=<<"END";
  655: var current = new Object();
  656: current.radiovalue = 'nochange';
  657: current.argfield = null;
  658: 
  659: function changed_radio(choice,currentform) {
  660:     var choicearg = choice + 'arg';
  661:     // If a radio button in changed, we need to change the argfield
  662:     if (current.radiovalue != choice) {
  663:         current.radiovalue = choice;
  664:         if (current.argfield != null) {
  665:             currentform.elements[current.argfield].value = '';
  666:         }
  667:         if (choice == 'nochange') {
  668:             current.argfield = null;
  669:         } else {
  670:             current.argfield = choicearg;
  671:             switch(choice) {
  672:                 case 'krb': 
  673:                     currentform.elements[current.argfield].value = 
  674:                         "$in{'kerb_def_dom'}";
  675:                 break;
  676:               default:
  677:                 break;
  678:             }
  679:         }
  680:     }
  681:     return;
  682: }
  683: 
  684: function changed_text(choice,currentform) {
  685:     var choicearg = choice + 'arg';
  686:     if (currentform.elements[choicearg].value !='') {
  687:         switch (choice) {
  688:             case 'krb': currentform.elements[choicearg].value =
  689:                 currentform.elements[choicearg].value.toUpperCase();
  690:                 break;
  691:             default:
  692:         }
  693:         // clear old field
  694:         if ((current.argfield != choicearg) && (current.argfield != null)) {
  695:             currentform.elements[current.argfield].value = '';
  696:         }
  697:         current.argfield = choicearg;
  698:     }
  699:     set_auth_radio_buttons(choice,currentform);
  700:     return;
  701: }
  702: 
  703: function set_auth_radio_buttons(newvalue,currentform) {
  704:     var i=0;
  705:     while (i < currentform.login.length) {
  706:         if (currentform.login[i].value == newvalue) { break; }
  707:         i++;
  708:     }
  709:     if (i == currentform.login.length) {
  710:         return;
  711:     }
  712:     current.radiovalue = newvalue;
  713:     currentform.login[i].checked = true;
  714:     return;
  715: }
  716: END
  717:     return $result;
  718: }
  719: 
  720: sub authform_authorwarning{
  721:     my $result='';
  722:     $result=<<"END";
  723: <i>As a general rule, only authors or co-authors should be filesystem
  724: authenticated (which allows access to the server filesystem).</i>
  725: END
  726:     return $result;
  727: }
  728: 
  729: sub authform_nochange{  
  730:     my %in = (
  731:               formname => 'document.cu',
  732:               kerb_def_dom => 'MSU.EDU',
  733:               @_,
  734:           );
  735:     my $result='';
  736:     $result.=<<"END";
  737: <input type="radio" name="login" value="nochange" checked="checked"
  738:        onclick="javascript:changed_radio('nochange',$in{'formname'});" />
  739: Do not change login data
  740: END
  741:     return $result;
  742: }
  743: 
  744: sub authform_kerberos{  
  745:     my %in = (
  746:               formname => 'document.cu',
  747:               kerb_def_dom => 'MSU.EDU',
  748:               @_,
  749:               );
  750:     my $result='';
  751:     $result.=<<"END";
  752: <input type="radio" name="login" value="krb" 
  753:        onclick="javascript:changed_radio('krb',$in{'formname'});"
  754:        onchange="javascript:changed_radio('krb',$in{'formname'});" />
  755: Kerberos authenticated with domain
  756: <input type="text" size="10" name="krbarg" value=""
  757:        onchange="javascript:changed_text('krb',$in{'formname'});" />
  758: <input type="radio" name="krbver" value="4" checked="on" />Version 4
  759: <input type="radio" name="krbver" value="5" />Version 5
  760: END
  761:     return $result;
  762: }
  763: 
  764: sub authform_internal{  
  765:     my %args = (
  766:                 formname => 'document.cu',
  767:                 kerb_def_dom => 'MSU.EDU',
  768:                 @_,
  769:                 );
  770:     my $result='';
  771:     $result.=<<"END";
  772: <input type="radio" name="login" value="int"
  773:        onchange="javascript:changed_radio('int',$args{'formname'});"
  774:        onclick="javascript:changed_radio('int',$args{'formname'});" />
  775: Internally authenticated (with initial password 
  776: <input type="text" size="10" name="intarg" value=""
  777:        onchange="javascript:changed_text('int',$args{'formname'});" />
  778: END
  779:     return $result;
  780: }
  781: 
  782: sub authform_local{  
  783:     my %in = (
  784:               formname => 'document.cu',
  785:               kerb_def_dom => 'MSU.EDU',
  786:               @_,
  787:               );
  788:     my $result='';
  789:     $result.=<<"END";
  790: <input type="radio" name="login" value="loc"
  791:        onchange="javascript:changed_radio('loc',$in{'formname'});"
  792:        onclick="javascript:changed_radio('loc',$in{'formname'});" />
  793: Local Authentication with argument
  794: <input type="text" size="10" name="locarg" value=""
  795:        onchange="javascript:changed_text('loc',$in{'formname'});" />
  796: END
  797:     return $result;
  798: }
  799: 
  800: sub authform_filesystem{  
  801:     my %in = (
  802:               formname => 'document.cu',
  803:               kerb_def_dom => 'MSU.EDU',
  804:               @_,
  805:               );
  806:     my $result='';
  807:     $result.=<<"END";
  808: <input type="radio" name="login" value="fsys" 
  809:        onchange="javascript:changed_radio('fsys',$in{'formname'});"
  810:        onclick="javascript:changed_radio('fsys',$in{'formname'});" />
  811: Filesystem authenticated (with initial password 
  812: <input type="text" size="10" name="fsysarg" value=""
  813:        onchange="javascript:changed_text('fsys',$in{'formname'});">
  814: END
  815:     return $result;
  816: }
  817: 
  818: ###############################################################
  819: ##   End Authentication changing form generation functions   ##
  820: ###############################################################
  821: 
  822: ###############################################################
  823: ##                Thesaurus Functions                        ##
  824: ###############################################################
  825: 
  826: =pod
  827: 
  828: =item initialize_keywords
  829: 
  830: Initializes the package variable %Keywords if it is empty.  Uses the
  831: package variable $thesaurus_db_file.
  832: 
  833: =cut
  834: 
  835: ###################################################
  836: 
  837: sub initialize_keywords {
  838:     return 1 if (scalar keys(%Keywords));
  839:     # If we are here, %Keywords is empty, so fill it up
  840:     #   Make sure the file we need exists...
  841:     if (! -e $thesaurus_db_file) {
  842:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
  843:                                  " failed because it does not exist");
  844:         return 0;
  845:     }
  846:     #   Set up the hash as a database
  847:     my %thesaurus_db;
  848:     if (! tie(%thesaurus_db,'GDBM_File',
  849:               $thesaurus_db_file,&GDBM_READER(),0640)){
  850:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
  851:                                  $thesaurus_db_file);
  852:         return 0;
  853:     } 
  854:     #  Get the average number of appearances of a word.
  855:     my $avecount = $thesaurus_db{'average.count'};
  856:     #  Put keywords (those that appear > average) into %Keywords
  857:     while (my ($word,$data)=each (%thesaurus_db)) {
  858:         my ($count,undef) = split /:/,$data;
  859:         $Keywords{$word}++ if ($count > $avecount);
  860:     }
  861:     untie %thesaurus_db;
  862:     # Remove special values from %Keywords.
  863:     foreach ('total.count','average.count') {
  864:         delete($Keywords{$_}) if (exists($Keywords{$_}));
  865:     }
  866:     return 1;
  867: }
  868: 
  869: ###################################################
  870: 
  871: =pod
  872: 
  873: =item keyword($word)
  874: 
  875: Returns true if $word is a keyword.  A keyword is a word that appears more 
  876: than the average number of times in the thesaurus database.  Calls 
  877: &initialize_keywords
  878: 
  879: =cut
  880: 
  881: ###################################################
  882: 
  883: sub keyword {
  884:     return if (!&initialize_keywords());
  885:     my $word=lc(shift());
  886:     $word=~s/\W//g;
  887:     return exists($Keywords{$word});
  888: }
  889: 
  890: ###############################################################
  891: 
  892: =pod 
  893: 
  894: =item get_related_words
  895: 
  896: Look up a word in the thesaurus.  Takes a scalar arguement and returns
  897: an array of words.  If the keyword is not in the thesaurus, an empty array
  898: will be returned.  The order of the words returned is determined by the
  899: database which holds them.
  900: 
  901: Uses global $thesaurus_db_file.
  902: 
  903: =cut
  904: 
  905: ###############################################################
  906: sub get_related_words {
  907:     my $keyword = shift;
  908:     my %thesaurus_db;
  909:     if (! -e $thesaurus_db_file) {
  910:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
  911:                                  "failed because the file does not exist");
  912:         return ();
  913:     }
  914:     if (! tie(%thesaurus_db,'GDBM_File',
  915:               $thesaurus_db_file,&GDBM_READER(),0640)){
  916:         return ();
  917:     } 
  918:     my @Words=();
  919:     if (exists($thesaurus_db{$keyword})) {
  920:         $_ = $thesaurus_db{$keyword};
  921:         (undef,@Words) = split/:/;  # The first element is the number of times
  922:                                     # the word appears.  We do not need it now.
  923:         for (my $i=0;$i<=$#Words;$i++) {
  924:             ($Words[$i],undef)= split/\,/,$Words[$i];
  925:         }
  926:     }
  927:     untie %thesaurus_db;
  928:     return @Words;
  929: }
  930: 
  931: ###############################################################
  932: ##              End Thesaurus Functions                      ##
  933: ###############################################################
  934: 
  935: # -------------------------------------------------------------- Plaintext name
  936: 
  937: sub plainname {
  938:     my ($uname,$udom)=@_;
  939:     my %names=&Apache::lonnet::get('environment',
  940:                     ['firstname','middlename','lastname','generation'],
  941: 					 $udom,$uname);
  942:     my $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
  943: 	$names{'lastname'}.' '.$names{'generation'};
  944:     $name=~s/\s+$//;
  945:     $name=~s/\s+/ /g;
  946:     return $name;
  947: }
  948: 
  949: # ------------------------------------------------------------------ Screenname
  950: 
  951: sub screenname {
  952:     my ($uname,$udom)=@_;
  953:     my %names=
  954:  &Apache::lonnet::get('environment',['screenname'],$udom,$uname);
  955:     return $names{'screenname'};
  956: }
  957: 
  958: # ------------------------------------------------------------- Message Wrapper
  959: 
  960: sub messagewrapper {
  961:     my ($link,$un,$do)=@_;
  962:     return 
  963: "<a href='/adm/email?compose=individual&recname=$un&recdom=$do'>$link</a>";
  964: }
  965: # ------------------------------------------------------------- Aboutme Wrapper
  966: 
  967: sub aboutmewrapper {
  968:     my ($link,$un,$do)=@_;
  969:     return "<a href='/adm/$do/$un/aboutme'>$link</a>";
  970: }
  971: 
  972: # ------------------------------------------------------------ Syllabus Wrapper
  973: 
  974: 
  975: sub syllabuswrapper {
  976:     my ($link,$un,$do)=@_;
  977:     return "<a href='/public/$do/$un/syllabus'>$link</a>";
  978: }
  979: 
  980: # ---------------------------------------------------------------- Language IDs
  981: sub languageids {
  982:     return sort(keys(%language));
  983: }
  984: 
  985: # -------------------------------------------------------- Language Description
  986: sub languagedescription {
  987:     return $language{shift(@_)};
  988: }
  989: 
  990: # --------------------------------------------------------------- Copyright IDs
  991: sub copyrightids {
  992:     return sort(keys(%cprtag));
  993: }
  994: 
  995: # ------------------------------------------------------- Copyright Description
  996: sub copyrightdescription {
  997:     return $cprtag{shift(@_)};
  998: }
  999: 
 1000: # ------------------------------------------------------------- File Categories
 1001: sub filecategories {
 1002:     return sort(keys(%category_extensions));
 1003: }
 1004: 
 1005: # -------------------------------------- File Types within a specified category
 1006: sub filecategorytypes {
 1007:     return @{$category_extensions{lc($_[0])}};
 1008: }
 1009: 
 1010: # ------------------------------------------------------------------ File Types
 1011: sub fileextensions {
 1012:     return sort(keys(%fe));
 1013: }
 1014: 
 1015: # ------------------------------------------------------------- Embedding Style
 1016: sub fileembstyle {
 1017:     return $fe{lc(shift(@_))};
 1018: }
 1019: 
 1020: # ------------------------------------------------------------ Description Text
 1021: sub filedescription {
 1022:     return $fd{lc(shift(@_))};
 1023: }
 1024: 
 1025: # ------------------------------------------------------------ Description Text
 1026: sub filedescriptionex {
 1027:     my $ex=shift;
 1028:     return '.'.$ex.' '.$fd{lc($ex)};
 1029: }
 1030: 
 1031: # ---- Retrieve attempts by students
 1032: # input
 1033: # $symb             - problem including path
 1034: # $username,$domain - that of the student
 1035: # $course           - course name
 1036: # $getattempt       - leave blank if want all attempts, else put something.
 1037: # $regexp           - regular expression. If string matches regexp send to
 1038: # $gradesub         - routine that process the string if it matches regexp
 1039: # 
 1040: # output
 1041: # formatted as a table all the attempts, if any.
 1042: #
 1043: sub get_previous_attempt {
 1044:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
 1045:   my $prevattempts='';
 1046:   no strict 'refs';
 1047:   if ($symb) {
 1048:     my (%returnhash)=
 1049:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 1050:     if ($returnhash{'version'}) {
 1051:       my %lasthash=();
 1052:       my $version;
 1053:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 1054:         foreach (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 1055: 	  $lasthash{$_}=$returnhash{$version.':'.$_};
 1056:         }
 1057:       }
 1058:       $prevattempts='<table border="0" width="100%"><tr><td bgcolor="#777777">';
 1059:       $prevattempts.='<table border="0" width="100%"><tr bgcolor="#e6ffff"><td>History</td>';
 1060:       foreach (sort(keys %lasthash)) {
 1061: 	my ($ign,@parts) = split(/\./,$_);
 1062: 	if ($#parts > 0) {
 1063: 	  my $data=$parts[-1];
 1064: 	  pop(@parts);
 1065: 	  $prevattempts.='<td>Part '.join('.',@parts).'<br />'.$data.'&nbsp;</td>';
 1066: 	} else {
 1067: 	  if ($#parts == 0) {
 1068: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 1069: 	  } else {
 1070: 	    $prevattempts.='<th>'.$ign.'</th>';
 1071: 	  }
 1072: 	}
 1073:       }
 1074:       if ($getattempt eq '') {
 1075: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 1076: 	  $prevattempts.='</tr><tr bgcolor="#ffffe6"><td>Transaction '.$version.'</td>';
 1077: 	    foreach (sort(keys %lasthash)) {
 1078: 	       my $value;
 1079: 	       if ($_ =~ /timestamp/) {
 1080: 		  $value=scalar(localtime($returnhash{$version.':'.$_}));
 1081: 	       } else {
 1082: 		  $value=$returnhash{$version.':'.$_};
 1083: 	       }
 1084: 	       $prevattempts.='<td>'.$value.'&nbsp;</td>';   
 1085: 	    }
 1086: 	 }
 1087:       }
 1088:       $prevattempts.='</tr><tr bgcolor="#ffffe6"><td>Current</td>';
 1089:       foreach (sort(keys %lasthash)) {
 1090: 	my $value;
 1091: 	if ($_ =~ /timestamp/) {
 1092: 	  $value=scalar(localtime($lasthash{$_}));
 1093: 	} else {
 1094: 	  $value=$lasthash{$_};
 1095: 	}
 1096: 	if ($_ =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
 1097: 	$prevattempts.='<td>'.$value.'&nbsp;</td>';
 1098:       }
 1099:       $prevattempts.='</tr></table></td></tr></table>';
 1100:     } else {
 1101:       $prevattempts='Nothing submitted - no attempts.';
 1102:     }
 1103:   } else {
 1104:     $prevattempts='No data.';
 1105:   }
 1106: }
 1107: 
 1108: sub get_student_view {
 1109:   my ($symb,$username,$domain,$courseid) = @_;
 1110:   my ($map,$id,$feedurl) = split(/___/,$symb);
 1111:   my (%old,%moreenv);
 1112:   my @elements=('symb','courseid','domain','username');
 1113:   foreach my $element (@elements) {
 1114:     $old{$element}=$ENV{'form.grade_'.$element};
 1115:     $moreenv{'form.grade_'.$element}=eval '$'.$element #'
 1116:   }
 1117:   &Apache::lonnet::appenv(%moreenv);
 1118:   my $userview=&Apache::lonnet::ssi('/res/'.$feedurl);
 1119:   &Apache::lonnet::delenv('form.grade_');
 1120:   foreach my $element (@elements) {
 1121:     $ENV{'form.grade_'.$element}=$old{$element};
 1122:   }
 1123:   $userview=~s/\<body[^\>]*\>//gi;
 1124:   $userview=~s/\<\/body\>//gi;
 1125:   $userview=~s/\<html\>//gi;
 1126:   $userview=~s/\<\/html\>//gi;
 1127:   $userview=~s/\<head\>//gi;
 1128:   $userview=~s/\<\/head\>//gi;
 1129:   $userview=~s/action\s*\=/would_be_action\=/gi;
 1130:   return $userview;
 1131: }
 1132: 
 1133: sub get_student_answers {
 1134:   my ($symb,$username,$domain,$courseid) = @_;
 1135:   my ($map,$id,$feedurl) = split(/___/,$symb);
 1136:   my (%old,%moreenv);
 1137:   my @elements=('symb','courseid','domain','username');
 1138:   foreach my $element (@elements) {
 1139:     $old{$element}=$ENV{'form.grade_'.$element};
 1140:     $moreenv{'form.grade_'.$element}=eval '$'.$element #'
 1141:   }
 1142:   $moreenv{'form.grade_target'}='answer';
 1143:   &Apache::lonnet::appenv(%moreenv);
 1144:   my $userview=&Apache::lonnet::ssi('/res/'.$feedurl);
 1145:   &Apache::lonnet::delenv('form.grade_');
 1146:   foreach my $element (@elements) {
 1147:     $ENV{'form.grade_'.$element}=$old{$element};
 1148:   }
 1149:   return $userview;
 1150: }
 1151: 
 1152: ###############################################
 1153: 
 1154: 
 1155: sub timehash {
 1156:     my @ltime=localtime(shift);
 1157:     return ( 'seconds' => $ltime[0],
 1158:              'minutes' => $ltime[1],
 1159:              'hours'   => $ltime[2],
 1160:              'day'     => $ltime[3],
 1161:              'month'   => $ltime[4]+1,
 1162:              'year'    => $ltime[5]+1900,
 1163:              'weekday' => $ltime[6],
 1164:              'dayyear' => $ltime[7]+1,
 1165:              'dlsav'   => $ltime[8] );
 1166: }
 1167: 
 1168: sub maketime {
 1169:     my %th=@_;
 1170:     return POSIX::mktime(
 1171:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 1172:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,$th{'dlsav'}));
 1173: }
 1174: 
 1175: 
 1176: sub findallcourses {
 1177:     my %courses=();
 1178:     my $now=time;
 1179:     foreach (keys %ENV) {
 1180: 	if ($_=~/^user\.role\.\w+\.\/(\w+)\/(\w+)/) {
 1181: 	    my ($starttime,$endtime)=$ENV{$_};
 1182:             my $active=1;
 1183:             if ($starttime) {
 1184: 		if ($now<$starttime) { $active=0; }
 1185:             }
 1186:             if ($endtime) {
 1187:                 if ($now>$endtime) { $active=0; }
 1188:             }
 1189:             if ($active) { $courses{$1.'_'.$2}=1; }
 1190:         }
 1191:     }
 1192:     return keys %courses;
 1193: }
 1194: 
 1195: ###############################################
 1196: ###############################################
 1197: 
 1198: =pod
 1199: 
 1200: =item &domainlogo()
 1201: 
 1202: Inputs: $domain (usually will be undef)
 1203: 
 1204: Returns: A link to a domain logo, if the domain logo exists.
 1205: If the domain logo does not exist, a description of the domain.
 1206: 
 1207: =cut
 1208: 
 1209: ###############################################
 1210: ###############################################
 1211: sub domainlogo {
 1212:     my ($domain) = @_;    
 1213:     if (! $domain) {
 1214:         # Determine domain if we have not been given one
 1215:         $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
 1216:         if ($ENV{'user.domain'}) { $domain=$ENV{'user.domain'}; }
 1217:         if ($ENV{'request.role.domain'}) { 
 1218:             $domain=$ENV{'request.role.domain'}; 
 1219:         }
 1220:     }
 1221:     # See if there is a logo
 1222:     if (-e '/home/httpd/html/adm/lonDomLogos/'.$domain.'.gif') {
 1223:         return '<img src="/adm/lonDomLogos/'.$domain.'.gif" />';
 1224:     } elsif(exists($Apache::lonnet::domaindescription{$domain})) {
 1225:         return $Apache::lonnet::domaindescription{$domain};
 1226:     } else {
 1227:         return '';
 1228:     }
 1229: }
 1230: 
 1231: ###############################################
 1232: ###############################################
 1233: 
 1234: =pod
 1235: 
 1236: =item &bodytag()
 1237: 
 1238: Returns a uniform header for LON-CAPA web pages.
 1239: 
 1240: Inputs: 
 1241: 
 1242:  $title, A title to be displayed on the page.
 1243:  $function, the current role (can be undef).
 1244:  $addentries, extra parameters for the <body> tag.
 1245:  $bodyonly, if defined, only return the <body> tag.
 1246:  $domain, if defined, force a given domain.
 1247: 
 1248: Returns: A uniform header for LON-CAPA web pages.  
 1249: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 1250: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 1251: other decorations will be returned.
 1252: 
 1253: =cut
 1254: 
 1255: ###############################################
 1256: ###############################################
 1257: sub bodytag {
 1258:     my ($title,$function,$addentries,$bodyonly,$domain)=@_;
 1259:     unless ($function) {
 1260: 	$function='student';
 1261:         if ($ENV{'request.role'}=~/^(cc|in|ta|ep)/) {
 1262: 	    $function='coordinator';
 1263:         }
 1264: 	if ($ENV{'request.role'}=~/^(su|dc|ad|li)/) {
 1265:             $function='admin';
 1266:         }
 1267:         if (($ENV{'request.role'}=~/^(au|ca)/) ||
 1268:             ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
 1269:             $function='author';
 1270:         }
 1271:     }
 1272:     my $img='';
 1273:     my $pgbg='';
 1274:     my $tabbg='';
 1275:     my $font='';
 1276:     my $link='';
 1277:     my $alink='#CC0000';
 1278:     my $vlink='';
 1279:     if ($function eq 'admin') {
 1280:         $img='admin';
 1281:         $pgbg='#FFFFCC';
 1282:         $tabbg='#CCCC99';
 1283:         $font='#772200';
 1284:         $link='#663300';
 1285:         $vlink='#666600';
 1286:     } elsif ($function eq 'coordinator') {
 1287:         $img='coordinator';
 1288:         $pgbg='#CCFFFF';
 1289:         $tabbg='#CCCCFF';
 1290:         $font='#000044';
 1291:         $link='#003333';
 1292:         $vlink='#006633';
 1293:    } elsif ($function eq 'author') {
 1294:         $img='author';
 1295:         $pgbg='#CCFFFF';
 1296:         $tabbg='#CCFFCC';
 1297:         $font='#004400';
 1298:         $link='#003333';
 1299:         $vlink='#006666';
 1300:     } else {
 1301:         $img='student';
 1302:         $pgbg='#FFFFAA';
 1303:         $tabbg='#FF9900';
 1304:         $font='#991100';
 1305:         $link='#993300';
 1306:         $vlink='#996600';
 1307:     }
 1308: # role and realm
 1309:     my ($role,$realm)
 1310:        =&Apache::lonnet::plaintext((split(/\./,$ENV{'request.role'}))[0]);
 1311: # realm
 1312:     if ($ENV{'request.course.id'}) {
 1313: 	$realm=
 1314:          $ENV{'course.'.$ENV{'request.course.id'}.'.description'};
 1315:     }
 1316:     unless ($realm) { $realm='&nbsp;'; }
 1317: # Set messages
 1318:     my $messages=&domainlogo($domain);
 1319: # Output
 1320:     my $bodytag = <<END;
 1321: <body bgcolor="$pgbg" text="$font" alink="$alink" vlink="$vlink" link="$link"
 1322: $addentries>
 1323: END
 1324:     if ($bodyonly) {
 1325:         return $bodytag;
 1326:     } else {
 1327:         return(<<ENDBODY);
 1328: $bodytag
 1329: <table width="100%" cellspacing="0" border="0" cellpadding="0">
 1330: <tr><td bgcolor="$font">
 1331: <img src="/adm/lonInterFace/$img.jpg" /></td>
 1332: <td bgcolor="$font"><font color='$pgbg'>$messages</font></td>
 1333: </tr>
 1334: <tr>
 1335: <td rowspan="3" bgcolor="$tabbg">
 1336: &nbsp;<font size="5"><b>$title</b></font>
 1337: <td bgcolor="$tabbg"  align="right">
 1338: <font size="2">
 1339:     $ENV{'environment.firstname'}
 1340:     $ENV{'environment.middlename'}
 1341:     $ENV{'environment.lastname'}
 1342:     $ENV{'environment.generation'}
 1343:     </font>&nbsp;
 1344: </td>
 1345: </tr>
 1346: <tr><td bgcolor="$tabbg" align="right">
 1347: <font size="2">$role</font>&nbsp;
 1348: </td></tr>
 1349: <tr>
 1350: <td bgcolor="$tabbg" align="right"><font size="2">$realm</font>&nbsp;</td></tr>
 1351: </table><br>
 1352: ENDBODY
 1353:     }
 1354: }
 1355: ###############################################
 1356: 
 1357: sub get_unprocessed_cgi {
 1358:   my ($query,$possible_names)= @_;
 1359:   # $Apache::lonxml::debug=1;
 1360:   foreach (split(/&/,$query)) {
 1361:     my ($name, $value) = split(/=/,$_);
 1362:     $name = &Apache::lonnet::unescape($name);
 1363:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
 1364:       $value =~ tr/+/ /;
 1365:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 1366:       &Apache::lonxml::debug("Seting :$name: to :$value:");
 1367:       unless (defined($ENV{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
 1368:     }
 1369:   }
 1370: }
 1371: 
 1372: sub cacheheader {
 1373:   unless ($ENV{'request.method'} eq 'GET') { return ''; }
 1374:   my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 1375:   my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
 1376:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
 1377:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
 1378:   return $output;
 1379: }
 1380: 
 1381: sub no_cache {
 1382:   my ($r) = @_;
 1383:   unless ($ENV{'request.method'} eq 'GET') { return ''; }
 1384:   #my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 1385:   $r->no_cache(1);
 1386:   $r->header_out("Pragma" => "no-cache");
 1387:   #$r->header_out("Expires" => $date);
 1388: }
 1389: 
 1390: sub add_to_env {
 1391:   my ($name,$value)=@_;
 1392:   if (defined($ENV{$name})) {
 1393:     if (ref($ENV{$name})) {
 1394:       #already have multiple values
 1395:       push(@{ $ENV{$name} },$value);
 1396:     } else {
 1397:       #first time seeing multiple values, convert hash entry to an arrayref
 1398:       my $first=$ENV{$name};
 1399:       undef($ENV{$name});
 1400:       push(@{ $ENV{$name} },$first,$value);
 1401:     }
 1402:   } else {
 1403:     $ENV{$name}=$value;
 1404:   }
 1405: }
 1406: 
 1407: =pod
 1408: 
 1409: =back 
 1410: 
 1411: =head2 CSV Upload/Handling functions
 1412: 
 1413: =over 4
 1414: 
 1415: =item  upfile_store($r)
 1416: 
 1417: Store uploaded file, $r should be the HTTP Request object,
 1418: needs $ENV{'form.upfile'}
 1419: returns $datatoken to be put into hidden field
 1420: 
 1421: =cut
 1422: 
 1423: sub upfile_store {
 1424:     my $r=shift;
 1425:     $ENV{'form.upfile'}=~s/\r/\n/gs;
 1426:     $ENV{'form.upfile'}=~s/\f/\n/gs;
 1427:     $ENV{'form.upfile'}=~s/\n+/\n/gs;
 1428:     $ENV{'form.upfile'}=~s/\n+$//gs;
 1429: 
 1430:     my $datatoken=$ENV{'user.name'}.'_'.$ENV{'user.domain'}.
 1431: 	'_enroll_'.$ENV{'request.course.id'}.'_'.time.'_'.$$;
 1432:     {
 1433: 	my $fh=Apache::File->new('>'.$r->dir_config('lonDaemons').
 1434: 				 '/tmp/'.$datatoken.'.tmp');
 1435: 	print $fh $ENV{'form.upfile'};
 1436:     }
 1437:     return $datatoken;
 1438: }
 1439: 
 1440: =pod
 1441: 
 1442: =item load_tmp_file($r)
 1443: 
 1444: Load uploaded file from tmp, $r should be the HTTP Request object,
 1445: needs $ENV{'form.datatoken'},
 1446: sets $ENV{'form.upfile'} to the contents of the file
 1447: 
 1448: =cut
 1449: 
 1450: sub load_tmp_file {
 1451:     my $r=shift;
 1452:     my @studentdata=();
 1453:     {
 1454: 	my $fh;
 1455: 	if ($fh=Apache::File->new($r->dir_config('lonDaemons').
 1456: 				  '/tmp/'.$ENV{'form.datatoken'}.'.tmp')) {
 1457: 	    @studentdata=<$fh>;
 1458: 	}
 1459:     }
 1460:     $ENV{'form.upfile'}=join('',@studentdata);
 1461: }
 1462: 
 1463: =pod
 1464: 
 1465: =item upfile_record_sep()
 1466: 
 1467: Separate uploaded file into records
 1468: returns array of records,
 1469: needs $ENV{'form.upfile'} and $ENV{'form.upfiletype'}
 1470: 
 1471: =cut
 1472: 
 1473: sub upfile_record_sep {
 1474:     if ($ENV{'form.upfiletype'} eq 'xml') {
 1475:     } else {
 1476: 	return split(/\n/,$ENV{'form.upfile'});
 1477:     }
 1478: }
 1479: 
 1480: =pod
 1481: 
 1482: =item record_sep($record)
 1483: 
 1484: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $ENV{'form.upfiletype'}
 1485: 
 1486: =cut
 1487: 
 1488: sub record_sep {
 1489:     my $record=shift;
 1490:     my %components=();
 1491:     if ($ENV{'form.upfiletype'} eq 'xml') {
 1492:     } elsif ($ENV{'form.upfiletype'} eq 'space') {
 1493:         my $i=0;
 1494:         foreach (split(/\s+/,$record)) {
 1495:             my $field=$_;
 1496:             $field=~s/^(\"|\')//;
 1497:             $field=~s/(\"|\')$//;
 1498:             $components{$i}=$field;
 1499:             $i++;
 1500:         }
 1501:     } elsif ($ENV{'form.upfiletype'} eq 'tab') {
 1502:         my $i=0;
 1503:         foreach (split(/\t+/,$record)) {
 1504:             my $field=$_;
 1505:             $field=~s/^(\"|\')//;
 1506:             $field=~s/(\"|\')$//;
 1507:             $components{$i}=$field;
 1508:             $i++;
 1509:         }
 1510:     } else {
 1511:         my @allfields=split(/\,/,$record);
 1512:         my $i=0;
 1513:         my $j;
 1514:         for ($j=0;$j<=$#allfields;$j++) {
 1515:             my $field=$allfields[$j];
 1516:             if ($field=~/^\s*(\"|\')/) {
 1517: 		my $delimiter=$1;
 1518:                 while (($field!~/$delimiter$/) && ($j<$#allfields)) {
 1519: 		    $j++;
 1520: 		    $field.=','.$allfields[$j];
 1521: 		}
 1522:                 $field=~s/^\s*$delimiter//;
 1523:                 $field=~s/$delimiter\s*$//;
 1524:             }
 1525:             $components{$i}=$field;
 1526: 	    $i++;
 1527:         }
 1528:     }
 1529:     return %components;
 1530: }
 1531: 
 1532: =pod
 1533: 
 1534: =item upfile_select_html()
 1535: 
 1536: return HTML code to select file and specify its type
 1537: 
 1538: =cut
 1539: 
 1540: sub upfile_select_html {
 1541:     return (<<'ENDUPFORM');
 1542: <input type="file" name="upfile" size="50" />
 1543: <br />Type: <select name="upfiletype">
 1544: <option value="csv">CSV (comma separated values, spreadsheet)</option>
 1545: <option value="space">Space separated</option>
 1546: <option value="tab">Tabulator separated</option>
 1547: <option value="xml">HTML/XML</option>
 1548: </select>
 1549: ENDUPFORM
 1550: }
 1551: 
 1552: =pod
 1553: 
 1554: =item csv_print_samples($r,$records)
 1555: 
 1556: Prints a table of sample values from each column uploaded $r is an
 1557: Apache Request ref, $records is an arrayref from
 1558: &Apache::loncommon::upfile_record_sep
 1559: 
 1560: =cut
 1561: 
 1562: sub csv_print_samples {
 1563:     my ($r,$records) = @_;
 1564:     my (%sone,%stwo,%sthree);
 1565:     %sone=&record_sep($$records[0]);
 1566:     if (defined($$records[1])) {%stwo=&record_sep($$records[1]);}
 1567:     if (defined($$records[2])) {%sthree=&record_sep($$records[2]);}
 1568: 
 1569:     $r->print('Samples<br /><table border="2"><tr>');
 1570:     foreach (sort({$a <=> $b} keys(%sone))) { $r->print('<th>Column&nbsp;'.($_+1).'</th>'); }
 1571:     $r->print('</tr>');
 1572:     foreach my $hash (\%sone,\%stwo,\%sthree) {
 1573: 	$r->print('<tr>');
 1574: 	foreach (sort({$a <=> $b} keys(%sone))) {
 1575: 	    $r->print('<td>');
 1576: 	    if (defined($$hash{$_})) { $r->print($$hash{$_}); }
 1577: 	    $r->print('</td>');
 1578: 	}
 1579: 	$r->print('</tr>');
 1580:     }
 1581:     $r->print('</tr></table><br />'."\n");
 1582: }
 1583: 
 1584: =pod
 1585: 
 1586: =item csv_print_select_table($r,$records,$d)
 1587: 
 1588: Prints a table to create associations between values and table columns.
 1589: $r is an Apache Request ref,
 1590: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 1591: $d is an array of 2 element arrays (internal name, displayed name)
 1592: 
 1593: =cut
 1594: 
 1595: sub csv_print_select_table {
 1596:     my ($r,$records,$d) = @_;
 1597:     my $i=0;my %sone;
 1598:     %sone=&record_sep($$records[0]);
 1599:     $r->print('Associate columns with student attributes.'."\n".
 1600: 	     '<table border="2"><tr><th>Attribute</th><th>Column</th></tr>'."\n");
 1601:     foreach (@$d) {
 1602: 	my ($value,$display)=@{ $_ };
 1603: 	$r->print('<tr><td>'.$display.'</td>');
 1604: 
 1605: 	$r->print('<td><select name=f'.$i.
 1606: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 1607: 	$r->print('<option value="none"></option>');
 1608: 	foreach (sort({$a <=> $b} keys(%sone))) {
 1609: 	    $r->print('<option value="'.$_.'">Column '.($_+1).'</option>');
 1610: 	}
 1611: 	$r->print('</select></td></tr>'."\n");
 1612: 	$i++;
 1613:     }
 1614:     $i--;
 1615:     return $i;
 1616: }
 1617: 
 1618: =pod
 1619: 
 1620: =item csv_samples_select_table($r,$records,$d)
 1621: 
 1622: Prints a table of sample values from the upload and can make associate samples to internal names.
 1623: 
 1624: $r is an Apache Request ref,
 1625: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 1626: $d is an array of 2 element arrays (internal name, displayed name)
 1627: 
 1628: =cut
 1629: 
 1630: sub csv_samples_select_table {
 1631:     my ($r,$records,$d) = @_;
 1632:     my %sone; my %stwo; my %sthree;
 1633:     my $i=0;
 1634: 
 1635:     $r->print('<table border=2><tr><th>Field</th><th>Samples</th></tr>');
 1636:     %sone=&record_sep($$records[0]);
 1637:     if (defined($$records[1])) {%stwo=&record_sep($$records[1]);}
 1638:     if (defined($$records[2])) {%sthree=&record_sep($$records[2]);}
 1639: 
 1640:     foreach (sort keys %sone) {
 1641: 	$r->print('<tr><td><select name=f'.$i.
 1642: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 1643: 	foreach (@$d) {
 1644: 	    my ($value,$display)=@{ $_ };
 1645: 	    $r->print('<option value='.$value.'>'.$display.'</option>');
 1646: 	}
 1647: 	$r->print('</select></td><td>');
 1648: 	if (defined($sone{$_})) { $r->print($sone{$_}."</br>\n"); }
 1649: 	if (defined($stwo{$_})) { $r->print($stwo{$_}."</br>\n"); }
 1650: 	if (defined($sthree{$_})) { $r->print($sthree{$_}."</br>\n"); }
 1651: 	$r->print('</td></tr>');
 1652: 	$i++;
 1653:     }
 1654:     $i--;
 1655:     return($i);
 1656: }
 1657: 1;
 1658: __END__;
 1659: 
 1660: =pod
 1661: 
 1662: =back
 1663: 
 1664: =head2 Access .tab File Data
 1665: 
 1666: =over 4
 1667: 
 1668: =item languageids() 
 1669: 
 1670: returns list of all language ids
 1671: 
 1672: =item languagedescription() 
 1673: 
 1674: returns description of a specified language id
 1675: 
 1676: =item copyrightids() 
 1677: 
 1678: returns list of all copyrights
 1679: 
 1680: =item copyrightdescription() 
 1681: 
 1682: returns description of a specified copyright id
 1683: 
 1684: =item filecategories() 
 1685: 
 1686: returns list of all file categories
 1687: 
 1688: =item filecategorytypes() 
 1689: 
 1690: returns list of file types belonging to a given file
 1691: category
 1692: 
 1693: =item fileembstyle() 
 1694: 
 1695: returns embedding style for a specified file type
 1696: 
 1697: =item filedescription() 
 1698: 
 1699: returns description for a specified file type
 1700: 
 1701: =item filedescriptionex() 
 1702: 
 1703: returns description for a specified file type with
 1704: extra formatting
 1705: 
 1706: =back
 1707: 
 1708: =head2 Alternate Problem Views
 1709: 
 1710: =over 4
 1711: 
 1712: =item get_previous_attempt() 
 1713: 
 1714: return string with previous attempt on problem
 1715: 
 1716: =item get_student_view() 
 1717: 
 1718: show a snapshot of what student was looking at
 1719: 
 1720: =item get_student_answers() 
 1721: 
 1722: show a snapshot of how student was answering problem
 1723: 
 1724: =back
 1725: 
 1726: =head2 HTTP Helper
 1727: 
 1728: =over 4
 1729: 
 1730: =item get_unprocessed_cgi($query,$possible_names)
 1731: 
 1732: Modify the %ENV hash to contain unprocessed CGI form parameters held in
 1733: $query.  The parameters listed in $possible_names (an array reference),
 1734: will be set in $ENV{'form.name'} if they do not already exist.
 1735: 
 1736: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
 1737: $possible_names is an ref to an array of form element names.  As an example:
 1738: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
 1739: will result in $ENV{'form.uname'} and $ENV{'form.udom'} being set.
 1740: 
 1741: =item cacheheader() 
 1742: 
 1743: returns cache-controlling header code
 1744: 
 1745: =item nocache() 
 1746: 
 1747: specifies header code to not have cache
 1748: 
 1749: =item add_to_env($name,$value) 
 1750: 
 1751: adds $name to the %ENV hash with value
 1752: $value, if $name already exists, the entry is converted to an array
 1753: reference and $value is added to the array.
 1754: 
 1755: =back
 1756: 
 1757: =cut

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