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

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

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