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

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

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