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

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

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