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

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

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