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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.128   ! albertel    4: # $Id: loncommon.pm,v 1.127 2003/10/09 22:07:08 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.12      harris41   28: # YEAR=2001
                     29: # 2/13-12/7 Guy Albertelli
1.18      www        30: # 12/21 Gerd Kortemeyer
1.22      www        31: # 12/25,12/28 Gerd Kortemeyer
1.23      www        32: # YEAR=2002
                     33: # 1/4 Gerd Kortemeyer
1.43      ng         34: # 6/24,7/2 H. K. Ng
1.1       albertel   35: 
                     36: # Makes a table out of the previous attempts
1.2       albertel   37: # Inputs result_from_symbread, user, domain, course_id
1.16      harris41   38: # Reads in non-network-related .tab files
1.1       albertel   39: 
1.35      matthew    40: # POD header:
                     41: 
1.45      matthew    42: =pod
                     43: 
1.35      matthew    44: =head1 NAME
                     45: 
                     46: Apache::loncommon - pile of common routines
                     47: 
                     48: =head1 SYNOPSIS
                     49: 
1.112     bowersj2   50: Common routines for manipulating connections, student answers,
                     51:     domains, common Javascript fragments, etc.
1.35      matthew    52: 
1.112     bowersj2   53: =head1 OVERVIEW
1.35      matthew    54: 
1.112     bowersj2   55: A collection of commonly used subroutines that don't have a natural
                     56: home anywhere else. This collection helps remove
1.35      matthew    57: redundancy from other modules and increase efficiency of memory usage.
                     58: 
                     59: =cut 
                     60: 
                     61: # End of POD header
1.1       albertel   62: package Apache::loncommon;
                     63: 
                     64: use strict;
1.22      www        65: use Apache::lonnet();
1.46      matthew    66: use GDBM_File;
1.51      www        67: use POSIX qw(strftime mktime);
1.99      www        68: use Apache::Constants qw(:common :http :methods);
1.1       albertel   69: use Apache::lonmsg();
1.82      www        70: use Apache::lonmenu();
1.117     www        71: use Apache::lonlocal;
                     72: 
1.22      www        73: my $readit;
                     74: 
1.46      matthew    75: =pod 
                     76: 
1.112     bowersj2   77: =head1 Global Variables
1.46      matthew    78: 
1.112     bowersj2   79: =cut
1.46      matthew    80: 
1.20      www        81: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41   82: my %language;
1.124     www        83: my %supported_language;
1.12      harris41   84: my %cprtag;
                     85: my %fe; my %fd;
1.41      ng         86: my %category_extensions;
1.12      harris41   87: 
1.63      www        88: # ---------------------------------------------- Designs
                     89: 
                     90: my %designhash;
                     91: 
1.46      matthew    92: # ---------------------------------------------- Thesaurus variables
                     93: 
1.112     bowersj2   94: # FIXME: I don't think it's necessary to document these things;
                     95: # they're privately used - Jeremy
                     96: 
1.46      matthew    97: =pod
                     98: 
1.112     bowersj2   99: =over 4
                    100: 
                    101: =item * %Keywords  
1.46      matthew   102: 
                    103: A hash used by &keyword to determine if a word is considered a keyword.
                    104: 
1.112     bowersj2  105: =item * $thesaurus_db_file
1.46      matthew   106: 
                    107: Scalar containing the full path to the thesaurus database.                 
                    108: 
1.112     bowersj2  109: =back
                    110: 
1.46      matthew   111: =cut
                    112: 
                    113: my %Keywords;
                    114: my $thesaurus_db_file;
                    115: 
1.112     bowersj2  116: # ----------------------------------------------------------------------- BEGIN
1.46      matthew   117: 
1.112     bowersj2  118: # FIXME: I don't think this needs to be documented, it prepares
                    119: # private data structures - Jeremy
1.46      matthew   120: =pod
                    121: 
1.112     bowersj2  122: =head1 General Subroutines
1.46      matthew   123: 
1.112     bowersj2  124: =over 4
1.20      www       125: 
1.112     bowersj2  126: =item * BEGIN() 
1.35      matthew   127: 
                    128: Initialize values from language.tab, copyright.tab, filetypes.tab,
1.45      matthew   129: thesaurus.tab, and filecategories.tab.
1.35      matthew   130: 
1.112     bowersj2  131: =back
                    132: 
1.35      matthew   133: =cut
1.45      matthew   134: 
1.35      matthew   135: # ----------------------------------------------------------------------- BEGIN
                    136: 
1.18      www       137: BEGIN {
1.46      matthew   138:     # Variable initialization
                    139:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    140:     #
1.22      www       141:     unless ($readit) {
1.12      harris41  142: # ------------------------------------------------------------------- languages
                    143:     {
                    144: 	my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.
                    145: 				 '/language.tab');
1.16      harris41  146: 	if ($fh) {
                    147: 	    while (<$fh>) {
                    148: 		next if /^\#/;
                    149: 		chomp;
1.124     www       150: 		my ($key,$two,$country,$three,$enc,$val,$sup)=(split(/\t/,$_));
1.98      www       151: 		$language{$key}=$val.' - '.$enc;
1.124     www       152: 		if ($sup) {
                    153: 		    $supported_language{$key}=$sup;
                    154: 		}
1.16      harris41  155: 	    }
1.12      harris41  156: 	}
                    157:     }
                    158: # ------------------------------------------------------------------ copyrights
                    159:     {
1.16      harris41  160: 	my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonIncludes'}.
                    161: 				  '/copyright.tab');
                    162: 	if ($fh) {
                    163: 	    while (<$fh>) {
                    164: 		next if /^\#/;
                    165: 		chomp;
                    166: 		my ($key,$val)=(split(/\s+/,$_,2));
                    167: 		$cprtag{$key}=$val;
                    168: 	    }
1.12      harris41  169: 	}
                    170:     }
1.63      www       171: 
                    172: # -------------------------------------------------------------- domain designs
                    173: 
                    174:     my $filename;
                    175:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                    176:     opendir(DIR,$designdir);
                    177:     while ($filename=readdir(DIR)) {
                    178: 	my ($domain)=($filename=~/^(\w+)\./);
                    179:     {
                    180: 	my $fh=Apache::File->new($designdir.'/'.$filename);
                    181: 	if ($fh) {
                    182: 	    while (<$fh>) {
                    183: 		next if /^\#/;
                    184: 		chomp;
                    185: 		my ($key,$val)=(split(/\=/,$_));
                    186: 		if ($val) { $designhash{$domain.'.'.$key}=$val; }
                    187: 	    }
                    188: 	}
                    189:     }
                    190: 
                    191:     }
                    192:     closedir(DIR);
                    193: 
                    194: 
1.15      harris41  195: # ------------------------------------------------------------- file categories
                    196:     {
                    197: 	my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.
1.16      harris41  198: 				  '/filecategories.tab');
                    199: 	if ($fh) {
                    200: 	    while (<$fh>) {
                    201: 		next if /^\#/;
                    202: 		chomp;
1.41      ng        203: 		my ($extension,$category)=(split(/\s+/,$_,2));
                    204: 		push @{$category_extensions{lc($category)}},$extension;
1.16      harris41  205: 	    }
1.15      harris41  206: 	}
                    207:     }
1.12      harris41  208: # ------------------------------------------------------------------ file types
                    209:     {
1.16      harris41  210: 	my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.
                    211: 	       '/filetypes.tab');
                    212: 	if ($fh) {
                    213:             while (<$fh>) {
                    214: 		next if (/^\#/);
                    215: 		chomp;
                    216: 		my ($ending,$emb,$descr)=split(/\s+/,$_,3);
                    217: 		if ($descr ne '') { 
                    218: 		    $fe{$ending}=lc($emb);
                    219: 		    $fd{$ending}=$descr;
                    220: 		}
1.12      harris41  221: 	    }
                    222: 	}
                    223:     }
1.22      www       224:     &Apache::lonnet::logthis(
1.46      matthew   225:               "<font color=yellow>INFO: Read file types</font>");
1.22      www       226:     $readit=1;
1.46      matthew   227:     }  # end of unless($readit) 
1.32      matthew   228:     
                    229: }
1.112     bowersj2  230: 
1.42      matthew   231: ###############################################################
                    232: ##           HTML and Javascript Helper Functions            ##
                    233: ###############################################################
                    234: 
                    235: =pod 
                    236: 
1.112     bowersj2  237: =head1 HTML and Javascript Functions
1.42      matthew   238: 
1.112     bowersj2  239: =over 4
                    240: 
                    241: =item * browser_and_searcher_javascript ()
                    242: 
                    243: X<browsing, javascript>X<searching, javascript>Returns a string
                    244: containing javascript with two functions, C<openbrowser> and
                    245: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    246: tags.
1.42      matthew   247: 
                    248: =over 4
                    249: 
1.112     bowersj2  250: =item * openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   251: 
                    252: inputs: formname, elementname, only, omit
                    253: 
                    254: formname and elementname indicate the name of the html form and name of
                    255: the element that the results of the browsing selection are to be placed in. 
                    256: 
                    257: Specifying 'only' will restrict the browser to displaying only files
                    258: with the given extension.  Can be a comma seperated list.
                    259: 
                    260: Specifying 'omit' will restrict the browser to NOT displaying files
                    261: with the given extension.  Can be a comma seperated list.
                    262: 
1.112     bowersj2  263: =item * opensearcher(formname, elementname) [javascript]
1.42      matthew   264: 
                    265: Inputs: formname, elementname
                    266: 
                    267: formname and elementname specify the name of the html form and the name
                    268: of the element the selection from the search results will be placed in.
                    269: 
                    270: =back
                    271: 
                    272: =cut
                    273: 
                    274: sub browser_and_searcher_javascript {
                    275:     return <<END;
1.50      matthew   276:     var editbrowser = null;
1.42      matthew   277:     function openbrowser(formname,elementname,only,omit) {
                    278:         var url = '/res/?';
                    279:         if (editbrowser == null) {
                    280:             url += 'launch=1&';
                    281:         }
                    282:         url += 'catalogmode=interactive&';
                    283:         url += 'mode=edit&';
                    284:         url += 'form=' + formname + '&';
                    285:         if (only != null) {
                    286:             url += 'only=' + only + '&';
                    287:         } 
                    288:         if (omit != null) {
                    289:             url += 'omit=' + omit + '&';
                    290:         }
                    291:         url += 'element=' + elementname + '';
                    292:         var title = 'Browser';
                    293:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    294:         options += ',width=700,height=600';
                    295:         editbrowser = open(url,title,options,'1');
                    296:         editbrowser.focus();
                    297:     }
                    298:     var editsearcher;
                    299:     function opensearcher(formname,elementname) {
                    300:         var url = '/adm/searchcat?';
                    301:         if (editsearcher == null) {
                    302:             url += 'launch=1&';
                    303:         }
                    304:         url += 'catalogmode=interactive&';
                    305:         url += 'mode=edit&';
                    306:         url += 'form=' + formname + '&';
                    307:         url += 'element=' + elementname + '';
                    308:         var title = 'Search';
                    309:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    310:         options += ',width=700,height=600';
                    311:         editsearcher = open(url,title,options,'1');
                    312:         editsearcher.focus();
                    313:     }
                    314: END
                    315: }
                    316: 
1.74      www       317: sub studentbrowser_javascript {
1.111     www       318:    unless (
                    319:             (($ENV{'request.course.id'}) && 
                    320:              (&Apache::lonnet::allowed('srm',$ENV{'request.course.id'})))
                    321:          || ($ENV{'request.role'}=~/^(au|dc|su)/)
                    322:           ) { return ''; }  
1.74      www       323:    return (<<'ENDSTDBRW');
                    324: <script type="text/javascript" language="Javascript" >
                    325:     var stdeditbrowser;
1.111     www       326:     function openstdbrowser(formname,uname,udom,roleflag) {
1.74      www       327:         var url = '/adm/pickstudent?';
                    328:         var filter;
                    329:         eval('filter=document.'+formname+'.'+uname+'.value;');
                    330:         if (filter != null) {
                    331:            if (filter != '') {
                    332:                url += 'filter='+filter+'&';
                    333: 	   }
                    334:         }
                    335:         url += 'form=' + formname + '&unameelement='+uname+
                    336:                                     '&udomelement='+udom;
1.111     www       337: 	if (roleflag) { url+="&roles=1"; }
1.102     www       338:         var title = 'Student_Browser';
1.74      www       339:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    340:         options += ',width=700,height=600';
                    341:         stdeditbrowser = open(url,title,options,'1');
                    342:         stdeditbrowser.focus();
                    343:     }
                    344: </script>
                    345: ENDSTDBRW
                    346: }
1.42      matthew   347: 
1.74      www       348: sub selectstudent_link {
1.111     www       349:    my ($form,$unameele,$udomele)=@_;
                    350:    if ($ENV{'request.course.id'}) {  
                    351:        unless (&Apache::lonnet::allowed('srm',$ENV{'request.course.id'})) {
                    352: 	   return '';
                    353:        }
                    354:        return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
1.119     www       355:         '","'.$udomele.'");'."'>".&mt('Select User')."</a>";
1.74      www       356:    }
1.111     www       357:    if ($ENV{'request.role'}=~/^(au|dc|su)/) {
                    358:        return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
1.119     www       359:         '","'.$udomele.'",1);'."'>".&mt('Select User')."</a>";
1.111     www       360:    }
                    361:    return '';
1.91      www       362: }
                    363: 
                    364: sub coursebrowser_javascript {
1.128   ! albertel  365:     my ($domainfilter)=@_;
        !           366:    return (<<ENDSTDBRW);
1.91      www       367: <script type="text/javascript" language="Javascript" >
                    368:     var stdeditbrowser;
                    369:     function opencrsbrowser(formname,uname,udom) {
                    370:         var url = '/adm/pickcourse?';
                    371:         var filter;
                    372:         if (filter != null) {
                    373:            if (filter != '') {
                    374:                url += 'filter='+filter+'&';
                    375: 	   }
                    376:         }
1.128   ! albertel  377:         var domainfilter='$domainfilter';
        !           378:         if (domainfilter != null) {
        !           379:            if (domainfilter != '') {
        !           380:                url += 'domainfilter='+domainfilter+'&';
        !           381: 	   }
        !           382:         }
1.91      www       383:         url += 'form=' + formname + '&cnumelement='+uname+
                    384:                                     '&cdomelement='+udom;
1.102     www       385:         var title = 'Course_Browser';
1.91      www       386:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    387:         options += ',width=700,height=600';
                    388:         stdeditbrowser = open(url,title,options,'1');
                    389:         stdeditbrowser.focus();
                    390:     }
                    391: </script>
                    392: ENDSTDBRW
                    393: }
                    394: 
                    395: sub selectcourse_link {
                    396:    my ($form,$unameele,$udomele)=@_;
                    397:     return "<a href='".'javascript:opencrsbrowser("'.$form.'","'.$unameele.
1.119     www       398:         '","'.$udomele.'");'."'>".&mt('Select Course')."</a>";
1.74      www       399: }
1.42      matthew   400: 
                    401: =pod
1.36      matthew   402: 
1.112     bowersj2  403: =item * linked_select_forms(...)
1.36      matthew   404: 
                    405: linked_select_forms returns a string containing a <script></script> block
                    406: and html for two <select> menus.  The select menus will be linked in that
                    407: changing the value of the first menu will result in new values being placed
                    408: in the second menu.  The values in the select menu will appear in alphabetical
                    409: order.
                    410: 
                    411: linked_select_forms takes the following ordered inputs:
                    412: 
                    413: =over 4
                    414: 
1.112     bowersj2  415: =item * $formname, the name of the <form> tag
1.36      matthew   416: 
1.112     bowersj2  417: =item * $middletext, the text which appears between the <select> tags
1.36      matthew   418: 
1.112     bowersj2  419: =item * $firstdefault, the default value for the first menu
1.36      matthew   420: 
1.112     bowersj2  421: =item * $firstselectname, the name of the first <select> tag
1.36      matthew   422: 
1.112     bowersj2  423: =item * $secondselectname, the name of the second <select> tag
1.36      matthew   424: 
1.112     bowersj2  425: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew   426: 
1.41      ng        427: =back 
                    428: 
1.36      matthew   429: Below is an example of such a hash.  Only the 'text', 'default', and 
                    430: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                    431: values for the first select menu.  The text that coincides with the 
1.41      ng        432: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew   433: and text for the second menu are given in the hash pointed to by 
                    434: $menu{$choice1}->{'select2'}.  
                    435: 
1.112     bowersj2  436:  my %menu = ( A1 => { text =>"Choice A1" ,
                    437:                        default => "B3",
                    438:                        select2 => { 
                    439:                            B1 => "Choice B1",
                    440:                            B2 => "Choice B2",
                    441:                            B3 => "Choice B3",
                    442:                            B4 => "Choice B4"
                    443:                            }
                    444:                    },
                    445:                A2 => { text =>"Choice A2" ,
                    446:                        default => "C2",
                    447:                        select2 => { 
                    448:                            C1 => "Choice C1",
                    449:                            C2 => "Choice C2",
                    450:                            C3 => "Choice C3"
                    451:                            }
                    452:                    },
                    453:                A3 => { text =>"Choice A3" ,
                    454:                        default => "D6",
                    455:                        select2 => { 
                    456:                            D1 => "Choice D1",
                    457:                            D2 => "Choice D2",
                    458:                            D3 => "Choice D3",
                    459:                            D4 => "Choice D4",
                    460:                            D5 => "Choice D5",
                    461:                            D6 => "Choice D6",
                    462:                            D7 => "Choice D7"
                    463:                            }
                    464:                    }
                    465:                );
1.36      matthew   466: 
                    467: =cut
                    468: 
                    469: sub linked_select_forms {
                    470:     my ($formname,
                    471:         $middletext,
                    472:         $firstdefault,
                    473:         $firstselectname,
                    474:         $secondselectname, 
                    475:         $hashref
                    476:         ) = @_;
                    477:     my $second = "document.$formname.$secondselectname";
                    478:     my $first = "document.$formname.$firstselectname";
                    479:     # output the javascript to do the changing
                    480:     my $result = '';
                    481:     $result.="<script>\n";
                    482:     $result.="var select2data = new Object();\n";
                    483:     $" = '","';
                    484:     my $debug = '';
                    485:     foreach my $s1 (sort(keys(%$hashref))) {
                    486:         $result.="select2data.d_$s1 = new Object();\n";        
                    487:         $result.="select2data.d_$s1.def = new String('".
                    488:             $hashref->{$s1}->{'default'}."');\n";
                    489:         $result.="select2data.d_$s1.values = new Array(";        
                    490:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
                    491:         $result.="\"@s2values\");\n";
                    492:         $result.="select2data.d_$s1.texts = new Array(";        
                    493:         my @s2texts;
                    494:         foreach my $value (@s2values) {
                    495:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
                    496:         }
                    497:         $result.="\"@s2texts\");\n";
                    498:     }
                    499:     $"=' ';
                    500:     $result.= <<"END";
                    501: 
                    502: function select1_changed() {
                    503:     // Determine new choice
                    504:     var newvalue = "d_" + $first.value;
                    505:     // update select2
                    506:     var values     = select2data[newvalue].values;
                    507:     var texts      = select2data[newvalue].texts;
                    508:     var select2def = select2data[newvalue].def;
                    509:     var i;
                    510:     // out with the old
                    511:     for (i = 0; i < $second.options.length; i++) {
                    512:         $second.options[i] = null;
                    513:     }
                    514:     // in with the nuclear
                    515:     for (i=0;i<values.length; i++) {
                    516:         $second.options[i] = new Option(values[i]);
                    517:         $second.options[i].text = texts[i];
                    518:         if (values[i] == select2def) {
                    519:             $second.options[i].selected = true;
                    520:         }
                    521:     }
                    522: }
                    523: </script>
                    524: END
                    525:     # output the initial values for the selection lists
                    526:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
                    527:     foreach my $value (sort(keys(%$hashref))) {
                    528:         $result.="    <option value=\"$value\" ";
                    529:         $result.=" selected=\"true\" " if ($value eq $firstdefault);
1.119     www       530:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew   531:     }
                    532:     $result .= "</select>\n";
                    533:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                    534:     $result .= $middletext;
                    535:     $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
                    536:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
                    537:     foreach my $value (sort(keys(%select2))) {
                    538:         $result.="    <option value=\"$value\" ";        
                    539:         $result.=" selected=\"true\" " if ($value eq $seconddefault);
1.119     www       540:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew   541:     }
                    542:     $result .= "</select>\n";
                    543:     #    return $debug;
                    544:     return $result;
                    545: }   #  end of sub linked_select_forms {
                    546: 
1.45      matthew   547: =pod
1.44      bowersj2  548: 
1.112     bowersj2  549: =item * help_open_topic($topic, $text, $stayOnPage, $width, $height)
1.44      bowersj2  550: 
1.112     bowersj2  551: Returns a string corresponding to an HTML link to the given help
                    552: $topic, where $topic corresponds to the name of a .tex file in
                    553: /home/httpd/html/adm/help/tex, with underscores replaced by
                    554: spaces. 
                    555: 
                    556: $text will optionally be linked to the same topic, allowing you to
                    557: link text in addition to the graphic. If you do not want to link
                    558: text, but wish to specify one of the later parameters, pass an
                    559: empty string. 
                    560: 
                    561: $stayOnPage is a value that will be interpreted as a boolean. If true,
                    562: the link will not open a new window. If false, the link will open
                    563: a new window using Javascript. (Default is false.) 
                    564: 
                    565: $width and $height are optional numerical parameters that will
                    566: override the width and height of the popped up window, which may
                    567: be useful for certain help topics with big pictures included. 
1.44      bowersj2  568: 
                    569: =cut
                    570: 
                    571: sub help_open_topic {
1.48      bowersj2  572:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
                    573:     $text = "" if (not defined $text);
1.44      bowersj2  574:     $stayOnPage = 0 if (not defined $stayOnPage);
1.108     bowersj2  575:     if ($ENV{'browser.interface'} eq 'textual' ||
                    576: 	$ENV{'environment.remote'} eq 'off' ) {
1.79      www       577: 	$stayOnPage=1;
                    578:     }
1.44      bowersj2  579:     $width = 350 if (not defined $width);
                    580:     $height = 400 if (not defined $height);
                    581:     my $filename = $topic;
                    582:     $filename =~ s/ /_/g;
                    583: 
1.48      bowersj2  584:     my $template = "";
                    585:     my $link;
1.44      bowersj2  586: 
                    587:     if (!$stayOnPage)
                    588:     {
1.72      bowersj2  589: 	$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  590:     }
                    591:     else
                    592:     {
1.48      bowersj2  593: 	$link = "/adm/help/${filename}.hlp";
                    594:     }
                    595: 
                    596:     # Add the text
                    597:     if ($text ne "")
                    598:     {
1.77      www       599: 	$template .= 
                    600:   "<table bgcolor='#3333AA' cellspacing='1' cellpadding='1' border='0'><tr>".
1.78      www       601:   "<td bgcolor='#5555FF'><a href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
1.48      bowersj2  602:     }
                    603: 
                    604:     # Add the graphic
                    605:     $template .= <<"ENDTEMPLATE";
1.77      www       606:  <a href="$link"><image src="/adm/help/gif/smallHelp.gif" border="0" alt="(Help: $topic)" /></a>
1.44      bowersj2  607: ENDTEMPLATE
1.78      www       608:     if ($text ne '') { $template.='</td></tr></table>' };
1.44      bowersj2  609:     return $template;
                    610: 
1.106     bowersj2  611: }
                    612: 
                    613: # This is a quicky function for Latex cheatsheet editing, since it 
                    614: # appears in at least four places
                    615: sub helpLatexCheatsheet {
                    616:     my $other = shift;
                    617:     my $addOther = '';
                    618:     if ($other) {
                    619: 	$addOther = Apache::loncommon::help_open_topic($other, shift,
                    620: 						       undef, undef, 600) .
                    621: 							   '</td><td>';
                    622:     }
                    623:     return '<table><tr><td>'.
                    624: 	$addOther .
                    625: 	&Apache::loncommon::help_open_topic("Greek_Symbols",'Greek Symbols',
                    626: 					    undef,undef,600)
                    627: 	.'</td><td>'.
                    628: 	&Apache::loncommon::help_open_topic("Other_Symbols",'Other Symbols',
                    629: 					    undef,undef,600)
                    630: 	.'</td></tr></table>';
1.44      bowersj2  631: }
1.37      matthew   632: 
1.45      matthew   633: =pod
                    634: 
1.112     bowersj2  635: =item * csv_translate($text) 
1.37      matthew   636: 
                    637: Translate $text to allow it to be output as a 'comma seperated values' 
                    638: format.
                    639: 
                    640: =cut
                    641: 
                    642: sub csv_translate {
                    643:     my $text = shift;
                    644:     $text =~ s/\"/\"\"/g;
                    645:     $text =~ s/\n//g;
                    646:     return $text;
                    647: }
1.113     bowersj2  648: 
                    649: =pod
                    650: 
                    651: =item * change_content_javascript():
                    652: 
                    653: This and the next function allow you to create small sections of an
                    654: otherwise static HTML page that you can update on the fly with
                    655: Javascript, even in Netscape 4.
                    656: 
                    657: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                    658: must be written to the HTML page once. It will prove the Javascript
                    659: function "change(name, content)". Calling the change function with the
                    660: name of the section 
                    661: you want to update, matching the name passed to C<changable_area>, and
                    662: the new content you want to put in there, will put the content into
                    663: that area.
                    664: 
                    665: B<Note>: Netscape 4 only reserves enough space for the changable area
                    666: to contain room for the original contents. You need to "make space"
                    667: for whatever changes you wish to make, and be B<sure> to check your
                    668: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                    669: it's adequate for updating a one-line status display, but little more.
                    670: This script will set the space to 100% width, so you only need to
                    671: worry about height in Netscape 4.
                    672: 
                    673: Modern browsers are much less limiting, and if you can commit to the
                    674: user not using Netscape 4, this feature may be used freely with
                    675: pretty much any HTML.
                    676: 
                    677: =cut
                    678: 
                    679: sub change_content_javascript {
                    680:     # If we're on Netscape 4, we need to use Layer-based code
                    681:     if ($ENV{'browser.type'} eq 'netscape' &&
                    682: 	$ENV{'browser.version'} =~ /^4\./) {
                    683: 	return (<<NETSCAPE4);
                    684: 	function change(name, content) {
                    685: 	    doc = document.layers[name+"___escape"].layers[0].document;
                    686: 	    doc.open();
                    687: 	    doc.write(content);
                    688: 	    doc.close();
                    689: 	}
                    690: NETSCAPE4
                    691:     } else {
                    692: 	# Otherwise, we need to use semi-standards-compliant code
                    693: 	# (technically, "innerHTML" isn't standard but the equivalent
                    694: 	# is really scary, and every useful browser supports it
                    695: 	return (<<DOMBASED);
                    696: 	function change(name, content) {
                    697: 	    element = document.getElementById(name);
                    698: 	    element.innerHTML = content;
                    699: 	}
                    700: DOMBASED
                    701:     }
                    702: }
                    703: 
                    704: =pod
                    705: 
                    706: =item * changable_area($name, $origContent):
                    707: 
                    708: This provides a "changable area" that can be modified on the fly via
                    709: the Javascript code provided in C<change_content_javascript>. $name is
                    710: the name you will use to reference the area later; do not repeat the
                    711: same name on a given HTML page more then once. $origContent is what
                    712: the area will originally contain, which can be left blank.
                    713: 
                    714: =cut
                    715: 
                    716: sub changable_area {
                    717:     my ($name, $origContent) = @_;
                    718: 
                    719:     if ($ENV{'browser.type'} eq 'netscape' &&
                    720: 	$ENV{'browser.version'} =~ /^4\./) {
                    721: 	# If this is netscape 4, we need to use the Layer tag
                    722: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                    723:     } else {
                    724: 	return "<span id='$name'>$origContent</span>";
                    725:     }
                    726: }
                    727: 
                    728: =pod
                    729: 
                    730: =back
                    731: 
                    732: =cut
1.37      matthew   733: 
                    734: ###############################################################
1.33      matthew   735: ##        Home server <option> list generating code          ##
                    736: ###############################################################
1.35      matthew   737: 
1.45      matthew   738: =pod
                    739: 
1.112     bowersj2  740: =head1 Home Server option list generating code
                    741: 
                    742: =over 4
                    743: 
                    744: =item * get_domains()
1.35      matthew   745: 
                    746: Returns an array containing each of the domains listed in the hosts.tab
                    747: file.
                    748: 
                    749: =cut
                    750: 
                    751: #-------------------------------------------
1.34      matthew   752: sub get_domains {
                    753:     # The code below was stolen from "The Perl Cookbook", p 102, 1st ed.
                    754:     my @domains;
                    755:     my %seen;
                    756:     foreach (sort values(%Apache::lonnet::hostdom)) {
                    757:         push (@domains,$_) unless $seen{$_}++;
                    758:     }
                    759:     return @domains;
                    760: }
1.88      www       761: 
                    762: #-------------------------------------------
                    763: 
                    764: =pod
                    765: 
1.112     bowersj2  766: =item * select_form($defdom,$name,%hash)
1.88      www       767: 
                    768: Returns a string containing a <select name='$name' size='1'> form to 
                    769: allow a user to select options from a hash option_name => displayed text.  
                    770: See lonrights.pm for an example invocation and use.
                    771: 
                    772: =cut
                    773: 
                    774: #-------------------------------------------
                    775: sub select_form {
                    776:     my ($def,$name,%hash) = @_;
                    777:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
1.128   ! albertel  778:     my @keys;
        !           779:     if (exists($hash{'select_form_order'})) {
        !           780: 	@keys=@{$hash{'select_form_order'}};
        !           781:     } else {
        !           782: 	@keys=sort(keys(%hash));
        !           783:     }
        !           784:     foreach (@keys) {
1.88      www       785:         $selectform.="<option value=\"$_\" ".
                    786:             ($_ eq $def ? 'selected' : '').
1.119     www       787:                 ">".&mt($hash{$_})."</option>\n";
1.88      www       788:     }
                    789:     $selectform.="</select>";
                    790:     return $selectform;
                    791: }
                    792: 
1.34      matthew   793: 
1.35      matthew   794: #-------------------------------------------
                    795: 
1.45      matthew   796: =pod
                    797: 
1.112     bowersj2  798: =item * select_dom_form($defdom,$name,$includeempty)
1.35      matthew   799: 
                    800: Returns a string containing a <select name='$name' size='1'> form to 
                    801: allow a user to select the domain to preform an operation in.  
                    802: See loncreateuser.pm for an example invocation and use.
                    803: 
1.90      www       804: If the $includeempty flag is set, it also includes an empty choice ("no domain
                    805: selected");
                    806: 
1.35      matthew   807: =cut
                    808: 
                    809: #-------------------------------------------
1.34      matthew   810: sub select_dom_form {
1.90      www       811:     my ($defdom,$name,$includeempty) = @_;
1.34      matthew   812:     my @domains = get_domains();
1.90      www       813:     if ($includeempty) { @domains=('',@domains); }
1.34      matthew   814:     my $selectdomain = "<select name=\"$name\" size=\"1\">\n";
                    815:     foreach (@domains) {
                    816:         $selectdomain.="<option value=\"$_\" ".
                    817:             ($_ eq $defdom ? 'selected' : '').
                    818:                 ">$_</option>\n";
                    819:     }
                    820:     $selectdomain.="</select>";
                    821:     return $selectdomain;
                    822: }
                    823: 
1.35      matthew   824: #-------------------------------------------
                    825: 
1.45      matthew   826: =pod
                    827: 
1.112     bowersj2  828: =item * get_library_servers($domain)
1.35      matthew   829: 
                    830: Returns a hash which contains keys like '103l3' and values like 
                    831: 'kirk.lite.msu.edu'.  All of the keys will be for machines in the
                    832: given $domain.
                    833: 
                    834: =cut
                    835: 
                    836: #-------------------------------------------
1.52      matthew   837: sub get_library_servers {
1.33      matthew   838:     my $domain = shift;
1.52      matthew   839:     my %library_servers;
1.33      matthew   840:     foreach (keys(%Apache::lonnet::libserv)) {
                    841:         if ($Apache::lonnet::hostdom{$_} eq $domain) {
1.52      matthew   842:             $library_servers{$_} = $Apache::lonnet::hostname{$_};
1.33      matthew   843:         }
                    844:     }
1.52      matthew   845:     return %library_servers;
1.33      matthew   846: }
                    847: 
1.35      matthew   848: #-------------------------------------------
                    849: 
1.45      matthew   850: =pod
                    851: 
1.112     bowersj2  852: =item * home_server_option_list($domain)
1.35      matthew   853: 
                    854: returns a string which contains an <option> list to be used in a 
                    855: <select> form input.  See loncreateuser.pm for an example.
                    856: 
                    857: =cut
                    858: 
                    859: #-------------------------------------------
1.33      matthew   860: sub home_server_option_list {
                    861:     my $domain = shift;
1.52      matthew   862:     my %servers = &get_library_servers($domain);
1.33      matthew   863:     my $result = '';
                    864:     foreach (sort keys(%servers)) {
                    865:         $result.=
                    866:             '<option value="'.$_.'">'.$_.' '.$servers{$_}."</option>\n";
                    867:     }
                    868:     return $result;
                    869: }
1.112     bowersj2  870: 
                    871: =pod
                    872: 
                    873: =back
                    874: 
                    875: =cut
1.87      matthew   876: 
                    877: ###############################################################
1.112     bowersj2  878: ##                  Decoding User Agent                      ##
1.87      matthew   879: ###############################################################
                    880: 
                    881: =pod
                    882: 
1.112     bowersj2  883: =head1 Decoding the User Agent
                    884: 
                    885: =over 4
                    886: 
                    887: =item * &decode_user_agent()
1.87      matthew   888: 
                    889: Inputs: $r
                    890: 
                    891: Outputs:
                    892: 
                    893: =over 4
                    894: 
1.112     bowersj2  895: =item * $httpbrowser
1.87      matthew   896: 
1.112     bowersj2  897: =item * $clientbrowser
1.87      matthew   898: 
1.112     bowersj2  899: =item * $clientversion
1.87      matthew   900: 
1.112     bowersj2  901: =item * $clientmathml
1.87      matthew   902: 
1.112     bowersj2  903: =item * $clientunicode
1.87      matthew   904: 
1.112     bowersj2  905: =item * $clientos
1.87      matthew   906: 
                    907: =back
                    908: 
                    909: =cut
                    910: 
                    911: ###############################################################
                    912: ###############################################################
                    913: sub decode_user_agent {
                    914:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                    915:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                    916:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
                    917:     my $clientbrowser='unknown';
                    918:     my $clientversion='0';
                    919:     my $clientmathml='';
                    920:     my $clientunicode='0';
                    921:     for (my $i=0;$i<=$#browsertype;$i++) {
                    922:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
                    923: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                    924: 	    $clientbrowser=$bname;
                    925:             $httpbrowser=~/$vreg/i;
                    926: 	    $clientversion=$1;
                    927:             $clientmathml=($clientversion>=$minv);
                    928:             $clientunicode=($clientversion>=$univ);
                    929: 	}
                    930:     }
                    931:     my $clientos='unknown';
                    932:     if (($httpbrowser=~/linux/i) ||
                    933:         ($httpbrowser=~/unix/i) ||
                    934:         ($httpbrowser=~/ux/i) ||
                    935:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                    936:     if (($httpbrowser=~/vax/i) ||
                    937:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                    938:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                    939:     if (($httpbrowser=~/mac/i) ||
                    940:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
                    941:     if ($httpbrowser=~/win/i) { $clientos='win'; }
                    942:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
                    943:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
                    944:             $clientunicode,$clientos,);
                    945: }
                    946: 
1.112     bowersj2  947: =pod
                    948: 
                    949: =back
1.87      matthew   950: 
1.112     bowersj2  951: =cut
1.32      matthew   952: 
                    953: ###############################################################
                    954: ##    Authentication changing form generation subroutines    ##
                    955: ###############################################################
                    956: ##
                    957: ## All of the authform_xxxxxxx subroutines take their inputs in a
                    958: ## hash, and have reasonable default values.
                    959: ##
                    960: ##    formname = the name given in the <form> tag.
1.35      matthew   961: #-------------------------------------------
                    962: 
1.45      matthew   963: =pod
                    964: 
1.112     bowersj2  965: =head1 Authentication Routines
                    966: 
                    967: =over 4
                    968: 
                    969: =item * authform_xxxxxx
1.35      matthew   970: 
                    971: The authform_xxxxxx subroutines provide javascript and html forms which 
                    972: handle some of the conveniences required for authentication forms.  
                    973: This is not an optimal method, but it works.  
                    974: 
                    975: See loncreateuser.pm for invocation and use examples.
                    976: 
                    977: =over 4
                    978: 
1.112     bowersj2  979: =item * authform_header
1.35      matthew   980: 
1.112     bowersj2  981: =item * authform_authorwarning
1.35      matthew   982: 
1.112     bowersj2  983: =item * authform_nochange
1.35      matthew   984: 
1.112     bowersj2  985: =item * authform_kerberos
1.35      matthew   986: 
1.112     bowersj2  987: =item * authform_internal
1.35      matthew   988: 
1.112     bowersj2  989: =item * authform_filesystem
1.35      matthew   990: 
                    991: =back
                    992: 
                    993: =cut
                    994: 
                    995: #-------------------------------------------
1.32      matthew   996: sub authform_header{  
                    997:     my %in = (
                    998:         formname => 'cu',
1.80      albertel  999:         kerb_def_dom => '',
1.32      matthew  1000:         @_,
                   1001:     );
                   1002:     $in{'formname'} = 'document.' . $in{'formname'};
                   1003:     my $result='';
1.80      albertel 1004: 
                   1005: #---------------------------------------------- Code for upper case translation
                   1006:     my $Javascript_toUpperCase;
                   1007:     unless ($in{kerb_def_dom}) {
                   1008:         $Javascript_toUpperCase =<<"END";
                   1009:         switch (choice) {
                   1010:            case 'krb': currentform.elements[choicearg].value =
                   1011:                currentform.elements[choicearg].value.toUpperCase();
                   1012:                break;
                   1013:            default:
                   1014:         }
                   1015: END
                   1016:     } else {
                   1017:         $Javascript_toUpperCase = "";
                   1018:     }
                   1019: 
1.32      matthew  1020:     $result.=<<"END";
                   1021: var current = new Object();
                   1022: current.radiovalue = 'nochange';
                   1023: current.argfield = null;
                   1024: 
                   1025: function changed_radio(choice,currentform) {
                   1026:     var choicearg = choice + 'arg';
                   1027:     // If a radio button in changed, we need to change the argfield
                   1028:     if (current.radiovalue != choice) {
                   1029:         current.radiovalue = choice;
                   1030:         if (current.argfield != null) {
                   1031:             currentform.elements[current.argfield].value = '';
                   1032:         }
                   1033:         if (choice == 'nochange') {
                   1034:             current.argfield = null;
                   1035:         } else {
                   1036:             current.argfield = choicearg;
                   1037:             switch(choice) {
                   1038:                 case 'krb': 
                   1039:                     currentform.elements[current.argfield].value = 
                   1040:                         "$in{'kerb_def_dom'}";
                   1041:                 break;
                   1042:               default:
                   1043:                 break;
                   1044:             }
                   1045:         }
                   1046:     }
                   1047:     return;
                   1048: }
1.22      www      1049: 
1.32      matthew  1050: function changed_text(choice,currentform) {
                   1051:     var choicearg = choice + 'arg';
                   1052:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 1053:         $Javascript_toUpperCase
1.32      matthew  1054:         // clear old field
                   1055:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   1056:             currentform.elements[current.argfield].value = '';
                   1057:         }
                   1058:         current.argfield = choicearg;
                   1059:     }
                   1060:     set_auth_radio_buttons(choice,currentform);
                   1061:     return;
1.20      www      1062: }
1.32      matthew  1063: 
                   1064: function set_auth_radio_buttons(newvalue,currentform) {
                   1065:     var i=0;
                   1066:     while (i < currentform.login.length) {
                   1067:         if (currentform.login[i].value == newvalue) { break; }
                   1068:         i++;
                   1069:     }
                   1070:     if (i == currentform.login.length) {
                   1071:         return;
                   1072:     }
                   1073:     current.radiovalue = newvalue;
                   1074:     currentform.login[i].checked = true;
                   1075:     return;
                   1076: }
                   1077: END
                   1078:     return $result;
                   1079: }
                   1080: 
                   1081: sub authform_authorwarning{
                   1082:     my $result='';
                   1083:     $result=<<"END";
                   1084: <i>As a general rule, only authors or co-authors should be filesystem
                   1085: authenticated (which allows access to the server filesystem).</i>
                   1086: END
                   1087:     return $result;
                   1088: }
                   1089: 
                   1090: sub authform_nochange{  
                   1091:     my %in = (
                   1092:               formname => 'document.cu',
                   1093:               kerb_def_dom => 'MSU.EDU',
                   1094:               @_,
                   1095:           );
                   1096:     my $result='';
                   1097:     $result.=<<"END";
                   1098: <input type="radio" name="login" value="nochange" checked="checked"
1.57      albertel 1099:        onclick="javascript:changed_radio('nochange',$in{'formname'});" />
1.32      matthew  1100: Do not change login data
                   1101: END
                   1102:     return $result;
                   1103: }
                   1104: 
                   1105: sub authform_kerberos{  
                   1106:     my %in = (
                   1107:               formname => 'document.cu',
                   1108:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 1109:               kerb_def_auth => 'krb4',
1.32      matthew  1110:               @_,
                   1111:               );
                   1112:     my $result='';
1.80      albertel 1113:     my $check4;
                   1114:     my $check5;
                   1115:     if ($in{'kerb_def_auth'} eq 'krb5') {
                   1116:        $check5 = " checked=\"on\"";
                   1117:     } else {
                   1118:        $check4 = " checked=\"on\"";
                   1119:     }
1.32      matthew  1120:     $result.=<<"END";
                   1121: <input type="radio" name="login" value="krb" 
                   1122:        onclick="javascript:changed_radio('krb',$in{'formname'});"
1.57      albertel 1123:        onchange="javascript:changed_radio('krb',$in{'formname'});" />
1.32      matthew  1124: Kerberos authenticated with domain
1.80      albertel 1125: <input type="text" size="10" name="krbarg" value="$in{'kerb_def_dom'}"
1.57      albertel 1126:        onchange="javascript:changed_text('krb',$in{'formname'});" />
1.80      albertel 1127: <input type="radio" name="krbver" value="4" $check4 />Version 4
                   1128: <input type="radio" name="krbver" value="5" $check5 />Version 5
1.32      matthew  1129: END
                   1130:     return $result;
                   1131: }
                   1132: 
                   1133: sub authform_internal{  
                   1134:     my %args = (
                   1135:                 formname => 'document.cu',
                   1136:                 kerb_def_dom => 'MSU.EDU',
                   1137:                 @_,
                   1138:                 );
                   1139:     my $result='';
                   1140:     $result.=<<"END";
                   1141: <input type="radio" name="login" value="int"
                   1142:        onchange="javascript:changed_radio('int',$args{'formname'});"
1.57      albertel 1143:        onclick="javascript:changed_radio('int',$args{'formname'});" />
1.32      matthew  1144: Internally authenticated (with initial password 
                   1145: <input type="text" size="10" name="intarg" value=""
1.75      www      1146:        onchange="javascript:changed_text('int',$args{'formname'});" />)
1.32      matthew  1147: END
                   1148:     return $result;
                   1149: }
                   1150: 
                   1151: sub authform_local{  
                   1152:     my %in = (
                   1153:               formname => 'document.cu',
                   1154:               kerb_def_dom => 'MSU.EDU',
                   1155:               @_,
                   1156:               );
                   1157:     my $result='';
                   1158:     $result.=<<"END";
                   1159: <input type="radio" name="login" value="loc"
                   1160:        onchange="javascript:changed_radio('loc',$in{'formname'});"
1.57      albertel 1161:        onclick="javascript:changed_radio('loc',$in{'formname'});" />
1.32      matthew  1162: Local Authentication with argument
                   1163: <input type="text" size="10" name="locarg" value=""
1.57      albertel 1164:        onchange="javascript:changed_text('loc',$in{'formname'});" />
1.32      matthew  1165: END
                   1166:     return $result;
                   1167: }
                   1168: 
                   1169: sub authform_filesystem{  
                   1170:     my %in = (
                   1171:               formname => 'document.cu',
                   1172:               kerb_def_dom => 'MSU.EDU',
                   1173:               @_,
                   1174:               );
                   1175:     my $result='';
                   1176:     $result.=<<"END";
                   1177: <input type="radio" name="login" value="fsys" 
                   1178:        onchange="javascript:changed_radio('fsys',$in{'formname'});"
1.57      albertel 1179:        onclick="javascript:changed_radio('fsys',$in{'formname'});" />
1.32      matthew  1180: Filesystem authenticated (with initial password 
                   1181: <input type="text" size="10" name="fsysarg" value=""
1.75      www      1182:        onchange="javascript:changed_text('fsys',$in{'formname'});">)
1.32      matthew  1183: END
                   1184:     return $result;
                   1185: }
                   1186: 
1.112     bowersj2 1187: =pod
                   1188: 
                   1189: =back
                   1190: 
                   1191: =cut
1.80      albertel 1192: 
                   1193: ###############################################################
                   1194: ##    Get Authentication Defaults for Domain                 ##
                   1195: ###############################################################
                   1196: 
                   1197: =pod
                   1198: 
1.112     bowersj2 1199: =head1 Domains and Authentication
                   1200: 
                   1201: Returns default authentication type and an associated argument as
                   1202: listed in file 'domain.tab'.
                   1203: 
                   1204: =over 4
                   1205: 
                   1206: =item * get_auth_defaults
1.80      albertel 1207: 
                   1208: get_auth_defaults($target_domain) returns the default authentication
                   1209: type and an associated argument (initial password or a kerberos domain).
                   1210: These values are stored in lonTabs/domain.tab
                   1211: 
                   1212: ($def_auth, $def_arg) = &get_auth_defaults($target_domain);
                   1213: 
                   1214: If target_domain is not found in domain.tab, returns nothing ('').
                   1215: 
                   1216: =cut
                   1217: 
                   1218: #-------------------------------------------
                   1219: sub get_auth_defaults {
                   1220:     my $domain=shift;
                   1221:     return ($Apache::lonnet::domain_auth_def{$domain},$Apache::lonnet::domain_auth_arg_def{$domain});
                   1222: }
                   1223: ###############################################################
                   1224: ##   End Get Authentication Defaults for Domain              ##
                   1225: ###############################################################
                   1226: 
                   1227: ###############################################################
                   1228: ##    Get Kerberos Defaults for Domain                 ##
                   1229: ###############################################################
                   1230: ##
                   1231: ## Returns default kerberos version and an associated argument
                   1232: ## as listed in file domain.tab. If not listed, provides
                   1233: ## appropriate default domain and kerberos version.
                   1234: ##
                   1235: #-------------------------------------------
                   1236: 
                   1237: =pod
                   1238: 
1.112     bowersj2 1239: =item * get_kerberos_defaults
1.80      albertel 1240: 
                   1241: get_kerberos_defaults($target_domain) returns the default kerberos
                   1242: version and domain. If not found in domain.tabs, it defaults to
                   1243: version 4 and the domain of the server.
                   1244: 
                   1245: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   1246: 
                   1247: =cut
                   1248: 
                   1249: #-------------------------------------------
                   1250: sub get_kerberos_defaults {
                   1251:     my $domain=shift;
                   1252:     my ($krbdef,$krbdefdom) =
                   1253:         &Apache::loncommon::get_auth_defaults($domain);
                   1254:     unless ($krbdef =~/^krb/ && $krbdefdom) {
                   1255:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   1256:         my $krbdefdom=$1;
                   1257:         $krbdefdom=~tr/a-z/A-Z/;
                   1258:         $krbdef = "krb4";
                   1259:     }
                   1260:     return ($krbdef,$krbdefdom);
                   1261: }
1.112     bowersj2 1262: 
                   1263: =pod
                   1264: 
                   1265: =back
                   1266: 
                   1267: =cut
1.32      matthew  1268: 
1.46      matthew  1269: ###############################################################
                   1270: ##                Thesaurus Functions                        ##
                   1271: ###############################################################
1.20      www      1272: 
1.46      matthew  1273: =pod
1.20      www      1274: 
1.112     bowersj2 1275: =head1 Thesaurus Functions
                   1276: 
                   1277: =over 4
                   1278: 
                   1279: =item * initialize_keywords
1.46      matthew  1280: 
                   1281: Initializes the package variable %Keywords if it is empty.  Uses the
                   1282: package variable $thesaurus_db_file.
                   1283: 
                   1284: =cut
                   1285: 
                   1286: ###################################################
                   1287: 
                   1288: sub initialize_keywords {
                   1289:     return 1 if (scalar keys(%Keywords));
                   1290:     # If we are here, %Keywords is empty, so fill it up
                   1291:     #   Make sure the file we need exists...
                   1292:     if (! -e $thesaurus_db_file) {
                   1293:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   1294:                                  " failed because it does not exist");
                   1295:         return 0;
                   1296:     }
                   1297:     #   Set up the hash as a database
                   1298:     my %thesaurus_db;
                   1299:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 1300:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  1301:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   1302:                                  $thesaurus_db_file);
                   1303:         return 0;
                   1304:     } 
                   1305:     #  Get the average number of appearances of a word.
                   1306:     my $avecount = $thesaurus_db{'average.count'};
                   1307:     #  Put keywords (those that appear > average) into %Keywords
                   1308:     while (my ($word,$data)=each (%thesaurus_db)) {
                   1309:         my ($count,undef) = split /:/,$data;
                   1310:         $Keywords{$word}++ if ($count > $avecount);
                   1311:     }
                   1312:     untie %thesaurus_db;
                   1313:     # Remove special values from %Keywords.
                   1314:     foreach ('total.count','average.count') {
                   1315:         delete($Keywords{$_}) if (exists($Keywords{$_}));
                   1316:     }
                   1317:     return 1;
                   1318: }
                   1319: 
                   1320: ###################################################
                   1321: 
                   1322: =pod
                   1323: 
1.112     bowersj2 1324: =item * keyword($word)
1.46      matthew  1325: 
                   1326: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   1327: than the average number of times in the thesaurus database.  Calls 
                   1328: &initialize_keywords
                   1329: 
                   1330: =cut
                   1331: 
                   1332: ###################################################
1.20      www      1333: 
                   1334: sub keyword {
1.46      matthew  1335:     return if (!&initialize_keywords());
                   1336:     my $word=lc(shift());
                   1337:     $word=~s/\W//g;
                   1338:     return exists($Keywords{$word});
1.20      www      1339: }
1.46      matthew  1340: 
                   1341: ###############################################################
                   1342: 
                   1343: =pod 
1.20      www      1344: 
1.112     bowersj2 1345: =item * get_related_words
1.46      matthew  1346: 
                   1347: Look up a word in the thesaurus.  Takes a scalar arguement and returns
                   1348: an array of words.  If the keyword is not in the thesaurus, an empty array
                   1349: will be returned.  The order of the words returned is determined by the
                   1350: database which holds them.
                   1351: 
                   1352: Uses global $thesaurus_db_file.
                   1353: 
                   1354: =cut
                   1355: 
                   1356: ###############################################################
                   1357: sub get_related_words {
                   1358:     my $keyword = shift;
                   1359:     my %thesaurus_db;
                   1360:     if (! -e $thesaurus_db_file) {
                   1361:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   1362:                                  "failed because the file does not exist");
                   1363:         return ();
                   1364:     }
                   1365:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 1366:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  1367:         return ();
                   1368:     } 
                   1369:     my @Words=();
                   1370:     if (exists($thesaurus_db{$keyword})) {
                   1371:         $_ = $thesaurus_db{$keyword};
                   1372:         (undef,@Words) = split/:/;  # The first element is the number of times
                   1373:                                     # the word appears.  We do not need it now.
                   1374:         for (my $i=0;$i<=$#Words;$i++) {
                   1375:             ($Words[$i],undef)= split/\,/,$Words[$i];
1.20      www      1376:         }
                   1377:     }
1.46      matthew  1378:     untie %thesaurus_db;
                   1379:     return @Words;
1.14      harris41 1380: }
1.46      matthew  1381: 
1.112     bowersj2 1382: =pod
                   1383: 
                   1384: =back
                   1385: 
                   1386: =cut
1.61      www      1387: 
                   1388: # -------------------------------------------------------------- Plaintext name
1.81      albertel 1389: =pod
                   1390: 
1.112     bowersj2 1391: =head1 User Name Functions
                   1392: 
                   1393: =over 4
                   1394: 
                   1395: =item * plainname($uname,$udom)
1.81      albertel 1396: 
1.112     bowersj2 1397: Takes a users logon name and returns it as a string in
                   1398: "first middle last generation" form
1.81      albertel 1399: 
                   1400: =cut
1.61      www      1401: 
1.81      albertel 1402: ###############################################################
1.61      www      1403: sub plainname {
                   1404:     my ($uname,$udom)=@_;
                   1405:     my %names=&Apache::lonnet::get('environment',
                   1406:                     ['firstname','middlename','lastname','generation'],
                   1407: 					 $udom,$uname);
1.62      www      1408:     my $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
1.61      www      1409: 	$names{'lastname'}.' '.$names{'generation'};
1.62      www      1410:     $name=~s/\s+$//;
                   1411:     $name=~s/\s+/ /g;
                   1412:     return $name;
1.61      www      1413: }
1.66      www      1414: 
                   1415: # -------------------------------------------------------------------- Nickname
1.81      albertel 1416: =pod
                   1417: 
1.112     bowersj2 1418: =item * nickname($uname,$udom)
1.81      albertel 1419: 
                   1420: Gets a users name and returns it as a string as
                   1421: 
                   1422: "&quot;nickname&quot;"
1.66      www      1423: 
1.81      albertel 1424: if the user has a nickname or
                   1425: 
                   1426: "first middle last generation"
                   1427: 
                   1428: if the user does not
                   1429: 
                   1430: =cut
1.66      www      1431: 
                   1432: sub nickname {
                   1433:     my ($uname,$udom)=@_;
                   1434:     my %names=&Apache::lonnet::get('environment',
                   1435:   ['nickname','firstname','middlename','lastname','generation'],$udom,$uname);
1.68      albertel 1436:     my $name=$names{'nickname'};
1.66      www      1437:     if ($name) {
                   1438:        $name='&quot;'.$name.'&quot;'; 
                   1439:     } else {
                   1440:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   1441: 	     $names{'lastname'}.' '.$names{'generation'};
                   1442:        $name=~s/\s+$//;
                   1443:        $name=~s/\s+/ /g;
                   1444:     }
                   1445:     return $name;
                   1446: }
                   1447: 
1.61      www      1448: 
                   1449: # ------------------------------------------------------------------ Screenname
1.81      albertel 1450: 
                   1451: =pod
                   1452: 
1.112     bowersj2 1453: =item * screenname($uname,$udom)
1.81      albertel 1454: 
                   1455: Gets a users screenname and returns it as a string
                   1456: 
                   1457: =cut
1.61      www      1458: 
                   1459: sub screenname {
                   1460:     my ($uname,$udom)=@_;
                   1461:     my %names=
                   1462:  &Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 1463:     return $names{'screenname'};
1.62      www      1464: }
                   1465: 
                   1466: # ------------------------------------------------------------- Message Wrapper
                   1467: 
                   1468: sub messagewrapper {
                   1469:     my ($link,$un,$do)=@_;
                   1470:     return 
                   1471: "<a href='/adm/email?compose=individual&recname=$un&recdom=$do'>$link</a>";
1.74      www      1472: }
                   1473: # --------------------------------------------------------------- Notes Wrapper
                   1474: 
                   1475: sub noteswrapper {
                   1476:     my ($link,$un,$do)=@_;
                   1477:     return 
                   1478: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
1.62      www      1479: }
                   1480: # ------------------------------------------------------------- Aboutme Wrapper
                   1481: 
                   1482: sub aboutmewrapper {
1.69      matthew  1483:     my ($link,$username,$domain)=@_;
                   1484:     return "<a href='/adm/$domain/$username/aboutme'>$link</a>";
1.62      www      1485: }
                   1486: 
                   1487: # ------------------------------------------------------------ Syllabus Wrapper
                   1488: 
                   1489: 
                   1490: sub syllabuswrapper {
1.109     matthew  1491:     my ($linktext,$coursedir,$domain,$fontcolor)=@_;
                   1492:     if ($fontcolor) { 
                   1493:         $linktext='<font color="'.$fontcolor.'">'.$linktext.'</font>'; 
                   1494:     }
                   1495:     return "<a href='/public/$domain/$coursedir/syllabus'>$linktext</a>";
1.61      www      1496: }
1.14      harris41 1497: 
1.112     bowersj2 1498: =pod
                   1499: 
                   1500: =back
                   1501: 
                   1502: =head1 Access .tab File Data
                   1503: 
                   1504: =over 4
                   1505: 
                   1506: =item * languageids() 
                   1507: 
                   1508: returns list of all language ids
                   1509: 
                   1510: =cut
                   1511: 
1.14      harris41 1512: sub languageids {
1.16      harris41 1513:     return sort(keys(%language));
1.14      harris41 1514: }
                   1515: 
1.112     bowersj2 1516: =pod
                   1517: 
                   1518: =item * languagedescription() 
                   1519: 
                   1520: returns description of a specified language id
                   1521: 
                   1522: =cut
                   1523: 
1.14      harris41 1524: sub languagedescription {
1.125     www      1525:     my $code=shift;
                   1526:     return  ($supported_language{$code}?'* ':'').
                   1527:             $language{$code}.
1.126     www      1528: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.97      www      1529: }
                   1530: 
1.112     bowersj2 1531: =pod
                   1532: 
                   1533: =item * copyrightids() 
                   1534: 
                   1535: returns list of all copyrights
                   1536: 
                   1537: =cut
                   1538: 
                   1539: sub copyrightids {
                   1540:     return sort(keys(%cprtag));
                   1541: }
                   1542: 
                   1543: =pod
                   1544: 
                   1545: =item * copyrightdescription() 
                   1546: 
                   1547: returns description of a specified copyright id
                   1548: 
                   1549: =cut
                   1550: 
                   1551: sub copyrightdescription {
                   1552:     return $cprtag{shift(@_)};
                   1553: }
                   1554: 
                   1555: =pod
                   1556: 
                   1557: =item * filecategories() 
                   1558: 
                   1559: returns list of all file categories
                   1560: 
                   1561: =cut
                   1562: 
                   1563: sub filecategories {
                   1564:     return sort(keys(%category_extensions));
                   1565: }
                   1566: 
                   1567: =pod
                   1568: 
                   1569: =item * filecategorytypes() 
                   1570: 
                   1571: returns list of file types belonging to a given file
                   1572: category
                   1573: 
                   1574: =cut
                   1575: 
                   1576: sub filecategorytypes {
                   1577:     return @{$category_extensions{lc($_[0])}};
                   1578: }
                   1579: 
                   1580: =pod
                   1581: 
                   1582: =item * fileembstyle() 
                   1583: 
                   1584: returns embedding style for a specified file type
                   1585: 
                   1586: =cut
                   1587: 
                   1588: sub fileembstyle {
                   1589:     return $fe{lc(shift(@_))};
                   1590: }
                   1591: 
                   1592: =pod
                   1593: 
                   1594: =item * filedescription() 
                   1595: 
                   1596: returns description for a specified file type
                   1597: 
                   1598: =cut
                   1599: 
                   1600: sub filedescription {
                   1601:     return $fd{lc(shift(@_))};
                   1602: }
                   1603: 
                   1604: =pod
                   1605: 
                   1606: =item * filedescriptionex() 
                   1607: 
                   1608: returns description for a specified file type with
                   1609: extra formatting
                   1610: 
                   1611: =cut
                   1612: 
                   1613: sub filedescriptionex {
                   1614:     my $ex=shift;
                   1615:     return '.'.$ex.' '.$fd{lc($ex)};
                   1616: }
                   1617: 
                   1618: # End of .tab access
                   1619: =pod
                   1620: 
                   1621: =back
                   1622: 
                   1623: =cut
                   1624: 
                   1625: # ------------------------------------------------------------------ File Types
                   1626: sub fileextensions {
                   1627:     return sort(keys(%fe));
                   1628: }
                   1629: 
1.97      www      1630: # ----------------------------------------------------------- Display Languages
                   1631: # returns a hash with all desired display languages
                   1632: #
                   1633: 
                   1634: sub display_languages {
                   1635:     my %languages=();
1.118     www      1636:     foreach (&preferred_languages()) {
                   1637: 	$languages{$_}=1;
1.97      www      1638:     }
                   1639:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
                   1640:     if ($ENV{'form.displaylanguage'}) {
                   1641: 	foreach (split(/\s*(\,|\;|\:)\s*/,$ENV{'form.displaylanguage'})) {
                   1642: 	    $languages{$_}=1;
                   1643:         }
                   1644:     }
                   1645:     return %languages;
1.14      harris41 1646: }
                   1647: 
1.117     www      1648: sub preferred_languages {
                   1649:     my @languages=();
                   1650:     if ($ENV{'environment.languages'}) {
                   1651: 	@languages=split(/\s*(\,|\;|\:)\s*/,$ENV{'environment.languages'});
                   1652:     }
                   1653:     if ($ENV{'course.'.$ENV{'request.course.id'}.'.languages'}) {
                   1654: 	@languages=(@languages,split(/\s*(\,|\;|\:)\s*/,
                   1655: 	         $ENV{'course.'.$ENV{'request.course.id'}.'.languages'}));
                   1656:     }
1.118     www      1657:     my $browser=(split(/\;/,$ENV{'HTTP_ACCEPT_LANGUAGE'}))[0];
                   1658:     if ($browser) {
                   1659: 	@languages=(@languages,split(/\s*(\,|\;|\:)\s*/,$browser));
                   1660:     }
                   1661:     if ($Apache::lonnet::domain_lang_def{$ENV{'user.domain'}}) {
                   1662: 	@languages=(@languages,
                   1663: 		$Apache::lonnet::domain_lang_def{$ENV{'user.domain'}});
                   1664:     }
                   1665:     if ($Apache::lonnet::domain_lang_def{$ENV{'request.role.domain'}}) {
                   1666: 	@languages=(@languages,
                   1667: 		$Apache::lonnet::domain_lang_def{$ENV{'request.role.domain'}});
                   1668:     }
                   1669:     if ($Apache::lonnet::domain_lang_def{
                   1670: 	                          $Apache::lonnet::perlvar{'lonDefDomain'}}) {
                   1671: 	@languages=(@languages,
                   1672: 		$Apache::lonnet::domain_lang_def{
                   1673:                                   $Apache::lonnet::perlvar{'lonDefDomain'}});
                   1674:     }
                   1675: # turn "en-ca" into "en-ca,en"
                   1676:     my @genlanguages;
                   1677:     foreach (@languages) {
                   1678: 	unless ($_=~/\w/) { next; }
                   1679: 	push (@genlanguages,$_);
                   1680: 	if ($_=~/(\-|\_)/) {
                   1681: 	    push (@genlanguages,(split(/(\-|\_)/,$_))[0]);
                   1682: 	}
                   1683:     }
                   1684:     return @genlanguages;
1.117     www      1685: }
                   1686: 
1.112     bowersj2 1687: ###############################################################
                   1688: ##               Student Answer Attempts                     ##
                   1689: ###############################################################
                   1690: 
                   1691: =pod
                   1692: 
                   1693: =head1 Alternate Problem Views
                   1694: 
                   1695: =over 4
                   1696: 
                   1697: =item * get_previous_attempt($symb, $username, $domain, $course,
                   1698:     $getattempt, $regexp, $gradesub)
                   1699: 
                   1700: Return string with previous attempt on problem. Arguments:
                   1701: 
                   1702: =over 4
                   1703: 
                   1704: =item * $symb: Problem, including path
                   1705: 
                   1706: =item * $username: username of the desired student
                   1707: 
                   1708: =item * $domain: domain of the desired student
1.14      harris41 1709: 
1.112     bowersj2 1710: =item * $course: Course ID
1.14      harris41 1711: 
1.112     bowersj2 1712: =item * $getattempt: Leave blank for all attempts, otherwise put
                   1713:     something
1.14      harris41 1714: 
1.112     bowersj2 1715: =item * $regexp: if string matches this regexp, the string will be
                   1716:     sent to $gradesub
1.14      harris41 1717: 
1.112     bowersj2 1718: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 1719: 
1.112     bowersj2 1720: =back
1.14      harris41 1721: 
1.112     bowersj2 1722: The output string is a table containing all desired attempts, if any.
1.16      harris41 1723: 
1.112     bowersj2 1724: =cut
1.1       albertel 1725: 
                   1726: sub get_previous_attempt {
1.43      ng       1727:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
1.1       albertel 1728:   my $prevattempts='';
1.43      ng       1729:   no strict 'refs';
1.1       albertel 1730:   if ($symb) {
1.3       albertel 1731:     my (%returnhash)=
                   1732:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 1733:     if ($returnhash{'version'}) {
                   1734:       my %lasthash=();
                   1735:       my $version;
                   1736:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.19      harris41 1737:         foreach (sort(split(/\:/,$returnhash{$version.':keys'}))) {
1.1       albertel 1738: 	  $lasthash{$_}=$returnhash{$version.':'.$_};
1.19      harris41 1739:         }
1.1       albertel 1740:       }
1.43      ng       1741:       $prevattempts='<table border="0" width="100%"><tr><td bgcolor="#777777">';
1.40      ng       1742:       $prevattempts.='<table border="0" width="100%"><tr bgcolor="#e6ffff"><td>History</td>';
1.16      harris41 1743:       foreach (sort(keys %lasthash)) {
1.31      albertel 1744: 	my ($ign,@parts) = split(/\./,$_);
1.41      ng       1745: 	if ($#parts > 0) {
1.31      albertel 1746: 	  my $data=$parts[-1];
                   1747: 	  pop(@parts);
1.40      ng       1748: 	  $prevattempts.='<td>Part '.join('.',@parts).'<br />'.$data.'&nbsp;</td>';
1.31      albertel 1749: 	} else {
1.41      ng       1750: 	  if ($#parts == 0) {
                   1751: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   1752: 	  } else {
                   1753: 	    $prevattempts.='<th>'.$ign.'</th>';
                   1754: 	  }
1.31      albertel 1755: 	}
1.16      harris41 1756:       }
1.40      ng       1757:       if ($getattempt eq '') {
                   1758: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
                   1759: 	  $prevattempts.='</tr><tr bgcolor="#ffffe6"><td>Transaction '.$version.'</td>';
                   1760: 	    foreach (sort(keys %lasthash)) {
                   1761: 	       my $value;
                   1762: 	       if ($_ =~ /timestamp/) {
                   1763: 		  $value=scalar(localtime($returnhash{$version.':'.$_}));
                   1764: 	       } else {
                   1765: 		  $value=$returnhash{$version.':'.$_};
                   1766: 	       }
                   1767: 	       $prevattempts.='<td>'.$value.'&nbsp;</td>';   
                   1768: 	    }
                   1769: 	 }
1.1       albertel 1770:       }
1.40      ng       1771:       $prevattempts.='</tr><tr bgcolor="#ffffe6"><td>Current</td>';
1.16      harris41 1772:       foreach (sort(keys %lasthash)) {
1.5       albertel 1773: 	my $value;
                   1774: 	if ($_ =~ /timestamp/) {
                   1775: 	  $value=scalar(localtime($lasthash{$_}));
                   1776: 	} else {
                   1777: 	  $value=$lasthash{$_};
                   1778: 	}
1.49      ng       1779: 	if ($_ =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
1.40      ng       1780: 	$prevattempts.='<td>'.$value.'&nbsp;</td>';
1.16      harris41 1781:       }
1.40      ng       1782:       $prevattempts.='</tr></table></td></tr></table>';
1.1       albertel 1783:     } else {
                   1784:       $prevattempts='Nothing submitted - no attempts.';
                   1785:     }
                   1786:   } else {
                   1787:     $prevattempts='No data.';
                   1788:   }
1.10      albertel 1789: }
                   1790: 
1.107     albertel 1791: sub relative_to_absolute {
                   1792:     my ($url,$output)=@_;
                   1793:     my $parser=HTML::TokeParser->new(\$output);
                   1794:     my $token;
                   1795:     my $thisdir=$url;
                   1796:     my @rlinks=();
                   1797:     while ($token=$parser->get_token) {
                   1798: 	if ($token->[0] eq 'S') {
                   1799: 	    if ($token->[1] eq 'a') {
                   1800: 		if ($token->[2]->{'href'}) {
                   1801: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   1802: 		}
                   1803: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   1804: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   1805: 	    } elsif ($token->[1] eq 'base') {
                   1806: 		$thisdir=$token->[2]->{'href'};
                   1807: 	    }
                   1808: 	}
                   1809:     }
                   1810:     $thisdir=~s-/[^/]*$--;
                   1811:     foreach (@rlinks) {
                   1812: 	unless (($_=~/^http:\/\//i) ||
                   1813: 		($_=~/^\//) ||
                   1814: 		($_=~/^javascript:/i) ||
                   1815: 		($_=~/^mailto:/i) ||
                   1816: 		($_=~/^\#/)) {
                   1817: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$_);
                   1818: 	    $output=~s/(\"|\'|\=\s*)$_(\"|\'|\s|\>)/$1$newlocation$2/;
                   1819: 	}
                   1820:     }
                   1821: # -------------------------------------------------- Deal with Applet codebases
                   1822:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   1823:     return $output;
                   1824: }
                   1825: 
1.112     bowersj2 1826: =pod
                   1827: 
                   1828: =item * get_student_view
                   1829: 
                   1830: show a snapshot of what student was looking at
                   1831: 
                   1832: =cut
                   1833: 
1.10      albertel 1834: sub get_student_view {
1.64      sakharuk 1835:   my ($symb,$username,$domain,$courseid,$target) = @_;
1.114     www      1836:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.10      albertel 1837:   my (%old,%moreenv);
                   1838:   my @elements=('symb','courseid','domain','username');
                   1839:   foreach my $element (@elements) {
                   1840:     $old{$element}=$ENV{'form.grade_'.$element};
                   1841:     $moreenv{'form.grade_'.$element}=eval '$'.$element #'
                   1842:   }
1.64      sakharuk 1843:   if ($target eq 'tex') {$moreenv{'form.grade_target'} = 'tex';}
1.11      albertel 1844:   &Apache::lonnet::appenv(%moreenv);
1.107     albertel 1845:   $feedurl=&Apache::lonnet::clutter($feedurl);
                   1846:   my $userview=&Apache::lonnet::ssi_body($feedurl);
1.11      albertel 1847:   &Apache::lonnet::delenv('form.grade_');
                   1848:   foreach my $element (@elements) {
                   1849:     $ENV{'form.grade_'.$element}=$old{$element};
                   1850:   }
                   1851:   $userview=~s/\<body[^\>]*\>//gi;
                   1852:   $userview=~s/\<\/body\>//gi;
                   1853:   $userview=~s/\<html\>//gi;
                   1854:   $userview=~s/\<\/html\>//gi;
                   1855:   $userview=~s/\<head\>//gi;
                   1856:   $userview=~s/\<\/head\>//gi;
                   1857:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 1858:   $userview=&relative_to_absolute($feedurl,$userview);
1.11      albertel 1859:   return $userview;
                   1860: }
                   1861: 
1.112     bowersj2 1862: =pod
                   1863: 
                   1864: =item * get_student_answers() 
                   1865: 
                   1866: show a snapshot of how student was answering problem
                   1867: 
                   1868: =cut
                   1869: 
1.11      albertel 1870: sub get_student_answers {
1.100     sakharuk 1871:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      1872:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.11      albertel 1873:   my (%old,%moreenv);
                   1874:   my @elements=('symb','courseid','domain','username');
                   1875:   foreach my $element (@elements) {
                   1876:     $old{$element}=$ENV{'form.grade_'.$element};
                   1877:     $moreenv{'form.grade_'.$element}=eval '$'.$element #'
                   1878:   }
                   1879:   $moreenv{'form.grade_target'}='answer';
1.10      albertel 1880:   &Apache::lonnet::appenv(%moreenv);
1.100     sakharuk 1881:   my $userview=&Apache::lonnet::ssi('/res/'.$feedurl,%form);
1.10      albertel 1882:   &Apache::lonnet::delenv('form.grade_');
                   1883:   foreach my $element (@elements) {
                   1884:     $ENV{'form.grade_'.$element}=$old{$element};
                   1885:   }
                   1886:   return $userview;
1.1       albertel 1887: }
1.116     albertel 1888: 
                   1889: =pod
                   1890: 
                   1891: =item * &submlink()
                   1892: 
                   1893: Inputs: $text $uname $udom $symb
                   1894: 
                   1895: Returns: A link to grades.pm such as to see the SUBM view of a student
                   1896: 
                   1897: =cut
                   1898: 
                   1899: ###############################################
                   1900: sub submlink {
                   1901:     my ($text,$uname,$udom,$symb)=@_;
                   1902:     if (!($uname && $udom)) {
                   1903: 	(my $cursymb, my $courseid,$udom,$uname)=
                   1904: 	    &Apache::lonxml::whichuser($symb);
                   1905: 	if (!$symb) { $symb=$cursymb; }
                   1906:     }
                   1907:     if (!$symb) { $symb=&symbread(); }
                   1908:     return '<a href="/adm/grades?symb='.$symb.'&student='.$uname.
                   1909: 	'&userdom='.$udom.'&command=submission">'.$text.'</a>';
                   1910: }
                   1911: ##############################################
1.37      matthew  1912: 
1.112     bowersj2 1913: =pod
                   1914: 
                   1915: =back
                   1916: 
                   1917: =cut
                   1918: 
1.37      matthew  1919: ###############################################
1.51      www      1920: 
                   1921: 
                   1922: sub timehash {
                   1923:     my @ltime=localtime(shift);
                   1924:     return ( 'seconds' => $ltime[0],
                   1925:              'minutes' => $ltime[1],
                   1926:              'hours'   => $ltime[2],
                   1927:              'day'     => $ltime[3],
                   1928:              'month'   => $ltime[4]+1,
                   1929:              'year'    => $ltime[5]+1900,
                   1930:              'weekday' => $ltime[6],
                   1931:              'dayyear' => $ltime[7]+1,
                   1932:              'dlsav'   => $ltime[8] );
                   1933: }
                   1934: 
                   1935: sub maketime {
                   1936:     my %th=@_;
                   1937:     return POSIX::mktime(
                   1938:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
                   1939:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,$th{'dlsav'}));
                   1940: }
                   1941: 
1.70      www      1942: 
                   1943: #########################################
                   1944: #
                   1945: # Retro-fixing of un-backward-compatible time format
                   1946: 
                   1947: sub unsqltime {
                   1948:     my $timestamp=shift;
                   1949:     if ($timestamp=~/^(\d+)\-(\d+)\-(\d+)\s+(\d+)\:(\d+)\:(\d+)$/) {
                   1950:        $timestamp=&maketime(
                   1951: 	   'year'=>$1,'month'=>$2,'day'=>$3,
                   1952:            'hours'=>$4,'minutes'=>$5,'seconds'=>$6);
                   1953:     }
                   1954:     return $timestamp;
                   1955: }
                   1956: 
                   1957: #########################################
1.51      www      1958: 
                   1959: sub findallcourses {
                   1960:     my %courses=();
                   1961:     my $now=time;
                   1962:     foreach (keys %ENV) {
                   1963: 	if ($_=~/^user\.role\.\w+\.\/(\w+)\/(\w+)/) {
                   1964: 	    my ($starttime,$endtime)=$ENV{$_};
                   1965:             my $active=1;
                   1966:             if ($starttime) {
                   1967: 		if ($now<$starttime) { $active=0; }
                   1968:             }
                   1969:             if ($endtime) {
                   1970:                 if ($now>$endtime) { $active=0; }
                   1971:             }
                   1972:             if ($active) { $courses{$1.'_'.$2}=1; }
                   1973:         }
                   1974:     }
                   1975:     return keys %courses;
                   1976: }
1.37      matthew  1977: 
1.54      www      1978: ###############################################
1.60      matthew  1979: ###############################################
                   1980: 
                   1981: =pod
                   1982: 
1.112     bowersj2 1983: =head1 Domain Template Functions
                   1984: 
                   1985: =over 4
                   1986: 
                   1987: =item * &determinedomain()
1.60      matthew  1988: 
                   1989: Inputs: $domain (usually will be undef)
                   1990: 
1.63      www      1991: Returns: Determines which domain should be used for designs
1.60      matthew  1992: 
                   1993: =cut
1.54      www      1994: 
1.60      matthew  1995: ###############################################
1.63      www      1996: sub determinedomain {
                   1997:     my $domain=shift;
                   1998:    if (! $domain) {
1.60      matthew  1999:         # Determine domain if we have not been given one
                   2000:         $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
                   2001:         if ($ENV{'user.domain'}) { $domain=$ENV{'user.domain'}; }
                   2002:         if ($ENV{'request.role.domain'}) { 
                   2003:             $domain=$ENV{'request.role.domain'}; 
                   2004:         }
                   2005:     }
1.63      www      2006:     return $domain;
                   2007: }
                   2008: ###############################################
                   2009: =pod
                   2010: 
1.112     bowersj2 2011: =item * &domainlogo()
1.63      www      2012: 
                   2013: Inputs: $domain (usually will be undef)
                   2014: 
                   2015: Returns: A link to a domain logo, if the domain logo exists.
                   2016: If the domain logo does not exist, a description of the domain.
                   2017: 
                   2018: =cut
1.112     bowersj2 2019: 
1.63      www      2020: ###############################################
                   2021: sub domainlogo {
                   2022:     my $domain = &determinedomain(shift);    
                   2023:      # See if there is a logo
1.59      www      2024:     if (-e '/home/httpd/html/adm/lonDomLogos/'.$domain.'.gif') {
1.83      albertel 2025: 	my $lonhttpdPort=$Apache::lonnet::perlvar{'lonhttpdPort'};
                   2026: 	if (!defined($lonhttpdPort)) { $lonhttpdPort='8080'; }
                   2027:         return '<img src="http://'.$ENV{'HTTP_HOST'}.':'.$lonhttpdPort.
                   2028: 	    '/adm/lonDomLogos/'.$domain.'.gif" />';
1.60      matthew  2029:     } elsif(exists($Apache::lonnet::domaindescription{$domain})) {
                   2030:         return $Apache::lonnet::domaindescription{$domain};
1.59      www      2031:     } else {
1.60      matthew  2032:         return '';
1.59      www      2033:     }
                   2034: }
1.63      www      2035: ##############################################
                   2036: 
                   2037: =pod
                   2038: 
1.112     bowersj2 2039: =item * &designparm()
1.63      www      2040: 
                   2041: Inputs: $which parameter; $domain (usually will be undef)
                   2042: 
                   2043: Returns: value of designparamter $which
                   2044: 
                   2045: =cut
1.112     bowersj2 2046: 
1.63      www      2047: ##############################################
                   2048: sub designparm {
                   2049:     my ($which,$domain)=@_;
1.110     www      2050:     if ($ENV{'browser.blackwhite'} eq 'on') {
                   2051: 	if ($which=~/\.(font|alink|vlink|link)$/) {
                   2052: 	    return '#000000';
                   2053: 	}
                   2054: 	if ($which=~/\.(pgbg|sidebg)$/) {
                   2055: 	    return '#FFFFFF';
                   2056: 	}
                   2057: 	if ($which=~/\.tabbg$/) {
                   2058: 	    return '#CCCCCC';
                   2059: 	}
                   2060:     }
1.96      www      2061:     if ($ENV{'environment.color.'.$which}) {
                   2062: 	return $ENV{'environment.color.'.$which};
                   2063:     }
1.63      www      2064:     $domain=&determinedomain($domain);
                   2065:     if ($designhash{$domain.'.'.$which}) {
                   2066: 	return $designhash{$domain.'.'.$which};
                   2067:     } else {
                   2068:         return $designhash{'default.'.$which};
                   2069:     }
                   2070: }
1.59      www      2071: 
1.60      matthew  2072: ###############################################
                   2073: ###############################################
                   2074: 
                   2075: =pod
                   2076: 
1.112     bowersj2 2077: =back
                   2078: 
                   2079: =head1 HTTP Helpers
                   2080: 
                   2081: =over 4
                   2082: 
                   2083: =item * &bodytag()
1.60      matthew  2084: 
                   2085: Returns a uniform header for LON-CAPA web pages.
                   2086: 
                   2087: Inputs: 
                   2088: 
1.112     bowersj2 2089: =over 4
                   2090: 
                   2091: =item * $title, A title to be displayed on the page.
                   2092: 
                   2093: =item * $function, the current role (can be undef).
                   2094: 
                   2095: =item * $addentries, extra parameters for the <body> tag.
                   2096: 
                   2097: =item * $bodyonly, if defined, only return the <body> tag.
                   2098: 
                   2099: =item * $domain, if defined, force a given domain.
                   2100: 
                   2101: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      2102:             text interface only)
1.60      matthew  2103: 
1.112     bowersj2 2104: =back
                   2105: 
1.60      matthew  2106: Returns: A uniform header for LON-CAPA web pages.  
                   2107: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   2108: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   2109: other decorations will be returned.
                   2110: 
                   2111: =cut
                   2112: 
1.54      www      2113: sub bodytag {
1.86      www      2114:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg)=@_;
1.117     www      2115:     $title=&mt($title);
1.55      www      2116:     unless ($function) {
                   2117: 	$function='student';
                   2118:         if ($ENV{'request.role'}=~/^(cc|in|ta|ep)/) {
                   2119: 	    $function='coordinator';
                   2120:         }
                   2121: 	if ($ENV{'request.role'}=~/^(su|dc|ad|li)/) {
                   2122:             $function='admin';
                   2123:         }
                   2124:         if (($ENV{'request.role'}=~/^(au|ca)/) ||
                   2125:             ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
                   2126:             $function='author';
                   2127:         }
                   2128:     }
1.63      www      2129:     my $img=&designparm($function.'.img',$domain);
                   2130:     my $pgbg=&designparm($function.'.pgbg',$domain);
                   2131:     my $tabbg=&designparm($function.'.tabbg',$domain);
                   2132:     my $font=&designparm($function.'.font',$domain);
                   2133:     my $link=&designparm($function.'.link',$domain);
                   2134:     my $alink=&designparm($function.'.alink',$domain);
                   2135:     my $vlink=&designparm($function.'.vlink',$domain);
                   2136:     my $sidebg=&designparm($function.'.sidebg',$domain);
1.110     www      2137: # Accessibility font enhance
                   2138:     unless ($addentries) { $addentries=''; }
                   2139:     if ($ENV{'browser.fontenhance'} eq 'on') {
                   2140: 	$addentries.=' style="font-size: x-large"';
                   2141:     }
1.63      www      2142:  # role and realm
1.55      www      2143:     my ($role,$realm)
                   2144:        =&Apache::lonnet::plaintext((split(/\./,$ENV{'request.role'}))[0]);
                   2145: # realm
1.54      www      2146:     if ($ENV{'request.course.id'}) {
1.55      www      2147: 	$realm=
                   2148:          $ENV{'course.'.$ENV{'request.course.id'}.'.description'};
1.54      www      2149:     }
1.55      www      2150:     unless ($realm) { $realm='&nbsp;'; }
                   2151: # Set messages
1.60      matthew  2152:     my $messages=&domainlogo($domain);
1.101     www      2153: # Port for miniserver
1.83      albertel 2154:     my $lonhttpdPort=$Apache::lonnet::perlvar{'lonhttpdPort'};
                   2155:     if (!defined($lonhttpdPort)) { $lonhttpdPort='8080'; }
1.101     www      2156: # construct main body tag
1.60      matthew  2157:     my $bodytag = <<END;
1.54      www      2158: <body bgcolor="$pgbg" text="$font" alink="$alink" vlink="$vlink" link="$link"
                   2159: $addentries>
1.60      matthew  2160: END
1.94      www      2161:     my $upperleft='<img src="http://'.$ENV{'HTTP_HOST'}.':'.
                   2162:                    $lonhttpdPort.$img.'" />';
1.60      matthew  2163:     if ($bodyonly) {
                   2164:         return $bodytag;
1.79      www      2165:     } elsif ($ENV{'browser.interface'} eq 'textual') {
1.95      www      2166: # Accessibility
1.93      www      2167:         return $bodytag.&Apache::lonmenu::menubuttons($forcereg,'web',
                   2168:                                                       $forcereg).
                   2169:                '<h1>LON-CAPA: '.$title.'</h1>';
                   2170:     } elsif ($ENV{'environment.remote'} eq 'off') {
1.95      www      2171: # No Remote
                   2172:         return $bodytag.&Apache::lonmenu::menubuttons($forcereg,'web',
                   2173:                                                       $forcereg).
                   2174:                '<table bgcolor="'.$pgbg.'" width="100%" border="0" cellspacing="3" cellpadding="3"><tr><td bgcolor="'.$tabbg.'"><font size="+3" color="'.$font.'"><b>'.$title.
                   2175: '</b></font></td></tr></table>';
1.94      www      2176:     }
1.95      www      2177: 
1.93      www      2178: #
1.95      www      2179: # Top frame rendering, Remote is up
1.93      www      2180: #
1.94      www      2181:     return(<<ENDBODY);
1.60      matthew  2182: $bodytag
1.55      www      2183: <table width="100%" cellspacing="0" border="0" cellpadding="0">
1.95      www      2184: <tr><td bgcolor="$sidebg">
1.94      www      2185: $upperleft</td>
1.95      www      2186: <td bgcolor="$sidebg" align="right">$messages&nbsp;</td>
1.55      www      2187: </tr>
1.54      www      2188: <tr>
1.55      www      2189: <td rowspan="3" bgcolor="$tabbg">
                   2190: &nbsp;<font size="5"><b>$title</b></font>
1.54      www      2191: <td bgcolor="$tabbg"  align="right">
                   2192: <font size="2">
                   2193:     $ENV{'environment.firstname'}
                   2194:     $ENV{'environment.middlename'}
                   2195:     $ENV{'environment.lastname'}
                   2196:     $ENV{'environment.generation'}
1.55      www      2197:     </font>&nbsp;
1.54      www      2198: </td>
                   2199: </tr>
                   2200: <tr><td bgcolor="$tabbg" align="right">
1.55      www      2201: <font size="2">$role</font>&nbsp;
1.54      www      2202: </td></tr>
1.55      www      2203: <tr>
                   2204: <td bgcolor="$tabbg" align="right"><font size="2">$realm</font>&nbsp;</td></tr>
1.54      www      2205: </table><br>
                   2206: ENDBODY
                   2207: }
1.99      www      2208: 
                   2209: ###############################################
                   2210: 
                   2211: sub get_posted_cgi {
                   2212:     my $r=shift;
                   2213: 
                   2214:     my $buffer;
                   2215:     
                   2216:     $r->read($buffer,$r->header_in('Content-length'),0);
                   2217:     unless ($buffer=~/^(\-+\w+)\s+Content\-Disposition\:\s*form\-data/si) {
                   2218: 	my @pairs=split(/&/,$buffer);
                   2219: 	my $pair;
                   2220: 	foreach $pair (@pairs) {
                   2221: 	    my ($name,$value) = split(/=/,$pair);
                   2222: 	    $value =~ tr/+/ /;
                   2223: 	    $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                   2224: 	    $name  =~ tr/+/ /;
                   2225: 	    $name  =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                   2226: 	    &add_to_env("form.$name",$value);
                   2227: 	}
                   2228:     } else {
                   2229: 	my $contentsep=$1;
                   2230: 	my @lines = split (/\n/,$buffer);
                   2231: 	my $name='';
                   2232: 	my $value='';
                   2233: 	my $fname='';
                   2234: 	my $fmime='';
                   2235: 	my $i;
                   2236: 	for ($i=0;$i<=$#lines;$i++) {
                   2237: 	    if ($lines[$i]=~/^$contentsep/) {
                   2238: 		if ($name) {
                   2239: 		    chomp($value);
                   2240: 		    if ($fname) {
                   2241: 			$ENV{"form.$name.filename"}=$fname;
                   2242: 			$ENV{"form.$name.mimetype"}=$fmime;
                   2243: 		    } else {
                   2244: 			$value=~s/\s+$//s;
                   2245: 		    }
                   2246: 		    &add_to_env("form.$name",$value);
                   2247: 		}
                   2248: 		if ($i<$#lines) {
                   2249: 		    $i++;
                   2250: 		    $lines[$i]=~
                   2251: 		/Content\-Disposition\:\s*form\-data\;\s*name\=\"([^\"]+)\"/i;
                   2252: 		    $name=$1;
                   2253: 		    $value='';
                   2254: 		    if ($lines[$i]=~/filename\=\"([^\"]+)\"/i) {
                   2255: 			$fname=$1;
                   2256: 			if 
                   2257:                             ($lines[$i+1]=~/Content\-Type\:\s*([\w\-\/]+)/i) {
                   2258: 				$fmime=$1;
                   2259: 				$i++;
                   2260: 			    } else {
                   2261: 				$fmime='';
                   2262: 			    }
                   2263: 		    } else {
                   2264: 			$fname='';
                   2265: 			$fmime='';
                   2266: 		    }
                   2267: 		    $i++;
                   2268: 		}
                   2269: 	    } else {
                   2270: 		$value.=$lines[$i]."\n";
                   2271: 	    }
                   2272: 	}
                   2273:     }
                   2274:     $ENV{'request.method'}=$ENV{'REQUEST_METHOD'};
                   2275:     $r->method_number(M_GET);
                   2276:     $r->method('GET');
                   2277:     $r->headers_in->unset('Content-length');
                   2278: }
                   2279: 
1.112     bowersj2 2280: =pod
                   2281: 
                   2282: =item * get_unprocessed_cgi($query,$possible_names)
                   2283: 
                   2284: Modify the %ENV hash to contain unprocessed CGI form parameters held in
                   2285: $query.  The parameters listed in $possible_names (an array reference),
                   2286: will be set in $ENV{'form.name'} if they do not already exist.
                   2287: 
                   2288: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   2289: $possible_names is an ref to an array of form element names.  As an example:
                   2290: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
                   2291: will result in $ENV{'form.uname'} and $ENV{'form.udom'} being set.
                   2292: 
                   2293: =cut
1.1       albertel 2294: 
1.6       albertel 2295: sub get_unprocessed_cgi {
1.25      albertel 2296:   my ($query,$possible_names)= @_;
1.26      matthew  2297:   # $Apache::lonxml::debug=1;
1.16      harris41 2298:   foreach (split(/&/,$query)) {
1.6       albertel 2299:     my ($name, $value) = split(/=/,$_);
1.25      albertel 2300:     $name = &Apache::lonnet::unescape($name);
                   2301:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   2302:       $value =~ tr/+/ /;
                   2303:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                   2304:       &Apache::lonxml::debug("Seting :$name: to :$value:");
1.30      albertel 2305:       unless (defined($ENV{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 2306:     }
1.16      harris41 2307:   }
1.6       albertel 2308: }
                   2309: 
1.112     bowersj2 2310: =pod
                   2311: 
                   2312: =item * cacheheader() 
                   2313: 
                   2314: returns cache-controlling header code
                   2315: 
                   2316: =cut
                   2317: 
1.7       albertel 2318: sub cacheheader {
1.23      www      2319:   unless ($ENV{'request.method'} eq 'GET') { return ''; }
1.8       albertel 2320:   my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
1.7       albertel 2321:   my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
                   2322:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   2323:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
                   2324:   return $output;
                   2325: }
                   2326: 
1.112     bowersj2 2327: =pod
                   2328: 
                   2329: =item * no_cache($r) 
                   2330: 
                   2331: specifies header code to not have cache
                   2332: 
                   2333: =cut
                   2334: 
1.9       albertel 2335: sub no_cache {
                   2336:   my ($r) = @_;
1.23      www      2337:   unless ($ENV{'request.method'} eq 'GET') { return ''; }
1.24      albertel 2338:   #my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
1.9       albertel 2339:   $r->no_cache(1);
                   2340:   $r->header_out("Pragma" => "no-cache");
1.24      albertel 2341:   #$r->header_out("Expires" => $date);
1.123     www      2342: }
                   2343: 
                   2344: sub content_type {
                   2345:   my ($r,$type,$charset) = @_;
                   2346:   unless ($charset) {
                   2347:       $charset=&Apache::lonlocal::current_encoding;
                   2348:   }
                   2349:   $r->content_type($type.($charset?'; charset='.$charset:''));
1.9       albertel 2350: }
1.25      albertel 2351: 
1.112     bowersj2 2352: =pod
                   2353: 
                   2354: =item * add_to_env($name,$value) 
                   2355: 
                   2356: adds $name to the %ENV hash with value
                   2357: $value, if $name already exists, the entry is converted to an array
                   2358: reference and $value is added to the array.
                   2359: 
                   2360: =cut
                   2361: 
1.25      albertel 2362: sub add_to_env {
                   2363:   my ($name,$value)=@_;
1.28      albertel 2364:   if (defined($ENV{$name})) {
1.27      albertel 2365:     if (ref($ENV{$name})) {
1.25      albertel 2366:       #already have multiple values
                   2367:       push(@{ $ENV{$name} },$value);
                   2368:     } else {
                   2369:       #first time seeing multiple values, convert hash entry to an arrayref
                   2370:       my $first=$ENV{$name};
                   2371:       undef($ENV{$name});
                   2372:       push(@{ $ENV{$name} },$first,$value);
                   2373:     }
                   2374:   } else {
                   2375:     $ENV{$name}=$value;
                   2376:   }
1.31      albertel 2377: }
                   2378: 
1.41      ng       2379: =pod
1.45      matthew  2380: 
                   2381: =back 
1.41      ng       2382: 
1.112     bowersj2 2383: =head1 CSV Upload/Handling functions
1.38      albertel 2384: 
1.41      ng       2385: =over 4
                   2386: 
1.112     bowersj2 2387: =item * upfile_store($r)
1.41      ng       2388: 
                   2389: Store uploaded file, $r should be the HTTP Request object,
                   2390: needs $ENV{'form.upfile'}
                   2391: returns $datatoken to be put into hidden field
                   2392: 
                   2393: =cut
1.31      albertel 2394: 
                   2395: sub upfile_store {
                   2396:     my $r=shift;
                   2397:     $ENV{'form.upfile'}=~s/\r/\n/gs;
                   2398:     $ENV{'form.upfile'}=~s/\f/\n/gs;
                   2399:     $ENV{'form.upfile'}=~s/\n+/\n/gs;
                   2400:     $ENV{'form.upfile'}=~s/\n+$//gs;
                   2401: 
                   2402:     my $datatoken=$ENV{'user.name'}.'_'.$ENV{'user.domain'}.
                   2403: 	'_enroll_'.$ENV{'request.course.id'}.'_'.time.'_'.$$;
                   2404:     {
                   2405: 	my $fh=Apache::File->new('>'.$r->dir_config('lonDaemons').
                   2406: 				 '/tmp/'.$datatoken.'.tmp');
                   2407: 	print $fh $ENV{'form.upfile'};
                   2408:     }
                   2409:     return $datatoken;
                   2410: }
                   2411: 
1.56      matthew  2412: =pod
                   2413: 
1.112     bowersj2 2414: =item * load_tmp_file($r)
1.41      ng       2415: 
                   2416: Load uploaded file from tmp, $r should be the HTTP Request object,
                   2417: needs $ENV{'form.datatoken'},
                   2418: sets $ENV{'form.upfile'} to the contents of the file
                   2419: 
                   2420: =cut
1.31      albertel 2421: 
                   2422: sub load_tmp_file {
                   2423:     my $r=shift;
                   2424:     my @studentdata=();
                   2425:     {
                   2426: 	my $fh;
                   2427: 	if ($fh=Apache::File->new($r->dir_config('lonDaemons').
                   2428: 				  '/tmp/'.$ENV{'form.datatoken'}.'.tmp')) {
                   2429: 	    @studentdata=<$fh>;
                   2430: 	}
                   2431:     }
                   2432:     $ENV{'form.upfile'}=join('',@studentdata);
                   2433: }
                   2434: 
1.56      matthew  2435: =pod
                   2436: 
1.112     bowersj2 2437: =item * upfile_record_sep()
1.41      ng       2438: 
                   2439: Separate uploaded file into records
                   2440: returns array of records,
                   2441: needs $ENV{'form.upfile'} and $ENV{'form.upfiletype'}
                   2442: 
                   2443: =cut
1.31      albertel 2444: 
                   2445: sub upfile_record_sep {
                   2446:     if ($ENV{'form.upfiletype'} eq 'xml') {
                   2447:     } else {
                   2448: 	return split(/\n/,$ENV{'form.upfile'});
                   2449:     }
                   2450: }
                   2451: 
1.56      matthew  2452: =pod
                   2453: 
1.112     bowersj2 2454: =item * record_sep($record)
1.41      ng       2455: 
                   2456: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $ENV{'form.upfiletype'}
                   2457: 
                   2458: =cut
                   2459: 
1.31      albertel 2460: sub record_sep {
                   2461:     my $record=shift;
                   2462:     my %components=();
                   2463:     if ($ENV{'form.upfiletype'} eq 'xml') {
                   2464:     } elsif ($ENV{'form.upfiletype'} eq 'space') {
                   2465:         my $i=0;
                   2466:         foreach (split(/\s+/,$record)) {
                   2467:             my $field=$_;
                   2468:             $field=~s/^(\"|\')//;
                   2469:             $field=~s/(\"|\')$//;
                   2470:             $components{$i}=$field;
                   2471:             $i++;
                   2472:         }
                   2473:     } elsif ($ENV{'form.upfiletype'} eq 'tab') {
                   2474:         my $i=0;
                   2475:         foreach (split(/\t+/,$record)) {
                   2476:             my $field=$_;
                   2477:             $field=~s/^(\"|\')//;
                   2478:             $field=~s/(\"|\')$//;
                   2479:             $components{$i}=$field;
                   2480:             $i++;
                   2481:         }
                   2482:     } else {
                   2483:         my @allfields=split(/\,/,$record);
                   2484:         my $i=0;
                   2485:         my $j;
                   2486:         for ($j=0;$j<=$#allfields;$j++) {
                   2487:             my $field=$allfields[$j];
                   2488:             if ($field=~/^\s*(\"|\')/) {
                   2489: 		my $delimiter=$1;
                   2490:                 while (($field!~/$delimiter$/) && ($j<$#allfields)) {
                   2491: 		    $j++;
                   2492: 		    $field.=','.$allfields[$j];
                   2493: 		}
                   2494:                 $field=~s/^\s*$delimiter//;
                   2495:                 $field=~s/$delimiter\s*$//;
                   2496:             }
                   2497:             $components{$i}=$field;
                   2498: 	    $i++;
                   2499:         }
                   2500:     }
                   2501:     return %components;
                   2502: }
                   2503: 
1.56      matthew  2504: =pod
                   2505: 
1.112     bowersj2 2506: =item * upfile_select_html()
1.41      ng       2507: 
                   2508: return HTML code to select file and specify its type
                   2509: 
                   2510: =cut
                   2511: 
1.31      albertel 2512: sub upfile_select_html {
                   2513:     return (<<'ENDUPFORM');
1.57      albertel 2514: <input type="file" name="upfile" size="50" />
1.31      albertel 2515: <br />Type: <select name="upfiletype">
                   2516: <option value="csv">CSV (comma separated values, spreadsheet)</option>
                   2517: <option value="space">Space separated</option>
                   2518: <option value="tab">Tabulator separated</option>
                   2519: <option value="xml">HTML/XML</option>
                   2520: </select>
                   2521: ENDUPFORM
                   2522: }
                   2523: 
1.56      matthew  2524: =pod
                   2525: 
1.112     bowersj2 2526: =item * csv_print_samples($r,$records)
1.41      ng       2527: 
                   2528: Prints a table of sample values from each column uploaded $r is an
                   2529: Apache Request ref, $records is an arrayref from
                   2530: &Apache::loncommon::upfile_record_sep
                   2531: 
                   2532: =cut
                   2533: 
1.31      albertel 2534: sub csv_print_samples {
                   2535:     my ($r,$records) = @_;
                   2536:     my (%sone,%stwo,%sthree);
                   2537:     %sone=&record_sep($$records[0]);
                   2538:     if (defined($$records[1])) {%stwo=&record_sep($$records[1]);}
                   2539:     if (defined($$records[2])) {%sthree=&record_sep($$records[2]);}
                   2540: 
                   2541:     $r->print('Samples<br /><table border="2"><tr>');
                   2542:     foreach (sort({$a <=> $b} keys(%sone))) { $r->print('<th>Column&nbsp;'.($_+1).'</th>'); }
                   2543:     $r->print('</tr>');
                   2544:     foreach my $hash (\%sone,\%stwo,\%sthree) {
                   2545: 	$r->print('<tr>');
                   2546: 	foreach (sort({$a <=> $b} keys(%sone))) {
                   2547: 	    $r->print('<td>');
                   2548: 	    if (defined($$hash{$_})) { $r->print($$hash{$_}); }
                   2549: 	    $r->print('</td>');
                   2550: 	}
                   2551: 	$r->print('</tr>');
                   2552:     }
                   2553:     $r->print('</tr></table><br />'."\n");
                   2554: }
                   2555: 
1.56      matthew  2556: =pod
                   2557: 
1.112     bowersj2 2558: =item * csv_print_select_table($r,$records,$d)
1.41      ng       2559: 
                   2560: Prints a table to create associations between values and table columns.
                   2561: $r is an Apache Request ref,
                   2562: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   2563: $d is an array of 2 element arrays (internal name, displayed name)
                   2564: 
                   2565: =cut
                   2566: 
1.31      albertel 2567: sub csv_print_select_table {
                   2568:     my ($r,$records,$d) = @_;
                   2569:     my $i=0;my %sone;
                   2570:     %sone=&record_sep($$records[0]);
                   2571:     $r->print('Associate columns with student attributes.'."\n".
                   2572: 	     '<table border="2"><tr><th>Attribute</th><th>Column</th></tr>'."\n");
                   2573:     foreach (@$d) {
                   2574: 	my ($value,$display)=@{ $_ };
                   2575: 	$r->print('<tr><td>'.$display.'</td>');
                   2576: 
                   2577: 	$r->print('<td><select name=f'.$i.
1.32      matthew  2578: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 2579: 	$r->print('<option value="none"></option>');
                   2580: 	foreach (sort({$a <=> $b} keys(%sone))) {
                   2581: 	    $r->print('<option value="'.$_.'">Column '.($_+1).'</option>');
                   2582: 	}
                   2583: 	$r->print('</select></td></tr>'."\n");
                   2584: 	$i++;
                   2585:     }
                   2586:     $i--;
                   2587:     return $i;
                   2588: }
1.56      matthew  2589: 
                   2590: =pod
1.31      albertel 2591: 
1.112     bowersj2 2592: =item * csv_samples_select_table($r,$records,$d)
1.41      ng       2593: 
                   2594: Prints a table of sample values from the upload and can make associate samples to internal names.
                   2595: 
                   2596: $r is an Apache Request ref,
                   2597: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   2598: $d is an array of 2 element arrays (internal name, displayed name)
                   2599: 
                   2600: =cut
                   2601: 
1.31      albertel 2602: sub csv_samples_select_table {
                   2603:     my ($r,$records,$d) = @_;
                   2604:     my %sone; my %stwo; my %sthree;
                   2605:     my $i=0;
                   2606: 
                   2607:     $r->print('<table border=2><tr><th>Field</th><th>Samples</th></tr>');
                   2608:     %sone=&record_sep($$records[0]);
                   2609:     if (defined($$records[1])) {%stwo=&record_sep($$records[1]);}
                   2610:     if (defined($$records[2])) {%sthree=&record_sep($$records[2]);}
                   2611: 
                   2612:     foreach (sort keys %sone) {
                   2613: 	$r->print('<tr><td><select name=f'.$i.
1.32      matthew  2614: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 2615: 	foreach (@$d) {
                   2616: 	    my ($value,$display)=@{ $_ };
                   2617: 	    $r->print('<option value='.$value.'>'.$display.'</option>');
                   2618: 	}
                   2619: 	$r->print('</select></td><td>');
                   2620: 	if (defined($sone{$_})) { $r->print($sone{$_}."</br>\n"); }
                   2621: 	if (defined($stwo{$_})) { $r->print($stwo{$_}."</br>\n"); }
                   2622: 	if (defined($sthree{$_})) { $r->print($sthree{$_}."</br>\n"); }
                   2623: 	$r->print('</td></tr>');
                   2624: 	$i++;
                   2625:     }
                   2626:     $i--;
                   2627:     return($i);
1.115     matthew  2628: }
                   2629: 
                   2630: =pod
                   2631: 
                   2632: =item clean_excel_name($name)
                   2633: 
                   2634: Returns a replacement for $name which does not contain any illegal characters.
                   2635: 
                   2636: =cut
                   2637: 
                   2638: sub clean_excel_name {
                   2639:     my ($name) = @_;
                   2640:     $name =~ s/[:\*\?\/\\]//g;
                   2641:     if (length($name) > 31) {
                   2642:         $name = substr($name,0,31);
                   2643:     }
                   2644:     return $name;
1.25      albertel 2645: }
1.84      albertel 2646: 
1.85      albertel 2647: =pod
                   2648: 
1.112     bowersj2 2649: =item * check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 2650: 
                   2651: Returns either 1 or undef
                   2652: 
                   2653: 1 if the part is to be hidden, undef if it is to be shown
                   2654: 
                   2655: Arguments are:
                   2656: 
                   2657: $id the id of the part to be checked
                   2658: $symb, optional the symb of the resource to check
                   2659: $udom, optional the domain of the user to check for
                   2660: $uname, optional the username of the user to check for
                   2661: 
                   2662: =cut
1.84      albertel 2663: 
                   2664: sub check_if_partid_hidden {
                   2665:     my ($id,$symb,$udom,$uname) = @_;
                   2666:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.parameter_hiddenparts',
                   2667: 					 $symb,$udom,$uname);
                   2668:     my @hiddenlist=split(/,/,$hiddenparts);
                   2669:     foreach my $checkid (@hiddenlist) {
                   2670: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return 1; }
                   2671:     }
                   2672:     return undef;
                   2673: }
1.127     matthew  2674: 
                   2675: ############################################################
                   2676: ############################################################
                   2677: 
                   2678: =pod
                   2679: 
                   2680: =item DrawGraph
                   2681: 
                   2682: Returns a link to cgi-bin/graph
                   2683: 
                   2684: =cut
                   2685: 
                   2686: ############################################################
                   2687: ############################################################
                   2688: sub DrawGraph {
                   2689:     my ($Title,$xlabel,$ylabel,$Max,$values1,$values2)=@_;
                   2690:     #
                   2691:     my $identifier = time.'_'.int(rand(1000));
                   2692:     if (! defined($values1) || ref($values1) ne 'ARRAY') {
                   2693:         return '';
                   2694:     }
                   2695:     #
                   2696:     $Title  = '' if (! defined($Title));
                   2697:     $xlabel = '' if (! defined($xlabel));
                   2698:     $ylabel = '' if (! defined($ylabel));
                   2699:     $Title  = &Apache::lonnet::escape($Title);
                   2700:     $xlabel = &Apache::lonnet::escape($xlabel);
                   2701:     $ylabel = &Apache::lonnet::escape($ylabel);
                   2702:     #
                   2703:     my $data1 = join(',', @$values1);
                   2704:     my $data2;
                   2705:     if (defined($values2)) {
                   2706:         $data2 = join(',', @$values2);
                   2707:     }
                   2708:     #
                   2709:     my $NumBars = scalar(@$values1);
                   2710:     $Max = 1 if ($Max < 1);
                   2711:     if ( int($Max) < $Max ) {
                   2712:         $Max++;
                   2713:         $Max = int($Max);
                   2714:     }
                   2715:     #
                   2716:     &Apache::lonnet::appenv($identifier.'.title'   => $Title,
                   2717:                             $identifier.'.xlabel'  => $xlabel,
                   2718:                             $identifier.'.ylabel'  => $ylabel,
                   2719:                             $identifier.'.Max'     => $Max,
                   2720:                             $identifier.'.NumBars' => $NumBars,
                   2721:                             $identifier.'.data1'   => $data1,
                   2722:                             $identifier.'.data2'   => $data2);
                   2723:     return '<IMG src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   2724: }
                   2725: 
                   2726: ############################################################
                   2727: ############################################################
1.84      albertel 2728: 
1.41      ng       2729: =pod
                   2730: 
                   2731: =back
                   2732: 
1.112     bowersj2 2733: =cut
1.41      ng       2734: 
1.112     bowersj2 2735: 1;
                   2736: __END__;
1.41      ng       2737: 

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