File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.219: download - view: text, annotated - select for diffs
Tue Oct 12 23:26:48 2004 UTC (19 years, 8 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- except for the <nobr> and the selected="on" Edit mode on a homework problem is now xhtml 1.0 transtional compliant

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

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