Annotation of loncom/interface/loncommon.pm, revision 1.231

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

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