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

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

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