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

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

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