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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.225   ! matthew     4: # $Id: loncommon.pm,v 1.224 2004/10/29 18:40:40 raeburn Exp $
1.10      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
                     29: # Makes a table out of the previous attempts
1.2       albertel   30: # Inputs result_from_symbread, user, domain, course_id
1.16      harris41   31: # Reads in non-network-related .tab files
1.1       albertel   32: 
1.35      matthew    33: # POD header:
                     34: 
1.45      matthew    35: =pod
                     36: 
1.35      matthew    37: =head1 NAME
                     38: 
                     39: Apache::loncommon - pile of common routines
                     40: 
                     41: =head1 SYNOPSIS
                     42: 
1.112     bowersj2   43: Common routines for manipulating connections, student answers,
                     44:     domains, common Javascript fragments, etc.
1.35      matthew    45: 
1.112     bowersj2   46: =head1 OVERVIEW
1.35      matthew    47: 
1.112     bowersj2   48: A collection of commonly used subroutines that don't have a natural
                     49: home anywhere else. This collection helps remove
1.35      matthew    50: redundancy from other modules and increase efficiency of memory usage.
                     51: 
                     52: =cut 
                     53: 
                     54: # End of POD header
1.1       albertel   55: package Apache::loncommon;
                     56: 
                     57: use strict;
1.22      www        58: use Apache::lonnet();
1.46      matthew    59: use GDBM_File;
1.51      www        60: use POSIX qw(strftime mktime);
1.99      www        61: use Apache::Constants qw(:common :http :methods);
1.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.224     raeburn  2521:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,$customtitle)=@_;
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.224     raeburn  2567:           
1.93      www      2568:         return $bodytag.&Apache::lonmenu::menubuttons($forcereg,'web',
                   2569:                                                       $forcereg).
                   2570:                '<h1>LON-CAPA: '.$title.'</h1>';
                   2571:     } elsif ($ENV{'environment.remote'} eq 'off') {
1.95      www      2572: # No Remote
1.206     albertel 2573: 	my $roleinfo=(<<ENDROLE);
                   2574: <td bgcolor="$tabbg" align="right">
                   2575: <p>
                   2576: <font size="2" face="Arial, Helvetica, sans-serif">
                   2577:     $ENV{'environment.firstname'}
                   2578:     $ENV{'environment.middlename'}
                   2579:     $ENV{'environment.lastname'}
                   2580:     $ENV{'environment.generation'}
                   2581:     </font>&nbsp;
                   2582: <br />
                   2583: <font size="2" face="Arial, Helvetica, sans-serif">$role</font>&nbsp;
                   2584: <br />
                   2585: <font size="2" face="Arial, Helvetica, sans-serif">$realm</font>&nbsp;
                   2586: </p>
                   2587: </td>
                   2588: ENDROLE
1.224     raeburn  2589:         my $titleinfo = '<font face="Arial, Helvetica, sans-serif" size="+3" color="'.
                   2590:                         $font.'"><b>'.$title.'</b></font>';
                   2591:         if ($customtitle) {
                   2592:             $titleinfo = $customtitle;
                   2593:         } 
1.95      www      2594:         return $bodytag.&Apache::lonmenu::menubuttons($forcereg,'web',
                   2595:                                                       $forcereg).
1.224     raeburn  2596:       '<table bgcolor="'.$pgbg.'" width="100%" border="0" cellspacing="3" cellpadding="3"><tr><td rowspan="3" bgcolor="'.$tabbg.'">'.$titleinfo.'</td>'.$roleinfo.'</tr></table>';
1.94      www      2597:     }
1.95      www      2598: 
1.93      www      2599: #
1.95      www      2600: # Top frame rendering, Remote is up
1.93      www      2601: #
1.224     raeburn  2602:     my $titleinfo = '&nbsp;<font size="5" face="Arial, Helvetica, sans-serif"><b>'.$title.'</b></font>';
                   2603:     if ($customtitle) {
                   2604:         $titleinfo = $customtitle;
                   2605:     }
1.94      www      2606:     return(<<ENDBODY);
1.60      matthew  2607: $bodytag
1.55      www      2608: <table width="100%" cellspacing="0" border="0" cellpadding="0">
1.95      www      2609: <tr><td bgcolor="$sidebg">
1.94      www      2610: $upperleft</td>
1.95      www      2611: <td bgcolor="$sidebg" align="right">$messages&nbsp;</td>
1.55      www      2612: </tr>
1.54      www      2613: <tr>
1.55      www      2614: <td rowspan="3" bgcolor="$tabbg">
1.224     raeburn  2615: $titleinfo
1.146     www      2616: <td bgcolor="$tabbg" align="right">
                   2617: <font size="2" face="Arial, Helvetica, sans-serif">
1.54      www      2618:     $ENV{'environment.firstname'}
                   2619:     $ENV{'environment.middlename'}
                   2620:     $ENV{'environment.lastname'}
                   2621:     $ENV{'environment.generation'}
1.55      www      2622:     </font>&nbsp;
1.54      www      2623: </td>
                   2624: </tr>
                   2625: <tr><td bgcolor="$tabbg" align="right">
1.146     www      2626: <font size="2" face="Arial, Helvetica, sans-serif">$role</font>&nbsp;
1.54      www      2627: </td></tr>
1.55      www      2628: <tr>
1.148     www      2629: <td bgcolor="$tabbg" align="right"><font size="2" face="Arial, Helvetica, sans-serif">$realm</font>&nbsp;</td></tr>
1.202     albertel 2630: </table><br />
1.54      www      2631: ENDBODY
1.182     matthew  2632: }
                   2633: 
                   2634: ###############################################
                   2635: 
                   2636: =pod
                   2637: 
                   2638: =item get_users_function
                   2639: 
                   2640: Used by &bodytag to determine the current users primary role.
                   2641: Returns either 'student','coordinator','admin', or 'author'.
                   2642: 
                   2643: =cut
                   2644: 
                   2645: ###############################################
                   2646: sub get_users_function {
                   2647:     my $function = 'student';
                   2648:     if ($ENV{'request.role'}=~/^(cc|in|ta|ep)/) {
                   2649:         $function='coordinator';
                   2650:     }
                   2651:     if ($ENV{'request.role'}=~/^(su|dc|ad|li)/) {
                   2652:         $function='admin';
                   2653:     }
                   2654:     if (($ENV{'request.role'}=~/^(au|ca)/) ||
                   2655:         ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
                   2656:         $function='author';
                   2657:     }
                   2658:     return $function;
1.54      www      2659: }
1.99      www      2660: 
                   2661: ###############################################
                   2662: 
                   2663: sub get_posted_cgi {
                   2664:     my $r=shift;
                   2665: 
                   2666:     my $buffer;
                   2667:     
                   2668:     $r->read($buffer,$r->header_in('Content-length'),0);
                   2669:     unless ($buffer=~/^(\-+\w+)\s+Content\-Disposition\:\s*form\-data/si) {
                   2670: 	my @pairs=split(/&/,$buffer);
                   2671: 	my $pair;
                   2672: 	foreach $pair (@pairs) {
                   2673: 	    my ($name,$value) = split(/=/,$pair);
                   2674: 	    $value =~ tr/+/ /;
                   2675: 	    $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                   2676: 	    $name  =~ tr/+/ /;
                   2677: 	    $name  =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                   2678: 	    &add_to_env("form.$name",$value);
                   2679: 	}
                   2680:     } else {
                   2681: 	my $contentsep=$1;
                   2682: 	my @lines = split (/\n/,$buffer);
                   2683: 	my $name='';
                   2684: 	my $value='';
                   2685: 	my $fname='';
                   2686: 	my $fmime='';
                   2687: 	my $i;
                   2688: 	for ($i=0;$i<=$#lines;$i++) {
                   2689: 	    if ($lines[$i]=~/^$contentsep/) {
                   2690: 		if ($name) {
                   2691: 		    chomp($value);
                   2692: 		    if ($fname) {
                   2693: 			$ENV{"form.$name.filename"}=$fname;
                   2694: 			$ENV{"form.$name.mimetype"}=$fmime;
                   2695: 		    } else {
                   2696: 			$value=~s/\s+$//s;
                   2697: 		    }
                   2698: 		    &add_to_env("form.$name",$value);
                   2699: 		}
                   2700: 		if ($i<$#lines) {
                   2701: 		    $i++;
                   2702: 		    $lines[$i]=~
                   2703: 		/Content\-Disposition\:\s*form\-data\;\s*name\=\"([^\"]+)\"/i;
                   2704: 		    $name=$1;
                   2705: 		    $value='';
                   2706: 		    if ($lines[$i]=~/filename\=\"([^\"]+)\"/i) {
                   2707: 			$fname=$1;
                   2708: 			if 
                   2709:                             ($lines[$i+1]=~/Content\-Type\:\s*([\w\-\/]+)/i) {
                   2710: 				$fmime=$1;
                   2711: 				$i++;
                   2712: 			    } else {
                   2713: 				$fmime='';
                   2714: 			    }
                   2715: 		    } else {
                   2716: 			$fname='';
                   2717: 			$fmime='';
                   2718: 		    }
                   2719: 		    $i++;
                   2720: 		}
                   2721: 	    } else {
                   2722: 		$value.=$lines[$i]."\n";
                   2723: 	    }
                   2724: 	}
                   2725:     }
                   2726:     $ENV{'request.method'}=$ENV{'REQUEST_METHOD'};
                   2727:     $r->method_number(M_GET);
                   2728:     $r->method('GET');
                   2729:     $r->headers_in->unset('Content-length');
                   2730: }
                   2731: 
1.112     bowersj2 2732: =pod
                   2733: 
                   2734: =item * get_unprocessed_cgi($query,$possible_names)
                   2735: 
                   2736: Modify the %ENV hash to contain unprocessed CGI form parameters held in
                   2737: $query.  The parameters listed in $possible_names (an array reference),
                   2738: will be set in $ENV{'form.name'} if they do not already exist.
                   2739: 
                   2740: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   2741: $possible_names is an ref to an array of form element names.  As an example:
                   2742: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
                   2743: will result in $ENV{'form.uname'} and $ENV{'form.udom'} being set.
                   2744: 
                   2745: =cut
1.1       albertel 2746: 
1.6       albertel 2747: sub get_unprocessed_cgi {
1.25      albertel 2748:   my ($query,$possible_names)= @_;
1.26      matthew  2749:   # $Apache::lonxml::debug=1;
1.16      harris41 2750:   foreach (split(/&/,$query)) {
1.6       albertel 2751:     my ($name, $value) = split(/=/,$_);
1.25      albertel 2752:     $name = &Apache::lonnet::unescape($name);
                   2753:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   2754:       $value =~ tr/+/ /;
                   2755:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                   2756:       &Apache::lonxml::debug("Seting :$name: to :$value:");
1.30      albertel 2757:       unless (defined($ENV{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 2758:     }
1.16      harris41 2759:   }
1.6       albertel 2760: }
                   2761: 
1.112     bowersj2 2762: =pod
                   2763: 
                   2764: =item * cacheheader() 
                   2765: 
                   2766: returns cache-controlling header code
                   2767: 
                   2768: =cut
                   2769: 
1.7       albertel 2770: sub cacheheader {
1.216     albertel 2771:     unless ($ENV{'request.method'} eq 'GET') { return ''; }
                   2772:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   2773:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 2774:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   2775:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 2776:     return $output;
1.7       albertel 2777: }
                   2778: 
1.112     bowersj2 2779: =pod
                   2780: 
                   2781: =item * no_cache($r) 
                   2782: 
                   2783: specifies header code to not have cache
                   2784: 
                   2785: =cut
                   2786: 
1.9       albertel 2787: sub no_cache {
1.216     albertel 2788:     my ($r) = @_;
                   2789:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
                   2790: 	$ENV{'request.method'} ne 'GET') { return ''; }
                   2791:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   2792:     $r->no_cache(1);
                   2793:     $r->header_out("Expires" => $date);
                   2794:     $r->header_out("Pragma" => "no-cache");
1.123     www      2795: }
                   2796: 
                   2797: sub content_type {
1.181     albertel 2798:     my ($r,$type,$charset) = @_;
                   2799:     unless ($charset) {
                   2800: 	$charset=&Apache::lonlocal::current_encoding;
                   2801:     }
                   2802:     if ($charset) { $type.='; charset='.$charset; }
                   2803:     if ($r) {
                   2804: 	$r->content_type($type);
                   2805:     } else {
                   2806: 	print("Content-type: $type\n\n");
                   2807:     }
1.9       albertel 2808: }
1.25      albertel 2809: 
1.112     bowersj2 2810: =pod
                   2811: 
                   2812: =item * add_to_env($name,$value) 
                   2813: 
                   2814: adds $name to the %ENV hash with value
                   2815: $value, if $name already exists, the entry is converted to an array
                   2816: reference and $value is added to the array.
                   2817: 
                   2818: =cut
                   2819: 
1.25      albertel 2820: sub add_to_env {
                   2821:   my ($name,$value)=@_;
1.28      albertel 2822:   if (defined($ENV{$name})) {
1.27      albertel 2823:     if (ref($ENV{$name})) {
1.25      albertel 2824:       #already have multiple values
                   2825:       push(@{ $ENV{$name} },$value);
                   2826:     } else {
                   2827:       #first time seeing multiple values, convert hash entry to an arrayref
                   2828:       my $first=$ENV{$name};
                   2829:       undef($ENV{$name});
                   2830:       push(@{ $ENV{$name} },$first,$value);
                   2831:     }
                   2832:   } else {
                   2833:     $ENV{$name}=$value;
                   2834:   }
1.31      albertel 2835: }
1.149     albertel 2836: 
                   2837: =pod
                   2838: 
                   2839: =item * get_env_multiple($name) 
                   2840: 
                   2841: gets $name from the %ENV hash, it seemlessly handles the cases where multiple
                   2842: values may be defined and end up as an array ref.
                   2843: 
                   2844: returns an array of values
                   2845: 
                   2846: =cut
                   2847: 
                   2848: sub get_env_multiple {
                   2849:     my ($name) = @_;
                   2850:     my @values;
                   2851:     if (defined($ENV{$name})) {
                   2852:         # exists is it an array
                   2853:         if (ref($ENV{$name})) {
                   2854:             @values=@{ $ENV{$name} };
                   2855:         } else {
                   2856:             $values[0]=$ENV{$name};
                   2857:         }
                   2858:     }
                   2859:     return(@values);
                   2860: }
                   2861: 
1.31      albertel 2862: 
1.41      ng       2863: =pod
1.45      matthew  2864: 
                   2865: =back 
1.41      ng       2866: 
1.112     bowersj2 2867: =head1 CSV Upload/Handling functions
1.38      albertel 2868: 
1.41      ng       2869: =over 4
                   2870: 
1.112     bowersj2 2871: =item * upfile_store($r)
1.41      ng       2872: 
                   2873: Store uploaded file, $r should be the HTTP Request object,
                   2874: needs $ENV{'form.upfile'}
                   2875: returns $datatoken to be put into hidden field
                   2876: 
                   2877: =cut
1.31      albertel 2878: 
                   2879: sub upfile_store {
                   2880:     my $r=shift;
                   2881:     $ENV{'form.upfile'}=~s/\r/\n/gs;
                   2882:     $ENV{'form.upfile'}=~s/\f/\n/gs;
                   2883:     $ENV{'form.upfile'}=~s/\n+/\n/gs;
                   2884:     $ENV{'form.upfile'}=~s/\n+$//gs;
                   2885: 
                   2886:     my $datatoken=$ENV{'user.name'}.'_'.$ENV{'user.domain'}.
                   2887: 	'_enroll_'.$ENV{'request.course.id'}.'_'.time.'_'.$$;
                   2888:     {
1.158     raeburn  2889:         my $datafile = $r->dir_config('lonDaemons').
                   2890:                            '/tmp/'.$datatoken.'.tmp';
                   2891:         if ( open(my $fh,">$datafile") ) {
                   2892:             print $fh $ENV{'form.upfile'};
                   2893:             close($fh);
                   2894:         }
1.31      albertel 2895:     }
                   2896:     return $datatoken;
                   2897: }
                   2898: 
1.56      matthew  2899: =pod
                   2900: 
1.112     bowersj2 2901: =item * load_tmp_file($r)
1.41      ng       2902: 
                   2903: Load uploaded file from tmp, $r should be the HTTP Request object,
                   2904: needs $ENV{'form.datatoken'},
                   2905: sets $ENV{'form.upfile'} to the contents of the file
                   2906: 
                   2907: =cut
1.31      albertel 2908: 
                   2909: sub load_tmp_file {
                   2910:     my $r=shift;
                   2911:     my @studentdata=();
                   2912:     {
1.158     raeburn  2913:         my $studentfile = $r->dir_config('lonDaemons').
                   2914:                               '/tmp/'.$ENV{'form.datatoken'}.'.tmp';
                   2915:         if ( open(my $fh,"<$studentfile") ) {
                   2916:             @studentdata=<$fh>;
                   2917:             close($fh);
                   2918:         }
1.31      albertel 2919:     }
                   2920:     $ENV{'form.upfile'}=join('',@studentdata);
                   2921: }
                   2922: 
1.56      matthew  2923: =pod
                   2924: 
1.112     bowersj2 2925: =item * upfile_record_sep()
1.41      ng       2926: 
                   2927: Separate uploaded file into records
                   2928: returns array of records,
                   2929: needs $ENV{'form.upfile'} and $ENV{'form.upfiletype'}
                   2930: 
                   2931: =cut
1.31      albertel 2932: 
                   2933: sub upfile_record_sep {
                   2934:     if ($ENV{'form.upfiletype'} eq 'xml') {
                   2935:     } else {
                   2936: 	return split(/\n/,$ENV{'form.upfile'});
                   2937:     }
                   2938: }
                   2939: 
1.56      matthew  2940: =pod
                   2941: 
1.112     bowersj2 2942: =item * record_sep($record)
1.41      ng       2943: 
                   2944: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $ENV{'form.upfiletype'}
                   2945: 
                   2946: =cut
                   2947: 
1.31      albertel 2948: sub record_sep {
                   2949:     my $record=shift;
                   2950:     my %components=();
                   2951:     if ($ENV{'form.upfiletype'} eq 'xml') {
                   2952:     } elsif ($ENV{'form.upfiletype'} eq 'space') {
                   2953:         my $i=0;
                   2954:         foreach (split(/\s+/,$record)) {
                   2955:             my $field=$_;
                   2956:             $field=~s/^(\"|\')//;
                   2957:             $field=~s/(\"|\')$//;
                   2958:             $components{$i}=$field;
                   2959:             $i++;
                   2960:         }
                   2961:     } elsif ($ENV{'form.upfiletype'} eq 'tab') {
                   2962:         my $i=0;
1.171     matthew  2963:         foreach (split(/\t/,$record)) {
1.31      albertel 2964:             my $field=$_;
                   2965:             $field=~s/^(\"|\')//;
                   2966:             $field=~s/(\"|\')$//;
                   2967:             $components{$i}=$field;
                   2968:             $i++;
                   2969:         }
                   2970:     } else {
                   2971:         my @allfields=split(/\,/,$record);
                   2972:         my $i=0;
                   2973:         my $j;
                   2974:         for ($j=0;$j<=$#allfields;$j++) {
                   2975:             my $field=$allfields[$j];
                   2976:             if ($field=~/^\s*(\"|\')/) {
                   2977: 		my $delimiter=$1;
                   2978:                 while (($field!~/$delimiter$/) && ($j<$#allfields)) {
                   2979: 		    $j++;
                   2980: 		    $field.=','.$allfields[$j];
                   2981: 		}
                   2982:                 $field=~s/^\s*$delimiter//;
                   2983:                 $field=~s/$delimiter\s*$//;
                   2984:             }
                   2985:             $components{$i}=$field;
                   2986: 	    $i++;
                   2987:         }
                   2988:     }
                   2989:     return %components;
                   2990: }
                   2991: 
1.144     matthew  2992: ######################################################
                   2993: ######################################################
                   2994: 
1.56      matthew  2995: =pod
                   2996: 
1.112     bowersj2 2997: =item * upfile_select_html()
1.41      ng       2998: 
1.144     matthew  2999: Return HTML code to select a file from the users machine and specify 
                   3000: the file type.
1.41      ng       3001: 
                   3002: =cut
                   3003: 
1.144     matthew  3004: ######################################################
                   3005: ######################################################
1.31      albertel 3006: sub upfile_select_html {
1.144     matthew  3007:     my %Types = (
                   3008:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
                   3009:                  space => &mt('Space separated'),
                   3010:                  tab   => &mt('Tabulator separated'),
                   3011: #                 xml   => &mt('HTML/XML'),
                   3012:                  );
                   3013:     my $Str = '<input type="file" name="upfile" size="50" />'.
                   3014:         '<br />Type: <select name="upfiletype">';
                   3015:     foreach my $type (sort(keys(%Types))) {
                   3016:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   3017:     }
                   3018:     $Str .= "</select>\n";
                   3019:     return $Str;
1.31      albertel 3020: }
                   3021: 
1.144     matthew  3022: ######################################################
                   3023: ######################################################
                   3024: 
1.56      matthew  3025: =pod
                   3026: 
1.112     bowersj2 3027: =item * csv_print_samples($r,$records)
1.41      ng       3028: 
                   3029: Prints a table of sample values from each column uploaded $r is an
                   3030: Apache Request ref, $records is an arrayref from
                   3031: &Apache::loncommon::upfile_record_sep
                   3032: 
                   3033: =cut
                   3034: 
1.144     matthew  3035: ######################################################
                   3036: ######################################################
1.31      albertel 3037: sub csv_print_samples {
                   3038:     my ($r,$records) = @_;
                   3039:     my (%sone,%stwo,%sthree);
                   3040:     %sone=&record_sep($$records[0]);
                   3041:     if (defined($$records[1])) {%stwo=&record_sep($$records[1]);}
                   3042:     if (defined($$records[2])) {%sthree=&record_sep($$records[2]);}
1.144     matthew  3043:     #
                   3044:     $r->print(&mt('Samples').'<br /><table border="2"><tr>');
                   3045:     foreach (sort({$a <=> $b} keys(%sone))) { 
                   3046:         $r->print('<th>'.&mt('Column&nbsp;[_1]',($_+1)).'</th>'); }
1.31      albertel 3047:     $r->print('</tr>');
                   3048:     foreach my $hash (\%sone,\%stwo,\%sthree) {
                   3049: 	$r->print('<tr>');
                   3050: 	foreach (sort({$a <=> $b} keys(%sone))) {
                   3051: 	    $r->print('<td>');
                   3052: 	    if (defined($$hash{$_})) { $r->print($$hash{$_}); }
                   3053: 	    $r->print('</td>');
                   3054: 	}
                   3055: 	$r->print('</tr>');
                   3056:     }
                   3057:     $r->print('</tr></table><br />'."\n");
                   3058: }
                   3059: 
1.144     matthew  3060: ######################################################
                   3061: ######################################################
                   3062: 
1.56      matthew  3063: =pod
                   3064: 
1.112     bowersj2 3065: =item * csv_print_select_table($r,$records,$d)
1.41      ng       3066: 
                   3067: Prints a table to create associations between values and table columns.
1.144     matthew  3068: 
1.41      ng       3069: $r is an Apache Request ref,
                   3070: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  3071: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       3072: 
                   3073: =cut
                   3074: 
1.144     matthew  3075: ######################################################
                   3076: ######################################################
1.31      albertel 3077: sub csv_print_select_table {
                   3078:     my ($r,$records,$d) = @_;
                   3079:     my $i=0;my %sone;
                   3080:     %sone=&record_sep($$records[0]);
1.144     matthew  3081:     $r->print(&mt('Associate columns with student attributes.')."\n".
                   3082: 	     '<table border="2"><tr>'.
                   3083:               '<th>'.&mt('Attribute').'</th>'.
                   3084:               '<th>'.&mt('Column').'</th></tr>'."\n");
1.31      albertel 3085:     foreach (@$d) {
1.174     matthew  3086: 	my ($value,$display,$defaultcol)=@{ $_ };
1.31      albertel 3087: 	$r->print('<tr><td>'.$display.'</td>');
                   3088: 
                   3089: 	$r->print('<td><select name=f'.$i.
1.32      matthew  3090: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 3091: 	$r->print('<option value="none"></option>');
                   3092: 	foreach (sort({$a <=> $b} keys(%sone))) {
1.174     matthew  3093: 	    $r->print('<option value="'.$_.'"'.
                   3094:                       ($_ eq $defaultcol ? ' selected ' : '').
                   3095:                       '>Column '.($_+1).'</option>');
1.31      albertel 3096: 	}
                   3097: 	$r->print('</select></td></tr>'."\n");
                   3098: 	$i++;
                   3099:     }
                   3100:     $i--;
                   3101:     return $i;
                   3102: }
1.56      matthew  3103: 
1.144     matthew  3104: ######################################################
                   3105: ######################################################
                   3106: 
1.56      matthew  3107: =pod
1.31      albertel 3108: 
1.112     bowersj2 3109: =item * csv_samples_select_table($r,$records,$d)
1.41      ng       3110: 
                   3111: Prints a table of sample values from the upload and can make associate samples to internal names.
                   3112: 
                   3113: $r is an Apache Request ref,
                   3114: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   3115: $d is an array of 2 element arrays (internal name, displayed name)
                   3116: 
                   3117: =cut
                   3118: 
1.144     matthew  3119: ######################################################
                   3120: ######################################################
1.31      albertel 3121: sub csv_samples_select_table {
                   3122:     my ($r,$records,$d) = @_;
                   3123:     my %sone; my %stwo; my %sthree;
                   3124:     my $i=0;
1.144     matthew  3125:     #
                   3126:     $r->print('<table border=2><tr><th>'.
                   3127:               &mt('Field').'</th><th>'.&mt('Samples').'</th></tr>');
1.31      albertel 3128:     %sone=&record_sep($$records[0]);
                   3129:     if (defined($$records[1])) {%stwo=&record_sep($$records[1]);}
                   3130:     if (defined($$records[2])) {%sthree=&record_sep($$records[2]);}
1.144     matthew  3131:     #
1.31      albertel 3132:     foreach (sort keys %sone) {
1.144     matthew  3133: 	$r->print('<tr><td><select name="f'.$i.'"'.
1.32      matthew  3134: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 3135: 	foreach (@$d) {
1.174     matthew  3136: 	    my ($value,$display,$defaultcol)=@{ $_ };
                   3137: 	    $r->print('<option value="'.$value.'"'.
                   3138:                       ($i eq $defaultcol ? ' selected ':'').'>'.
                   3139:                       $display.'</option>');
1.31      albertel 3140: 	}
                   3141: 	$r->print('</select></td><td>');
                   3142: 	if (defined($sone{$_})) { $r->print($sone{$_}."</br>\n"); }
                   3143: 	if (defined($stwo{$_})) { $r->print($stwo{$_}."</br>\n"); }
                   3144: 	if (defined($sthree{$_})) { $r->print($sthree{$_}."</br>\n"); }
                   3145: 	$r->print('</td></tr>');
                   3146: 	$i++;
                   3147:     }
                   3148:     $i--;
                   3149:     return($i);
1.115     matthew  3150: }
                   3151: 
1.144     matthew  3152: ######################################################
                   3153: ######################################################
                   3154: 
1.115     matthew  3155: =pod
                   3156: 
                   3157: =item clean_excel_name($name)
                   3158: 
                   3159: Returns a replacement for $name which does not contain any illegal characters.
                   3160: 
                   3161: =cut
                   3162: 
1.144     matthew  3163: ######################################################
                   3164: ######################################################
1.115     matthew  3165: sub clean_excel_name {
                   3166:     my ($name) = @_;
                   3167:     $name =~ s/[:\*\?\/\\]//g;
                   3168:     if (length($name) > 31) {
                   3169:         $name = substr($name,0,31);
                   3170:     }
                   3171:     return $name;
1.25      albertel 3172: }
1.84      albertel 3173: 
1.85      albertel 3174: =pod
                   3175: 
1.112     bowersj2 3176: =item * check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 3177: 
                   3178: Returns either 1 or undef
                   3179: 
                   3180: 1 if the part is to be hidden, undef if it is to be shown
                   3181: 
                   3182: Arguments are:
                   3183: 
                   3184: $id the id of the part to be checked
                   3185: $symb, optional the symb of the resource to check
                   3186: $udom, optional the domain of the user to check for
                   3187: $uname, optional the username of the user to check for
                   3188: 
                   3189: =cut
1.84      albertel 3190: 
                   3191: sub check_if_partid_hidden {
                   3192:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 3193:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 3194: 					 $symb,$udom,$uname);
1.141     albertel 3195:     my $truth=1;
                   3196:     #if the string starts with !, then the list is the list to show not hide
                   3197:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 3198:     my @hiddenlist=split(/,/,$hiddenparts);
                   3199:     foreach my $checkid (@hiddenlist) {
1.141     albertel 3200: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 3201:     }
1.141     albertel 3202:     return !$truth;
1.84      albertel 3203: }
1.127     matthew  3204: 
1.138     matthew  3205: 
                   3206: ############################################################
                   3207: ############################################################
                   3208: 
                   3209: =pod
                   3210: 
1.157     matthew  3211: =back 
                   3212: 
1.138     matthew  3213: =head1 cgi-bin script and graphing routines
                   3214: 
1.157     matthew  3215: =over 4
                   3216: 
1.138     matthew  3217: =item get_cgi_id
                   3218: 
                   3219: Inputs: none
                   3220: 
                   3221: Returns an id which can be used to pass environment variables
                   3222: to various cgi-bin scripts.  These environment variables will
                   3223: be removed from the users environment after a given time by
                   3224: the routine &Apache::lonnet::transfer_profile_to_env.
                   3225: 
                   3226: =cut
                   3227: 
                   3228: ############################################################
                   3229: ############################################################
1.152     albertel 3230: my $uniq=0;
1.136     matthew  3231: sub get_cgi_id {
1.154     albertel 3232:     $uniq=($uniq+1)%100000;
1.152     albertel 3233:     return (time.'_'.$uniq);
1.136     matthew  3234: }
                   3235: 
1.127     matthew  3236: ############################################################
                   3237: ############################################################
                   3238: 
                   3239: =pod
                   3240: 
1.134     matthew  3241: =item DrawBarGraph
1.127     matthew  3242: 
1.138     matthew  3243: Facilitates the plotting of data in a (stacked) bar graph.
                   3244: Puts plot definition data into the users environment in order for 
                   3245: graph.png to plot it.  Returns an <img> tag for the plot.
                   3246: The bars on the plot are labeled '1','2',...,'n'.
                   3247: 
                   3248: Inputs:
                   3249: 
                   3250: =over 4
                   3251: 
                   3252: =item $Title: string, the title of the plot
                   3253: 
                   3254: =item $xlabel: string, text describing the X-axis of the plot
                   3255: 
                   3256: =item $ylabel: string, text describing the Y-axis of the plot
                   3257: 
                   3258: =item $Max: scalar, the maximum Y value to use in the plot
                   3259: If $Max is < any data point, the graph will not be rendered.
                   3260: 
1.140     matthew  3261: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  3262: they are plotted.  If undefined, default values will be used.
                   3263: 
1.178     matthew  3264: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   3265: 
1.138     matthew  3266: =item @Values: An array of array references.  Each array reference holds data
                   3267: to be plotted in a stacked bar chart.
                   3268: 
                   3269: =back
                   3270: 
                   3271: Returns:
                   3272: 
                   3273: An <img> tag which references graph.png and the appropriate identifying
                   3274: information for the plot.
                   3275: 
1.127     matthew  3276: =cut
                   3277: 
                   3278: ############################################################
                   3279: ############################################################
1.134     matthew  3280: sub DrawBarGraph {
1.178     matthew  3281:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  3282:     #
                   3283:     if (! defined($colors)) {
                   3284:         $colors = ['#33ff00', 
                   3285:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   3286:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   3287:                   ]; 
                   3288:     }
1.127     matthew  3289:     #
1.136     matthew  3290:     my $identifier = &get_cgi_id();
                   3291:     my $id = 'cgi.'.$identifier;        
1.129     matthew  3292:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  3293:         return '';
                   3294:     }
1.225   ! matthew  3295:     #
        !          3296:     my @Labels;
        !          3297:     if (defined($labels)) {
        !          3298:         @Labels = @$labels;
        !          3299:     } else {
        !          3300:         for (my $i=0;$i<@{$Values[0]};$i++) {
        !          3301:             push (@Labels,$i+1);
        !          3302:         }
        !          3303:     }
        !          3304:     #
1.129     matthew  3305:     my $NumBars = scalar(@{$Values[0]});
1.225   ! matthew  3306:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  3307:     my %ValuesHash;
                   3308:     my $NumSets=1;
                   3309:     foreach my $array (@Values) {
                   3310:         next if (! ref($array));
1.136     matthew  3311:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  3312:             join(',',@$array);
1.129     matthew  3313:     }
1.127     matthew  3314:     #
1.136     matthew  3315:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225   ! matthew  3316:     if ($NumBars < 3) {
        !          3317:         $width = 120+$NumBars*32;
1.220     matthew  3318:         $xskip = 1;
1.225   ! matthew  3319:         $bar_width = 30;
        !          3320:     } elsif ($NumBars < 5) {
        !          3321:         $width = 120+$NumBars*20;
        !          3322:         $xskip = 1;
        !          3323:         $bar_width = 20;
1.220     matthew  3324:     } elsif ($NumBars < 10) {
1.136     matthew  3325:         $width = 120+$NumBars*15;
                   3326:         $xskip = 1;
                   3327:         $bar_width = 15;
                   3328:     } elsif ($NumBars <= 25) {
                   3329:         $width = 120+$NumBars*11;
                   3330:         $xskip = 5;
                   3331:         $bar_width = 8;
                   3332:     } elsif ($NumBars <= 50) {
                   3333:         $width = 120+$NumBars*8;
                   3334:         $xskip = 5;
                   3335:         $bar_width = 4;
                   3336:     } else {
                   3337:         $width = 120+$NumBars*8;
                   3338:         $xskip = 5;
                   3339:         $bar_width = 4;
                   3340:     }
                   3341:     #
1.137     matthew  3342:     $Max = 1 if ($Max < 1);
                   3343:     if ( int($Max) < $Max ) {
                   3344:         $Max++;
                   3345:         $Max = int($Max);
                   3346:     }
1.127     matthew  3347:     $Title  = '' if (! defined($Title));
                   3348:     $xlabel = '' if (! defined($xlabel));
                   3349:     $ylabel = '' if (! defined($ylabel));
1.136     matthew  3350:     $ValuesHash{$id.'.title'}    = &Apache::lonnet::escape($Title);
                   3351:     $ValuesHash{$id.'.xlabel'}   = &Apache::lonnet::escape($xlabel);
                   3352:     $ValuesHash{$id.'.ylabel'}   = &Apache::lonnet::escape($ylabel);
1.137     matthew  3353:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  3354:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   3355:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   3356:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   3357:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   3358:     $ValuesHash{$id.'.height'}   = $height;
                   3359:     $ValuesHash{$id.'.width'}    = $width;
                   3360:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   3361:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   3362:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  3363:     #
1.137     matthew  3364:     &Apache::lonnet::appenv(%ValuesHash);
                   3365:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   3366: }
                   3367: 
                   3368: ############################################################
                   3369: ############################################################
                   3370: 
                   3371: =pod
                   3372: 
                   3373: =item DrawXYGraph
                   3374: 
1.138     matthew  3375: Facilitates the plotting of data in an XY graph.
                   3376: Puts plot definition data into the users environment in order for 
                   3377: graph.png to plot it.  Returns an <img> tag for the plot.
                   3378: 
                   3379: Inputs:
                   3380: 
                   3381: =over 4
                   3382: 
                   3383: =item $Title: string, the title of the plot
                   3384: 
                   3385: =item $xlabel: string, text describing the X-axis of the plot
                   3386: 
                   3387: =item $ylabel: string, text describing the Y-axis of the plot
                   3388: 
                   3389: =item $Max: scalar, the maximum Y value to use in the plot
                   3390: If $Max is < any data point, the graph will not be rendered.
                   3391: 
                   3392: =item $colors: Array ref containing the hex color codes for the data to be 
                   3393: plotted in.  If undefined, default values will be used.
                   3394: 
                   3395: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   3396: 
                   3397: =item $Ydata: Array ref containing Array refs.  
1.185     www      3398: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  3399: 
                   3400: =item %Values: hash indicating or overriding any default values which are 
                   3401: passed to graph.png.  
                   3402: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   3403: 
                   3404: =back
                   3405: 
                   3406: Returns:
                   3407: 
                   3408: An <img> tag which references graph.png and the appropriate identifying
                   3409: information for the plot.
                   3410: 
1.137     matthew  3411: =cut
                   3412: 
                   3413: ############################################################
                   3414: ############################################################
                   3415: sub DrawXYGraph {
                   3416:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   3417:     #
                   3418:     # Create the identifier for the graph
                   3419:     my $identifier = &get_cgi_id();
                   3420:     my $id = 'cgi.'.$identifier;
                   3421:     #
                   3422:     $Title  = '' if (! defined($Title));
                   3423:     $xlabel = '' if (! defined($xlabel));
                   3424:     $ylabel = '' if (! defined($ylabel));
                   3425:     my %ValuesHash = 
                   3426:         (
                   3427:          $id.'.title'  => &Apache::lonnet::escape($Title),
                   3428:          $id.'.xlabel' => &Apache::lonnet::escape($xlabel),
                   3429:          $id.'.ylabel' => &Apache::lonnet::escape($ylabel),
                   3430:          $id.'.y_max_value'=> $Max,
                   3431:          $id.'.labels'     => join(',',@$Xlabels),
                   3432:          $id.'.PlotType'   => 'XY',
                   3433:          );
                   3434:     #
                   3435:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   3436:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   3437:     }
                   3438:     #
                   3439:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   3440:         return '';
                   3441:     }
                   3442:     my $NumSets=1;
1.138     matthew  3443:     foreach my $array (@{$Ydata}){
1.137     matthew  3444:         next if (! ref($array));
                   3445:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   3446:     }
1.138     matthew  3447:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  3448:     #
                   3449:     # Deal with other parameters
                   3450:     while (my ($key,$value) = each(%Values)) {
                   3451:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  3452:     }
                   3453:     #
1.136     matthew  3454:     &Apache::lonnet::appenv(%ValuesHash);
                   3455:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   3456: }
                   3457: 
                   3458: ############################################################
                   3459: ############################################################
                   3460: 
                   3461: =pod
                   3462: 
1.138     matthew  3463: =item DrawXYYGraph
                   3464: 
                   3465: Facilitates the plotting of data in an XY graph with two Y axes.
                   3466: Puts plot definition data into the users environment in order for 
                   3467: graph.png to plot it.  Returns an <img> tag for the plot.
                   3468: 
                   3469: Inputs:
                   3470: 
                   3471: =over 4
                   3472: 
                   3473: =item $Title: string, the title of the plot
                   3474: 
                   3475: =item $xlabel: string, text describing the X-axis of the plot
                   3476: 
                   3477: =item $ylabel: string, text describing the Y-axis of the plot
                   3478: 
                   3479: =item $colors: Array ref containing the hex color codes for the data to be 
                   3480: plotted in.  If undefined, default values will be used.
                   3481: 
                   3482: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   3483: 
                   3484: =item $Ydata1: The first data set
                   3485: 
                   3486: =item $Min1: The minimum value of the left Y-axis
                   3487: 
                   3488: =item $Max1: The maximum value of the left Y-axis
                   3489: 
                   3490: =item $Ydata2: The second data set
                   3491: 
                   3492: =item $Min2: The minimum value of the right Y-axis
                   3493: 
                   3494: =item $Max2: The maximum value of the left Y-axis
                   3495: 
                   3496: =item %Values: hash indicating or overriding any default values which are 
                   3497: passed to graph.png.  
                   3498: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   3499: 
                   3500: =back
                   3501: 
                   3502: Returns:
                   3503: 
                   3504: An <img> tag which references graph.png and the appropriate identifying
                   3505: information for the plot.
1.136     matthew  3506: 
                   3507: =cut
                   3508: 
                   3509: ############################################################
                   3510: ############################################################
1.137     matthew  3511: sub DrawXYYGraph {
                   3512:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   3513:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  3514:     #
                   3515:     # Create the identifier for the graph
                   3516:     my $identifier = &get_cgi_id();
                   3517:     my $id = 'cgi.'.$identifier;
                   3518:     #
                   3519:     $Title  = '' if (! defined($Title));
                   3520:     $xlabel = '' if (! defined($xlabel));
                   3521:     $ylabel = '' if (! defined($ylabel));
                   3522:     my %ValuesHash = 
                   3523:         (
                   3524:          $id.'.title'  => &Apache::lonnet::escape($Title),
                   3525:          $id.'.xlabel' => &Apache::lonnet::escape($xlabel),
                   3526:          $id.'.ylabel' => &Apache::lonnet::escape($ylabel),
                   3527:          $id.'.labels' => join(',',@$Xlabels),
                   3528:          $id.'.PlotType' => 'XY',
                   3529:          $id.'.NumSets' => 2,
1.137     matthew  3530:          $id.'.two_axes' => 1,
                   3531:          $id.'.y1_max_value' => $Max1,
                   3532:          $id.'.y1_min_value' => $Min1,
                   3533:          $id.'.y2_max_value' => $Max2,
                   3534:          $id.'.y2_min_value' => $Min2,
1.136     matthew  3535:          );
                   3536:     #
1.137     matthew  3537:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   3538:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   3539:     }
                   3540:     #
                   3541:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   3542:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  3543:         return '';
                   3544:     }
                   3545:     my $NumSets=1;
1.137     matthew  3546:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  3547:         next if (! ref($array));
                   3548:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  3549:     }
                   3550:     #
                   3551:     # Deal with other parameters
                   3552:     while (my ($key,$value) = each(%Values)) {
                   3553:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  3554:     }
                   3555:     #
                   3556:     &Apache::lonnet::appenv(%ValuesHash);
1.130     albertel 3557:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  3558: }
                   3559: 
                   3560: ############################################################
                   3561: ############################################################
                   3562: 
                   3563: =pod
                   3564: 
1.157     matthew  3565: =back 
                   3566: 
1.139     matthew  3567: =head1 Statistics helper routines?  
                   3568: 
                   3569: Bad place for them but what the hell.
                   3570: 
1.157     matthew  3571: =over 4
                   3572: 
1.139     matthew  3573: =item &chartlink
                   3574: 
                   3575: Returns a link to the chart for a specific student.  
                   3576: 
                   3577: Inputs:
                   3578: 
                   3579: =over 4
                   3580: 
                   3581: =item $linktext: The text of the link
                   3582: 
                   3583: =item $sname: The students username
                   3584: 
                   3585: =item $sdomain: The students domain
                   3586: 
                   3587: =back
                   3588: 
1.157     matthew  3589: =back
                   3590: 
1.139     matthew  3591: =cut
                   3592: 
                   3593: ############################################################
                   3594: ############################################################
                   3595: sub chartlink {
                   3596:     my ($linktext, $sname, $sdomain) = @_;
                   3597:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.219     albertel 3598:         '&amp;SelectedStudent='.&Apache::lonnet::escape($sname.':'.$sdomain).
                   3599:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  3600:        '">'.$linktext.'</a>';
1.153     matthew  3601: }
                   3602: 
                   3603: #######################################################
                   3604: #######################################################
                   3605: 
                   3606: =pod
                   3607: 
                   3608: =head1 Course Environment Routines
1.157     matthew  3609: 
                   3610: =over 4
1.153     matthew  3611: 
                   3612: =item &restore_course_settings 
                   3613: 
                   3614: =item &store_course_settings
                   3615: 
                   3616: Restores/Store indicated form parameters from the course environment.
                   3617: Will not overwrite existing values of the form parameters.
                   3618: 
                   3619: Inputs: 
                   3620: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   3621: 
                   3622: a hash ref describing the data to be stored.  For example:
                   3623:    
                   3624: %Save_Parameters = ('Status' => 'scalar',
                   3625:     'chartoutputmode' => 'scalar',
                   3626:     'chartoutputdata' => 'scalar',
                   3627:     'Section' => 'array',
                   3628:     'StudentData' => 'array',
                   3629:     'Maps' => 'array');
                   3630: 
                   3631: Returns: both routines return nothing
                   3632: 
                   3633: =cut
                   3634: 
                   3635: #######################################################
                   3636: #######################################################
                   3637: sub store_course_settings {
                   3638:     # save to the environment
                   3639:     # appenv the same items, just to be safe
                   3640:     my $courseid = $ENV{'request.course.id'};
                   3641:     my $coursedom = $ENV{'course.'.$courseid.'.domain'};
                   3642:     my ($prefix,$Settings) = @_;
                   3643:     my %SaveHash;
                   3644:     my %AppHash;
                   3645:     while (my ($setting,$type) = each(%$Settings)) {
1.176     albertel 3646:         my $basename = 'internal.'.$prefix.'.'.$setting;
1.153     matthew  3647:         my $envname = 'course.'.$courseid.'.'.$basename;
                   3648:         if (exists($ENV{'form.'.$setting})) {
                   3649:             # Save this value away
                   3650:             if ($type eq 'scalar' &&
                   3651:                 (! exists($ENV{$envname}) || 
                   3652:                  $ENV{$envname} ne $ENV{'form.'.$setting})) {
                   3653:                 $SaveHash{$basename} = $ENV{'form.'.$setting};
                   3654:                 $AppHash{$envname}   = $ENV{'form.'.$setting};
                   3655:             } elsif ($type eq 'array') {
                   3656:                 my $stored_form;
                   3657:                 if (ref($ENV{'form.'.$setting})) {
                   3658:                     $stored_form = join(',',
                   3659:                                         map {
                   3660:                                             &Apache::lonnet::escape($_);
                   3661:                                         } sort(@{$ENV{'form.'.$setting}}));
                   3662:                 } else {
                   3663:                     $stored_form = 
                   3664:                         &Apache::lonnet::escape($ENV{'form.'.$setting});
                   3665:                 }
                   3666:                 # Determine if the array contents are the same.
                   3667:                 if ($stored_form ne $ENV{$envname}) {
                   3668:                     $SaveHash{$basename} = $stored_form;
                   3669:                     $AppHash{$envname}   = $stored_form;
                   3670:                 }
                   3671:             }
                   3672:         }
                   3673:     }
                   3674:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
                   3675:                                           $coursedom,
                   3676:                                           $ENV{'course.'.$courseid.'.num'});
                   3677:     if ($put_result !~ /^(ok|delayed)/) {
                   3678:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   3679:                                  'got error:'.$put_result);
                   3680:     }
                   3681:     # Make sure these settings stick around in this session, too
                   3682:     &Apache::lonnet::appenv(%AppHash);
                   3683:     return;
                   3684: }
                   3685: 
                   3686: sub restore_course_settings {
                   3687:     my $courseid = $ENV{'request.course.id'};
                   3688:     my ($prefix,$Settings) = @_;
                   3689:     while (my ($setting,$type) = each(%$Settings)) {
                   3690:         next if (exists($ENV{'form.'.$setting}));
1.176     albertel 3691:         my $envname = 'course.'.$courseid.'.internal.'.$prefix.
1.153     matthew  3692:             '.'.$setting;
                   3693:         if (exists($ENV{$envname})) {
                   3694:             if ($type eq 'scalar') {
                   3695:                 $ENV{'form.'.$setting} = $ENV{$envname};
                   3696:             } elsif ($type eq 'array') {
                   3697:                 $ENV{'form.'.$setting} = [ 
                   3698:                                            map { 
                   3699:                                                &Apache::lonnet::unescape($_); 
                   3700:                                            } split(',',$ENV{$envname})
                   3701:                                            ];
                   3702:             }
                   3703:         }
                   3704:     }
1.127     matthew  3705: }
                   3706: 
                   3707: ############################################################
                   3708: ############################################################
1.154     albertel 3709: 
                   3710: sub propath {
                   3711:     my ($udom,$uname)=@_;
                   3712:     $udom=~s/\W//g;
                   3713:     $uname=~s/\W//g;
                   3714:     my $subdir=$uname.'__';
                   3715:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   3716:     my $proname="$Apache::lonnet::perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
                   3717:     return $proname;
1.156     albertel 3718: } 
                   3719: 
                   3720: sub icon {
                   3721:     my ($file)=@_;
1.168     albertel 3722:     my $curfext = (split(/\./,$file))[-1];
                   3723:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 3724:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 3725:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   3726: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   3727: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   3728: 	            $curfext.".gif") {
                   3729: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   3730: 		$curfext.".gif";
                   3731: 	}
                   3732:     }
                   3733:     return $iconname;
1.154     albertel 3734: } 
1.84      albertel 3735: 
1.215     albertel 3736: sub lonhttpdurl {
                   3737:     my ($url)=@_;
                   3738:     my $lonhttpd_port=$Apache::lonnet::perlvar{'lonhttpdPort'};
                   3739:     if (!defined($lonhttpd_port)) { $lonhttpd_port='8080'; }
                   3740:     return 'http://'.$ENV{'SERVER_NAME'}.':'.$lonhttpd_port.$url;
                   3741: }
                   3742: 
1.213     albertel 3743: sub connection_aborted {
                   3744:     my ($r)=@_;
                   3745:     $r->print(" ");$r->rflush();
                   3746:     my $c = $r->connection;
                   3747:     return $c->aborted();
                   3748: }
                   3749: 
1.221     foxr     3750: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     3751: #    strings as 'strings'.
                   3752: sub escape_single {
1.221     foxr     3753:     my ($input) = @_;
1.223     albertel 3754:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     3755:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   3756:     return $input;
                   3757: }
1.223     albertel 3758: 
1.222     foxr     3759: #  Same as escape_single, but escape's "'s  This 
                   3760: #  can be used for  "strings"
                   3761: sub escape_double {
                   3762:     my ($input) = @_;
                   3763:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   3764:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   3765:     return $input;
                   3766: }
1.223     albertel 3767:  
1.222     foxr     3768: #   Escapes the last element of a full URL.
                   3769: sub escape_url {
                   3770:     my ($url)   = @_;
                   3771:     my @urlslices = split(/\//, $url);
1.223     albertel 3772:     my $lastitem = &Apache::lonnet::escape(pop(@urlslices));
                   3773:     return join('/',@urlslices).'/'.$lastitem;
1.222     foxr     3774: }
1.41      ng       3775: =pod
                   3776: 
                   3777: =back
                   3778: 
1.112     bowersj2 3779: =cut
1.41      ng       3780: 
1.112     bowersj2 3781: 1;
                   3782: __END__;
1.41      ng       3783: 

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