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

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

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