File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.178: download - view: text, annotated - select for diffs
Mon Feb 2 19:32:11 2004 UTC (20 years, 4 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Added \@Labels to DrawBarGraph inputs (labels on the x-axis).

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

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