File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.186: download - view: text, annotated - select for diffs
Mon Mar 15 22:32:37 2004 UTC (20 years, 2 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- Fixes for BUG#2834, printing wasn't passing the textwidth paramaeter along.
- Fixed some of my orginal get_student_view code from back when I didn't know what I was doing (Nov 2001)

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

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