File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.179: download - view: text, annotated - select for diffs
Wed Feb 4 15:29:06 2004 UTC (20 years, 4 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Now translate the titles of help/bug/faq links.

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

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