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

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

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