File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.187: download - view: text, annotated - select for diffs
Fri Mar 19 03:47:09 2004 UTC (20 years, 2 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- BUG# 2716, show course title when picking a course

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

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