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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.249   ! albertel    4: # $Id: loncommon.pm,v 1.248 2005/02/12 03:27:57 albertel Exp $
1.10      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
                     29: # Makes a table out of the previous attempts
1.2       albertel   30: # Inputs result_from_symbread, user, domain, course_id
1.16      harris41   31: # Reads in non-network-related .tab files
1.1       albertel   32: 
1.35      matthew    33: # POD header:
                     34: 
1.45      matthew    35: =pod
                     36: 
1.35      matthew    37: =head1 NAME
                     38: 
                     39: Apache::loncommon - pile of common routines
                     40: 
                     41: =head1 SYNOPSIS
                     42: 
1.112     bowersj2   43: Common routines for manipulating connections, student answers,
                     44:     domains, common Javascript fragments, etc.
1.35      matthew    45: 
1.112     bowersj2   46: =head1 OVERVIEW
1.35      matthew    47: 
1.112     bowersj2   48: A collection of commonly used subroutines that don't have a natural
                     49: home anywhere else. This collection helps remove
1.35      matthew    50: redundancy from other modules and increase efficiency of memory usage.
                     51: 
                     52: =cut 
                     53: 
                     54: # End of POD header
1.1       albertel   55: package Apache::loncommon;
                     56: 
                     57: use strict;
1.22      www        58: use Apache::lonnet();
1.46      matthew    59: use GDBM_File;
1.51      www        60: use POSIX qw(strftime mktime);
1.99      www        61: use Apache::Constants qw(:common :http :methods);
1.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);
1.246     matthew   897:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew   898:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew   899:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew   900:     return $format;
                    901: }
                    902: 
                    903: ###############################################################
                    904: ###############################################################
1.113     bowersj2  905: 
                    906: =pod
                    907: 
                    908: =item * change_content_javascript():
                    909: 
                    910: This and the next function allow you to create small sections of an
                    911: otherwise static HTML page that you can update on the fly with
                    912: Javascript, even in Netscape 4.
                    913: 
                    914: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                    915: must be written to the HTML page once. It will prove the Javascript
                    916: function "change(name, content)". Calling the change function with the
                    917: name of the section 
                    918: you want to update, matching the name passed to C<changable_area>, and
                    919: the new content you want to put in there, will put the content into
                    920: that area.
                    921: 
                    922: B<Note>: Netscape 4 only reserves enough space for the changable area
                    923: to contain room for the original contents. You need to "make space"
                    924: for whatever changes you wish to make, and be B<sure> to check your
                    925: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                    926: it's adequate for updating a one-line status display, but little more.
                    927: This script will set the space to 100% width, so you only need to
                    928: worry about height in Netscape 4.
                    929: 
                    930: Modern browsers are much less limiting, and if you can commit to the
                    931: user not using Netscape 4, this feature may be used freely with
                    932: pretty much any HTML.
                    933: 
                    934: =cut
                    935: 
                    936: sub change_content_javascript {
                    937:     # If we're on Netscape 4, we need to use Layer-based code
                    938:     if ($ENV{'browser.type'} eq 'netscape' &&
                    939: 	$ENV{'browser.version'} =~ /^4\./) {
                    940: 	return (<<NETSCAPE4);
                    941: 	function change(name, content) {
                    942: 	    doc = document.layers[name+"___escape"].layers[0].document;
                    943: 	    doc.open();
                    944: 	    doc.write(content);
                    945: 	    doc.close();
                    946: 	}
                    947: NETSCAPE4
                    948:     } else {
                    949: 	# Otherwise, we need to use semi-standards-compliant code
                    950: 	# (technically, "innerHTML" isn't standard but the equivalent
                    951: 	# is really scary, and every useful browser supports it
                    952: 	return (<<DOMBASED);
                    953: 	function change(name, content) {
                    954: 	    element = document.getElementById(name);
                    955: 	    element.innerHTML = content;
                    956: 	}
                    957: DOMBASED
                    958:     }
                    959: }
                    960: 
                    961: =pod
                    962: 
                    963: =item * changable_area($name, $origContent):
                    964: 
                    965: This provides a "changable area" that can be modified on the fly via
                    966: the Javascript code provided in C<change_content_javascript>. $name is
                    967: the name you will use to reference the area later; do not repeat the
                    968: same name on a given HTML page more then once. $origContent is what
                    969: the area will originally contain, which can be left blank.
                    970: 
                    971: =cut
                    972: 
                    973: sub changable_area {
                    974:     my ($name, $origContent) = @_;
                    975: 
                    976:     if ($ENV{'browser.type'} eq 'netscape' &&
                    977: 	$ENV{'browser.version'} =~ /^4\./) {
                    978: 	# If this is netscape 4, we need to use the Layer tag
                    979: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                    980:     } else {
                    981: 	return "<span id='$name'>$origContent</span>";
                    982:     }
                    983: }
                    984: 
                    985: =pod
                    986: 
                    987: =back
                    988: 
                    989: =cut
1.37      matthew   990: 
                    991: ###############################################################
1.33      matthew   992: ##        Home server <option> list generating code          ##
                    993: ###############################################################
1.35      matthew   994: 
1.45      matthew   995: =pod
                    996: 
1.112     bowersj2  997: =head1 Home Server option list generating code
                    998: 
                    999: =over 4
                   1000: 
                   1001: =item * get_domains()
1.35      matthew  1002: 
                   1003: Returns an array containing each of the domains listed in the hosts.tab
                   1004: file.
                   1005: 
                   1006: =cut
                   1007: 
                   1008: #-------------------------------------------
1.34      matthew  1009: sub get_domains {
                   1010:     # The code below was stolen from "The Perl Cookbook", p 102, 1st ed.
                   1011:     my @domains;
                   1012:     my %seen;
                   1013:     foreach (sort values(%Apache::lonnet::hostdom)) {
1.169     www      1014: 	push (@domains,$_) unless $seen{$_}++;
1.34      matthew  1015:     }
                   1016:     return @domains;
                   1017: }
1.88      www      1018: 
1.169     www      1019: # ------------------------------------------
                   1020: 
                   1021: sub domain_select {
                   1022:     my ($name,$value,$multiple)=@_;
                   1023:     my %domains=map { 
                   1024: 	$_ => $_.' '.$Apache::lonnet::domaindescription{$_} 
                   1025:     } &get_domains;
                   1026:     if ($multiple) {
                   1027: 	$domains{''}=&mt('Any domain');
1.191     matthew  1028: 	return &multiple_select_form($name,$value,4,%domains);
1.169     www      1029:     } else {
                   1030: 	return &select_form($name,$value,%domains);
                   1031:     }
                   1032: }
                   1033: 
                   1034: sub multiple_select_form {
1.191     matthew  1035:     my ($name,$value,$size,%hash)=@_;
1.169     www      1036:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   1037:     my $output='';
1.191     matthew  1038:     if (! defined($size)) {
                   1039:         $size = 4;
                   1040:         if (scalar(keys(%hash))<4) {
                   1041:             $size = scalar(keys(%hash));
                   1042:         }
                   1043:     }
1.169     www      1044:     $output.="\n<select name='$name' size='$size' multiple='1'>";
1.191     matthew  1045:     foreach (sort(keys(%hash))) {
                   1046:         $output.='<option value="'.$_.'" ';
                   1047:         $output.='selected ' if ($selected{$_});
                   1048:         $output.='>'.$hash{$_}."</option>\n";
1.169     www      1049:     }
                   1050:     $output.="</select>\n";
                   1051:     return $output;
                   1052: }
                   1053: 
1.88      www      1054: #-------------------------------------------
                   1055: 
                   1056: =pod
                   1057: 
1.112     bowersj2 1058: =item * select_form($defdom,$name,%hash)
1.88      www      1059: 
                   1060: Returns a string containing a <select name='$name' size='1'> form to 
                   1061: allow a user to select options from a hash option_name => displayed text.  
                   1062: See lonrights.pm for an example invocation and use.
                   1063: 
                   1064: =cut
                   1065: 
                   1066: #-------------------------------------------
                   1067: sub select_form {
                   1068:     my ($def,$name,%hash) = @_;
                   1069:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
1.128     albertel 1070:     my @keys;
                   1071:     if (exists($hash{'select_form_order'})) {
                   1072: 	@keys=@{$hash{'select_form_order'}};
                   1073:     } else {
                   1074: 	@keys=sort(keys(%hash));
                   1075:     }
                   1076:     foreach (@keys) {
1.88      www      1077:         $selectform.="<option value=\"$_\" ".
                   1078:             ($_ eq $def ? 'selected' : '').
1.119     www      1079:                 ">".&mt($hash{$_})."</option>\n";
1.88      www      1080:     }
                   1081:     $selectform.="</select>";
                   1082:     return $selectform;
                   1083: }
                   1084: 
1.167     www      1085: sub gradeleveldescription {
                   1086:     my $gradelevel=shift;
                   1087:     my %gradelevels=(0 => 'Not specified',
                   1088: 		     1 => 'Grade 1',
                   1089: 		     2 => 'Grade 2',
                   1090: 		     3 => 'Grade 3',
                   1091: 		     4 => 'Grade 4',
                   1092: 		     5 => 'Grade 5',
                   1093: 		     6 => 'Grade 6',
                   1094: 		     7 => 'Grade 7',
                   1095: 		     8 => 'Grade 8',
                   1096: 		     9 => 'Grade 9',
                   1097: 		     10 => 'Grade 10',
                   1098: 		     11 => 'Grade 11',
                   1099: 		     12 => 'Grade 12',
                   1100: 		     13 => 'Grade 13',
                   1101: 		     14 => '100 Level',
                   1102: 		     15 => '200 Level',
                   1103: 		     16 => '300 Level',
                   1104: 		     17 => '400 Level',
                   1105: 		     18 => 'Graduate Level');
                   1106:     return &mt($gradelevels{$gradelevel});
                   1107: }
                   1108: 
1.163     www      1109: sub select_level_form {
                   1110:     my ($deflevel,$name)=@_;
                   1111:     unless ($deflevel) { $deflevel=0; }
1.167     www      1112:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   1113:     for (my $i=0; $i<=18; $i++) {
                   1114:         $selectform.="<option value=\"$i\" ".
                   1115:             ($i==$deflevel ? 'selected' : '').
                   1116:                 ">".&gradeleveldescription($i)."</option>\n";
                   1117:     }
                   1118:     $selectform.="</select>";
                   1119:     return $selectform;
1.163     www      1120: }
1.167     www      1121: 
1.35      matthew  1122: #-------------------------------------------
                   1123: 
1.45      matthew  1124: =pod
                   1125: 
1.112     bowersj2 1126: =item * select_dom_form($defdom,$name,$includeempty)
1.35      matthew  1127: 
                   1128: Returns a string containing a <select name='$name' size='1'> form to 
                   1129: allow a user to select the domain to preform an operation in.  
                   1130: See loncreateuser.pm for an example invocation and use.
                   1131: 
1.90      www      1132: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   1133: selected");
                   1134: 
1.35      matthew  1135: =cut
                   1136: 
                   1137: #-------------------------------------------
1.34      matthew  1138: sub select_dom_form {
1.90      www      1139:     my ($defdom,$name,$includeempty) = @_;
1.34      matthew  1140:     my @domains = get_domains();
1.90      www      1141:     if ($includeempty) { @domains=('',@domains); }
1.34      matthew  1142:     my $selectdomain = "<select name=\"$name\" size=\"1\">\n";
                   1143:     foreach (@domains) {
                   1144:         $selectdomain.="<option value=\"$_\" ".
1.249   ! albertel 1145:             ($_ eq $defdom ? 'selected="selected"' : '').
1.34      matthew  1146:                 ">$_</option>\n";
                   1147:     }
                   1148:     $selectdomain.="</select>";
                   1149:     return $selectdomain;
                   1150: }
                   1151: 
1.35      matthew  1152: #-------------------------------------------
                   1153: 
1.45      matthew  1154: =pod
                   1155: 
1.112     bowersj2 1156: =item * get_library_servers($domain)
1.35      matthew  1157: 
                   1158: Returns a hash which contains keys like '103l3' and values like 
                   1159: 'kirk.lite.msu.edu'.  All of the keys will be for machines in the
                   1160: given $domain.
                   1161: 
                   1162: =cut
                   1163: 
                   1164: #-------------------------------------------
1.52      matthew  1165: sub get_library_servers {
1.33      matthew  1166:     my $domain = shift;
1.52      matthew  1167:     my %library_servers;
1.33      matthew  1168:     foreach (keys(%Apache::lonnet::libserv)) {
                   1169:         if ($Apache::lonnet::hostdom{$_} eq $domain) {
1.52      matthew  1170:             $library_servers{$_} = $Apache::lonnet::hostname{$_};
1.33      matthew  1171:         }
                   1172:     }
1.52      matthew  1173:     return %library_servers;
1.33      matthew  1174: }
                   1175: 
1.35      matthew  1176: #-------------------------------------------
                   1177: 
1.45      matthew  1178: =pod
                   1179: 
1.112     bowersj2 1180: =item * home_server_option_list($domain)
1.35      matthew  1181: 
                   1182: returns a string which contains an <option> list to be used in a 
                   1183: <select> form input.  See loncreateuser.pm for an example.
                   1184: 
                   1185: =cut
                   1186: 
                   1187: #-------------------------------------------
1.33      matthew  1188: sub home_server_option_list {
                   1189:     my $domain = shift;
1.52      matthew  1190:     my %servers = &get_library_servers($domain);
1.33      matthew  1191:     my $result = '';
                   1192:     foreach (sort keys(%servers)) {
                   1193:         $result.=
                   1194:             '<option value="'.$_.'">'.$_.' '.$servers{$_}."</option>\n";
                   1195:     }
                   1196:     return $result;
                   1197: }
1.112     bowersj2 1198: 
                   1199: =pod
                   1200: 
                   1201: =back
                   1202: 
                   1203: =cut
1.87      matthew  1204: 
                   1205: ###############################################################
1.112     bowersj2 1206: ##                  Decoding User Agent                      ##
1.87      matthew  1207: ###############################################################
                   1208: 
                   1209: =pod
                   1210: 
1.112     bowersj2 1211: =head1 Decoding the User Agent
                   1212: 
                   1213: =over 4
                   1214: 
                   1215: =item * &decode_user_agent()
1.87      matthew  1216: 
                   1217: Inputs: $r
                   1218: 
                   1219: Outputs:
                   1220: 
                   1221: =over 4
                   1222: 
1.112     bowersj2 1223: =item * $httpbrowser
1.87      matthew  1224: 
1.112     bowersj2 1225: =item * $clientbrowser
1.87      matthew  1226: 
1.112     bowersj2 1227: =item * $clientversion
1.87      matthew  1228: 
1.112     bowersj2 1229: =item * $clientmathml
1.87      matthew  1230: 
1.112     bowersj2 1231: =item * $clientunicode
1.87      matthew  1232: 
1.112     bowersj2 1233: =item * $clientos
1.87      matthew  1234: 
                   1235: =back
                   1236: 
1.157     matthew  1237: =back 
                   1238: 
1.87      matthew  1239: =cut
                   1240: 
                   1241: ###############################################################
                   1242: ###############################################################
                   1243: sub decode_user_agent {
1.247     albertel 1244:     my ($r)=@_;
1.87      matthew  1245:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   1246:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   1247:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 1248:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  1249:     my $clientbrowser='unknown';
                   1250:     my $clientversion='0';
                   1251:     my $clientmathml='';
                   1252:     my $clientunicode='0';
                   1253:     for (my $i=0;$i<=$#browsertype;$i++) {
                   1254:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
                   1255: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   1256: 	    $clientbrowser=$bname;
                   1257:             $httpbrowser=~/$vreg/i;
                   1258: 	    $clientversion=$1;
                   1259:             $clientmathml=($clientversion>=$minv);
                   1260:             $clientunicode=($clientversion>=$univ);
                   1261: 	}
                   1262:     }
                   1263:     my $clientos='unknown';
                   1264:     if (($httpbrowser=~/linux/i) ||
                   1265:         ($httpbrowser=~/unix/i) ||
                   1266:         ($httpbrowser=~/ux/i) ||
                   1267:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   1268:     if (($httpbrowser=~/vax/i) ||
                   1269:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   1270:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   1271:     if (($httpbrowser=~/mac/i) ||
                   1272:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
                   1273:     if ($httpbrowser=~/win/i) { $clientos='win'; }
                   1274:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
                   1275:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
                   1276:             $clientunicode,$clientos,);
                   1277: }
                   1278: 
1.32      matthew  1279: ###############################################################
                   1280: ##    Authentication changing form generation subroutines    ##
                   1281: ###############################################################
                   1282: ##
                   1283: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   1284: ## hash, and have reasonable default values.
                   1285: ##
                   1286: ##    formname = the name given in the <form> tag.
1.35      matthew  1287: #-------------------------------------------
                   1288: 
1.45      matthew  1289: =pod
                   1290: 
1.112     bowersj2 1291: =head1 Authentication Routines
                   1292: 
                   1293: =over 4
                   1294: 
                   1295: =item * authform_xxxxxx
1.35      matthew  1296: 
                   1297: The authform_xxxxxx subroutines provide javascript and html forms which 
                   1298: handle some of the conveniences required for authentication forms.  
                   1299: This is not an optimal method, but it works.  
                   1300: 
                   1301: See loncreateuser.pm for invocation and use examples.
                   1302: 
                   1303: =over 4
                   1304: 
1.112     bowersj2 1305: =item * authform_header
1.35      matthew  1306: 
1.112     bowersj2 1307: =item * authform_authorwarning
1.35      matthew  1308: 
1.112     bowersj2 1309: =item * authform_nochange
1.35      matthew  1310: 
1.112     bowersj2 1311: =item * authform_kerberos
1.35      matthew  1312: 
1.112     bowersj2 1313: =item * authform_internal
1.35      matthew  1314: 
1.112     bowersj2 1315: =item * authform_filesystem
1.35      matthew  1316: 
                   1317: =back
                   1318: 
1.157     matthew  1319: =back 
                   1320: 
1.35      matthew  1321: =cut
                   1322: 
                   1323: #-------------------------------------------
1.32      matthew  1324: sub authform_header{  
                   1325:     my %in = (
                   1326:         formname => 'cu',
1.80      albertel 1327:         kerb_def_dom => '',
1.32      matthew  1328:         @_,
                   1329:     );
                   1330:     $in{'formname'} = 'document.' . $in{'formname'};
                   1331:     my $result='';
1.80      albertel 1332: 
                   1333: #---------------------------------------------- Code for upper case translation
                   1334:     my $Javascript_toUpperCase;
                   1335:     unless ($in{kerb_def_dom}) {
                   1336:         $Javascript_toUpperCase =<<"END";
                   1337:         switch (choice) {
                   1338:            case 'krb': currentform.elements[choicearg].value =
                   1339:                currentform.elements[choicearg].value.toUpperCase();
                   1340:                break;
                   1341:            default:
                   1342:         }
                   1343: END
                   1344:     } else {
                   1345:         $Javascript_toUpperCase = "";
                   1346:     }
                   1347: 
1.165     raeburn  1348:     my $radioval = "'nochange'";
1.174     matthew  1349:     if (exists($in{'curr_authtype'}) &&
                   1350:         defined($in{'curr_authtype'}) &&
                   1351:         $in{'curr_authtype'} ne '') {
                   1352:         $radioval = "'$in{'curr_authtype'}arg'";
                   1353:     }
1.165     raeburn  1354:     my $argfield = 'null';
                   1355:     if ( grep/^mode$/,(keys %in) ) {
                   1356:         if ($in{'mode'} eq 'modifycourse')  {
                   1357:             if ( grep/^curr_authtype$/,(keys %in) ) {
                   1358:                 $radioval = "'$in{'curr_authtype'}'";
                   1359:             }
                   1360:             if ( grep/^curr_autharg$/,(keys %in) ) {
                   1361:                 unless ($in{'curr_autharg'} eq '') {
                   1362:                     $argfield = "'$in{'curr_autharg'}'";
                   1363:                 }
                   1364:             }
                   1365:         }
                   1366:     }
                   1367: 
1.32      matthew  1368:     $result.=<<"END";
                   1369: var current = new Object();
1.165     raeburn  1370: current.radiovalue = $radioval;
                   1371: current.argfield = $argfield;
1.32      matthew  1372: 
                   1373: function changed_radio(choice,currentform) {
                   1374:     var choicearg = choice + 'arg';
                   1375:     // If a radio button in changed, we need to change the argfield
                   1376:     if (current.radiovalue != choice) {
                   1377:         current.radiovalue = choice;
                   1378:         if (current.argfield != null) {
                   1379:             currentform.elements[current.argfield].value = '';
                   1380:         }
                   1381:         if (choice == 'nochange') {
                   1382:             current.argfield = null;
                   1383:         } else {
                   1384:             current.argfield = choicearg;
                   1385:             switch(choice) {
                   1386:                 case 'krb': 
                   1387:                     currentform.elements[current.argfield].value = 
                   1388:                         "$in{'kerb_def_dom'}";
                   1389:                 break;
                   1390:               default:
                   1391:                 break;
                   1392:             }
                   1393:         }
                   1394:     }
                   1395:     return;
                   1396: }
1.22      www      1397: 
1.32      matthew  1398: function changed_text(choice,currentform) {
                   1399:     var choicearg = choice + 'arg';
                   1400:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 1401:         $Javascript_toUpperCase
1.32      matthew  1402:         // clear old field
                   1403:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   1404:             currentform.elements[current.argfield].value = '';
                   1405:         }
                   1406:         current.argfield = choicearg;
                   1407:     }
                   1408:     set_auth_radio_buttons(choice,currentform);
                   1409:     return;
1.20      www      1410: }
1.32      matthew  1411: 
                   1412: function set_auth_radio_buttons(newvalue,currentform) {
                   1413:     var i=0;
                   1414:     while (i < currentform.login.length) {
                   1415:         if (currentform.login[i].value == newvalue) { break; }
                   1416:         i++;
                   1417:     }
                   1418:     if (i == currentform.login.length) {
                   1419:         return;
                   1420:     }
                   1421:     current.radiovalue = newvalue;
                   1422:     currentform.login[i].checked = true;
                   1423:     return;
                   1424: }
                   1425: END
                   1426:     return $result;
                   1427: }
                   1428: 
                   1429: sub authform_authorwarning{
                   1430:     my $result='';
1.144     matthew  1431:     $result='<i>'.
                   1432:         &mt('As a general rule, only authors or co-authors should be '.
                   1433:             'filesystem authenticated '.
                   1434:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  1435:     return $result;
                   1436: }
                   1437: 
                   1438: sub authform_nochange{  
                   1439:     my %in = (
                   1440:               formname => 'document.cu',
                   1441:               kerb_def_dom => 'MSU.EDU',
                   1442:               @_,
                   1443:           );
1.144     matthew  1444:     my $result = &mt('[_1] Do not change login data',
                   1445:                      '<input type="radio" name="login" value="nochange" '.
                   1446:                      'checked="checked" onclick="'.
                   1447:             "javascript:changed_radio('nochange',$in{'formname'});".'" />');
1.32      matthew  1448:     return $result;
                   1449: }
                   1450: 
                   1451: sub authform_kerberos{  
                   1452:     my %in = (
                   1453:               formname => 'document.cu',
                   1454:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 1455:               kerb_def_auth => 'krb4',
1.32      matthew  1456:               @_,
                   1457:               );
1.165     raeburn  1458:     my ($check4,$check5,$krbarg);
1.80      albertel 1459:     if ($in{'kerb_def_auth'} eq 'krb5') {
                   1460:        $check5 = " checked=\"on\"";
                   1461:     } else {
                   1462:        $check4 = " checked=\"on\"";
                   1463:     }
1.165     raeburn  1464:     $krbarg = $in{'kerb_def_dom'};
                   1465: 
                   1466:     my $krbcheck = "";
                   1467:     if ( grep/^curr_authtype$/,(keys %in) ) {
                   1468:         if ($in{'curr_authtype'} =~ m/^krb/) {
                   1469:             $krbcheck = " checked=\"on\"";
                   1470:             if ( grep/^curr_autharg$/,(keys %in) ) {
                   1471:                 $krbarg = $in{'curr_autharg'};
                   1472:             }
                   1473:         }
                   1474:     }
                   1475: 
1.144     matthew  1476:     my $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   1477:     my $result .= &mt
                   1478:         ('[_1] Kerberos authenticated with domain [_2] '.
                   1479:          '[_3] Version 4 [_4] Version 5',
                   1480:          '<input type="radio" name="login" value="krb" '.
1.165     raeburn  1481:              'onclick="'.$jscall.'" onchange="'.$jscall.'"'.$krbcheck.' />',
1.144     matthew  1482:          '<input type="text" size="10" name="krbarg" '.
1.165     raeburn  1483:              'value="'.$krbarg.'" '.
1.144     matthew  1484:              'onchange="'.$jscall.'" />',
                   1485:          '<input type="radio" name="krbver" value="4" '.$check4.' />',
                   1486:          '<input type="radio" name="krbver" value="5" '.$check5.' />');
1.32      matthew  1487:     return $result;
                   1488: }
                   1489: 
                   1490: sub authform_internal{  
                   1491:     my %args = (
                   1492:                 formname => 'document.cu',
                   1493:                 kerb_def_dom => 'MSU.EDU',
                   1494:                 @_,
                   1495:                 );
1.165     raeburn  1496: 
                   1497:     my $intcheck = "";
                   1498:     my $intarg = 'value=""';
                   1499:     if ( grep/^curr_authtype$/,(keys %args) ) {
                   1500:         if ($args{'curr_authtype'} eq 'int') {
                   1501:             $intcheck = " checked=\"on\"";
                   1502:             if ( grep/^curr_autharg$/,(keys %args) ) {
                   1503:                 $intarg = "value=\"$args{'curr_autharg'}\"";
                   1504:             }
                   1505:         }
                   1506:     }
                   1507: 
1.144     matthew  1508:     my $jscall = "javascript:changed_radio('int',$args{'formname'});";
                   1509:     my $result.=&mt
                   1510:         ('[_1] Internally authenticated (with initial password [_2])',
1.165     raeburn  1511:          '<input type="radio" name="login" value="int" '.$intcheck.
                   1512:              ' onchange="'.$jscall.'" onclick="'.$jscall.'" />',
                   1513:          '<input type="text" size="10" name="intarg" '.$intarg.
                   1514:              ' onchange="'.$jscall.'" />');
1.32      matthew  1515:     return $result;
                   1516: }
                   1517: 
                   1518: sub authform_local{  
                   1519:     my %in = (
                   1520:               formname => 'document.cu',
                   1521:               kerb_def_dom => 'MSU.EDU',
                   1522:               @_,
                   1523:               );
1.165     raeburn  1524: 
                   1525:     my $loccheck = "";
                   1526:     my $locarg = 'value=""';
                   1527:     if ( grep/^curr_authtype$/,(keys %in) ) {
                   1528:         if ($in{'curr_authtype'} eq 'loc') {
                   1529:             $loccheck = " checked=\"on\"";
                   1530:             if ( grep/^curr_autharg$/,(keys %in) ) {
                   1531:                 $locarg = "value=\"$in{'curr_autharg'}\"";
                   1532:             }
                   1533:         }
                   1534:     }
                   1535: 
1.144     matthew  1536:     my $jscall = "javascript:changed_radio('loc',$in{'formname'});";
1.160     matthew  1537:     my $result.=&mt('[_1] Local Authentication with argument [_2]',
1.165     raeburn  1538:                     '<input type="radio" name="login" value="loc" '.$loccheck.
                   1539:                         ' onchange="'.$jscall.'" onclick="'.$jscall.'" />',
                   1540:                     '<input type="text" size="10" name="locarg" '.$locarg.
                   1541:                         ' onchange="'.$jscall.'" />');
1.32      matthew  1542:     return $result;
                   1543: }
                   1544: 
                   1545: sub authform_filesystem{  
                   1546:     my %in = (
                   1547:               formname => 'document.cu',
                   1548:               kerb_def_dom => 'MSU.EDU',
                   1549:               @_,
                   1550:               );
1.144     matthew  1551:     my $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   1552:     my $result.= &mt
                   1553:         ('[_1] Filesystem Authenticated (with initial password [_2])',
                   1554:          '<input type="radio" name="login" value="fsys" '.
                   1555:          'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
                   1556:          '<input type="text" size="10" name="fsysarg" value="" '.
                   1557:                   'onchange="'.$jscall.'" />');
1.32      matthew  1558:     return $result;
                   1559: }
                   1560: 
1.80      albertel 1561: ###############################################################
                   1562: ##    Get Authentication Defaults for Domain                 ##
                   1563: ###############################################################
                   1564: 
                   1565: =pod
                   1566: 
1.112     bowersj2 1567: =head1 Domains and Authentication
                   1568: 
                   1569: Returns default authentication type and an associated argument as
                   1570: listed in file 'domain.tab'.
                   1571: 
                   1572: =over 4
                   1573: 
                   1574: =item * get_auth_defaults
1.80      albertel 1575: 
                   1576: get_auth_defaults($target_domain) returns the default authentication
                   1577: type and an associated argument (initial password or a kerberos domain).
                   1578: These values are stored in lonTabs/domain.tab
                   1579: 
                   1580: ($def_auth, $def_arg) = &get_auth_defaults($target_domain);
                   1581: 
                   1582: If target_domain is not found in domain.tab, returns nothing ('').
                   1583: 
                   1584: =cut
                   1585: 
                   1586: #-------------------------------------------
                   1587: sub get_auth_defaults {
                   1588:     my $domain=shift;
                   1589:     return ($Apache::lonnet::domain_auth_def{$domain},$Apache::lonnet::domain_auth_arg_def{$domain});
                   1590: }
                   1591: ###############################################################
                   1592: ##   End Get Authentication Defaults for Domain              ##
                   1593: ###############################################################
                   1594: 
                   1595: ###############################################################
                   1596: ##    Get Kerberos Defaults for Domain                 ##
                   1597: ###############################################################
                   1598: ##
                   1599: ## Returns default kerberos version and an associated argument
                   1600: ## as listed in file domain.tab. If not listed, provides
                   1601: ## appropriate default domain and kerberos version.
                   1602: ##
                   1603: #-------------------------------------------
                   1604: 
                   1605: =pod
                   1606: 
1.112     bowersj2 1607: =item * get_kerberos_defaults
1.80      albertel 1608: 
                   1609: get_kerberos_defaults($target_domain) returns the default kerberos
                   1610: version and domain. If not found in domain.tabs, it defaults to
                   1611: version 4 and the domain of the server.
                   1612: 
                   1613: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   1614: 
                   1615: =cut
                   1616: 
                   1617: #-------------------------------------------
                   1618: sub get_kerberos_defaults {
                   1619:     my $domain=shift;
                   1620:     my ($krbdef,$krbdefdom) =
                   1621:         &Apache::loncommon::get_auth_defaults($domain);
                   1622:     unless ($krbdef =~/^krb/ && $krbdefdom) {
                   1623:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   1624:         my $krbdefdom=$1;
                   1625:         $krbdefdom=~tr/a-z/A-Z/;
                   1626:         $krbdef = "krb4";
                   1627:     }
                   1628:     return ($krbdef,$krbdefdom);
                   1629: }
1.112     bowersj2 1630: 
                   1631: =pod
                   1632: 
                   1633: =back
                   1634: 
                   1635: =cut
1.32      matthew  1636: 
1.46      matthew  1637: ###############################################################
                   1638: ##                Thesaurus Functions                        ##
                   1639: ###############################################################
1.20      www      1640: 
1.46      matthew  1641: =pod
1.20      www      1642: 
1.112     bowersj2 1643: =head1 Thesaurus Functions
                   1644: 
                   1645: =over 4
                   1646: 
                   1647: =item * initialize_keywords
1.46      matthew  1648: 
                   1649: Initializes the package variable %Keywords if it is empty.  Uses the
                   1650: package variable $thesaurus_db_file.
                   1651: 
                   1652: =cut
                   1653: 
                   1654: ###################################################
                   1655: 
                   1656: sub initialize_keywords {
                   1657:     return 1 if (scalar keys(%Keywords));
                   1658:     # If we are here, %Keywords is empty, so fill it up
                   1659:     #   Make sure the file we need exists...
                   1660:     if (! -e $thesaurus_db_file) {
                   1661:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   1662:                                  " failed because it does not exist");
                   1663:         return 0;
                   1664:     }
                   1665:     #   Set up the hash as a database
                   1666:     my %thesaurus_db;
                   1667:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 1668:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  1669:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   1670:                                  $thesaurus_db_file);
                   1671:         return 0;
                   1672:     } 
                   1673:     #  Get the average number of appearances of a word.
                   1674:     my $avecount = $thesaurus_db{'average.count'};
                   1675:     #  Put keywords (those that appear > average) into %Keywords
                   1676:     while (my ($word,$data)=each (%thesaurus_db)) {
                   1677:         my ($count,undef) = split /:/,$data;
                   1678:         $Keywords{$word}++ if ($count > $avecount);
                   1679:     }
                   1680:     untie %thesaurus_db;
                   1681:     # Remove special values from %Keywords.
                   1682:     foreach ('total.count','average.count') {
                   1683:         delete($Keywords{$_}) if (exists($Keywords{$_}));
                   1684:     }
                   1685:     return 1;
                   1686: }
                   1687: 
                   1688: ###################################################
                   1689: 
                   1690: =pod
                   1691: 
1.112     bowersj2 1692: =item * keyword($word)
1.46      matthew  1693: 
                   1694: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   1695: than the average number of times in the thesaurus database.  Calls 
                   1696: &initialize_keywords
                   1697: 
                   1698: =cut
                   1699: 
                   1700: ###################################################
1.20      www      1701: 
                   1702: sub keyword {
1.46      matthew  1703:     return if (!&initialize_keywords());
                   1704:     my $word=lc(shift());
                   1705:     $word=~s/\W//g;
                   1706:     return exists($Keywords{$word});
1.20      www      1707: }
1.46      matthew  1708: 
                   1709: ###############################################################
                   1710: 
                   1711: =pod 
1.20      www      1712: 
1.112     bowersj2 1713: =item * get_related_words
1.46      matthew  1714: 
1.160     matthew  1715: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  1716: an array of words.  If the keyword is not in the thesaurus, an empty array
                   1717: will be returned.  The order of the words returned is determined by the
                   1718: database which holds them.
                   1719: 
                   1720: Uses global $thesaurus_db_file.
                   1721: 
                   1722: =cut
                   1723: 
                   1724: ###############################################################
                   1725: sub get_related_words {
                   1726:     my $keyword = shift;
                   1727:     my %thesaurus_db;
                   1728:     if (! -e $thesaurus_db_file) {
                   1729:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   1730:                                  "failed because the file does not exist");
                   1731:         return ();
                   1732:     }
                   1733:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 1734:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  1735:         return ();
                   1736:     } 
                   1737:     my @Words=();
                   1738:     if (exists($thesaurus_db{$keyword})) {
                   1739:         $_ = $thesaurus_db{$keyword};
                   1740:         (undef,@Words) = split/:/;  # The first element is the number of times
                   1741:                                     # the word appears.  We do not need it now.
                   1742:         for (my $i=0;$i<=$#Words;$i++) {
                   1743:             ($Words[$i],undef)= split/\,/,$Words[$i];
1.20      www      1744:         }
                   1745:     }
1.46      matthew  1746:     untie %thesaurus_db;
                   1747:     return @Words;
1.14      harris41 1748: }
1.46      matthew  1749: 
1.112     bowersj2 1750: =pod
                   1751: 
                   1752: =back
                   1753: 
                   1754: =cut
1.61      www      1755: 
                   1756: # -------------------------------------------------------------- Plaintext name
1.81      albertel 1757: =pod
                   1758: 
1.112     bowersj2 1759: =head1 User Name Functions
                   1760: 
                   1761: =over 4
                   1762: 
1.226     albertel 1763: =item * plainname($uname,$udom,$first)
1.81      albertel 1764: 
1.112     bowersj2 1765: Takes a users logon name and returns it as a string in
1.226     albertel 1766: "first middle last generation" form 
                   1767: if $first is set to 'lastname' then it returns it as
                   1768: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 1769: 
                   1770: =cut
1.61      www      1771: 
1.81      albertel 1772: ###############################################################
1.61      www      1773: sub plainname {
1.226     albertel 1774:     my ($uname,$udom,$first)=@_;
1.61      www      1775:     my %names=&Apache::lonnet::get('environment',
                   1776:                     ['firstname','middlename','lastname','generation'],
                   1777: 					 $udom,$uname);
1.226     albertel 1778:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   1779: 					  $names{'middlename'},
                   1780: 					  $names{'lastname'},
                   1781: 					  $names{'generation'},$first);
                   1782:     $name=~s/^\s+//;
1.62      www      1783:     $name=~s/\s+$//;
                   1784:     $name=~s/\s+/ /g;
1.190     albertel 1785:     if ($name !~ /\S/) { $name=$uname.'@'.$udom; }
1.62      www      1786:     return $name;
1.61      www      1787: }
1.66      www      1788: 
                   1789: # -------------------------------------------------------------------- Nickname
1.81      albertel 1790: =pod
                   1791: 
1.112     bowersj2 1792: =item * nickname($uname,$udom)
1.81      albertel 1793: 
                   1794: Gets a users name and returns it as a string as
                   1795: 
                   1796: "&quot;nickname&quot;"
1.66      www      1797: 
1.81      albertel 1798: if the user has a nickname or
                   1799: 
                   1800: "first middle last generation"
                   1801: 
                   1802: if the user does not
                   1803: 
                   1804: =cut
1.66      www      1805: 
                   1806: sub nickname {
                   1807:     my ($uname,$udom)=@_;
1.212     albertel 1808:     my %names;
                   1809:     if ($uname eq $ENV{'user.name'} &&
                   1810: 	$udom eq $ENV{'user.domain'}) {
                   1811: 	%names=('nickname'   => $ENV{'environment.nickname'}  ,
                   1812: 		'firstname'  => $ENV{'environment.firstname'} ,
                   1813: 		'middlename' => $ENV{'environment.middlename'},
                   1814: 		'lastname'   => $ENV{'environment.lastname'}  ,
                   1815: 		'generation' => $ENV{'environment.generation'});
                   1816:     } else {
                   1817: 	%names=&Apache::lonnet::get('environment',
                   1818: 				    ['nickname','firstname','middlename',
                   1819: 				     'lastname','generation'],$udom,$uname);
                   1820:     }
1.68      albertel 1821:     my $name=$names{'nickname'};
1.66      www      1822:     if ($name) {
                   1823:        $name='&quot;'.$name.'&quot;'; 
                   1824:     } else {
                   1825:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   1826: 	     $names{'lastname'}.' '.$names{'generation'};
                   1827:        $name=~s/\s+$//;
                   1828:        $name=~s/\s+/ /g;
                   1829:     }
                   1830:     return $name;
                   1831: }
                   1832: 
1.61      www      1833: 
                   1834: # ------------------------------------------------------------------ Screenname
1.81      albertel 1835: 
                   1836: =pod
                   1837: 
1.112     bowersj2 1838: =item * screenname($uname,$udom)
1.81      albertel 1839: 
                   1840: Gets a users screenname and returns it as a string
                   1841: 
                   1842: =cut
1.61      www      1843: 
                   1844: sub screenname {
                   1845:     my ($uname,$udom)=@_;
1.212     albertel 1846:     if ($uname eq $ENV{'user.name'} &&
                   1847: 	$udom eq $ENV{'user.domain'}) {return $ENV{'environment.screenname'};}
                   1848:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 1849:     return $names{'screenname'};
1.62      www      1850: }
                   1851: 
1.212     albertel 1852: 
1.62      www      1853: # ------------------------------------------------------------- Message Wrapper
                   1854: 
                   1855: sub messagewrapper {
1.200     matthew  1856:     my ($link,$username,$domain)=@_;
1.62      www      1857:     return 
1.200     matthew  1858:         '<a href="/adm/email?compose=individual&'.
                   1859:         'recname='.$username.'&recdom='.$domain.'" '.
                   1860:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      1861: }
                   1862: # --------------------------------------------------------------- Notes Wrapper
                   1863: 
                   1864: sub noteswrapper {
                   1865:     my ($link,$un,$do)=@_;
                   1866:     return 
                   1867: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
1.62      www      1868: }
                   1869: # ------------------------------------------------------------- Aboutme Wrapper
                   1870: 
                   1871: sub aboutmewrapper {
1.166     www      1872:     my ($link,$username,$domain,$target)=@_;
1.205     www      1873:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.200     matthew  1874: 	($target?' target="$target"':'').' title="'.&mt('View this users personal page').'">'.$link.'</a>';
1.62      www      1875: }
                   1876: 
                   1877: # ------------------------------------------------------------ Syllabus Wrapper
                   1878: 
                   1879: 
                   1880: sub syllabuswrapper {
1.109     matthew  1881:     my ($linktext,$coursedir,$domain,$fontcolor)=@_;
                   1882:     if ($fontcolor) { 
                   1883:         $linktext='<font color="'.$fontcolor.'">'.$linktext.'</font>'; 
                   1884:     }
1.208     matthew  1885:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      1886: }
1.14      harris41 1887: 
1.208     matthew  1888: sub track_student_link {
                   1889:     my ($linktext,$sname,$sdom,$target) = @_;
                   1890:     my $link ="/adm/trackstudent";
                   1891:     my $title = 'View recent activity';
                   1892:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   1893:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   1894:         $link .= "?selected_student=$sname:$sdom";
                   1895:         $title .= ' of this student';
                   1896:     }
                   1897:     if (defined($target) && $target !~ /^\s*$/) {
                   1898:         $target = qq{target="$target"};
                   1899:     } else {
                   1900:         $target = '';
                   1901:     }
                   1902:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   1903: }
                   1904: 
                   1905: 
                   1906: 
1.112     bowersj2 1907: =pod
                   1908: 
                   1909: =back
                   1910: 
                   1911: =head1 Access .tab File Data
                   1912: 
                   1913: =over 4
                   1914: 
                   1915: =item * languageids() 
                   1916: 
                   1917: returns list of all language ids
                   1918: 
                   1919: =cut
                   1920: 
1.14      harris41 1921: sub languageids {
1.16      harris41 1922:     return sort(keys(%language));
1.14      harris41 1923: }
                   1924: 
1.112     bowersj2 1925: =pod
                   1926: 
                   1927: =item * languagedescription() 
                   1928: 
                   1929: returns description of a specified language id
                   1930: 
                   1931: =cut
                   1932: 
1.14      harris41 1933: sub languagedescription {
1.125     www      1934:     my $code=shift;
                   1935:     return  ($supported_language{$code}?'* ':'').
                   1936:             $language{$code}.
1.126     www      1937: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      1938: }
                   1939: 
                   1940: sub plainlanguagedescription {
                   1941:     my $code=shift;
                   1942:     return $language{$code};
                   1943: }
                   1944: 
                   1945: sub supportedlanguagecode {
                   1946:     my $code=shift;
                   1947:     return $supported_language{$code};
1.97      www      1948: }
                   1949: 
1.112     bowersj2 1950: =pod
                   1951: 
                   1952: =item * copyrightids() 
                   1953: 
                   1954: returns list of all copyrights
                   1955: 
                   1956: =cut
                   1957: 
                   1958: sub copyrightids {
                   1959:     return sort(keys(%cprtag));
                   1960: }
                   1961: 
                   1962: =pod
                   1963: 
                   1964: =item * copyrightdescription() 
                   1965: 
                   1966: returns description of a specified copyright id
                   1967: 
                   1968: =cut
                   1969: 
                   1970: sub copyrightdescription {
1.166     www      1971:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 1972: }
1.197     matthew  1973: 
                   1974: =pod
                   1975: 
1.192     taceyjo1 1976: =item * source_copyrightids() 
                   1977: 
                   1978: returns list of all source copyrights
                   1979: 
                   1980: =cut
                   1981: 
                   1982: sub source_copyrightids {
                   1983:     return sort(keys(%scprtag));
                   1984: }
                   1985: 
                   1986: =pod
                   1987: 
                   1988: =item * source_copyrightdescription() 
                   1989: 
                   1990: returns description of a specified source copyright id
                   1991: 
                   1992: =cut
                   1993: 
                   1994: sub source_copyrightdescription {
                   1995:     return &mt($scprtag{shift(@_)});
                   1996: }
1.112     bowersj2 1997: 
                   1998: =pod
                   1999: 
                   2000: =item * filecategories() 
                   2001: 
                   2002: returns list of all file categories
                   2003: 
                   2004: =cut
                   2005: 
                   2006: sub filecategories {
                   2007:     return sort(keys(%category_extensions));
                   2008: }
                   2009: 
                   2010: =pod
                   2011: 
                   2012: =item * filecategorytypes() 
                   2013: 
                   2014: returns list of file types belonging to a given file
                   2015: category
                   2016: 
                   2017: =cut
                   2018: 
                   2019: sub filecategorytypes {
                   2020:     return @{$category_extensions{lc($_[0])}};
                   2021: }
                   2022: 
                   2023: =pod
                   2024: 
                   2025: =item * fileembstyle() 
                   2026: 
                   2027: returns embedding style for a specified file type
                   2028: 
                   2029: =cut
                   2030: 
                   2031: sub fileembstyle {
                   2032:     return $fe{lc(shift(@_))};
1.169     www      2033: }
                   2034: 
                   2035: 
                   2036: sub filecategoryselect {
                   2037:     my ($name,$value)=@_;
1.189     matthew  2038:     return &select_form($value,$name,
1.169     www      2039: 			'' => &mt('Any category'),
                   2040: 			map { $_,$_ } sort(keys(%category_extensions)));
1.112     bowersj2 2041: }
                   2042: 
                   2043: =pod
                   2044: 
                   2045: =item * filedescription() 
                   2046: 
                   2047: returns description for a specified file type
                   2048: 
                   2049: =cut
                   2050: 
                   2051: sub filedescription {
1.188     matthew  2052:     my $file_description = $fd{lc(shift())};
                   2053:     $file_description =~ s:([\[\]]):~$1:g;
                   2054:     return &mt($file_description);
1.112     bowersj2 2055: }
                   2056: 
                   2057: =pod
                   2058: 
                   2059: =item * filedescriptionex() 
                   2060: 
                   2061: returns description for a specified file type with
                   2062: extra formatting
                   2063: 
                   2064: =cut
                   2065: 
                   2066: sub filedescriptionex {
                   2067:     my $ex=shift;
1.188     matthew  2068:     my $file_description = $fd{lc($ex)};
                   2069:     $file_description =~ s:([\[\]]):~$1:g;
                   2070:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 2071: }
                   2072: 
                   2073: # End of .tab access
                   2074: =pod
                   2075: 
                   2076: =back
                   2077: 
                   2078: =cut
                   2079: 
                   2080: # ------------------------------------------------------------------ File Types
                   2081: sub fileextensions {
                   2082:     return sort(keys(%fe));
                   2083: }
                   2084: 
1.97      www      2085: # ----------------------------------------------------------- Display Languages
                   2086: # returns a hash with all desired display languages
                   2087: #
                   2088: 
                   2089: sub display_languages {
                   2090:     my %languages=();
1.118     www      2091:     foreach (&preferred_languages()) {
                   2092: 	$languages{$_}=1;
1.97      www      2093:     }
                   2094:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
                   2095:     if ($ENV{'form.displaylanguage'}) {
                   2096: 	foreach (split(/\s*(\,|\;|\:)\s*/,$ENV{'form.displaylanguage'})) {
                   2097: 	    $languages{$_}=1;
                   2098:         }
                   2099:     }
                   2100:     return %languages;
1.14      harris41 2101: }
                   2102: 
1.117     www      2103: sub preferred_languages {
                   2104:     my @languages=();
                   2105:     if ($ENV{'course.'.$ENV{'request.course.id'}.'.languages'}) {
                   2106: 	@languages=(@languages,split(/\s*(\,|\;|\:)\s*/,
                   2107: 	         $ENV{'course.'.$ENV{'request.course.id'}.'.languages'}));
1.177     www      2108:     }
                   2109:     if ($ENV{'environment.languages'}) {
                   2110: 	@languages=split(/\s*(\,|\;|\:)\s*/,$ENV{'environment.languages'});
1.118     www      2111:     }
1.162     www      2112:     my $browser=(split(/\;/,$ENV{'HTTP_ACCEPT_LANGUAGE'}))[0];
                   2113:     if ($browser) {
                   2114: 	@languages=(@languages,split(/\s*(\,|\;|\:)\s*/,$browser));
                   2115:     }
1.118     www      2116:     if ($Apache::lonnet::domain_lang_def{$ENV{'user.domain'}}) {
                   2117: 	@languages=(@languages,
                   2118: 		$Apache::lonnet::domain_lang_def{$ENV{'user.domain'}});
                   2119:     }
                   2120:     if ($Apache::lonnet::domain_lang_def{$ENV{'request.role.domain'}}) {
                   2121: 	@languages=(@languages,
                   2122: 		$Apache::lonnet::domain_lang_def{$ENV{'request.role.domain'}});
                   2123:     }
                   2124:     if ($Apache::lonnet::domain_lang_def{
                   2125: 	                          $Apache::lonnet::perlvar{'lonDefDomain'}}) {
                   2126: 	@languages=(@languages,
                   2127: 		$Apache::lonnet::domain_lang_def{
                   2128:                                   $Apache::lonnet::perlvar{'lonDefDomain'}});
                   2129:     }
                   2130: # turn "en-ca" into "en-ca,en"
                   2131:     my @genlanguages;
                   2132:     foreach (@languages) {
                   2133: 	unless ($_=~/\w/) { next; }
                   2134: 	push (@genlanguages,$_);
                   2135: 	if ($_=~/(\-|\_)/) {
                   2136: 	    push (@genlanguages,(split(/(\-|\_)/,$_))[0]);
                   2137: 	}
                   2138:     }
                   2139:     return @genlanguages;
1.117     www      2140: }
                   2141: 
1.112     bowersj2 2142: ###############################################################
                   2143: ##               Student Answer Attempts                     ##
                   2144: ###############################################################
                   2145: 
                   2146: =pod
                   2147: 
                   2148: =head1 Alternate Problem Views
                   2149: 
                   2150: =over 4
                   2151: 
                   2152: =item * get_previous_attempt($symb, $username, $domain, $course,
                   2153:     $getattempt, $regexp, $gradesub)
                   2154: 
                   2155: Return string with previous attempt on problem. Arguments:
                   2156: 
                   2157: =over 4
                   2158: 
                   2159: =item * $symb: Problem, including path
                   2160: 
                   2161: =item * $username: username of the desired student
                   2162: 
                   2163: =item * $domain: domain of the desired student
1.14      harris41 2164: 
1.112     bowersj2 2165: =item * $course: Course ID
1.14      harris41 2166: 
1.112     bowersj2 2167: =item * $getattempt: Leave blank for all attempts, otherwise put
                   2168:     something
1.14      harris41 2169: 
1.112     bowersj2 2170: =item * $regexp: if string matches this regexp, the string will be
                   2171:     sent to $gradesub
1.14      harris41 2172: 
1.112     bowersj2 2173: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 2174: 
1.112     bowersj2 2175: =back
1.14      harris41 2176: 
1.112     bowersj2 2177: The output string is a table containing all desired attempts, if any.
1.16      harris41 2178: 
1.112     bowersj2 2179: =cut
1.1       albertel 2180: 
                   2181: sub get_previous_attempt {
1.43      ng       2182:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
1.1       albertel 2183:   my $prevattempts='';
1.43      ng       2184:   no strict 'refs';
1.1       albertel 2185:   if ($symb) {
1.3       albertel 2186:     my (%returnhash)=
                   2187:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 2188:     if ($returnhash{'version'}) {
                   2189:       my %lasthash=();
                   2190:       my $version;
                   2191:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.19      harris41 2192:         foreach (sort(split(/\:/,$returnhash{$version.':keys'}))) {
1.1       albertel 2193: 	  $lasthash{$_}=$returnhash{$version.':'.$_};
1.19      harris41 2194:         }
1.1       albertel 2195:       }
1.43      ng       2196:       $prevattempts='<table border="0" width="100%"><tr><td bgcolor="#777777">';
1.40      ng       2197:       $prevattempts.='<table border="0" width="100%"><tr bgcolor="#e6ffff"><td>History</td>';
1.16      harris41 2198:       foreach (sort(keys %lasthash)) {
1.31      albertel 2199: 	my ($ign,@parts) = split(/\./,$_);
1.41      ng       2200: 	if ($#parts > 0) {
1.31      albertel 2201: 	  my $data=$parts[-1];
                   2202: 	  pop(@parts);
1.40      ng       2203: 	  $prevattempts.='<td>Part '.join('.',@parts).'<br />'.$data.'&nbsp;</td>';
1.31      albertel 2204: 	} else {
1.41      ng       2205: 	  if ($#parts == 0) {
                   2206: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   2207: 	  } else {
                   2208: 	    $prevattempts.='<th>'.$ign.'</th>';
                   2209: 	  }
1.31      albertel 2210: 	}
1.16      harris41 2211:       }
1.40      ng       2212:       if ($getattempt eq '') {
                   2213: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
                   2214: 	  $prevattempts.='</tr><tr bgcolor="#ffffe6"><td>Transaction '.$version.'</td>';
                   2215: 	    foreach (sort(keys %lasthash)) {
                   2216: 	       my $value;
                   2217: 	       if ($_ =~ /timestamp/) {
                   2218: 		  $value=scalar(localtime($returnhash{$version.':'.$_}));
                   2219: 	       } else {
                   2220: 		  $value=$returnhash{$version.':'.$_};
                   2221: 	       }
1.142     albertel 2222: 	       $prevattempts.='<td>'.&Apache::lonnet::unescape($value).'&nbsp;</td>';   
1.40      ng       2223: 	    }
                   2224: 	 }
1.1       albertel 2225:       }
1.40      ng       2226:       $prevattempts.='</tr><tr bgcolor="#ffffe6"><td>Current</td>';
1.16      harris41 2227:       foreach (sort(keys %lasthash)) {
1.5       albertel 2228: 	my $value;
                   2229: 	if ($_ =~ /timestamp/) {
                   2230: 	  $value=scalar(localtime($lasthash{$_}));
                   2231: 	} else {
                   2232: 	  $value=$lasthash{$_};
                   2233: 	}
1.142     albertel 2234: 	$value=&Apache::lonnet::unescape($value);
1.49      ng       2235: 	if ($_ =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
1.40      ng       2236: 	$prevattempts.='<td>'.$value.'&nbsp;</td>';
1.16      harris41 2237:       }
1.40      ng       2238:       $prevattempts.='</tr></table></td></tr></table>';
1.1       albertel 2239:     } else {
                   2240:       $prevattempts='Nothing submitted - no attempts.';
                   2241:     }
                   2242:   } else {
                   2243:     $prevattempts='No data.';
                   2244:   }
1.10      albertel 2245: }
                   2246: 
1.107     albertel 2247: sub relative_to_absolute {
                   2248:     my ($url,$output)=@_;
                   2249:     my $parser=HTML::TokeParser->new(\$output);
                   2250:     my $token;
                   2251:     my $thisdir=$url;
                   2252:     my @rlinks=();
                   2253:     while ($token=$parser->get_token) {
                   2254: 	if ($token->[0] eq 'S') {
                   2255: 	    if ($token->[1] eq 'a') {
                   2256: 		if ($token->[2]->{'href'}) {
                   2257: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   2258: 		}
                   2259: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   2260: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   2261: 	    } elsif ($token->[1] eq 'base') {
                   2262: 		$thisdir=$token->[2]->{'href'};
                   2263: 	    }
                   2264: 	}
                   2265:     }
                   2266:     $thisdir=~s-/[^/]*$--;
                   2267:     foreach (@rlinks) {
                   2268: 	unless (($_=~/^http:\/\//i) ||
                   2269: 		($_=~/^\//) ||
                   2270: 		($_=~/^javascript:/i) ||
                   2271: 		($_=~/^mailto:/i) ||
                   2272: 		($_=~/^\#/)) {
                   2273: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$_);
                   2274: 	    $output=~s/(\"|\'|\=\s*)$_(\"|\'|\s|\>)/$1$newlocation$2/;
                   2275: 	}
                   2276:     }
                   2277: # -------------------------------------------------- Deal with Applet codebases
                   2278:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   2279:     return $output;
                   2280: }
                   2281: 
1.112     bowersj2 2282: =pod
                   2283: 
                   2284: =item * get_student_view
                   2285: 
                   2286: show a snapshot of what student was looking at
                   2287: 
                   2288: =cut
                   2289: 
1.10      albertel 2290: sub get_student_view {
1.186     albertel 2291:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      2292:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 2293:   my (%form);
1.10      albertel 2294:   my @elements=('symb','courseid','domain','username');
                   2295:   foreach my $element (@elements) {
1.186     albertel 2296:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 2297:   }
1.186     albertel 2298:   if (defined($moreenv)) {
                   2299:       %form=(%form,%{$moreenv});
                   2300:   }
1.236     albertel 2301:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 2302:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.186     albertel 2303:   my $userview=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 2304:   $userview=~s/\<body[^\>]*\>//gi;
                   2305:   $userview=~s/\<\/body\>//gi;
                   2306:   $userview=~s/\<html\>//gi;
                   2307:   $userview=~s/\<\/html\>//gi;
                   2308:   $userview=~s/\<head\>//gi;
                   2309:   $userview=~s/\<\/head\>//gi;
                   2310:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 2311:   $userview=&relative_to_absolute($feedurl,$userview);
1.11      albertel 2312:   return $userview;
                   2313: }
                   2314: 
1.112     bowersj2 2315: =pod
                   2316: 
                   2317: =item * get_student_answers() 
                   2318: 
                   2319: show a snapshot of how student was answering problem
                   2320: 
                   2321: =cut
                   2322: 
1.11      albertel 2323: sub get_student_answers {
1.100     sakharuk 2324:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      2325:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 2326:   my (%moreenv);
1.11      albertel 2327:   my @elements=('symb','courseid','domain','username');
                   2328:   foreach my $element (@elements) {
1.186     albertel 2329:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 2330:   }
1.186     albertel 2331:   $moreenv{'grade_target'}='answer';
                   2332:   %moreenv=(%form,%moreenv);
                   2333:   my $userview=&Apache::lonnet::ssi('/res/'.$feedurl,%moreenv);
1.10      albertel 2334:   return $userview;
1.1       albertel 2335: }
1.116     albertel 2336: 
                   2337: =pod
                   2338: 
                   2339: =item * &submlink()
                   2340: 
1.242     albertel 2341: Inputs: $text $uname $udom $symb $target
1.116     albertel 2342: 
                   2343: Returns: A link to grades.pm such as to see the SUBM view of a student
                   2344: 
                   2345: =cut
                   2346: 
                   2347: ###############################################
                   2348: sub submlink {
1.242     albertel 2349:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 2350:     if (!($uname && $udom)) {
                   2351: 	(my $cursymb, my $courseid,$udom,$uname)=
                   2352: 	    &Apache::lonxml::whichuser($symb);
                   2353: 	if (!$symb) { $symb=$cursymb; }
                   2354:     }
                   2355:     if (!$symb) { $symb=&symbread(); }
1.242     albertel 2356:     $symb=&Apache::lonnet::escape($symb);
                   2357:     if ($target) { $target="target=\"$target\""; }
                   2358:     return '<a href="/adm/grades?&command=submission&'.
                   2359: 	'symb='.$symb.'&student='.$uname.
                   2360: 	'&userdom='.$udom.'" '.$target.'>'.$text.'</a>';
                   2361: }
                   2362: ##############################################
                   2363: 
                   2364: =pod
                   2365: 
                   2366: =item * &pgrdlink()
                   2367: 
                   2368: Inputs: $text $uname $udom $symb $target
                   2369: 
                   2370: Returns: A link to grades.pm such as to see the PGRD view of a student
                   2371: 
                   2372: =cut
                   2373: 
                   2374: ###############################################
                   2375: sub pgrdlink {
                   2376:     my $link=&submlink(@_);
                   2377:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   2378:     return $link;
                   2379: }
                   2380: ##############################################
                   2381: 
                   2382: =pod
                   2383: 
                   2384: =item * &pprmlink()
                   2385: 
                   2386: Inputs: $text $uname $udom $symb $target
                   2387: 
                   2388: Returns: A link to parmset.pm such as to see the PPRM view of a
                   2389: student andn resource
                   2390: 
                   2391: =cut
                   2392: 
                   2393: ###############################################
                   2394: sub pprmlink {
                   2395:     my ($text,$uname,$udom,$symb,$target)=@_;
                   2396:     if (!($uname && $udom)) {
                   2397: 	(my $cursymb, my $courseid,$udom,$uname)=
                   2398: 	    &Apache::lonxml::whichuser($symb);
                   2399: 	if (!$symb) { $symb=$cursymb; }
                   2400:     }
                   2401:     if (!$symb) { $symb=&symbread(); }
                   2402:     $symb=&Apache::lonnet::escape($symb);
                   2403:     if ($target) { $target="target=\"$target\""; }
                   2404:     return '<a href="/adm/parmset?&command=set&'.
                   2405: 	'symb='.$symb.'&uname='.$uname.
                   2406: 	'&udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 2407: }
                   2408: ##############################################
1.37      matthew  2409: 
1.112     bowersj2 2410: =pod
                   2411: 
                   2412: =back
                   2413: 
                   2414: =cut
                   2415: 
1.37      matthew  2416: ###############################################
1.51      www      2417: 
                   2418: 
                   2419: sub timehash {
                   2420:     my @ltime=localtime(shift);
                   2421:     return ( 'seconds' => $ltime[0],
                   2422:              'minutes' => $ltime[1],
                   2423:              'hours'   => $ltime[2],
                   2424:              'day'     => $ltime[3],
                   2425:              'month'   => $ltime[4]+1,
                   2426:              'year'    => $ltime[5]+1900,
                   2427:              'weekday' => $ltime[6],
                   2428:              'dayyear' => $ltime[7]+1,
                   2429:              'dlsav'   => $ltime[8] );
                   2430: }
                   2431: 
                   2432: sub maketime {
                   2433:     my %th=@_;
                   2434:     return POSIX::mktime(
                   2435:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      2436:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      2437: }
                   2438: 
                   2439: #########################################
1.51      www      2440: 
                   2441: sub findallcourses {
                   2442:     my %courses=();
                   2443:     my $now=time;
                   2444:     foreach (keys %ENV) {
                   2445: 	if ($_=~/^user\.role\.\w+\.\/(\w+)\/(\w+)/) {
                   2446: 	    my ($starttime,$endtime)=$ENV{$_};
                   2447:             my $active=1;
                   2448:             if ($starttime) {
                   2449: 		if ($now<$starttime) { $active=0; }
                   2450:             }
                   2451:             if ($endtime) {
                   2452:                 if ($now>$endtime) { $active=0; }
                   2453:             }
                   2454:             if ($active) { $courses{$1.'_'.$2}=1; }
                   2455:         }
                   2456:     }
                   2457:     return keys %courses;
                   2458: }
1.37      matthew  2459: 
1.54      www      2460: ###############################################
1.60      matthew  2461: ###############################################
                   2462: 
                   2463: =pod
                   2464: 
1.112     bowersj2 2465: =head1 Domain Template Functions
                   2466: 
                   2467: =over 4
                   2468: 
                   2469: =item * &determinedomain()
1.60      matthew  2470: 
                   2471: Inputs: $domain (usually will be undef)
                   2472: 
1.63      www      2473: Returns: Determines which domain should be used for designs
1.60      matthew  2474: 
                   2475: =cut
1.54      www      2476: 
1.60      matthew  2477: ###############################################
1.63      www      2478: sub determinedomain {
                   2479:     my $domain=shift;
                   2480:    if (! $domain) {
1.60      matthew  2481:         # Determine domain if we have not been given one
                   2482:         $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
                   2483:         if ($ENV{'user.domain'}) { $domain=$ENV{'user.domain'}; }
                   2484:         if ($ENV{'request.role.domain'}) { 
                   2485:             $domain=$ENV{'request.role.domain'}; 
                   2486:         }
                   2487:     }
1.63      www      2488:     return $domain;
                   2489: }
                   2490: ###############################################
                   2491: =pod
                   2492: 
1.112     bowersj2 2493: =item * &domainlogo()
1.63      www      2494: 
                   2495: Inputs: $domain (usually will be undef)
                   2496: 
                   2497: Returns: A link to a domain logo, if the domain logo exists.
                   2498: If the domain logo does not exist, a description of the domain.
                   2499: 
                   2500: =cut
1.112     bowersj2 2501: 
1.63      www      2502: ###############################################
                   2503: sub domainlogo {
                   2504:     my $domain = &determinedomain(shift);    
                   2505:      # See if there is a logo
1.59      www      2506:     if (-e '/home/httpd/html/adm/lonDomLogos/'.$domain.'.gif') {
1.215     albertel 2507: 	my $logo=&lonhttpdurl("/adm/lonDomLogos/$domain.gif");
                   2508:         return '<img src="'.$logo.'" alt="'.$domain.'" />';
1.60      matthew  2509:     } elsif(exists($Apache::lonnet::domaindescription{$domain})) {
                   2510:         return $Apache::lonnet::domaindescription{$domain};
1.59      www      2511:     } else {
1.60      matthew  2512:         return '';
1.59      www      2513:     }
                   2514: }
1.63      www      2515: ##############################################
                   2516: 
                   2517: =pod
                   2518: 
1.112     bowersj2 2519: =item * &designparm()
1.63      www      2520: 
                   2521: Inputs: $which parameter; $domain (usually will be undef)
                   2522: 
                   2523: Returns: value of designparamter $which
                   2524: 
                   2525: =cut
1.112     bowersj2 2526: 
1.63      www      2527: ##############################################
                   2528: sub designparm {
                   2529:     my ($which,$domain)=@_;
1.110     www      2530:     if ($ENV{'browser.blackwhite'} eq 'on') {
                   2531: 	if ($which=~/\.(font|alink|vlink|link)$/) {
                   2532: 	    return '#000000';
                   2533: 	}
                   2534: 	if ($which=~/\.(pgbg|sidebg)$/) {
                   2535: 	    return '#FFFFFF';
                   2536: 	}
                   2537: 	if ($which=~/\.tabbg$/) {
                   2538: 	    return '#CCCCCC';
                   2539: 	}
                   2540:     }
1.96      www      2541:     if ($ENV{'environment.color.'.$which}) {
                   2542: 	return $ENV{'environment.color.'.$which};
                   2543:     }
1.63      www      2544:     $domain=&determinedomain($domain);
                   2545:     if ($designhash{$domain.'.'.$which}) {
                   2546: 	return $designhash{$domain.'.'.$which};
                   2547:     } else {
                   2548:         return $designhash{'default.'.$which};
                   2549:     }
                   2550: }
1.59      www      2551: 
1.60      matthew  2552: ###############################################
                   2553: ###############################################
                   2554: 
                   2555: =pod
                   2556: 
1.112     bowersj2 2557: =back
                   2558: 
                   2559: =head1 HTTP Helpers
                   2560: 
                   2561: =over 4
                   2562: 
                   2563: =item * &bodytag()
1.60      matthew  2564: 
                   2565: Returns a uniform header for LON-CAPA web pages.
                   2566: 
                   2567: Inputs: 
                   2568: 
1.112     bowersj2 2569: =over 4
                   2570: 
                   2571: =item * $title, A title to be displayed on the page.
                   2572: 
                   2573: =item * $function, the current role (can be undef).
                   2574: 
                   2575: =item * $addentries, extra parameters for the <body> tag.
                   2576: 
                   2577: =item * $bodyonly, if defined, only return the <body> tag.
                   2578: 
                   2579: =item * $domain, if defined, force a given domain.
                   2580: 
                   2581: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      2582:             text interface only)
1.60      matthew  2583: 
1.112     bowersj2 2584: =back
                   2585: 
1.60      matthew  2586: Returns: A uniform header for LON-CAPA web pages.  
                   2587: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   2588: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   2589: other decorations will be returned.
                   2590: 
                   2591: =cut
                   2592: 
1.54      www      2593: sub bodytag {
1.224     raeburn  2594:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,$customtitle)=@_;
1.117     www      2595:     $title=&mt($title);
1.183     matthew  2596:     $function = &get_users_function() if (!$function);
1.63      www      2597:     my $img=&designparm($function.'.img',$domain);
                   2598:     my $pgbg=&designparm($function.'.pgbg',$domain);
                   2599:     my $tabbg=&designparm($function.'.tabbg',$domain);
                   2600:     my $font=&designparm($function.'.font',$domain);
                   2601:     my $link=&designparm($function.'.link',$domain);
                   2602:     my $alink=&designparm($function.'.alink',$domain);
                   2603:     my $vlink=&designparm($function.'.vlink',$domain);
                   2604:     my $sidebg=&designparm($function.'.sidebg',$domain);
1.110     www      2605: # Accessibility font enhance
                   2606:     unless ($addentries) { $addentries=''; }
1.146     www      2607:     my $addstyle='';
1.110     www      2608:     if ($ENV{'browser.fontenhance'} eq 'on') {
1.146     www      2609: 	$addstyle=' font-size: x-large;';
1.110     www      2610:     }
1.63      www      2611:  # role and realm
1.55      www      2612:     my ($role,$realm)
                   2613:        =&Apache::lonnet::plaintext((split(/\./,$ENV{'request.role'}))[0]);
                   2614: # realm
1.54      www      2615:     if ($ENV{'request.course.id'}) {
1.55      www      2616: 	$realm=
                   2617:          $ENV{'course.'.$ENV{'request.course.id'}.'.description'};
1.54      www      2618:     }
1.55      www      2619:     unless ($realm) { $realm='&nbsp;'; }
                   2620: # Set messages
1.60      matthew  2621:     my $messages=&domainlogo($domain);
1.101     www      2622: # Port for miniserver
1.83      albertel 2623:     my $lonhttpdPort=$Apache::lonnet::perlvar{'lonhttpdPort'};
                   2624:     if (!defined($lonhttpdPort)) { $lonhttpdPort='8080'; }
1.101     www      2625: # construct main body tag
1.60      matthew  2626:     my $bodytag = <<END;
1.231     albertel 2627: <style type="text/css">
1.147     www      2628: h1, h2, h3, th { font-family: Arial, Helvetica, sans-serif }
1.146     www      2629: a:focus { color: red; background: yellow } 
                   2630: </style>
1.54      www      2631: <body bgcolor="$pgbg" text="$font" alink="$alink" vlink="$vlink" link="$link"
1.151     www      2632: style="margin-top: 0px;$addstyle" $addentries>
1.60      matthew  2633: END
1.94      www      2634:     my $upperleft='<img src="http://'.$ENV{'HTTP_HOST'}.':'.
1.150     matthew  2635:                    $lonhttpdPort.$img.'" alt="'.$function.'" />';
1.60      matthew  2636:     if ($bodyonly) {
                   2637:         return $bodytag;
1.79      www      2638:     } elsif ($ENV{'browser.interface'} eq 'textual') {
1.95      www      2639: # Accessibility
1.224     raeburn  2640:           
1.93      www      2641:         return $bodytag.&Apache::lonmenu::menubuttons($forcereg,'web',
                   2642:                                                       $forcereg).
                   2643:                '<h1>LON-CAPA: '.$title.'</h1>';
                   2644:     } elsif ($ENV{'environment.remote'} eq 'off') {
1.95      www      2645: # No Remote
1.206     albertel 2646: 	my $roleinfo=(<<ENDROLE);
                   2647: <td bgcolor="$tabbg" align="right">
                   2648: <font size="2" face="Arial, Helvetica, sans-serif">
                   2649:     $ENV{'environment.firstname'}
                   2650:     $ENV{'environment.middlename'}
                   2651:     $ENV{'environment.lastname'}
                   2652:     $ENV{'environment.generation'}
                   2653:     </font>&nbsp;
                   2654: <br />
                   2655: <font size="2" face="Arial, Helvetica, sans-serif">$role</font>&nbsp;
                   2656: <br />
                   2657: <font size="2" face="Arial, Helvetica, sans-serif">$realm</font>&nbsp;
                   2658: </td>
                   2659: ENDROLE
1.224     raeburn  2660:         my $titleinfo = '<font face="Arial, Helvetica, sans-serif" size="+3" color="'.
1.229     albertel 2661: 		$font.'"><b>'.$title.'</b></font>';
1.224     raeburn  2662:         if ($customtitle) {
                   2663:             $titleinfo = $customtitle;
1.235     raeburn  2664:         }
                   2665: 
1.229     albertel 2666: 	if ($ENV{'request.state'} eq 'construct') {
                   2667: 	    my ($uname,$thisdisfn)=
                   2668: 		($ENV{'request.filename'} =~ m|^/home/([^/]+)/public_html/(.*)|);
                   2669: 	    my $formaction='/priv/'.$uname.'/'.$thisdisfn;
                   2670: 	    $formaction=~s/\/+/\//g;
1.237     raeburn  2671:             unless ($customtitle) {  #this is for resources; directories have customtitle, and crumbs and select recent are created in lonpubdir.pm  
                   2672:                 my $parentpath = '';
1.241     raeburn  2673:                 my $lastitem = '';
                   2674:                 if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
1.235     raeburn  2675:                     $parentpath = $1;
1.241     raeburn  2676:                     $lastitem = $2;
                   2677:                 } else {
                   2678:                     $lastitem = $thisdisfn;
1.235     raeburn  2679:                 }
                   2680: 	        $titleinfo = &Apache::loncommon::help_open_menu('','','','',3,'Authoring').
                   2681:                       '<font face="Arial, Helvetica, sans-serif"><b>Construction Space</b>:</font>&nbsp;'. 
                   2682:                       '<form name="dirs" method="post" action="'.$formaction
                   2683: 		    .'" target="_top"><tt><b>'
1.241     raeburn  2684: 		    .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv','','+1',1)."<font size=\"+1\">$lastitem</font></b></tt><br />"
1.235     raeburn  2685: 		    .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   2686: 		    .'</form>'
                   2687: 		    .&Apache::lonmenu::constspaceform();
1.229     albertel 2688: 
1.235     raeburn  2689:             }
                   2690: 	    $forcereg=1;
                   2691:         }
                   2692:         my $titletable = '<table bgcolor="'.$pgbg.'" width="100%" border="0" '.
                   2693:                          'cellspacing="3" cellpadding="3">'.
                   2694:                          '<tr><td rowspan="3" bgcolor="'.$tabbg.'">'.
                   2695:                          $titleinfo.'</td>'.$roleinfo.'</tr></table>';
                   2696:         if ($ENV{'request.state'} eq 'construct') {
                   2697:             $bodytag .= &Apache::lonmenu::menubuttons($forcereg,'web',$forcereg,$titletable);
                   2698: 	} else {
                   2699:             $bodytag .= &Apache::lonmenu::menubuttons($forcereg,'web',$forcereg).
                   2700:                         $titletable;
                   2701:         }
                   2702:         return $bodytag;
1.94      www      2703:     }
1.95      www      2704: 
1.93      www      2705: #
1.95      www      2706: # Top frame rendering, Remote is up
1.93      www      2707: #
1.224     raeburn  2708:     my $titleinfo = '&nbsp;<font size="5" face="Arial, Helvetica, sans-serif"><b>'.$title.'</b></font>';
                   2709:     if ($customtitle) {
                   2710:         $titleinfo = $customtitle;
                   2711:     }
1.245     matthew  2712:     #
                   2713:     # Extra info if you are the DC
                   2714:     my $dc_info = '';
                   2715:     if ($ENV{'user.adv'} && exists($ENV{'user.role.dc./'.
                   2716:                         $ENV{'course.'.$ENV{'request.course.id'}.
                   2717:                                  '.domain'}.'/'})) {
                   2718:         my $cid = $ENV{'request.course.id'};
                   2719:         $dc_info.= $cid.' '.$ENV{'course.'.$cid.'.internal.coursecode'};
                   2720:         $dc_info = '('.$dc_info.')';
                   2721:     }
                   2722:     #
1.94      www      2723:     return(<<ENDBODY);
1.60      matthew  2724: $bodytag
1.55      www      2725: <table width="100%" cellspacing="0" border="0" cellpadding="0">
1.95      www      2726: <tr><td bgcolor="$sidebg">
1.94      www      2727: $upperleft</td>
1.95      www      2728: <td bgcolor="$sidebg" align="right">$messages&nbsp;</td>
1.55      www      2729: </tr>
1.54      www      2730: <tr>
1.55      www      2731: <td rowspan="3" bgcolor="$tabbg">
1.245     matthew  2732: $titleinfo $dc_info
1.146     www      2733: <td bgcolor="$tabbg" align="right">
                   2734: <font size="2" face="Arial, Helvetica, sans-serif">
1.54      www      2735:     $ENV{'environment.firstname'}
                   2736:     $ENV{'environment.middlename'}
                   2737:     $ENV{'environment.lastname'}
                   2738:     $ENV{'environment.generation'}
1.55      www      2739:     </font>&nbsp;
1.54      www      2740: </td>
                   2741: </tr>
                   2742: <tr><td bgcolor="$tabbg" align="right">
1.146     www      2743: <font size="2" face="Arial, Helvetica, sans-serif">$role</font>&nbsp;
1.54      www      2744: </td></tr>
1.55      www      2745: <tr>
1.148     www      2746: <td bgcolor="$tabbg" align="right"><font size="2" face="Arial, Helvetica, sans-serif">$realm</font>&nbsp;</td></tr>
1.202     albertel 2747: </table><br />
1.54      www      2748: ENDBODY
1.182     matthew  2749: }
                   2750: 
                   2751: ###############################################
                   2752: 
                   2753: =pod
                   2754: 
                   2755: =item get_users_function
                   2756: 
                   2757: Used by &bodytag to determine the current users primary role.
                   2758: Returns either 'student','coordinator','admin', or 'author'.
                   2759: 
                   2760: =cut
                   2761: 
                   2762: ###############################################
                   2763: sub get_users_function {
                   2764:     my $function = 'student';
                   2765:     if ($ENV{'request.role'}=~/^(cc|in|ta|ep)/) {
                   2766:         $function='coordinator';
                   2767:     }
                   2768:     if ($ENV{'request.role'}=~/^(su|dc|ad|li)/) {
                   2769:         $function='admin';
                   2770:     }
                   2771:     if (($ENV{'request.role'}=~/^(au|ca)/) ||
                   2772:         ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
                   2773:         $function='author';
                   2774:     }
                   2775:     return $function;
1.54      www      2776: }
1.99      www      2777: 
                   2778: ###############################################
                   2779: 
1.233     raeburn  2780: =pod
                   2781: 
                   2782: =item get_sections
                   2783: 
                   2784: Determines all the sections for a course including
                   2785: sections with students and sections containing other roles.
                   2786: Incoming parameters: domain, course number, reference to 
                   2787: section hash (keys to be section/group IDs), reference to 
                   2788: array containing roles for which sections should be gathered
                   2789: (optional). If the fourth argument is undefined, sections
                   2790: are gathered for any role.
                   2791:  
                   2792: Returns number of sections.
                   2793: 
                   2794: =cut
                   2795: 
                   2796: ###############################################
                   2797: sub get_sections {
                   2798:     my ($cdom,$cnum,$sectioncount,$possible_roles) = @_;
1.240     albertel 2799:     if (!($cdom && $cnum)) { return 0; }
1.233     raeburn  2800:     my $cid = $cdom.'_'.$cnum;
                   2801:     my $numsections = 0;
1.240     albertel 2802: 
                   2803:     if (!defined($possible_roles) || (grep/^st$/,@$possible_roles)) {
                   2804: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cid,$cdom,$cnum);
                   2805: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   2806: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
                   2807: 	while (my ($student,$data) = each %$classlist) {
                   2808: 	    my ($section,$status) = ($data->[$sec_index],
                   2809: 				     $data->[$status_index]);
                   2810: 	    unless ($section eq '-1' || $section =~ /^\s*$/) {
                   2811: 		if (!defined($$sectioncount{$section})) { $numsections++; }
                   2812: 		$$sectioncount{$section}++;
                   2813: 	    }
                   2814: 	}
                   2815:     }
                   2816:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   2817:     foreach my $user (sort(keys(%courseroles))) {
                   2818: 	if ($user !~ /^(\w{2})/) { next; }
                   2819: 	my ($role) = ($user =~ /^(\w{2})/);
                   2820: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
                   2821: 	my $section;
                   2822: 	if ($role eq 'cr' &&
                   2823: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   2824: 	    $section=$1;
                   2825: 	}
                   2826: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   2827: 	if (!defined($section) || $section eq '-1') { next; }
                   2828: 	if (!defined($$sectioncount{$section})) { $numsections++; } 
                   2829: 	$$sectioncount{$section}++;
1.233     raeburn  2830:     }
                   2831:     return $numsections;
                   2832: }
                   2833: 
                   2834: 
1.99      www      2835: sub get_posted_cgi {
                   2836:     my $r=shift;
                   2837: 
                   2838:     my $buffer;
                   2839:     
                   2840:     $r->read($buffer,$r->header_in('Content-length'),0);
                   2841:     unless ($buffer=~/^(\-+\w+)\s+Content\-Disposition\:\s*form\-data/si) {
                   2842: 	my @pairs=split(/&/,$buffer);
                   2843: 	my $pair;
                   2844: 	foreach $pair (@pairs) {
                   2845: 	    my ($name,$value) = split(/=/,$pair);
                   2846: 	    $value =~ tr/+/ /;
                   2847: 	    $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                   2848: 	    $name  =~ tr/+/ /;
                   2849: 	    $name  =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                   2850: 	    &add_to_env("form.$name",$value);
                   2851: 	}
                   2852:     } else {
                   2853: 	my $contentsep=$1;
                   2854: 	my @lines = split (/\n/,$buffer);
                   2855: 	my $name='';
                   2856: 	my $value='';
                   2857: 	my $fname='';
                   2858: 	my $fmime='';
                   2859: 	my $i;
                   2860: 	for ($i=0;$i<=$#lines;$i++) {
                   2861: 	    if ($lines[$i]=~/^$contentsep/) {
                   2862: 		if ($name) {
                   2863: 		    chomp($value);
                   2864: 		    if ($fname) {
                   2865: 			$ENV{"form.$name.filename"}=$fname;
                   2866: 			$ENV{"form.$name.mimetype"}=$fmime;
                   2867: 		    } else {
                   2868: 			$value=~s/\s+$//s;
                   2869: 		    }
                   2870: 		    &add_to_env("form.$name",$value);
                   2871: 		}
                   2872: 		if ($i<$#lines) {
                   2873: 		    $i++;
                   2874: 		    $lines[$i]=~
                   2875: 		/Content\-Disposition\:\s*form\-data\;\s*name\=\"([^\"]+)\"/i;
                   2876: 		    $name=$1;
                   2877: 		    $value='';
                   2878: 		    if ($lines[$i]=~/filename\=\"([^\"]+)\"/i) {
                   2879: 			$fname=$1;
                   2880: 			if 
                   2881:                             ($lines[$i+1]=~/Content\-Type\:\s*([\w\-\/]+)/i) {
                   2882: 				$fmime=$1;
                   2883: 				$i++;
                   2884: 			    } else {
                   2885: 				$fmime='';
                   2886: 			    }
                   2887: 		    } else {
                   2888: 			$fname='';
                   2889: 			$fmime='';
                   2890: 		    }
                   2891: 		    $i++;
                   2892: 		}
                   2893: 	    } else {
                   2894: 		$value.=$lines[$i]."\n";
                   2895: 	    }
                   2896: 	}
                   2897:     }
                   2898:     $ENV{'request.method'}=$ENV{'REQUEST_METHOD'};
                   2899:     $r->method_number(M_GET);
                   2900:     $r->method('GET');
                   2901:     $r->headers_in->unset('Content-length');
                   2902: }
                   2903: 
1.112     bowersj2 2904: =pod
                   2905: 
                   2906: =item * get_unprocessed_cgi($query,$possible_names)
                   2907: 
                   2908: Modify the %ENV hash to contain unprocessed CGI form parameters held in
                   2909: $query.  The parameters listed in $possible_names (an array reference),
                   2910: will be set in $ENV{'form.name'} if they do not already exist.
                   2911: 
                   2912: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   2913: $possible_names is an ref to an array of form element names.  As an example:
                   2914: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
                   2915: will result in $ENV{'form.uname'} and $ENV{'form.udom'} being set.
                   2916: 
                   2917: =cut
1.1       albertel 2918: 
1.6       albertel 2919: sub get_unprocessed_cgi {
1.25      albertel 2920:   my ($query,$possible_names)= @_;
1.26      matthew  2921:   # $Apache::lonxml::debug=1;
1.16      harris41 2922:   foreach (split(/&/,$query)) {
1.6       albertel 2923:     my ($name, $value) = split(/=/,$_);
1.25      albertel 2924:     $name = &Apache::lonnet::unescape($name);
                   2925:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   2926:       $value =~ tr/+/ /;
                   2927:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                   2928:       &Apache::lonxml::debug("Seting :$name: to :$value:");
1.30      albertel 2929:       unless (defined($ENV{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 2930:     }
1.16      harris41 2931:   }
1.6       albertel 2932: }
                   2933: 
1.112     bowersj2 2934: =pod
                   2935: 
                   2936: =item * cacheheader() 
                   2937: 
                   2938: returns cache-controlling header code
                   2939: 
                   2940: =cut
                   2941: 
1.7       albertel 2942: sub cacheheader {
1.216     albertel 2943:     unless ($ENV{'request.method'} eq 'GET') { return ''; }
                   2944:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   2945:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 2946:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   2947:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 2948:     return $output;
1.7       albertel 2949: }
                   2950: 
1.112     bowersj2 2951: =pod
                   2952: 
                   2953: =item * no_cache($r) 
                   2954: 
                   2955: specifies header code to not have cache
                   2956: 
                   2957: =cut
                   2958: 
1.9       albertel 2959: sub no_cache {
1.216     albertel 2960:     my ($r) = @_;
                   2961:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
                   2962: 	$ENV{'request.method'} ne 'GET') { return ''; }
                   2963:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   2964:     $r->no_cache(1);
                   2965:     $r->header_out("Expires" => $date);
                   2966:     $r->header_out("Pragma" => "no-cache");
1.123     www      2967: }
                   2968: 
                   2969: sub content_type {
1.181     albertel 2970:     my ($r,$type,$charset) = @_;
                   2971:     unless ($charset) {
                   2972: 	$charset=&Apache::lonlocal::current_encoding;
                   2973:     }
                   2974:     if ($charset) { $type.='; charset='.$charset; }
                   2975:     if ($r) {
                   2976: 	$r->content_type($type);
                   2977:     } else {
                   2978: 	print("Content-type: $type\n\n");
                   2979:     }
1.9       albertel 2980: }
1.25      albertel 2981: 
1.112     bowersj2 2982: =pod
                   2983: 
                   2984: =item * add_to_env($name,$value) 
                   2985: 
                   2986: adds $name to the %ENV hash with value
                   2987: $value, if $name already exists, the entry is converted to an array
                   2988: reference and $value is added to the array.
                   2989: 
                   2990: =cut
                   2991: 
1.25      albertel 2992: sub add_to_env {
                   2993:   my ($name,$value)=@_;
1.28      albertel 2994:   if (defined($ENV{$name})) {
1.27      albertel 2995:     if (ref($ENV{$name})) {
1.25      albertel 2996:       #already have multiple values
                   2997:       push(@{ $ENV{$name} },$value);
                   2998:     } else {
                   2999:       #first time seeing multiple values, convert hash entry to an arrayref
                   3000:       my $first=$ENV{$name};
                   3001:       undef($ENV{$name});
                   3002:       push(@{ $ENV{$name} },$first,$value);
                   3003:     }
                   3004:   } else {
                   3005:     $ENV{$name}=$value;
                   3006:   }
1.31      albertel 3007: }
1.149     albertel 3008: 
                   3009: =pod
                   3010: 
                   3011: =item * get_env_multiple($name) 
                   3012: 
                   3013: gets $name from the %ENV hash, it seemlessly handles the cases where multiple
                   3014: values may be defined and end up as an array ref.
                   3015: 
                   3016: returns an array of values
                   3017: 
                   3018: =cut
                   3019: 
                   3020: sub get_env_multiple {
                   3021:     my ($name) = @_;
                   3022:     my @values;
                   3023:     if (defined($ENV{$name})) {
                   3024:         # exists is it an array
                   3025:         if (ref($ENV{$name})) {
                   3026:             @values=@{ $ENV{$name} };
                   3027:         } else {
                   3028:             $values[0]=$ENV{$name};
                   3029:         }
                   3030:     }
                   3031:     return(@values);
                   3032: }
                   3033: 
1.31      albertel 3034: 
1.41      ng       3035: =pod
1.45      matthew  3036: 
                   3037: =back 
1.41      ng       3038: 
1.112     bowersj2 3039: =head1 CSV Upload/Handling functions
1.38      albertel 3040: 
1.41      ng       3041: =over 4
                   3042: 
1.112     bowersj2 3043: =item * upfile_store($r)
1.41      ng       3044: 
                   3045: Store uploaded file, $r should be the HTTP Request object,
                   3046: needs $ENV{'form.upfile'}
                   3047: returns $datatoken to be put into hidden field
                   3048: 
                   3049: =cut
1.31      albertel 3050: 
                   3051: sub upfile_store {
                   3052:     my $r=shift;
                   3053:     $ENV{'form.upfile'}=~s/\r/\n/gs;
                   3054:     $ENV{'form.upfile'}=~s/\f/\n/gs;
                   3055:     $ENV{'form.upfile'}=~s/\n+/\n/gs;
                   3056:     $ENV{'form.upfile'}=~s/\n+$//gs;
                   3057: 
                   3058:     my $datatoken=$ENV{'user.name'}.'_'.$ENV{'user.domain'}.
                   3059: 	'_enroll_'.$ENV{'request.course.id'}.'_'.time.'_'.$$;
                   3060:     {
1.158     raeburn  3061:         my $datafile = $r->dir_config('lonDaemons').
                   3062:                            '/tmp/'.$datatoken.'.tmp';
                   3063:         if ( open(my $fh,">$datafile") ) {
                   3064:             print $fh $ENV{'form.upfile'};
                   3065:             close($fh);
                   3066:         }
1.31      albertel 3067:     }
                   3068:     return $datatoken;
                   3069: }
                   3070: 
1.56      matthew  3071: =pod
                   3072: 
1.112     bowersj2 3073: =item * load_tmp_file($r)
1.41      ng       3074: 
                   3075: Load uploaded file from tmp, $r should be the HTTP Request object,
                   3076: needs $ENV{'form.datatoken'},
                   3077: sets $ENV{'form.upfile'} to the contents of the file
                   3078: 
                   3079: =cut
1.31      albertel 3080: 
                   3081: sub load_tmp_file {
                   3082:     my $r=shift;
                   3083:     my @studentdata=();
                   3084:     {
1.158     raeburn  3085:         my $studentfile = $r->dir_config('lonDaemons').
                   3086:                               '/tmp/'.$ENV{'form.datatoken'}.'.tmp';
                   3087:         if ( open(my $fh,"<$studentfile") ) {
                   3088:             @studentdata=<$fh>;
                   3089:             close($fh);
                   3090:         }
1.31      albertel 3091:     }
                   3092:     $ENV{'form.upfile'}=join('',@studentdata);
                   3093: }
                   3094: 
1.56      matthew  3095: =pod
                   3096: 
1.112     bowersj2 3097: =item * upfile_record_sep()
1.41      ng       3098: 
                   3099: Separate uploaded file into records
                   3100: returns array of records,
                   3101: needs $ENV{'form.upfile'} and $ENV{'form.upfiletype'}
                   3102: 
                   3103: =cut
1.31      albertel 3104: 
                   3105: sub upfile_record_sep {
                   3106:     if ($ENV{'form.upfiletype'} eq 'xml') {
                   3107:     } else {
1.248     albertel 3108: 	my @records;
                   3109: 	foreach my $line (split(/\n/,$ENV{'form.upfile'})) {
                   3110: 	    if ($line=~/^\s*$/) { next; }
                   3111: 	    push(@records,$line);
                   3112: 	}
                   3113: 	return @records;
1.31      albertel 3114:     }
                   3115: }
                   3116: 
1.56      matthew  3117: =pod
                   3118: 
1.112     bowersj2 3119: =item * record_sep($record)
1.41      ng       3120: 
                   3121: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $ENV{'form.upfiletype'}
                   3122: 
                   3123: =cut
                   3124: 
1.31      albertel 3125: sub record_sep {
                   3126:     my $record=shift;
                   3127:     my %components=();
                   3128:     if ($ENV{'form.upfiletype'} eq 'xml') {
                   3129:     } elsif ($ENV{'form.upfiletype'} eq 'space') {
                   3130:         my $i=0;
                   3131:         foreach (split(/\s+/,$record)) {
                   3132:             my $field=$_;
                   3133:             $field=~s/^(\"|\')//;
                   3134:             $field=~s/(\"|\')$//;
                   3135:             $components{$i}=$field;
                   3136:             $i++;
                   3137:         }
                   3138:     } elsif ($ENV{'form.upfiletype'} eq 'tab') {
                   3139:         my $i=0;
1.171     matthew  3140:         foreach (split(/\t/,$record)) {
1.31      albertel 3141:             my $field=$_;
                   3142:             $field=~s/^(\"|\')//;
                   3143:             $field=~s/(\"|\')$//;
                   3144:             $components{$i}=$field;
                   3145:             $i++;
                   3146:         }
                   3147:     } else {
                   3148:         my @allfields=split(/\,/,$record);
                   3149:         my $i=0;
                   3150:         my $j;
                   3151:         for ($j=0;$j<=$#allfields;$j++) {
                   3152:             my $field=$allfields[$j];
                   3153:             if ($field=~/^\s*(\"|\')/) {
                   3154: 		my $delimiter=$1;
                   3155:                 while (($field!~/$delimiter$/) && ($j<$#allfields)) {
                   3156: 		    $j++;
                   3157: 		    $field.=','.$allfields[$j];
                   3158: 		}
                   3159:                 $field=~s/^\s*$delimiter//;
                   3160:                 $field=~s/$delimiter\s*$//;
                   3161:             }
                   3162:             $components{$i}=$field;
                   3163: 	    $i++;
                   3164:         }
                   3165:     }
                   3166:     return %components;
                   3167: }
                   3168: 
1.144     matthew  3169: ######################################################
                   3170: ######################################################
                   3171: 
1.56      matthew  3172: =pod
                   3173: 
1.112     bowersj2 3174: =item * upfile_select_html()
1.41      ng       3175: 
1.144     matthew  3176: Return HTML code to select a file from the users machine and specify 
                   3177: the file type.
1.41      ng       3178: 
                   3179: =cut
                   3180: 
1.144     matthew  3181: ######################################################
                   3182: ######################################################
1.31      albertel 3183: sub upfile_select_html {
1.144     matthew  3184:     my %Types = (
                   3185:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
                   3186:                  space => &mt('Space separated'),
                   3187:                  tab   => &mt('Tabulator separated'),
                   3188: #                 xml   => &mt('HTML/XML'),
                   3189:                  );
                   3190:     my $Str = '<input type="file" name="upfile" size="50" />'.
                   3191:         '<br />Type: <select name="upfiletype">';
                   3192:     foreach my $type (sort(keys(%Types))) {
                   3193:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   3194:     }
                   3195:     $Str .= "</select>\n";
                   3196:     return $Str;
1.31      albertel 3197: }
                   3198: 
1.144     matthew  3199: ######################################################
                   3200: ######################################################
                   3201: 
1.56      matthew  3202: =pod
                   3203: 
1.112     bowersj2 3204: =item * csv_print_samples($r,$records)
1.41      ng       3205: 
                   3206: Prints a table of sample values from each column uploaded $r is an
                   3207: Apache Request ref, $records is an arrayref from
                   3208: &Apache::loncommon::upfile_record_sep
                   3209: 
                   3210: =cut
                   3211: 
1.144     matthew  3212: ######################################################
                   3213: ######################################################
1.31      albertel 3214: sub csv_print_samples {
                   3215:     my ($r,$records) = @_;
                   3216:     my (%sone,%stwo,%sthree);
                   3217:     %sone=&record_sep($$records[0]);
                   3218:     if (defined($$records[1])) {%stwo=&record_sep($$records[1]);}
                   3219:     if (defined($$records[2])) {%sthree=&record_sep($$records[2]);}
1.144     matthew  3220:     #
                   3221:     $r->print(&mt('Samples').'<br /><table border="2"><tr>');
                   3222:     foreach (sort({$a <=> $b} keys(%sone))) { 
                   3223:         $r->print('<th>'.&mt('Column&nbsp;[_1]',($_+1)).'</th>'); }
1.31      albertel 3224:     $r->print('</tr>');
                   3225:     foreach my $hash (\%sone,\%stwo,\%sthree) {
                   3226: 	$r->print('<tr>');
                   3227: 	foreach (sort({$a <=> $b} keys(%sone))) {
                   3228: 	    $r->print('<td>');
                   3229: 	    if (defined($$hash{$_})) { $r->print($$hash{$_}); }
                   3230: 	    $r->print('</td>');
                   3231: 	}
                   3232: 	$r->print('</tr>');
                   3233:     }
                   3234:     $r->print('</tr></table><br />'."\n");
                   3235: }
                   3236: 
1.144     matthew  3237: ######################################################
                   3238: ######################################################
                   3239: 
1.56      matthew  3240: =pod
                   3241: 
1.112     bowersj2 3242: =item * csv_print_select_table($r,$records,$d)
1.41      ng       3243: 
                   3244: Prints a table to create associations between values and table columns.
1.144     matthew  3245: 
1.41      ng       3246: $r is an Apache Request ref,
                   3247: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  3248: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       3249: 
                   3250: =cut
                   3251: 
1.144     matthew  3252: ######################################################
                   3253: ######################################################
1.31      albertel 3254: sub csv_print_select_table {
                   3255:     my ($r,$records,$d) = @_;
                   3256:     my $i=0;my %sone;
                   3257:     %sone=&record_sep($$records[0]);
1.144     matthew  3258:     $r->print(&mt('Associate columns with student attributes.')."\n".
                   3259: 	     '<table border="2"><tr>'.
                   3260:               '<th>'.&mt('Attribute').'</th>'.
                   3261:               '<th>'.&mt('Column').'</th></tr>'."\n");
1.31      albertel 3262:     foreach (@$d) {
1.174     matthew  3263: 	my ($value,$display,$defaultcol)=@{ $_ };
1.31      albertel 3264: 	$r->print('<tr><td>'.$display.'</td>');
                   3265: 
                   3266: 	$r->print('<td><select name=f'.$i.
1.32      matthew  3267: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 3268: 	$r->print('<option value="none"></option>');
                   3269: 	foreach (sort({$a <=> $b} keys(%sone))) {
1.174     matthew  3270: 	    $r->print('<option value="'.$_.'"'.
                   3271:                       ($_ eq $defaultcol ? ' selected ' : '').
                   3272:                       '>Column '.($_+1).'</option>');
1.31      albertel 3273: 	}
                   3274: 	$r->print('</select></td></tr>'."\n");
                   3275: 	$i++;
                   3276:     }
                   3277:     $i--;
                   3278:     return $i;
                   3279: }
1.56      matthew  3280: 
1.144     matthew  3281: ######################################################
                   3282: ######################################################
                   3283: 
1.56      matthew  3284: =pod
1.31      albertel 3285: 
1.112     bowersj2 3286: =item * csv_samples_select_table($r,$records,$d)
1.41      ng       3287: 
                   3288: Prints a table of sample values from the upload and can make associate samples to internal names.
                   3289: 
                   3290: $r is an Apache Request ref,
                   3291: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   3292: $d is an array of 2 element arrays (internal name, displayed name)
                   3293: 
                   3294: =cut
                   3295: 
1.144     matthew  3296: ######################################################
                   3297: ######################################################
1.31      albertel 3298: sub csv_samples_select_table {
                   3299:     my ($r,$records,$d) = @_;
                   3300:     my %sone; my %stwo; my %sthree;
                   3301:     my $i=0;
1.144     matthew  3302:     #
                   3303:     $r->print('<table border=2><tr><th>'.
                   3304:               &mt('Field').'</th><th>'.&mt('Samples').'</th></tr>');
1.31      albertel 3305:     %sone=&record_sep($$records[0]);
                   3306:     if (defined($$records[1])) {%stwo=&record_sep($$records[1]);}
                   3307:     if (defined($$records[2])) {%sthree=&record_sep($$records[2]);}
1.144     matthew  3308:     #
1.31      albertel 3309:     foreach (sort keys %sone) {
1.144     matthew  3310: 	$r->print('<tr><td><select name="f'.$i.'"'.
1.32      matthew  3311: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 3312: 	foreach (@$d) {
1.174     matthew  3313: 	    my ($value,$display,$defaultcol)=@{ $_ };
                   3314: 	    $r->print('<option value="'.$value.'"'.
                   3315:                       ($i eq $defaultcol ? ' selected ':'').'>'.
                   3316:                       $display.'</option>');
1.31      albertel 3317: 	}
                   3318: 	$r->print('</select></td><td>');
                   3319: 	if (defined($sone{$_})) { $r->print($sone{$_}."</br>\n"); }
                   3320: 	if (defined($stwo{$_})) { $r->print($stwo{$_}."</br>\n"); }
                   3321: 	if (defined($sthree{$_})) { $r->print($sthree{$_}."</br>\n"); }
                   3322: 	$r->print('</td></tr>');
                   3323: 	$i++;
                   3324:     }
                   3325:     $i--;
                   3326:     return($i);
1.115     matthew  3327: }
                   3328: 
1.144     matthew  3329: ######################################################
                   3330: ######################################################
                   3331: 
1.115     matthew  3332: =pod
                   3333: 
                   3334: =item clean_excel_name($name)
                   3335: 
                   3336: Returns a replacement for $name which does not contain any illegal characters.
                   3337: 
                   3338: =cut
                   3339: 
1.144     matthew  3340: ######################################################
                   3341: ######################################################
1.115     matthew  3342: sub clean_excel_name {
                   3343:     my ($name) = @_;
                   3344:     $name =~ s/[:\*\?\/\\]//g;
                   3345:     if (length($name) > 31) {
                   3346:         $name = substr($name,0,31);
                   3347:     }
                   3348:     return $name;
1.25      albertel 3349: }
1.84      albertel 3350: 
1.85      albertel 3351: =pod
                   3352: 
1.112     bowersj2 3353: =item * check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 3354: 
                   3355: Returns either 1 or undef
                   3356: 
                   3357: 1 if the part is to be hidden, undef if it is to be shown
                   3358: 
                   3359: Arguments are:
                   3360: 
                   3361: $id the id of the part to be checked
                   3362: $symb, optional the symb of the resource to check
                   3363: $udom, optional the domain of the user to check for
                   3364: $uname, optional the username of the user to check for
                   3365: 
                   3366: =cut
1.84      albertel 3367: 
                   3368: sub check_if_partid_hidden {
                   3369:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 3370:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 3371: 					 $symb,$udom,$uname);
1.141     albertel 3372:     my $truth=1;
                   3373:     #if the string starts with !, then the list is the list to show not hide
                   3374:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 3375:     my @hiddenlist=split(/,/,$hiddenparts);
                   3376:     foreach my $checkid (@hiddenlist) {
1.141     albertel 3377: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 3378:     }
1.141     albertel 3379:     return !$truth;
1.84      albertel 3380: }
1.127     matthew  3381: 
1.138     matthew  3382: 
                   3383: ############################################################
                   3384: ############################################################
                   3385: 
                   3386: =pod
                   3387: 
1.157     matthew  3388: =back 
                   3389: 
1.138     matthew  3390: =head1 cgi-bin script and graphing routines
                   3391: 
1.157     matthew  3392: =over 4
                   3393: 
1.138     matthew  3394: =item get_cgi_id
                   3395: 
                   3396: Inputs: none
                   3397: 
                   3398: Returns an id which can be used to pass environment variables
                   3399: to various cgi-bin scripts.  These environment variables will
                   3400: be removed from the users environment after a given time by
                   3401: the routine &Apache::lonnet::transfer_profile_to_env.
                   3402: 
                   3403: =cut
                   3404: 
                   3405: ############################################################
                   3406: ############################################################
1.152     albertel 3407: my $uniq=0;
1.136     matthew  3408: sub get_cgi_id {
1.154     albertel 3409:     $uniq=($uniq+1)%100000;
1.152     albertel 3410:     return (time.'_'.$uniq);
1.136     matthew  3411: }
                   3412: 
1.127     matthew  3413: ############################################################
                   3414: ############################################################
                   3415: 
                   3416: =pod
                   3417: 
1.134     matthew  3418: =item DrawBarGraph
1.127     matthew  3419: 
1.138     matthew  3420: Facilitates the plotting of data in a (stacked) bar graph.
                   3421: Puts plot definition data into the users environment in order for 
                   3422: graph.png to plot it.  Returns an <img> tag for the plot.
                   3423: The bars on the plot are labeled '1','2',...,'n'.
                   3424: 
                   3425: Inputs:
                   3426: 
                   3427: =over 4
                   3428: 
                   3429: =item $Title: string, the title of the plot
                   3430: 
                   3431: =item $xlabel: string, text describing the X-axis of the plot
                   3432: 
                   3433: =item $ylabel: string, text describing the Y-axis of the plot
                   3434: 
                   3435: =item $Max: scalar, the maximum Y value to use in the plot
                   3436: If $Max is < any data point, the graph will not be rendered.
                   3437: 
1.140     matthew  3438: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  3439: they are plotted.  If undefined, default values will be used.
                   3440: 
1.178     matthew  3441: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   3442: 
1.138     matthew  3443: =item @Values: An array of array references.  Each array reference holds data
                   3444: to be plotted in a stacked bar chart.
                   3445: 
1.239     matthew  3446: =item If the final element of @Values is a hash reference the key/value
                   3447: pairs will be added to the graph definition.
                   3448: 
1.138     matthew  3449: =back
                   3450: 
                   3451: Returns:
                   3452: 
                   3453: An <img> tag which references graph.png and the appropriate identifying
                   3454: information for the plot.
                   3455: 
1.127     matthew  3456: =cut
                   3457: 
                   3458: ############################################################
                   3459: ############################################################
1.134     matthew  3460: sub DrawBarGraph {
1.178     matthew  3461:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  3462:     #
                   3463:     if (! defined($colors)) {
                   3464:         $colors = ['#33ff00', 
                   3465:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   3466:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   3467:                   ]; 
                   3468:     }
1.228     matthew  3469:     my $extra_settings = {};
                   3470:     if (ref($Values[-1]) eq 'HASH') {
                   3471:         $extra_settings = pop(@Values);
                   3472:     }
1.127     matthew  3473:     #
1.136     matthew  3474:     my $identifier = &get_cgi_id();
                   3475:     my $id = 'cgi.'.$identifier;        
1.129     matthew  3476:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  3477:         return '';
                   3478:     }
1.225     matthew  3479:     #
                   3480:     my @Labels;
                   3481:     if (defined($labels)) {
                   3482:         @Labels = @$labels;
                   3483:     } else {
                   3484:         for (my $i=0;$i<@{$Values[0]};$i++) {
                   3485:             push (@Labels,$i+1);
                   3486:         }
                   3487:     }
                   3488:     #
1.129     matthew  3489:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  3490:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  3491:     my %ValuesHash;
                   3492:     my $NumSets=1;
                   3493:     foreach my $array (@Values) {
                   3494:         next if (! ref($array));
1.136     matthew  3495:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  3496:             join(',',@$array);
1.129     matthew  3497:     }
1.127     matthew  3498:     #
1.136     matthew  3499:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  3500:     if ($NumBars < 3) {
                   3501:         $width = 120+$NumBars*32;
1.220     matthew  3502:         $xskip = 1;
1.225     matthew  3503:         $bar_width = 30;
                   3504:     } elsif ($NumBars < 5) {
                   3505:         $width = 120+$NumBars*20;
                   3506:         $xskip = 1;
                   3507:         $bar_width = 20;
1.220     matthew  3508:     } elsif ($NumBars < 10) {
1.136     matthew  3509:         $width = 120+$NumBars*15;
                   3510:         $xskip = 1;
                   3511:         $bar_width = 15;
                   3512:     } elsif ($NumBars <= 25) {
                   3513:         $width = 120+$NumBars*11;
                   3514:         $xskip = 5;
                   3515:         $bar_width = 8;
                   3516:     } elsif ($NumBars <= 50) {
                   3517:         $width = 120+$NumBars*8;
                   3518:         $xskip = 5;
                   3519:         $bar_width = 4;
                   3520:     } else {
                   3521:         $width = 120+$NumBars*8;
                   3522:         $xskip = 5;
                   3523:         $bar_width = 4;
                   3524:     }
                   3525:     #
1.137     matthew  3526:     $Max = 1 if ($Max < 1);
                   3527:     if ( int($Max) < $Max ) {
                   3528:         $Max++;
                   3529:         $Max = int($Max);
                   3530:     }
1.127     matthew  3531:     $Title  = '' if (! defined($Title));
                   3532:     $xlabel = '' if (! defined($xlabel));
                   3533:     $ylabel = '' if (! defined($ylabel));
1.136     matthew  3534:     $ValuesHash{$id.'.title'}    = &Apache::lonnet::escape($Title);
                   3535:     $ValuesHash{$id.'.xlabel'}   = &Apache::lonnet::escape($xlabel);
                   3536:     $ValuesHash{$id.'.ylabel'}   = &Apache::lonnet::escape($ylabel);
1.137     matthew  3537:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  3538:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   3539:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   3540:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   3541:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   3542:     $ValuesHash{$id.'.height'}   = $height;
                   3543:     $ValuesHash{$id.'.width'}    = $width;
                   3544:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   3545:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   3546:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  3547:     #
1.228     matthew  3548:     # Deal with other parameters
                   3549:     while (my ($key,$value) = each(%$extra_settings)) {
                   3550:         $ValuesHash{$id.'.'.$key} = $value;
                   3551:     }
                   3552:     #
1.137     matthew  3553:     &Apache::lonnet::appenv(%ValuesHash);
                   3554:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   3555: }
                   3556: 
                   3557: ############################################################
                   3558: ############################################################
                   3559: 
                   3560: =pod
                   3561: 
                   3562: =item DrawXYGraph
                   3563: 
1.138     matthew  3564: Facilitates the plotting of data in an XY graph.
                   3565: Puts plot definition data into the users environment in order for 
                   3566: graph.png to plot it.  Returns an <img> tag for the plot.
                   3567: 
                   3568: Inputs:
                   3569: 
                   3570: =over 4
                   3571: 
                   3572: =item $Title: string, the title of the plot
                   3573: 
                   3574: =item $xlabel: string, text describing the X-axis of the plot
                   3575: 
                   3576: =item $ylabel: string, text describing the Y-axis of the plot
                   3577: 
                   3578: =item $Max: scalar, the maximum Y value to use in the plot
                   3579: If $Max is < any data point, the graph will not be rendered.
                   3580: 
                   3581: =item $colors: Array ref containing the hex color codes for the data to be 
                   3582: plotted in.  If undefined, default values will be used.
                   3583: 
                   3584: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   3585: 
                   3586: =item $Ydata: Array ref containing Array refs.  
1.185     www      3587: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  3588: 
                   3589: =item %Values: hash indicating or overriding any default values which are 
                   3590: passed to graph.png.  
                   3591: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   3592: 
                   3593: =back
                   3594: 
                   3595: Returns:
                   3596: 
                   3597: An <img> tag which references graph.png and the appropriate identifying
                   3598: information for the plot.
                   3599: 
1.137     matthew  3600: =cut
                   3601: 
                   3602: ############################################################
                   3603: ############################################################
                   3604: sub DrawXYGraph {
                   3605:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   3606:     #
                   3607:     # Create the identifier for the graph
                   3608:     my $identifier = &get_cgi_id();
                   3609:     my $id = 'cgi.'.$identifier;
                   3610:     #
                   3611:     $Title  = '' if (! defined($Title));
                   3612:     $xlabel = '' if (! defined($xlabel));
                   3613:     $ylabel = '' if (! defined($ylabel));
                   3614:     my %ValuesHash = 
                   3615:         (
                   3616:          $id.'.title'  => &Apache::lonnet::escape($Title),
                   3617:          $id.'.xlabel' => &Apache::lonnet::escape($xlabel),
                   3618:          $id.'.ylabel' => &Apache::lonnet::escape($ylabel),
                   3619:          $id.'.y_max_value'=> $Max,
                   3620:          $id.'.labels'     => join(',',@$Xlabels),
                   3621:          $id.'.PlotType'   => 'XY',
                   3622:          );
                   3623:     #
                   3624:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   3625:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   3626:     }
                   3627:     #
                   3628:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   3629:         return '';
                   3630:     }
                   3631:     my $NumSets=1;
1.138     matthew  3632:     foreach my $array (@{$Ydata}){
1.137     matthew  3633:         next if (! ref($array));
                   3634:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   3635:     }
1.138     matthew  3636:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  3637:     #
                   3638:     # Deal with other parameters
                   3639:     while (my ($key,$value) = each(%Values)) {
                   3640:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  3641:     }
                   3642:     #
1.136     matthew  3643:     &Apache::lonnet::appenv(%ValuesHash);
                   3644:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   3645: }
                   3646: 
                   3647: ############################################################
                   3648: ############################################################
                   3649: 
                   3650: =pod
                   3651: 
1.138     matthew  3652: =item DrawXYYGraph
                   3653: 
                   3654: Facilitates the plotting of data in an XY graph with two Y axes.
                   3655: Puts plot definition data into the users environment in order for 
                   3656: graph.png to plot it.  Returns an <img> tag for the plot.
                   3657: 
                   3658: Inputs:
                   3659: 
                   3660: =over 4
                   3661: 
                   3662: =item $Title: string, the title of the plot
                   3663: 
                   3664: =item $xlabel: string, text describing the X-axis of the plot
                   3665: 
                   3666: =item $ylabel: string, text describing the Y-axis of the plot
                   3667: 
                   3668: =item $colors: Array ref containing the hex color codes for the data to be 
                   3669: plotted in.  If undefined, default values will be used.
                   3670: 
                   3671: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   3672: 
                   3673: =item $Ydata1: The first data set
                   3674: 
                   3675: =item $Min1: The minimum value of the left Y-axis
                   3676: 
                   3677: =item $Max1: The maximum value of the left Y-axis
                   3678: 
                   3679: =item $Ydata2: The second data set
                   3680: 
                   3681: =item $Min2: The minimum value of the right Y-axis
                   3682: 
                   3683: =item $Max2: The maximum value of the left Y-axis
                   3684: 
                   3685: =item %Values: hash indicating or overriding any default values which are 
                   3686: passed to graph.png.  
                   3687: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   3688: 
                   3689: =back
                   3690: 
                   3691: Returns:
                   3692: 
                   3693: An <img> tag which references graph.png and the appropriate identifying
                   3694: information for the plot.
1.136     matthew  3695: 
                   3696: =cut
                   3697: 
                   3698: ############################################################
                   3699: ############################################################
1.137     matthew  3700: sub DrawXYYGraph {
                   3701:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   3702:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  3703:     #
                   3704:     # Create the identifier for the graph
                   3705:     my $identifier = &get_cgi_id();
                   3706:     my $id = 'cgi.'.$identifier;
                   3707:     #
                   3708:     $Title  = '' if (! defined($Title));
                   3709:     $xlabel = '' if (! defined($xlabel));
                   3710:     $ylabel = '' if (! defined($ylabel));
                   3711:     my %ValuesHash = 
                   3712:         (
                   3713:          $id.'.title'  => &Apache::lonnet::escape($Title),
                   3714:          $id.'.xlabel' => &Apache::lonnet::escape($xlabel),
                   3715:          $id.'.ylabel' => &Apache::lonnet::escape($ylabel),
                   3716:          $id.'.labels' => join(',',@$Xlabels),
                   3717:          $id.'.PlotType' => 'XY',
                   3718:          $id.'.NumSets' => 2,
1.137     matthew  3719:          $id.'.two_axes' => 1,
                   3720:          $id.'.y1_max_value' => $Max1,
                   3721:          $id.'.y1_min_value' => $Min1,
                   3722:          $id.'.y2_max_value' => $Max2,
                   3723:          $id.'.y2_min_value' => $Min2,
1.136     matthew  3724:          );
                   3725:     #
1.137     matthew  3726:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   3727:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   3728:     }
                   3729:     #
                   3730:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   3731:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  3732:         return '';
                   3733:     }
                   3734:     my $NumSets=1;
1.137     matthew  3735:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  3736:         next if (! ref($array));
                   3737:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  3738:     }
                   3739:     #
                   3740:     # Deal with other parameters
                   3741:     while (my ($key,$value) = each(%Values)) {
                   3742:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  3743:     }
                   3744:     #
                   3745:     &Apache::lonnet::appenv(%ValuesHash);
1.130     albertel 3746:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  3747: }
                   3748: 
                   3749: ############################################################
                   3750: ############################################################
                   3751: 
                   3752: =pod
                   3753: 
1.157     matthew  3754: =back 
                   3755: 
1.139     matthew  3756: =head1 Statistics helper routines?  
                   3757: 
                   3758: Bad place for them but what the hell.
                   3759: 
1.157     matthew  3760: =over 4
                   3761: 
1.139     matthew  3762: =item &chartlink
                   3763: 
                   3764: Returns a link to the chart for a specific student.  
                   3765: 
                   3766: Inputs:
                   3767: 
                   3768: =over 4
                   3769: 
                   3770: =item $linktext: The text of the link
                   3771: 
                   3772: =item $sname: The students username
                   3773: 
                   3774: =item $sdomain: The students domain
                   3775: 
                   3776: =back
                   3777: 
1.157     matthew  3778: =back
                   3779: 
1.139     matthew  3780: =cut
                   3781: 
                   3782: ############################################################
                   3783: ############################################################
                   3784: sub chartlink {
                   3785:     my ($linktext, $sname, $sdomain) = @_;
                   3786:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.219     albertel 3787:         '&amp;SelectedStudent='.&Apache::lonnet::escape($sname.':'.$sdomain).
                   3788:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  3789:        '">'.$linktext.'</a>';
1.153     matthew  3790: }
                   3791: 
                   3792: #######################################################
                   3793: #######################################################
                   3794: 
                   3795: =pod
                   3796: 
                   3797: =head1 Course Environment Routines
1.157     matthew  3798: 
                   3799: =over 4
1.153     matthew  3800: 
                   3801: =item &restore_course_settings 
                   3802: 
                   3803: =item &store_course_settings
                   3804: 
                   3805: Restores/Store indicated form parameters from the course environment.
                   3806: Will not overwrite existing values of the form parameters.
                   3807: 
                   3808: Inputs: 
                   3809: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   3810: 
                   3811: a hash ref describing the data to be stored.  For example:
                   3812:    
                   3813: %Save_Parameters = ('Status' => 'scalar',
                   3814:     'chartoutputmode' => 'scalar',
                   3815:     'chartoutputdata' => 'scalar',
                   3816:     'Section' => 'array',
                   3817:     'StudentData' => 'array',
                   3818:     'Maps' => 'array');
                   3819: 
                   3820: Returns: both routines return nothing
                   3821: 
                   3822: =cut
                   3823: 
                   3824: #######################################################
                   3825: #######################################################
                   3826: sub store_course_settings {
                   3827:     # save to the environment
                   3828:     # appenv the same items, just to be safe
                   3829:     my $courseid = $ENV{'request.course.id'};
                   3830:     my $coursedom = $ENV{'course.'.$courseid.'.domain'};
                   3831:     my ($prefix,$Settings) = @_;
                   3832:     my %SaveHash;
                   3833:     my %AppHash;
                   3834:     while (my ($setting,$type) = each(%$Settings)) {
1.176     albertel 3835:         my $basename = 'internal.'.$prefix.'.'.$setting;
1.153     matthew  3836:         my $envname = 'course.'.$courseid.'.'.$basename;
                   3837:         if (exists($ENV{'form.'.$setting})) {
                   3838:             # Save this value away
                   3839:             if ($type eq 'scalar' &&
                   3840:                 (! exists($ENV{$envname}) || 
                   3841:                  $ENV{$envname} ne $ENV{'form.'.$setting})) {
                   3842:                 $SaveHash{$basename} = $ENV{'form.'.$setting};
                   3843:                 $AppHash{$envname}   = $ENV{'form.'.$setting};
                   3844:             } elsif ($type eq 'array') {
                   3845:                 my $stored_form;
                   3846:                 if (ref($ENV{'form.'.$setting})) {
                   3847:                     $stored_form = join(',',
                   3848:                                         map {
                   3849:                                             &Apache::lonnet::escape($_);
                   3850:                                         } sort(@{$ENV{'form.'.$setting}}));
                   3851:                 } else {
                   3852:                     $stored_form = 
                   3853:                         &Apache::lonnet::escape($ENV{'form.'.$setting});
                   3854:                 }
                   3855:                 # Determine if the array contents are the same.
                   3856:                 if ($stored_form ne $ENV{$envname}) {
                   3857:                     $SaveHash{$basename} = $stored_form;
                   3858:                     $AppHash{$envname}   = $stored_form;
                   3859:                 }
                   3860:             }
                   3861:         }
                   3862:     }
                   3863:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
                   3864:                                           $coursedom,
                   3865:                                           $ENV{'course.'.$courseid.'.num'});
                   3866:     if ($put_result !~ /^(ok|delayed)/) {
                   3867:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   3868:                                  'got error:'.$put_result);
                   3869:     }
                   3870:     # Make sure these settings stick around in this session, too
                   3871:     &Apache::lonnet::appenv(%AppHash);
                   3872:     return;
                   3873: }
                   3874: 
                   3875: sub restore_course_settings {
                   3876:     my $courseid = $ENV{'request.course.id'};
                   3877:     my ($prefix,$Settings) = @_;
                   3878:     while (my ($setting,$type) = each(%$Settings)) {
                   3879:         next if (exists($ENV{'form.'.$setting}));
1.176     albertel 3880:         my $envname = 'course.'.$courseid.'.internal.'.$prefix.
1.153     matthew  3881:             '.'.$setting;
                   3882:         if (exists($ENV{$envname})) {
                   3883:             if ($type eq 'scalar') {
                   3884:                 $ENV{'form.'.$setting} = $ENV{$envname};
                   3885:             } elsif ($type eq 'array') {
                   3886:                 $ENV{'form.'.$setting} = [ 
                   3887:                                            map { 
                   3888:                                                &Apache::lonnet::unescape($_); 
                   3889:                                            } split(',',$ENV{$envname})
                   3890:                                            ];
                   3891:             }
                   3892:         }
                   3893:     }
1.127     matthew  3894: }
                   3895: 
                   3896: ############################################################
                   3897: ############################################################
1.154     albertel 3898: 
                   3899: sub propath {
                   3900:     my ($udom,$uname)=@_;
                   3901:     $udom=~s/\W//g;
                   3902:     $uname=~s/\W//g;
                   3903:     my $subdir=$uname.'__';
                   3904:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   3905:     my $proname="$Apache::lonnet::perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
                   3906:     return $proname;
1.156     albertel 3907: } 
                   3908: 
                   3909: sub icon {
                   3910:     my ($file)=@_;
1.168     albertel 3911:     my $curfext = (split(/\./,$file))[-1];
                   3912:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 3913:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 3914:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   3915: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   3916: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   3917: 	            $curfext.".gif") {
                   3918: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   3919: 		$curfext.".gif";
                   3920: 	}
                   3921:     }
1.249   ! albertel 3922:     return &lonhttpdurl($iconname);
1.154     albertel 3923: } 
1.84      albertel 3924: 
1.215     albertel 3925: sub lonhttpdurl {
                   3926:     my ($url)=@_;
                   3927:     my $lonhttpd_port=$Apache::lonnet::perlvar{'lonhttpdPort'};
                   3928:     if (!defined($lonhttpd_port)) { $lonhttpd_port='8080'; }
                   3929:     return 'http://'.$ENV{'SERVER_NAME'}.':'.$lonhttpd_port.$url;
                   3930: }
                   3931: 
1.213     albertel 3932: sub connection_aborted {
                   3933:     my ($r)=@_;
                   3934:     $r->print(" ");$r->rflush();
                   3935:     my $c = $r->connection;
                   3936:     return $c->aborted();
                   3937: }
                   3938: 
1.221     foxr     3939: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     3940: #    strings as 'strings'.
                   3941: sub escape_single {
1.221     foxr     3942:     my ($input) = @_;
1.223     albertel 3943:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     3944:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   3945:     return $input;
                   3946: }
1.223     albertel 3947: 
1.222     foxr     3948: #  Same as escape_single, but escape's "'s  This 
                   3949: #  can be used for  "strings"
                   3950: sub escape_double {
                   3951:     my ($input) = @_;
                   3952:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   3953:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   3954:     return $input;
                   3955: }
1.223     albertel 3956:  
1.222     foxr     3957: #   Escapes the last element of a full URL.
                   3958: sub escape_url {
                   3959:     my ($url)   = @_;
1.238     raeburn  3960:     my @urlslices = split(/\//, $url,-1);
1.223     albertel 3961:     my $lastitem = &Apache::lonnet::escape(pop(@urlslices));
                   3962:     return join('/',@urlslices).'/'.$lastitem;
1.222     foxr     3963: }
1.41      ng       3964: =pod
                   3965: 
                   3966: =back
                   3967: 
1.112     bowersj2 3968: =cut
1.41      ng       3969: 
1.112     bowersj2 3970: 1;
                   3971: __END__;
1.41      ng       3972: 

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