File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.111: download - view: text, annotated - select for diffs
Wed Aug 13 20:40:31 2003 UTC (20 years, 10 months ago) by www
Branches: MAIN
CVS tags: HEAD
Bug #768: Now, if you are not in a course, the "Select User" link on the
CUSR front page can show the users whom you had assigned roles to, including
co-authors.

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

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