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

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

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