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

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

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