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

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

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