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

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

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