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

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

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